Skip to content

an open-source alternative to the dots, bots and muses of the world, run an office of claude code/codex like agents on your laptop, sandboxes or anywhere, uses your existing subscriptions

feat(settings): conform integrations UI to registry spec v1 (Jim §1/§6)

Chaitanya Giri23ce74649cd3
diff --git a/src/renderer/src/components/IntegrationsRegistry.tsx b/src/renderer/src/components/IntegrationsRegistry.tsx
index 46e28b3c..932464ca 100644
--- a/src/renderer/src/components/IntegrationsRegistry.tsx
+++ b/src/renderer/src/components/IntegrationsRegistry.tsx
@@ -1,187 +1,229 @@
import { useEffect, useState, type CSSProperties } from 'react';
+import { authTypeNeedsSecret as needsSecret } from '@shared/integrations';
import { PixelButton } from './PixelButton';
import {
integrationsClient,
- type IntegrationDraft,
- type IntegrationEntry,
- type IntegrationGlyph,
- type IntegrationStatus,
+ slugify,
+ type IntegrationAuthType,
+ type IntegrationKind,
+ type IntegrationRecord,
+ type IntegrationRecordView,
type IntegrationTemplate,
- type IntegrationWorker,
type TestResult
} from '@/integrations/registryClient';
-// Integrations configuration UI. Goal (per dispatch): CLEAN + EASY TO
-// UNDERSTAND. Built against Pam's reference mockup
-// (hive/docs/integrations-ui-mockup.html): a configured-integrations list, a
-// two-step Add flow (pick a template -> configure & test), a write-only masked
-// secret field, and per-row test-connection. The dispatch also requires showing
-// which workers can use an integration, so a worker picker lives in the
-// configure step (the mockup omits it; we adapt).
+// Integrations configuration UI — Settings → Integrations. Conformed to Jim's
+// spec v1 (hive/docs/integrations-spec.md) and styled to Pam's mockup
+// (hive/docs/integrations-ui-mockup.html). Three views: the configured list, a
+// pick-a-template gallery, and a configure-&-test step.
//
-// All data flows through integrationsClient — this component never touches IPC
-// directly, so it is unaffected when that client is wired to Jim's registry.
+// All data flows through integrationsClient — never IPC directly.
+//
+// v1 worker model (Jim §4): the broker grants EVERY enabled integration to ALL
+// workers; there is no per-integration worker scoping yet. So "which workers can
+// use it" is surfaced as the usability gate — usable === enabled && hasSecret —
+// rather than an editable per-integration picker. Per-worker scoping is a future
+// extension; this reflection updates when Jim confirms that model.
type View = 'list' | 'gallery' | 'configure';
-const dispLabel: CSSProperties = {
- fontFamily: 'var(--cth-font-display)', fontSize: 8, lineHeight: '12px',
- color: 'var(--cth-ink-500)', textTransform: 'uppercase'
+interface Draft {
+ isNew: boolean;
+ id: string;
+ label: string;
+ kind: IntegrationKind;
+ baseUrl: string;
+ authType: IntegrationAuthType;
+ authHeader: string;
+ enabled: boolean;
+ hasSecret: boolean; // an existing stored secret (edit)
+ createdAt: number;
+ secret: string; // write-only input buffer
+}
+
+const AUTH_LABEL: Record<IntegrationAuthType, string> = {
+ none: 'None (public API)',
+ bearer: 'Bearer token',
+ header: 'Custom header',
+ github: 'GitHub'
};
+// Auth types a user may pick for a custom-REST integration.
+const CUSTOM_AUTH: IntegrationAuthType[] = ['none', 'bearer', 'header'];
+
+// UI-only brand glyphs (Jim's templates carry no glyph). Falls back to label initials.
+const GLYPH: Record<string, { mono: string; bg: string }> = {
+ github: { mono: 'Gh', bg: '#1A1320' },
+ 'custom-rest': { mono: '{}', bg: '#2E9E5B' }
+};
+function glyphFor(kind: string, label: string): { mono: string; bg: string } {
+ return GLYPH[kind] ?? { mono: (label.replace(/[^A-Za-z0-9]/g, '').slice(0, 2) || '··'), bg: '#6B5878' };
+}
+
+const dispLabel: CSSProperties = { fontFamily: 'var(--cth-font-display)', fontSize: 8, lineHeight: '12px', color: 'var(--cth-ink-500)', textTransform: 'uppercase' };
const fieldLabel: CSSProperties = { ...dispLabel, color: 'var(--cth-ink-700)' };
const subText: CSSProperties = { fontSize: 12, lineHeight: '16px', color: 'var(--cth-ink-500)' };
const hint: CSSProperties = { fontSize: 11, lineHeight: '15px', color: 'var(--cth-ink-500)' };
-const inputStyle: CSSProperties = {
- width: '100%', padding: '6px 8px', background: 'var(--cth-paper-100)', border: 'none',
- boxShadow: 'inset 0 0 0 1px var(--cth-ink-700)', fontSize: 13, lineHeight: '18px', color: 'var(--cth-ink-900)'
-};
-
-const STATUS_META: Record<IntegrationStatus, { dot: string; color: string; text: string }> = {
- ok: { dot: '●', color: 'var(--cth-mint-700, #1f7a4d)', text: 'Connected' },
- error: { dot: '▲', color: 'var(--cth-danger, #6E1423)', text: 'Auth failed' },
- untested: { dot: '○', color: 'var(--cth-ink-500)', text: 'Not tested' }
-};
+const inputStyle: CSSProperties = { width: '100%', padding: '6px 8px', background: 'var(--cth-paper-100)', border: 'none', boxShadow: 'inset 0 0 0 1px var(--cth-ink-700)', fontSize: 13, lineHeight: '18px', color: 'var(--cth-ink-900)' };
+const linkBtn: CSSProperties = { background: 'none', border: 'none', cursor: 'pointer', padding: 0, alignSelf: 'flex-start', fontSize: 12, color: 'var(--cth-ink-500)' };
-function Glyph({ glyph, lg }: { glyph: IntegrationGlyph; lg?: boolean }) {
+function Glyph({ mono, bg, lg }: { mono: string; bg: string; lg?: boolean }) {
const size = lg ? 48 : 40;
return (
- <div style={{
- width: size, height: size, flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'center',
- background: glyph.bg, color: '#fff', boxShadow: 'inset 0 0 0 2px var(--cth-ink-900)',
- fontFamily: 'var(--cth-font-display)', fontSize: lg ? 13 : 11
- }}>{glyph.mono}</div>
+ <div style={{ width: size, height: size, flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', background: bg, color: '#fff', boxShadow: 'inset 0 0 0 2px var(--cth-ink-900)', fontFamily: 'var(--cth-font-display)', fontSize: lg ? 13 : 11 }}>{mono}</div>
);
}
-function blankDraft(templateId: string): IntegrationDraft {
- return { label: '', templateId, fields: {}, secret: '', workers: [] };
+/** Is an integration actually usable by workers? (Jim §6 gate.) */
+function usable(r: { enabled: boolean; authType: IntegrationAuthType; hasSecret: boolean }): boolean {
+ return r.enabled && (!needsSecret(r.authType) || r.hasSecret);
}
-function draftFromEntry(entry: IntegrationEntry): IntegrationDraft {
- // Write-only: secret starts empty and is never pulled back.
- return { id: entry.id, label: entry.label, templateId: entry.templateId, fields: { ...entry.fields }, secret: '', workers: [...entry.workers] };
+
+function draftFromTemplate(t: IntegrationTemplate, now: number): Draft {
+ return {
+ isNew: true, id: slugify(t.idSuggestion || t.label), label: t.label, kind: t.kind,
+ baseUrl: t.baseUrl, authType: t.authType, authHeader: t.authHeader ?? '',
+ enabled: true, hasSecret: false, createdAt: now, secret: ''
+ };
+}
+function draftFromRecord(r: IntegrationRecordView): Draft {
+ return {
+ isNew: false, id: r.id, label: r.label, kind: r.kind, baseUrl: r.baseUrl,
+ authType: r.authType, authHeader: r.authHeader ?? '', enabled: r.enabled,
+ hasSecret: r.hasSecret, createdAt: r.createdAt, secret: ''
+ };
}
export function IntegrationsRegistry() {
const [templates, setTemplates] = useState<IntegrationTemplate[]>([]);
- const [workers, setWorkers] = useState<IntegrationWorker[]>([]);
- const [entries, setEntries] = useState<IntegrationEntry[]>([]);
+ const [records, setRecords] = useState<IntegrationRecordView[]>([]);
const [view, setView] = useState<View>('list');
- const [picked, setPicked] = useState<string>(''); // selected template id in the gallery
- const [draft, setDraft] = useState<IntegrationDraft | null>(null);
- const [replacing, setReplacing] = useState(false); // edit: user chose to swap the saved secret
+ const [picked, setPicked] = useState<string>(''); // selected template idSuggestion in gallery
+ const [draft, setDraft] = useState<Draft | null>(null);
+ const [replacing, setReplacing] = useState(false);
const [showSecret, setShowSecret] = useState(false);
- const [draftTest, setDraftTest] = useState<TestResult | null>(null);
- const [testingDraft, setTestingDraft] = useState(false);
+ const [cfgTest, setCfgTest] = useState<TestResult | null>(null);
+ const [testing, setTesting] = useState(false);
+ const [rowTest, setRowTest] = useState<Record<string, TestResult>>({});
const [testingId, setTestingId] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
+ const [err, setErr] = useState('');
const [note, setNote] = useState('');
const flash = (msg: string) => { setNote(msg); setTimeout(() => setNote(''), 2400); };
- const refresh = async () => setEntries(await integrationsClient.list());
- const templateOf = (id: string) => templates.find((t) => t.id === id);
+ const refresh = async () => setRecords(await integrationsClient.list());
useEffect(() => {
let alive = true;
(async () => {
- const [tpls, wkrs, list] = await Promise.all([
- integrationsClient.listTemplates(), integrationsClient.listWorkers(), integrationsClient.list()
- ]);
+ const [tpls, recs] = await Promise.all([integrationsClient.listTemplates(), integrationsClient.list()]);
if (!alive) return;
- setTemplates(tpls); setWorkers(wkrs); setEntries(list);
+ setTemplates(tpls); setRecords(recs);
})();
return () => { alive = false; };
}, []);
- const editing = draft?.id != null;
- const editEntry = editing ? entries.find((e) => e.id === draft?.id) : undefined;
- const activeTemplate = draft ? templateOf(draft.templateId) : undefined;
- // Show the masked "saved" state only while editing an entry that has a secret
- // and the user hasn't chosen to replace it.
- const showSavedPill = !!(editing && editEntry?.hasSecret && !replacing);
-
- const goList = () => {
- setView('list'); setDraft(null); setPicked(''); setReplacing(false);
- setShowSecret(false); setDraftTest(null);
- };
- const startAdd = () => { setPicked(''); setView('gallery'); };
+ const goList = () => { setView('list'); setDraft(null); setPicked(''); setReplacing(false); setShowSecret(false); setCfgTest(null); setErr(''); };
+ const startAdd = () => { setPicked(''); setErr(''); setView('gallery'); };
const continueFromGallery = () => {
- if (!picked) return;
- setDraft(blankDraft(picked)); setReplacing(false); setShowSecret(false); setDraftTest(null); setView('configure');
+ const t = templates.find((x) => x.idSuggestion === picked);
+ if (!t) return;
+ setDraft(draftFromTemplate(t, Date.now())); setReplacing(false); setShowSecret(false); setCfgTest(null); setErr(''); setView('configure');
};
- const startEdit = (entry: IntegrationEntry) => {
- setDraft(draftFromEntry(entry)); setReplacing(false); setShowSecret(false); setDraftTest(null); setView('configure');
+ const startEdit = (r: IntegrationRecordView) => { setDraft(draftFromRecord(r)); setReplacing(false); setShowSecret(false); setCfgTest(null); setErr(''); setView('configure'); };
+
+ const patch = (p: Partial<Draft>) => setDraft((d) => (d ? { ...d, ...p } : d));
+
+ const validate = (d: Draft): string | null => {
+ if (!d.label.trim()) return 'Give it a label.';
+ if (!slugify(d.id || d.label)) return 'Could not derive a valid id from the label.';
+ if (d.kind === 'custom-rest') {
+ const u = d.baseUrl.trim();
+ if (!u) return 'Base URL is required.';
+ if (!/^https:\/\//.test(u) && !/^http:\/\/(127\.0\.0\.1|localhost|\[::1\])(:\d+)?(\/|$)/.test(u)) return 'Base URL must be https:// (or http://127.0.0.1 / localhost for a local target).';
+ }
+ if (d.authType === 'header' && !/^[A-Za-z0-9-]{1,64}$/.test(d.authHeader.trim())) return 'Header name must be 1–64 chars of A–Z, 0–9, or "-".';
+ return null;
};
- const setField = (key: string, value: string) =>
- setDraft((d) => (d ? { ...d, fields: { ...d.fields, [key]: value } } : d));
- const toggleWorker = (id: string) =>
- setDraft((d) => {
- if (!d) return d;
- const has = d.workers.includes(id);
- return { ...d, workers: has ? d.workers.filter((w) => w !== id) : [...d.workers, id] };
- });
-
- /** Secret to send: only when the user actually typed one (write-only). */
- const draftPayload = (d: IntegrationDraft): IntegrationDraft => ({
- ...d, label: d.label.trim(),
- secret: d.secret && d.secret.length > 0 ? d.secret : undefined
- });
-
- const onTestDraft = async () => {
- if (!draft) return;
- setTestingDraft(true); setDraftTest(null);
- try { setDraftTest(await integrationsClient.testDraft(draftPayload(draft))); }
- catch { setDraftTest({ ok: false, message: 'Test failed to run.' }); }
- finally { setTestingDraft(false); }
+ const recordFromDraft = (d: Draft, now: number): IntegrationRecord => {
+ const id = slugify(d.id || d.label);
+ return {
+ id,
+ label: d.label.trim(),
+ kind: d.kind,
+ baseUrl: d.baseUrl.trim(),
+ authType: d.authType,
+ authHeader: d.authType === 'header' ? d.authHeader.trim() : undefined,
+ secretRef: needsSecret(d.authType) ? `int:${id}` : undefined,
+ enabled: d.enabled,
+ createdAt: d.isNew ? now : d.createdAt,
+ updatedAt: now
+ };
};
+
const onSave = async () => {
if (!draft) return;
- if (!draft.label.trim()) { flash('Give it a label first.'); return; }
- setBusy(true);
+ const v = validate(draft);
+ if (v) { setErr(v); return; }
+ setBusy(true); setErr('');
try {
- await integrationsClient.save(draftPayload(draft));
+ const secret = draft.secret.trim().length > 0 ? draft.secret : undefined;
+ const res = await integrationsClient.save(recordFromDraft(draft, Date.now()), secret);
+ if (!res.ok) { setErr(res.error || 'Could not save.'); return; }
await refresh();
- flash(editing ? 'Integration updated.' : 'Integration added.');
+ flash(draft.isNew ? 'Integration added.' : 'Integration updated.');
goList();
- } catch { flash('Could not save.'); }
+ } catch { setErr('Could not save.'); }
finally { setBusy(false); }
};
- const onRemove = async (entry: IntegrationEntry) => {
+
+ const onRemove = async (r: IntegrationRecordView) => {
setBusy(true);
- try { await integrationsClient.remove(entry.id); await refresh(); flash(`Removed “${entry.label}”.`); }
+ try { await integrationsClient.remove(r.id); setRowTest((m) => { const n = { ...m }; delete n[r.id]; return n; }); await refresh(); flash(`Removed “${r.label}”.`); }
catch { flash('Could not remove.'); }
finally { setBusy(false); }
};
- const onTestRow = async (entry: IntegrationEntry) => {
- setTestingId(entry.id);
- try { const r = await integrationsClient.test(entry.id); await refresh(); flash(r.message); }
- catch { flash('Test failed to run.'); }
+
+ const fmtTest = (t: TestResult) => t.ok ? `✓ Connected${t.status ? ` (${t.status})` : ''}` : `✕ ${t.error || 'Failed'}${t.status ? ` (${t.status})` : ''}`;
+
+ const onTestRow = async (r: IntegrationRecordView) => {
+ setTestingId(r.id);
+ try { const res = await integrationsClient.test(r.id); setRowTest((m) => ({ ...m, [r.id]: res })); }
+ catch { setRowTest((m) => ({ ...m, [r.id]: { ok: false, error: 'Test failed to run.' } })); }
finally { setTestingId(null); }
};
+ const onTestCfg = async () => {
+ if (!draft || draft.isNew) return;
+ setTesting(true); setCfgTest(null);
+ try { setCfgTest(await integrationsClient.test(draft.id)); }
+ catch { setCfgTest({ ok: false, error: 'Test failed to run.' }); }
+ finally { setTesting(false); }
+ };
// ───────────────────────── GALLERY ─────────────────────────
if (view === 'gallery') {
return (
<div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
- <button type="button" onClick={goList} style={{ background: 'none', border: 'none', cursor: 'pointer', padding: 0, alignSelf: 'flex-start', fontSize: 12, color: 'var(--cth-ink-500)' }}>← Integrations</button>
+ <button type="button" onClick={goList} style={linkBtn}>← Integrations</button>
<div>
<div style={{ ...dispLabel, marginBottom: 4 }}>Pick a template</div>
- <span style={subText}>Choose what you’re connecting. The template decides which fields and scopes are requested. Pick <b>Custom REST</b> for anything not listed.</span>
+ <span style={subText}>Choose what you’re connecting. The template sets the defaults. Pick <b>Custom REST</b> for anything not listed.</span>
</div>
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8 }}>
{templates.map((t) => {
- const on = picked === t.id;
+ const on = picked === t.idSuggestion;
+ const g = glyphFor(t.kind, t.label);
return (
- <button key={t.id} type="button" onClick={() => setPicked(t.id)} style={{
+ <button key={t.idSuggestion} type="button" onClick={() => setPicked(t.idSuggestion)} style={{
display: 'flex', alignItems: 'center', gap: 10, padding: 10, textAlign: 'left', cursor: 'pointer', border: 'none',
background: on ? 'var(--cth-lemon-light, #FFEC99)' : 'var(--cth-paper-100)',
boxShadow: `inset 0 0 0 ${on ? 2 : 1}px ${on ? 'var(--cth-ink-900)' : 'var(--cth-ink-300)'}`
}}>
- <Glyph glyph={t.glyph} />
+ <Glyph mono={g.mono} bg={g.bg} />
<div style={{ display: 'flex', flexDirection: 'column', gap: 2, minWidth: 0 }}>
<span style={{ fontSize: 13, lineHeight: '17px', color: 'var(--cth-ink-900)', fontWeight: 600 }}>{t.label}</span>
- <span style={hint}>{t.description}</span>
+ <span style={hint}>{t.secretHelp || (t.kind === 'custom-rest' ? 'Any HTTP API' : '')}</span>
</div>
</button>
);
@@ -196,167 +238,165 @@ export function IntegrationsRegistry() {
}
// ───────────────────────── CONFIGURE ─────────────────────────
- if (view === 'configure' && draft && activeTemplate) {
+ if (view === 'configure' && draft) {
+ const g = glyphFor(draft.kind, draft.label);
+ const tpl = templates.find((t) => t.kind === draft.kind);
+ const secretLabel = tpl?.secretLabel || 'Secret';
+ const showSavedPill = !draft.isNew && draft.hasSecret && !replacing;
+ const isUsable = usable(draft);
return (
<div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
- <button type="button" onClick={editing ? goList : startAdd} style={{ background: 'none', border: 'none', cursor: 'pointer', padding: 0, alignSelf: 'flex-start', fontSize: 12, color: 'var(--cth-ink-500)' }}>
- {editing ? '← Integrations' : '← Templates'}
- </button>
+ <button type="button" onClick={draft.isNew ? startAdd : goList} style={linkBtn}>{draft.isNew ? '← Templates' : '← Integrations'}</button>
<div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: 12, background: 'var(--cth-cream-100)', boxShadow: 'inset 0 0 0 1px var(--cth-ink-300)' }}>
- <Glyph glyph={activeTemplate.glyph} lg />
+ <Glyph mono={g.mono} bg={g.bg} lg />
<div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
- <span style={{ fontSize: 14, lineHeight: '18px', fontWeight: 600, color: 'var(--cth-ink-900)' }}>{activeTemplate.label}</span>
- <span style={hint}>{activeTemplate.description} · needs a {activeTemplate.secretLabel.toLowerCase()}</span>
+ <span style={{ fontSize: 14, lineHeight: '18px', fontWeight: 600, color: 'var(--cth-ink-900)' }}>{tpl?.label ?? draft.kind}</span>
+ <span style={hint}>{needsSecret(draft.authType) ? `Needs a ${secretLabel.toLowerCase()}` : 'Public API — no secret needed'}</span>
</div>
</div>
{/* Label */}
<label style={{ display: 'flex', flexDirection: 'column', gap: 5 }}>
<span style={fieldLabel}>Label</span>
- <input value={draft.label} onChange={(e) => setDraft({ ...draft, label: e.target.value })} placeholder={`e.g. ${activeTemplate.label} (prod)`} style={inputStyle} />
- <span style={hint}>A friendly name shown in your integrations list. You can have more than one {activeTemplate.label} connection.</span>
+ <input value={draft.label} onChange={(e) => patch({ label: e.target.value, ...(draft.isNew ? { id: slugify(e.target.value) } : {}) })} placeholder={`e.g. ${tpl?.label ?? 'My API'} (prod)`} style={inputStyle} />
+ <span style={hint}>Shown in your list. Id: <code style={{ fontFamily: 'var(--cth-font-mono)' }}>{slugify(draft.id || draft.label) || '—'}</code>{draft.isNew ? '' : ' (fixed)'}</span>
</label>
- {/* Non-secret fields */}
- {activeTemplate.fields.map((f) => (
- <label key={f.key} style={{ display: 'flex', flexDirection: 'column', gap: 5 }}>
- <span style={fieldLabel}>{f.label}{f.optional ? ' (optional)' : ''}</span>
- <input value={draft.fields[f.key] ?? ''} onChange={(e) => setField(f.key, e.target.value)} placeholder={f.placeholder} style={{ ...inputStyle, fontFamily: 'var(--cth-font-mono)' }} />
+ {/* Base URL — editable for custom-rest, fixed for presets */}
+ <label style={{ display: 'flex', flexDirection: 'column', gap: 5 }}>
+ <span style={fieldLabel}>Base URL</span>
+ <input value={draft.baseUrl} onChange={(e) => patch({ baseUrl: e.target.value })} placeholder="https://api.example.com" readOnly={draft.kind !== 'custom-rest'} style={{ ...inputStyle, fontFamily: 'var(--cth-font-mono)', opacity: draft.kind !== 'custom-rest' ? 0.7 : 1 }} />
+ {draft.kind !== 'custom-rest' && <span style={hint}>Set by the {tpl?.label ?? 'preset'} template.</span>}
+ </label>
+
+ {/* Auth type — selectable only for custom-rest */}
+ {draft.kind === 'custom-rest' ? (
+ <label style={{ display: 'flex', flexDirection: 'column', gap: 5, maxWidth: 260 }}>
+ <span style={fieldLabel}>Authentication</span>
+ <select value={draft.authType} onChange={(e) => patch({ authType: e.target.value as IntegrationAuthType })} style={{ ...inputStyle, fontFamily: 'var(--cth-font-mono)' }}>
+ {CUSTOM_AUTH.map((a) => <option key={a} value={a}>{AUTH_LABEL[a]}</option>)}
+ </select>
</label>
- ))}
+ ) : (
+ <div style={{ display: 'flex', flexDirection: 'column', gap: 5 }}>
+ <span style={fieldLabel}>Authentication</span>
+ <span style={hint}>{AUTH_LABEL[draft.authType]} (set by template)</span>
+ </div>
+ )}
- {/* Secret — WRITE-ONLY */}
- <div style={{ display: 'flex', flexDirection: 'column', gap: 5 }}>
- <span style={fieldLabel}>{activeTemplate.secretLabel}</span>
- {showSavedPill ? (
- <div style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
- <span style={{ fontFamily: 'var(--cth-font-mono)', fontSize: 13, color: 'var(--cth-ink-500)', background: 'var(--cth-paper-100)', boxShadow: 'inset 0 0 0 1px var(--cth-ink-300)', padding: '6px 10px', letterSpacing: 2 }}>•••••••• saved</span>
- <PixelButton variant="secondary" size="sm" onClick={() => { setReplacing(true); setShowSecret(false); setDraft({ ...draft, secret: '' }); }}>Replace key</PixelButton>
- </div>
- ) : (
- <>
- <div style={{ display: 'flex', gap: 6 }}>
- <input
- type={showSecret ? 'text' : 'password'}
- value={draft.secret ?? ''}
- onChange={(e) => setDraft({ ...draft, secret: e.target.value })}
- placeholder={`Paste your ${activeTemplate.secretLabel.toLowerCase()}`}
- autoComplete="off"
- style={{ ...inputStyle, fontFamily: 'var(--cth-font-mono)' }}
- />
- <PixelButton variant="secondary" size="sm" onClick={() => setShowSecret((v) => !v)} disabled={!draft.secret}>
- {showSecret ? 'hide' : 'show'}
- </PixelButton>
- </div>
- <div style={{ display: 'flex', gap: 6, alignItems: 'flex-start', padding: '7px 9px', background: 'var(--cth-cream-100)', boxShadow: 'inset 0 0 0 1px var(--cth-ink-100, var(--cth-ink-300))', ...hint }}>
- 🔒&nbsp;<span><b style={{ color: 'var(--cth-ink-700)' }}>Write-only.</b> Stored encrypted in the main process and never displayed again after you save. To change it later, paste a new key — there’s no way to read the old one back.{editing && editEntry?.hasSecret ? ' Leave blank to keep the saved key.' : ''}</span>
+ {/* Custom header name (header auth only) */}
+ {draft.authType === 'header' && (
+ <label style={{ display: 'flex', flexDirection: 'column', gap: 5, maxWidth: 320 }}>
+ <span style={fieldLabel}>Header name</span>
+ <input value={draft.authHeader} onChange={(e) => patch({ authHeader: e.target.value })} placeholder="X-Api-Key" style={{ ...inputStyle, fontFamily: 'var(--cth-font-mono)' }} />
+ <span style={hint}>The secret is sent as <code style={{ fontFamily: 'var(--cth-font-mono)' }}>{(draft.authHeader.trim() || 'X-Header')}: &lt;secret&gt;</code>.</span>
+ </label>
+ )}
+
+ {/* Secret — WRITE-ONLY (separate setSecret IPC) */}
+ {needsSecret(draft.authType) && (
+ <div style={{ display: 'flex', flexDirection: 'column', gap: 5 }}>
+ <span style={fieldLabel}>{secretLabel}</span>
+ {showSavedPill ? (
+ <div style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
+ <span style={{ fontFamily: 'var(--cth-font-mono)', fontSize: 13, color: 'var(--cth-ink-500)', background: 'var(--cth-paper-100)', boxShadow: 'inset 0 0 0 1px var(--cth-ink-300)', padding: '6px 10px', letterSpacing: 2 }}>•••••••• saved</span>
+ <PixelButton variant="secondary" size="sm" onClick={() => { setReplacing(true); setShowSecret(false); patch({ secret: '' }); }}>Replace key</PixelButton>
</div>
- </>
- )}
- </div>
+ ) : (
+ <>
+ <div style={{ display: 'flex', gap: 6 }}>
+ <input type={showSecret ? 'text' : 'password'} value={draft.secret} onChange={(e) => patch({ secret: e.target.value })} placeholder={`Paste your ${secretLabel.toLowerCase()}`} autoComplete="off" style={{ ...inputStyle, fontFamily: 'var(--cth-font-mono)' }} />
+ <PixelButton variant="secondary" size="sm" onClick={() => setShowSecret((s) => !s)} disabled={!draft.secret}>{showSecret ? 'hide' : 'show'}</PixelButton>
+ </div>
+ <div style={{ display: 'flex', gap: 6, alignItems: 'flex-start', padding: '7px 9px', background: 'var(--cth-cream-100)', boxShadow: 'inset 0 0 0 1px var(--cth-ink-100, var(--cth-ink-300))', ...hint }}>
+ 🔒&nbsp;<span><b style={{ color: 'var(--cth-ink-700)' }}>Write-only.</b> Encrypted in the main process and never shown again. To change it, paste a new key — the old one can’t be read back.{!draft.isNew && draft.hasSecret ? ' Leave blank to keep the saved key.' : ''}</span>
+ </div>
+ {tpl?.secretHelp && <span style={hint}>{tpl.secretHelp}</span>}
+ </>
+ )}
+ </div>
+ )}
- {/* Workers (dispatch requirement) */}
- <div style={{ display: 'flex', flexDirection: 'column', gap: 5 }}>
- <span style={fieldLabel}>Workers that can use it</span>
- <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
- {workers.length === 0 && <span style={hint}>no workers available</span>}
- {workers.map((w) => {
- const on = draft.workers.includes(w.id);
- return (
- <button key={w.id} type="button" onClick={() => toggleWorker(w.id)} style={{
- padding: '2px 8px', border: 'none', cursor: 'pointer', fontSize: 11, lineHeight: '16px', color: 'var(--cth-ink-900)',
- background: on ? 'var(--cth-lemon)' : 'var(--cth-cream-200)',
- boxShadow: `inset 0 0 0 1px ${on ? 'var(--cth-ink-900)' : 'var(--cth-ink-300)'}`
- }}>{on ? '✓ ' : ''}{w.label}</button>
- );
- })}
+ {/* Enabled gate + worker availability */}
+ <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
+ <span style={fieldLabel}>Availability</span>
+ <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
+ <PixelButton variant={draft.enabled ? 'primary' : 'secondary'} size="sm" onClick={() => patch({ enabled: !draft.enabled })}>{draft.enabled ? 'enabled' : 'disabled'}</PixelButton>
+ <span style={hint}>{isUsable ? 'Available to all workers.' : needsSecret(draft.authType) && !(draft.hasSecret || draft.secret.trim()) ? 'Add a secret and enable to make it available.' : draft.enabled ? 'Ready once saved.' : 'Disabled — no worker can use it.'}</span>
</div>
- <span style={hint}>Only the selected workers may use this integration. Leave empty to keep it unused for now.</span>
+ <span style={hint}>v1 grants every enabled integration to all workers. Per-worker scoping is coming.</span>
</div>
- {/* Test connection */}
+ {/* Test connection (saved integrations only — broker probes by id) */}
<div style={{ display: 'flex', flexDirection: 'column', gap: 5 }}>
<span style={fieldLabel}>Test connection</span>
<div style={{ display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' }}>
- <PixelButton variant="secondary" size="sm" onClick={() => { void onTestDraft(); }} disabled={testingDraft}>
- {testingDraft ? 'testing…' : 'Test connection'}
- </PixelButton>
- {draftTest && (
- <span style={{ fontSize: 13, lineHeight: '18px', color: draftTest.ok ? 'var(--cth-mint-700, #1f7a4d)' : 'var(--cth-danger, #6E1423)' }}>
- {draftTest.ok ? '✓ ' : '✕ '}{draftTest.message}
- </span>
- )}
+ <PixelButton variant="secondary" size="sm" onClick={() => { void onTestCfg(); }} disabled={draft.isNew || testing}>{testing ? 'testing…' : 'Test connection'}</PixelButton>
+ {cfgTest && <span style={{ fontSize: 13, color: cfgTest.ok ? 'var(--cth-mint-700, #1f7a4d)' : 'var(--cth-danger, #6E1423)' }}>{fmtTest(cfgTest)}</span>}
</div>
- <span style={hint}>Runs a live read-only call with the key above before you save. On failure it shows the API error inline.</span>
+ <span style={hint}>{draft.isNew ? 'Save the integration first, then test the live connection.' : 'Runs a live read-only probe against the base URL with the stored secret.'}</span>
</div>
<div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end', alignItems: 'center' }}>
- {note && <span style={{ marginRight: 'auto', ...subText }}>{note}</span>}
+ {(err || note) && <span style={{ marginRight: 'auto', fontSize: 12, color: err ? 'var(--cth-danger, #6E1423)' : 'var(--cth-ink-500)' }}>{err || note}</span>}
<PixelButton variant="secondary" size="sm" onClick={goList} disabled={busy}>cancel</PixelButton>
- <PixelButton variant="primary" size="sm" onClick={() => { void onSave(); }} disabled={busy}>
- {busy ? '…' : editing ? 'Save changes' : 'Save integration'}
- </PixelButton>
+ <PixelButton variant="primary" size="sm" onClick={() => { void onSave(); }} disabled={busy}>{busy ? '…' : draft.isNew ? 'Save integration' : 'Save changes'}</PixelButton>
</div>
</div>
);
}
// ───────────────────────── LIST (default) ─────────────────────────
- const connected = entries.filter((e) => e.status === 'ok').length;
+ const usableCount = records.filter(usable).length;
return (
<div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
<div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 16 }}>
<div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
<div style={dispLabel}>Integrations</div>
- <span style={{ ...subText, maxWidth: 440 }}>Connect outside tools so your agents can read and act on them. Secrets are stored in the main process, encrypted, and never shown again.</span>
+ <span style={{ ...subText, maxWidth: 440 }}>Connect outside tools so your agents can read and act on them. Secrets are stored encrypted in the main process and never shown again.</span>
</div>
- {entries.length > 0 && (
- <PixelButton variant="primary" size="sm" onClick={startAdd} disabled={busy || templates.length === 0}>+ add integration</PixelButton>
- )}
+ {records.length > 0 && <PixelButton variant="primary" size="sm" onClick={startAdd} disabled={busy || templates.length === 0}>+ add integration</PixelButton>}
</div>
- {entries.length === 0 ? (
+ {records.length === 0 ? (
<div style={{ padding: 24, textAlign: 'center', background: 'var(--cth-paper-100)', boxShadow: 'inset 0 0 0 1px var(--cth-ink-300)' }}>
- <p style={{ margin: '0 0 12px', fontSize: 13, lineHeight: '18px', color: 'var(--cth-ink-500)' }}>
- No integrations yet. Connect Linear, Stripe, Notion, GitHub and more — or a custom REST API.
- </p>
+ <p style={{ margin: '0 0 12px', fontSize: 13, lineHeight: '18px', color: 'var(--cth-ink-500)' }}>No integrations yet. Connect GitHub or a custom REST API so your agents can use it.</p>
<PixelButton variant="primary" size="sm" onClick={startAdd} disabled={templates.length === 0}>+ add your first integration</PixelButton>
</div>
) : (
<>
- <span style={hint}>{entries.length} integration{entries.length === 1 ? '' : 's'} · {connected} connected</span>
+ <span style={hint}>{records.length} integration{records.length === 1 ? '' : 's'} · {usableCount} available to workers</span>
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
- {entries.map((entry) => {
- const tpl = templateOf(entry.templateId);
- const st = STATUS_META[entry.status];
- const assigned = workers.filter((w) => entry.workers.includes(w.id));
+ {records.map((r) => {
+ const g = glyphFor(r.kind, r.label);
+ const tpl = templates.find((t) => t.kind === r.kind);
+ const st = !r.enabled
+ ? { dot: '○', color: 'var(--cth-ink-500)', text: 'Disabled' }
+ : needsSecret(r.authType) && !r.hasSecret
+ ? { dot: '▲', color: 'var(--cth-danger, #6E1423)', text: 'Needs secret' }
+ : { dot: '●', color: 'var(--cth-mint-700, #1f7a4d)', text: 'Enabled' };
+ const rt = rowTest[r.id];
return (
- <div key={entry.id} style={{ display: 'flex', flexDirection: 'column', gap: 8, padding: 10, background: 'var(--cth-paper-100)', boxShadow: 'inset 0 0 0 1px var(--cth-ink-300)' }}>
+ <div key={r.id} style={{ display: 'flex', flexDirection: 'column', gap: 6, padding: 10, background: 'var(--cth-paper-100)', boxShadow: 'inset 0 0 0 1px var(--cth-ink-300)' }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
- {tpl && <Glyph glyph={tpl.glyph} />}
+ <Glyph mono={g.mono} bg={g.bg} />
<div style={{ display: 'flex', flexDirection: 'column', gap: 2, flex: 1, minWidth: 0 }}>
- <span style={{ fontSize: 13, lineHeight: '18px', color: 'var(--cth-ink-900)', fontWeight: 600 }}>{entry.label}</span>
- <span style={hint}>{tpl ? `${tpl.label} · ${tpl.description}` : entry.templateId}{entry.hasSecret ? '' : ' · no secret'}</span>
+ <span style={{ fontSize: 13, lineHeight: '18px', color: 'var(--cth-ink-900)', fontWeight: 600 }}>{r.label}</span>
+ <span style={hint}>{tpl?.label ?? r.kind} · <code style={{ fontFamily: 'var(--cth-font-mono)' }}>{r.baseUrl || '—'}</code></span>
</div>
- <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 12, color: st.color, whiteSpace: 'nowrap' }}>
- <span style={{ fontSize: 10 }}>{st.dot}</span> {st.text}
- </span>
+ <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 12, color: st.color, whiteSpace: 'nowrap' }}><span style={{ fontSize: 10 }}>{st.dot}</span> {st.text}</span>
<div style={{ display: 'flex', gap: 6, flexShrink: 0 }}>
- <PixelButton variant="secondary" size="sm" onClick={() => { void onTestRow(entry); }} disabled={busy || testingId === entry.id}>
- {testingId === entry.id ? '…' : 'test'}
- </PixelButton>
- <PixelButton variant="ghost" size="sm" onClick={() => startEdit(entry)} disabled={busy}>edit</PixelButton>
- <PixelButton variant="ghost" size="sm" onClick={() => { void onRemove(entry); }} disabled={busy}>✕</PixelButton>
+ <PixelButton variant="secondary" size="sm" onClick={() => { void onTestRow(r); }} disabled={busy || testingId === r.id}>{testingId === r.id ? '…' : 'test'}</PixelButton>
+ <PixelButton variant="ghost" size="sm" onClick={() => startEdit(r)} disabled={busy}>edit</PixelButton>
+ <PixelButton variant="ghost" size="sm" onClick={() => { void onRemove(r); }} disabled={busy}>✕</PixelButton>
</div>
</div>
- <div style={{ display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap' }}>
- <span style={dispLabel}>Workers</span>
- {assigned.length === 0 ? (
- <span style={hint}>none assigned</span>
- ) : assigned.map((w) => (
- <span key={w.id} style={{ fontSize: 11, lineHeight: '16px', padding: '1px 6px', background: 'var(--cth-cream-200)', boxShadow: 'inset 0 0 0 1px var(--cth-ink-300)', color: 'var(--cth-ink-900)' }}>{w.label}</span>
- ))}
+ <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
+ <span style={{ ...hint, color: usable(r) ? 'var(--cth-mint-700, #1f7a4d)' : 'var(--cth-ink-500)' }}>
+ {usable(r) ? '✓ Available to all workers' : 'Not available to workers yet'}
+ </span>
+ {rt && <span style={{ fontSize: 12, color: rt.ok ? 'var(--cth-mint-700, #1f7a4d)' : 'var(--cth-danger, #6E1423)' }}>· {fmtTest(rt)}</span>}
</div>
</div>
);
diff --git a/src/renderer/src/integrations/registryClient.ts b/src/renderer/src/integrations/registryClient.ts
index 800d283c..45cc2162 100644
--- a/src/renderer/src/integrations/registryClient.ts
+++ b/src/renderer/src/integrations/registryClient.ts
@@ -1,197 +1,157 @@
// Integrations registry client — the renderer's single doorway to the
// integrations registry + secret broker.
//
-// ⚠️ PROVISIONAL: the types and the client body below are a scaffold. They will
-// be CONFORMED to Jim's hive/docs/integrations-spec.md (registry schema + IPC
-// channel names) once it is published. Conforming is intentionally a ONE-FILE
-// change: swap the in-memory mock bodies for `window.cth.*` IPC calls and align
-// the types with the spec. The UI (IntegrationsRegistry.tsx) talks ONLY to this
-// module, never to IPC directly, so nothing downstream changes when we wire up.
+// CONFORMED to Jim's spec v1 (hive/docs/integrations-spec.md): the types are the
+// CANONICAL ones from `@shared/integrations` (Jim's src/shared/integrations.ts),
+// and the client maps 1:1 to the §6 IPC surface — whose handlers already exist in
+// src/main/index.ts (integrations:list / templates / upsert / setSecret / remove /
+// test). The real path calls window.cth.* (Jim's preload bridge).
//
-// The template set + glyphs mirror Pam's reference mockup
-// (hive/docs/integrations-ui-mockup.html). The REAL catalog is Dwight's; these
-// stand in until the registry serves templates.
+// ⚠️ The preload bridge is NOT landed yet (Jim owns it — god relays when it's in).
+// Until then this falls back to an in-memory mock so the UI is fully usable in dev.
+// The real path is FEATURE-DETECTED: the moment Jim's preload methods appear it
+// activates with NO change here. Two coordination notes:
+// 1. The bridge method NAMES below (integrationsList, …) follow the existing
+// preload camelCase→colon-channel convention (getConfig→'config:get', etc.).
+// Jim: expose exactly these (or tell me the names) so the detect matches.
+// 2. The catalog served by `integrations:templates` is Jim's `INTEGRATION_TEMPLATES`
+// (the 2 v1 reference templates). Dwight's richer src/shared/integrationTemplates.ts
+// is a SEPARATE, currently-unwired file — reconciliation is a god/Jim/Dwight call.
//
-// SECURITY INVARIANT (must survive conformance): a secret value flows ONE WAY —
-// from the form into save()/testDraft() and onward to the broker. It is NEVER
-// read back. `IntegrationEntry` carries `hasSecret: boolean` (presence only);
-// there is no field that could carry the secret value back to the renderer.
-
-/** A small brand monogram tile (stands in for a logo). */
-export interface IntegrationGlyph {
- /** 1–2 char monogram, e.g. 'Li', 'Gh', '{}'. */
- mono: string;
- /** Background hex, e.g. '#5E6AD2'. */
- bg: string;
+// SECURITY INVARIANT (matches §2): a secret value flows ONE WAY — from the form
+// into save()'s setSecret call and onward to the encrypted store. It is NEVER read
+// back. list() returns records with secretRef redacted to hasSecret:boolean.
+
+import {
+ INTEGRATION_TEMPLATES,
+ authTypeNeedsSecret,
+ secretRefFor,
+ validateIntegrationRecord,
+ type IntegrationRecord,
+ type IntegrationTemplate
+} from '@shared/integrations';
+
+export type { IntegrationRecord, IntegrationTemplate } from '@shared/integrations';
+export type { IntegrationKind, IntegrationAuthType } from '@shared/integrations';
+
+/** The renderer-visible record: secretRef is redacted to a presence boolean.
+ * Matches main `integrations.listRecordsRedacted()`. */
+export type IntegrationRecordView = Omit<IntegrationRecord, 'secretRef'> & { hasSecret: boolean };
+
+/** Result of a §6 `integrations:test` probe. */
+export interface TestResult {
+ ok: boolean;
+ status?: number;
+ error?: string;
}
-/** A non-secret field a template asks the user to fill in. */
-export interface IntegrationFieldSpec {
- key: string;
- label: string;
- placeholder?: string;
- optional?: boolean;
-}
+type UpsertResult = { ok: true; record: IntegrationRecord } | { ok: false; error: string };
-/** A kind/template of integration (authored by Dwight; served by the registry). */
-export interface IntegrationTemplate {
- /** Stable kind id, e.g. 'linear', 'github', 'custom-rest'. */
- id: string;
- label: string;
- /** Short one-liner, e.g. 'Issues & projects'. */
- description: string;
- glyph: IntegrationGlyph;
- /** Human label for the one secret this kind needs, e.g. 'API secret key'. */
- secretLabel: string;
- /** Non-secret config fields. */
- fields: IntegrationFieldSpec[];
+export interface IntegrationsClient {
+ listTemplates(): Promise<IntegrationTemplate[]>;
+ list(): Promise<IntegrationRecordView[]>;
+ /** §6 upsert (metadata, no secret) + §6 setSecret when a new secret was typed. */
+ save(record: IntegrationRecord, secret?: string): Promise<{ ok: boolean; error?: string }>;
+ remove(id: string): Promise<{ ok: boolean }>;
+ test(id: string): Promise<TestResult>;
}
-export type IntegrationStatus = 'untested' | 'ok' | 'error';
-
-/** A configured integration instance. The secret value is NEVER present here. */
-export interface IntegrationEntry {
- id: string;
- /** User-given label. */
- label: string;
- /** Template/kind id this instance is built from. */
- templateId: string;
- /** Non-secret field values. */
- fields: Record<string, string>;
- /** Whether a secret has been stored in the broker for this entry (value never echoed). */
- hasSecret: boolean;
- /** Worker ids that are allowed to use this integration. */
- workers: string[];
- status: IntegrationStatus;
- /** Epoch ms of the last test-connection, if any. */
- lastTestedAt?: number;
+// The preload bridge Jim exposes (Deliverable 2). Channels are fixed by §6;
+// accessed via a tolerant cast so this compiles before the bridge exists.
+interface IntegrationsBridge {
+ integrationsList(): Promise<IntegrationRecordView[]>;
+ integrationsTemplates(): Promise<IntegrationTemplate[]>;
+ integrationsUpsert(record: IntegrationRecord): Promise<UpsertResult>;
+ integrationsSetSecret(req: { id: string; secret: string }): Promise<{ ok: boolean; error?: string }>;
+ integrationsRemove(req: { id: string }): Promise<{ ok: boolean }>;
+ integrationsTest(req: { id: string; path?: string }): Promise<TestResult>;
}
-/** A worker that may be granted use of an integration. */
-export interface IntegrationWorker {
- id: string;
- label: string;
+function liveBridge(): IntegrationsBridge | undefined {
+ if (typeof window === 'undefined') return undefined;
+ const b = (window as unknown as { cth?: Partial<IntegrationsBridge> }).cth;
+ return b && typeof b.integrationsList === 'function' ? (b as IntegrationsBridge) : undefined;
}
-/** Result of a test-connection probe. */
-export interface TestResult {
- ok: boolean;
- message: string;
-}
+// ───────────────────────── PROVISIONAL mock (dev fallback only) ─────────────────────────
+// Serves Jim's canonical INTEGRATION_TEMPLATES and validates upserts with Jim's
+// real validateIntegrationRecord, so the mock behaves like the wired backend.
-/**
- * Payload for add (no `id`) or edit (with `id`). `secret` is WRITE-ONLY:
- * include it to (re)set the secret; omit it to leave the stored secret as-is.
- */
-export interface IntegrationDraft {
- id?: string;
- label: string;
- templateId: string;
- fields: Record<string, string>;
- secret?: string;
- workers: string[];
-}
+let mockRecords: IntegrationRecord[] = [];
+const mockSecret = new Set<string>(); // secretRef membership only — never values
-export interface IntegrationsClient {
- listTemplates(): Promise<IntegrationTemplate[]>;
- listWorkers(): Promise<IntegrationWorker[]>;
- list(): Promise<IntegrationEntry[]>;
- /** Add (draft.id absent) or edit (draft.id present). Returns the saved entry (no secret). */
- save(draft: IntegrationDraft): Promise<IntegrationEntry>;
- remove(id: string): Promise<void>;
- /** Test a saved integration by id (used by the list rows). */
- test(id: string): Promise<TestResult>;
- /** Test the in-progress draft (with its typed secret) before saving — the configure step. */
- testDraft(draft: IntegrationDraft): Promise<TestResult>;
+function redact(r: IntegrationRecord): IntegrationRecordView {
+ const { secretRef, ...rest } = r;
+ return { ...rest, hasSecret: !!secretRef && mockSecret.has(secretRef) };
}
-// ---------------------------------------------------------------------------
-// PROVISIONAL template catalog — mirrors Pam's mockup gallery (11 templates).
-// ---------------------------------------------------------------------------
-
-const CUSTOM_REST_FIELDS: IntegrationFieldSpec[] = [
- { key: 'baseUrl', label: 'Base URL', placeholder: 'https://api.example.com' },
- { key: 'authHeader', label: 'Auth header', placeholder: 'Authorization: Bearer …', optional: true }
-];
-
-const MOCK_TEMPLATES: IntegrationTemplate[] = [
- { id: 'linear', label: 'Linear', description: 'Issues & projects', glyph: { mono: 'Li', bg: '#5E6AD2' }, secretLabel: 'API key', fields: [] },
- { id: 'jira', label: 'Jira', description: 'Tickets & boards', glyph: { mono: 'Ji', bg: '#2684FF' }, secretLabel: 'API token', fields: [{ key: 'site', label: 'Site URL', placeholder: 'https://acme.atlassian.net' }, { key: 'email', label: 'Account email', placeholder: '[email protected]' }] },
- { id: 'notion', label: 'Notion', description: 'Pages & databases', glyph: { mono: 'No', bg: '#1A1320' }, secretLabel: 'Integration token', fields: [] },
- { id: 'stripe', label: 'Stripe', description: 'Payments & billing', glyph: { mono: 'St', bg: '#635BFF' }, secretLabel: 'API secret key', fields: [] },
- { id: 'confluence', label: 'Confluence', description: 'Wiki & docs', glyph: { mono: 'Cf', bg: '#1868DB' }, secretLabel: 'API token', fields: [{ key: 'site', label: 'Site URL', placeholder: 'https://acme.atlassian.net/wiki' }] },
- { id: 'sentry', label: 'Sentry', description: 'Error monitoring', glyph: { mono: 'Sy', bg: '#C84B4B' }, secretLabel: 'Auth token', fields: [{ key: 'org', label: 'Org slug', placeholder: 'acme', optional: true }] },
- { id: 'hubspot', label: 'HubSpot', description: 'CRM & contacts', glyph: { mono: 'Hs', bg: '#FF7A59' }, secretLabel: 'Private app token', fields: [] },
- { id: 'github', label: 'GitHub', description: 'Repos & pull requests', glyph: { mono: 'Gh', bg: '#1A1320' }, secretLabel: 'Personal access token', fields: [{ key: 'org', label: 'Org / owner', placeholder: 'acme', optional: true }] },
- { id: 'google-workspace', label: 'Gmail + Calendar', description: 'Mail & events', glyph: { mono: 'GC', bg: '#EA4335' }, secretLabel: 'OAuth client secret', fields: [{ key: 'clientId', label: 'Client ID', placeholder: '…apps.googleusercontent.com' }] },
- { id: 'salesforce', label: 'Salesforce', description: 'CRM & pipeline', glyph: { mono: 'Sf', bg: '#00A1E0' }, secretLabel: 'Access token', fields: [{ key: 'instanceUrl', label: 'Instance URL', placeholder: 'https://acme.my.salesforce.com' }] },
- { id: 'custom-rest', label: 'Custom REST', description: 'Any HTTP API', glyph: { mono: '{}', bg: '#2E9E5B' }, secretLabel: 'Auth token / API key', fields: CUSTOM_REST_FIELDS }
-];
-
-const MOCK_WORKERS: IntegrationWorker[] = [
- { id: 'michael', label: 'Michael (manager)' },
- { id: 'jim', label: 'Jim' },
- { id: 'pam', label: 'Pam' },
- { id: 'dwight', label: 'Dwight' }
-];
-
-let mockEntries: IntegrationEntry[] = [];
-let mockSeq = 1;
-// Secrets live only in this set's membership (presence), never their values —
-// mirrors the broker boundary so the UI behaves identically once wired.
-const mockHasSecret = new Set<string>();
-
-function delay<T>(value: T): Promise<T> {
- return Promise.resolve(value);
-}
+const mockClient: IntegrationsClient = {
+ listTemplates: () => Promise.resolve(INTEGRATION_TEMPLATES.map((t) => ({ ...t }))),
+ list: () => Promise.resolve(mockRecords.map(redact)),
+ save: (record, secret) => {
+ const v = validateIntegrationRecord(record);
+ if (!v.ok) return Promise.resolve({ ok: false, error: v.error });
+ const now = Date.now();
+ const prev = mockRecords.find((r) => r.id === v.value.id);
+ const full: IntegrationRecord = { ...v.value, createdAt: prev?.createdAt ?? now, updatedAt: now };
+ if (prev) mockRecords = mockRecords.map((r) => (r.id === full.id ? full : r));
+ else mockRecords.push(full);
+ if (secret && secret.length > 0 && full.secretRef) mockSecret.add(full.secretRef);
+ return Promise.resolve({ ok: true });
+ },
+ remove: (id) => {
+ const r = mockRecords.find((x) => x.id === id);
+ if (r?.secretRef) mockSecret.delete(r.secretRef);
+ mockRecords = mockRecords.filter((x) => x.id !== id);
+ return Promise.resolve({ ok: true });
+ },
+ test: (id) => {
+ const r = mockRecords.find((x) => x.id === id);
+ if (!r) return Promise.resolve({ ok: false, error: 'unknown integration' });
+ if (!r.enabled) return Promise.resolve({ ok: false, error: 'integration is disabled' });
+ if (authTypeNeedsSecret(r.authType) && !(r.secretRef && mockSecret.has(r.secretRef))) {
+ return Promise.resolve({ ok: false, status: 503, error: 'no secret set' });
+ }
+ return Promise.resolve({ ok: true, status: 200 });
+ }
+};
-/** Provisional probe: a secret that looks plausible "connects". */
-function mockProbe(hasSecret: boolean): TestResult {
- return hasSecret
- ? { ok: true, message: 'Connected — authenticated (mock).' }
- : { ok: false, message: '401 — no secret set.' };
-}
+// ───────────────────────── exported client (real → mock fallback) ─────────────────────────
export const integrationsClient: IntegrationsClient = {
- listTemplates: () => delay(MOCK_TEMPLATES.map((t) => ({ ...t }))),
- listWorkers: () => delay(MOCK_WORKERS.map((w) => ({ ...w }))),
- list: () => delay(mockEntries.map((e) => ({ ...e, hasSecret: mockHasSecret.has(e.id) }))),
- save: (draft) => {
- const id = draft.id ?? `int-${mockSeq++}`;
- if (draft.secret && draft.secret.length > 0) mockHasSecret.add(id);
- const entry: IntegrationEntry = {
- id,
- label: draft.label,
- templateId: draft.templateId,
- fields: { ...draft.fields },
- hasSecret: mockHasSecret.has(id),
- workers: [...draft.workers],
- // Changing config invalidates a prior pass; force a re-test.
- status: 'untested'
- };
- const idx = mockEntries.findIndex((e) => e.id === id);
- if (idx >= 0) mockEntries[idx] = entry;
- else mockEntries.push(entry);
- return delay({ ...entry });
+ listTemplates: () => {
+ const b = liveBridge();
+ return b ? b.integrationsTemplates() : mockClient.listTemplates();
+ },
+ list: () => {
+ const b = liveBridge();
+ return b ? b.integrationsList() : mockClient.list();
+ },
+ save: async (record, secret) => {
+ const b = liveBridge();
+ if (!b) return mockClient.save(record, secret);
+ const up = await b.integrationsUpsert(record);
+ if (!up.ok) return { ok: false, error: up.error };
+ if (secret && secret.length > 0) {
+ const ss = await b.integrationsSetSecret({ id: record.id, secret });
+ if (!ss.ok) return { ok: false, error: ss.error };
+ }
+ return { ok: true };
},
remove: (id) => {
- mockEntries = mockEntries.filter((e) => e.id !== id);
- mockHasSecret.delete(id);
- return delay(undefined);
+ const b = liveBridge();
+ return b ? b.integrationsRemove({ id }) : mockClient.remove(id);
},
test: (id) => {
- const entry = mockEntries.find((e) => e.id === id);
- if (!entry) return delay({ ok: false, message: 'No such integration.' });
- const res = mockProbe(mockHasSecret.has(id));
- entry.status = res.ok ? 'ok' : 'error';
- entry.lastTestedAt = 0; // stamped by the real broker; mock leaves 0
- return delay(res);
- },
- testDraft: (draft) => {
- // A draft "connects" if it already has a stored secret (edit) or the user
- // just typed one (add). The real broker runs a live read-only call.
- const had = draft.id ? mockHasSecret.has(draft.id) : false;
- const typed = !!(draft.secret && draft.secret.length > 0);
- return delay(mockProbe(had || typed));
+ const b = liveBridge();
+ return b ? b.integrationsTest({ id }) : mockClient.test(id);
}
};
+
+// ───────────────────────── small UI helper ─────────────────────────
+
+/** Best-effort slug from a label (server-side validateIntegrationRecord is authoritative). */
+export function slugify(label: string): string {
+ const base = label.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 40).replace(/-+$/g, '');
+ return base.length >= 2 ? base : `${base || 'api'}-x`;
+}