445 lines
14 KiB
JavaScript
445 lines
14 KiB
JavaScript
import { test } from "node:test";
|
|
import assert from "node:assert/strict";
|
|
import { Matrix4, Euler, Vector3 } from "three";
|
|
import fixture from "./demand-fixtures.json" with { type: "json" };
|
|
import {
|
|
DemandApi,
|
|
DemandSession,
|
|
DemandError,
|
|
checkedAnalysis,
|
|
} from "../src/ai/demand-api.ts";
|
|
import { sseEvents } from "../shared/sse.mjs";
|
|
import {
|
|
resolveResource,
|
|
alignInterfaceFrames,
|
|
} from "../src/scene/assembly-plan.ts";
|
|
const clone = (value) => structuredClone(value);
|
|
const view = () => clone(fixture.analysis);
|
|
const plan = () => clone(fixture.match);
|
|
const envelope = (data) => ({
|
|
code: "OK",
|
|
message: "success",
|
|
data,
|
|
requestId: "test-1",
|
|
});
|
|
const json = (data) => Response.json(envelope(data));
|
|
const wire = (event, data) =>
|
|
`event:${event}\ndata:${JSON.stringify(envelope(data))}\n\n`;
|
|
const sse = (body) =>
|
|
new Response(body, { headers: { "Content-Type": "text/event-stream" } });
|
|
const progress = {
|
|
analysisId: view().analysisId,
|
|
revision: 1,
|
|
stage: "analyzing_requirements",
|
|
message: "正在分析",
|
|
};
|
|
const signal = () => new AbortController().signal;
|
|
const conversation = {
|
|
conversationId: view().conversationId,
|
|
revision: 0,
|
|
expiresAt: "2026-10-20",
|
|
};
|
|
|
|
test("gateway HTML and empty errors retain HTTP status instead of reporting incomplete backend fields", async () => {
|
|
for (const mode of ["request", "stream"]) {
|
|
for (const [status, body] of [
|
|
[403, "Invalid CORS request"],
|
|
[502, "<html>Bad Gateway</html>"],
|
|
[503, ""],
|
|
[504, "Gateway Timeout"],
|
|
]) {
|
|
const api = new DemandApi(
|
|
async () =>
|
|
new Response(body, {
|
|
status,
|
|
headers: {
|
|
"Content-Type": "text/html",
|
|
"X-Request-Id": "gateway-trace",
|
|
},
|
|
}),
|
|
);
|
|
const call =
|
|
mode === "request"
|
|
? api.createConversation()
|
|
: api.stream(
|
|
"/api/robot-conversations/DC-1/messages",
|
|
{},
|
|
signal(),
|
|
() => {},
|
|
);
|
|
await assert.rejects(call, (error) => {
|
|
assert.equal(error.code, "HTTP_ERROR");
|
|
assert.equal(error.status, status);
|
|
assert.equal(error.requestId, "gateway-trace");
|
|
assert.match(error.message, new RegExp(`HTTP ${status}`));
|
|
assert.doesNotMatch(error.message, /格式不完整|Bad Gateway|<html>/);
|
|
return true;
|
|
});
|
|
}
|
|
}
|
|
});
|
|
|
|
test("successful HTTP with invalid business data remains a genuine response format error", async () => {
|
|
const api = new DemandApi(
|
|
async () =>
|
|
new Response("<html>index</html>", {
|
|
headers: { "Content-Type": "text/html" },
|
|
}),
|
|
);
|
|
await assert.rejects(
|
|
api.createConversation(),
|
|
(error) => error.code === "INVALID_RESPONSE" && error.status === 200,
|
|
);
|
|
});
|
|
|
|
test("named SSE preserves split UTF-8, CRLF, heartbeats and multiline data", async () => {
|
|
const bytes = new TextEncoder().encode(
|
|
': heartbeat\r\nevent:analysis.progress\r\ndata:{"text":\r\ndata:"中文"}\r\n\r\n',
|
|
);
|
|
const stream = new ReadableStream({
|
|
start(c) {
|
|
bytes.forEach((byte) => c.enqueue(Uint8Array.of(byte)));
|
|
c.close();
|
|
},
|
|
});
|
|
const events = [];
|
|
for await (const event of sseEvents(stream)) events.push(event);
|
|
assert.deepEqual(events, [
|
|
{ event: "analysis.progress", data: '{"text":\n"中文"}' },
|
|
]);
|
|
});
|
|
test("conversation and multipart upload send credentials, then only new message IDs/text/attachments", async () => {
|
|
const calls = [];
|
|
const api = new DemandApi(async (path, options) => {
|
|
calls.push({ path, options });
|
|
assert.equal(options.credentials, "include");
|
|
if (path === "/api/robot-conversations") {
|
|
assert.equal(options.body, undefined);
|
|
return json(conversation);
|
|
}
|
|
if (path.endsWith("/attachments")) {
|
|
assert.ok(options.body instanceof FormData);
|
|
assert.equal(options.headers["Content-Type"], undefined);
|
|
assert.equal(options.body.get("file").name, "draft.png");
|
|
return json({
|
|
attachmentId: "DA-1",
|
|
previewUrl: `/api/robot-conversations/${conversation.conversationId}/attachments/DA-1`,
|
|
});
|
|
}
|
|
return sse(
|
|
wire("analysis.progress", progress) + wire("analysis.completed", view()),
|
|
);
|
|
});
|
|
const session = new DemandSession(api);
|
|
const message = {
|
|
id: "m-stable",
|
|
text: "右臂至少20N·m",
|
|
images: [
|
|
{
|
|
id: "local",
|
|
name: "draft.png",
|
|
url: "blob:preview",
|
|
file: new File(["image"], "draft.png", { type: "image/png" }),
|
|
},
|
|
],
|
|
};
|
|
const result = await session.send(message, signal(), () => {});
|
|
assert.equal(result.canSubmit, true);
|
|
assert.deepEqual(JSON.parse(calls.at(-1).options.body), {
|
|
messageId: "m-stable",
|
|
text: "右臂至少20N·m",
|
|
attachmentIds: ["DA-1"],
|
|
});
|
|
assert.equal(session.analysisId, result.analysisId);
|
|
assert.equal(calls.length, 3);
|
|
});
|
|
test("clarification uses same conversation, later revision; no history, role, prompt or request JSON", async () => {
|
|
const sent = [];
|
|
let creates = 0;
|
|
const api = new DemandApi(async (path, options) => {
|
|
if (path === "/api/robot-conversations") {
|
|
creates++;
|
|
return json(conversation);
|
|
}
|
|
sent.push(JSON.parse(options.body));
|
|
const next = view();
|
|
next.revision = sent.length;
|
|
next.analysisId = "DN-" + sent.length;
|
|
if (sent.length === 1) {
|
|
next.status = "needs_clarification";
|
|
next.canSubmit = false;
|
|
next.questions = ["单位是什么?"];
|
|
}
|
|
return sse(wire("analysis.completed", next));
|
|
});
|
|
const session = new DemandSession(api);
|
|
assert.equal(
|
|
(await session.send({ id: "m1", text: "右臂至少30" }, signal(), () => {}))
|
|
.canSubmit,
|
|
false,
|
|
);
|
|
const ready = await session.send(
|
|
{ id: "m2", text: "单位是N·m" },
|
|
signal(),
|
|
() => {},
|
|
);
|
|
assert.equal(ready.revision, 2);
|
|
assert.equal(creates, 1);
|
|
assert.deepEqual(sent[1], {
|
|
messageId: "m2",
|
|
text: "单位是N·m",
|
|
attachmentIds: [],
|
|
});
|
|
});
|
|
test("confirm/rematch/accept use revision only and keep blocked/partial after acceptance", async () => {
|
|
const calls = [];
|
|
const api = new DemandApi(async (path, options) => {
|
|
calls.push({ path, body: JSON.parse(options.body) });
|
|
const m = plan();
|
|
if (path.endsWith("/accept-degradation")) {
|
|
m.status = "partial";
|
|
m.degradationAccepted = true;
|
|
m.assembly.status = "blocked";
|
|
m.assembly.issues = [{ code: "MISSING_MOUNTING_REFERENCE" }];
|
|
}
|
|
return json(m);
|
|
});
|
|
await api.confirm(view());
|
|
await api.confirm(view(), true);
|
|
const accepted = await api.accept(plan());
|
|
assert.deepEqual(
|
|
calls.map((c) => c.body),
|
|
[
|
|
{ revision: 1, confirmed: true },
|
|
{ revision: 1, confirmed: true },
|
|
{ revision: 1, accepted: true },
|
|
],
|
|
);
|
|
assert.equal(accepted.assembly.status, "blocked");
|
|
assert.equal(accepted.status, "partial");
|
|
assert.match(calls[1].path, /\/rematch$/);
|
|
const stale = view();
|
|
stale.status = "superseded";
|
|
stale.canSubmit = false;
|
|
await assert.rejects(api.confirm(stale), {
|
|
code: "DEMAND_REVISION_CONFLICT",
|
|
});
|
|
});
|
|
test("connection interruption queries persisted analysis; never silently treats EOF as completion", async () => {
|
|
const paths = [];
|
|
const session = new DemandSession(
|
|
new DemandApi(async (path) => {
|
|
paths.push(path);
|
|
if (path === "/api/robot-conversations") return json(conversation);
|
|
if (path.endsWith("/messages"))
|
|
return sse(wire("analysis.progress", progress));
|
|
return json(view());
|
|
}),
|
|
);
|
|
const result = await session.send(
|
|
{ id: "m1", text: "右臂" },
|
|
signal(),
|
|
() => {},
|
|
);
|
|
assert.equal(result.status, "ready");
|
|
assert.match(paths.at(-1), /robot-analyses/);
|
|
assert.equal(paths.filter((p) => p.endsWith("/messages")).length, 1);
|
|
});
|
|
test("retry checks status first and uses retry endpoint only for failed/cancelled versions", async () => {
|
|
const paths = [];
|
|
let queries = 0;
|
|
const api = new DemandApi(async (path) => {
|
|
paths.push(path);
|
|
if (path === "/api/robot-conversations") return json(conversation);
|
|
if (path.endsWith("/messages"))
|
|
return sse(
|
|
wire("analysis.progress", progress) +
|
|
'event:analysis.failed\ndata:{"code":"DEMAND_TIMEOUT","data":null}\n\n',
|
|
);
|
|
if (path.endsWith("/retry")) return sse(wire("analysis.completed", view()));
|
|
queries++;
|
|
return json({
|
|
...view(),
|
|
status: "failed",
|
|
result: null,
|
|
canSubmit: false,
|
|
});
|
|
});
|
|
const session = new DemandSession(api);
|
|
await assert.rejects(
|
|
session.send({ id: "m1", text: "右臂" }, signal(), () => {}),
|
|
{ code: "DEMAND_TIMEOUT" },
|
|
);
|
|
assert.equal((await session.retry(signal(), () => {})).status, "ready");
|
|
assert.equal(queries, 1);
|
|
assert.match(paths.at(-1), /\/retry$/);
|
|
});
|
|
test("network resend reuses original message and successful attachments without reupload", async () => {
|
|
let sends = 0,
|
|
uploads = 0;
|
|
const bodies = [];
|
|
const session = new DemandSession(
|
|
new DemandApi(async (path, options) => {
|
|
if (path === "/api/robot-conversations") return json(conversation);
|
|
if (path.endsWith("/attachments")) {
|
|
uploads++;
|
|
return json({
|
|
attachmentId: "DA-1",
|
|
previewUrl: `/api/robot-conversations/${conversation.conversationId}/attachments/DA-1`,
|
|
});
|
|
}
|
|
bodies.push(options.body);
|
|
if (++sends === 1) throw TypeError("network");
|
|
return sse(wire("analysis.completed", view()));
|
|
}),
|
|
);
|
|
await assert.rejects(
|
|
session.send(
|
|
{
|
|
id: "same",
|
|
text: "草图",
|
|
images: [
|
|
{
|
|
id: "1",
|
|
name: "a.png",
|
|
url: "blob:a",
|
|
file: new File(["x"], "a.png"),
|
|
},
|
|
],
|
|
},
|
|
signal(),
|
|
() => {},
|
|
),
|
|
);
|
|
await session.retry(signal(), () => {});
|
|
assert.equal(uploads, 1);
|
|
assert.equal(bodies[0], bodies[1]);
|
|
});
|
|
test("HTTP and SSE errors preserve business code without exposing provider details", async () => {
|
|
for (const response of [
|
|
Response.json(
|
|
{
|
|
code: "DATABASE_UNAVAILABLE",
|
|
message: "internal-secret",
|
|
data: null,
|
|
requestId: "trace",
|
|
},
|
|
{ status: 503 },
|
|
),
|
|
sse(
|
|
'event:analysis.failed\ndata:{"code":"DEMAND_PROVIDER_FAILURE","message":"internal-secret","data":null}\n\n',
|
|
),
|
|
]) {
|
|
const api = new DemandApi(async () => response);
|
|
await assert.rejects(
|
|
api.stream("/x", {}, signal(), () => {}),
|
|
(error) =>
|
|
error instanceof DemandError &&
|
|
!error.message.includes("internal-secret"),
|
|
);
|
|
}
|
|
assert.throws(
|
|
() =>
|
|
checkedAnalysis({
|
|
...view(),
|
|
status: "needs_clarification",
|
|
canSubmit: true,
|
|
}),
|
|
{ code: "INVALID_RESPONSE" },
|
|
);
|
|
});
|
|
test("stop sends explicit DELETE and does not fabricate ready state", async () => {
|
|
let method;
|
|
const api = new DemandApi(async (_path, options) => {
|
|
method = options.method;
|
|
return json({
|
|
...view(),
|
|
status: "cancelled",
|
|
canSubmit: false,
|
|
result: null,
|
|
});
|
|
});
|
|
assert.equal((await api.stop(view().analysisId)).status, "cancelled");
|
|
assert.equal(method, "DELETE");
|
|
});
|
|
test("URDF node alignment matches position and rotation with nested nonzero child frames", () => {
|
|
const parent = new Matrix4().makeRotationFromEuler(
|
|
new Euler(-Math.PI / 2, -Math.PI / 2, 0, "ZYX"),
|
|
);
|
|
parent.setPosition(0, 0.0434269852498788, 0);
|
|
const child = new Matrix4()
|
|
.makeTranslation(0.2, 0.1, 0.3)
|
|
.multiply(new Matrix4().makeRotationZ(0.7));
|
|
const placement = alignInterfaceFrames(parent, child);
|
|
const actual = placement.clone().multiply(child);
|
|
actual.elements.forEach((value, i) =>
|
|
assert.ok(Math.abs(value - parent.elements[i]) < 1e-12),
|
|
);
|
|
assert.ok(
|
|
new Vector3()
|
|
.setFromMatrixPosition(alignInterfaceFrames(parent, new Matrix4()))
|
|
.distanceTo(new Vector3(0, 0.0434269852498788, 0)) < 1e-12,
|
|
);
|
|
assert.throws(
|
|
() => alignInterfaceFrames(parent, new Matrix4().makeScale(0, 1, 1)),
|
|
/坐标矩阵无效/,
|
|
);
|
|
});
|
|
|
|
test("resource lookup preserves directories and rejects basename-only or ambiguous package matches", () => {
|
|
const resources = [
|
|
{ relativePath: "meshes/arm.stl", url: "https://assets/a" },
|
|
{ relativePath: "other/arm.stl", url: "https://assets/b" },
|
|
];
|
|
assert.equal(
|
|
resolveResource(resources, "meshes/arm.stl").url,
|
|
"https://assets/a",
|
|
);
|
|
assert.equal(
|
|
resolveResource(resources, "package://robot/meshes/arm.stl").url,
|
|
"https://assets/a",
|
|
);
|
|
assert.throws(() => resolveResource(resources, "arm.stl"));
|
|
assert.throws(() => resolveResource(resources, "unknown/arm.stl"));
|
|
});
|
|
|
|
test("automatic retrieval forwards the saved revision even when backend analysis asks questions", async () => {
|
|
const input = view();
|
|
input.status = "needs_clarification";
|
|
input.canSubmit = false;
|
|
input.questions = ["工作场景是什么?"];
|
|
const before = clone(input),
|
|
calls = [];
|
|
const api = new DemandApi(async (path, options) => {
|
|
calls.push({ path, body: JSON.parse(options.body) });
|
|
return json(plan());
|
|
});
|
|
const result = await api.confirm(input);
|
|
assert.deepEqual(input, before);
|
|
assert.deepEqual(calls[0].body, {
|
|
revision: input.revision,
|
|
confirmed: true,
|
|
});
|
|
assert.equal(result.components.length, plan().components.length);
|
|
});
|
|
test("a real backend clarification refusal remains explicit and does not become a frontend question", async () => {
|
|
const api = new DemandApi(async () =>
|
|
Response.json(
|
|
{
|
|
code: "DEMAND_REVISION_CONFLICT",
|
|
message: "需求尚未完成解析或仍需补充说明",
|
|
data: null,
|
|
requestId: "trace-409",
|
|
},
|
|
{ status: 409 },
|
|
),
|
|
);
|
|
await assert.rejects(
|
|
api.confirm(view()),
|
|
(error) =>
|
|
error.code === "DEMAND_CLARIFICATION_REQUIRED" &&
|
|
error.status === 409 &&
|
|
error.requestId === "trace-409",
|
|
);
|
|
});
|