Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 56 additions & 0 deletions .github/workflows/demo-refresh.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
# Rebuilds the mocked console demo (static/demo) from upstream cozystack-ui and
# opens a PR with the result. Self-contained: the demo overlay lives in
# demo-src/, the build clones upstream fresh, and the PR is opened in THIS repo
# with the built-in GITHUB_TOKEN — no external tokens, no forks.
#
# Requires: Settings → Actions → General → "Allow GitHub Actions to create and
# approve pull requests" (enabled once). This repo is public, so Actions
# minutes are free.

name: Refresh console demo

on:
workflow_dispatch:
schedule:
- cron: "0 3 * * 1" # Mondays 03:00 UTC

concurrency:
group: demo-refresh
cancel-in-progress: false

permissions:
contents: write
pull-requests: write

jobs:
refresh:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v4
- uses: actions/setup-node@v4
with:
node-version: 22
cache: pnpm

- name: Build demo from upstream (with smoke gate)
run: bash demo-src/build.sh main

- name: Open a PR if the demo changed
env:
GH_TOKEN: ${{ github.token }}
run: |
if git diff --quiet -- static/demo; then
echo "No demo changes — nothing to do."
exit 0
fi
BR="demo/refresh-${GITHUB_RUN_ID}"
git config user.name "github-actions[bot]"
git config user.email "github-actions[bot]@users.noreply.github.com"
git checkout -b "$BR"
git add static/demo
git commit --signoff -m "chore(demo): refresh mocked console demo from cozystack-ui"
git push origin "$BR"
gh pr create --base main --head "$BR" --draft \
--title "chore(demo): refresh mocked console demo" \
--body "Automated rebuild of the /demo/ bundle from the current cozystack-ui. The Playwright smoke check (every sidebar/tab screen, no un-mocked API call or page error) passed on this build. Review the Netlify deploy preview, then merge. Not auto-merged."
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,4 @@ static/docs/*/cozystack-api/

# Claude Code local settings
.claude/
.demo-build-uidir
57 changes: 57 additions & 0 deletions demo-src/build.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
#!/usr/bin/env bash
# Builds the mocked Cozystack console demo into ../static/demo.
#
# The demo is a thin overlay on cozystack/cozystack-ui: a few new files
# (demo/ mock layer, MSW worker, smoke test) plus small patches to main.tsx,
# vite.config and the manifests. This fetches upstream fresh, lays the overlay
# on top, smoke-checks a root build, then produces the /demo/ bundle.
#
# demo-src/build.sh [cozystack-ui-ref] # ref defaults to "main"
# SKIP_SMOKE=1 demo-src/build.sh # regenerate the bundle only
#
set -euo pipefail

REF="${1:-main}"
HERE="$(cd "$(dirname "$0")" && pwd)"
SITE="$(cd "$HERE/.." && pwd)"
WORK="$(mktemp -d)"
trap 'rm -rf "$WORK"' EXIT
UI="$WORK/ui"

echo "==> cloning cozystack-ui @ $REF"
git clone --depth 1 --branch "$REF" https://github.com/cozystack/cozystack-ui.git "$UI"

echo "==> applying demo overlay"
cp -R "$HERE/overlay/." "$UI/"

echo "==> applying patches"
( cd "$UI"
for p in "$HERE"/patches/*.patch; do
echo " $(basename "$p")"
git apply --3way "$p" || { echo "PATCH FAILED: $(basename "$p") — upstream drifted, needs a human"; exit 3; }
done )

echo "==> installing deps"
corepack enable >/dev/null 2>&1 || true
( cd "$UI" && pnpm install --frozen-lockfile=false )

if [ "${SKIP_SMOKE:-0}" != "1" ]; then
echo "==> smoke: root build + walk every screen"
( cd "$UI"
VITE_DEMO=1 DEMO_BASE_PATH=/ pnpm --filter @cozystack/console build
cp apps/console/dist/index.html apps/console/dist/404.html
PW_FLAGS=""; [ "${CI:-}" = "true" ] && PW_FLAGS="--with-deps"
pnpm --filter @cozystack/console exec playwright install $PW_FLAGS chromium
SMOKE_DIST="$UI/apps/console/dist" node apps/console/demo-smoke.mjs )
fi

echo "==> building demo (base /demo/)"
( cd "$UI"
VITE_DEMO=1 DEMO_BASE_PATH=/demo/ pnpm --filter @cozystack/console build
cp apps/console/dist/index.html apps/console/dist/404.html )

echo "==> publishing to static/demo"
rm -rf "$SITE/static/demo"
mkdir -p "$SITE/static/demo"
cp -R "$UI/apps/console/dist/." "$SITE/static/demo/"
echo "==> done: $(find "$SITE/static/demo" -type f | wc -l) files in static/demo"
82 changes: 82 additions & 0 deletions demo-src/overlay/apps/console/demo-smoke.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
// Demo smoke check for the mocked console. Serves nothing itself — point it at
// a running static server of the VITE_DEMO build (SPA fallback required):
//
// VITE_DEMO=1 pnpm --filter @cozystack/console build
// cp apps/console/dist/index.html apps/console/dist/404.html
// (serve apps/console/dist on $SMOKE_BASE with SPA fallback)
// node apps/console/demo-smoke.mjs
//
// It walks every sidebar/tab destination reachable from the three top sections,
// visits each, and fails on any un-mocked Kubernetes call (4xx/5xx to /api or
// /apis), any page error. Exit code is non-zero on
// failure so CI can gate a deploy on it.

import { chromium } from "@playwright/test"
import http from "node:http"
import fs from "node:fs"
import path from "node:path"

// Self-contained: serve the built demo (SPA fallback) so CI just runs
// VITE_DEMO=1 pnpm --filter @cozystack/console build && node demo-smoke.mjs
const DIST = process.env.SMOKE_DIST || "dist"
const TYPES = { ".html":"text/html", ".js":"text/javascript", ".css":"text/css", ".json":"application/json", ".svg":"image/svg+xml", ".ico":"image/x-icon", ".woff2":"font/woff2", ".png":"image/png" }
const server = http.createServer((req, res) => {
const url = req.url.split("?")[0]
let file = path.join(DIST, url)
if (!fs.existsSync(file) || fs.statSync(file).isDirectory()) file = path.join(DIST, "index.html")
res.setHeader("Content-Type", TYPES[path.extname(file)] || "application/octet-stream")
fs.createReadStream(file).pipe(res)
})
await new Promise((r) => server.listen(0, r))
const PORT = server.address().port

const BASE = `http://localhost:${PORT}`
const ENTRIES = ["/marketplace", "/console", "/admin/capacity/cluster"]

// Deliberately un-mocked, handled gracefully by the app — not failures.
const ALLOWED_404 = [
"cozy-dashboard-console-config", // config configmap, swallowed to {}
"buckets/cozy-backups", // optional backup bucket
]

const browser = await chromium.launch()
const page = await browser.newPage({ viewport: { width: 1440, height: 900 } })

const badApi = new Set()
const pageErrors = []
page.on("response", (r) => {
const u = new URL(r.url()).pathname
if (!/^\/(api|apis)\b/.test(u) && !u.startsWith("/api/") && !u.startsWith("/apis/")) return
if (r.status() < 400) return
if (ALLOWED_404.some((a) => u.includes(a))) return
badApi.add(`${r.status()} ${u}`)
})
page.on("pageerror", (e) => pageErrors.push(String(e).slice(0, 160)))

const routes = new Set(ENTRIES)
for (const entry of ENTRIES) {
await page.goto(BASE + entry, { waitUntil: "domcontentloaded" })
await page.waitForTimeout(1500)
for (const href of await page
.locator("aside a, nav a, [role=tablist] a, a[href^='/console'], a[href^='/admin'], a[href^='/marketplace']")
.evaluateAll((as) => as.map((a) => a.getAttribute("href"))))
if (href && href.startsWith("/") && !href.startsWith("//")) routes.add(href)
}

console.log(`\n########## visiting ${routes.size} destinations\n`)
for (const route of [...routes].sort()) {
await page.goto(BASE + route, { waitUntil: "domcontentloaded" })
await page.waitForTimeout(1200)
}
// This console has no distinct "not found" screen (an unknown route just
// renders the shell), so a broken screen shows up as an un-mocked API call or
// a page error, both collected above — not as body text.

await browser.close()
server.close()

const fail = badApi.size || pageErrors.length
console.log("un-mocked API calls:", badApi.size ? [...badApi] : "none")
console.log("page errors:", pageErrors.length ? pageErrors : "none")
console.log(fail ? "\nSMOKE FAILED" : "\nsmoke OK")
process.exit(fail ? 1 : 0)
15 changes: 15 additions & 0 deletions demo-src/overlay/apps/console/src/demo/browser.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { setupWorker } from "msw/browser"
import { handlers } from "./handlers.ts"

// Запускается только в demo-сборке (VITE_DEMO=1). unhandled-запросы пропускаем
// молча — часть путей k8s UI может дёргать опционально.
export async function startDemo() {
const worker = setupWorker(...handlers)
// worker + его scope должны жить под base-путём (напр. /demo/), иначе на
// под-путях моки не перехватываются.
await worker.start({
onUnhandledRequest: "bypass",
quiet: true,
serviceWorker: { url: `${import.meta.env.BASE_URL}mockServiceWorker.js` },
})
}

Large diffs are not rendered by default.

4,604 changes: 4,604 additions & 0 deletions demo-src/overlay/apps/console/src/demo/fixtures/applicationdefinitions.json

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"apiVersion": "v1", "items": [{"apiVersion": "backups.cozystack.io/v1alpha1", "kind": "BackupClass", "metadata": {"creationTimestamp": "2026-08-12T10:14:33Z", "generation": 1, "labels": {"app.kubernetes.io/managed-by": "Helm", "helm.toolkit.fluxcd.io/name": "backupstrategy-controller", "helm.toolkit.fluxcd.io/namespace": "cozy-backup-controller"}, "name": "cozy-default", "resourceVersion": "38140", "uid": "2cf068c8-bbcc-4511-b829-87dfb2edefd8"}, "spec": {"strategies": [{"application": {"apiGroup": "apps.cozystack.io", "kind": "Postgres"}, "strategyRef": {"apiGroup": "strategy.backups.cozystack.io", "kind": "CNPG", "name": "cozy-default-cnpg"}}, {"application": {"apiGroup": "apps.cozystack.io", "kind": "MariaDB"}, "strategyRef": {"apiGroup": "strategy.backups.cozystack.io", "kind": "MariaDB", "name": "cozy-default-mariadb"}}, {"application": {"apiGroup": "apps.cozystack.io", "kind": "Etcd"}, "strategyRef": {"apiGroup": "strategy.backups.cozystack.io", "kind": "Etcd", "name": "cozy-default-etcd"}}, {"application": {"apiGroup": "apps.cozystack.io", "kind": "ClickHouse"}, "strategyRef": {"apiGroup": "strategy.backups.cozystack.io", "kind": "Altinity", "name": "cozy-default-altinity"}}, {"application": {"apiGroup": "apps.cozystack.io", "kind": "VMInstance"}, "strategyRef": {"apiGroup": "strategy.backups.cozystack.io", "kind": "Velero", "name": "cozy-default-velero-vminstance"}}, {"application": {"apiGroup": "apps.cozystack.io", "kind": "VMDisk"}, "strategyRef": {"apiGroup": "strategy.backups.cozystack.io", "kind": "Velero", "name": "cozy-default-velero-vmdisk"}}]}}], "kind": "List", "metadata": {"resourceVersion": ""}}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"apiVersion": "v1",
"items": [],
"kind": "List",
"metadata": {
"resourceVersion": ""
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"apiVersion": "v1",
"items": [],
"kind": "List",
"metadata": {
"resourceVersion": ""
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"apiVersion": "v1",
"items": [],
"kind": "List",
"metadata": {
"resourceVersion": ""
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"apiVersion": "v1",
"items": [],
"kind": "List",
"metadata": {
"resourceVersion": ""
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"apiVersion": "apiextensions.k8s.io/v1", "kind": "CustomResourceDefinition", "metadata": {"creationTimestamp": "2026-08-12T09:57:04Z", "generation": 1, "labels": {"app.kubernetes.io/managed-by": "Helm", "helm.toolkit.fluxcd.io/name": "backup-controller", "helm.toolkit.fluxcd.io/namespace": "cozy-backup-controller"}, "name": "backupclasses.backups.cozystack.io", "resourceVersion": "8194", "uid": "66aeacc9-c9ca-447c-8a2d-211a2077a214"}, "spec": {"conversion": {"strategy": "None"}, "group": "backups.cozystack.io", "names": {"kind": "BackupClass", "listKind": "BackupClassList", "plural": "backupclasses", "singular": "backupclass"}, "scope": "Cluster", "versions": [{"name": "v1alpha1", "schema": {"openAPIV3Schema": {"description": "BackupClass defines a class of backup configurations that can be referenced\nby BackupJob and Plan resources. It encapsulates strategy and storage configuration\nper application type.", "properties": {"apiVersion": {"description": "APIVersion defines the versioned schema of this representation of an object.\nServers should convert recognized schemas to the latest internal value, and\nmay reject unrecognized values.\nMore info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", "type": "string"}, "kind": {"description": "Kind is a string value representing the REST resource this object represents.\nServers may infer this from the endpoint the client submits requests to.\nCannot be updated.\nIn CamelCase.\nMore info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds", "type": "string"}, "metadata": {"type": "object"}, "spec": {"description": "BackupClassSpec defines the desired state of a BackupClass.", "properties": {"strategies": {"description": "Strategies is a list of backup strategies, each matching a specific application type.", "items": {"description": "BackupClassStrategy defines a backup strategy for a specific application type.", "properties": {"application": {"description": "Application specifies which application types this strategy applies to.", "properties": {"apiGroup": {"description": "APIGroup is the API group of the application.\nIf not specified, defaults to \"apps.cozystack.io\".", "type": "string"}, "kind": {"description": "Kind is the kind of the application (e.g., VirtualMachine, MariaDB).", "type": "string"}}, "required": ["kind"], "type": "object"}, "parameters": {"additionalProperties": {"type": "string"}, "description": "Parameters holds strategy-specific and storage-specific parameters.\nCommon parameters include:\n- backupStorageLocationName: Name of Velero BackupStorageLocation\n\nSECURITY: parameter values MUST NOT contain credentials, access keys,\npasswords, or any other secret material. The CNPG driver persists this\nmap verbatim into Backup.status.underlyingResources at backup time so\nthat restore-time template rendering reproduces the exact values used\nat backup time; that status field is tenant-readable and replicated\nthrough every Backup artifact derived from a strategy. Route credentials\nthrough the Secret references on the strategy template instead\n(e.g. CNPG's barmanObjectStore.s3Credentials.secretRef and endpointCA).", "type": "object"}, "strategyRef": {"description": "StrategyRef references the driver-specific BackupStrategy (e.g., Velero).", "properties": {"apiGroup": {"description": "APIGroup is the group for the resource being referenced.\nIf APIGroup is not specified, the specified Kind must be in the core API group.\nFor any other third-party types, APIGroup is required.", "type": "string"}, "kind": {"description": "Kind is the type of resource being referenced", "type": "string"}, "name": {"description": "Name is the name of resource being referenced", "type": "string"}}, "required": ["kind", "name"], "type": "object", "x-kubernetes-map-type": "atomic"}}, "required": ["application", "strategyRef"], "type": "object"}, "type": "array"}}, "required": ["strategies"], "type": "object"}, "status": {"description": "BackupClassStatus defines the observed state of a BackupClass.", "properties": {"conditions": {"description": "Conditions represents the latest available observations of a BackupClass's state.", "items": {"description": "Condition contains details for one aspect of the current state of this API Resource.", "properties": {"lastTransitionTime": {"description": "lastTransitionTime is the last time the condition transitioned from one status to another.\nThis should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable.", "format": "date-time", "type": "string"}, "message": {"description": "message is a human readable message indicating details about the transition.\nThis may be an empty string.", "maxLength": 32768, "type": "string"}, "observedGeneration": {"description": "observedGeneration represents the .metadata.generation that the condition was set based upon.\nFor instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date\nwith respect to the current state of the instance.", "format": "int64", "minimum": 0, "type": "integer"}, "reason": {"description": "reason contains a programmatic identifier indicating the reason for the condition's last transition.\nProducers of specific condition types may define expected values and meanings for this field,\nand whether the values are considered a guaranteed API.\nThe value should be a CamelCase string.\nThis field may not be empty.", "maxLength": 1024, "minLength": 1, "pattern": "^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$", "type": "string"}, "status": {"description": "status of the condition, one of True, False, Unknown.", "enum": ["True", "False", "Unknown"], "type": "string"}, "type": {"description": "type of condition in CamelCase or in foo.example.com/CamelCase.", "maxLength": 316, "pattern": "^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$", "type": "string"}}, "required": ["lastTransitionTime", "message", "reason", "status", "type"], "type": "object"}, "type": "array"}}, "type": "object"}}, "type": "object"}}, "served": true, "storage": true, "subresources": {"status": {}}}]}, "status": {"acceptedNames": {"kind": "BackupClass", "listKind": "BackupClassList", "plural": "backupclasses", "singular": "backupclass"}, "conditions": [{"lastTransitionTime": "2026-08-12T09:57:04Z", "message": "no conflicts found", "reason": "NoConflicts", "status": "True", "type": "NamesAccepted"}, {"lastTransitionTime": "2026-08-12T09:57:04Z", "message": "the initial names have been accepted", "reason": "InitialNamesAccepted", "status": "True", "type": "Established"}], "storedVersions": ["v1alpha1"]}}
Loading