feat(infra): 落地 M01 基础框架与本机开发环境

交付 FastAPI/Celery/Vue 薄壳、FORCE RLS、Compose 回环与 review 修复证据,关闭 M01 DONE_LOCAL。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
unknownandCursor committed 2026-11-17 15:00:39 +08:00
1 parent 8b2a809f06
commit 8fb16f4a4a
97 files changed
+8059 -22

No files matched your search

+92
View File
@@ -0,0 +1,92 @@
import { expect, test } from "@playwright/test";
import path from "node:path";
import { fileURLToPath } from "node:url";
const evidenceDir = path.resolve(
path.dirname(fileURLToPath(import.meta.url)),
"../../../../docs/evidence/M01/ui",
);
test.describe("health three states", () => {
test("loading then success", async ({ page }) => {
await page.route("**/health", async (route) => {
await new Promise((resolve) => setTimeout(resolve, 800));
await route.fulfill({
status: 200,
contentType: "application/json",
body: JSON.stringify({
success: true,
data: { status: "ok", app: "watchman", version: "0.1.0" },
request_id: "pw-success",
}),
});
});
await page.goto("/");
await expect(page.getByTestId("health-loading")).toBeVisible();
await page.screenshot({
path: path.join(evidenceDir, "health-loading.png"),
fullPage: true,
});
await expect(page.getByTestId("health-success")).toBeVisible();
await expect(page.getByTestId("health-tag")).toContainText("健康检查成功");
await page.screenshot({
path: path.join(evidenceDir, "health-success.png"),
fullPage: true,
});
});
test("failure state", async ({ page }) => {
await page.route("**/health", async (route) => {
await route.fulfill({
status: 500,
contentType: "application/json",
body: JSON.stringify({
success: false,
error: {
code: 50000,
message: "Internal server error",
details: {},
retryable: true,
},
request_id: "pw-fail",
}),
});
});
await page.goto("/");
await expect(page.getByTestId("health-failure")).toBeVisible();
await expect(page.getByTestId("health-tag")).toContainText("健康检查失败");
await expect(page.getByTestId("health-failure")).toContainText("50000");
await page.screenshot({
path: path.join(evidenceDir, "health-failure.png"),
fullPage: true,
});
});
test("english locale via query override is readable", async ({ page }) => {
await page.addInitScript(() => {
window.localStorage.setItem("watchman.lang", "en");
});
await page.route("**/health", async (route) => {
await route.fulfill({
status: 200,
contentType: "application/json",
body: JSON.stringify({
success: true,
data: { status: "ok", app: "watchman", version: "0.1.0" },
request_id: "pw-en",
}),
});
});
await page.goto("/?lang=en");
await expect(page.getByTestId("health-tag")).toContainText("Health check succeeded");
await expect(page.getByTestId("health-success")).toBeVisible();
await page.screenshot({
path: path.join(evidenceDir, "health-success-en.png"),
fullPage: true,
});
});
});
+12
View File
@@ -0,0 +1,12 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Watchman</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
+10
View File
@@ -0,0 +1,10 @@
{
"appName": "Watchman",
"health": {
"loading": "Checking health",
"success": "Health check succeeded",
"failure": "Health check failed",
"successDetail": "Service available: {detail}",
"failureDetail": "Service unavailable: {detail}"
}
}
+8
View File
@@ -0,0 +1,8 @@
{
"codes": {
"40000": "Invalid parameters",
"41000": "Authentication failed",
"42000": "Permission denied",
"50000": "Service error"
}
}
+10
View File
@@ -0,0 +1,10 @@
{
"appName": "Watchman",
"health": {
"loading": "กำลังตรวจสอบสถานะ",
"success": "ตรวจสอบสถานะสำเร็จ",
"failure": "ตรวจสอบสถานะล้มเหลว",
"successDetail": "บริการพร้อมใช้งาน: {detail}",
"failureDetail": "บริการไม่พร้อมใช้งาน: {detail}"
}
}
+8
View File
@@ -0,0 +1,8 @@
{
"codes": {
"40000": "พารามิเตอร์ไม่ถูกต้อง",
"41000": "ยืนยันตัวตนล้มเหลว",
"42000": "ไม่มีสิทธิ์",
"50000": "ข้อผิดพลาดของบริการ"
}
}
@@ -0,0 +1,10 @@
{
"appName": "Watchman",
"health": {
"loading": "健康检查加载中",
"success": "健康检查成功",
"failure": "健康检查失败",
"successDetail": "服务可用:{detail}",
"failureDetail": "服务不可用:{detail}"
}
}
@@ -0,0 +1,8 @@
{
"codes": {
"40000": "参数错误",
"41000": "认证失败",
"42000": "权限不足",
"50000": "服务错误"
}
}
@@ -0,0 +1,10 @@
{
"appName": "Watchman",
"health": {
"loading": "健康檢查載入中",
"success": "健康檢查成功",
"failure": "健康檢查失敗",
"successDetail": "服務可用:{detail}",
"failureDetail": "服務不可用:{detail}"
}
}
@@ -0,0 +1,8 @@
{
"codes": {
"40000": "參數錯誤",
"41000": "認證失敗",
"42000": "權限不足",
"50000": "服務錯誤"
}
}
+34
View File
@@ -0,0 +1,34 @@
{
"name": "@watchman/console",
"private": true,
"version": "0.1.0",
"type": "module",
"scripts": {
"dev": "vite --host 127.0.0.1 --port 5173",
"build": "vue-tsc -b && vite build",
"typecheck": "vue-tsc --noEmit",
"test:unit": "vitest run",
"test:e2e": "playwright test",
"preview": "vite preview --host 127.0.0.1 --port 5173"
},
"dependencies": {
"@watchman/api": "workspace:*",
"element-plus": "^2.11.0",
"pinia": "^3.0.3",
"vue": "^3.5.22",
"vue-i18n": "^11.1.11",
"vue-router": "^4.5.1"
},
"devDependencies": {
"@playwright/test": "^1.65.1",
"@tailwindcss/vite": "^4.3.5",
"@vitejs/plugin-vue": "^6.0.1",
"@vue/test-utils": "^2.4.6",
"jsdom": "^26.1.0",
"tailwindcss": "^4.3.5",
"typescript": "~5.9.3",
"vite": "^7.1.7",
"vitest": "^3.2.4",
"vue-tsc": "^3.0.8"
}
}
+29
View File
@@ -0,0 +1,29 @@
import { defineConfig, devices } from "@playwright/test";
const evidenceDir = "../../../../docs/evidence/M01/ui";
export default defineConfig({
testDir: "./e2e",
fullyParallel: false,
forbidOnly: !!process.env.CI,
retries: 0,
reporter: [["list"], ["html", { open: "never", outputFolder: "playwright-report" }]],
use: {
baseURL: "http://127.0.0.1:5173",
trace: "on-first-retry",
locale: "zh-CN",
},
projects: [
{
name: "chromium",
use: { ...devices["Desktop Chrome"] },
},
],
webServer: {
command: "pnpm exec vite --host 127.0.0.1 --port 5173",
url: "http://127.0.0.1:5173",
reuseExistingServer: true,
timeout: 120_000,
},
outputDir: evidenceDir + "/test-results",
});
+123
View File
@@ -0,0 +1,123 @@
import { flushPromises, mount } from "@vue/test-utils";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { createI18n } from "vue-i18n";
import { BusinessError } from "@watchman/api";
import App from "./App.vue";
import zhCN from "../locales/zh-CN/common.json";
import en from "../locales/en/common.json";
vi.mock("@watchman/api", async () => {
const actual = await vi.importActual<typeof import("@watchman/api")>("@watchman/api");
return {
...actual,
requestJson: vi.fn(),
};
});
import { requestJson } from "@watchman/api";
const mockedRequestJson = vi.mocked(requestJson);
function mountApp(locale = "zh-CN") {
const i18n = createI18n({
legacy: false,
locale,
fallbackLocale: "zh-CN",
messages: {
"zh-CN": zhCN,
en,
// Intentionally omit th to prove fallbackLocale=zh-CN.
},
});
return mount(App, {
global: {
plugins: [i18n],
stubs: {
ElConfigProvider: { template: "<div><slot /></div>" },
ElCard: {
template:
'<div class="el-card"><div class="el-card__header"><slot name="header" /></div><slot /></div>',
},
ElTag: {
props: ["type"],
template: '<span data-testid="health-tag"><slot /></span>',
},
ElAlert: {
props: ["title", "type"],
template:
'<div :data-testid="type === \'success\' ? \'health-success\' : \'health-failure\'">{{ title }}</div>',
},
},
},
});
}
describe("App health three states", () => {
beforeEach(() => {
mockedRequestJson.mockReset();
});
it("shows loading before the request settles", async () => {
let resolveRequest: (value: unknown) => void = () => undefined;
mockedRequestJson.mockImplementation(
() =>
new Promise((resolve) => {
resolveRequest = resolve;
}),
);
const wrapper = mountApp();
expect(wrapper.get("[data-testid=health-loading]").text()).toContain("健康检查加载中");
resolveRequest({ status: "ok", app: "watchman", version: "0.1.0" });
await flushPromises();
});
it("shows success after a healthy response", async () => {
mockedRequestJson.mockResolvedValue({
status: "ok",
app: "watchman",
version: "0.1.0",
});
const wrapper = mountApp();
await flushPromises();
expect(wrapper.get("[data-testid=health-tag]").text()).toContain("健康检查成功");
expect(wrapper.get("[data-testid=health-success]").text()).toContain("watchman 0.1.0");
});
it("shows failure after a BusinessError", async () => {
mockedRequestJson.mockRejectedValue(
new BusinessError({
code: 50000,
message: "Internal server error",
status: 500,
requestId: "req-fail",
}),
);
const wrapper = mountApp();
await flushPromises();
expect(wrapper.get("[data-testid=health-tag]").text()).toContain("健康检查失败");
expect(wrapper.get("[data-testid=health-failure]").text()).toContain("50000");
});
it("falls back to zh-CN when locale messages are missing", async () => {
mockedRequestJson.mockResolvedValue({
status: "ok",
app: "watchman",
version: "0.1.0",
});
const wrapper = mountApp("th");
await flushPromises();
expect(wrapper.get("[data-testid=health-tag]").text()).toContain("健康检查成功");
});
it("shows english health copy when locale is en", async () => {
mockedRequestJson.mockResolvedValue({
status: "ok",
app: "watchman",
version: "0.1.0",
});
const wrapper = mountApp("en");
await flushPromises();
expect(wrapper.get("[data-testid=health-tag]").text()).toContain("Health check succeeded");
expect(wrapper.get("[data-testid=health-success]").text()).toContain("Service available");
});
});
+90
View File
@@ -0,0 +1,90 @@
<script setup lang="ts">
import { computed, onMounted, ref } from "vue";
import { useI18n } from "vue-i18n";
import { ElAlert, ElCard, ElConfigProvider, ElTag } from "element-plus";
import zhCn from "element-plus/es/locale/lang/zh-cn";
import zhTw from "element-plus/es/locale/lang/zh-tw";
import en from "element-plus/es/locale/lang/en";
import th from "element-plus/es/locale/lang/th";
import { requestJson } from "@watchman/api";
import {
healthFailureView,
healthSuccessView,
type HealthPayload,
type HealthState,
} from "./health";
const { t, locale } = useI18n();
const elementLocale = computed(() => {
switch (locale.value) {
case "zh-TW":
return zhTw;
case "en":
return en;
case "th":
return th;
default:
return zhCn;
}
});
const state = ref<HealthState>("loading");
const detail = ref("");
onMounted(async () => {
try {
const data = await requestJson<HealthPayload>("/health");
const view = healthSuccessView(data);
state.value = view.state;
detail.value = view.detail;
} catch (error) {
const view = healthFailureView(error);
state.value = view.state;
detail.value = view.detail;
}
});
</script>
<template>
<ElConfigProvider :locale="elementLocale">
<main class="min-h-screen p-8 bg-[var(--bg-surface-soft)] text-[length:var(--font-size-base)] text-[var(--text-primary)]">
<ElCard>
<template #header>
<div class="flex items-center justify-between gap-4">
<span>{{ t("appName") }}</span>
<span data-testid="health-tag">
<ElTag
:type="state === 'loading' ? 'info' : state === 'success' ? 'success' : 'danger'"
>
{{
state === "loading"
? t("health.loading")
: state === "success"
? t("health.success")
: t("health.failure")
}}
</ElTag>
</span>
</div>
</template>
<ElAlert
v-if="state === 'success'"
type="success"
data-testid="health-success"
:title="t('health.successDetail', { detail })"
show-icon
:closable="false"
/>
<ElAlert
v-else-if="state === 'failure'"
type="error"
data-testid="health-failure"
:title="t('health.failureDetail', { detail })"
show-icon
:closable="false"
/>
<p v-else data-testid="health-loading">{{ t("health.loading") }}</p>
</ElCard>
</main>
</ElConfigProvider>
</template>
+39
View File
@@ -0,0 +1,39 @@
import { describe, expect, it } from "vitest";
import { BusinessError } from "@watchman/api";
import { healthFailureView, healthSuccessView } from "./health";
describe("health view mapping", () => {
it("maps success payload", () => {
const view = healthSuccessView({
status: "ok",
app: "watchman",
version: "0.1.0",
});
expect(view).toEqual({
state: "success",
detail: "watchman 0.1.0",
});
});
it("maps BusinessError failure", () => {
const view = healthFailureView(
new BusinessError({
code: 50000,
message: "Service error",
status: 500,
requestId: "req-1",
}),
);
expect(view.state).toBe("failure");
expect(view.detail).toContain("50000");
expect(view.detail).toContain("Service error");
});
it("maps unknown failure", () => {
const view = healthFailureView(new Error("network down"));
expect(view).toEqual({
state: "failure",
detail: "Error: network down",
});
});
});
+39
View File
@@ -0,0 +1,39 @@
/**
* Health check presentation helpers for the M01 thin shell.
* Keeps fetch outcome mapping testable without mounting Element Plus.
*/
import { BusinessError } from "@watchman/api";
export type HealthState = "loading" | "success" | "failure";
export type HealthView = {
state: HealthState;
detail: string;
};
export type HealthPayload = {
status: string;
app: string;
version: string;
};
export function healthSuccessView(data: HealthPayload): HealthView {
return {
state: "success",
detail: `${data.app} ${data.version}`,
};
}
export function healthFailureView(error: unknown): HealthView {
if (error instanceof BusinessError) {
return {
state: "failure",
detail: `${error.code}: ${error.message}`,
};
}
return {
state: "failure",
detail: String(error),
};
}
+38
View File
@@ -0,0 +1,38 @@
import { createI18n } from "vue-i18n";
import zhCN from "../locales/zh-CN/common.json";
import zhTW from "../locales/zh-TW/common.json";
import en from "../locales/en/common.json";
import th from "../locales/th/common.json";
import zhCNErrors from "../locales/zh-CN/errors.json";
import zhTWErrors from "../locales/zh-TW/errors.json";
import enErrors from "../locales/en/errors.json";
import thErrors from "../locales/th/errors.json";
const supported = new Set(["zh-CN", "zh-TW", "en", "th"]);
function resolveLocale(): string {
if (typeof window !== "undefined") {
const fromQuery = new URLSearchParams(window.location.search).get("lang");
if (fromQuery && supported.has(fromQuery)) {
window.localStorage.setItem("watchman.lang", fromQuery);
return fromQuery;
}
const stored = window.localStorage.getItem("watchman.lang");
if (stored && supported.has(stored)) {
return stored;
}
}
return "zh-CN";
}
export const i18n = createI18n({
legacy: false,
locale: resolveLocale(),
fallbackLocale: "zh-CN",
messages: {
"zh-CN": { ...zhCN, ...zhCNErrors },
"zh-TW": { ...zhTW, ...zhTWErrors },
en: { ...en, ...enErrors },
th: { ...th, ...thErrors },
},
});
+12
View File
@@ -0,0 +1,12 @@
import { createApp } from "vue";
import { createPinia } from "pinia";
import "element-plus/dist/index.css";
import "element-plus/theme-chalk/dark/css-vars.css";
import "./styles.css";
import App from "./App.vue";
import { i18n } from "./i18n";
const app = createApp(App);
app.use(createPinia());
app.use(i18n);
app.mount("#app");
@@ -0,0 +1,24 @@
/* Map Element Plus skin vars to web/design/tokens.css (standards://frontend/element-plus). */
:root,
html.dark {
--el-color-primary: var(--color-primary);
--el-font-size-base: var(--font-size-base);
--el-font-size-small: 13px;
--el-font-size-extra-small: 12px;
--el-text-color-primary: var(--text-primary);
--el-text-color-regular: var(--text-secondary);
--el-text-color-secondary: var(--text-muted);
--el-border-color: var(--border-default);
--el-border-color-light: var(--border-subtle);
--el-border-color-lighter: var(--border-subtle);
--el-bg-color: var(--bg-surface);
--el-fill-color-light: var(--bg-surface-soft);
--el-border-radius-base: var(--radius-control);
--el-component-size: 32px;
}
/* Tailwind preflight sets svg { display:block }; keep Element button icons inline. */
.el-button svg {
display: inline-block;
vertical-align: middle;
}
+3
View File
@@ -0,0 +1,3 @@
@import "tailwindcss";
@import "../../../design/tokens.css";
@import "./shared/styles/element-theme.css";
+12
View File
@@ -0,0 +1,12 @@
/// <reference types="vite/client" />
declare module "*.vue" {
import type { DefineComponent } from "vue";
const component: DefineComponent<Record<string, unknown>, Record<string, unknown>, unknown>;
export default component;
}
declare module "*.json" {
const value: Record<string, unknown>;
export default value;
}
+19
View File
@@ -0,0 +1,19 @@
{
"compilerOptions": {
"target": "ES2022",
"useDefineForClassFields": true,
"module": "ESNext",
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"skipLibCheck": true,
"moduleResolution": "Bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "preserve",
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true
},
"include": ["src/**/*.ts", "src/**/*.vue"]
}
+15
View File
@@ -0,0 +1,15 @@
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import tailwindcss from "@tailwindcss/vite";
export default defineConfig({
plugins: [vue(), tailwindcss()],
server: {
host: "127.0.0.1",
port: 5173,
proxy: {
"/health": "http://127.0.0.1:8000",
"/platform": "http://127.0.0.1:8000",
},
},
});
+10
View File
@@ -0,0 +1,10 @@
import { defineConfig } from "vitest/config";
import vue from "@vitejs/plugin-vue";
export default defineConfig({
plugins: [vue()],
test: {
environment: "jsdom",
include: ["src/**/*.spec.ts"],
},
});
+12
View File
@@ -0,0 +1,12 @@
:root {
--color-primary: #5e6ad2;
--text-primary: #1f2328;
--text-secondary: #59636e;
--text-muted: #8b949e;
--bg-surface: #ffffff;
--bg-surface-soft: #f6f8fa;
--border-default: #d0d7de;
--border-subtle: #eaeef2;
--radius-control: 8px;
--font-size-base: 13.5px;
}
+13
View File
@@ -0,0 +1,13 @@
{
"name": "watchman-web",
"private": true,
"packageManager": "pnpm@12.21.0",
"scripts": {
"dev": "pnpm --filter @watchman/console dev",
"build": "pnpm -r build",
"typecheck": "pnpm -r typecheck"
},
"devDependencies": {
"typescript": "~5.9.3"
}
}
+16
View File
@@ -0,0 +1,16 @@
{
"name": "@watchman/api",
"private": true,
"version": "0.1.0",
"type": "module",
"exports": {
".": "./src/index.ts"
},
"scripts": {
"typecheck": "tsc --noEmit",
"build": "tsc --noEmit"
},
"devDependencies": {
"typescript": "~5.9.3"
}
}
+93
View File
@@ -0,0 +1,93 @@
/**
* Shared JSON API client.
* Parses the company success/error envelope and throws BusinessError on failure.
*/
export type ApiSuccess<T> = {
success: true;
data: T;
request_id: string;
};
export type ApiFailure = {
success: false;
error: {
code: number;
message: string;
details?: Record<string, unknown>;
retryable?: boolean;
permission_node?: string;
};
request_id: string;
};
export class BusinessError extends Error {
readonly code: number;
readonly details: Record<string, unknown>;
readonly status: number;
readonly requestId: string;
readonly retryable: boolean;
constructor(args: {
code: number;
message: string;
details?: Record<string, unknown>;
status: number;
requestId: string;
retryable?: boolean;
}) {
super(args.message);
this.name = "BusinessError";
this.code = args.code;
this.details = args.details ?? {};
this.status = args.status;
this.requestId = args.requestId;
this.retryable = args.retryable ?? false;
}
}
function requestIdFrom(response: Response): string {
return response.headers.get("X-Request-Id") ?? "unknown";
}
export async function requestJson<T>(
input: string,
init: RequestInit = {},
): Promise<T> {
const headers = new Headers(init.headers);
if (!headers.has("Accept")) {
headers.set("Accept", "application/json");
}
const response = await fetch(input, { ...init, headers });
let body: ApiSuccess<T> | ApiFailure;
try {
body = (await response.json()) as ApiSuccess<T> | ApiFailure;
} catch {
throw new BusinessError({
code: 50000,
message: "Invalid API envelope",
status: response.status,
requestId: requestIdFrom(response),
retryable: true,
});
}
if (!body || typeof body !== "object" || !("success" in body)) {
throw new BusinessError({
code: 50000,
message: "Invalid API envelope",
status: response.status,
requestId: requestIdFrom(response),
});
}
if (body.success) {
return body.data;
}
throw new BusinessError({
code: body.error.code,
message: body.error.message,
details: body.error.details,
status: response.status,
requestId: body.request_id,
retryable: body.error.retryable,
});
}
+12
View File
@@ -0,0 +1,12 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "Bundler",
"strict": true,
"skipLibCheck": true,
"noEmit": true,
"lib": ["ES2022", "DOM"]
},
"include": ["src"]
}
+11
View File
@@ -0,0 +1,11 @@
{
"name": "@watchman/ui-components",
"private": true,
"version": "0.1.0",
"description": "Placeholder package for shared Element Plus wrappers. Empty in M01 thin shell.",
"type": "module",
"scripts": {
"typecheck": "node -e \"process.exit(0)\"",
"build": "node -e \"process.exit(0)\""
}
}
+2677
View File
File diff suppressed because it is too large. Load diff
+5
View File
@@ -0,0 +1,5 @@
packages:
- "apps/*"
- "packages/*"
allowBuilds:
esbuild: true