ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.
Python astracloudflarecontrol-panelcyberpaneldnsfablehosting-control-panelhosting-panelkimi-k3server-managementserverkitubuntu-web-panelwebserver
feat(ai): add resource attachment composer
Juan Denis885df406b20a
diff --git a/frontend/src/components/ai/AttachmentChip.jsx b/frontend/src/components/ai/AttachmentChip.jsxnew file mode 100644index 00000000..3ddaf9da--- /dev/null+++ b/frontend/src/components/ai/AttachmentChip.jsx@@ -0,0 +1,42 @@+import { AlertTriangle, Paperclip, X } from 'lucide-react';+import { useTranslation } from 'react-i18next';++import { attachmentKey } from '../../lib/ai/attachments';+import IconButton from '../IconButton';++const WARNING_STATUSES = new Set(['denied', 'stale', 'unknown', 'unavailable', 'omitted']);++export default function AttachmentChip({ attachment, onRemove }) {+ const { t } = useTranslation();+ const warning = WARNING_STATUSES.has(attachment.status);+ const statusLabel = attachment.status === 'denied'+ ? t('app.attachmentChip.denied', 'Access denied')+ : attachment.status === 'stale'+ ? t('app.attachmentChip.stale', 'No longer available')+ : attachment.status === 'unknown'+ ? t('app.attachmentChip.unknown', 'Unsupported attachment')+ : attachment.status === 'omitted'+ ? t('app.attachmentChip.omitted', 'Context limit reached')+ : t('app.attachmentChip.unavailable', 'Unavailable');+ const title = warning ? (attachment.warning || statusLabel) : attachment.label;++ return (+ <span+ className={`sk-ai-attachment${warning ? ' is-warning' : ''}`}+ title={title}+ >+ {warning ? <AlertTriangle size={12} aria-hidden="true" /> : <Paperclip size={12} aria-hidden="true" />}+ <span className="sk-ai-attachment__type">{attachment.runKind || attachment.type}</span>+ <span className="sk-ai-attachment__label">{attachment.label}</span>+ {warning && <span className="sk-ai-attachment__status">{statusLabel}</span>}+ {onRemove && (+ <IconButton+ className="sk-ai-attachment__remove"+ onClick={() => onRemove(attachmentKey(attachment))}+ label={t('app.attachmentChip.remove', 'Remove {{label}}', { label: attachment.label })}+ icon={<X size={12} aria-hidden="true" />}+ />+ )}+ </span>+ );+}diff --git a/frontend/src/components/ai/Composer.jsx b/frontend/src/components/ai/Composer.jsxindex 5200e55b..c4fe731e 100644--- a/frontend/src/components/ai/Composer.jsx+++ b/frontend/src/components/ai/Composer.jsx@@ -1,11 +1,25 @@import { useRef, useState } from 'react';-import { Send, Square } from 'lucide-react';+import { Paperclip, Send, Square } from 'lucide-react';import { useServerkitAI } from '../../contexts/AIContext';import { useTranslation } from 'react-i18next';+import ResourcePicker from '../ResourcePicker';+import { Button } from '../ui/button';+import { MAX_AI_ATTACHMENTS } from '../../lib/ai/attachments';+import AttachmentChip from './AttachmentChip';++const ATTACHMENT_TYPES = ['service', 'server', 'project', 'environment', 'domain'];const Composer = () => {const { t } = useTranslation();- const { send, stop, isStreaming, providerConfigured } = useServerkitAI();+ const {+ send,+ stop,+ isStreaming,+ providerConfigured,+ attachments,+ addAttachment,+ removeAttachment,+ } = useServerkitAI();const [value, setValue] = useState('');const textareaRef = useRef(null);@@ -33,32 +47,57 @@ const Composer = () => {return (<div className="sk-ai-composer">- <textarea- ref={textareaRef}- className="sk-ai-composer__input"- rows={1}- placeholder={providerConfigured ? t('app.composer.askAboutYourServers', 'Ask about your servers…') : t('app.composer.assistantNotConfigured', 'Assistant not configured')}- value={value}- disabled={!providerConfigured}- onChange={onInput}- onKeyDown={onKeyDown}- aria-label={t('app.composer.messageTheAssistant', 'Message the assistant')}- />- {isStreaming ? (- <button type="button" className="sk-ai-composer__btn sk-ai-composer__btn--stop" onClick={stop} aria-label={t('app.composer.stop', 'Stop')}>- <Square size={16} />- </button>- ) : (- <button- type="button"- className="sk-ai-composer__btn"- onClick={submit}- disabled={!providerConfigured || !value.trim()}- aria-label={t('app.composer.send', 'Send')}- >- <Send size={16} />- </button>+ {attachments.length > 0 && (+ <div className="sk-ai-composer__attachments">+ {attachments.map((attachment) => (+ <AttachmentChip+ key={`${attachment.type}:${attachment.runKind || ''}:${attachment.id}`}+ attachment={attachment}+ onRemove={removeAttachment}+ />+ ))}+ </div>)}+ <div className="sk-ai-composer__main">+ <ResourcePicker+ value={null}+ onChange={addAttachment}+ types={ATTACHMENT_TYPES}+ icon={Paperclip}+ disabled={!providerConfigured || isStreaming || attachments.length >= MAX_AI_ATTACHMENTS}+ className="sk-ai-composer__attach"+ label={t('app.composer.attachResource', 'Attach a resource')}+ placeholder={t('app.composer.attach', 'Attach')}+ searchPlaceholder={t('app.composer.searchResources', 'Search resources…')}+ emptyMessage={t('app.composer.noResources', 'No accessible resources found')}+ />+ <textarea+ ref={textareaRef}+ className="sk-ai-composer__input"+ rows={1}+ placeholder={providerConfigured ? t('app.composer.askAboutYourServers', 'Ask about your servers…') : t('app.composer.assistantNotConfigured', 'Assistant not configured')}+ value={value}+ disabled={!providerConfigured}+ onChange={onInput}+ onKeyDown={onKeyDown}+ aria-label={t('app.composer.messageTheAssistant', 'Message the assistant')}+ />+ {isStreaming ? (+ <Button type="button" className="sk-ai-composer__btn sk-ai-composer__btn--stop" onClick={stop} aria-label={t('app.composer.stop', 'Stop')}>+ <Square size={16} />+ </Button>+ ) : (+ <Button+ type="button"+ className="sk-ai-composer__btn"+ onClick={submit}+ disabled={!providerConfigured || !value.trim()}+ aria-label={t('app.composer.send', 'Send')}+ >+ <Send size={16} />+ </Button>+ )}+ </div></div>);};diff --git a/frontend/src/components/ai/Message.jsx b/frontend/src/components/ai/Message.jsxindex f47016fa..da50d026 100644--- a/frontend/src/components/ai/Message.jsx+++ b/frontend/src/components/ai/Message.jsx@@ -1,10 +1,21 @@import Markdown from './Markdown';import ToolCallCard from './ToolCallCard';+import AttachmentChip from './AttachmentChip';const Message = ({ message }) => {if (message.role === 'user') {return (<div className="sk-ai-message sk-ai-message--user">+ {(message.attachments || []).length > 0 && (+ <div className="sk-ai-message__attachments">+ {message.attachments.map((attachment) => (+ <AttachmentChip+ key={`${attachment.type}:${attachment.runKind || ''}:${attachment.id}`}+ attachment={attachment}+ />+ ))}+ </div>+ )}<div className="sk-ai-message__bubble">{message.content}</div></div>);diff --git a/frontend/src/contexts/AIContext.jsx b/frontend/src/contexts/AIContext.jsxindex a836e58a..4b6cddb7 100644--- a/frontend/src/contexts/AIContext.jsx+++ b/frontend/src/contexts/AIContext.jsx@@ -3,6 +3,15 @@ import {} from 'react';import api from '../services/api';import usePageContext from '../hooks/ai/usePageContext';+import {+ addAttachment as appendAttachment,+ applyAttachmentWarning,+ attachmentKey,+ markAttachmentsResolved,+ normalizeAttachment,+ removeAttachment as discardAttachment,+ toAttachmentPayload,+} from '../lib/ai/attachments';const AIContext = createContext(null);@@ -18,6 +27,7 @@ const initialState = {statusLoaded: false,conversations: [],activeId: null,+ attachments: [],messages: [], // [{ id, role, content, toolCalls, thinking, status, error }]isStreaming: false,error: null,@@ -37,6 +47,17 @@ function patchLastAssistant(messages, patch) {return next;}+function patchLastUser(messages, patch) {+ const next = [...messages];+ for (let i = next.length - 1; i >= 0; i -= 1) {+ if (next[i].role === 'user') {+ next[i] = typeof patch === 'function' ? patch(next[i]) : { ...next[i], ...patch };+ break;+ }+ }+ return next;+}+function reducer(state, action) {switch (action.type) {case 'SET_OPEN':@@ -54,13 +75,31 @@ function reducer(state, action) {case 'SET_ACTIVE':return { ...state, activeId: action.id };case 'LOAD_MESSAGES':- return { ...state, messages: action.messages, activeId: action.id, pendingConfirm: null, error: null };+ return {+ ...state, messages: action.messages, activeId: action.id,+ attachments: [], pendingConfirm: null, error: null,+ };case 'NEW_CONVERSATION':- return { ...state, activeId: null, messages: [], pendingConfirm: null, error: null };+ return {+ ...state, activeId: null, messages: [], attachments: [],+ pendingConfirm: null, error: null,+ };+ case 'ADD_ATTACHMENT':+ return { ...state, attachments: appendAttachment(state.attachments, action.attachment) };+ case 'REMOVE_ATTACHMENT':+ return { ...state, attachments: discardAttachment(state.attachments, action.key) };+ case 'CLEAR_ATTACHMENTS':+ return { ...state, attachments: [] };case 'ADD_USER_MESSAGE':return {...state,- messages: [...state.messages, { id: action.id, role: 'user', content: action.content, status: 'done' }],+ messages: [...state.messages, {+ id: action.id,+ role: 'user',+ content: action.content,+ attachments: action.attachments || [],+ status: 'done',+ }],};case 'BEGIN_ASSISTANT':return {@@ -113,6 +152,14 @@ function reducer(state, action) {};case 'SET_PENDING_CONFIRM':return { ...state, pendingConfirm: action.payload };+ case 'ATTACHMENT_WARNING':+ return {+ ...state,+ messages: patchLastUser(state.messages, (message) => ({+ ...message,+ attachments: applyAttachmentWarning(message.attachments || [], action.warning),+ })),+ };case 'CLEAR_PENDING_CONFIRM':return { ...state, pendingConfirm: null };case 'TURN_DONE':@@ -121,7 +168,16 @@ function reducer(state, action) {isStreaming: false,activeId: action.conversationId || state.activeId,unread: state.open ? 0 : state.unread + 1,- messages: patchLastAssistant(state.messages, (m) => ({ ...m, status: m.status === 'streaming' ? 'done' : m.status })),+ messages: patchLastAssistant(+ patchLastUser(state.messages, (message) => ({+ ...message,+ attachments: markAttachmentsResolved(message.attachments || []),+ })),+ (message) => ({+ ...message,+ status: message.status === 'streaming' ? 'done' : message.status,+ }),+ ),};case 'SET_ERROR':return {@@ -178,6 +234,7 @@ export function AIProvider({ children }) {id: `srv_${m.id}`,role: m.role === 'assistant' ? 'assistant' : 'user',content: m.content || '',+ attachments: (m.attachments || []).map(normalizeAttachment).filter(Boolean),toolCalls: (m.tool_calls || []).map((tc) => ({id: tc.id, name: tc.name, input: tc.input, output: tc.output,isError: tc.is_error, status: tc.is_error ? 'error' : 'done',@@ -224,6 +281,7 @@ export function AIProvider({ children }) {case 'tool_use_stop': dispatch({ type: 'TOOL_STOP', id: data.id, name: data.name, input: data.input }); break;case 'tool_result': dispatch({ type: 'TOOL_RESULT', id: data.id, output: data.output, isError: !!data.is_error }); break;case 'pending_action': dispatch({ type: 'SET_PENDING_CONFIRM', payload: data }); break;+ case 'attachment_warning': dispatch({ type: 'ATTACHMENT_WARNING', warning: data }); break;case 'error': dispatch({ type: 'SET_ERROR', message: data.message || 'The assistant hit an error.' }); break;case 'done': dispatch({ type: 'TURN_DONE', conversationId: data.conversation_id }); break;default: break;@@ -235,18 +293,31 @@ export function AIProvider({ children }) {const text = (prompt || '').trim();if (!text || state.isStreaming) return;const mode = opts.mode || state.mode;+ const requestedAttachments = (opts.attachments || []).reduce(+ (items, attachment) => appendAttachment(items, attachment),+ state.attachments,+ );const payload = {conversation_id: activeIdRef.current || undefined,message: text,mode,};+ if (requestedAttachments.length) {+ payload.attachments = requestedAttachments.map(toAttachmentPayload).filter(Boolean);+ }if (mode === 'assistant' && state.includeContext) {payload.page_context = buildPageContext(opts.context);} else if (opts.context) {payload.page_context = opts.context;}- dispatch({ type: 'ADD_USER_MESSAGE', id: newId(), content: text });+ dispatch({+ type: 'ADD_USER_MESSAGE',+ id: newId(),+ content: text,+ attachments: requestedAttachments,+ });+ dispatch({ type: 'CLEAR_ATTACHMENTS' });dispatch({ type: 'BEGIN_ASSISTANT', id: newId() });const controller = new AbortController();@@ -263,7 +334,10 @@ export function AIProvider({ children }) {abortRef.current = null;loadConversations();}- }, [state.isStreaming, state.mode, state.includeContext, buildPageContext, handleEvent, loadConversations]);+ }, [+ state.isStreaming, state.mode, state.includeContext, state.attachments,+ buildPageContext, handleEvent, loadConversations,+ ]);const stop = useCallback(() => {abortRef.current?.abort();@@ -309,6 +383,14 @@ export function AIProvider({ children }) {const setMode = useCallback((mode) => dispatch({ type: 'SET_MODE', mode }), []);const setIncludeContext = useCallback((value) => dispatch({ type: 'SET_INCLUDE_CONTEXT', value }), []);+ const addAttachment = useCallback((attachment, options = {}) => {+ dispatch({ type: 'ADD_ATTACHMENT', attachment });+ if (options.open !== false) dispatch({ type: 'SET_OPEN', open: true });+ }, []);+ const removeAttachment = useCallback((attachment) => {+ const key = typeof attachment === 'string' ? attachment : attachmentKey(attachment);+ dispatch({ type: 'REMOVE_ATTACHMENT', key });+ }, []);// --- plugin registries (returned to plugin components via useServerkitAI) ---const registerContextProvider = useCallback((routePattern, fn) => {@@ -328,12 +410,14 @@ export function AIProvider({ children }) {pageContext,// controlsopen, close, toggle, ask, send, stop, confirmAction, setMode, setIncludeContext,+ addAttachment, removeAttachment,loadConversations, switchConversation, newConversation, deleteConversation, loadStatus,// plugin SDK surfaceregisterContextProvider, registerToolRenderer, getToolRenderer,}), [state, pageContext, open, close, toggle, ask, send, stop, confirmAction, setMode,- setIncludeContext, loadConversations, switchConversation, newConversation,+ setIncludeContext, addAttachment, removeAttachment,+ loadConversations, switchConversation, newConversation,deleteConversation, loadStatus, registerContextProvider, registerToolRenderer, getToolRenderer,]);diff --git a/frontend/src/i18n/locales/en.json b/frontend/src/i18n/locales/en.jsonindex 166dfefc..20e41720 100644--- a/frontend/src/i18n/locales/en.json+++ b/frontend/src/i18n/locales/en.json@@ -365,6 +365,14 @@"violet": "Violet","widgetsAreArrangedOnTheDashboard": "Widgets are arranged on the dashboard itself now — add, move, resize and configure them in place, across as many boards as you need."},+ "attachmentChip": {+ "denied": "Access denied",+ "omitted": "Context limit reached",+ "remove": "Remove {{label}}",+ "stale": "No longer available",+ "unavailable": "Unavailable",+ "unknown": "Unsupported attachment"+ },"auditTab": {"generated": "Generated","recommendations": "Recommendations",@@ -944,7 +952,11 @@"composer": {"askAboutYourServers": "Ask about your servers…","assistantNotConfigured": "Assistant not configured",+ "attach": "Attach",+ "attachResource": "Attach a resource","messageTheAssistant": "Message the assistant",+ "noResources": "No accessible resources found",+ "searchResources": "Search resources…","send": "Send","stop": "Stop"},diff --git a/frontend/src/lib/ai/attachments.js b/frontend/src/lib/ai/attachments.jsnew file mode 100644index 00000000..b23761c8--- /dev/null+++ b/frontend/src/lib/ai/attachments.js@@ -0,0 +1,68 @@+export const MAX_AI_ATTACHMENTS = 8;++const RESOLUTION_STATUSES = new Set([+ 'resolved', 'denied', 'stale', 'unknown', 'unavailable', 'omitted',+]);++export function attachmentKey(attachment) {+ const runKind = attachment?.runKind || attachment?.run_kind || '';+ return `${attachment?.type || ''}:${runKind}:${attachment?.id || ''}`;+}++export function normalizeAttachment(reference) {+ if (!reference || reference.type == null || reference.id == null) return null;+ const type = reference.type === 'app' || reference.type === 'application'+ ? 'service'+ : String(reference.type);+ const rawStatus = reference.attachmentStatus || reference.status;+ return {+ type,+ id: String(reference.id),+ label: String(reference.label || `${type} ${reference.id}`),+ sublabel: String(reference.sublabel || ''),+ path: reference.path ? String(reference.path) : null,+ runKind: reference.runKind || reference.run_kind || null,+ status: RESOLUTION_STATUSES.has(rawStatus) ? rawStatus : null,+ };+}++export function addAttachment(current, reference) {+ const normalized = normalizeAttachment(reference);+ if (!normalized) return current;+ if (current.some((item) => attachmentKey(item) === attachmentKey(normalized))) {+ return current;+ }+ if (current.length >= MAX_AI_ATTACHMENTS) return current;+ return [...current, normalized];+}++export function removeAttachment(current, key) {+ return current.filter((item) => attachmentKey(item) !== key);+}++export function applyAttachmentWarning(current, warning) {+ const warningKey = attachmentKey({+ ...warning,+ runKind: warning.runKind || warning.run_kind,+ });+ return current.map((item) => (+ attachmentKey(item) === warningKey+ ? { ...item, status: warning.status || 'unavailable', warning: warning.message || '' }+ : item+ ));+}++export function markAttachmentsResolved(current) {+ return current.map((item) => (item.status ? item : { ...item, status: 'resolved' }));+}++export function toAttachmentPayload(reference) {+ const normalized = normalizeAttachment(reference);+ if (!normalized) return null;+ return {+ type: normalized.type,+ id: normalized.id,+ label: normalized.label,+ ...(normalized.runKind ? { run_kind: normalized.runKind } : {}),+ };+}diff --git a/frontend/src/lib/ai/attachments.test.js b/frontend/src/lib/ai/attachments.test.jsnew file mode 100644index 00000000..af66b0f7--- /dev/null+++ b/frontend/src/lib/ai/attachments.test.js@@ -0,0 +1,45 @@+import assert from 'node:assert/strict';+import test from 'node:test';++import {+ MAX_AI_ATTACHMENTS,+ addAttachment,+ applyAttachmentWarning,+ markAttachmentsResolved,+ toAttachmentPayload,+} from './attachments.js';++test('attachment drafts normalize service aliases, deduplicate, and cap', () => {+ let items = addAttachment([], { type: 'app', id: 7, label: 'API', path: '/services/7' });+ items = addAttachment(items, { type: 'service', id: '7', label: 'Duplicate' });+ assert.equal(items.length, 1);+ assert.equal(items[0].type, 'service');++ for (let index = 1; index < MAX_AI_ATTACHMENTS + 3; index += 1) {+ items = addAttachment(items, { type: 'server', id: index, label: `Node ${index}` });+ }+ assert.equal(items.length, MAX_AI_ATTACHMENTS);+});++test('resolver warnings update only the matching chip', () => {+ const items = [+ { type: 'service', id: '1', label: 'API', status: null },+ { type: 'server', id: '2', label: 'Worker', status: null },+ ];+ const warned = applyAttachmentWarning(items, {+ type: 'server', id: '2', status: 'denied', message: 'Access denied',+ });+ const resolved = markAttachmentsResolved(warned);+ assert.equal(resolved[0].status, 'resolved');+ assert.equal(resolved[1].status, 'denied');+ assert.equal(resolved[1].warning, 'Access denied');+});++test('attachment payload contains references but not presentation fields', () => {+ assert.deepEqual(toAttachmentPayload({+ type: 'run', id: '42', label: 'Backup', sublabel: 'failed',+ path: '/jobs/42', runKind: 'job', status: 'resolved',+ }), {+ type: 'run', id: '42', label: 'Backup', run_kind: 'job',+ });+});diff --git a/frontend/src/styles/components/_ai-assistant.scss b/frontend/src/styles/components/_ai-assistant.scssindex 2c3f1fab..27b2b505 100644--- a/frontend/src/styles/components/_ai-assistant.scss+++ b/frontend/src/styles/components/_ai-assistant.scss@@ -223,6 +223,60 @@ body:has(.ui-sheet-content[data-state='open']) .sk-ai-bubble {.sk-ai-message { display: flex; flex-direction: column; gap: 8px; max-width: 100%; }.sk-ai-message--user { align-items: flex-end; }+.sk-ai-message__attachments,+.sk-ai-composer__attachments {+ display: flex;+ flex-wrap: wrap;+ justify-content: flex-end;+ gap: 6px;+}+.sk-ai-attachment {+ min-width: 0;+ max-width: 100%;+ display: inline-flex;+ align-items: center;+ gap: 5px;+ padding: 4px 6px;+ border: 1px solid var(--sk-ai-border);+ border-radius: 999px;+ background: var(--sk-ai-bg-body);+ color: var(--sk-ai-fg-2);+ font-size: 11px;++ &.is-warning {+ border-color: fade($warning-raw, 48%);+ color: var(--warning, #fbbf24);+ }+}+.sk-ai-attachment__type {+ color: var(--sk-ai-fg-3);+ font-family: var(--sk-ai-mono);+ text-transform: uppercase;+}+.sk-ai-attachment__label {+ overflow: hidden;+ max-width: 150px;+ color: var(--sk-ai-fg);+ text-overflow: ellipsis;+ white-space: nowrap;+}+.sk-ai-attachment__status { white-space: nowrap; }+.sk-ai-attachment__remove {+ width: 18px;+ height: 18px;+ display: inline-flex;+ align-items: center;+ justify-content: center;+ padding: 0;+ border: 0;+ border-radius: 50%;+ background: transparent;+ color: inherit;+ cursor: pointer;++ &:hover { background: var(--sk-ai-hover); }+ &:focus-visible { outline: 2px solid var(--sk-ai-accent); outline-offset: 1px; }+}.sk-ai-message--user .sk-ai-message__bubble {background: var(--sk-ai-accent);color: #fff;@@ -341,11 +395,28 @@ body:has(.ui-sheet-content[data-state='open']) .sk-ai-bubble {// ---------------------------------------------------------------- Composer.sk-ai-composer {display: flex;- align-items: flex-end;+ flex-direction: column;gap: 8px;padding: 12px 14px;border-top: 1px solid var(--sk-ai-border);}+.sk-ai-composer__attachments { width: 100%; }+.sk-ai-composer__main {+ width: 100%;+ display: flex;+ align-items: flex-end;+ gap: 8px;+}+.sk-ai-composer__attach.sk-resource-picker__trigger {+ min-width: 40px;+ width: 40px;+ height: 40px;+ padding: 0;+ justify-content: center;++ > span,+ .sk-resource-picker__chevron { display: none; }+}.sk-ai-composer__input {flex: 1;resize: none;