feat: add seat-scoped static and dynamic assistant modes

This commit is contained in:
vee
2026-09-12 14:56:30 +08:00
parent d09b5967f8
commit d8dad22ec0
60 changed files with 5847 additions and 149 deletions
+193 -18
View File
@@ -11,6 +11,7 @@
let pendingMessage = null;
let latestControlResult = null;
let activeModeDraftContext = null;
let activeSchedulePoll = null;
let initialized = false;
const $ = (selector, root = document) => root.querySelector(selector);
@@ -542,7 +543,7 @@
const consumed = new Set();
const rows = [];
const targetZone = (action) => String(
action?.target?.instance || action?.target?.zone || action?.target || "",
action?.target?.instance || action?.target?.zone || action?.target_scope || action?.target || "",
);
const parameters = (action) => (
action?.parameters && typeof action.parameters === "object" ? action.parameters : {}
@@ -613,6 +614,10 @@
const capability = String(action.capability || "");
const domain = String(action.domain || "");
const zone = targetZone(action);
const zoneLabel = {
driver: "主驾", passenger: "副驾", front_left: "主驾", front_right: "副驾",
front_row: "前排", rear_row: "后排", rear_left: "左后", rear_right: "右后",
}[zone] || "";
const params = parameters(action);
let label = capability || domain || "座舱设备";
let value = "已配置";
@@ -683,7 +688,7 @@
icon = "armchair";
order = instructionOrder("座椅", "副驾", "主驾");
} else if (capability === "climate.set_temperature") {
label = "空调温度";
label = `${zoneLabel}空调温度`;
value = `${params.temperature_c ?? "--"}℃`;
icon = "thermometer";
order = instructionOrder("空调", "温度");
@@ -701,13 +706,14 @@
: capability === "climate.set_cycle_mode" ? "空调循环"
: capability === "climate.set_control_mode" ? "空调控制模式"
: capability === "climate.set_outlet_mode" ? "空调出风模式" : "空调";
label = `${zoneLabel}${label}`;
value = params.level != null ? `${params.level}档`
: params.mode != null ? (climateModeLabels[capability]?.[String(params.mode)] || String(params.mode))
: motionLabel(params.state);
icon = "fan";
order = instructionOrder("空调", "风量");
} else if (capability === "interior_light.set_reading_power") {
label = "阅读灯";
label = `${zoneLabel}阅读灯`;
value = motionLabel(params.state);
icon = "book-open";
order = instructionOrder("阅读灯", "灯光");
@@ -734,6 +740,63 @@
return rows.sort((left, right) => left.order - right.order);
}
function modeDraftScheduleView(draft) {
const schedule = draft?.schedule;
if (
schedule?.schema !== "cognitive-agent-mode-schedule/v1"
|| !Array.isArray(schedule.phases) || !schedule.phases.length
|| !Number.isInteger(schedule.repeat_count)
|| schedule.repeat_count < 1 || schedule.repeat_count > 20
|| schedule.phases.some((phase) => !Number.isFinite(phase?.duration_ms)
|| phase.duration_ms <= 0 || !Array.isArray(phase.operations))
) return null;
const durationLabel = (durationMs) => {
const minutes = Math.floor(durationMs / 60000);
const seconds = Number(((durationMs % 60000) / 1000).toFixed(3));
return minutes ? `${minutes}分${seconds ? `${seconds}秒` : ""}` : `${seconds}秒`;
};
let offsetMs = 0;
const phases = schedule.phases.map((phase, index) => {
// Each phase is rendered separately, without instruction-based grouping:
// the same seat or temperature can have a different target later on.
const rows = modeDraftRows({ instruction: "" }, phase.operations.map((operation) => ({
...operation,
target: operation.target || (operation.domain === "seat"
? { instance: operation.target_scope }
: { zone: operation.target_scope }),
})));
const view = {
id: String(phase.id || `phase-${index + 1}`),
name: String(phase.name || `阶段 ${index + 1}`),
timing: `+${durationLabel(offsetMs)} 开始 · 持续 ${durationLabel(phase.duration_ms)}`,
rows,
};
offsetMs += phase.duration_ms;
return view;
});
return {
phases,
operationCount: schedule.phases.reduce((count, phase) => count + phase.operations.length, 0),
summary: `${phases.length} 个阶段 · 重复 ${schedule.repeat_count} 次 · 总时长 ${durationLabel(offsetMs * schedule.repeat_count)}`,
stopHint: "执行后可输入“停止动态模式”提前结束,已执行状态不自动回滚。各阶段按顺序执行,时间为每轮的相对时间。",
};
}
function appendModeDraftRows(container, rows) {
rows.forEach((item) => {
const row = document.createElement("div");
row.className = "assistant-mode-draft-row";
const icon = document.createElement("i");
icon.dataset.lucide = item.icon;
const label = document.createElement("span");
label.textContent = item.label;
const value = document.createElement("strong");
value.textContent = item.value;
row.append(icon, label, value);
container.append(row);
});
}
async function saveModeProfileDraft(message, card, draft, buttons, status) {
buttons.forEach((button) => { button.disabled = true; });
card.classList.add("is-busy");
@@ -849,23 +912,39 @@
headingCopy.append(eyebrow, title);
const badge = document.createElement("span");
badge.className = "assistant-mode-draft-badge";
badge.textContent = `${Number(draft.operation_count) || 0} 项动作`;
const scheduleView = modeDraftScheduleView(draft);
badge.textContent = `${scheduleView?.operationCount ?? (Number(draft.operation_count) || 0)} 项动作`;
heading.append(headingCopy, badge);
const list = document.createElement("div");
list.className = "assistant-mode-draft-list";
modeDraftRows(draft, actions).forEach((item) => {
const row = document.createElement("div");
row.className = "assistant-mode-draft-row";
const icon = document.createElement("i");
icon.dataset.lucide = item.icon;
const label = document.createElement("span");
label.textContent = item.label;
const value = document.createElement("strong");
value.textContent = item.value;
row.append(icon, label, value);
list.append(row);
});
if (scheduleView) {
card.classList.add("assistant-mode-draft-scheduled");
const summary = document.createElement("p");
summary.className = "assistant-mode-schedule-summary";
summary.textContent = scheduleView.summary;
list.append(summary);
scheduleView.phases.forEach((phase, index) => {
const section = document.createElement("section");
section.className = "assistant-mode-schedule-phase";
section.dataset.modeSchedulePhase = phase.id;
const phaseHeading = document.createElement("header");
const name = document.createElement("strong");
name.textContent = `${index + 1}. ${phase.name}`;
const timing = document.createElement("small");
timing.textContent = phase.timing;
phaseHeading.append(name, timing);
section.append(phaseHeading);
appendModeDraftRows(section, phase.rows);
list.append(section);
});
const hint = document.createElement("p");
hint.className = "assistant-mode-schedule-hint";
hint.textContent = scheduleView.stopHint;
list.append(hint);
} else {
appendModeDraftRows(list, modeDraftRows(draft, actions));
}
const controls = document.createElement("div");
controls.className = "assistant-mode-draft-actions";
@@ -965,6 +1044,90 @@
}
}
function stopScheduleStatusPoll() {
if (!activeSchedulePoll) return;
window.clearTimeout(activeSchedulePoll.timer);
activeSchedulePoll.controller?.abort();
activeSchedulePoll = null;
}
function startScheduleStatusPoll(payload, message) {
stopScheduleStatusPoll();
const vehicleId = String(payload?.vehicle_id || payload?.vehicle?.id
|| payload?.mode_profile?.vehicle_id || $("#vehicleSelect")?.value || "");
if (!vehicleId) return;
const poll = {
vehicleId, conversationId: conversationId(), message,
sessionId: String(payload?.schedule_execution?.session_id || ""),
runId: String(payload?.schedule_execution?.run_id || ""),
modeProfileId: String(payload?.mode_profile?.id || ""),
timer: null, controller: null,
};
activeSchedulePoll = poll;
const isCurrent = () => activeSchedulePoll === poll
&& conversationId() === poll.conversationId
&& (!$("#vehicleSelect")?.value || $("#vehicleSelect").value === poll.vehicleId);
const update = async () => {
if (!isCurrent()) {
if (activeSchedulePoll === poll) stopScheduleStatusPoll();
return;
}
poll.controller = new AbortController();
try {
const response = await window.CognitiveAgentNetwork.request(
`/api/modes/schedule/status?vehicle_id=${encodeURIComponent(poll.vehicleId)}`,
{ method: "GET", signal: poll.controller.signal, timeoutMs: 8000, retries: 0 },
);
if (!isCurrent()) return;
if (response.status === 401) {
setActionStatus(message, "登录状态已失效,无法继续查询时间轴状态;请重新登录查看。", "failed");
stopScheduleStatusPoll();
return;
}
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const status = await response.json();
if (!isCurrent()) return;
if (status.vehicle_id && String(status.vehicle_id) !== poll.vehicleId) {
throw new Error("时间轴状态车型不匹配");
}
if ((poll.runId && status.run_id && String(status.run_id) !== poll.runId)
|| (poll.sessionId && status.session_id && String(status.session_id) !== poll.sessionId)) {
setActionStatus(message, "当前时间轴已被新的运行任务替换,请查看最新模式消息。", "working");
stopScheduleStatusPoll();
return;
}
const terminal = ["completed", "failed", "cancelled", "stopped", "idle"].includes(status.status);
if (status.status === "running") {
const phase = Number.isInteger(status.phase_index) && status.phase_index >= 0
? ` · 阶段 ${status.phase_index + 1}` : "";
const repeat = Number.isInteger(status.repeat_index) && status.repeat_index >= 0
? ` · 第 ${status.repeat_index + 1} 轮` : "";
setActionStatus(message, `动态时间轴执行中${repeat}${phase}。可输入“停止动态模式”;已执行状态不自动回滚。`, "working");
} else if (terminal) {
const stopped = ["cancelled", "stopped"].includes(status.status);
const failed = status.status === "failed";
const copy = failed
? `动态时间轴执行失败:${status.error || "某个阶段未通过执行校验"}。后续阶段不再执行,已执行状态不自动回滚。`
: stopped
? "动态时间轴已停止,后续阶段不再执行;已执行状态不自动回滚。"
: status.status === "completed"
? "动态时间轴已结束,全部计划阶段已处理;请以车辆反馈确认设备实际状态。"
: "当前没有正在运行的动态时间轴。";
setActionStatus(message, copy, failed ? "failed" : "success");
window.CognitiveAgentConsole?.updateScheduleExecutionStatus?.(poll.modeProfileId, status.status);
stopScheduleStatusPoll();
return;
}
} catch (error) {
if (!isCurrent() || poll.controller?.signal.aborted) return;
setActionStatus(message, "暂时无法获取时间轴状态,正在重新查询;需要停止时可输入“停止动态模式”。", "working");
} finally {
if (isCurrent()) poll.timer = window.setTimeout(update, 2000);
}
};
poll.timer = window.setTimeout(update, 2000);
}
function applyAssistantEvent(event, message) {
if (event.type === "answer.delta") {
setMessageContent(message, `${message.content}${event.delta || ""}`);
@@ -985,14 +1148,20 @@
if (event.type === "action.completed" || event.type === "work.completed") {
latestControlResult = event.payload || latestControlResult;
const completed = event.success !== false;
const scheduleRunning = completed
&& event.payload?.orchestration_route === "mode_schedule_execute"
&& (event.payload?.status === "running" || event.payload?.schedule_execution?.status === "running");
const defaultText = event.type === "work.completed"
? (completed ? "AI助手已完成工作" : "AI助手未能完成工作")
: (completed ? "座舱控制已完成" : "座舱控制未完成");
setActionStatus(
message,
event.display_text || defaultText,
completed ? "success" : "failed",
scheduleRunning
? "已启动动态时间轴;后续动作将分阶段执行。可输入“停止动态模式”提前结束,已执行的设备状态不会自动回滚。"
: event.display_text || defaultText,
scheduleRunning ? "working" : completed ? "success" : "failed",
);
if (scheduleRunning) startScheduleStatusPoll(event.payload, message);
if (event.payload) {
window.CognitiveAgentConsole?.applySyncedResult?.(event.payload);
if (
@@ -1238,11 +1407,17 @@
document.addEventListener("click", (event) => {
const target = event.target instanceof Element ? event.target : null;
if (!target?.closest("#newConversation")) return;
stopScheduleStatusPoll();
sessionStorage.removeItem(STORAGE_KEY);
clearActiveModeDraftContext();
sessionStorage.setItem(CONVERSATION_STORAGE_KEY, createConversationId());
}, true);
document.addEventListener("change", (event) => {
if (event.target?.id === "vehicleSelect") stopScheduleStatusPoll();
});
window.addEventListener("pagehide", stopScheduleStatusPoll);
document.addEventListener("DOMContentLoaded", initialize);
window.CognitiveAgentAssistant = {
submit: submitAssistant,