From 1d4dd157fef016569d9523edcc3052dfe3a8852e Mon Sep 17 00:00:00 2001
From: Cursor Agent
Date: Tue, 1 Sep 2026 13:32:51 +0000
Subject: [PATCH 1/2] feat: add Conduit-wide prompt instructions and files
Operators can create instructions (prepended to every agent prompt) and
files (written into each run workspace and inlined in the prompt) that
apply to every run, with the same ownership/sharing model as global MCPs.
Co-authored-by: Doug Rathbone
---
CLAUDE.md | 8 +
README.md | 1 +
src/main/db/index.ts | 12 +
src/main/db/queries/access.ts | 1 +
src/main/db/queries/globalPromptComponents.ts | 143 +++++++
src/main/db/schema.ts | 12 +
src/renderer/App.tsx | 5 +-
.../components/agents/AgentEditor.tsx | 12 +-
src/renderer/components/layout/Sidebar.tsx | 31 +-
.../settings/PromptComponentManager.tsx | 401 ++++++++++++++++++
.../hooks/useGlobalPromptComponents.ts | 49 +++
src/renderer/hooks/useShares.ts | 2 +
src/renderer/lib/ipc.ts | 3 +
src/renderer/lib/ws-client.ts | 12 +
src/renderer/store/ui.ts | 41 +-
src/server/index.ts | 48 +++
src/server/runner.ts | 7 +-
src/server/workers/localWorker.ts | 4 +
src/server/workspaceFiles.test.ts | 43 ++
src/server/workspaceFiles.ts | 36 ++
src/shared/promptComponents.test.ts | 87 ++++
src/shared/promptComponents.ts | 118 ++++++
src/shared/types.ts | 38 +-
src/shared/worker.ts | 6 +
24 files changed, 1107 insertions(+), 13 deletions(-)
create mode 100644 src/main/db/queries/globalPromptComponents.ts
create mode 100644 src/renderer/components/settings/PromptComponentManager.tsx
create mode 100644 src/renderer/hooks/useGlobalPromptComponents.ts
create mode 100644 src/server/workspaceFiles.test.ts
create mode 100644 src/server/workspaceFiles.ts
create mode 100644 src/shared/promptComponents.test.ts
create mode 100644 src/shared/promptComponents.ts
diff --git a/CLAUDE.md b/CLAUDE.md
index c61b846..4aabf9c 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -225,6 +225,14 @@ per-run configs post-run plus a startup sweep (6h grace). Runs record
any workspace/config they created when `startRun` throws; `fixedDir` workspaces
are local-only.
+## Conduit-wide prompt components
+
+Enabled rows in `global_prompt_components` are applied to **every** run (same
+injection model as global MCPs — sharing only controls who can see/edit them
+in the UI). Instructions are prepended to the prompt; files are written into
+the materialized workspace (`RunSpec.workspaceFiles`) and also inlined in the
+prompt. Path validation lives in `src/shared/promptComponents.ts`.
+
## Key Patterns
**Adding a new entity type** — follow the publish targets pattern:
diff --git a/README.md b/README.md
index 22e6f0f..96b1f58 100644
--- a/README.md
+++ b/README.md
@@ -9,6 +9,7 @@ A self-hosted web app for managing and running AI CLI agents (Claude Code, Amp,
- **Multi-runner** — Claude Code, Amp, and Cursor agents
- **Live terminal streaming** — xterm.js with full ANSI colour output
- **MCP management** — global and per-agent servers with OAuth support and health indicators
+- **Prompt components** — Conduit-wide instructions and files prepended to every agent run
- **Pluggable execution** — run agents in-process, on remote workers, or as ephemeral EKS Jobs / Fargate tasks
- **Scheduled runs** — cron triggers per agent
- **Publish targets** — deliver agent output to Slack, email (SMTP), or signed webhooks
diff --git a/src/main/db/index.ts b/src/main/db/index.ts
index 453c894..e44195a 100644
--- a/src/main/db/index.ts
+++ b/src/main/db/index.ts
@@ -164,6 +164,18 @@ export async function initDb(): Promise {
updated_at BIGINT NOT NULL
);
+ CREATE TABLE IF NOT EXISTS global_prompt_components (
+ id TEXT PRIMARY KEY,
+ name TEXT NOT NULL,
+ kind TEXT NOT NULL,
+ content TEXT NOT NULL DEFAULT '',
+ file_path TEXT,
+ enabled BOOLEAN NOT NULL DEFAULT TRUE,
+ owner_id TEXT,
+ created_at BIGINT NOT NULL,
+ updated_at BIGINT NOT NULL
+ );
+
CREATE TABLE IF NOT EXISTS runs (
id TEXT PRIMARY KEY,
agent_id TEXT NOT NULL REFERENCES agents(id),
diff --git a/src/main/db/queries/access.ts b/src/main/db/queries/access.ts
index dd6b368..8bac246 100644
--- a/src/main/db/queries/access.ts
+++ b/src/main/db/queries/access.ts
@@ -7,6 +7,7 @@ const TABLE_MAP: Record = {
publishTarget: 'publish_targets',
repository: 'repositories',
globalMcpServer: 'global_mcp_servers',
+ globalPromptComponent: 'global_prompt_components',
}
// Rewrites `?` placeholders to pg-style `$1..$n` in positional order.
diff --git a/src/main/db/queries/globalPromptComponents.ts b/src/main/db/queries/globalPromptComponents.ts
new file mode 100644
index 0000000..afd1a82
--- /dev/null
+++ b/src/main/db/queries/globalPromptComponents.ts
@@ -0,0 +1,143 @@
+import { eq } from 'drizzle-orm'
+import { getDb } from '../index'
+import { globalPromptComponents } from '../schema'
+import { getVisibleEntityIds } from './access'
+import { deleteSharesForEntity } from './shares'
+import type { GlobalPromptComponent, GlobalPromptComponentKind } from '../../../shared/types'
+import { validatePromptComponentInput } from '../../../shared/promptComponents'
+
+function rowToComponent(row: typeof globalPromptComponents.$inferSelect): GlobalPromptComponent {
+ return {
+ id: row.id,
+ name: row.name,
+ kind: row.kind as GlobalPromptComponentKind,
+ content: row.content,
+ filePath: row.filePath ?? undefined,
+ enabled: row.enabled,
+ ownerId: row.ownerId ?? undefined,
+ createdAt: row.createdAt,
+ updatedAt: row.updatedAt,
+ }
+}
+
+async function findFilePathConflict(filePath: string, excludeId?: string): Promise {
+ const rows = await getDb().select().from(globalPromptComponents)
+ const hit = rows.find((r) => r.kind === 'file' && r.filePath === filePath && r.id !== excludeId)
+ return hit ? hit.name : null
+}
+
+export async function listGlobalPromptComponents(
+ userId: string,
+ userGroupIds: string[]
+): Promise {
+ const visibleIds = await getVisibleEntityIds('globalPromptComponent', userId, userGroupIds)
+ if (visibleIds.length === 0) return []
+ const rows = await getDb().select().from(globalPromptComponents)
+ return rows.filter((r) => visibleIds.includes(r.id)).map(rowToComponent)
+}
+
+/** All enabled components — injected into every run regardless of sharing. */
+export async function listEnabledGlobalPromptComponents(): Promise {
+ const rows = await getDb()
+ .select()
+ .from(globalPromptComponents)
+ .where(eq(globalPromptComponents.enabled, true))
+ return rows.map(rowToComponent)
+}
+
+export async function getGlobalPromptComponent(id: string): Promise {
+ const rows = await getDb()
+ .select()
+ .from(globalPromptComponents)
+ .where(eq(globalPromptComponents.id, id))
+ return rows.length ? rowToComponent(rows[0]) : null
+}
+
+export async function createGlobalPromptComponent(
+ data: Omit,
+ ownerId: string
+): Promise {
+ const validated = validatePromptComponentInput(data)
+ if (validated.kind === 'file' && validated.filePath) {
+ const conflict = await findFilePathConflict(validated.filePath)
+ if (conflict) {
+ throw new Error(
+ `A file component already writes "${validated.filePath}" (component "${conflict}"). File paths must be unique.`
+ )
+ }
+ }
+
+ const now = Date.now()
+ const id = crypto.randomUUID()
+ await getDb().insert(globalPromptComponents).values({
+ id,
+ name: data.name.trim(),
+ kind: validated.kind,
+ content: data.content ?? '',
+ filePath: validated.kind === 'file' ? validated.filePath : null,
+ enabled: data.enabled,
+ ownerId,
+ createdAt: now,
+ updatedAt: now,
+ })
+
+ const rows = await getDb()
+ .select()
+ .from(globalPromptComponents)
+ .where(eq(globalPromptComponents.id, id))
+ if (rows.length === 0) throw new Error(`Failed to create prompt component with id ${id}`)
+ return rowToComponent(rows[0])
+}
+
+export async function updateGlobalPromptComponent(
+ id: string,
+ data: Partial>
+): Promise {
+ const existing = await getGlobalPromptComponent(id)
+ if (!existing) throw new Error(`Prompt component with id ${id} not found`)
+
+ const merged = {
+ name: data.name ?? existing.name,
+ kind: data.kind ?? existing.kind,
+ content: data.content ?? existing.content,
+ filePath: data.filePath !== undefined ? data.filePath : existing.filePath,
+ enabled: data.enabled ?? existing.enabled,
+ }
+ const validated = validatePromptComponentInput(merged)
+ if (validated.kind === 'file' && validated.filePath) {
+ const conflict = await findFilePathConflict(validated.filePath, id)
+ if (conflict) {
+ throw new Error(
+ `A file component already writes "${validated.filePath}" (component "${conflict}"). File paths must be unique.`
+ )
+ }
+ }
+
+ await getDb()
+ .update(globalPromptComponents)
+ .set({
+ name: merged.name.trim(),
+ kind: validated.kind,
+ content: merged.content,
+ filePath: validated.kind === 'file' ? validated.filePath : null,
+ enabled: merged.enabled,
+ updatedAt: Date.now(),
+ })
+ .where(eq(globalPromptComponents.id, id))
+
+ const rows = await getDb()
+ .select()
+ .from(globalPromptComponents)
+ .where(eq(globalPromptComponents.id, id))
+ if (rows.length === 0) throw new Error(`Prompt component with id ${id} not found after update`)
+ return rowToComponent(rows[0])
+}
+
+export async function deleteGlobalPromptComponent(id: string): Promise {
+ await deleteSharesForEntity('globalPromptComponent', id)
+ const deleted = await getDb()
+ .delete(globalPromptComponents)
+ .where(eq(globalPromptComponents.id, id))
+ .returning({ id: globalPromptComponents.id })
+ return deleted.length
+}
diff --git a/src/main/db/schema.ts b/src/main/db/schema.ts
index 696dcc7..a497879 100644
--- a/src/main/db/schema.ts
+++ b/src/main/db/schema.ts
@@ -160,6 +160,18 @@ export const globalMcpServers = pgTable('global_mcp_servers', {
updatedAt: bigint('updated_at', { mode: 'number' }).notNull(),
})
+export const globalPromptComponents = pgTable('global_prompt_components', {
+ id: text('id').primaryKey(),
+ name: text('name').notNull(),
+ kind: text('kind').notNull(),
+ content: text('content').notNull().default(''),
+ filePath: text('file_path'),
+ enabled: boolean('enabled').notNull().default(true),
+ ownerId: text('owner_id'),
+ createdAt: bigint('created_at', { mode: 'number' }).notNull(),
+ updatedAt: bigint('updated_at', { mode: 'number' }).notNull(),
+})
+
export const publishTargets = pgTable('publish_targets', {
id: text('id').primaryKey(),
name: text('name').notNull(),
diff --git a/src/renderer/App.tsx b/src/renderer/App.tsx
index 4066f09..06a90b5 100644
--- a/src/renderer/App.tsx
+++ b/src/renderer/App.tsx
@@ -6,6 +6,7 @@ import { GlobalMcpManager } from './components/settings/GlobalMcpManager'
import { PublishTargetManager } from './components/settings/PublishTargetManager'
import { RepositoryManager } from './components/settings/RepositoryManager'
import { SettingsManager } from './components/settings/SettingsManager'
+import { PromptComponentManager } from './components/settings/PromptComponentManager'
import { LoginPage } from './components/LoginPage'
import { useAuth } from './contexts/AuthContext'
import { useUIStore } from './store/ui'
@@ -65,7 +66,7 @@ function EmptyState() {
export default function App() {
const { isAuthenticated } = useAuth()
- const { selectedAgentId, selectAgent, showGlobalMcpManager, showPublishTargets, showRepositories, showSettings } = useUIStore()
+ const { selectedAgentId, selectAgent, showGlobalMcpManager, showPublishTargets, showRepositories, showSettings, showPromptComponents } = useUIStore()
const createAgent = useCreateAgent()
const handleNewAgent = useCallback(async () => {
@@ -133,6 +134,8 @@ export default function App() {
) : showRepositories ? (
+ ) : showPromptComponents ? (
+
) : showGlobalMcpManager ? (
) : showPublishTargets ? (
diff --git a/src/renderer/components/agents/AgentEditor.tsx b/src/renderer/components/agents/AgentEditor.tsx
index a268877..0bbd2ef 100644
--- a/src/renderer/components/agents/AgentEditor.tsx
+++ b/src/renderer/components/agents/AgentEditor.tsx
@@ -174,7 +174,7 @@ export const AgentEditor = forwardRef(funct
const { data: allRepos = [] } = useRepositories()
const { data: triggers = [] } = useTriggers(agentId)
useRepoSyncEvents()
- const { setShowPublishTargets, setShowRepositories } = useUIStore()
+ const { setShowPublishTargets, setShowRepositories, setShowPromptComponents } = useUIStore()
const [draft, setDraft] = useState>({})
const [saveState, setSaveState] = useState('idle')
@@ -438,6 +438,16 @@ export const AgentEditor = forwardRef(funct
{/* Prompt — the heart of the agent */}
+
+ Conduit-wide instructions and files are prepended automatically.{' '}
+ setShowPromptComponents(true)}
+ >
+ Manage prompt components
+
+
handleChange('prompt', v)}
diff --git a/src/renderer/components/layout/Sidebar.tsx b/src/renderer/components/layout/Sidebar.tsx
index 4a41db2..0d956fa 100644
--- a/src/renderer/components/layout/Sidebar.tsx
+++ b/src/renderer/components/layout/Sidebar.tsx
@@ -1,5 +1,5 @@
import React from 'react'
-import { Plus, Sun, Moon, Monitor, Server, Send, FolderGit2, Settings } from 'lucide-react'
+import { Plus, Sun, Moon, Monitor, Server, Send, FolderGit2, Settings, ScrollText } from 'lucide-react'
import { Button } from '@renderer/components/ui/button'
import { AgentList } from '@renderer/components/agents/AgentList'
import { UserMenu } from '@renderer/components/UserMenu'
@@ -8,17 +8,20 @@ import { useCreateAgent } from '@renderer/hooks/useAgents'
import { useGlobalMcps } from '@renderer/hooks/useGlobalMcps'
import { usePublishTargets } from '@renderer/hooks/usePublishTargets'
import { useRepositories } from '@renderer/hooks/useRepositories'
+import { useGlobalPromptComponents } from '@renderer/hooks/useGlobalPromptComponents'
import { cn } from '@renderer/lib/utils'
export function Sidebar() {
- const { theme, setTheme, selectAgent, showGlobalMcpManager, setShowGlobalMcpManager, showPublishTargets, setShowPublishTargets, showRepositories, setShowRepositories, showSettings, setShowSettings } = useUIStore()
+ const { theme, setTheme, selectAgent, showGlobalMcpManager, setShowGlobalMcpManager, showPublishTargets, setShowPublishTargets, showRepositories, setShowRepositories, showSettings, setShowSettings, showPromptComponents, setShowPromptComponents } = useUIStore()
const createAgent = useCreateAgent()
const { data: globalMcps = [] } = useGlobalMcps()
const { data: publishTargets = [] } = usePublishTargets()
const { data: repositories = [] } = useRepositories()
+ const { data: promptComponents = [] } = useGlobalPromptComponents()
const enabledGlobalCount = globalMcps.filter((m) => m.enabled).length
const enabledPublishCount = publishTargets.filter((t) => t.enabled).length
const readyRepoCount = repositories.filter((r) => r.syncStatus === 'ready').length
+ const enabledPromptCount = promptComponents.filter((c) => c.enabled).length
const handleNewAgent = async () => {
try {
@@ -111,6 +114,30 @@ export function Sidebar() {
)}
+ setShowPromptComponents(true)}
+ className={cn(
+ 'w-full flex items-center gap-2 px-2.5 py-2 rounded-md text-xs font-medium transition-colors',
+ showPromptComponents
+ ? 'bg-[var(--accent)]/15 text-[var(--accent)]'
+ : 'text-[var(--text-secondary)] hover:bg-[var(--bg-secondary)] hover:text-[var(--text-primary)]'
+ )}
+ >
+
+ Prompt components
+ {enabledPromptCount > 0 && (
+
+ {enabledPromptCount}
+
+ )}
+
setShowGlobalMcpManager(true)}
className={cn(
diff --git a/src/renderer/components/settings/PromptComponentManager.tsx b/src/renderer/components/settings/PromptComponentManager.tsx
new file mode 100644
index 0000000..26a6a92
--- /dev/null
+++ b/src/renderer/components/settings/PromptComponentManager.tsx
@@ -0,0 +1,401 @@
+import React, { useState } from 'react'
+import { Plus, Pencil, Trash2, Info, Loader2, X, Check, Share2, FileText, ScrollText } from 'lucide-react'
+import { Button } from '@renderer/components/ui/button'
+import { Input } from '@renderer/components/ui/input'
+import { ShareDialog } from '@renderer/components/ShareDialog'
+import {
+ useGlobalPromptComponents,
+ useCreateGlobalPromptComponent,
+ useUpdateGlobalPromptComponent,
+ useDeleteGlobalPromptComponent,
+} from '@renderer/hooks/useGlobalPromptComponents'
+import { useAuth } from '@renderer/contexts/AuthContext'
+import { useToast } from '@renderer/contexts/ToastContext'
+import { cn } from '@renderer/lib/utils'
+import type { GlobalPromptComponent, GlobalPromptComponentKind } from '@shared/types'
+
+interface FormState {
+ name: string
+ kind: GlobalPromptComponentKind
+ content: string
+ filePath: string
+ enabled: boolean
+}
+
+const emptyForm = (): FormState => ({
+ name: '',
+ kind: 'instruction',
+ content: '',
+ filePath: '',
+ enabled: true,
+})
+
+function formFrom(item: GlobalPromptComponent): FormState {
+ return {
+ name: item.name,
+ kind: item.kind,
+ content: item.content,
+ filePath: item.filePath ?? '',
+ enabled: item.enabled,
+ }
+}
+
+function ComponentForm({
+ initial,
+ onSave,
+ onClose,
+ saving,
+}: {
+ initial: FormState
+ onSave: (values: FormState) => Promise<{ ok: boolean; error?: string }>
+ onClose: () => void
+ saving: boolean
+}) {
+ const [form, setForm] = useState(initial)
+ const [error, setError] = useState(null)
+
+ const handleSubmit = async (e: React.FormEvent) => {
+ e.preventDefault()
+ setError(null)
+ const result = await onSave(form)
+ if (result.ok) onClose()
+ else setError(result.error ?? 'Save failed')
+ }
+
+ return (
+
+ )
+}
+
+function ComponentRow({
+ item,
+ isOwner,
+ onShare,
+}: {
+ item: GlobalPromptComponent
+ isOwner: boolean
+ onShare: () => void
+}) {
+ const toast = useToast()
+ const update = useUpdateGlobalPromptComponent()
+ const remove = useDeleteGlobalPromptComponent()
+ const [editing, setEditing] = useState(false)
+
+ if (editing) {
+ return (
+ setEditing(false)}
+ onSave={async (values) => {
+ try {
+ await update.mutateAsync({
+ id: item.id,
+ data: {
+ name: values.name,
+ kind: values.kind,
+ content: values.content,
+ filePath: values.kind === 'file' ? values.filePath : undefined,
+ enabled: values.enabled,
+ },
+ })
+ return { ok: true }
+ } catch (err) {
+ return { ok: false, error: err instanceof Error ? err.message : String(err) }
+ }
+ }}
+ />
+ )
+ }
+
+ return (
+
+
+ {item.kind === 'file' ? : }
+
+
+
+ {item.name}
+ {item.kind}
+ {!item.enabled && (
+
+ Off
+
+ )}
+
+ {item.kind === 'file' && item.filePath && (
+
{item.filePath}
+ )}
+
+ {item.content.trim() || '(empty)'}
+
+
+
+
+ update.mutate(
+ { id: item.id, data: { enabled: !item.enabled } },
+ { onError: (err) => toast.error(err instanceof Error ? err.message : String(err)) }
+ )
+ }
+ className={cn(
+ 'h-7 px-2 rounded text-[10px] font-medium',
+ item.enabled ? 'text-[var(--accent)]' : 'text-[var(--text-secondary)]'
+ )}
+ >
+ {item.enabled ? 'On' : 'Off'}
+
+
setEditing(true)}>
+
+
+ {isOwner && (
+
+
+
+ )}
+ {isOwner && (
+
{
+ if (!window.confirm(`Delete "${item.name}"? It will no longer be added to runs.`)) return
+ remove.mutate(item.id, {
+ onSuccess: () => toast.success('Prompt component deleted'),
+ onError: (err) => toast.error(err instanceof Error ? err.message : String(err)),
+ })
+ }}
+ >
+
+
+ )}
+
+
+ )
+}
+
+export function PromptComponentManager() {
+ const { data: items = [], isLoading } = useGlobalPromptComponents()
+ const { user } = useAuth()
+ const create = useCreateGlobalPromptComponent()
+ const [showAdd, setShowAdd] = useState(false)
+ const [shareId, setShareId] = useState(null)
+
+ const isLegacyGlobal = (s: { ownerId?: string | null }) => s.ownerId == null || s.ownerId === 'dev-user'
+ const mine = items.filter((s) => s.ownerId === user?.id)
+ const shared = items.filter((s) => s.ownerId !== user?.id)
+
+ return (
+
+
+
+
Prompt components
+
Added to every agent run
+
+
setShowAdd(true)} disabled={showAdd} className="gap-1.5">
+
+ Add
+
+
+
+
+
+
+
+ Instructions are prepended to every agent prompt.
+ Files are written into the run workspace (and also
+ included in the prompt). Enabled items apply to all runs; share an item so others can view or edit it.
+
+
+
+ {showAdd && (
+
setShowAdd(false)}
+ onSave={async (values) => {
+ try {
+ await create.mutateAsync({
+ name: values.name,
+ kind: values.kind,
+ content: values.content,
+ filePath: values.kind === 'file' ? values.filePath : undefined,
+ enabled: values.enabled,
+ })
+ return { ok: true }
+ } catch (err) {
+ return { ok: false, error: err instanceof Error ? err.message : String(err) }
+ }
+ }}
+ />
+ )}
+
+ {isLoading ? (
+
+
+ Loading…
+
+ ) : items.length === 0 && !showAdd ? (
+
+
No Conduit-wide instructions or files yet.
+
+ Add house style, org rules, or a CLAUDE.md / AGENTS.md that every agent should see.
+
+
setShowAdd(true)}>
+
+ Add your first component
+
+
+ ) : (
+
+ {mine.length > 0 && (
+ <>
+
+ Mine {mine.length}
+
+ {mine.map((item) => (
+
setShareId(item.id)} />
+ ))}
+ >
+ )}
+ {shared.length > 0 && (
+ <>
+
+ Shared with me {shared.length}
+
+ {shared.map((item) => (
+ setShareId(item.id)}
+ />
+ ))}
+ >
+ )}
+
+ )}
+
+
+ {shareId && (
+
setShareId(null)}
+ />
+ )}
+
+ )
+}
diff --git a/src/renderer/hooks/useGlobalPromptComponents.ts b/src/renderer/hooks/useGlobalPromptComponents.ts
new file mode 100644
index 0000000..8419198
--- /dev/null
+++ b/src/renderer/hooks/useGlobalPromptComponents.ts
@@ -0,0 +1,49 @@
+import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
+import { api } from '@renderer/lib/ipc'
+import type { GlobalPromptComponent } from '@shared/types'
+
+const KEY = ['globalPromptComponents'] as const
+
+export function useGlobalPromptComponents() {
+ return useQuery({
+ queryKey: KEY,
+ queryFn: () => api.globalPromptComponents.list(),
+ })
+}
+
+export function useCreateGlobalPromptComponent() {
+ const queryClient = useQueryClient()
+ return useMutation({
+ mutationFn: (data: Omit) =>
+ api.globalPromptComponents.create(data),
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: KEY })
+ },
+ })
+}
+
+export function useUpdateGlobalPromptComponent() {
+ const queryClient = useQueryClient()
+ return useMutation({
+ mutationFn: ({
+ id,
+ data,
+ }: {
+ id: string
+ data: Partial>
+ }) => api.globalPromptComponents.update(id, data),
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: KEY })
+ },
+ })
+}
+
+export function useDeleteGlobalPromptComponent() {
+ const queryClient = useQueryClient()
+ return useMutation({
+ mutationFn: (id: string) => api.globalPromptComponents.delete(id),
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: KEY })
+ },
+ })
+}
diff --git a/src/renderer/hooks/useShares.ts b/src/renderer/hooks/useShares.ts
index 11d14cb..79c56ce 100644
--- a/src/renderer/hooks/useShares.ts
+++ b/src/renderer/hooks/useShares.ts
@@ -14,6 +14,8 @@ function entityListKey(entityType: ShareableEntityType): string[] {
return ['repos']
case 'globalMcpServer':
return ['globalMcps']
+ case 'globalPromptComponent':
+ return ['globalPromptComponents']
}
}
diff --git a/src/renderer/lib/ipc.ts b/src/renderer/lib/ipc.ts
index 9bfa5d0..20c3b0b 100644
--- a/src/renderer/lib/ipc.ts
+++ b/src/renderer/lib/ipc.ts
@@ -29,6 +29,9 @@ export const api = {
get globalMcps() {
return getConduit().globalMcps
},
+ get globalPromptComponents() {
+ return getConduit().globalPromptComponents
+ },
get repos() {
return getConduit().repos
},
diff --git a/src/renderer/lib/ws-client.ts b/src/renderer/lib/ws-client.ts
index da0c641..3f30cdb 100644
--- a/src/renderer/lib/ws-client.ts
+++ b/src/renderer/lib/ws-client.ts
@@ -8,6 +8,7 @@ import type {
ExecutionRun,
RunLog,
GlobalMcpServer,
+ GlobalPromptComponent,
PublishTarget,
Repository,
RepositoryInput,
@@ -229,6 +230,17 @@ export function createWsConduitClient(wsUrl: string): ConduitAPI {
invoke('globalMcps:listTools', serverConfig),
},
+ globalPromptComponents: {
+ list: () => invoke('globalPromptComponents:list'),
+ create: (data: Omit) =>
+ invoke('globalPromptComponents:create', data),
+ update: (
+ id: string,
+ data: Partial>
+ ) => invoke('globalPromptComponents:update', id, data),
+ delete: (id: string) => invoke('globalPromptComponents:delete', id),
+ },
+
repos: {
list: () => invoke('repos:list'),
get: (id: string) => invoke('repos:get', id),
diff --git a/src/renderer/store/ui.ts b/src/renderer/store/ui.ts
index dc1aac0..c094f58 100644
--- a/src/renderer/store/ui.ts
+++ b/src/renderer/store/ui.ts
@@ -2,6 +2,14 @@ import { create } from 'zustand'
type Theme = 'dark' | 'light' | 'system'
+const exclusiveOff = {
+ showGlobalMcpManager: false,
+ showPublishTargets: false,
+ showRepositories: false,
+ showSettings: false,
+ showPromptComponents: false,
+}
+
interface UIState {
selectedAgentId: string | null
activeRunId: string | null
@@ -13,6 +21,7 @@ interface UIState {
showPublishTargets: boolean
showRepositories: boolean
showSettings: boolean
+ showPromptComponents: boolean
// Actions
selectAgent: (id: string | null) => void
setActiveRun: (id: string | null) => void
@@ -23,6 +32,7 @@ interface UIState {
setShowPublishTargets: (show: boolean) => void
setShowRepositories: (show: boolean) => void
setShowSettings: (show: boolean) => void
+ setShowPromptComponents: (show: boolean) => void
}
function applyTheme(theme: Theme) {
@@ -82,21 +92,31 @@ interface UrlState {
publishTargets: boolean
repositories: boolean
settings: boolean
+ promptComponents: boolean
}
function readUrlState(): UrlState {
- const empty: UrlState = { agentId: null, runId: null, globalMcps: false, publishTargets: false, repositories: false, settings: false }
+ const empty: UrlState = {
+ agentId: null,
+ runId: null,
+ globalMcps: false,
+ publishTargets: false,
+ repositories: false,
+ settings: false,
+ promptComponents: false,
+ }
if (typeof window === 'undefined') return empty
const path = window.location.pathname
const globalMcps = path === '/global-mcps'
const publishTargets = path === '/publish-targets'
const repositories = path === '/repositories'
const settings = path === '/settings'
+ const promptComponents = path === '/prompt-components'
// /agents/:agentId/runs/:runId (deep link to a run) or /agents/:agentId
const runMatch = path.match(/^\/agents\/([^/]+)\/runs\/([^/]+)$/)
if (runMatch) return { ...empty, agentId: runMatch[1], runId: runMatch[2] }
const agentMatch = path.match(/^\/agents\/([^/]+)$/)
- return { ...empty, agentId: agentMatch ? agentMatch[1] : null, globalMcps, publishTargets, repositories, settings }
+ return { ...empty, agentId: agentMatch ? agentMatch[1] : null, globalMcps, publishTargets, repositories, settings, promptComponents }
}
function pushUrl(path: string) {
@@ -117,13 +137,14 @@ export const useUIStore = create((set, get) => ({
showPublishTargets: initialUrl.publishTargets,
showRepositories: initialUrl.repositories,
showSettings: initialUrl.settings,
+ showPromptComponents: initialUrl.promptComponents,
// activeRunId/viewedRunId belong to the agent they were selected under, so
// they're cleared here — otherwise the new agent's runs tab opens on a run
// from the previous one.
selectAgent: (id) => {
pushUrl(id ? `/agents/${id}` : '/')
- set({ selectedAgentId: id, activeRunId: null, viewedRunId: null, showGlobalMcpManager: false, showPublishTargets: false, showRepositories: false, showSettings: false })
+ set({ selectedAgentId: id, activeRunId: null, viewedRunId: null, ...exclusiveOff })
},
setViewedRun: (id) => {
@@ -145,22 +166,27 @@ export const useUIStore = create((set, get) => ({
setShowGlobalMcpManager: (show) => {
pushUrl(show ? '/global-mcps' : '/')
- set({ showGlobalMcpManager: show, showPublishTargets: false, showRepositories: false, showSettings: false })
+ set({ ...exclusiveOff, showGlobalMcpManager: show })
},
setShowPublishTargets: (show) => {
pushUrl(show ? '/publish-targets' : '/')
- set({ showPublishTargets: show, showGlobalMcpManager: false, showRepositories: false, showSettings: false })
+ set({ ...exclusiveOff, showPublishTargets: show })
},
setShowRepositories: (show) => {
pushUrl(show ? '/repositories' : '/')
- set({ showRepositories: show, showGlobalMcpManager: false, showPublishTargets: false, showSettings: false })
+ set({ ...exclusiveOff, showRepositories: show })
},
setShowSettings: (show) => {
pushUrl(show ? '/settings' : '/')
- set({ showSettings: show, showGlobalMcpManager: false, showPublishTargets: false, showRepositories: false })
+ set({ ...exclusiveOff, showSettings: show })
+ },
+
+ setShowPromptComponents: (show) => {
+ pushUrl(show ? '/prompt-components' : '/')
+ set({ ...exclusiveOff, showPromptComponents: show })
},
setTheme: (theme) => {
@@ -196,6 +222,7 @@ if (typeof window !== 'undefined') {
showPublishTargets: s.publishTargets,
showRepositories: s.repositories,
showSettings: s.settings,
+ showPromptComponents: s.promptComponents,
})
})
}
diff --git a/src/server/index.ts b/src/server/index.ts
index afd1012..5a92aea 100644
--- a/src/server/index.ts
+++ b/src/server/index.ts
@@ -25,6 +25,13 @@ import {
updateGlobalMcp,
deleteGlobalMcp,
} from '../main/db/queries/globalMcps'
+import {
+ listGlobalPromptComponents,
+ getGlobalPromptComponent,
+ createGlobalPromptComponent,
+ updateGlobalPromptComponent,
+ deleteGlobalPromptComponent,
+} from '../main/db/queries/globalPromptComponents'
import {
listPublishTargets,
getPublishTarget,
@@ -87,6 +94,7 @@ import type { ReporterUser } from '../shared/observability'
import type {
AgentConfig,
GlobalMcpServer,
+ GlobalPromptComponent,
PublishTarget,
RepositoryInput,
RepoTestConnectionInput,
@@ -331,6 +339,46 @@ const handlers: Record = {
return Promise.resolve()
},
+ // Conduit-wide prompt components (instructions + files injected into every run)
+ 'globalPromptComponents:list': (_args, _ws, ctx) =>
+ Promise.resolve(listGlobalPromptComponents(ctx.userId, ctx.userGroupIds)),
+ 'globalPromptComponents:create': async ([data], _ws, ctx) => {
+ try {
+ return await createGlobalPromptComponent(
+ data as Omit,
+ ctx.userId
+ )
+ } catch (err) {
+ throw new ClientError(err instanceof Error ? err.message : String(err))
+ }
+ },
+ 'globalPromptComponents:update': async ([id, data], _ws, ctx) => {
+ if (!(await canAccessEntity('globalPromptComponent', id as string, ctx.userId, ctx.userGroupIds))) {
+ throw new ClientError('Access denied')
+ }
+ try {
+ return await updateGlobalPromptComponent(
+ id as string,
+ data as Partial>
+ )
+ } catch (err) {
+ throw new ClientError(err instanceof Error ? err.message : String(err))
+ }
+ },
+ 'globalPromptComponents:delete': async ([id], _ws, ctx) => {
+ const existing = await getGlobalPromptComponent(id as string)
+ if (!existing) throw new ClientError('Prompt component not found')
+ const isLegacyGlobal = existing.ownerId == null || existing.ownerId === DEV_USER_ID
+ if (
+ !isLegacyGlobal &&
+ !(await isEntityOwner('globalPromptComponent', id as string, ctx.userId))
+ ) {
+ throw new ClientError('Only the owner can delete this prompt component')
+ }
+ const deleted = await deleteGlobalPromptComponent(id as string)
+ if (deleted === 0) throw new ClientError('Prompt component not found')
+ },
+
'globalMcps:checkHealth': async ([serverConfig]) => {
const config = serverConfig as import('../shared/types').McpServerEntry
diff --git a/src/server/runner.ts b/src/server/runner.ts
index 2a8dac0..5b6b0f5 100644
--- a/src/server/runner.ts
+++ b/src/server/runner.ts
@@ -19,6 +19,8 @@ import { buildRunFailureReport } from './runFailure'
import { resolvePushCredential, githubTokenEnvEntry } from './githubApp'
import { publishRunResult } from './publisher'
import { buildTriggeredPrompt } from './triggers/promptBuilder'
+import { listEnabledGlobalPromptComponents } from '../main/db/queries/globalPromptComponents'
+import { applyGlobalPromptComponents, workspaceFilesFromComponents } from '../shared/promptComponents'
import { createRunEventHandlers } from './runEventSink'
import { resolveRunLogMaxBytes } from './runDeliveryLog'
import { reporter } from './observability'
@@ -578,13 +580,16 @@ export async function startRunServer(
// 6. Build the fully-resolved RunSpec and hand execution to the worker
// factory. Events stream back through the sink into the pipeline above.
+ const agentPrompt = triggerContext ? buildTriggeredPrompt(agent.prompt, triggerContext) : agent.prompt
+ const promptComponents = await listEnabledGlobalPromptComponents()
const spec: RunSpec = {
runId,
agentId,
runner: agent.runner,
model: agent.model,
effort: agent.effort,
- prompt: triggerContext ? buildTriggeredPrompt(agent.prompt, triggerContext) : agent.prompt,
+ prompt: applyGlobalPromptComponents(agentPrompt, promptComponents),
+ workspaceFiles: workspaceFilesFromComponents(promptComponents),
env: await buildRunnerEnvOverlay(agent, startedBy, pushToken),
mcpConfigContent,
strictMcpConfig: agent.runner === 'claude' ? !agent.enableRepoMcps : undefined,
diff --git a/src/server/workers/localWorker.ts b/src/server/workers/localWorker.ts
index 1649513..6edbf60 100644
--- a/src/server/workers/localWorker.ts
+++ b/src/server/workers/localWorker.ts
@@ -4,6 +4,7 @@ import type { RunSpec, WorkerEventSink, WorkerFactory, WorkerHandle } from '../.
import { createWorkspace, deleteWorkspace } from '../../main/execution/workspace'
import { writeMcpConfigContent, deleteMcpConfig } from '../../main/utils/mcpConfigFile'
import { writeClaudeConfig, deleteClaudeConfig } from '../../main/utils/claudeConfig'
+import { writeWorkspaceFiles } from '../workspaceFiles'
import { createConfiguredWorktree, removeWorktree, runGit, buildAuthUrl, configureWorktreeGit, DEFAULT_GIT_TIMEOUT_MS } from '../gitOps'
import { buildClaudeArgs, parseClaudeEvents } from '../../main/execution/adapters/claude'
import { buildAmpArgs, parseAmpEvents } from '../../main/execution/adapters/amp'
@@ -62,6 +63,9 @@ export class LocalWorkerFactory implements WorkerFactory {
}
try {
+ if (spec.workspaceFiles && spec.workspaceFiles.length > 0) {
+ writeWorkspaceFiles(workspacePath, spec.workspaceFiles)
+ }
return await this.spawn(spec, sink, workspacePath, worktreeClonePath, ephemeral)
} catch (err) {
// Roll back everything this factory created so a failed start never
diff --git a/src/server/workspaceFiles.test.ts b/src/server/workspaceFiles.test.ts
new file mode 100644
index 0000000..af7b079
--- /dev/null
+++ b/src/server/workspaceFiles.test.ts
@@ -0,0 +1,43 @@
+import * as fs from 'fs'
+import * as os from 'os'
+import * as path from 'path'
+import { afterEach, describe, expect, it } from 'vitest'
+import { writeWorkspaceFiles } from './workspaceFiles'
+
+const dirs: string[] = []
+
+afterEach(() => {
+ for (const d of dirs) fs.rmSync(d, { recursive: true, force: true })
+ dirs.length = 0
+})
+
+function tmp(): string {
+ const d = fs.mkdtempSync(path.join(os.tmpdir(), 'conduit-ws-'))
+ dirs.push(d)
+ return d
+}
+
+describe('writeWorkspaceFiles', () => {
+ it('writes nested relative files', () => {
+ const root = tmp()
+ writeWorkspaceFiles(root, [{ path: '.cursor/rules/org.mdc', content: 'always apply', name: 'Org rules' }])
+ expect(fs.readFileSync(path.join(root, '.cursor/rules/org.mdc'), 'utf8')).toBe('always apply\n')
+ })
+
+ it('prepends when the file already exists', () => {
+ const root = tmp()
+ fs.writeFileSync(path.join(root, 'CLAUDE.md'), 'from the repo\n')
+ writeWorkspaceFiles(root, [{ path: 'CLAUDE.md', content: 'from conduit', name: 'Global CLAUDE.md' }])
+ const out = fs.readFileSync(path.join(root, 'CLAUDE.md'), 'utf8')
+ expect(out).toContain('BEGIN CONDUIT-WIDE FILE: Global CLAUDE.md')
+ expect(out).toContain('from conduit')
+ expect(out.endsWith('from the repo\n')).toBe(true)
+ })
+
+ it('refuses paths that escape the workspace', () => {
+ const root = tmp()
+ expect(() =>
+ writeWorkspaceFiles(root, [{ path: '../escape.md', content: 'nope', name: 'x' }])
+ ).toThrow(/"\.\."/)
+ })
+})
diff --git a/src/server/workspaceFiles.ts b/src/server/workspaceFiles.ts
new file mode 100644
index 0000000..2bed541
--- /dev/null
+++ b/src/server/workspaceFiles.ts
@@ -0,0 +1,36 @@
+import * as fs from 'fs'
+import * as path from 'path'
+import { normalizeWorkspaceRelativePath } from '../shared/promptComponents'
+
+/**
+ * Write Conduit-wide files into a materialized workspace. Parent directories
+ * are created as needed. If the target already exists, the Conduit content is
+ * prepended so a repo's own file is not discarded.
+ */
+export function writeWorkspaceFiles(
+ workspaceRoot: string,
+ files: { path: string; content: string; name: string }[]
+): void {
+ const root = path.resolve(workspaceRoot)
+ for (const file of files) {
+ const relative = normalizeWorkspaceRelativePath(file.path)
+ const dest = path.resolve(root, relative)
+ const relativeToRoot = path.relative(root, dest)
+ if (relativeToRoot.startsWith('..') || path.isAbsolute(relativeToRoot)) {
+ throw new Error(`Refusing to write workspace file outside the workspace: ${file.path}`)
+ }
+ fs.mkdirSync(path.dirname(dest), { recursive: true })
+ const banner = [
+ `===== BEGIN CONDUIT-WIDE FILE: ${file.name} =====`,
+ file.content,
+ `===== END CONDUIT-WIDE FILE: ${file.name} =====`,
+ '',
+ ].join('\n')
+ if (fs.existsSync(dest)) {
+ const existing = fs.readFileSync(dest, 'utf8')
+ fs.writeFileSync(dest, `${banner}${existing}`, 'utf8')
+ } else {
+ fs.writeFileSync(dest, file.content.endsWith('\n') ? file.content : `${file.content}\n`, 'utf8')
+ }
+ }
+}
diff --git a/src/shared/promptComponents.test.ts b/src/shared/promptComponents.test.ts
new file mode 100644
index 0000000..a1cac8e
--- /dev/null
+++ b/src/shared/promptComponents.test.ts
@@ -0,0 +1,87 @@
+import { describe, expect, it } from 'vitest'
+import {
+ applyGlobalPromptComponents,
+ normalizeWorkspaceRelativePath,
+ validatePromptComponentInput,
+ workspaceFilesFromComponents,
+} from './promptComponents'
+
+describe('normalizeWorkspaceRelativePath', () => {
+ it('normalizes dots and backslashes', () => {
+ expect(normalizeWorkspaceRelativePath(' .cursor/rules/foo.mdc ')).toBe('.cursor/rules/foo.mdc')
+ expect(normalizeWorkspaceRelativePath('docs\\guide.md')).toBe('docs/guide.md')
+ expect(normalizeWorkspaceRelativePath('./AGENTS.md')).toBe('AGENTS.md')
+ })
+
+ it('rejects traversal and absolute paths', () => {
+ expect(() => normalizeWorkspaceRelativePath('../secret')).toThrow(/"\.\."/)
+ expect(() => normalizeWorkspaceRelativePath('/etc/passwd')).toThrow(/relative/)
+ expect(() => normalizeWorkspaceRelativePath('C:\\Windows')).toThrow(/relative/)
+ expect(() => normalizeWorkspaceRelativePath('')).toThrow(/required/)
+ })
+})
+
+describe('validatePromptComponentInput', () => {
+ it('requires a name and a file path for file kind', () => {
+ expect(() => validatePromptComponentInput({ name: ' ', kind: 'instruction' })).toThrow(/Name/)
+ expect(() => validatePromptComponentInput({ name: 'x', kind: 'other' })).toThrow(/Kind/)
+ expect(() => validatePromptComponentInput({ name: 'x', kind: 'file' })).toThrow(/required/)
+ expect(validatePromptComponentInput({ name: 'Rules', kind: 'file', filePath: 'CLAUDE.md' })).toEqual({
+ kind: 'file',
+ filePath: 'CLAUDE.md',
+ })
+ expect(validatePromptComponentInput({ name: 'Tone', kind: 'instruction' })).toEqual({
+ kind: 'instruction',
+ })
+ })
+})
+
+describe('applyGlobalPromptComponents', () => {
+ it('returns the agent prompt unchanged when nothing is enabled', () => {
+ expect(applyGlobalPromptComponents('do the thing', [])).toBe('do the thing')
+ expect(
+ applyGlobalPromptComponents('do the thing', [
+ { name: 'off', kind: 'instruction', content: 'nope', enabled: false },
+ { name: 'empty', kind: 'instruction', content: ' ', enabled: true },
+ ])
+ ).toBe('do the thing')
+ })
+
+ it('prepends instructions then inlines files, oldest first', () => {
+ const withDates = [
+ { name: 'Later', kind: 'instruction' as const, content: 'later', enabled: true, createdAt: 20 },
+ { name: 'First', kind: 'instruction' as const, content: 'first', enabled: true, createdAt: 10 },
+ {
+ name: 'House style',
+ kind: 'file' as const,
+ content: 'use tabs',
+ filePath: 'STYLE.md',
+ enabled: true,
+ createdAt: 15,
+ },
+ ]
+ const out = applyGlobalPromptComponents('agent task', withDates)
+ expect(out).toContain('# Conduit-wide instructions')
+ expect(out.indexOf('## First')).toBeLessThan(out.indexOf('## Later'))
+ expect(out).toContain('### `STYLE.md` (House style)')
+ expect(out).toContain('use tabs')
+ expect(out.endsWith('agent task')).toBe(true)
+ expect(out).toContain('\n---\n')
+ })
+})
+
+describe('workspaceFilesFromComponents', () => {
+ it('returns only enabled files, oldest first', () => {
+ expect(
+ workspaceFilesFromComponents([
+ { name: 'B', kind: 'file', content: 'b', filePath: 'b.md', enabled: true, createdAt: 2 },
+ { name: 'A', kind: 'file', content: 'a', filePath: 'a.md', enabled: true, createdAt: 1 },
+ { name: 'Off', kind: 'file', content: 'x', filePath: 'x.md', enabled: false, createdAt: 0 },
+ { name: 'Instr', kind: 'instruction', content: 'i', enabled: true, createdAt: 0 },
+ ])
+ ).toEqual([
+ { path: 'a.md', content: 'a', name: 'A' },
+ { path: 'b.md', content: 'b', name: 'B' },
+ ])
+ })
+})
diff --git a/src/shared/promptComponents.ts b/src/shared/promptComponents.ts
new file mode 100644
index 0000000..838d091
--- /dev/null
+++ b/src/shared/promptComponents.ts
@@ -0,0 +1,118 @@
+import type { GlobalPromptComponent } from './types'
+
+const MAX_RELATIVE_PATH_LENGTH = 512
+
+/**
+ * Normalize a workspace-relative file path. Rejects absolute paths, `..`
+ * traversal, empty paths, and NUL bytes so a component cannot write outside
+ * the run workspace.
+ */
+export function normalizeWorkspaceRelativePath(raw: string): string {
+ const trimmed = raw.trim().replace(/\\/g, '/')
+ if (!trimmed) {
+ throw new Error('File path is required for file components.')
+ }
+ if (trimmed.length > MAX_RELATIVE_PATH_LENGTH) {
+ throw new Error(`File path must be at most ${MAX_RELATIVE_PATH_LENGTH} characters.`)
+ }
+ if (trimmed.includes('\0')) {
+ throw new Error('File path cannot contain a NUL byte.')
+ }
+ if (trimmed.startsWith('/') || /^[a-zA-Z]:/.test(trimmed)) {
+ throw new Error('File path must be relative to the workspace (not absolute).')
+ }
+ const parts = trimmed.split('/').filter((p) => p !== '' && p !== '.')
+ if (parts.length === 0) {
+ throw new Error('File path is required for file components.')
+ }
+ if (parts.some((p) => p === '..')) {
+ throw new Error('File path cannot contain ".." segments.')
+ }
+ return parts.join('/')
+}
+
+export function validatePromptComponentInput(data: {
+ name: string
+ kind: string
+ content?: string
+ filePath?: string | null
+}): { kind: 'instruction' | 'file'; filePath?: string } {
+ const name = data.name.trim()
+ if (!name) {
+ throw new Error('Name is required.')
+ }
+ if (data.kind !== 'instruction' && data.kind !== 'file') {
+ throw new Error('Kind must be "instruction" or "file".')
+ }
+ if (data.kind === 'file') {
+ return { kind: 'file', filePath: normalizeWorkspaceRelativePath(data.filePath ?? '') }
+ }
+ return { kind: 'instruction' }
+}
+
+type PromptComponentInput = Pick<
+ GlobalPromptComponent,
+ 'name' | 'kind' | 'content' | 'filePath' | 'enabled'
+> & { createdAt?: number }
+
+export function sortPromptComponents(items: T[]): T[] {
+ return [...items].sort(
+ (a, b) => (a.createdAt ?? 0) - (b.createdAt ?? 0) || a.name.localeCompare(b.name)
+ )
+}
+
+/**
+ * Prepend enabled Conduit-wide instructions and file contents to an agent prompt.
+ * No-op when there are no enabled components with content.
+ */
+export function applyGlobalPromptComponents(
+ agentPrompt: string,
+ components: PromptComponentInput[]
+): string {
+ const enabled = sortPromptComponents(
+ components.filter((c) => c.enabled && c.content.trim().length > 0)
+ )
+ if (enabled.length === 0) return agentPrompt
+
+ const instructions = enabled.filter((c) => c.kind === 'instruction')
+ const files = enabled.filter((c) => c.kind === 'file')
+
+ const parts: string[] = ['# Conduit-wide instructions', '']
+ parts.push(
+ 'These apply to every agent run in this Conduit instance. Follow them in addition to the agent prompt below.'
+ )
+ parts.push('')
+
+ for (const item of instructions) {
+ parts.push(`## ${item.name}`, '', item.content.trim(), '')
+ }
+
+ if (files.length > 0) {
+ parts.push(
+ '## Files in the workspace',
+ '',
+ 'The following files have also been written into the run workspace (paths are relative to the working directory):',
+ ''
+ )
+ for (const item of files) {
+ const path = item.filePath ?? item.name
+ parts.push(`### \`${path}\` (${item.name})`, '', '```', item.content.trim(), '```', '')
+ }
+ }
+
+ parts.push('---', '', agentPrompt)
+ return parts.join('\n')
+}
+
+export function workspaceFilesFromComponents(
+ components: PromptComponentInput[]
+): { path: string; content: string; name: string }[] {
+ const files = sortPromptComponents(
+ components.filter((c) => c.enabled && c.kind === 'file' && c.filePath)
+ )
+ return files.map((c) => ({
+ path: c.filePath as string,
+ content: c.content,
+ name: c.name,
+ }))
+}
diff --git a/src/shared/types.ts b/src/shared/types.ts
index e8eb554..f1b7908 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -88,7 +88,12 @@ export interface Group {
updatedAt: number
}
-export type ShareableEntityType = 'agent' | 'publishTarget' | 'repository' | 'globalMcpServer'
+export type ShareableEntityType =
+ | 'agent'
+ | 'publishTarget'
+ | 'repository'
+ | 'globalMcpServer'
+ | 'globalPromptComponent'
export interface Share {
id: string
@@ -380,6 +385,26 @@ export interface GlobalMcpServer {
updatedAt: number
}
+/**
+ * Instance-wide prompt component. Enabled items are applied to every agent run:
+ * instructions are prepended to the prompt, files are written into the workspace
+ * (and their contents are also included in the prompt).
+ */
+export type GlobalPromptComponentKind = 'instruction' | 'file'
+
+export interface GlobalPromptComponent {
+ id: string
+ name: string
+ kind: GlobalPromptComponentKind
+ content: string
+ /** Workspace-relative path; required when kind is `file`. */
+ filePath?: string
+ enabled: boolean
+ ownerId?: string
+ createdAt: number
+ updatedAt: number
+}
+
// ── Repositories ────────────────────────────────────────────────────────────
export type RepoSyncStatus = 'pending' | 'cloning' | 'ready' | 'syncing' | 'error'
@@ -598,6 +623,17 @@ export interface ConduitAPI {
checkHealth: (serverConfig: McpServerEntry) => Promise
listTools: (serverConfig: McpServerEntry) => Promise
}
+ globalPromptComponents: {
+ list: () => Promise
+ create: (
+ data: Omit
+ ) => Promise
+ update: (
+ id: string,
+ data: Partial>
+ ) => Promise
+ delete: (id: string) => Promise
+ }
runners: {
/** Report which runner CLIs are installed and on the server's PATH. */
checkCli: () => Promise
diff --git a/src/shared/worker.ts b/src/shared/worker.ts
index 1cd9c4e..848ddd0 100644
--- a/src/shared/worker.ts
+++ b/src/shared/worker.ts
@@ -47,6 +47,12 @@ export interface RunSpec {
effort?: string
/** Final prompt (trigger context already folded in). Written to the CLI's stdin. */
prompt: string
+ /**
+ * Files to write into the workspace after it is materialized (Conduit-wide
+ * prompt files). Paths are workspace-relative; the worker creates parent
+ * directories. Existing files are prepended to, not overwritten.
+ */
+ workspaceFiles?: { path: string; content: string; name: string }[]
/**
* Env overlay applied on top of the worker's own process env — agent
* envVars, the runner API key, GH_TOKEN, timeout vars. Resolved server-side
From 8e279211dea8ada83ff5697610d745434802c9e4 Mon Sep 17 00:00:00 2001
From: Cursor Agent
Date: Wed, 2 Sep 2026 00:35:49 +0000
Subject: [PATCH 2/2] Move prompt components into Settings
Drop the sidebar nav item and standalone /prompt-components page. Add and
edit Conduit-wide instructions and files from Settings instead. The old
route still opens Settings so existing links keep working.
Co-authored-by: Doug Rathbone
---
CLAUDE.md | 2 +-
README.md | 2 +-
src/renderer/App.tsx | 5 +-
.../components/agents/AgentEditor.tsx | 6 +-
src/renderer/components/layout/Sidebar.tsx | 31 +---
.../settings/PromptComponentManager.tsx | 160 +++++++++---------
.../components/settings/SettingsManager.tsx | 9 +-
src/renderer/store/ui.ts | 18 +-
8 files changed, 96 insertions(+), 137 deletions(-)
diff --git a/CLAUDE.md b/CLAUDE.md
index 4aabf9c..fd398f2 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -229,7 +229,7 @@ are local-only.
Enabled rows in `global_prompt_components` are applied to **every** run (same
injection model as global MCPs — sharing only controls who can see/edit them
-in the UI). Instructions are prepended to the prompt; files are written into
+in the UI, under **Settings → Prompt components**). Instructions are prepended to the prompt; files are written into
the materialized workspace (`RunSpec.workspaceFiles`) and also inlined in the
prompt. Path validation lives in `src/shared/promptComponents.ts`.
diff --git a/README.md b/README.md
index 96b1f58..d77fb60 100644
--- a/README.md
+++ b/README.md
@@ -9,7 +9,7 @@ A self-hosted web app for managing and running AI CLI agents (Claude Code, Amp,
- **Multi-runner** — Claude Code, Amp, and Cursor agents
- **Live terminal streaming** — xterm.js with full ANSI colour output
- **MCP management** — global and per-agent servers with OAuth support and health indicators
-- **Prompt components** — Conduit-wide instructions and files prepended to every agent run
+- **Prompt components** — Conduit-wide instructions and files prepended to every agent run (Settings)
- **Pluggable execution** — run agents in-process, on remote workers, or as ephemeral EKS Jobs / Fargate tasks
- **Scheduled runs** — cron triggers per agent
- **Publish targets** — deliver agent output to Slack, email (SMTP), or signed webhooks
diff --git a/src/renderer/App.tsx b/src/renderer/App.tsx
index 06a90b5..4066f09 100644
--- a/src/renderer/App.tsx
+++ b/src/renderer/App.tsx
@@ -6,7 +6,6 @@ import { GlobalMcpManager } from './components/settings/GlobalMcpManager'
import { PublishTargetManager } from './components/settings/PublishTargetManager'
import { RepositoryManager } from './components/settings/RepositoryManager'
import { SettingsManager } from './components/settings/SettingsManager'
-import { PromptComponentManager } from './components/settings/PromptComponentManager'
import { LoginPage } from './components/LoginPage'
import { useAuth } from './contexts/AuthContext'
import { useUIStore } from './store/ui'
@@ -66,7 +65,7 @@ function EmptyState() {
export default function App() {
const { isAuthenticated } = useAuth()
- const { selectedAgentId, selectAgent, showGlobalMcpManager, showPublishTargets, showRepositories, showSettings, showPromptComponents } = useUIStore()
+ const { selectedAgentId, selectAgent, showGlobalMcpManager, showPublishTargets, showRepositories, showSettings } = useUIStore()
const createAgent = useCreateAgent()
const handleNewAgent = useCallback(async () => {
@@ -134,8 +133,6 @@ export default function App() {
) : showRepositories ? (
- ) : showPromptComponents ? (
-
) : showGlobalMcpManager ? (
) : showPublishTargets ? (
diff --git a/src/renderer/components/agents/AgentEditor.tsx b/src/renderer/components/agents/AgentEditor.tsx
index 0bbd2ef..877a89f 100644
--- a/src/renderer/components/agents/AgentEditor.tsx
+++ b/src/renderer/components/agents/AgentEditor.tsx
@@ -174,7 +174,7 @@ export const AgentEditor = forwardRef(funct
const { data: allRepos = [] } = useRepositories()
const { data: triggers = [] } = useTriggers(agentId)
useRepoSyncEvents()
- const { setShowPublishTargets, setShowRepositories, setShowPromptComponents } = useUIStore()
+ const { setShowPublishTargets, setShowRepositories, setShowSettings } = useUIStore()
const [draft, setDraft] = useState>({})
const [saveState, setSaveState] = useState('idle')
@@ -443,9 +443,9 @@ export const AgentEditor = forwardRef(funct
setShowPromptComponents(true)}
+ onClick={() => setShowSettings(true)}
>
- Manage prompt components
+ Manage in Settings
m.enabled).length
const enabledPublishCount = publishTargets.filter((t) => t.enabled).length
const readyRepoCount = repositories.filter((r) => r.syncStatus === 'ready').length
- const enabledPromptCount = promptComponents.filter((c) => c.enabled).length
const handleNewAgent = async () => {
try {
@@ -114,30 +111,6 @@ export function Sidebar() {
)}
- setShowPromptComponents(true)}
- className={cn(
- 'w-full flex items-center gap-2 px-2.5 py-2 rounded-md text-xs font-medium transition-colors',
- showPromptComponents
- ? 'bg-[var(--accent)]/15 text-[var(--accent)]'
- : 'text-[var(--text-secondary)] hover:bg-[var(--bg-secondary)] hover:text-[var(--text-primary)]'
- )}
- >
-
- Prompt components
- {enabledPromptCount > 0 && (
-
- {enabledPromptCount}
-
- )}
-
setShowGlobalMcpManager(true)}
className={cn(
diff --git a/src/renderer/components/settings/PromptComponentManager.tsx b/src/renderer/components/settings/PromptComponentManager.tsx
index 26a6a92..7fd26ef 100644
--- a/src/renderer/components/settings/PromptComponentManager.tsx
+++ b/src/renderer/components/settings/PromptComponentManager.tsx
@@ -297,96 +297,91 @@ export function PromptComponentManager() {
const shared = items.filter((s) => s.ownerId !== user?.id)
return (
-
-
-
-
Prompt components
-
Added to every agent run
-
+
+
+
Prompt components
setShowAdd(true)} disabled={showAdd} className="gap-1.5">
Add
-
-
-
-
- Instructions are prepended to every agent prompt.
- Files are written into the run workspace (and also
- included in the prompt). Enabled items apply to all runs; share an item so others can view or edit it.
-
-
+
+
+
+ Instructions are prepended to every agent prompt.{' '}
+ Files are written into the run workspace (and also
+ included in the prompt). Enabled items apply to all runs; share an item so others can view or edit it.
+
+
- {showAdd && (
-
setShowAdd(false)}
- onSave={async (values) => {
- try {
- await create.mutateAsync({
- name: values.name,
- kind: values.kind,
- content: values.content,
- filePath: values.kind === 'file' ? values.filePath : undefined,
- enabled: values.enabled,
- })
- return { ok: true }
- } catch (err) {
- return { ok: false, error: err instanceof Error ? err.message : String(err) }
- }
- }}
- />
- )}
+ {showAdd && (
+ setShowAdd(false)}
+ onSave={async (values) => {
+ try {
+ await create.mutateAsync({
+ name: values.name,
+ kind: values.kind,
+ content: values.content,
+ filePath: values.kind === 'file' ? values.filePath : undefined,
+ enabled: values.enabled,
+ })
+ return { ok: true }
+ } catch (err) {
+ return { ok: false, error: err instanceof Error ? err.message : String(err) }
+ }
+ }}
+ />
+ )}
- {isLoading ? (
-
-
- Loading…
-
- ) : items.length === 0 && !showAdd ? (
-
-
No Conduit-wide instructions or files yet.
-
- Add house style, org rules, or a CLAUDE.md / AGENTS.md that every agent should see.
-
-
setShowAdd(true)}>
-
- Add your first component
-
-
- ) : (
-
- {mine.length > 0 && (
- <>
-
- Mine {mine.length}
-
- {mine.map((item) => (
-
setShareId(item.id)} />
- ))}
- >
- )}
- {shared.length > 0 && (
- <>
-
- Shared with me {shared.length}
-
- {shared.map((item) => (
- setShareId(item.id)}
- />
- ))}
- >
- )}
-
- )}
-
+ {isLoading ? (
+
+
+ Loading…
+
+ ) : items.length === 0 && !showAdd ? (
+
+
No Conduit-wide instructions or files yet.
+
+ Add house style, org rules, or a CLAUDE.md / AGENTS.md that every agent should see.
+
+
setShowAdd(true)}>
+
+ Add your first component
+
+
+ ) : (
+
+ {mine.length > 0 && (
+ <>
+
+ Mine {mine.length}
+
+ {mine.map((item) => (
+
setShareId(item.id)} />
+ ))}
+ >
+ )}
+ {shared.length > 0 && (
+ <>
+
+ Shared with me {shared.length}
+
+ {shared.map((item) => (
+ setShareId(item.id)}
+ />
+ ))}
+ >
+ )}
+
+ )}
{shareId && (
)
}
+
diff --git a/src/renderer/components/settings/SettingsManager.tsx b/src/renderer/components/settings/SettingsManager.tsx
index 1d70621..1a3360e 100644
--- a/src/renderer/components/settings/SettingsManager.tsx
+++ b/src/renderer/components/settings/SettingsManager.tsx
@@ -8,6 +8,7 @@ import { useDataDirSweep } from '@renderer/hooks/useDataDirSweep'
import { useStorageUsage } from '@renderer/hooks/useStorageUsage'
import { formatBytes } from '@renderer/lib/utils'
import type { RunnerType, SweepResult } from '@shared/types'
+import { PromptComponentManager } from './PromptComponentManager'
interface RunnerMeta {
runner: RunnerType
@@ -278,13 +279,13 @@ export function SettingsManager() {
Settings
- Agent authentication and storage maintenance
+ Agent authentication, Conduit-wide prompts, and storage
{/* Body */}
-
+
@@ -305,6 +306,10 @@ export function SettingsManager() {
/>
))}
+
+
Storage maintenance
diff --git a/src/renderer/store/ui.ts b/src/renderer/store/ui.ts
index c094f58..368f332 100644
--- a/src/renderer/store/ui.ts
+++ b/src/renderer/store/ui.ts
@@ -7,7 +7,6 @@ const exclusiveOff = {
showPublishTargets: false,
showRepositories: false,
showSettings: false,
- showPromptComponents: false,
}
interface UIState {
@@ -21,7 +20,6 @@ interface UIState {
showPublishTargets: boolean
showRepositories: boolean
showSettings: boolean
- showPromptComponents: boolean
// Actions
selectAgent: (id: string | null) => void
setActiveRun: (id: string | null) => void
@@ -32,7 +30,6 @@ interface UIState {
setShowPublishTargets: (show: boolean) => void
setShowRepositories: (show: boolean) => void
setShowSettings: (show: boolean) => void
- setShowPromptComponents: (show: boolean) => void
}
function applyTheme(theme: Theme) {
@@ -92,7 +89,6 @@ interface UrlState {
publishTargets: boolean
repositories: boolean
settings: boolean
- promptComponents: boolean
}
function readUrlState(): UrlState {
@@ -103,20 +99,19 @@ function readUrlState(): UrlState {
publishTargets: false,
repositories: false,
settings: false,
- promptComponents: false,
}
if (typeof window === 'undefined') return empty
const path = window.location.pathname
const globalMcps = path === '/global-mcps'
const publishTargets = path === '/publish-targets'
const repositories = path === '/repositories'
- const settings = path === '/settings'
- const promptComponents = path === '/prompt-components'
+ // Prompt components used to have their own route; they now live in Settings.
+ const settings = path === '/settings' || path === '/prompt-components'
// /agents/:agentId/runs/:runId (deep link to a run) or /agents/:agentId
const runMatch = path.match(/^\/agents\/([^/]+)\/runs\/([^/]+)$/)
if (runMatch) return { ...empty, agentId: runMatch[1], runId: runMatch[2] }
const agentMatch = path.match(/^\/agents\/([^/]+)$/)
- return { ...empty, agentId: agentMatch ? agentMatch[1] : null, globalMcps, publishTargets, repositories, settings, promptComponents }
+ return { ...empty, agentId: agentMatch ? agentMatch[1] : null, globalMcps, publishTargets, repositories, settings }
}
function pushUrl(path: string) {
@@ -137,7 +132,6 @@ export const useUIStore = create
((set, get) => ({
showPublishTargets: initialUrl.publishTargets,
showRepositories: initialUrl.repositories,
showSettings: initialUrl.settings,
- showPromptComponents: initialUrl.promptComponents,
// activeRunId/viewedRunId belong to the agent they were selected under, so
// they're cleared here — otherwise the new agent's runs tab opens on a run
@@ -184,11 +178,6 @@ export const useUIStore = create((set, get) => ({
set({ ...exclusiveOff, showSettings: show })
},
- setShowPromptComponents: (show) => {
- pushUrl(show ? '/prompt-components' : '/')
- set({ ...exclusiveOff, showPromptComponents: show })
- },
-
setTheme: (theme) => {
try {
localStorage.setItem('conduit-theme', theme)
@@ -222,7 +211,6 @@ if (typeof window !== 'undefined') {
showPublishTargets: s.publishTargets,
showRepositories: s.repositories,
showSettings: s.settings,
- showPromptComponents: s.promptComponents,
})
})
}