From e96ceedd7ebd6a8e138e8b363ef36a2ffbf7e20f Mon Sep 17 00:00:00 2001
From: ZverGuy
Date: Wed, 4 Nov 2026 05:25:58 +0700
Subject: [PATCH 01/46] feat(dashboard): add a console client for the
observability proxy
The observability proxy serves metrics and logs under Kubernetes-shaped
paths but answers in native Prometheus JSON and VictoriaLogs NDJSON, so
the typed K8sClient methods cannot read it. A raw fetch on the client
keeps the same credentials and 401 handling the rest of the console
uses, and the proxy module maps each documented status to its own
error kind so a cluster without the proxy (404) can be told apart from
a denied request or a store that is down.
Assisted-by: LLM
Signed-off-by: ZverGuy
---
.../__tests__/k8s-client/client.raw.test.ts | 47 ++++
.../src/lib/observability/proxy.test.ts | 179 +++++++++++++++
.../console/src/lib/observability/proxy.ts | 203 ++++++++++++++++++
.../console/packages/k8s-client/src/client.ts | 18 ++
4 files changed, 447 insertions(+)
create mode 100644 packages/system/dashboard/images/console/apps/console/src/__tests__/k8s-client/client.raw.test.ts
create mode 100644 packages/system/dashboard/images/console/apps/console/src/lib/observability/proxy.test.ts
create mode 100644 packages/system/dashboard/images/console/apps/console/src/lib/observability/proxy.ts
diff --git a/packages/system/dashboard/images/console/apps/console/src/__tests__/k8s-client/client.raw.test.ts b/packages/system/dashboard/images/console/apps/console/src/__tests__/k8s-client/client.raw.test.ts
new file mode 100644
index 000000000..ab6c056f5
--- /dev/null
+++ b/packages/system/dashboard/images/console/apps/console/src/__tests__/k8s-client/client.raw.test.ts
@@ -0,0 +1,47 @@
+import { describe, it, expect, vi, afterEach } from "vitest"
+import { K8sClient } from "@cozystack/k8s-client"
+
+afterEach(() => {
+ vi.unstubAllGlobals()
+ vi.restoreAllMocks()
+})
+
+describe("K8sClient.raw", () => {
+ it("returns the response untouched, including a non-2xx one", async () => {
+ const res = new Response("not found", { status: 404 })
+ vi.stubGlobal("fetch", vi.fn(async () => res))
+ const client = new K8sClient()
+
+ await expect(client.raw("/x")).resolves.toBe(res)
+ })
+
+ it("prefixes the base URL and attaches the bearer token", async () => {
+ const fetchMock = vi.fn(async () => new Response("{}"))
+ vi.stubGlobal("fetch", fetchMock)
+ const client = new K8sClient({ baseUrl: "/base", getToken: async () => "t0k" })
+
+ await client.raw("/apis/x", { headers: { Accept: "application/json" } })
+
+ const [url, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit]
+ expect(url).toBe("/base/apis/x")
+ expect(init.headers).toEqual({ Accept: "application/json", Authorization: "Bearer t0k" })
+ })
+
+ it("routes a 401 through the client's unauthorized handler", async () => {
+ const onUnauthorized = vi.fn()
+ vi.stubGlobal("fetch", vi.fn(async () => new Response("", { status: 401 })))
+ const client = new K8sClient({ onUnauthorized })
+
+ const res = await client.raw("/x")
+
+ expect(res.status).toBe(401)
+ expect(onUnauthorized).toHaveBeenCalledTimes(1)
+ })
+
+ it("does not swallow a network failure", async () => {
+ vi.stubGlobal("fetch", vi.fn(async () => { throw new TypeError("offline") }))
+ const client = new K8sClient()
+
+ await expect(client.raw("/x")).rejects.toThrow("offline")
+ })
+})
diff --git a/packages/system/dashboard/images/console/apps/console/src/lib/observability/proxy.test.ts b/packages/system/dashboard/images/console/apps/console/src/lib/observability/proxy.test.ts
new file mode 100644
index 000000000..f06835ff7
--- /dev/null
+++ b/packages/system/dashboard/images/console/apps/console/src/lib/observability/proxy.test.ts
@@ -0,0 +1,179 @@
+import { describe, it, expect, vi } from "vitest"
+import { K8sClient } from "@cozystack/k8s-client"
+import {
+ ProxyError,
+ errorKindForStatus,
+ fieldValues,
+ logsRoot,
+ metricsRoot,
+ queryLogs,
+ queryRange,
+ tailLogs,
+} from "./proxy.ts"
+
+const app = { namespace: "tenant-a", plural: "postgreses", name: "db" }
+const ns = { namespace: "tenant-a" }
+
+function clientReturning(...responses: Response[]) {
+ const client = new K8sClient({ onUnauthorized: () => {} })
+ const raw = vi.spyOn(client, "raw")
+ for (const r of responses) raw.mockResolvedValueOnce(r)
+ return { client, raw }
+}
+
+function calledUrl(raw: ReturnType["raw"], call = 0): URL {
+ return new URL(raw.mock.calls[call][0], "http://x")
+}
+
+describe("roots", () => {
+ it("builds the application roots under apps.cozystack.io", () => {
+ expect(metricsRoot(app)).toBe("/apis/apps.cozystack.io/v1alpha1/namespaces/tenant-a/postgreses/db/metrics/")
+ expect(logsRoot(app)).toBe("/apis/apps.cozystack.io/v1alpha1/namespaces/tenant-a/postgreses/db/log/")
+ })
+
+ it("builds the namespace roots under cozystack.io", () => {
+ expect(metricsRoot(ns)).toBe("/apis/cozystack.io/v1alpha1/namespaces/tenant-a/metrics/")
+ expect(logsRoot(ns)).toBe("/apis/cozystack.io/v1alpha1/namespaces/tenant-a/logs/")
+ })
+})
+
+describe("errorKindForStatus", () => {
+ it.each([
+ [400, "bad-request"],
+ [401, "unauthorized"],
+ [403, "forbidden"],
+ [404, "not-available"],
+ [422, "limit"],
+ [429, "rate-limited"],
+ [502, "store-unreachable"],
+ [503, "unavailable"],
+ [504, "timeout"],
+ [500, "unknown"],
+ ])("maps %i to %s", (status, kind) => {
+ expect(errorKindForStatus(status)).toBe(kind)
+ })
+})
+
+describe("queryRange", () => {
+ it("GETs query_range under the root and returns the matrix", async () => {
+ const body = { status: "success", data: { resultType: "matrix", result: [{ metric: { pod: "p" }, values: [[1, "2"]] }] } }
+ const { client, raw } = clientReturning(Response.json(body))
+
+ const result = await queryRange(client, metricsRoot(app), { query: "up", start: 10, end: 20, step: 5 })
+
+ const url = calledUrl(raw)
+ expect(url.pathname).toBe(`${metricsRoot(app)}api/v1/query_range`)
+ expect(Object.fromEntries(url.searchParams)).toEqual({ query: "up", start: "10", end: "20", step: "5" })
+ expect(result).toEqual(body.data.result)
+ })
+
+ it("throws a ProxyError carrying the Prometheus error text", async () => {
+ const { client } = clientReturning(
+ Response.json({ status: "error", error: "range too long" }, { status: 422 }),
+ )
+
+ const err = await queryRange(client, metricsRoot(app), { query: "up", start: 0, end: 1, step: 1 }).catch((e) => e)
+
+ expect(err).toBeInstanceOf(ProxyError)
+ expect(err).toMatchObject({ kind: "limit", status: 422, message: "range too long" })
+ })
+
+ it("reports a fetch failure as a network error", async () => {
+ const client = new K8sClient()
+ vi.spyOn(client, "raw").mockRejectedValue(new TypeError("offline"))
+
+ const err = await queryRange(client, metricsRoot(app), { query: "up", start: 0, end: 1, step: 1 }).catch((e) => e)
+
+ expect(err).toMatchObject({ kind: "network" })
+ })
+})
+
+describe("queryLogs", () => {
+ it("parses NDJSON lines and sorts them by _time ascending", async () => {
+ const ndjson = [
+ JSON.stringify({ _time: "2026-11-04T10:00:02Z", _msg: "b" }),
+ "",
+ JSON.stringify({ _time: "2026-11-04T10:00:01Z", _msg: "a" }),
+ ].join("\n")
+ const { client, raw } = clientReturning(new Response(ndjson))
+
+ const entries = await queryLogs(client, logsRoot(ns), { query: "*", start: "s", end: "e", limit: 100 })
+
+ expect(calledUrl(raw).pathname).toBe(`${logsRoot(ns)}select/logsql/query`)
+ expect(Object.fromEntries(calledUrl(raw).searchParams)).toEqual({ query: "*", start: "s", end: "e", limit: "100" })
+ expect(entries.map((e) => e._msg)).toEqual(["a", "b"])
+ })
+
+ it("keeps a plain-text error body as the message", async () => {
+ const { client } = clientReturning(new Response("cannot parse query", { status: 400 }))
+
+ const err = await queryLogs(client, logsRoot(ns), { query: "(", start: "s", end: "e", limit: 1 }).catch((e) => e)
+
+ expect(err).toMatchObject({ kind: "bad-request", message: "cannot parse query" })
+ })
+})
+
+describe("fieldValues", () => {
+ it("uses stream_field_values for stream fields and returns the values", async () => {
+ const { client, raw } = clientReturning(
+ Response.json({ values: [{ value: "pod-b", hits: 1 }, { value: "pod-a", hits: 9 }] }),
+ )
+
+ const values = await fieldValues(client, logsRoot(app), {
+ field: "kubernetes_pod_name",
+ stream: true,
+ query: "*",
+ start: "s",
+ end: "e",
+ })
+
+ expect(calledUrl(raw).pathname).toBe(`${logsRoot(app)}select/logsql/stream_field_values`)
+ expect(calledUrl(raw).searchParams.get("field")).toBe("kubernetes_pod_name")
+ expect(values).toEqual(["pod-a", "pod-b"])
+ })
+
+ it("uses field_values for other fields", async () => {
+ const { client, raw } = clientReturning(Response.json({ values: [] }))
+
+ await fieldValues(client, logsRoot(app), { field: "level", stream: false, query: "*", start: "s", end: "e" })
+
+ expect(calledUrl(raw).pathname).toBe(`${logsRoot(app)}select/logsql/field_values`)
+ })
+})
+
+describe("tailLogs", () => {
+ it("delivers every line as it arrives, including one split across chunks", async () => {
+ const enc = new TextEncoder()
+ const chunks = ['{"_time":"t1","_msg":"a"}\n{"_ti', 'me":"t2","_msg":"b"}\n']
+ const body = new ReadableStream({
+ start(c) {
+ for (const ch of chunks) c.enqueue(enc.encode(ch))
+ c.close()
+ },
+ })
+ const { client, raw } = clientReturning(new Response(body))
+ const seen: string[] = []
+
+ await tailLogs(client, logsRoot(ns), { query: "*", since: "t0" }, (e) => seen.push(e._msg))
+
+ expect(calledUrl(raw).pathname).toBe(`${logsRoot(ns)}select/logsql/tail`)
+ expect(calledUrl(raw).searchParams.get("since")).toBe("t0")
+ expect(seen).toEqual(["a", "b"])
+ })
+
+ it("omits since on the first connect", async () => {
+ const { client, raw } = clientReturning(new Response(""))
+
+ await tailLogs(client, logsRoot(ns), { query: "*" }, () => {})
+
+ expect(calledUrl(raw).searchParams.has("since")).toBe(false)
+ })
+
+ it("throws a ProxyError when the tail is refused", async () => {
+ const { client } = clientReturning(new Response("", { status: 403 }))
+
+ const err = await tailLogs(client, logsRoot(ns), { query: "*" }, () => {}).catch((e) => e)
+
+ expect(err).toMatchObject({ kind: "forbidden" })
+ })
+})
diff --git a/packages/system/dashboard/images/console/apps/console/src/lib/observability/proxy.ts b/packages/system/dashboard/images/console/apps/console/src/lib/observability/proxy.ts
new file mode 100644
index 000000000..a257825c9
--- /dev/null
+++ b/packages/system/dashboard/images/console/apps/console/src/lib/observability/proxy.ts
@@ -0,0 +1,203 @@
+import type { K8sClient } from "@cozystack/k8s-client"
+
+export type ObservabilityScope =
+ | { namespace: string }
+ | { namespace: string; plural: string; name: string }
+
+function appBase(scope: ObservabilityScope): string | null {
+ if (!("plural" in scope)) return null
+ return `/apis/apps.cozystack.io/v1alpha1/namespaces/${scope.namespace}/${scope.plural}/${scope.name}`
+}
+
+export function metricsRoot(scope: ObservabilityScope): string {
+ const app = appBase(scope)
+ return app ? `${app}/metrics/` : `/apis/cozystack.io/v1alpha1/namespaces/${scope.namespace}/metrics/`
+}
+
+export function logsRoot(scope: ObservabilityScope): string {
+ const app = appBase(scope)
+ return app ? `${app}/log/` : `/apis/cozystack.io/v1alpha1/namespaces/${scope.namespace}/logs/`
+}
+
+export type ProxyErrorKind =
+ | "bad-request"
+ | "unauthorized"
+ | "forbidden"
+ | "not-available"
+ | "limit"
+ | "rate-limited"
+ | "store-unreachable"
+ | "unavailable"
+ | "timeout"
+ | "network"
+ | "unknown"
+
+const KIND_BY_STATUS: Record = {
+ 400: "bad-request",
+ 401: "unauthorized",
+ 403: "forbidden",
+ 404: "not-available",
+ 422: "limit",
+ 429: "rate-limited",
+ 502: "store-unreachable",
+ 503: "unavailable",
+ 504: "timeout",
+}
+
+export function errorKindForStatus(status: number): ProxyErrorKind {
+ return KIND_BY_STATUS[status] ?? "unknown"
+}
+
+export class ProxyError extends Error {
+ kind: ProxyErrorKind
+ status: number
+
+ constructor(kind: ProxyErrorKind, status: number, message: string) {
+ super(message)
+ this.name = "ProxyError"
+ this.kind = kind
+ this.status = status
+ }
+}
+
+// Prometheus answers {"error": "..."}, VictoriaLogs and nginx answer plain text.
+function errorMessage(text: string, status: number): string {
+ try {
+ const parsed: unknown = JSON.parse(text)
+ if (parsed && typeof parsed === "object" && "error" in parsed && typeof parsed.error === "string") {
+ return parsed.error
+ }
+ } catch {
+ // not JSON
+ }
+ const trimmed = text.trim()
+ return trimmed && trimmed.length < 300 && !trimmed.startsWith("<") ? trimmed : `Server returned ${status}`
+}
+
+async function proxyGet(
+ client: K8sClient,
+ path: string,
+ params: Record,
+ signal?: AbortSignal,
+): Promise {
+ const search = new URLSearchParams()
+ for (const [k, v] of Object.entries(params)) if (v !== undefined) search.set(k, String(v))
+ let res: Response
+ try {
+ res = await client.raw(`${path}?${search}`, { signal })
+ } catch (err) {
+ if (signal?.aborted) throw err
+ throw new ProxyError("network", 0, "Unable to connect to the server")
+ }
+ if (!res.ok) {
+ const text = await res.text().catch(() => "")
+ throw new ProxyError(errorKindForStatus(res.status), res.status, errorMessage(text, res.status))
+ }
+ return res
+}
+
+export interface PromSeries {
+ metric: Record
+ values: [number, string][]
+}
+
+export interface RangeParams {
+ query: string
+ start: number
+ end: number
+ step: number
+}
+
+export async function queryRange(
+ client: K8sClient,
+ root: string,
+ params: RangeParams,
+ signal?: AbortSignal,
+): Promise {
+ const res = await proxyGet(client, `${root}api/v1/query_range`, { ...params }, signal)
+ const body = (await res.json()) as { data?: { result?: PromSeries[] } }
+ return body.data?.result ?? []
+}
+
+export interface LogEntry {
+ _time: string
+ _msg: string
+ _stream_id?: string
+ [field: string]: string | undefined
+}
+
+function parseLine(line: string): LogEntry | null {
+ if (!line.trim()) return null
+ try {
+ const value: unknown = JSON.parse(line)
+ if (value && typeof value === "object" && "_time" in value) return value as LogEntry
+ } catch {
+ // a torn or non-JSON line carries nothing to show
+ }
+ return null
+}
+
+export interface LogsQueryParams {
+ query: string
+ start: string
+ end: string
+ limit: number
+}
+
+export async function queryLogs(
+ client: K8sClient,
+ root: string,
+ params: LogsQueryParams,
+ signal?: AbortSignal,
+): Promise {
+ const res = await proxyGet(client, `${root}select/logsql/query`, { ...params }, signal)
+ const entries = (await res.text()).split("\n").map(parseLine).filter((e) => e !== null)
+ return entries.sort((a, b) => (a._time < b._time ? -1 : a._time > b._time ? 1 : 0))
+}
+
+export interface FieldValuesParams {
+ field: string
+ stream: boolean
+ query: string
+ start: string
+ end: string
+}
+
+export async function fieldValues(
+ client: K8sClient,
+ root: string,
+ { stream, ...params }: FieldValuesParams,
+ signal?: AbortSignal,
+): Promise {
+ const endpoint = stream ? "stream_field_values" : "field_values"
+ const res = await proxyGet(client, `${root}select/logsql/${endpoint}`, { ...params }, signal)
+ const body = (await res.json()) as { values?: { value: string }[] }
+ return (body.values ?? []).map((v) => v.value).sort()
+}
+
+export async function tailLogs(
+ client: K8sClient,
+ root: string,
+ params: { query: string; since?: string },
+ onEntry: (entry: LogEntry) => void,
+ signal?: AbortSignal,
+): Promise {
+ const res = await proxyGet(client, `${root}select/logsql/tail`, params, signal)
+ if (!res.body) return
+ const reader = res.body.getReader()
+ const decoder = new TextDecoder()
+ let buffer = ""
+ for (;;) {
+ const { done, value } = await reader.read()
+ if (done) break
+ buffer += decoder.decode(value, { stream: true })
+ const lines = buffer.split("\n")
+ buffer = lines.pop() ?? ""
+ for (const line of lines) {
+ const entry = parseLine(line)
+ if (entry) onEntry(entry)
+ }
+ }
+ const last = parseLine(buffer)
+ if (last) onEntry(last)
+}
diff --git a/packages/system/dashboard/images/console/packages/k8s-client/src/client.ts b/packages/system/dashboard/images/console/packages/k8s-client/src/client.ts
index 12f50e0fd..04c528760 100644
--- a/packages/system/dashboard/images/console/packages/k8s-client/src/client.ts
+++ b/packages/system/dashboard/images/console/packages/k8s-client/src/client.ts
@@ -241,6 +241,24 @@ export class K8sClient {
})
}
+ /**
+ * Fetch a same-origin path with the client's credentials and 401 handling,
+ * leaving status and body to the caller. For endpoints that do not speak
+ * Kubernetes JSON, such as the observability proxy's streamed NDJSON.
+ */
+ async raw(path: string, init?: RequestInit): Promise {
+ const headers: Record = {
+ ...(init?.headers as Record),
+ }
+ if (this.getToken) {
+ headers["Authorization"] = `Bearer ${await this.getToken()}`
+ }
+ const res = await fetch(`${this.baseUrl}${path}`, { ...init, headers })
+ if (res.status === 401) this.handleUnauthorized()
+ else if (res.ok) this.unauthorizedHandled = false
+ return res
+ }
+
getApiGroups(): Promise {
return this.request("/apis")
}
From 063e56ede57a481b2db223a37641e601a2d51a05 Mon Sep 17 00:00:00 2001
From: ZverGuy
Date: Wed, 4 Nov 2026 05:30:03 +0700
Subject: [PATCH 02/46] feat(dashboard): show resource consumption on
application pages
Tenants had no way to see what their applications consume. A Metrics
tab on every application detail page (except VM disks, which run no
containers) charts CPU, memory and network for a selectable range
through the observability proxy's application root, which injects the
scope server-side, so the queries stay kind-agnostic and no per-kind
UI is needed.
Charts use uPlot: about 25 KB gzipped with no dependencies, built for
time series, and loaded only with the Metrics tab so other pages do
not pay for it. A cluster without the proxy answers 404 and the tab
says metrics are not available there instead of showing an error.
Assisted-by: LLM
Signed-off-by: ZverGuy
---
.../images/console/apps/console/package.json | 3 +-
.../observability/MetricsView.test.tsx | 88 +++++++++++++
.../components/observability/MetricsView.tsx | 72 +++++++++++
.../observability/ProxyNotice.test.tsx | 43 +++++++
.../components/observability/ProxyNotice.tsx | 49 +++++++
.../components/observability/RangePicker.tsx | 30 +++++
.../observability/TimeSeriesChart.test.tsx | 46 +++++++
.../observability/TimeSeriesChart.tsx | 51 ++++++++
.../src/lib/observability/metrics.test.ts | 107 ++++++++++++++++
.../console/src/lib/observability/metrics.ts | 121 ++++++++++++++++++
.../src/lib/observability/proxy.test.ts | 10 ++
.../console/src/lib/observability/proxy.ts | 8 ++
.../detail/ApplicationDetailPage.test.tsx | 28 ++++
.../routes/detail/ApplicationDetailPage.tsx | 12 ++
.../console/src/routes/detail/MetricsTab.tsx | 15 +++
.../dashboard/images/console/pnpm-lock.yaml | 8 ++
16 files changed, 690 insertions(+), 1 deletion(-)
create mode 100644 packages/system/dashboard/images/console/apps/console/src/components/observability/MetricsView.test.tsx
create mode 100644 packages/system/dashboard/images/console/apps/console/src/components/observability/MetricsView.tsx
create mode 100644 packages/system/dashboard/images/console/apps/console/src/components/observability/ProxyNotice.test.tsx
create mode 100644 packages/system/dashboard/images/console/apps/console/src/components/observability/ProxyNotice.tsx
create mode 100644 packages/system/dashboard/images/console/apps/console/src/components/observability/RangePicker.tsx
create mode 100644 packages/system/dashboard/images/console/apps/console/src/components/observability/TimeSeriesChart.test.tsx
create mode 100644 packages/system/dashboard/images/console/apps/console/src/components/observability/TimeSeriesChart.tsx
create mode 100644 packages/system/dashboard/images/console/apps/console/src/lib/observability/metrics.test.ts
create mode 100644 packages/system/dashboard/images/console/apps/console/src/lib/observability/metrics.ts
create mode 100644 packages/system/dashboard/images/console/apps/console/src/routes/detail/MetricsTab.tsx
diff --git a/packages/system/dashboard/images/console/apps/console/package.json b/packages/system/dashboard/images/console/apps/console/package.json
index fcddb7023..254195f28 100644
--- a/packages/system/dashboard/images/console/apps/console/package.json
+++ b/packages/system/dashboard/images/console/apps/console/package.json
@@ -31,7 +31,8 @@
"react": "^19.2.4",
"react-dom": "^19.2.4",
"react-router": "^7.6.1",
- "simple-icons": "^16.22.0"
+ "simple-icons": "^16.22.0",
+ "uplot": "^1.6.32"
},
"devDependencies": {
"@tailwindcss/vite": "^4.2.2",
diff --git a/packages/system/dashboard/images/console/apps/console/src/components/observability/MetricsView.test.tsx b/packages/system/dashboard/images/console/apps/console/src/components/observability/MetricsView.test.tsx
new file mode 100644
index 000000000..f09e15201
--- /dev/null
+++ b/packages/system/dashboard/images/console/apps/console/src/components/observability/MetricsView.test.tsx
@@ -0,0 +1,88 @@
+import { describe, it, expect, vi } from "vitest"
+import { screen, waitFor } from "@testing-library/react"
+import userEvent from "@testing-library/user-event"
+import { K8sClient } from "@cozystack/k8s-client"
+import { renderWithK8sProvider } from "../../test-utils/render.tsx"
+import type { ChartData } from "../../lib/observability/metrics.ts"
+
+vi.mock("./TimeSeriesChart.tsx", () => ({
+ TimeSeriesChart: ({ data }: { data: ChartData }) => (
+ {data.series.map((s) => s.label).join(",")}
+ ),
+}))
+
+const { MetricsView } = await import("./MetricsView.tsx")
+
+const scope = { namespace: "tenant-a", plural: "postgreses", name: "db" }
+
+function matrix(pod: string) {
+ return Response.json({
+ status: "success",
+ data: { resultType: "matrix", result: [{ metric: { pod }, values: [[1, "1"]] }] },
+ })
+}
+
+function clientWith(handler: (url: URL) => Response) {
+ const client = new K8sClient()
+ const raw = vi.spyOn(client, "raw").mockImplementation(async (path) => handler(new URL(path, "http://x")))
+ return { client, raw }
+}
+
+describe("MetricsView", () => {
+ it("draws CPU, memory and network from the application root", async () => {
+ const { client, raw } = clientWith(() => matrix("db-0"))
+
+ renderWithK8sProvider( , { client })
+
+ await waitFor(() => expect(screen.getAllByTestId("chart")).toHaveLength(3))
+ expect(screen.getByText("CPU (cores)")).toBeInTheDocument()
+ expect(screen.getByText("Memory (working set)")).toBeInTheDocument()
+ expect(screen.getByText("Network")).toBeInTheDocument()
+ for (const [path] of raw.mock.calls) {
+ expect(path.startsWith("/apis/apps.cozystack.io/v1alpha1/namespaces/tenant-a/postgreses/db/metrics/api/v1/query_range?")).toBe(true)
+ }
+ })
+
+ it("requeries with a coarser step when a longer range is picked", async () => {
+ const { client, raw } = clientWith(() => matrix("db-0"))
+ renderWithK8sProvider( , { client })
+ await waitFor(() => expect(raw).toHaveBeenCalled())
+
+ await userEvent.click(screen.getByRole("button", { name: "7d" }))
+
+ await waitFor(() =>
+ expect(raw.mock.calls.some(([p]) => new URL(p, "http://x").searchParams.get("step") === "2520")).toBe(true),
+ )
+ })
+
+ it("shows one quiet notice instead of three errors when the proxy is absent", async () => {
+ const { client } = clientWith(() => new Response("404 page not found", { status: 404 }))
+
+ renderWithK8sProvider( , { client })
+
+ expect(await screen.findByText("Metrics are not available on this cluster.")).toBeInTheDocument()
+ expect(screen.getAllByRole("status")).toHaveLength(1)
+ expect(screen.queryByText("CPU (cores)")).toBeNull()
+ })
+
+ it("keeps the other panels when one query hits a limit", async () => {
+ const { client } = clientWith((url) =>
+ url.searchParams.get("query")?.includes("memory")
+ ? Response.json({ status: "error", error: "too many series" }, { status: 422 })
+ : matrix("db-0"),
+ )
+
+ renderWithK8sProvider( , { client })
+
+ expect(await screen.findByText("too many series. Choose a shorter range.")).toBeInTheDocument()
+ await waitFor(() => expect(screen.getAllByTestId("chart")).toHaveLength(2))
+ })
+
+ it("says so when a panel has no data", async () => {
+ const { client } = clientWith(() => Response.json({ status: "success", data: { resultType: "matrix", result: [] } }))
+
+ renderWithK8sProvider( , { client })
+
+ await waitFor(() => expect(screen.getAllByText("No data for this range.")).toHaveLength(3))
+ })
+})
diff --git a/packages/system/dashboard/images/console/apps/console/src/components/observability/MetricsView.tsx b/packages/system/dashboard/images/console/apps/console/src/components/observability/MetricsView.tsx
new file mode 100644
index 000000000..35c8e8417
--- /dev/null
+++ b/packages/system/dashboard/images/console/apps/console/src/components/observability/MetricsView.tsx
@@ -0,0 +1,72 @@
+import { useState } from "react"
+import { useQueries } from "@tanstack/react-query"
+import { useK8sClient } from "@cozystack/k8s-client"
+import { Section, Spinner } from "@cozystack/ui"
+import {
+ METRIC_PANELS,
+ RANGES,
+ rangeWindow,
+ toChartData,
+ type RangeKey,
+} from "../../lib/observability/metrics.ts"
+import { isScopeWide, metricsRoot, queryRange, type ObservabilityScope } from "../../lib/observability/proxy.ts"
+import { ProxyNotice } from "./ProxyNotice.tsx"
+import { TimeSeriesChart } from "./TimeSeriesChart.tsx"
+import { RangePicker } from "./RangePicker.tsx"
+
+const REFRESH_MS = 60_000
+
+export function MetricsView({ scope }: { scope: ObservabilityScope }) {
+ const client = useK8sClient()
+ const root = metricsRoot(scope)
+ const [range, setRange] = useState("1h")
+
+ const results = useQueries({
+ queries: METRIC_PANELS.map((panel) => ({
+ queryKey: ["observability", "metrics", root, panel.id, range],
+ queryFn: async ({ signal }: { signal: AbortSignal }) => {
+ const window = rangeWindow(range, Math.floor(Date.now() / 1000))
+ const series = await Promise.all(
+ panel.queries(window).map(async (q) => ({
+ label: q.label,
+ series: await queryRange(client, root, { query: q.expr, ...window }, signal),
+ })),
+ )
+ return toChartData(series)
+ },
+ retry: false,
+ refetchInterval: REFRESH_MS,
+ })),
+ })
+
+ const wide = results.find((r) => isScopeWide(r.error))?.error
+
+ return (
+
+
+
Resource consumption
+
+
+ {wide ? (
+
+ ) : (
+ METRIC_PANELS.map((panel, i) => {
+ const { data, error, isLoading } = results[i]
+ return (
+
+ {error ? (
+
+ ) : isLoading || !data ? (
+
+ ) : data.series.length === 0 ? (
+ No data for this range.
+ ) : (
+
+ )}
+
+ )
+ })
+ )}
+
+ )
+}
diff --git a/packages/system/dashboard/images/console/apps/console/src/components/observability/ProxyNotice.test.tsx b/packages/system/dashboard/images/console/apps/console/src/components/observability/ProxyNotice.test.tsx
new file mode 100644
index 000000000..fd001bcae
--- /dev/null
+++ b/packages/system/dashboard/images/console/apps/console/src/components/observability/ProxyNotice.test.tsx
@@ -0,0 +1,43 @@
+import { describe, it, expect } from "vitest"
+import { render, screen } from "@testing-library/react"
+import { ProxyError } from "../../lib/observability/proxy.ts"
+import { ProxyNotice } from "./ProxyNotice.tsx"
+
+describe("ProxyNotice", () => {
+ it("renders a 404 as not available on this cluster, not as an error", () => {
+ render( )
+
+ expect(screen.getByRole("status")).toHaveTextContent("Metrics are not available on this cluster.")
+ expect(screen.queryByRole("alert")).toBeNull()
+ })
+
+ it("renders a 502 as a quiet notice about the store", () => {
+ render( )
+
+ expect(screen.getByRole("status")).toHaveTextContent("The logs store is unreachable right now.")
+ })
+
+ it.each([
+ ["forbidden", 403, "You do not have permission to read metrics here."],
+ ["limit", 422, "too many points. Choose a shorter range."],
+ ["rate-limited", 429, "Too many requests. Try again in a moment."],
+ ["timeout", 504, "The store did not answer in time. Choose a shorter range or a narrower filter."],
+ ["unavailable", 503, "The service is temporarily unavailable. Try again in a moment."],
+ ] as const)("explains %s", (kind, status, text) => {
+ render( )
+
+ expect(screen.getByRole("alert")).toHaveTextContent(text)
+ })
+
+ it("shows the server message for a rejected query", () => {
+ render( )
+
+ expect(screen.getByRole("alert")).toHaveTextContent("cannot parse query")
+ })
+
+ it("falls back to the message of an unexpected error", () => {
+ render( )
+
+ expect(screen.getByRole("alert")).toHaveTextContent("boom")
+ })
+})
diff --git a/packages/system/dashboard/images/console/apps/console/src/components/observability/ProxyNotice.tsx b/packages/system/dashboard/images/console/apps/console/src/components/observability/ProxyNotice.tsx
new file mode 100644
index 000000000..a60b831b0
--- /dev/null
+++ b/packages/system/dashboard/images/console/apps/console/src/components/observability/ProxyNotice.tsx
@@ -0,0 +1,49 @@
+import { ProxyError } from "../../lib/observability/proxy.ts"
+
+interface ProxyNoticeProps {
+ what: "Metrics" | "Logs"
+ error: unknown
+}
+
+function describe(what: ProxyNoticeProps["what"], error: unknown): { quiet: boolean; text: string } {
+ const lower = what.toLowerCase()
+ if (!(error instanceof ProxyError)) {
+ return { quiet: false, text: error instanceof Error ? error.message : String(error) }
+ }
+ switch (error.kind) {
+ case "not-available":
+ return { quiet: true, text: `${what} are not available on this cluster.` }
+ case "store-unreachable":
+ return { quiet: true, text: `The ${lower} store is unreachable right now.` }
+ case "unauthorized":
+ return { quiet: false, text: "Your session has expired. Sign in again." }
+ case "forbidden":
+ return { quiet: false, text: `You do not have permission to read ${lower} here.` }
+ case "limit":
+ return { quiet: false, text: `${error.message}. Choose a shorter range.` }
+ case "rate-limited":
+ return { quiet: false, text: "Too many requests. Try again in a moment." }
+ case "timeout":
+ return { quiet: false, text: "The store did not answer in time. Choose a shorter range or a narrower filter." }
+ case "unavailable":
+ return { quiet: false, text: "The service is temporarily unavailable. Try again in a moment." }
+ default:
+ return { quiet: false, text: error.message }
+ }
+}
+
+export function ProxyNotice({ what, error }: ProxyNoticeProps) {
+ const { quiet, text } = describe(what, error)
+ if (quiet) {
+ return (
+
+ {text}
+
+ )
+ }
+ return (
+
+ {text}
+
+ )
+}
diff --git a/packages/system/dashboard/images/console/apps/console/src/components/observability/RangePicker.tsx b/packages/system/dashboard/images/console/apps/console/src/components/observability/RangePicker.tsx
new file mode 100644
index 000000000..22030c706
--- /dev/null
+++ b/packages/system/dashboard/images/console/apps/console/src/components/observability/RangePicker.tsx
@@ -0,0 +1,30 @@
+import { cn } from "@cozystack/ui"
+
+export function RangePicker({
+ options,
+ value,
+ onChange,
+}: {
+ options: readonly K[]
+ value: K
+ onChange: (value: K) => void
+}) {
+ return (
+
+ {options.map((key) => (
+ onChange(key)}
+ className={cn(
+ "rounded px-2.5 py-1 text-xs",
+ value === key ? "bg-slate-900 text-white" : "text-slate-600 hover:bg-slate-100",
+ )}
+ >
+ {key}
+
+ ))}
+
+ )
+}
diff --git a/packages/system/dashboard/images/console/apps/console/src/components/observability/TimeSeriesChart.test.tsx b/packages/system/dashboard/images/console/apps/console/src/components/observability/TimeSeriesChart.test.tsx
new file mode 100644
index 000000000..57cf6fb99
--- /dev/null
+++ b/packages/system/dashboard/images/console/apps/console/src/components/observability/TimeSeriesChart.test.tsx
@@ -0,0 +1,46 @@
+import { describe, it, expect, vi, beforeEach } from "vitest"
+import { render } from "@testing-library/react"
+
+const created: { opts: { series: { label?: string }[] }; data: unknown[]; destroy: ReturnType }[] = []
+
+vi.mock("uplot", () => ({
+ default: class {
+ destroy = vi.fn()
+ constructor(opts: { series: { label?: string }[] }, data: unknown[]) {
+ created.push({ opts, data, destroy: this.destroy })
+ }
+ setSize() {}
+ },
+}))
+
+const { TimeSeriesChart } = await import("./TimeSeriesChart.tsx")
+
+beforeEach(() => {
+ created.length = 0
+})
+
+describe("TimeSeriesChart", () => {
+ const data = {
+ timestamps: [1, 2],
+ series: [
+ { label: "db-0", values: [1, 2] },
+ { label: "db-1", values: [null, 3] },
+ ],
+ }
+
+ it("hands uPlot the timestamps first and one labelled series per input", () => {
+ render( )
+
+ expect(created).toHaveLength(1)
+ expect(created[0].data).toEqual([[1, 2], [1, 2], [null, 3]])
+ expect(created[0].opts.series.slice(1).map((s) => s.label)).toEqual(["db-0", "db-1"])
+ })
+
+ it("destroys the chart on unmount", () => {
+ const { unmount } = render( )
+
+ unmount()
+
+ expect(created[0].destroy).toHaveBeenCalled()
+ })
+})
diff --git a/packages/system/dashboard/images/console/apps/console/src/components/observability/TimeSeriesChart.tsx b/packages/system/dashboard/images/console/apps/console/src/components/observability/TimeSeriesChart.tsx
new file mode 100644
index 000000000..6b596e17f
--- /dev/null
+++ b/packages/system/dashboard/images/console/apps/console/src/components/observability/TimeSeriesChart.tsx
@@ -0,0 +1,51 @@
+import { useEffect, useRef } from "react"
+import uPlot from "uplot"
+import "uplot/dist/uPlot.min.css"
+import type { ChartData } from "../../lib/observability/metrics.ts"
+
+const COLORS = ["#2563eb", "#16a34a", "#d97706", "#9333ea", "#dc2626", "#0891b2", "#4b5563", "#db2777"]
+const HEIGHT = 200
+
+interface TimeSeriesChartProps {
+ data: ChartData
+ format: (value: number) => string
+}
+
+export function TimeSeriesChart({ data, format }: TimeSeriesChartProps) {
+ const ref = useRef(null)
+
+ useEffect(() => {
+ const el = ref.current
+ if (!el) return
+ const fmt = (v: number | null) => (v === null ? "–" : format(v))
+ const chart = new uPlot(
+ {
+ width: el.clientWidth || 600,
+ height: HEIGHT,
+ scales: { x: { time: true } },
+ legend: { live: true },
+ series: [
+ {},
+ ...data.series.map((s, i) => ({
+ label: s.label,
+ stroke: COLORS[i % COLORS.length],
+ width: 1.5,
+ value: (_: uPlot, v: number | null) => fmt(v),
+ })),
+ ],
+ axes: [{}, { size: 70, values: (_: uPlot, splits: number[]) => splits.map(format) }],
+ },
+ [data.timestamps, ...data.series.map((s) => s.values)],
+ el,
+ )
+ if (typeof ResizeObserver === "undefined") return () => chart.destroy()
+ const observer = new ResizeObserver(() => chart.setSize({ width: el.clientWidth, height: HEIGHT }))
+ observer.observe(el)
+ return () => {
+ observer.disconnect()
+ chart.destroy()
+ }
+ }, [data, format])
+
+ return
+}
diff --git a/packages/system/dashboard/images/console/apps/console/src/lib/observability/metrics.test.ts b/packages/system/dashboard/images/console/apps/console/src/lib/observability/metrics.test.ts
new file mode 100644
index 000000000..0803940bf
--- /dev/null
+++ b/packages/system/dashboard/images/console/apps/console/src/lib/observability/metrics.test.ts
@@ -0,0 +1,107 @@
+import { describe, it, expect } from "vitest"
+import {
+ METRIC_PANELS,
+ formatBytes,
+ formatCores,
+ rangeWindow,
+ toChartData,
+} from "./metrics.ts"
+
+describe("rangeWindow", () => {
+ it("ends now and spans the range in about 240 points", () => {
+ const w = rangeWindow("6h", 1_000_000)
+
+ expect(w.end).toBe(1_000_000)
+ expect(w.start).toBe(1_000_000 - 6 * 3600)
+ expect(w.step).toBe(90)
+ })
+
+ it("never steps finer than 15s", () => {
+ expect(rangeWindow("1h", 0).step).toBe(15)
+ })
+})
+
+describe("METRIC_PANELS", () => {
+ const window = { start: 0, end: 3600, step: 15 }
+
+ it("rates CPU over at least five minutes so sparse scrapes still draw", () => {
+ const [query] = METRIC_PANELS.find((p) => p.id === "cpu")!.queries(window)
+
+ expect(query.expr).toBe(
+ 'sum by (pod) (rate(container_cpu_usage_seconds_total{container!="",container!="POD"}[300s]))',
+ )
+ })
+
+ it("widens the rate window with the step on long ranges", () => {
+ const [query] = METRIC_PANELS.find((p) => p.id === "cpu")!.queries({ start: 0, end: 1, step: 2520 })
+
+ expect(query.expr).toContain("[5040s]")
+ })
+
+ it("reads memory as working set per pod", () => {
+ const [query] = METRIC_PANELS.find((p) => p.id === "memory")!.queries(window)
+
+ expect(query.expr).toBe('sum by (pod) (container_memory_working_set_bytes{container!="",container!="POD"})')
+ })
+
+ it("draws network receive and transmit as two named series", () => {
+ const queries = METRIC_PANELS.find((p) => p.id === "network")!.queries(window)
+
+ expect(queries.map((q) => q.label)).toEqual(["receive", "transmit"])
+ expect(queries[0].expr).toBe("sum(rate(container_network_receive_bytes_total[300s]))")
+ expect(queries[1].expr).toBe("sum(rate(container_network_transmit_bytes_total[300s]))")
+ })
+
+ it("names no application kind in any query", () => {
+ for (const panel of METRIC_PANELS) {
+ for (const q of panel.queries(window)) expect(q.expr).not.toMatch(/apps_cozystack_io|namespace=/)
+ }
+ })
+})
+
+describe("toChartData", () => {
+ it("aligns series on the union of timestamps and leaves gaps as null", () => {
+ const data = toChartData([
+ { label: "a", series: [{ metric: {}, values: [[10, "1"], [20, "2"]] }] },
+ { label: "b", series: [{ metric: {}, values: [[20, "5"], [30, "6"]] }] },
+ ])
+
+ expect(data.timestamps).toEqual([10, 20, 30])
+ expect(data.series).toEqual([
+ { label: "a", values: [1, 2, null] },
+ { label: "b", values: [null, 5, 6] },
+ ])
+ })
+
+ it("labels each series by its pod, falling back to the query label", () => {
+ const data = toChartData([
+ {
+ label: "cpu",
+ series: [
+ { metric: { pod: "db-1" }, values: [[1, "0.5"]] },
+ { metric: {}, values: [[1, "0.1"]] },
+ ],
+ },
+ ])
+
+ expect(data.series.map((s) => s.label)).toEqual(["db-1", "cpu"])
+ })
+
+ it("drops NaN samples instead of drawing them as zero", () => {
+ const data = toChartData([{ label: "x", series: [{ metric: {}, values: [[1, "NaN"]] }] }])
+
+ expect(data.series[0].values).toEqual([null])
+ })
+})
+
+describe("formatters", () => {
+ it("formats CPU in millicores below one core", () => {
+ expect(formatCores(0.25)).toBe("250m")
+ expect(formatCores(2)).toBe("2")
+ })
+
+ it("formats bytes with binary units", () => {
+ expect(formatBytes(512)).toBe("512 B")
+ expect(formatBytes(3 * 1024 * 1024)).toBe("3.0 MiB")
+ })
+})
diff --git a/packages/system/dashboard/images/console/apps/console/src/lib/observability/metrics.ts b/packages/system/dashboard/images/console/apps/console/src/lib/observability/metrics.ts
new file mode 100644
index 000000000..b23a51e27
--- /dev/null
+++ b/packages/system/dashboard/images/console/apps/console/src/lib/observability/metrics.ts
@@ -0,0 +1,121 @@
+import type { PromSeries } from "./proxy.ts"
+
+export const RANGES = {
+ "1h": 3600,
+ "6h": 6 * 3600,
+ "24h": 24 * 3600,
+ "7d": 7 * 24 * 3600,
+} as const
+
+export type RangeKey = keyof typeof RANGES
+
+export interface RangeWindow {
+ start: number
+ end: number
+ step: number
+}
+
+const POINTS = 240
+const MIN_STEP = 15
+
+export function rangeWindow(range: RangeKey, nowSeconds: number): RangeWindow {
+ const span = RANGES[range]
+ return { start: nowSeconds - span, end: nowSeconds, step: Math.max(MIN_STEP, Math.round(span / POINTS)) }
+}
+
+// A rate needs several scrapes inside its window, and on long ranges the window
+// must also cover the step or samples between points are skipped.
+function rateWindow(step: number): string {
+ return `${Math.max(300, step * 2)}s`
+}
+
+const CONTAINERS = 'container!="",container!="POD"'
+
+export interface MetricQuery {
+ label: string
+ expr: string
+}
+
+export interface MetricPanel {
+ id: "cpu" | "memory" | "network"
+ title: string
+ format: (value: number) => string
+ queries: (window: RangeWindow) => MetricQuery[]
+}
+
+export function formatCores(value: number): string {
+ if (value === 0) return "0"
+ if (Math.abs(value) < 1) return `${Math.round(value * 1000)}m`
+ return `${Number(value.toFixed(2))}`
+}
+
+const BYTE_UNITS = ["B", "KiB", "MiB", "GiB", "TiB"]
+
+export function formatBytes(value: number): string {
+ let v = value
+ let unit = 0
+ while (Math.abs(v) >= 1024 && unit < BYTE_UNITS.length - 1) {
+ v /= 1024
+ unit++
+ }
+ return unit === 0 ? `${Math.round(v)} B` : `${v.toFixed(1)} ${BYTE_UNITS[unit]}`
+}
+
+// The proxy injects the namespace or application scope, so these stay kind-agnostic.
+export const METRIC_PANELS: MetricPanel[] = [
+ {
+ id: "cpu",
+ title: "CPU (cores)",
+ format: formatCores,
+ queries: ({ step }) => [
+ {
+ label: "cpu",
+ expr: `sum by (pod) (rate(container_cpu_usage_seconds_total{${CONTAINERS}}[${rateWindow(step)}]))`,
+ },
+ ],
+ },
+ {
+ id: "memory",
+ title: "Memory (working set)",
+ format: formatBytes,
+ queries: () => [
+ { label: "memory", expr: `sum by (pod) (container_memory_working_set_bytes{${CONTAINERS}})` },
+ ],
+ },
+ {
+ id: "network",
+ title: "Network",
+ format: (v) => `${formatBytes(v)}/s`,
+ queries: ({ step }) => [
+ { label: "receive", expr: `sum(rate(container_network_receive_bytes_total[${rateWindow(step)}]))` },
+ { label: "transmit", expr: `sum(rate(container_network_transmit_bytes_total[${rateWindow(step)}]))` },
+ ],
+ },
+]
+
+export interface ChartSeries {
+ label: string
+ values: (number | null)[]
+}
+
+export interface ChartData {
+ timestamps: number[]
+ series: ChartSeries[]
+}
+
+export function toChartData(results: { label: string; series: PromSeries[] }[]): ChartData {
+ const flat = results.flatMap(({ label, series }) =>
+ series.map((s) => ({ label: s.metric.pod ?? label, points: new Map(s.values.map(([t, v]) => [t, Number(v)])) })),
+ )
+ const timestamps = [...new Set(flat.flatMap((s) => [...s.points.keys()]))].sort((a, b) => a - b)
+ return {
+ timestamps,
+ series: flat.map(({ label, points }) => ({
+ label,
+ values: timestamps.map((t) => {
+ const v = points.get(t)
+ return v === undefined || Number.isNaN(v) ? null : v
+ }),
+ })),
+ }
+}
diff --git a/packages/system/dashboard/images/console/apps/console/src/lib/observability/proxy.test.ts b/packages/system/dashboard/images/console/apps/console/src/lib/observability/proxy.test.ts
index f06835ff7..f8cf44656 100644
--- a/packages/system/dashboard/images/console/apps/console/src/lib/observability/proxy.test.ts
+++ b/packages/system/dashboard/images/console/apps/console/src/lib/observability/proxy.test.ts
@@ -4,6 +4,7 @@ import {
ProxyError,
errorKindForStatus,
fieldValues,
+ isScopeWide,
logsRoot,
metricsRoot,
queryLogs,
@@ -177,3 +178,12 @@ describe("tailLogs", () => {
expect(err).toMatchObject({ kind: "forbidden" })
})
})
+
+describe("isScopeWide", () => {
+ it("is true for answers that do not depend on the query", () => {
+ expect(isScopeWide(new ProxyError("not-available", 404, ""))).toBe(true)
+ expect(isScopeWide(new ProxyError("forbidden", 403, ""))).toBe(true)
+ expect(isScopeWide(new ProxyError("limit", 422, ""))).toBe(false)
+ expect(isScopeWide(new Error("x"))).toBe(false)
+ })
+})
diff --git a/packages/system/dashboard/images/console/apps/console/src/lib/observability/proxy.ts b/packages/system/dashboard/images/console/apps/console/src/lib/observability/proxy.ts
index a257825c9..40b451b0b 100644
--- a/packages/system/dashboard/images/console/apps/console/src/lib/observability/proxy.ts
+++ b/packages/system/dashboard/images/console/apps/console/src/lib/observability/proxy.ts
@@ -60,6 +60,14 @@ export class ProxyError extends Error {
}
}
+// These answers hold for every query in the scope, so one notice replaces the whole view.
+export function isScopeWide(error: unknown): boolean {
+ return (
+ error instanceof ProxyError &&
+ (error.kind === "not-available" || error.kind === "forbidden" || error.kind === "unauthorized")
+ )
+}
+
// Prometheus answers {"error": "..."}, VictoriaLogs and nginx answer plain text.
function errorMessage(text: string, status: number): string {
try {
diff --git a/packages/system/dashboard/images/console/apps/console/src/routes/detail/ApplicationDetailPage.test.tsx b/packages/system/dashboard/images/console/apps/console/src/routes/detail/ApplicationDetailPage.test.tsx
index a015a98bf..40b923f62 100644
--- a/packages/system/dashboard/images/console/apps/console/src/routes/detail/ApplicationDetailPage.test.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/routes/detail/ApplicationDetailPage.test.tsx
@@ -59,6 +59,7 @@ vi.mock("./EventsTab.tsx", () => ({ EventsTab: () => null }))
vi.mock("./VncTab.tsx", () => ({ VncTab: () => null }))
vi.mock("./SerialTab.tsx", () => ({ SerialTab: () => null }))
vi.mock("./VMPowerControls.tsx", () => ({ VMPowerControls: () => null }))
+vi.mock("./MetricsTab.tsx", () => ({ MetricsTab: () => null }))
const { ApplicationDetailPage } = await import("./ApplicationDetailPage.tsx")
@@ -111,11 +112,38 @@ describe("ApplicationDetailPage tabs for a virtual machine", () => {
"VNC",
"Workloads",
"Services",
+ "Metrics",
"Events",
])
})
})
+describe("ApplicationDetailPage observability tabs", () => {
+ function showKind(kind: string, plural: string) {
+ h.appKind = kind
+ h.appPlural = plural
+ h.get = {
+ data: { kind, metadata: { name: "demo", namespace: "tenant-test" } },
+ isLoading: false,
+ error: undefined,
+ }
+ h.configMaps = []
+ h.configMapsError = undefined
+ h.tabLabels = []
+ renderPage()
+ }
+
+ it("offers Metrics on any application kind, ahead of Events", () => {
+ showKind("Postgres", "postgreses")
+ expect(h.tabLabels.slice(-3)).toEqual(["Secrets", "Metrics", "Events"])
+ })
+
+ it("leaves Metrics off a VM disk, which runs no containers", () => {
+ showKind("VMDisk", "vmdisks")
+ expect(h.tabLabels).not.toContain("Metrics")
+ })
+})
+
describe("ApplicationDetailPage configuration", () => {
it("offers ConfigMaps declared by the application's resource map", () => {
h.appKind = "FoundationDB"
diff --git a/packages/system/dashboard/images/console/apps/console/src/routes/detail/ApplicationDetailPage.tsx b/packages/system/dashboard/images/console/apps/console/src/routes/detail/ApplicationDetailPage.tsx
index 55fa684b8..4520244d5 100644
--- a/packages/system/dashboard/images/console/apps/console/src/routes/detail/ApplicationDetailPage.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/routes/detail/ApplicationDetailPage.tsx
@@ -37,6 +37,8 @@ import { VncTab } from "./VncTab.tsx"
// fetched only when a VM's console is opened. Every dashboard page reaches this
// file, and most of them never touch a VM.
const SerialTab = lazy(() => import("./SerialTab.tsx").then((m) => ({ default: m.SerialTab })))
+// Same for the charting library behind the Metrics tab.
+const MetricsTab = lazy(() => import("./MetricsTab.tsx").then((m) => ({ default: m.MetricsTab })))
import { VMPowerControls } from "./VMPowerControls.tsx"
import { useResourceBasePath } from "../../lib/portal.ts"
import { useResourcePresence } from "./use-resource-presence.ts"
@@ -143,6 +145,7 @@ export function ApplicationDetailPage() {
{ to: `${base}/vnc`, label: "VNC", end: false },
{ to: `${base}/workloads`, label: "Workloads", end: false },
{ to: `${base}/services`, label: "Services", end: false },
+ { to: `${base}/metrics`, label: "Metrics", end: false },
{ to: `${base}/events`, label: "Events", end: false },
)
} else {
@@ -163,6 +166,7 @@ export function ApplicationDetailPage() {
}
tabs.push(
{ to: `${base}/secrets`, label: "Secrets", end: false },
+ { to: `${base}/metrics`, label: "Metrics", end: false },
{ to: `${base}/events`, label: "Events", end: false },
)
}
@@ -262,6 +266,14 @@ export function ApplicationDetailPage() {
}
/>
} />
+ }>
+
+
+ }
+ />
diff --git a/packages/system/dashboard/images/console/apps/console/src/routes/detail/MetricsTab.tsx b/packages/system/dashboard/images/console/apps/console/src/routes/detail/MetricsTab.tsx
new file mode 100644
index 000000000..a928e633d
--- /dev/null
+++ b/packages/system/dashboard/images/console/apps/console/src/routes/detail/MetricsTab.tsx
@@ -0,0 +1,15 @@
+import type { ApplicationDefinition, ApplicationInstance } from "@cozystack/types"
+import { useTenantContext } from "../../lib/tenant-context.tsx"
+import { MetricsView } from "../../components/observability/MetricsView.tsx"
+
+interface MetricsTabProps {
+ ad: ApplicationDefinition
+ instance: ApplicationInstance
+}
+
+export function MetricsTab({ ad, instance }: MetricsTabProps) {
+ const { tenantNamespace } = useTenantContext()
+ const plural = ad.spec?.application.plural
+ if (!tenantNamespace || !plural) return null
+ return
+}
diff --git a/packages/system/dashboard/images/console/pnpm-lock.yaml b/packages/system/dashboard/images/console/pnpm-lock.yaml
index 9d90b0c5c..4661c444a 100644
--- a/packages/system/dashboard/images/console/pnpm-lock.yaml
+++ b/packages/system/dashboard/images/console/pnpm-lock.yaml
@@ -92,6 +92,9 @@ importers:
simple-icons:
specifier: ^16.22.0
version: 16.22.0
+ uplot:
+ specifier: ^1.6.32
+ version: 1.6.32
devDependencies:
'@tailwindcss/vite':
specifier: ^4.2.2
@@ -1773,6 +1776,9 @@ packages:
peerDependencies:
browserslist: '>= 4.21.0'
+ uplot@1.6.32:
+ resolution: {integrity: sha512-KIMVnG68zvu5XXUbC4LQEPnhwOxBuLyW1AHtpm6IKTXImkbLgkMy+jabjLgSLMasNuGGzQm/ep3tOkyTxpiQIw==}
+
uri-js@4.4.1:
resolution: {integrity: sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==}
@@ -3405,6 +3411,8 @@ snapshots:
escalade: 3.2.0
picocolors: 1.1.1
+ uplot@1.6.32: {}
+
uri-js@4.4.1:
dependencies:
punycode: 2.3.1
From b5a0ab8de6db7e68a6f4396f01becd8cb98b1dff Mon Sep 17 00:00:00 2001
From: ZverGuy
Date: Wed, 4 Nov 2026 05:34:01 +0700
Subject: [PATCH 03/46] feat(dashboard): add a log viewer for the observability
proxy
Tenants could not read their applications' logs without Grafana. The
viewer reads VictoriaLogs' native responses through a proxy root: a
time-ranged LogsQL query, pod and container pickers fed by the stream
field values of the same scope, and a follow mode over the streamed
tail.
The picked pod and container wrap the filter part of the query rather
than being appended to it, because AND binds tighter than OR in LogsQL
and the user's pipes must still run last. A dropped tail resumes from
the last line's _time; the proxy may replay lines around that point,
so the client drops replayed lines it already holds by stream and
time, which VictoriaLogs does not guarantee unique and is therefore
applied only at the resume boundary. Follow keeps the newest 1000
lines so a chatty stream cannot grow the page without bound.
Assisted-by: LLM
Signed-off-by: ZverGuy
---
.../observability/LogsView.test.tsx | 111 +++++++++++++
.../src/components/observability/LogsView.tsx | 152 ++++++++++++++++++
.../src/lib/observability/logs.test.ts | 65 ++++++++
.../console/src/lib/observability/logs.ts | 73 +++++++++
.../console/src/lib/observability/proxy.ts | 3 +-
.../lib/observability/use-log-tail.test.tsx | 65 ++++++++
.../src/lib/observability/use-log-tail.ts | 95 +++++++++++
7 files changed, 563 insertions(+), 1 deletion(-)
create mode 100644 packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.test.tsx
create mode 100644 packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.tsx
create mode 100644 packages/system/dashboard/images/console/apps/console/src/lib/observability/logs.test.ts
create mode 100644 packages/system/dashboard/images/console/apps/console/src/lib/observability/logs.ts
create mode 100644 packages/system/dashboard/images/console/apps/console/src/lib/observability/use-log-tail.test.tsx
create mode 100644 packages/system/dashboard/images/console/apps/console/src/lib/observability/use-log-tail.ts
diff --git a/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.test.tsx b/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.test.tsx
new file mode 100644
index 000000000..693adf70a
--- /dev/null
+++ b/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.test.tsx
@@ -0,0 +1,111 @@
+import { describe, it, expect, vi } from "vitest"
+import { screen, waitFor } from "@testing-library/react"
+import userEvent from "@testing-library/user-event"
+import { K8sClient } from "@cozystack/k8s-client"
+import { renderWithK8sProvider } from "../../test-utils/render.tsx"
+import { LogsView } from "./LogsView.tsx"
+
+const app = { namespace: "tenant-a", plural: "postgreses", name: "db" }
+const ROOT = "/apis/apps.cozystack.io/v1alpha1/namespaces/tenant-a/postgreses/db/log/"
+
+const line = (time: string, msg: string, pod = "db-0") =>
+ JSON.stringify({ _time: time, _msg: msg, _stream_id: "s", kubernetes_pod_name: pod, kubernetes_container_name: "postgres" })
+
+function clientWith(handler: (endpoint: string, params: URLSearchParams) => Response | Promise) {
+ const client = new K8sClient()
+ const raw = vi.spyOn(client, "raw").mockImplementation(async (path) => {
+ const url = new URL(path, "http://x")
+ return handler(url.pathname, url.searchParams)
+ })
+ return { client, raw }
+}
+
+const values = (...v: string[]) => Response.json({ values: v.map((value) => ({ value, hits: 1 })) })
+
+function defaultHandler(endpoint: string, params?: URLSearchParams): Response | Promise {
+ if (endpoint.endsWith("stream_field_values")) {
+ return params?.get("field") === "kubernetes_pod_name" ? values("db-0", "db-1") : values("postgres")
+ }
+ if (endpoint.endsWith("query")) return new Response(`${line("2026-11-04T10:00:01Z", "ready to accept connections")}\n`)
+ return new Promise(() => {})
+}
+
+describe("LogsView", () => {
+ it("shows recent lines from the application root", async () => {
+ const { client, raw } = clientWith(defaultHandler)
+
+ renderWithK8sProvider( , { client })
+
+ expect(await screen.findByText("ready to accept connections")).toBeInTheDocument()
+ const call = raw.mock.calls.find(([p]) => p.includes("select/logsql/query?"))!
+ expect(call[0].startsWith(`${ROOT}select/logsql/query?`)).toBe(true)
+ const params = new URL(call[0], "http://x").searchParams
+ expect(params.get("query")).toBe("*")
+ expect(params.get("limit")).toBe("500")
+ })
+
+ it("narrows to the picked pod with a stream filter", async () => {
+ const { client, raw } = clientWith(defaultHandler)
+ renderWithK8sProvider( , { client })
+ await screen.findByRole("option", { name: "db-1" })
+
+ await userEvent.selectOptions(screen.getByLabelText("Pod"), "db-1")
+
+ await waitFor(() =>
+ expect(
+ raw.mock.calls.some(([p]) => new URL(p, "http://x").searchParams.get("query") === '{kubernetes_pod_name="db-1"} (*)'),
+ ).toBe(true),
+ )
+ })
+
+ it("applies the LogsQL filter on submit", async () => {
+ const { client, raw } = clientWith(defaultHandler)
+ renderWithK8sProvider( , { client })
+
+ await userEvent.type(screen.getByLabelText("LogsQL filter"), "error{Enter}")
+
+ await waitFor(() =>
+ expect(raw.mock.calls.some(([p]) => p.includes("select/logsql/query?") && p.includes("query=error"))).toBe(true),
+ )
+ })
+
+ it("follows the live tail when Follow is pressed", async () => {
+ const { client } = clientWith((endpoint, params) =>
+ endpoint.endsWith("tail") ? new Response(`${line("2026-11-04T10:00:05Z", "checkpoint complete")}\n`) : defaultHandler(endpoint, params),
+ )
+ renderWithK8sProvider( , { client })
+
+ await userEvent.click(screen.getByRole("button", { name: "Follow" }))
+
+ expect(await screen.findByText("checkpoint complete")).toBeInTheDocument()
+ expect(screen.getByRole("button", { name: "Follow" })).toHaveAttribute("aria-pressed", "true")
+ })
+
+ it("renders a cluster without the proxy as not available", async () => {
+ const { client } = clientWith(() => new Response("404 page not found", { status: 404 }))
+
+ renderWithK8sProvider( , { client })
+
+ expect(await screen.findByText("Logs are not available on this cluster.")).toBeInTheDocument()
+ expect(screen.queryByLabelText("LogsQL filter")).toBeNull()
+ })
+
+ it("keeps the controls and explains a rejected query", async () => {
+ const { client } = clientWith((endpoint, params) =>
+ endpoint.endsWith("query") ? new Response("cannot parse query", { status: 400 }) : defaultHandler(endpoint, params),
+ )
+
+ renderWithK8sProvider( , { client })
+
+ expect(await screen.findByText("cannot parse query")).toBeInTheDocument()
+ expect(screen.getByLabelText("LogsQL filter")).toBeInTheDocument()
+ })
+
+ it("names the source pod and container of each line", async () => {
+ const { client } = clientWith(defaultHandler)
+
+ renderWithK8sProvider( , { client })
+
+ expect(await screen.findByText("db-0/postgres")).toBeInTheDocument()
+ })
+})
diff --git a/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.tsx b/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.tsx
new file mode 100644
index 000000000..03235cda3
--- /dev/null
+++ b/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.tsx
@@ -0,0 +1,152 @@
+import { useEffect, useRef, useState } from "react"
+import { useQuery } from "@tanstack/react-query"
+import { useK8sClient } from "@cozystack/k8s-client"
+import { Button, Spinner } from "@cozystack/ui"
+import {
+ CONTAINER_FIELD,
+ LOG_RANGES,
+ POD_FIELD,
+ buildLogsQuery,
+ type LogRangeKey,
+} from "../../lib/observability/logs.ts"
+import {
+ fieldValues,
+ isScopeWide,
+ logsRoot,
+ queryLogs,
+ type LogEntry,
+ type ObservabilityScope,
+} from "../../lib/observability/proxy.ts"
+import { useLogTail } from "../../lib/observability/use-log-tail.ts"
+import { ProxyNotice } from "./ProxyNotice.tsx"
+import { RangePicker } from "./RangePicker.tsx"
+
+const HISTORY_LIMIT = 500
+const FOLLOW_CAP = 1000
+
+function windowFor(range: LogRangeKey) {
+ const end = Date.now()
+ return { start: new Date(end - LOG_RANGES[range] * 1000).toISOString(), end: new Date(end).toISOString() }
+}
+
+function Picker({ label, value, options, onChange }: { label: string; value: string; options: string[]; onChange: (v: string) => void }) {
+ return (
+
+ {label}
+ onChange(e.target.value)}
+ className="rounded-md border border-slate-200 bg-white px-2 py-1 text-xs text-slate-900"
+ >
+ All
+ {options.map((o) => (
+
+ {o}
+
+ ))}
+
+
+ )
+}
+
+function LogLines({ entries, follow }: { entries: LogEntry[]; follow: boolean }) {
+ const ref = useRef(null)
+ useEffect(() => {
+ if (follow && ref.current) ref.current.scrollTop = ref.current.scrollHeight
+ }, [entries, follow])
+ if (entries.length === 0) return No log lines for this range and filter.
+ return (
+
+ {entries.map((e, i) => (
+
+ {new Date(e._time).toLocaleTimeString()} {" "}
+ {`${e[POD_FIELD] ?? ""}/${e[CONTAINER_FIELD] ?? ""}`} {" "}
+ {e._msg}
+
+ ))}
+
+ )
+}
+
+export function LogsView({ scope }: { scope: ObservabilityScope }) {
+ const client = useK8sClient()
+ const root = logsRoot(scope)
+ const [range, setRange] = useState("1h")
+ const [draft, setDraft] = useState("")
+ const [filter, setFilter] = useState("")
+ const [pod, setPod] = useState("")
+ const [container, setContainer] = useState("")
+ const [follow, setFollow] = useState(false)
+ const query = buildLogsQuery({ filter, pod, container })
+
+ const pickerQuery = (field: string, narrowTo?: string) => ({
+ queryKey: ["observability", "logs-fields", root, field, range, narrowTo ?? ""],
+ queryFn: ({ signal }: { signal: AbortSignal }) =>
+ fieldValues(client, root, {
+ field,
+ stream: true,
+ query: buildLogsQuery({ filter: "", pod: narrowTo }),
+ ...windowFor(range),
+ }, signal),
+ retry: false,
+ })
+ const pods = useQuery(pickerQuery(POD_FIELD))
+ const containers = useQuery(pickerQuery(CONTAINER_FIELD, pod || undefined))
+
+ const history = useQuery({
+ queryKey: ["observability", "logs", root, query, range],
+ queryFn: ({ signal }) => queryLogs(client, root, { query, limit: HISTORY_LIMIT, ...windowFor(range) }, signal),
+ enabled: !follow,
+ retry: false,
+ })
+ const tail = useLogTail(root, query, follow, { cap: FOLLOW_CAP })
+
+ const wide = [pods.error, history.error, tail.error].find(isScopeWide)
+ if (wide) {
+ return (
+
+ )
+ }
+
+ const error = follow ? tail.error : history.error
+ const entries = follow ? tail.entries : (history.data ?? [])
+
+ return (
+
+
+
+
{ setPod(v); setContainer("") }} />
+
+ {!follow && }
+ setFollow(!follow)}>
+ Follow
+
+
+ {follow && (
+
+ {tail.state === "live" ? "Live" : tail.state === "reconnecting" ? "Reconnecting…" : "Connecting…"}
+ {` · newest ${FOLLOW_CAP} lines kept`}
+
+ )}
+ {error ?
: null}
+ {!follow && history.isLoading ?
:
}
+
+ )
+}
diff --git a/packages/system/dashboard/images/console/apps/console/src/lib/observability/logs.test.ts b/packages/system/dashboard/images/console/apps/console/src/lib/observability/logs.test.ts
new file mode 100644
index 000000000..25d26a23a
--- /dev/null
+++ b/packages/system/dashboard/images/console/apps/console/src/lib/observability/logs.test.ts
@@ -0,0 +1,65 @@
+import { describe, it, expect } from "vitest"
+import { buildLogsQuery, compareTime, mergeTail } from "./logs.ts"
+
+describe("buildLogsQuery", () => {
+ it("passes the filter through when nothing is picked", () => {
+ expect(buildLogsQuery({ filter: "error or warn" })).toBe("error or warn")
+ expect(buildLogsQuery({ filter: " " })).toBe("*")
+ })
+
+ it("ANDs the picked pod and container as a stream filter around the whole filter", () => {
+ expect(buildLogsQuery({ filter: "error or warn", pod: "db-0", container: "postgres" })).toBe(
+ '{kubernetes_pod_name="db-0",kubernetes_container_name="postgres"} (error or warn)',
+ )
+ })
+
+ it("keeps the user's pipes after the scoped filter", () => {
+ expect(buildLogsQuery({ filter: 'a or "x|y" | fields _msg', pod: "db-0" })).toBe(
+ '{kubernetes_pod_name="db-0"} (a or "x|y") | fields _msg',
+ )
+ })
+
+ it("escapes quotes in picked values", () => {
+ expect(buildLogsQuery({ filter: "", pod: 'a"b' })).toBe('{kubernetes_pod_name="a\\"b"} (*)')
+ })
+})
+
+describe("compareTime", () => {
+ it("orders RFC3339 times with differing fraction lengths", () => {
+ expect(compareTime("2026-11-04T10:00:01Z", "2026-11-04T10:00:01.1Z")).toBeLessThan(0)
+ expect(compareTime("2026-11-04T10:00:01.5Z", "2026-11-04T10:00:01.123Z")).toBeGreaterThan(0)
+ expect(compareTime("2026-11-04T10:00:01.10Z", "2026-11-04T10:00:01.1Z")).toBe(0)
+ })
+})
+
+const e = (time: string, msg: string, stream = "s1") => ({ _time: time, _msg: msg, _stream_id: stream })
+
+describe("mergeTail", () => {
+ it("appends and keeps only the newest lines over the cap", () => {
+ const out = mergeTail([e("t1", "a"), e("t2", "b")], [e("t3", "c")], 2)
+
+ expect(out.map((x) => x._msg)).toEqual(["b", "c"])
+ })
+
+ it("drops replayed lines at or before the resume point", () => {
+ const buffer = [e("2026-01-01T00:00:01Z", "a"), e("2026-01-01T00:00:02Z", "b")]
+
+ const out = mergeTail(buffer, [e("2026-01-01T00:00:02Z", "b"), e("2026-01-01T00:00:03Z", "c")], 10, "2026-01-01T00:00:02Z")
+
+ expect(out.map((x) => x._msg)).toEqual(["a", "b", "c"])
+ })
+
+ it("keeps a line at the resume point from another stream", () => {
+ const buffer = [e("2026-01-01T00:00:02Z", "b", "s1")]
+
+ const out = mergeTail(buffer, [e("2026-01-01T00:00:02Z", "other", "s2")], 10, "2026-01-01T00:00:02Z")
+
+ expect(out).toHaveLength(2)
+ })
+
+ it("does not deduplicate outside a resume", () => {
+ const out = mergeTail([e("t1", "a")], [e("t1", "a")], 10)
+
+ expect(out).toHaveLength(2)
+ })
+})
diff --git a/packages/system/dashboard/images/console/apps/console/src/lib/observability/logs.ts b/packages/system/dashboard/images/console/apps/console/src/lib/observability/logs.ts
new file mode 100644
index 000000000..a6255e541
--- /dev/null
+++ b/packages/system/dashboard/images/console/apps/console/src/lib/observability/logs.ts
@@ -0,0 +1,73 @@
+import type { LogEntry } from "./proxy.ts"
+
+export const LOG_RANGES = {
+ "15m": 15 * 60,
+ "1h": 3600,
+ "6h": 6 * 3600,
+ "24h": 24 * 3600,
+} as const
+
+export type LogRangeKey = keyof typeof LOG_RANGES
+
+export const POD_FIELD = "kubernetes_pod_name"
+export const CONTAINER_FIELD = "kubernetes_container_name"
+
+function quote(value: string): string {
+ return `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`
+}
+
+function splitAtFirstPipe(query: string): [string, string] {
+ let quoteChar = ""
+ for (let i = 0; i < query.length; i++) {
+ const c = query[i]
+ if (quoteChar) {
+ if (c === "\\") i++
+ else if (c === quoteChar) quoteChar = ""
+ } else if (c === '"' || c === "'" || c === "`") {
+ quoteChar = c
+ } else if (c === "|") {
+ return [query.slice(0, i), query.slice(i + 1)]
+ }
+ }
+ return [query, ""]
+}
+
+// The picker narrows the filter part only: AND binds tighter than OR in
+// LogsQL, and the user's pipes must still run after the narrowed filter.
+export function buildLogsQuery({ filter, pod, container }: { filter: string; pod?: string; container?: string }): string {
+ const trimmed = filter.trim() || "*"
+ const matchers = [
+ pod ? `${POD_FIELD}=${quote(pod)}` : "",
+ container ? `${CONTAINER_FIELD}=${quote(container)}` : "",
+ ].filter(Boolean)
+ if (matchers.length === 0) return trimmed
+ const [head, pipes] = splitAtFirstPipe(trimmed)
+ const scoped = `{${matchers.join(",")}} (${head.trim() || "*"})`
+ return pipes.trim() ? `${scoped} | ${pipes.trim()}` : scoped
+}
+
+// VictoriaLogs trims trailing zeros from the fraction, so the strings do not sort lexically.
+function padFraction(time: string): string {
+ const m = /^([^.Z]+)(?:\.(\d+))?Z$/.exec(time)
+ return m ? `${m[1]}.${(m[2] ?? "").padEnd(9, "0")}Z` : time
+}
+
+export function compareTime(a: string, b: string): number {
+ const x = padFraction(a)
+ const y = padFraction(b)
+ return x < y ? -1 : x > y ? 1 : 0
+}
+
+const entryKey = (e: LogEntry) => `${e._stream_id ?? ""}\u0000${e._time}`
+
+// (_stream_id, _time) is not unique in VictoriaLogs, so dedup applies only to
+// lines a resumed tail replays at or before the resume point.
+export function mergeTail(buffer: LogEntry[], incoming: LogEntry[], cap: number, resumedFrom?: string): LogEntry[] {
+ let fresh = incoming
+ if (resumedFrom) {
+ const seen = new Set(buffer.map(entryKey))
+ fresh = incoming.filter((e) => compareTime(e._time, resumedFrom) > 0 || !seen.has(entryKey(e)))
+ }
+ const merged = buffer.concat(fresh)
+ return merged.length > cap ? merged.slice(merged.length - cap) : merged
+}
diff --git a/packages/system/dashboard/images/console/apps/console/src/lib/observability/proxy.ts b/packages/system/dashboard/images/console/apps/console/src/lib/observability/proxy.ts
index 40b451b0b..345d49815 100644
--- a/packages/system/dashboard/images/console/apps/console/src/lib/observability/proxy.ts
+++ b/packages/system/dashboard/images/console/apps/console/src/lib/observability/proxy.ts
@@ -1,4 +1,5 @@
import type { K8sClient } from "@cozystack/k8s-client"
+import { compareTime } from "./logs.ts"
export type ObservabilityScope =
| { namespace: string }
@@ -160,7 +161,7 @@ export async function queryLogs(
): Promise {
const res = await proxyGet(client, `${root}select/logsql/query`, { ...params }, signal)
const entries = (await res.text()).split("\n").map(parseLine).filter((e) => e !== null)
- return entries.sort((a, b) => (a._time < b._time ? -1 : a._time > b._time ? 1 : 0))
+ return entries.sort((a, b) => compareTime(a._time, b._time))
}
export interface FieldValuesParams {
diff --git a/packages/system/dashboard/images/console/apps/console/src/lib/observability/use-log-tail.test.tsx b/packages/system/dashboard/images/console/apps/console/src/lib/observability/use-log-tail.test.tsx
new file mode 100644
index 000000000..5c420314a
--- /dev/null
+++ b/packages/system/dashboard/images/console/apps/console/src/lib/observability/use-log-tail.test.tsx
@@ -0,0 +1,65 @@
+import { describe, it, expect, vi } from "vitest"
+import { renderHook, waitFor } from "@testing-library/react"
+import type { ReactNode } from "react"
+import { K8sClient, K8sProvider } from "@cozystack/k8s-client"
+import { useLogTail } from "./use-log-tail.ts"
+
+const line = (time: string, msg: string) => JSON.stringify({ _time: time, _msg: msg, _stream_id: "s" })
+
+function ndjson(...lines: string[]): Response {
+ return new Response(lines.map((l) => `${l}\n`).join(""))
+}
+
+function setup(...responses: Response[]) {
+ const client = new K8sClient()
+ const raw = vi.spyOn(client, "raw")
+ for (const r of responses) raw.mockResolvedValueOnce(r)
+ raw.mockImplementation(() => new Promise(() => {}))
+ const wrapper = ({ children }: { children: ReactNode }) => {children}
+ return { raw, wrapper }
+}
+
+const T1 = "2026-11-04T10:00:01Z"
+const T2 = "2026-11-04T10:00:02Z"
+const T3 = "2026-11-04T10:00:03Z"
+
+describe("useLogTail", () => {
+ it("streams lines and resumes after a disconnect from the last _time without duplicates", async () => {
+ const { raw, wrapper } = setup(ndjson(line(T1, "a"), line(T2, "b")), ndjson(line(T2, "b"), line(T3, "c")))
+
+ const { result } = renderHook(() => useLogTail("/root/", "*", true, { cap: 100, retryDelayMs: 1 }), { wrapper })
+
+ await waitFor(() => expect(result.current.entries.map((e) => e._msg)).toEqual(["a", "b", "c"]))
+ expect(new URL(raw.mock.calls[0][0], "http://x").searchParams.has("since")).toBe(false)
+ expect(new URL(raw.mock.calls[1][0], "http://x").searchParams.get("since")).toBe(T2)
+ })
+
+ it("stops and reports an error the proxy will repeat on every retry", async () => {
+ const { raw, wrapper } = setup(new Response("", { status: 403 }))
+
+ const { result } = renderHook(() => useLogTail("/root/", "*", true, { cap: 100, retryDelayMs: 1 }), { wrapper })
+
+ await waitFor(() => expect(result.current.state).toBe("stopped"))
+ expect(result.current.error).toMatchObject({ kind: "forbidden" })
+ expect(raw).toHaveBeenCalledTimes(1)
+ })
+
+ it("does not connect while disabled", () => {
+ const { raw, wrapper } = setup()
+
+ renderHook(() => useLogTail("/root/", "*", false), { wrapper })
+
+ expect(raw).not.toHaveBeenCalled()
+ })
+
+ it("aborts the stream on unmount", async () => {
+ const { raw, wrapper } = setup()
+ const { unmount } = renderHook(() => useLogTail("/root/", "*", true), { wrapper })
+ await waitFor(() => expect(raw).toHaveBeenCalled())
+
+ unmount()
+
+ const init = raw.mock.calls[0][1] as RequestInit
+ expect(init.signal?.aborted).toBe(true)
+ })
+})
diff --git a/packages/system/dashboard/images/console/apps/console/src/lib/observability/use-log-tail.ts b/packages/system/dashboard/images/console/apps/console/src/lib/observability/use-log-tail.ts
new file mode 100644
index 000000000..cb9222f48
--- /dev/null
+++ b/packages/system/dashboard/images/console/apps/console/src/lib/observability/use-log-tail.ts
@@ -0,0 +1,95 @@
+import { useEffect, useState } from "react"
+import { useK8sClient } from "@cozystack/k8s-client"
+import { mergeTail } from "./logs.ts"
+import { ProxyError, tailLogs, type LogEntry } from "./proxy.ts"
+
+export type TailState = "connecting" | "live" | "reconnecting" | "stopped"
+
+interface TailSnapshot {
+ key: string
+ entries: LogEntry[]
+ state: TailState
+ error: unknown
+}
+
+const FLUSH_MS = 100
+const MAX_RETRY_MS = 30_000
+const FATAL: ReadonlySet = new Set(["bad-request", "unauthorized", "forbidden", "not-available", "limit"])
+
+const sleep = (ms: number, signal: AbortSignal) =>
+ new Promise((resolve) => {
+ const t = setTimeout(resolve, ms)
+ signal.addEventListener("abort", () => {
+ clearTimeout(t)
+ resolve()
+ })
+ })
+
+export function useLogTail(
+ root: string,
+ query: string,
+ enabled: boolean,
+ { cap = 1000, retryDelayMs = 2000 }: { cap?: number; retryDelayMs?: number } = {},
+): Omit {
+ const client = useK8sClient()
+ const key = `${root}\n${query}\n${enabled}`
+ const [snap, setSnap] = useState({ key, entries: [], state: "connecting", error: null })
+
+ useEffect(() => {
+ if (!enabled) return
+ const controller = new AbortController()
+ const { signal } = controller
+ let pending: LogEntry[] = []
+ let timer: ReturnType | undefined
+ let resumedFrom: string | undefined
+ let lastTime: string | undefined
+
+ const update = (patch: Partial, batch: LogEntry[] = [], from = resumedFrom) =>
+ setSnap((prev) => {
+ const base = prev.key === key ? prev : { key, entries: [], state: "connecting" as const, error: null }
+ return { ...base, ...patch, entries: batch.length ? mergeTail(base.entries, batch, cap, from) : base.entries }
+ })
+ const flush = () => {
+ clearTimeout(timer)
+ timer = undefined
+ if (pending.length === 0 || signal.aborted) return
+ const batch = pending
+ pending = []
+ update({ state: "live", error: null }, batch)
+ }
+
+ const run = async () => {
+ for (let attempt = 0; !signal.aborted; attempt++) {
+ resumedFrom = lastTime
+ try {
+ await tailLogs(client, root, { query, since: lastTime }, (entry) => {
+ attempt = 0
+ lastTime = entry._time
+ pending.push(entry)
+ timer ??= setTimeout(flush, FLUSH_MS)
+ }, signal)
+ flush()
+ } catch (err) {
+ flush()
+ if (signal.aborted) return
+ if (err instanceof ProxyError && FATAL.has(err.kind)) {
+ update({ state: "stopped", error: err })
+ return
+ }
+ update({ error: err })
+ }
+ if (signal.aborted) return
+ update({ state: "reconnecting" })
+ await sleep(Math.min(retryDelayMs * 2 ** attempt, MAX_RETRY_MS), signal)
+ }
+ }
+ void run()
+ return () => {
+ controller.abort()
+ clearTimeout(timer)
+ }
+ }, [client, root, query, enabled, key, cap, retryDelayMs])
+
+ const current = snap.key === key ? snap : { key, entries: [], state: "connecting" as const, error: null }
+ return { entries: current.entries, state: current.state, error: current.error }
+}
From f9ed2afad749646bb5c1de0a56b4e8d17e773bc1 Mon Sep 17 00:00:00 2001
From: ZverGuy
Date: Wed, 4 Nov 2026 05:34:01 +0700
Subject: [PATCH 04/46] feat(dashboard): show logs on application pages and per
tenant
A Logs tab on application detail pages reads the application root of
the observability proxy, and a Logs page under a new Observability
sidebar group reads the tenant namespace root, so lines from before
the application identity labels existed stay reachable there.
Assisted-by: LLM
Signed-off-by: ZverGuy
---
.../apps/console/src/routes/ConsolePage.tsx | 2 ++
.../apps/console/src/routes/LogsPage.test.tsx | 20 +++++++++++++++++++
.../apps/console/src/routes/LogsPage.tsx | 15 ++++++++++++++
.../detail/ApplicationDetailPage.test.tsx | 9 ++++++---
.../routes/detail/ApplicationDetailPage.tsx | 4 ++++
.../console/src/routes/detail/LogsTab.tsx | 15 ++++++++++++++
.../src/routes/sidebar-sections.test.tsx | 10 ++++++++++
.../console/src/routes/sidebar-sections.tsx | 8 +++++++-
8 files changed, 79 insertions(+), 4 deletions(-)
create mode 100644 packages/system/dashboard/images/console/apps/console/src/routes/LogsPage.test.tsx
create mode 100644 packages/system/dashboard/images/console/apps/console/src/routes/LogsPage.tsx
create mode 100644 packages/system/dashboard/images/console/apps/console/src/routes/detail/LogsTab.tsx
diff --git a/packages/system/dashboard/images/console/apps/console/src/routes/ConsolePage.tsx b/packages/system/dashboard/images/console/apps/console/src/routes/ConsolePage.tsx
index 37caae92f..5e204e84f 100644
--- a/packages/system/dashboard/images/console/apps/console/src/routes/ConsolePage.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/routes/ConsolePage.tsx
@@ -15,6 +15,7 @@ import { MigrationSourceEditPage } from "./MigrationSourceEditPage.tsx"
import { MigrationTaskCreatePage } from "./MigrationTaskCreatePage.tsx"
import { MigrationTaskDetailPage } from "./MigrationTaskDetailPage.tsx"
import { ApplicationOrderPage } from "./ApplicationOrderPage.tsx"
+import { LogsPage } from "./LogsPage.tsx"
export function ConsolePage() {
return (
@@ -96,6 +97,7 @@ export function ConsolePage() {
path="migration/vmimporttasks/:name"
element={ }
/>
+ } />
} />
} />
} />
diff --git a/packages/system/dashboard/images/console/apps/console/src/routes/LogsPage.test.tsx b/packages/system/dashboard/images/console/apps/console/src/routes/LogsPage.test.tsx
new file mode 100644
index 000000000..1f4263cf1
--- /dev/null
+++ b/packages/system/dashboard/images/console/apps/console/src/routes/LogsPage.test.tsx
@@ -0,0 +1,20 @@
+import { describe, it, expect, vi } from "vitest"
+import { render, screen } from "@testing-library/react"
+
+vi.mock("../lib/tenant-context.tsx", () => ({
+ useTenantContext: () => ({ tenantNamespace: "tenant-a" }),
+}))
+vi.mock("../components/observability/LogsView.tsx", () => ({
+ LogsView: ({ scope }: { scope: object }) => {JSON.stringify(scope)} ,
+}))
+
+const { LogsPage } = await import("./LogsPage.tsx")
+
+describe("LogsPage", () => {
+ it("reads logs from the selected tenant's namespace root", () => {
+ render( )
+
+ expect(screen.getByRole("heading", { name: "Logs" })).toBeInTheDocument()
+ expect(JSON.parse(screen.getByTestId("scope").textContent ?? "")).toEqual({ namespace: "tenant-a" })
+ })
+})
diff --git a/packages/system/dashboard/images/console/apps/console/src/routes/LogsPage.tsx b/packages/system/dashboard/images/console/apps/console/src/routes/LogsPage.tsx
new file mode 100644
index 000000000..7612dfbb2
--- /dev/null
+++ b/packages/system/dashboard/images/console/apps/console/src/routes/LogsPage.tsx
@@ -0,0 +1,15 @@
+import { useTenantContext } from "../lib/tenant-context.tsx"
+import { LogsView } from "../components/observability/LogsView.tsx"
+
+export function LogsPage() {
+ const { tenantNamespace } = useTenantContext()
+ return (
+
+
+
Logs
+
Every application in {tenantNamespace ?? "this tenant"}
+
+ {tenantNamespace &&
}
+
+ )
+}
diff --git a/packages/system/dashboard/images/console/apps/console/src/routes/detail/ApplicationDetailPage.test.tsx b/packages/system/dashboard/images/console/apps/console/src/routes/detail/ApplicationDetailPage.test.tsx
index 40b923f62..a0c3a6b84 100644
--- a/packages/system/dashboard/images/console/apps/console/src/routes/detail/ApplicationDetailPage.test.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/routes/detail/ApplicationDetailPage.test.tsx
@@ -60,6 +60,7 @@ vi.mock("./VncTab.tsx", () => ({ VncTab: () => null }))
vi.mock("./SerialTab.tsx", () => ({ SerialTab: () => null }))
vi.mock("./VMPowerControls.tsx", () => ({ VMPowerControls: () => null }))
vi.mock("./MetricsTab.tsx", () => ({ MetricsTab: () => null }))
+vi.mock("./LogsTab.tsx", () => ({ LogsTab: () => null }))
const { ApplicationDetailPage } = await import("./ApplicationDetailPage.tsx")
@@ -113,6 +114,7 @@ describe("ApplicationDetailPage tabs for a virtual machine", () => {
"Workloads",
"Services",
"Metrics",
+ "Logs",
"Events",
])
})
@@ -133,14 +135,15 @@ describe("ApplicationDetailPage observability tabs", () => {
renderPage()
}
- it("offers Metrics on any application kind, ahead of Events", () => {
+ it("offers Metrics and Logs on any application kind, ahead of Events", () => {
showKind("Postgres", "postgreses")
- expect(h.tabLabels.slice(-3)).toEqual(["Secrets", "Metrics", "Events"])
+ expect(h.tabLabels.slice(-4)).toEqual(["Secrets", "Metrics", "Logs", "Events"])
})
- it("leaves Metrics off a VM disk, which runs no containers", () => {
+ it("leaves Metrics and Logs off a VM disk, which runs no containers", () => {
showKind("VMDisk", "vmdisks")
expect(h.tabLabels).not.toContain("Metrics")
+ expect(h.tabLabels).not.toContain("Logs")
})
})
diff --git a/packages/system/dashboard/images/console/apps/console/src/routes/detail/ApplicationDetailPage.tsx b/packages/system/dashboard/images/console/apps/console/src/routes/detail/ApplicationDetailPage.tsx
index 4520244d5..ca499aac1 100644
--- a/packages/system/dashboard/images/console/apps/console/src/routes/detail/ApplicationDetailPage.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/routes/detail/ApplicationDetailPage.tsx
@@ -44,6 +44,7 @@ import { useResourceBasePath } from "../../lib/portal.ts"
import { useResourcePresence } from "./use-resource-presence.ts"
import { useApplicationConfigMaps } from "./use-app-configmaps.ts"
import { ConfigMapsTab } from "./ConfigMapsTab.tsx"
+import { LogsTab } from "./LogsTab.tsx"
export function ApplicationDetailPage() {
const { plural, name } = useParams<{ plural: string; name: string }>()
@@ -146,6 +147,7 @@ export function ApplicationDetailPage() {
{ to: `${base}/workloads`, label: "Workloads", end: false },
{ to: `${base}/services`, label: "Services", end: false },
{ to: `${base}/metrics`, label: "Metrics", end: false },
+ { to: `${base}/logs`, label: "Logs", end: false },
{ to: `${base}/events`, label: "Events", end: false },
)
} else {
@@ -167,6 +169,7 @@ export function ApplicationDetailPage() {
tabs.push(
{ to: `${base}/secrets`, label: "Secrets", end: false },
{ to: `${base}/metrics`, label: "Metrics", end: false },
+ { to: `${base}/logs`, label: "Logs", end: false },
{ to: `${base}/events`, label: "Events", end: false },
)
}
@@ -274,6 +277,7 @@ export function ApplicationDetailPage() {
}
/>
+ } />
diff --git a/packages/system/dashboard/images/console/apps/console/src/routes/detail/LogsTab.tsx b/packages/system/dashboard/images/console/apps/console/src/routes/detail/LogsTab.tsx
new file mode 100644
index 000000000..4ac5f878d
--- /dev/null
+++ b/packages/system/dashboard/images/console/apps/console/src/routes/detail/LogsTab.tsx
@@ -0,0 +1,15 @@
+import type { ApplicationDefinition, ApplicationInstance } from "@cozystack/types"
+import { useTenantContext } from "../../lib/tenant-context.tsx"
+import { LogsView } from "../../components/observability/LogsView.tsx"
+
+interface LogsTabProps {
+ ad: ApplicationDefinition
+ instance: ApplicationInstance
+}
+
+export function LogsTab({ ad, instance }: LogsTabProps) {
+ const { tenantNamespace } = useTenantContext()
+ const plural = ad.spec?.application.plural
+ if (!tenantNamespace || !plural) return null
+ return
+}
diff --git a/packages/system/dashboard/images/console/apps/console/src/routes/sidebar-sections.test.tsx b/packages/system/dashboard/images/console/apps/console/src/routes/sidebar-sections.test.tsx
index efb69dc7b..da40081bc 100644
--- a/packages/system/dashboard/images/console/apps/console/src/routes/sidebar-sections.test.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/routes/sidebar-sections.test.tsx
@@ -110,6 +110,16 @@ describe("useConsoleSidebarSections — admin areas moved out", () => {
expect(findItem(result.current, "Imports")?.to).toBe("/console/migration/vmimporttasks")
expect(result.current.some((s) => s.title === "Migration")).toBe(true)
})
+
+ it("offers the tenant's namespace logs in an Observability group", async () => {
+ const client = makeClient({ nodes: true, backupclasses: true })
+ const { result } = renderHook(() => useConsoleSidebarSections(), {
+ wrapper: makeWrapper(client),
+ })
+ await waitFor(() => expect(result.current.length).toBeGreaterThan(0))
+ expect(findItem(result.current, "Logs")?.to).toBe("/console/logs")
+ expect(result.current.find((s) => s.title === "Observability")?.items).toHaveLength(1)
+ })
})
function appDef(name: string, kind: string, category: string, module = false) {
diff --git a/packages/system/dashboard/images/console/apps/console/src/routes/sidebar-sections.tsx b/packages/system/dashboard/images/console/apps/console/src/routes/sidebar-sections.tsx
index d5d100813..4cec3a94c 100644
--- a/packages/system/dashboard/images/console/apps/console/src/routes/sidebar-sections.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/routes/sidebar-sections.tsx
@@ -11,6 +11,7 @@ import {
Layers,
Network,
Package,
+ ScrollText,
Plug,
Server,
ToyBrick,
@@ -118,7 +119,12 @@ export function useConsoleSidebarSections(): SidebarSection[] {
],
}
- return [...categorySections, backupsSection, migrationSection]
+ const observabilitySection: SidebarSection = {
+ title: "Observability",
+ items: [{ label: "Logs", to: "/console/logs", icon: ScrollText }],
+ }
+
+ return [...categorySections, backupsSection, migrationSection, observabilitySection]
}, [grouped])
}
From c5b57bffd173ea5e4bb371edb75a13a60f549d96 Mon Sep 17 00:00:00 2001
From: ZverGuy
Date: Wed, 4 Nov 2026 05:39:27 +0700
Subject: [PATCH 05/46] fix(dashboard): open log history at the newest line
A historical query lists lines oldest first, so the viewer opened at
the top of a 500-line window while the line a user looks for is
usually the latest. The chart's value axis also clipped wide labels
such as "476.8 MiB".
Assisted-by: LLM
Signed-off-by: ZverGuy
---
.../console/src/components/observability/LogsView.tsx | 8 ++++----
.../src/components/observability/TimeSeriesChart.tsx | 2 +-
2 files changed, 5 insertions(+), 5 deletions(-)
diff --git a/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.tsx b/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.tsx
index 03235cda3..707b037b9 100644
--- a/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.tsx
@@ -50,11 +50,11 @@ function Picker({ label, value, options, onChange }: { label: string; value: str
)
}
-function LogLines({ entries, follow }: { entries: LogEntry[]; follow: boolean }) {
+function LogLines({ entries }: { entries: LogEntry[] }) {
const ref = useRef(null)
useEffect(() => {
- if (follow && ref.current) ref.current.scrollTop = ref.current.scrollHeight
- }, [entries, follow])
+ if (ref.current) ref.current.scrollTop = ref.current.scrollHeight
+ }, [entries])
if (entries.length === 0) return No log lines for this range and filter.
return (
@@ -146,7 +146,7 @@ export function LogsView({ scope }: { scope: ObservabilityScope }) {
)}
{error ? : null}
- {!follow && history.isLoading ? : }
+ {!follow && history.isLoading ? : }
)
}
diff --git a/packages/system/dashboard/images/console/apps/console/src/components/observability/TimeSeriesChart.tsx b/packages/system/dashboard/images/console/apps/console/src/components/observability/TimeSeriesChart.tsx
index 6b596e17f..683df2dff 100644
--- a/packages/system/dashboard/images/console/apps/console/src/components/observability/TimeSeriesChart.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/components/observability/TimeSeriesChart.tsx
@@ -33,7 +33,7 @@ export function TimeSeriesChart({ data, format }: TimeSeriesChartProps) {
value: (_: uPlot, v: number | null) => fmt(v),
})),
],
- axes: [{}, { size: 70, values: (_: uPlot, splits: number[]) => splits.map(format) }],
+ axes: [{}, { size: 84, values: (_: uPlot, splits: number[]) => splits.map(format) }],
},
[data.timestamps, ...data.series.map((s) => s.values)],
el,
From 97dcf4c4f02d78dc2dcd4ec862cdaa77631de4f3 Mon Sep 17 00:00:00 2001
From: ZverGuy
Date: Wed, 4 Nov 2026 05:45:42 +0700
Subject: [PATCH 06/46] fix(dashboard): treat an apiserver answer on a proxy
path as no proxy
Until the console nginx routes the proxy roots, those paths reach
kube-apiserver, which RBAC-denies the namespace root with 403 for a
tenant, so the Logs page told every tenant they lacked permission. The
proxy itself answers in plain text, so a Kubernetes Status body is a
reliable sign that the path did not reach it.
Assisted-by: LLM
Signed-off-by: ZverGuy
---
.../components/observability/LogsView.test.tsx | 10 ++++++++++
.../console/src/lib/observability/proxy.test.ts | 17 +++++++++++++++++
.../apps/console/src/lib/observability/proxy.ts | 14 +++++++++++++-
3 files changed, 40 insertions(+), 1 deletion(-)
diff --git a/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.test.tsx b/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.test.tsx
index 693adf70a..fae3f6a4b 100644
--- a/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.test.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.test.tsx
@@ -90,6 +90,16 @@ describe("LogsView", () => {
expect(screen.queryByLabelText("LogsQL filter")).toBeNull()
})
+ it("renders the tenant logs page as not available when kube-apiserver answers instead of the proxy", async () => {
+ const { client } = clientWith(() =>
+ Response.json({ kind: "Status", apiVersion: "v1", status: "Failure", reason: "Forbidden", code: 403 }, { status: 403 }),
+ )
+
+ renderWithK8sProvider( , { client })
+
+ expect(await screen.findByText("Logs are not available on this cluster.")).toBeInTheDocument()
+ })
+
it("keeps the controls and explains a rejected query", async () => {
const { client } = clientWith((endpoint, params) =>
endpoint.endsWith("query") ? new Response("cannot parse query", { status: 400 }) : defaultHandler(endpoint, params),
diff --git a/packages/system/dashboard/images/console/apps/console/src/lib/observability/proxy.test.ts b/packages/system/dashboard/images/console/apps/console/src/lib/observability/proxy.test.ts
index f8cf44656..69a8c7c8c 100644
--- a/packages/system/dashboard/images/console/apps/console/src/lib/observability/proxy.test.ts
+++ b/packages/system/dashboard/images/console/apps/console/src/lib/observability/proxy.test.ts
@@ -79,6 +79,23 @@ describe("queryRange", () => {
expect(err).toMatchObject({ kind: "limit", status: 422, message: "range too long" })
})
+ it("treats a Kubernetes Status 403 as a cluster without the proxy route", async () => {
+ const status = { kind: "Status", apiVersion: "v1", status: "Failure", reason: "Forbidden", code: 403, message: "logs.cozystack.io \"select\" is forbidden" }
+ const { client } = clientReturning(Response.json(status, { status: 403 }))
+
+ const err = await queryRange(client, metricsRoot(ns), { query: "up", start: 0, end: 1, step: 1 }).catch((e) => e)
+
+ expect(err).toMatchObject({ kind: "not-available", status: 403 })
+ })
+
+ it("keeps the proxy's own plain-text 403 as forbidden", async () => {
+ const { client } = clientReturning(new Response("forbidden\n", { status: 403 }))
+
+ const err = await queryRange(client, metricsRoot(ns), { query: "up", start: 0, end: 1, step: 1 }).catch((e) => e)
+
+ expect(err).toMatchObject({ kind: "forbidden" })
+ })
+
it("reports a fetch failure as a network error", async () => {
const client = new K8sClient()
vi.spyOn(client, "raw").mockRejectedValue(new TypeError("offline"))
diff --git a/packages/system/dashboard/images/console/apps/console/src/lib/observability/proxy.ts b/packages/system/dashboard/images/console/apps/console/src/lib/observability/proxy.ts
index 345d49815..c9fce3d4f 100644
--- a/packages/system/dashboard/images/console/apps/console/src/lib/observability/proxy.ts
+++ b/packages/system/dashboard/images/console/apps/console/src/lib/observability/proxy.ts
@@ -69,6 +69,17 @@ export function isScopeWide(error: unknown): boolean {
)
}
+// The proxy answers in plain text; a Kubernetes Status body means nginx sent
+// the path to kube-apiserver, which RBAC-denies or 404s a route it does not serve.
+function isKubernetesStatus(text: string): boolean {
+ try {
+ const parsed: unknown = JSON.parse(text)
+ return !!parsed && typeof parsed === "object" && "kind" in parsed && parsed.kind === "Status"
+ } catch {
+ return false
+ }
+}
+
// Prometheus answers {"error": "..."}, VictoriaLogs and nginx answer plain text.
function errorMessage(text: string, status: number): string {
try {
@@ -100,7 +111,8 @@ async function proxyGet(
}
if (!res.ok) {
const text = await res.text().catch(() => "")
- throw new ProxyError(errorKindForStatus(res.status), res.status, errorMessage(text, res.status))
+ const kind = isKubernetesStatus(text) ? "not-available" : errorKindForStatus(res.status)
+ throw new ProxyError(kind, res.status, errorMessage(text, res.status))
}
return res
}
From 4b44971d125cce2c2fd06457c68f23cf1645ac87 Mon Sep 17 00:00:00 2001
From: ZverGuy
Date: Wed, 4 Nov 2026 05:47:13 +0700
Subject: [PATCH 07/46] fix(dashboard): start each log follow run with its own
buffer
Turning Follow off and on again reused the previous run's buffer, so
new lines were appended after a silent gap and, on a quick toggle,
duplicated. A follow run is now identified by a session value, so the
buffer starts empty each time.
A resume now uses the newest _time seen rather than the last line
received, so an out-of-order line cannot move since backwards, and
the backoff sleep no longer leaves an abort listener per retry.
Assisted-by: LLM
Signed-off-by: ZverGuy
---
.../lib/observability/use-log-tail.test.tsx | 31 ++++++++++++++++---
.../src/lib/observability/use-log-tail.ts | 23 ++++++++------
2 files changed, 41 insertions(+), 13 deletions(-)
diff --git a/packages/system/dashboard/images/console/apps/console/src/lib/observability/use-log-tail.test.tsx b/packages/system/dashboard/images/console/apps/console/src/lib/observability/use-log-tail.test.tsx
index 5c420314a..46df47970 100644
--- a/packages/system/dashboard/images/console/apps/console/src/lib/observability/use-log-tail.test.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/lib/observability/use-log-tail.test.tsx
@@ -27,7 +27,7 @@ describe("useLogTail", () => {
it("streams lines and resumes after a disconnect from the last _time without duplicates", async () => {
const { raw, wrapper } = setup(ndjson(line(T1, "a"), line(T2, "b")), ndjson(line(T2, "b"), line(T3, "c")))
- const { result } = renderHook(() => useLogTail("/root/", "*", true, { cap: 100, retryDelayMs: 1 }), { wrapper })
+ const { result } = renderHook(() => useLogTail("/root/", "*", 1, { cap: 100, retryDelayMs: 1 }), { wrapper })
await waitFor(() => expect(result.current.entries.map((e) => e._msg)).toEqual(["a", "b", "c"]))
expect(new URL(raw.mock.calls[0][0], "http://x").searchParams.has("since")).toBe(false)
@@ -37,24 +37,47 @@ describe("useLogTail", () => {
it("stops and reports an error the proxy will repeat on every retry", async () => {
const { raw, wrapper } = setup(new Response("", { status: 403 }))
- const { result } = renderHook(() => useLogTail("/root/", "*", true, { cap: 100, retryDelayMs: 1 }), { wrapper })
+ const { result } = renderHook(() => useLogTail("/root/", "*", 1, { cap: 100, retryDelayMs: 1 }), { wrapper })
await waitFor(() => expect(result.current.state).toBe("stopped"))
expect(result.current.error).toMatchObject({ kind: "forbidden" })
expect(raw).toHaveBeenCalledTimes(1)
})
+ it("starts a new follow session with an empty buffer", async () => {
+ const { wrapper } = setup(ndjson(line(T1, "first")), ndjson(line(T3, "second")))
+ const { result, rerender } = renderHook(
+ ({ session }: { session: number | null }) => useLogTail("/root/", "*", session, { retryDelayMs: 60_000 }),
+ { wrapper, initialProps: { session: 1 as number | null } },
+ )
+ await waitFor(() => expect(result.current.entries.map((e) => e._msg)).toEqual(["first"]))
+
+ rerender({ session: null })
+ rerender({ session: 2 })
+
+ await waitFor(() => expect(result.current.entries.map((e) => e._msg)).toEqual(["second"]))
+ })
+
+ it("resumes from the newest line seen, not the last one received", async () => {
+ const { raw, wrapper } = setup(ndjson(line(T3, "c"), line(T1, "a")), ndjson())
+
+ renderHook(() => useLogTail("/root/", "*", 1, { retryDelayMs: 1 }), { wrapper })
+
+ await waitFor(() => expect(raw.mock.calls.length).toBeGreaterThan(1))
+ expect(new URL(raw.mock.calls[1][0], "http://x").searchParams.get("since")).toBe(T3)
+ })
+
it("does not connect while disabled", () => {
const { raw, wrapper } = setup()
- renderHook(() => useLogTail("/root/", "*", false), { wrapper })
+ renderHook(() => useLogTail("/root/", "*", null), { wrapper })
expect(raw).not.toHaveBeenCalled()
})
it("aborts the stream on unmount", async () => {
const { raw, wrapper } = setup()
- const { unmount } = renderHook(() => useLogTail("/root/", "*", true), { wrapper })
+ const { unmount } = renderHook(() => useLogTail("/root/", "*", 1), { wrapper })
await waitFor(() => expect(raw).toHaveBeenCalled())
unmount()
diff --git a/packages/system/dashboard/images/console/apps/console/src/lib/observability/use-log-tail.ts b/packages/system/dashboard/images/console/apps/console/src/lib/observability/use-log-tail.ts
index cb9222f48..ddc835821 100644
--- a/packages/system/dashboard/images/console/apps/console/src/lib/observability/use-log-tail.ts
+++ b/packages/system/dashboard/images/console/apps/console/src/lib/observability/use-log-tail.ts
@@ -1,6 +1,6 @@
import { useEffect, useState } from "react"
import { useK8sClient } from "@cozystack/k8s-client"
-import { mergeTail } from "./logs.ts"
+import { compareTime, mergeTail } from "./logs.ts"
import { ProxyError, tailLogs, type LogEntry } from "./proxy.ts"
export type TailState = "connecting" | "live" | "reconnecting" | "stopped"
@@ -18,25 +18,30 @@ const FATAL: ReadonlySet = new Set(["bad-request", "unauthorized", "forb
const sleep = (ms: number, signal: AbortSignal) =>
new Promise((resolve) => {
- const t = setTimeout(resolve, ms)
- signal.addEventListener("abort", () => {
+ const onAbort = () => {
clearTimeout(t)
resolve()
- })
+ }
+ const t = setTimeout(() => {
+ signal.removeEventListener("abort", onAbort)
+ resolve()
+ }, ms)
+ signal.addEventListener("abort", onAbort, { once: true })
})
+// Each non-null session is one follow run with its own buffer; null stops following.
export function useLogTail(
root: string,
query: string,
- enabled: boolean,
+ session: number | null,
{ cap = 1000, retryDelayMs = 2000 }: { cap?: number; retryDelayMs?: number } = {},
): Omit {
const client = useK8sClient()
- const key = `${root}\n${query}\n${enabled}`
+ const key = `${root}\n${query}\n${session}`
const [snap, setSnap] = useState({ key, entries: [], state: "connecting", error: null })
useEffect(() => {
- if (!enabled) return
+ if (session === null) return
const controller = new AbortController()
const { signal } = controller
let pending: LogEntry[] = []
@@ -64,7 +69,7 @@ export function useLogTail(
try {
await tailLogs(client, root, { query, since: lastTime }, (entry) => {
attempt = 0
- lastTime = entry._time
+ if (!lastTime || compareTime(entry._time, lastTime) > 0) lastTime = entry._time
pending.push(entry)
timer ??= setTimeout(flush, FLUSH_MS)
}, signal)
@@ -88,7 +93,7 @@ export function useLogTail(
controller.abort()
clearTimeout(timer)
}
- }, [client, root, query, enabled, key, cap, retryDelayMs])
+ }, [client, root, query, session, key, cap, retryDelayMs])
const current = snap.key === key ? snap : { key, entries: [], state: "connecting" as const, error: null }
return { entries: current.entries, state: current.state, error: current.error }
From 290490769eacf8906256290d3078bba02e4e9d04 Mon Sep 17 00:00:00 2001
From: ZverGuy
Date: Wed, 4 Nov 2026 05:47:13 +0700
Subject: [PATCH 08/46] fix(dashboard): let the reader scroll up while logs
stream
The viewer jumped to the newest line on every 100 ms flush, so a line
could not be read on a busy application. It now follows the bottom
only while the reader is already there, and says when a refused tail
has stopped instead of showing it as connecting.
Assisted-by: LLM
Signed-off-by: ZverGuy
---
.../observability/LogLines.test.tsx | 34 +++++++++++++++++++
.../src/components/observability/LogLines.tsx | 34 +++++++++++++++++++
.../observability/LogsView.test.tsx | 12 +++++++
.../src/components/observability/LogsView.tsx | 33 +++++-------------
4 files changed, 88 insertions(+), 25 deletions(-)
create mode 100644 packages/system/dashboard/images/console/apps/console/src/components/observability/LogLines.test.tsx
create mode 100644 packages/system/dashboard/images/console/apps/console/src/components/observability/LogLines.tsx
diff --git a/packages/system/dashboard/images/console/apps/console/src/components/observability/LogLines.test.tsx b/packages/system/dashboard/images/console/apps/console/src/components/observability/LogLines.test.tsx
new file mode 100644
index 000000000..775c5fcc6
--- /dev/null
+++ b/packages/system/dashboard/images/console/apps/console/src/components/observability/LogLines.test.tsx
@@ -0,0 +1,34 @@
+import { describe, it, expect } from "vitest"
+import { fireEvent, render, screen } from "@testing-library/react"
+import { LogLines } from "./LogLines.tsx"
+
+const entry = (n: number) => ({ _time: `2026-11-04T10:00:0${n}Z`, _msg: `line ${n}`, _stream_id: "s" })
+
+function sized(list: HTMLElement, scrollHeight: number) {
+ Object.defineProperty(list, "scrollHeight", { configurable: true, value: scrollHeight })
+ Object.defineProperty(list, "clientHeight", { configurable: true, value: 100 })
+}
+
+describe("LogLines", () => {
+ it("keeps following the newest line while the reader is at the bottom", () => {
+ const { rerender } = render( )
+ const list = screen.getByRole("list")
+ sized(list, 500)
+
+ rerender( )
+
+ expect(list.scrollTop).toBe(500)
+ })
+
+ it("leaves the position alone once the reader scrolls up", () => {
+ const { rerender } = render( )
+ const list = screen.getByRole("list")
+ sized(list, 500)
+ list.scrollTop = 120
+ fireEvent.scroll(list)
+
+ rerender( )
+
+ expect(list.scrollTop).toBe(120)
+ })
+})
diff --git a/packages/system/dashboard/images/console/apps/console/src/components/observability/LogLines.tsx b/packages/system/dashboard/images/console/apps/console/src/components/observability/LogLines.tsx
new file mode 100644
index 000000000..a6f4b5861
--- /dev/null
+++ b/packages/system/dashboard/images/console/apps/console/src/components/observability/LogLines.tsx
@@ -0,0 +1,34 @@
+import { useEffect, useRef } from "react"
+import { CONTAINER_FIELD, POD_FIELD } from "../../lib/observability/logs.ts"
+import type { LogEntry } from "../../lib/observability/proxy.ts"
+
+const BOTTOM_SLACK_PX = 24
+
+export function LogLines({ entries }: { entries: LogEntry[] }) {
+ const ref = useRef(null)
+ const pinned = useRef(true)
+
+ useEffect(() => {
+ if (ref.current && pinned.current) ref.current.scrollTop = ref.current.scrollHeight
+ }, [entries])
+
+ if (entries.length === 0) return No log lines for this range and filter.
+ return (
+ {
+ const el = e.currentTarget
+ pinned.current = el.scrollHeight - el.scrollTop - el.clientHeight <= BOTTOM_SLACK_PX
+ }}
+ className="max-h-[60vh] overflow-auto rounded-md bg-slate-950 p-3 font-mono text-xs leading-5 text-slate-100"
+ >
+ {entries.map((e, i) => (
+
+ {new Date(e._time).toLocaleTimeString()} {" "}
+ {`${e[POD_FIELD] ?? ""}/${e[CONTAINER_FIELD] ?? ""}`} {" "}
+ {e._msg}
+
+ ))}
+
+ )
+}
diff --git a/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.test.tsx b/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.test.tsx
index fae3f6a4b..526efeb23 100644
--- a/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.test.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.test.tsx
@@ -81,6 +81,18 @@ describe("LogsView", () => {
expect(screen.getByRole("button", { name: "Follow" })).toHaveAttribute("aria-pressed", "true")
})
+ it("says the tail stopped when the proxy refuses the query", async () => {
+ const { client } = clientWith((endpoint, params) =>
+ endpoint.endsWith("tail") ? new Response("pipe not allowed in tail", { status: 400 }) : defaultHandler(endpoint, params),
+ )
+ renderWithK8sProvider( , { client })
+
+ await userEvent.click(screen.getByRole("button", { name: "Follow" }))
+
+ expect(await screen.findByText(/Stopped/)).toBeInTheDocument()
+ expect(screen.getByText("pipe not allowed in tail")).toBeInTheDocument()
+ })
+
it("renders a cluster without the proxy as not available", async () => {
const { client } = clientWith(() => new Response("404 page not found", { status: 404 }))
diff --git a/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.tsx b/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.tsx
index 707b037b9..f21f2eb86 100644
--- a/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useRef, useState } from "react"
+import { useState } from "react"
import { useQuery } from "@tanstack/react-query"
import { useK8sClient } from "@cozystack/k8s-client"
import { Button, Spinner } from "@cozystack/ui"
@@ -14,15 +14,16 @@ import {
isScopeWide,
logsRoot,
queryLogs,
- type LogEntry,
type ObservabilityScope,
} from "../../lib/observability/proxy.ts"
import { useLogTail } from "../../lib/observability/use-log-tail.ts"
import { ProxyNotice } from "./ProxyNotice.tsx"
import { RangePicker } from "./RangePicker.tsx"
+import { LogLines } from "./LogLines.tsx"
const HISTORY_LIMIT = 500
const FOLLOW_CAP = 1000
+const TAIL_STATE_LABEL = { connecting: "Connecting…", live: "Live", reconnecting: "Reconnecting…", stopped: "Stopped" }
function windowFor(range: LogRangeKey) {
const end = Date.now()
@@ -50,25 +51,6 @@ function Picker({ label, value, options, onChange }: { label: string; value: str
)
}
-function LogLines({ entries }: { entries: LogEntry[] }) {
- const ref = useRef(null)
- useEffect(() => {
- if (ref.current) ref.current.scrollTop = ref.current.scrollHeight
- }, [entries])
- if (entries.length === 0) return No log lines for this range and filter.
- return (
-
- {entries.map((e, i) => (
-
- {new Date(e._time).toLocaleTimeString()} {" "}
- {`${e[POD_FIELD] ?? ""}/${e[CONTAINER_FIELD] ?? ""}`} {" "}
- {e._msg}
-
- ))}
-
- )
-}
-
export function LogsView({ scope }: { scope: ObservabilityScope }) {
const client = useK8sClient()
const root = logsRoot(scope)
@@ -77,7 +59,8 @@ export function LogsView({ scope }: { scope: ObservabilityScope }) {
const [filter, setFilter] = useState("")
const [pod, setPod] = useState("")
const [container, setContainer] = useState("")
- const [follow, setFollow] = useState(false)
+ const [followRun, setFollowRun] = useState(null)
+ const follow = followRun !== null
const query = buildLogsQuery({ filter, pod, container })
const pickerQuery = (field: string, narrowTo?: string) => ({
@@ -100,7 +83,7 @@ export function LogsView({ scope }: { scope: ObservabilityScope }) {
enabled: !follow,
retry: false,
})
- const tail = useLogTail(root, query, follow, { cap: FOLLOW_CAP })
+ const tail = useLogTail(root, query, followRun, { cap: FOLLOW_CAP })
const wide = [pods.error, history.error, tail.error].find(isScopeWide)
if (wide) {
@@ -135,13 +118,13 @@ export function LogsView({ scope }: { scope: ObservabilityScope }) {
{ setPod(v); setContainer("") }} />
{!follow && }
- setFollow(!follow)}>
+ setFollowRun(follow ? null : Date.now())}>
Follow
{follow && (
- {tail.state === "live" ? "Live" : tail.state === "reconnecting" ? "Reconnecting…" : "Connecting…"}
+ {TAIL_STATE_LABEL[tail.state]}
{` · newest ${FOLLOW_CAP} lines kept`}
)}
From b05323f6bee913256c3e4ae6eedc764689ec508c Mon Sep 17 00:00:00 2001
From: ZverGuy
Date: Wed, 4 Nov 2026 05:47:22 +0700
Subject: [PATCH 09/46] docs(dashboard): note the observability proxy client in
the console guide
The next session needs to know why one module bypasses the typed
Kubernetes client and where the charting dependency is loaded.
Assisted-by: LLM
Signed-off-by: ZverGuy
---
packages/system/dashboard/images/console/CLAUDE.md | 2 ++
1 file changed, 2 insertions(+)
diff --git a/packages/system/dashboard/images/console/CLAUDE.md b/packages/system/dashboard/images/console/CLAUDE.md
index 2acf80504..96419d118 100644
--- a/packages/system/dashboard/images/console/CLAUDE.md
+++ b/packages/system/dashboard/images/console/CLAUDE.md
@@ -32,6 +32,8 @@ Implications:
- **RJSF** (`@rjsf/core` + `validator-ajv8`) for application config forms.
- **Vitest + jsdom + @testing-library/react** for tests.
- **Monaco** for YAML view, **noVNC** for the VM console tab.
+- **uPlot** for the Metrics tab charts, lazy-loaded with that tab.
+- Metrics and logs come from the observability proxy, not kube-apiserver: `lib/observability/proxy.ts` reads its native Prometheus JSON and VictoriaLogs NDJSON through `K8sClient.raw`, under the paths nginx routes to it ahead of `/apis`.
## Dev loop
From 84ed3aaefd34159549534dd8ff6f7e0e3111c3c9 Mon Sep 17 00:00:00 2001
From: ZverGuy
Date: Wed, 4 Nov 2026 05:50:33 +0700
Subject: [PATCH 10/46] fix(dashboard): follow the newest line again after the
log list clears
A reader who scrolled up stayed unpinned across a new follow run or a
new filter, so the fresh list sat at its top while lines streamed in
below. An empty list now means the reader is back at the bottom.
Assisted-by: LLM
Signed-off-by: ZverGuy
---
.../components/observability/LogLines.test.tsx | 16 ++++++++++++++++
.../src/components/observability/LogLines.tsx | 3 ++-
2 files changed, 18 insertions(+), 1 deletion(-)
diff --git a/packages/system/dashboard/images/console/apps/console/src/components/observability/LogLines.test.tsx b/packages/system/dashboard/images/console/apps/console/src/components/observability/LogLines.test.tsx
index 775c5fcc6..7110fe464 100644
--- a/packages/system/dashboard/images/console/apps/console/src/components/observability/LogLines.test.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/components/observability/LogLines.test.tsx
@@ -31,4 +31,20 @@ describe("LogLines", () => {
expect(list.scrollTop).toBe(120)
})
+
+ it("follows again once the list is cleared for a new run", () => {
+ const { rerender } = render( )
+ const first = screen.getByRole("list")
+ sized(first, 500)
+ first.scrollTop = 120
+ fireEvent.scroll(first)
+
+ rerender( )
+ rerender( )
+ const second = screen.getByRole("list")
+ sized(second, 300)
+ rerender( )
+
+ expect(second.scrollTop).toBe(300)
+ })
})
diff --git a/packages/system/dashboard/images/console/apps/console/src/components/observability/LogLines.tsx b/packages/system/dashboard/images/console/apps/console/src/components/observability/LogLines.tsx
index a6f4b5861..452faac72 100644
--- a/packages/system/dashboard/images/console/apps/console/src/components/observability/LogLines.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/components/observability/LogLines.tsx
@@ -9,7 +9,8 @@ export function LogLines({ entries }: { entries: LogEntry[] }) {
const pinned = useRef(true)
useEffect(() => {
- if (ref.current && pinned.current) ref.current.scrollTop = ref.current.scrollHeight
+ if (entries.length === 0) pinned.current = true
+ else if (ref.current && pinned.current) ref.current.scrollTop = ref.current.scrollHeight
}, [entries])
if (entries.length === 0) return No log lines for this range and filter.
From 1b4ce7433e1acbb7d5b1d5ec6a4634fe2cd1b730 Mon Sep 17 00:00:00 2001
From: ZverGuy
Date: Wed, 4 Nov 2026 05:50:33 +0700
Subject: [PATCH 11/46] fix(dashboard): keep retrying a log tail refused for
load
The proxy answers a tail over its rate or concurrent-tail cap with a
4xx, and a reconnect can arrive before the previous tail's slot is
freed. Treating that as final left Follow stopped for good, while the
existing backoff already waits long enough for the cap to clear.
Assisted-by: LLM
Signed-off-by: ZverGuy
---
.../console/src/lib/observability/use-log-tail.test.tsx | 8 ++++++++
.../apps/console/src/lib/observability/use-log-tail.ts | 3 ++-
2 files changed, 10 insertions(+), 1 deletion(-)
diff --git a/packages/system/dashboard/images/console/apps/console/src/lib/observability/use-log-tail.test.tsx b/packages/system/dashboard/images/console/apps/console/src/lib/observability/use-log-tail.test.tsx
index 46df47970..794f30216 100644
--- a/packages/system/dashboard/images/console/apps/console/src/lib/observability/use-log-tail.test.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/lib/observability/use-log-tail.test.tsx
@@ -67,6 +67,14 @@ describe("useLogTail", () => {
expect(new URL(raw.mock.calls[1][0], "http://x").searchParams.get("since")).toBe(T3)
})
+ it("retries a tail refused for load instead of stopping", async () => {
+ const { wrapper } = setup(new Response("too many concurrent requests", { status: 422 }), ndjson(line(T1, "a")))
+
+ const { result } = renderHook(() => useLogTail("/root/", "*", 1, { retryDelayMs: 1 }), { wrapper })
+
+ await waitFor(() => expect(result.current.entries.map((e) => e._msg)).toEqual(["a"]))
+ })
+
it("does not connect while disabled", () => {
const { raw, wrapper } = setup()
diff --git a/packages/system/dashboard/images/console/apps/console/src/lib/observability/use-log-tail.ts b/packages/system/dashboard/images/console/apps/console/src/lib/observability/use-log-tail.ts
index ddc835821..292f93e9e 100644
--- a/packages/system/dashboard/images/console/apps/console/src/lib/observability/use-log-tail.ts
+++ b/packages/system/dashboard/images/console/apps/console/src/lib/observability/use-log-tail.ts
@@ -14,7 +14,8 @@ interface TailSnapshot {
const FLUSH_MS = 100
const MAX_RETRY_MS = 30_000
-const FATAL: ReadonlySet = new Set(["bad-request", "unauthorized", "forbidden", "not-available", "limit"])
+// A 422 or 429 on tail is load (rate or concurrent-tail caps), which backoff outlasts.
+const FATAL: ReadonlySet = new Set(["bad-request", "unauthorized", "forbidden", "not-available"])
const sleep = (ms: number, signal: AbortSignal) =>
new Promise((resolve) => {
From ebdd74ce4e010cc347d1ddae312b2c20dfeb39fa Mon Sep 17 00:00:00 2001
From: ZverGuy
Date: Wed, 4 Nov 2026 05:53:23 +0700
Subject: [PATCH 12/46] fix(dashboard): name the proxy's real load status for a
refused tail
The proxy caps rate and concurrent tails with 429, so the retry
reasoning and its test now say so. Leaving Follow also remounts the
log list, so the history it falls back to opens at the newest line
even when the reader had scrolled up while following.
Assisted-by: LLM
Signed-off-by: ZverGuy
---
.../apps/console/src/components/observability/LogsView.tsx | 2 +-
.../apps/console/src/lib/observability/use-log-tail.test.tsx | 2 +-
.../console/apps/console/src/lib/observability/use-log-tail.ts | 3 ++-
3 files changed, 4 insertions(+), 3 deletions(-)
diff --git a/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.tsx b/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.tsx
index f21f2eb86..a27ca41c5 100644
--- a/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.tsx
@@ -129,7 +129,7 @@ export function LogsView({ scope }: { scope: ObservabilityScope }) {
)}
{error ? : null}
- {!follow && history.isLoading ? : }
+ {!follow && history.isLoading ? : }
)
}
diff --git a/packages/system/dashboard/images/console/apps/console/src/lib/observability/use-log-tail.test.tsx b/packages/system/dashboard/images/console/apps/console/src/lib/observability/use-log-tail.test.tsx
index 794f30216..0c2306613 100644
--- a/packages/system/dashboard/images/console/apps/console/src/lib/observability/use-log-tail.test.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/lib/observability/use-log-tail.test.tsx
@@ -68,7 +68,7 @@ describe("useLogTail", () => {
})
it("retries a tail refused for load instead of stopping", async () => {
- const { wrapper } = setup(new Response("too many concurrent requests", { status: 422 }), ndjson(line(T1, "a")))
+ const { wrapper } = setup(new Response("too many concurrent requests", { status: 429 }), ndjson(line(T1, "a")))
const { result } = renderHook(() => useLogTail("/root/", "*", 1, { retryDelayMs: 1 }), { wrapper })
diff --git a/packages/system/dashboard/images/console/apps/console/src/lib/observability/use-log-tail.ts b/packages/system/dashboard/images/console/apps/console/src/lib/observability/use-log-tail.ts
index 292f93e9e..53cbaf856 100644
--- a/packages/system/dashboard/images/console/apps/console/src/lib/observability/use-log-tail.ts
+++ b/packages/system/dashboard/images/console/apps/console/src/lib/observability/use-log-tail.ts
@@ -14,7 +14,8 @@ interface TailSnapshot {
const FLUSH_MS = 100
const MAX_RETRY_MS = 30_000
-// A 422 or 429 on tail is load (rate or concurrent-tail caps), which backoff outlasts.
+// Load refusals retry: the proxy caps rate and concurrent tails with 429 (422 in
+// its first builds), and a reconnect can race the previous tail's freed slot.
const FATAL: ReadonlySet = new Set(["bad-request", "unauthorized", "forbidden", "not-available"])
const sleep = (ms: number, signal: AbortSignal) =>
From 2b823ab79fa178f22b338ad654962bc9c334a30e Mon Sep 17 00:00:00 2001
From: ZverGuy
Date: Wed, 4 Nov 2026 05:53:50 +0700
Subject: [PATCH 13/46] fix(dashboard): rate over at least 5m and four steps
Long metric ranges are served by the longterm store, which keeps one
sample per 5m, so a rate window narrower than that can hold no samples
and the chart comes back empty. Four steps also keep every sample
between two points inside some window.
Assisted-by: LLM
Signed-off-by: ZverGuy
---
.../src/lib/observability/metrics.test.ts | 17 +++++++++++++----
.../console/src/lib/observability/metrics.ts | 6 +++---
2 files changed, 16 insertions(+), 7 deletions(-)
diff --git a/packages/system/dashboard/images/console/apps/console/src/lib/observability/metrics.test.ts b/packages/system/dashboard/images/console/apps/console/src/lib/observability/metrics.test.ts
index 0803940bf..0598c0c7f 100644
--- a/packages/system/dashboard/images/console/apps/console/src/lib/observability/metrics.test.ts
+++ b/packages/system/dashboard/images/console/apps/console/src/lib/observability/metrics.test.ts
@@ -32,10 +32,19 @@ describe("METRIC_PANELS", () => {
)
})
- it("widens the rate window with the step on long ranges", () => {
- const [query] = METRIC_PANELS.find((p) => p.id === "cpu")!.queries({ start: 0, end: 1, step: 2520 })
-
- expect(query.expr).toContain("[5040s]")
+ // Long ranges are served by the longterm store, deduplicated at 5m, where a
+ // narrower window can hold no samples and the rate comes back empty.
+ it.each([
+ [15, "300s"],
+ [75, "300s"],
+ [90, "360s"],
+ [2520, "10080s"],
+ ])("rates over max(5m, 4 x step) for step %is", (step, window) => {
+ for (const panel of METRIC_PANELS) {
+ for (const q of panel.queries({ start: 0, end: 1, step })) {
+ if (q.expr.includes("rate(")) expect(q.expr).toContain(`[${window}]`)
+ }
+ }
})
it("reads memory as working set per pod", () => {
diff --git a/packages/system/dashboard/images/console/apps/console/src/lib/observability/metrics.ts b/packages/system/dashboard/images/console/apps/console/src/lib/observability/metrics.ts
index b23a51e27..d7182b8d6 100644
--- a/packages/system/dashboard/images/console/apps/console/src/lib/observability/metrics.ts
+++ b/packages/system/dashboard/images/console/apps/console/src/lib/observability/metrics.ts
@@ -23,10 +23,10 @@ export function rangeWindow(range: RangeKey, nowSeconds: number): RangeWindow {
return { start: nowSeconds - span, end: nowSeconds, step: Math.max(MIN_STEP, Math.round(span / POINTS)) }
}
-// A rate needs several scrapes inside its window, and on long ranges the window
-// must also cover the step or samples between points are skipped.
+// The longterm store keeps one sample per 5m, so a narrower window can be empty;
+// 4 x step also keeps samples between points from being skipped.
function rateWindow(step: number): string {
- return `${Math.max(300, step * 2)}s`
+ return `${Math.max(300, step * 4)}s`
}
const CONTAINERS = 'container!="",container!="POD"'
From 3b1302ba8e8d44a5294b28302a775f805bd40e2a Mon Sep 17 00:00:00 2001
From: ZverGuy
Date: Wed, 4 Nov 2026 18:45:36 +0700
Subject: [PATCH 14/46] feat(dashboard): add an accessible Select to the
console
The console has no select primitive: form widgets fall back to the
native element, and the shared Dropdown has no listbox roles, no
keyboard navigation and no label association. Base UI, already a
dependency, ships one; this wraps it the same way dialog.tsx wraps the
Base UI dialog so pickers get a labelled, keyboard-driven listbox that
matches the console's buttons.
Assisted-by: LLM
Signed-off-by: ZverGuy
---
.../console/src/components/ui/select.test.tsx | 64 +++++++++++
.../apps/console/src/components/ui/select.tsx | 107 ++++++++++++++++++
2 files changed, 171 insertions(+)
create mode 100644 packages/system/dashboard/images/console/apps/console/src/components/ui/select.test.tsx
create mode 100644 packages/system/dashboard/images/console/apps/console/src/components/ui/select.tsx
diff --git a/packages/system/dashboard/images/console/apps/console/src/components/ui/select.test.tsx b/packages/system/dashboard/images/console/apps/console/src/components/ui/select.test.tsx
new file mode 100644
index 000000000..fb5b84e6f
--- /dev/null
+++ b/packages/system/dashboard/images/console/apps/console/src/components/ui/select.test.tsx
@@ -0,0 +1,64 @@
+import { describe, it, expect, vi } from "vitest"
+import { render, screen } from "@testing-library/react"
+import userEvent from "@testing-library/user-event"
+import { SelectItem, SelectLabel, SelectPopup, SelectRoot, SelectTrigger, SelectValue } from "./select.tsx"
+
+const items = [
+ { value: "", label: "All" },
+ { value: "db-0", label: "db-0" },
+ { value: "db-1", label: "db-1" },
+]
+
+function PodSelect({ value = "", onValueChange = () => {} }: { value?: string; onValueChange?: (v: string) => void }) {
+ return (
+ onValueChange(v ?? "")}>
+ Pod
+
+
+
+
+ {items.map((i) => (
+
+ {i.label}
+
+ ))}
+
+
+ )
+}
+
+describe("Select", () => {
+ it("names the trigger by its label and shows the chosen item", () => {
+ render( )
+
+ expect(screen.getByRole("combobox", { name: "Pod" })).toHaveTextContent("db-1")
+ })
+
+ it("shows the label of an empty-string value", () => {
+ render( )
+
+ expect(screen.getByRole("combobox", { name: "Pod" })).toHaveTextContent("All")
+ })
+
+ it("lists the items and reports the one clicked", async () => {
+ const onValueChange = vi.fn()
+ render( )
+
+ await userEvent.click(screen.getByRole("combobox", { name: "Pod" }))
+ await userEvent.click(await screen.findByRole("option", { name: "db-1" }))
+
+ expect(onValueChange).toHaveBeenCalledWith("db-1")
+ })
+
+ it("can be driven from the keyboard", async () => {
+ const onValueChange = vi.fn()
+ render( )
+
+ screen.getByRole("combobox", { name: "Pod" }).focus()
+ await userEvent.keyboard("{ArrowDown}")
+ expect(await screen.findByRole("listbox")).toBeInTheDocument()
+ await userEvent.keyboard("{ArrowDown}{Enter}")
+
+ expect(onValueChange).toHaveBeenCalledWith("db-0")
+ })
+})
diff --git a/packages/system/dashboard/images/console/apps/console/src/components/ui/select.tsx b/packages/system/dashboard/images/console/apps/console/src/components/ui/select.tsx
new file mode 100644
index 000000000..f256dba45
--- /dev/null
+++ b/packages/system/dashboard/images/console/apps/console/src/components/ui/select.tsx
@@ -0,0 +1,107 @@
+import { Select as SelectPrimitive } from "@base-ui/react/select"
+import { Check, ChevronDown } from "lucide-react"
+import { cn } from "@cozystack/ui"
+
+const SelectRoot = SelectPrimitive.Root
+
+function SelectLabel({
+ className,
+ ...props
+}: SelectPrimitive.Label.Props) {
+ return (
+
+ )
+}
+
+function SelectTrigger({
+ className,
+ children,
+ ...props
+}: SelectPrimitive.Trigger.Props) {
+ return (
+
+ {children}
+
+
+
+
+ )
+}
+
+function SelectValue({
+ className,
+ ...props
+}: SelectPrimitive.Value.Props) {
+ return (
+
+ )
+}
+
+function SelectPopup({
+ className,
+ children,
+ ...props
+}: SelectPrimitive.Popup.Props) {
+ return (
+
+
+
+ {children}
+
+
+
+ )
+}
+
+function SelectItem({
+ className,
+ children,
+ ...props
+}: SelectPrimitive.Item.Props) {
+ return (
+
+
+
+
+ {children}
+
+ )
+}
+
+export {
+ SelectRoot,
+ SelectLabel,
+ SelectTrigger,
+ SelectValue,
+ SelectPopup,
+ SelectItem,
+}
From f500aa955ac65384b527bf61167e77bf5dd02a3e Mon Sep 17 00:00:00 2001
From: ZverGuy
Date: Wed, 4 Nov 2026 18:46:15 +0700
Subject: [PATCH 15/46] feat(dashboard): add a text Input matching the console
select
Every text field in the console restyles a bare input by hand, each a
little differently. A toolbar that mixes a text filter with the new
Select needs the two at the same height, border and focus ring, so the
styling lives in one place next to the Select instead of being copied.
Assisted-by: LLM
Signed-off-by: ZverGuy
---
.../console/src/components/ui/input.test.tsx | 21 +++++++++++++++++++
.../apps/console/src/components/ui/input.tsx | 17 +++++++++++++++
2 files changed, 38 insertions(+)
create mode 100644 packages/system/dashboard/images/console/apps/console/src/components/ui/input.test.tsx
create mode 100644 packages/system/dashboard/images/console/apps/console/src/components/ui/input.tsx
diff --git a/packages/system/dashboard/images/console/apps/console/src/components/ui/input.test.tsx b/packages/system/dashboard/images/console/apps/console/src/components/ui/input.test.tsx
new file mode 100644
index 000000000..e65a70a3a
--- /dev/null
+++ b/packages/system/dashboard/images/console/apps/console/src/components/ui/input.test.tsx
@@ -0,0 +1,21 @@
+import { describe, it, expect, vi } from "vitest"
+import { render, screen } from "@testing-library/react"
+import userEvent from "@testing-library/user-event"
+import { Input } from "./input.tsx"
+
+describe("Input", () => {
+ it("is a labelled text box that reports what is typed", async () => {
+ const onValueChange = vi.fn()
+ render( )
+
+ await userEvent.type(screen.getByRole("textbox", { name: "Filter" }), "x")
+
+ expect(onValueChange).toHaveBeenCalledWith("x", expect.anything())
+ })
+
+ it("keeps the caller's classes next to its own", () => {
+ render( )
+
+ expect(screen.getByRole("textbox", { name: "Filter" })).toHaveClass("font-mono", "rounded-lg")
+ })
+})
diff --git a/packages/system/dashboard/images/console/apps/console/src/components/ui/input.tsx b/packages/system/dashboard/images/console/apps/console/src/components/ui/input.tsx
new file mode 100644
index 000000000..b079e6b35
--- /dev/null
+++ b/packages/system/dashboard/images/console/apps/console/src/components/ui/input.tsx
@@ -0,0 +1,17 @@
+import { Input as InputPrimitive } from "@base-ui/react/input"
+import { cn } from "@cozystack/ui"
+
+function Input({ className, ...props }: InputPrimitive.Props) {
+ return (
+
+ )
+}
+
+export { Input }
From b88ad09678a234ff351173a1cc0674b9721d795f Mon Sep 17 00:00:00 2001
From: ZverGuy
Date: Wed, 4 Nov 2026 18:47:25 +0700
Subject: [PATCH 16/46] fix(dashboard): keep the log console on screen when it
has no lines
With no matching lines, while loading, and while Follow waits for the
first line, the dark log console vanished and left a line of small
grey text or a bare spinner, so the page jumped and an empty result
looked like a broken view. The console frame now keeps a fixed height
in every state and says inside it what is going on.
The pod and container pickers move to the console Select and the
filter to the console Input, so the toolbar is keyboard and screen
reader friendly and a long pod name truncates instead of widening it.
Assisted-by: LLM
Signed-off-by: ZverGuy
---
.../observability/EmptyState.test.tsx | 17 +++++
.../components/observability/EmptyState.tsx | 25 ++++++++
.../observability/LogLines.test.tsx | 35 ++++++++---
.../src/components/observability/LogLines.tsx | 44 +++++++------
.../observability/LogsView.test.tsx | 50 ++++++++++++++-
.../src/components/observability/LogsView.tsx | 62 +++++++++++++------
6 files changed, 184 insertions(+), 49 deletions(-)
create mode 100644 packages/system/dashboard/images/console/apps/console/src/components/observability/EmptyState.test.tsx
create mode 100644 packages/system/dashboard/images/console/apps/console/src/components/observability/EmptyState.tsx
diff --git a/packages/system/dashboard/images/console/apps/console/src/components/observability/EmptyState.test.tsx b/packages/system/dashboard/images/console/apps/console/src/components/observability/EmptyState.test.tsx
new file mode 100644
index 000000000..8872f4d43
--- /dev/null
+++ b/packages/system/dashboard/images/console/apps/console/src/components/observability/EmptyState.test.tsx
@@ -0,0 +1,17 @@
+import { describe, it, expect } from "vitest"
+import { render, screen } from "@testing-library/react"
+import { EmptyState } from "./EmptyState.tsx"
+
+describe("EmptyState", () => {
+ it("announces its message as a status", () => {
+ render( )
+
+ expect(screen.getByRole("status")).toHaveTextContent("No data for this range.Pick a longer range.")
+ })
+
+ it("marks itself busy while something is loading", () => {
+ render( )
+
+ expect(screen.getByRole("status")).toHaveAttribute("aria-busy", "true")
+ })
+})
diff --git a/packages/system/dashboard/images/console/apps/console/src/components/observability/EmptyState.tsx b/packages/system/dashboard/images/console/apps/console/src/components/observability/EmptyState.tsx
new file mode 100644
index 000000000..0cf58224b
--- /dev/null
+++ b/packages/system/dashboard/images/console/apps/console/src/components/observability/EmptyState.tsx
@@ -0,0 +1,25 @@
+import type { ReactNode } from "react"
+import { cn, Spinner } from "@cozystack/ui"
+
+interface EmptyStateProps {
+ title: ReactNode
+ hint?: ReactNode
+ busy?: boolean
+ tone?: "light" | "dark"
+ className?: string
+}
+
+export function EmptyState({ title, hint, busy, tone = "light", className }: EmptyStateProps) {
+ const dark = tone === "dark"
+ return (
+
+ {busy &&
}
+
{title}
+ {hint &&
{hint}
}
+
+ )
+}
diff --git a/packages/system/dashboard/images/console/apps/console/src/components/observability/LogLines.test.tsx b/packages/system/dashboard/images/console/apps/console/src/components/observability/LogLines.test.tsx
index 7110fe464..dd8c503eb 100644
--- a/packages/system/dashboard/images/console/apps/console/src/components/observability/LogLines.test.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/components/observability/LogLines.test.tsx
@@ -10,40 +10,59 @@ function sized(list: HTMLElement, scrollHeight: number) {
}
describe("LogLines", () => {
+ it("keeps the console frame and shows the placeholder inside it when there are no lines", () => {
+ render( )
+
+ const frame = screen.getByRole("region", { name: "Log lines" })
+ expect(frame).toHaveTextContent("Waiting for new log lines…")
+ expect(screen.queryByRole("list")).toBeNull()
+ })
+
+ it("puts the lines in the same frame once they arrive", () => {
+ const { rerender } = render( )
+ const frame = screen.getByRole("region", { name: "Log lines" })
+
+ rerender( )
+
+ expect(screen.getByRole("region", { name: "Log lines" })).toBe(frame)
+ expect(frame).toContainElement(screen.getByRole("list"))
+ expect(frame).not.toHaveTextContent("Waiting")
+ })
+
it("keeps following the newest line while the reader is at the bottom", () => {
- const { rerender } = render( )
+ const { rerender } = render( )
const list = screen.getByRole("list")
sized(list, 500)
- rerender( )
+ rerender( )
expect(list.scrollTop).toBe(500)
})
it("leaves the position alone once the reader scrolls up", () => {
- const { rerender } = render( )
+ const { rerender } = render( )
const list = screen.getByRole("list")
sized(list, 500)
list.scrollTop = 120
fireEvent.scroll(list)
- rerender( )
+ rerender( )
expect(list.scrollTop).toBe(120)
})
it("follows again once the list is cleared for a new run", () => {
- const { rerender } = render( )
+ const { rerender } = render( )
const first = screen.getByRole("list")
sized(first, 500)
first.scrollTop = 120
fireEvent.scroll(first)
- rerender( )
- rerender( )
+ rerender( )
+ rerender( )
const second = screen.getByRole("list")
sized(second, 300)
- rerender( )
+ rerender( )
expect(second.scrollTop).toBe(300)
})
diff --git a/packages/system/dashboard/images/console/apps/console/src/components/observability/LogLines.tsx b/packages/system/dashboard/images/console/apps/console/src/components/observability/LogLines.tsx
index 452faac72..14b941ab2 100644
--- a/packages/system/dashboard/images/console/apps/console/src/components/observability/LogLines.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/components/observability/LogLines.tsx
@@ -1,10 +1,10 @@
-import { useEffect, useRef } from "react"
+import { useEffect, useRef, type ReactNode } from "react"
import { CONTAINER_FIELD, POD_FIELD } from "../../lib/observability/logs.ts"
import type { LogEntry } from "../../lib/observability/proxy.ts"
const BOTTOM_SLACK_PX = 24
-export function LogLines({ entries }: { entries: LogEntry[] }) {
+export function LogLines({ entries, placeholder }: { entries: LogEntry[]; placeholder: ReactNode }) {
const ref = useRef(null)
const pinned = useRef(true)
@@ -13,23 +13,31 @@ export function LogLines({ entries }: { entries: LogEntry[] }) {
else if (ref.current && pinned.current) ref.current.scrollTop = ref.current.scrollHeight
}, [entries])
- if (entries.length === 0) return No log lines for this range and filter.
return (
- {
- const el = e.currentTarget
- pinned.current = el.scrollHeight - el.scrollTop - el.clientHeight <= BOTTOM_SLACK_PX
- }}
- className="max-h-[60vh] overflow-auto rounded-md bg-slate-950 p-3 font-mono text-xs leading-5 text-slate-100"
+
- {entries.map((e, i) => (
-
- {new Date(e._time).toLocaleTimeString()} {" "}
- {`${e[POD_FIELD] ?? ""}/${e[CONTAINER_FIELD] ?? ""}`} {" "}
- {e._msg}
-
- ))}
-
+ {entries.length === 0 ? (
+ placeholder
+ ) : (
+ {
+ const el = e.currentTarget
+ pinned.current = el.scrollHeight - el.scrollTop - el.clientHeight <= BOTTOM_SLACK_PX
+ }}
+ className="h-full overflow-auto p-3"
+ >
+ {entries.map((e, i) => (
+
+ {new Date(e._time).toLocaleTimeString()} {" "}
+ {`${e[POD_FIELD] ?? ""}/${e[CONTAINER_FIELD] ?? ""}`} {" "}
+ {e._msg}
+
+ ))}
+
+ )}
+
)
}
diff --git a/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.test.tsx b/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.test.tsx
index 526efeb23..31c6fac0e 100644
--- a/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.test.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.test.tsx
@@ -1,5 +1,5 @@
import { describe, it, expect, vi } from "vitest"
-import { screen, waitFor } from "@testing-library/react"
+import { screen, waitFor, within } from "@testing-library/react"
import userEvent from "@testing-library/user-event"
import { K8sClient } from "@cozystack/k8s-client"
import { renderWithK8sProvider } from "../../test-utils/render.tsx"
@@ -47,9 +47,9 @@ describe("LogsView", () => {
it("narrows to the picked pod with a stream filter", async () => {
const { client, raw } = clientWith(defaultHandler)
renderWithK8sProvider( , { client })
- await screen.findByRole("option", { name: "db-1" })
- await userEvent.selectOptions(screen.getByLabelText("Pod"), "db-1")
+ await userEvent.click(screen.getByRole("combobox", { name: "Pod" }))
+ await userEvent.click(await screen.findByRole("option", { name: "db-1" }))
await waitFor(() =>
expect(
@@ -58,6 +58,50 @@ describe("LogsView", () => {
)
})
+ it("offers All next to every pod and starts on it", async () => {
+ const { client } = clientWith(defaultHandler)
+ renderWithK8sProvider( , { client })
+ const pod = screen.getByRole("combobox", { name: "Pod" })
+ expect(pod).toHaveTextContent("All")
+
+ await userEvent.click(pod)
+
+ expect(await screen.findByRole("option", { name: "db-1" })).toBeInTheDocument()
+ expect(screen.getAllByRole("option").map((o) => o.textContent)).toEqual(["All", "db-0", "db-1"])
+ })
+
+ it("keeps the log console and says so inside it when nothing matches", async () => {
+ const { client } = clientWith((endpoint, params) =>
+ endpoint.endsWith("query") ? new Response("") : defaultHandler(endpoint, params),
+ )
+
+ renderWithK8sProvider( , { client })
+
+ const frame = screen.getByRole("region", { name: "Log lines" })
+ expect(await within(frame).findByText("No log lines for this range and filter.")).toBeInTheDocument()
+ })
+
+ it("shows loading inside the log console", () => {
+ const { client } = clientWith((endpoint, params) =>
+ endpoint.endsWith("query") ? new Promise(() => {}) : defaultHandler(endpoint, params),
+ )
+
+ renderWithK8sProvider( , { client })
+
+ const frame = screen.getByRole("region", { name: "Log lines" })
+ expect(within(frame).getByRole("status")).toHaveAttribute("aria-busy", "true")
+ })
+
+ it("says it is waiting while Follow has no line yet", async () => {
+ const { client } = clientWith(defaultHandler)
+ renderWithK8sProvider( , { client })
+
+ await userEvent.click(screen.getByRole("button", { name: "Follow" }))
+
+ const frame = screen.getByRole("region", { name: "Log lines" })
+ expect(within(frame).getByText("Waiting for new log lines…")).toBeInTheDocument()
+ })
+
it("applies the LogsQL filter on submit", async () => {
const { client, raw } = clientWith(defaultHandler)
renderWithK8sProvider( , { client })
diff --git a/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.tsx b/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.tsx
index a27ca41c5..d2a000010 100644
--- a/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.tsx
@@ -1,7 +1,9 @@
import { useState } from "react"
import { useQuery } from "@tanstack/react-query"
import { useK8sClient } from "@cozystack/k8s-client"
-import { Button, Spinner } from "@cozystack/ui"
+import { Button } from "@cozystack/ui"
+import { Input } from "../ui/input.tsx"
+import { SelectItem, SelectLabel, SelectPopup, SelectRoot, SelectTrigger, SelectValue } from "../ui/select.tsx"
import {
CONTAINER_FIELD,
LOG_RANGES,
@@ -20,6 +22,7 @@ import { useLogTail } from "../../lib/observability/use-log-tail.ts"
import { ProxyNotice } from "./ProxyNotice.tsx"
import { RangePicker } from "./RangePicker.tsx"
import { LogLines } from "./LogLines.tsx"
+import { EmptyState } from "./EmptyState.tsx"
const HISTORY_LIMIT = 500
const FOLLOW_CAP = 1000
@@ -30,27 +33,42 @@ function windowFor(range: LogRangeKey) {
return { start: new Date(end - LOG_RANGES[range] * 1000).toISOString(), end: new Date(end).toISOString() }
}
+const ALL = ""
+
function Picker({ label, value, options, onChange }: { label: string; value: string; options: string[]; onChange: (v: string) => void }) {
+ const items = [{ value: ALL, label: "All" }, ...options.map((o) => ({ value: o, label: o }))]
return (
-
- {label}
- onChange(e.target.value)}
- className="rounded-md border border-slate-200 bg-white px-2 py-1 text-xs text-slate-900"
- >
- All
- {options.map((o) => (
-
- {o}
-
+ onChange(v ?? ALL)}>
+
+ {label}
+
+
+
+
+
+ {items.map((item) => (
+
+ {item.label}
+
))}
-
-
+
+
)
}
+function placeholderFor({ follow, stopped, loading, failed }: { follow: boolean; stopped: boolean; loading: boolean; failed: boolean }) {
+ if (follow) {
+ return stopped ? (
+
+ ) : (
+
+ )
+ }
+ if (loading) return
+ if (failed) return
+ return
+}
+
export function LogsView({ scope }: { scope: ObservabilityScope }) {
const client = useK8sClient()
const root = logsRoot(scope)
@@ -107,12 +125,12 @@ export function LogsView({ scope }: { scope: ObservabilityScope }) {
setFilter(draft)
}}
>
- setDraft(e.target.value)}
+ onValueChange={setDraft}
placeholder='LogsQL filter, e.g. error or "connection refused"'
- className="w-full rounded-md border border-slate-200 px-2.5 py-1.5 font-mono text-xs"
+ className="font-mono"
/>
{ setPod(v); setContainer("") }} />
@@ -129,7 +147,11 @@ export function LogsView({ scope }: { scope: ObservabilityScope }) {
)}
{error ? : null}
- {!follow && history.isLoading ? : }
+
)
}
From f5ebb43c4bdce908887029568065eb27785ff833 Mon Sep 17 00:00:00 2001
From: ZverGuy
Date: Wed, 4 Nov 2026 18:48:43 +0700
Subject: [PATCH 17/46] fix(dashboard): match the range picker to the log
toolbar controls
Next to the new Select and Input the range picker was shorter, lighter
bordered and had no focus ring, so the toolbar looked uneven and a
keyboard user could not see which range had focus. It now shares their
height, border and focus ring, and its buttons are grouped under one
accessible name.
Assisted-by: LLM
Signed-off-by: ZverGuy
---
.../observability/RangePicker.test.tsx | 23 +++++++++++++++++++
.../components/observability/RangePicker.tsx | 4 ++--
2 files changed, 25 insertions(+), 2 deletions(-)
create mode 100644 packages/system/dashboard/images/console/apps/console/src/components/observability/RangePicker.test.tsx
diff --git a/packages/system/dashboard/images/console/apps/console/src/components/observability/RangePicker.test.tsx b/packages/system/dashboard/images/console/apps/console/src/components/observability/RangePicker.test.tsx
new file mode 100644
index 000000000..9787963b2
--- /dev/null
+++ b/packages/system/dashboard/images/console/apps/console/src/components/observability/RangePicker.test.tsx
@@ -0,0 +1,23 @@
+import { describe, it, expect, vi } from "vitest"
+import { render, screen, within } from "@testing-library/react"
+import userEvent from "@testing-library/user-event"
+import { RangePicker } from "./RangePicker.tsx"
+
+describe("RangePicker", () => {
+ it("groups the ranges under one name and marks the chosen one pressed", () => {
+ render( {}} />)
+
+ const group = screen.getByRole("group", { name: "Time range" })
+ expect(within(group).getByRole("button", { name: "6h" })).toHaveAttribute("aria-pressed", "true")
+ expect(within(group).getByRole("button", { name: "1h" })).toHaveAttribute("aria-pressed", "false")
+ })
+
+ it("reports the range clicked", async () => {
+ const onChange = vi.fn()
+ render( )
+
+ await userEvent.click(screen.getByRole("button", { name: "1h" }))
+
+ expect(onChange).toHaveBeenCalledWith("1h")
+ })
+})
diff --git a/packages/system/dashboard/images/console/apps/console/src/components/observability/RangePicker.tsx b/packages/system/dashboard/images/console/apps/console/src/components/observability/RangePicker.tsx
index 22030c706..95d245176 100644
--- a/packages/system/dashboard/images/console/apps/console/src/components/observability/RangePicker.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/components/observability/RangePicker.tsx
@@ -10,7 +10,7 @@ export function RangePicker({
onChange: (value: K) => void
}) {
return (
-
+
{options.map((key) => (
({
aria-pressed={value === key}
onClick={() => onChange(key)}
className={cn(
- "rounded px-2.5 py-1 text-xs",
+ "h-full rounded-md px-2.5 text-xs outline-none focus-visible:ring-2 focus-visible:ring-slate-400",
value === key ? "bg-slate-900 text-white" : "text-slate-600 hover:bg-slate-100",
)}
>
From 05b0ea0c4558c5363cc38d79b7549548de7fe504 Mon Sep 17 00:00:00 2001
From: ZverGuy
Date: Wed, 4 Nov 2026 18:49:39 +0700
Subject: [PATCH 18/46] fix(dashboard): hold each metrics chart's place while
empty or loading
A metrics panel with no series, or still loading, shrank to one line of
small text or a bare spinner, so the tab jumped by the chart's height
when data arrived and an empty range looked like a broken panel. Both
states now fill the chart's slot and say what is going on, the same way
the log console does.
Assisted-by: LLM
Signed-off-by: ZverGuy
---
.../observability/MetricsView.test.tsx | 16 +++++++++++++++-
.../src/components/observability/MetricsView.tsx | 9 ++++++---
2 files changed, 21 insertions(+), 4 deletions(-)
diff --git a/packages/system/dashboard/images/console/apps/console/src/components/observability/MetricsView.test.tsx b/packages/system/dashboard/images/console/apps/console/src/components/observability/MetricsView.test.tsx
index f09e15201..b4c7fc3a4 100644
--- a/packages/system/dashboard/images/console/apps/console/src/components/observability/MetricsView.test.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/components/observability/MetricsView.test.tsx
@@ -22,7 +22,7 @@ function matrix(pod: string) {
})
}
-function clientWith(handler: (url: URL) => Response) {
+function clientWith(handler: (url: URL) => Response | Promise) {
const client = new K8sClient()
const raw = vi.spyOn(client, "raw").mockImplementation(async (path) => handler(new URL(path, "http://x")))
return { client, raw }
@@ -84,5 +84,19 @@ describe("MetricsView", () => {
renderWithK8sProvider( , { client })
await waitFor(() => expect(screen.getAllByText("No data for this range.")).toHaveLength(3))
+ for (const status of screen.getAllByRole("status")) expect(status).toHaveClass("h-[230px]")
+ })
+
+ it("holds each chart's place while it loads", () => {
+ const { client } = clientWith(() => new Promise(() => {}))
+
+ renderWithK8sProvider( , { client })
+
+ const statuses = screen.getAllByRole("status")
+ expect(statuses).toHaveLength(3)
+ for (const status of statuses) {
+ expect(status).toHaveAttribute("aria-busy", "true")
+ expect(status).toHaveClass("h-[230px]")
+ }
})
})
diff --git a/packages/system/dashboard/images/console/apps/console/src/components/observability/MetricsView.tsx b/packages/system/dashboard/images/console/apps/console/src/components/observability/MetricsView.tsx
index 35c8e8417..34d3b33a0 100644
--- a/packages/system/dashboard/images/console/apps/console/src/components/observability/MetricsView.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/components/observability/MetricsView.tsx
@@ -1,7 +1,7 @@
import { useState } from "react"
import { useQueries } from "@tanstack/react-query"
import { useK8sClient } from "@cozystack/k8s-client"
-import { Section, Spinner } from "@cozystack/ui"
+import { Section } from "@cozystack/ui"
import {
METRIC_PANELS,
RANGES,
@@ -13,8 +13,11 @@ import { isScopeWide, metricsRoot, queryRange, type ObservabilityScope } from ".
import { ProxyNotice } from "./ProxyNotice.tsx"
import { TimeSeriesChart } from "./TimeSeriesChart.tsx"
import { RangePicker } from "./RangePicker.tsx"
+import { EmptyState } from "./EmptyState.tsx"
const REFRESH_MS = 60_000
+// The uPlot canvas plus its one-row legend, so a placeholder takes the chart's place without a jump.
+const CHART_SLOT = "h-[230px] rounded-md border border-dashed border-slate-200 bg-slate-50"
export function MetricsView({ scope }: { scope: ObservabilityScope }) {
const client = useK8sClient()
@@ -57,9 +60,9 @@ export function MetricsView({ scope }: { scope: ObservabilityScope }) {
{error ? (
) : isLoading || !data ? (
-
+
) : data.series.length === 0 ? (
- No data for this range.
+
) : (
)}
From 6740ed445899fdd689ef7676840bc2d7a74936bc Mon Sep 17 00:00:00 2001
From: ZverGuy
Date: Wed, 4 Nov 2026 18:53:47 +0700
Subject: [PATCH 19/46] fix(dashboard): offer All once when a log stream has no
pod name
VictoriaLogs can return an empty value for the pod or container field
when some streams lack the label. That empty value is the picker's own
"All" sentinel, so the list showed two selected "All" entries with the
same key. Empty values are dropped from the field values.
The tests now also pin what the log console says when Follow stops
before any line and when the history query fails, so those messages
cannot silently swap with the empty-result one.
Assisted-by: LLM
Signed-off-by: ZverGuy
---
.../components/observability/LogsView.test.tsx | 18 ++++++++++++++++++
.../src/components/observability/LogsView.tsx | 2 +-
2 files changed, 19 insertions(+), 1 deletion(-)
diff --git a/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.test.tsx b/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.test.tsx
index 31c6fac0e..47b6b4ef9 100644
--- a/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.test.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.test.tsx
@@ -135,6 +135,8 @@ describe("LogsView", () => {
expect(await screen.findByText(/Stopped/)).toBeInTheDocument()
expect(screen.getByText("pipe not allowed in tail")).toBeInTheDocument()
+ const frame = screen.getByRole("region", { name: "Log lines" })
+ expect(within(frame).getByText("Follow stopped before any line arrived.")).toBeInTheDocument()
})
it("renders a cluster without the proxy as not available", async () => {
@@ -165,6 +167,22 @@ describe("LogsView", () => {
expect(await screen.findByText("cannot parse query")).toBeInTheDocument()
expect(screen.getByLabelText("LogsQL filter")).toBeInTheDocument()
+ const frame = screen.getByRole("region", { name: "Log lines" })
+ expect(within(frame).getByText("No log lines to show.")).toBeInTheDocument()
+ })
+
+ it("offers All once when some lines carry no pod name", async () => {
+ const { client } = clientWith((endpoint, params) =>
+ endpoint.endsWith("stream_field_values") && params.get("field") === "kubernetes_pod_name"
+ ? values("", "db-0")
+ : defaultHandler(endpoint, params),
+ )
+ renderWithK8sProvider( , { client })
+
+ await userEvent.click(screen.getByRole("combobox", { name: "Pod" }))
+
+ await screen.findByRole("option", { name: "db-0" })
+ expect(screen.getAllByRole("option").map((o) => o.textContent)).toEqual(["All", "db-0"])
})
it("names the source pod and container of each line", async () => {
diff --git a/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.tsx b/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.tsx
index d2a000010..1976c7dfc 100644
--- a/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.tsx
@@ -36,7 +36,7 @@ function windowFor(range: LogRangeKey) {
const ALL = ""
function Picker({ label, value, options, onChange }: { label: string; value: string; options: string[]; onChange: (v: string) => void }) {
- const items = [{ value: ALL, label: "All" }, ...options.map((o) => ({ value: o, label: o }))]
+ const items = [{ value: ALL, label: "All" }, ...options.filter((o) => o !== ALL).map((o) => ({ value: o, label: o }))]
return (
onChange(v ?? ALL)}>
From 554dad87bb18ece7adf5afd02c050a3520cf759a Mon Sep 17 00:00:00 2001
From: ZverGuy
Date: Wed, 4 Nov 2026 18:53:58 +0700
Subject: [PATCH 20/46] fix(dashboard): give the range picker the toolbar's
focus ring offset
The range buttons drew their focus ring flush against the button while
the Select and Input next to them offset it, so keyboard focus looked
different from one control to the next. The empty metrics hint also
repeated its title; it now suggests the one thing that can help.
Assisted-by: LLM
Signed-off-by: ZverGuy
---
.../apps/console/src/components/observability/MetricsView.tsx | 2 +-
.../apps/console/src/components/observability/RangePicker.tsx | 2 +-
2 files changed, 2 insertions(+), 2 deletions(-)
diff --git a/packages/system/dashboard/images/console/apps/console/src/components/observability/MetricsView.tsx b/packages/system/dashboard/images/console/apps/console/src/components/observability/MetricsView.tsx
index 34d3b33a0..ce7bcbe38 100644
--- a/packages/system/dashboard/images/console/apps/console/src/components/observability/MetricsView.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/components/observability/MetricsView.tsx
@@ -62,7 +62,7 @@ export function MetricsView({ scope }: { scope: ObservabilityScope }) {
) : isLoading || !data ? (
) : data.series.length === 0 ? (
-
+
) : (
)}
diff --git a/packages/system/dashboard/images/console/apps/console/src/components/observability/RangePicker.tsx b/packages/system/dashboard/images/console/apps/console/src/components/observability/RangePicker.tsx
index 95d245176..49abd8b1d 100644
--- a/packages/system/dashboard/images/console/apps/console/src/components/observability/RangePicker.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/components/observability/RangePicker.tsx
@@ -18,7 +18,7 @@ export function RangePicker({
aria-pressed={value === key}
onClick={() => onChange(key)}
className={cn(
- "h-full rounded-md px-2.5 text-xs outline-none focus-visible:ring-2 focus-visible:ring-slate-400",
+ "h-full rounded-md px-2.5 text-xs outline-none focus-visible:ring-2 focus-visible:ring-slate-400 focus-visible:ring-offset-2",
value === key ? "bg-slate-900 text-white" : "text-slate-600 hover:bg-slate-100",
)}
>
From c9a15cb8aed81e3b72d4e703c381474c6dc4db2b Mon Sep 17 00:00:00 2001
From: ZverGuy
Date: Wed, 4 Nov 2026 18:56:01 +0700
Subject: [PATCH 21/46] fix(dashboard): suggest a longer metrics range only
when there is one
With the longest range already picked, the empty panel still told the
reader to try a longer range, which the picker cannot offer.
Assisted-by: LLM
Signed-off-by: ZverGuy
---
.../src/components/observability/MetricsView.test.tsx | 11 +++++++++++
.../src/components/observability/MetricsView.tsx | 6 ++++--
2 files changed, 15 insertions(+), 2 deletions(-)
diff --git a/packages/system/dashboard/images/console/apps/console/src/components/observability/MetricsView.test.tsx b/packages/system/dashboard/images/console/apps/console/src/components/observability/MetricsView.test.tsx
index b4c7fc3a4..d3f1fc1dd 100644
--- a/packages/system/dashboard/images/console/apps/console/src/components/observability/MetricsView.test.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/components/observability/MetricsView.test.tsx
@@ -87,6 +87,17 @@ describe("MetricsView", () => {
for (const status of screen.getAllByRole("status")) expect(status).toHaveClass("h-[230px]")
})
+ it("suggests a longer range only while one exists", async () => {
+ const { client } = clientWith(() => Response.json({ status: "success", data: { resultType: "matrix", result: [] } }))
+ renderWithK8sProvider( , { client })
+ await waitFor(() => expect(screen.getAllByText("Try a longer range.")).toHaveLength(3))
+
+ await userEvent.click(screen.getByRole("button", { name: "7d" }))
+
+ await waitFor(() => expect(screen.getAllByText("No data for this range.")).toHaveLength(3))
+ expect(screen.queryByText("Try a longer range.")).toBeNull()
+ })
+
it("holds each chart's place while it loads", () => {
const { client } = clientWith(() => new Promise(() => {}))
diff --git a/packages/system/dashboard/images/console/apps/console/src/components/observability/MetricsView.tsx b/packages/system/dashboard/images/console/apps/console/src/components/observability/MetricsView.tsx
index ce7bcbe38..fac2a6b91 100644
--- a/packages/system/dashboard/images/console/apps/console/src/components/observability/MetricsView.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/components/observability/MetricsView.tsx
@@ -23,6 +23,8 @@ export function MetricsView({ scope }: { scope: ObservabilityScope }) {
const client = useK8sClient()
const root = metricsRoot(scope)
const [range, setRange] = useState("1h")
+ const rangeKeys = Object.keys(RANGES) as RangeKey[]
+ const longestRange = range === rangeKeys[rangeKeys.length - 1]
const results = useQueries({
queries: METRIC_PANELS.map((panel) => ({
@@ -48,7 +50,7 @@ export function MetricsView({ scope }: { scope: ObservabilityScope }) {
Resource consumption
-
+
{wide ? (
@@ -62,7 +64,7 @@ export function MetricsView({ scope }: { scope: ObservabilityScope }) {
) : isLoading || !data ? (
) : data.series.length === 0 ? (
-
+
) : (
)}
From fca5ca78de81666be249769a8496d4f0567cc022 Mon Sep 17 00:00:00 2001
From: ZverGuy
Date: Wed, 4 Nov 2026 19:04:29 +0700
Subject: [PATCH 22/46] fix(dashboard): treat an open log tail as live before
its first line
The tail counted as live, cleared its error and reset its backoff only
when a line arrived. A quiet application therefore showed "Connecting"
forever, a 429 warning stuck after the retry succeeded, and every idle
close by the proxy (its tail idle timeout) raised the backoff towards
30s and reconnected without since, losing lines written in the gap.
The tail now reports when the response opens. That marks it live,
clears the error and resets the backoff; a clean close reconnects at
the base delay; and with no line seen yet the reconnect resumes from
the time the stream opened.
Assisted-by: LLM
Signed-off-by: ZverGuy
---
.../src/lib/observability/proxy.test.ts | 18 +++++++++
.../console/src/lib/observability/proxy.ts | 2 +
.../lib/observability/use-log-tail.test.tsx | 37 +++++++++++++++++++
.../src/lib/observability/use-log-tail.ts | 19 +++++++---
4 files changed, 71 insertions(+), 5 deletions(-)
diff --git a/packages/system/dashboard/images/console/apps/console/src/lib/observability/proxy.test.ts b/packages/system/dashboard/images/console/apps/console/src/lib/observability/proxy.test.ts
index 69a8c7c8c..2809905d8 100644
--- a/packages/system/dashboard/images/console/apps/console/src/lib/observability/proxy.test.ts
+++ b/packages/system/dashboard/images/console/apps/console/src/lib/observability/proxy.test.ts
@@ -194,6 +194,24 @@ describe("tailLogs", () => {
expect(err).toMatchObject({ kind: "forbidden" })
})
+
+ it("says the stream opened before any line arrives", async () => {
+ const { client } = clientReturning(new Response(""))
+ const onOpen = vi.fn()
+
+ await tailLogs(client, logsRoot(ns), { query: "*" }, () => {}, undefined, onOpen)
+
+ expect(onOpen).toHaveBeenCalledTimes(1)
+ })
+
+ it("does not say the stream opened when the tail is refused", async () => {
+ const { client } = clientReturning(new Response("", { status: 429 }))
+ const onOpen = vi.fn()
+
+ await tailLogs(client, logsRoot(ns), { query: "*" }, () => {}, undefined, onOpen).catch(() => {})
+
+ expect(onOpen).not.toHaveBeenCalled()
+ })
})
describe("isScopeWide", () => {
diff --git a/packages/system/dashboard/images/console/apps/console/src/lib/observability/proxy.ts b/packages/system/dashboard/images/console/apps/console/src/lib/observability/proxy.ts
index c9fce3d4f..3b5567f6b 100644
--- a/packages/system/dashboard/images/console/apps/console/src/lib/observability/proxy.ts
+++ b/packages/system/dashboard/images/console/apps/console/src/lib/observability/proxy.ts
@@ -202,8 +202,10 @@ export async function tailLogs(
params: { query: string; since?: string },
onEntry: (entry: LogEntry) => void,
signal?: AbortSignal,
+ onOpen?: () => void,
): Promise {
const res = await proxyGet(client, `${root}select/logsql/tail`, params, signal)
+ onOpen?.()
if (!res.body) return
const reader = res.body.getReader()
const decoder = new TextDecoder()
diff --git a/packages/system/dashboard/images/console/apps/console/src/lib/observability/use-log-tail.test.tsx b/packages/system/dashboard/images/console/apps/console/src/lib/observability/use-log-tail.test.tsx
index 0c2306613..b5232d18e 100644
--- a/packages/system/dashboard/images/console/apps/console/src/lib/observability/use-log-tail.test.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/lib/observability/use-log-tail.test.tsx
@@ -10,6 +10,10 @@ function ndjson(...lines: string[]): Response {
return new Response(lines.map((l) => `${l}\n`).join(""))
}
+function openStream(): Response {
+ return new Response(new ReadableStream({ start() {} }))
+}
+
function setup(...responses: Response[]) {
const client = new K8sClient()
const raw = vi.spyOn(client, "raw")
@@ -75,6 +79,39 @@ describe("useLogTail", () => {
await waitFor(() => expect(result.current.entries.map((e) => e._msg)).toEqual(["a"]))
})
+ it("goes live and clears a load warning once the stream opens, before any line", async () => {
+ const { wrapper } = setup(new Response("too many concurrent requests", { status: 429 }), openStream())
+
+ const { result } = renderHook(() => useLogTail("/root/", "*", 1, { retryDelayMs: 1 }), { wrapper })
+
+ await waitFor(() => expect(result.current.state).toBe("live"))
+ expect(result.current.error).toBeNull()
+ })
+
+ it("reconnects after an idle close at the base delay, from when the quiet stream opened", async () => {
+ const delays: number[] = []
+ const realSetTimeout = globalThis.setTimeout
+ const spy = vi.spyOn(globalThis, "setTimeout").mockImplementation(((fn: () => void, ms?: number) => {
+ if (ms !== undefined && ms % 7 === 0 && ms > 0) delays.push(ms)
+ return realSetTimeout(fn, ms)
+ }) as typeof setTimeout)
+ const refused = () => new Response("", { status: 429 })
+ const { raw, wrapper } = setup(refused(), refused(), ndjson())
+
+ try {
+ renderHook(() => useLogTail("/root/", "*", 1, { retryDelayMs: 7 }), { wrapper })
+ await waitFor(() => expect(raw).toHaveBeenCalledTimes(4))
+ } finally {
+ spy.mockRestore()
+ }
+
+ expect(delays).toEqual([7, 14, 7])
+ expect(new URL(raw.mock.calls[2][0], "http://x").searchParams.has("since")).toBe(false)
+ const since = new URL(raw.mock.calls[3][0], "http://x").searchParams.get("since")
+ expect(since).not.toBeNull()
+ expect(new Date(since!).toISOString()).toBe(since)
+ })
+
it("does not connect while disabled", () => {
const { raw, wrapper } = setup()
diff --git a/packages/system/dashboard/images/console/apps/console/src/lib/observability/use-log-tail.ts b/packages/system/dashboard/images/console/apps/console/src/lib/observability/use-log-tail.ts
index 53cbaf856..2e3b4d706 100644
--- a/packages/system/dashboard/images/console/apps/console/src/lib/observability/use-log-tail.ts
+++ b/packages/system/dashboard/images/console/apps/console/src/lib/observability/use-log-tail.ts
@@ -66,15 +66,22 @@ export function useLogTail(
}
const run = async () => {
- for (let attempt = 0; !signal.aborted; attempt++) {
+ let failures = 0
+ let openedAt: string | undefined
+ while (!signal.aborted) {
resumedFrom = lastTime
+ let delay = retryDelayMs
try {
- await tailLogs(client, root, { query, since: lastTime }, (entry) => {
- attempt = 0
+ await tailLogs(client, root, { query, since: lastTime ?? openedAt }, (entry) => {
if (!lastTime || compareTime(entry._time, lastTime) > 0) lastTime = entry._time
pending.push(entry)
timer ??= setTimeout(flush, FLUSH_MS)
- }, signal)
+ }, signal, () => {
+ failures = 0
+ // With no line yet, the next reconnect resumes from here so the gap is not lost.
+ openedAt = new Date().toISOString()
+ update({ state: "live", error: null })
+ })
flush()
} catch (err) {
flush()
@@ -84,10 +91,12 @@ export function useLogTail(
return
}
update({ error: err })
+ delay = Math.min(retryDelayMs * 2 ** failures, MAX_RETRY_MS)
+ failures++
}
if (signal.aborted) return
update({ state: "reconnecting" })
- await sleep(Math.min(retryDelayMs * 2 ** attempt, MAX_RETRY_MS), signal)
+ await sleep(delay, signal)
}
}
void run()
From 881eea524693248cdcfb4421bad190cbf7b586c8 Mon Sep 17 00:00:00 2001
From: ZverGuy
Date: Wed, 4 Nov 2026 19:04:58 +0700
Subject: [PATCH 23/46] fix(dashboard): suggest a longer log range only when
there is one
On 24h, the longest range the log view offers, the empty console still
told the reader to try a longer range. It now suggests only a broader
filter there, as the metrics panels already do.
Assisted-by: LLM
Signed-off-by: ZverGuy
---
.../src/components/observability/LogsView.test.tsx | 14 ++++++++++++++
.../src/components/observability/LogsView.tsx | 11 +++++++----
2 files changed, 21 insertions(+), 4 deletions(-)
diff --git a/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.test.tsx b/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.test.tsx
index 47b6b4ef9..1b18dd208 100644
--- a/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.test.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.test.tsx
@@ -81,6 +81,20 @@ describe("LogsView", () => {
expect(await within(frame).findByText("No log lines for this range and filter.")).toBeInTheDocument()
})
+ it("suggests a longer range only while one exists", async () => {
+ const { client } = clientWith((endpoint, params) =>
+ endpoint.endsWith("query") ? new Response("") : defaultHandler(endpoint, params),
+ )
+ renderWithK8sProvider( , { client })
+ const frame = screen.getByRole("region", { name: "Log lines" })
+ expect(await within(frame).findByText("Try a longer range or a broader filter.")).toBeInTheDocument()
+
+ await userEvent.click(screen.getByRole("button", { name: "24h" }))
+
+ expect(await within(frame).findByText("Try a broader filter.")).toBeInTheDocument()
+ expect(within(frame).queryByText(/longer range/)).toBeNull()
+ })
+
it("shows loading inside the log console", () => {
const { client } = clientWith((endpoint, params) =>
endpoint.endsWith("query") ? new Promise(() => {}) : defaultHandler(endpoint, params),
diff --git a/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.tsx b/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.tsx
index 1976c7dfc..a0a73cc43 100644
--- a/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.tsx
@@ -56,7 +56,10 @@ function Picker({ label, value, options, onChange }: { label: string; value: str
)
}
-function placeholderFor({ follow, stopped, loading, failed }: { follow: boolean; stopped: boolean; loading: boolean; failed: boolean }) {
+const RANGE_KEYS = Object.keys(LOG_RANGES) as LogRangeKey[]
+const LONGEST_RANGE = RANGE_KEYS[RANGE_KEYS.length - 1]
+
+function placeholderFor({ follow, stopped, loading, failed, longestRange }: { follow: boolean; stopped: boolean; loading: boolean; failed: boolean; longestRange: boolean }) {
if (follow) {
return stopped ? (
@@ -66,7 +69,7 @@ function placeholderFor({ follow, stopped, loading, failed }: { follow: boolean;
}
if (loading) return
if (failed) return
- return
+ return
}
export function LogsView({ scope }: { scope: ObservabilityScope }) {
@@ -135,7 +138,7 @@ export function LogsView({ scope }: { scope: ObservabilityScope }) {
{ setPod(v); setContainer("") }} />
- {!follow && }
+ {!follow && }
setFollowRun(follow ? null : Date.now())}>
Follow
@@ -150,7 +153,7 @@ export function LogsView({ scope }: { scope: ObservabilityScope }) {
)
From 9498c9bff520d73fe200f5043bc7efce9eb901ef Mon Sep 17 00:00:00 2001
From: ZverGuy
Date: Wed, 4 Nov 2026 19:05:42 +0700
Subject: [PATCH 24/46] fix(dashboard): keep the proxy's own advice on a limit
refusal
The notice appended "Choose a shorter range." to every 422, so a
message that already ended in "use a shorter range" said it twice and
one that ended in "raise step" got advice that contradicted it. The
console's own advice is now added only when the proxy gave none.
Assisted-by: LLM
Signed-off-by: ZverGuy
---
.../src/components/observability/ProxyNotice.test.tsx | 9 +++++++++
.../console/src/components/observability/ProxyNotice.tsx | 3 ++-
2 files changed, 11 insertions(+), 1 deletion(-)
diff --git a/packages/system/dashboard/images/console/apps/console/src/components/observability/ProxyNotice.test.tsx b/packages/system/dashboard/images/console/apps/console/src/components/observability/ProxyNotice.test.tsx
index fd001bcae..6e85ced33 100644
--- a/packages/system/dashboard/images/console/apps/console/src/components/observability/ProxyNotice.test.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/components/observability/ProxyNotice.test.tsx
@@ -29,6 +29,15 @@ describe("ProxyNotice", () => {
expect(screen.getByRole("alert")).toHaveTextContent(text)
})
+ it.each([
+ "the application has more than 50 pods in this window; use a shorter range",
+ "1200 points per series exceed the limit of 1000; raise step",
+ ])("does not add advice to a limit message that already carries its own: %s", (message) => {
+ render( )
+
+ expect(screen.getByRole("alert").textContent).toBe(`${message}.`)
+ })
+
it("shows the server message for a rejected query", () => {
render( )
diff --git a/packages/system/dashboard/images/console/apps/console/src/components/observability/ProxyNotice.tsx b/packages/system/dashboard/images/console/apps/console/src/components/observability/ProxyNotice.tsx
index a60b831b0..ee68e4633 100644
--- a/packages/system/dashboard/images/console/apps/console/src/components/observability/ProxyNotice.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/components/observability/ProxyNotice.tsx
@@ -20,7 +20,8 @@ function describe(what: ProxyNoticeProps["what"], error: unknown): { quiet: bool
case "forbidden":
return { quiet: false, text: `You do not have permission to read ${lower} here.` }
case "limit":
- return { quiet: false, text: `${error.message}. Choose a shorter range.` }
+ // The proxy puts its own remedy after "; " (e.g. "use a shorter range", "raise step").
+ return { quiet: false, text: error.message.includes("; ") ? `${error.message}.` : `${error.message}. Choose a shorter range.` }
case "rate-limited":
return { quiet: false, text: "Too many requests. Try again in a moment." }
case "timeout":
From 76441871b8c3ae73f40ecf29fd454a468f1e0573 Mon Sep 17 00:00:00 2001
From: ZverGuy
Date: Wed, 4 Nov 2026 19:06:59 +0700
Subject: [PATCH 25/46] fix(dashboard): keep caller headers of any shape in the
k8s client
The client spread init.headers as a plain object, so a Headers
instance or a list of pairs passed by a caller was silently dropped
and the request went out without them. Headers are now built with the
Headers constructor, which accepts every shape fetch does.
Assisted-by: LLM
Signed-off-by: ZverGuy
---
.../k8s-client/client.headers.test.ts | 31 +++++++++++++++++++
.../__tests__/k8s-client/client.raw.test.ts | 20 +++++++++++-
.../console/packages/k8s-client/src/client.ts | 14 +++------
3 files changed, 55 insertions(+), 10 deletions(-)
create mode 100644 packages/system/dashboard/images/console/apps/console/src/__tests__/k8s-client/client.headers.test.ts
diff --git a/packages/system/dashboard/images/console/apps/console/src/__tests__/k8s-client/client.headers.test.ts b/packages/system/dashboard/images/console/apps/console/src/__tests__/k8s-client/client.headers.test.ts
new file mode 100644
index 000000000..37985fca5
--- /dev/null
+++ b/packages/system/dashboard/images/console/apps/console/src/__tests__/k8s-client/client.headers.test.ts
@@ -0,0 +1,31 @@
+import { describe, it, expect, vi, afterEach } from "vitest"
+import { K8sClient } from "@cozystack/k8s-client"
+
+afterEach(() => {
+ vi.unstubAllGlobals()
+})
+
+describe("K8sClient request headers", () => {
+ it("lets a method's own content type replace the JSON default", async () => {
+ const fetchMock = vi.fn(async () => new Response("{}"))
+ vi.stubGlobal("fetch", fetchMock)
+ const client = new K8sClient({ getToken: async () => "t0k" })
+
+ await client.patch("apps", "v1", "deployments", "web", { spec: {} }, "default", "merge")
+
+ const [, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit]
+ const headers = new Headers(init.headers)
+ expect(headers.get("Content-Type")).toBe("application/merge-patch+json")
+ expect(headers.get("Authorization")).toBe("Bearer t0k")
+ })
+
+ it("sends JSON by default", async () => {
+ const fetchMock = vi.fn(async () => new Response("{}"))
+ vi.stubGlobal("fetch", fetchMock)
+
+ await new K8sClient().getApiGroups()
+
+ const [, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit]
+ expect(new Headers(init.headers).get("Content-Type")).toBe("application/json")
+ })
+})
diff --git a/packages/system/dashboard/images/console/apps/console/src/__tests__/k8s-client/client.raw.test.ts b/packages/system/dashboard/images/console/apps/console/src/__tests__/k8s-client/client.raw.test.ts
index ab6c056f5..0ac0d75ae 100644
--- a/packages/system/dashboard/images/console/apps/console/src/__tests__/k8s-client/client.raw.test.ts
+++ b/packages/system/dashboard/images/console/apps/console/src/__tests__/k8s-client/client.raw.test.ts
@@ -24,7 +24,25 @@ describe("K8sClient.raw", () => {
const [url, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit]
expect(url).toBe("/base/apis/x")
- expect(init.headers).toEqual({ Accept: "application/json", Authorization: "Bearer t0k" })
+ const headers = new Headers(init.headers)
+ expect(headers.get("Accept")).toBe("application/json")
+ expect(headers.get("Authorization")).toBe("Bearer t0k")
+ })
+
+ it.each([
+ ["a Headers instance", new Headers({ Accept: "application/x-ndjson" })],
+ ["a tuple list", [["Accept", "application/x-ndjson"]] as [string, string][]],
+ ])("keeps caller headers passed as %s", async (_, given) => {
+ const fetchMock = vi.fn(async () => new Response("{}"))
+ vi.stubGlobal("fetch", fetchMock)
+ const client = new K8sClient({ getToken: async () => "t0k" })
+
+ await client.raw("/x", { headers: given })
+
+ const [, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit]
+ const headers = new Headers(init.headers)
+ expect(headers.get("Accept")).toBe("application/x-ndjson")
+ expect(headers.get("Authorization")).toBe("Bearer t0k")
})
it("routes a 401 through the client's unauthorized handler", async () => {
diff --git a/packages/system/dashboard/images/console/packages/k8s-client/src/client.ts b/packages/system/dashboard/images/console/packages/k8s-client/src/client.ts
index 04c528760..64af1131d 100644
--- a/packages/system/dashboard/images/console/packages/k8s-client/src/client.ts
+++ b/packages/system/dashboard/images/console/packages/k8s-client/src/client.ts
@@ -50,14 +50,12 @@ export class K8sClient {
}
private async request(path: string, init?: RequestInit): Promise {
- const headers: Record = {
- "Content-Type": "application/json",
- ...(init?.headers as Record),
- }
+ const headers = new Headers(init?.headers)
+ if (!headers.has("Content-Type")) headers.set("Content-Type", "application/json")
if (this.getToken) {
const token = await this.getToken()
- headers["Authorization"] = `Bearer ${token}`
+ headers.set("Authorization", `Bearer ${token}`)
}
let res: Response
@@ -247,11 +245,9 @@ export class K8sClient {
* Kubernetes JSON, such as the observability proxy's streamed NDJSON.
*/
async raw(path: string, init?: RequestInit): Promise {
- const headers: Record = {
- ...(init?.headers as Record),
- }
+ const headers = new Headers(init?.headers)
if (this.getToken) {
- headers["Authorization"] = `Bearer ${await this.getToken()}`
+ headers.set("Authorization", `Bearer ${await this.getToken()}`)
}
const res = await fetch(`${this.baseUrl}${path}`, { ...init, headers })
if (res.status === 401) this.handleUnauthorized()
From 2a473086cf6cd1d245e014ed56ed44f9594038cd Mon Sep 17 00:00:00 2001
From: ZverGuy
Date: Wed, 4 Nov 2026 19:11:05 +0700
Subject: [PATCH 26/46] fix(dashboard): advise a shorter range unless the proxy
already did
Any "; " in a 422 message was taken as the proxy's own remedy, but the
proxy passes vmselect's 422 bodies through, and their advice (raise
the -search.max* flags) is for operators. Those lost the one thing a
tenant can do. Only the remedies the proxy itself appends now replace
the console's advice.
Assisted-by: LLM
Signed-off-by: ZverGuy
---
.../src/components/observability/ProxyNotice.test.tsx | 7 +++++++
.../src/components/observability/ProxyNotice.tsx | 10 ++++++++--
2 files changed, 15 insertions(+), 2 deletions(-)
diff --git a/packages/system/dashboard/images/console/apps/console/src/components/observability/ProxyNotice.test.tsx b/packages/system/dashboard/images/console/apps/console/src/components/observability/ProxyNotice.test.tsx
index 6e85ced33..c4b4e89c1 100644
--- a/packages/system/dashboard/images/console/apps/console/src/components/observability/ProxyNotice.test.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/components/observability/ProxyNotice.test.tsx
@@ -38,6 +38,13 @@ describe("ProxyNotice", () => {
expect(screen.getByRole("alert").textContent).toBe(`${message}.`)
})
+ it("still advises a shorter range for a store limit whose own advice is for operators", () => {
+ const message = "the number of matching timeseries exceeds 300000; either narrow down the search or increase -search.max* command-line flag values"
+ render( )
+
+ expect(screen.getByRole("alert").textContent).toBe(`${message}. Choose a shorter range.`)
+ })
+
it("shows the server message for a rejected query", () => {
render( )
diff --git a/packages/system/dashboard/images/console/apps/console/src/components/observability/ProxyNotice.tsx b/packages/system/dashboard/images/console/apps/console/src/components/observability/ProxyNotice.tsx
index ee68e4633..1fb30c8ff 100644
--- a/packages/system/dashboard/images/console/apps/console/src/components/observability/ProxyNotice.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/components/observability/ProxyNotice.tsx
@@ -5,6 +5,10 @@ interface ProxyNoticeProps {
error: unknown
}
+// Remedies the observability proxy itself appends; vmselect's 422 text carries
+// advice for operators (raise -search.max* flags), so it still gets ours.
+const PROXY_REMEDIES = ["; use a shorter range", "; raise step"]
+
function describe(what: ProxyNoticeProps["what"], error: unknown): { quiet: boolean; text: string } {
const lower = what.toLowerCase()
if (!(error instanceof ProxyError)) {
@@ -20,8 +24,10 @@ function describe(what: ProxyNoticeProps["what"], error: unknown): { quiet: bool
case "forbidden":
return { quiet: false, text: `You do not have permission to read ${lower} here.` }
case "limit":
- // The proxy puts its own remedy after "; " (e.g. "use a shorter range", "raise step").
- return { quiet: false, text: error.message.includes("; ") ? `${error.message}.` : `${error.message}. Choose a shorter range.` }
+ return {
+ quiet: false,
+ text: PROXY_REMEDIES.some((r) => error.message.endsWith(r)) ? `${error.message}.` : `${error.message}. Choose a shorter range.`,
+ }
case "rate-limited":
return { quiet: false, text: "Too many requests. Try again in a moment." }
case "timeout":
From 1e1fdb740c229f7233e3be4993d063c2fd5cc5fb Mon Sep 17 00:00:00 2001
From: ZverGuy
Date: Thu, 5 Nov 2026 00:14:24 +0700
Subject: [PATCH 27/46] fix(dashboard): show log rows a pipe stripped of their
timestamp
A LogsQL pipe such as `fields _msg` or `stats` returns rows without
_time, and the console dropped every one of them, so a successful
query read as "no lines matched". Such rows are now kept in the order
the store sent them, shown without a timestamp, and never
deduplicated on a tail resume. A row without _msg shows its remaining
fields instead of an empty line.
Assisted-by: LLM
Signed-off-by: ZverGuy
---
.../observability/LogLines.test.tsx | 12 +++++++
.../src/components/observability/LogLines.tsx | 33 +++++++++++++++----
.../observability/LogsView.test.tsx | 13 ++++++++
.../src/lib/observability/logs.test.ts | 6 ++++
.../console/src/lib/observability/logs.ts | 5 +--
.../src/lib/observability/proxy.test.ts | 20 ++++++++++-
.../console/src/lib/observability/proxy.ts | 10 +++---
.../src/lib/observability/use-log-tail.ts | 2 +-
8 files changed, 86 insertions(+), 15 deletions(-)
diff --git a/packages/system/dashboard/images/console/apps/console/src/components/observability/LogLines.test.tsx b/packages/system/dashboard/images/console/apps/console/src/components/observability/LogLines.test.tsx
index dd8c503eb..a0f519852 100644
--- a/packages/system/dashboard/images/console/apps/console/src/components/observability/LogLines.test.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/components/observability/LogLines.test.tsx
@@ -29,6 +29,18 @@ describe("LogLines", () => {
expect(frame).not.toHaveTextContent("Waiting")
})
+ it("shows a line without _time with no timestamp and no empty source", () => {
+ render( )
+
+ expect(screen.getByRole("listitem")).toHaveTextContent(/^visible message$/)
+ })
+
+ it("shows the remaining fields of a row without _msg", () => {
+ render( )
+
+ expect(screen.getByRole("listitem")).toHaveTextContent(/^db-0\/ rows=42$/)
+ })
+
it("keeps following the newest line while the reader is at the bottom", () => {
const { rerender } = render( )
const list = screen.getByRole("list")
diff --git a/packages/system/dashboard/images/console/apps/console/src/components/observability/LogLines.tsx b/packages/system/dashboard/images/console/apps/console/src/components/observability/LogLines.tsx
index 14b941ab2..f29af017c 100644
--- a/packages/system/dashboard/images/console/apps/console/src/components/observability/LogLines.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/components/observability/LogLines.tsx
@@ -3,6 +3,22 @@ import { CONTAINER_FIELD, POD_FIELD } from "../../lib/observability/logs.ts"
import type { LogEntry } from "../../lib/observability/proxy.ts"
const BOTTOM_SLACK_PX = 24
+const SHOWN_APART = new Set(["_time", "_msg", "_stream_id", POD_FIELD, CONTAINER_FIELD])
+
+function source(e: LogEntry): string | null {
+ const pod = e[POD_FIELD]
+ const container = e[CONTAINER_FIELD]
+ return pod || container ? `${pod ?? ""}/${container ?? ""}` : null
+}
+
+// A `fields` or `stats` pipe can leave a row without _msg; its other fields are then the content.
+function message(e: LogEntry): string {
+ if (e._msg !== undefined) return e._msg
+ return Object.entries(e)
+ .filter(([k, v]) => v !== undefined && !SHOWN_APART.has(k))
+ .map(([k, v]) => `${k}=${v}`)
+ .join(" ")
+}
export function LogLines({ entries, placeholder }: { entries: LogEntry[]; placeholder: ReactNode }) {
const ref = useRef(null)
@@ -29,13 +45,16 @@ export function LogLines({ entries, placeholder }: { entries: LogEntry[]; placeh
}}
className="h-full overflow-auto p-3"
>
- {entries.map((e, i) => (
-
- {new Date(e._time).toLocaleTimeString()} {" "}
- {`${e[POD_FIELD] ?? ""}/${e[CONTAINER_FIELD] ?? ""}`} {" "}
- {e._msg}
-
- ))}
+ {entries.map((e, i) => {
+ const from = source(e)
+ return (
+
+ {e._time !== undefined && <>{new Date(e._time).toLocaleTimeString()} {" "}>}
+ {from !== null && <>{from} {" "}>}
+ {message(e)}
+
+ )
+ })}
)}
diff --git a/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.test.tsx b/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.test.tsx
index 1b18dd208..770c8a263 100644
--- a/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.test.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.test.tsx
@@ -199,6 +199,19 @@ describe("LogsView", () => {
expect(screen.getAllByRole("option").map((o) => o.textContent)).toEqual(["All", "db-0"])
})
+ it("shows rows of a query whose pipe removed _time", async () => {
+ const { client } = clientWith((endpoint, params) =>
+ endpoint.endsWith("query") ? new Response('{"_msg":"visible message"}\n') : defaultHandler(endpoint, params),
+ )
+ renderWithK8sProvider( , { client })
+
+ await userEvent.type(screen.getByLabelText("LogsQL filter"), "* | fields _msg{Enter}")
+
+ const frame = screen.getByRole("region", { name: "Log lines" })
+ expect(await within(frame).findByText("visible message")).toBeInTheDocument()
+ expect(within(frame).queryByText(/No log lines/)).toBeNull()
+ })
+
it("names the source pod and container of each line", async () => {
const { client } = clientWith(defaultHandler)
diff --git a/packages/system/dashboard/images/console/apps/console/src/lib/observability/logs.test.ts b/packages/system/dashboard/images/console/apps/console/src/lib/observability/logs.test.ts
index 25d26a23a..62d1ac249 100644
--- a/packages/system/dashboard/images/console/apps/console/src/lib/observability/logs.test.ts
+++ b/packages/system/dashboard/images/console/apps/console/src/lib/observability/logs.test.ts
@@ -57,6 +57,12 @@ describe("mergeTail", () => {
expect(out).toHaveLength(2)
})
+ it("never deduplicates lines without _time, even on a resume", () => {
+ const out = mergeTail([{ _msg: "a" }], [{ _msg: "a" }], 10, "2026-01-01T00:00:02Z")
+
+ expect(out).toHaveLength(2)
+ })
+
it("does not deduplicate outside a resume", () => {
const out = mergeTail([e("t1", "a")], [e("t1", "a")], 10)
diff --git a/packages/system/dashboard/images/console/apps/console/src/lib/observability/logs.ts b/packages/system/dashboard/images/console/apps/console/src/lib/observability/logs.ts
index a6255e541..eb24a5f96 100644
--- a/packages/system/dashboard/images/console/apps/console/src/lib/observability/logs.ts
+++ b/packages/system/dashboard/images/console/apps/console/src/lib/observability/logs.ts
@@ -61,12 +61,13 @@ export function compareTime(a: string, b: string): number {
const entryKey = (e: LogEntry) => `${e._stream_id ?? ""}\u0000${e._time}`
// (_stream_id, _time) is not unique in VictoriaLogs, so dedup applies only to
-// lines a resumed tail replays at or before the resume point.
+// lines a resumed tail replays at or before the resume point, and never to
+// lines a pipe stripped of _time.
export function mergeTail(buffer: LogEntry[], incoming: LogEntry[], cap: number, resumedFrom?: string): LogEntry[] {
let fresh = incoming
if (resumedFrom) {
const seen = new Set(buffer.map(entryKey))
- fresh = incoming.filter((e) => compareTime(e._time, resumedFrom) > 0 || !seen.has(entryKey(e)))
+ fresh = incoming.filter((e) => e._time === undefined || compareTime(e._time, resumedFrom) > 0 || !seen.has(entryKey(e)))
}
const merged = buffer.concat(fresh)
return merged.length > cap ? merged.slice(merged.length - cap) : merged
diff --git a/packages/system/dashboard/images/console/apps/console/src/lib/observability/proxy.test.ts b/packages/system/dashboard/images/console/apps/console/src/lib/observability/proxy.test.ts
index 2809905d8..f2ba8d7c3 100644
--- a/packages/system/dashboard/images/console/apps/console/src/lib/observability/proxy.test.ts
+++ b/packages/system/dashboard/images/console/apps/console/src/lib/observability/proxy.test.ts
@@ -122,6 +122,15 @@ describe("queryLogs", () => {
expect(entries.map((e) => e._msg)).toEqual(["a", "b"])
})
+ it("keeps rows a pipe stripped of _time, in the order the store sent them", async () => {
+ const ndjson = ['{"_msg":"visible message"}', '{"_msg":"second"}', "[1]", "null", "{torn"].join("\n")
+ const { client } = clientReturning(new Response(ndjson))
+
+ const entries = await queryLogs(client, logsRoot(ns), { query: "* | fields _msg", start: "s", end: "e", limit: 100 })
+
+ expect(entries).toEqual([{ _msg: "visible message" }, { _msg: "second" }])
+ })
+
it("keeps a plain-text error body as the message", async () => {
const { client } = clientReturning(new Response("cannot parse query", { status: 400 }))
@@ -170,7 +179,7 @@ describe("tailLogs", () => {
},
})
const { client, raw } = clientReturning(new Response(body))
- const seen: string[] = []
+ const seen: (string | undefined)[] = []
await tailLogs(client, logsRoot(ns), { query: "*", since: "t0" }, (e) => seen.push(e._msg))
@@ -179,6 +188,15 @@ describe("tailLogs", () => {
expect(seen).toEqual(["a", "b"])
})
+ it("delivers a line without _time", async () => {
+ const { client } = clientReturning(new Response('{"_msg":"untimed"}\n'))
+ const seen: (string | undefined)[] = []
+
+ await tailLogs(client, logsRoot(ns), { query: "* | fields _msg" }, (e) => seen.push(e._msg))
+
+ expect(seen).toEqual(["untimed"])
+ })
+
it("omits since on the first connect", async () => {
const { client, raw } = clientReturning(new Response(""))
diff --git a/packages/system/dashboard/images/console/apps/console/src/lib/observability/proxy.ts b/packages/system/dashboard/images/console/apps/console/src/lib/observability/proxy.ts
index 3b5567f6b..c28bd12d4 100644
--- a/packages/system/dashboard/images/console/apps/console/src/lib/observability/proxy.ts
+++ b/packages/system/dashboard/images/console/apps/console/src/lib/observability/proxy.ts
@@ -140,9 +140,10 @@ export async function queryRange(
return body.data?.result ?? []
}
+// A pipe such as `fields _msg` or `stats` can drop _time and _msg.
export interface LogEntry {
- _time: string
- _msg: string
+ _time?: string
+ _msg?: string
_stream_id?: string
[field: string]: string | undefined
}
@@ -151,7 +152,7 @@ function parseLine(line: string): LogEntry | null {
if (!line.trim()) return null
try {
const value: unknown = JSON.parse(line)
- if (value && typeof value === "object" && "_time" in value) return value as LogEntry
+ if (value && typeof value === "object" && !Array.isArray(value)) return value as LogEntry
} catch {
// a torn or non-JSON line carries nothing to show
}
@@ -173,7 +174,8 @@ export async function queryLogs(
): Promise {
const res = await proxyGet(client, `${root}select/logsql/query`, { ...params }, signal)
const entries = (await res.text()).split("\n").map(parseLine).filter((e) => e !== null)
- return entries.sort((a, b) => compareTime(a._time, b._time))
+ if (entries.some((e) => e._time === undefined)) return entries
+ return entries.sort((a, b) => compareTime(a._time ?? "", b._time ?? ""))
}
export interface FieldValuesParams {
diff --git a/packages/system/dashboard/images/console/apps/console/src/lib/observability/use-log-tail.ts b/packages/system/dashboard/images/console/apps/console/src/lib/observability/use-log-tail.ts
index 2e3b4d706..d55bd5708 100644
--- a/packages/system/dashboard/images/console/apps/console/src/lib/observability/use-log-tail.ts
+++ b/packages/system/dashboard/images/console/apps/console/src/lib/observability/use-log-tail.ts
@@ -73,7 +73,7 @@ export function useLogTail(
let delay = retryDelayMs
try {
await tailLogs(client, root, { query, since: lastTime ?? openedAt }, (entry) => {
- if (!lastTime || compareTime(entry._time, lastTime) > 0) lastTime = entry._time
+ if (entry._time && (!lastTime || compareTime(entry._time, lastTime) > 0)) lastTime = entry._time
pending.push(entry)
timer ??= setTimeout(flush, FLUSH_MS)
}, signal, () => {
From 8e6048eb4a2556cc9af587b4df3259cface49b37 Mon Sep 17 00:00:00 2001
From: ZverGuy
Date: Thu, 5 Nov 2026 00:16:04 +0700
Subject: [PATCH 28/46] fix(dashboard): make metric samples readable without a
pointer
The charts are a canvas and their legend showed dashes until a point
was hovered, so keyboard and screen-reader users could not read any
sample. The legend now shows each series' latest value when nothing is
hovered, and every panel has a Show data toggle that opens a focusable
table of all samples, newest first, in the chart's units.
Assisted-by: LLM
Signed-off-by: ZverGuy
---
.../observability/MetricsView.test.tsx | 27 ++++++++++-
.../components/observability/MetricsView.tsx | 36 ++++++++++++--
.../observability/SeriesTable.test.tsx | 37 +++++++++++++++
.../components/observability/SeriesTable.tsx | 47 +++++++++++++++++++
.../observability/TimeSeriesChart.test.tsx | 17 ++++++-
.../observability/TimeSeriesChart.tsx | 4 +-
6 files changed, 160 insertions(+), 8 deletions(-)
create mode 100644 packages/system/dashboard/images/console/apps/console/src/components/observability/SeriesTable.test.tsx
create mode 100644 packages/system/dashboard/images/console/apps/console/src/components/observability/SeriesTable.tsx
diff --git a/packages/system/dashboard/images/console/apps/console/src/components/observability/MetricsView.test.tsx b/packages/system/dashboard/images/console/apps/console/src/components/observability/MetricsView.test.tsx
index d3f1fc1dd..8e7829ed5 100644
--- a/packages/system/dashboard/images/console/apps/console/src/components/observability/MetricsView.test.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/components/observability/MetricsView.test.tsx
@@ -1,5 +1,5 @@
import { describe, it, expect, vi } from "vitest"
-import { screen, waitFor } from "@testing-library/react"
+import { screen, waitFor, within } from "@testing-library/react"
import userEvent from "@testing-library/user-event"
import { K8sClient } from "@cozystack/k8s-client"
import { renderWithK8sProvider } from "../../test-utils/render.tsx"
@@ -98,6 +98,31 @@ describe("MetricsView", () => {
expect(screen.queryByText("Try a longer range.")).toBeNull()
})
+ it("shows a panel's samples as a table on request", async () => {
+ const { client } = clientWith(() => matrix("db-0"))
+ renderWithK8sProvider( , { client })
+ await waitFor(() => expect(screen.getAllByTestId("chart")).toHaveLength(3))
+ const toggle = screen.getByRole("button", { name: "Show data for CPU (cores)" })
+ expect(toggle).toHaveAttribute("aria-expanded", "false")
+
+ await userEvent.click(toggle)
+
+ const table = screen.getByRole("region", { name: "CPU (cores) data" })
+ expect(toggle).toHaveAttribute("aria-expanded", "true")
+ expect(toggle).toHaveAttribute("aria-controls", table.id)
+ expect(toggle).toHaveTextContent("Hide data")
+ expect(within(table).getByRole("columnheader", { name: "db-0" })).toBeInTheDocument()
+ expect(screen.queryByRole("region", { name: "Memory (working set) data" })).toBeNull()
+ })
+
+ it("offers no table while a panel has no samples", () => {
+ const { client } = clientWith(() => new Promise(() => {}))
+
+ renderWithK8sProvider( , { client })
+
+ expect(screen.getByRole("button", { name: "Show data for Network" })).toBeDisabled()
+ })
+
it("holds each chart's place while it loads", () => {
const { client } = clientWith(() => new Promise(() => {}))
diff --git a/packages/system/dashboard/images/console/apps/console/src/components/observability/MetricsView.tsx b/packages/system/dashboard/images/console/apps/console/src/components/observability/MetricsView.tsx
index fac2a6b91..4663b2ae3 100644
--- a/packages/system/dashboard/images/console/apps/console/src/components/observability/MetricsView.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/components/observability/MetricsView.tsx
@@ -1,7 +1,7 @@
-import { useState } from "react"
+import { useId, useState } from "react"
import { useQueries } from "@tanstack/react-query"
import { useK8sClient } from "@cozystack/k8s-client"
-import { Section } from "@cozystack/ui"
+import { Button, Section } from "@cozystack/ui"
import {
METRIC_PANELS,
RANGES,
@@ -14,6 +14,7 @@ import { ProxyNotice } from "./ProxyNotice.tsx"
import { TimeSeriesChart } from "./TimeSeriesChart.tsx"
import { RangePicker } from "./RangePicker.tsx"
import { EmptyState } from "./EmptyState.tsx"
+import { SeriesTable } from "./SeriesTable.tsx"
const REFRESH_MS = 60_000
// The uPlot canvas plus its one-row legend, so a placeholder takes the chart's place without a jump.
@@ -23,6 +24,8 @@ export function MetricsView({ scope }: { scope: ObservabilityScope }) {
const client = useK8sClient()
const root = metricsRoot(scope)
const [range, setRange] = useState("1h")
+ const [tables, setTables] = useState>(new Set())
+ const idBase = useId()
const rangeKeys = Object.keys(RANGES) as RangeKey[]
const longestRange = range === rangeKeys[rangeKeys.length - 1]
@@ -57,8 +60,30 @@ export function MetricsView({ scope }: { scope: ObservabilityScope }) {
) : (
METRIC_PANELS.map((panel, i) => {
const { data, error, isLoading } = results[i]
+ const hasSeries = !error && !isLoading && !!data && data.series.length > 0
+ const tableOpen = hasSeries && tables.has(panel.id)
+ const tableId = `${idBase}-${panel.id}-data`
+ const toggle = (
+
+ setTables((prev) => {
+ const next = new Set(prev)
+ if (!next.delete(panel.id)) next.add(panel.id)
+ return next
+ })
+ }
+ >
+ {tableOpen ? "Hide data" : "Show data"}{" "}
+ for {panel.title}
+
+ )
return (
-
+
{error ? (
) : isLoading || !data ? (
@@ -66,7 +91,10 @@ export function MetricsView({ scope }: { scope: ObservabilityScope }) {
) : data.series.length === 0 ? (
) : (
-
+ <>
+
+ {tableOpen && }
+ >
)}
)
diff --git a/packages/system/dashboard/images/console/apps/console/src/components/observability/SeriesTable.test.tsx b/packages/system/dashboard/images/console/apps/console/src/components/observability/SeriesTable.test.tsx
new file mode 100644
index 000000000..0b3364268
--- /dev/null
+++ b/packages/system/dashboard/images/console/apps/console/src/components/observability/SeriesTable.test.tsx
@@ -0,0 +1,37 @@
+import { describe, it, expect } from "vitest"
+import { render, screen, within } from "@testing-library/react"
+import { SeriesTable } from "./SeriesTable.tsx"
+
+const data = {
+ timestamps: [1_700_000_000, 1_700_000_060],
+ series: [
+ { label: "db-0", values: [1, 2] },
+ { label: "db-1", values: [null, 3] },
+ ],
+}
+
+describe("SeriesTable", () => {
+ it("is a named region the keyboard can reach", () => {
+ render( )
+
+ const region = screen.getByRole("region", { name: "Memory data" })
+ expect(region).toHaveAttribute("id", "t")
+ expect(region).toHaveAttribute("tabindex", "0")
+ })
+
+ it("has a time column and one column per series", () => {
+ render( )
+
+ expect(screen.getAllByRole("columnheader").map((h) => h.textContent)).toEqual(["Time", "db-0", "db-1"])
+ })
+
+ it("lists every sample newest first in the chart's units", () => {
+ render( `${v} B`} />)
+
+ const rows = screen.getAllByRole("row").slice(1)
+ expect(rows).toHaveLength(2)
+ expect(within(rows[0]).getAllByRole("cell").map((c) => c.textContent)).toEqual(["2 B", "3 B"])
+ expect(within(rows[1]).getAllByRole("cell").map((c) => c.textContent)).toEqual(["1 B", "–"])
+ expect(within(rows[0]).getByRole("rowheader")).toHaveTextContent(new Date(1_700_000_060_000).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }))
+ })
+})
diff --git a/packages/system/dashboard/images/console/apps/console/src/components/observability/SeriesTable.tsx b/packages/system/dashboard/images/console/apps/console/src/components/observability/SeriesTable.tsx
new file mode 100644
index 000000000..57cf755a0
--- /dev/null
+++ b/packages/system/dashboard/images/console/apps/console/src/components/observability/SeriesTable.tsx
@@ -0,0 +1,47 @@
+import type { ChartData } from "../../lib/observability/metrics.ts"
+
+interface SeriesTableProps {
+ id: string
+ title: string
+ data: ChartData
+ format: (value: number) => string
+}
+
+const formatTime = (seconds: number) =>
+ new Date(seconds * 1000).toLocaleString([], { month: "short", day: "numeric", hour: "2-digit", minute: "2-digit" })
+
+export function SeriesTable({ id, title, data, format }: SeriesTableProps) {
+ const newestFirst = data.timestamps.map((t, i) => ({ t, i })).reverse()
+ return (
+
+
+ {`${title}, newest first`}
+
+
+ Time
+ {data.series.map((s, j) => (
+ {s.label}
+ ))}
+
+
+
+ {newestFirst.map(({ t, i }) => (
+
+ {formatTime(t)}
+ {data.series.map((s, j) => {
+ const v = s.values[i]
+ return {v === null ? "–" : format(v)}
+ })}
+
+ ))}
+
+
+
+ )
+}
diff --git a/packages/system/dashboard/images/console/apps/console/src/components/observability/TimeSeriesChart.test.tsx b/packages/system/dashboard/images/console/apps/console/src/components/observability/TimeSeriesChart.test.tsx
index 57cf6fb99..3df8125e3 100644
--- a/packages/system/dashboard/images/console/apps/console/src/components/observability/TimeSeriesChart.test.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/components/observability/TimeSeriesChart.test.tsx
@@ -1,12 +1,15 @@
import { describe, it, expect, vi, beforeEach } from "vitest"
import { render } from "@testing-library/react"
-const created: { opts: { series: { label?: string }[] }; data: unknown[]; destroy: ReturnType }[] = []
+type LegendValue = (u: unknown, v: number | null, sidx: number, idx: number | null) => string
+type Opts = { series: { label?: string; value?: LegendValue }[] }
+
+const created: { opts: Opts; data: unknown[]; destroy: ReturnType }[] = []
vi.mock("uplot", () => ({
default: class {
destroy = vi.fn()
- constructor(opts: { series: { label?: string }[] }, data: unknown[]) {
+ constructor(opts: Opts, data: unknown[]) {
created.push({ opts, data, destroy: this.destroy })
}
setSize() {}
@@ -36,6 +39,16 @@ describe("TimeSeriesChart", () => {
expect(created[0].opts.series.slice(1).map((s) => s.label)).toEqual(["db-0", "db-1"])
})
+ it("shows each series' latest value in the legend while nothing is hovered", () => {
+ render( `${v} B`} />)
+
+ const legend = created[0].opts.series[1].value!
+
+ expect(legend(null, null, 1, null)).toBe("2 B")
+ expect(legend(null, 1, 1, 0)).toBe("1 B")
+ expect(legend(null, null, 1, 2)).toBe("–")
+ })
+
it("destroys the chart on unmount", () => {
const { unmount } = render( )
diff --git a/packages/system/dashboard/images/console/apps/console/src/components/observability/TimeSeriesChart.tsx b/packages/system/dashboard/images/console/apps/console/src/components/observability/TimeSeriesChart.tsx
index 683df2dff..a6251d40f 100644
--- a/packages/system/dashboard/images/console/apps/console/src/components/observability/TimeSeriesChart.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/components/observability/TimeSeriesChart.tsx
@@ -18,6 +18,7 @@ export function TimeSeriesChart({ data, format }: TimeSeriesChartProps) {
const el = ref.current
if (!el) return
const fmt = (v: number | null) => (v === null ? "–" : format(v))
+ const latest = data.series.map((s) => s.values.findLast((v) => v !== null) ?? null)
const chart = new uPlot(
{
width: el.clientWidth || 600,
@@ -30,7 +31,8 @@ export function TimeSeriesChart({ data, format }: TimeSeriesChartProps) {
label: s.label,
stroke: COLORS[i % COLORS.length],
width: 1.5,
- value: (_: uPlot, v: number | null) => fmt(v),
+ // Without a hovered point the legend shows the latest sample instead of a dash.
+ value: (_: uPlot, v: number | null, sidx: number, idx: number | null) => fmt(idx === null ? latest[sidx - 1] : v),
})),
],
axes: [{}, { size: 84, values: (_: uPlot, splits: number[]) => splits.map(format) }],
From e65d827cf9eca51f742200e76172b62224003871 Mon Sep 17 00:00:00 2001
From: ZverGuy
Date: Thu, 5 Nov 2026 00:16:49 +0700
Subject: [PATCH 29/46] fix(dashboard): move the tenant logs page under
observability/
The fixed /console/logs route came before the generic :plural route,
so an application kind with the plural "logs" would have its list page
replaced by the logs page. A two-segment path cannot shadow an
application list, the same way the backups and migration pages avoid
it.
Assisted-by: LLM
Signed-off-by: ZverGuy
---
.../src/routes/ConsolePage.routing.test.tsx | 24 +++++++++++++++++++
.../apps/console/src/routes/ConsolePage.tsx | 2 +-
.../src/routes/sidebar-sections.test.tsx | 2 +-
.../console/src/routes/sidebar-sections.tsx | 2 +-
4 files changed, 27 insertions(+), 3 deletions(-)
diff --git a/packages/system/dashboard/images/console/apps/console/src/routes/ConsolePage.routing.test.tsx b/packages/system/dashboard/images/console/apps/console/src/routes/ConsolePage.routing.test.tsx
index 7c6d1209c..cf6982823 100644
--- a/packages/system/dashboard/images/console/apps/console/src/routes/ConsolePage.routing.test.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/routes/ConsolePage.routing.test.tsx
@@ -70,4 +70,28 @@ describe("ConsolePage routing", () => {
await waitFor(() => expect(client.list).toHaveBeenCalled())
expect(screen.queryByText(/Cluster-scoped capacity/i)).toBeNull()
})
+
+ it("serves the tenant logs page under observability/", async () => {
+ renderWithK8sProvider(
+
+
+ ,
+ { client: makeClient(), initialRoute: "/observability/logs" },
+ )
+
+ expect(await screen.findByText(/^Every application in/)).toBeInTheDocument()
+ })
+
+ it("leaves /logs to an application kind whose plural is logs", async () => {
+ const client = makeClient()
+ renderWithK8sProvider(
+
+
+ ,
+ { client, initialRoute: "/logs" },
+ )
+
+ await waitFor(() => expect(client.list).toHaveBeenCalled())
+ expect(screen.queryByText(/^Every application in/)).toBeNull()
+ })
})
diff --git a/packages/system/dashboard/images/console/apps/console/src/routes/ConsolePage.tsx b/packages/system/dashboard/images/console/apps/console/src/routes/ConsolePage.tsx
index 5e204e84f..2b2aed3e4 100644
--- a/packages/system/dashboard/images/console/apps/console/src/routes/ConsolePage.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/routes/ConsolePage.tsx
@@ -97,7 +97,7 @@ export function ConsolePage() {
path="migration/vmimporttasks/:name"
element={ }
/>
- } />
+ } />
} />
} />
} />
diff --git a/packages/system/dashboard/images/console/apps/console/src/routes/sidebar-sections.test.tsx b/packages/system/dashboard/images/console/apps/console/src/routes/sidebar-sections.test.tsx
index da40081bc..1fcc3cde4 100644
--- a/packages/system/dashboard/images/console/apps/console/src/routes/sidebar-sections.test.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/routes/sidebar-sections.test.tsx
@@ -117,7 +117,7 @@ describe("useConsoleSidebarSections — admin areas moved out", () => {
wrapper: makeWrapper(client),
})
await waitFor(() => expect(result.current.length).toBeGreaterThan(0))
- expect(findItem(result.current, "Logs")?.to).toBe("/console/logs")
+ expect(findItem(result.current, "Logs")?.to).toBe("/console/observability/logs")
expect(result.current.find((s) => s.title === "Observability")?.items).toHaveLength(1)
})
})
diff --git a/packages/system/dashboard/images/console/apps/console/src/routes/sidebar-sections.tsx b/packages/system/dashboard/images/console/apps/console/src/routes/sidebar-sections.tsx
index 4cec3a94c..0cf1ce089 100644
--- a/packages/system/dashboard/images/console/apps/console/src/routes/sidebar-sections.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/routes/sidebar-sections.tsx
@@ -121,7 +121,7 @@ export function useConsoleSidebarSections(): SidebarSection[] {
const observabilitySection: SidebarSection = {
title: "Observability",
- items: [{ label: "Logs", to: "/console/logs", icon: ScrollText }],
+ items: [{ label: "Logs", to: "/console/observability/logs", icon: ScrollText }],
}
return [...categorySections, backupsSection, migrationSection, observabilitySection]
From 52087d92dcaae1316463973643ccbeaf37869a43 Mon Sep 17 00:00:00 2001
From: ZverGuy
Date: Thu, 5 Nov 2026 00:18:25 +0700
Subject: [PATCH 30/46] fix(dashboard): keep the logs view when only the pod
list is refused
The pod picker's values query counted as a scope-wide refusal, so a
proxy that refused only that path replaced the whole view, filter and
lines included, with a notice even though the log query itself worked.
A real scope-wide refusal still reaches the history or tail query and
shows the notice from there.
Assisted-by: LLM
Signed-off-by: ZverGuy
---
.../src/components/observability/LogsView.test.tsx | 12 ++++++++++++
.../src/components/observability/LogsView.tsx | 3 ++-
2 files changed, 14 insertions(+), 1 deletion(-)
diff --git a/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.test.tsx b/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.test.tsx
index 770c8a263..86428733d 100644
--- a/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.test.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.test.tsx
@@ -212,6 +212,18 @@ describe("LogsView", () => {
expect(within(frame).queryByText(/No log lines/)).toBeNull()
})
+ it("keeps the view when only the pod list is refused", async () => {
+ const status = JSON.stringify({ kind: "Status", apiVersion: "v1", status: "Failure", code: 404 })
+ const { client } = clientWith((endpoint, params) =>
+ endpoint.endsWith("stream_field_values") ? new Response(status, { status: 404 }) : defaultHandler(endpoint, params),
+ )
+
+ renderWithK8sProvider( , { client })
+
+ expect(await screen.findByText("ready to accept connections")).toBeInTheDocument()
+ expect(screen.queryByText("Logs are not available on this cluster.")).toBeNull()
+ })
+
it("names the source pod and container of each line", async () => {
const { client } = clientWith(defaultHandler)
diff --git a/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.tsx b/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.tsx
index a0a73cc43..c7a1f5d58 100644
--- a/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.tsx
@@ -106,7 +106,8 @@ export function LogsView({ scope }: { scope: ObservabilityScope }) {
})
const tail = useLogTail(root, query, followRun, { cap: FOLLOW_CAP })
- const wide = [pods.error, history.error, tail.error].find(isScopeWide)
+ // The pod list is optional: refusing it alone must not hide lines the query can still read.
+ const wide = [history.error, tail.error].find(isScopeWide)
if (wide) {
return (
From ef7312579d9872272baf407f622dea7e5fd05944 Mon Sep 17 00:00:00 2001
From: ZverGuy
Date: Thu, 5 Nov 2026 00:18:33 +0700
Subject: [PATCH 31/46] fix(dashboard): offer a retry when the log query fails
The console does not refetch on window focus and must not poll, so a
failed history query stayed failed until the filter or range changed,
even after the store recovered. The failed state now has a Retry
button that runs the same query again.
Assisted-by: LLM
Signed-off-by: ZverGuy
---
.../src/components/observability/EmptyState.tsx | 4 +++-
.../src/components/observability/LogsView.test.tsx | 13 +++++++++++++
.../src/components/observability/LogsView.tsx | 14 +++++++++++---
3 files changed, 27 insertions(+), 4 deletions(-)
diff --git a/packages/system/dashboard/images/console/apps/console/src/components/observability/EmptyState.tsx b/packages/system/dashboard/images/console/apps/console/src/components/observability/EmptyState.tsx
index 0cf58224b..5b41ef13d 100644
--- a/packages/system/dashboard/images/console/apps/console/src/components/observability/EmptyState.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/components/observability/EmptyState.tsx
@@ -4,12 +4,13 @@ import { cn, Spinner } from "@cozystack/ui"
interface EmptyStateProps {
title: ReactNode
hint?: ReactNode
+ action?: ReactNode
busy?: boolean
tone?: "light" | "dark"
className?: string
}
-export function EmptyState({ title, hint, busy, tone = "light", className }: EmptyStateProps) {
+export function EmptyState({ title, hint, action, busy, tone = "light", className }: EmptyStateProps) {
const dark = tone === "dark"
return (
}
{title}
{hint && {hint}
}
+ {action && {action}
}
)
}
diff --git a/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.test.tsx b/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.test.tsx
index 86428733d..8b60b7d35 100644
--- a/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.test.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.test.tsx
@@ -224,6 +224,19 @@ describe("LogsView", () => {
expect(screen.queryByText("Logs are not available on this cluster.")).toBeNull()
})
+ it("retries a failed history query on request", async () => {
+ let calls = 0
+ const { client } = clientWith((endpoint, params) =>
+ endpoint.endsWith("query") && calls++ === 0 ? new Response("upstream down", { status: 502 }) : defaultHandler(endpoint, params),
+ )
+ renderWithK8sProvider( , { client })
+
+ await userEvent.click(await screen.findByRole("button", { name: "Retry" }))
+
+ expect(await screen.findByText("ready to accept connections")).toBeInTheDocument()
+ expect(screen.queryByRole("button", { name: "Retry" })).toBeNull()
+ })
+
it("names the source pod and container of each line", async () => {
const { client } = clientWith(defaultHandler)
diff --git a/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.tsx b/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.tsx
index c7a1f5d58..b8d77003a 100644
--- a/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.tsx
@@ -59,7 +59,7 @@ function Picker({ label, value, options, onChange }: { label: string; value: str
const RANGE_KEYS = Object.keys(LOG_RANGES) as LogRangeKey[]
const LONGEST_RANGE = RANGE_KEYS[RANGE_KEYS.length - 1]
-function placeholderFor({ follow, stopped, loading, failed, longestRange }: { follow: boolean; stopped: boolean; loading: boolean; failed: boolean; longestRange: boolean }) {
+function placeholderFor({ follow, stopped, loading, failed, longestRange, retry }: { follow: boolean; stopped: boolean; loading: boolean; failed: boolean; longestRange: boolean; retry: () => void }) {
if (follow) {
return stopped ? (
@@ -68,7 +68,15 @@ function placeholderFor({ follow, stopped, loading, failed, longestRange }: { fo
)
}
if (loading) return
- if (failed) return
+ if (failed) {
+ return (
+ Retry}
+ />
+ )
+ }
return
}
@@ -154,7 +162,7 @@ export function LogsView({ scope }: { scope: ObservabilityScope }) {
void history.refetch() })}
/>
)
From 7d43c3bcd6470c1282a539e05609e9a96de25067 Mon Sep 17 00:00:00 2001
From: ZverGuy
Date: Thu, 5 Nov 2026 00:18:38 +0700
Subject: [PATCH 32/46] fix(dashboard): open each new log result at its newest
line
The console keeps a query's previous data as placeholder while the next
one loads, so the log list was never remounted between queries. After
a reader scrolled up, a new filter or range opened at the old scroll
offset instead of the newest lines. The list is now keyed on the query
and range as well.
Assisted-by: LLM
Signed-off-by: ZverGuy
---
.../observability/LogsView.test.tsx | 25 ++++++++++++++++---
.../src/components/observability/LogsView.tsx | 3 ++-
2 files changed, 23 insertions(+), 5 deletions(-)
diff --git a/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.test.tsx b/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.test.tsx
index 8b60b7d35..1a703cceb 100644
--- a/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.test.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.test.tsx
@@ -86,13 +86,13 @@ describe("LogsView", () => {
endpoint.endsWith("query") ? new Response("") : defaultHandler(endpoint, params),
)
renderWithK8sProvider( , { client })
- const frame = screen.getByRole("region", { name: "Log lines" })
- expect(await within(frame).findByText("Try a longer range or a broader filter.")).toBeInTheDocument()
+ const frame = () => screen.getByRole("region", { name: "Log lines" })
+ expect(await within(frame()).findByText("Try a longer range or a broader filter.")).toBeInTheDocument()
await userEvent.click(screen.getByRole("button", { name: "24h" }))
- expect(await within(frame).findByText("Try a broader filter.")).toBeInTheDocument()
- expect(within(frame).queryByText(/longer range/)).toBeNull()
+ await waitFor(() => expect(within(frame()).getByText("Try a broader filter.")).toBeInTheDocument())
+ expect(within(frame()).queryByText(/longer range/)).toBeNull()
})
it("shows loading inside the log console", () => {
@@ -237,6 +237,23 @@ describe("LogsView", () => {
expect(screen.queryByRole("button", { name: "Retry" })).toBeNull()
})
+ it("opens a new history result at its newest line, not the old scroll position", async () => {
+ const { client } = clientWith((endpoint, params) =>
+ endpoint.endsWith("query")
+ ? new Response(`${line("2026-11-04T10:00:01Z", `result for ${params.get("query")}`)}\n`)
+ : defaultHandler(endpoint, params),
+ )
+ const { queryClient } = renderWithK8sProvider( , { client })
+ queryClient.setDefaultOptions({ queries: { ...queryClient.getDefaultOptions().queries, placeholderData: (prev: unknown) => prev } })
+ await screen.findByText("result for *")
+ const before = screen.getByRole("list")
+
+ await userEvent.type(screen.getByLabelText("LogsQL filter"), "error{Enter}")
+
+ await screen.findByText("result for error")
+ expect(screen.getByRole("list")).not.toBe(before)
+ })
+
it("names the source pod and container of each line", async () => {
const { client } = clientWith(defaultHandler)
diff --git a/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.tsx b/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.tsx
index b8d77003a..1a25d4229 100644
--- a/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.tsx
@@ -160,7 +160,8 @@ export function LogsView({ scope }: { scope: ObservabilityScope }) {
)}
{error ? : null}
void history.refetch() })}
/>
From 601c9ece3f0ce24792d1dc1f9dce862a6826e876 Mon Sep 17 00:00:00 2001
From: ZverGuy
Date: Thu, 5 Nov 2026 00:18:47 +0700
Subject: [PATCH 33/46] docs(dashboard): note why the metrics panels refresh on
an interval
The console rule against refetchInterval assumes a watch is available,
which holds for Kubernetes lists but not for the proxy's Prometheus
query API. Record the exception so the metrics panels' refresh does
not read as a rule violation.
Assisted-by: LLM
Signed-off-by: ZverGuy
---
packages/system/dashboard/images/console/CLAUDE.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/packages/system/dashboard/images/console/CLAUDE.md b/packages/system/dashboard/images/console/CLAUDE.md
index 96419d118..036e527d6 100644
--- a/packages/system/dashboard/images/console/CLAUDE.md
+++ b/packages/system/dashboard/images/console/CLAUDE.md
@@ -81,6 +81,7 @@ the apiserver checks that user's RBAC.
to a chunked-encoding WATCH against the same `resourceVersion`. Don't
poll. Don't add `refetchInterval`. If you need a one-shot, pass
`{ watch: false }`.
+ The one exception is the metrics panels in `components/observability`: the observability proxy serves the Prometheus query API, which has no watch, so they refresh on a fixed interval instead. Log lines stream through the tail endpoint and are not polled.
4. **Tenant scoping.** Most resources live in `tenant-` namespaces.
Pull the active tenant from `useTenantContext()` — never read the
namespace from a URL param or guess it.
From 046df7fe969f2b0b6d62ced127ed601463d9dfc8 Mon Sep 17 00:00:00 2001
From: ZverGuy
Date: Thu, 5 Nov 2026 00:53:06 +0700
Subject: [PATCH 34/46] fix(dashboard): say the legend shows the latest sample
In the browser the legend's time still read "--" next to the latest
values, and the data table repeated the same minute on every row at
the one-hour range, whose step is 15 seconds. The legend's time now
reads "latest" until a point is hovered, and the table shows seconds.
Assisted-by: LLM
Signed-off-by: ZverGuy
---
.../src/components/observability/SeriesTable.test.tsx | 2 +-
.../src/components/observability/SeriesTable.tsx | 2 +-
.../components/observability/TimeSeriesChart.test.tsx | 10 ++++++++++
.../src/components/observability/TimeSeriesChart.tsx | 3 ++-
4 files changed, 14 insertions(+), 3 deletions(-)
diff --git a/packages/system/dashboard/images/console/apps/console/src/components/observability/SeriesTable.test.tsx b/packages/system/dashboard/images/console/apps/console/src/components/observability/SeriesTable.test.tsx
index 0b3364268..e85041c0a 100644
--- a/packages/system/dashboard/images/console/apps/console/src/components/observability/SeriesTable.test.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/components/observability/SeriesTable.test.tsx
@@ -32,6 +32,6 @@ describe("SeriesTable", () => {
expect(rows).toHaveLength(2)
expect(within(rows[0]).getAllByRole("cell").map((c) => c.textContent)).toEqual(["2 B", "3 B"])
expect(within(rows[1]).getAllByRole("cell").map((c) => c.textContent)).toEqual(["1 B", "–"])
- expect(within(rows[0]).getByRole("rowheader")).toHaveTextContent(new Date(1_700_000_060_000).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }))
+ expect(within(rows[0]).getByRole("rowheader")).toHaveTextContent(new Date(1_700_000_060_000).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit", second: "2-digit" }))
})
})
diff --git a/packages/system/dashboard/images/console/apps/console/src/components/observability/SeriesTable.tsx b/packages/system/dashboard/images/console/apps/console/src/components/observability/SeriesTable.tsx
index 57cf755a0..4cc382781 100644
--- a/packages/system/dashboard/images/console/apps/console/src/components/observability/SeriesTable.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/components/observability/SeriesTable.tsx
@@ -8,7 +8,7 @@ interface SeriesTableProps {
}
const formatTime = (seconds: number) =>
- new Date(seconds * 1000).toLocaleString([], { month: "short", day: "numeric", hour: "2-digit", minute: "2-digit" })
+ new Date(seconds * 1000).toLocaleString([], { month: "short", day: "numeric", hour: "2-digit", minute: "2-digit", second: "2-digit" })
export function SeriesTable({ id, title, data, format }: SeriesTableProps) {
const newestFirst = data.timestamps.map((t, i) => ({ t, i })).reverse()
diff --git a/packages/system/dashboard/images/console/apps/console/src/components/observability/TimeSeriesChart.test.tsx b/packages/system/dashboard/images/console/apps/console/src/components/observability/TimeSeriesChart.test.tsx
index 3df8125e3..13cbe933d 100644
--- a/packages/system/dashboard/images/console/apps/console/src/components/observability/TimeSeriesChart.test.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/components/observability/TimeSeriesChart.test.tsx
@@ -13,6 +13,7 @@ vi.mock("uplot", () => ({
created.push({ opts, data, destroy: this.destroy })
}
setSize() {}
+ static fmtDate = () => (d: Date) => d.toISOString()
},
}))
@@ -49,6 +50,15 @@ describe("TimeSeriesChart", () => {
expect(legend(null, null, 1, 2)).toBe("–")
})
+ it("labels the legend's time as latest while nothing is hovered", () => {
+ render( )
+
+ const time = created[0].opts.series[0].value!
+
+ expect(time(null, null, 0, null)).toBe("latest")
+ expect(time(null, 2, 0, 1)).toBe(new Date(2000).toISOString())
+ })
+
it("destroys the chart on unmount", () => {
const { unmount } = render( )
diff --git a/packages/system/dashboard/images/console/apps/console/src/components/observability/TimeSeriesChart.tsx b/packages/system/dashboard/images/console/apps/console/src/components/observability/TimeSeriesChart.tsx
index a6251d40f..063b42b12 100644
--- a/packages/system/dashboard/images/console/apps/console/src/components/observability/TimeSeriesChart.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/components/observability/TimeSeriesChart.tsx
@@ -19,6 +19,7 @@ export function TimeSeriesChart({ data, format }: TimeSeriesChartProps) {
if (!el) return
const fmt = (v: number | null) => (v === null ? "–" : format(v))
const latest = data.series.map((s) => s.values.findLast((v) => v !== null) ?? null)
+ const stamp = uPlot.fmtDate("{M}/{D}/{YY} {h}:{mm}:{ss} {AA}")
const chart = new uPlot(
{
width: el.clientWidth || 600,
@@ -26,7 +27,7 @@ export function TimeSeriesChart({ data, format }: TimeSeriesChartProps) {
scales: { x: { time: true } },
legend: { live: true },
series: [
- {},
+ { value: (_: uPlot, v: number | null, _sidx: number, idx: number | null) => (idx === null || v === null ? "latest" : stamp(new Date(v * 1000))) },
...data.series.map((s, i) => ({
label: s.label,
stroke: COLORS[i % COLORS.length],
From bfa85e57bfe9a619d6c6bcba31c842171a4d848d Mon Sep 17 00:00:00 2001
From: ZverGuy
Date: Thu, 5 Nov 2026 00:56:26 +0700
Subject: [PATCH 35/46] fix(dashboard): show sample times the same way in
legend and table
The legend used a fixed US date format while the data table used the
reader's locale, so one panel showed the same instant two ways. Both
now use one locale-aware format. A test also pins that the data
toggle stays disabled for a panel with no series or an error.
Assisted-by: LLM
Signed-off-by: ZverGuy
---
.../components/observability/MetricsView.test.tsx | 15 +++++++++++++++
.../src/components/observability/SeriesTable.tsx | 7 ++-----
.../observability/TimeSeriesChart.test.tsx | 4 ++--
.../components/observability/TimeSeriesChart.tsx | 5 ++---
.../apps/console/src/lib/observability/metrics.ts | 4 ++++
5 files changed, 25 insertions(+), 10 deletions(-)
diff --git a/packages/system/dashboard/images/console/apps/console/src/components/observability/MetricsView.test.tsx b/packages/system/dashboard/images/console/apps/console/src/components/observability/MetricsView.test.tsx
index 8e7829ed5..ece4d70ba 100644
--- a/packages/system/dashboard/images/console/apps/console/src/components/observability/MetricsView.test.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/components/observability/MetricsView.test.tsx
@@ -123,6 +123,21 @@ describe("MetricsView", () => {
expect(screen.getByRole("button", { name: "Show data for Network" })).toBeDisabled()
})
+ it("offers no table for a panel with no series or an error", async () => {
+ const { client } = clientWith((url) =>
+ url.searchParams.get("query")?.includes("memory")
+ ? Response.json({ status: "error", error: "too many series" }, { status: 422 })
+ : Response.json({ status: "success", data: { resultType: "matrix", result: [] } }),
+ )
+ renderWithK8sProvider( , { client })
+
+ await screen.findByText("too many series. Choose a shorter range.")
+ await waitFor(() => expect(screen.getAllByText("No data for this range.")).toHaveLength(2))
+ for (const title of ["CPU (cores)", "Memory (working set)", "Network"]) {
+ expect(screen.getByRole("button", { name: `Show data for ${title}` })).toBeDisabled()
+ }
+ })
+
it("holds each chart's place while it loads", () => {
const { client } = clientWith(() => new Promise(() => {}))
diff --git a/packages/system/dashboard/images/console/apps/console/src/components/observability/SeriesTable.tsx b/packages/system/dashboard/images/console/apps/console/src/components/observability/SeriesTable.tsx
index 4cc382781..5e9d88ba1 100644
--- a/packages/system/dashboard/images/console/apps/console/src/components/observability/SeriesTable.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/components/observability/SeriesTable.tsx
@@ -1,4 +1,4 @@
-import type { ChartData } from "../../lib/observability/metrics.ts"
+import { formatSampleTime, type ChartData } from "../../lib/observability/metrics.ts"
interface SeriesTableProps {
id: string
@@ -7,9 +7,6 @@ interface SeriesTableProps {
format: (value: number) => string
}
-const formatTime = (seconds: number) =>
- new Date(seconds * 1000).toLocaleString([], { month: "short", day: "numeric", hour: "2-digit", minute: "2-digit", second: "2-digit" })
-
export function SeriesTable({ id, title, data, format }: SeriesTableProps) {
const newestFirst = data.timestamps.map((t, i) => ({ t, i })).reverse()
return (
@@ -33,7 +30,7 @@ export function SeriesTable({ id, title, data, format }: SeriesTableProps) {
{newestFirst.map(({ t, i }) => (
- {formatTime(t)}
+ {formatSampleTime(t)}
{data.series.map((s, j) => {
const v = s.values[i]
return {v === null ? "–" : format(v)}
diff --git a/packages/system/dashboard/images/console/apps/console/src/components/observability/TimeSeriesChart.test.tsx b/packages/system/dashboard/images/console/apps/console/src/components/observability/TimeSeriesChart.test.tsx
index 13cbe933d..bb76edb5a 100644
--- a/packages/system/dashboard/images/console/apps/console/src/components/observability/TimeSeriesChart.test.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/components/observability/TimeSeriesChart.test.tsx
@@ -13,11 +13,11 @@ vi.mock("uplot", () => ({
created.push({ opts, data, destroy: this.destroy })
}
setSize() {}
- static fmtDate = () => (d: Date) => d.toISOString()
},
}))
const { TimeSeriesChart } = await import("./TimeSeriesChart.tsx")
+const { formatSampleTime } = await import("../../lib/observability/metrics.ts")
beforeEach(() => {
created.length = 0
@@ -56,7 +56,7 @@ describe("TimeSeriesChart", () => {
const time = created[0].opts.series[0].value!
expect(time(null, null, 0, null)).toBe("latest")
- expect(time(null, 2, 0, 1)).toBe(new Date(2000).toISOString())
+ expect(time(null, 2, 0, 1)).toBe(formatSampleTime(2))
})
it("destroys the chart on unmount", () => {
diff --git a/packages/system/dashboard/images/console/apps/console/src/components/observability/TimeSeriesChart.tsx b/packages/system/dashboard/images/console/apps/console/src/components/observability/TimeSeriesChart.tsx
index 063b42b12..607d44593 100644
--- a/packages/system/dashboard/images/console/apps/console/src/components/observability/TimeSeriesChart.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/components/observability/TimeSeriesChart.tsx
@@ -1,7 +1,7 @@
import { useEffect, useRef } from "react"
import uPlot from "uplot"
import "uplot/dist/uPlot.min.css"
-import type { ChartData } from "../../lib/observability/metrics.ts"
+import { formatSampleTime, type ChartData } from "../../lib/observability/metrics.ts"
const COLORS = ["#2563eb", "#16a34a", "#d97706", "#9333ea", "#dc2626", "#0891b2", "#4b5563", "#db2777"]
const HEIGHT = 200
@@ -19,7 +19,6 @@ export function TimeSeriesChart({ data, format }: TimeSeriesChartProps) {
if (!el) return
const fmt = (v: number | null) => (v === null ? "–" : format(v))
const latest = data.series.map((s) => s.values.findLast((v) => v !== null) ?? null)
- const stamp = uPlot.fmtDate("{M}/{D}/{YY} {h}:{mm}:{ss} {AA}")
const chart = new uPlot(
{
width: el.clientWidth || 600,
@@ -27,7 +26,7 @@ export function TimeSeriesChart({ data, format }: TimeSeriesChartProps) {
scales: { x: { time: true } },
legend: { live: true },
series: [
- { value: (_: uPlot, v: number | null, _sidx: number, idx: number | null) => (idx === null || v === null ? "latest" : stamp(new Date(v * 1000))) },
+ { value: (_: uPlot, v: number | null, _sidx: number, idx: number | null) => (idx === null || v === null ? "latest" : formatSampleTime(v)) },
...data.series.map((s, i) => ({
label: s.label,
stroke: COLORS[i % COLORS.length],
diff --git a/packages/system/dashboard/images/console/apps/console/src/lib/observability/metrics.ts b/packages/system/dashboard/images/console/apps/console/src/lib/observability/metrics.ts
index d7182b8d6..2f77e251f 100644
--- a/packages/system/dashboard/images/console/apps/console/src/lib/observability/metrics.ts
+++ b/packages/system/dashboard/images/console/apps/console/src/lib/observability/metrics.ts
@@ -93,6 +93,10 @@ export const METRIC_PANELS: MetricPanel[] = [
},
]
+export function formatSampleTime(seconds: number): string {
+ return new Date(seconds * 1000).toLocaleString([], { month: "short", day: "numeric", hour: "2-digit", minute: "2-digit", second: "2-digit" })
+}
+
export interface ChartSeries {
label: string
values: (number | null)[]
From 311cb1c90b751bcc24cf962e68676a6997680c4d Mon Sep 17 00:00:00 2001
From: ZverGuy
Date: Thu, 5 Nov 2026 06:10:02 +0700
Subject: [PATCH 36/46] fix(dashboard): skip tail dedup for rows without a
stream ID
A pipe such as `delete _stream_id` leaves rows from different streams
that share a timestamp with the same dedup key, so a resumed tail
dropped a record it had never shown. Only rows that still carry both
_stream_id and _time are deduplicated now, as the accepted logs design
specifies.
Assisted-by: LLM
Signed-off-by: ZverGuy
---
.../console/src/lib/observability/logs.test.ts | 18 ++++++++++++++++++
.../apps/console/src/lib/observability/logs.ts | 15 ++++++++++-----
2 files changed, 28 insertions(+), 5 deletions(-)
diff --git a/packages/system/dashboard/images/console/apps/console/src/lib/observability/logs.test.ts b/packages/system/dashboard/images/console/apps/console/src/lib/observability/logs.test.ts
index 62d1ac249..278da6890 100644
--- a/packages/system/dashboard/images/console/apps/console/src/lib/observability/logs.test.ts
+++ b/packages/system/dashboard/images/console/apps/console/src/lib/observability/logs.test.ts
@@ -63,6 +63,24 @@ describe("mergeTail", () => {
expect(out).toHaveLength(2)
})
+ it("never deduplicates lines a pipe stripped of _stream_id, even on a resume", () => {
+ const t = "2026-01-01T00:00:02Z"
+ const buffer = [{ _time: t, _msg: "from stream 1" }]
+
+ const out = mergeTail(buffer, [{ _time: t, _msg: "from stream 2" }], 10, t)
+
+ expect(out.map((x) => x._msg)).toEqual(["from stream 1", "from stream 2"])
+ })
+
+ it("deduplicates only the complete rows of a mixed resume", () => {
+ const t = "2026-01-01T00:00:02Z"
+ const buffer = [e(t, "seen"), { _time: t, _msg: "no stream" }, { _stream_id: "s1", _msg: "no time" }]
+
+ const out = mergeTail(buffer, [e(t, "seen"), { _time: t, _msg: "no stream" }, { _stream_id: "s1", _msg: "no time" }], 10, t)
+
+ expect(out.map((x) => x._msg)).toEqual(["seen", "no stream", "no time", "no stream", "no time"])
+ })
+
it("does not deduplicate outside a resume", () => {
const out = mergeTail([e("t1", "a")], [e("t1", "a")], 10)
diff --git a/packages/system/dashboard/images/console/apps/console/src/lib/observability/logs.ts b/packages/system/dashboard/images/console/apps/console/src/lib/observability/logs.ts
index eb24a5f96..b1005a1cd 100644
--- a/packages/system/dashboard/images/console/apps/console/src/lib/observability/logs.ts
+++ b/packages/system/dashboard/images/console/apps/console/src/lib/observability/logs.ts
@@ -58,16 +58,21 @@ export function compareTime(a: string, b: string): number {
return x < y ? -1 : x > y ? 1 : 0
}
-const entryKey = (e: LogEntry) => `${e._stream_id ?? ""}\u0000${e._time}`
+// Null when a pipe removed either identity field: such a row cannot be told from another stream's.
+const entryKey = (e: LogEntry) =>
+ e._stream_id !== undefined && e._time !== undefined ? `${e._stream_id}\u0000${e._time}` : null
// (_stream_id, _time) is not unique in VictoriaLogs, so dedup applies only to
-// lines a resumed tail replays at or before the resume point, and never to
-// lines a pipe stripped of _time.
+// lines a resumed tail replays at or before the resume point, and only to
+// lines that still carry both fields.
export function mergeTail(buffer: LogEntry[], incoming: LogEntry[], cap: number, resumedFrom?: string): LogEntry[] {
let fresh = incoming
if (resumedFrom) {
- const seen = new Set(buffer.map(entryKey))
- fresh = incoming.filter((e) => e._time === undefined || compareTime(e._time, resumedFrom) > 0 || !seen.has(entryKey(e)))
+ const seen = new Set(buffer.map(entryKey).filter((k) => k !== null))
+ fresh = incoming.filter((e) => {
+ const key = entryKey(e)
+ return key === null || compareTime(e._time ?? "", resumedFrom) > 0 || !seen.has(key)
+ })
}
const merged = buffer.concat(fresh)
return merged.length > cap ? merged.slice(merged.length - cap) : merged
From 9c111b3a95f77731b8296310cfd0d32a431b50d6 Mon Sep 17 00:00:00 2001
From: ZverGuy
Date: Thu, 5 Nov 2026 06:11:34 +0700
Subject: [PATCH 37/46] fix(dashboard): keep placeholder results within one
observability scope
The provider keeps a query's previous result while its key changes, so
switching tenants showed the first tenant's log lines and pod names
under the second tenant's heading until its request returned. Every
observability query now keeps the previous result only while the
proxy root is the same, so a new filter or range still shows the old
lines, but a new tenant or application starts empty. Tests render with
the provider's own query defaults.
Assisted-by: LLM
Signed-off-by: ZverGuy
---
.../observability/LogsView.test.tsx | 49 ++++++++++++++++++-
.../src/components/observability/LogsView.tsx | 3 ++
.../observability/MetricsView.test.tsx | 20 +++++++-
.../components/observability/MetricsView.tsx | 3 +-
.../console/src/lib/observability/proxy.ts | 8 +++
5 files changed, 78 insertions(+), 5 deletions(-)
diff --git a/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.test.tsx b/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.test.tsx
index 1a703cceb..fe73e4164 100644
--- a/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.test.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.test.tsx
@@ -1,7 +1,7 @@
import { describe, it, expect, vi } from "vitest"
-import { screen, waitFor, within } from "@testing-library/react"
+import { render, screen, waitFor, within } from "@testing-library/react"
import userEvent from "@testing-library/user-event"
-import { K8sClient } from "@cozystack/k8s-client"
+import { K8sClient, K8sProvider } from "@cozystack/k8s-client"
import { renderWithK8sProvider } from "../../test-utils/render.tsx"
import { LogsView } from "./LogsView.tsx"
@@ -30,6 +30,51 @@ function defaultHandler(endpoint: string, params?: URLSearchParams): Response |
return new Promise(() => {})
}
+// The provider's own QueryClient keeps the previous result while a key changes; it is
+// shared across tests, so each test below uses namespaces no other test reads.
+function renderWithProductionDefaults(client: K8sClient, namespace: string) {
+ const view = (ns: string) => (
+
+
+
+ )
+ const result = render(view(namespace))
+ return { switchTo: (ns: string) => result.rerender(view(ns)) }
+}
+
+describe("LogsView with the production query defaults", () => {
+ it("drops the previous tenant's lines and pods while the next tenant loads", async () => {
+ const { client } = clientWith((endpoint, params) =>
+ endpoint.includes("/tenant-switch-b/") ? new Promise(() => {}) : defaultHandler(endpoint, params),
+ )
+ const { switchTo } = renderWithProductionDefaults(client, "tenant-switch-a")
+ expect(await screen.findByText("ready to accept connections")).toBeInTheDocument()
+ await userEvent.click(screen.getByRole("combobox", { name: "Pod" }))
+ await screen.findByRole("option", { name: "db-1" })
+ await userEvent.keyboard("{Escape}")
+
+ switchTo("tenant-switch-b")
+
+ const frame = screen.getByRole("region", { name: "Log lines" })
+ expect(within(frame).getByText("Loading log lines…")).toBeInTheDocument()
+ expect(screen.queryByText("ready to accept connections")).toBeNull()
+ await userEvent.click(screen.getByRole("combobox", { name: "Pod" }))
+ expect((await screen.findAllByRole("option")).map((o) => o.textContent)).toEqual(["All"])
+ })
+
+ it("keeps the current lines while a new filter in the same tenant loads", async () => {
+ const { client } = clientWith((endpoint, params) =>
+ endpoint.endsWith("query") && params.get("query") === "slow" ? new Promise(() => {}) : defaultHandler(endpoint, params),
+ )
+ renderWithProductionDefaults(client, "tenant-filter-a")
+ expect(await screen.findByText("ready to accept connections")).toBeInTheDocument()
+
+ await userEvent.type(screen.getByLabelText("LogsQL filter"), "slow{Enter}")
+
+ expect(screen.getByText("ready to accept connections")).toBeInTheDocument()
+ })
+})
+
describe("LogsView", () => {
it("shows recent lines from the application root", async () => {
const { client, raw } = clientWith(defaultHandler)
diff --git a/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.tsx b/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.tsx
index 1a25d4229..c2dc8ca5c 100644
--- a/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.tsx
@@ -14,6 +14,7 @@ import {
import {
fieldValues,
isScopeWide,
+ keepWithinScope,
logsRoot,
queryLogs,
type ObservabilityScope,
@@ -101,6 +102,7 @@ export function LogsView({ scope }: { scope: ObservabilityScope }) {
query: buildLogsQuery({ filter: "", pod: narrowTo }),
...windowFor(range),
}, signal),
+ placeholderData: keepWithinScope(root),
retry: false,
})
const pods = useQuery(pickerQuery(POD_FIELD))
@@ -110,6 +112,7 @@ export function LogsView({ scope }: { scope: ObservabilityScope }) {
queryKey: ["observability", "logs", root, query, range],
queryFn: ({ signal }) => queryLogs(client, root, { query, limit: HISTORY_LIMIT, ...windowFor(range) }, signal),
enabled: !follow,
+ placeholderData: keepWithinScope(root),
retry: false,
})
const tail = useLogTail(root, query, followRun, { cap: FOLLOW_CAP })
diff --git a/packages/system/dashboard/images/console/apps/console/src/components/observability/MetricsView.test.tsx b/packages/system/dashboard/images/console/apps/console/src/components/observability/MetricsView.test.tsx
index ece4d70ba..fccb6f43d 100644
--- a/packages/system/dashboard/images/console/apps/console/src/components/observability/MetricsView.test.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/components/observability/MetricsView.test.tsx
@@ -1,7 +1,7 @@
import { describe, it, expect, vi } from "vitest"
-import { screen, waitFor, within } from "@testing-library/react"
+import { render, screen, waitFor, within } from "@testing-library/react"
import userEvent from "@testing-library/user-event"
-import { K8sClient } from "@cozystack/k8s-client"
+import { K8sClient, K8sProvider } from "@cozystack/k8s-client"
import { renderWithK8sProvider } from "../../test-utils/render.tsx"
import type { ChartData } from "../../lib/observability/metrics.ts"
@@ -138,6 +138,22 @@ describe("MetricsView", () => {
}
})
+ it("drops the previous application's charts while the next one loads, with the production query defaults", async () => {
+ const { client } = clientWith((url) => (url.pathname.includes("/switch-b/") ? new Promise(() => {}) : matrix("db-0")))
+ const view = (name: string) => (
+
+
+
+ )
+ const { rerender } = render(view("switch-a"))
+ await waitFor(() => expect(screen.getAllByTestId("chart")).toHaveLength(3))
+
+ rerender(view("switch-b"))
+
+ expect(screen.queryAllByTestId("chart")).toHaveLength(0)
+ expect(screen.getAllByText("Loading…")).toHaveLength(3)
+ })
+
it("holds each chart's place while it loads", () => {
const { client } = clientWith(() => new Promise(() => {}))
diff --git a/packages/system/dashboard/images/console/apps/console/src/components/observability/MetricsView.tsx b/packages/system/dashboard/images/console/apps/console/src/components/observability/MetricsView.tsx
index 4663b2ae3..07980aacf 100644
--- a/packages/system/dashboard/images/console/apps/console/src/components/observability/MetricsView.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/components/observability/MetricsView.tsx
@@ -9,7 +9,7 @@ import {
toChartData,
type RangeKey,
} from "../../lib/observability/metrics.ts"
-import { isScopeWide, metricsRoot, queryRange, type ObservabilityScope } from "../../lib/observability/proxy.ts"
+import { isScopeWide, keepWithinScope, metricsRoot, queryRange, type ObservabilityScope } from "../../lib/observability/proxy.ts"
import { ProxyNotice } from "./ProxyNotice.tsx"
import { TimeSeriesChart } from "./TimeSeriesChart.tsx"
import { RangePicker } from "./RangePicker.tsx"
@@ -42,6 +42,7 @@ export function MetricsView({ scope }: { scope: ObservabilityScope }) {
)
return toChartData(series)
},
+ placeholderData: keepWithinScope(root),
retry: false,
refetchInterval: REFRESH_MS,
})),
diff --git a/packages/system/dashboard/images/console/apps/console/src/lib/observability/proxy.ts b/packages/system/dashboard/images/console/apps/console/src/lib/observability/proxy.ts
index c28bd12d4..3986c6a3d 100644
--- a/packages/system/dashboard/images/console/apps/console/src/lib/observability/proxy.ts
+++ b/packages/system/dashboard/images/console/apps/console/src/lib/observability/proxy.ts
@@ -20,6 +20,14 @@ export function logsRoot(scope: ObservabilityScope): string {
return app ? `${app}/log/` : `/apis/cozystack.io/v1alpha1/namespaces/${scope.namespace}/logs/`
}
+// The provider keeps a query's previous result while its key changes; across
+// scopes that would show one tenant's or application's data under another.
+// Every observability query key carries its root at index 2.
+export function keepWithinScope(root: string) {
+ return (previous: T | undefined, previousQuery?: { queryKey: readonly unknown[] }): T | undefined =>
+ previousQuery?.queryKey[2] === root ? previous : undefined
+}
+
export type ProxyErrorKind =
| "bad-request"
| "unauthorized"
From 711a82eaaf3b073c4e69b6bca94c235adf9a891f Mon Sep 17 00:00:00 2001
From: ZverGuy
Date: Thu, 5 Nov 2026 06:15:06 +0700
Subject: [PATCH 38/46] refactor(dashboard): drop the scoped placeholder from
metrics panels
useQueries creates a new observer for every new key, so the metrics
panels never carried a previous result across scopes and the scoped
placeholder there did nothing. The switch test for the panels stays
and passes without it; the helper's comment now says which queries it
is for.
Assisted-by: LLM
Signed-off-by: ZverGuy
---
.../console/src/components/observability/MetricsView.tsx | 3 +--
.../console/apps/console/src/lib/observability/proxy.ts | 5 +++--
2 files changed, 4 insertions(+), 4 deletions(-)
diff --git a/packages/system/dashboard/images/console/apps/console/src/components/observability/MetricsView.tsx b/packages/system/dashboard/images/console/apps/console/src/components/observability/MetricsView.tsx
index 07980aacf..4663b2ae3 100644
--- a/packages/system/dashboard/images/console/apps/console/src/components/observability/MetricsView.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/components/observability/MetricsView.tsx
@@ -9,7 +9,7 @@ import {
toChartData,
type RangeKey,
} from "../../lib/observability/metrics.ts"
-import { isScopeWide, keepWithinScope, metricsRoot, queryRange, type ObservabilityScope } from "../../lib/observability/proxy.ts"
+import { isScopeWide, metricsRoot, queryRange, type ObservabilityScope } from "../../lib/observability/proxy.ts"
import { ProxyNotice } from "./ProxyNotice.tsx"
import { TimeSeriesChart } from "./TimeSeriesChart.tsx"
import { RangePicker } from "./RangePicker.tsx"
@@ -42,7 +42,6 @@ export function MetricsView({ scope }: { scope: ObservabilityScope }) {
)
return toChartData(series)
},
- placeholderData: keepWithinScope(root),
retry: false,
refetchInterval: REFRESH_MS,
})),
diff --git a/packages/system/dashboard/images/console/apps/console/src/lib/observability/proxy.ts b/packages/system/dashboard/images/console/apps/console/src/lib/observability/proxy.ts
index 3986c6a3d..d33052f70 100644
--- a/packages/system/dashboard/images/console/apps/console/src/lib/observability/proxy.ts
+++ b/packages/system/dashboard/images/console/apps/console/src/lib/observability/proxy.ts
@@ -20,8 +20,9 @@ export function logsRoot(scope: ObservabilityScope): string {
return app ? `${app}/log/` : `/apis/cozystack.io/v1alpha1/namespaces/${scope.namespace}/logs/`
}
-// The provider keeps a query's previous result while its key changes; across
-// scopes that would show one tenant's or application's data under another.
+// The provider's default keeps a useQuery's previous result while its key
+// changes; across scopes that would show one tenant's or application's data
+// under another. (useQueries starts a new observer per key, so it never does.)
// Every observability query key carries its root at index 2.
export function keepWithinScope(root: string) {
return (previous: T | undefined, previousQuery?: { queryKey: readonly unknown[] }): T | undefined =>
From 89194b4f88e4a7399709a48946419745be7326ec Mon Sep 17 00:00:00 2001
From: ZverGuy
Date: Thu, 5 Nov 2026 06:17:48 +0700
Subject: [PATCH 39/46] fix(dashboard): reset the log filters when the tenant
or app changes
LogsView kept its filter, pod and container across a scope switch, so
the first request for the new tenant still asked for the previous
tenant's pod before the picker fell back to All. The view's state is
now keyed on the proxy root, so a new tenant or application starts
with no filter and All selected.
Assisted-by: LLM
Signed-off-by: ZverGuy
---
.../observability/LogsView.test.tsx | 20 +++++++++++++++++++
.../src/components/observability/LogsView.tsx | 7 ++++++-
2 files changed, 26 insertions(+), 1 deletion(-)
diff --git a/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.test.tsx b/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.test.tsx
index fe73e4164..a0df67c68 100644
--- a/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.test.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.test.tsx
@@ -62,6 +62,26 @@ describe("LogsView with the production query defaults", () => {
expect((await screen.findAllByRole("option")).map((o) => o.textContent)).toEqual(["All"])
})
+ it("starts the next tenant with no filter, pod or container of the previous one", async () => {
+ const { client, raw } = clientWith(defaultHandler)
+ const { switchTo } = renderWithProductionDefaults(client, "tenant-reset-a")
+ await userEvent.type(screen.getByLabelText("LogsQL filter"), "error{Enter}")
+ await userEvent.click(screen.getByRole("combobox", { name: "Pod" }))
+ await userEvent.click(await screen.findByRole("option", { name: "db-1" }))
+ await waitFor(() =>
+ expect(raw.mock.calls.some(([p]) => new URL(p, "http://x").searchParams.get("query") === '{kubernetes_pod_name="db-1"} (error)')).toBe(true),
+ )
+
+ switchTo("tenant-reset-b")
+
+ await waitFor(() => expect(raw.mock.calls.some(([p]) => p.includes("/tenant-reset-b/") && p.includes("select/logsql/query?"))).toBe(true))
+ const first = raw.mock.calls.find(([p]) => p.includes("/tenant-reset-b/") && p.includes("select/logsql/query?"))!
+ expect(new URL(first[0], "http://x").searchParams.get("query")).toBe("*")
+ expect(screen.getByRole("combobox", { name: "Pod" })).toHaveTextContent("All")
+ expect(screen.getByRole("combobox", { name: "Container" })).toHaveTextContent("All")
+ expect(screen.getByLabelText("LogsQL filter")).toHaveValue("")
+ })
+
it("keeps the current lines while a new filter in the same tenant loads", async () => {
const { client } = clientWith((endpoint, params) =>
endpoint.endsWith("query") && params.get("query") === "slow" ? new Promise(() => {}) : defaultHandler(endpoint, params),
diff --git a/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.tsx b/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.tsx
index c2dc8ca5c..8c05a8743 100644
--- a/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.tsx
@@ -81,9 +81,14 @@ function placeholderFor({ follow, stopped, loading, failed, longestRange, retry
return
}
+// Filter, pod and container belong to one scope; a new tenant or application starts clean.
export function LogsView({ scope }: { scope: ObservabilityScope }) {
- const client = useK8sClient()
const root = logsRoot(scope)
+ return
+}
+
+function ScopedLogsView({ root }: { root: string }) {
+ const client = useK8sClient()
const [range, setRange] = useState("1h")
const [draft, setDraft] = useState("")
const [filter, setFilter] = useState("")
From 32a466fb141b27833737fa6bc634f428376ad4ce Mon Sep 17 00:00:00 2001
From: ZverGuy
Date: Thu, 5 Nov 2026 18:10:35 +0700
Subject: [PATCH 40/46] fix(dashboard): scope the logs and metrics tabs to the
selected app
The provider keeps a query's previous result while its key changes, so
while the next application's GET is pending the detail page still holds
the previous instance. The Logs and Metrics tabs took the application
name from that instance, so their proxy root did not change and the
previous application's lines and series stayed under the new heading
until the GET completed.
Take the name from the route instead, which is the identity the user
selected, and cover the pending GET at the route level with the real
page, router and production query defaults.
Assisted-by: LLM
Signed-off-by: ZverGuy
---
...plicationDetailPage.observability.test.tsx | 113 ++++++++++++++++++
.../routes/detail/ApplicationDetailPage.tsx | 4 +-
.../console/src/routes/detail/LogsTab.tsx | 9 +-
.../console/src/routes/detail/MetricsTab.tsx | 9 +-
4 files changed, 125 insertions(+), 10 deletions(-)
create mode 100644 packages/system/dashboard/images/console/apps/console/src/routes/detail/ApplicationDetailPage.observability.test.tsx
diff --git a/packages/system/dashboard/images/console/apps/console/src/routes/detail/ApplicationDetailPage.observability.test.tsx b/packages/system/dashboard/images/console/apps/console/src/routes/detail/ApplicationDetailPage.observability.test.tsx
new file mode 100644
index 000000000..e16bf1665
--- /dev/null
+++ b/packages/system/dashboard/images/console/apps/console/src/routes/detail/ApplicationDetailPage.observability.test.tsx
@@ -0,0 +1,113 @@
+import { describe, it, expect, vi, beforeEach } from "vitest"
+import { act, render, screen, waitFor } from "@testing-library/react"
+import { createMemoryRouter, RouterProvider } from "react-router"
+import { K8sProvider } from "@cozystack/k8s-client"
+import { TenantContext, type TenantContextValue } from "../../lib/tenant-context.tsx"
+import type { ChartData } from "../../lib/observability/metrics.ts"
+
+// Keep the consoles' and the chart's browser-only libraries out of jsdom; the
+// Logs and Metrics tabs, the page and the providers stay real.
+vi.mock("./VncTab.tsx", () => ({ VncTab: () => null }))
+vi.mock("./SerialTab.tsx", () => ({ SerialTab: () => null }))
+vi.mock("../../components/observability/TimeSeriesChart.tsx", () => ({
+ TimeSeriesChart: ({ data }: { data: ChartData }) => (
+ {data.series.map((s) => s.label).join(",")}
+ ),
+}))
+
+const { ApplicationDetailPage } = await import("./ApplicationDetailPage.tsx")
+
+const NS = "tenant-test"
+const APPS = `/apis/apps.cozystack.io/v1alpha1/namespaces/${NS}/postgreses`
+
+const tenant: TenantContextValue = {
+ tenants: [],
+ selectedTenant: "test",
+ selectTenant: () => {},
+ tenantNamespace: NS,
+ isLoading: false,
+ error: null,
+}
+
+const definitions = {
+ items: [{ metadata: { name: "postgres" }, spec: { application: { plural: "postgreses", kind: "Postgres" } } }],
+}
+
+const instance = (name: string) => ({
+ apiVersion: "apps.cozystack.io/v1alpha1",
+ kind: "Postgres",
+ metadata: { name, namespace: NS },
+})
+
+const logLine = (name: string) =>
+ `${JSON.stringify({ _time: "2026-11-04T10:00:01Z", _msg: `${name} is ready`, _stream_id: "s", kubernetes_pod_name: `${name}-0`, kubernetes_container_name: "postgres" })}\n`
+
+const matrix = (name: string) =>
+ Response.json({ status: "success", data: { resultType: "matrix", result: [{ metric: { pod: `${name}-0` }, values: [[1, "1"]] }] } })
+
+// app-b's own GET never answers, so the page keeps the placeholder of app-a
+// that the production query defaults hand it; its proxy reads do answer.
+function handle(url: URL): Response | Promise {
+ const path = url.pathname
+ if (path.endsWith("/applicationdefinitions")) return Response.json(definitions)
+ if (path === `${APPS}/app-a`) return Response.json(instance("app-a"))
+ if (path === `${APPS}/app-b`) return new Promise(() => {})
+ const app = path.match(/\/postgreses\/(app-[ab])\//)?.[1]
+ if (app && path.endsWith("/select/logsql/query")) return new Response(logLine(app))
+ if (app && path.endsWith("/stream_field_values")) return Response.json({ values: [] })
+ if (app && path.includes("/metrics/api/v1/query_range")) return matrix(app)
+ return Response.json({ items: [] })
+}
+
+const fetchMock = vi.fn(async (input: RequestInfo | URL) => handle(new URL(String(input), "http://x")))
+
+function renderAt(path: string) {
+ const router = createMemoryRouter(
+ [{ path: "/console/:plural/:name/*", element: }],
+ { initialEntries: [path] },
+ )
+ // No queryClient: the provider's production defaults keep a query's previous
+ // result while its key changes, which is what exposes the stale instance.
+ render(
+
+
+
+
+ ,
+ )
+ return { go: (to: string) => act(() => router.navigate(to)) }
+}
+
+const requested = (prefix: string) =>
+ fetchMock.mock.calls.some(([input]) => new URL(String(input), "http://x").pathname.startsWith(prefix))
+
+beforeEach(() => {
+ vi.stubGlobal("fetch", fetchMock)
+ fetchMock.mockClear()
+})
+
+describe("ApplicationDetailPage observability while the next application loads", () => {
+ it("shows the selected application's logs, not the previous one's", async () => {
+ const { go } = renderAt("/console/postgreses/app-a/logs")
+ expect(await screen.findByText("app-a is ready")).toBeInTheDocument()
+
+ await go("/console/postgreses/app-b/logs")
+
+ expect(screen.getByRole("heading", { name: "app-b" })).toBeInTheDocument()
+ expect(screen.queryByText("app-a is ready")).toBeNull()
+ await waitFor(() => expect(requested(`${APPS}/app-b/log/`)).toBe(true))
+ expect(await screen.findByText("app-b is ready")).toBeInTheDocument()
+ })
+
+ it("shows the selected application's metrics, not the previous one's", async () => {
+ const { go } = renderAt("/console/postgreses/app-a/metrics")
+ await waitFor(() => expect(screen.getAllByTestId("chart")[0]).toHaveTextContent("app-a-0"))
+
+ await go("/console/postgreses/app-b/metrics")
+
+ expect(screen.getByRole("heading", { name: "app-b" })).toBeInTheDocument()
+ expect(screen.queryAllByText("app-a-0", { exact: false })).toEqual([])
+ await waitFor(() => expect(requested(`${APPS}/app-b/metrics/`)).toBe(true))
+ await waitFor(() => expect(screen.getAllByTestId("chart")[0]).toHaveTextContent("app-b-0"))
+ })
+})
diff --git a/packages/system/dashboard/images/console/apps/console/src/routes/detail/ApplicationDetailPage.tsx b/packages/system/dashboard/images/console/apps/console/src/routes/detail/ApplicationDetailPage.tsx
index ca499aac1..ab68f7c49 100644
--- a/packages/system/dashboard/images/console/apps/console/src/routes/detail/ApplicationDetailPage.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/routes/detail/ApplicationDetailPage.tsx
@@ -273,11 +273,11 @@ export function ApplicationDetailPage() {
path="metrics"
element={
}>
-
+
}
/>
- } />
+ } />
diff --git a/packages/system/dashboard/images/console/apps/console/src/routes/detail/LogsTab.tsx b/packages/system/dashboard/images/console/apps/console/src/routes/detail/LogsTab.tsx
index 4ac5f878d..64cbcc89e 100644
--- a/packages/system/dashboard/images/console/apps/console/src/routes/detail/LogsTab.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/routes/detail/LogsTab.tsx
@@ -1,15 +1,16 @@
-import type { ApplicationDefinition, ApplicationInstance } from "@cozystack/types"
+import type { ApplicationDefinition } from "@cozystack/types"
import { useTenantContext } from "../../lib/tenant-context.tsx"
import { LogsView } from "../../components/observability/LogsView.tsx"
interface LogsTabProps {
ad: ApplicationDefinition
- instance: ApplicationInstance
+ // The route's name: while the next application loads, the page still holds the previous instance.
+ name: string
}
-export function LogsTab({ ad, instance }: LogsTabProps) {
+export function LogsTab({ ad, name }: LogsTabProps) {
const { tenantNamespace } = useTenantContext()
const plural = ad.spec?.application.plural
if (!tenantNamespace || !plural) return null
- return
+ return
}
diff --git a/packages/system/dashboard/images/console/apps/console/src/routes/detail/MetricsTab.tsx b/packages/system/dashboard/images/console/apps/console/src/routes/detail/MetricsTab.tsx
index a928e633d..992cfc89b 100644
--- a/packages/system/dashboard/images/console/apps/console/src/routes/detail/MetricsTab.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/routes/detail/MetricsTab.tsx
@@ -1,15 +1,16 @@
-import type { ApplicationDefinition, ApplicationInstance } from "@cozystack/types"
+import type { ApplicationDefinition } from "@cozystack/types"
import { useTenantContext } from "../../lib/tenant-context.tsx"
import { MetricsView } from "../../components/observability/MetricsView.tsx"
interface MetricsTabProps {
ad: ApplicationDefinition
- instance: ApplicationInstance
+ // The route's name: while the next application loads, the page still holds the previous instance.
+ name: string
}
-export function MetricsTab({ ad, instance }: MetricsTabProps) {
+export function MetricsTab({ ad, name }: MetricsTabProps) {
const { tenantNamespace } = useTenantContext()
const plural = ad.spec?.application.plural
if (!tenantNamespace || !plural) return null
- return
+ return
}
From 2e5a3bd6a7bcbd85f77e1043f782951ce37411cd Mon Sep 17 00:00:00 2001
From: ZverGuy
Date: Mon, 9 Nov 2026 15:47:34 +0700
Subject: [PATCH 41/46] fix(dashboard): keep the tenant logs page off
application URLs
Every console path of one or two segments belongs to an application
list or detail page, so /console/observability/logs took the Overview
of an application named logs whose kind has the plural observability.
Kubernetes names must start with an alphanumeric character, so the
reserved "-" segment cannot collide with any application.
Assisted-by: LLM
Signed-off-by: ZverGuy
---
.../src/routes/ConsolePage.routing.test.tsx | 18 ++++++++++++++++--
.../apps/console/src/routes/ConsolePage.tsx | 2 +-
.../src/routes/sidebar-sections.test.tsx | 2 +-
.../console/src/routes/sidebar-sections.tsx | 2 +-
4 files changed, 19 insertions(+), 5 deletions(-)
diff --git a/packages/system/dashboard/images/console/apps/console/src/routes/ConsolePage.routing.test.tsx b/packages/system/dashboard/images/console/apps/console/src/routes/ConsolePage.routing.test.tsx
index cf6982823..8e71ff98a 100644
--- a/packages/system/dashboard/images/console/apps/console/src/routes/ConsolePage.routing.test.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/routes/ConsolePage.routing.test.tsx
@@ -71,12 +71,12 @@ describe("ConsolePage routing", () => {
expect(screen.queryByText(/Cluster-scoped capacity/i)).toBeNull()
})
- it("serves the tenant logs page under observability/", async () => {
+ it("serves the tenant logs page under the reserved -/ segment", async () => {
renderWithK8sProvider(
,
- { client: makeClient(), initialRoute: "/observability/logs" },
+ { client: makeClient(), initialRoute: "/-/observability/logs" },
)
expect(await screen.findByText(/^Every application in/)).toBeInTheDocument()
@@ -94,4 +94,18 @@ describe("ConsolePage routing", () => {
await waitFor(() => expect(client.list).toHaveBeenCalled())
expect(screen.queryByText(/^Every application in/)).toBeNull()
})
+
+ // No ApplicationDefinition plural or application name can be "-", so only
+ // routes under it are safe from shadowing an application's own pages.
+ it("leaves /observability/logs to an application named logs of kind observability", async () => {
+ renderWithK8sProvider(
+
+
+ ,
+ { client: makeClient(), initialRoute: "/observability/logs" },
+ )
+
+ expect(await screen.findByText("Loading…")).toBeInTheDocument()
+ expect(screen.queryByText(/^Every application in/)).toBeNull()
+ })
})
diff --git a/packages/system/dashboard/images/console/apps/console/src/routes/ConsolePage.tsx b/packages/system/dashboard/images/console/apps/console/src/routes/ConsolePage.tsx
index 2b2aed3e4..c78ae619e 100644
--- a/packages/system/dashboard/images/console/apps/console/src/routes/ConsolePage.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/routes/ConsolePage.tsx
@@ -97,7 +97,7 @@ export function ConsolePage() {
path="migration/vmimporttasks/:name"
element={ }
/>
- } />
+ } />
} />
} />
} />
diff --git a/packages/system/dashboard/images/console/apps/console/src/routes/sidebar-sections.test.tsx b/packages/system/dashboard/images/console/apps/console/src/routes/sidebar-sections.test.tsx
index 1fcc3cde4..e678c7dd4 100644
--- a/packages/system/dashboard/images/console/apps/console/src/routes/sidebar-sections.test.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/routes/sidebar-sections.test.tsx
@@ -117,7 +117,7 @@ describe("useConsoleSidebarSections — admin areas moved out", () => {
wrapper: makeWrapper(client),
})
await waitFor(() => expect(result.current.length).toBeGreaterThan(0))
- expect(findItem(result.current, "Logs")?.to).toBe("/console/observability/logs")
+ expect(findItem(result.current, "Logs")?.to).toBe("/console/-/observability/logs")
expect(result.current.find((s) => s.title === "Observability")?.items).toHaveLength(1)
})
})
diff --git a/packages/system/dashboard/images/console/apps/console/src/routes/sidebar-sections.tsx b/packages/system/dashboard/images/console/apps/console/src/routes/sidebar-sections.tsx
index 0cf1ce089..51c9ea00a 100644
--- a/packages/system/dashboard/images/console/apps/console/src/routes/sidebar-sections.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/routes/sidebar-sections.tsx
@@ -121,7 +121,7 @@ export function useConsoleSidebarSections(): SidebarSection[] {
const observabilitySection: SidebarSection = {
title: "Observability",
- items: [{ label: "Logs", to: "/console/observability/logs", icon: ScrollText }],
+ items: [{ label: "Logs", to: "/console/-/observability/logs", icon: ScrollText }],
}
return [...categorySections, backupsSection, migrationSection, observabilitySection]
From 4be80657beaf164067a0e08675f951452bd8b3dd Mon Sep 17 00:00:00 2001
From: ZverGuy
Date: Tue, 10 Nov 2026 00:41:10 +0700
Subject: [PATCH 42/46] test(dashboard): prove /observability/logs opens the
application page
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
The list page shows the same "Loading…" text as the detail page, so the
previous check could not tell which route matched. A missing instance
makes only the detail page answer with its own name, and the GET it
issues names the plural and the application.
Assisted-by: LLM
Signed-off-by: ZverGuy
---
.../src/routes/ConsolePage.routing.test.tsx | 16 ++++++++++++++--
1 file changed, 14 insertions(+), 2 deletions(-)
diff --git a/packages/system/dashboard/images/console/apps/console/src/routes/ConsolePage.routing.test.tsx b/packages/system/dashboard/images/console/apps/console/src/routes/ConsolePage.routing.test.tsx
index 8e71ff98a..c3b014f4d 100644
--- a/packages/system/dashboard/images/console/apps/console/src/routes/ConsolePage.routing.test.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/routes/ConsolePage.routing.test.tsx
@@ -98,14 +98,26 @@ describe("ConsolePage routing", () => {
// No ApplicationDefinition plural or application name can be "-", so only
// routes under it are safe from shadowing an application's own pages.
it("leaves /observability/logs to an application named logs of kind observability", async () => {
+ const client = makeClient()
+ vi.mocked(client.list).mockImplementation(async (_g, _v, plural) => ({
+ apiVersion: "v1",
+ kind: `${plural}List`,
+ metadata: {},
+ items:
+ plural === "tenantnamespaces"
+ ? [{ apiVersion: "core.cozystack.io/v1alpha1", kind: "TenantNamespace", metadata: { name: "tenant-root" } }]
+ : [],
+ }) as K8sList)
+ const get = vi.spyOn(client, "get").mockRejectedValue(new Error("not found"))
renderWithK8sProvider(
,
- { client: makeClient(), initialRoute: "/observability/logs" },
+ { client, initialRoute: "/observability/logs" },
)
- expect(await screen.findByText("Loading…")).toBeInTheDocument()
+ expect(await screen.findByText(/^Application/)).toHaveTextContent("Application logs not found.")
+ expect(get).toHaveBeenCalledWith(expect.anything(), expect.anything(), "observability", "logs", expect.anything())
expect(screen.queryByText(/^Every application in/)).toBeNull()
})
})
From 7eff63b028cf769fcd1237e9f7fdd3dc568588a9 Mon Sep 17 00:00:00 2001
From: ZverGuy
Date: Tue, 10 Nov 2026 00:51:01 +0700
Subject: [PATCH 43/46] refactor(dashboard): drop the scope-keyed placeholder
from the logs view
The logs view remounts under a key per scope, so its queries start with
no previous result to carry over and the scope check never had anything
to refuse. The key is the one guard, and the tenant-switch tests fail
without it.
Assisted-by: LLM
Signed-off-by: ZverGuy
---
.../console/src/components/observability/LogsView.tsx | 5 +----
.../console/apps/console/src/lib/observability/proxy.ts | 9 ---------
2 files changed, 1 insertion(+), 13 deletions(-)
diff --git a/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.tsx b/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.tsx
index 8c05a8743..05535e12e 100644
--- a/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.tsx
@@ -14,7 +14,6 @@ import {
import {
fieldValues,
isScopeWide,
- keepWithinScope,
logsRoot,
queryLogs,
type ObservabilityScope,
@@ -81,7 +80,7 @@ function placeholderFor({ follow, stopped, loading, failed, longestRange, retry
return
}
-// Filter, pod and container belong to one scope; a new tenant or application starts clean.
+// Filter, pod, container and the lines already read belong to one scope; a new tenant or application starts clean.
export function LogsView({ scope }: { scope: ObservabilityScope }) {
const root = logsRoot(scope)
return
@@ -107,7 +106,6 @@ function ScopedLogsView({ root }: { root: string }) {
query: buildLogsQuery({ filter: "", pod: narrowTo }),
...windowFor(range),
}, signal),
- placeholderData: keepWithinScope(root),
retry: false,
})
const pods = useQuery(pickerQuery(POD_FIELD))
@@ -117,7 +115,6 @@ function ScopedLogsView({ root }: { root: string }) {
queryKey: ["observability", "logs", root, query, range],
queryFn: ({ signal }) => queryLogs(client, root, { query, limit: HISTORY_LIMIT, ...windowFor(range) }, signal),
enabled: !follow,
- placeholderData: keepWithinScope(root),
retry: false,
})
const tail = useLogTail(root, query, followRun, { cap: FOLLOW_CAP })
diff --git a/packages/system/dashboard/images/console/apps/console/src/lib/observability/proxy.ts b/packages/system/dashboard/images/console/apps/console/src/lib/observability/proxy.ts
index d33052f70..c28bd12d4 100644
--- a/packages/system/dashboard/images/console/apps/console/src/lib/observability/proxy.ts
+++ b/packages/system/dashboard/images/console/apps/console/src/lib/observability/proxy.ts
@@ -20,15 +20,6 @@ export function logsRoot(scope: ObservabilityScope): string {
return app ? `${app}/log/` : `/apis/cozystack.io/v1alpha1/namespaces/${scope.namespace}/logs/`
}
-// The provider's default keeps a useQuery's previous result while its key
-// changes; across scopes that would show one tenant's or application's data
-// under another. (useQueries starts a new observer per key, so it never does.)
-// Every observability query key carries its root at index 2.
-export function keepWithinScope(root: string) {
- return (previous: T | undefined, previousQuery?: { queryKey: readonly unknown[] }): T | undefined =>
- previousQuery?.queryKey[2] === root ? previous : undefined
-}
-
export type ProxyErrorKind =
| "bad-request"
| "unauthorized"
From 48f459e103f4b3a3bc6a79e3932160cee659c788 Mon Sep 17 00:00:00 2001
From: ZverGuy
Date: Tue, 10 Nov 2026 00:54:51 +0700
Subject: [PATCH 44/46] fix(dashboard): say the logs are loading while an empty
result stands in
The previous result stays on screen while a new range or filter loads.
When that result was empty, the query reports success, so the view said
no lines matched the range it had not read yet.
Assisted-by: LLM
Signed-off-by: ZverGuy
---
.../components/observability/LogsView.test.tsx | 17 +++++++++++++++++
.../src/components/observability/LogsView.tsx | 2 +-
2 files changed, 18 insertions(+), 1 deletion(-)
diff --git a/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.test.tsx b/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.test.tsx
index a0df67c68..47cbf1c22 100644
--- a/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.test.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.test.tsx
@@ -93,6 +93,23 @@ describe("LogsView with the production query defaults", () => {
expect(screen.getByText("ready to accept connections")).toBeInTheDocument()
})
+
+ it("says it is loading, not that nothing matched, while a longer range replaces an empty one", async () => {
+ const { client } = clientWith((endpoint, params) => {
+ if (!endpoint.endsWith("query")) return defaultHandler(endpoint, params)
+ return Date.parse(params.get("start") ?? "") < Date.now() - 2 * 3600_000
+ ? new Promise(() => {})
+ : new Response("")
+ })
+ renderWithProductionDefaults(client, "tenant-range-a")
+ const frame = () => screen.getByRole("region", { name: "Log lines" })
+ expect(await within(frame()).findByText("No log lines for this range and filter.")).toBeInTheDocument()
+
+ await userEvent.click(screen.getByRole("button", { name: "24h" }))
+
+ await waitFor(() => expect(within(frame()).getByRole("status")).toHaveAttribute("aria-busy", "true"))
+ expect(within(frame()).queryByText("No log lines for this range and filter.")).toBeNull()
+ })
})
describe("LogsView", () => {
diff --git a/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.tsx b/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.tsx
index 05535e12e..1563d90b5 100644
--- a/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.tsx
@@ -168,7 +168,7 @@ function ScopedLogsView({ root }: { root: string }) {
// Previous results stay as placeholder data while a new query loads, so only a new key resets the scroll pin.
key={followRun ?? `history\n${query}\n${range}`}
entries={entries}
- placeholder={placeholderFor({ follow, stopped: tail.state === "stopped", loading: history.isLoading, failed: Boolean(error), longestRange: range === LONGEST_RANGE, retry: () => void history.refetch() })}
+ placeholder={placeholderFor({ follow, stopped: tail.state === "stopped", loading: history.isLoading || (history.isPlaceholderData && history.isFetching), failed: Boolean(error), longestRange: range === LONGEST_RANGE, retry: () => void history.refetch() })}
/>
)
From 051442b3187abbe0eb73e21924ee1eebd1b1e701 Mon Sep 17 00:00:00 2001
From: ZverGuy
Date: Tue, 10 Nov 2026 00:58:29 +0700
Subject: [PATCH 45/46] fix(dashboard): mark previous log lines while a new
query replaces them
The previous result stays on screen while a new range or filter loads,
with nothing saying those lines answer the old query. A status line now
says so until the new result arrives. The empty case reads a placeholder
as loading whether or not the request is in flight, so a paused query
does not claim that nothing matched either.
Assisted-by: LLM
Signed-off-by: ZverGuy
---
.../observability/LogsView.test.tsx | 31 +++++++++++++++++++
.../src/components/observability/LogsView.tsx | 7 ++++-
2 files changed, 37 insertions(+), 1 deletion(-)
diff --git a/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.test.tsx b/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.test.tsx
index 47cbf1c22..be8bff1a8 100644
--- a/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.test.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.test.tsx
@@ -110,6 +110,22 @@ describe("LogsView with the production query defaults", () => {
await waitFor(() => expect(within(frame()).getByRole("status")).toHaveAttribute("aria-busy", "true"))
expect(within(frame()).queryByText("No log lines for this range and filter.")).toBeNull()
})
+
+ it("marks the lines of the previous range as standing in while a longer range loads", async () => {
+ const { client } = clientWith((endpoint, params) =>
+ endpoint.endsWith("query") && Date.parse(params.get("start") ?? "") < Date.now() - 2 * 3600_000
+ ? new Promise(() => {})
+ : defaultHandler(endpoint, params),
+ )
+ renderWithProductionDefaults(client, "tenant-range-b")
+ expect(await screen.findByText("ready to accept connections")).toBeInTheDocument()
+ expect(screen.queryByText(/previous lines/)).toBeNull()
+
+ await userEvent.click(screen.getByRole("button", { name: "24h" }))
+
+ expect(await screen.findByText(/previous lines/)).toHaveAttribute("aria-busy", "true")
+ expect(screen.getByText("ready to accept connections")).toBeInTheDocument()
+ })
})
describe("LogsView", () => {
@@ -319,6 +335,21 @@ describe("LogsView", () => {
expect(screen.queryByRole("button", { name: "Retry" })).toBeNull()
})
+ it("says it is loading while a retry runs", async () => {
+ let calls = 0
+ const { client } = clientWith((endpoint, params) => {
+ if (!endpoint.endsWith("query")) return defaultHandler(endpoint, params)
+ return calls++ === 0 ? new Response("upstream down", { status: 502 }) : new Promise(() => {})
+ })
+ renderWithK8sProvider( , { client })
+
+ await userEvent.click(await screen.findByRole("button", { name: "Retry" }))
+
+ const frame = screen.getByRole("region", { name: "Log lines" })
+ await waitFor(() => expect(within(frame).getByRole("status")).toHaveAttribute("aria-busy", "true"))
+ expect(within(frame).queryByRole("button", { name: "Retry" })).toBeNull()
+ })
+
it("opens a new history result at its newest line, not the old scroll position", async () => {
const { client } = clientWith((endpoint, params) =>
endpoint.endsWith("query")
diff --git a/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.tsx b/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.tsx
index 1563d90b5..a4376df47 100644
--- a/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.tsx
@@ -163,12 +163,17 @@ function ScopedLogsView({ root }: { root: string }) {
{` · newest ${FOLLOW_CAP} lines kept`}
)}
+ {!follow && history.isPlaceholderData && entries.length > 0 && (
+
+ Showing the previous lines until the new range or filter loads…
+
+ )}
{error ? : null}
void history.refetch() })}
+ placeholder={placeholderFor({ follow, stopped: tail.state === "stopped", loading: history.isLoading || history.isPlaceholderData, failed: Boolean(error), longestRange: range === LONGEST_RANGE, retry: () => void history.refetch() })}
/>
)
From 7105364161b9b0dea4afaae49681647c32edf1ca Mon Sep 17 00:00:00 2001
From: ZverGuy
Date: Tue, 10 Nov 2026 01:02:17 +0700
Subject: [PATCH 46/46] test(dashboard): pin when the previous-lines note goes
away
The note must leave as soon as the new result lands and must not appear
over live lines while following; neither was exercised, since the only
test kept the longer range pending forever.
Assisted-by: LLM
Signed-off-by: ZverGuy
---
.../observability/LogsView.test.tsx | 39 +++++++++++++++++++
1 file changed, 39 insertions(+)
diff --git a/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.test.tsx b/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.test.tsx
index be8bff1a8..faba85a4e 100644
--- a/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.test.tsx
+++ b/packages/system/dashboard/images/console/apps/console/src/components/observability/LogsView.test.tsx
@@ -126,6 +126,45 @@ describe("LogsView with the production query defaults", () => {
expect(await screen.findByText(/previous lines/)).toHaveAttribute("aria-busy", "true")
expect(screen.getByText("ready to accept connections")).toBeInTheDocument()
})
+
+ it("drops the standing-in note once the longer range answers", async () => {
+ let answer: (r: Response) => void = () => {}
+ const longer = new Promise((resolve) => { answer = resolve })
+ const { client } = clientWith((endpoint, params) =>
+ endpoint.endsWith("query") && Date.parse(params.get("start") ?? "") < Date.now() - 2 * 3600_000
+ ? longer
+ : defaultHandler(endpoint, params),
+ )
+ renderWithProductionDefaults(client, "tenant-range-c")
+ expect(await screen.findByText("ready to accept connections")).toBeInTheDocument()
+ await userEvent.click(screen.getByRole("button", { name: "24h" }))
+ expect(await screen.findByText(/previous lines/)).toBeInTheDocument()
+
+ answer(new Response(`${line("2026-11-03T12:00:00Z", "checkpoint complete")}\n`))
+
+ expect(await screen.findByText("checkpoint complete")).toBeInTheDocument()
+ expect(screen.queryByText(/previous lines/)).toBeNull()
+ expect(screen.queryByText("ready to accept connections")).toBeNull()
+ })
+
+ it("shows no standing-in note while following", async () => {
+ const { client } = clientWith((endpoint, params) =>
+ endpoint.endsWith("tail")
+ ? new Response(`${line("2026-11-04T10:00:02Z", "live line")}\n`)
+ : endpoint.endsWith("query") && params.get("query")?.includes("error")
+ ? new Promise(() => {})
+ : defaultHandler(endpoint, params),
+ )
+ renderWithProductionDefaults(client, "tenant-follow-a")
+ expect(await screen.findByText("ready to accept connections")).toBeInTheDocument()
+
+ await userEvent.type(screen.getByLabelText("LogsQL filter"), "error{Enter}")
+ expect(await screen.findByText(/previous lines/)).toBeInTheDocument()
+ await userEvent.click(screen.getByRole("button", { name: "Follow" }))
+
+ expect(await screen.findByText("live line")).toBeInTheDocument()
+ expect(screen.queryByText(/previous lines/)).toBeNull()
+ })
})
describe("LogsView", () => {