ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.
Python astracloudflarecontrol-panelcyberpaneldnsfablehosting-control-panelhosting-panelkimi-k3server-managementserverkitubuntu-web-panelwebserver
feat(frontend): dynamic walkthrough registry and SDK support
Juan Denis3708227d0edb
diff --git a/frontend/public/serverkit-vendor/serverkit-sdk.mjs b/frontend/public/serverkit-vendor/serverkit-sdk.mjsindex 3341792a..7f2f32fb 100644--- a/frontend/public/serverkit-vendor/serverkit-sdk.mjs+++ b/frontend/public/serverkit-vendor/serverkit-sdk.mjs@@ -113,3 +113,9 @@ export const TabsTrigger = m.TabsTrigger;export const TabsContent = m.TabsContent;export const PageLoader = m.PageLoader;export const copyToClipboard = m.copyToClipboard;+export const downloadBlob = m.downloadBlob;+export const WALKTHROUGH_COMPLETION_TYPES = m.WALKTHROUGH_COMPLETION_TYPES;+export const emitWalkthroughSignal = m.emitWalkthroughSignal;+export const normalizeWalkthroughDefinition = m.normalizeWalkthroughDefinition;+export const validateWalkthroughDefinition = m.validateWalkthroughDefinition;+export const useWalkthroughs = m.useWalkthroughs;diff --git a/frontend/src/components/WalkthroughHub.jsx b/frontend/src/components/WalkthroughHub.jsxindex 86d21757..10090f69 100644--- a/frontend/src/components/WalkthroughHub.jsx+++ b/frontend/src/components/WalkthroughHub.jsx@@ -10,6 +10,7 @@ import {ShieldCheck,Square,UserPlus,+ WandSparkles,} from 'lucide-react';import { useEffect, useMemo, useState } from 'react';import { useNavigate } from 'react-router-dom';@@ -30,6 +31,8 @@ const ICONS = {backup: Archive,server: Server,team: UserPlus,+ guide: WandSparkles,+ wordpress: Globe2,};// Recipes console — the prototype's guided-walkthrough surface: a library of@@ -73,6 +76,9 @@ function RecipeLibrary({ walkthroughs, state, onStart, onStop, t }) {})}{completed && <Pill kind="green">{t('app.walkthroughs.completed', 'Completed')}</Pill>}{active && <Pill kind="cyan">{progress.count}/{progress.total}</Pill>}+ {walkthrough.origin?.plugin && (+ <Pill kind="neutral">{walkthrough.origin.plugin.replace(/^serverkit-/, '')}</Pill>+ )}{active && (<buttontype="button"diff --git a/frontend/src/contexts/WalkthroughContext.jsx b/frontend/src/contexts/WalkthroughContext.jsxindex 0e84eef8..2d3f1c24 100644--- a/frontend/src/contexts/WalkthroughContext.jsx+++ b/frontend/src/contexts/WalkthroughContext.jsx@@ -7,12 +7,9 @@ import {import { useLocation, useNavigate } from 'react-router-dom';import { useTranslation } from 'react-i18next';-import {- WALKTHROUGHS,- WALKTHROUGH_BY_ID,- localizeWalkthroughs,-} from '../data/walkthroughs';+import { localizeWalkthroughs } from '../data/walkthroughs';import api from '../services/api';+import { useContributions } from '../plugins/contributions';import {EMPTY_WALKTHROUGH_STATE,completeWalkthroughStepState,@@ -22,22 +19,26 @@ import {routeMatches,startWalkthroughState,} from '../services/walkthroughState';+import {+ buildWalkthroughRegistry,+ normalizeWalkthroughDefinition,+ WALKTHROUGH_LIBRARY_EVENT,+ WALKTHROUGH_SIGNAL_EVENT,+} from '../services/walkthroughRegistry';import { useAuth } from './AuthContext';import usePolling from '../hooks/usePolling';import { WalkthroughContext } from './walkthroughContextValue';-const WALKTHROUGH_IDS = WALKTHROUGHS.map((item) => item.id);-function storageKey(userId) {return `serverkit.walkthroughs.v1.${userId || 'anonymous'}`;}-function readCachedState(userId) {+function readCachedState(userId, walkthroughIds) {try {return normalizeWalkthroughState(JSON.parse(localStorage.getItem(storageKey(userId)) || 'null'),- WALKTHROUGH_IDS,+ walkthroughIds,);} catch {return { ...EMPTY_WALKTHROUGH_STATE };@@ -49,41 +50,94 @@ export function WalkthroughProvider({ children }) {const { user, hasPermission } = useAuth();const location = useLocation();const navigate = useNavigate();- const [state, setState] = useState(() => readCachedState(user?.id));+ const contributions = useContributions();+ const [customDefinitions, setCustomDefinitions] = useState([]);+ const [previewDefinition, setPreviewDefinition] = useState(null);+ const [pendingPreviewId, setPendingPreviewId] = useState(null);+ const [customLoaded, setCustomLoaded] = useState(false);+ const [state, setState] = useState({ ...EMPTY_WALKTHROUGH_STATE });const [hydrated, setHydrated] = useState(false);const [open, setOpen] = useState(false);- const localizedWalkthroughs = useMemo(() => localizeWalkthroughs(t), [t]);- const availableWalkthroughs = useMemo(() => localizedWalkthroughs.filter((item) => {+ const localizedCore = useMemo(() => localizeWalkthroughs(t), [t]);+ const registry = useMemo(() => buildWalkthroughRegistry({+ core: localizedCore,+ contributed: contributions.walkthroughs,+ custom: previewDefinition+ ? [previewDefinition, ...customDefinitions]+ : customDefinitions,+ t,+ }), [contributions.walkthroughs, customDefinitions, localizedCore, previewDefinition, t]);+ const walkthroughIds = useMemo(+ () => registry.walkthroughs.map((item) => item.id),+ [registry.walkthroughs],+ );+ const walkthroughIdsKey = walkthroughIds.join('|');+ const registryReady = Boolean(contributions.__ready && customLoaded);+ const availableWalkthroughs = useMemo(() => registry.walkthroughs.filter((item) => {const required = item.permissions || (item.permission ? [item.permission] : []);return required.every((permission) => (hasPermission(permission.feature, permission.level)));- }), [hasPermission, localizedWalkthroughs]);+ }), [hasPermission, registry.walkthroughs]);- const activeWalkthrough = localizedWalkthroughs.find(- (walkthrough) => walkthrough.id === state.active_id,- ) || null;+ const activeWalkthrough = registry.byId[state.active_id] || null;const activeProgress = activeWalkthrough? getWalkthroughProgress(state, activeWalkthrough): null;const currentStep = activeProgress?.currentStep || null;useEffect(() => {- if (!user?.id) return undefined;+ if (!pendingPreviewId || !registry.byId[pendingPreviewId]) return;+ setState((previous) => startWalkthroughState(previous, pendingPreviewId));+ setOpen(true);+ setPendingPreviewId(null);+ }, [pendingPreviewId, registry.byId]);++ const refreshDefinitions = useCallback(() => {+ if (!user?.id) {+ setCustomDefinitions([]);+ setCustomLoaded(true);+ return Promise.resolve([]);+ }+ return api.getWalkthroughDefinitions()+ .then((response) => {+ const definitions = Array.isArray(response?.definitions)+ ? response.definitions+ : [];+ setCustomDefinitions(definitions);+ return definitions;+ })+ .catch(() => {+ setCustomDefinitions([]);+ return [];+ })+ .finally(() => setCustomLoaded(true));+ }, [user?.id]);++ useEffect(() => {+ setCustomLoaded(false);+ refreshDefinitions();+ window.addEventListener(WALKTHROUGH_LIBRARY_EVENT, refreshDefinitions);+ return () => window.removeEventListener(WALKTHROUGH_LIBRARY_EVENT, refreshDefinitions);+ }, [refreshDefinitions]);++ useEffect(() => {+ if (!user?.id || !registryReady) return undefined;let cancelled = false;- setState(readCachedState(user.id));+ const currentIds = walkthroughIdsKey ? walkthroughIdsKey.split('|') : [];+ setState(readCachedState(user.id, currentIds));setHydrated(false);api.getWalkthroughState().then((response) => {if (!cancelled) {- setState(normalizeWalkthroughState(response.state, WALKTHROUGH_IDS));+ setState(normalizeWalkthroughState(response.state, currentIds));}}).catch(() => { /* local cache remains the offline fallback */ }).finally(() => { if (!cancelled) setHydrated(true); });return () => { cancelled = true; };- }, [user?.id]);+ }, [registryReady, user?.id, walkthroughIdsKey]);useEffect(() => {if (!hydrated || !user?.id) return undefined;@@ -95,13 +149,13 @@ export function WalkthroughProvider({ children }) {}, [hydrated, state, user?.id]);const start = useCallback((walkthroughId) => {- if (!WALKTHROUGH_BY_ID[walkthroughId]) return;+ if (!registry.byId[walkthroughId]) return;setState((previous) => startWalkthroughState(previous, walkthroughId));setOpen(true);- }, []);+ }, [registry.byId]);const completeStep = useCallback((walkthroughId, stepId) => {- const walkthrough = WALKTHROUGH_BY_ID[walkthroughId];+ const walkthrough = registry.byId[walkthroughId];if (!walkthrough) return;setState((previous) => completeWalkthroughStepState(previous,@@ -109,12 +163,20 @@ export function WalkthroughProvider({ children }) {stepId,walkthrough.steps.map((step) => step.id),));- }, []);+ }, [registry.byId]);const dismiss = useCallback((walkthroughId) => {setState((previous) => dismissWalkthroughState(previous, walkthroughId));}, []);+ const preview = useCallback((definition) => {+ const normalized = normalizeWalkthroughDefinition(definition, { source: 'custom', t });+ if (!normalized) return false;+ setPreviewDefinition(definition);+ setPendingPreviewId(normalized.id);+ return true;+ }, [t]);+useEffect(() => {if (!activeWalkthrough || !currentStep?.route) return;if (routeMatches(location.pathname, currentStep.route)) {@@ -137,13 +199,13 @@ export function WalkthroughProvider({ children }) {);if (signaledStep) completeStep(activeWalkthrough.id, signaledStep.id);};- window.addEventListener('serverkit:walkthrough-signal', handleSignal);- return () => window.removeEventListener('serverkit:walkthrough-signal', handleSignal);- }, [activeWalkthrough, completeStep, currentStep]);+ window.addEventListener(WALKTHROUGH_SIGNAL_EVENT, handleSignal);+ return () => window.removeEventListener(WALKTHROUGH_SIGNAL_EVENT, handleSignal);+ }, [activeWalkthrough, completeStep]);const checkCurrent = useCallback(async () => {if (!activeWalkthrough) return false;- if (activeWalkthrough.id === 'enable-two-factor') {+ if (currentStep?.check === 'two-factor-enabled') {const status = await api.get2FAStatus();if (status?.enabled) {activeWalkthrough.steps.forEach((step) => (@@ -153,12 +215,12 @@ export function WalkthroughProvider({ children }) {}}return false;- }, [activeWalkthrough, completeStep]);+ }, [activeWalkthrough, completeStep, currentStep?.check]);usePolling(() => checkCurrent(),5000,- { enabled: activeWalkthrough?.id === 'enable-two-factor' },+ { enabled: currentStep?.check === 'two-factor-enabled' },);useEffect(() => {@@ -169,6 +231,9 @@ export function WalkthroughProvider({ children }) {target = document.querySelector(currentStep.target);if (target) {target.classList.add('is-walkthrough-target');+ if (currentStep.completeWhenTargetVisible && activeWalkthrough) {+ completeStep(activeWalkthrough.id, currentStep.id);+ }return;}if (attempts++ < 20) timer = setTimeout(findTarget, 100);@@ -178,7 +243,7 @@ export function WalkthroughProvider({ children }) {clearTimeout(timer);target?.classList.remove('is-walkthrough-target');};- }, [currentStep?.target, location.pathname, open]);+ }, [activeWalkthrough, completeStep, currentStep, location.pathname, open]);const goToCurrent = useCallback(() => {if (currentStep?.path) navigate(currentStep.path);@@ -198,6 +263,8 @@ export function WalkthroughProvider({ children }) {completeStep,checkCurrent,goToCurrent,+ refreshDefinitions,+ preview,}), [activeProgress,activeWalkthrough,@@ -208,6 +275,8 @@ export function WalkthroughProvider({ children }) {dismiss,goToCurrent,open,+ preview,+ refreshDefinitions,start,state,]);diff --git a/frontend/src/i18n/locales/en.json b/frontend/src/i18n/locales/en.jsonindex 31cfc7db..9ec1aad3 100644--- a/frontend/src/i18n/locales/en.json+++ b/frontend/src/i18n/locales/en.json@@ -6739,6 +6739,8 @@"download": "Download","edit": "Edit","enable": "Enable",+ "export": "Export",+ "import": "Import","loadMore": "Load more","logOut": "Log out","open": "Open",@@ -6841,6 +6843,7 @@"more": "More","moreSections": "More sections","page": "Page",+ "saving": "Saving…","state": {"failed": "Failed","loading": "Loading",@@ -7038,5 +7041,86 @@"setup": {"subtitle": "Let’s get your server ready","welcome": "Welcome to {{panel}}"+ },+ "walkthroughStudio": {+ "actionLabel": "Action label",+ "actionPlaceholder": "Open services",+ "addDescription": "Add a description to explain the outcome.",+ "addStep": "Add step",+ "adminRequired": "Administrator access is required to publish walkthroughs.",+ "checkHint": "Checks must be implemented and allowlisted by the host.",+ "checkName": "Named host check",+ "completionCheck": "Named status check",+ "completionManual": "Manual confirmation",+ "completionRoute": "Completion route",+ "completionRouteReached": "Route reached",+ "completionSignal": "Success signal received",+ "completionTarget": "Target becomes visible",+ "completionType": "Completion type",+ "contributionCopied": "Extension contribution copied.",+ "copyContribution": "Copy contribution",+ "createFirst": "Create the first custom guide",+ "definitionJson": "Definition JSON",+ "deleteFailed": "Could not delete the walkthrough.",+ "deleteMessage": "Delete “{{title}}” from the shared walkthrough library?",+ "deleteTitle": "Delete walkthrough",+ "deleted": "Walkthrough deleted.",+ "description": "Outcome description",+ "duration": "Duration",+ "fixIssues": "Fix the validation issues before publishing.",+ "flowEyebrow": "02 / FLOW",+ "guideEyebrow": "01 / GUIDE",+ "guideTitle": "Title",+ "icon": "Icon token",+ "importFailed": "Could not import this file.",+ "importInvalid": "The file does not contain a valid walkthrough.",+ "imported": "Walkthrough imported as a draft.",+ "initialDescription": "Help an operator complete one clear outcome.",+ "initialStepAction": "Open page",+ "initialStepDescription": "Navigate to the place where this task begins.",+ "initialStepTitle": "Open the page",+ "initialTitle": "My walkthrough",+ "instruction": "Instruction",+ "issueCount": "{{count}} issues",+ "keepOneStep": "A walkthrough needs at least one step.",+ "library": "Shared library",+ "libraryIntro": "Published guides appear in the walkthrough dock for everyone with the required permissions.",+ "livePreview": "Live preview",+ "loadFailed": "Could not load the walkthrough library.",+ "manualCompletionHint": "The operator uses Done · next step after completing the instruction.",+ "meta": "Declarative guide authoring",+ "moveDown": "Move down",+ "moveUp": "Move up",+ "newGuide": "New walkthrough",+ "newStepDescription": "Describe the operator action and the expected outcome.",+ "noCodeRequired": "No application code required",+ "noDuration": "No duration",+ "noTarget": "no target",+ "numberedStep": "Step {{number}}",+ "openPath": "Open path",+ "optional": "Optional guide",+ "outcome": "Define the outcome",+ "previewFailed": "The draft could not be previewed.",+ "previewOpened": "Draft opened in the walkthrough dock.",+ "publish": "Publish",+ "publishFailed": "Could not publish the walkthrough.",+ "published": "Walkthrough published.",+ "runInDock": "Run in walkthrough dock",+ "signalHint": "Emit this token only after the operation succeeds.",+ "signalName": "Success signal",+ "stableId": "Stable id",+ "stableIdHint": "Do not rename after publishing; progress uses this id.",+ "stepId": "Step id",+ "stepTitle": "Step title",+ "steps": "steps",+ "stepsAndSignals": "Shape the steps and signals",+ "targetCompletionHint": "This step completes when its data-walkthrough target becomes visible.",+ "targetHint": "Matches data-walkthrough=\"token\" in the page markup.",+ "targetToken": "Target token",+ "title": "Walkthrough Studio",+ "tone": "Tone",+ "untitled": "Untitled walkthrough",+ "untitledStep": "Untitled step",+ "valid": "Valid"}}diff --git a/frontend/src/plugins/PluginLoader.jsx b/frontend/src/plugins/PluginLoader.jsxindex 6f7daca4..60500dbe 100644--- a/frontend/src/plugins/PluginLoader.jsx+++ b/frontend/src/plugins/PluginLoader.jsx@@ -15,7 +15,7 @@* the contribution model.** Plugins that declare ANY contribution (routes, nav, tabs, widgets,- * palette entries, layouts, ai) own their rendering through the+ * palette entries, layouts, walkthroughs, ai) own their rendering through the* contribution model and are excluded from the legacy auto-render.* Gating on widgets alone let bundled extensions whose index module* happened to have a default export (WordPress, Cloudflare zone ops)@@ -59,6 +59,7 @@ const PluginLoader = ({ api }) => {contributions.routes, contributions.nav, contributions.tabs,contributions.widgets, contributions.command_palette,contributions.layouts,+ contributions.walkthroughs,contributions.ai?.suggested_prompts, contributions.ai?.tool_renderers,];for (const bucket of buckets) {diff --git a/frontend/src/plugins/contributions.js b/frontend/src/plugins/contributions.jsindex 62e225b6..1b5ad4a1 100644--- a/frontend/src/plugins/contributions.js+++ b/frontend/src/plugins/contributions.js@@ -91,6 +91,9 @@ const EMPTY = {// (== the sidebar item id: files | servers | monitoring). Consumed by// TabGroupLayout (tab strip merge) + Sidebar (group item stays lit).tabs: [],+ // Declarative guided flows supplied by extensions. The walkthrough+ // registry validates and namespaces these before they reach the shell.+ walkthroughs: [],// AI assistant contributions: per-route suggested prompts + custom// tool-result renderers. Consumed by the core AIAssistant via// useContributions().ai.@@ -128,6 +131,7 @@ function getBuildTimeContributions() {const dashboard_widgets = [];const layouts = [];const tabs = [];+ const walkthroughs = [];const ai = { suggested_prompts: [], tool_renderers: [] };for (const entry of installed) {@@ -145,6 +149,7 @@ function getBuildTimeContributions() {dashboard_widgets.push(...tagItems(contrib.dashboard_widgets, slug));layouts.push(...tagItems(contrib.layouts, slug));tabs.push(...tagItems(contrib.tabs, slug));+ walkthroughs.push(...tagItems(contrib.walkthroughs, slug));if (contrib.ai && typeof contrib.ai === 'object') {ai.suggested_prompts.push(...tagItems(contrib.ai.suggested_prompts, slug));@@ -165,6 +170,7 @@ function getBuildTimeContributions() {dashboard_widgets,layouts,tabs,+ walkthroughs,ai,};}diff --git a/frontend/src/plugins/sdk/index.js b/frontend/src/plugins/sdk/index.jsindex 004a9859..f072245d 100644--- a/frontend/src/plugins/sdk/index.js+++ b/frontend/src/plugins/sdk/index.js@@ -38,7 +38,7 @@// GET /api/v1/plugins/contributions. The backend mirror lives in// backend/app/utils/sdk.py — keep the two in lock-step (asserted by// backend/tests/test_sdk_contract.py).-export const SDK_VERSION = '1.4.0';+export const SDK_VERSION = '1.5.0';export { api, default as defaultApi } from '../../services/api';@@ -196,3 +196,16 @@ export { useColumnVisibility } from '../../hooks/useColumnVisibility';export { Tabs, TabsList, TabsTrigger, TabsContent } from '../../components/ui/tabs';export { PageLoader } from '../../components/PageLoader';export { copyToClipboard } from '../../utils/clipboard';+export { downloadBlob } from '../../utils/downloadBlob';++// Declarative walkthrough authoring (1.5.0). Extensions normally contribute+// definitions through plugin.json; these exports power authoring tools,+// validation previews, and successful-action signals without exposing the+// walkthrough engine's internal state shape.+export {+ WALKTHROUGH_COMPLETION_TYPES,+ emitWalkthroughSignal,+ normalizeWalkthroughDefinition,+ validateWalkthroughDefinition,+} from '../../services/walkthroughRegistry';+export { useWalkthroughs } from '../../contexts/walkthroughContextValue';diff --git a/frontend/src/plugins/sdk/walkthroughs.d.ts b/frontend/src/plugins/sdk/walkthroughs.d.tsnew file mode 100644index 00000000..5aafbd99--- /dev/null+++ b/frontend/src/plugins/sdk/walkthroughs.d.ts@@ -0,0 +1,83 @@+export type WalkthroughPermissionLevel = 'read' | 'write' | 'admin';+export type WalkthroughTone = 'cyan' | 'green' | 'amber' | 'blue' | 'violet' | 'neutral';++export interface WalkthroughPermission {+ feature: string;+ level: WalkthroughPermissionLevel;+}++export type WalkthroughCompletion =+ | { type: 'manual' }+ | { type: 'route'; path?: string }+ | { type: 'signal'; signal: string }+ | { type: 'check'; check: string }+ | { type: 'target' };++export interface WalkthroughStepDefinition {+ id: string;+ title: string;+ title_key?: string;+ description: string;+ description_key?: string;+ action?: string;+ action_key?: string;+ path?: string;+ /** Stable value from an element's data-walkthrough attribute, not a selector. */+ target?: string;+ completion?: WalkthroughCompletion;+}++export interface WalkthroughDefinition {+ id: string;+ title: string;+ title_key?: string;+ description: string;+ description_key?: string;+ duration?: string;+ duration_key?: string;+ icon?: string;+ tone?: WalkthroughTone | string;+ secondary?: boolean;+ permissions?: WalkthroughPermission[];+ steps: WalkthroughStepDefinition[];+}++export interface WalkthroughValidationIssue {+ path: string;+ message: string;+}++export interface NormalizedWalkthroughStep extends WalkthroughStepDefinition {+ target: string | null;+ completionType: WalkthroughCompletion['type'];+ route?: string;+ signal?: string;+ check?: string;+ completeWhenTargetVisible?: boolean;+}++export interface NormalizedWalkthrough extends Omit<WalkthroughDefinition, 'steps'> {+ definitionId: string;+ steps: NormalizedWalkthroughStep[];+ origin: { source: 'core' | 'extension' | 'custom'; plugin: string | null };+}++export declare const WALKTHROUGH_COMPLETION_TYPES: ReadonlyArray<{+ value: WalkthroughCompletion['type'];+ key: string;+ fallback: string;+}>;++export declare function validateWalkthroughDefinition(+ definition: unknown,+): WalkthroughValidationIssue[];++export declare function normalizeWalkthroughDefinition(+ definition: WalkthroughDefinition,+ options?: { plugin?: string | null; source?: 'extension' | 'custom'; t?: Function | null },+): NormalizedWalkthrough | null;++export declare function emitWalkthroughSignal(+ type: string,+ detail?: Record<string, unknown>,+): boolean;diff --git a/frontend/src/services/__tests__/walkthroughRegistry.test.mjs b/frontend/src/services/__tests__/walkthroughRegistry.test.mjsindex da217a26..ab406cd5 100644--- a/frontend/src/services/__tests__/walkthroughRegistry.test.mjs+++ b/frontend/src/services/__tests__/walkthroughRegistry.test.mjs@@ -6,6 +6,12 @@ import {WALKTHROUGH_BY_ID,localizeWalkthroughs,} from '../../data/walkthroughs.js';+import {+ buildWalkthroughRegistry,+ normalizeWalkthroughDefinition,+ validateWalkthroughDefinition,+ WALKTHROUGH_COMPLETION_TYPES,+} from '../walkthroughRegistry.js';const OPTIONAL_IDS = [@@ -59,3 +65,65 @@ test('every guide and step retains localized display copy', () => {assert.ok(guide.steps.every((step) => step.title && step.description && step.action));}});++const contributedGuide = {+ id: 'first-run',+ plugin: 'serverkit-demo',+ title: 'Try Demo',+ description: 'Complete the first Demo task.',+ duration: 'About 2 minutes',+ steps: [+ {+ id: 'open-demo',+ title: 'Open Demo',+ description: 'Navigate to Demo.',+ action: 'Open Demo',+ path: '/demo',+ target: 'demo-page',+ completion: { type: 'route', path: '/demo' },+ },+ {+ id: 'create-item',+ title: 'Create an item',+ description: 'Submit the form successfully.',+ target: 'demo-submit',+ completion: { type: 'signal', signal: 'demo.item-created' },+ },+ ],+};++test('normalizes extension walkthroughs into a namespaced runtime guide', () => {+ const guide = normalizeWalkthroughDefinition(contributedGuide);+ assert.equal(guide.id, 'serverkit-demo.first-run');+ assert.equal(guide.origin.plugin, 'serverkit-demo');+ assert.equal(guide.steps[0].route, '/demo');+ assert.equal(guide.steps[0].target, '[data-walkthrough="demo-page"]');+ assert.equal(guide.steps[1].signal, 'demo.item-created');+});++test('merges core, extension, and custom guides without id collisions', () => {+ const custom = { ...contributedGuide, id: 'first-run' };+ delete custom.plugin;+ const registry = buildWalkthroughRegistry({+ core: WALKTHROUGHS,+ contributed: [contributedGuide, contributedGuide],+ custom: [custom, custom],+ });+ assert.ok(registry.byId['serverkit-demo.first-run']);+ assert.ok(registry.byId['custom.first-run']);+ assert.equal(+ registry.walkthroughs.filter((guide) => guide.id.endsWith('.first-run')).length,+ 2,+ );+});++test('supports five safe declarative completion modes and rejects selectors', () => {+ assert.deepEqual(+ WALKTHROUGH_COMPLETION_TYPES.map((type) => type.value),+ ['manual', 'route', 'signal', 'check', 'target'],+ );+ const invalid = structuredClone(contributedGuide);+ invalid.steps[0].target = '#password';+ assert.ok(validateWalkthroughDefinition(invalid).some((item) => item.path.endsWith('target')));+ assert.equal(normalizeWalkthroughDefinition(invalid), null);+});diff --git a/frontend/src/services/api/walkthroughs.js b/frontend/src/services/api/walkthroughs.jsindex 5c5abffd..cf3f0c97 100644--- a/frontend/src/services/api/walkthroughs.js+++ b/frontend/src/services/api/walkthroughs.js@@ -8,3 +8,14 @@ export async function updateWalkthroughState(state) {body: { state },});}++export async function getWalkthroughDefinitions() {+ return this.request('/walkthroughs/definitions');+}++export async function updateWalkthroughDefinitions(definitions) {+ return this.request('/walkthroughs/definitions', {+ method: 'PUT',+ body: { definitions },+ });+}diff --git a/frontend/src/services/walkthroughRegistry.js b/frontend/src/services/walkthroughRegistry.jsnew file mode 100644index 00000000..d3200d21--- /dev/null+++ b/frontend/src/services/walkthroughRegistry.js@@ -0,0 +1,243 @@+export const WALKTHROUGH_COMPLETION_TYPES = Object.freeze([+ { value: 'manual', key: 'walkthroughStudio.completionManual', fallback: 'Manual confirmation' },+ { value: 'route', key: 'walkthroughStudio.completionRouteReached', fallback: 'Route reached' },+ { value: 'signal', key: 'walkthroughStudio.completionSignal', fallback: 'Success signal received' },+ { value: 'check', key: 'walkthroughStudio.completionCheck', fallback: 'Named status check' },+ { value: 'target', key: 'walkthroughStudio.completionTarget', fallback: 'Target becomes visible' },+]);++export const WALKTHROUGH_LIBRARY_EVENT = 'serverkit:walkthrough-library-changed';+export const WALKTHROUGH_SIGNAL_EVENT = 'serverkit:walkthrough-signal';++const ID_RE = /^[a-z0-9][a-z0-9._-]{0,79}$/;+const TOKEN_RE = /^[a-z0-9][a-z0-9._:-]{0,119}$/;+const TARGET_RE = /^[a-z0-9][a-z0-9._:-]{0,79}$/;+const COMPLETION_TYPES = new Set(WALKTHROUGH_COMPLETION_TYPES.map((item) => item.value));+const GUIDE_FIELDS = new Set([+ '$schema', 'plugin', 'id', 'title', 'title_key', 'titleKey', 'description',+ 'description_key', 'descriptionKey', 'duration', 'duration_key', 'durationKey',+ 'icon', 'tone', 'secondary', 'permissions', 'steps',+]);+const STEP_FIELDS = new Set([+ 'id', 'title', 'title_key', 'titleKey', 'description', 'description_key',+ 'descriptionKey', 'action', 'action_key', 'actionKey', 'path', 'target',+ 'completion', 'route', 'signal', 'check',+]);+const COMPLETION_FIELDS = new Set(['type', 'path', 'signal', 'check']);++function text(value) {+ return typeof value === 'string' ? value.trim() : '';+}++function translated(translator, key, fallback) {+ const cleanKey = text(key);+ return cleanKey && translator ? translator(cleanKey, fallback) : fallback;+}++function issue(path, message) {+ return { path, message };+}++export function validateWalkthroughDefinition(definition) {+ const issues = [];+ if (!definition || typeof definition !== 'object' || Array.isArray(definition)) {+ return [issue('', 'Walkthrough must be an object.')];+ }++ const unknownGuideFields = Object.keys(definition).filter((key) => !GUIDE_FIELDS.has(key));+ if (unknownGuideFields.length) {+ issues.push(issue('', `Unsupported fields: ${unknownGuideFields.join(', ')}.`));+ }++ if (!ID_RE.test(text(definition.id))) issues.push(issue('id', 'Use a stable lowercase id.'));+ if (!text(definition.title)) issues.push(issue('title', 'Title is required.'));+ if (text(definition.title).length > 120) issues.push(issue('title', 'Title is too long.'));+ if (!text(definition.description)) issues.push(issue('description', 'Description is required.'));+ if (text(definition.description).length > 320) issues.push(issue('description', 'Description is too long.'));+ if (definition.permissions != null && !Array.isArray(definition.permissions)) {+ issues.push(issue('permissions', 'Permissions must be a list.'));+ } else {+ (definition.permissions || []).forEach((permission, index) => {+ if (!text(permission?.feature)) issues.push(issue(`permissions.${index}.feature`, 'Feature is required.'));+ if (!['read', 'write', 'admin'].includes(permission?.level)) {+ issues.push(issue(`permissions.${index}.level`, 'Choose read, write, or admin.'));+ }+ });+ }+ if (!Array.isArray(definition.steps) || definition.steps.length === 0) {+ issues.push(issue('steps', 'Add at least one step.'));+ return issues;+ }+ if (definition.steps.length > 32) issues.push(issue('steps', 'A walkthrough can have at most 32 steps.'));++ const stepIds = new Set();+ definition.steps.forEach((step, index) => {+ const base = `steps.${index}`;+ if (!step || typeof step !== 'object' || Array.isArray(step)) {+ issues.push(issue(base, 'Step must be an object.'));+ return;+ }+ const unknownStepFields = Object.keys(step).filter((key) => !STEP_FIELDS.has(key));+ if (unknownStepFields.length) {+ issues.push(issue(base, `Unsupported fields: ${unknownStepFields.join(', ')}.`));+ }+ const stepId = text(step.id);+ if (!ID_RE.test(stepId)) issues.push(issue(`${base}.id`, 'Use a stable lowercase step id.'));+ if (stepIds.has(stepId)) issues.push(issue(`${base}.id`, 'Step ids must be unique.'));+ stepIds.add(stepId);+ if (!text(step.title)) issues.push(issue(`${base}.title`, 'Step title is required.'));+ if (!text(step.description)) issues.push(issue(`${base}.description`, 'Step description is required.'));+ if (step.path && !text(step.path).startsWith('/')) {+ issues.push(issue(`${base}.path`, 'Paths must begin with /.'));+ }+ if (step.target && !TARGET_RE.test(text(step.target))) {+ issues.push(issue(`${base}.target`, 'Use a data-walkthrough token, not a CSS selector.'));+ }++ const completion = step.completion || { type: 'manual' };+ if (!completion || typeof completion !== 'object' || Array.isArray(completion)) {+ issues.push(issue(`${base}.completion`, 'Completion must be an object.'));+ return;+ }+ const unknownCompletionFields = Object.keys(completion)+ .filter((key) => !COMPLETION_FIELDS.has(key));+ if (unknownCompletionFields.length) {+ issues.push(issue(+ `${base}.completion`,+ `Unsupported fields: ${unknownCompletionFields.join(', ')}.`,+ ));+ }+ const completionType = text(completion.type) || 'manual';+ if (!COMPLETION_TYPES.has(completionType)) {+ issues.push(issue(`${base}.completion.type`, 'Choose a supported completion type.'));+ } else if (completionType === 'route') {+ const path = text(completion.path) || text(step.path);+ if (!path.startsWith('/')) issues.push(issue(`${base}.completion.path`, 'Route completion needs a path.'));+ } else if (completionType === 'signal' && !TOKEN_RE.test(text(completion.signal))) {+ issues.push(issue(`${base}.completion.signal`, 'Signal completion needs a stable event token.'));+ } else if (completionType === 'check' && !TOKEN_RE.test(text(completion.check))) {+ issues.push(issue(`${base}.completion.check`, 'Check completion needs a named host check.'));+ } else if (completionType === 'target' && !text(step.target)) {+ issues.push(issue(`${base}.target`, 'Target completion needs a target token.'));+ }+ });++ return issues;+}++function completionFor(step) {+ if (step.completion && typeof step.completion === 'object') return step.completion;+ if (step.signal) return { type: 'signal', signal: step.signal };+ if (step.check) return { type: 'check', check: step.check };+ if (step.route) return { type: 'route', path: step.route };+ return { type: 'manual' };+}++function targetSelector(target) {+ const token = text(target);+ if (!token) return null;+ if (token.startsWith('[data-walkthrough=')) return token;+ return TARGET_RE.test(token) ? `[data-walkthrough="${token}"]` : null;+}++export function normalizeWalkthroughDefinition(definition, {+ plugin = definition?.plugin || null,+ source = plugin ? 'extension' : 'custom',+ t = null,+} = {}) {+ if (validateWalkthroughDefinition(definition).length > 0) return null;+ const rawId = text(definition.id);+ const namespace = plugin || (source === 'custom' ? 'custom' : null);+ const id = namespace && !rawId.startsWith(`${namespace}.`)+ ? `${namespace}.${rawId}`+ : rawId;+ if (!ID_RE.test(id)) return null;++ const steps = definition.steps.map((step) => {+ const completion = completionFor(step);+ const completionType = completion.type || 'manual';+ const path = text(step.path) || null;+ const normalized = {+ id: text(step.id),+ title: translated(t, step.title_key || step.titleKey, text(step.title)),+ description: translated(+ t,+ step.description_key || step.descriptionKey,+ text(step.description),+ ),+ action: translated(+ t,+ step.action_key || step.actionKey,+ text(step.action) || (path ? 'Open' : 'Continue'),+ ),+ path,+ target: targetSelector(step.target),+ completionType,+ };+ if (completionType === 'route') normalized.route = text(completion.path) || path;+ if (completionType === 'signal') normalized.signal = text(completion.signal);+ if (completionType === 'check') normalized.check = text(completion.check);+ if (completionType === 'target') normalized.completeWhenTargetVisible = true;+ return normalized;+ });++ return {+ id,+ definitionId: rawId,+ icon: text(definition.icon) || 'guide',+ tone: text(definition.tone) || 'cyan',+ secondary: definition.secondary !== false,+ title: translated(t, definition.title_key || definition.titleKey, text(definition.title)),+ description: translated(+ t,+ definition.description_key || definition.descriptionKey,+ text(definition.description),+ ),+ duration: translated(+ t,+ definition.duration_key || definition.durationKey,+ text(definition.duration) || `${steps.length} steps`,+ ),+ permissions: Array.isArray(definition.permissions) ? definition.permissions : [],+ steps,+ origin: { source, plugin },+ };+}++export function buildWalkthroughRegistry({ core = [], contributed = [], custom = [], t = null }) {+ const walkthroughs = [...core];+ const seen = new Set(core.map((guide) => guide.id));++ const append = (definitions, source) => {+ for (const definition of definitions || []) {+ const guide = normalizeWalkthroughDefinition(definition, {+ plugin: source === 'extension' ? definition?.plugin : null,+ source,+ t,+ });+ if (!guide || seen.has(guide.id)) continue;+ seen.add(guide.id);+ walkthroughs.push(guide);+ }+ };++ append(contributed, 'extension');+ append(custom, 'custom');+ return {+ walkthroughs,+ byId: Object.fromEntries(walkthroughs.map((guide) => [guide.id, guide])),+ };+}++export function emitWalkthroughSignal(type, detail = {}) {+ if (!TOKEN_RE.test(text(type)) || typeof window === 'undefined') return false;+ window.dispatchEvent(new CustomEvent(WALKTHROUGH_SIGNAL_EVENT, {+ detail: { ...detail, type },+ }));+ return true;+}++export function notifyWalkthroughLibraryChanged() {+ if (typeof window === 'undefined') return;+ window.dispatchEvent(new Event(WALKTHROUGH_LIBRARY_EVENT));+}diff --git a/frontend/src/styles/components/_walkthroughs.scss b/frontend/src/styles/components/_walkthroughs.scssindex 8cf65959..06668e3f 100644--- a/frontend/src/styles/components/_walkthroughs.scss+++ b/frontend/src/styles/components/_walkthroughs.scss@@ -53,6 +53,9 @@&.is-cyan { color: var(--cyan); background: color-mix(in srgb, var(--cyan) 13%, transparent); }&.is-amber { color: var(--amber); background: color-mix(in srgb, var(--amber) 13%, transparent); }&.is-green { color: var(--green); background: color-mix(in srgb, var(--green) 13%, transparent); }+ &.is-blue { color: var(--cyan); background: color-mix(in srgb, var(--cyan) 13%, transparent); }+ &.is-violet { color: var(--violet); background: color-mix(in srgb, var(--violet) 13%, transparent); }+ &.is-neutral { color: var(--text-dim); background: var(--surface-3); }}&__card-name {