Skip to content

Commit b3f6332

Browse files
authored
feat(data-inspector): copy query results with context (#485)
1 parent 415a307 commit b3f6332

6 files changed

Lines changed: 469 additions & 13 deletions

File tree

‎plugins/data-inspector/app/App.vue‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,8 @@ function saveCurrent(input: { title?: string, description?: string, scope: Saved
8989
<Pane class="min-w-0">
9090
<ResultViewer
9191
:result="wb.result.value"
92+
:observation="wb.observation.value"
93+
:observation-notices="wb.observationNotices.value"
9294
:has-result="wb.hasResult.value"
9395
:stats="wb.stats.value"
9496
:stats-stale="wb.statsStale.value"

‎plugins/data-inspector/app/components/ResultViewer.vue‎

Lines changed: 57 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,23 @@
11
<script setup lang="ts">
22
import type { NodePath, QueryStats } from '@devframes/plugin-data-inspector/engine'
3+
import type { QueryObservation } from '../composables/query-observation'
34
import ActionIconButton from '@antfu/design/components/Action/ActionIconButton.vue'
45
import DisplayBadge from '@antfu/design/components/Display/DisplayBadge.vue'
56
import DisplayBytes from '@antfu/design/components/Display/DisplayBytes.vue'
67
import DisplayDate from '@antfu/design/components/Display/DisplayDate.vue'
78
import DisplayDuration from '@antfu/design/components/Display/DisplayDuration.vue'
8-
import { computed, shallowRef, watch } from 'vue'
9+
import FormTextarea from '@antfu/design/components/Form/FormTextarea.vue'
10+
import OverlayModal from '@antfu/design/components/Overlay/OverlayModal.vue'
11+
import { computed, onUnmounted, shallowRef, watch } from 'vue'
912
import { useDiscoveryViewer } from '../composables/discovery'
1013
import { prepareForDisplay } from '../composables/display-transform'
14+
import { observationMarkdown } from '../composables/query-observation'
1115
import { colorScheme } from '../composables/scheme'
1216
import EditPanel from './EditPanel.vue'
1317
1418
const props = defineProps<{
19+
observation: QueryObservation | null
20+
observationNotices: string[]
1521
result: unknown
1622
hasResult: boolean
1723
stats: (QueryStats & { rpcMs: number }) | null
@@ -72,16 +78,38 @@ const lockTooltip = computed(() => {
7278
return ''
7379
})
7480
75-
const copied = shallowRef(false)
81+
const copied = shallowRef<'json' | 'markdown' | null>(null)
82+
const copying = shallowRef(false)
83+
const manualCopyOpen = shallowRef(false)
84+
const manualCopyText = shallowRef('')
85+
const copyError = shallowRef('')
7686
let copiedTimer: ReturnType<typeof setTimeout> | undefined
77-
function copyResult(): void {
87+
onUnmounted(() => clearTimeout(copiedTimer))
88+
89+
async function copyResult(format: 'json' | 'markdown'): Promise<void> {
90+
if (!props.hasResult || !props.observation || copying.value)
91+
return
92+
// Serialize at the click, before a refresh can replace the observation.
93+
const text = format === 'markdown'
94+
? observationMarkdown(props.observation, props.observationNotices)
95+
: JSON.stringify(props.observation.result, null, 2) ?? 'null'
96+
copying.value = true
97+
copied.value = null
98+
copyError.value = ''
99+
clearTimeout(copiedTimer)
78100
try {
79-
void navigator.clipboard.writeText(JSON.stringify(props.result, null, 2))
80-
copied.value = true
81-
clearTimeout(copiedTimer)
82-
copiedTimer = setTimeout(() => (copied.value = false), 1200)
101+
await navigator.clipboard.writeText(text)
102+
copied.value = format
103+
copiedTimer = setTimeout(() => (copied.value = null), 1200)
104+
}
105+
catch {
106+
copyError.value = 'Clipboard write failed. Select and copy the complete text below.'
107+
manualCopyText.value = text
108+
manualCopyOpen.value = true
109+
}
110+
finally {
111+
copying.value = false
83112
}
84-
catch {}
85113
}
86114
</script>
87115

@@ -138,13 +166,22 @@ function copyResult(): void {
138166
@click="viewer.setExpanded(1)"
139167
/>
140168
<ActionIconButton
141-
v-if="hasResult"
142169
class="text-sm"
143-
:icon="copied ? 'i-ph:check' : 'i-ph:copy-duotone'"
170+
:disabled="!hasResult || copying"
171+
:icon="copied === 'json' ? 'i-ph:check' : 'i-ph:copy-duotone'"
144172
label="Copy result as JSON"
145173
tooltip="Copy the result as JSON"
146-
@click="copyResult"
174+
@click="copyResult('json')"
147175
/>
176+
<ActionIconButton
177+
class="text-sm"
178+
:disabled="!hasResult || copying"
179+
:icon="copied === 'markdown' ? 'i-ph:check' : 'i-ph:file-text-duotone'"
180+
label="Copy result with context"
181+
tooltip="Copy result with context"
182+
@click="copyResult('markdown')"
183+
/>
184+
<span class="sr-only" role="status">{{ copied ? 'Copied to clipboard' : '' }}</span>
148185
<ActionIconButton
149186
class="text-sm"
150187
:icon="running ? 'i-ph:arrows-clockwise animate-spin' : 'i-ph:arrows-clockwise'"
@@ -155,6 +192,14 @@ function copyResult(): void {
155192
/>
156193
</div>
157194

195+
<div v-if="hasResult && observationNotices.length" class="px-3 py-2 text-xs color-muted border-b border-base" role="status">
196+
<p v-for="notice in observationNotices" :key="notice">
197+
{{ notice }}
198+
</p>
199+
</div>
200+
<OverlayModal v-model:open="manualCopyOpen" title="Copy manually" :description="copyError">
201+
<FormTextarea v-model="manualCopyText" readonly :rows="14" class="font-mono text-xs" aria-label="Complete copy text" @focus="($event.target as HTMLTextAreaElement).select()" />
202+
</OverlayModal>
158203
<div
159204
v-if="error"
160205
class="mx-3 mt-2 px-3 py-2 font-mono text-xs whitespace-pre-wrap rounded-lg border border-red-600/40 bg-red-500:8 color-red-700 dark:(border-red-400/40 color-red-300)"
@@ -173,7 +218,7 @@ function copyResult(): void {
173218
<div v-if="!hasResult" class="flex-1 grid place-items-center select-none">
174219
<div class="flex flex-col items-center gap-2 color-faint">
175220
<span class="i-ph:tree-structure-duotone text-3xl" />
176-
<span class="text-sm">Results render here, start typing a query</span>
221+
<span class="text-sm">Run a successful query to view and copy its result</span>
177222
</div>
178223
</div>
179224
</div>
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import type { FilterOptions, QueryStats } from '@devframes/plugin-data-inspector/engine'
2+
3+
/** One successful response and the conditions that produced it. */
4+
export interface QueryObservation {
5+
source: { id: string, title: string }
6+
query: string
7+
filters: Required<FilterOptions>
8+
receivedAt: number
9+
result: unknown
10+
normalize: QueryStats['normalize']
11+
}
12+
13+
function fenced(text: string, language = ''): string {
14+
const runs = text.match(/`+/g) ?? []
15+
const fence = '`'.repeat(runs.reduce((length, run) => Math.max(length, run.length + 1), 3))
16+
return `${fence}${language}\n${text}\n${fence}`
17+
}
18+
19+
export function observationMarkdown(observation: QueryObservation, notices: string[]): string {
20+
const { source, query, filters, receivedAt, result, normalize } = observation
21+
return [
22+
'# Data Inspector query result',
23+
'## Source and time',
24+
fenced(`Name: ${source.title}\nID: ${source.id}`),
25+
`Browser received this result at ${new Date(receivedAt).toISOString()} (UTC). This is not the time when the data was sampled on the node side.`,
26+
...notices,
27+
'## Executed query',
28+
fenced(query, 'jora'),
29+
'Filters:',
30+
...Object.entries(filters).map(([key, value]) => `- ${key}: ${value}`),
31+
'## Result',
32+
fenced(JSON.stringify(result, null, 2) ?? 'null', 'json'),
33+
'## Data scope and limits',
34+
'This is one successful response after Data Inspector conversion and filtering, not a lossless copy of the original object.',
35+
`Reported truncation: depth=${normalize.truncatedDepth}, entries=${normalize.truncatedEntries}, properties=${normalize.truncatedProps}.`,
36+
'No reported truncation does not prove completeness. Later node expansions are not included. The source name and ID do not identify a machine or deployment.',
37+
].join('\n\n')
38+
}

‎plugins/data-inspector/app/composables/workbench.ts‎

Lines changed: 42 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import type { DataSourceMeta, FilterOptions, NodePath, QueryOutcome, QueryStats,
88
* An empty query runs `$` (the root), so every source lands on a full view.
99
*/
1010
import type { InjectionKey } from 'vue'
11+
import type { QueryObservation } from './query-observation'
1112
import jora from 'jora'
1213
import { computed, inject, reactive, ref, shallowRef, watch } from 'vue'
1314
import { backend, connection } from './rpc'
@@ -178,6 +179,22 @@ export function useWorkbench() {
178179
const statsStale = ref(false)
179180
const result = shallowRef<unknown>()
180181
const hasResult = ref(false)
182+
const observation = shallowRef<QueryObservation | null>(null)
183+
const observationNotices = computed(() => {
184+
const saved = observation.value
185+
if (!saved)
186+
return []
187+
const notices: string[] = []
188+
if (saved.query !== (query.value.trim() || '$') || FILTER_KEYS.some(key => saved.filters[key] !== settings[key]))
189+
notices.push('Query conditions changed. This result uses the earlier conditions shown in the copy.')
190+
if (running.value)
191+
notices.push('A new query is pending. This is the previous successful result.')
192+
if (serverError.value)
193+
notices.push('The latest query failed. This is an earlier successful result.')
194+
if (syntax.value.kind !== 'ok')
195+
notices.push('The current query has incomplete or invalid syntax and was not executed.')
196+
return notices
197+
})
181198
/** When the last successful query landed, driving the "ran … ago" label. */
182199
const lastRunAt = ref<number | null>(null)
183200

@@ -270,12 +287,17 @@ export function useWorkbench() {
270287
syntax.value = { kind: 'ok' }
271288
}
272289

290+
const request = {
291+
source: { id: sourceId.value, title: activeSource.value?.title ?? sourceId.value },
292+
query: text,
293+
filters: { ...settings },
294+
}
273295
const seq = ++runSeq
274296
running.value = true
275297
const started = performance.now()
276298
let outcome: QueryOutcome
277299
try {
278-
outcome = await backend().query(sourceId.value, text, { ...settings })
300+
outcome = await backend().query(request.source.id, request.query, request.filters)
279301
}
280302
catch (error) {
281303
if (seq === runSeq) {
@@ -305,6 +327,12 @@ export function useWorkbench() {
305327
result.value = outcome.result
306328
hasResult.value = true
307329
lastRunAt.value = Date.now()
330+
observation.value = {
331+
...request,
332+
receivedAt: lastRunAt.value,
333+
result: outcome.result,
334+
normalize: { ...outcome.stats.normalize },
335+
}
308336
}
309337

310338
function scheduleRun(): void {
@@ -499,6 +527,17 @@ export function useWorkbench() {
499527
}
500528
scheduleRun()
501529
})
530+
watch(sourceId, () => {
531+
++runSeq
532+
running.value = false
533+
result.value = undefined
534+
hasResult.value = false
535+
observation.value = null
536+
lastRunAt.value = null
537+
stats.value = null
538+
statsStale.value = false
539+
serverError.value = null
540+
}, { flush: 'sync' })
502541
watch(sourceId, () => {
503542
suggestions.value = []
504543
restoreDraft()
@@ -569,6 +608,8 @@ export function useWorkbench() {
569608
statsStale,
570609
result,
571610
hasResult,
611+
observation,
612+
observationNotices,
572613
lastRunAt,
573614
suggestions,
574615
skeleton,
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
import type { QueryObservation } from '../app/composables/query-observation'
2+
import { describe, expect, it } from 'vitest'
3+
import { observationMarkdown } from '../app/composables/query-observation'
4+
5+
function observation(): QueryObservation {
6+
return {
7+
source: { id: 'tasks', title: 'Task queue' },
8+
query: '$',
9+
filters: { excludeFunctions: false, excludeUnderscoreProps: true, excludeDollarProps: false },
10+
receivedAt: Date.UTC(2026, 10, 5, 12),
11+
result: [],
12+
normalize: {
13+
nodes: 1,
14+
refs: 0,
15+
truncatedDepth: 0,
16+
truncatedEntries: 0,
17+
truncatedProps: 0,
18+
ms: 1,
19+
},
20+
}
21+
}
22+
23+
describe('query observation Markdown', () => {
24+
it('copies large results with many backtick runs without dropping content', () => {
25+
const saved = observation()
26+
saved.result = Array.from({ length: 200 }, () => '`a'.repeat(2000))
27+
expect(observationMarkdown(saved, [])).toContain(JSON.stringify(saved.result, null, 2))
28+
})
29+
30+
it('includes the successful empty result, explicit filters, receipt time and limits', () => {
31+
const text = observationMarkdown(observation(), ['A new query is pending. This is the previous successful result.'])
32+
expect(text).toContain('Name: Task queue\nID: tasks')
33+
expect(text).toContain('2026-11-05T12:00:00.000Z (UTC)')
34+
expect(text).toContain('excludeFunctions: false')
35+
expect(text).toContain('excludeUnderscoreProps: true')
36+
expect(text).toContain('excludeDollarProps: false')
37+
expect(text).toContain('```json\n[]\n```')
38+
expect(text).toContain('A new query is pending.')
39+
expect(text).toContain('No reported truncation does not prove completeness.')
40+
expect(text).not.toContain('queryMs')
41+
})
42+
43+
it('reports all truncation counters and preserves arbitrary fenced content', () => {
44+
const saved = observation()
45+
saved.source.title = 'Queue\n```\n# arbitrary title'
46+
saved.query = '"````"'
47+
saved.result = { value: '`````\ntext' }
48+
saved.normalize.truncatedProps = 5
49+
const text = observationMarkdown(saved, [])
50+
expect(text).toContain('````\nName: Queue\n```\n# arbitrary title\nID: tasks\n````')
51+
expect(text).toContain('`````jora\n"````"\n`````')
52+
expect(text).toContain('``````json\n')
53+
expect(text).toContain('depth=0, entries=0, properties=5')
54+
expect(text).toContain(JSON.stringify(saved.result, null, 2))
55+
})
56+
})

0 commit comments

Comments
 (0)