248 lines
8.1 KiB
JavaScript
248 lines
8.1 KiB
JavaScript
// Isolated contract fixture for browser verification; never enabled by npm run dev/start.
|
|
import { createServer } from "node:http";
|
|
import { createBackendServer } from "../server/backend-proxy.mjs";
|
|
import fixture from "./demand-fixtures.json" with { type: "json" };
|
|
const sessions = new Map(),
|
|
analyses = new Map(),
|
|
matches = new Map();
|
|
let serial = 0;
|
|
const clone = (value) => structuredClone(value);
|
|
const box = (name, size, color, extra = "") =>
|
|
`<robot name="${name}"><link name="${name}"><visual><geometry><box size="${size}"/></geometry><material name="body"><color rgba="${color}"/></material></visual></link>${extra}</robot>`;
|
|
const torso = box(
|
|
"BASE",
|
|
".25 .15 .3",
|
|
".65 .7 .8 1",
|
|
'<link name="LINK_ARM_R"/><joint name="J_ARM" type="fixed"><parent link="BASE"/><child link="LINK_ARM_R"/><origin xyz=".2 0 0"/></joint>',
|
|
);
|
|
const arm = box("ARM_ROOT", ".12 .12 .4", ".3 .5 .8 1");
|
|
const mock = createServer(async (req, res) => {
|
|
const path = new URL(req.url, "http://local").pathname;
|
|
res.setHeader("Content-Type", "application/json");
|
|
const send = (data, status = 200, code = "OK") => {
|
|
res.writeHead(status);
|
|
res.end(
|
|
JSON.stringify({ code, message: "fixture", data, requestId: "fixture" }),
|
|
);
|
|
};
|
|
if (path === "/fixture/torso.urdf" || path === "/fixture/arm.urdf") {
|
|
res.setHeader("Access-Control-Allow-Origin", "*");
|
|
res.setHeader("Content-Type", "application/xml");
|
|
res.end(path.includes("torso") ? torso : arm);
|
|
return;
|
|
}
|
|
if (path === "/api/robot-conversations") {
|
|
const id = "DC-test-" + ++serial;
|
|
sessions.set(id, 0);
|
|
res.setHeader(
|
|
"Set-Cookie",
|
|
"demand_test=local; Path=/; HttpOnly; SameSite=Lax",
|
|
);
|
|
send({ conversationId: id, revision: 0, expiresAt: "2026-10-20" });
|
|
return;
|
|
}
|
|
if (!req.headers.cookie?.includes("demand_test=local")) {
|
|
send(null, 404, "DEMAND_NOT_FOUND");
|
|
return;
|
|
}
|
|
let raw = "";
|
|
for await (const chunk of req) raw += chunk;
|
|
if (path.endsWith("/attachments") && req.method === "POST") {
|
|
const conversationId = path.split("/")[3];
|
|
send({
|
|
attachmentId: "DA-test",
|
|
previewUrl: `/api/robot-conversations/${conversationId}/attachments/DA-test`,
|
|
mimeType: "image/png",
|
|
sizeBytes: raw.length,
|
|
});
|
|
return;
|
|
}
|
|
if (path.includes("/attachments/")) {
|
|
res.setHeader("Content-Type", "image/png");
|
|
res.end(
|
|
Buffer.from(
|
|
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+j2ioAAAAASUVORK5CYII=",
|
|
"base64",
|
|
),
|
|
);
|
|
return;
|
|
}
|
|
const body =
|
|
raw && req.headers["content-type"]?.includes("application/json")
|
|
? JSON.parse(raw)
|
|
: {};
|
|
const id = path.split("/")[3];
|
|
if (path.endsWith("/messages") || path.endsWith("/retry")) {
|
|
let view;
|
|
if (path.endsWith("/retry")) view = analyses.get(id);
|
|
else {
|
|
const revision = (sessions.get(id) || 0) + 1;
|
|
sessions.set(id, revision);
|
|
view = clone(fixture.analysis);
|
|
view.conversationId = id;
|
|
view.analysisId = "DN-test-" + ++serial;
|
|
view.revision = revision;
|
|
view.summary = body.text;
|
|
view.result.analysis.summary = body.text;
|
|
view.questions = body.text.includes("缺单位")
|
|
? ["右臂扭矩的单位是什么?"]
|
|
: [];
|
|
view.canSubmit = !view.questions.length;
|
|
view.status = view.canSubmit ? "ready" : "needs_clarification";
|
|
view.result.analysis.questions = view.questions;
|
|
view.result.analysis.canSubmit = view.canSubmit;
|
|
view.result.analysis.status = view.status;
|
|
if (body.attachmentIds?.length)
|
|
view.result.analysis.observations.push({
|
|
id: "img1",
|
|
messageId: body.messageId,
|
|
imageId: body.attachmentIds[0],
|
|
kind: "image_visual",
|
|
content: "参考草图",
|
|
clarity: "uncertain",
|
|
region: [],
|
|
});
|
|
analyses.set(view.analysisId, view);
|
|
}
|
|
res.writeHead(200, { "Content-Type": "text/event-stream" });
|
|
const event = (name, data) =>
|
|
res.write(
|
|
`event:${name}\ndata:${JSON.stringify({ code: "OK", data })}\n\n`,
|
|
);
|
|
event("analysis.progress", {
|
|
analysisId: view.analysisId,
|
|
revision: view.revision,
|
|
stage: "analyzing_requirements",
|
|
message: "fixture",
|
|
});
|
|
if (body.text?.includes("停止")) {
|
|
view.status = "processing";
|
|
view.result = null;
|
|
view.canSubmit = false;
|
|
const interval = setInterval(() => res.write(": heartbeat\n\n"), 1000);
|
|
res.on("close", () => clearInterval(interval));
|
|
return;
|
|
}
|
|
if (view.status === "cancelled") {
|
|
const completed = clone(fixture.analysis);
|
|
Object.assign(view, {
|
|
...completed,
|
|
analysisId: view.analysisId,
|
|
conversationId: view.conversationId,
|
|
revision: view.revision,
|
|
});
|
|
}
|
|
setTimeout(() => {
|
|
event("analysis.completed", view);
|
|
res.end();
|
|
}, 200);
|
|
return;
|
|
}
|
|
if (path.startsWith("/api/robot-analyses/")) {
|
|
const view = analyses.get(id);
|
|
if (!view) {
|
|
send(null, 404, "DEMAND_NOT_FOUND");
|
|
return;
|
|
}
|
|
if (req.method === "DELETE") {
|
|
Object.assign(view, {
|
|
status: "cancelled",
|
|
canSubmit: false,
|
|
result: null,
|
|
});
|
|
send(view);
|
|
return;
|
|
}
|
|
if (path.endsWith("/confirm") || path.endsWith("/rematch")) {
|
|
if (body.revision !== view.revision || body.confirmed !== true) {
|
|
send(null, 409, "DEMAND_REVISION_CONFLICT");
|
|
return;
|
|
}
|
|
const match = clone(fixture.match);
|
|
match.analysisId = id;
|
|
match.revision = view.revision;
|
|
match.matchId = "DM-test-" + ++serial;
|
|
match.components.forEach((item, index) => {
|
|
item.resources = [
|
|
{
|
|
relativePath: "robot.urdf",
|
|
url: `http://127.0.0.1:8997/fixture/${index ? "arm" : "torso"}.urdf`,
|
|
version: 1,
|
|
expiresAt: null,
|
|
},
|
|
];
|
|
item.urdfMainPath = "robot.urdf";
|
|
if (view.summary.includes("物料清单")) {
|
|
item.component.bomList = [
|
|
{
|
|
partName: "H-DOF0-R-C",
|
|
position: "头",
|
|
dof: 0,
|
|
material: "POM",
|
|
function: "摄像头",
|
|
shape: "圆形",
|
|
size: "—",
|
|
torque: "—",
|
|
},
|
|
{
|
|
partName: "aaa",
|
|
position: "身体",
|
|
dof: 11,
|
|
material: "1122",
|
|
function: "333",
|
|
shape: "444",
|
|
size: "555",
|
|
torque: "66",
|
|
},
|
|
];
|
|
}
|
|
});
|
|
if (view.summary.includes("未满足")) {
|
|
match.status = "partial";
|
|
match.degradationAcceptanceRequired = true;
|
|
match.assembly.status = "blocked";
|
|
match.requirementChecks[0].status = "unmet";
|
|
match.requirementChecks[0].reason = "扭矩低于需求";
|
|
match.assembly.issues = [
|
|
{ code: "DEGRADATION_NOT_ACCEPTED", message: "等待接受降级" },
|
|
{ code: "MISSING_MOUNTING_REFERENCE", message: "子组件缺少安装基准" },
|
|
];
|
|
}
|
|
matches.set(match.matchId, match);
|
|
send(match);
|
|
return;
|
|
}
|
|
send(view);
|
|
return;
|
|
}
|
|
if (path.startsWith("/api/robot-demand-matches/")) {
|
|
const match = matches.get(id);
|
|
if (!match) {
|
|
send(null, 404, "DEMAND_NOT_FOUND");
|
|
return;
|
|
}
|
|
if (path.endsWith("/accept-degradation")) {
|
|
match.degradationAccepted = true;
|
|
match.degradationAcceptanceRequired = false;
|
|
match.assembly.issues = match.assembly.issues.filter(
|
|
(issue) => issue.code !== "DEGRADATION_NOT_ACCEPTED",
|
|
);
|
|
}
|
|
send(match);
|
|
return;
|
|
}
|
|
send(null, 404, "DEMAND_NOT_FOUND");
|
|
});
|
|
mock.listen(8997, "127.0.0.1");
|
|
const front = createBackendServer({ target: "http://127.0.0.1:8997" });
|
|
front.listen(8096, "127.0.0.1", () =>
|
|
console.log("Contract preview: http://127.0.0.1:8096 (fixture only)"),
|
|
);
|
|
for (const signal of ["SIGINT", "SIGTERM"])
|
|
process.on(signal, () => {
|
|
mock.closeAllConnections();
|
|
mock.close();
|
|
front.closeAllConnections();
|
|
front.close();
|
|
});
|