将客户端页面重构为设备接入清单

This commit is contained in:
monster committed 2026-10-29 18:45:02 +08:00
1 parent 8be22a22a5
commit 0215257cbc
23 files changed
+2272 -209

No files matched your search

+15
View File
@@ -66,6 +66,21 @@ CHROME_BIN=/path/to/current-chrome pnpm test:browser:billing-users
此回归使用真实构建产物与模拟 API,覆盖键盘/鼠标选择、重名、刷新、分页、清空、旧文字查询、过期请求、失败重试和已删除用户。
## 客户端接入清单
客户端页面使用管理员接口 `/api/admin/v1/endpoints` 和 `/api/admin/v1/endpoints/overview`,以 `endpoints` 关联 `users` 展示当前登记信息;每行对应 `(user_id, machine_id)`,不依赖会话、对话上报。默认显示全部登记记录,包含已撤销登记及已删除用户;同一设备在不同用户下分别计为登记记录。设备升级后更新原记录,不累积版本历史。
默认仅展示用户、设备名称、操作系统、最近活动时间四列。系统版本、客户端类型/名称/版本、CPU 架构、语言、runtime/引擎版本、首次登记等可通过“选择列”开启,操作系统与系统版本保持独立。Electron 版本和发布渠道不在此清单中展示。首次登记为记录创建时间,最近活动为设备记录中最近可见与信息上报的较新时间,不将登记状态解读为在线状态。最新登记字段不足以追溯首次实际连接,多个客户端共用同一用户和设备 ID 时仍只保留一条登记。
搜索支持用户姓名/邮箱、设备名称/别名、客户端名称及设备 ID;操作系统、客户端类型、CPU、版本、登记状态和最近活动日期可独立筛选。最近活动默认不限制,支持单边日期;列表与三个分布使用同一筛选口径,页面不另显示标题、说明或登记数/用户数摘要。列表为 `page_size+1/has_next` 分页,默认 50,切换筛选或页容量回到第一页。图表分页独立,失败时分别重试。
```sh
CHROME_BIN=/path/to/chrome86 pnpm test:browser:client-devices
CHROME_BIN=/path/to/current-chrome pnpm test:browser:client-devices
```
回归使用真实构建产物和模拟 API,覆盖桌面/手机、中文/阿拉伯语、系统分列、旧设备显示、默认无时间限制、筛选、分页、单边日期、加载、独立失败重试及空页恢复。后端实际 PostgreSQL 测试验证没有任何会话的登记、跨用户设备 ID、当前字段更新、时间边界、空活动时间、已撤销/已删除记录、权限及返回字段白名单。
## 客户端登录授权
`/client-login` 登录后必须明确确认当前账号、实际返回地址和附加权限,空权限列表也不会自动完成。确认提交始终携带 `X-CSRF-Token` 和 `approved_scopes` 数组。后台仅允许登记的应用回调,或桌面端固定路径的本机回环动态端口(`localhost`、`127.0.0.1`、`[::1]`);前端还会核对最终返回地址与确认页展示的地址一致,拒绝外部网站、脚本 URL 和其他未登记目标。
+1
View File
@@ -15,6 +15,7 @@
"test:browser:groups": "node scripts/check-group-select.mjs",
"test:browser:models": "node scripts/check-model-config.mjs",
"test:browser:history": "node scripts/check-history-pagination.mjs",
"test:browser:client-devices": "node scripts/check-client-devices.mjs",
"test:browser:billing-users": "node scripts/check-billing-user-search.mjs",
"test:browser:auth": "node scripts/check-client-authorization.mjs",
"test:browser:branding": "node scripts/check-public-branding.mjs",
@@ -0,0 +1,498 @@
import assert from "node:assert/strict"
import { readFile, stat } from "node:fs/promises"
import path from "node:path"
import { fileURLToPath } from "node:url"
import { chromium } from "playwright-core"
import { zhCN } from "../src/i18n/locales/zh-CN.ts"
import { ar } from "../src/i18n/locales/ar.ts"
const executablePath = process.env.CHROME_BIN
if (!executablePath) throw new Error("请设置 CHROME_BIN;先执行 pnpm build")
const dist = fileURLToPath(new URL("../dist/", import.meta.url))
const browser = await chromium.launch({
executablePath,
args: ["--no-sandbox", "--disable-dev-shm-usage"],
})
const id = "00000000-0000-4000-8000-000000000001"
const mime = {
".html": "text/html",
".js": "text/javascript",
".css": "text/css",
".woff2": "font/woff2",
".png": "image/png",
".webp": "image/webp",
".svg": "image/svg+xml",
}
const gate = () => {
let release
const promise = new Promise((resolve) => {
release = resolve
})
return { promise, release }
}
// Avoid current Playwright visibility helpers, which need checkVisibility in Chrome 86.
async function click(page, selector, text) {
await page.evaluate(() => document.fonts.ready)
const handle = await page.waitForFunction(
({ selector, text }) => {
const el = [...document.querySelectorAll(selector)].find(
(el) =>
text === undefined ||
el.textContent.trim() === text ||
el.getAttribute("aria-label") === text
)
if (!el || el.disabled || el.getAttribute("aria-disabled") === "true")
return null
el.scrollIntoView({ block: "center", inline: "nearest" })
const r = el.getBoundingClientRect(),
x = r.x + r.width / 2,
y = r.y + r.height / 2
return el.contains(document.elementFromPoint(x, y)) ? { x, y } : null
},
{ selector, text }
)
const point = await handle.jsonValue()
await handle.dispose()
await page.mouse.click(point.x, point.y)
}
try {
for (const [locale, tr] of [
["zh-CN", zhCN],
["ar", ar],
])
for (const width of [1440, 390]) {
const labels = tr.pages.clientDevices
const page = await browser.newPage({
viewport: { width, height: 1000 },
locale,
timezoneId: "Asia/Shanghai",
})
page.setDefaultTimeout(15000)
await page.clock.setFixedTime(new Date("2026-10-29T10:20:30+08:00"))
await page.addInitScript((locale) => {
localStorage.setItem("monkeyai-admin-language", locale)
localStorage.setItem("theme", locale === "ar" ? "dark" : "light")
}, locale)
const errors = [],
lists = [],
overviews = [],
legacy = []
page.on("pageerror", (error) => errors.push(error.message))
const firstList = gate(),
firstOverview = gate()
let listWait = firstList.promise,
overviewWait = firstOverview.promise,
listMode = "data",
overviewMode = "data",
vanished = false
const rows = Array.from({ length: 51 }, (_, i) => ({
id: `10000000-0000-4000-8000-${String(i + 1).padStart(12, "0")}`,
user_id: id,
machine_id: `20000000-0000-4000-8000-${String(i + 1).padStart(12, "0")}`,
user_name: i === 0 ? "旧设备用户" : `成员 ${i}`,
user_email: `person-${i}@example.test`,
user_avatar_url: null,
user_deleted: i === 2,
device_name: `设备 ${i}`,
alias: i === 0 ? "办公室电脑" : null,
platform: i % 2 ? "linux" : "windows",
os_version: i % 2 ? "Ubuntu 24.04" : "11 24H2",
arch: "arm64",
client_type: "desktop",
client_name: "MonkeyAI Desktop",
client_version: "1.2.0",
runtime_version: "22.1.0",
engine_version: "1.9.0",
locale: "zh-CN",
system_locale: "en-US",
timezone: "Asia/Shanghai",
status: i === 2 ? "revoked" : "active",
created_at: "2025-01-01T00:00:00Z",
updated_at: "2025-01-02T00:00:00Z",
last_seen_at: "2025-01-02T00:00:00Z",
last_reported_at: null,
last_active_at: "2025-01-02T00:00:00Z",
}))
await page.route("**/*", async (route) => {
const url = new URL(route.request().url())
if (url.pathname.startsWith("/api/")) {
let body = {}
if (url.pathname.endsWith("/session"))
body = {
authenticated: true,
user: {
id,
name: "管理员",
email: "admin@example.test",
role: "admin",
status: "active",
},
}
else if (url.pathname.endsWith("/branding"))
body = { product_name: "百智办公" }
else if (url.pathname === "/api/admin/v1/endpoints/overview") {
overviews.push(url.searchParams)
await overviewWait
if (overviewMode === "error")
return route.fulfill({
status: 503,
json: { error: { message: "设备概览失败" } },
})
const total = overviewMode === "empty" ? 0 : 51
body = {
metric: "devices",
total,
users: total ? 3 : 0,
distributions: {
client_type: total ? [{ value: "desktop", count: 51 }] : [],
platform: total
? [
{ value: "windows", count: 26 },
{ value: "linux", count: 25 },
]
: [],
client_version: total ? [{ value: "1.2.0", count: 51 }] : [],
},
}
} else if (url.pathname === "/api/admin/v1/endpoints") {
lists.push(url.searchParams)
await listWait
if (listMode === "error")
return route.fulfill({
status: 503,
json: { error: { message: "设备列表失败" } },
})
const active = Number(url.searchParams.get("page") || 1),
size = Number(url.searchParams.get("page_size") || 50)
body = {
items:
listMode === "empty" || (vanished && active > 1)
? []
: rows.slice((active - 1) * size, active * size),
page: active,
page_size: size,
has_next: listMode !== "empty" && active * size < rows.length,
}
} else if (url.pathname.includes("session-reporting/clients"))
legacy.push(url.pathname)
return route.fulfill({ json: body })
}
let file = path.join(dist, decodeURIComponent(url.pathname))
if (!file.startsWith(dist))
return route.fulfill({ status: 404, body: "missing" })
if (!(await stat(file).catch(() => null))?.isFile())
file = path.join(dist, "index.html")
return route.fulfill({
contentType: mime[path.extname(file)] || "application/octet-stream",
body: await readFile(file),
})
})
const ready = () =>
page.waitForFunction(
() =>
document.querySelector('button[type="submit"]')?.disabled === false
)
const submit = async () => {
const count = lists.length
await ready()
await click(page, 'button[type="submit"]')
await ready()
assert.equal(lists.length, count + 1)
}
const assertSharedFilters = () => {
for (const key of ["query", "platform", "client_type", "from", "until"])
assert.equal(lists.at(-1).get(key), overviews.at(-1).get(key), key)
}
try {
await page.goto(
"http://monkeyai.test/console/statistics/session-reporting/clients"
)
await page.waitForFunction(
() =>
document.querySelectorAll('[role="figure"] [role="status"]')
.length === 3
)
assert.equal(
await page.locator('button[type="submit"]').isDisabled(),
true
)
firstList.release()
listWait = Promise.resolve()
await page.waitForFunction(
() => document.querySelectorAll("tbody tr").length === 50
)
assert.equal(
await page.locator('button[type="submit"]').isDisabled(),
true,
"search waits for the overview as well"
)
firstOverview.release()
overviewWait = Promise.resolve()
await ready()
for (const query of [...lists, ...overviews]) {
assert.equal(query.has("from"), false)
assert.equal(query.has("until"), false)
}
assert.deepEqual(
legacy,
[],
"inventory must not depend on session reports"
)
const heads = await page.locator("thead th").allTextContents()
assert.deepEqual(
heads,
["user", "device_name", "platform", "last_active_at"].map(
(field) => labels.fields[field]
)
)
assert.equal(
(await page.locator("section").textContent()).includes(
labels.description
),
false
)
await click(page, "button", labels.selectColumns)
await page.waitForFunction(
() =>
document.querySelectorAll('[role="menuitemcheckbox"]').length === 17
)
assert.equal(
await page.locator('[role="menuitemcheckbox"]').count(),
17
)
for (const field of [
"os_version",
"client_type",
"client_name",
"client_version",
"arch",
"locale",
"runtime_version",
"engine_version",
"created_at",
]) {
await click(page, '[role="menuitemcheckbox"]', labels.fields[field])
}
await page.keyboard.press("Escape")
const expandedHeads = await page.locator("thead th").allTextContents()
for (const field of [
"os_version",
"client_type",
"client_name",
"client_version",
"arch",
"locale",
"runtime_version",
"engine_version",
"created_at",
])
assert(expandedHeads.includes(labels.fields[field]), field)
const first = await page.locator("tbody tr").first().textContent()
for (const value of [
"旧设备用户",
"办公室电脑",
"Windows",
"11 24H2",
"arm64",
"MonkeyAI Desktop",
"1.2.0",
"22.1.0",
"1.9.0",
"2025",
])
assert(first.includes(value), value)
const beforePaging = overviews.length
await click(
page,
'[data-slot="table-pagination"] button',
tr.pages.operationLogs.pagination.next
)
await ready()
assert.equal(lists.at(-1).get("page"), "2")
assert.equal(overviews.length, beforePaging)
await click(
page,
'[data-slot="table-pagination"] button',
tr.pages.operationLogs.pagination.previous
)
await ready()
assert.equal(lists.at(-1).get("page"), "1")
const sizeTrigger = '[data-slot="table-pagination"] [role="combobox"]'
await click(page, sizeTrigger)
await click(
page,
'[role="option"]',
tr.pages.operationLogs.pagination.perPage.replace("{{count}}", "20")
)
await ready()
assert.equal(lists.at(-1).get("page_size"), "20")
assert.equal(overviews.length, beforePaging)
const prior = lists.length
await click(page, "#client-device-query")
await page.keyboard.insertText("旧设备用户")
assert.equal(lists.length, prior)
const slowList = gate(),
slowOverview = gate()
listWait = slowList.promise
overviewWait = slowOverview.promise
await click(page, 'button[type="submit"]')
await page.waitForFunction(
() => document.querySelector('button[type="submit"]').disabled
)
slowList.release()
listWait = Promise.resolve()
await page.waitForFunction(
() =>
document.querySelector("table").getAttribute("aria-busy") ===
"false"
)
assert.equal(
await page.locator('button[type="submit"]').isDisabled(),
true
)
slowOverview.release()
overviewWait = Promise.resolve()
await ready()
assertSharedFilters()
assert.equal(lists.at(-1).get("query"), "旧设备用户")
assert.equal(lists.at(-1).get("page"), "1")
await click(page, "button", tr.common.more)
await click(
page,
'[role="menuitemcheckbox"]',
labels.fields.last_active_at
)
await page.keyboard.press("Escape")
assert.equal(
await page.locator("#client-analysis-from").textContent(),
labels.activeFrom
)
assert.equal(
await page.locator("#client-analysis-until").textContent(),
labels.activeUntil
)
await click(page, "#client-analysis-from")
const day = await page.evaluate(
(locale) =>
new Date("2026-10-26T00:00:00+08:00").toLocaleDateString(locale),
locale
)
await click(page, `[data-slot="calendar"] button[data-day="${day}"]`)
await submit()
assert.equal(lists.at(-1).get("from"), "2026-10-25T16:00:00.000Z")
assertSharedFilters()
await click(page, "#client-analysis-from")
await click(page, `[data-slot="calendar"] button[data-day="${day}"]`)
await page.keyboard.press("Escape")
await submit()
assert.equal(lists.at(-1).has("from"), false)
assert.equal(lists.at(-1).has("until"), false)
overviewMode = "error"
await submit()
await page.waitForFunction(
() =>
document.querySelectorAll('[role="figure"] [role="alert"]')
.length === 3
)
const beforeRetry = lists.length
overviewMode = "data"
await click(page, '[role="figure"] button')
await ready()
assert.equal(lists.length, beforeRetry)
listMode = "error"
await submit()
await page.waitForFunction(() =>
document
.querySelector('div[role="alert"]')
?.textContent.includes("设备列表失败")
)
const oldOverview = overviews.length
listMode = "data"
await click(page, 'div[role="alert"] button')
await ready()
assert.equal(overviews.length, oldOverview)
listMode = "empty"
overviewMode = "empty"
await submit()
assert.equal(
await page.locator('[role="figure"] [data-slot="chart"]').count(),
0
)
assert.equal(await page.locator("tbody tr").count(), 1)
listMode = "data"
overviewMode = "data"
await submit()
vanished = true
await click(
page,
'[data-slot="table-pagination"] button',
tr.pages.operationLogs.pagination.next
)
await ready()
await page.waitForFunction(() =>
document
.querySelector('[data-slot="table-pagination"]')
.textContent.includes("1")
)
assert.equal(
lists.at(-1).get("page"),
"1",
"empty later page must recover"
)
assert.equal(
await page.evaluate(
() => document.documentElement.scrollWidth > innerWidth
),
false
)
assert.deepEqual(errors, [])
// Capture the default view after the interaction checks, without transient toasts.
await page.reload()
await ready()
assert.equal(await page.locator("#client-analysis-from").count(), 0)
const rowHeights = await page.evaluate(() =>
[...document.querySelectorAll("thead tr, tbody tr")]
.slice(0, 3)
.map((row) => row.getBoundingClientRect().height)
)
assert(
rowHeights.every((height) => Math.abs(height - 48) <= 1),
`table density: ${rowHeights}`
)
await page.waitForFunction(() => {
const cell = document.querySelector("tbody td")
cell.scrollIntoView({ block: "center", inline: "nearest" })
const r = cell.getBoundingClientRect()
return cell.contains(
document.elementFromPoint(r.x + r.width / 2, r.y + r.height / 2)
)
})
// Chrome 86 does not reliably paint beyond the viewport in full-page captures.
const height = await page.evaluate(() =>
Math.max(1000, Math.min(3000, document.documentElement.scrollHeight))
)
await page.setViewportSize({ width, height })
await page.evaluate(() => window.scrollTo(0, 0))
await page.screenshot({
path: `/tmp/monkeyai-client-devices-${locale}-${width}-${path.basename(executablePath)}.png`,
fullPage: true,
})
console.log(
`PASS client device inventory ${locale} ${width}: endpoint data, all-time defaults, split OS fields, metadata, pagination, filters, dates, independent retry, empty recovery`
)
} catch (error) {
await page.screenshot({
path: "/tmp/monkeyai-client-devices-failed.png",
fullPage: true,
})
console.error(await page.locator("body").textContent())
throw error
} finally {
firstList.release()
firstOverview.release()
await page.close()
}
}
} finally {
await browser.close()
}
@@ -17,9 +17,9 @@ import {
ChartTooltipContent,
} from "@/components/ui/chart"
import type {
ClientDistributionDimension,
ClientOverview,
} from "@/lib/session-reporting"
DeviceDistributionDimension,
DeviceOverview,
} from "@/lib/client-devices"
type DistributionItem = {
id: string
@@ -28,7 +28,7 @@ type DistributionItem = {
fill: string
}
const key = "pages.sessionReporting.clients.distribution"
const key = "pages.clientDevices.distribution"
const colors = [
"#3b82f6",
"#2dd4bf",
@@ -38,7 +38,7 @@ const colors = [
"#94a3b8",
]
const dimensions: {
field: ClientDistributionDimension
field: DeviceDistributionDimension
icon: IconSvgElement
}[] = [
{ field: "client_type", icon: ComputerIcon },
@@ -59,7 +59,7 @@ const platformLabels: Record<string, string> = {
}
function categoryColor(
field: ClientDistributionDimension,
field: DeviceDistributionDimension,
value: string | null
) {
if (value === null || value === "unknown") return colors[5]
@@ -157,7 +157,7 @@ function DistributionCard({
<div className="legacy-aspect-square relative aspect-square w-32 max-w-40 shrink-0 group-data-[container-wide=true]/distribution:w-[42%]">
{items.length ? (
<ChartContainer
config={{ count: { label: t(`${key}.sessions`) } }}
config={{ count: { label: t(`${key}.devices`) } }}
className="absolute inset-0 aspect-square h-full w-full"
role="img"
aria-label={`${title}: ${chartDescription}`}
@@ -200,7 +200,7 @@ function DistributionCard({
<li
key={item.id}
className="grid grid-cols-[minmax(0,1fr)_auto] items-center gap-x-2 text-xs"
title={`${item.label} · ${formatter.format(item.count)} ${t(`${key}.sessions`)}`}
title={`${item.label} · ${formatter.format(item.count)} ${t(`${key}.devices`)}`}
>
<span className="flex min-w-0 items-center gap-2">
<span
@@ -234,7 +234,7 @@ export function ClientDistributionCards({
error,
onRetry,
}: {
data?: ClientOverview
data?: DeviceOverview
loading: boolean
error?: string
onRetry: () => void
@@ -247,7 +247,7 @@ export function ClientDistributionCards({
({ value, count }) => ({
id: JSON.stringify(value),
label:
value === null
value === null || value === "unknown"
? t(`${key}.unknown`)
: field === "client_type"
? t(`${key}.types.${value}`, { defaultValue: value })
+53
View File
@@ -156,6 +156,59 @@ export const ar = {
systemSettings: "إعدادات النظام",
},
pages: {
clientDevices: {
title: "تسجيلات العملاء",
description: "يعرض كل صف أحدث بيانات العميل لمستخدم وجهاز واحد.",
records: "التسجيلات",
users: "المستخدمون",
search: "ابحث عن مستخدم أو جهاز أو عميل",
deletedUser: "محذوف",
activeFrom: "النشاط من",
activeUntil: "النشاط حتى",
invalidRange: "يجب ألا يسبق تاريخ النهاية تاريخ البداية.",
registeredHint: "وقت إنشاء سجل الجهاز، وليس أول محادثة أو اتصال.",
activityHint: "الوقت الأحدث بين آخر ظهور وتقرير المعلومات في سجل الجهاز.",
selectColumns: "اختيار الأعمدة",
statuses: {
active: "مسجل",
revoked: "ملغى",
},
fields: {
user: "المستخدم",
device_name: "اسم الجهاز",
platform: "نظام التشغيل",
os_version: "إصدار النظام",
client_type: "نوع العميل",
client_name: "اسم العميل",
client_version: "إصدار العميل",
arch: "معمارية CPU",
locale: "اللغة",
runtime_version: "إصدار Runtime",
engine_version: "إصدار المحرك",
created_at: "أول تسجيل",
last_active_at: "آخر نشاط",
system_locale: "لغة النظام",
timezone: "المنطقة الزمنية",
status: "حالة التسجيل",
machine_id: "معرف الجهاز",
},
distribution: {
client_type: "أنواع العملاء",
platform: "أنظمة التشغيل",
client_version: "إصدارات العملاء",
devices: "تسجيلات",
empty: "لا توجد بيانات مطابقة",
unknown: "غير معروف",
types: {
desktop: "سطح المكتب",
web: "الويب",
extension: "إضافة",
mobile: "جوال",
runtime: "Runtime",
unknown: "غير معروف",
},
},
},
license: enUS.pages.license,
realtimeStatus: {
title: "نظرة عامة على البيانات",
+55
View File
@@ -170,6 +170,61 @@ export const deDE = {
systemSettings: "Systemeinstellungen",
},
pages: {
clientDevices: {
title: "Clientregistrierungen",
description:
"Jede Zeile zeigt die aktuellen Clientdaten eines Benutzers und Geräts.",
records: "Registrierungen",
users: "Benutzer",
search: "Benutzer, Geräte oder Clients suchen",
deletedUser: "Gelöscht",
activeFrom: "Aktivität ab",
activeUntil: "Aktivität bis",
invalidRange: "Das Enddatum darf nicht vor dem Startdatum liegen.",
registeredHint:
"Erstellung des Gerätedatensatzes, nicht das erste Gespräch oder die erste Verbindung.",
activityHint: "Der neuere Zeitpunkt von letzter Sichtung und Gerätebericht im Gerätedatensatz.",
selectColumns: "Spalten auswählen",
statuses: {
active: "Registriert",
revoked: "Widerrufen",
},
fields: {
user: "Benutzer",
device_name: "Gerätename",
platform: "Betriebssystem",
os_version: "Betriebssystemversion",
client_type: "Clienttyp",
client_name: "Clientname",
client_version: "Clientversion",
arch: "CPU-Architektur",
locale: "Sprache",
runtime_version: "Runtime-Version",
engine_version: "Engine-Version",
created_at: "Erstmals registriert",
last_active_at: "Letzte Aktivität",
system_locale: "Systemsprache",
timezone: "Zeitzone",
status: "Registrierungsstatus",
machine_id: "Geräte-ID",
},
distribution: {
client_type: "Clienttypen",
platform: "Betriebssysteme",
client_version: "Clientversionen",
devices: "Registrierungen",
empty: "Keine passenden Daten",
unknown: "Unbekannt",
types: {
desktop: "Desktop",
web: "Web",
extension: "Erweiterung",
mobile: "Mobil",
runtime: "Runtime",
unknown: "Unbekannt",
},
},
},
license: enUS.pages.license,
realtimeStatus: {
title: "Datenübersicht",
+59 -1
View File
@@ -317,6 +317,61 @@ export const enUS = {
systemSettings: "System Settings",
},
pages: {
clientDevices: {
title: "Client registrations",
description:
"Each row shows the latest client details for one user and device.",
records: "Registrations",
users: "Users",
search: "Search users, devices, or clients",
deletedUser: "Deleted",
activeFrom: "Activity from",
activeUntil: "Activity through",
invalidRange: "End date must not precede start date.",
registeredHint:
"When the device record was created, not the first conversation or connection.",
activityHint: "The later of the device record’s last-seen time and information report.",
selectColumns: "Select columns",
statuses: {
active: "Registered",
revoked: "Revoked",
},
fields: {
user: "User",
device_name: "Device name",
platform: "Operating system",
os_version: "OS version",
client_type: "Client type",
client_name: "Client name",
client_version: "Client version",
arch: "CPU architecture",
locale: "Language",
runtime_version: "Runtime version",
engine_version: "Engine version",
created_at: "First registered",
last_active_at: "Last activity",
system_locale: "System language",
timezone: "Time zone",
status: "Registration status",
machine_id: "Device ID",
},
distribution: {
client_type: "Client types",
platform: "Operating systems",
client_version: "Client versions",
devices: "registrations",
empty: "No matching data",
unknown: "Unknown",
types: {
desktop: "Desktop",
web: "Web",
extension: "Extension",
mobile: "Mobile",
runtime: "Runtime",
unknown: "Unknown",
},
},
},
resourceImports: {
title: "Resource packages",
description: "Preview and apply a resource release",
@@ -444,7 +499,10 @@ export const enUS = {
title: "AI behavior",
description: "Resource availability and usage.",
},
clientAnalysis: { title: "Clients", description: "Client breakdown." },
clientAnalysis: {
title: "Clients",
description: "Device registrations, users, and client environments.",
},
resources: {
title: "Resource usage",
note: "Team connectors use gateway MCP facts; local tools use reported turn facts.",
+55
View File
@@ -165,6 +165,61 @@ export const es419 = {
systemSettings: "Configuración del sistema",
},
pages: {
clientDevices: {
title: "Clientes registrados",
description:
"Cada fila muestra los datos más recientes del cliente de un usuario y dispositivo.",
records: "Registros",
users: "Usuarios",
search: "Buscar usuarios, dispositivos o clientes",
deletedUser: "Eliminado",
activeFrom: "Actividad desde",
activeUntil: "Actividad hasta",
invalidRange: "La fecha final no puede ser anterior a la inicial.",
registeredHint:
"Fecha de creación del registro del dispositivo, no de la primera conversación o conexión.",
activityHint: "La fecha más reciente entre la última presencia y el informe de información del dispositivo.",
selectColumns: "Elegir columnas",
statuses: {
active: "Registrado",
revoked: "Revocado",
},
fields: {
user: "Usuario",
device_name: "Nombre del dispositivo",
platform: "Sistema operativo",
os_version: "Versión del sistema",
client_type: "Tipo de cliente",
client_name: "Nombre del cliente",
client_version: "Versión del cliente",
arch: "Arquitectura de CPU",
locale: "Idioma",
runtime_version: "Versión de Runtime",
engine_version: "Versión del motor",
created_at: "Primer registro",
last_active_at: "Última actividad",
system_locale: "Idioma del sistema",
timezone: "Zona horaria",
status: "Estado del registro",
machine_id: "ID del dispositivo",
},
distribution: {
client_type: "Tipos de cliente",
platform: "Sistemas operativos",
client_version: "Versiones de cliente",
devices: "registros",
empty: "No hay datos coincidentes",
unknown: "Desconocido",
types: {
desktop: "Escritorio",
web: "Web",
extension: "Extensión",
mobile: "Móvil",
runtime: "Runtime",
unknown: "Desconocido",
},
},
},
license: enUS.pages.license,
realtimeStatus: {
title: "Resumen de datos",
+55
View File
@@ -170,6 +170,61 @@ export const frFR = {
systemSettings: "Paramètres système",
},
pages: {
clientDevices: {
title: "Clients enregistrés",
description:
"Chaque ligne affiche les dernières informations du client pour un utilisateur et un appareil.",
records: "Enregistrements",
users: "Utilisateurs",
search: "Rechercher un utilisateur, appareil ou client",
deletedUser: "Supprimé",
activeFrom: "Activité depuis",
activeUntil: "Activité jusqu’au",
invalidRange: "La date de fin doit suivre ou égaler la date de début.",
registeredHint:
"Date de création de la fiche appareil, et non du premier échange ou de la première connexion.",
activityHint: "La plus récente entre la dernière présence et le rapport d’informations enregistrés pour l’appareil.",
selectColumns: "Choisir les colonnes",
statuses: {
active: "Enregistré",
revoked: "Révoqué",
},
fields: {
user: "Utilisateur",
device_name: "Nom de l’appareil",
platform: "Système d’exploitation",
os_version: "Version du système",
client_type: "Type de client",
client_name: "Nom du client",
client_version: "Version du client",
arch: "Architecture CPU",
locale: "Langue",
runtime_version: "Version Runtime",
engine_version: "Version du moteur",
created_at: "Premier enregistrement",
last_active_at: "Dernière activité",
system_locale: "Langue du système",
timezone: "Fuseau horaire",
status: "Statut d’enregistrement",
machine_id: "ID de l’appareil",
},
distribution: {
client_type: "Types de clients",
platform: "Systèmes d’exploitation",
client_version: "Versions des clients",
devices: "enregistrements",
empty: "Aucune donnée correspondante",
unknown: "Inconnu",
types: {
desktop: "Bureau",
web: "Web",
extension: "Extension",
mobile: "Mobile",
runtime: "Runtime",
unknown: "Inconnu",
},
},
},
license: enUS.pages.license,
realtimeStatus: {
title: "Vue d’ensemble des données",
+55
View File
@@ -163,6 +163,61 @@ export const jaJP = {
systemSettings: "システム設定",
},
pages: {
clientDevices: {
title: "クライアント登録一覧",
description:
"各行は、ユーザーと端末ごとに最新のクライアント情報を表示します。",
records: "登録数",
users: "ユーザー数",
search: "ユーザー、端末、クライアントを検索",
deletedUser: "削除済み",
activeFrom: "最終活動の開始日",
activeUntil: "最終活動の終了日",
invalidRange: "終了日は開始日以降にしてください。",
registeredHint:
"端末レコードの作成日時です。最初の会話や接続の日時ではありません。",
activityHint: "端末レコードの最終確認日時と情報報告日時のうち新しい日時です。",
selectColumns: "列を選択",
statuses: {
active: "登録済み",
revoked: "失効済み",
},
fields: {
user: "ユーザー",
device_name: "端末名",
platform: "OS",
os_version: "OS バージョン",
client_type: "クライアント種別",
client_name: "クライアント名",
client_version: "クライアントバージョン",
arch: "CPU アーキテクチャ",
locale: "言語",
runtime_version: "Runtime バージョン",
engine_version: "エンジンバージョン",
created_at: "初回登録",
last_active_at: "最終活動",
system_locale: "システム言語",
timezone: "タイムゾーン",
status: "登録状態",
machine_id: "端末 ID",
},
distribution: {
client_type: "クライアント種別",
platform: "OS の分布",
client_version: "クライアントバージョン",
devices: "件の登録",
empty: "一致するデータがありません",
unknown: "不明",
types: {
desktop: "デスクトップ",
web: "Web",
extension: "拡張機能",
mobile: "モバイル",
runtime: "Runtime",
unknown: "不明",
},
},
},
license: enUS.pages.license,
realtimeStatus: {
title: "データ概要",
+55
View File
@@ -157,6 +157,61 @@ export const koKR = {
systemSettings: "시스템 설정",
},
pages: {
clientDevices: {
title: "클라이언트 등록 목록",
description:
"각 행에는 사용자와 기기별 최신 클라이언트 정보가 표시됩니다.",
records: "등록 수",
users: "사용자 수",
search: "사용자, 기기 또는 클라이언트 검색",
deletedUser: "삭제됨",
activeFrom: "최근 활동 시작일",
activeUntil: "최근 활동 종료일",
invalidRange: "종료일은 시작일보다 빠를 수 없습니다.",
registeredHint:
"기기 기록이 처음 생성된 시간이며 최초 대화나 연결 시간이 아닙니다.",
activityHint: "기기 기록의 마지막 확인 시간과 정보 보고 시간 중 더 최근 시간입니다.",
selectColumns: "열 선택",
statuses: {
active: "등록됨",
revoked: "취소됨",
},
fields: {
user: "사용자",
device_name: "기기 이름",
platform: "운영 체제",
os_version: "OS 버전",
client_type: "클라이언트 유형",
client_name: "클라이언트 이름",
client_version: "클라이언트 버전",
arch: "CPU 아키텍처",
locale: "언어",
runtime_version: "Runtime 버전",
engine_version: "엔진 버전",
created_at: "최초 등록",
last_active_at: "최근 활동",
system_locale: "시스템 언어",
timezone: "시간대",
status: "등록 상태",
machine_id: "기기 ID",
},
distribution: {
client_type: "클라이언트 유형",
platform: "운영 체제 분포",
client_version: "클라이언트 버전",
devices: "개 등록",
empty: "일치하는 데이터 없음",
unknown: "알 수 없음",
types: {
desktop: "데스크톱",
web: "웹",
extension: "확장 프로그램",
mobile: "모바일",
runtime: "Runtime",
unknown: "알 수 없음",
},
},
},
license: enUS.pages.license,
realtimeStatus: {
title: "데이터 개요",
+55
View File
@@ -168,6 +168,61 @@ export const ruRU = {
systemSettings: "Системные настройки",
},
pages: {
clientDevices: {
title: "Зарегистрированные клиенты",
description:
"Каждая строка показывает последние данные клиента для пользователя и устройства.",
records: "Регистрации",
users: "Пользователи",
search: "Поиск пользователей, устройств или клиентов",
deletedUser: "Удалён",
activeFrom: "Активность с",
activeUntil: "Активность по",
invalidRange: "Конечная дата не может предшествовать начальной.",
registeredHint:
"Дата создания записи устройства, а не первого диалога или подключения.",
activityHint: "Более позднее время последнего обнаружения или отчёта в записи устройства.",
selectColumns: "Выбрать столбцы",
statuses: {
active: "Зарегистрировано",
revoked: "Отозвано",
},
fields: {
user: "Пользователь",
device_name: "Имя устройства",
platform: "Операционная система",
os_version: "Версия ОС",
client_type: "Тип клиента",
client_name: "Имя клиента",
client_version: "Версия клиента",
arch: "Архитектура CPU",
locale: "Язык",
runtime_version: "Версия Runtime",
engine_version: "Версия движка",
created_at: "Первая регистрация",
last_active_at: "Последняя активность",
system_locale: "Язык системы",
timezone: "Часовой пояс",
status: "Статус регистрации",
machine_id: "ID устройства",
},
distribution: {
client_type: "Типы клиентов",
platform: "Операционные системы",
client_version: "Версии клиентов",
devices: "регистраций",
empty: "Нет подходящих данных",
unknown: "Неизвестно",
types: {
desktop: "Настольный",
web: "Веб",
extension: "Расширение",
mobile: "Мобильный",
runtime: "Runtime",
unknown: "Неизвестно",
},
},
},
license: enUS.pages.license,
realtimeStatus: {
title: "Обзор данных",
+54 -1
View File
@@ -291,6 +291,59 @@ export const zhCN = {
systemSettings: "系统设置",
},
pages: {
clientDevices: {
title: "客户端接入记录",
description: "每行对应一个用户的一台设备,展示最近登记的客户端信息。",
records: "登记记录",
users: "使用用户",
search: "搜索用户、设备或客户端",
deletedUser: "已删除",
activeFrom: "最近活动起始",
activeUntil: "最近活动截止",
invalidRange: "结束日期不能早于开始日期。",
registeredHint: "设备记录首次创建时间,不代表首次对话或首次连接时间。",
activityHint: "设备记录中的最近可见时间与信息上报时间中较新者。",
selectColumns: "选择列",
statuses: {
active: "已登记",
revoked: "已撤销",
},
fields: {
user: "用户",
device_name: "设备名称",
platform: "操作系统",
os_version: "系统版本",
client_type: "客户端类型",
client_name: "客户端名称",
client_version: "客户端版本",
arch: "CPU 架构",
locale: "语言",
runtime_version: "Runtime 版本",
engine_version: "引擎版本",
created_at: "首次登记",
last_active_at: "最近活动时间",
system_locale: "系统语言",
timezone: "时区",
status: "登记状态",
machine_id: "设备 ID",
},
distribution: {
client_type: "客户端类型分布",
platform: "操作系统分布",
client_version: "客户端版本分布",
devices: "条登记",
empty: "无匹配数据",
unknown: "未知",
types: {
desktop: "桌面端",
web: "网页端",
extension: "扩展端",
mobile: "移动端",
runtime: "运行时",
unknown: "未知",
},
},
},
resourceImports: {
title: "资源包",
description: "预览并导入资源发布包",
@@ -417,7 +470,7 @@ export const zhCN = {
},
clientAnalysis: {
title: "客户端",
description: "查看客户端维度统计。",
description: "查看接入设备、使用用户和客户端环境。",
},
resources: {
title: "资源使用",
+53
View File
@@ -146,6 +146,59 @@ export const zhTW = {
systemSettings: "系統設定",
},
pages: {
clientDevices: {
title: "用戶端接入記錄",
description: "每列對應一位使用者的一台裝置,顯示最近登記的用戶端資訊。",
records: "登記記錄",
users: "使用者",
search: "搜尋使用者、裝置或用戶端",
deletedUser: "已刪除",
activeFrom: "最近活動起始",
activeUntil: "最近活動截止",
invalidRange: "結束日期不可早於開始日期。",
registeredHint: "裝置記錄首次建立時間,不代表首次對話或連線時間。",
activityHint: "裝置記錄中的最近可見時間與資訊上報時間中較新者。",
selectColumns: "選擇欄位",
statuses: {
active: "已登記",
revoked: "已撤銷",
},
fields: {
user: "使用者",
device_name: "裝置名稱",
platform: "作業系統",
os_version: "系統版本",
client_type: "用戶端類型",
client_name: "用戶端名稱",
client_version: "用戶端版本",
arch: "CPU 架構",
locale: "語言",
runtime_version: "Runtime 版本",
engine_version: "引擎版本",
created_at: "首次登記",
last_active_at: "最近活動",
system_locale: "系統語言",
timezone: "時區",
status: "登記狀態",
machine_id: "裝置 ID",
},
distribution: {
client_type: "用戶端類型分佈",
platform: "作業系統分佈",
client_version: "用戶端版本分佈",
devices: "筆登記",
empty: "無符合資料",
unknown: "未知",
types: {
desktop: "桌面端",
web: "網頁端",
extension: "擴充功能",
mobile: "行動端",
runtime: "執行階段",
unknown: "未知",
},
},
},
license: {
title: "付費授權",
description: "用於查看與管理付費授權",
+81
View File
@@ -0,0 +1,81 @@
export type DeviceFilters = Partial<
Record<
| "query"
| "user_id"
| "platform"
| "client_type"
| "client_version"
| "arch"
| "status"
| "from"
| "until",
string
>
>
export type ClientDevice = {
id: string
user_id: string
machine_id: string
user_name: string | null
user_email: string | null
user_avatar_url: string | null
user_deleted: boolean
device_name: string
alias: string | null
platform: string
os_version: string
arch: string
client_type: string | null
client_name: string | null
client_version: string
locale: string | null
system_locale: string | null
timezone: string | null
runtime_version: string | null
engine_version: string | null
status: "active" | "revoked"
created_at: string
updated_at: string
last_seen_at: string | null
last_reported_at: string | null
last_active_at: string | null
}
export type DevicePage = {
items: ClientDevice[]
page: number
page_size: number
has_next: boolean
}
export type DeviceDistributionDimension =
"client_type" | "platform" | "client_version"
export type DeviceOverview = {
metric: "devices"
total: number
users: number
distributions: Record<
DeviceDistributionDimension,
{ value: string | null; count: number }[]
>
}
export const devicePaths = {
list: "/api/admin/v1/endpoints",
overview: "/api/admin/v1/endpoints/overview",
}
export function deviceQuery(filters: DeviceFilters) {
const query = new URLSearchParams()
for (const [key, value] of Object.entries(filters))
if (value?.trim()) query.set(key, value.trim())
return query.toString()
}
export function devicePlatform(value: string) {
const labels: Record<string, string> = {
windows: "Windows",
macos: "macOS",
linux: "Linux",
ios: "iOS",
android: "Android",
web: "Web",
}
const key = value.toLowerCase()
return Object.hasOwn(labels, key) ? labels[key] : value
}
+287 -197
View File
@@ -7,12 +7,12 @@ import {
import { HugeiconsIcon } from "@hugeicons/react"
import { addDays } from "date-fns"
import { useTranslation } from "react-i18next"
import { TablePagination } from "@/components/table-pagination"
import { TableLoading } from "@/components/table-loading"
import { useAppToast } from "@/components/animated-toast-provider"
import { ClientDistributionCards } from "@/components/client-distribution-cards"
import { DatePickerField } from "@/components/date-picker-field"
import { TablePagination } from "@/components/table-pagination"
import { TableLoading } from "@/components/table-loading"
import { UserAvatar } from "@/components/user-avatar"
import { Button } from "@/components/ui/button"
import { Card, CardContent } from "@/components/ui/card"
import {
@@ -26,13 +26,6 @@ import {
} from "@/components/ui/dropdown-menu"
import { Input } from "@/components/ui/input"
import { ScrollArea } from "@/components/ui/scroll-area"
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select"
import {
Table,
TableBody,
@@ -42,139 +35,150 @@ import {
TableRow,
} from "@/components/ui/table"
import { api } from "@/lib/api"
import {
devicePaths,
devicePlatform,
deviceQuery,
type ClientDevice,
type DeviceFilters,
type DeviceOverview,
type DevicePage,
} from "@/lib/client-devices"
import { startOfLocalDay } from "@/lib/date-range"
import {
defaultWindow,
reportPaths,
reportQuery,
type ClientOverview,
type ReportClient,
type ReportPage,
type ReportWindow,
} from "@/lib/session-reporting"
import { TABLE_DATE_TIME_OPTIONS } from "@/lib/date-time"
import { cn } from "@/lib/utils"
import {
ReportNumber,
ReportTime,
ReportValue,
} from "@/pages/session-reporting-page"
type ClientColumn = Exclude<keyof ReportClient, "sort_key">
type ClientColumn =
| "user"
| "device_name"
| "platform"
| "os_version"
| "client_type"
| "client_name"
| "client_version"
| "arch"
| "locale"
| "system_locale"
| "timezone"
| "runtime_version"
| "engine_version"
| "status"
| "machine_id"
| "created_at"
| "last_active_at"
type ClientSearchField =
| "client_type"
| "platform"
| "outcome"
| "user_id"
| "group_id"
| "model_id"
| "expert_id"
const key = "pages.sessionReporting"
| "arch"
| "client_version"
| "status"
| "last_active_at"
const key = "pages.clientDevices"
const columns: ClientColumn[] = [
"client_type",
"user",
"device_name",
"platform",
"os_version",
"client_type",
"client_name",
"client_version",
"engine_version",
"runtime_version",
"arch",
"locale",
"timezone",
"sessions",
"turns",
"interrupted",
"completion_rate",
"anomaly_rate",
"p95_duration_seconds",
"runtime_version",
"engine_version",
"created_at",
"last_active_at",
"system_locale",
"timezone",
"status",
"machine_id",
]
const defaultColumns: ClientColumn[] = [
"client_type",
"user",
"device_name",
"platform",
"os_version",
"client_version",
"last_active_at",
]
const searchFields: ClientSearchField[] = [
"client_type",
"platform",
"outcome",
"user_id",
"group_id",
"model_id",
"expert_id",
"arch",
"client_version",
"status",
"last_active_at",
]
const clientTypes = [
"desktop",
"web",
"extension",
"mobile",
"runtime",
"unknown",
]
const selectValues = {
client_type: ["desktop", "web", "extension", "mobile", "runtime", "unknown"],
outcome: [
"complete",
"interrupted",
"error",
"max_turns",
"output_limit",
"unknown",
],
}
export function ClientAnalysisPage() {
const { i18n, t } = useTranslation()
const { showToast } = useAppToast()
const [filters, setFilters] = useState<ReportWindow>(defaultWindow)
const [draft, setDraft] = useState<ReportWindow>(filters)
const [startDay, setStartDay] = useState<Date>()
const [endDay, setEndDay] = useState<Date>()
const [filters, setFilters] = useState<DeviceFilters>({})
const [draft, setDraft] = useState<DeviceFilters>({})
const [visibleFields, setVisibleFields] = useState<Set<ClientSearchField>>(
() => new Set(["client_type"])
() => new Set(["client_type", "platform"])
)
const [visibleColumns, setVisibleColumns] = useState<Set<ClientColumn>>(
() => new Set(defaultColumns)
)
const [invalidRange, setInvalidRange] = useState(false)
const [cursors, setCursors] = useState<(string | undefined)[]>([undefined])
const [active, setActive] = useState(0)
const [page, setPage] = useState(1)
const [pageSize, setPageSize] = useState(50)
const [revision, setRevision] = useState(0)
const [listRetry, setListRetry] = useState(0)
const [overviewRetry, setOverviewRetry] = useState(0)
const [overviewResponse, setOverviewResponse] = useState<{
key: string
data?: ClientOverview
data?: DeviceOverview
error?: string
}>()
const searchRevisionRef = useRef<number | null>(null)
const [data, setData] = useState<ReportPage<ReportClient>>()
const [data, setData] = useState<DevicePage>()
const [loading, setLoading] = useState(true)
const [searching, setSearching] = useState(false)
const [error, setError] = useState<string>()
const displayedColumns = columns.filter((column) =>
visibleColumns.has(column)
)
const items = data?.items ?? []
const path = `${reportPaths.clients}${reportQuery(filters, cursors[active])}&limit=${pageSize}`
const overviewPath = `${reportPaths.clientsOverview}${reportQuery(filters)}`
const startDay = draft.from
? startOfLocalDay(new Date(draft.from))
: undefined
const endDay = draft.until
? startOfLocalDay(new Date(new Date(draft.until).getTime() - 1))
: undefined
const query = deviceQuery(filters)
const path = `${devicePaths.list}?${query}&page=${page}&page_size=${pageSize}`
const overviewPath = `${devicePaths.overview}?${query}`
const overviewKey = `${overviewPath}:${revision}:${overviewRetry}`
const overviewLoading = overviewResponse?.key !== overviewKey
const overview = overviewLoading ? undefined : overviewResponse.data
const overviewError = overviewLoading ? undefined : overviewResponse.error
const searchBusy = searching || (revision > 0 && overviewLoading)
const items = data?.items ?? []
const displayedColumns = columns.filter((column) =>
visibleColumns.has(column)
)
const timeFormatter = new Intl.DateTimeFormat(
i18n.resolvedLanguage ?? i18n.language,
TABLE_DATE_TIME_OPTIONS
)
useEffect(() => {
const controller = new AbortController()
api<ClientOverview>(overviewPath, {
void api<DeviceOverview>(overviewPath, {
signal: controller.signal,
cache: "no-store",
})
.then((result) => {
if (!controller.signal.aborted) {
if (!controller.signal.aborted)
setOverviewResponse({ key: overviewKey, data: result })
}
})
.catch((reason: unknown) => {
if (!controller.signal.aborted) {
setOverviewResponse({
key: overviewKey,
error: reason instanceof Error ? reason.message : String(reason),
})
}
.catch((reason: Error) => {
if (!controller.signal.aborted)
setOverviewResponse({ key: overviewKey, error: reason.message })
})
return () => controller.abort()
}, [overviewPath, overviewKey])
@@ -186,29 +190,27 @@ export function ClientAnalysisPage() {
setLoading(true)
setError(undefined)
}
api<ReportPage<ReportClient>>(path, {
signal: controller.signal,
cache: "no-store",
})
void api<DevicePage>(path, { signal: controller.signal, cache: "no-store" })
.then((result) => {
if (controller.signal.aborted) return
if (result.items.length === 0 && page > 1) {
setPage(1)
return
}
setData(result)
setError(undefined)
if (isSearch) {
if (isSearch)
showToast({
status: "success",
title: t("pages.operationLogs.filters.searchSuccess"),
})
}
})
.catch((reason: unknown) => {
.catch((reason: Error) => {
if (controller.signal.aborted) return
const message =
reason instanceof Error ? reason.message : String(reason)
setError(message)
setError(reason.message)
showToast({
status: "error",
title: message,
title: reason.message,
...(!isSearch && {
action: {
label: t("statistics.retry"),
@@ -226,50 +228,85 @@ export function ClientAnalysisPage() {
}
})
return () => controller.abort()
}, [path, revision, listRetry, showToast, t])
}, [path, page, revision, listRetry, showToast, t])
function applySearch(event: FormEvent<HTMLFormElement>) {
event.preventDefault()
if (loading || searchBusy || overviewLoading) return
if (
Boolean(startDay) !== Boolean(endDay) ||
(startDay &&
endDay &&
startOfLocalDay(startDay) > startOfLocalDay(endDay))
draft.from &&
draft.until &&
new Date(draft.from) >= new Date(draft.until)
) {
setInvalidRange(true)
return
}
setInvalidRange(false)
setError(undefined)
const timeWindow = defaultWindow()
setFilters({
...draft,
from: startDay
? startOfLocalDay(startDay).toISOString()
: timeWindow.from,
until: endDay
? startOfLocalDay(addDays(endDay, 1)).toISOString()
: timeWindow.until,
})
setCursors([undefined])
setActive(0)
setFilters({ ...draft })
setPage(1)
const nextRevision = revision + 1
searchRevisionRef.current = nextRevision
setSearching(true)
setRevision(nextRevision)
}
function renderCell(row: ReportClient, column: ClientColumn) {
if (column === "last_active_at")
return <ReportTime value={row.last_active_at} />
if (column === "completion_rate" || column === "anomaly_rate") {
return <ReportNumber value={row[column]} suffix="%" />
function renderCell(row: ClientDevice, column: ClientColumn) {
if (column === "user")
return (
<span
className="flex items-center gap-2"
title={`${row.user_name || ""} ${row.user_email || ""} ${row.user_id}`}
>
<UserAvatar src={row.user_avatar_url} />
<span className="min-w-0">
<span className="block max-w-40 truncate">
{row.user_name || row.user_email || row.user_id}
{row.user_deleted ? ` · ${t(`${key}.deletedUser`)}` : ""}
</span>
<span className="block max-w-40 truncate text-xs text-muted-foreground">
{row.user_email || row.user_id}
</span>
</span>
</span>
)
if (column === "device_name")
return (
<span
className="block max-w-48 truncate"
title={`${row.alias || row.device_name} · ${row.machine_id}`}
>
{row.alias || row.device_name}
</span>
)
if (column === "created_at" || column === "last_active_at") {
const value = row[column]
return (
<span title={value || undefined}>
{value && !Number.isNaN(Date.parse(value))
? timeFormatter.format(new Date(value))
: "—"}
</span>
)
}
if (column === "p95_duration_seconds") {
return <ReportNumber value={row[column]} suffix="s" />
}
return <ReportValue value={row[column]} />
if (column === "platform") return devicePlatform(row.platform)
if (column === "client_type")
return row.client_type
? t(`pages.clientDevices.distribution.types.${row.client_type}`, {
defaultValue: row.client_type,
})
: "—"
if (column === "status") return t(`${key}.statuses.${row.status}`)
const value = row[column]
return (
<span className="block max-w-48 truncate" title={value || undefined}>
{!value
? "—"
: value === "unknown"
? t("pages.clientDevices.distribution.unknown")
: value}
</span>
)
}
return (
@@ -286,25 +323,19 @@ export function ClientAnalysisPage() {
onSubmit={applySearch}
className="flex flex-wrap items-center gap-2 px-[var(--card-spacing)]"
>
<DatePickerField
id="client-analysis-from"
className="w-32 sm:w-32"
label={t("audit.since")}
placeholder={t("audit.since")}
locale={i18n.resolvedLanguage ?? i18n.language}
value={startDay}
onChange={setStartDay}
disabled={endDay ? { after: endDay } : undefined}
/>
<DatePickerField
id="client-analysis-until"
className="w-32 sm:w-32"
label={t("audit.until")}
placeholder={t("audit.until")}
locale={i18n.resolvedLanguage ?? i18n.language}
value={endDay}
onChange={setEndDay}
disabled={startDay ? { before: startDay } : undefined}
<Input
id="client-device-query"
className="w-56"
maxLength={200}
placeholder={t(`${key}.search`)}
aria-label={t(`${key}.search`)}
value={draft.query ?? ""}
onChange={(event) =>
setDraft((current) => ({
...current,
query: event.target.value,
}))
}
/>
{visibleFields.has("client_type") && (
<DropdownMenu>
@@ -319,14 +350,19 @@ export function ClientAnalysisPage() {
/>
}
>
{draft.client_type || t(`${key}.fields.client_type`)}
{draft.client_type
? t(
`pages.clientDevices.distribution.types.${draft.client_type}`,
{ defaultValue: draft.client_type }
)
: t(`${key}.fields.client_type`)}
</DropdownMenuTrigger>
<DropdownMenuContent align="start">
<DropdownMenuGroup>
<DropdownMenuLabel>
{t(`${key}.fields.client_type`)}
</DropdownMenuLabel>
{selectValues.client_type.map((value) => (
{clientTypes.map((value) => (
<DropdownMenuCheckboxItem
key={value}
checked={draft.client_type === value}
@@ -337,7 +373,7 @@ export function ClientAnalysisPage() {
}))
}
>
{value}
{t(`pages.clientDevices.distribution.types.${value}`)}
</DropdownMenuCheckboxItem>
))}
</DropdownMenuGroup>
@@ -346,7 +382,7 @@ export function ClientAnalysisPage() {
)}
{visibleFields.has("platform") && (
<Input
className="w-40"
className="w-32"
maxLength={64}
placeholder={t(`${key}.fields.platform`)}
aria-label={t(`${key}.fields.platform`)}
@@ -359,53 +395,90 @@ export function ClientAnalysisPage() {
}
/>
)}
{visibleFields.has("outcome") && (
<Select
value={draft.outcome || "__all__"}
onValueChange={(value) =>
setDraft((current) => ({
...current,
outcome: value === "__all__" ? "" : (value ?? ""),
}))
}
>
<SelectTrigger
aria-label={t(`${key}.fields.outcome`)}
className="min-w-32"
>
<SelectValue placeholder={t(`${key}.fields.outcome`)} />
</SelectTrigger>
<SelectContent>
<SelectItem value="__all__">
{t(`${key}.fields.outcome`)}
</SelectItem>
{selectValues.outcome.map((option) => (
<SelectItem key={option} value={option}>
{t(`${key}.outcomes.${option}`)}
</SelectItem>
))}
</SelectContent>
</Select>
)}
{(["user_id", "group_id", "model_id", "expert_id"] as const).map(
{(["arch", "client_version"] as const).map(
(field) =>
visibleFields.has(field) && (
<Input
key={field}
className="w-40"
pattern="[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}"
className="w-32"
maxLength={field === "arch" ? 32 : 64}
placeholder={t(`${key}.fields.${field}`)}
aria-label={t(`${key}.fields.${field}`)}
value={draft[field] ?? ""}
onChange={(event) =>
setDraft((current) => ({
...current,
[field]: event.target.value.trim(),
[field]: event.target.value,
}))
}
/>
)
)}
{visibleFields.has("status") && (
<DropdownMenu>
<DropdownMenuTrigger
render={<Button type="button" variant="outline" />}
>
{draft.status
? t(`${key}.statuses.${draft.status}`)
: t(`${key}.fields.status`)}
</DropdownMenuTrigger>
<DropdownMenuContent align="start">
<DropdownMenuGroup>
{["active", "revoked"].map((value) => (
<DropdownMenuCheckboxItem
key={value}
checked={draft.status === value}
onCheckedChange={(checked) =>
setDraft((current) => ({
...current,
status: checked ? value : "",
}))
}
>
{t(`${key}.statuses.${value}`)}
</DropdownMenuCheckboxItem>
))}
</DropdownMenuGroup>
</DropdownMenuContent>
</DropdownMenu>
)}
{visibleFields.has("last_active_at") && (
<>
<DatePickerField
id="client-analysis-from"
className="w-40 sm:w-40"
label={t(`${key}.activeFrom`)}
placeholder={t(`${key}.activeFrom`)}
locale={i18n.resolvedLanguage ?? i18n.language}
value={startDay}
onChange={(value) =>
setDraft((current) => ({
...current,
from: value ? startOfLocalDay(value).toISOString() : "",
}))
}
disabled={endDay ? { after: endDay } : undefined}
/>
<DatePickerField
id="client-analysis-until"
className="w-40 sm:w-40"
label={t(`${key}.activeUntil`)}
placeholder={t(`${key}.activeUntil`)}
locale={i18n.resolvedLanguage ?? i18n.language}
value={endDay}
onChange={(value) =>
setDraft((current) => ({
...current,
until: value
? startOfLocalDay(addDays(value, 1)).toISOString()
: "",
}))
}
disabled={startDay ? { before: startDay } : undefined}
/>
</>
)}
<DropdownMenu>
<DropdownMenuTrigger
render={<Button type="button" variant="outline" />}
@@ -422,14 +495,20 @@ export function ClientAnalysisPage() {
<DropdownMenuCheckboxItem
key={field}
checked={visibleFields.has(field)}
onCheckedChange={(checked) =>
onCheckedChange={(checked) => {
setVisibleFields((current) => {
const next = new Set(current)
if (checked) next.add(field)
else next.delete(field)
return next
})
}
if (!checked)
setDraft((current) =>
field === "last_active_at"
? { ...current, from: "", until: "" }
: { ...current, [field]: "" }
)
}}
>
{t(`${key}.fields.${field}`)}
</DropdownMenuCheckboxItem>
@@ -458,7 +537,7 @@ export function ClientAnalysisPage() {
<Button type="button" variant="outline" className="ms-auto" />
}
>
{t(`${key}.clients.selectColumns`)}
{t("pages.clientDevices.selectColumns")}
</DropdownMenuTrigger>
<DropdownMenuOptionsContent align="end" className="max-h-80">
<DropdownMenuGroup>
@@ -484,12 +563,16 @@ export function ClientAnalysisPage() {
</DropdownMenu>
{invalidRange && (
<p role="alert" className="text-sm text-destructive">
{t(`${key}.invalidFilter`)}
{t(`${key}.invalidRange`)}
</p>
)}
</form>
{error && (
<div className="px-[var(--card-spacing)]">
<div
role="alert"
className="flex items-center gap-2 px-[var(--card-spacing)]"
>
<span className="text-sm text-destructive">{error}</span>
<Button
variant="outline"
onClick={() => setListRetry((value) => value + 1)}
@@ -507,13 +590,23 @@ export function ClientAnalysisPage() {
!items.length && "h-full",
"[&_td:first-child]:ps-[var(--card-spacing)] [&_td:last-child]:pe-[var(--card-spacing)] [&_th:first-child]:ps-[var(--card-spacing)] [&_th:last-child]:pe-[var(--card-spacing)]"
)}
aria-label={t(`${key}.clients.title`)}
aria-label={t(`${key}.title`)}
aria-busy={loading || searching}
>
<TableHeader className="sticky top-0 z-10">
<TableRow>
{displayedColumns.map((column) => (
<TableHead key={column} className="whitespace-nowrap">
<TableHead
key={column}
className="whitespace-nowrap"
title={
column === "created_at"
? t(`${key}.registeredHint`)
: column === "last_active_at"
? t(`${key}.activityHint`)
: undefined
}
>
{t(`${key}.fields.${column}`)}
</TableHead>
))}
@@ -522,13 +615,14 @@ export function ClientAnalysisPage() {
<TableBody>
{items.length ? (
items.map((row) => (
<TableRow key={row.sort_key}>
<TableRow key={row.id}>
{displayedColumns.map((column) => (
<TableCell
key={column}
className={cn(
"whitespace-nowrap",
column === "last_active_at" &&
(column === "created_at" ||
column === "last_active_at") &&
"text-muted-foreground"
)}
>
@@ -557,23 +651,19 @@ export function ClientAnalysisPage() {
</Table>
</ScrollArea>
<TablePagination
page={active + 1}
page={page}
pageSize={pageSize}
itemCount={items.length}
loading={loading || searching}
error={Boolean(error)}
hasNext={Boolean(data?.next_cursor)}
hasNext={Boolean(data?.has_next)}
onPageSizeChange={(size) => {
setPageSize(size)
setCursors([undefined])
setActive(0)
setPage(1)
}}
onPrevious={() => setActive((value) => Math.max(0, value - 1))}
onPrevious={() => setPage((value) => Math.max(1, value - 1))}
onNext={() => {
const next = data?.next_cursor
if (!next) return
setCursors((current) => [...current.slice(0, active + 1), next])
setActive((value) => value + 1)
if (data?.has_next) setPage((value) => value + 1)
}}
/>
</CardContent>
@@ -48,6 +48,7 @@ for (const page of [
"taskHistory",
"billingDetails",
"billingSettings",
"clientDevices",
]) {
test(`${page} is fully translated in every supported language`, () => {
const expectedPaths = getLeafPaths(enUS.pages[page]).sort()
+372
View File
@@ -5059,6 +5059,189 @@ paths:
$ref: '#/components/responses/ResourceError500'
'502':
$ref: '#/components/responses/ResourceError502'
/api/admin/v1/endpoints:
get:
summary: 查询所有用户的客户端设备登记记录
description: 一行对应 (user_id,machine_id) 的一条设备登记记录,字段为当前登记值。以 endpoints 为主表关联 users,不依赖会话或轮次上报。默认无时间限制,包含已撤销登记和已删除用户的记录;按最近活动降序(空值最后)、创建时间降序、ID 降序分页。最近活动为设备记录中 last_seen_at 与 last_reported_at 较新的时间,不能据此推断实时在线。每次读取 page_size+1 判断 has_next,不执行列表总数
COUNT。只返回展示字段,不返回执行公钥或授权信息。
parameters:
- in: query
name: query
description: 对使用者姓名、邮箱、设备名称、别名、客户端名称及设备 ID 做不区分大小写的字面子串搜索。
schema:
type: string
maxLength: 200
- in: query
name: user_id
description: 按所属用户精确筛选。
schema:
type: string
format: uuid
- in: query
name: platform
description: 操作系统类型,不区分大小写精确匹配。
schema:
type: string
maxLength: 64
- in: query
name: client_type
description: 客户端类型,不区分大小写精确匹配。
schema:
type: string
maxLength: 32
- in: query
name: client_version
description: 客户端版本,精确匹配。
schema:
type: string
maxLength: 64
- in: query
name: arch
description: CPU 架构,不区分大小写精确匹配。
schema:
type: string
maxLength: 32
- in: query
name: status
description: 登记状态,不代表实时在线。
schema:
type: string
enum:
- active
- revoked
- in: query
name: from
description: 最近活动时间下界,包含;不提供时不限制。
schema:
type: string
format: date-time
- in: query
name: until
description: 最近活动时间上界,不包含;不提供时不限制。
schema:
type: string
format: date-time
- in: query
name: page
schema:
type: integer
default: 1
minimum: 1
maximum: 1000000
- in: query
name: page_size
schema:
type: integer
default: 50
minimum: 1
maximum: 500
responses:
'200':
description: '登记记录页,Cache-Control: private, no-store'
content:
application/json:
schema:
type: object
required:
- items
- page
- page_size
- has_next
properties:
items:
type: array
items:
$ref: '#/components/schemas/ClientDevice'
page:
type: integer
page_size:
type: integer
has_next:
type: boolean
'400':
description: 参数不合法
'401':
description: 未登录
'403':
description: 需要管理员权限
'503':
description: 设备清单暂不可用
/api/admin/v1/endpoints/overview:
get:
summary: 统计客户端设备登记记录及其分布
description: 筛选口径与设备列表一致,默认覆盖全部登记记录。total 按 (user_id,machine_id) 记录计数,users 按 user_id 去重;三个分布均按设备登记记录计数,不是会话数,也不是按物理设备去重的安装量。不接受分页参数。
parameters:
- in: query
name: query
description: 对使用者姓名、邮箱、设备名称、别名、客户端名称及设备 ID 做不区分大小写的字面子串搜索。
schema:
type: string
maxLength: 200
- in: query
name: user_id
description: 按所属用户精确筛选。
schema:
type: string
format: uuid
- in: query
name: platform
description: 操作系统类型,不区分大小写精确匹配。
schema:
type: string
maxLength: 64
- in: query
name: client_type
description: 客户端类型,不区分大小写精确匹配。
schema:
type: string
maxLength: 32
- in: query
name: client_version
description: 客户端版本,精确匹配。
schema:
type: string
maxLength: 64
- in: query
name: arch
description: CPU 架构,不区分大小写精确匹配。
schema:
type: string
maxLength: 32
- in: query
name: status
description: 登记状态,不代表实时在线。
schema:
type: string
enum:
- active
- revoked
- in: query
name: from
description: 最近活动时间下界,包含;不提供时不限制。
schema:
type: string
format: date-time
- in: query
name: until
description: 最近活动时间上界,不包含;不提供时不限制。
schema:
type: string
format: date-time
responses:
'200':
description: '登记统计,Cache-Control: private, no-store'
content:
application/json:
schema:
$ref: '#/components/schemas/ClientDeviceOverview'
'400':
description: 参数不合法
'401':
description: 未登录
'403':
description: 需要管理员权限
'503':
description: 设备清单暂不可用
components:
securitySchemes:
AdminSession:
@@ -5169,6 +5352,195 @@ components:
schema:
$ref: "#/components/schemas/ErrorResponse"
schemas:
ClientDevice:
type: object
required:
- id
- user_id
- machine_id
- user_name
- user_email
- user_avatar_url
- alias
- client_type
- client_name
- locale
- system_locale
- timezone
- runtime_version
- engine_version
- user_deleted
- device_name
- platform
- os_version
- arch
- client_version
- status
- created_at
- updated_at
- last_seen_at
- last_reported_at
- last_active_at
properties:
id:
type: string
format: uuid
user_id:
type: string
format: uuid
machine_id:
type: string
format: uuid
user_name:
type:
- string
- 'null'
user_email:
type:
- string
- 'null'
user_avatar_url:
type:
- string
- 'null'
alias:
type:
- string
- 'null'
client_type:
type:
- string
- 'null'
client_name:
type:
- string
- 'null'
locale:
type:
- string
- 'null'
system_locale:
type:
- string
- 'null'
timezone:
type:
- string
- 'null'
runtime_version:
type:
- string
- 'null'
engine_version:
type:
- string
- 'null'
user_deleted:
type: boolean
device_name:
type: string
platform:
type: string
os_version:
type: string
arch:
type: string
client_version:
type: string
status:
type: string
enum:
- active
- revoked
description: active 表示登记有效,不表示在线。
created_at:
type: string
format: date-time
description: 首次创建登记记录时间,不等同于首次连接或首次对话。
updated_at:
type: string
format: date-time
last_seen_at:
type:
- string
- 'null'
format: date-time
last_reported_at:
type:
- string
- 'null'
format: date-time
last_active_at:
type:
- string
- 'null'
format: date-time
description: GREATEST(last_seen_at,last_reported_at),两者均为空时为 null。
ClientDeviceOverview:
type: object
required:
- metric
- total
- users
- distributions
properties:
metric:
type: string
enum:
- devices
total:
type: integer
users:
type: integer
distributions:
type: object
required:
- client_type
- platform
- client_version
properties:
client_type:
type: array
items:
type: object
required:
- value
- count
properties:
value:
type:
- string
- 'null'
count:
type: integer
platform:
type: array
items:
type: object
required:
- value
- count
properties:
value:
type:
- string
- 'null'
count:
type: integer
client_version:
type: array
items:
type: object
required:
- value
- count
properties:
value:
type:
- string
- 'null'
count:
type: integer
ResourceImportUploadFile:
type: object
required: [name, size]
+1
View File
@@ -297,6 +297,7 @@ func newApplicationHandlerWithMembers(ctx context.Context, logger *slog.Logger,
resourceImports.WithDesignCatalog(designs)
endpoints := endpoint.NewService(endpointStore, endpointAuth{identities}, logger, cfg.PublicURL).WithMaxConnections(cfg.EndpointMaxConnections)
endpoints.RegisterAgent(agent)
endpoints.RegisterAdmin(admin)
identities.RegisterAgent(agent)
group.NewService(pool).RegisterAgent(agent)
keys.RegisterAgent(agent)
+158
View File
@@ -0,0 +1,158 @@
package endpoint
import (
"context"
"encoding/json"
"net/http"
"strconv"
"strings"
"time"
"unicode/utf8"
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/endpoint/sqlc"
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/resource"
"github.com/go-chi/chi/v5"
"github.com/jackc/pgx/v5/pgtype"
)
// AdminReader keeps the administrator inventory separate from per-user device management.
type AdminReader interface {
AdminDevices(context.Context, []byte, int, int) ([][]byte, error)
AdminDeviceOverview(context.Context, []byte) ([]byte, error)
}
func (s *Service) RegisterAdmin(r chi.Router) {
r.Get("/endpoints", s.adminDevices)
r.Get("/endpoints/overview", s.adminOverview)
}
func deviceFilters(r *http.Request) ([]byte, error) {
filters := map[string]string{}
for _, field := range []struct {
key string
limit int
}{{"query", 200}, {"platform", 64}, {"client_type", 32}, {"client_version", 64}, {"arch", 32}, {"status", 16}, {"user_id", 36}} {
value := strings.TrimSpace(r.URL.Query().Get(field.key))
if value == "" {
continue
}
if utf8.RuneCountInString(value) > field.limit {
return nil, resource.Invalid("筛选条件过长")
}
filters[field.key] = value
}
if id := filters["user_id"]; id != "" {
var value pgtype.UUID
if err := value.Scan(id); err != nil || !value.Valid {
return nil, resource.Invalid("用户 ID 无效")
}
}
if status := filters["status"]; status != "" && status != "active" && status != "revoked" {
return nil, resource.Invalid("设备状态无效")
}
var from, until time.Time
for _, key := range []string{"from", "until"} {
value := strings.TrimSpace(r.URL.Query().Get(key))
if value == "" {
continue
}
at, err := time.Parse(time.RFC3339Nano, value)
if err != nil {
return nil, resource.Invalid("时间需使用 RFC3339 格式")
}
filters[key] = at.UTC().Format(time.RFC3339Nano)
if key == "from" {
from = at
} else {
until = at
}
}
if !from.IsZero() && !until.IsZero() && !from.Before(until) {
return nil, resource.Invalid("结束时间必须晚于开始时间")
}
return json.Marshal(filters)
}
func devicePage(r *http.Request) (int, int, error) {
page, size := 1, 50
for _, entry := range []struct {
key string
value *int
max int
}{{"page", &page, 1000000}, {"page_size", &size, 500}} {
if raw := r.URL.Query().Get(entry.key); raw != "" {
value, err := strconv.Atoi(raw)
if err != nil || value < 1 || value > entry.max {
return 0, 0, resource.Invalid("分页参数无效")
}
*entry.value = value
}
}
return page, size, nil
}
func (s *Service) adminDevices(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "private, no-store")
filters, err := deviceFilters(r)
if err != nil {
resource.Fail(r.Context(), w, err)
return
}
page, size, err := devicePage(r)
if err != nil {
resource.Fail(r.Context(), w, err)
return
}
reader, ok := s.store.(AdminReader)
if !ok {
resource.Fail(r.Context(), w, &resource.Error{Status: 503, Code: "service_unavailable", Message: "设备清单暂不可用"})
return
}
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
defer cancel()
items, err := resource.DecodeObjects(reader.AdminDevices(ctx, filters, (page-1)*size, size+1))
if err != nil {
resource.Fail(r.Context(), w, err)
return
}
hasNext := len(items) > size
if hasNext {
items = items[:size]
}
resource.JSON(r.Context(), w, 200, resource.Object{"items": items, "page": page, "page_size": size, "has_next": hasNext})
}
func (s *Service) adminOverview(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "private, no-store")
for _, key := range []string{"page", "page_size", "cursor", "limit"} {
if r.URL.Query().Has(key) {
resource.Fail(r.Context(), w, resource.Invalid("设备概览不支持分页参数"))
return
}
}
filters, err := deviceFilters(r)
if err != nil {
resource.Fail(r.Context(), w, err)
return
}
reader, ok := s.store.(AdminReader)
if !ok {
resource.Fail(r.Context(), w, &resource.Error{Status: 503, Code: "service_unavailable", Message: "设备清单暂不可用"})
return
}
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
defer cancel()
out, err := resource.DecodeObject(reader.AdminDeviceOverview(ctx, filters))
if err != nil {
resource.Fail(r.Context(), w, err)
return
}
resource.JSON(r.Context(), w, 200, out)
}
func (p *Postgres) AdminDevices(ctx context.Context, filters []byte, offset, limit int) ([][]byte, error) {
return sqlc.New(p.pool).AdminDevices(ctx, sqlc.AdminDevicesParams{Filters: filters, PageOffset: int32(offset), PageLimit: int32(limit)})
}
func (p *Postgres) AdminDeviceOverview(ctx context.Context, filters []byte) ([]byte, error) {
return sqlc.New(p.pool).AdminDeviceOverview(ctx, filters)
}
@@ -0,0 +1,156 @@
package endpoint
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/identity"
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/resource"
"github.com/go-chi/chi/v5"
)
func TestAdminDeviceInventory(t *testing.T) {
pool := testDatabase(t)
admin, user, deleted := testUser(t, pool, "inventory-admin"), testUser(t, pool, "inventory-user"), testUser(t, pool, "inventory-deleted")
exec := func(query string, args ...any) {
t.Helper()
if _, err := pool.Exec(t.Context(), query, args...); err != nil {
t.Fatal(err)
}
}
exec(`UPDATE users SET role='admin',name='管理员',email='admin@inventory.test',avatar_url=' /avatar.png ' WHERE id=$1`, admin)
exec(`UPDATE users SET name='普通成员',email='member@inventory.test' WHERE id=$1`, user)
exec(`UPDATE users SET deleted_at=now() WHERE id=$1`, deleted)
machine := resource.ID()
ids := []string{resource.ID(), resource.ID(), resource.ID(), resource.ID(), resource.ID()}
for i, owner := range []string{admin, admin, user, user, deleted} {
m := resource.ID()
if i == 0 || i == 2 {
m = machine
}
exec(`INSERT INTO endpoints(id,user_id,machine_id,device_name,platform,os_version,arch,client_version,client_type,client_name,locale,system_locale,runtime_version,engine_version,created_at,last_seen_at,last_reported_at,status,revoked_at)
VALUES($1,$2,$3,$4,$5,'11','arm64',$6,'desktop','MonkeyAI','zh-CN','en-US','22.1','1.9','2025-01-01',
CASE WHEN $7=3 THEN NULL ELSE ('2026-10-20'::timestamptz+$7*interval '1 day') END,
CASE WHEN $7=3 THEN NULL ELSE ('2026-10-20'::timestamptz+$7*interval '2 day') END,
CASE WHEN $7=4 THEN 'revoked' ELSE 'active' END,CASE WHEN $7=4 THEN now() ELSE NULL END)`, ids[i], owner, m, fmt.Sprintf("测试设备 %d", i), []string{"windows", "Windows", "linux", "custom-os", "macos"}[i], fmt.Sprintf("1.%d", i), i)
}
// A device can be inventoried without any reported conversations.
var facts int
if err := pool.QueryRow(t.Context(), `SELECT count(*) FROM session_turns`).Scan(&facts); err != nil || facts != 0 {
t.Fatalf("unexpected conversation facts: %d %v", facts, err)
}
service := NewService(NewPostgres(pool), nil, nil, "")
router := chi.NewRouter()
router.Use(identity.NewService(pool, nil, "").RequireAdmin)
service.RegisterAdmin(router)
for _, id := range []string{admin, user} {
hash := sha256.Sum256([]byte(id))
exec(`INSERT INTO browser_sessions(token_hash,user_id,authentication_method,expires_at) VALUES($1,$2,'password',now()+interval '1 hour')`, hex.EncodeToString(hash[:]), id)
}
call := func(path, token string, status int) map[string]any {
t.Helper()
r := httptest.NewRequest("GET", path, nil)
if token != "" {
r.AddCookie(&http.Cookie{Name: "monkeyai_session", Value: token})
}
w := httptest.NewRecorder()
router.ServeHTTP(w, r)
if w.Code != status {
t.Fatalf("%s: %d %s", path, w.Code, w.Body)
}
if status == 200 && w.Header().Get("Cache-Control") != "private, no-store" {
t.Fatal("inventory must not be cached")
}
var out map[string]any
if err := json.Unmarshal(w.Body.Bytes(), &out); err != nil {
t.Fatal(err)
}
return out
}
for _, path := range []string{"/endpoints", "/endpoints/overview"} {
call(path, "", 401)
call(path, user, 403)
}
list := call("/endpoints?page_size=2", admin, 200)
if len(list["items"].([]any)) != 2 || list["has_next"] != true || list["total"] != nil {
t.Fatalf("bounded page: %#v", list)
}
first := list["items"].([]any)[0].(map[string]any)
if first["id"] != ids[4] || first["user_deleted"] != true || first["status"] != "revoked" {
t.Fatalf("latest activity and deleted user: %#v", first)
}
for _, field := range []string{"execution_public_key", "key_id", "active_grant_id", "registration_version", "grant_version", "lease_epoch", "execution_protocols", "password_hash", "electron_version", "channel"} {
if _, ok := first[field]; ok {
t.Fatalf("sensitive/internal field exposed: %s", field)
}
}
list = call("/endpoints?page_size=2&page=3", admin, 200)
last := list["items"].([]any)[0].(map[string]any)
if len(list["items"].([]any)) != 1 || list["has_next"] != false || last["id"] != ids[3] || last["last_active_at"] != nil {
t.Fatalf("null activity sorted last: %#v", list)
}
list = call("/endpoints?page=99", admin, 200)
if len(list["items"].([]any)) != 0 {
t.Fatal("out-of-range page must be empty")
}
for _, tc := range []struct {
query string
count, users int
}{
{"", 5, 3}, {"user_id=" + admin, 2, 1}, {"query=" + url.QueryEscape("普通成员"), 2, 1}, {"query=ADMIN%40INVENTORY.TEST", 2, 1},
{"query=MonkeyAI", 5, 3}, {"query=%25", 0, 0}, {"query=%5F", 0, 0}, {"query=" + machine, 2, 2},
{"platform=WINDOWS", 2, 1}, {"client_type=DESKTOP", 5, 3}, {"arch=ARM64", 5, 3}, {"client_version=1.2", 1, 1},
{"status=revoked", 1, 1}, {"status=active&platform=linux", 1, 1},
{"from=2026-10-24T00:00:00Z", 2, 2}, {"until=2026-10-24T00:00:00Z", 2, 1},
{"from=2026-10-24T00:00:00Z&until=2026-10-28T00:00:00Z", 1, 1},
} {
rows := call("/endpoints?"+tc.query, admin, 200)["items"].([]any)
overview := call("/endpoints/overview?"+tc.query, admin, 200)
if len(rows) != tc.count || overview["metric"] != "devices" || overview["total"] != float64(tc.count) || overview["users"] != float64(tc.users) {
t.Fatalf("filter %s: list=%d overview=%#v", tc.query, len(rows), overview)
}
for _, entries := range overview["distributions"].(map[string]any) {
sum := float64(0)
for _, entry := range entries.([]any) {
sum += entry.(map[string]any)["count"].(float64)
}
if sum != float64(tc.count) {
t.Fatalf("inconsistent distribution: %#v", overview)
}
}
}
all := call("/endpoints/overview", admin, 200)
for _, entry := range all["distributions"].(map[string]any)["platform"].([]any) {
item := entry.(map[string]any)
if item["value"] == "windows" && item["count"] != float64(2) {
t.Fatal("known OS case variants must share a chart category")
}
}
// Legacy clients may not have reported a type; the Unknown filter includes them.
exec(`UPDATE endpoints SET client_type=NULL WHERE id=$1`, ids[3])
unknown := call("/endpoints?client_type=unknown", admin, 200)["items"].([]any)
if len(unknown) != 1 || unknown[0].(map[string]any)["id"] != ids[3] {
t.Fatalf("missing client type was excluded: %#v", unknown)
}
unknownOverview := call("/endpoints/overview?client_type=unknown", admin, 200)
if unknownOverview["total"] != float64(1) {
t.Fatalf("unknown type overview differs: %#v", unknownOverview)
}
// Updated registration details remain one row rather than accumulating versions.
exec(`UPDATE endpoints SET client_version='2.0',runtime_version='24',engine_version='2.1' WHERE id=$1`, ids[0])
changed := call("/endpoints?user_id="+admin+"&client_version=2.0", admin, 200)["items"].([]any)
if len(changed) != 1 || changed[0].(map[string]any)["runtime_version"] != "24" {
t.Fatalf("updated registration not reflected: %#v", changed)
}
for _, query := range []string{"page=0", "page_size=501", "page=no", "user_id=invalid", "status=online", "from=bad", "from=2026-10-25T00:00:00Z&until=2026-10-24T00:00:00Z", "query=" + url.QueryEscape(strings.Repeat("张", 201))} {
call("/endpoints?"+query, admin, 400)
}
call("/endpoints/overview?page=1", admin, 400)
}
@@ -110,3 +110,57 @@ WHERE user_id = $1 AND machine_id = $2 RETURNING *;
SELECT * FROM endpoints WHERE user_id = $1
AND (NOT sqlc.arg(execute_only)::boolean OR execution_public_key IS NOT NULL)
ORDER BY created_at DESC, id DESC;
-- name: AdminDevices :many
WITH opts AS (SELECT sqlc.arg(filters)::jsonb AS f), devices AS (
SELECT e.*,u.name AS user_name,u.email AS user_email,nullif(btrim(u.avatar_url),'') AS user_avatar_url,
u.deleted_at IS NOT NULL AS user_deleted,greatest(e.last_seen_at,e.last_reported_at) AS last_active_at
FROM endpoints e LEFT JOIN users u ON u.id=e.user_id CROSS JOIN opts p
WHERE (p.f->>'query' IS NULL OR strpos(lower(concat_ws(' ',u.name,u.email,e.device_name,e.alias,e.client_name,e.machine_id::text)),lower(p.f->>'query'))>0)
AND (p.f->>'user_id' IS NULL OR e.user_id=(p.f->>'user_id')::uuid)
AND (p.f->>'platform' IS NULL OR lower(e.platform)=lower(p.f->>'platform'))
AND (p.f->>'client_type' IS NULL OR lower(coalesce(nullif(btrim(e.client_type),''),'unknown'))=lower(p.f->>'client_type'))
AND (p.f->>'client_version' IS NULL OR e.client_version=p.f->>'client_version')
AND (p.f->>'arch' IS NULL OR lower(e.arch)=lower(p.f->>'arch'))
AND (p.f->>'status' IS NULL OR e.status=p.f->>'status')
AND (p.f->>'from' IS NULL OR greatest(e.last_seen_at,e.last_reported_at)>=(p.f->>'from')::timestamptz)
AND (p.f->>'until' IS NULL OR greatest(e.last_seen_at,e.last_reported_at)<(p.f->>'until')::timestamptz)
)
SELECT jsonb_build_object(
'id',id,'user_id',user_id,'machine_id',machine_id,'user_name',user_name,'user_email',user_email,'user_avatar_url',user_avatar_url,'user_deleted',user_deleted,
'device_name',device_name,'alias',alias,'platform',platform,'os_version',os_version,'arch',arch,
'client_type',client_type,'client_name',client_name,'client_version',client_version,
'locale',locale,'system_locale',system_locale,'timezone',timezone,'runtime_version',runtime_version,'engine_version',engine_version,
'status',status,'created_at',created_at,'updated_at',updated_at,'last_seen_at',last_seen_at,'last_reported_at',last_reported_at,'last_active_at',last_active_at)
FROM devices ORDER BY last_active_at DESC NULLS LAST,created_at DESC,id DESC
LIMIT sqlc.arg(page_limit)::integer OFFSET sqlc.arg(page_offset)::integer;
-- name: AdminDeviceOverview :one
WITH opts AS (SELECT sqlc.arg(filters)::jsonb AS f), devices AS (
SELECT e.*,u.name AS user_name,u.email AS user_email,nullif(btrim(u.avatar_url),'') AS user_avatar_url,
u.deleted_at IS NOT NULL AS user_deleted,greatest(e.last_seen_at,e.last_reported_at) AS last_active_at
FROM endpoints e LEFT JOIN users u ON u.id=e.user_id CROSS JOIN opts p
WHERE (p.f->>'query' IS NULL OR strpos(lower(concat_ws(' ',u.name,u.email,e.device_name,e.alias,e.client_name,e.machine_id::text)),lower(p.f->>'query'))>0)
AND (p.f->>'user_id' IS NULL OR e.user_id=(p.f->>'user_id')::uuid)
AND (p.f->>'platform' IS NULL OR lower(e.platform)=lower(p.f->>'platform'))
AND (p.f->>'client_type' IS NULL OR lower(coalesce(nullif(btrim(e.client_type),''),'unknown'))=lower(p.f->>'client_type'))
AND (p.f->>'client_version' IS NULL OR e.client_version=p.f->>'client_version')
AND (p.f->>'arch' IS NULL OR lower(e.arch)=lower(p.f->>'arch'))
AND (p.f->>'status' IS NULL OR e.status=p.f->>'status')
AND (p.f->>'from' IS NULL OR greatest(e.last_seen_at,e.last_reported_at)>=(p.f->>'from')::timestamptz)
AND (p.f->>'until' IS NULL OR greatest(e.last_seen_at,e.last_reported_at)<(p.f->>'until')::timestamptz)
)
, normalized AS (
SELECT coalesce(nullif(btrim(client_type),''),'unknown') AS client_type,
CASE WHEN lower(btrim(platform)) IN ('windows','macos','linux','web','android','ios') THEN lower(btrim(platform)) ELSE nullif(btrim(platform),'') END AS platform,
nullif(btrim(client_version),'') AS client_version FROM devices
), counts AS (
SELECT 'client_type'::text AS dimension,client_type AS value,count(*) AS count FROM normalized GROUP BY client_type
UNION ALL SELECT 'platform',platform,count(*) FROM normalized GROUP BY platform
UNION ALL SELECT 'client_version',client_version,count(*) FROM normalized GROUP BY client_version
)
SELECT jsonb_build_object('metric','devices','total',(SELECT count(*) FROM devices),'users',(SELECT count(DISTINCT user_id) FROM devices),
'distributions',jsonb_build_object(
'client_type',coalesce((SELECT jsonb_agg(jsonb_build_object('value',value,'count',count) ORDER BY count DESC,value COLLATE "C" ASC NULLS LAST) FROM counts WHERE dimension='client_type'),'[]'::jsonb),
'platform',coalesce((SELECT jsonb_agg(jsonb_build_object('value',value,'count',count) ORDER BY count DESC,value COLLATE "C" ASC NULLS LAST) FROM counts WHERE dimension='platform'),'[]'::jsonb),
'client_version',coalesce((SELECT jsonb_agg(jsonb_build_object('value',value,'count',count) ORDER BY count DESC,value COLLATE "C" ASC NULLS LAST) FROM counts WHERE dimension='client_version'),'[]'::jsonb)));
@@ -69,6 +69,95 @@ func (q *Queries) Active(ctx context.Context, userID string) ([]Endpoint, error)
return items, nil
}
const adminDeviceOverview = `-- name: AdminDeviceOverview :one
WITH opts AS (SELECT $1::jsonb AS f), devices AS (
SELECT e.id, e.user_id, e.machine_id, e.device_name, e.alias, e.platform, e.os_version, e.arch, e.client_version, e.protocol_version, e.status, e.created_at, e.updated_at, e.last_seen_at, e.revoked_at, e.client_type, e.client_name, e.channel, e.locale, e.system_locale, e.timezone, e.runtime_version, e.engine_version, e.electron_version, e.last_reported_at, e.execution_protocols, e.execution_public_key, e.key_id, e.deployment_mode, e.remote_access_state, e.active_grant_id, e.registration_version, e.grant_version, e.lease_epoch,u.name AS user_name,u.email AS user_email,nullif(btrim(u.avatar_url),'') AS user_avatar_url,
u.deleted_at IS NOT NULL AS user_deleted,greatest(e.last_seen_at,e.last_reported_at) AS last_active_at
FROM endpoints e LEFT JOIN users u ON u.id=e.user_id CROSS JOIN opts p
WHERE (p.f->>'query' IS NULL OR strpos(lower(concat_ws(' ',u.name,u.email,e.device_name,e.alias,e.client_name,e.machine_id::text)),lower(p.f->>'query'))>0)
AND (p.f->>'user_id' IS NULL OR e.user_id=(p.f->>'user_id')::uuid)
AND (p.f->>'platform' IS NULL OR lower(e.platform)=lower(p.f->>'platform'))
AND (p.f->>'client_type' IS NULL OR lower(coalesce(nullif(btrim(e.client_type),''),'unknown'))=lower(p.f->>'client_type'))
AND (p.f->>'client_version' IS NULL OR e.client_version=p.f->>'client_version')
AND (p.f->>'arch' IS NULL OR lower(e.arch)=lower(p.f->>'arch'))
AND (p.f->>'status' IS NULL OR e.status=p.f->>'status')
AND (p.f->>'from' IS NULL OR greatest(e.last_seen_at,e.last_reported_at)>=(p.f->>'from')::timestamptz)
AND (p.f->>'until' IS NULL OR greatest(e.last_seen_at,e.last_reported_at)<(p.f->>'until')::timestamptz)
)
, normalized AS (
SELECT coalesce(nullif(btrim(client_type),''),'unknown') AS client_type,
CASE WHEN lower(btrim(platform)) IN ('windows','macos','linux','web','android','ios') THEN lower(btrim(platform)) ELSE nullif(btrim(platform),'') END AS platform,
nullif(btrim(client_version),'') AS client_version FROM devices
), counts AS (
SELECT 'client_type'::text AS dimension,client_type AS value,count(*) AS count FROM normalized GROUP BY client_type
UNION ALL SELECT 'platform',platform,count(*) FROM normalized GROUP BY platform
UNION ALL SELECT 'client_version',client_version,count(*) FROM normalized GROUP BY client_version
)
SELECT jsonb_build_object('metric','devices','total',(SELECT count(*) FROM devices),'users',(SELECT count(DISTINCT user_id) FROM devices),
'distributions',jsonb_build_object(
'client_type',coalesce((SELECT jsonb_agg(jsonb_build_object('value',value,'count',count) ORDER BY count DESC,value COLLATE "C" ASC NULLS LAST) FROM counts WHERE dimension='client_type'),'[]'::jsonb),
'platform',coalesce((SELECT jsonb_agg(jsonb_build_object('value',value,'count',count) ORDER BY count DESC,value COLLATE "C" ASC NULLS LAST) FROM counts WHERE dimension='platform'),'[]'::jsonb),
'client_version',coalesce((SELECT jsonb_agg(jsonb_build_object('value',value,'count',count) ORDER BY count DESC,value COLLATE "C" ASC NULLS LAST) FROM counts WHERE dimension='client_version'),'[]'::jsonb)))
`
func (q *Queries) AdminDeviceOverview(ctx context.Context, filters []byte) ([]byte, error) {
row := q.db.QueryRow(ctx, adminDeviceOverview, filters)
var jsonb_build_object []byte
err := row.Scan(&jsonb_build_object)
return jsonb_build_object, err
}
const adminDevices = `-- name: AdminDevices :many
WITH opts AS (SELECT $3::jsonb AS f), devices AS (
SELECT e.id, e.user_id, e.machine_id, e.device_name, e.alias, e.platform, e.os_version, e.arch, e.client_version, e.protocol_version, e.status, e.created_at, e.updated_at, e.last_seen_at, e.revoked_at, e.client_type, e.client_name, e.channel, e.locale, e.system_locale, e.timezone, e.runtime_version, e.engine_version, e.electron_version, e.last_reported_at, e.execution_protocols, e.execution_public_key, e.key_id, e.deployment_mode, e.remote_access_state, e.active_grant_id, e.registration_version, e.grant_version, e.lease_epoch,u.name AS user_name,u.email AS user_email,nullif(btrim(u.avatar_url),'') AS user_avatar_url,
u.deleted_at IS NOT NULL AS user_deleted,greatest(e.last_seen_at,e.last_reported_at) AS last_active_at
FROM endpoints e LEFT JOIN users u ON u.id=e.user_id CROSS JOIN opts p
WHERE (p.f->>'query' IS NULL OR strpos(lower(concat_ws(' ',u.name,u.email,e.device_name,e.alias,e.client_name,e.machine_id::text)),lower(p.f->>'query'))>0)
AND (p.f->>'user_id' IS NULL OR e.user_id=(p.f->>'user_id')::uuid)
AND (p.f->>'platform' IS NULL OR lower(e.platform)=lower(p.f->>'platform'))
AND (p.f->>'client_type' IS NULL OR lower(coalesce(nullif(btrim(e.client_type),''),'unknown'))=lower(p.f->>'client_type'))
AND (p.f->>'client_version' IS NULL OR e.client_version=p.f->>'client_version')
AND (p.f->>'arch' IS NULL OR lower(e.arch)=lower(p.f->>'arch'))
AND (p.f->>'status' IS NULL OR e.status=p.f->>'status')
AND (p.f->>'from' IS NULL OR greatest(e.last_seen_at,e.last_reported_at)>=(p.f->>'from')::timestamptz)
AND (p.f->>'until' IS NULL OR greatest(e.last_seen_at,e.last_reported_at)<(p.f->>'until')::timestamptz)
)
SELECT jsonb_build_object(
'id',id,'user_id',user_id,'machine_id',machine_id,'user_name',user_name,'user_email',user_email,'user_avatar_url',user_avatar_url,'user_deleted',user_deleted,
'device_name',device_name,'alias',alias,'platform',platform,'os_version',os_version,'arch',arch,
'client_type',client_type,'client_name',client_name,'client_version',client_version,
'locale',locale,'system_locale',system_locale,'timezone',timezone,'runtime_version',runtime_version,'engine_version',engine_version,
'status',status,'created_at',created_at,'updated_at',updated_at,'last_seen_at',last_seen_at,'last_reported_at',last_reported_at,'last_active_at',last_active_at)
FROM devices ORDER BY last_active_at DESC NULLS LAST,created_at DESC,id DESC
LIMIT $2::integer OFFSET $1::integer
`
type AdminDevicesParams struct {
PageOffset int32
PageLimit int32
Filters []byte
}
func (q *Queries) AdminDevices(ctx context.Context, arg AdminDevicesParams) ([][]byte, error) {
rows, err := q.db.Query(ctx, adminDevices, arg.PageOffset, arg.PageLimit, arg.Filters)
if err != nil {
return nil, err
}
defer rows.Close()
items := [][]byte{}
for rows.Next() {
var jsonb_build_object []byte
if err := rows.Scan(&jsonb_build_object); err != nil {
return nil, err
}
items = append(items, jsonb_build_object)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const count = `-- name: Count :one
SELECT count(*) FROM endpoints WHERE user_id = $1
`