Skip to content

Web UI: make query tabs persistent across switches - #109425

Merged
alexey-milovidov merged 58 commits into
masterfrom
web-ui-persistent-tabs
Jul 20, 2026
Merged

alexey-milovidov merged 58 commits into
masterfrom
web-ui-persistent-tabs

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jul 5, 2026 •

Copy link
Copy Markdown
Member

Makes the Web UI (play.html) query tabs persistent.

Previously the UI kept a single shared editor and a single shared result element and swapped their content on every tab switch. As a result, switching away from a tab and back re-rendered its result from a stored snapshot (losing images from FORMAT PNG, resetting uPlot chart zoom/selection, and dropping any result over 100 KB whose data is not snapshotted), and switching tabs aborted the in-flight query so a long query could not keep running in the background.

Now each tab owns a persistent result panel that stays alive in the DOM while inactive (just hidden), plus its own query-execution state. Switching neither re-renders the result nor aborts a running query — a query keeps streaming into its own tab's element in the background, and returning to that tab shows its live progress or finished result intact. Panels are materialized lazily: a tab loaded from IndexedDB builds its result DOM only when first activated.

The global request_num supersede token is split into activation_num (guards the shared editor + parameter-input restore, never aborts queries) and a per-tab tab.reqNum (guards writes into a tab's own result element, so a re-run/cancel/close supersedes stale writes while a plain switch does not). The run path threads the launching tab explicitly, and saveHistory writes browser history/URL only for the active tab. Per-column color modes are per-tab. Back/Forward keeps its time-travel semantics.

Tab titles gain activity effects: a spinning hourglass while the tab's query runs, a progress-bar fill behind the title, and a completion check-mark shown once a query finishes while the tab is inactive (cleared when the tab is opened). The favicon shows "running" while any tab has a query in flight.

Verified end-to-end with headless Playwright against play.clickhouse.com (?user=play): result persistence across switch (same DOM node, no re-render, including an oversized result whose snapshot stores no data), independent background queries with completion, lazy materialization after reload, tab-title spinner/check-mark, multi-query persistence, and error persistence.

Changelog category (leave one):

  • Improvement

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

Web UI: query tabs are now persistent — each tab keeps its rendered result (including images and charts) and its running query when you switch away and back, and long queries continue running in the background. Tab titles show a spinner, progress bar, and completion check-mark for their query.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.7.1.1256 (included in 26.7 and later)

Previously the Web UI (`play.html`) kept a SINGLE shared editor and a single
shared result element, swapping their content on every tab switch. This had two
drawbacks:

- Switching away from a tab and back re-rendered its result from a stored
  snapshot. Results that cannot be reconstructed from text - an image
  (`FORMAT PNG`), a `uPlot` chart's zoom/selection, or any result over 100 KB
  whose data is not snapshotted - were lost or reset.
- Switching tabs aborted the in-flight query, so a long query could not keep
  running while you worked in another tab.

Now each tab owns a persistent result panel (`tab.panel` / `tab.resultEl`) that
stays alive in the DOM while inactive (just hidden), and its own query
execution state. Switching neither re-renders the result nor aborts a running
query: a query keeps streaming into its own tab's element in the background, and
returning to that tab shows its live progress or finished result intact. Panels
are materialized lazily - a tab loaded from `IndexedDB` builds its result DOM
only when first activated.

The global `request_num` supersede token is split into two roles:
- `activation_num` (global) guards the shared editor + parameter-input restore
  (`restoreEditor`), so a superseded switch stops writing the editor; it never
  aborts queries.
- `tab.reqNum` (per tab) guards everything that writes into a tab's own result
  element - both a live `postImpl` stream and a snapshot materialization - so a
  re-run / cancel / close supersedes stale writes while a plain switch does not.

The run path (`postOne`/`postAll`/`postSingle`/`postMulti`/`postImpl`/
`saveHistory`) now takes the tab it was launched in explicitly, so a run always
targets that tab even after the user switches away; `saveHistory` only writes
browser history / URL for the active tab. Per-column color modes become per-tab
(`tab.colorModes`, mirrored onto each `query-result`). Back/Forward keeps its
time-travel semantics (re-render from the history snapshot).

Tab titles gain activity effects: a spinning hourglass while the tab's query
runs, a progress-bar fill behind the title, and a completion check-mark shown
once a query finishes while the tab is inactive (cleared when the tab is
opened). The favicon shows "running" while any tab has a query in flight.

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

clickhouse-gh Bot commented Jul 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1b71eaa]

Summary: ✅


AI Review

Summary

This PR makes play.html tabs persistent, keeps background queries running across tab switches, and reworks history/startup reconciliation heavily. Most of the previously reported state-isolation issues are fixed in the current head, but one blocker remains: the run=1 auto-run directive is still tracked as a page-global flag, so after opening a ?run=1 link it can leak onto a different clean tab and make a later reload or shared URL execute the wrong query.

Findings

❌ Blockers

  • [programs/server/play.html:7807] run=1 is still page-global instead of tab/entry-scoped. After a ?run=1 link finishes its deferred auto-run in tab A, switching to another clean tab B with an existing result calls syncHistory -> buildHistoryParams(..., fromRun = true) for B, so this branch adds run=1 to B as well. Reloading or sharing that URL then auto-executes B even though the original directive belonged only to A. Carry the marker per tab/entry (for example, preserve it only when that tab already had it, or consume the global flag once the deferred auto-run has been honored) instead of reusing a page-global run_immediately for every later tabReflectsRun write.
Final Verdict

Changes requested.

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Jul 5, 2026
@alexey-milovidov
alexey-milovidov marked this pull request as draft July 5, 2026 01:40
Comment thread programs/server/play.html Resolved
Comment thread programs/server/play.html Resolved
Comment thread programs/server/play.html Resolved
Address the AI review of the persistent-tabs change:

- `syncActiveTabChrome` now fully resets the shared progress widget and
  rebuilds both of its halves (the live "Read ..." stats + bar and the
  "N rows in result" line) from the opened tab's own state. Previously the
  running branch left the "N rows in result" line from the previously active
  tab, and the done branch left its stale "Read ..." stats.

- `cancel` now drops the tab's `'running'` progress phase and its live
  progress snapshot and clears the shared progress widget. Previously an
  explicit Stop left the tab logically stuck in `'running'`, so the shared
  hourglass kept spinning and reopening the tab replayed a stale "still
  running" bar under a `Run` button.

- Startup reconciliation now preserves the URL's `color_modes` for the
  URL-authoritative tab (a fresh/shared link whose query is substituted, or a
  new tab opened for it). Previously `materializeResult` reset the tab's
  color modes from its empty snapshot, so a shared link lost its per-column
  colors once the bootstrap tab was replaced by the `IndexedDB` workspace.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment thread programs/server/play.html Resolved
Comment thread programs/server/play.html Resolved
Comment thread programs/server/play.html Resolved
Comment thread programs/server/play.html Resolved
alexey-milovidov and others added 3 commits July 5, 2026 03:46
Follow-up to the persistent-query-tabs work, addressing the five Majors from
the AI review on #109425:

1. First long query could not be backgrounded: `renderTabBar` kept the tab bar
   hidden until a finished result existed, so a fresh page never showed the
   `[+]` button while the first query was in flight. The bar's `hidden` state
   now also accounts for a running query (`anyInFlight`), `beginFlight` reveals
   it when a run starts, and `endFlight` collapses it again if the run left no
   result (e.g. cancelled before the first row).

2. A launched run was dropped on a tab switch during the lexer/tokenization
   preflight: `postOne`/`postAll` cancelled the run when `activation_num`
   changed while `splitAllQueries`/`getQueryUnderCursor` awaited the WASM lexer.
   The editor text and selection are now snapshotted before the await and the
   run parses that snapshot, superseded only by a newer run/cancel in the SAME
   tab (`tab.reqNum`). `getQueryUnderCursor` is refactored to be DOM-pure: it
   takes the snapshot and returns the query plus the range to highlight, and the
   caller applies the selection/focus only when its tab is still active, so a
   background run never moves the foreground editor.

3. A shared/bookmarked link lost its encoded `color_modes` on an exact-match
   reconciliation: `reconcileStartup` only re-applied `url_color_modes` when it
   substituted the query or created a fresh tab, so an exact match kept the
   saved palette and `syncHistory` rewrote the URL back to it. The URL is now
   treated as authoritative for the tab's color coding whenever it carries a
   query and this is not a stale reload, including exact matches. The re-apply
   mutates the modes object in place and recolors the single and any multi-query
   result elements, keeping every aliasing element in sync.

4. A rerun inherited the previous run's progress fill: `beginFlight` cleared
   `completed` but left the old `tab.progress` snapshot, so the tab indicator
   (and `syncActiveTabChrome` on a quick switch-away/back) showed stale numbers
   until the first new `query-progress` event. `beginFlight` now resets
   `tab.progress`.

5. `tab.completed` was set even when a query finished in the foreground, so
   switching away later wrongly showed a "finished while away" check-mark. All
   three completion sites (single-query success and error paths, and `postMulti`)
   now gate `tab.completed` on the tab being inactive at the moment the run ends.

The `getQueryUnderCursor` token-walking algorithm is unchanged, so its C++
regression port in `src/Parsers/tests/gtest_play_get_query_under_cursor.cpp`
stays in sync.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Extends the tab-title completion indicator: a tab whose query finished while it
was inactive shows a green check-mark on success and now a red cross (`✖`) when
the query errored. Tracked by a per-tab `failed` flag set on the error paths of
`postSingle`/`postMulti` (and mirrored on snapshot materialization); a "Run all"
where any statement fails counts as failed. Both the check and the cross clear
when the tab is opened, and neither appears for a query that finished while its
tab was active.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
A query finishing in an inactive (hidden) tab produced a broken table layout:
`transposeIfNeeded` and `_changeTableLayout` measure `offsetWidth`/`offsetHeight`
to freeze column widths, but a `display:none` panel measures 0, so every column
collapsed to minimal width.

The streamed rows still render into the hidden element (cheap, and progress keeps
working), but the two measurement-based passes are now deferred when the tab is
not active: `postImpl`/`postSingle` set `_pendingTranspose`/`_pendingChangeLayout`
instead of running them, and `activateTab` calls a new `applyDeferredLayout` on
every `query-result` in the tab's panel once it is shown, so widths are measured
against the visible panel. `renderTotals`/`applyColumnColors` are content-only and
still run immediately.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment thread programs/server/play.html Resolved
Comment thread programs/server/play.html Resolved
Comment thread programs/server/play.html Resolved
alexey-milovidov and others added 2 commits July 5, 2026 07:29
…cess

A query that streams progress under a 200 response and then fails (e.g. a
`SETTINGS max_execution_time` timeout, or `throwIf` after some progress) sends a
`{"exception":...}` line in the middle of the stream. The streaming reader passed
it to `update`, which rendered the error, but the HTTP response was `ok`, so the
run was classified as a SUCCESS: the tab got a green check-mark, the snapshot was
saved with `ok:true`, and the success path ran `renderTotals`/`transposeIfNeeded`
— which for the 0-row result showed the "empty result" layout. In a background
tab this surfaced as an empty result when switching to it.

The reader now detects a mid-stream `{"exception":...}`, renders just the error,
and returns it as a failure so the caller takes the error path (red cross,
`ok:false` snapshot, restored as the exception on reload). Blank lines in the
stream are also skipped, so a trailing/empty line no longer makes `JSON.parse('')`
throw a spurious "Unexpected end of JSON input" client error over the real result.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Follow-up to the mid-stream-exception fix: instead of clearing the result when a
`{"exception":...}` arrives after a 200, keep whatever rows already streamed in
and render the error beneath them — a partial result is still worth showing, and
its layout pass runs (deferred while the tab is hidden) so the columns are sized
correctly. Only when nothing but a header arrived is the empty table cleared, so
a failed query never shows a bare header-only "result"; just the error. The run
is still reported as a failure (red cross, ok:false snapshot) in both cases.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment thread programs/server/play.html Resolved
@alexey-milovidov
alexey-milovidov requested a review from pamarcos July 6, 2026 04:56
@pamarcos pamarcos self-assigned this Jul 7, 2026
@pamarcos

pamarcos commented Jul 7, 2026

Copy link
Copy Markdown
Member

Feedback from GPT-5.5:
One current restore-path issue remains: saved ok: false snapshots that contain partial rows followed by an in-band exception restore only the exception. A live tab can keep the partial rows, but after switching away/reopening or reloading, the restored result drops those rows and shows only the error. Please replay the non-exception rows first and render the exception underneath, falling back to a bare error only when no rows were produced.

`saveHistory` replaced `tab.query` with the editor text captured at
launch unconditionally. A run can finish in the background after the
user edited the query and switched away: `captureActiveTab` has already
saved the newer draft into `tab.query`, and the completion callback
then overwrote it with the old launch text, losing the draft on the
next activation or reload.

Record the launch-time editor text on the tab (`tab.launchQuery`) in
`postOne`/`postAll`, and let `saveHistory` adopt the launch text only
while the tab's draft still matches it. When the draft diverged, the
history entry now carries the unrun draft, so it must not be stamped
`run=1` — pass `fromRun` accordingly, keeping the invariant that an
unrun edit is never auto-runnable from a reload or shared link.
`last_query_start` was a page-wide global, but tabs now execute
queries concurrently: when tab B launched a query while tab A's was
still running, B overwrote the timestamp and A's completion path
recorded B's start time, underreporting `elapsed_ns` in the saved
snapshot (wrong runtime shown after reopening or reloading the
finished tab, for raw/image results and for error snapshots).

Capture the start time in a `const` local to `postSingle`/`postMulti`
so each run's completion closes over its own launch time. The only
other `last_query_start` is an unrelated shadowed local in
`getQueryUnderCursor`, which stays.
The guard that stops `captureActiveTab` from snapshotting the
`param_*` DOM inputs while a tab activation is still restoring them was
tied to `activation_num` (`params_restore_pending_token !==
activation_num` meant "no restore pending"). `postOne`/`postAll` bump
`activation_num` at launch, which superseded the in-flight
`restoreEditor` BEFORE it committed the destination tab's parameter
values — but also lifted the guard, so a subsequent capture (switching
away again, or the debounced persist) snapshotted the previous tab's
still-visible parameter values into the wrong tab and persisted them.

Repro: tab A has `{x}`, tab B has none; switch to B, hit Run before the
lexer-driven restore finishes, then immediately switch away — B's saved
state received A's `param_x`.

Make the guard survive the run's bump: it stays armed until a restore
actually commits (`restoreEditor` nulls the token; a superseded restore
leaves it set because the inputs it was going to write never made it to
the DOM). Every activation starts a new restore and the latest one
always commits, so capture cannot stay suppressed across a tab switch.
The run itself is unaffected: it already sources its parameters from
the tab's saved snapshot via `resolveRunParams` while a restore is
uncommitted, and that check now uses the same non-null-token predicate.
The live streaming path was already fixed to keep the rows that
streamed before a mid-stream `{"exception":...}` and render the error
beneath them, but the restore paths still scanned an `ok: false`
snapshot for the first exception line and rendered only that: switching
away and back (after a re-materialization), reloading, or restoring a
multi-query statement dropped the partial rows the live tab had kept.

Factor the restore into `restoreErrorSnapshot`: replay the
pre-exception lines as rows first, then render the exception message
underneath, falling back to a bare error when the snapshot holds no
rows or its payload is not row JSON at all (a non-200 error body). Used
by both `materializeResult` and `renderSnapshotIntoElement`, with the
same transpose/layout passes as the success restore.

Requested by @pamarcos in the PR discussion.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

@pamarcos Implemented in a8fa9b4: the ok: false snapshot restore now replays the non-exception rows first and renders the exception underneath them, in both restore branches (materializeResult for single-query snapshots and renderSnapshotIntoElement for multi-query statements, via a shared restoreErrorSnapshot helper), falling back to a bare error only when no rows were produced — matching the live mid-stream behavior.

Also pushed on top of a fresh master merge (the branch was 8 days behind): efd8743 (saveHistory no longer clobbers a newer draft saved into tab.query by a background finish), cdb1fbf (per-run query start time instead of the shared last_query_start global), and c091bf9 (the param-restore guard stays armed until the restore commits, so a run during the restore can no longer cause the previous tab's param_* values to be captured into the wrong tab).

Comment thread programs/server/play.html Resolved
Comment thread programs/server/play.html Resolved
…large to store

Addresses an AI-review finding (`clickhouse-gh` on `play.html:4853`): a failed
reply larger than 100000 bytes was persisted as `ok: false` with `data: null`,
and `materializeResult` returned to the idle state on `!result.data` before it
checked `result.ok`. A query that streamed many rows and then threw, or that
returned a long error body, therefore reopened blank after a reload instead of
restoring the failure this PR promises.

Persist a compact stand-in (`compactFailureSnapshot`) for an oversized failure
instead of dropping it to `null`: the `{"exception":...}` line when the stream
carried one, otherwise a bounded prefix of the error body. Also make the restore
path treat `ok: false` with no data as a failed snapshot, replaying the stored
error (or a short notice for a legacy/edge snapshot) rather than reopening idle.

#109425
Addresses an AI-review finding (`clickhouse-gh` on `play.html:6421`): starting a
run marks the tab's live panel authoritative (`tab.materialized = true`) but left
`tab.result` pointing at the previous completed snapshot. A debounced `persist` /
`refreshCurrentHistoryEntry` scheduled by the editor edit that preceded the run
would then serialize that old snapshot under the new query text, so a rerun that
is cancelled or reloaded before `saveHistory` records a fresh snapshot reopened
showing the previous result attached to the new editor contents.

Clear `tab.result` in `beginFlight` the moment a run supersedes it, and schedule a
save so the cleared state is persisted; `saveHistory` installs the new snapshot on
completion.

#109425
Comment thread programs/server/play.html Resolved
Comment thread programs/server/play.html Resolved
alexey-milovidov and others added 3 commits July 13, 2026 08:31
Reconcile the persistent-tabs rewrite of `programs/server/play.html` with
master's `web-ui-highlight-syntax-error-position` feature (which added
syntax-error highlighting in the editor after a failed run):

- `postImpl`/`postSingle`/`postMulti` now take both the PR's `tab` (owning the
  run) and master's `queryStart` (the query's absolute character offset, threaded
  to `highlightQueryError`). The PR's per-run `query_start = performance.now()`
  timestamp (for `elapsed_ns`) is kept distinct from master's `queryStart` offset.
- `beginFlight` performs master's per-run highlight resets (`clearQueryError`,
  `queryErrorOwnerStart = -1`, `runEditorInteraction = editorInteractionGen`) for
  the active tab.
- `getQueryUnderCursor` stays DOM-pure: instead of master's mutable global
  `queryUnderCursorStart` (which would race across concurrent background runs),
  the query's start offset is returned as `queryStart` on its result object and
  threaded through by the caller, alongside the per-statement `queryStart` that
  `splitAllQueries` already returns.
- The run-launch callers use `focusEditorForRun` (which suppresses the
  return-to-editor interaction bump) instead of a plain `query_area.focus`, so the
  programmatic focus does not cancel the very highlight the run is about to produce.

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

`postOne`/`postAll` snapshot the editor text before awaiting the WASM lexer
(`splitAllQueries` / `getQueryUnderCursor`) so a background run keeps executing
after a tab switch. But the parameter values were still resolved *inside*
`postSingle`/`postMulti` — after that await — from the shared `param_*` inputs
(`getParamValues`) or, in the pending-restore branch, from `getActiveTab`. If tab
`B` launched a parameterized query and the user switched to tab `A` before the
lexer preflight finished, the run that correctly stayed attached to `B` executed
with `A`'s bindings. That is a correctness bug for parameterized queries, not just
stale UI.

Resolve the parameter values up front in `postOne`/`postAll`, from the launching
tab, before the await, and thread that single snapshot through
`postSingle`/`postMulti`/`postImpl`. `resolveRunParams` now takes the launching
`tab` explicitly instead of re-reading `getActiveTab`, so the pending-restore
branch reads the launching tab's saved `params` rather than whichever tab is
active by the time the run resumes.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`materializeResult` rebuilds a historical snapshot into a tab's panel but did not
clear `tab.progress`, so `syncActiveTabChrome`'s `'done'` branch could replay a
later run's live `Read ...` counters and progress-bar fill underneath an older
restored result. Repro: run `Q1`, rerun the same tab with `Q2`, then press Back to
the `Q1` entry — the restored result is `Q1`'s, but the progress widget still
painted `Q2`'s live-progress snapshot, breaking the Back/Forward time-travel
semantics this feature promises.

Clear `tab.progress` at the start of `materializeResult`: a rematerialized
snapshot is a historical result with no live progress, and its finished stats come
from `tab.finalStats`. `materializeResult` only runs for a tab that is not in
flight (lazy first open, or Back/Forward after `abortTabQuery`), so clearing the
live-progress numbers there is always safe.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment thread programs/server/play.html Resolved
Comment thread programs/server/play.html Resolved
alexey-milovidov and others added 7 commits July 19, 2026 01:42
…nnection replay

The persistent-tabs `onpopstate` restores a navigated-to entry's connection by
assigning `url_elem`/`user_elem` and dispatching synthetic `input` events so the
normal connection listeners (`checkURL`, `updateDocsURL`, `resetCredentialsStatus`,
`resetConnectionScopedState`) replay a real connection edit's side effects.

But `resetConnectionScopedState` also restamps the CURRENT history entry via
`refreshCurrentHistoryEntry(getActiveTab())` whenever the connection or selection
changed. Inside `onpopstate` that is wrong twice over: `history.state` is already
the popped entry the restore is rebuilding, and `activeTabId` still points at the
tab being left (it is rebound only later in the handler). So for a same-tab
Back/Forward that changes the connection with a non-null `selected_database`, the
synthetic `url` input cleared the selection and then rewrote the popped entry from
the leaving tab's newer query/cleared `database=`, corrupting the time-travel
target before the handler could restore `event.state`.

Guard the synthetic replay with `restoring_connection_from_history` (set only
around the dispatch, cleared in a `finally`); while it is set,
`resetConnectionScopedState` still resets its connection-scoped caches but skips
the history restamp. `onpopstate` performs the authoritative entry/URL restore
itself.

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

`onpopstate` treats a result-less history entry specially: an entry written while
its tab was mid-run holds `result: null` (a run nulls `tab.result` at launch and
reinstalls it only on completion, and a background run finishing in another tab
reinstalls the result in memory without rewriting the null entry). Rather than
time-travelling over such an entry and blanking a tab that is still streaming or
just finished, the handler navigated to it like a plain tab switch when the tab
was in flight or already held a result.

That shortcut was too broad: it preserved ANY later `tab.result`, not
specifically the run the null entry came from. Start `Q1` in a tab, switch away
(entry stores `result: null`), later run `Q2` in the same tab, then jump straight
back to the old mid-run entry via the browser history menu / `history.go`:
`tab.result` is now `Q2`, so the shortcut kept `Q2` on screen even though the
entry predates that run.

Gate the shortcut on run provenance: a mid-run entry records the launch query
(and params), and that identity survives on the tab as the still-running launch
(`launchQuery`) or the completed in-memory snapshot (`tab.result`). Keep the live
state only when it matches the entry's query (and, for a completed result, its
params); otherwise fall through to plain time-travel and render the entry itself.
This preserves the legitimate "background run finished after a tab switch" case
while dropping an unrelated later result.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`window.onpopstate`'s `result: null` shortcut (which lets a tab's live state
stand in for a mid-run history entry so a completed background run is not blanked
by Back/Forward) inferred "same run" from matching `query` + `params` against
`tab.result.query`. That misidentified two real cases:

- A multi-statement `Run selected` stores only the selected statement in
  `tab.result.query`, while the mid-run `result: null` entry keeps the full editor
  text in `event.state.query`, so `Back` to that entry still reopened the tab blank.
- A later rerun with the same text and bindings satisfied the predicate too, so an
  unrelated later result could be shown under an older entry's URL.

Give each run launch a unique identity (`run_seq` -> `tab.launchRunId`), stamp it
onto the completed snapshot (`tab.result.run_id`) and every history entry
(`state.run_id`), and gate the shortcut on the id instead of the query text: the
live state stands in only when the tab's still-running launch or completed snapshot
carries the entry's own `run_id`. Legacy entries persisted before `run_id` existed
fall back to the earlier launch-query / snapshot-query heuristic.

Addresses review: #109425 (comment)
The `run_seq` counter backing per-run identities (`tab.launchRunId`,
`tab.result.run_id`, history entries' `state.run_id`) was page-local while
the ids it minted are persisted in browser history and `IndexedDB` tab
snapshots. After a reload the counter restarted at `1`, so a fresh launch
could reuse the identity of an old mid-run (`result: null`) history entry
and `window.onpopstate` would keep the newer result under the older URL.

`persist` now stores the counter in the meta record (like `tabSeq` /
`tabTitleSeq`) and `reconcileStartup` re-seeds `run_seq` above every
persisted `run_id` it can see: the restored meta counter, the saved tab
snapshots (covers meta records from before the counter was persisted), and
the current `history.state` (covers a reload whose `IndexedDB` state is
gone while the history entry survived).

Co-Authored-By: Claude Fable 5 <[email protected]>
The per-tab pinned-columns reconciliation (merge of #109439) made
`reconcileStartup` call `el.applyPinnedColumns` next to
`el.applyColumnColors` on the restored result elements. The stub DOM in
`reconcile_harness.js` provides inert versions of every method the page
script calls on the un-upgraded `<query-result>` elements, but predates
that call, so `test_play_reconcile_startup` failed with
`TypeError: el.applyPinnedColumns is not a function`:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109425&sha=d9cb588f299b55f85865afdb3749a8d8dadbe951&name_0=PR&name_1=Integration%20tests%20%28amd_asan_ubsan%2C%20db%20disk%2C%20old%20analyzer%2C%204%2F6%29

Co-Authored-By: Claude Fable 5 <[email protected]>
The run-identity counter (`run_seq`) could still alias an old mid-run
history entry after a reload: a higher `run_id` may survive only in a
deeper Back/Forward entry that never reached `IndexedDB` (the deferred
`persist` window, or `IndexedDB` unavailable), and session-history
entries are not enumerable at startup, so no counter re-seeding can
promise uniqueness against them.

Instead of re-seeding, qualify every id with `run_epoch` — a random
token drawn once per page instance. Ids minted by different page
instances can never be equal, so a post-reload launch can never adopt
the identity of an entry written before the reload, while ids persisted
together by a previous instance (a tab snapshot and the history entries
of the same run) still match each other after a reload. The counter
persistence (`meta.runSeq`) and the startup re-seeding are removed as
obsolete; the harness sandbox gains `crypto` (webcrypto) for the
epoch's `getRandomValues`.

Co-Authored-By: Claude Fable 5 <[email protected]>
Comment thread programs/server/play.html
state.pinned_columns = url_pinned_columns_out || {};
/// The producing user/server/database are serialized into the URL and stamped into the state so
/// Back/Forward can restore this entry's `database=` only while the live connection still matches.
const history_params = buildHistoryParams(tab.params, tab.title, carries_run, color_modes, pinned_columns, entry_user, entry_server, entry_database);

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.

run=1 is still treated as a page-global sticky flag here. If I open a ?run=1 link and let its deferred auto-run finish in tab A, then switch to another clean tab B that already has a result, syncHistory calls buildHistoryParams(..., fromRun = true) for B and this branch stamps run=1 onto B as well. Reloading or sharing that URL will then auto-execute B even though the original directive belonged only to A.

This needs to be carried per tab / per history entry (or the global flag needs to be consumed once the deferred auto-run has been honored) instead of reusing a page-global run_immediately for every later tabReflectsRun write.

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.

While this is real, it's not a big problem.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jul 20, 2026
Merged via the queue into master with commit 9a6b3a5 Jul 20, 2026
178 checks passed
@alexey-milovidov
alexey-milovidov deleted the web-ui-persistent-tabs branch July 20, 2026 23:44
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 21, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
Follow-up to the persistent-query-tabs work, addressing the five Majors from
the AI review on ClickHouse#109425:

1. First long query could not be backgrounded: `renderTabBar` kept the tab bar
   hidden until a finished result existed, so a fresh page never showed the
   `[+]` button while the first query was in flight. The bar's `hidden` state
   now also accounts for a running query (`anyInFlight`), `beginFlight` reveals
   it when a run starts, and `endFlight` collapses it again if the run left no
   result (e.g. cancelled before the first row).

2. A launched run was dropped on a tab switch during the lexer/tokenization
   preflight: `postOne`/`postAll` cancelled the run when `activation_num`
   changed while `splitAllQueries`/`getQueryUnderCursor` awaited the WASM lexer.
   The editor text and selection are now snapshotted before the await and the
   run parses that snapshot, superseded only by a newer run/cancel in the SAME
   tab (`tab.reqNum`). `getQueryUnderCursor` is refactored to be DOM-pure: it
   takes the snapshot and returns the query plus the range to highlight, and the
   caller applies the selection/focus only when its tab is still active, so a
   background run never moves the foreground editor.

3. A shared/bookmarked link lost its encoded `color_modes` on an exact-match
   reconciliation: `reconcileStartup` only re-applied `url_color_modes` when it
   substituted the query or created a fresh tab, so an exact match kept the
   saved palette and `syncHistory` rewrote the URL back to it. The URL is now
   treated as authoritative for the tab's color coding whenever it carries a
   query and this is not a stale reload, including exact matches. The re-apply
   mutates the modes object in place and recolors the single and any multi-query
   result elements, keeping every aliasing element in sync.

4. A rerun inherited the previous run's progress fill: `beginFlight` cleared
   `completed` but left the old `tab.progress` snapshot, so the tab indicator
   (and `syncActiveTabChrome` on a quick switch-away/back) showed stale numbers
   until the first new `query-progress` event. `beginFlight` now resets
   `tab.progress`.

5. `tab.completed` was set even when a query finished in the foreground, so
   switching away later wrongly showed a "finished while away" check-mark. All
   three completion sites (single-query success and error paths, and `postMulti`)
   now gate `tab.completed` on the tab being inactive at the moment the run ends.

The `getQueryUnderCursor` token-walking algorithm is unchanged, so its C++
regression port in `src/Parsers/tests/gtest_play_get_query_under_cursor.cpp`
stays in sync.

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
…large to store

Addresses an AI-review finding (`clickhouse-gh` on `play.html:4853`): a failed
reply larger than 100000 bytes was persisted as `ok: false` with `data: null`,
and `materializeResult` returned to the idle state on `!result.data` before it
checked `result.ok`. A query that streamed many rows and then threw, or that
returned a long error body, therefore reopened blank after a reload instead of
restoring the failure this PR promises.

Persist a compact stand-in (`compactFailureSnapshot`) for an oversized failure
instead of dropping it to `null`: the `{"exception":...}` line when the stream
carried one, otherwise a bounded prefix of the error body. Also make the restore
path treat `ok: false` with no data as a failed snapshot, replaying the stored
error (or a short notice for a legacy/edge snapshot) rather than reopening idle.

ClickHouse#109425
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
Addresses an AI-review finding (`clickhouse-gh` on `play.html:6421`): starting a
run marks the tab's live panel authoritative (`tab.materialized = true`) but left
`tab.result` pointing at the previous completed snapshot. A debounced `persist` /
`refreshCurrentHistoryEntry` scheduled by the editor edit that preceded the run
would then serialize that old snapshot under the new query text, so a rerun that
is cancelled or reloaded before `saveHistory` records a fresh snapshot reopened
showing the previous result attached to the new editor contents.

Clear `tab.result` in `beginFlight` the moment a run supersedes it, and schedule a
save so the cleared state is persisted; `saveHistory` installs the new snapshot on
completion.

ClickHouse#109425
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…tement

`beginFlight` (which now drops the tab's previous result and clears its
panel) was called before the lexer preflight in `postOne`/`postAll` had
proved there is a statement to run. A whitespace-only selection in
multi-query mode therefore erased the previous result as a no-op, and a
tokenizer exception in the preflight (documented for huge queries) exited
before `endFlight`, leaving the tab stuck "running" with its result wiped.

Defer `beginFlight` until after the preflight has produced a runnable
statement: a no-op launch returns without touching the tab, and a
preflight failure leaves the tab idle with its result intact. The
editor-interaction generation is snapshotted at launch and threaded into
`beginFlight`, so an edit made during the preflight still disarms the
late server-error highlight, and the snapshot-null + panel-clear stay
atomic with `postSingle`/`postMulti` (no await in between anymore).

Addresses the AI review finding at play.html:6583 in
ClickHouse#109425

Co-Authored-By: Claude Fable 5 <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
`paramValuesSnapshot` was frozen at launch from `currentQueryParams`,
which is rebuilt only by the asynchronous `updateQueryParams` started by
the last editor edit. A quick `SELECT {x}` -> `SELECT {y}` edit followed
immediately by Run (e.g. on a cold WASM load or a large buffer) still
snapshotted `{x}` from the stale controls and executed the new SQL
without `param_y` — and recorded the foreign `param_x` as the params
that produced the result.

`postOne`/`postAll` now derive the parameter NAMES from the run's own
tokenization of the launched text (`extractRunParamNames`) and bind them
to the VALUES snapshotted at launch (`pickRunParams` over the live
inputs merged with the tab's saved params, so a value restored moments
ago is found even when its input has not been rebuilt yet). A name with
no known value is omitted, so the server reports it as not set instead
of the run silently executing with a stale or foreign binding. When the
list cannot be derived (no lexer / text too large to tokenize), the
launch-time snapshot is used as before.

Addresses the AI review finding at play.html:6577 in
ClickHouse#109425

Co-Authored-By: Claude Fable 5 <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…ished run

`saveHistory` gated the `run=1` marker only on the query text still
matching the launch snapshot. Editing a `param_*` input while the run
was still in flight updates `tab.params`, and the history entry / URL is
written from `tab.params` — so the entry carried the EDITED bindings
with `run=1`, and reloading or sharing that URL reran different bindings
than the result currently shown (start `SELECT {x:Int32}` with
`param_x=1`, change it to `2` mid-run, let the run finish).

Apply the same "draft still matches the launched run" predicate to the
parameters: compare `tab.params` against `stateData.params` (the
launch-time snapshot the run executed with — the same comparison
`tabReflectsRun` uses against `result.params`) and stamp `run=1` only
when both the text and the params are unchanged.

Addresses the AI review finding at play.html:6334 in
ClickHouse#109425

Co-Authored-By: Claude Fable 5 <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
`bootstrap_settled` was set right after `loadFromDb` resolved, i.e. before
`reconcileStartup` had run `activateTab`, `updateQueryParams`, and the deferred
auto-run. Once it was set, `markBootstrapDirty` returned early, so a genuine
user edit made during those remaining awaits was no longer recorded as dirty.
As a result a cold `?run=1` load could auto-run text the user typed after the
page became interactive, and the URL-driven parameter restore could overwrite
an in-flight edit instead of yielding to it.

Set `bootstrap_settled` only once reconciliation has fully finished (at each
terminal path), so an edit during any reconciliation await marks the workspace
dirty and gates both the URL parameter restore and the auto-run. Reconciliation's
own synthetic input events carry `isTrusted === false` and are already filtered,
so keeping the flag live does not misattribute them. Also re-check the flag after
the `updateQueryParams` await before applying URL parameters.

Addresses AI review (blocker) for ClickHouse#109425

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
When `extractRunParamNames` cannot derive the run's parameter names (no WASM
lexer, or the query is too large to tokenize) `postOne`/`postAll` fell back to
`param_values_at_launch`. In the non-restore case that is just the live
`param_*` inputs, which `restoreEditor` / the URL-reconciliation failure path
deliberately clear while the authoritative bindings still live in `tab.params`.
Reloading a saved parameterized tab whose query the lexer cannot tokenize and
pressing `Run` then dropped its persisted `param_*` values entirely.

Fall back to the merged `param_sources` (live inputs over the tab's saved
`params`) instead, so the persisted bindings are sent whenever there is no live
parameter list.

Addresses AI review (major) for ClickHouse#109425

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
`postMulti` recorded a failed multi-query run with `progressPhase = 'done'`, and
`restoreMultiQuery` persisted the same phase. `syncActiveTabChrome` treats every
`'done'` tab as success and calls `progressEl.finish()`, so reopening a
background tab whose `Run all` had any statement error painted a green success
check-mark in the shared chrome, contradicting the tab's saved failure state.

Encode a failed `Run all` with the same `'error'` phase single-query failures
use (in both `postMulti` and `restoreMultiQuery`), and clear the shared progress
widget on a foreground failure instead of calling `finish()`. The per-statement
errors remain rendered in their own panels, and the tab title keeps its red cross.

Addresses AI review (major) for ClickHouse#109425

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
A run executes against the launch-time connection snapshot, while
`buildHistoryParams` serializes the current shared `url`/`user` inputs into the
history entry. Changing the server or user while a query is in flight (or after
it finished) therefore produced a `run=1` URL that displays a result from one
target but auto-reruns the SQL against another on reload or share.

Record the producing connection (server and user only — the password is never
persisted, the snapshot travels into browser history state and `IndexedDB`) on
the result snapshot in `saveHistory`, and require the current inputs to still
name it before stamping `run=1` (`connection_unchanged`) or keeping it in the
editor-only history writers (`tabReflectsRun` via the new
`connectionMatchesInputs`). A result persisted before connections were recorded
conservatively drops the marker.

Addresses ClickHouse#109425 (comment)
and the first finding of the GPT-5.6 review feedback.
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
`reconcileStartup`'s deferred auto-run (`postAll`) and its URL-driven parameter
restore both act on `getActiveTab()`/`activeTabId` AFTER an await
(`updateQueryParams`, and the lexer preflight inside `postAll` itself). A
plain tab switch does not mark the workspace `bootstrap_dirty`, so a click
during one of those awaits silently retargets the deferred restore/auto-run
at the newly active tab instead of the URL-authoritative one it was resolved
for.

`switchToTab` (used by tab-bar clicks, Enter/Space, and wheel-scroll) now
calls `markBootstrapDirty()`, the same signal `addTab`/`openQueryInNewTab`
already send for an analogous reason. Reconciliation then yields to the
switch exactly as it would to any other genuine interaction during the load
window.

Addresses the review finding at ClickHouse#109425 (comment)
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
`writeHistoryEntry`/`buildHistoryParams` serialize the `url`/`user` in effect
when an entry was written into its query string (omitted when they equal the
defaults), but `onpopstate` only ever restored the tab/query/result — never
the connection. The browser updates `location.href` to the target entry's URL
before `popstate` fires, so a Back/Forward across a connection change left
the live `url`/`user` inputs on whatever was active before navigating, while
the address bar and the restored tab/result pointed at the entry's own
server/user. Running from that "restored" entry then executed against the
wrong target.

`onpopstate` now reads the connection back from the post-navigation URL and,
if it differs from the live inputs, applies it and calls
`resetConnectionScopedState()` (mirroring what editing the connection inputs
does), before resolving/reactivating the tab.

Addresses the review finding at ClickHouse#109425 (comment)
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
`captureActiveTab` already skips snapshotting the `param_*` DOM inputs into
`tab.params` while `params_restore_pending_token` is set — right after
`activateTab` switches `activeTabId` but before `restoreEditor`'s
`updateQueryParams` await has rebuilt the inputs for the newly active tab,
they still hold the PREVIOUS tab's values. The per-input `input` listener had
no such guard: a genuine edit to one of those still-visible stale inputs
during that window wrote `getParamValues()` straight into
`getActiveTab().params`, attributing the previous tab's parameter values (now
including the edit) to the newly active tab and clobbering whatever it was
actually restoring.

Skip the same write while a restore is pending; `restoreEditor`'s own commit
sets `tab.params` correctly once it resolves.

Addresses the review finding at ClickHouse#109425 (comment)
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
`window.onpopstate`'s `result: null` shortcut (which lets a tab's live state
stand in for a mid-run history entry so a completed background run is not blanked
by Back/Forward) inferred "same run" from matching `query` + `params` against
`tab.result.query`. That misidentified two real cases:

- A multi-statement `Run selected` stores only the selected statement in
  `tab.result.query`, while the mid-run `result: null` entry keeps the full editor
  text in `event.state.query`, so `Back` to that entry still reopened the tab blank.
- A later rerun with the same text and bindings satisfied the predicate too, so an
  unrelated later result could be shown under an older entry's URL.

Give each run launch a unique identity (`run_seq` -> `tab.launchRunId`), stamp it
onto the completed snapshot (`tab.result.run_id`) and every history entry
(`state.run_id`), and gate the shortcut on the id instead of the query text: the
live state stands in only when the tab's still-running launch or completed snapshot
carries the entry's own `run_id`. Legacy entries persisted before `run_id` existed
fall back to the earlier launch-query / snapshot-query heuristic.

Addresses review: ClickHouse#109425 (comment)
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…t-tabs

Web UI: make query tabs persistent across switches
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-improvement Pull request with some product improvements 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.

4 participants