This commit is contained in:
Timothy Jaeryang Baek
2026-01-24 04:13:19 +04:00
parent b7e9992d78
commit 32810b4152
4 changed files with 270 additions and 85 deletions

View File

@@ -307,12 +307,14 @@ class PromptsTable:
# Check if content changed to decide on history creation
content_changed = (
prompt.name != form_data.name
or prompt.command != form_data.command
or prompt.content != form_data.content
or prompt.access_control != form_data.access_control
)
# Update prompt fields
prompt.name = form_data.name
prompt.command = form_data.command
prompt.content = form_data.content
prompt.data = form_data.data or prompt.data
prompt.meta = form_data.meta or prompt.meta
@@ -350,6 +352,29 @@ class PromptsTable:
except Exception:
return None
def update_prompt_metadata(
self,
prompt_id: str,
name: str,
command: str,
db: Optional[Session] = None,
) -> Optional[PromptModel]:
"""Update only name and command (no history created)."""
try:
with get_db_context(db) as db:
prompt = db.query(Prompt).filter_by(id=prompt_id).first()
if not prompt:
return None
prompt.name = name
prompt.command = command
prompt.updated_at = int(time.time())
db.commit()
return PromptModel.model_validate(prompt)
except Exception:
return None
def update_prompt_version(
self,
prompt_id: str,

View File

@@ -25,6 +25,12 @@ from pydantic import BaseModel
class PromptVersionUpdateForm(BaseModel):
version_id: str
class PromptMetadataForm(BaseModel):
name: str
command: str
router = APIRouter()
@@ -209,6 +215,15 @@ async def update_prompt_by_id(
detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
)
# Check for command collision if command is being changed
if form_data.command != prompt.command:
existing_prompt = Prompts.get_prompt_by_command(form_data.command, db=db)
if existing_prompt and existing_prompt.id != prompt.id:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f"Command '/{form_data.command}' is already in use by another prompt",
)
# Use the ID from the found prompt
updated_prompt = Prompts.update_prompt_by_id(
prompt.id, form_data, user.id, db=db
@@ -222,7 +237,59 @@ async def update_prompt_by_id(
)
@router.post("/id/{prompt_id}/set/version", response_model=Optional[PromptModel])
############################
# UpdatePromptMetadata
############################
@router.post("/id/{prompt_id}/update/meta", response_model=Optional[PromptModel])
async def update_prompt_metadata(
prompt_id: str,
form_data: PromptMetadataForm,
user=Depends(get_verified_user),
db: Session = Depends(get_session),
):
"""Update prompt name and command only (no history created)."""
prompt = Prompts.get_prompt_by_id(prompt_id, db=db)
if not prompt:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=ERROR_MESSAGES.NOT_FOUND,
)
if (
prompt.user_id != user.id
and not has_access(user.id, "write", prompt.access_control, db=db)
and user.role != "admin"
):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
)
# Check for command collision if command is being changed
if form_data.command != prompt.command:
existing_prompt = Prompts.get_prompt_by_command(form_data.command, db=db)
if existing_prompt and existing_prompt.id != prompt.id:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f"Command '/{form_data.command}' is already in use",
)
updated_prompt = Prompts.update_prompt_metadata(
prompt.id, form_data.name, form_data.command, db=db
)
if updated_prompt:
return updated_prompt
else:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=ERROR_MESSAGES.DEFAULT(),
)
@router.post("/id/{prompt_id}/update/version", response_model=Optional[PromptModel])
async def set_prompt_version(
prompt_id: str,
form_data: PromptVersionUpdateForm,

View File

@@ -238,6 +238,40 @@ export const updatePromptById = async (token: string, prompt: PromptItem) => {
return res;
};
export const updatePromptMetadata = async (
token: string,
promptId: string,
name: string,
command: string
) => {
let error = null;
const res = await fetch(`${WEBUI_API_BASE_URL}/prompts/id/${promptId}/update/meta`, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
authorization: `Bearer ${token}`
},
body: JSON.stringify({ name, command })
})
.then(async (res) => {
if (!res.ok) throw await res.json();
return res.json();
})
.catch((err) => {
error = err.detail;
console.error(err);
return null;
});
if (error) {
throw error;
}
return res;
};
export const setProductionPromptVersion = async (
token: string,
promptId: string,
@@ -245,7 +279,7 @@ export const setProductionPromptVersion = async (
) => {
let error = null;
const res = await fetch(`${WEBUI_API_BASE_URL}/prompts/id/${promptId}/set/version`, {
const res = await fetch(`${WEBUI_API_BASE_URL}/prompts/id/${promptId}/update/version`, {
method: 'POST',
headers: {
Accept: 'application/json',

View File

@@ -16,7 +16,8 @@
import {
getPromptHistory,
setProductionPromptVersion,
deletePromptHistoryVersion
deletePromptHistoryVersion,
updatePromptMetadata
} from '$lib/apis/prompts';
import dayjs from 'dayjs';
import localizedFormat from 'dayjs/plugin/localizedFormat';
@@ -53,6 +54,11 @@
let historyHasMore = true;
let contentCopied = false;
// For debounced auto-save of name/command
let originalName = '';
let originalCommand = '';
let debounceTimer: ReturnType<typeof setTimeout> | null = null;
$: if (!edit && !hasManualEdit) {
command = name !== '' ? slugify(name) : '';
}
@@ -191,6 +197,41 @@
LOCALIZED_DATE: dayjs(dateVal).format('L')
});
};
const debouncedSaveMetadata = () => {
if (disabled || !edit) return;
if (debounceTimer) {
clearTimeout(debounceTimer);
}
debounceTimer = setTimeout(async () => {
// Skip if nothing changed
if (name === originalName && command === originalCommand) return;
if (!validateCommandString(command)) {
toast.error(
$i18n.t('Only alphanumeric characters and hyphens are allowed in the command string.')
);
command = originalCommand;
return;
}
try {
await updatePromptMetadata(localStorage.token, prompt?.id, name, command);
// Update originals on success
originalName = name;
originalCommand = command;
toast.success($i18n.t('Saved'));
} catch (error) {
toast.error(`${error}`);
// Revert on error (collision)
name = originalName;
command = originalCommand;
}
}, 500);
};
onMount(async () => {
if (prompt) {
name = prompt.name || '';
@@ -199,6 +240,10 @@
content = prompt.content;
accessControl = prompt?.access_control === undefined ? {} : prompt?.access_control;
// Store originals for revert on collision
originalName = name;
originalCommand = command;
if (edit) {
await loadHistory();
// Auto-select production version
@@ -295,87 +340,101 @@
{#if edit}
<!-- Edit mode: Read-only view with history -->
<div class="w-full max-h-full">
<!-- Main Content -->
<div class="flex-1 min-w-0">
<!-- Header -->
<div class="flex items-start justify-between gap-4 mb-2">
<div class="min-w-0">
<h1 class="text-2xl font-medium truncate">{name}</h1>
<div class="text-sm text-gray-500 mt-0.5">/{command}</div>
<div class="flex flex-col w-full h-full max-h-[100dvh]">
<!-- Header -->
<div class="flex items-start justify-between gap-4 mb-2 shrink-0">
<div class="min-w-0 flex-1">
<input
class="text-2xl font-medium w-full bg-transparent outline-hidden"
placeholder={$i18n.t('Prompt Name')}
bind:value={name}
on:input={debouncedSaveMetadata}
{disabled}
/>
<div class="flex items-center gap-0.5 text-sm text-gray-500 mt-0.5">
<span>/</span>
<input
class="bg-transparent outline-hidden"
placeholder={$i18n.t('command')}
bind:value={command}
on:input={debouncedSaveMetadata}
{disabled}
/>
</div>
<div class="flex items-center gap-2 shrink-0">
{#if !disabled}
<button
class="bg-gray-50 hover:bg-gray-100 text-black dark:bg-gray-850 dark:hover:bg-gray-800 dark:text-white transition px-2.5 py-1.5 rounded-full flex gap-1.5 items-center text-sm border border-gray-100 dark:border-gray-800"
on:click={() => (showAccessControlModal = true)}
>
<LockClosed strokeWidth="2.5" className="size-3.5" />
{$i18n.t('Access')}
</button>
<button
class="px-4 py-1.5 text-sm font-medium bg-black text-white dark:bg-white dark:text-black rounded-full hover:opacity-90 transition shadow-xs"
on:click={() => (showEditModal = true)}
>
{$i18n.t('Edit')}
</button>
{:else}
<span class="text-xs text-gray-500 bg-gray-100 dark:bg-gray-800 px-2 py-1 rounded-full"
>{$i18n.t('Read Only')}</span
>
{/if}
</div>
<div class="flex items-center gap-2 shrink-0">
{#if !disabled}
<button
class="bg-gray-50 hover:bg-gray-100 text-black dark:bg-gray-850 dark:hover:bg-gray-800 dark:text-white transition px-2.5 py-1 rounded-full flex gap-1.5 items-center text-sm border border-gray-100 dark:border-gray-800"
on:click={() => (showAccessControlModal = true)}
>
<LockClosed strokeWidth="2.5" className="size-3.5" />
{$i18n.t('Access')}
</button>
<button
class="px-4 py-1 text-sm font-medium bg-black text-white dark:bg-white dark:text-black rounded-full hover:opacity-90 transition shadow-xs"
on:click={() => (showEditModal = true)}
>
{$i18n.t('Edit')}
</button>
{:else}
<span class="text-xs text-gray-500 bg-gray-100 dark:bg-gray-800 px-2 py-1 rounded-full"
>{$i18n.t('Read Only')}</span
>
{/if}
</div>
</div>
<div class="flex flex-col md:flex-row gap-4 flex-1 overflow-hidden pb-6">
<!-- Desktop History Sidebar -->
<div class="hidden md:flex md:flex-col w-72 shrink-0 overflow-hidden">
<div class="flex-1 overflow-y-auto">
{@render historySection()}
</div>
</div>
<div class="flex flex-col lg:flex-row gap-4">
<!-- Desktop History Sidebar -->
<div class="hidden lg:block w-72 shrink-0 mt-1 mb-2">
<div class="sticky">
{@render historySection()}
</div>
</div>
<!-- Prompt Content -->
<div class="mb-6 flex-1">
<div class="flex items-center justify-between mb-1">
<div class="flex items-center gap-2">
<div class="text-gray-500 text-xs">
{$i18n.t('Prompt Content')}
</div>
{#if selectedHistoryEntry}
<span
class="text-xs text-gray-500 font-mono bg-gray-100 dark:bg-gray-800 px-1.5 py-0.5 rounded"
>
{selectedHistoryEntry.id.slice(0, 7)}
</span>
{/if}
<!-- Prompt Content -->
<div class="flex-1 flex flex-col min-h-0 overflow-hidden">
<div class="flex items-center justify-between mb-1 shrink-0">
<div class="flex items-center gap-2">
<div class="text-gray-500 text-xs">
{$i18n.t('Prompt Content')}
</div>
{#if selectedHistoryEntry && !disabled}
<div class="flex items-center gap-2">
{#if selectedHistoryEntry.id === prompt?.version_id}
<Badge type="success" content={$i18n.t('Live')} />
{:else}
<button
class="text-xs text-gray-500 hover:text-gray-900 dark:hover:text-gray-300 hover:underline transition"
on:click={() => setAsProduction(selectedHistoryEntry)}
>
{$i18n.t('Set as Production')}
</button>
{/if}
<PromptHistoryMenu
isProduction={selectedHistoryEntry.id === prompt?.version_id}
onDelete={() => handleDeleteHistory(selectedHistoryEntry.id)}
onClose={() => {}}
/>
</div>
{#if selectedHistoryEntry}
<span
class="text-xs text-gray-500 font-mono bg-gray-100 dark:bg-gray-800 px-1.5 py-0.5 rounded"
>
{selectedHistoryEntry.id.slice(0, 7)}
</span>
{/if}
</div>
<div
class="relative bg-gray-50 dark:bg-gray-900 rounded-xl px-4 py-3 border border-gray-100 dark:border-gray-800"
>
{#if selectedHistoryEntry && !disabled}
<div class="flex items-center gap-2">
{#if selectedHistoryEntry.id === prompt?.version_id}
<Badge type="success" content={$i18n.t('Live')} />
{:else}
<button
class="text-xs text-gray-500 hover:text-gray-900 dark:hover:text-gray-300 hover:underline transition"
on:click={() => setAsProduction(selectedHistoryEntry)}
>
{$i18n.t('Set as Production')}
</button>
{/if}
<PromptHistoryMenu
isProduction={selectedHistoryEntry.id === prompt?.version_id}
onDelete={() => handleDeleteHistory(selectedHistoryEntry.id)}
onClose={() => {}}
/>
</div>
{/if}
</div>
<!-- Content container with copy button -->
<div class="relative flex-1 min-h-0">
<!-- Copy button - outside scroll area -->
<div class="absolute top-2 right-2 z-10">
<button
class="absolute top-2 right-2 p-1.5 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-800 transition"
class="p-1.5 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-800 transition"
on:click={copyContent}
>
{#if contentCopied}
@@ -384,15 +443,15 @@
<Clipboard className="size-4 text-gray-500" />
{/if}
</button>
</div>
<!-- Scrollable content -->
<div
class="bg-gray-50 dark:bg-gray-900 rounded-xl px-4 py-3 border border-gray-100 dark:border-gray-800 h-full overflow-y-auto"
>
<pre class="text-sm whitespace-pre-wrap font-mono pr-8">{selectedHistoryEntry?.snapshot
?.content || content}</pre>
</div>
</div>
<!-- Mobile History -->
<div class="lg:hidden pb-20">
{@render historySection()}
</div>
</div>
</div>
</div>
@@ -477,8 +536,8 @@
{/if}
{#snippet historySection()}
<div>
<div class="flex items-center justify-between mb-2">
<div class="flex flex-col h-full">
<div class="flex items-center justify-between mb-2 shrink-0">
<div class="text-gray-500 text-xs">{$i18n.t('History')}</div>
{#if historyLoading}
<Spinner className="size-3" />
@@ -486,7 +545,7 @@
</div>
{#if history.length > 0}
<div class="space-y-0 max-h-96 overflow-y-auto" on:scroll={handleHistoryScroll}>
<div class="space-y-0 flex-1 overflow-y-auto" on:scroll={handleHistoryScroll}>
{#each history as entry, index}
<div class="flex">
<!-- Content -->
@@ -513,7 +572,7 @@
<img
src={`/api/v1/users/${entry.user.id}/profile/image`}
alt={entry.user.name}
class="size-3 rounded-full"
class="size-3 rounded-full mr-0.5"
on:error={(e) => (e.target.src = '/user.png')}
/>
<span class="truncate">{entry.user.name}</span>