feat: Actions system — scheduled mutations on external services

Full-stack implementation of provider-scoped Actions with extensible
executor architecture. First action type: Immich auto_organize (sort
assets into albums by person, CLIP search, date range, favorites).

Core:
- ActionTypeDefinition registry + ActionExecutor ABC with execute/validate/dry-run
- ImmichActionExecutor with multi-album support and client-side filtering
- ImmichClient write methods: add/remove assets, create album, paginated search

Server:
- Action, ActionRule, ActionExecution DB models
- Full CRUD API + manual execute + dry-run + execution history endpoints
- APScheduler integration (interval + cron) for automated execution
- Action type discovery API + provider people endpoint

Frontend:
- Actions page with CRUD, execute/dry-run buttons, inline rule editor
- RuleEditor: person/album MultiEntitySelect pickers, criteria config
- ExecutionHistory: expandable per-rule result details
- MultiEntitySelect reusable component (searchable multi-pick palette)
- Notification tracker album picker migrated to MultiEntitySelect
- Fixed MdiIcon race condition (icons missing after cache-clearing reload)
This commit is contained in:
2026-03-23 16:59:20 +03:00
parent 0fde3c6b3d
commit 6a559bfcd2
26 changed files with 2888 additions and 25 deletions
@@ -1,5 +1,5 @@
<script lang="ts">
import { getMdiPath, getAllMdiNames } from '$lib/mdi-lookup';
import { getMdiPath, getAllMdiNames } from '$lib/mdi-lookup.svelte';
let { value = '', onselect } = $props<{
value: string;
+1 -1
View File
@@ -1,5 +1,5 @@
<script lang="ts">
import { getMdiPath } from '$lib/mdi-lookup';
import { getMdiPath } from '$lib/mdi-lookup.svelte';
let { name = '', size = 18 } = $props<{ name: string; size?: number }>();
</script>
@@ -0,0 +1,352 @@
<script lang="ts">
import MdiIcon from './MdiIcon.svelte';
export interface MultiEntityItem {
value: string;
label: string;
icon?: string;
desc?: string;
}
let {
items = [],
values = $bindable<string[]>(),
placeholder = 'Select...',
size = 'default',
onchange,
}: {
items: MultiEntityItem[];
values: string[];
placeholder?: string;
size?: 'sm' | 'default';
onchange?: (values: string[]) => void;
} = $props();
let open = $state(false);
let query = $state('');
let highlightIdx = $state(0);
let inputEl: HTMLInputElement;
let listEl: HTMLDivElement;
const selectedItems = $derived(items.filter(i => (values || []).includes(i.value)));
const filtered = $derived.by(() => {
const q = query.toLowerCase().trim();
return q
? items.filter(i => i.label.toLowerCase().includes(q) || (i.desc || '').toLowerCase().includes(q))
: items;
});
function openPalette() {
open = true;
query = '';
highlightIdx = 0;
requestAnimationFrame(() => inputEl?.focus());
}
function closePalette() {
open = false;
query = '';
}
function toggleItem(item: MultiEntityItem) {
const current = values || [];
if (current.includes(item.value)) {
values = current.filter(v => v !== item.value);
} else {
values = [...current, item.value];
}
onchange?.(values);
}
function removeItem(value: string) {
values = (values || []).filter(v => v !== value);
onchange?.(values);
}
function handleKeydown(e: KeyboardEvent) {
if (e.key === 'Escape') { closePalette(); return; }
if (e.key === 'ArrowDown') {
e.preventDefault();
highlightIdx = Math.min(highlightIdx + 1, filtered.length - 1);
scrollToHighlight();
} else if (e.key === 'ArrowUp') {
e.preventDefault();
highlightIdx = Math.max(highlightIdx - 1, 0);
scrollToHighlight();
} else if (e.key === 'Enter') {
e.preventDefault();
if (filtered[highlightIdx]) toggleItem(filtered[highlightIdx]);
}
}
function scrollToHighlight() {
requestAnimationFrame(() => {
listEl?.querySelector('.mes-highlight')?.scrollIntoView({ block: 'nearest' });
});
}
$effect(() => { query; highlightIdx = 0; });
</script>
<!-- Trigger: chips + button -->
<div class="mes-trigger-wrap" class:mes-sm={size === 'sm'}>
{#if selectedItems.length > 0}
<div class="mes-chips">
{#each selectedItems as item}
<span class="mes-chip">
{#if item.icon}<span class="mes-chip-icon"><MdiIcon name={item.icon} size={12} /></span>{/if}
<span class="mes-chip-label">{item.label}</span>
<button type="button" class="mes-chip-remove" onclick={() => removeItem(item.value)}>&times;</button>
</span>
{/each}
</div>
{/if}
<button type="button" class="mes-trigger" onclick={openPalette}>
<MdiIcon name="mdiPlus" size={14} />
<span>{(values || []).length === 0 ? placeholder : `${(values || []).length} selected`}</span>
<span class="mes-trigger-arrow"><MdiIcon name="mdiChevronDown" size={14} /></span>
</button>
</div>
<!-- Palette overlay -->
{#if open}
<div class="mes-overlay" onclick={closePalette} role="presentation"></div>
<div class="mes-container">
<div class="mes-search-row">
<MdiIcon name="mdiMagnify" size={18} />
<input
bind:this={inputEl}
bind:value={query}
placeholder="Search..."
class="mes-input"
type="text"
autocomplete="off"
spellcheck="false"
onkeydown={handleKeydown}
/>
<span class="mes-count">{(values || []).length}/{items.length}</span>
<kbd class="mes-kbd">ESC</kbd>
</div>
<div class="mes-list" bind:this={listEl} role="listbox">
{#if filtered.length === 0}
<div class="mes-empty">No matches</div>
{:else}
{#each filtered as item, i}
{@const checked = (values || []).includes(item.value)}
<button
class="mes-item"
class:mes-highlight={i === highlightIdx}
class:mes-checked={checked}
role="option"
aria-selected={checked}
onclick={() => toggleItem(item)}
onmouseenter={() => highlightIdx = i}
type="button"
>
<span class="mes-item-check">
<MdiIcon name={checked ? 'mdiCheckboxMarked' : 'mdiCheckboxBlankOutline'} size={16} />
</span>
{#if item.icon}
<span class="mes-item-icon"><MdiIcon name={item.icon} size={18} /></span>
{/if}
<span class="mes-item-label">{item.label}</span>
{#if item.desc}
<span class="mes-item-desc">{item.desc}</span>
{/if}
</button>
{/each}
{/if}
</div>
</div>
{/if}
<style>
.mes-trigger-wrap {
display: flex;
flex-direction: column;
gap: 0.375rem;
}
.mes-chips {
display: flex;
flex-wrap: wrap;
gap: 0.25rem;
}
.mes-chip {
display: inline-flex;
align-items: center;
gap: 0.25rem;
font-size: 0.75rem;
padding: 0.125rem 0.5rem;
border-radius: 9999px;
background: color-mix(in srgb, var(--color-primary) 10%, transparent);
color: var(--color-primary);
border: 1px solid color-mix(in srgb, var(--color-primary) 30%, transparent);
}
.mes-chip-icon {
display: flex;
align-items: center;
}
.mes-chip-label {
max-width: 12rem;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.mes-chip-remove {
cursor: pointer;
font-size: 0.875rem;
line-height: 1;
opacity: 0.6;
transition: opacity 0.1s;
}
.mes-chip-remove:hover {
opacity: 1;
}
.mes-trigger {
display: flex;
align-items: center;
gap: 0.375rem;
width: 100%;
padding: 0.375rem 0.625rem;
border: 1px solid var(--color-border);
border-radius: 0.375rem;
font-size: 0.8rem;
background: var(--color-background);
color: var(--color-muted-foreground);
cursor: pointer;
transition: border-color 0.15s;
}
.mes-sm .mes-trigger {
padding: 0.25rem 0.5rem;
font-size: 0.75rem;
}
.mes-trigger:hover {
border-color: var(--color-primary);
}
.mes-trigger-arrow {
margin-left: auto;
flex-shrink: 0;
}
/* Overlay */
.mes-overlay {
position: fixed;
inset: 0;
z-index: 9998;
background: rgba(0, 0, 0, 0.4);
backdrop-filter: blur(2px);
}
/* Palette container */
.mes-container {
position: fixed;
top: min(20vh, 120px);
left: 50%;
transform: translateX(-50%);
z-index: 9999;
width: min(460px, 90vw);
max-height: 60vh;
background: var(--color-card);
border: 1px solid var(--color-border);
border-radius: 0.75rem;
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.4);
display: flex;
flex-direction: column;
overflow: hidden;
}
.mes-search-row {
display: flex;
align-items: center;
gap: 0.5rem;
padding: 0.625rem 0.875rem;
border-bottom: 1px solid var(--color-border);
color: var(--color-muted-foreground);
}
.mes-input {
flex: 1;
border: none;
outline: none;
background: transparent;
font-size: 0.9rem;
color: var(--color-foreground);
padding: 0;
}
.mes-count {
font-size: 0.7rem;
color: var(--color-muted-foreground);
white-space: nowrap;
}
.mes-kbd {
font-size: 0.55rem;
font-family: var(--font-mono);
padding: 0.1rem 0.3rem;
border-radius: 0.2rem;
background: var(--color-muted);
color: var(--color-muted-foreground);
border: 1px solid var(--color-border);
}
.mes-list {
overflow-y: auto;
scrollbar-width: thin;
padding: 0.25rem 0;
}
.mes-empty {
padding: 1rem;
text-align: center;
color: var(--color-muted-foreground);
font-size: 0.85rem;
}
.mes-item {
display: flex;
align-items: center;
gap: 0.5rem;
width: 100%;
padding: 0.4rem 0.875rem;
border: none;
background: transparent;
color: var(--color-foreground);
font-size: 0.875rem;
cursor: pointer;
text-align: left;
transition: background 0.1s;
}
.mes-item:hover, .mes-item.mes-highlight {
background: var(--color-muted);
}
.mes-item-check {
flex-shrink: 0;
display: flex;
align-items: center;
color: var(--color-muted-foreground);
}
.mes-item.mes-checked .mes-item-check {
color: var(--color-primary);
}
.mes-item-icon {
flex-shrink: 0;
display: flex;
align-items: center;
color: var(--color-muted-foreground);
}
.mes-item-label {
flex: 1;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.mes-item-desc {
font-size: 0.75rem;
color: var(--color-muted-foreground);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 40%;
}
</style>
+58 -1
View File
@@ -33,7 +33,9 @@
"targetDiscord": "Discord",
"targetSlack": "Slack",
"targetNtfy": "ntfy",
"targetMatrix": "Matrix"
"targetMatrix": "Matrix",
"automation": "Automation",
"actions": "Actions"
},
"auth": {
"signIn": "Sign in",
@@ -138,6 +140,7 @@
"server": "Provider",
"selectServer": "Select provider...",
"albums": "Albums",
"selectAlbums": "Select albums...",
"eventTypes": "Event Types",
"notificationTargets": "Notification Targets",
"scanInterval": "Scan Interval (seconds)",
@@ -828,5 +831,59 @@
"navigate": "navigate",
"open": "open",
"close": "close"
},
"actions": {
"title": "Actions",
"description": "Scheduled mutations on external services",
"addAction": "Add Action",
"noActions": "No actions configured yet.",
"provider": "Provider",
"selectProvider": "Select provider...",
"actionType": "Action Type",
"name": "Name",
"schedule": "Schedule",
"interval": "Interval",
"seconds": "seconds",
"cronHint": "Standard cron expression (e.g. 0 3 * * * for daily at 3 AM)",
"enabled": "Enabled",
"rules": "rules",
"addRule": "Add Rule",
"ruleName": "Rule Name",
"ruleNamePlaceholder": "e.g. Alice → Family Album",
"unnamedRule": "Unnamed rule",
"noRules": "No rules yet. Add a rule to define what this action does.",
"on": "ON",
"off": "OFF",
"criteria": "Criteria",
"persons": "Persons",
"addPerson": "Add person...",
"searchQuery": "Smart Search Query",
"searchQueryPlaceholder": "e.g. sunset, beach, birthday...",
"assetType": "Asset type",
"dateFrom": "From date",
"dateTo": "To date",
"favoritesOnly": "Favorites only",
"targetAlbum": "Target Album",
"selectAlbum": "Album",
"selectAlbumPlaceholder": "— Select album —",
"albumId": "Album ID",
"createAlbumIfMissing": "Create album if it doesn't exist",
"newAlbumName": "New album name",
"execute": "Execute",
"dryRun": "Dry Run",
"history": "History",
"affected": "affected",
"executeResult": "Action executed: {affected} items affected",
"dryRunResult": "Dry run: {affected} items would be affected",
"saved": "Action saved",
"deleted": "Action deleted",
"ruleSaved": "Rule saved",
"ruleDeleted": "Rule deleted",
"confirmDelete": "Are you sure you want to delete this action? All rules and execution history will be lost.",
"loadError": "Failed to load actions",
"noExecutions": "No executions yet.",
"triggerManual": "manual",
"triggerDryRun": "dry-run",
"triggerScheduled": "scheduled"
}
}
+58 -1
View File
@@ -33,7 +33,9 @@
"targetDiscord": "Discord",
"targetSlack": "Slack",
"targetNtfy": "ntfy",
"targetMatrix": "Matrix"
"targetMatrix": "Matrix",
"automation": "Автоматизация",
"actions": "Действия"
},
"auth": {
"signIn": "Войти",
@@ -138,6 +140,7 @@
"server": "Провайдер",
"selectServer": "Выберите провайдер...",
"albums": "Альбомы",
"selectAlbums": "Выберите альбомы...",
"eventTypes": "Типы событий",
"notificationTargets": "Получатели уведомлений",
"scanInterval": "Интервал проверки (секунды)",
@@ -828,5 +831,59 @@
"navigate": "навигация",
"open": "открыть",
"close": "закрыть"
},
"actions": {
"title": "Действия",
"description": "Запланированные операции над внешними сервисами",
"addAction": "Добавить действие",
"noActions": "Действия ещё не настроены.",
"provider": "Провайдер",
"selectProvider": "Выберите провайдер...",
"actionType": "Тип действия",
"name": "Название",
"schedule": "Расписание",
"interval": "Интервал",
"seconds": "секунд",
"cronHint": "Стандартное cron-выражение (напр. 0 3 * * * — ежедневно в 3:00)",
"enabled": "Включено",
"rules": "правил",
"addRule": "Добавить правило",
"ruleName": "Название правила",
"ruleNamePlaceholder": "напр. Алиса → Семейный альбом",
"unnamedRule": "Без названия",
"noRules": "Правил пока нет. Добавьте правило, чтобы определить, что делает это действие.",
"on": "ВКЛ",
"off": "ВЫКЛ",
"criteria": "Критерии",
"persons": "Люди",
"addPerson": "Добавить человека...",
"searchQuery": "Умный поиск",
"searchQueryPlaceholder": "напр. закат, пляж, день рождения...",
"assetType": "Тип файла",
"dateFrom": "С даты",
"dateTo": "По дату",
"favoritesOnly": "Только избранное",
"targetAlbum": "Целевой альбом",
"selectAlbum": "Альбом",
"selectAlbumPlaceholder": "— Выберите альбом —",
"albumId": "ID альбома",
"createAlbumIfMissing": "Создать альбом, если не существует",
"newAlbumName": "Название нового альбома",
"execute": "Выполнить",
"dryRun": "Пробный запуск",
"history": "История",
"affected": "затронуто",
"executeResult": "Действие выполнено: затронуто {affected} объектов",
"dryRunResult": "Пробный запуск: было бы затронуто {affected} объектов",
"saved": "Действие сохранено",
"deleted": "Действие удалено",
"ruleSaved": "Правило сохранено",
"ruleDeleted": "Правило удалено",
"confirmDelete": "Вы уверены, что хотите удалить это действие? Все правила и история выполнений будут потеряны.",
"loadError": "Не удалось загрузить действия",
"noExecutions": "Выполнений пока нет.",
"triggerManual": "вручную",
"triggerDryRun": "пробный",
"triggerScheduled": "по расписанию"
}
}
@@ -4,9 +4,13 @@
* Instead of `import * as mdi from '@mdi/js'` (which loads ~5MB of SVG paths
* into memory), this module loads the full set once on first use and caches it.
* Vite only processes the import once, reducing HMR memory pressure.
*
* Uses $state so that components re-render once the icon module finishes loading
* (fixes icons not appearing until page reload after cache-clearing navigations).
*/
let _cache: Record<string, string> | null = null;
let _ready = $state<Record<string, string> | null>(null);
async function _load(): Promise<Record<string, string>> {
if (_cache) return _cache;
@@ -16,7 +20,6 @@ async function _load(): Promise<Record<string, string>> {
}
// Eagerly load on module init (runs once)
let _ready: Record<string, string> | null = null;
_load().then(m => { _ready = m; });
/**
+5
View File
@@ -18,6 +18,7 @@ import type {
CommandConfig,
CommandTemplateConfig,
CommandTracker,
Action,
} from '$lib/types';
/** Service providers — used by Dashboard, Trackers, Command Trackers, Providers page. */
@@ -53,6 +54,9 @@ export const commandTemplateConfigsCache = createEntityCache<CommandTemplateConf
/** Command trackers — used by Command Trackers page. */
export const commandTrackersCache = createEntityCache<CommandTracker>('/command-trackers');
/** Actions — used by Actions page. */
export const actionsCache = createEntityCache<Action>('/actions');
/** Provider capabilities — used by Template Configs, Command Configs. */
export const capabilitiesCache = (() => {
let data = $state<Record<string, any>>({});
@@ -85,6 +89,7 @@ export const allCaches = {
command_configs: commandConfigsCache,
command_template_configs: commandTemplateConfigsCache,
command_trackers: commandTrackersCache,
actions: actionsCache,
} as const;
/**
+49
View File
@@ -219,6 +219,55 @@ export interface CommandTracker {
created_at: string;
}
export interface ActionRule {
id: number;
action_id: number;
name: string;
rule_config: Record<string, any>;
enabled: boolean;
order: number;
created_at: string;
}
export interface Action {
id: number;
name: string;
icon: string;
provider_id: number;
action_type: string;
config: Record<string, any>;
schedule_type: string;
schedule_interval: number;
schedule_cron: string;
enabled: boolean;
last_run_at: string | null;
last_run_status: string;
rules: ActionRule[];
created_at: string;
}
export interface ActionExecution {
id: number;
action_id: number;
started_at: string;
finished_at: string | null;
status: string;
rules_processed: number;
rules_succeeded: number;
rules_failed: number;
total_items_affected: number;
summary: Record<string, any>;
error: string;
trigger: string;
}
export interface ActionTypeInfo {
key: string;
name: string;
description: string;
provider_type: string;
}
export interface DashboardStatus {
providers: number;
trackers: { total: number; active: number };