Files
LEDMatrix/web_interface/templates/v3/partials/logs.html
T
ChuckandClaude Opus 5.5 f6afbdbb15 fix(web): Cache/Logs error mix-up, store errors, tab fallbacks; remove ~2.5k lines of dead JS (#639)
* fix(web): keep Cache and Logs helpers out of each other's way

Both partials declared top-level showError and escapeHtml. Their scripts
run at global scope after every HTMX swap, so whichever tab was opened
last owned window.showError, and a Cache failure after visiting Logs
rendered into the Logs panel (and the other way round). Each script is
now an IIFE; Cache still exports deleteCacheFile for its row buttons.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(web): make the HTMX-failure fallbacks for tab panels actually run

- The "HTMX never loaded" fallback read appElement.__x.$data, which is
  Alpine 2. The page ships Alpine 3, so the check was always false and
  the Overview never loaded without HTMX. It now reads Alpine.$data().
- The Overview and WiFi panels used hx-on::htmx:response-error, which
  htmx expands to "htmx:htmx:response-error", an event that never fires.
- loadTabContent sent requests with <body> as the source, so htmx fired
  its events on <body> and no panel's hx-on handler ran at all. The
  panel is now the source. htmx also resolves its promise on a 4xx/5xx,
  and the panel was stamped data-loaded anyway, leaving a skeleton that
  never retried; it is now stamped only when no responseError fired.

loadPluginsDirect, loadOverviewDirect and loadWifiDirect are merged into
one window.loadPartialDirect(id, url), which also runs the partial's
inline scripts before Alpine sees the markup (as htmx-config.js does on
htmx:afterSwap). The ~10 s "htmx never arrived" path in loadTabContent
uses it for every tab instead of four hard-coded ones.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(web): store and registry failures no longer wipe the Plugin Manager

showError replaced the whole #plugins-content with an error message, so
one failed store search, custom-registry install or saved-repository
call took the installed list, the store and every control with it, with
no way back short of reloading the tab. Those failures are now error
notifications. The full-panel message is kept only for a first load of
the installed list that failed (nothing to show yet); a failed refresh
of an already-rendered list is a notification too. showSuccess's
fallback branch, which wrote the message into innerHTML unescaped, is
gone: showNotification always exists.

The "Please try refreshing your browser" hint tested for the text
"Failed to Fetch", which no browser produces (Chrome says "Failed to
fetch", Firefox "NetworkError..."), so it never appeared. It now keys on
the failure itself: a TypeError from fetch(), or PluginAPI's
NETWORK_ERROR wrapper around one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(web): escape plugin action and install output on every path

executePluginAction escaped data.message and data.output when an action
failed but put data.message straight into innerHTML when it succeeded,
and set the OAuth step-2 button's innerHTML from the manifest's
step2_button_text. Plugin actions run plugin code, so that is plugin- or
server-controlled markup in the page. Both paths now escape, and the
button label is set with textContent.

The same pattern sat in the install-from-GitHub-URL status lines
(plugin_id, the server's message, and error.message, which can echo a
repository URL) and the custom-registry load error; those are escaped
too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(web): file-upload widget owns the image list and schedule editor

plugins_manager.js loads after the widget bundle, so its older copies of
deleteUploadedFile, updateImageList, hideUploadProgress, formatDate,
openImageSchedule, toggleImageScheduleEnabled, updateImageSchedule{Mode,
Time,Day} and updateCheckboxGroupData replaced the widget's. They are
deleted; the widget files are the only definitions.

Before switching over, the two sets were diffed and fixed so nothing
regresses:

- The old copy labelled the schedule/delete buttons for screen readers
  and lazy-loaded thumbnails; the widget now does both.
- The schedule button did nothing on a card rendered by
  plugin_config.html whenever the image id is a UUID (every upload): the
  template turns "-" into "_" in the editor's id, and neither JS copy
  did. Both now use the template's rule.
- The widget's "keep the open editor open" copied the editor's innerHTML
  into the new list. That dropped its event listeners and showed the old
  values, so after the first change the editor looked live but ignored
  input. A schedule edit now saves to the hidden input and updates the
  card's summary in place without re-rendering the list; a list re-render
  (upload, delete) rebuilds an open editor from the data. Editor controls
  are routed by one delegated change listener, so there are no
  per-element listeners to lose.
- The old deleteUploadedFile had a JSON branch that removed a
  #file_<id> element and skipped the re-render. No template or script
  renders such an element, and JSON uploads are listed through
  updateImageList like images, so re-rendering (the widget's behaviour) is
  the consistent one; the branch was not carried over.
- The template always renders the summary line (".image-schedule-summary",
  "Always shown" when unscheduled) so an edit has a line to update.

The inline-handler test evaluated plugins_manager.js's updateImageList;
test_file_upload_widget.js now covers the widget's list and editor.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(web): delete the unused handleCredentialsUpload

Its last caller went when plugin_config.html switched credential uploads
to the file-upload widget's handleSingleFileSelect. Nothing in the web
UI, the tests or the plugin monorepo references it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(web): delete dead and shadowed front-end code

Nothing calls any of these (checked across web_interface/, test/ and the
ledmatrix-plugins monorepo, including hx-*/x-*/onclick attributes):

- app-shell.js: the Alpine methods refreshPlugins (it called a
  nonexistent this.searchPluginStore), loadPluginConfig,
  savePluginConfig, getSchemaPropertyType, escapeCssSelector,
  formatCommitInfo and formatDateInfo, and the top-level copies of
  savePluginConfig, getSchemaPropertyType, escapeCssSelector,
  formatCommitInfo, formatDateInfo and togglePluginFromTab. Plugin config
  forms save through hx-post in plugin_config.html.
- window.reconnectSSE (app-shell.js); window.updateArrayTableAddButtonState
  (array-table.js).
- toggleNestedSection, defined twice (app-shell.js and
  plugins_manager.js) and called from nowhere.
- plugins_manager.js: the window.initializePlugins wrapper around an
  IIFE-local origInit that was always undefined, and __pluginDomReady,
  which was written but never read.
- display.html's fixInvalidNumberInputs fallback: app-shell.js defines it
  before any partial loads.
- base.html's window.loadCodeMirror and the two CodeMirror stylesheet
  preloads, and the .CodeMirror rules in plugins.html. The raw JSON
  editor is a plain textarea.

Also deleted: app-shell.js definitions that a later script always
replaced, so they never ran: executePluginAction (plugins_manager.js
assigns its own), uninstallPlugin and its pollUninstallOperation
(plugins_manager.js), and updateAllPlugins (install_manager.js).

vendor/codemirror stays: test/test_web_smoke.py still requests
codemirror.min.js as a sample static asset.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(web): call showNotification without checking it exists

app-shell.js defines window.showNotification (a stand-in that queues
until the notification widget loads) and base.html runs it, deferred,
before every other script that notifies: app.js, the utilities, the
widget bundle, plugins_manager.js, and all partials, which HTMX loads
after the page. The 81 `typeof showNotification === 'function'` /
`!== 'undefined'` checks, the `window.showNotification || console.log`
and `|| alert` fallbacks, and their else branches (alert(), console
output, and schedule.html's own hand-built toast) could never take the
fallback path. They are removed, as is fonts.html's second copy of the
queueing stand-in.

The stand-in in app-shell.js keeps its guard (it must not replace the
widget's implementation if load order ever changes), and BaseWidget's
public notify()/getNotificationFunction() keep their shape for widgets
that plugins ship.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(web): one HTML escaper, window.LEDEscape

About 30 files each carried their own escapeHtml / escapeAttr / escHtml /
_esc / escapeJs. They disagreed: several (notification.js, display.html's
escapeHtml, operation_history.html, the app() stub) did not escape
quotes, google-calendar-picker.js and tools.html's escHtml left ' alone,
and some turned 0 into ''. Most were fine only because the quote-safe
widget copies were preferred at runtime.

window.LEDEscape now lives at the top of app-early.js, a blocking script
in <head>, so it exists before any other script runs:

  html(v)          & < > " ' as entities, null/undefined as ''
  attr(v)          the same, for call sites that want to say "attribute"
  jsStringAttr(v)  a JS string literal safe inside an inline handler

Every former copy is now a one-line name for it (kept so call sites do
not change), widgets included, with no fallback. plugins_manager.js
loses its four escapeJs wrappers (callers use jsStringAttr), the
duplicate escapeAttr and escapeHtml inside renderInstalledCards and
renderCustomRegistryPlugins, and the window.escapeHtml /
window.escapeAttribute exports, which nothing read.
addArrayObjectItem's fallback markup (with a sixth hand-written escape
chain) is gone too: window.renderArrayObjectItem is defined earlier in
the same file, so the fallback could not run. The unused escapeHtml
methods on the Alpine app (app-early.js stub and app-shell.js) are
deleted.

test_html_escaping.js now runs LEDEscape and every remaining name for it,
and fails if a hand-rolled escaper reappears anywhere in web_interface/.
Suites that evaluate slices of plugins_manager.js or widget files load
LEDEscape from app-early.js through test/js/led_escape.js.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(web): stop htmx re-running partial scripts after every tab load

htmx-config.js runs each swapped-in <script> itself on htmx:afterSwap
and meant to turn htmx's own script handling off with
htmx.config.allowScriptTags = false. It did that once, while setting up,
but base.html loads htmx with a dynamic <script>, so htmx was not defined
yet and the setting never applied. On every tab load htmx then tried to
run each script again in its settle phase, found it already replaced
(no parent node) and threw "Cannot read properties of null (reading
'insertBefore')" into the console, which also skipped the rest of that
swap's settle tasks.

The setting is now applied in the afterSwap handler, which always runs
after htmx exists and before htmx settles the same swap.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(web): show "--" for a system stat the server could not read

The stats stream and /system/status now send null for a metric they
cannot read (cpu_temp off a Pi, for one) instead of 0. updateSystemStats
built the header and Overview text as value + unit, so a null showed as
"null°C". CPU, memory and temperature, in the header and on the
Overview, now render "--" plus the unit for null or a missing field --
the same placeholder the page starts with, and what tools.html already
shows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(web): one Alpine accessor and one plugin-list signal

window.getApp() (app-early.js) returns the root <body x-data="app()">
component through Alpine's public Alpine.$data, or null before Alpine
has initialised it. It replaces the private el._x_dataStack[0] reads in
app.js, app-early.js, app-shell.js, settings-search.js, overview.html and
plugins_manager.js, the three local getAppComponent/appData/getAppData
copies, and the Alpine 2 el.__x.$data fallbacks, which Alpine 3 never
provides.

Publishing the installed-plugin list: one load set window.installedPlugins
and dispatched pluginsUpdated twice (loadInstalledPlugins, then
renderInstalledPlugins), then wrote into the Alpine component through
_x_dataStack[0] and called its updatePluginTabs() directly, and
app-early.js's global listener set window.installedPlugins a third time
and called updatePluginTabs() again. Now renderInstalledPlugins is the
one publisher: it sets window.installedPlugins and dispatches
pluginsUpdated once, and the full app()'s listener (app-shell.js) is the
receiver. The app-early.js listener only builds the tab row while the app
is not the full implementation yet. The "grid not loaded yet" case is a
normal state (Plugin Manager tab not opened), so it logs through
pluginLog instead of console.warn.

updatePluginTabs had a "Debounce" comment and clearTimeout over a timer
nothing ever set, and two identical branches; it now just calls
_doUpdatePluginTabs (app-early.js detects the full implementation by
that name in its source, which the new comment says).

app()'s unused baseComponent lookup is removed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(web): reload the plugin list after installs and failed toggles

Several callers refreshed the installed list with

    if (typeof loadInstalledPlugins === 'function') loadInstalledPlugins();
    else if (typeof window.loadInstalledPlugins === 'function') ...

but loadInstalledPlugins is local to the plugin-manager IIFE and
window.loadInstalledPlugins is never defined, so from outside that IIFE
both tests were false and nothing reloaded:

- A failed plugin toggle left the switch drawn in the new state while
  the data said the old one. It now re-renders from the reverted data.
  The optimistic in-place edit also has to forget the grid's
  last-rendered markup, or setGridHtmlIfChanged sees identical HTML and
  skips the revert. A successful toggle still keeps the switch (and
  focus) as drawn.
- Installing from a GitHub URL (the early handleGitHubPluginInstall),
  installing or uploading a Starlark app, and toggling a Starlark app on
  its config tab never refreshed the list, so the new app had no tab or
  Installed badge until the page was reloaded. They now force a reload
  through window.pluginManager.loadInstalledPlugins(true), and the
  Starlark grid redraws when that finishes instead of after a fixed
  500 ms.
- The Starlark uninstall inside the IIFE reloaded from the 3 s cache,
  which could still hold the app; it now forces a reload.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(web): route debug output through debugLog

base.html defines window.debugLog, gated on localStorage.pluginDebug.
plugins_manager.js read the same key twice more into its own flags
(_PLUGIN_DEBUG_EARLY, and PLUGIN_DEBUG behind a pluginLog() wrapper), and
api_client.js's RequestThrottler had a separate `debug` property with a
setDebug() that nothing called. All of it now goes through debugLog. The
"functions defined" dumps with their ✓ lines, and two per-plugin
"enabled=" loops that ran on every render, are dropped; "[PLUGINS STUB]"
labels on code that has not been a stub for a long time read
"[PLUGINS]".

Ungated console.log calls that announced normal events on every page
load or action (settings search and tooltips registering, every toast
repeated to the console, the schedule pickers initialising, widget
registry unregister/clear) go through debugLog too. What remains on
console.log is the widget registry's on-demand LEDMatrixWidgets.debug()
dump and BaseWidget.notify's no-notifier fallback.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(web): drop waits and guards that could never fire

- handlePluginAction polled up to 10 x 50 ms for window.togglePlugin,
  configurePlugin, updatePlugin and uninstallPlugin before calling them.
  All four are defined when the scripts load, before any card can be
  clicked, so the poll always succeeded at once; it now calls them.
  The long thinking-aloud comment over the toggle state is replaced by
  two lines on why the stored state, not the checkbox, decides.
- initializePlugins checked typeof on setupGitHubInstallHandlers and
  applyStoreFiltersAndSort, function declarations in the same IIFE, and
  wrapped window.checkGitHubAuthStatus(), which returns a promise with
  its own .catch, in try/catch.
- searchPluginStore wrapped each "#store-count" update (a getElementById
  and an innerHTML assignment) in try/catch four times; one
  setStoreCount() helper does it. The store's post-render re-attach of
  the GitHub token handler dropped its try/catch and existence checks
  for the same reason.
- The load-time fallback outside the IIFE tested typeof
  initializePluginPageWhenReady, which is IIFE-local and so always
  undefined there; it calls window.initPluginsPage directly.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(web): delete two unused plugin-manager helpers

stopOnDemand (IIFE-local; the page's stop button calls window.stopOnDemand
from app-shell.js) and debounce had no callers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(web): document the plugin-config handlers templates call

validatePluginConfigForm, handleConfigSave, handleToggleResponse,
handlePluginUpdate and refreshPluginConfig each get a JSDoc naming the
attribute in partials/plugin_config.html that calls it and what the
return value means (only validatePluginConfigForm's matters: false
cancels the submit).

- The `if (!window.__pluginConfigHandlersInitialized)` wrapper is gone:
  app-shell.js runs once per page, so it was never false. The block is
  dedented one level; `git diff -w` shows the real change.
- The three handlers read xhr.responseJSON first. XMLHttpRequest has no
  such property (it is jQuery's), so that branch never ran; one
  xhrJson(xhr) helper parses responseText for all of them, with the same
  fallbacks as before.
- runPluginOnDemand and stopOnDemand checked that plugins_manager.js's
  openOnDemandModal/requestOnDemandStop exist; plugins_manager.js is on
  every page, so they call them.
- fixInvalidNumberInputs had a stray "Notification helper function"
  comment on top of its own; a leftover "section toggle ... duplicate
  definition removed" note is gone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(web): one toast per save, and a failed durations save says so

app.js's global htmx:afterRequest listener showed the server's message
for every htmx request, and every form and button that posts through
htmx (plugin config save/toggle/update, Display, Durations, General,
Schedule, Dim schedule, the Overview actions) also reports its own result
from hx-on after-request. Each save showed two toasts. The global
listener now stays quiet for a request whose element, or its form, has
its own after-request handler.

That exposed the Rotation & Durations form's handler, which read
xhr.responseJSON: XMLHttpRequest has no such property, so it always said
"Durations saved" in green, even when the save failed (the global toast
had been the only place the error showed). display.html already had a
correct version (2xx only counts as saved; the server's message wins;
its status may refine success but never overturn failure). That is now
window.showSaveResult(xhr, savedText, failedText) in app.js, used by the
Display, Durations and General forms; General's inline copy of the same
logic is gone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(web): file headers and comments that say what the code does now

- plugins_manager.js, app-shell.js, app.js and app-early.js open with a
  header: what the file owns, how base.html loads it and in what order
  relative to the others, and the globals it defines. app-early.js's
  app() stub also says why it exists and that, with app-shell.js now
  loaded before Alpine, it does not run in practice.
- base.html's note on plugins_manager.js said it must load last to win
  over same-named functions in app.js/app-shell.js; there are none left,
  so it now gives the real reason (it uses everything loaded before it).
- Change-narration and "already defined at the top, no need to redefine"
  notes are gone or rewritten as present-tense reasons; comments that
  were wrong are fixed ("Toggle password visibility" over the function
  that opens the token panel, "Insert before the closing </nav>" over an
  appendChild, "(from v2)", the export note that still listed
  escapeHtml). About forty comments that restated the line below them
  are removed, and a second window.currentPluginConfig = null outside the
  IIFE is dropped (the IIFE sets it).
- The file-upload, checkbox-group and custom-feeds widgets' render()
  stubs say plainly that the widget is rendered server-side, instead of
  "for now" / "placeholder for future client-side rendering".

test_plugin_action_delegation.js sliced the source up to one of the
removed notes; it now ends the slice at the next section header.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(web): keep the escapeHtml/escapeAttribute globals for plugin pages

6da77363 removed window.escapeHtml and window.escapeAttribute because nothing in core or the plugin monorepo read them. Plugin web UIs served through serve_plugin_web_ui and third-party plugin pages may still call them, so they come back as aliases of window.LEDEscape.html and .attr, defined in app-early.js before any other script runs. test_html_escaping.js checks the aliases exist.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(changelog): web-frontend

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(web): encode the image thumbnail path; match script tags case-insensitively

CodeQL flagged the upload widget building an <img> src from a stored path,
and the escaper test extracting inline scripts with a case-sensitive regex.
Each path segment is now URL-encoded (still a same-origin path, and correct
for names with spaces or

* fix(web): clear Codacy findings in the escaper, app shell and upload widget

- LEDEscape looks entities up in a Map instead of indexing an object.
- showNotification is declared as a global for app-shell.js.
- openImageSchedule checks the index is a non-negative integer and reads
  the image with Array.prototype.at.
- The schedule editor calls escapeHtml directly and documents why its
  innerHTML template is safe: every value is escaped or constrained.
  The remaining rule hits are suppressed on that line with the reason.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(web): build the image schedule editor with DOM calls

Codacy does not honour inline suppressions, and the editor's innerHTML
template kept tripping its XSS rules even though every value was escaped.
The editor is now built with a small element helper (createElement and
setAttribute), so no value is ever parsed as HTML, and the file's own
escapeHtml goes away.

Also for Codacy:
- LEDEscape.attr is its own function rather than a second name for html.
- The tab loader records a failed load on the panel (data-load-failed)
  from a named handler, instead of a closure over a local flag.

The fake DOM in test_file_upload_widget.js gains append/replaceChildren,
its hostile-id check now asserts the id arrives as attribute data with no
innerHTML anywhere in the editor, and test_html_escaping.js drops the
file-upload.js escaper it no longer has.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(web): schedule editor helpers as plain functions

Codacy's lint flags arrow functions held in local constants and a forEach
callback that returns a value. The editor's pieces are now named function
declarations (displayStyle, scheduleModeOption, scheduleRangeTime,
scheduleDayTime, scheduleDayRow) taking what they need as arguments, and
the element helper loops with for...of. htmx is declared as a global in
app-shell.js. Output is unchanged; test_file_upload_widget.js passes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 17:36:53 -04:00

934 lines
36 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<div class="bg-white rounded-lg shadow p-6">
<div class="border-b border-gray-200 pb-4 mb-6">
<h2 class="text-lg font-semibold text-gray-900">System Logs</h2>
<p class="mt-1 text-sm text-gray-600">View real-time logs from the LED matrix service for troubleshooting.</p>
</div>
<!-- Currently displayed plugin -->
<div id="current-plugin-banner" class="hidden mb-4 flex items-center gap-2 text-sm bg-blue-50 border border-blue-200 text-blue-800 rounded-lg px-3 py-2">
<i class="fas fa-tv"></i>
<span>Now showing: <strong id="current-plugin-mode">-</strong>
<span id="current-plugin-id-wrap" class="hidden">(plugin: <code id="current-plugin-id" class="bg-blue-100 px-1 rounded"></code>)</span>
</span>
<button id="current-plugin-filter-btn" class="hidden ml-auto btn bg-blue-600 hover:bg-blue-700 text-white px-2 py-0.5 rounded text-xs">
Filter to this plugin
</button>
</div>
<!-- Controls -->
<div class="flex flex-wrap items-center justify-between gap-4 mb-6">
<div class="flex flex-wrap items-center gap-3 sm:gap-4">
<!-- Log Mode Toggle -->
<div class="flex items-center gap-2">
<label class="flex items-center">
<input type="checkbox" id="log-realtime-toggle" class="form-control h-4 w-4" checked>
<span class="ml-2 text-sm font-medium">Real-time</span>
</label>
<span class="text-sm text-gray-600">|</span>
<button id="refresh-logs-btn" class="btn bg-gray-600 hover:bg-gray-700 text-white px-3 py-1 rounded text-sm">
<i class="fas fa-sync-alt mr-1"></i>Refresh
</button>
</div>
<!-- Log Level Filter -->
<select id="log-level-filter" aria-label="Filter logs by level" class="form-control text-sm w-auto">
<option value="">All Levels</option>
<option value="ERROR">Errors Only</option>
<option value="WARNING">Warnings & Errors</option>
<option value="INFO">Info & Above</option>
</select>
<!-- Plugin Filter -->
<select id="log-plugin-filter" aria-label="Filter logs by plugin" class="form-control text-sm w-auto">
<option value="">All Plugins</option>
</select>
<!-- Search -->
<div class="relative">
<input type="text" id="log-search" placeholder="Search logs..." aria-label="Search logs" class="form-control text-sm pl-8 pr-4 py-1 w-48">
<i class="fas fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 text-xs pointer-events-none" aria-hidden="true"></i>
</div>
</div>
<div class="flex flex-wrap items-center gap-2">
<!-- Auto-scroll toggle -->
<label class="flex items-center">
<input type="checkbox" id="log-autoscroll" class="form-control h-4 w-4" checked>
<span class="ml-2 text-sm">Auto-scroll</span>
</label>
<!-- Clear logs -->
<button id="clear-logs-btn" class="btn bg-red-600 hover:bg-red-700 text-white px-3 py-1 rounded text-sm">
<i class="fas fa-trash mr-1"></i>Clear
</button>
<!-- Download logs -->
<button id="download-logs-btn" class="btn bg-green-600 hover:bg-green-700 text-white px-3 py-1 rounded text-sm">
<i class="fas fa-download mr-1"></i>Download
</button>
</div>
</div>
<!-- Log Display -->
<div class="relative">
<div id="logs-container" class="bg-gray-900 text-gray-100 font-mono text-sm rounded-lg p-3 border border-gray-700 shadow-inner relative" style="height: 500px; min-height: 400px; max-height: 70vh;">
<div id="logs-loading" class="absolute inset-0 flex items-center justify-center text-gray-300 bg-gray-900">
<div class="text-center">
<i class="fas fa-spinner fa-spin text-2xl mb-2"></i>
<p>Loading logs...</p>
</div>
</div>
<div id="logs-display" class="hidden absolute inset-0 overflow-y-auto bg-gray-900">
<div class="logs-content p-0">
<!-- Logs will be inserted here -->
</div>
</div>
<div id="logs-empty" class="hidden absolute inset-0 flex items-center justify-center text-gray-300 bg-gray-900">
<div class="text-center">
<i class="fas fa-file-alt text-4xl mb-2"></i>
<p>No logs available</p>
<p class="text-sm mt-2">Logs will appear here when the service runs</p>
</div>
</div>
</div>
<!-- Log stats -->
<div id="log-stats" class="absolute top-2 right-2 bg-black bg-opacity-70 text-white text-xs px-3 py-1.5 rounded-md backdrop-blur-sm hidden">
<i class="fas fa-list-ul mr-1"></i>
<span id="log-count">0</span> entries
</div>
</div>
<!-- Connection Status -->
<div id="log-connection-status" class="mt-4 text-sm text-gray-600 flex items-center space-x-2">
<div class="w-2 h-2 bg-green-500 rounded-full"></div>
<span>Connected to log stream</span>
</div>
<!-- Plugin errors, as recorded by the display service -->
<div id="plugin-errors-panel" class="mt-6 border-t border-gray-200 pt-4">
<div class="flex flex-wrap items-center justify-between gap-2 mb-3">
<div>
<h3 class="text-base font-semibold text-gray-900">Plugin errors</h3>
<p id="plugin-errors-meta" class="text-xs text-gray-600">Recorded by the display service</p>
</div>
<div class="flex items-center gap-2">
<button id="plugin-errors-refresh-btn" type="button" class="btn bg-gray-600 hover:bg-gray-700 text-white px-3 py-1 rounded text-sm">
<i class="fas fa-sync-alt mr-1"></i>Refresh
</button>
<button id="plugin-errors-clear-btn" type="button" class="btn bg-red-600 hover:bg-red-700 text-white px-3 py-1 rounded text-sm">
<i class="fas fa-eraser mr-1"></i>Clear
</button>
</div>
</div>
<div id="plugin-errors-body" class="text-sm text-gray-600" aria-live="polite">Loading...</div>
</div>
</div>
<script>
// Scoped: this script runs at global scope after every HTMX swap, and the
// Cache partial has helpers with the same names (showError, escapeHtml). State
// that must survive a reload of this partial lives on window._logs* instead.
(function() {
if (typeof window._logsEventSource === 'undefined') {
window._logsEventSource = null;
}
if (typeof window._allLogs === 'undefined') {
window._allLogs = [];
}
if (typeof window._filteredLogs === 'undefined') {
window._filteredLogs = [];
}
if (typeof window._logContainer === 'undefined') {
window._logContainer = null;
}
if (typeof window._logsContent === 'undefined') {
window._logsContent = null;
}
if (typeof window._isRealtime === 'undefined') {
window._isRealtime = true;
}
if (typeof window._MAX_LOGS === 'undefined') {
window._MAX_LOGS = 500; // Maximum number of logs to keep in memory
}
// Use window properties directly to avoid redeclaration issues
// Clean up any existing event source before reinitializing
if (window._logsEventSource) {
window._logsEventSource.close();
window._logsEventSource = null;
}
// Reset arrays on reload
window._allLogs = [];
window._filteredLogs = [];
// Initialize immediately (this script runs when the partial is loaded)
(function() {
window._logContainer = document.getElementById('logs-container');
window._logsContent = document.querySelector('#logs-display .logs-content');
// Logs container initialized successfully
initializeLogs();
// Event listeners - remove old ones first to prevent duplicates
const realtimeToggle = document.getElementById('log-realtime-toggle');
const refreshBtn = document.getElementById('refresh-logs-btn');
const levelFilter = document.getElementById('log-level-filter');
const pluginFilter = document.getElementById('log-plugin-filter');
const searchInput = document.getElementById('log-search');
const autoscrollToggle = document.getElementById('log-autoscroll');
const clearBtn = document.getElementById('clear-logs-btn');
const downloadBtn = document.getElementById('download-logs-btn');
// Clone and replace to remove old listeners
if (realtimeToggle) {
const newToggle = realtimeToggle.cloneNode(true);
realtimeToggle.parentNode.replaceChild(newToggle, realtimeToggle);
newToggle.addEventListener('change', toggleRealtime);
}
if (refreshBtn) {
const newBtn = refreshBtn.cloneNode(true);
refreshBtn.parentNode.replaceChild(newBtn, refreshBtn);
newBtn.addEventListener('click', refreshLogs);
}
if (levelFilter) {
const newFilter = levelFilter.cloneNode(true);
levelFilter.parentNode.replaceChild(newFilter, levelFilter);
newFilter.addEventListener('change', filterLogs);
}
if (pluginFilter) {
const newFilter = pluginFilter.cloneNode(true);
pluginFilter.parentNode.replaceChild(newFilter, pluginFilter);
newFilter.addEventListener('change', filterLogs);
}
if (searchInput) {
const newInput = searchInput.cloneNode(true);
searchInput.parentNode.replaceChild(newInput, searchInput);
newInput.addEventListener('input', filterLogs);
}
if (autoscrollToggle) {
const newToggle = autoscrollToggle.cloneNode(true);
autoscrollToggle.parentNode.replaceChild(newToggle, autoscrollToggle);
newToggle.addEventListener('change', toggleAutoscroll);
}
if (clearBtn) {
const newBtn = clearBtn.cloneNode(true);
clearBtn.parentNode.replaceChild(newBtn, clearBtn);
newBtn.addEventListener('click', clearLogs);
}
if (downloadBtn) {
const newBtn = downloadBtn.cloneNode(true);
downloadBtn.parentNode.replaceChild(newBtn, downloadBtn);
newBtn.addEventListener('click', downloadLogs);
}
const currentPluginFilterBtn = document.getElementById('current-plugin-filter-btn');
if (currentPluginFilterBtn) {
const newBtn = currentPluginFilterBtn.cloneNode(true);
currentPluginFilterBtn.parentNode.replaceChild(newBtn, currentPluginFilterBtn);
newBtn.addEventListener('click', function() {
const pluginFilterEl = document.getElementById('log-plugin-filter');
if (pluginFilterEl && window._currentPluginId) {
pluginFilterEl.value = window._currentPluginId;
filterLogs();
}
});
}
// Current-plugin poll and the realtime log stream run only while the Logs
// tab is active and the page is visible (both restart with an immediate
// refresh). Re-registering on partial reload replaces the old one.
const pluginErrorsRefreshBtn = document.getElementById('plugin-errors-refresh-btn');
if (pluginErrorsRefreshBtn) pluginErrorsRefreshBtn.onclick = refreshPluginErrors;
const pluginErrorsClearBtn = document.getElementById('plugin-errors-clear-btn');
if (pluginErrorsClearBtn) pluginErrorsClearBtn.onclick = clearPluginErrors;
function startLogsActivity() {
refreshCurrentPluginStatus();
if (window._currentPluginPollTimer) clearInterval(window._currentPluginPollTimer);
window._currentPluginPollTimer = setInterval(refreshCurrentPluginStatus, 5000);
refreshPluginErrors();
if (window._pluginErrorsPollTimer) clearInterval(window._pluginErrorsPollTimer);
window._pluginErrorsPollTimer = setInterval(refreshPluginErrors, 15000);
if (window._isRealtime && !window._logsEventSource) setupRealtimeLogs();
}
function stopLogsActivity() {
if (window._currentPluginPollTimer) {
clearInterval(window._currentPluginPollTimer);
window._currentPluginPollTimer = null;
}
if (window._pluginErrorsPollTimer) {
clearInterval(window._pluginErrorsPollTimer);
window._pluginErrorsPollTimer = null;
}
stopRealtimeLogs();
}
if (window.LEDVisibility) {
window.LEDVisibility.onActive('logs', startLogsActivity, stopLogsActivity);
} else {
startLogsActivity();
}
// Handle window resize for responsive height. Added once: this script
// re-runs on every partial load, and the handler reads window globals.
if (window._logsResizeListenerAdded) return;
window._logsResizeListenerAdded = true;
window.addEventListener('resize', function() {
if (window._logContainer) {
// Force a reflow to update sizing
window._logContainer.style.display = 'none';
window._logContainer.offsetHeight; // Trigger reflow
window._logContainer.style.display = '';
// Re-evaluate scroll position after resize
setTimeout(function() {
const distanceFromBottom = window._logContainer.scrollHeight - window._logContainer.scrollTop - window._logContainer.clientHeight;
window._isUserNearBottom = distanceFromBottom <= window._scrollThreshold;
}, 100);
}
});
})();
function initializeLogs() {
// Load initial logs
loadLogs();
// Setup SSE for real-time logs
setupRealtimeLogs();
// Setup auto-scroll
setupAutoscroll();
}
function loadLogs() {
showLoading();
fetch('/api/v3/logs')
.then(response => response.json())
.then(data => {
hideLoading();
if (data.status === 'success' && data.data && data.data.logs) {
processLogs(data.data.logs);
updateLogStats();
} else {
showEmptyState();
}
})
.catch(error => {
hideLoading();
showError('Failed to load logs: ' + error.message);
});
}
// Closes the log stream and cancels any pending reconnect, so a paused
// (inactive tab / hidden page) stream stays closed.
function stopRealtimeLogs() {
if (window._logsReconnectTimer) {
clearTimeout(window._logsReconnectTimer);
window._logsReconnectTimer = null;
}
if (window._logsEventSource) {
window._logsEventSource.close();
window._logsEventSource = null;
}
}
function setupRealtimeLogs() {
stopRealtimeLogs();
// Don't open (or reconnect) while the Logs tab isn't on screen;
// LEDVisibility restarts the stream when it is.
if (window.LEDVisibility && !window.LEDVisibility.isActive('logs')) return;
window._logsEventSource = new EventSource('/api/v3/stream/logs');
window._logsEventSource.onopen = function() {
document.getElementById('log-connection-status').innerHTML = `
<div class="w-2 h-2 bg-green-500 rounded-full"></div>
<span>Connected to log stream</span>
`;
};
window._logsEventSource.onmessage = function(event) {
const data = JSON.parse(event.data);
if (data.logs && window._isRealtime) {
processLogs(data.logs, true);
updateLogStats();
// Use the new smart scroll function
scrollToBottomIfNeeded();
}
};
window._logsEventSource.onerror = function() {
document.getElementById('log-connection-status').innerHTML = `
<div class="w-2 h-2 bg-red-500 rounded-full"></div>
<span>Disconnected from log stream</span>
`;
// Attempt to reconnect after 5 seconds (cancelled by stopRealtimeLogs)
if (window._logsReconnectTimer) clearTimeout(window._logsReconnectTimer);
window._logsReconnectTimer = setTimeout(setupRealtimeLogs, 5000);
};
}
function processLogs(logsText, append = false) {
if (!append) {
window._allLogs = [];
if (window._logsContent) {
window._logsContent.innerHTML = '';
}
// Container cleared for new logs
}
// Parse journalctl output
const lines = logsText.split('\n').filter(line => line.trim());
lines.forEach(line => {
// Skip empty lines
if (!line.trim()) return;
// journalctl (--output=short-iso) emits: "YYYY-MM-DDTHH:MM:SS+ZZZZ hostname service[pid]: message"
// Example: "2024-01-15T10:23:45+0000 raspberrypi ledmatrix[1234]: INFO - plugin.nhl_scoreboard - [Plugin: nhl_scoreboard] Updated scores"
// Also accept the older syslog-style "MMM DD HH:MM:SS" timestamp for compatibility.
let timestamp = '';
let level = 'INFO';
let message = line;
let plugin = '';
let rest = null;
const isoMatch = line.match(/^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:[+-]\d{2}:?\d{2}|Z))\s+(.*)$/);
const syslogMatch = !isoMatch && line.match(/^([A-Z][a-z]{2}\s+\d{1,2}\s+\d{2}:\d{2}:\d{2})\s+(.*)$/);
if (isoMatch) {
timestamp = isoMatch[1];
rest = isoMatch[2];
} else if (syslogMatch) {
timestamp = syslogMatch[1];
rest = syslogMatch[2];
} else {
// If no timestamp, use current time
timestamp = new Date().toLocaleString('en-US', {
month: 'short',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hour12: false
});
}
if (rest !== null) {
// Find the message part (after hostname + service name/pid)
const messageMatch = rest.match(/:\s*(.+)$/);
if (messageMatch) {
message = messageMatch[1];
// Detect log level from message
if (message.match(/\b(ERROR|CRITICAL|FATAL)\b/i)) {
level = 'ERROR';
} else if (message.match(/\b(WARNING|WARN)\b/i)) {
level = 'WARNING';
} else if (message.match(/\bDEBUG\b/i)) {
level = 'DEBUG';
} else if (message.match(/\bINFO\b/i)) {
level = 'INFO';
}
// Clean up level prefix from message if it exists
message = message.replace(/^(ERROR|WARNING|WARN|INFO|DEBUG)\s*[-:]\s*/i, '');
// journalctl already carries its own timestamp; strip the app's
// internal "YYYY-MM-DD HH:MM:SS.mmm - LEVEL - logger.name - "
// prefix (see ContextualFormatter in src/logging_config.py) so
// it isn't duplicated in the displayed message.
message = message.replace(
/^\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2}(?:\.\d+)?\s*-\s*(ERROR|WARNING|WARN|INFO|DEBUG|CRITICAL)\s*-\s*[\w.]+\s*-\s*/i,
''
);
// Extract the "[Plugin: <id>]" context tag emitted by
// ContextualFormatter for every plugin logger (see
// src/logging_config.py PluginLoggerAdapter), and pull it out
// of the displayed message into its own field.
const pluginMatch = message.match(/^\[Plugin:\s*([^\]]+)\]\s*/);
if (pluginMatch) {
plugin = pluginMatch[1].trim();
message = message.replace(pluginMatch[0], '');
}
} else {
message = rest;
}
}
const logEntry = {
timestamp: timestamp,
level: level,
plugin: plugin,
message: message,
raw: line,
id: Date.now() + Math.random()
};
// Don't add duplicate entries when appending
if (!append || !window._allLogs.find(log => log.raw === line)) {
window._allLogs.push(logEntry);
}
});
// Trim logs if we exceed the maximum
if (window._allLogs.length > window._MAX_LOGS) {
window._allLogs = window._allLogs.slice(-window._MAX_LOGS);
}
updatePluginFilterOptions();
filterLogs();
}
function updatePluginFilterOptions() {
const pluginFilterEl = document.getElementById('log-plugin-filter');
if (!pluginFilterEl) return;
const previousValue = pluginFilterEl.value;
const plugins = Array.from(new Set(window._allLogs.map(log => log.plugin).filter(Boolean))).sort();
pluginFilterEl.innerHTML = '<option value="">All Plugins</option>' +
plugins.map(p => `<option value="${escapeHtml(p)}">${escapeHtml(p)}</option>`).join('');
// Restore previous selection if it's still a valid option
if (previousValue && plugins.includes(previousValue)) {
pluginFilterEl.value = previousValue;
}
}
function renderLogs() {
if (window._filteredLogs.length === 0) {
showEmptyState();
return;
}
showLogs();
if (window._logsContent) {
window._logsContent.innerHTML = '';
}
window._filteredLogs.forEach(log => {
const logElement = document.createElement('div');
logElement.className = `log-entry py-1 px-2 hover:bg-gray-800 rounded transition-colors duration-150 ${getLogLevelClass(log.level)}`;
const pluginBadge = log.plugin
? `<span class="log-plugin flex-shrink-0 px-2 py-0.5 rounded text-xs font-semibold bg-purple-700 text-white" title="Plugin: ${escapeHtml(log.plugin)}">${escapeHtml(log.plugin)}</span>`
: '';
logElement.innerHTML = `
<div class="flex items-start gap-3 text-xs font-mono">
<span class="log-timestamp text-gray-400 flex-shrink-0 w-32">${escapeHtml(log.timestamp)}</span>
<span class="log-level flex-shrink-0 px-2 py-0.5 rounded text-xs font-semibold ${getLogLevelBadgeClass(log.level)}">${log.level}</span>
${pluginBadge}
<span class="log-message flex-1 ${getLogLevelTextClass(log.level)} break-words">${escapeHtml(log.message)}</span>
</div>
`;
if (window._logsContent) {
window._logsContent.appendChild(logElement);
}
});
}
function getLogLevelClass(level) {
// Background color for the entire log entry row
const classes = {
'ERROR': 'log-level-error',
'WARNING': 'log-level-warning',
'INFO': '',
'DEBUG': 'log-level-debug'
};
return classes[level] || '';
}
function getLogLevelBadgeClass(level) {
const classes = {
'ERROR': 'bg-red-600 text-white',
'WARNING': 'bg-yellow-600 text-white',
'INFO': 'bg-blue-600 text-white',
'DEBUG': 'bg-gray-600 text-white'
};
return classes[level] || 'bg-gray-600 text-white';
}
function getLogLevelTextClass(level) {
const classes = {
'ERROR': 'text-red-300',
'WARNING': 'text-yellow-300',
'INFO': 'text-gray-200',
'DEBUG': 'text-gray-400'
};
return classes[level] || 'text-gray-300';
}
function filterLogs() {
const levelFilterEl = document.getElementById('log-level-filter');
const pluginFilterEl = document.getElementById('log-plugin-filter');
const searchEl = document.getElementById('log-search');
if (!levelFilterEl || !searchEl) return;
const levelFilter = levelFilterEl.value;
const pluginFilter = pluginFilterEl ? pluginFilterEl.value : '';
const searchTerm = searchEl.value.toLowerCase();
window._filteredLogs = window._allLogs.filter(log => {
// Level filter
if (levelFilter) {
const levels = {
'ERROR': ['ERROR'],
'WARNING': ['ERROR', 'WARNING'],
'INFO': ['ERROR', 'WARNING', 'INFO']
};
if (!levels[levelFilter].includes(log.level)) {
return false;
}
}
// Plugin filter
if (pluginFilter && log.plugin !== pluginFilter) {
return false;
}
// Search filter
if (searchTerm && !log.message.toLowerCase().includes(searchTerm) &&
!(log.plugin && log.plugin.toLowerCase().includes(searchTerm))) {
return false;
}
return true;
});
renderLogs();
updateLogStats();
}
function toggleRealtime() {
const toggleEl = document.getElementById('log-realtime-toggle');
if (!toggleEl) return;
window._isRealtime = toggleEl.checked;
if (window._isRealtime) {
setupRealtimeLogs();
} else if (window._logsEventSource) {
window._logsEventSource.close();
window._logsEventSource = null;
}
}
function refreshLogs() {
loadLogs();
showNotification('Logs refreshed', 'success');
}
function clearLogs() {
window._allLogs = [];
window._filteredLogs = [];
if (window._logsContent) {
window._logsContent.innerHTML = '';
}
showEmptyState();
updateLogStats();
showNotification('Logs cleared', 'info');
}
function downloadLogs() {
if (window._filteredLogs.length === 0) {
showNotification('No logs to download', 'warning');
return;
}
const logText = window._filteredLogs.map(log => log.raw).join('\n');
const blob = new Blob([logText], { type: 'text/plain' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `ledmatrix-logs-${new Date().toISOString().slice(0, 19)}.txt`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
showNotification('Logs downloaded', 'success');
}
// Track if user is near bottom for smart auto-scroll
if (typeof window._isUserNearBottom === 'undefined') {
window._isUserNearBottom = true;
}
if (typeof window._scrollThreshold === 'undefined') {
window._scrollThreshold = 100; // pixels from bottom to consider "near bottom"
}
function setupAutoscroll() {
if (!window._logsContent) return;
const observer = new MutationObserver(function() {
// Use requestAnimationFrame for better timing
requestAnimationFrame(scrollToBottomIfNeeded);
});
observer.observe(window._logsContent, { childList: true });
// Also listen for manual scroll events to detect when user is not at bottom
if (window._logContainer) {
window._logContainer.addEventListener('scroll', function() {
const distanceFromBottom = window._logContainer.scrollHeight - window._logContainer.scrollTop - window._logContainer.clientHeight;
window._isUserNearBottom = distanceFromBottom <= window._scrollThreshold;
});
}
}
function scrollToBottomIfNeeded() {
const autoscrollEl = document.getElementById('log-autoscroll');
if (autoscrollEl && autoscrollEl.checked && window._logContainer && window._isUserNearBottom) {
// Use requestAnimationFrame for smooth scrolling
requestAnimationFrame(function() {
// Remember current scroll position
const previousScrollHeight = window._logContainer.scrollHeight;
// Scroll to bottom
window._logContainer.scrollTop = window._logContainer.scrollHeight;
// Ensure we're actually at the bottom after a brief delay
setTimeout(function() {
if (window._logContainer.scrollTop + window._logContainer.clientHeight >= window._logContainer.scrollHeight - 10) {
window._isUserNearBottom = true;
}
}, 50);
});
}
}
function scrollToBottom() {
// Legacy function for backward compatibility
if (window._logContainer) {
window._logContainer.scrollTop = window._logContainer.scrollHeight;
window._isUserNearBottom = true;
}
}
function toggleAutoscroll() {
const autoscrollEl = document.getElementById('log-autoscroll');
if (!autoscrollEl || !autoscrollEl.checked) {
// Don't auto-scroll if unchecked or element doesn't exist
window._isUserNearBottom = false;
return;
}
// Scroll to bottom when re-enabled and user was near bottom
if (window._isUserNearBottom) {
scrollToBottom();
}
}
function updateLogStats() {
const stats = document.getElementById('log-stats');
const count = document.getElementById('log-count');
if (stats && count) {
count.textContent = window._filteredLogs.length;
stats.classList.remove('hidden');
}
}
function showLoading() {
document.getElementById('logs-loading').classList.remove('hidden');
document.getElementById('logs-display').classList.add('hidden');
document.getElementById('logs-empty').classList.add('hidden');
}
function showLogs() {
document.getElementById('logs-loading').classList.add('hidden');
document.getElementById('logs-display').classList.remove('hidden');
document.getElementById('logs-empty').classList.add('hidden');
}
function hideLoading() {
document.getElementById('logs-loading').classList.add('hidden');
}
function showEmptyState() {
document.getElementById('logs-loading').classList.add('hidden');
document.getElementById('logs-display').classList.add('hidden');
document.getElementById('logs-empty').classList.remove('hidden');
document.getElementById('log-stats').classList.add('hidden');
}
function showError(message) {
if (window._logsContent) {
window._logsContent.innerHTML = `<div class="text-red-400 p-4">${escapeHtml(message)}</div>`;
window._logsContent.classList.remove('hidden');
}
}
function escapeHtml(text) { return window.LEDEscape.html(text); }
function refreshCurrentPluginStatus() {
fetch('/api/v3/display/current-status')
.then(response => response.json())
.then(data => {
if (data.status !== 'success' || !data.data) return;
const state = data.data;
const banner = document.getElementById('current-plugin-banner');
const modeEl = document.getElementById('current-plugin-mode');
const idWrap = document.getElementById('current-plugin-id-wrap');
const idEl = document.getElementById('current-plugin-id');
const filterBtn = document.getElementById('current-plugin-filter-btn');
if (!banner || !modeEl) return;
window._currentPluginId = state.plugin_id || null;
modeEl.textContent = state.mode || 'unknown';
if (state.plugin_id) {
idEl.textContent = state.plugin_id;
idWrap.classList.remove('hidden');
if (filterBtn) filterBtn.classList.remove('hidden');
} else {
idWrap.classList.add('hidden');
if (filterBtn) filterBtn.classList.add('hidden');
}
banner.classList.remove('hidden');
})
.catch(() => {
// Silently ignore - banner just stays hidden/stale
});
}
// Plugin errors panel. The display service records them and publishes a
// snapshot every few seconds; /api/v3/errors/summary serves that snapshot.
// Plugin ids and messages come from plugins: everything goes through escapeHtml.
function formatErrorTime(iso) {
return iso ? String(iso).replace('T', ' ').slice(0, 19) : '';
}
function renderPluginErrors(summary) {
const body = document.getElementById('plugin-errors-body');
const meta = document.getElementById('plugin-errors-meta');
if (!body) return;
if (meta) {
let text = 'Recorded by the display service';
if (summary.generated_at) text += ' · updated ' + formatErrorTime(summary.generated_at);
if (summary.clear_pending) text += ' · clearing…';
meta.textContent = text;
}
if (!summary.snapshot_available) {
body.innerHTML = '<p class="text-gray-600"><i class="fas fa-hourglass-half mr-1"></i>' +
'Display service hasn’t reported yet. Errors appear here once it is running.</p>';
return;
}
const plugins = Object.entries(summary.plugin_error_counts || {}).map(([id, types]) => {
const total = Object.values(types || {}).reduce((sum, n) => sum + (Number(n) || 0), 0);
return { id, types: types || {}, total };
}).sort((a, b) => b.total - a.total);
const patterns = Object.values(summary.active_patterns || {});
if (!Number(summary.total_errors) && plugins.length === 0 && patterns.length === 0) {
body.innerHTML = '<p class="text-gray-600"><i class="fas fa-check-circle text-green-600 mr-1"></i>' +
'No plugin errors recorded</p>';
return;
}
let html = '';
if (plugins.length) {
html += '<div class="overflow-x-auto"><table class="min-w-full text-sm">' +
'<thead><tr class="text-left text-xs uppercase text-gray-500 border-b border-gray-200">' +
'<th class="py-1 pr-4 font-medium">Plugin</th><th class="py-1 pr-4 font-medium">Errors</th>' +
'<th class="py-1 font-medium">Types</th></tr></thead><tbody>';
plugins.forEach(p => {
const types = Object.entries(p.types)
.map(([type, n]) => `${escapeHtml(type)} ×${escapeHtml(String(Number(n) || 0))}`)
.join(', ');
html += '<tr class="border-b border-gray-100">' +
`<td class="py-1 pr-4"><code class="bg-gray-100 px-1 rounded">${escapeHtml(p.id)}</code></td>` +
`<td class="py-1 pr-4 font-semibold text-gray-900">${escapeHtml(String(p.total))}</td>` +
`<td class="py-1 text-gray-700 break-words">${types}</td></tr>`;
});
html += '</tbody></table></div>';
}
if (patterns.length) {
const badge = {
critical: 'bg-red-100 text-red-800',
error: 'bg-amber-100 text-amber-800',
warning: 'bg-yellow-100 text-yellow-800'
};
html += '<h4 class="mt-4 mb-2 text-sm font-semibold text-gray-900">Repeating errors</h4><ul class="list-none pl-0 space-y-2">';
patterns.forEach(p => {
const severity = String(p.severity || 'warning');
const affected = (p.affected_plugins || []).map(id => escapeHtml(id)).join(', ') || 'unknown';
const sample = (p.sample_messages || [])[0];
html += '<li class="border border-gray-200 rounded-lg px-3 py-2">' +
'<div class="flex flex-wrap items-center gap-2">' +
`<span class="px-2 py-0.5 rounded text-xs font-semibold ${badge[severity] || badge.warning}">${escapeHtml(severity)}</span>` +
`<code class="font-semibold text-gray-900">${escapeHtml(p.error_type || '')}</code>` +
`<span class="text-gray-700">×${escapeHtml(String(Number(p.count) || 0))}</span>` +
`<span class="text-xs text-gray-500 ml-auto">last seen ${escapeHtml(formatErrorTime(p.last_seen))}</span></div>` +
`<div class="mt-1 text-xs text-gray-600">Plugins: ${affected}</div>` +
(sample ? `<div class="mt-1 text-xs font-mono text-gray-700 break-words">${escapeHtml(sample)}</div>` : '') +
'</li>';
});
html += '</ul>';
}
body.innerHTML = html;
}
function refreshPluginErrors() {
fetch('/api/v3/errors/summary')
.then(response => response.json())
.then(data => {
if (data.status !== 'success' || !data.data) throw new Error(data.message || 'Request failed');
renderPluginErrors(data.data);
})
.catch(() => {
const body = document.getElementById('plugin-errors-body');
if (body) body.textContent = 'Could not load plugin errors.';
});
}
function clearPluginErrors() {
if (!confirm('Clear all recorded plugin errors?')) return;
fetch('/api/v3/errors/clear', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ all: true })
})
.then(response => response.json())
.then(data => {
showNotification(data.status === 'success' ? 'Plugin errors cleared'
: (data.message || 'Could not clear plugin errors'),
data.status === 'success' ? 'success' : 'error');
refreshPluginErrors();
})
.catch(() => {
showNotification('Could not clear plugin errors', 'error');
});
}
// Cleanup on page unload
window.addEventListener('beforeunload', function() {
if (window._logsEventSource) {
window._logsEventSource.close();
}
if (window._currentPluginPollTimer) {
clearInterval(window._currentPluginPollTimer);
window._currentPluginPollTimer = null;
}
if (window._pluginErrorsPollTimer) {
clearInterval(window._pluginErrorsPollTimer);
window._pluginErrorsPollTimer = null;
}
});
})();
</script>