Files
planet/frontend/public/earth/js/workflow-bindings.js
T
linkong 3b1b9ef68c
ci / backend (push) Canceled after 0s
ci / frontend (push) Canceled after 0s
ci / delivery (push) Canceled after 0s
release: bump version to 0.83.0
2026-12-02 18:53:58 +08:00

537 lines
18 KiB
JavaScript

import { getEarthLocale, translateText } from "./i18n.js";
const BINDINGS_API = "/api/v1/ai/workflows/bindings";
const CACHE_TTL_MS = 5 * 60 * 1000;
const MAX_COMPARE_TARGETS = 6;
const TEMPLATE_TOKEN_RE = /\{\{\s*([a-zA-Z0-9_.-]+)\s*\}\}/g;
const EARTH_INTERACTABLE_PREFIX = "earth_interactable";
let cachedBindings = [];
let cacheLoadedAt = 0;
let inFlightPromise = null;
let compareTargets = [];
let activeMenuEl = null;
let activeMenuCleanup = null;
let trayEl = null;
function safeFetchImpl(explicit) {
if (typeof explicit === "function") return explicit;
return typeof fetch === "function" ? fetch.bind(globalThis) : null;
}
export function getCachedWorkflowBindings() {
return cachedBindings;
}
export function setCachedWorkflowBindingsForTest(items = []) {
cachedBindings = Array.isArray(items) ? items : [];
cacheLoadedAt = Date.now();
}
export async function loadWorkflowBindings({ force = false, fetchImpl = null } = {}) {
if (!force && cacheLoadedAt > 0 && Date.now() - cacheLoadedAt < CACHE_TTL_MS) {
return cachedBindings;
}
if (!force && inFlightPromise) return inFlightPromise;
const fetcher = safeFetchImpl(fetchImpl);
if (!fetcher) return cachedBindings;
inFlightPromise = (async () => {
try {
const resp = await fetcher(BINDINGS_API, {
method: "GET",
headers: { Accept: "application/json" },
});
if (!resp.ok) return cachedBindings;
const body = await resp.json();
if (Array.isArray(body?.items)) {
cachedBindings = body.items;
cacheLoadedAt = Date.now();
}
return cachedBindings;
} catch {
return cachedBindings;
} finally {
inFlightPromise = null;
}
})();
return inFlightPromise;
}
function finiteOrNull(value) {
const num = Number(value);
return Number.isFinite(num) ? num : null;
}
function compactProperties(raw = {}) {
const out = {};
if (!raw || typeof raw !== "object") return out;
const entries = Object.entries(raw);
for (let i = 0; i < entries.length && Object.keys(out).length < 16; i += 1) {
const [k, v] = entries[i];
if (v === null || v === undefined) continue;
if (typeof v === "boolean" || typeof v === "number") {
if (typeof v === "number" && !Number.isFinite(v)) continue;
out[k] = v;
} else if (typeof v === "string") {
const trimmed = v.trim();
if (trimmed) out[k] = trimmed.slice(0, 300);
}
}
return out;
}
export function normalizeEarthTarget(entityType, rawData = {}) {
const data = rawData && typeof rawData === "object" ? rawData : {};
const type = String(entityType || data.entity_type || "global").trim() || "global";
const label = String(
data.label
|| data.name
|| data.title
|| data.collector
|| data.city
|| data.anomaly_type
|| data.country
|| data.code
|| type,
).trim().slice(0, 200);
const entityId = String(
data.entity_id
|| data.incident_key
|| data.event_key
|| data.source_id
|| data.norad_id
|| data.norad_cat_id
|| data.mmsi
|| data.cable_id
|| data.collector
|| data.code
|| data.id
|| label,
).trim().slice(0, 160) || null;
const lat = finiteOrNull(data.latitude ?? data.lat ?? data.anchor?.latitude);
const lon = finiteOrNull(data.longitude ?? data.lon ?? data.anchor?.longitude);
const layer = data.layer ? String(data.layer).trim().slice(0, 80) : null;
const kind = data.kind ? String(data.kind).trim().slice(0, 80) : null;
return {
entity_type: type,
entity_id: entityId,
label,
latitude: lat,
longitude: lon,
layer,
kind,
properties: compactProperties(data),
};
}
export function getTargetKey(target) {
if (!target || typeof target !== "object") return "";
return `${target.entity_type || "entity"}:${target.entity_id || target.label || ""}`;
}
export function matchWorkflowBindings({
surface,
targets = [],
catalog = cachedBindings,
} = {}) {
if (!Array.isArray(catalog) || !catalog.length) return [];
const cleanTargets = Array.isArray(targets) ? targets.filter((t) => t && typeof t === "object") : [];
const targetCount = Math.max(1, cleanTargets.length);
const effectiveTargets = cleanTargets.length
? cleanTargets
: [{ entity_type: "global", kind: null }];
const matched = [];
for (const wf of catalog) {
const bindings = wf?.bindings;
if (!bindings || !bindings.enabled) continue;
const surfaces = Array.isArray(bindings.surfaces) ? bindings.surfaces : [];
if (surface && !surfaces.includes(surface)) continue;
const minTargets = Math.max(1, Number(bindings.min_targets || 1));
const maxTargets = Math.max(minTargets, Number(bindings.max_targets || 5));
if (cleanTargets.length > 0 && (targetCount < minTargets || targetCount > maxTargets)) {
continue;
}
const allowedTypes = Array.isArray(bindings.entity_types) ? bindings.entity_types : [];
if (!allowedTypes.length) continue;
const allowedKinds = Array.isArray(bindings.interactable_kinds)
? bindings.interactable_kinds.map((k) => String(k).trim().toLowerCase()).filter(Boolean)
: [];
const allMatch = effectiveTargets.every((t) => {
const et = String(t.entity_type || "global").trim();
if (!allowedTypes.includes(et)) return false;
if (et === EARTH_INTERACTABLE_PREFIX && allowedKinds.length > 0) {
const tk = String(t.kind || "").trim().toLowerCase();
return Boolean(tk && allowedKinds.includes(tk));
}
return true;
});
if (!allMatch) continue;
matched.push(wf);
}
matched.sort((a, b) => {
const pDiff = Number(b?.bindings?.priority || 0) - Number(a?.bindings?.priority || 0);
if (pDiff !== 0) return pDiff;
if (Boolean(a?.is_builtin) !== Boolean(b?.is_builtin)) {
return a?.is_builtin ? 1 : -1;
}
return String(a?.workflow_id || "").localeCompare(String(b?.workflow_id || ""));
});
return matched;
}
export function renderBindingPromptTemplate(template, targets = [], fallbackQuestion = "") {
const raw = String(template || "").trim();
if (!raw) return String(fallbackQuestion || "").trim();
const list = Array.isArray(targets) ? targets : [];
const first = list[0] || {};
const targetsSummary = list
.map((item) => {
const et = item.entity_type || "entity";
const lbl = item.label || item.entity_id || et;
const coord = Number.isFinite(item.latitude) && Number.isFinite(item.longitude)
? `(${item.latitude.toFixed(2)}, ${item.longitude.toFixed(2)})`
: "";
return `${et}「${lbl}」${coord}`;
})
.join("; ");
return raw.replace(TEMPLATE_TOKEN_RE, (_match, key) => {
if (key === "question") return String(fallbackQuestion || "");
if (key === "targets_summary") return targetsSummary || first.label || "";
if (key === "target.label") return String(first.label || "");
if (key === "target.type") return String(first.entity_type || "");
if (key === "target.id") return String(first.entity_id || "");
if (key === "target.lat") return Number.isFinite(first.latitude) ? first.latitude.toFixed(4) : "";
if (key === "target.lon") return Number.isFinite(first.longitude) ? first.longitude.toFixed(4) : "";
if (key === "target.kind") return String(first.kind || "");
if (key === "target.layer") return String(first.layer || "");
return "";
}).trim();
}
export function getCompareTargets() {
return [...compareTargets];
}
export function resetCompareTargetsForTest() {
compareTargets = [];
trayEl = null;
}
export function addTargetToCompare(target) {
if (!target || typeof target !== "object") return compareTargets;
const key = getTargetKey(target);
if (!key) return compareTargets;
if (!compareTargets.some((t) => getTargetKey(t) === key)) {
compareTargets = [...compareTargets.slice(-(MAX_COMPARE_TARGETS - 1)), target];
}
renderCompareTray();
return compareTargets;
}
export function removeTargetFromCompare(targetKey) {
compareTargets = compareTargets.filter((t) => getTargetKey(t) !== targetKey);
renderCompareTray();
return compareTargets;
}
export function clearCompareTargets() {
compareTargets = [];
renderCompareTray();
}
function escapeHtml(val) {
return String(val ?? "").replace(/[&<>"']/g, (ch) => ({
"&": "&amp;",
"<": "&lt;",
">": "&gt;",
'"': "&quot;",
"'": "&#39;",
})[ch]);
}
export function closeWorkflowActionPicker() {
if (typeof activeMenuCleanup === "function") {
activeMenuCleanup();
activeMenuCleanup = null;
}
if (activeMenuEl) {
activeMenuEl.remove();
activeMenuEl = null;
}
}
export function ensureEarthBottomDock() {
if (typeof document === "undefined" || !document.body) return null;
let dock = document.getElementById("earth-bottom-dock");
if (!dock) {
dock = document.createElement("div");
dock.id = "earth-bottom-dock";
dock.className = "earth-bottom-dock";
document.body.appendChild(dock);
}
return dock;
}
function renderCompareTray() {
if (
typeof window === "undefined"
|| typeof document === "undefined"
|| typeof document.querySelector !== "function"
|| typeof document.createElement !== "function"
|| typeof document.body?.appendChild !== "function"
) {
return;
}
if (!compareTargets.length) {
if (trayEl) trayEl.hidden = true;
return;
}
if (!trayEl || !trayEl.isConnected) {
trayEl = document.createElement("aside");
trayEl.id = "earth-target-tray";
trayEl.className = "hud-panel earth-target-tray";
trayEl.setAttribute("aria-label", translateText("多物件联合分析对比栏"));
const dock = ensureEarthBottomDock() || document.body;
dock.appendChild(trayEl);
trayEl.addEventListener?.("click", (event) => {
event.stopPropagation();
const target = event.target instanceof Element ? event.target : null;
if (!target) return;
const removeBtn = target.closest("[data-tray-remove]");
if (removeBtn instanceof HTMLElement) {
removeTargetFromCompare(removeBtn.dataset.trayRemove || "");
return;
}
if (target.closest("[data-tray-clear]")) {
clearCompareTargets();
return;
}
const analyzeBtn = target.closest("[data-tray-analyze]");
if (analyzeBtn instanceof HTMLElement) {
const snapshot = getCompareTargets();
if (!snapshot.length) return;
const isEn = getEarthLocale() === "en-US";
const summary = snapshot.map((t) => `${t.label || t.entity_id || t.entity_type}`).join(isEn ? ", " : "、");
openWorkflowActionPicker({
anchorEl: analyzeBtn,
surface: "multi_select",
targets: snapshot,
fallbackDetail: {
domain: "global",
entityId: snapshot[0]?.entity_id || null,
targets: snapshot,
initialQuestion: isEn
? `Perform a cross-layer joint analysis on these ${snapshot.length} selected Earth objects: ${summary}`
: `请对以下选中的 ${snapshot.length} 个地球对象进行联合分析:${summary}`,
autoAsk: true,
},
onSelect: (detail) => {
window.dispatchEvent(new CustomEvent("earth:open-workbench", { detail }));
},
});
}
});
}
trayEl.hidden = false;
const chipsHtml = compareTargets
.map((item) => {
const key = getTargetKey(item);
const label = item.label || item.entity_id || item.entity_type;
return `<span class="earth-target-tray__chip">
<span class="earth-target-tray__chip-label" title="${escapeHtml(label)}">${escapeHtml(label)}</span>
<button type="button" class="earth-target-tray__chip-remove" data-tray-remove="${escapeHtml(key)}" aria-label="${escapeHtml(translateText("移出对比"))}">
<span class="material-symbols-rounded earth-target-tray__icon" aria-hidden="true">close</span>
</button>
</span>`;
})
.join("");
trayEl.innerHTML = `<div class="earth-target-tray__list">${chipsHtml}</div>
<div class="earth-target-tray__actions">
<button type="button" class="earth-target-tray__analyze" data-tray-analyze="true">
<span class="material-symbols-rounded earth-target-tray__icon" aria-hidden="true">hub</span>
<span>${escapeHtml(translateText("联合分析"))} (${compareTargets.length})</span>
</button>
<button type="button" class="hud-panel__action" data-tray-clear="true" aria-label="${escapeHtml(translateText("清空对比栏"))}" title="${escapeHtml(translateText("清空对比栏"))}">
<span class="material-symbols-rounded earth-target-tray__icon" aria-hidden="true">delete_sweep</span>
</button>
</div>`;
}
function getLocalizedWorkflowTitle(wf) {
const isEn = getEarthLocale() === "en-US";
const b = wf?.bindings || {};
if (isEn) {
return b.action_label_en || wf?.name_en || b.action_label || wf?.name || wf?.workflow_id || "";
}
return b.action_label || wf?.name || wf?.workflow_id || "";
}
function positionMenuNearAnchor(menu, anchorEl) {
if (!anchorEl || typeof anchorEl.getBoundingClientRect !== "function") return;
const rect = anchorEl.getBoundingClientRect();
const vw = window.innerWidth || 1280;
const vh = window.innerHeight || 800;
const menuW = Math.min(280, Math.max(210, vw - 24));
const left = Math.max(12, Math.min(rect.right - menuW, vw - menuW - 12));
const openBelow = vh - rect.bottom >= 180 || vh - rect.bottom >= rect.top;
menu.style.width = `${menuW}px`;
menu.style.left = `${left}px`;
if (openBelow) {
menu.style.top = `${Math.min(vh - 180, rect.bottom + 6)}px`;
menu.style.bottom = "auto";
} else {
menu.style.bottom = `${Math.max(12, vh - rect.top + 6)}px`;
menu.style.top = "auto";
}
}
export function openWorkflowActionPicker({
anchorEl = null,
surface = "info_card",
targets = [],
fallbackDetail = {},
onSelect = null,
} = {}) {
const dispatch = typeof onSelect === "function"
? onSelect
: (detail) => {
if (typeof window !== "undefined") {
window.dispatchEvent(new CustomEvent("earth:open-workbench", { detail }));
}
};
// Trigger non-blocking catalog refresh in background if needed.
if (!cacheLoadedAt) {
void loadWorkflowBindings();
}
const matches = matchWorkflowBindings({ surface, targets, catalog: cachedBindings });
const buildDispatchPayload = (wf) => {
const workflowId = wf?.workflow_id || null;
const workflowName = wf ? getLocalizedWorkflowTitle(wf) : "";
const tmpl = wf?.bindings?.prompt_template || "";
const question = renderBindingPromptTemplate(
tmpl,
targets,
fallbackDetail.initialQuestion || "",
);
return {
...fallbackDetail,
workflowId,
workflowName,
targets,
initialQuestion: question,
autoAsk: fallbackDetail.autoAsk !== undefined ? Boolean(fallbackDetail.autoAsk) : true,
};
};
if (matches.length === 0) {
dispatch({ ...fallbackDetail, targets });
return;
}
if (matches.length === 1 && surface === "multi_select") {
dispatch(buildDispatchPayload(matches[0]));
return;
}
if (matches.length === 1 && surface !== "info_card") {
dispatch(buildDispatchPayload(matches[0]));
return;
}
if (typeof document === "undefined" || !document.body || !anchorEl) {
dispatch(buildDispatchPayload(matches[0]));
return;
}
// If clicked a second time on same trigger while open, toggle closed.
if (activeMenuEl && activeMenuEl.dataset.anchorKey === `${surface}:${getTargetKey(targets[0])}`) {
closeWorkflowActionPicker();
return;
}
closeWorkflowActionPicker();
const menu = document.createElement("div");
menu.className = "hud-panel earth-workflow-menu";
menu.dataset.anchorKey = `${surface}:${getTargetKey(targets[0])}`;
menu.setAttribute("role", "menu");
const itemsHtml = matches
.map((wf, idx) => {
const icon = wf?.bindings?.icon || "forum";
const label = getLocalizedWorkflowTitle(wf);
const isCustom = wf?.is_builtin === false;
return `<button type="button" class="earth-workflow-menu__item" data-wf-index="${idx}" role="menuitem">
<span class="material-symbols-rounded earth-workflow-menu__icon" aria-hidden="true">${escapeHtml(icon)}</span>
<span class="earth-workflow-menu__label">${escapeHtml(label)}</span>
${isCustom ? `<span class="earth-workflow-menu__tag">${escapeHtml(translateText("自定义"))}</span>` : ""}
</button>`;
})
.join("");
const showPinCompare = surface !== "multi_select" && targets.length === 1;
const alreadyPinned = showPinCompare && compareTargets.some((t) => getTargetKey(t) === getTargetKey(targets[0]));
const pinHtml = showPinCompare
? `<div class="earth-workflow-menu__sep"></div>
<button type="button" class="earth-workflow-menu__item earth-workflow-menu__item--pin" data-wf-pin="true" role="menuitem">
<span class="material-symbols-rounded earth-workflow-menu__icon" aria-hidden="true">${alreadyPinned ? "check_circle" : "add_circle_outline"}</span>
<span class="earth-workflow-menu__label">${escapeHtml(alreadyPinned ? translateText("已在多物件对比栏") : translateText("加入多物件对比分析"))}</span>
</button>`
: "";
menu.innerHTML = `<div class="earth-workflow-menu__head">${escapeHtml(translateText("选择 AI 工作流"))}</div>${itemsHtml}${pinHtml}`;
document.body.appendChild(menu);
positionMenuNearAnchor(menu, anchorEl);
activeMenuEl = menu;
menu.addEventListener("click", (event) => {
event.stopPropagation();
const target = event.target instanceof Element ? event.target : null;
if (!target) return;
const wfBtn = target.closest("[data-wf-index]");
if (wfBtn instanceof HTMLElement) {
const wf = matches[Number(wfBtn.dataset.wfIndex)];
closeWorkflowActionPicker();
if (wf) dispatch(buildDispatchPayload(wf));
return;
}
if (target.closest("[data-wf-pin]")) {
if (targets[0]) addTargetToCompare(targets[0]);
closeWorkflowActionPicker();
}
});
const onOutsidePointer = (event) => {
const t = event.target instanceof Node ? event.target : null;
if (t && (menu.contains(t) || anchorEl.contains(t))) return;
closeWorkflowActionPicker();
};
const onEscape = (event) => {
if (event.key === "Escape") closeWorkflowActionPicker();
};
document.addEventListener("pointerdown", onOutsidePointer, true);
document.addEventListener("keydown", onEscape, true);
activeMenuCleanup = () => {
document.removeEventListener("pointerdown", onOutsidePointer, true);
document.removeEventListener("keydown", onEscape, true);
};
}