Skip to content

Commit 130f4ac

Browse files
authored
feat: add layered agent system prompts (#187)
* feat: add layered agent system prompts * fix: gate custom prompts to ultimate subscribers * copy: simplify agent prompt upgrade message * copy: simplify connection prompt upgrade message * fix: load AI settings before allowing prompt edits
1 parent 084b61f commit 130f4ac

16 files changed

Lines changed: 661 additions & 22 deletions

File tree

‎src-tauri/src/mcp_bridge.rs‎

Lines changed: 38 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -207,7 +207,7 @@ async fn handle_tools(State(state): State<Arc<BridgeState>>) -> Response {
207207
Json(result).into_response()
208208
}
209209

210-
/// List saved connections from the store — id/name/db_type only, no credentials.
210+
/// List safe connection metadata and agent context from the store, without credentials.
211211
fn list_connections() -> Value {
212212
let handle = match crate::APP_HANDLE.get() {
213213
Some(h) => h,
@@ -221,25 +221,25 @@ fn list_connections() -> Value {
221221
let connections = store.get("connections").unwrap_or(json!([]));
222222
let safe_list: Vec<Value> = connections
223223
.as_array()
224-
.map(|arr| {
225-
arr.iter()
226-
.map(|c| {
227-
json!({
228-
"id": c.get("id"),
229-
"name": c.get("name"),
230-
"type": c.get("db_type"),
231-
// First discovery tool an agent should call for this
232-
// connection type to learn its objects before querying.
233-
"discover": json!(discover_tool_for(&db_type_str(c))),
234-
})
235-
})
236-
.collect()
237-
})
224+
.map(|arr| arr.iter().map(safe_connection_summary).collect())
238225
.unwrap_or_default();
239226

240227
json!(safe_list)
241228
}
242229

230+
fn safe_connection_summary(connection: &Value) -> Value {
231+
let mut summary = json!({
232+
"id": connection.get("id"),
233+
"name": connection.get("name"),
234+
"type": connection.get("db_type"),
235+
"discover": discover_tool_for(&db_type_str(connection)),
236+
});
237+
if let Some(prompt) = connection.get("prompt").filter(|value| !value.is_null()) {
238+
summary["prompt"] = prompt.clone();
239+
}
240+
summary
241+
}
242+
243243
/// The SQL discovery entry point for a connection type: list tables first,
244244
/// then drill into a table with describe_table or the full schema.
245245
fn discover_tool_for(_db_type: &str) -> &'static str {
@@ -812,6 +812,29 @@ mod tests {
812812
assert_eq!(list_connections(), json!([]));
813813
}
814814

815+
#[test]
816+
fn test_safe_connection_summary_includes_prompt_but_excludes_credentials() {
817+
let summary = safe_connection_summary(&json!({
818+
"id": "connection-1",
819+
"name": "analytics",
820+
"db_type": "PostgreSQL",
821+
"prompt": "Revenue is stored in cents.",
822+
"password": "secret",
823+
"apiKey": "secret-key"
824+
}));
825+
826+
assert_eq!(
827+
summary,
828+
json!({
829+
"id": "connection-1",
830+
"name": "analytics",
831+
"type": "PostgreSQL",
832+
"discover": "sqlkit__list_tables",
833+
"prompt": "Revenue is stored in cents."
834+
})
835+
);
836+
}
837+
815838
#[test]
816839
fn test_invoke_response_ok_serialization() {
817840
let resp = InvokeResponse::ok(json!({"rows": 1}));

‎src-tauri/src/state.rs‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,9 @@ pub struct ServerConfig {
9898
/// because a read-write instance holds an exclusive file lock.
9999
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
100100
pub read_only: bool,
101+
/// Optional context for AI agents using this connection.
102+
#[serde(default, skip_serializing_if = "Option::is_none")]
103+
pub prompt: Option<String>,
101104
}
102105

103106
fn default_timeout_10() -> u64 {
@@ -138,6 +141,7 @@ impl ServerConfig {
138141
query_timeout_secs: default_timeout_30(),
139142
transport_layers: None,
140143
read_only: false,
144+
prompt: None,
141145
}
142146
}
143147

@@ -395,6 +399,43 @@ mod tests {
395399
config
396400
}
397401

402+
#[test]
403+
fn server_config_prompt_survives_store_serialization_round_trip() {
404+
let mut config = ServerConfig::new(
405+
"analytics".into(),
406+
"PostgreSQL".into(),
407+
"localhost".into(),
408+
5432,
409+
"user".into(),
410+
);
411+
config.prompt = Some("Revenue values are stored in cents.".into());
412+
413+
let stored = serde_json::to_value(&config).unwrap();
414+
let reopened: ServerConfig = serde_json::from_value(stored).unwrap();
415+
416+
assert_eq!(
417+
reopened.prompt.as_deref(),
418+
Some("Revenue values are stored in cents.")
419+
);
420+
}
421+
422+
#[test]
423+
fn server_config_without_prompt_remains_compatible() {
424+
let config = ServerConfig::new(
425+
"analytics".into(),
426+
"PostgreSQL".into(),
427+
"localhost".into(),
428+
5432,
429+
"user".into(),
430+
);
431+
432+
let mut stored = serde_json::to_value(config).unwrap();
433+
stored.as_object_mut().unwrap().remove("prompt");
434+
let reopened: ServerConfig = serde_json::from_value(stored).unwrap();
435+
436+
assert!(reopened.prompt.is_none());
437+
}
438+
398439
#[test]
399440
fn duckdb_maps_the_file_path_into_the_database_field() {
400441
let config = file_config("duckdb", "/tmp/analytics.duckdb", false)
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
import { createPinia, setActivePinia } from 'pinia'
2+
import { storeApi } from '@/datasources/storeApi'
3+
import { useAppStore } from '@/store/appStore'
4+
5+
jest.mock('@/datasources/storeApi', () => ({
6+
storeApi: {
7+
getSecret: jest.fn(),
8+
setSecret: jest.fn(),
9+
},
10+
}))
11+
12+
describe('global system prompt persistence', () => {
13+
beforeEach(() => {
14+
setActivePinia(createPinia())
15+
jest.clearAllMocks()
16+
})
17+
18+
it('round-trips the saved prompt when AI settings are loaded again', async () => {
19+
let persisted: unknown
20+
jest.mocked(storeApi.getSecret).mockImplementation(async () => persisted as never)
21+
jest.mocked(storeApi.setSecret).mockImplementation(async (_key, value) => {
22+
persisted = value
23+
})
24+
25+
const appStore = useAppStore()
26+
await appStore.saveChatSettings({ systemPrompt: 'Our fiscal year starts in July.' })
27+
setActivePinia(createPinia())
28+
const reopenedAppStore = useAppStore()
29+
await reopenedAppStore.fetchLlmSettings()
30+
31+
expect(reopenedAppStore.llmSettings.chat.systemPrompt).toBe('Our fiscal year starts in July.')
32+
})
33+
})

‎src/common/agentPrompt.test.ts‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import { assembleSystemPrompt } from './agentPrompt'
2+
3+
describe('assembleSystemPrompt', () => {
4+
it('joins layers in developer, global, connections, sidebar order', () => {
5+
expect(assembleSystemPrompt({
6+
base: 'base',
7+
userGlobal: 'global',
8+
connectionPrompts: [{ alias: 'warehouse', prompt: 'warehouse context' }],
9+
sidebarContext: 'editor context',
10+
})).toBe('base\n\nglobal\n\nwarehouse context\n\neditor context')
11+
})
12+
13+
it('labels each prompt when multiple connection contexts are attached', () => {
14+
expect(assembleSystemPrompt({
15+
base: 'base',
16+
connectionPrompts: [
17+
{ alias: 'warehouse', prompt: 'revenue data' },
18+
{ alias: 'crm', prompt: 'customer data' },
19+
],
20+
})).toBe('base\n\n## Connection Context: warehouse\n\nrevenue data\n\n## Connection Context: crm\n\ncustomer data')
21+
})
22+
23+
it('skips blank optional layers', () => {
24+
expect(assembleSystemPrompt({
25+
base: 'base',
26+
userGlobal: ' ',
27+
connectionPrompts: [{ alias: 'warehouse', prompt: '\n' }],
28+
sidebarContext: '',
29+
})).toBe('base')
30+
})
31+
32+
it('returns an empty prompt when every layer is blank', () => {
33+
expect(assembleSystemPrompt({ base: ' ', userGlobal: '\n', sidebarContext: '' })).toBe('')
34+
})
35+
})

‎src/common/agentPrompt.ts‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
export type ConnectionPrompt = {
2+
alias: string
3+
prompt: string
4+
}
5+
6+
export type SystemPromptLayers = {
7+
base: string
8+
userGlobal?: string
9+
connectionPrompts?: ConnectionPrompt[]
10+
sidebarContext?: string
11+
}
12+
13+
const isNonEmpty = (value: string | undefined | null): value is string => Boolean(value?.trim())
14+
15+
export const assembleSystemPrompt = (layers: SystemPromptLayers): string => {
16+
const parts = isNonEmpty(layers.base) ? [layers.base.trim()] : []
17+
if (isNonEmpty(layers.userGlobal))
18+
parts.push(layers.userGlobal.trim())
19+
20+
const prompts = (layers.connectionPrompts ?? []).filter(({ prompt }) => isNonEmpty(prompt))
21+
prompts.forEach(({ alias, prompt }) => {
22+
parts.push(prompts.length > 1 ? `## Connection Context: ${alias}\n\n${prompt.trim()}` : prompt.trim())
23+
})
24+
25+
if (isNonEmpty(layers.sidebarContext))
26+
parts.push(layers.sidebarContext.trim())
27+
28+
return parts.join('\n\n')
29+
}

‎src/common/index.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
*/
44
export const pureObject = <T>(obj: T): T => JSON.parse(JSON.stringify(obj)) as T
55

6+
export * from './agentPrompt'
67
export * from './entitlement'
78
export * from './sessionExpiry'
89
export * from './sessionPhase'
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
<script setup lang="ts">
2+
import { ref } from 'vue'
3+
import { useI18n } from 'vue-i18n'
4+
import { Button } from '@/components/ui/button'
5+
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
6+
7+
const emit = defineEmits<{ save: [value: string] }>()
8+
const { t } = useI18n()
9+
const open = ref(false)
10+
const draft = ref('')
11+
12+
const show = (value?: string) => {
13+
draft.value = value ?? ''
14+
open.value = true
15+
}
16+
17+
const save = () => {
18+
emit('save', draft.value)
19+
open.value = false
20+
}
21+
22+
defineExpose({ show })
23+
</script>
24+
25+
<template>
26+
<Dialog v-model:open="open">
27+
<DialogContent class="sm:max-w-[560px]">
28+
<DialogHeader>
29+
<DialogTitle>{{ t('connection.prompt.title') }}</DialogTitle>
30+
<DialogDescription>{{ t('connection.prompt.description') }}</DialogDescription>
31+
</DialogHeader>
32+
<textarea
33+
v-model="draft"
34+
autocomplete="off"
35+
class="text-sm px-3 py-2 border border-input rounded-md bg-background max-h-80 min-h-48 w-full resize-y"
36+
:placeholder="t('connection.prompt.placeholder')"
37+
/>
38+
<DialogFooter class="sm:justify-between">
39+
<Button type="button" variant="outline" :disabled="!draft.trim()" @click="draft = ''">
40+
{{ t('connection.prompt.clear') }}
41+
</Button>
42+
<div class="flex gap-2">
43+
<Button type="button" variant="outline" @click="open = false">
44+
{{ t('connection.prompt.cancel') }}
45+
</Button>
46+
<Button type="button" @click="save">
47+
{{ t('connection.prompt.confirm') }}
48+
</Button>
49+
</div>
50+
</DialogFooter>
51+
</DialogContent>
52+
</Dialog>
53+
</template>

‎src/components/connections/ServerFormDialog.vue‎

Lines changed: 42 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import { openUrl } from '@tauri-apps/plugin-opener'
77
import { computed, ref, watch } from 'vue'
88
import { useI18n } from 'vue-i18n'
99
import { shouldStripSshTunnel, UPGRADE_URL } from '@/common'
10+
import { Badge } from '@/components/ui/badge'
1011
import { Button } from '@/components/ui/button'
1112
import { SearchableSelect } from '@/components/ui/combobox'
1213
import { Dialog, DialogContent, DialogDescription, DialogTitle } from '@/components/ui/dialog'
@@ -21,6 +22,7 @@ import {
2122
SelectValue,
2223
} from '@/components/ui/select'
2324
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
25+
import { ProBadge } from '@/components/upgrade'
2426
import { useDatabaseIcon } from '@/composables/useDatabaseIcon'
2527
import { useDownloadEvents } from '@/composables/useDownloadEvents'
2628
import { toast } from '@/composables/useNotifications'
@@ -30,6 +32,7 @@ import { buildOracleOptions, buildTransportLayers, databasePlaceholderFor, Datab
3032
import { DEFAULT_SSL_MODE, sslModeToBackend, validateSslConfig } from '@/types/connection'
3133
import { buildMemoryDatabaseHost, createMemoryDatabaseLabel, isMemoryDatabaseHost, isSameDatabaseFile, memoryDatabaseLabel } from '@/utils/databaseFiles'
3234
import { classifyDuckDbFailure } from '@/utils/duckdbErrors'
35+
import ConnectionPromptDialog from './ConnectionPromptDialog.vue'
3336
import DatabaseFileField from './DatabaseFileField.vue'
3437
import SshTunnelConfigPanel from './SshTunnelConfigPanel.vue'
3538
import SslConfigSection from './ssl/SslConfigSection.vue'
@@ -211,6 +214,14 @@ const duckdbFileStatus = ref<DatabaseFileAssessment | null>(null)
211214
212215
const connectionStore = useConnectionStore()
213216
const entitlementStore = useEntitlementStore()
217+
const isPromptGated = computed(() => !entitlementStore.isLocalUltimate)
218+
const promptDialogRef = ref<InstanceType<typeof ConnectionPromptDialog> | null>(null)
219+
const promptValue = computed(() => formData.value.prompt ?? '')
220+
221+
const editPrompt = () => promptDialogRef.value?.show(promptValue.value)
222+
const savePrompt = (value: string) => {
223+
formData.value.prompt = value.trim() || undefined
224+
}
214225
const { platform } = usePlatform()
215226
216227
watch(() => props.open, (open) => {
@@ -906,7 +917,7 @@ function handleSave() {
906917

907918
<form class="space-y-4" @submit.prevent="handleSave">
908919
<Tabs :model-value="formSectionTab" @update:model-value="formSectionTab = $event as 'basic' | 'advanced'">
909-
<TabsList v-if="!isFileBased" class="p-0.5 h-7 w-fit">
920+
<TabsList class="p-0.5 h-7 w-fit">
910921
<TabsTrigger value="basic" class="text-xs px-3 py-0 gap-1.5 h-6">
911922
<span class="i-carbon-plug h-3.5 w-3.5" />
912923
{{ t('components.serverForm.basicTab') }}
@@ -1482,9 +1493,39 @@ function handleSave() {
14821493
:remote-port="formData.port"
14831494
@update:model-value="formData.sshTunnel = $event"
14841495
/>
1496+
1497+
<button
1498+
v-if="isPromptGated"
1499+
type="button"
1500+
class="px-3 py-2.5 text-left border rounded-lg border-dashed flex gap-2.5 w-full cursor-pointer transition-colors items-center hover:bg-accent/50"
1501+
@click="openUpgrade"
1502+
>
1503+
<ProBadge size="xs" />
1504+
<span class="text-sm text-muted-foreground">{{ t('connection.prompt.ultimateOnly') }}</span>
1505+
<span class="text-xs text-primary font-medium ml-auto px-2 py-1 rounded-md bg-primary/10 shrink-0">{{ t('plan.upgrade.cta') }}</span>
1506+
</button>
1507+
<div v-else class="p-3 border rounded-lg space-y-2">
1508+
<div class="flex gap-2 items-center">
1509+
<Label>{{ t('connection.prompt.label') }}</Label>
1510+
<Badge v-if="promptValue" variant="secondary">
1511+
{{ t('connection.prompt.configured') }}
1512+
</Badge>
1513+
<Button type="button" variant="outline" size="sm" class="ml-auto" @click="editPrompt">
1514+
{{ promptValue ? t('connection.prompt.edit') : t('connection.prompt.add') }}
1515+
</Button>
1516+
</div>
1517+
<p class="text-xs text-muted-foreground">
1518+
{{ t('connection.prompt.help') }}
1519+
</p>
1520+
<p v-if="promptValue" class="text-xs text-muted-foreground whitespace-pre-wrap line-clamp-2">
1521+
{{ promptValue }}
1522+
</p>
1523+
</div>
14851524
</TabsContent>
14861525
</Tabs>
14871526

1527+
<ConnectionPromptDialog ref="promptDialogRef" @save="savePrompt" />
1528+
14881529
<!-- Test Connection Status -->
14891530
<div
14901531
v-if="testStatus !== 'idle' || (isJdbcDb && setupSteps.some(s => s.status !== 'pending'))" class="p-3 rounded-md" :class="{

0 commit comments

Comments
 (0)