diff --git a/src/client/ts/main.ts b/src/client/ts/main.ts index 8f1f14d..d41b44c 100644 --- a/src/client/ts/main.ts +++ b/src/client/ts/main.ts @@ -200,7 +200,7 @@ async function renderCurrentView(): Promise { return; } if (route === 'config') { - await renderConfigView(root, state.overview!, async () => { + await renderConfigView(root, state.overview!, state, wsClient, async () => { await refreshOverview(); await renderCurrentView(); }); @@ -253,7 +253,7 @@ async function renderCurrentView(): Promise { } if (route === 'alerts') { const { renderAlertsView } = await import('./views/alerts-view.js'); - await renderAlertsView(root, state); + await renderAlertsView(root, state, wsClient); } } diff --git a/src/client/ts/views/ai-drawer.ts b/src/client/ts/views/ai-drawer.ts new file mode 100644 index 0000000..d3620f7 --- /dev/null +++ b/src/client/ts/views/ai-drawer.ts @@ -0,0 +1,352 @@ +import type { ServerWsFrame } from '../../../shared/ws-protocol.js'; +import { apiFetch } from '../api.js'; +import { confirmDialog } from '../dialogs.js'; +import { + appendBoundedStreamText, + el, + extractErrorMessage, + type ClientState, +} from '../state.js'; +import type { MultiplexWsClient } from '../ws-client.js'; + +export type ClientAiSurface = 'workflows' | 'systems' | 'snippets' | 'logs' | 'setup'; +export type ClientAiDraftKind = + | 'workflow' + | 'system' + | 'snippet' + | 'server' + | 'alerts' + | 'settings'; + +export interface OpenAiDrawerOptions { + state: ClientState; + wsClient: MultiplexWsClient; + surface: ClientAiSurface; + title?: string; + initialPrompt?: string; + contextText?: string; + serverId?: string; + targetPath?: string; + defaultDraftKind?: ClientAiDraftKind; + onInsertTerminalText?: (cmd: string) => void; + onApplied?: () => Promise | void; +} + +interface PreviewResponse { + enabled: boolean; + baseUrl: string; + model: string; + surface: ClientAiSurface; + defaultDraftKind?: ClientAiDraftKind; + systemPrompt: string; + inventorySummary: string; + sanitizedContext: string; + redactedCount: number; + truncated: boolean; +} + +function extractLastFencedBlock(text: string, langPattern: RegExp): string | null { + const re = /```([a-zA-Z0-9_-]*)\s*\r?\n([\s\S]*?)```/g; + let match: RegExpExecArray | null; + let last: string | null = null; + while ((match = re.exec(text)) !== null) { + const lang = match[1] ?? ''; + if (langPattern.test(lang)) { + last = match[2]!.trim(); + } + } + return last; +} + +export async function openAiAssistantDrawer(opts: OpenAiDrawerOptions): Promise { + const existing = document.getElementById('ai-drawer-dialog'); + if (existing) existing.remove(); + + const dialog = document.createElement('dialog'); + dialog.id = 'ai-drawer-dialog'; + dialog.className = 'ai-drawer'; + dialog.setAttribute('aria-labelledby', 'ai-drawer-title'); + + const closeBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Close'); + const titleEl = el( + 'h1', + { id: 'ai-drawer-title' }, + opts.title ?? `AI Assistant (${opts.surface})`, + ); + + const previewSummary = el('summary', { class: 'muted mono' }, 'Loading sanitized context preview...'); + const previewPre = el('pre', { class: 'stream-log mono', style: 'max-height:180px' }, ''); + const previewDetails = el('details', { class: 'panel', style: 'margin:0' }, previewSummary, previewPre); + + const streamPre = el( + 'pre', + { class: 'stream-log mono', style: 'flex:1 1 auto;min-height:160px;max-height:none;margin:0' }, + 'Ask the assistant to draft a schema-checked JSON config, snippet, or debug log error.\nAll drafts require explicit review before Apply.\n', + ); + + const draftBar = el('div', { class: 'stack', hidden: true }); + const draftKindSel = el( + 'select', + { class: 'input-sm', 'aria-label': 'Draft schema type' }, + ...(['workflow', 'system', 'snippet', 'server', 'alerts', 'settings'] as const).map((k) => + el('option', { value: k, selected: opts.defaultDraftKind === k ? true : undefined }, k), + ), + ); + const draftOutputBox = el('div', { class: 'stack' }); + + const promptArea = el('textarea', { + rows: 3, + autofocus: true, + placeholder: 'Describe what you want to create or diagnose (no secrets sent)...', + }); + if (opts.initialPrompt) promptArea.value = opts.initialPrompt; + + const statusLine = el('p', { class: 'form-msg muted' }, ''); + const sendBtn = el('button', { type: 'submit', class: 'btn btn-primary btn-sm' }, 'Send'); + const stopBtn = el('button', { type: 'button', class: 'btn btn-danger btn-sm', disabled: true }, 'Stop'); + + const history: Array<{ role: 'user' | 'assistant'; content: string }> = []; + let activeChatId: string | null = null; + let currentReply = ''; + let unsubWs: (() => void) | null = null; + + const cleanup = () => { + if (activeChatId) { + opts.wsClient.send({ type: 'ai:cancel', chatId: activeChatId }); + activeChatId = null; + } + if (unsubWs) { + unsubWs(); + unsubWs = null; + } + dialog.returnValue = ''; + dialog.remove(); + }; + + closeBtn.addEventListener('click', () => { + if (dialog.open) dialog.close(); + }); + dialog.addEventListener('close', cleanup); + + const refreshDraftActions = () => { + draftBar.replaceChildren(); + draftOutputBox.replaceChildren(); + const jsonBlock = extractLastFencedBlock(currentReply, /^(?:json)?$/i); + const shBlock = extractLastFencedBlock(currentReply, /^(?:sh|bash|zsh|shell)$/i); + if (!jsonBlock && (!shBlock || !opts.onInsertTerminalText)) { + draftBar.hidden = true; + return; + } + draftBar.hidden = false; + const btnRow = el('div', { class: 'row' }); + + if (shBlock && opts.onInsertTerminalText) { + const insertBtn = el( + 'button', + { type: 'button', class: 'btn btn-sm btn-primary mutating-action' }, + 'Insert into Prompt (No Enter)', + ); + insertBtn.addEventListener('click', () => { + const cleanCmd = shBlock.replace(/[\r\n]+$/, ''); + opts.onInsertTerminalText!(cleanCmd); + if (dialog.open) dialog.close(); + }); + btnRow.append(insertBtn); + } + + if (jsonBlock) { + const validateBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Validate JSON Draft'); + validateBtn.addEventListener('click', async () => { + draftOutputBox.replaceChildren(el('p', { class: 'muted mono' }, 'Validating against Zod schema...')); + try { + const res = await apiFetch< + | { + valid: true; + kind: string; + targetPath: string; + normalizedJson: string; + diffLines: Array<{ type: 'equal' | 'add' | 'del'; text: string }>; + } + | { valid: false; issues: Array<{ path: string; message: string }> } + >('/api/ai/validate-draft', { + method: 'POST', + body: { kind: draftKindSel.value, jsonText: jsonBlock }, + }); + + draftOutputBox.replaceChildren(); + if (!res.valid) { + draftOutputBox.append(el('p', { class: 'err-text' }, 'Schema validation failed:')); + for (const iss of res.issues) { + draftOutputBox.append(el('div', { class: 'mono err-text' }, ` ${iss.path}: ${iss.message}`)); + } + return; + } + + const diffPreview = res.diffLines + .slice(0, 80) + .map((l) => `${l.type === 'add' ? '+' : l.type === 'del' ? '-' : ' '} ${l.text}`) + .join('\n'); + const applyBtn = el( + 'button', + { type: 'button', class: 'btn btn-sm btn-primary mutating-action' }, + `Apply to ${res.targetPath}`, + ); + applyBtn.addEventListener('click', async () => { + const ok = await confirmDialog( + 'dialog-confirm', + `Apply validated AI draft to "${res.targetPath}"?`, + ); + if (!ok) return; + await apiFetch('/api/config/file', { + method: 'PUT', + body: { + path: res.targetPath, + content: res.normalizedJson, + summary: `Applied AI ${res.kind} draft`, + }, + }); + await opts.onApplied?.(); + if (dialog.open) dialog.close(); + }); + + draftOutputBox.append( + el('div', { class: 'row-between' }, el('span', { class: 'badge badge-ok' }, `[VALID] -> ${res.targetPath}`), applyBtn), + el('pre', { class: 'diff-body mono', style: 'max-height:180px' }, diffPreview), + ); + } catch (err) { + draftOutputBox.replaceChildren(el('p', { class: 'err-text' }, extractErrorMessage(err))); + } + }); + btnRow.append(draftKindSel, validateBtn); + } + + draftBar.append(btnRow, draftOutputBox); + }; + + unsubWs = opts.wsClient.onFrame((frame: ServerWsFrame) => { + if (frame.type !== 'ai:delta' || frame.chatId !== activeChatId) return; + if (frame.chunk) { + currentReply += frame.chunk; + appendBoundedStreamText(streamPre, frame.chunk); + streamPre.scrollTop = streamPre.scrollHeight; + } + if (frame.error) { + statusLine.className = 'form-msg err-text'; + statusLine.textContent = frame.error; + } + if (frame.done) { + if (currentReply) history.push({ role: 'assistant', content: currentReply }); + appendBoundedStreamText(streamPre, '\n'); + activeChatId = null; + sendBtn.disabled = false; + stopBtn.disabled = true; + if (!frame.error) { + statusLine.className = 'form-msg ok-text'; + statusLine.textContent = 'Response complete. Review any extracted draft below.'; + } + refreshDraftActions(); + } + }); + + stopBtn.addEventListener('click', async () => { + if (!activeChatId) return; + const cid = activeChatId; + opts.wsClient.send({ type: 'ai:cancel', chatId: cid }); + await apiFetch(`/api/ai/chat/${encodeURIComponent(cid)}/cancel`, { method: 'POST' }).catch( + () => undefined, + ); + stopBtn.disabled = true; + statusLine.textContent = 'Cancelling...'; + }); + + const form = el( + 'form', + { class: 'stack', style: 'margin-top:4px' }, + promptArea, + el( + 'div', + { class: 'row-between' }, + statusLine, + el('div', { class: 'row' }, stopBtn, sendBtn), + ), + ); + + form.addEventListener('submit', async (ev) => { + ev.preventDefault(); + const prompt = promptArea.value.trim(); + if (!prompt || activeChatId) return; + promptArea.value = ''; + history.push({ role: 'user', content: prompt }); + appendBoundedStreamText(streamPre, `\n> ${prompt}\n\n`); + currentReply = ''; + draftBar.hidden = true; + sendBtn.disabled = true; + stopBtn.disabled = false; + statusLine.className = 'form-msg muted'; + statusLine.textContent = 'Streaming response...'; + + try { + const started = await apiFetch<{ + chatId: string; + redactedCount: number; + truncated: boolean; + }>('/api/ai/chat', { + method: 'POST', + body: { + surface: opts.surface, + messages: history.slice(-12), + contextText: opts.contextText, + serverId: opts.serverId, + targetPath: opts.targetPath, + }, + }); + activeChatId = started.chatId; + opts.wsClient.subscribe([`ai:${started.chatId}`]); + } catch (err) { + history.pop(); + sendBtn.disabled = false; + stopBtn.disabled = true; + statusLine.className = 'form-msg err-text'; + statusLine.textContent = extractErrorMessage(err); + } + }); + + dialog.append( + el('div', { class: 'row-between' }, titleEl, closeBtn), + previewDetails, + streamPre, + draftBar, + form, + ); + document.body.append(dialog); + dialog.showModal(); + + try { + const preview = await apiFetch('/api/ai/context-preview', { + method: 'POST', + body: { + surface: opts.surface, + contextText: opts.contextText, + serverId: opts.serverId, + targetPath: opts.targetPath, + }, + }); + if (!opts.defaultDraftKind && preview.defaultDraftKind) { + draftKindSel.value = preview.defaultDraftKind; + } + previewSummary.textContent = `Sanitized Context Preview (${preview.redactedCount} redacted${preview.truncated ? ', truncated' : ''}) — model: ${preview.model}`; + previewPre.textContent = [ + preview.systemPrompt, + '', + 'INVENTORY:', + preview.inventorySummary, + ...(preview.sanitizedContext ? ['', 'CONTEXT:', preview.sanitizedContext] : []), + ].join('\n'); + if (!preview.enabled) { + statusLine.className = 'form-msg warn-text'; + statusLine.textContent = 'AI Assistant is currently disabled in Settings -> AI Assistant.'; + } + } catch (err) { + previewSummary.textContent = `Context preview unavailable: ${extractErrorMessage(err)}`; + } +} diff --git a/src/client/ts/views/alerts-view.ts b/src/client/ts/views/alerts-view.ts index 90cbec1..9014748 100644 --- a/src/client/ts/views/alerts-view.ts +++ b/src/client/ts/views/alerts-view.ts @@ -1,6 +1,13 @@ import { apiFetch } from '../api.js'; import { confirmDialog } from '../dialogs.js'; -import { el, extractErrorMessage, fmtTime, type ClientState } from '../state.js'; +import { + el, + extractErrorMessage, + fmtTime, + isAiEnabled, + type ClientState, +} from '../state.js'; +import type { MultiplexWsClient } from '../ws-client.js'; interface AlertChannelItem { id: string; @@ -87,6 +94,7 @@ interface AlertsPayload { export async function renderAlertsView( root: HTMLElement, state: ClientState, + wsClient: MultiplexWsClient, ): Promise { root.replaceChildren(); const [data, credsRes] = await Promise.all([ @@ -101,15 +109,33 @@ export async function renderAlertsView( const refreshBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Refresh'); refreshBtn.addEventListener('click', () => { - void renderAlertsView(root, state); + void renderAlertsView(root, state, wsClient); }); + const aiHelpBtn = isAiEnabled(state) + ? el('button', { type: 'button', class: 'btn btn-sm' }, '[AI Setup Helper]') + : null; + if (aiHelpBtn) { + aiHelpBtn.addEventListener('click', async () => { + const { openAiAssistantDrawer } = await import('./ai-drawer.js'); + await openAiAssistantDrawer({ + state, + wsClient, + surface: 'setup', + title: 'AI Alert Rules & Channels Helper', + contextText: JSON.stringify(cfg, null, 2), + targetPath: 'alerts.json', + defaultDraftKind: 'alerts', + onApplied: () => renderAlertsView(root, state, wsClient), + }); + }); + } root.append( el( 'section', { class: 'panel row-between' }, el('div', {}, el('h1', {}, `Alerting & Webhooks (${data.activeCount} firing)`), el('p', { class: 'muted' }, `${cfg.rules.length} rules, ${cfg.channels.length} channels, ${cfg.maintenanceWindows.length} maintenance windows, ${data.silences.length} active silences.`)), - refreshBtn, + el('div', { class: 'row' }, ...(aiHelpBtn ? [aiHelpBtn] : []), refreshBtn), ), ); @@ -133,15 +159,31 @@ export async function renderAlertsView( method: 'POST', body: { scopeType, targetId, durationMinutes, reason: `Quick snooze from ${evt.id}` }, }); - await renderAlertsView(root, state); + await renderAlertsView(root, state, wsClient); }); return b; }); + const diagBtn = isAiEnabled(state) + ? el('button', { type: 'button', class: 'btn btn-sm' }, '[AI Diagnose]') + : null; + if (diagBtn) { + diagBtn.addEventListener('click', async () => { + const { openAiAssistantDrawer } = await import('./ai-drawer.js'); + await openAiAssistantDrawer({ + state, + wsClient, + surface: 'logs', + title: `AI Alert Debugger (${evt.ruleId})`, + contextText: `Alert ${evt.id} (${evt.severity})\nRule: ${evt.ruleId}\nServer: ${evt.serverId ?? 'hub'}\nMessage: ${evt.message}\nWebhook: ${evt.webhookStatus ?? 'none'}`, + serverId: evt.serverId ?? undefined, + }); + }); + } firingPanel.append( el( 'div', { class: 'alert-box' }, - el('div', { class: 'row-between' }, el('strong', { class: evt.severity === 'critical' ? 'err-text' : 'warn-text' }, `[${evt.severity.toUpperCase()}] ${evt.ruleId}${evt.serverId ? ` @ ${evt.serverId}` : ''}`), el('div', { class: 'row' }, ...snoozeButtons)), + el('div', { class: 'row-between' }, el('strong', { class: evt.severity === 'critical' ? 'err-text' : 'warn-text' }, `[${evt.severity.toUpperCase()}] ${evt.ruleId}${evt.serverId ? ` @ ${evt.serverId}` : ''}`), el('div', { class: 'row' }, ...snoozeButtons, ...(diagBtn ? [diagBtn] : []))), el('div', { class: 'mono' }, evt.message), el('div', { class: 'mono muted' }, `Fired: ${fmtTime(evt.triggeredAt)} | Webhook: ${evt.webhookStatus ?? 'none'}`), ), @@ -184,7 +226,7 @@ export async function renderAlertsView( reason: silReason.value.trim() || undefined, }, }); - await renderAlertsView(root, state); + await renderAlertsView(root, state, wsClient); }); silPanel.append(silForm); @@ -192,7 +234,7 @@ export async function renderAlertsView( const unmuteBtn = el('button', { type: 'button', class: 'btn btn-sm btn-danger mutating-action' }, 'Remove'); unmuteBtn.addEventListener('click', async () => { await apiFetch(`/api/alerts/silences/${encodeURIComponent(s.id)}`, { method: 'DELETE' }); - await renderAlertsView(root, state); + await renderAlertsView(root, state, wsClient); }); silPanel.append( el('div', { class: 'row-between panel' }, el('span', { class: 'mono' }, `[${s.scopeType}:${s.targetId}] expires ${fmtTime(s.expiresAt)}${s.reason ? ` — ${s.reason}` : ''}`), unmuteBtn), @@ -203,7 +245,7 @@ export async function renderAlertsView( silPanel.append(el('h2', { style: 'margin-top:12px' }, `Scheduled Maintenance Windows (${cfg.maintenanceWindows.length})`)); const saveConfig = async (nextCfg: AlertsPayload['alertsConfig']) => { await apiFetch('/api/alerts/config', { method: 'PUT', body: nextCfg }); - await renderAlertsView(root, state); + await renderAlertsView(root, state, wsClient); }; for (const w of cfg.maintenanceWindows) { diff --git a/src/client/ts/views/config-view.ts b/src/client/ts/views/config-view.ts index 6df092d..6bc070f 100644 --- a/src/client/ts/views/config-view.ts +++ b/src/client/ts/views/config-view.ts @@ -1,6 +1,14 @@ import { apiFetch, type ApiError } from '../api.js'; import { confirmDialog, openDiffModal } from '../dialogs.js'; -import { el, extractErrorMessage, fmtTime, type ConfigOverview } from '../state.js'; +import { + el, + extractErrorMessage, + fmtTime, + isAiEnabled, + type ClientState, + type ConfigOverview, +} from '../state.js'; +import type { MultiplexWsClient } from '../ws-client.js'; interface FileDetails { filePath: string; @@ -82,6 +90,8 @@ let selectedPath = 'settings.json'; export async function renderConfigView( root: HTMLElement, overview: ConfigOverview, + state: ClientState, + wsClient: MultiplexWsClient, onReloadOverview: () => Promise, ): Promise { root.replaceChildren(); @@ -158,7 +168,7 @@ export async function renderConfigView( ); btn.addEventListener('click', () => { selectedPath = f.filePath; - void renderConfigView(root, overview, onReloadOverview); + void renderConfigView(root, overview, state, wsClient, onReloadOverview); }); fileList.append(el('li', {}, btn)); } @@ -249,6 +259,42 @@ export async function renderConfigView( }); const actionRow = el('div', { class: 'row' }, fmtBtn, saveBtn); + if (isAiEnabled(state)) { + const aiBtn = el('button', { type: 'button', class: 'btn btn-sm' }, '[AI Assist]'); + aiBtn.addEventListener('click', async () => { + const surface = details.filePath.startsWith('workflows/') + ? 'workflows' + : details.filePath.startsWith('systems/') + ? 'systems' + : details.filePath === 'snippets.json' + ? 'snippets' + : 'setup'; + const defaultDraftKind = + surface === 'workflows' + ? 'workflow' + : surface === 'systems' + ? 'system' + : surface === 'snippets' + ? 'snippet' + : details.filePath.startsWith('servers/') + ? 'server' + : details.filePath === 'alerts.json' + ? 'alerts' + : 'settings'; + const { openAiAssistantDrawer } = await import('./ai-drawer.js'); + await openAiAssistantDrawer({ + state, + wsClient, + surface, + title: `AI Assist: ${details.filePath}`, + contextText: editor.value, + targetPath: details.filePath, + defaultDraftKind, + onApplied: onReloadOverview, + }); + }); + actionRow.append(aiBtn); + } if (details.filePath.includes('/')) { const delBtn = el( 'button', diff --git a/src/client/ts/views/settings-view.ts b/src/client/ts/views/settings-view.ts index 9176402..4830224 100644 --- a/src/client/ts/views/settings-view.ts +++ b/src/client/ts/views/settings-view.ts @@ -55,10 +55,13 @@ export async function renderSettingsView( ): Promise { root.replaceChildren(); - const [sessRes, auditRes, factorsRes] = await Promise.all([ + const [sessRes, auditRes, factorsRes, credsRes] = await Promise.all([ apiFetch<{ sessions: SessionRow[] }>('/api/auth/sessions'), apiFetch<{ total: number; items: AuditRow[] }>('/api/audit?limit=40'), apiFetch('/api/auth/factors'), + apiFetch<{ credentials: Array<{ id: string; name: string; type: string }> }>( + '/api/vault/credentials', + ).catch(() => ({ credentials: [] })), ]); const sec = factorsRes.security; @@ -318,6 +321,234 @@ export async function renderSettingsView( ); root.append(policyPanel); + // 2b. Optional BYO-API AI Assistant (Strictly Opt-In) + const rawAi = (state.overview?.settings?.ai ?? {}) as { + enabled?: boolean; + baseUrl?: string; + model?: string; + secretRef?: string; + maxContextChars?: number; + }; + const aiPanel = el('section', { class: 'panel panel-region' }); + aiPanel.append( + el('h2', {}, 'Optional BYO-API AI Assistant'), + el( + 'p', + { class: 'muted' }, + 'Strictly opt-in. Uses any OpenAI-compatible v1 endpoint (Ollama, llama.cpp, vLLM, or cloud) with secret redaction and manual Apply confirmation.', + ), + ); + const aiEnabledChk = el('input', { type: 'checkbox', checked: rawAi.enabled ? true : undefined }); + const aiBaseUrlInp = el('input', { + value: rawAi.baseUrl ?? 'http://127.0.0.1:11434', + placeholder: 'http://127.0.0.1:11434', + }); + const aiModelInp = el('input', { + value: rawAi.model ?? 'qwen2.5-coder:7b', + placeholder: 'qwen2.5-coder:7b', + }); + const aiSecretSel = el( + 'select', + {}, + el('option', { value: '' }, '(None — local unauthenticated LLM)'), + ...credsRes.credentials.map((c) => + el( + 'option', + { value: c.id, selected: rawAi.secretRef === c.id ? true : undefined }, + `${c.id} (${c.type})`, + ), + ), + ); + const aiMaxCtxInp = el('input', { + type: 'number', + min: 1000, + max: 128000, + value: String(rawAi.maxContextChars ?? 16000), + }); + const aiMsg = el('p', { class: 'form-msg' }); + const aiTestBtn = el('button', { type: 'button', class: 'btn btn-sm mutating-action' }, 'Test AI Endpoint'); + aiTestBtn.addEventListener('click', async () => { + aiMsg.className = 'form-msg muted'; + aiMsg.textContent = 'Testing AI endpoint...'; + try { + const r = await apiFetch<{ ok: boolean; latencyMs: number; replyPreview?: string; error?: string }>( + '/api/ai/test', + { + method: 'POST', + body: { + baseUrl: aiBaseUrlInp.value.trim(), + model: aiModelInp.value.trim(), + secretRef: aiSecretSel.value, + }, + }, + ); + aiMsg.className = r.ok ? 'form-msg ok-text' : 'form-msg err-text'; + aiMsg.textContent = r.ok + ? `Connected (${r.latencyMs}ms): ${r.replyPreview ?? 'OK'}` + : `Endpoint test failed (${r.latencyMs}ms): ${r.error ?? 'error'}`; + } catch (err) { + aiMsg.className = 'form-msg err-text'; + aiMsg.textContent = extractErrorMessage(err); + } + }); + const aiSaveBtn = el('button', { type: 'button', class: 'btn btn-primary btn-sm mutating-action' }, 'Save AI Settings'); + aiSaveBtn.addEventListener('click', async () => { + aiMsg.textContent = ''; + try { + const nextSettings = { + ...(state.overview?.settings ?? {}), + ai: { + enabled: aiEnabledChk.checked, + baseUrl: aiBaseUrlInp.value.trim(), + model: aiModelInp.value.trim(), + ...(aiSecretSel.value ? { secretRef: aiSecretSel.value } : {}), + maxContextChars: Number(aiMaxCtxInp.value || 16000), + }, + }; + await apiFetch('/api/config/file', { + method: 'PUT', + body: { + path: 'settings.json', + content: `${JSON.stringify(nextSettings, null, 2)}\n`, + summary: `AI Assistant -> ${aiEnabledChk.checked ? 'enabled' : 'disabled'}`, + }, + }); + await onReloadState(); + } catch (err) { + aiMsg.className = 'form-msg err-text'; + aiMsg.textContent = extractErrorMessage(err); + } + }); + aiPanel.append( + el('label', { class: 'chk-row' }, aiEnabledChk, 'Enable AI Assistant Drawer Across UI Surfaces'), + el( + 'div', + { class: 'grid-2', style: 'margin-top:8px' }, + el('div', {}, el('label', {}, 'OpenAI-Compatible Base URL'), aiBaseUrlInp), + el('div', {}, el('label', {}, 'Model Name'), aiModelInp), + el('div', {}, el('label', {}, 'API Key Credential (Optional)'), aiSecretSel), + el('div', {}, el('label', {}, 'Max Context Chars'), aiMaxCtxInp), + ), + el('div', { class: 'row', style: 'margin-top:8px' }, aiTestBtn, aiSaveBtn), + aiMsg, + ); + root.append(aiPanel); + + // 2c. Portable Encrypted Backup (.gcoord.enc) + const portableBackupPanel = el('section', { class: 'panel panel-region' }); + portableBackupPanel.append( + el('h2', {}, 'Portable Encrypted Backup (.gcoord.enc)'), + el( + 'p', + { class: 'muted' }, + 'Package /data/config, vault.enc, known_hosts, and active silences into a single AES-256-GCM authenticated bundle.', + ), + ); + const expPassInp = el('input', { + type: 'password', + placeholder: 'Optional backup passphrase (blank = Vault master key)', + }); + const expBtn = el('button', { type: 'button', class: 'btn btn-primary btn-sm mutating-action' }, 'Export .gcoord.enc'); + const backupMsg = el('p', { class: 'form-msg' }); + expBtn.addEventListener('click', async () => { + backupMsg.className = 'form-msg muted'; + backupMsg.textContent = 'Generating encrypted bundle...'; + try { + const res = await apiFetch<{ + filename: string; + bundleBase64: string; + summary: { configFileCount: number; knownHostsCount: number; kdf: string }; + }>('/api/backup/export', { + method: 'POST', + body: { passphrase: expPassInp.value || undefined }, + }); + const bin = Uint8Array.from(atob(res.bundleBase64), (ch) => ch.charCodeAt(0)); + const url = URL.createObjectURL(new Blob([bin], { type: 'application/json' })); + const a = document.createElement('a'); + a.href = url; + a.download = res.filename; + a.click(); + URL.revokeObjectURL(url); + backupMsg.className = 'form-msg ok-text'; + backupMsg.textContent = `Downloaded ${res.filename} (${res.summary.configFileCount} configs, ${res.summary.knownHostsCount} known_hosts, kdf=${res.summary.kdf}).`; + } catch (err) { + backupMsg.className = 'form-msg err-text'; + backupMsg.textContent = extractErrorMessage(err); + } + }); + + const impFileInp = el('input', { type: 'file', accept: '.enc,.json,application/json' }); + const impPassInp = el('input', { + type: 'password', + placeholder: 'Passphrase or Master Key (if not runtime-ready)', + }); + const readSelectedBase64 = async (): Promise => { + const file = impFileInp.files?.[0]; + if (!file) throw new Error('Select a .gcoord.enc file first'); + const bytes = new Uint8Array(await file.arrayBuffer()); + let bin = ''; + for (let i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i]!); + return btoa(bin); + }; + const verifyImpBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Verify Bundle'); + verifyImpBtn.addEventListener('click', async () => { + backupMsg.className = 'form-msg muted'; + backupMsg.textContent = 'Verifying bundle integrity...'; + try { + const bundleBase64 = await readSelectedBase64(); + const raw = impPassInp.value.trim(); + const isHexKey = /^[0-9a-fA-F]{64}$/.test(raw); + const res = await apiFetch<{ summary: Record }>('/api/backup/verify', { + method: 'POST', + body: { + bundleBase64, + ...(raw ? (isHexKey ? { masterKey: raw } : { passphrase: raw }) : {}), + }, + }); + backupMsg.className = 'form-msg ok-text'; + backupMsg.textContent = `Verified cleanly: ${JSON.stringify(res.summary)}`; + } catch (err) { + backupMsg.className = 'form-msg err-text'; + backupMsg.textContent = extractErrorMessage(err); + } + }); + const restoreImpBtn = el('button', { type: 'button', class: 'btn btn-danger btn-sm mutating-action' }, 'Restore Bundle'); + restoreImpBtn.addEventListener('click', async () => { + try { + const bundleBase64 = await readSelectedBase64(); + const ok = await confirmDialog( + 'dialog-confirm', + 'Atomically replace /data/config, vault.enc, and known_hosts from this backup bundle?', + ); + if (!ok) return; + const raw = impPassInp.value.trim(); + const isHexKey = /^[0-9a-fA-F]{64}$/.test(raw); + const res = await apiFetch<{ summary: { configFileCount: number; knownHostsCount: number } }>( + '/api/backup/restore', + { + method: 'POST', + body: { + bundleBase64, + ...(raw ? (isHexKey ? { masterKey: raw } : { passphrase: raw }) : {}), + }, + }, + ); + backupMsg.className = 'form-msg ok-text'; + backupMsg.textContent = `Restored ${res.summary.configFileCount} configs & ${res.summary.knownHostsCount} known_hosts.`; + await onReloadState(); + } catch (err) { + backupMsg.className = 'form-msg err-text'; + backupMsg.textContent = extractErrorMessage(err); + } + }); + portableBackupPanel.append( + el('div', { class: 'grid-2' }, el('div', {}, el('label', {}, 'Export Passphrase (Optional)'), expPassInp), el('div', { style: 'align-self:end' }, expBtn)), + el('div', { class: 'grid-2', style: 'margin-top:8px' }, el('div', {}, el('label', {}, 'Verify / Restore .gcoord.enc File'), impFileInp), el('div', {}, el('label', {}, 'Backup Passphrase / 64-Hex Master Key'), impPassInp)), + el('div', { class: 'row', style: 'margin-top:8px' }, verifyImpBtn, restoreImpBtn), + backupMsg, + ); + root.append(portableBackupPanel); + // 3. Multi-Password & Multi-TOTP Factor Management const factorsGrid = el('div', { class: 'grid-2' }); diff --git a/src/client/ts/views/systems-view.ts b/src/client/ts/views/systems-view.ts index a6d813d..a24300b 100644 --- a/src/client/ts/views/systems-view.ts +++ b/src/client/ts/views/systems-view.ts @@ -1,7 +1,15 @@ import type { ServerWsFrame } from '../../../shared/ws-protocol.js'; import { apiFetch } from '../api.js'; import { confirmDialog } from '../dialogs.js'; -import { appendBoundedStreamText, el, extractErrorMessage, fmtTime, type ClientState, type ServerEntry } from '../state.js'; +import { + appendBoundedStreamText, + el, + extractErrorMessage, + fmtTime, + isAiEnabled, + type ClientState, + type ServerEntry, +} from '../state.js'; import type { MultiplexWsClient } from '../ws-client.js'; interface SystemActionDef { @@ -156,6 +164,7 @@ async function openAttachModal( } async function runSystemAction(opts: { + state: ClientState; systemId: string; serverId: string; action: SystemActionDef; @@ -198,12 +207,34 @@ async function runSystemAction(opts: { } if (res.mode === 'oneshot') { + const outText = [res.stdout, res.stderr].filter(Boolean).join('\n') || '(no output)'; + const debugBtn = isAiEnabled(opts.state) + ? el('button', { type: 'button', class: 'btn btn-sm' }, '[AI Debug Output]') + : null; + if (debugBtn) { + debugBtn.addEventListener('click', async () => { + const { openAiAssistantDrawer } = await import('./ai-drawer.js'); + await openAiAssistantDrawer({ + state: opts.state, + wsClient: opts.wsClient, + surface: 'logs', + title: `AI Debug (${opts.systemId}: ${action.label})`, + contextText: `Exit code: ${String(res.exitCode)}\n\n${outText}`, + serverId: opts.serverId, + }); + }); + } opts.outputHost.replaceChildren( el( 'div', { class: 'panel' }, - el('div', { class: 'row-between' }, el('strong', {}, `${action.label} finished (exit ${String(res.exitCode)}, ${res.durationMs}ms)`)), - el('pre', { class: 'stream-log mono' }, [res.stdout, res.stderr].filter(Boolean).join('\n') || '(no output)'), + el( + 'div', + { class: 'row-between' }, + el('strong', {}, `${action.label} finished (exit ${String(res.exitCode)}, ${res.durationMs}ms)`), + ...(debugBtn ? [debugBtn] : []), + ), + el('pre', { class: 'stream-log mono' }, outText), ), ); await opts.onFinished(); @@ -222,12 +253,33 @@ async function runSystemAction(opts: { await apiFetch(`/api/systems/streams/${encodeURIComponent(res.jobId)}/cancel`, { method: 'POST' }); stopBtn.disabled = true; }); + const streamAiBtn = isAiEnabled(opts.state) + ? el('button', { type: 'button', class: 'btn btn-sm' }, '[AI Debug Output]') + : null; + if (streamAiBtn) { + streamAiBtn.addEventListener('click', async () => { + const { openAiAssistantDrawer } = await import('./ai-drawer.js'); + await openAiAssistantDrawer({ + state: opts.state, + wsClient: opts.wsClient, + surface: 'logs', + title: `AI Debug (${opts.systemId}: ${action.label})`, + contextText: logPre.textContent ?? '', + serverId: opts.serverId, + }); + }); + } opts.outputHost.replaceChildren( el( 'div', { class: 'panel' }, - el('div', { class: 'row-between' }, el('strong', {}, `Live Stream: ${action.label} (${res.jobId})`), stopBtn), + el( + 'div', + { class: 'row-between' }, + el('strong', {}, `Live Stream: ${action.label} (${res.jobId})`), + el('div', { class: 'row' }, ...(streamAiBtn ? [streamAiBtn] : []), stopBtn), + ), logPre, ), ); @@ -276,12 +328,29 @@ export async function renderSystemsView( }>; }>('/api/systems'); + const aiSysBtn = isAiEnabled(state) + ? el('button', { type: 'button', class: 'btn btn-sm' }, '[AI Author System]') + : null; + if (aiSysBtn) { + aiSysBtn.addEventListener('click', async () => { + const { openAiAssistantDrawer } = await import('./ai-drawer.js'); + await openAiAssistantDrawer({ + state, + wsClient, + surface: 'systems', + title: 'AI Custom System Author', + defaultDraftKind: 'system', + onApplied: () => renderSystemsView(root, state, wsClient), + }); + }); + } + root.append( el( 'section', { class: 'panel row-between' }, el('div', {}, el('h1', {}, 'Custom Systems Engine'), el('p', { class: 'muted' }, 'Declarative service managers defined in /data/config/systems/*.json')), - el('a', { href: '#config', class: 'btn btn-sm' }, 'Edit System JSONs'), + el('div', { class: 'row' }, ...(aiSysBtn ? [aiSysBtn] : []), el('a', { href: '#config', class: 'btn btn-sm' }, 'Edit System JSONs')), ), ); @@ -350,6 +419,7 @@ export async function renderSystemsView( ); btn.addEventListener('click', () => { void runSystemAction({ + state, systemId, serverId: targetServerId, action: act, @@ -466,6 +536,7 @@ export async function renderSystemsView( const btn = el('button', { type: 'button', class: 'btn btn-sm mutating-action' }, act.label); btn.addEventListener('click', () => { void runSystemAction({ + state, systemId, serverId: targetServerId, action: act, @@ -743,6 +814,7 @@ export async function renderSystemsView( ); btn.addEventListener('click', () => { void runSystemAction({ + state, systemId, serverId: snap.serverId, action: act, @@ -796,6 +868,7 @@ export async function renderSystemsView( const b = el('button', { type: 'button', class: 'btn btn-sm mutating-action' }, act.label); b.addEventListener('click', () => { void runSystemAction({ + state, systemId, serverId: snap.serverId, action: act, diff --git a/src/client/ts/views/terminal-view.ts b/src/client/ts/views/terminal-view.ts index 0c747f4..3bf01db 100644 --- a/src/client/ts/views/terminal-view.ts +++ b/src/client/ts/views/terminal-view.ts @@ -3,7 +3,7 @@ import type { FitAddon } from '@xterm/addon-fit'; import type { ServerWsFrame } from '../../../shared/ws-protocol.js'; import { apiFetch } from '../api.js'; import { confirmDialog } from '../dialogs.js'; -import { el, extractErrorMessage, fmtTime, type ClientState, type ServerEntry } from '../state.js'; +import { el, extractErrorMessage, fmtTime, isAiEnabled, type ClientState, type ServerEntry } from '../state.js'; import type { MultiplexWsClient } from '../ws-client.js'; import { clearTerminalComposition, @@ -349,6 +349,39 @@ export async function renderTerminalView( const fontPlusBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'A+'); const fitBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Fit'); const snippetsBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Snippets'); + const aiTermBtn = isAiEnabled(state) + ? el('button', { type: 'button', class: 'btn btn-sm' }, '[AI Helper]') + : null; + if (aiTermBtn) { + aiTermBtn.addEventListener('click', async () => { + let scrollbackTail = ''; + try { + const res = await fetch( + `/api/terminal/sessions/${encodeURIComponent(current.sessionId)}/export?format=plain`, + { credentials: 'same-origin' }, + ); + if (res.ok) { + scrollbackTail = (await res.text()).slice(-4000); + } + } catch { + // Ignore export errors + } + const { openAiAssistantDrawer } = await import('./ai-drawer.js'); + await openAiAssistantDrawer({ + state, + wsClient, + surface: 'snippets', + title: `AI Terminal Helper (${current.serverId})`, + contextText: scrollbackTail, + serverId: current.serverId, + defaultDraftKind: 'snippet', + onInsertTerminalText: (cmd) => { + sendPtyInput(cmd.replace(/[\r\n]+/g, ' ')); + term?.focus(); + }, + }); + }); + } const closeTabBtn = el( 'button', { type: 'button', class: 'btn btn-sm btn-danger mutating-action' }, @@ -457,7 +490,7 @@ export async function renderTerminalView( { class: 'mono muted' }, `${current.title} | ${current.cols}x${current.rows} | opened ${fmtTime(current.createdAt)}`, ), - el('div', { class: 'row' }, fontMinusBtn, fontPlusBtn, fitBtn, snippetsBtn, exportPlainBtn, exportAnsiBtn, closeTabBtn), + el('div', { class: 'row' }, fontMinusBtn, fontPlusBtn, fitBtn, snippetsBtn, ...(aiTermBtn ? [aiTermBtn] : []), exportPlainBtn, exportAnsiBtn, closeTabBtn), ), el('div', { class: 'term-shell' }, termContainer, touchBar), ), diff --git a/src/client/ts/views/workflows-view.ts b/src/client/ts/views/workflows-view.ts index 45d6435..83a4b30 100644 --- a/src/client/ts/views/workflows-view.ts +++ b/src/client/ts/views/workflows-view.ts @@ -6,6 +6,7 @@ import { el, extractErrorMessage, fmtTime, + isAiEnabled, type ClientState, type ServerEntry, } from '../state.js'; @@ -737,9 +738,25 @@ export async function renderWorkflowsView( refBtn.addEventListener('click', () => { void renderWorkflowsView(root, state, wsClient); }); + const aiWfBtn = isAiEnabled(state) + ? el('button', { type: 'button', class: 'btn btn-sm' }, '[AI Draft Workflow]') + : null; + if (aiWfBtn) { + aiWfBtn.addEventListener('click', async () => { + const { openAiAssistantDrawer } = await import('./ai-drawer.js'); + await openAiAssistantDrawer({ + state, + wsClient, + surface: 'workflows', + title: 'AI Workflow DAG Drafter', + defaultDraftKind: 'workflow', + onApplied: () => renderWorkflowsView(root, state, wsClient), + }); + }); + } const wfSection = el('section', { class: 'panel panel-region' }); - wfSection.append(el('div', { class: 'row-between' }, el('h2', {}, `Configured Workflows (${wfRes.workflows.length})`), el('div', { class: 'row' }, newBtn, refBtn))); + wfSection.append(el('div', { class: 'row-between' }, el('h2', {}, `Configured Workflows (${wfRes.workflows.length})`), el('div', { class: 'row' }, newBtn, ...(aiWfBtn ? [aiWfBtn] : []), refBtn))); const watchRunStream = (runId: string, wfId: string) => { streamPanel.hidden = false; @@ -785,6 +802,31 @@ export async function renderWorkflowsView( }>(`/api/workflows/runs/${encodeURIComponent(runId)}`); detailPanel.hidden = false; renderStructuredOutput(detailPanel, res.workflow, res.run, res.stepLogs); + if (isAiEnabled(state)) { + const diagBtn = el( + 'button', + { type: 'button', class: 'btn btn-sm', style: 'margin-top:8px' }, + '[AI Diagnose Run]', + ); + diagBtn.addEventListener('click', async () => { + const logText = res.stepLogs + .map( + (l) => + `[${l.stepId}@${l.serverId} exit=${String(l.exitCode)} ${l.durationMs}ms]\n${l.stdout}${l.stderr ? `\nSTDERR:\n${l.stderr}` : ''}`, + ) + .join('\n\n'); + const { openAiAssistantDrawer } = await import('./ai-drawer.js'); + await openAiAssistantDrawer({ + state, + wsClient, + surface: 'logs', + title: `AI Log Debugger (${runId})`, + contextText: `Workflow: ${res.run.workflowId} (${res.run.status})\n\n${logText}`, + serverId: res.stepLogs[0]?.serverId.split(':')[0], + }); + }); + detailPanel.append(diagBtn); + } }; if (wfRes.workflows.length === 0) { @@ -1111,7 +1153,25 @@ export async function renderWorkflowsView( // Command Snippets tab const listPanel = el('section', { class: 'panel panel-region' }); - listPanel.append(el('h2', {}, `Saved Command Snippets (${snippets.length})`)); + const aiSnipBtn = isAiEnabled(state) + ? el('button', { type: 'button', class: 'btn btn-sm' }, '[AI Draft Snippet]') + : null; + if (aiSnipBtn) { + aiSnipBtn.addEventListener('click', async () => { + const { openAiAssistantDrawer } = await import('./ai-drawer.js'); + await openAiAssistantDrawer({ + state, + wsClient, + surface: 'snippets', + title: 'AI Snippet Generator', + defaultDraftKind: 'snippet', + onApplied: () => renderWorkflowsView(root, state, wsClient), + }); + }); + } + listPanel.append( + el('div', { class: 'row-between' }, el('h2', {}, `Saved Command Snippets (${snippets.length})`), ...(aiSnipBtn ? [aiSnipBtn] : [])), + ); const sTbl = el('table'); sTbl.append(el('thead', {}, el('tr', {}, el('th', {}, 'ID'), el('th', {}, 'Name'), el('th', {}, 'Command'), el('th', {}, 'Flags'), el('th', {}, 'Actions')))); const sBody = el('tbody');