Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/__tests__/agentOutcomes.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ jest.mock('@/components/ui/button', () => ({
const call: AgentToolCall = {
id: 'call',
toolName: 'sqlkit__execute_ddl',
args: '{"connection_id":"dev","sql":"CREATE TABLE example(id INT)"}',
args: { connection_id: 'dev', sql: 'CREATE TABLE example(id INT)' },
status: 'denied',
riskLevel: 'destructive',
requiresConfirmation: false,
Expand Down
10 changes: 8 additions & 2 deletions src/__tests__/aiPermissions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,12 @@ jest.mock('vue-i18n', () => ({
jest.mock('@/components/ui/button', () => ({
Button: { template: '<button><slot /></button>' },
}))
jest.mock('@/components/ui/tooltip', () => ({
Tooltip: { template: '<div><slot /></div>' },
TooltipContent: { template: '<div><slot /></div>' },
TooltipProvider: { template: '<div><slot /></div>' },
TooltipTrigger: { template: '<div><slot /></div>' },
}))
jest.mock('@/components/ui/label', () => ({
Label: { template: '<label><slot /></label>' },
}))
Expand Down Expand Up @@ -311,7 +317,7 @@ describe('aI permission chain', () => {
await wrapper.get('#ai-default-create').setValue(false)
expect(wrapper.get('[data-value]').attributes('data-value')).toBe('custom')
expect(wrapper.findAll('input[type="checkbox"]')).toHaveLength(5)
await wrapper.get('button').trigger('click')
await wrapper.findAll('button').find(button => button.text() === 'aiPermissions.save')!.trigger('click')
await flushPromises()
expect(mockInvoke).toHaveBeenLastCalledWith('save_ai_permissions', {
defaults: aiPreset('read'),
Expand All @@ -323,7 +329,7 @@ describe('aI permission chain', () => {
await flushPromises()
await wrapper.get('input[value="custom"]').setValue()
expect(wrapper.findAll('input[type="checkbox"]')).toHaveLength(5)
await wrapper.get('button').trigger('click')
await wrapper.findAll('button').find(button => button.text() === 'aiPermissions.save')!.trigger('click')
await flushPromises()
expect(mockInvoke).toHaveBeenLastCalledWith('save_ai_permissions', {
defaults: aiPreset('read'),
Expand Down
5 changes: 4 additions & 1 deletion src/__tests__/sidebarAgentRuntime.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,10 @@ jest.mock('@tauri-apps/api/core', () => ({
jest.mock('@tauri-apps/api/event', () => ({
listen: jest.fn(),
}))
jest.mock('@/common', () => jest.requireActual('@/common/agentPrompt'))
jest.mock('@/common', () => ({
...jest.requireActual('@/common/agentPrompt'),
...jest.requireActual('@/common/toolCallPresentation'),
}))
jest.mock('@/store/connectionStore', () => ({
useConnectionStore: () => ({
getConnectionById: () => undefined,
Expand Down
199 changes: 199 additions & 0 deletions src/__tests__/toolCallPresentation.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,199 @@
import {
describeSqlImpact,
highlightCodeHtml,
parseToolArguments,
presentToolCall,
toArgBlocks,
} from '@/common'

const SCREENSHOT_SQL = [
'INSERT INTO store.orders',
' (order_no, user_id, status, order_date, total_amount, discount, shipping_fee, shipping_addr, remarks)',
'VALUES',
'(\'SO-20260400007\', 1, \'paid\', \'2026-04-22\', 299.00, 0, 15.00,',
' \'{"recipient":"User One","phone":"13800000001","address":"No.1 Sample Road, Shanghai","zip":"200000"}\'::jsonb,',
' \'sample order 1\'),',
'(\'SO-20260400008\', 2, \'draft\', \'2026-04-25\', 89.90, 0, 8.00,',
' \'{"recipient":"User Two","phone":"13800000002","address":"No.2 Demo Avenue, Beijing","zip":"100000"}\'::jsonb,',
' \'sample order 2\')',
'RETURNING id, order_no, user_id, status, order_date, total_amount, placed_at;',
].join('\n')

describe('toolCallPresentation', () => {
it('parses boundary payloads from IPC objects or DB JSON strings into typed args', () => {
const payload = {
connection_id: 'pg-bastion-password',
sql: SCREENSHOT_SQL,
}

expect(parseToolArguments(payload)).toEqual(payload)
expect(parseToolArguments(JSON.stringify(payload))).toEqual(payload)
expect(parseToolArguments('not valid json')).toEqual({})
expect(parseToolArguments('[1, 2, 3]')).toEqual({})
expect(parseToolArguments(null)).toEqual({})
})

it('presents the screenshot payload as clean SQL with extracted target and operation', () => {
const result = presentToolCall('sqlkit__execute_write', {
connection_id: 'pg-bastion-password',
sql: SCREENSHOT_SQL,
})

expect(result.target).toBe('pg-bastion-password')
expect(result.operation).toEqual({ verb: 'INSERT', object: 'store.orders' })
expect(result.hints).toEqual([])
expect(result.blocks).toEqual([
{
kind: 'code',
key: 'sql',
language: 'sql',
text: SCREENSHOT_SQL,
},
])
})

it('keeps multi-line SQL verbatim without reformatting', () => {
const sql = 'UPDATE store.orders\n SET status = \'shipped\'\n WHERE id = 42;'
const result = presentToolCall('sqlkit__execute_write', {
connection_id: 'prod-pg',
sql,
})

expect(result.blocks).toEqual([
{
kind: 'code',
key: 'sql',
language: 'sql',
text: sql,
},
])
expect(result.hints).toEqual([])
})

it('decodes JSON string fields and orders scalar fields before code blocks', () => {
const result = presentToolCall('dynamo__create_item', {
connection_id: 'aws-prod',
attributes: '[{"key":"id","value":"42","type":"N"}]',
table_name: 'Orders',
})

expect(result.target).toBe('aws-prod')
expect(result.operation).toEqual({ verb: 'CREATE ITEM', object: 'Orders' })
expect(result.blocks).toEqual([
{ kind: 'field', key: 'table_name', value: 'Orders' },
{
kind: 'code',
key: 'attributes',
language: 'json',
text: JSON.stringify([
{ key: 'id', value: '42', type: 'N' },
], null, 2),
},
])
})

it('pretty-prints Elasticsearch bulk NDJSON bodies', () => {
const bulkBody = '{"index":{"_index":"orders","_id":"1"}}\n{"status":"paid"}\n'
const result = presentToolCall('es__bulk', {
connection_id: 'es-prod',
body: bulkBody,
})

expect(result.target).toBe('es-prod')
expect(result.operation).toEqual({ verb: 'BULK', object: undefined })
expect(result.blocks).toEqual([
{
kind: 'code',
key: 'body',
language: 'json',
text: `${JSON.stringify({
index: { _index: 'orders', _id: '1' },
}, null, 2)}\n${JSON.stringify({ status: 'paid' }, null, 2)}`,
},
])
})

it('returns empty blocks for empty args', () => {
expect(toArgBlocks({})).toEqual([])
})

describe('describeSqlImpact', () => {
it('flags UPDATE and DELETE without WHERE', () => {
expect(describeSqlImpact('UPDATE store.orders SET status = \'cancelled\'')).toEqual({
operation: { verb: 'UPDATE', object: 'store.orders' },
hints: ['noWhereClause'],
})

expect(describeSqlImpact('DELETE FROM "store"."orders"')).toEqual({
operation: { verb: 'DELETE', object: 'store.orders' },
hints: ['noWhereClause'],
})
})

it('ignores WHERE inside comments and string literals', () => {
const commentWhere = 'DELETE FROM store.orders -- WHERE id = 1'
expect(describeSqlImpact(commentWhere).hints).toContain('noWhereClause')

const blockCommentWhere = 'UPDATE store.orders SET status = \'x\' /* WHERE id = 1 */'
expect(describeSqlImpact(blockCommentWhere).hints).toContain('noWhereClause')

const literalWhere = 'UPDATE store.orders SET note = \'WHERE id = 1\''
expect(describeSqlImpact(literalWhere).hints).toContain('noWhereClause')

const dollarQuoted = 'UPDATE store.orders SET note = $$WHERE id = 1$$'
expect(describeSqlImpact(dollarQuoted).hints).toContain('noWhereClause')
})

it('does not false-positive on keywords inside string literals', () => {
const sql = 'INSERT INTO store.logs (msg) VALUES (\'ok; DROP TABLE users; TRUNCATE x\');'
expect(describeSqlImpact(sql)).toEqual({
operation: { verb: 'INSERT', object: 'store.logs' },
hints: [],
})
})

it('detects DROP, TRUNCATE, and multi-statement batches', () => {
expect(describeSqlImpact('DROP TABLE IF EXISTS `store`.`legacy_orders` CASCADE;')).toEqual({
operation: { verb: 'DROP', object: 'store.legacy_orders' },
hints: ['dropsObject'],
})

expect(describeSqlImpact('TRUNCATE TABLE [dbo].[temp_events]')).toEqual({
operation: { verb: 'TRUNCATE', object: 'dbo.temp_events' },
hints: ['truncates'],
})

expect(
describeSqlImpact('UPDATE store.orders SET status = \'a\' WHERE id = 1; DELETE FROM store.audit'),
).toEqual({
operation: { verb: 'UPDATE', object: 'store.orders' },
hints: ['noWhereClause', 'multipleStatements'],
})
})
})

it('derives operation and hints for non-SQL destructive tools', () => {
const deleteIndex = presentToolCall('es__delete_index', {
connection_id: 'es-prod',
index: 'orders-2025',
})
expect(deleteIndex.operation).toEqual({ verb: 'DELETE INDEX', object: 'orders-2025' })
expect(deleteIndex.hints).toEqual(['dropsObject'])

const truncateTable = presentToolCall('dynamo__truncate_table', {
connection_id: 'aws-prod',
table_name: 'Events',
})
expect(truncateTable.operation).toEqual({ verb: 'TRUNCATE TABLE', object: 'Events' })
expect(truncateTable.hints).toEqual(['truncates'])
})

it('highlights SQL and JSON safely with highlight.js', () => {
const sqlHtml = highlightCodeHtml('INSERT INTO store.orders VALUES (\'<script>alert(1)</script>\')', 'sql')
expect(sqlHtml).toContain('hljs-keyword')
expect(sqlHtml).not.toContain('<script>')

const jsonHtml = highlightCodeHtml('{"status": "paid"}', 'json')
expect(jsonHtml).toContain('hljs-attr')
})
})
128 changes: 128 additions & 0 deletions src/__tests__/toolConfirmationCard.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
/** @jest-environment jsdom */
import type { AgentToolCall } from '@/store/dataStudioStore'
import { mount } from '@vue/test-utils'
import { enUS } from '@/lang/enUS'
import ToolConfirmationCard from '@/views/data-studio/components/tool-confirmation-card.vue'

jest.mock('vue-i18n', () => ({
useI18n: () => ({
t: (key: string) => {
const value = key.split('.').reduce<unknown>(
(acc, part) => (acc && typeof acc === 'object'
? (acc as Record<string, unknown>)[part]
: undefined),
enUS,
)
return typeof value === 'string'
? value
: key
},
}),
}))

jest.mock('@/store/appStore', () => ({
ThemeType: { AUTO: 'auto', LIGHT: 'light', DARK: 'dark' },
useAppStore: () => ({ uiThemeType: 'light' }),
}))

jest.mock('@/components/ui/badge', () => ({
Badge: { template: '<span class="mock-badge"><slot /></span>' },
}))

jest.mock('@/components/ui/button', () => ({
Button: { template: '<button type="button" v-bind="$attrs"><slot /></button>' },
}))

describe('toolConfirmationCard', () => {
it('renders formatted highlighted SQL without escaped quotes for the screenshot payload', () => {
const sql = [
'INSERT INTO store.orders',
' (order_no, shipping_addr)',
'VALUES',
'(\'SO-20260400007\', \'{"recipient":"User One"}\'::jsonb);',
].join('\n')

const toolCall: AgentToolCall = {
id: 'tc-1',
toolName: 'sqlkit__execute_write',
args: { connection_id: 'pg-bastion-password', sql },
status: 'pending',
riskLevel: 'elevated',
requiresConfirmation: true,
}

const wrapper = mount(ToolConfirmationCard, {
props: { toolCall },
})
const text = wrapper.text()

expect(text).toContain('Elevated Risk')
expect(text).toContain('Modifies data — review before allowing')
expect(text).toContain('pg-bastion-password')
expect(text).toContain('INSERT')
expect(text).toContain('store.orders')
expect(text).toContain('"recipient":"User One"')
expect(text).not.toContain('\\"connection_id\\"')
expect(text).not.toContain('\\n')
expect(wrapper.find('code.hljs').html()).toContain('hljs-keyword')
})

it('shows destructive risk, impact hints, and keeps Always Allow available', async () => {
const toolCall: AgentToolCall = {
id: 'tc-2',
toolName: 'sqlkit__execute_delete',
args: {
connection_id: 'prod-db',
sql: 'DELETE FROM store.orders',
},
status: 'pending',
riskLevel: 'destructive',
requiresConfirmation: true,
}

const wrapper = mount(ToolConfirmationCard, {
props: { toolCall },
})
const text = wrapper.text()

expect(text).toContain('Destructive Operation')
expect(text).toContain('Deletes data or alters schema — may be irreversible')
expect(text).toContain('No WHERE clause detected')

const actionLabels = wrapper.findAll('button').map(btn => btn.text().trim())
expect(actionLabels).toContain('Allow Once')
expect(actionLabels).toContain('Always Allow')
expect(actionLabels).toContain('Deny')
expect(actionLabels).toContain('Always Deny')
expect(actionLabels).toContain('Cancel')

const allowAlwaysBtn = wrapper.findAll('button').find(btn => btn.text().trim() === 'Always Allow')!
await allowAlwaysBtn.trigger('click')
expect(wrapper.emitted('confirm')?.[0]).toEqual([
{ toolCallId: 'tc-2', action: 'allow_always' },
])
})

it('toggles Show all / Show less for long statements', async () => {
const longSql = Array.from({ length: 15 }, (_, index) => `SELECT ${index};`).join('\n')
const toolCall: AgentToolCall = {
id: 'tc-3',
toolName: 'sqlkit__execute_write',
args: { connection_id: 'dev', sql: longSql },
status: 'pending',
riskLevel: 'elevated',
requiresConfirmation: true,
}

const wrapper = mount(ToolConfirmationCard, {
props: { toolCall },
})
const pre = wrapper.get('pre')
expect(pre.classes()).toContain('max-h-60')

const toggleBtn = wrapper.findAll('button').find(btn => btn.text().includes('Show all'))!
await toggleBtn.trigger('click')
expect(pre.classes()).toContain('max-h-[480px]')
expect(wrapper.text()).toContain('Show less')
})
})
Loading
Loading