Skip to content

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.

Refetch logs with the values just chosen

Juan Denis5e4ca2e8a10a
diff --git a/.github/workflows/frontend-ci.yml b/.github/workflows/frontend-ci.yml
index e28b573e..6d6444a8 100644
--- a/.github/workflows/frontend-ci.yml
+++ b/.github/workflows/frontend-ci.yml
@@ -71,6 +71,9 @@ jobs:
- name: SVG sanitizer browser regressions
working-directory: frontend
run: npm run test:sanitize-svg
+ - name: Terminal log viewer browser regressions
+ working-directory: frontend
+ run: npm run test:terminal-logs
- name: Upload Settings screenshots
if: always()
uses: actions/upload-artifact@v4
diff --git a/frontend/package.json b/frontend/package.json
index 06dab10c..c584231a 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -17,6 +17,7 @@
"test:hooks": "node scripts/hooks-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",
"lint:settings-index": "node scripts/check-settings-index.mjs",
"lint:fonts": "node scripts/check-font-integrity.mjs",
"lint:status": "node scripts/check-status-one-door.mjs",
diff --git a/frontend/scripts/terminal-logs-browser.mjs b/frontend/scripts/terminal-logs-browser.mjs
new file mode 100644
index 00000000..b3dc0707
--- /dev/null
+++ b/frontend/scripts/terminal-logs-browser.mjs
@@ -0,0 +1,108 @@
+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';
+
+// The real Terminal page. Changing the line count, clearing a search or
+// picking a journal unit used to re-fetch through a stale closure, i.e. with
+// the PREVIOUS value. Only HTTP, toasts and translation are stubbed.
+const root = fileURLToPath(new URL('../', import.meta.url));
+const fixture = `
+import React from 'react';
+import {createRoot} from 'react-dom/client';
+import {MemoryRouter,Routes,Route} from 'react-router-dom';
+import Terminal from '/src/pages/Terminal.jsx';
+window.calls=[];
+const log=(...c)=>{window.calls.push(c);return Promise.resolve({content:'line',lines:['line']});};
+window.testApi={
+ getLogFiles:()=>Promise.resolve({logs:[{path:'/var/log/syslog',name:'syslog',size:10}]}),
+ readLog:(p,n)=>log('read',p,n),
+ searchLog:(p,q,n)=>log('search',p,q,n),
+ getJournalLogs:(u,n)=>log('journal',u,n),
+};
+const tab=new URLSearchParams(location.search).get('tab');
+createRoot(document.getElementById('root')).render(
+ <MemoryRouter initialEntries={['/terminal/'+tab]}><Routes><Route path='/terminal/:tab' element={<Terminal/>}/></Routes></MemoryRouter>);
+`;
+const server = await createServer({
+ root, configFile: false, logLevel: 'error', resolve: { alias: { '@': path.join(root, 'src') } },
+ cacheDir: path.join(root, 'node_modules/.vite-terminal-regression'),
+ server: { host: '127.0.0.1', port: 0 },
+ plugins: [{
+ name: 'terminal-regression-fixtures', enforce: 'pre',
+ resolveId(id) {
+ if (id === 'react-i18next') return '\0test-i18n';
+ if (id.endsWith('/terminal-fixture.jsx')) return path.join(root, 'terminal-fixture.jsx');
+ },
+ load(id) {
+ const normalized = id.replaceAll('\\', '/');
+ if (id === '\0test-i18n') return `const t=(key,fallback)=>typeof fallback==='string'?fallback:key;export const useTranslation=()=>({t,i18n:{language:'en'}});export const Trans=({children})=>children;export const initReactI18next={type:'3rdParty',init(){}};`;
+ if (normalized.endsWith('/src/contexts/useAuth.js')) return `import {createContext} from 'react';export const AuthContext=createContext(null);const auth={user:{id:1,username:'admin',role:'admin'},isAdmin:true,isAuthenticated:true,hasPermission:()=>true};export const useAuth=()=>auth;`;
+ if (normalized.endsWith('/src/contexts/useWorkspace.js')) return `const ws={activeWorkspaceId:null,activeWorkspace:null,workspaces:[],setActiveWorkspace(){}};export const useWorkspace=()=>ws;`;
+ if (normalized.endsWith('/src/contexts/useToast.js')) return `const toast={error(){},success(){},info(){},warning(){}};export const useToast=()=>toast;`;
+ if (normalized.endsWith('/src/services/api.js') || normalized.endsWith('/src/services/api/index.js')) return `export default new Proxy({}, {get:(_,key)=>(...args)=>(window.testApi[key]?window.testApi[key](...args):Promise.resolve({}))});`;
+ if (normalized.endsWith('/terminal-fixture.jsx')) return fixture;
+ },
+ configureServer(vite) {
+ vite.middlewares.use('/terminal-check', async (_req, res) => {
+ res.setHeader('Content-Type', 'text/html');
+ res.end(await vite.transformIndexHtml('/terminal-check', '<div id="root"></div><script type="module" src="/terminal-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));
+const LINE_OPTIONS = [50, 100, 200, 500, 1000, 5000];
+async function pickLines(page, n) {
+ await page.getByLabel('Lines to fetch').first().click();
+ await page.getByRole('option').nth(LINE_OPTIONS.indexOf(n)).click();
+}
+const last = (page, kind) => page.evaluate(k => window.calls.filter(c => c[0] === k).at(-1), kind);
+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.addInitScript(() => localStorage.clear());
+ const base = `http://127.0.0.1:${server.httpServer.address().port}/terminal-check`;
+
+ await page.goto(`${base}?tab=logs`);
+ await page.getByText('syslog', { exact: false }).first().click();
+ await page.waitForFunction(() => window.calls.some(c => c[0] === 'read'));
+ const before = (await last(page, 'read'))[2];
+ await pickLines(page, 1000);
+ await page.waitForFunction(() => window.calls.filter(c => c[0] === 'read').at(-1)[2] === 1000);
+ assert.notEqual(before, 1000);
+ console.log('PASS changing the line count re-reads the file with the NEW count');
+
+ const search = page.getByPlaceholder('Search in log…').first();
+ await search.fill('error');
+ await search.press('Enter');
+ await page.waitForFunction(() => window.calls.some(c => c[0] === 'search'));
+ const reads = await page.evaluate(() => window.calls.filter(c => c[0] === 'read').length);
+ const searches = await page.evaluate(() => window.calls.filter(c => c[0] === 'search').length);
+ await page.getByTitle('Clear', { exact: true }).first().click();
+ await page.waitForFunction(n => window.calls.filter(c => c[0] === 'read').length > n, reads);
+ assert.equal(await page.evaluate(() => window.calls.filter(c => c[0] === 'search').length), searches);
+ console.log('PASS clearing the search re-reads unfiltered instead of searching the old pattern');
+
+ await page.goto(`${base}?tab=journal`);
+ await page.waitForFunction(() => window.calls.some(c => c[0] === 'journal'));
+ await page.getByText('Nginx', { exact: true }).first().click();
+ await page.waitForFunction(() => window.calls.filter(c => c[0] === 'journal').at(-1)[1] === 'nginx');
+ await pickLines(page, 1000);
+ await page.waitForFunction(() => {
+ const c = window.calls.filter(x => x[0] === 'journal').at(-1);
+ return c[1] === 'nginx' && c[2] === 1000;
+ });
+ console.log('PASS picking a unit and a line count fetch the journal with the NEW values');
+ assert.deepEqual(errors, []);
+} finally {
+ await browser?.close();
+ await server.close();
+}
diff --git a/frontend/src/pages/Terminal.jsx b/frontend/src/pages/Terminal.jsx
index 0586155a..566ba3c1 100644
--- a/frontend/src/pages/Terminal.jsx
+++ b/frontend/src/pages/Terminal.jsx
@@ -246,14 +246,18 @@ const LogFilesTab = () => {
}
}
- async function loadLogContent(logPath, showLoading = true) {
+ // Callers that just set state pass the new values: this render's
+ // lineCount/appliedSearch are still the old ones.
+ async function loadLogContent(logPath, showLoading = true, overrides = {}) {
+ const lines = overrides.lineCount ?? lineCount;
+ const search = overrides.search ?? appliedSearch;
if (showLoading) setLoadingContent(true);
try {
let data;
- if (appliedSearch.trim()) {
- data = await api.searchLog(logPath, appliedSearch, lineCount);
+ if (search.trim()) {
+ data = await api.searchLog(logPath, search, lines);
} else {
- data = await api.readLog(logPath, lineCount);
+ data = await api.readLog(logPath, lines);
}
setLogContent(data.content || data.lines?.join('\n') || '');
setSelectedLog(logPath);
@@ -297,7 +301,7 @@ const LogFilesTab = () => {
function handleSearchClear() {
setSearchPattern('');
setAppliedSearch('');
- if (selectedLog) loadLogContent(selectedLog);
+ if (selectedLog) loadLogContent(selectedLog, true, { search: '' });
}
function scrollToBottom() {
@@ -412,7 +416,7 @@ const LogFilesTab = () => {
onSearchSubmit={handleSearchSubmit}
onSearchClear={handleSearchClear}
lineCount={lineCount}
- onLineCountChange={(n) => { setLineCount(n); if (selectedLog) setTimeout(() => loadLogContent(selectedLog), 0); }}
+ onLineCountChange={(n) => { setLineCount(n); if (selectedLog) loadLogContent(selectedLog, true, { lineCount: n }); }}
autoRefresh={autoRefresh}
onAutoRefreshToggle={() => setAutoRefresh(!autoRefresh)}
showLineNumbers={showLineNumbers}
@@ -533,7 +537,10 @@ const JournalTab = () => {
immediate: false,
});
- async function loadJournalLogs(showSpinner = true) {
+ // Same as loadLogContent: pass values that were just set.
+ async function loadJournalLogs(showSpinner = true, overrides = {}) {
+ const lines = overrides.lineCount ?? lineCount;
+ const selectedUnit = overrides.unit ?? unit;
if (isRemote && !REMOTE_JOURNAL_SUPPORTED.has('read')) {
setLogContent('');
setSource('');
@@ -544,7 +551,7 @@ const JournalTab = () => {
if (showSpinner) setLoading(true);
setUnavailable(false);
try {
- const data = await api.getJournalLogs(unit || null, lineCount);
+ const data = await api.getJournalLogs(selectedUnit || null, lines);
setLogContent(data.lines?.join('\n') || '');
setSource(data.source || '');
setSourceLabel(data.source_label || '');
@@ -567,18 +574,18 @@ const JournalTab = () => {
function pickUnit(u) {
setUnit(u);
setUnitInput(u);
- setTimeout(() => loadJournalLogs(), 0);
+ loadJournalLogs(true, { unit: u });
}
function clearUnit() {
setUnit('');
setUnitInput('');
- setTimeout(() => loadJournalLogs(), 0);
+ loadJournalLogs(true, { unit: '' });
}
function applyUnitInput() {
setUnit(unitInput);
- setTimeout(() => loadJournalLogs(), 0);
+ loadJournalLogs(true, { unit: unitInput });
}
function handleDownload() {
@@ -698,7 +705,7 @@ const JournalTab = () => {
{filteredUnits.map(u => (
<SharedButton variant="unstyled" type="button"
key={u.id}
- className={`lv-file lv-file--compact ${unit === u.id ? 'active' : ''}}`}
+ className={`lv-file lv-file--compact ${unit === u.id ? 'active' : ''}`}
onClick={() => pickUnit(u.id)}
>
<span className={`lv-file-dot kind-${u.kind}`} />
@@ -750,7 +757,7 @@ const JournalTab = () => {
onSearchSubmit={() => setAppliedSearch(searchPattern)}
onSearchClear={() => { setSearchPattern(''); setAppliedSearch(''); }}
lineCount={lineCount}
- onLineCountChange={(n) => { setLineCount(n); setTimeout(loadJournalLogs, 0); }}
+ onLineCountChange={(n) => { setLineCount(n); loadJournalLogs(true, { lineCount: n }); }}
autoRefresh={autoRefresh}
onAutoRefreshToggle={() => setAutoRefresh(!autoRefresh)}
showLineNumbers={showLineNumbers}