Skip to content

Add query tabs to the Web UI (Play) - #107826

Merged
alexey-milovidov merged 62 commits into
masterfrom
play-query-tabs
Jul 2, 2026
Merged

alexey-milovidov merged 62 commits into
masterfrom
play-query-tabs

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jun 18, 2026 •

Copy link
Copy Markdown
Member

Add tabs to the ClickHouse Web UI (Play) so multiple queries can be kept side by side instead of juggling them in a single editor or relying on browser history.

Each tab has its own query text, title, query parameters and last result; the connection settings (URL/user/password) stay global. The tab bar appears once a query has been run (or once there is more than one tab), so a single result-less tab looks exactly as before. The active tab merges into the page (its background tracks the per-query hash color, with a gradient that is more saturated/brighter at the top), while inactive tabs are tinted by the hash of their own query so they are visually distinguished.

Highlights:

  • Workspace (tabs, titles, active tab, order and small result snapshots) is persisted in IndexedDB and restored on reload (best-effort; degrades to in-memory if unavailable).
  • The History API state carries the active tab, so browser back/forward switches tabs; the URL gains a tab=<name> parameter and is reconciled with saved tabs on load.
  • New tab via [+], close via x, default names Query A, Query B, …; double-purpose click on the active tab title edits it inline.
  • Switch tabs with the mouse wheel over the tab panel (vertical or horizontal).
  • The tab bar is horizontally sticky (stays at the left during horizontal scroll) and scrolls away vertically with the page.

All work is contained in programs/server/play.html, which remains a single self-contained file with no frameworks or build step.

Current limitation: switching tabs while the query is running will discard the running state.

Changelog category (leave one):

  • New Feature

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Added tabs to the ClickHouse Web UI (Play) for working with multiple queries at once. Tabs, their titles, parameters, active state, and small result snapshots are persisted across reloads (large and image results are not restored), integrate with browser history and the URL, and can be switched with the mouse wheel.

alexey-milovidov and others added 23 commits June 18, 2026 04:52
Implement tabs in `play.html` so multiple independent queries can be kept
side by side. Each tab owns its query text, title, query parameters and the
last result snapshot; connection settings (`url`/`user`/`password`) stay
global and shared across tabs.

The tab bar appears at the top of the page once a query has been run (or once
there is more than one tab), so the UI is byte-identical to before for a single
result-less tab. The active tab is a slab whose background matches the page
background (derived from the hash of the query via `queryToColor`), while
inactive tabs are tinted by the hash of their own query text, so different
queries are automatically distinguished by color. The strip around the tabs is
light gray in the light theme and pure black in the dark theme. A `[+]` button
opens a new tab, each tab has an `x` to close it, and clicking the active tab's
title edits it inline. Default titles are `Query A`, `Query B`, etc.

Workspace state (tabs, titles, active tab, order and small result snapshots) is
persisted in IndexedDB (best-effort; degrades to in-memory tabs if unavailable).
The History API state now carries the active tab identity so browser
back/forward switches tabs, and the URL gains a `tab=<name>` parameter. On load,
saved tabs are reconciled with the URL: a query is substituted into the named
tab if it exists, otherwise a new tab is created (or the default tab is used
when there were no saved tabs).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The visibility rule must reflect an actual run. Previously `syncHistory`
(invoked on tab switch, rename and startup reconciliation) fabricated a
result snapshot via `saveHistory`, so a single tab with a query that was
typed but never run would show the tab bar after a reload.

Split the history writing into `writeHistoryEntry`, which never touches the
tab's stored result, and have only real runs (`saveHistory`) set `tab.result`.
`syncHistory` now records history reusing the existing result (or none), so a
never-run single tab stays result-less and the bar stays hidden, matching the
behaviour before tabs existed.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
A single tab kept showing the tab bar on a fresh page when IndexedDB still
held a result snapshot persisted by an earlier build (including the fabricated
snapshot the first tabs commit wrote via `syncHistory`). The visibility rule
checked only `result != null`, so such a stale snapshot kept the bar visible.

Mark results produced by a genuine run with `ran: true` and base the
visibility rule on `result.ran` rather than on the mere presence of a result.
Stale or fabricated snapshots lack the flag and are therefore treated as
"not run", so the bar stays hidden until a real run; the state self-heals on
the next run. The tab's query is still restored as before.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The tab bar was always visible on a fresh load despite the `hidden` attribute
being set correctly. The rule `#tab-bar { display: flex }` (id specificity
1,0,0) overrides the user-agent `[hidden] { display: none }` rule (0,1,0), so
toggling the `hidden` attribute had no visual effect.

Add an explicit `#tab-bar[hidden] { display: none }` rule (specificity 1,1,0)
that wins, so the visibility logic actually takes effect. The earlier behaviour
tests passed only because they checked the `hidden` property rather than the
rendered display; the test now asserts computed visibility.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…itle

The inline title editor used a fixed `8rem` width; make it grow and shrink to
fit its text by measuring the value with a hidden span that copies the input's
typography. Also show a `text` cursor when hovering the active tab's title, so
it is discoverable that clicking it edits the title in place.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
- The tab's own keydown handler (Enter/Space switches tab) also fired for
  events bubbling from the inline title editor, so Space was prevented and
  could not be typed. Ignore keydowns whose target is not the tab element.
- The auto-size width omitted the input's padding and border, so it came up
  slightly short; include them (box-sizing is border-box) plus a little slack.
- Remove the editor's background and border so editing happens in place,
  visually consistent with the tab title.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Previously editing swapped the title `span` for an `input` whose auto-sized
width included a few pixels of caret slack, so the tab grew slightly when
editing started. Make the title `span` itself `contenteditable` instead: the
same element becomes editable and grows with its content, so there is no
element swap, no width measurement, and no jump (measured 0.00px). Pasted
newlines/whitespace are collapsed on commit, and the `editing` state drops the
ellipsis clipping and focus outline.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The tab bar previously lived inside `#main` and bled into its `0.5rem` padding
with a negative margin while being `position: sticky`. Chrome and Firefox paint
that negative-margin region differently under sticky: in Chrome the left padding
showed the `#main` background instead of the gray/black strip.

Promote the tab bar to its own grid row in the body grid (the `tabbar` area in
the main column) and drop the negative margin and sticky positioning. The strip
background now fills the whole row natively, so the top space spans the full
width including the left padding identically in both browsers. The row is `auto`
height and collapses to nothing when the bar is hidden, so there is still no
layout shift on a fresh load.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
- All tabs (active and inactive) now sit at the same vertical position; the
  previous stagger (inactive tabs lifted off the strip) is gone.
- A border runs along the top of the main area; the active tab covers its own
  segment of that line (its bottom border matches the page background), so the
  active tab's title reads as part of the main area below. To keep that 1px
  merge from being clipped, the tab list no longer sets overflow (which forced
  overflow-y to clip); many tabs now compress with an ellipsis instead.
- Reduced the gap between the page top and the tabs.
- The [+] button sits directly after the last tab (the list no longer grows to
  push it to the right) and is styled like a tab.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Tabs and the [+] button each drew their own 1px bottom border in addition to
the strip's border-bottom. The two lines did not coincide exactly (the native
button rasterized a device pixel lower, and the per-tab border doubled the
line), so inactive tabs and the [+] button showed a 1px overshoot below the
top-of-main line.

Use a single line — the strip's border-bottom — and give tabs and the button no
bottom border, so they sit directly on it. The active tab now erases its own
segment of that line with a 1px box-shadow (which adds no layout offset) instead
of a colored bottom border. Verified by pixel sampling: exactly one border row
under inactive tabs and the button, none under the active tab.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Tab titles already had `overflow: hidden; text-overflow: ellipsis`, but the
per-tab `max-width: 16rem` was wide enough that most titles never reached the
truncation point. Tighten the cap to `12rem` so longer titles are truncated
with an ellipsis and tabs stay compact.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
When editing a title, the tab was still capped at max-width: 12rem, clipping a
long title being typed. Mark the tab element as `editing` and, in that state,
drop the max-width and let it flex to the full content. On commit the tab is
rebuilt without the class, so it returns to the compact capped width with the
ellipsis.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The tab bar lived in its own body-grid row outside #main (the scroll
container), so it stayed put while the content scrolled under it. Move it back
inside #main as the first child so it scrolls together with the page content.

It bleeds into #main's 0.5rem padding with a negative margin to keep the strip
full-width; that bleed is reliable now because the element is no longer
position: sticky (sticky + negative margin was what rendered differently across
browsers earlier). Verified: scrolling the content moves the tab bar up out of
view, and the left padding still paints the strip color.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The active tab background is exactly the page background (verified: both render
oklch(0.96 0.0296 h) / the same pixels). The faint "different shade" was the
controls' soft drop-shadow bleeding upward into the 0.5rem gap between the tab
strip and the form, darkening that band of page background right below the
active tab.

Drop the strip's bottom margin to 0 so the active tab connects directly to the
controls, leaving no exposed page-background band for the shadow to tint. The
active tab now reads as continuous with the main area.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The tab bar should stay at the left edge while a wide result is scrolled
horizontally, like #controls and #logo-container, while still scrolling away
vertically.

Add position: sticky; left: 0 for that. The previous full-width bleed used a
negative left/right margin, but that bleed is clamped away under position:
sticky in some browsers (Chrome), leaving #main's padding visible to the left
of the tabs. Paint the full-width gray/black strip and the top-of-main border
with a ::before pseudo-element that extends 0.5rem into #main's side padding
instead; the pseudo is not subject to the sticky clamp, so the strip stays
full-width both at rest and during horizontal scroll.

Verified: horizontal scroll keeps the tabs pinned at the left with the strip
still spanning the padding, vertical scroll still moves the bar away, the active
tab still merges with the main area, and the top-of-main border spans the full
width.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
With the tab bar no longer using a negative left margin, its content edge
already sits at #main's content edge, so the 0.5rem left padding pushed the
first tab 8px to the right of the editor. Drop the left padding so the first
tab lines up with the query editor and the result tables.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Add a vertical gradient to the active tab: more saturated (light theme) /
brighter (dark theme) at the top via a new --active-tab-top-color, fading down
to the page background so the bottom still merges with the main area.

Also make the active tab cover its segment of the top-of-main border with a 2px
(was 1px) page-background box-shadow. On the sticky compositing layer a 1px
shadow and the 1px border can round to different device rows and leave a faint
sliver of the border visible; 2px guarantees coverage. The extra pixel is the
page background (part of the merge), not a line, and it adds no layout offset,
so the active and inactive tabs keep the same height and position.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Set the tab strip's top padding to 0.25rem, equal to the inter-tab gap, so the
margin between the page top and the tabs is the same size as the margin between
tabs. It is a whole pixel (4px) at the default root size, so it does not
reintroduce the sub-pixel border rasterization a fractional value would cause.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The active tab covered its full width's segment of the top-of-main border (via a
box-shadow), which also erased the line under its own 1px side borders, leaving
the bottom-left and bottom-right corners disconnected (a missing border pixel at
each corner).

Replace the box-shadow with an ::after that erases the line only in the tab's
interior (left/right: 0 are inset by the side borders relative to the padding
box). The line now continues under the side borders, so they connect to it at
the bottom corners, while the interior stays open and merges with the main area.
The 2px height robustly covers the 1px line despite sticky-layer rounding.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The close icon was 1.1em while the [+] button was 1em, and the [+] relied on
default button text centering, so the two glyphs sat ~0.5px apart vertically.
Set the close icon to 1em (matching the [+]) and center the [+] with flexbox.
Their glyph centers now coincide exactly at device-pixel scales 1x, 2x and 4x.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Scrolling the wheel up over the tab panel switches to the tab on the left and
scrolling down to the tab on the right, when such a tab exists. Wheel deltas are
accumulated (and normalized for line-mode) past a threshold so one mouse notch
switches one tab and a trackpad swipe switches one tab per gesture; switching
stops at the first and last tab. With a single tab the wheel is left alone so
the page scrolls normally.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Use the dominant wheel axis, so a horizontal wheel or trackpad gesture switches
tabs as well: scrolling left switches to the left tab and right to the right
tab, alongside the existing vertical up/down behaviour.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jun 18, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c50888f]

Summary: ✅


AI Review

Summary

This PR adds persistent query tabs, tab-local result snapshots, URL/history reconciliation, and new user documentation for the built-in Web SQL UI. The current head appears to address the concrete state-corruption bugs raised earlier in review, but the remaining concern is evidence: this browser-history / IndexedDB reconciliation logic still has no executable regression coverage in-tree despite how many correctness fixes it needed during review.

Tests
  • ⚠️ [programs/server/play.html:7143] Please add at least one focused browser/headless regression that exercises saved tabs, URL reconciliation, and an unrun edit surviving reload or Back/Forward. Right now the PR relies on ad-hoc simulations in discussion comments, so CI still has no way to catch the next non-destructive-restore regression in this state machine.
Final Verdict

⚠️ Request changes for missing regression coverage on the startup/history restore contract.

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Jun 18, 2026
@alexey-milovidov

alexey-milovidov commented Jun 18, 2026 •

Copy link
Copy Markdown
Member Author

The spec and refinements:

I want to implement tabs (to allow switching between multiple queries) in the Web UI (play.html).

Tab headers should display at the top of the page. The current tab header - a recrangular slab with the tab title - should have the same background as the rest of the page. We have background color changing based on the hash of the query text, and will give a nice visual solution - different tabs will be automatically distinguished by colors. Part of the top space outside of the tab headers should have a gray / pure black background (depending on the light/dark theme). To the right of the tabs there should be a [+] button to open a new tab. When there is only a single tab and the query was not run (there is no result), the top space with tabs should not display - so there will be no visible tabs, as it is now, before our changes. When the query was successfully run, we should display the top space with the current tab and the [+] button. Every tab should have a name and the x icon to close it. By default, the names are assigned as Query A, Query B, etc. When you click on an inactive tab, we switch into it. When you click on the title of the active tab, it should let you edit the title.

The state - queries in every tab, their titles, the current active tab, and query results when they are not large - should be saved in IndexedDB. The history API, that we already use, should also keep track on the active tab, so that back/forward buttons in the browser may also switch tabs.

The currently active query and connection parameters are tracked in the URL, as usual, but we will also add the current tab name - so that on navigating to that URL, we can load existing tabs from IndexedDB, then find existing tab and substitute the query there, or if it is not found or was unnamed - create a new tab with that name (or open in the default tab if there were no saved tabs). This allows a nice solution when a user has their own saved queries and at the same time opens URLs with new queries.


+ The width of title editing textarea should adapt to the width of the text.
When the cursor is over the text of the active tab, the pointer should indicate text-edit.

+ There is padding at the left, and it has the background color of the tab, but at the top it should belong to the the top space. So the top space should take the width including the padding.

+ The left position of the first tab should be aligned to the position of the query editor and tables. So it should be right after the padding.

+ Do not offset position of the active/inactive tab.
Display border at the top of the main area, but not below the active tab title, so that the active tab title will look like part of the main area.
Lower the margin between page top and the tabs.
The [+] button should be right after the last tab and should be visually similar to tabs.

+ Tab titles should use overflow: hellip.
When I edit the tab title, remove max-width, let it flex.

+ If I scroll mouse wheel over the tab panel, scrolling up should switch to the left tab and scrolling down to the right tab (if they exist).

+ Make the tab panel not sticky (disappear when I scroll the page down).

+ It looks like the tab color is just a tiny bit different than the main background color.

+ On the active tab, make the background gradient, so at the bottom it will remain the same color, but at the top, make the color more saturated (in the light theme) / more bright (in the dark theme).

+ Horizontal scroll of the page shouldn't move tabs. So that they are sticky relative to horizontal scroll in the same way as the ClickHouse logo at the bottom.

+ The x (close tab) and + (open a new tab) should be perfectly vertically aligned to each other.

+ The margin between the page top and tabs should be exactly the same size as the margin between tabs.

+ Active tab has two missing border pixels - at the bottom left and bottom right corners.

Comment thread programs/server/play.html Resolved
Comment thread programs/server/play.html Resolved
Comment thread programs/server/play.html Resolved
…sult

`restoreFromHistory` still supports legacy flat history entries (those whose
state is `{query, format, ok, data, ...}` with no nested `result`) via
`state.result || state`, but `onpopstate` stored `tab.result =
event.state.result || null`. Navigating Back to such an entry therefore rendered
its result for that one navigation and then immediately dropped the snapshot from
tab state: in a single-tab session the tab bar stayed hidden even though a result
was visible, and the next tab switch or reload persisted `null` and lost the
restored result.

Normalize a flat entry that actually carries a result (top-level `data` or a
`multi` array) into the nested per-tab snapshot shape here, keeping the
compatibility path intact. Modern entries keep their nested `result` verbatim,
and a genuinely result-less entry stays null. Verified with `node --check` on
the extracted inline `<script>` and a logic simulation (the pre-fix code drops
the legacy snapshot to null; the fix preserves it, while modern and result-less
entries are unchanged).
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Merged master and addressed the AI review (⚠️ Request changes) on b6c78e73; new head 2e66578c83c.

Merge / integration. master gained a per-column color coding feature (column_color_modes, applyColumnColors, persistColorModes, the color_modes URL parameter) that overlapped this PR's history refactor in play.html. Resolved the conflicts by keeping the tabs saveHistory/writeHistoryEntry/restoreFromHistory/renderSnapshotIntoElement refactor and integrating color coding into the tabbed model:

  • renderExtremes was removed on master (superseded by applyColumnColors); dropped the surviving calls in postImpl and renderSnapshotIntoElement and adopted master's render order (renderTotals before applyColumnColors).
  • saveHistory snapshots column_color_modes into the per-tab result, so the coloring travels with the tab (persisted to IndexedDB, restored on re-activation); restoreFromHistory re-applies result.color_modes, and buildHistoryParams carries the color_modes URL parameter.
  • persistColorModes now records the modes on the active tab's result and re-stamps the current history entry + URL in place (nested under the entry's result, matching state.result || state).

❌ Blocker — pending-restore run parameters (resolveRunParams, 34f43c68642). The values already came from the destination tab, but the parameter names were still enumerated from the global currentQueryParams, which is stale until updateQueryParams's tokenization completes. A SELECT {x} → SELECT {y} switch + Run mid-tokenize sent param_x and dropped param_y. Now the names come from the destination tab's saved params keys, so param_y is sent with the tab's saved value.

⚠️ Major — legacy flat history entries (onpopstate, 2e66578c83c). tab.result = event.state.result || null dropped the snapshot for legacy flat entries that restoreFromHistory still renders via state.result || state. Now such an entry (top-level data/multi) is normalized into the nested per-tab snapshot; modern and result-less entries are unchanged.

Verified the extracted inline <script> with node --check and a faithful logic simulation (26/26, with pre-fix controls reproducing both bugs and a color-modes roundtrip). There is no JS/headless harness for play.html in the repo. Replied to and resolved both inline threads (0 unresolved). CI is re-running on the new head.

Comment thread programs/server/play.html Resolved
Comment thread programs/server/play.html Resolved
@alexey-milovidov

Copy link
Copy Markdown
Member Author

@groeneai, fix 02024_storage_filelog_mv

@groeneai

groeneai commented Jul 2, 2026

Copy link
Copy Markdown
Collaborator

@alexey-milovidov fixed the flaky 02024_storage_filelog_mv in #109109.

Root cause: the test waited with two unbounded while true; sleep 1 loops. FileLog's watcher and reader task back off exponentially up to poll_directory_watch_events_backoff_max (32s default), so on the WasmEdge+MSan lane the reader reschedule path can wait up to 32s per idle cycle; stacked across the two wait phases plus BackgroundSchedulePool contention it exceeded the 600s per-test kill (test_duration_ms=600100, reason Timeout!). The runner's own rerun confirmed it was a timing flake, not a settings issue.

Fix (same approach as sibling 02968_file_log_multiple_read): cap poll_directory_watch_events_backoff_max=1000 to bound detection to ~1s, and use a bounded wait helper that fails fast with a diagnostic. Test intent unchanged.

Two remaining state mismatches on the restore/Back-Forward path in
`play.html`, both breaking the "a tab restores exactly what it last showed"
contract flagged by the review.

- Recolor on Back/Forward. `restoreFromHistory` only recolors the page (and
  thus the active-tab slab) on its full-result path; every early return
  (result-less, error, or large/image snapshot) leaves the previous tab's hue.
  `activateTab` already compensates with an unconditional
  `queryToColor(tab.query)` after the await, but `window.onpopstate` did not, so
  navigating Back/Forward into such a tab landed on the right tab with the wrong
  color. Mirror `activateTab`: recolor to the tab's own query after the restore
  resolves (guarded on the request token so a superseded navigation does not
  recolor). For full and multi results this also makes browser navigation land
  on the same color as a click switch.

- Idle logo on a restored JSON exception. The live single-query error path
  (`postSingle`) hides `logoEl` once at the top of its error block, for both
  JSON exceptions and plain-text errors. `restoreFromHistory` only hid it in the
  plain-text `renderError` subpath, so reloading or switching back to a tab that
  had failed with the usual JSON exception showed the exception together with the
  idle logo. Hide the logo for the whole `!result.ok` branch.

Verified with `node --check` on the extracted inline `<script>` and a logic
simulation covering both findings: pre-fix controls reproduce the stale hue and
the leftover logo, the fixes correct them, and full/multi-result tabs color
identically via click and via Back/Forward while a successful restore leaves the
logo untouched.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Addressed the AI review (⚠️ Request changes) on 2e66578c83c; new head 7c86c052d3c (programs/server/play.html only, +15/-2). Both findings were the same class — the restore/Back-Forward path diverging from the live/click path.

  • Recolor on Back/Forward (play.html:5300). restoreFromHistory recolors the page (and the active-tab slab) only on its full-result path; every early return (result-less, error, or large/image snapshot) left the previously active tab's hue. activateTab already compensates with an unconditional queryToColor(tab.query) after the restore, but window.onpopstate did not, so browser navigation into such a tab landed on the right tab with the wrong color. onpopstate now mirrors activateTab (guarded on the request token). For full and multi-query results this also makes Back/Forward land on the same color as a click switch (both end on tab.query).

  • Idle logo on a restored JSON exception (play.html:4671). The live single-query error path (postSingle) hides logoEl once at the top of its error block, for both JSON exceptions and plain-text errors. restoreFromHistory only hid it in the plain-text renderError subpath, so reloading or switching back to a tab that failed with the usual JSON exception showed the exception together with the idle logo. The logo is now hidden for the whole !result.ok branch.

Verified with node --check on the extracted inline <script> and a logic simulation (11/11): pre-fix controls reproduce the stale hue and the leftover logo; the fixes correct both; full/multi-result tabs color identically via click and via Back/Forward; a successful restore leaves the logo untouched. Both inline threads are resolved.

The two remaining CI failures are unrelated to this HTML/JS-only change and already tracked:

Comment thread programs/server/play.html Resolved
Comment thread programs/server/play.html Resolved
…g across tabs

Addresses the AI review (`⚠️ Request changes`) on `7c86c052d3c`. Both findings are
the editor-only history/restore paths diverging from what a genuine run produced.

- Preserve `run=1` while a tab still reflects its run (`play.html`). The editor-only
  history writers (`refreshCurrentHistoryEntry` on tab switch/rename/trusted edit, and
  `syncHistory` on switching into a tab) always dropped `run=1`, so ordinary tab
  navigation or a rename stripped the run marker from an entry that still exactly
  reflected its run. For a shared `run=1` link whose result is not snapshotted (an
  image or an oversized/`multi: null` result), the reload could then no longer reproduce
  what the tab showed. New helper `tabReflectsRun` reports whether the editor
  (`tab.query` + `tab.params`) still matches the query/params that produced
  `tab.result`; both writers now pass it as `fromRun`, so the marker is preserved on a
  clean tab and dropped the moment the editor diverges (so an unrun edit — e.g. a
  `DROP`/`INSERT` — never becomes auto-runnable on reload). `result.query` holds the
  full editor text for a single "Run" and for a multi-query "Run all", so both stay
  reproducible; a "Run selected" result stores only the selected statement and thus
  conservatively drops the marker (its URL hash is the whole editor and could not
  reproduce that single-statement result anyway).

- Do not restore parameters from a stale `currentQueryParams` (`play.html`).
  `restoreFromHistory` and the startup URL reconciliation rebuilt the destination tab's
  parameters by iterating `currentQueryParams`, assuming `updateQueryParams` had just
  rebuilt it. On its failure path (a query too large for the WASM lexer, or no lexer),
  `updateQueryParams` returned early leaving the PREVIOUS tab's list in place, so
  switching `A: SELECT {x:String}` -> `B: <large query>` copied `x` into tab B and
  persisted a bogus `param_x` into history / `IndexedDB`. `updateQueryParams` now
  returns whether the list reflects the current query; both callers honor a `false`
  result by clearing the stale inputs/list and falling back to the tab's own saved
  params instead of deriving cross-tab ones.

Verified with `node --check` on the extracted inline `<script>` and a logic simulation
(14/14): the pre-fix logic reproduces both regressions (image `run=1` lost on a tab
switch; tab B inheriting `{x: ''}`) and the fixes correct them, while single/multi/
"Run selected"/edited/parametrized/result-less tabs and the successful restore path all
behave as intended. Both inline threads are addressed.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Addressed the AI review (⚠️ Request changes) on 7c86c052d3c; new head c50888f45a7 (programs/server/play.html only, +91/-30). Both findings are the editor-only history/restore paths diverging from what a genuine run produced.

  • run=1 stripped on tab switch/rename (play.html). The editor-only history writers (refreshCurrentHistoryEntry, syncHistory) always dropped run=1, so ordinary tab navigation or a rename stripped the run marker from an entry that still exactly reflected its run — a shared run=1 link whose result is not snapshotted (an image or an oversized/multi: null result) could then no longer reproduce what the tab showed on reload. New helper tabReflectsRun reports whether the editor (tab.query + tab.params) still matches the query/params that produced tab.result; both writers pass it as fromRun, so the marker is preserved on a clean tab and dropped the moment the editor diverges (an unrun DROP/INSERT never becomes auto-runnable). Single "Run" and multi-query "Run all" store the full editor into result.query, so both stay reproducible; "Run selected" stores only the selected statement and conservatively drops the marker.

  • Stale currentQueryParams leaking across tabs (play.html). restoreFromHistory and the startup URL reconciliation rebuilt the destination tab's parameters from currentQueryParams, assuming updateQueryParams had just rebuilt it; on its tokenizer-failure path (a query too large for the WASM lexer) it returned early leaving the previous tab's list in place, so a SELECT {x:String} -> <large query> switch copied x into the destination tab and persisted a bogus param_x into history / IndexedDB. updateQueryParams now returns whether the list reflects the current query; both callers honor a false result by clearing the stale inputs/list and falling back to the tab's own saved params.

Verified with node --check on the extracted inline <script> and a logic simulation (14/14): the pre-fix logic reproduces both regressions and the fixes correct them, while single/multi/"Run selected"/edited/parametrized/result-less tabs and the successful restore path all behave as intended. Both inline threads are resolved.

CI on the previous head was fully green (0 failures).

Comment thread programs/server/play.html
const liveIds = new Set(liveTabs.map(t => t.id));
for (const t of savedTabs) {
if (liveIds.has(t.id)) t.id = 't' + (++tabSeq);
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This state machine still lands without any executable regression coverage in-tree. Review already found a long chain of correctness bugs across reconcileStartup, window.onpopstate, and restoreFromHistory, but the proof here is still only ad-hoc simulations in PR comments. Please add at least one focused browser/headless regression that covers saved tabs + URL reconciliation + an unrun edit surviving reload/Back-Forward, or this contract will be easy to break silently in a later play.html refactor.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a fair concern, and I agree the lack of executable coverage for this state machine is a real gap. The constraint is that ClickHouse has no in-tree JavaScript/headless-browser test harness and no CI job that runs one: programs/server/play.html is a single self-contained file with no build step, there is no package.json or bundler, and the only automated coverage today is 01528_play.sh, which just curls /play and greps for a string.

So a saved-tabs + URL-reconciliation + unrun-edit-survives-Back/Forward/reload regression cannot be added as an in-tree test without first introducing that infrastructure — a headless browser (or jsdom) in the test image, a JS test framework, and a dedicated CI job to run it. That is a separate, cross-cutting decision rather than part of this feature, and I would rather add it deliberately than bolt a script onto this PR that no CI job executes (a test CI never runs gives no real regression protection, which is exactly the concern here).

In the meantime, each correctness fix on this PR was verified against the extracted inline <script> with node --check plus a faithful logic simulation of reconcileStartup / window.onpopstate / restoreFromHistory, with pre-fix controls that reproduce each bug. I will track adding a proper headless harness for play.html separately rather than as part of this change.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Status on c50888f45a7:

  • CI: no failures — 107 checks green and the rest still in progress on the fresh run after the last push (0 FAILURE/ERROR).
  • Merge: MERGEABLE, merges cleanly into master (merge-base b00c7d77ffa, ~8h old), so no re-merge and nothing to re-run.
  • Sole open item: the AI review's ⚠️ Request changes for missing in-tree regression coverage of the tab / URL / history restore state machine (programs/server/play.html:7143). As explained in the inline reply, a browser/headless regression test cannot be added without first introducing JS/headless test infrastructure into ClickHouse CI — there is none today (no package.json, no JS test runner; the only /play coverage is the 01528_play.sh curl check). That is a separate, cross-cutting infrastructure decision rather than part of this feature, so no code change this round; the state-machine fixes remain verified via node --check + faithful logic simulations.

Blocked on that test-infra decision plus human review (pamarcos) and merge.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jul 2, 2026
@alexey-milovidov alexey-milovidov self-assigned this Jul 2, 2026
Merged via the queue into master with commit bafd528 Jul 2, 2026
176 checks passed
@alexey-milovidov
alexey-milovidov deleted the play-query-tabs branch July 2, 2026 20:44
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 2, 2026
alexey-milovidov added a commit that referenced this pull request Jul 3, 2026
…ntax-error-position

Resolve conflicts in `programs/server/play.html` between this PR's
syntax-error position highlight and the Web UI features that merged into
`master` in the meantime (query tabs `#107826`, expanded-database restore
`#108964`, and rainbow-bracket / matched-identifier highlighting `#109108`).

- `postSingle` now takes both `params_restore_pending` (tabs feature) and
  `queryStart` (this PR); all call sites use the newer `my_request_num`
  ownership handling and pass both arguments.
- The token render loop keeps `master`'s rainbow-bracket, bold matched-bracket,
  matched-identifier and per-digit-group number rendering, and additionally
  OR-s the `q-err-pos` class onto the token at the reported error position.

The net diff of the branch over `master` is exactly this PR's
syntax-error-highlight feature; no tabs / restore / bracket functionality
was dropped.
dhtclk pushed a commit to fastio/clickhouse-docs that referenced this pull request Jul 7, 2026
The ClickHouse main repository adds a new `docs/en/interfaces/web-sql.md` page
(documenting the `/play` Web SQL UI and its new query tabs) in
ClickHouse/ClickHouse#107826. Like `interfaces/web-terminal`, it is reachable
from the interfaces index but is not part of an autogenerated sidebar, so the
floating-pages check fails the `Docs check` job on that PR.

Add `interfaces/web-sql` to the exceptions list, matching how
`interfaces/web-terminal` is handled.

Related: ClickHouse/ClickHouse#107826

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@Michicosun

Copy link
Copy Markdown
Member

@alexey-milovidov

Will it be better to make different browser tabs independent and not share query tabs in UI? It is not convenient to open multiple play links, each in a different browser tab.

zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
Both issues were raised by the AI review on PR ClickHouse#107826 as the remaining
"Request changes" majors. They concern how startup reconciliation in
`reconcileStartup` blends the URL (query + `param_*`) against tabs saved in
IndexedDB.

1. Stale reload could discard an edited tab's saved query (play.html:5205).
   Editor edits are persisted to IndexedDB by the `input` listener but do not
   re-sync the URL hash. So after running `Query A` as `SELECT 1`, editing it to
   `SELECT 2` and letting it save without running or switching, a reload still
   carried the old `SELECT 1` hash. The named-tab branch then rewrote the saved
   tab back to `SELECT 1`, cleared its result, and `scheduleSave` persisted the
   loss.

   Fix: `lastSavedQuery` (the query as of the last URL/history sync, already
   maintained by `writeHistoryEntry`) is now persisted to IndexedDB and read
   back on load. The URL query is substituted into a matched tab only when it
   differs from `lastSavedQuery` too — i.e. the URL holds a query this tab was
   never synced to (a fresh/shared link for an existing tab name). When the URL
   hash is exactly this tab's own last-synced query but the saved tab has since
   diverged (an unsaved-to-URL edit), the IndexedDB value is newer and is kept.

2. Shared URL could inherit a matched tab's stale parameters (play.html:5232).
   The reconciliation only overlaid `param_*` values present in the URL, so a
   URL query applied to an existing tab inherited whatever parameters that tab
   had saved. Opening `/play?tab=Query%20A&run=1#...` for `SELECT {x:UInt64}`
   without `param_x` reused a saved `x=42` and auto-ran with that stale value.

   Fix: when the URL is authoritative for the query it is authoritative for the
   parameters too. Each placeholder detected in the query now takes its URL
   value when present and is cleared to empty (its default) when absent, fully
   replacing the active tab's parameter snapshot instead of overlaying. This is
   skipped on a stale reload (case 1), where the saved parameters are newer.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…p path

The AI review on PR ClickHouse#107826 flagged the remaining "Request changes" major: the
no-saved-tabs named-URL bootstrap path in `reconcileStartup` adopts the URL tab
name but never seeds `lastSavedQuery`, leaving it `undefined`.

Repro: with no saved workspace, open `/play?tab=New#<SELECT 1>`, edit the tab to
`SELECT 2`, let it persist to IndexedDB, then reload the same URL. On reload there
is now a saved tab, so the named-tab branch matches it by title and, with
`match.lastSavedQuery` still `undefined !== url_query`, treats the old hash as a
fresh external query: it rewrites the tab back to `SELECT 1`, clears its result,
and `scheduleSave` persists the loss.

The loaded-tab and new-tab paths avoid this because they set `activated = true`
and so seed `lastSavedQuery` via `syncHistory`/`postAll` (`writeHistoryEntry` sets
`tab.lastSavedQuery = tab.query`). The bootstrap branch leaves `activated` false
and runs neither, so seed `lastSavedQuery = url_query` explicitly when the URL
carries a query.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…s unique in play.html

Two state-consistency issues flagged by the AI review ("Request changes") on the
Web UI (Play) query tabs:

- Leaving a tab after editing its query without rerunning left the tab's
  browser-history entry holding the last run/URL query. A later Back/Forward to
  that entry restored the stale query and the scheduled IndexedDB save persisted
  over the edit. `switchToTab` and `addTab` now fold the captured editor state
  back into the leaving tab's current history entry: `writeHistoryEntry` gains a
  `forceReplace` path, used by the new `refreshCurrentHistoryEntry`, so
  Back/Forward restores the latest edit rather than the stale run snapshot.

- Tab titles double as the URL `tab=` reconciliation key, so two tabs sharing a
  title let a shared/reloaded URL match — and overwrite — the wrong tab.
  Committing a title edit now disambiguates a collision via `uniqueTitle`, and
  startup reconciliation prefers the originating tab among any (legacy)
  same-titled tabs (its `query` or `lastSavedQuery` equals the URL's) so a shared
  link stays non-destructive.

CI report: ClickHouse#107826

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…ntax-error-position

Resolve conflicts in `programs/server/play.html` between this PR's
syntax-error position highlight and the Web UI features that merged into
`master` in the meantime (query tabs `ClickHouse#107826`, expanded-database restore
`ClickHouse#108964`, and rainbow-bracket / matched-identifier highlighting `ClickHouse#109108`).

- `postSingle` now takes both `params_restore_pending` (tabs feature) and
  `queryStart` (this PR); all call sites use the newer `my_request_num`
  ownership handling and pass both arguments.
- The token render loop keeps `master`'s rainbow-bracket, bold matched-bracket,
  matched-identifier and per-digit-group number rendering, and additionally
  OR-s the `q-err-pos` class onto the token at the reported error position.

The net diff of the branch over `master` is exactly this PR's
syntax-error-highlight feature; no tabs / restore / bracket functionality
was dropped.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-feature Pull request with new product feature pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants