diff --git a/monkeyai/admin/README.md b/monkeyai/admin/README.md index e0c16f3a..aadd86e5 100644 --- a/monkeyai/admin/README.md +++ b/monkeyai/admin/README.md @@ -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 和其他未登记目标。 diff --git a/monkeyai/admin/package.json b/monkeyai/admin/package.json index b791f12d..f61758aa 100644 --- a/monkeyai/admin/package.json +++ b/monkeyai/admin/package.json @@ -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", diff --git a/monkeyai/admin/scripts/check-client-devices.mjs b/monkeyai/admin/scripts/check-client-devices.mjs new file mode 100644 index 00000000..5757270b --- /dev/null +++ b/monkeyai/admin/scripts/check-client-devices.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() +} diff --git a/monkeyai/admin/src/components/client-distribution-cards.tsx b/monkeyai/admin/src/components/client-distribution-cards.tsx index 59c53114..1c79f24c 100644 --- a/monkeyai/admin/src/components/client-distribution-cards.tsx +++ b/monkeyai/admin/src/components/client-distribution-cards.tsx @@ -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 = { } function categoryColor( - field: ClientDistributionDimension, + field: DeviceDistributionDimension, value: string | null ) { if (value === null || value === "unknown") return colors[5] @@ -157,7 +157,7 @@ function DistributionCard({
{items.length ? ( 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 }) diff --git a/monkeyai/admin/src/i18n/locales/ar.ts b/monkeyai/admin/src/i18n/locales/ar.ts index 58feb543..cf861455 100644 --- a/monkeyai/admin/src/i18n/locales/ar.ts +++ b/monkeyai/admin/src/i18n/locales/ar.ts @@ -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: "نظرة عامة على البيانات", diff --git a/monkeyai/admin/src/i18n/locales/de-DE.ts b/monkeyai/admin/src/i18n/locales/de-DE.ts index 86809511..4f1eae16 100644 --- a/monkeyai/admin/src/i18n/locales/de-DE.ts +++ b/monkeyai/admin/src/i18n/locales/de-DE.ts @@ -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", diff --git a/monkeyai/admin/src/i18n/locales/en-US.ts b/monkeyai/admin/src/i18n/locales/en-US.ts index 8d263d3d..68ef912e 100644 --- a/monkeyai/admin/src/i18n/locales/en-US.ts +++ b/monkeyai/admin/src/i18n/locales/en-US.ts @@ -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.", diff --git a/monkeyai/admin/src/i18n/locales/es-419.ts b/monkeyai/admin/src/i18n/locales/es-419.ts index 558d48ec..34d56e7a 100644 --- a/monkeyai/admin/src/i18n/locales/es-419.ts +++ b/monkeyai/admin/src/i18n/locales/es-419.ts @@ -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", diff --git a/monkeyai/admin/src/i18n/locales/fr-FR.ts b/monkeyai/admin/src/i18n/locales/fr-FR.ts index 93fc64b6..f0429cd9 100644 --- a/monkeyai/admin/src/i18n/locales/fr-FR.ts +++ b/monkeyai/admin/src/i18n/locales/fr-FR.ts @@ -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", diff --git a/monkeyai/admin/src/i18n/locales/ja-JP.ts b/monkeyai/admin/src/i18n/locales/ja-JP.ts index c7a1f6b8..2ca1838f 100644 --- a/monkeyai/admin/src/i18n/locales/ja-JP.ts +++ b/monkeyai/admin/src/i18n/locales/ja-JP.ts @@ -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: "データ概要", diff --git a/monkeyai/admin/src/i18n/locales/ko-KR.ts b/monkeyai/admin/src/i18n/locales/ko-KR.ts index 9aeadba7..7fab063f 100644 --- a/monkeyai/admin/src/i18n/locales/ko-KR.ts +++ b/monkeyai/admin/src/i18n/locales/ko-KR.ts @@ -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: "데이터 개요", diff --git a/monkeyai/admin/src/i18n/locales/ru-RU.ts b/monkeyai/admin/src/i18n/locales/ru-RU.ts index 7584c624..1fc497aa 100644 --- a/monkeyai/admin/src/i18n/locales/ru-RU.ts +++ b/monkeyai/admin/src/i18n/locales/ru-RU.ts @@ -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: "Обзор данных", diff --git a/monkeyai/admin/src/i18n/locales/zh-CN.ts b/monkeyai/admin/src/i18n/locales/zh-CN.ts index 109ff013..99ad49ec 100644 --- a/monkeyai/admin/src/i18n/locales/zh-CN.ts +++ b/monkeyai/admin/src/i18n/locales/zh-CN.ts @@ -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: "资源使用", diff --git a/monkeyai/admin/src/i18n/locales/zh-TW.ts b/monkeyai/admin/src/i18n/locales/zh-TW.ts index 17e65756..bab4d441 100644 --- a/monkeyai/admin/src/i18n/locales/zh-TW.ts +++ b/monkeyai/admin/src/i18n/locales/zh-TW.ts @@ -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: "用於查看與管理付費授權", diff --git a/monkeyai/admin/src/lib/client-devices.ts b/monkeyai/admin/src/lib/client-devices.ts new file mode 100644 index 00000000..c22a0e4a --- /dev/null +++ b/monkeyai/admin/src/lib/client-devices.ts @@ -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 = { + windows: "Windows", + macos: "macOS", + linux: "Linux", + ios: "iOS", + android: "Android", + web: "Web", + } + const key = value.toLowerCase() + return Object.hasOwn(labels, key) ? labels[key] : value +} diff --git a/monkeyai/admin/src/pages/client-analysis-page.tsx b/monkeyai/admin/src/pages/client-analysis-page.tsx index 08f516ff..38187410 100644 --- a/monkeyai/admin/src/pages/client-analysis-page.tsx +++ b/monkeyai/admin/src/pages/client-analysis-page.tsx @@ -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 +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(defaultWindow) - const [draft, setDraft] = useState(filters) - const [startDay, setStartDay] = useState() - const [endDay, setEndDay] = useState() + const [filters, setFilters] = useState({}) + const [draft, setDraft] = useState({}) const [visibleFields, setVisibleFields] = useState>( - () => new Set(["client_type"]) + () => new Set(["client_type", "platform"]) ) const [visibleColumns, setVisibleColumns] = useState>( () => 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(null) - const [data, setData] = useState>() + const [data, setData] = useState() const [loading, setLoading] = useState(true) const [searching, setSearching] = useState(false) const [error, setError] = useState() - 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(overviewPath, { + void api(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>(path, { - signal: controller.signal, - cache: "no-store", - }) + void api(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) { 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 - if (column === "completion_rate" || column === "anomaly_rate") { - return + function renderCell(row: ClientDevice, column: ClientColumn) { + if (column === "user") + return ( + + + + + {row.user_name || row.user_email || row.user_id} + {row.user_deleted ? ` · ${t(`${key}.deletedUser`)}` : ""} + + + {row.user_email || row.user_id} + + + + ) + if (column === "device_name") + return ( + + {row.alias || row.device_name} + + ) + if (column === "created_at" || column === "last_active_at") { + const value = row[column] + return ( + + {value && !Number.isNaN(Date.parse(value)) + ? timeFormatter.format(new Date(value)) + : "—"} + + ) } - if (column === "p95_duration_seconds") { - return - } - return + 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 ( + + {!value + ? "—" + : value === "unknown" + ? t("pages.clientDevices.distribution.unknown") + : value} + + ) } return ( @@ -286,25 +323,19 @@ export function ClientAnalysisPage() { onSubmit={applySearch} className="flex flex-wrap items-center gap-2 px-[var(--card-spacing)]" > - - + setDraft((current) => ({ + ...current, + query: event.target.value, + })) + } /> {visibleFields.has("client_type") && ( @@ -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`)} {t(`${key}.fields.client_type`)} - {selectValues.client_type.map((value) => ( + {clientTypes.map((value) => ( - {value} + {t(`pages.clientDevices.distribution.types.${value}`)} ))} @@ -346,7 +382,7 @@ export function ClientAnalysisPage() { )} {visibleFields.has("platform") && ( )} - {visibleFields.has("outcome") && ( - - )} - {(["user_id", "group_id", "model_id", "expert_id"] as const).map( + {(["arch", "client_version"] as const).map( (field) => visibleFields.has(field) && ( setDraft((current) => ({ ...current, - [field]: event.target.value.trim(), + [field]: event.target.value, })) } /> ) )} + {visibleFields.has("status") && ( + + } + > + {draft.status + ? t(`${key}.statuses.${draft.status}`) + : t(`${key}.fields.status`)} + + + + {["active", "revoked"].map((value) => ( + + setDraft((current) => ({ + ...current, + status: checked ? value : "", + })) + } + > + {t(`${key}.statuses.${value}`)} + + ))} + + + + )} + {visibleFields.has("last_active_at") && ( + <> + + setDraft((current) => ({ + ...current, + from: value ? startOfLocalDay(value).toISOString() : "", + })) + } + disabled={endDay ? { after: endDay } : undefined} + /> + + setDraft((current) => ({ + ...current, + until: value + ? startOfLocalDay(addDays(value, 1)).toISOString() + : "", + })) + } + disabled={startDay ? { before: startDay } : undefined} + /> + + )} } @@ -422,14 +495,20 @@ export function ClientAnalysisPage() { + 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}`)} @@ -458,7 +537,7 @@ export function ClientAnalysisPage() {