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
+12
View File
@@ -334,6 +334,7 @@
"runtimePath": { "type": "string" },
"imageTagMode": { "type": "string", "enum": ["short", "full"] },
"workbench": { "$ref": "#/$defs/workbenchUiPolicy" },
"observability": { "$ref": "#/$defs/runtimeObservabilityPolicy" },
"runtimeStore": { "$ref": "#/$defs/runtimeStore" },
"sourceRepo": { "type": "string" },
"envReuseServices": {
@@ -360,6 +361,17 @@
},
"additionalProperties": false
},
"runtimeObservabilityPolicy": {
"type": "object",
"properties": {
"traceExplorerUrlTemplate": {
"type": "string",
"minLength": 1,
"pattern": "\\{trace_id\\}"
}
},
"additionalProperties": false
},
"runtimeStore": {
"type": "object",
"properties": {
+2
View File
@@ -255,6 +255,8 @@ lanes:
traceTimeline:
autoExpandRunning: false
autoCollapseTerminal: false
observability:
traceExplorerUrlTemplate: /v1/workbench/traces/{trace_id}/events
externalPostgres:
enabled: true
serviceName: g14-platform-postgres
+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);
+10
View File
@@ -979,6 +979,12 @@ function runtimeWorkbenchTraceTimelinePolicy(deploy, profile) {
return Object.keys(result).length > 0 ? result : null;
}
function runtimeTraceExplorerUrlTemplate(deploy, profile) {
if (!isRuntimeLane(profile)) return null;
const template = runtimeLaneConfig(deploy, profile)?.observability?.traceExplorerUrlTemplate;
return typeof template === "string" && template.trim().length > 0 ? template.trim() : null;
}
function runtimeStoreEnvForProfile(deploy, profile, serviceId) {
if (!isRuntimeLane(profile) || serviceId !== "hwlab-cloud-api") return {};
const postgres = runtimeLaneConfig(deploy, profile)?.runtimeStore?.postgres;
@@ -1225,6 +1231,10 @@ function transformWorkloads({ workloads, deploy, catalog, source, sourceBranch =
if (typeof traceTimelinePolicy?.autoCollapseTerminal === "boolean") {
upsertEnv(container.env, "HWLAB_WORKBENCH_TRACE_AUTO_COLLAPSE_TERMINAL", booleanEnv(traceTimelinePolicy.autoCollapseTerminal));
}
const traceExplorerUrlTemplate = runtimeTraceExplorerUrlTemplate(deploy, profile);
if (traceExplorerUrlTemplate) {
upsertEnv(container.env, "HWLAB_WORKBENCH_TRACE_EXPLORER_URL_TEMPLATE", traceExplorerUrlTemplate);
}
}
}
rewritePodSecretRefs(podTemplate.spec, profile);
+3
View File
@@ -44,6 +44,9 @@ export type RuntimeLaneConfig = {
api?: string;
[key: string]: string | undefined;
};
observability?: {
traceExplorerUrlTemplate?: string;
};
sourceRepo?: string;
};
@@ -2,6 +2,7 @@ import assert from "node:assert/strict";
import test from "node:test";
import type { ApiResult, HwpodNodeOpsResponse, HwpodSpecsResponse, LiveProbePayload, LiveSurface } from "../src/types/index.ts";
import { traceExplorerHref } from "../src/config/runtime.ts";
import { summarizeBuilds, summarizeHwpodNodeOps, summarizeProbeRows } from "../src/stores/workbench-live.ts";
import { liveCall } from "../src/stores/workbench.ts";
@@ -56,6 +57,21 @@ test("R3 live refresh keeps partial evidence when one endpoint throws", async ()
assert.equal(passed.data?.revision, "155530d8d9355887a23a08e341291994cc312f54");
});
test("R3 trace explorer href is config gated and trace_id only", () => {
window.HWLAB_CLOUD_WEB_CONFIG = {
displayTime: { timeZone: "Asia/Shanghai", locale: "zh-CN", label: "北京时间" },
workbench: { traceExplorerUrlTemplate: "/v1/workbench/traces/{trace_id}/events" }
};
assert.equal(traceExplorerHref("trc_completed"), "/v1/workbench/traces/trc_completed/events");
assert.equal(traceExplorerHref("bad/trace"), null);
window.HWLAB_CLOUD_WEB_CONFIG.workbench = { traceExplorerUrlTemplate: "/trace/{trace_id}?prompt={prompt}" };
assert.equal(traceExplorerHref("trc_completed"), null);
window.HWLAB_CLOUD_WEB_CONFIG.workbench = {};
assert.equal(traceExplorerHref("trc_completed"), null);
});
function liveSurface(): LiveSurface {
const liveProbe = ok<LiveProbePayload>({ serviceId: "hwlab-cloud-api", environment: "v03", status: "ok", ready: true, revision: "c0cbdbb38de77f1ecc9d1222438a13294d81d4dd", observedAt: "2026-06-13T17:59:15.000Z" });
return {
@@ -1,6 +1,7 @@
<script setup lang="ts">
import { computed } from "vue";
import type { ChatMessage } from "@/types";
import { traceExplorerHref } from "@/config/runtime";
import { canCancelMessage, canRetryMessage, messageTraceId } from "./message-rendering";
const props = defineProps<{ message: ChatMessage }>();
@@ -11,7 +12,7 @@ const emit = defineEmits<{
}>();
const traceId = computed(() => messageTraceId(props.message));
const traceHref = computed(() => traceId.value ? `/v1/workbench/traces/${encodeURIComponent(traceId.value)}/events` : "#");
const traceHref = computed(() => traceExplorerHref(traceId.value));
const canCancel = computed(() => canCancelMessage(props.message));
const canRetry = computed(() => canRetryMessage(props.message));
const hasTrace = computed(() => props.message.role === "agent" && Boolean(traceId.value));
@@ -22,6 +23,6 @@ const hasTrace = computed(() => props.message.role === "agent" && Boolean(traceI
<button v-if="canCancel" class="btn btn-secondary btn-sm" type="button" @click="emit('cancel', message)">取消</button>
<button v-if="canRetry" class="btn btn-secondary btn-sm" type="button" @click="emit('retry', message)">重试</button>
<button v-if="hasTrace" class="btn btn-secondary btn-sm" type="button" @click="emit('copyTrace', message)">复制 Trace</button>
<a v-if="hasTrace" class="btn btn-secondary btn-sm" :href="traceHref" target="_blank" rel="noreferrer">打开 Trace</a>
<a v-if="traceHref" class="btn btn-secondary btn-sm" :href="traceHref" target="_blank" rel="noreferrer">打开 Trace</a>
</div>
</template>
+43
View File
@@ -15,6 +15,9 @@ const DEFAULT_DISPLAY_DATE_TIME_OPTIONS: Intl.DateTimeFormatOptions = {
second: "2-digit",
hour12: false
};
const TRACE_ID_PATTERN = /^[A-Za-z0-9_.:-]{3,160}$/u;
const TRACE_EXPLORER_TEMPLATE_TOKEN = "{trace_id}";
const TRACE_EXPLORER_TEMPLATE_PLACEHOLDER_PATTERN = /\{([A-Za-z0-9_:-]+)\}/gu;
export function displayTimeConfig(): DisplayTimeConfig {
const config = window.HWLAB_CLOUD_WEB_CONFIG?.displayTime;
@@ -72,3 +75,43 @@ export function workbenchTraceTimelinePolicy(): WorkbenchTraceTimelinePolicy {
autoCollapseTerminal: config?.autoCollapseTerminal === true
};
}
export function traceExplorerHref(traceId: string | null | undefined): string | null {
const safeTraceId = normalizedTraceId(traceId);
if (!safeTraceId) return null;
const template = window.HWLAB_CLOUD_WEB_CONFIG?.workbench?.traceExplorerUrlTemplate;
if (typeof template !== "string" || !isSafeTraceExplorerUrlTemplate(template)) return null;
const rendered = template.trim().replaceAll(TRACE_EXPLORER_TEMPLATE_TOKEN, encodeURIComponent(safeTraceId));
try {
const url = new URL(rendered, runtimeOrigin());
if (url.protocol !== "http:" && url.protocol !== "https:") return null;
return rendered;
} catch {
return null;
}
}
function normalizedTraceId(value: string | null | undefined): string | null {
const traceId = typeof value === "string" ? value.trim() : "";
return TRACE_ID_PATTERN.test(traceId) ? traceId : null;
}
function isSafeTraceExplorerUrlTemplate(template: string): boolean {
const trimmed = template.trim();
if (!trimmed.includes(TRACE_EXPLORER_TEMPLATE_TOKEN) || trimmed.startsWith("//")) return false;
const placeholders = Array.from(trimmed.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 = trimmed.replaceAll(TRACE_EXPLORER_TEMPLATE_TOKEN, "trc_template_probe");
const url = new URL(rendered, runtimeOrigin());
return url.protocol === "http:" || url.protocol === "https:";
} catch {
return false;
}
}
function runtimeOrigin(): string {
return typeof window.location?.origin === "string" && window.location.origin.length > 0
? window.location.origin
: "http://hwlab-cloud-web.local";
}
+1
View File
@@ -12,6 +12,7 @@ declare global {
autoExpandRunning?: boolean;
autoCollapseTerminal?: boolean;
};
traceExplorerUrlTemplate?: string;
};
};
__HWLAB_WORKBENCH_UI_TRACE__?: {
@@ -16,6 +16,28 @@ test("TraceTimeline renders readable rows and hides backend noise", async ({ pag
await saveScreenshot(page, testInfo, "trace-rendering-detail");
});
test("trace explorer link is gated by runtime config", async ({ page }) => {
await gotoWorkbench(page, "/workbench/sessions/ses_completed");
const card = page.locator(`${selectors.messageCard}[data-role="agent"]`).first();
await card.locator(".message-detail-button").click();
const dialog = page.locator(selectors.messageDetailDialog);
await expect(dialog.getByRole("button", { name: "复制 Trace" })).toBeVisible();
await expect(dialog.getByRole("link", { name: "打开 Trace" })).toHaveCount(0);
await dialog.getByRole("button", { name: "关闭" }).click();
await page.addInitScript(() => {
window.HWLAB_CLOUD_WEB_CONFIG = {
displayTime: { timeZone: "Asia/Shanghai", locale: "zh-CN", label: "北京时间" },
workbench: { traceExplorerUrlTemplate: "/v1/workbench/traces/{trace_id}/events" }
};
});
await page.reload();
await expect(page.locator(selectors.workspace)).toBeVisible();
const configuredCard = page.locator(`${selectors.messageCard}[data-role="agent"]`).first();
await configuredCard.locator(".message-detail-button").click();
await expect(dialog.getByRole("link", { name: "打开 Trace" })).toHaveAttribute("href", /\/v1\/workbench\/traces\/trc_completed\/events$/u);
});
test.describe("trace disclosure policy", () => {
test.use({ scenarioId: "event-replay" });