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
fix: preserve search focus and ignore stale list responses
Juan Denisfd4795a376ce
diff --git a/frontend/package.json b/frontend/package.jsonindex 617f03a2..b3461be5 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -15,6 +15,7 @@"test:metrics": "node scripts/metrics-browser.mjs","measure:build": "node scripts/measure-build.mjs","test:hooks": "node scripts/hooks-browser.mjs",+ "test:search-focus": "node scripts/search-focus-browser.mjs","test:backups": "node scripts/backups-browser.mjs","test:sanitize-svg": "node scripts/sanitize-svg-browser.mjs","test:terminal-logs": "node scripts/terminal-logs-browser.mjs",diff --git a/frontend/scripts/search-focus-browser.mjs b/frontend/scripts/search-focus-browser.mjsnew file mode 100644index 00000000..e9beb850--- /dev/null+++ b/frontend/scripts/search-focus-browser.mjs@@ -0,0 +1,141 @@+import assert from 'node:assert/strict';+import { existsSync } from 'node:fs';+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import { createServer } from 'vite';+import react from '@vitejs/plugin-react';+import { chromium } from 'playwright';++const root = fileURLToPath(new URL('../', import.meta.url));+const fixture = `+import React,{useState} from 'react';+import {createRoot} from 'react-dom/client';+import {MemoryRouter, Routes, Route} from 'react-router-dom';+import TabGroupLayout from '/src/layouts/TabGroupLayout.jsx';+import Services from '/src/pages/Services.jsx';+import Templates from '/src/pages/Templates.jsx';+import Monitors from '/src/pages/Monitors.jsx';+import Jobs from '/src/pages/Jobs.jsx';+import Telemetry from '/src/pages/Telemetry.jsx';+import SearchField from '/src/components/ds/SearchField.jsx';+window.searchPending={monitors:[],jobs:[],telemetry:[]};+const defer=(kind,params)=>new Promise(resolve=>window.searchPending[kind].push({params,resolve}));+window.testApi={+ getApps:()=>Promise.resolve({apps:[{id:1,name:'serverkit-app',status:'running',app_type:'node',project_name:'alpha'},{id:2,name:'other-app',status:'stopped',app_type:'node',project_name:'beta'}]}),+ getBandwidthApps:()=>Promise.resolve({apps:{}}),+ getTemplateCategories:()=>Promise.resolve({categories:[]}),+ listTemplates:(_category,search)=>new Promise(resolve=>setTimeout(()=>resolve({templates:[{id:'wordpress',name:'WordPress',description:'CMS',categories:['cms']}].filter(item=>!search||item.name.toLowerCase().includes(search.toLowerCase()))}),400)),+ getMonitors:(params)=>defer('monitors',params),+ getJobs:(params)=>defer('jobs',params),+ getScheduledJobs:()=>Promise.resolve({scheduled:[]}),+ getJobKinds:()=>Promise.resolve([]),+ getTelemetrySources:()=>Promise.resolve({sources:[]}),+ getTelemetryEventTypes:()=>Promise.resolve({event_types:[]}),+ getTelemetryEvents:(params)=>defer('telemetry',params),+};+const page=new URLSearchParams(location.search).get('page')||'services';+function FieldReset(){const [query,setQuery]=useState('old');return <><SearchField value={query} onSearch={setQuery} placeholder="Reset search"/><button onClick={()=>setQuery('')}>Reset search</button><output id="query">{query}</output></>}+const initial=page==='templates'?'/templates':page==='monitors'?'/monitors':page==='jobs'?'/jobs':page==='telemetry'?'/telemetry':'/services';+const app=page==='field'?<FieldReset/>:<MemoryRouter initialEntries={[initial]}><Routes><Route element={<TabGroupLayout tabs={[{to:'/services',label:'Services'},{to:'/templates',label:'Templates'},{to:'/monitors',label:'Monitors'},{to:'/jobs',label:'Jobs'},{to:'/telemetry',label:'Telemetry'}]}/>}><Route path="/services" element={<Services/>}/><Route path="/templates" element={<Templates/>}/><Route path="/monitors" element={<Monitors/>}/><Route path="/jobs" element={<Jobs/>}/><Route path="/telemetry" element={<Telemetry/>}/></Route></Routes></MemoryRouter>;+createRoot(document.getElementById('root')).render(page==='monitors'||page==='jobs'||page==='telemetry'?app:<React.StrictMode>{app}</React.StrictMode>);+`;+const server = await createServer({+ root, configFile: false, logLevel: 'error', resolve: { alias: { '@': path.join(root, 'src') } },+ cacheDir: path.join(root, 'node_modules/.vite-search-focus'), optimizeDeps: { entries: [] },+ server: { host: '127.0.0.1', port: 0 },+ plugins: [{+ name: 'search-focus-fixtures', enforce: 'pre',+ resolveId(id) {+ if (id === 'react-i18next') return '\0test-i18n';+ if (id.endsWith('/search-fixture.jsx')) return path.join(root, 'search-fixture.jsx');+ },+ load(id) {+ const normalized = id.replaceAll('\\', '/');+ if (id === '\0test-i18n') return `const t=(key,f)=>typeof f==='string'?f:(f&&(f.defaultValue_other||f.defaultValue))||key;export const useTranslation=()=>({t,i18n:{language:'en'}});export const Trans=({children})=>children;export const initReactI18next={type:'3rdParty',init(){}};`;+ if (normalized.endsWith('/src/services/api.js') || normalized.endsWith('/src/services/api/index.js')) return `const api=new Proxy({}, {get:(_,key)=>(...args)=>(window.testApi[key]?window.testApi[key](...args):Promise.resolve({}))});export {api};export default api;`;+ if (normalized.endsWith('/src/contexts/useToast.js')) return `const toast={error(){},success(){},info(){},warning(){}};export const useToast=()=>toast;`;+ if (normalized.endsWith('/src/contexts/useResourceTier.js')) return `export const useResourceTier=()=>({canHostApps:true,loading:false});`;+ if (normalized.endsWith('/src/contexts/useManagedProfile.js')) return `export const useManagedProfile=()=>({isControlHeld:()=>false,profile:null});`;+ if (normalized.endsWith('/src/contexts/useAuth.js')) return `export const useAuth=()=>({user:{id:1,role:'admin'},isAdmin:true,isAuthenticated:true,hasPermission:()=>true});`;+ if (normalized.endsWith('/src/hooks/useConfirm.js')) return `export const useConfirm=()=>({confirm:async()=>true,confirmState:{isOpen:false},handleConfirm(){},handleCancel(){}});`;+ if (normalized.endsWith('/src/plugins/contributions.js')) return `export const useContributions=()=>({tabs:[]});`;+ if (normalized.endsWith('/search-fixture.jsx')) return fixture;+ },+ configureServer(vite) {+ vite.middlewares.use('/search-check', async (_req, res) => {+ res.setHeader('Content-Type', 'text/html');+ res.end(await vite.transformIndexHtml('/search-check', '<div id="root"></div><script type="module" src="/search-fixture.jsx"></script>'));+ });+ },+ }, react()],+});++const executablePath = [process.env.CHROME_PATH, chromium.executablePath(), 'C:/Program Files/Google/Chrome/Application/chrome.exe', 'C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe'].find(candidate => candidate && existsSync(candidate));+let browser;+try {+ await server.listen();+ browser = await chromium.launch({ ...(executablePath ? { executablePath } : {}), headless: true });+ const page = await browser.newPage();+ const errors = [];+ page.on('pageerror', error => errors.push(error.message));+ await page.goto(`http://127.0.0.1:${server.httpServer.address().port}/search-check`);+ const search = page.getByRole('searchbox', { name: 'Search services…' });+ await search.waitFor();+ await search.click();+ await search.pressSequentially('serverkit', { delay: 100 });+ await page.waitForTimeout(350);+ assert.equal(await search.inputValue(), 'serverkit');+ assert.equal(await search.evaluate(el => document.activeElement === el), true);+ await search.fill('');+ await page.waitForTimeout(350);+ await search.pressSequentially('zzzzz', { delay: 300 });+ await page.waitForTimeout(350);+ assert.equal(await search.inputValue(), 'zzzzz');+ assert.equal(await search.evaluate(el => document.activeElement === el), true);+ console.log('PASS Services search keeps full text and focus, including no matches');+ await page.goto(`http://127.0.0.1:${server.httpServer.address().port}/search-check?page=templates`);+ const templateSearch = page.getByRole('searchbox', { name: 'Search templates…' });+ await templateSearch.waitFor();+ await templateSearch.click();+ await templateSearch.pressSequentially('wordpress', { delay: 300 });+ await page.waitForTimeout(500);+ assert.equal(await templateSearch.inputValue(), 'wordpress');+ assert.equal(await templateSearch.evaluate(el => document.activeElement === el), true);+ console.log('PASS Templates search keeps focus while requests load');+ await page.goto(`http://127.0.0.1:${server.httpServer.address().port}/search-check?page=field`);+ const resetSearch = page.getByRole('searchbox', { name: 'Reset search' });+ await resetSearch.fill('new');+ await page.getByRole('button', { name: 'Reset search' }).click();+ await page.waitForTimeout(350);+ assert.equal(await resetSearch.inputValue(), '');+ assert.equal(await page.locator('#query').textContent(), '');+ console.log('PASS clearing a search cancels a pending debounce');++ const cases = [+ { kind: 'monitors', label: 'Search monitors or targets…', response: (name) => ({ monitors: name ? [{ id: name, name, check_type: 'http', status: 'operational' }] : [] }) },+ { kind: 'jobs', label: 'Search by kind or owner…', response: (name) => ({ jobs: name ? [{ id: name, kind: name, status: 'queued' }] : [], total: name ? 1 : 0 }) },+ { kind: 'telemetry', label: 'Search messages…', response: (name) => ({ events: name ? [{ id: name, message: name, event_type: 'test', source: 'test', severity: 'info', timestamp: '2026-01-01T00:00:00Z' }] : [] }) },+ ];+ for (const { kind, label, response } of cases) {+ await page.goto(`http://127.0.0.1:${server.httpServer.address().port}/search-check?page=${kind}`);+ await page.waitForFunction(kind => window.searchPending[kind].length === 1, kind);+ await page.evaluate(({ kind, value }) => window.searchPending[kind][0].resolve(value), { kind, value: response('') });+ const input = page.getByRole('searchbox', { name: label });+ await input.waitFor();+ await input.fill('alpha');+ await page.waitForFunction(kind => window.searchPending[kind].length === 2, kind);+ await input.fill('beta');+ await page.waitForFunction(kind => window.searchPending[kind].length === 3, kind);+ await page.evaluate(({ kind, value }) => window.searchPending[kind][2].resolve(value), { kind, value: response('beta-result') });+ await page.getByText('beta-result').first().waitFor();+ await page.evaluate(({ kind, value }) => window.searchPending[kind][1].resolve(value), { kind, value: response('alpha-result') });+ await page.waitForTimeout(100);+ assert.equal(await page.getByText('beta-result').count() > 0, true, `${kind}: newest result disappeared`);+ assert.equal(await page.getByText('alpha-result').count(), 0, `${kind}: stale result appeared`);+ console.log(`PASS ${kind} ignores a late response from an older search`);+ }+ assert.deepEqual(errors, []);+} finally {+ await browser?.close();+ await server.close();+}diff --git a/frontend/src/components/ds/SearchField.jsx b/frontend/src/components/ds/SearchField.jsxindex 2262c71d..e55fb06f 100644--- a/frontend/src/components/ds/SearchField.jsx+++ b/frontend/src/components/ds/SearchField.jsx@@ -17,15 +17,24 @@ export function SearchField({const timer = useRef(null);// Sync when the parent resets/changes the value programmatically (e.g. a- // "Reset filters" action). Typing keeps text ahead of the debounced value,- // and setting to an equal string is a no-op, so this won't fight the user.- useEffect(() => { setText(value); }, [value]);+ // "Reset filters" action). Cancel any pending search so it cannot restore+ // the old query after the parent has cleared it.+ useEffect(() => {+ if (timer.current) {+ clearTimeout(timer.current);+ timer.current = null;+ }+ setText(value);+ }, [value]);useEffect(() => () => { if (timer.current) clearTimeout(timer.current); }, []);const handleChange = (next) => {setText(next);if (timer.current) clearTimeout(timer.current);- timer.current = setTimeout(() => onSearch?.(next), debounce);+ timer.current = setTimeout(() => {+ timer.current = null;+ onSearch?.(next);+ }, debounce);};return (diff --git a/frontend/src/hooks/useTopbarActions.js b/frontend/src/hooks/useTopbarActions.jsindex 096205c9..596e57ca 100644--- a/frontend/src/hooks/useTopbarActions.js+++ b/frontend/src/hooks/useTopbarActions.js@@ -20,9 +20,16 @@ export function useTopbarActions(actions, deps = []) {useEffect(() => {if (!setTopbarActions) return undefined;setTopbarActions(typeof actions === 'function' ? actions() : actions);- return () => setTopbarActions(null);// eslint-disable-next-line react-hooks/exhaustive-deps}, [setTopbarActions, ...deps]);++ // Clear only when this page leaves the tab group. Dependency changes+ // republish the actions in place; a transient clear is unnecessary and+ // can disrupt controls hosted in the bar.+ useEffect(() => {+ if (!setTopbarActions) return undefined;+ return () => setTopbarActions(null);+ }, [setTopbarActions]);}// The SECOND top-bar slot: a table's own chrome — search, the filter button anddiff --git a/frontend/src/pages/Jobs.jsx b/frontend/src/pages/Jobs.jsxindex 5fe655a6..b0b97cca 100644--- a/frontend/src/pages/Jobs.jsx+++ b/frontend/src/pages/Jobs.jsx@@ -10,7 +10,7 @@// Activity shows a view bar, a DataTable of runs, and server-side pagination// over a job store that can hold six figures of scheduler-tick rows.// Wired to the real ApiService job methods (see frontend/src/services/api/jobs.js).-import { useState, useEffect, useCallback, useMemo } from 'react';+import { useState, useEffect, useCallback, useMemo, useRef } from 'react';import { useLocation, useNavigate } from 'react-router-dom';import { ListChecks, RefreshCw, RotateCcw, XCircle, Play, Clock } from 'lucide-react';import api from '../services/api';@@ -174,6 +174,10 @@ export default function Jobs() {const [page, setPage] = useState(0);const [loading, setLoading] = useState(true);const [loadErrors, setLoadErrors] = useState({ jobs: null, scheduled: null });+ // Search, pagination and polling may finish out of order.+ const requestSeq = useRef(0);+ const currentQuery = useRef(null);+ currentQuery.current = { filters, q, page };// Table sort + column visibility, controlled so saved views can drive// them — same localStorage keys the DataTables used when uncontrolled.@@ -206,6 +210,10 @@ export default function Jobs() {}, []);const load = useCallback(async () => {+ const isCurrent = () => filters === currentQuery.current.filters+ && q === currentQuery.current.q && page === currentQuery.current.page;+ if (!isCurrent()) return;+ const request = ++requestSeq.current;try {const params = { limit: PAGE_SIZE, offset: page * PAGE_SIZE };if (filters.status) params.status = filters.status;@@ -221,6 +229,7 @@ export default function Jobs() {api.getJobs(params),api.getScheduledJobs(),]);+ if (request !== requestSeq.current || !isCurrent()) return;if (jobsRes.status === 'fulfilled') {const data = jobsRes.value;setJobs(data?.jobs || []);@@ -235,7 +244,7 @@ export default function Jobs() {scheduled: schedRes.status === 'rejected' ? schedRes.reason : null,});} finally {- setLoading(false);+ if (request === requestSeq.current && isCurrent()) setLoading(false);}}, [filters, q, page]);diff --git a/frontend/src/pages/Monitors.jsx b/frontend/src/pages/Monitors.jsxindex cc0e3460..ac8062c4 100644--- a/frontend/src/pages/Monitors.jsx+++ b/frontend/src/pages/Monitors.jsx@@ -9,7 +9,7 @@// rows this client never loaded), while the grid chrome's column rules narrow// the rows already on screen. A saved view carries both — the server pair under// `page.serverFilters`, the rules under `columnFilters`.-import { useCallback, useEffect, useMemo, useState } from 'react';+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';import { useNavigate } from 'react-router-dom';import {ChevronRight, Globe, Pause, Play, Plus, Radar, RefreshCw,@@ -195,23 +195,35 @@ export default function Monitors() {const [formOpen, setFormOpen] = useState(false);const [form, setForm] = useState(emptyForm);const [saving, setSaving] = useState(false);+ // Search changes and polling can overlap; only the latest current query wins.+ const requestSeq = useRef(0);+ const currentQuery = useRef(null);+ currentQuery.current = { q, status: filters.status, type: filters.type };// Bumps once a second so "next check in 42s" actually counts down between// polls instead of sitting still for 15 seconds at a time.const [, setTick] = useState(0);const load = useCallback(async () => {+ const query = { q, status: filters.status, type: filters.type };+ const isCurrent = () => query.q === currentQuery.current.q+ && query.status === currentQuery.current.status+ && query.type === currentQuery.current.type;+ if (!isCurrent()) return;+ const request = ++requestSeq.current;try {const listRes = await api.getMonitors({q: q || undefined, status: filters.status || undefined, type: filters.type || undefined,});+ if (request !== requestSeq.current || !isCurrent()) return;setMonitors(listRes?.monitors || []);setLoadError(null);} catch (err) {+ if (request !== requestSeq.current || !isCurrent()) return;// Keep the last good list on screen rather than blanking the page;// the error shows above it, or in its place on a first load.setLoadError(err);} finally {- setLoading(false);+ if (request === requestSeq.current && isCurrent()) setLoading(false);}}, [q, filters.status, filters.type]);diff --git a/frontend/src/pages/Telemetry.jsx b/frontend/src/pages/Telemetry.jsxindex 9056ca4a..7abecd78 100644--- a/frontend/src/pages/Telemetry.jsx+++ b/frontend/src/pages/Telemetry.jsx@@ -18,7 +18,7 @@// sixth, "Total (24h)", was a real backend aggregate, but the view row is the// view name alone now and there was nowhere left to put it — so the// /telemetry/stats call went with it. The footer counts what is loaded.-import { useCallback, useEffect, useMemo, useState } from 'react';+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';import {Activity, ChevronRight, Info, Loader2, RefreshCw, Trash2,} from 'lucide-react';@@ -127,6 +127,11 @@ export default function Telemetry() {const [filtersOpen, setFiltersOpen] = useState(false);const [filters, setFilters] = useState(EMPTY_FILTERS);const [q, setQ] = useState('');+ // Guard both event pages and source-dependent options against late responses.+ const eventRequestSeq = useRef(0);+ const optionsRequestSeq = useRef(0);+ const currentQuery = useRef(null);+ currentQuery.current = { filters, q };// Table sort + column visibility, controlled so saved views can drive// them — same localStorage keys the DataTable used when uncontrolled.@@ -145,11 +150,14 @@ export default function Telemetry() {}, []);const loadFilterOptions = useCallback(async () => {+ if (filters.source !== currentQuery.current.filters.source) return;+ const request = ++optionsRequestSeq.current;try {const [sourcesData, typesData] = await Promise.all([api.getTelemetrySources(),api.getTelemetryEventTypes({ source: filters.source || undefined }),]);+ if (request !== optionsRequestSeq.current || filters.source !== currentQuery.current.filters.source) return;setSources(sourcesData.sources || []);setEventTypes(typesData.event_types || []);} catch {@@ -158,6 +166,9 @@ export default function Telemetry() {}, [filters.source]);const fetchEvents = useCallback(async (nextPage = 1, replace = true) => {+ const isCurrent = () => filters === currentQuery.current.filters && q === currentQuery.current.q;+ if (!isCurrent()) return;+ const request = ++eventRequestSeq.current;setLoading(true);try {const params = { ...filters, q, per_page: PAGE_SIZE, page: nextPage };@@ -165,18 +176,20 @@ export default function Telemetry() {if (params[key] === '') delete params[key];});const data = await api.getTelemetryEvents(params);+ if (request !== eventRequestSeq.current || !isCurrent()) return;const fresh = data.events || [];setEvents((prev) => (replace ? fresh : [...prev, ...fresh]));setHasMore(fresh.length === PAGE_SIZE);setPage(nextPage);setLoadError(null);} catch (err) {+ if (request !== eventRequestSeq.current || !isCurrent()) return;// Rendered in the list area (with Retry) rather than as a toast// that fades and leaves "No events recorded yet" behind.setLoadError(err);setHasMore(false);} finally {- setLoading(false);+ if (request === eventRequestSeq.current && isCurrent()) setLoading(false);}}, [filters, q]);diff --git a/frontend/src/pages/Templates.jsx b/frontend/src/pages/Templates.jsxindex 5fa5cc95..bf07fd8d 100644--- a/frontend/src/pages/Templates.jsx+++ b/frontend/src/pages/Templates.jsx@@ -521,6 +521,7 @@ const Templates = () => {if (loading) {return (<div className="sk-tabgroup__inner">+ {topbarChrome}<EmptyState loading loadingVariant="cards" title={t('app.templates.loadingTemplates', 'Loading templates')} /></div>);