Skip to content

Separate the default type view from persisted query nodes #1919

Closed

Description

@malibio

Summary

Every schema/type has a default query — all nodes of that type, no filters. It is never persisted; there is no node behind it.

A query node materializes only when the user diverges from that default: changing the filters, or changing the view. Until then nothing is saved, not even for the default "all" query.

Current State — the default already exists, unnamed

Clicking a schema in the side nav opens a tab whose nodeId is the schema's own id, tagged nodeType: 'query' (navigation-sidebar.svelte:239). QueryNodeViewer loads that id twice — getNode(schemaId) for raw properties, getSchema(schemaId) for fields — and runs:

const nodes = await backendAdapter.queryNodes({ nodeType: schema.id });  // query-node-viewer.svelte:100

All nodes of the type, unfiltered, nothing persisted. That is the default query, and it is already correct — it just isn't named as such, and nothing distinguishes it from a saved one.

What's broken around it:

  1. currentQueryDefinition reads query properties off the schema node (query-node-viewer.svelte:145–154) — normally absent, hence null.
  2. handleQuerySave writes targetType/filters/sorting/limit onto the schema node (lines 163–171). Schema nodes should not carry query definitions.
  3. Those filters never take effect — loadAndQuery ignores them and re-runs the unfiltered fetch at line 100. By the code, editing filters today changes nothing about what you see.
  4. View selection has nowhere to live. QueryPreferencesService persists lastView to localStorage keyed by node id — a per-device side-channel for a page that has no node.

Target Model

Default query — not persisted. Every type has one. Shows all nodes of that type. No node exists for it. Opening a type, looking at it, and closing it writes nothing.

Divergence materializes a query node. The moment the user changes the filters or the view, a real type: 'query' node is created holding targetType, filters, sorting, limit, and the view configuration. From then on that tab is backed by a node and edits persist to it.

The view change is a materializing trigger because there is otherwise nowhere to persist the selection. This replaces the localStorage side-channel: view config — including the Kanban groupBy and its column setup — lives on the query node, so a board travels with the query rather than being stranded per-device.

QueryNodeViewer serves both, branching on what it was handed:

  • schema id → default query: unfiltered fetch, no persistence, materialize on divergence
  • query node id → load the stored definition and view config, execute, persist edits

The backend is ready: QueryNodeBehavior (packages/core/src/behaviors/mod.rs:1564) is registered and validated with exactly these properties, and QueryNode is typed in packages/desktop-app/src/lib/types/query.ts:36–60. No backend work expected.

Scope

Stop writing queries to schema nodes

  • Delete the handleQuerySave path writing query properties onto the schema node
  • Delete currentQueryDefinition's read of those properties off the schema node
  • Stray properties on existing schema nodes are pre-release debris — no migration (CLAUDE.md), but they must not affect behavior

Viewer branches on default vs. saved

  • Distinguish "schema id" from "query node id". Every schema tab is currently tagged nodeType: 'query', so that flag is decorative and must become truthful
  • Default branch: today's unfiltered fetch, unchanged
  • Saved branch: read definition and view config from the query node, execute with filters

Materialize on divergence

  • Changing filters or view on the default creates a type: 'query' node via backendAdapter.createNode
  • targetType is carried from the schema — never asked for
  • generatedBy: 'user'
  • The tab rebinds to the new node id so subsequent edits persist to it
  • Materialize once: the first divergence creates the node, later changes update it

Titles — follow the BaseNodeViewer pattern

  • The default query shows "Default" at the top, editable, in the same editable-title treatment BaseNodeViewer already provides (TaskNodeViewer delegates to it wholesale; 'Untitled' is the established fallback at base-node-viewer.svelte:1330)
  • Editing that title is itself a divergence — it materializes the node with the typed name
  • Queries beyond the default are created as "Untitled Query", renamed in place
  • Tab title follows the query name

Reverting does not delete

Clearing filters back to "all" and returning to the default view leaves the node in place. It becomes an unfiltered saved query. Nodes are removed only by explicit deletion — a node must not vanish from under an open tab or a nav entry.

Retire the localStorage view preference for this path

With view config on the node, QueryPreferencesService's role here ends. The default query has no node to key on and no persisted view — it opens in the default view every time. Remove the redundant path rather than leaving two mechanisms.

Acceptance Criteria

  • Opening a type shows the default query — all nodes, no filters — and creates no node
  • Viewing and closing the default query persists nothing
  • The default query's title shows "Default" and is editable in place
  • Changing filters on the default materializes a query node
  • Changing the view on the default materializes a query node
  • Renaming the default's title materializes a query node with that name
  • A materialized query is never asked for its targetType — it is inherited from the schema
  • Subsequent edits update the existing node rather than creating another
  • Queries beyond the default are created as "Untitled Query" and can be renamed in place
  • Opening a saved query executes its stored filters and restores its stored view
  • Clearing filters back to "all" leaves the node in place — no auto-delete
  • Kanban groupBy persists on the query node, not in localStorage
  • Deleting a saved query affects neither the default query nor the nodes it matched
  • The tab title reflects the query's name
  • The /query slash command no longer appears in the slash-command menu
  • queryNodePlugin retains its node, viewer, and reference registrations — only slashCommands is emptied
  • Existing query nodes and AI/MCP-created query nodes are unaffected by the removal

The /query slash command creates definition-less nodes

queryNodePlugin (core-plugins.ts:520–548) registers a /query slash command with contentTemplate: ''. It creates a type: 'query' node with freehand content and empty properties — no targetType, no filters. query-node.svelte states in its own header that query nodes are "primarily created by AI/MCP, not manually" and that "full query execution and visualization is not yet implemented."

This collides with the model above. QueryNodeViewer derives everything from targetType; a /query node has none. Opening one calls getSchema(nodeId) against a node that is not a schema, which by the code falls into the SCHEMA_NOT_FOUND empty state (query-node-viewer.svelte:120–125) — so /query currently produces a node that cannot render as a query. Confirm this in the running app before implementing.

Two creation paths must therefore agree:

  • Materialize-on-divergence (above) — type is known from the schema page, filters already exist
  • /query inline — created in a document with no type context and no definition

Decision: disable /query for now. Remove the slash command from queryNodePlugin's slashCommands array (core-plugins.ts:526–534), leaving it as slashCommands: [] — the same shape dateNodePlugin (line 273), documentNodePlugin and others already use. There is no point offering a command that produces a node which cannot render.

This removes only the manual creation path. Everything else about the plugin stays: the node component, the viewer registration, and the reference component all remain, so existing query nodes and AI/MCP-created ones are untouched.

If manual inline creation is wanted later, a /query node still needs to acquire a targetType somehow — either the slash command prompts for a type at creation, or the viewer handles a definition-less node by prompting rather than showing an empty state. The latter is the better shape (prompting mid-document interrupts writing, and it keeps one place responsible for incomplete queries), but that is a future decision, not part of this issue.

Either way, a definition-less query node must not render as a silent empty state.

Open Question — side nav placement

Once queries persist they need to be findable. Nesting them under their type in the side nav is the natural home and the reason to persist at all, but the nav renders schemas flat from schemasStore (navigation-sidebar.svelte:559), so it means loading queries per type and adding a nesting level.

Recommendation: nest under the type in the side nav. If that's too large to bundle, split it into a follow-up — but then materialized queries are unreachable once their tab closes, which is worth deciding deliberately rather than discovering. Proceeding with nesting unless redirected.

Out of Scope

  • Structured filter-builder UI — separate issue; this one owns what is and isn't persisted
  • Sharing or syncing saved queries between users
  • AI-generated queries (generatedBy: 'ai') already create QueryNodes; this must not break them
  • Changing a saved query's target type — fixed at creation

Notes

  • QueryNodeBehavior declares query nodes as leaf nodes (can have children: false) — do not give a saved query children
  • handleQueryPreview (query-node-viewer.svelte:184) ignores filters and counts the whole type; addressed in the filter-builder issue
  • Prerequisite for the filter-builder issue — the builder is simpler once the viewer knows whether it's on a default or a persisted query
  • Materialization is a write triggered by an interaction that doesn't look like saving. It must be unmistakable in the UI (title and tab change) and must not fire on incidental interactions like sorting a table column, unless sorting is deliberately chosen as a divergence too

Activity

  1. mstomar125 commented on Aug 6, 2026

    @mstomar125
    Contributor

    Pragmatic code review (pre-PR) — issue #1919 "Separate the default type view from persisted query nodes"

    Review Type: Initial · Commit reviewed: 44ccd3d9 (branch worktree-issue-1919-default-query-view, 1 ahead of origin/main, 11 files, +975/−618) · Build reported green (quality:fix 0/0; suite 184 files / 4346 tests; 25 new model tests). This is a large behavioral change to core query-view UX that was not run in a live app, so the focus below is runtime/logic/UX correctness.

    The architecture is clean and the split is the right one: pure, unit-tested helpers in query-node-model.ts; the viewer branching on the loaded node rather than the decorative tab flag; view config moved onto properties.viewConfig; the localStorage side-channel fully removed (no dangling refs — only two doc-comment mentions remain). The re-route/remount plumbing is sound: pane-content preserves content.nodeType (already 'query' for schema tabs), so the {#key} remount re-loads correctly, and tab titles resolve reactively via computeTabTitle → so the materialized name shows up without pushing title state. Credit where due.

    That said, the client-side execution model and a few interaction edges have real defects worth fixing before this ships.


    Requirements Check (17 acceptance criteria)

    # Criterion Status
    1 Opening a type shows the default query (all nodes, no filters), creates no node ✅
    2 Viewing and closing the default persists nothing ✅
    3 Default title shows "Default", editable in place ✅
    4 Changing filters on the default materializes a query node ✅
    5 Changing the view on the default materializes a query node ✅
    6 Renaming the default's title materializes a query node with that name ✅ (content = typed name, not "Untitled Query")
    7 A materialized query is never asked for its targetType (inherited) ✅ (closure targetType; buildMaterializedProperties force-sets it, ignoring the editor's value)
    8 Subsequent edits update the existing node, not create another ⚠️ Broken in the create-succeeds/get-returns-null path — see F3
    9 Queries beyond the default → "Untitled Query", renamable in place ✅
    10 Opening a saved query executes stored filters and restores stored view ⚠️ View restored correctly; filter execution is not faithful — see F1 (fetch cap) and F2 (parent/children pass-through)
    11 Clearing filters back to "all" leaves the node in place — no auto-delete ✅ (saved-branch updateNode with filters:[]; no delete path)
    12 Kanban groupBy persists on the query node, not localStorage ✅
    13 Deleting a saved query affects neither the default nor matched nodes ✅ by construction (no delete path in this component; query node is independent)
    14 Tab title reflects the query's name ✅ (computeTabTitle reads the seeded node reactively)
    15 /query no longer appears in the slash-command menu ✅ (slashCommands: []; test counts updated 14→13)
    16 queryNodePlugin keeps node/viewer/reference; only slashCommands emptied ✅
    17 Existing + AI/MCP query nodes unaffected ⚠️ Not broken — actually improved (an AI query with a real targetType now renders + executes where it previously hit the SCHEMA_NOT_FOUND empty state). But targetType:'*' still shows the empty state, and F1/F2 apply. See F2/F7.

    Findings

    🟡 F1 — Saved-query filters run against a server-capped fetch (default 100), so a saved query silently under-returns

    📁 packages/desktop-app/src/lib/components/viewers/query-node-viewer.svelte:177 (+ query-node-model.ts:executeQueryDefinition)

    The saved branch does queryNodes({ nodeType: targetType }) with no limit, then filters/sorts/limits client-side. But the backend applies a default cap: the daemon maps req.limit == 0 → None (packages/daemon/src/services/node_service.rs:511-514) and NodeService::query_nodes_simple then substitutes DEFAULT_QUERY_LIMIT = 100 (packages/core/src/services/node_service/query.rs:298-300, node_service/mod.rs:352). So for any type with >100 instances, only the first 100 (store order, effectively arbitrary) are fetched and the filter is evaluated against that slice.

    Failure scenario: a type has 500 invoices, 40 of them status = closed but all beyond the first 100 by store order. A saved query "status = closed" renders "0 items" / the empty state, even though 40 match. The result is silently wrong, and the header count ("N items") reinforces the wrong number. This directly undercuts criterion 10 ("executes its stored filters"), which is the reason the feature exists. The default unfiltered view has the same cap but is far less surprising (it's visibly "all", truncated).

    Principle: correctness of a persisted query must not depend on incidental fetch ordering/limits. Either pass an explicit high limit for the client-side path, or (better, as a follow-up) push filters server-side. At minimum this cap should be a conscious, documented decision, not an inherited accident.

    🟡 F2 — parent / children relationship filters are treated as pass-through (return true), silently widening results

    📁 packages/desktop-app/src/lib/components/query/query-node-model.ts:282

    matchesFilter evaluates mentions/mentioned_by from node-local data but, for parent/children (and any unknown operator, line 313), returns true. The doc comment frames this as "return the type's nodes rather than silently emptying" — but that trade means a saved query whose intent is "children of X" instead shows every node of the type. That is arguably worse than empty: empty signals "nothing matched", whereas a full list looks authoritative while being wrong.

    Failure scenario: an AI/MCP-created query with a {type:'relationship', relationshipType:'children', nodeId:'X'} filter (well within what generatedBy:'ai' can emit per query.ts) renders all nodes of the type as if unfiltered. Criterion 17 says AI queries "must not break" — they don't error, but they display incorrect results.

    Principle: a filter the engine cannot honor should fail visibly (or exclude), not be silently dropped in the widening direction. Consider surfacing "this query uses a filter this view can't evaluate yet" rather than pretending it passed.

    🟡 F3 — createNode succeeds but getNode returns null → orphan node, no re-route, no error, and "materialize once" is broken

    📁 packages/desktop-app/src/lib/components/viewers/query-node-viewer.svelte:297-299

    await backendAdapter.createNode({...});               // node now exists in the DB
    if (sharedNodeStore.currentEpoch() !== epoch) return; // ok (ADR-053)
    const created = await backendAdapter.getNode(newId);
    if (!created || sharedNodeStore.currentEpoch() !== epoch) return; // <-- silent

    If getNode returns null (or the epoch shifts) after a successful create, the function returns without re-routing and without setting saveError; finally resets materializing = false. Net effect: a real query node was persisted but the tab stays on the default view, the user sees no change and no error, and because the guard is cleared, the next divergence creates another node — violating criterion 8 ("update the existing node rather than creating another"). The node is also unreachable (no nav nesting yet — see F7).

    Principle: a completed write must not leave the UI in a state that implies it didn't happen. Since newId is known, either re-route anyway (the remount's loadAndQuery(newId) will re-fetch) or surface saveError. Silent success-that-looks-like-nothing is the worst outcome.

    🟡 F4 — Escape does not reliably cancel a title edit; it can still materialize/rename

    📁 packages/desktop-app/src/lib/components/viewers/query-node-viewer.svelte:436-444 (with commitTitle at 409-434)

    Enter calls .blur() (→ onblur=commitTitle, the intended commit). Escape only sets isEditingTitle = false — it does not clear titleDraft and there is no "cancelled" guard. When isEditingTitle flips false the {#if} destroys the focused <input>, and in most browsers removing a focused element dispatches a blur. If that blur reaches the handler, commitTitle runs with the still-typed titleDraft: on the default branch a non-empty name materializes a query; on the saved branch it renames — the exact opposite of "cancel".

    Failure scenario: user clicks "Default", types "scratch", changes their mind, presses Escape → a scratch query node is materialized and the tab re-routes to it. Whether the stray blur fires is environment-dependent, which is precisely the kind of thing that won't show up in svelte-check but bites in the running app (which this wasn't). Add an explicit cancel guard (e.g. set a cancelling flag or reset titleDraft before flipping isEditingTitle), and have commitTitle early-return when cancelling.

    🟢 F5 — Rapid view/group-by changes on a saved query fire concurrent updateNodes sharing one version → optimistic-concurrency error

    📁 packages/desktop-app/src/lib/components/viewers/query-node-viewer.svelte:315-330 (persistViewConfig, also commitTitle/saved handleQuerySave)

    persistViewConfig is fire-and-forget and reads queryNode.version at call time. Two quick toggles (List→Table before the first updateNode resolves) dispatch two writes with the same version; the second loses the version check and surfaces "Failed to save view" while the persisted config diverges from the on-screen view. Low likelihood against a fast local daemon (needs sub-round-trip clicks), but view toggling is a common gesture and the error banner is confusing. Consider serializing writes or refreshing version from the store before each write.

    🟢 F6 — Divergence handlers mutate view state before the materializing guard, so a dropped second divergence loses the user's last choice

    📁 packages/desktop-app/src/lib/components/viewers/query-node-viewer.svelte:378, 389

    handleViewChange/handleKanbanGroupByChange set activeView/kanbanGroupBy first, then call materializeQuery, which early-returns if materializing. During an in-flight materialize (e.g. a title-blur materialize triggered by the same gesture that clicks a view tab), the second handler updates local state but is dropped; after remount the view snaps back to the first divergence's choice, silently discarding the user's last click. Note: the guard itself is sound against true double-materialization — Svelte 5 flushes the reroute/remount in a microtask before the next click (macrotask), so separate clicks can't create two nodes. This is only the lost-last-choice edge. Set state after the guard, or fold the pending choice into the single materialize.

    🟢 F7 — Empty-state copy misleads for a filtered saved query, and materialized queries are currently unreachable after tab close

    📁 packages/desktop-app/src/lib/components/viewers/query-node-viewer.svelte:591

    "No nodes of this type yet." is correct for the default view but wrong for a saved query that matched 0 of N existing nodes (and for targetType:'*', which fetches empty). Reword to distinguish "no matches" from "type is empty". Separately, materialized nodes are created at root (parentId: null) with nav nesting deferred to a TODO — the issue itself flags this as a decision worth making deliberately, since a persisted query that vanishes from navigation once its tab closes partly defeats the point of persisting. Fine to defer, but call it out in the PR.

    🟢 F8 — Minor

    • Dead branch: the default-mode branch of handleKanbanGroupByChange (:393-395) is effectively unreachable — reaching Kanban requires a view switch, which already materializes and remounts into saved mode. Harmless, but it reads as reachable.
    • Edit→Save with no change still materializes (handleQuerySave default branch): opening the editor and saving an unchanged empty definition creates a redundant unfiltered query. Defensible (explicit user action) but worth a conscious call.
    • handleQueryPreview (:367-369) still counts the whole type ignoring filters — the issue explicitly scopes this to the filter-builder issue; noting only for completeness.

    What I checked and found clean (stated plainly, per the adversarial brief)

    • Double-materialize: not a real risk — the materializing guard holds across the await createNode, and the reroute/remount flushes in a microtask before any subsequent click, so separate gestures cannot mint two nodes.
    • Re-route correctness: content.nodeType stays 'query' through updateTabContent, the {#key} remounts on the new id, and the remounted viewer re-loads as saved. Sound.
    • resolveViewerMode / parsing / merge helpers: defensively typed, no any, good unknown-narrowing; 25 tests cover the branch/parse/execute logic.
    • Reactivity after a saved groupBy change: KanbanView.picked + viewer kanbanGroupBy stay consistent (no remount); after a materialize the remount resets picked. Consistent.
    • Deletions: QueryPreferencesService + its type/test removed with no dangling imports; plugin/slash-command test counts updated correctly.
    • Code quality vs CLAUDE.md: createLogger used, no any, no lint suppressions, greenfield (no compat shims). Good.

    Recommendation: REQUEST CHANGES

    Nothing here is a crash or data-loss critical, and the design is solid — but F1 (saved queries silently return wrong results past 100 nodes) and F2 (parent/children filters silently widen) undermine the feature's core promise that a saved query executes its filters, and F3/F4 are real runtime correctness/UX defects that unit tests + svelte-check will not catch and that a live run would likely surface. Address F1–F4 (F1/F2 may legitimately be scoped as documented follow-ups if the cap/pass-through are made visible rather than silent); F5–F8 are polish. Given this hasn't been run in the app, a manual pass exercising materialize-from-view-change, Escape-during-rename, and a saved query over a >100-instance type is strongly advised before merge.

  2. mstomar125 commented on Aug 7, 2026

    @mstomar125
    Contributor

    Resolved via PR #1986 (squash-merged to main, branch deleted). Default type view now materializes as a distinct in-memory view separate from persisted query nodes; gate-green, adversarially re-reviewed (APPROVE). Unblocks #1920 (structured filter builder).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions