feat(web): configure trace explorer links

This commit is contained in:
lyon
2026-06-20 16:20:41 +08:00
parent c5f51f2b1b
commit c73b19fcaa
11 changed files with 202 additions and 4 deletions
+29 -1
View File
@@ -18,6 +18,8 @@ const CLIENT_DISCONNECT_ERROR_PATTERN = /\b(?:socket hang up|client disconnected
const CLOUD_WEB_ERROR_HANDLER_INSTALLED = Symbol.for("hwlab.cloud-web.error-handler-installed");
const CLIENT_ROUTE_FALLBACK_PATHS = new Set(["/workbench", "/workspace", "/gate", "/diagnostics/gate", "/help", "/skills", "/access"]);
const STATIC_ASSET_EXTENSION_PATTERN = /\.[A-Za-z0-9][A-Za-z0-9_-]*$/u;
const TRACE_EXPLORER_TEMPLATE_TOKEN = "{trace_id}";
const TRACE_EXPLORER_TEMPLATE_PLACEHOLDER_PATTERN = /\{([A-Za-z0-9_:-]+)\}/gu;
export async function serveCloudWeb(options) {
installCloudWebProcessErrorHandlers({ serviceId: options.serviceId });
@@ -167,11 +169,37 @@ function validateDisplayLocale(locale) {
function workbenchRuntimeConfigFromEnv() {
const traceTimeline = {};
const result = {};
const autoExpandRunning = parseEnvBoolean(process.env.HWLAB_WORKBENCH_TRACE_AUTO_EXPAND_RUNNING);
const autoCollapseTerminal = parseEnvBoolean(process.env.HWLAB_WORKBENCH_TRACE_AUTO_COLLAPSE_TERMINAL);
const traceExplorerUrlTemplate = traceExplorerUrlTemplateFromEnv(process.env.HWLAB_WORKBENCH_TRACE_EXPLORER_URL_TEMPLATE);
if (typeof autoExpandRunning === "boolean") traceTimeline.autoExpandRunning = autoExpandRunning;
if (typeof autoCollapseTerminal === "boolean") traceTimeline.autoCollapseTerminal = autoCollapseTerminal;
return Object.keys(traceTimeline).length > 0 ? { traceTimeline } : null;
if (Object.keys(traceTimeline).length > 0) result.traceTimeline = traceTimeline;
if (traceExplorerUrlTemplate) result.traceExplorerUrlTemplate = traceExplorerUrlTemplate;
return Object.keys(result).length > 0 ? result : null;
}
function traceExplorerUrlTemplateFromEnv(value) {
if (value === undefined || value === null || value === "") return null;
const template = String(value).trim();
if (!isSafeTraceExplorerUrlTemplate(template)) {
throw new Error("invalid HWLAB_WORKBENCH_TRACE_EXPLORER_URL_TEMPLATE: template must be http(s) or same-origin relative URL and contain only {trace_id}");
}
return template;
}
function isSafeTraceExplorerUrlTemplate(template) {
if (!template.includes(TRACE_EXPLORER_TEMPLATE_TOKEN)) return false;
const placeholders = Array.from(template.matchAll(TRACE_EXPLORER_TEMPLATE_PLACEHOLDER_PATTERN), (match) => match[0]);
if (placeholders.length === 0 || placeholders.some((placeholder) => placeholder !== TRACE_EXPLORER_TEMPLATE_TOKEN)) return false;
try {
const rendered = template.replaceAll(TRACE_EXPLORER_TEMPLATE_TOKEN, "trc_template_probe");
const url = new URL(rendered, "http://hwlab-cloud-web.local");
return (url.protocol === "http:" || url.protocol === "https:") && !template.startsWith("//");
} catch {
return false;
}
}
function parseEnvBoolean(value) {
@@ -341,6 +341,11 @@ test("cloud web remains healthy after a client disconnects during static respons
});
test("cloud web serves client deep links through the Vue shell", async () => {
const restoreEnv = withEnv({
HWLAB_CLOUD_WEB_DISPLAY_TIME_ZONE: "Asia/Shanghai",
HWLAB_CLOUD_WEB_DISPLAY_TIME_LOCALE: "zh-CN",
HWLAB_CLOUD_WEB_DISPLAY_TIME_LABEL: "北京时间"
});
const root = await mkdtemp(path.join(os.tmpdir(), "hwlab-cloud-web-runtime-"));
await writeFile(path.join(root, "index.html"), "<div id=\"root\"></div>\n", "utf8");
await writeFile(path.join(root, "asset.txt"), "asset body\n", "utf8");
@@ -367,7 +372,9 @@ test("cloud web serves client deep links through the Vue shell", async () => {
});
assert.equal(response.status, 200, route);
assert.equal(response.headers.get("content-type"), "text/html; charset=utf-8", route);
assert.equal(await response.text(), "<div id=\"root\"></div>\n", route);
const html = await response.text();
assert.match(html, /<div id="root"><\/div>/u, route);
assert.match(html, /HWLAB_CLOUD_WEB_CONFIG/u, route);
}
const assetResponse = await fetch(`${serverUrl(cloudWeb)}/asset.txt`, {
@@ -381,11 +388,64 @@ test("cloud web serves client deep links through the Vue shell", async () => {
});
assert.equal(missingAssetResponse.status, 404);
} finally {
restoreEnv();
await close(cloudWeb);
await rm(root, { recursive: true, force: true });
}
});
test("cloud web injects trace explorer runtime config from env", async () => {
const restoreEnv = withEnv({
HWLAB_CLOUD_WEB_DISPLAY_TIME_ZONE: "Asia/Shanghai",
HWLAB_CLOUD_WEB_DISPLAY_TIME_LOCALE: "zh-CN",
HWLAB_CLOUD_WEB_DISPLAY_TIME_LABEL: "北京时间",
HWLAB_WORKBENCH_TRACE_EXPLORER_URL_TEMPLATE: "/v1/workbench/traces/{trace_id}/events"
});
const root = await mkdtemp(path.join(os.tmpdir(), "hwlab-cloud-web-runtime-"));
await writeFile(path.join(root, "index.html"), "<html><head></head><body><div id=\"root\"></div></body></html>\n", "utf8");
const cloudWeb = createCloudWebServer({
serviceId: "hwlab-cloud-web",
roots: [root],
cloudApiBaseUrl: "http://127.0.0.1:1",
healthPayload: () => ({ status: "ok" }),
sendJson(response, statusCode, body) {
const payload = JSON.stringify(body);
response.writeHead(statusCode, {
"content-type": "application/json",
"content-length": Buffer.byteLength(payload)
});
response.end(payload);
}
});
await listen(cloudWeb);
try {
const response = await fetch(`${serverUrl(cloudWeb)}/workbench`, { headers: { accept: "text/html" } });
assert.equal(response.status, 200);
const html = await response.text();
assert.match(html, /traceExplorerUrlTemplate":"\/v1\/workbench\/traces\/\{trace_id\}\/events/u);
assert.doesNotMatch(html, /api key|secret|password/iu);
} finally {
restoreEnv();
await close(cloudWeb);
await rm(root, { recursive: true, force: true });
}
});
function withEnv(values) {
const previous = new Map();
for (const [key, value] of Object.entries(values)) {
previous.set(key, process.env[key]);
process.env[key] = value;
}
return () => {
for (const [key, value] of previous.entries()) {
if (value === undefined) delete process.env[key];
else process.env[key] = value;
}
};
}
function listen(server) {
return new Promise((resolve, reject) => {
server.once("error", reject);