409 lines
13 KiB
JavaScript
409 lines
13 KiB
JavaScript
import { test } from "node:test";
|
|
import assert from "node:assert/strict";
|
|
import fixture from "./demand-fixtures.json" with { type: "json" };
|
|
import {
|
|
DemandApi,
|
|
DemandSession,
|
|
DemandError,
|
|
checkedAnalysis,
|
|
} from "../src/ai/demand-api.ts";
|
|
import { setAuthSession } from "../src/auth/auth.ts";
|
|
import { sseEvents } from "../shared/sse.mjs";
|
|
import {
|
|
resolveResource,
|
|
urdfPackagePath,
|
|
} from "../src/scene/assembly-plan.ts";
|
|
const clone = (value) => structuredClone(value);
|
|
const view = () => ({
|
|
...clone(fixture.analysis),
|
|
match: clone(fixture.match),
|
|
});
|
|
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",
|
|
};
|
|
setAuthSession({
|
|
token: "test-token",
|
|
tokenType: "Bearer",
|
|
expiresAt: Date.now() + 60_000,
|
|
user: { userCode: "U1", nickname: "测试用户", email: "u@example.com" },
|
|
});
|
|
|
|
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 bearer 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, "omit");
|
|
assert.equal(options.headers.Authorization, "Bearer test-token");
|
|
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("new user messages reuse the conversation and only send the latest message", 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;
|
|
next.match.analysisId = next.analysisId;
|
|
next.match.revision = next.revision;
|
|
if (sent.length === 1) {
|
|
next.status = "needs_clarification";
|
|
next.canSubmit = false;
|
|
next.questions = ["单位是什么?"];
|
|
next.match = null;
|
|
}
|
|
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("completed analysis carries the saved match and does not need another API call", async () => {
|
|
const paths = [];
|
|
const session = new DemandSession(
|
|
new DemandApi(async (path) => {
|
|
paths.push(path);
|
|
if (path === "/api/robot-conversations") return json(conversation);
|
|
return sse(wire("analysis.completed", view()));
|
|
}),
|
|
);
|
|
const result = await session.send(
|
|
{ id: "m1", text: "右臂" },
|
|
signal(),
|
|
() => {},
|
|
);
|
|
assert.equal(result.match.matchId, fixture.match.matchId);
|
|
assert.deepEqual(paths, [
|
|
"/api/robot-conversations",
|
|
`/api/robot-conversations/${conversation.conversationId}/messages`,
|
|
]);
|
|
});
|
|
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,
|
|
match: 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(),
|
|
match: null,
|
|
}),
|
|
{ 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,
|
|
match: null,
|
|
});
|
|
});
|
|
assert.equal((await api.stop(view().analysisId)).status, "cancelled");
|
|
assert.equal(method, "DELETE");
|
|
});
|
|
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("package mesh paths resolve when the manifest retains the exported package directory", () => {
|
|
const packageName = "头_0_DOF0-方-双摄.SLDASM";
|
|
const relativePath = `${packageName}/meshes/LINK_HEAD_0.STL`;
|
|
const resources = [{ relativePath, url: "/head-mesh" }];
|
|
const packagePath = `${urdfPackagePath(packageName)}/meshes/LINK_HEAD_0.STL`;
|
|
|
|
assert.equal(urdfPackagePath(packageName), `package://${packageName}`);
|
|
|
|
assert.equal(
|
|
resolveResource(resources, packagePath).relativePath,
|
|
relativePath,
|
|
);
|
|
assert.throws(
|
|
() =>
|
|
resolveResource(
|
|
resources,
|
|
`package://${packageName}//meshes/LINK_HEAD_0.STL`,
|
|
),
|
|
/资源清单缺少或无法唯一定位/,
|
|
);
|
|
});
|
|
|
|
test("new API has no removed confirm, match or degradation methods", () => {
|
|
assert.equal("confirm" in DemandApi.prototype, false);
|
|
assert.equal("match" in DemandApi.prototype, false);
|
|
assert.equal("accept" in DemandApi.prototype, false);
|
|
});
|