Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
Import bots dialog: Bring a bot from…, preview, import, undo, export
Lin (kwant bot)2fcdc3e8122c
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsxindex 6baffdb5..ac9c1017 100644--- a/frontend/src/App.tsx+++ b/frontend/src/App.tsx@@ -2612,6 +2612,14 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({onOpenTools={() => setIsMcpOpen(true)}onOpenAppSettings={onOpenAppSettings}routineFocus={routineFocus}+ onImported={() => {+ // New bots, teams and their team chats.+ refreshRoster();+ fetch('/api/channels')+ .then((r) => (r.ok ? r.json() : null))+ .then((c) => Array.isArray(c) && setChannels(c))+ .catch(() => undefined);+ }}/>)}diff --git a/frontend/src/components/ImportDialog.tsx b/frontend/src/components/ImportDialog.tsxnew file mode 100644index 00000000..420e8ec3--- /dev/null+++ b/frontend/src/components/ImportDialog.tsx@@ -0,0 +1,546 @@+import React, { useEffect, useRef, useState } from 'react';+import { AlertTriangle, ArrowLeft, Check, ChevronRight, ClipboardCopy, FileUp, Info, Loader2, Undo2, Upload, X } from 'lucide-react';+import {+ Applied,+ ExportPrompt,+ IMPORT_ACCEPT,+ ImportError,+ ImportRecord,+ Preview,+ canImport,+ fileTooBig,+ importApi,+ importErrorText,+ plural,+ previewRows,+ sourceName,+ textTooLong,+} from '../imports';++const btn =+ 'flex items-center justify-center gap-1.5 px-3 py-2 rounded-lg text-xs font-medium text-zinc-300 border border-zinc-700/60 bg-zinc-800/60 hover:bg-zinc-700/70 hover:text-zinc-100 transition-colors disabled:opacity-50';+const primary =+ 'flex items-center justify-center gap-1.5 px-3 py-2 rounded-lg text-xs font-medium text-white bg-sky-600 hover:bg-sky-500 transition-colors disabled:opacity-50';+const danger =+ 'flex items-center justify-center gap-1.5 px-3 py-2 rounded-lg text-xs font-medium text-white bg-rose-600 hover:bg-rose-500 transition-colors disabled:opacity-50';+const card = 'rounded-xl border border-zinc-800 bg-zinc-950/60';++/** One line under each source in "Bring a bot from…". */+const SOURCE_HINT: Record<string, string> = {+ grok: 'A Grok Project or custom Grok bot',+ chatgpt: 'A custom GPT or ChatGPT Project',+ claude: 'A Claude Project',+ other: 'Any other bot or assistant',+};++export const ErrorBox: React.FC<{ error: unknown; children?: React.ReactNode }> = ({ error, children }) => {+ const { title, detail } = importErrorText(error);+ const problems = error instanceof ImportError ? error.problems : [];+ return (+ <div role="alert" className="rounded-lg border border-rose-500/40 bg-rose-500/10 p-3 space-y-1.5">+ <p className="flex items-center gap-2 text-xs font-medium text-rose-200">+ <AlertTriangle size={14} aria-hidden="true" /> {title}+ </p>+ {detail && <p className="text-xs text-rose-100/80">{detail}</p>}+ {problems.length > 0 && (+ <ul className="list-disc pl-5 text-xs text-rose-100/80">+ {problems.map((n, i) => <li key={i}>{n.message}</li>)}+ </ul>+ )}+ {children}+ </div>+ );+};++export const SourceList: React.FC<{+ prompts: ExportPrompt[] | null;+ error: unknown;+ onPick: (p: ExportPrompt) => void;+ onUpload: () => void;+ onRetry: () => void;+}> = ({ prompts, error, onPick, onUpload, onRetry }) => (+ <div className="space-y-3">+ <p className="text-xs text-zinc-400">+ Pick where your bot lives now. Nothing is created until you check a preview and press Import.+ </p>+ <h3 className="text-xs font-semibold text-zinc-300">Bring a bot from…</h3>+ {error ? (+ <ErrorBox error={error}>+ <button type="button" onClick={onRetry} className={btn}>Try again</button>+ </ErrorBox>+ ) : !prompts ? (+ <p className="flex items-center gap-2 text-xs text-zinc-500" role="status">+ <Loader2 size={13} className="animate-spin motion-reduce:animate-none" /> Loading…+ </p>+ ) : (+ <ul className="space-y-1.5">+ {prompts.map((p) => (+ <li key={p.id}>+ <button type="button" onClick={() => onPick(p)} className={`${card} w-full flex items-center gap-3 p-3 text-left hover:border-zinc-600 transition-colors`}>+ <span className="flex-1 min-w-0">+ <span className="block text-sm font-medium text-zinc-100">{p.label}</span>+ <span className="block text-[11px] text-zinc-500">{SOURCE_HINT[p.id] ?? 'Copy a message, paste the reply'}</span>+ </span>+ <ChevronRight size={16} className="text-zinc-500 shrink-0" aria-hidden="true" />+ </button>+ </li>+ ))}+ </ul>+ )}+ <button type="button" onClick={onUpload} className={`${card} w-full flex items-center gap-3 p-3 text-left hover:border-zinc-600 transition-colors`}>+ <FileUp size={18} className="text-zinc-400 shrink-0" aria-hidden="true" />+ <span className="flex-1 min-w-0">+ <span className="block text-sm font-medium text-zinc-100">Upload a file</span>+ <span className="block text-[11px] text-zinc-500">A Claude Code subagent or SKILL.md, a character card, or a Grok Bot, OpenMausBot or .kwant.json export</span>+ </span>+ <ChevronRight size={16} className="text-zinc-500 shrink-0" aria-hidden="true" />+ </button>+ </div>+);++/** The prompt to copy, with steps, and the box for the bot's reply. */+export const PromptStep: React.FC<{+ prompt: ExportPrompt;+ reply: string;+ onReply: (s: string) => void;+ copied: boolean;+ onCopy: () => void;+}> = ({ prompt, reply, onReply, copied, onCopy }) => (+ <div className="space-y-4">+ <ol className="space-y-1.5 text-xs text-zinc-300 list-decimal pl-5">+ <li>{prompt.where_to_send}</li>+ <li>Copy the message below and send it to your bot.</li>+ <li>Copy everything your bot replies and paste it in the box at the bottom.</li>+ </ol>+ <div className={`${card} p-3 space-y-2`}>+ <div className="flex items-center justify-between gap-2">+ <p className="text-xs font-medium text-zinc-300" id="import-prompt-label">Message for your bot</p>+ <button type="button" onClick={onCopy} className={copied ? `${btn} text-emerald-300` : btn}>+ {copied ? <Check size={13} /> : <ClipboardCopy size={13} />} {copied ? 'Copied' : 'Copy'}+ </button>+ </div>+ <pre+ aria-labelledby="import-prompt-label"+ tabIndex={0}+ className="max-h-40 overflow-y-auto whitespace-pre-wrap break-words text-[11px] leading-relaxed text-zinc-400 font-mono bg-zinc-900/60 rounded-lg p-2.5 select-text"+ >+ {prompt.prompt}+ </pre>+ </div>+ <div>+ <label htmlFor="import-reply" className="block text-xs font-medium text-zinc-300 mb-1">+ Your bot’s reply+ </label>+ <textarea+ id="import-reply"+ value={reply}+ onChange={(e) => onReply(e.target.value)}+ rows={6}+ placeholder="Paste the whole reply here"+ className="w-full bg-zinc-950 border border-zinc-800 focus:border-sky-500 rounded-lg px-3 py-2 text-xs text-zinc-100 font-mono focus:outline-none"+ />+ {textTooLong(reply) && <p className="mt-1 text-[11px] text-rose-300">That’s longer than 256 KB. Paste only your bot’s reply.</p>}+ </div>+ </div>+);++export const UploadStep: React.FC<{ file: File | null; onFile: (f: File | null) => void; inputRef: React.RefObject<HTMLInputElement> }> = ({ file, onFile, inputRef }) => {+ const [over, setOver] = useState(false);+ return (+ <div className="space-y-3">+ <div+ onDragOver={(e) => {+ e.preventDefault();+ setOver(true);+ }}+ onDragLeave={() => setOver(false)}+ onDrop={(e) => {+ e.preventDefault();+ setOver(false);+ onFile(e.dataTransfer.files?.[0] ?? null);+ }}+ className={`rounded-xl border-2 border-dashed p-6 text-center space-y-2 ${over ? 'border-sky-500 bg-sky-500/5' : 'border-zinc-700'}`}+ >+ <Upload size={22} className="mx-auto text-zinc-500" aria-hidden="true" />+ <p className="text-xs text-zinc-300">{file ? file.name : 'Drop a file here, or'}</p>+ <label className={`${btn} inline-flex cursor-pointer`}>+ {file ? 'Choose another file' : 'Choose a file'}+ <input ref={inputRef} type="file" accept={IMPORT_ACCEPT} className="sr-only" onChange={(e) => onFile(e.target.files?.[0] ?? null)} />+ </label>+ {file && fileTooBig(file.size) && <p className="text-[11px] text-rose-300">That file is over 20 MB, so it can’t be imported.</p>}+ </div>+ <ul className="text-[11px] text-zinc-500 space-y-0.5 list-disc pl-5">+ <li>Claude Code subagent (.md) or a SKILL.md</li>+ <li>Character card (.json or .png)</li>+ <li>Grok Bot or OpenMausBot export (.json)</li>+ <li>A .kwant.json file exported from here</li>+ <li>A .zip of any of these. Chat history inside is skipped.</li>+ </ul>+ </div>+ );+};++const Notes: React.FC<{ items: string[]; tone: 'warn' | 'drop' | 'problem'; label: string }> = ({ items, tone, label }) =>+ items.length === 0 ? null : (+ <div>+ <p className={`text-[11px] font-medium ${tone === 'problem' ? 'text-rose-300' : tone === 'warn' ? 'text-amber-300' : 'text-zinc-400'}`}>{label}</p>+ <ul className={`list-disc pl-5 text-[11px] ${tone === 'problem' ? 'text-rose-200/90' : tone === 'warn' ? 'text-amber-100/80' : 'text-zinc-500'}`}>+ {items.map((m, i) => <li key={i}>{m}</li>)}+ </ul>+ </div>+ );++/** What the import will create. Each bot can be left out. */+export const PreviewView: React.FC<{ preview: Preview; skip: ReadonlySet<string>; onToggle: (ref: string) => void }> = ({ preview, skip, onToggle }) => {+ const { bots, general } = previewRows(preview);+ const teams = preview.bundle.teams ?? [];+ const shared = preview.bundle.skills ?? [];+ const omitted = preview.bundle.omitted ?? [];+ const kept = bots.filter((b) => !skip.has(b.ref)).length;+ const from = sourceName(preview.bundle.source.kind);+ return (+ <div className="space-y-3">+ <p className="text-xs text-zinc-300">+ {bots.length > 0 ? `${plural(kept, 'bot')} will be created` : 'No bots in this one'}+ {from ? ` from ${from}` : ''}. Untick any you don’t want.+ </p>+ <Notes items={general.problems} tone="problem" label="Must be fixed before importing" />+ <ul className="space-y-2">+ {bots.map((b) => {+ const off = skip.has(b.ref);+ return (+ <li key={b.ref} className={`${card} p-3 space-y-2 ${off ? 'opacity-50' : ''}`}>+ <label className="flex items-start gap-2.5 cursor-pointer">+ <input type="checkbox" checked={!off} onChange={() => onToggle(b.ref)} className="mt-0.5 accent-sky-500" aria-label={`Import ${b.name}`} />+ <span className="flex-1 min-w-0">+ <span className="block text-sm font-medium text-zinc-100 break-words">{b.name}</span>+ {b.renamedFrom && (+ <span className="block text-[11px] text-amber-300">+ Renamed from {b.renamedFrom}: that name is already taken here.+ </span>+ )}+ {b.title && <span className="block text-[11px] text-zinc-500">{b.title}</span>}+ </span>+ </label>+ {b.excerpt && <p className="text-[11px] text-zinc-400 italic break-words">“{b.excerpt}”</p>}+ <p className="text-[11px] text-zinc-500">+ {plural(b.memories, 'memory', 'memories')} · {plural(b.skills, 'skill')} · {plural(b.routines, 'routine')}+ </p>+ <Notes items={b.problems} tone="problem" label="Must be fixed before importing" />+ <Notes items={b.warnings} tone="warn" label="Worth a look" />+ <Notes items={b.dropped} tone="drop" label="Not brought over" />+ </li>+ );+ })}+ </ul>+ {(teams.length > 0 || shared.length > 0) && (+ <p className="text-[11px] text-zinc-400">+ Also: {[teams.length ? plural(teams.length, 'team') : '', shared.length ? plural(shared.length, 'shared skill') : ''].filter(Boolean).join(' and ')}+ {teams.length ? ` (${teams.map((t) => t.name).join(', ')})` : ''}.+ </p>+ )}+ <Notes items={general.warnings} tone="warn" label="Worth a look" />+ <Notes items={[...general.dropped, ...omitted]} tone="drop" label="Not brought over" />+ <p className="flex gap-2 text-[11px] text-zinc-400 rounded-lg bg-zinc-900/60 p-2.5">+ <Info size={13} className="shrink-0 mt-px text-sky-400" aria-hidden="true" />+ <span>To keep you safe, imported bots start with no tools, their skills wait for your OK, and routines start paused. Keys are removed.</span>+ </p>+ </div>+ );+};++export type UndoState =+ | { kind: 'idle' }+ | { kind: 'busy' }+ | { kind: 'confirm_edited'; names: string[] }+ | { kind: 'in_use'; names: string[] }+ | { kind: 'undone' }+ | { kind: 'error'; error: unknown };++/** After Import: what was made, and Undo. */+export const DoneView: React.FC<{ applied: Applied; undo: UndoState; onUndo: (force: boolean) => void; onKeep: () => void }> = ({ applied, undo, onUndo, onKeep }) => {+ const c = applied.import.created;+ const names = c.kwants.map((k) => k.name);+ if (undo.kind === 'undone') {+ return (+ <div className="space-y-2" role="status">+ <p className="flex items-center gap-2 text-sm text-zinc-100">+ <Undo2 size={16} className="text-sky-400" /> Import undone+ </p>+ <p className="text-xs text-zinc-400">{names.length ? `${names.join(', ')} ${names.length === 1 ? 'was' : 'were'} removed.` : 'Everything it made was removed.'}</p>+ </div>+ );+ }+ const extras = [+ c.teams.length ? plural(c.teams.length, 'team') : '',+ c.skills.length ? `${plural(c.skills.length, 'skill')} to review` : '',+ c.routines.length ? `${plural(c.routines.length, 'paused routine')}` : '',+ c.memories ? plural(c.memories, 'memory', 'memories') : '',+ ].filter(Boolean);+ return (+ <div className="space-y-3">+ <div role="status" className="space-y-1">+ <p className="flex items-center gap-2 text-sm text-zinc-100">+ <Check size={16} className="text-emerald-400" /> Imported {plural(names.length, 'bot')}+ </p>+ {names.length > 0 && <p className="text-xs text-zinc-300 break-words">{names.join(', ')}</p>}+ {extras.length > 0 && <p className="text-[11px] text-zinc-500">Also {extras.join(', ')}.</p>}+ </div>+ <Notes items={applied.warnings.map((n) => n.message)} tone="warn" label="Worth a look" />+ <p className="text-[11px] text-zinc-400">Give them an account and tools in Space settings when you’re ready. Skills and routines are there to review.</p>+ {undo.kind === 'confirm_edited' && (+ <div role="alert" className="rounded-lg border border-amber-500/40 bg-amber-500/10 p-3 space-y-2">+ <p className="text-xs text-amber-100">+ {undo.names.join(', ')} changed since the import. Undo anyway removes {undo.names.length === 1 ? 'it' : 'them'} with your changes.+ </p>+ <div className="flex flex-wrap gap-2">+ <button type="button" onClick={onKeep} className={btn}>Keep them</button>+ <button type="button" onClick={() => onUndo(true)} className={danger}>Undo anyway</button>+ </div>+ </div>+ )}+ {undo.kind === 'in_use' && (+ <div role="alert" className="rounded-lg border border-zinc-700 bg-zinc-900 p-3">+ <p className="text-xs text-zinc-300">+ {undo.names.length ? `${undo.names.join(', ')} ${undo.names.length === 1 ? 'has' : 'have'}` : 'Something it made has'} already been used, so this import can’t be undone in one step. Delete those bots yourself in Kwant bots.+ </p>+ </div>+ )}+ {undo.kind === 'error' && <ErrorBox error={undo.error} />}+ </div>+ );+};++type Step = { kind: 'choose' } | { kind: 'prompt'; prompt: ExportPrompt } | { kind: 'upload' } | { kind: 'preview'; from: 'prompt' | 'upload'; prompt?: ExportPrompt } | { kind: 'done' };++interface Props {+ spaceName: string;+ onClose: () => void;+ /** After Import or Undo, so the sidebar and lists load again. */+ onChanged: () => void;+}++/** "Import bots": pick a source, paste a reply or upload a file, check the preview, import, undo. */+export const ImportDialog: React.FC<Props> = ({ spaceName, onClose, onChanged }) => {+ const [step, setStep] = useState<Step>({ kind: 'choose' });+ const [prompts, setPrompts] = useState<ExportPrompt[] | null>(null);+ const [promptsError, setPromptsError] = useState<unknown>(null);+ const [reply, setReply] = useState('');+ const [copied, setCopied] = useState(false);+ const [file, setFile] = useState<File | null>(null);+ const [preview, setPreview] = useState<Preview | null>(null);+ const [skip, setSkip] = useState<Set<string>>(new Set());+ const [busy, setBusy] = useState(false);+ const [error, setError] = useState<unknown>(null);+ const [applied, setApplied] = useState<Applied | null>(null);+ const [undo, setUndo] = useState<UndoState>({ kind: 'idle' });+ const fileRef = useRef<HTMLInputElement>(null);+ const bodyRef = useRef<HTMLDivElement>(null);+ const closeRef = useRef(onClose);+ closeRef.current = onClose;++ const loadPrompts = () => {+ setPromptsError(null);+ importApi.prompts().then(setPrompts, setPromptsError);+ };+ useEffect(loadPrompts, []);+ useEffect(() => {+ const onKey = (e: KeyboardEvent) => {+ // Space settings underneath leaves Escape to this dialog while it's open.+ if (e.key === 'Escape') closeRef.current();+ };+ window.addEventListener('keydown', onKey);+ return () => window.removeEventListener('keydown', onKey);+ }, []);+ // Each step starts at the top, with focus inside the dialog.+ useEffect(() => {+ bodyRef.current?.scrollTo?.(0, 0);+ bodyRef.current?.querySelector<HTMLElement>('button, textarea, input, [tabindex="0"]')?.focus();+ }, [step.kind]);++ const go = (s: Step) => {+ setError(null);+ setStep(s);+ };++ const copy = async () => {+ if (step.kind !== 'prompt') return;+ try {+ await navigator.clipboard.writeText(step.prompt.prompt);+ setCopied(true);+ setTimeout(() => setCopied(false), 2000);+ } catch {+ // No clipboard (plain http): select the text so Ctrl+C works.+ const pre = bodyRef.current?.querySelector('pre');+ if (pre) window.getSelection()?.selectAllChildren(pre);+ }+ };++ const check = async () => {+ setBusy(true);+ setError(null);+ // From the preview ("Check again" after a name was taken), read the same input again.+ const prompt = step.kind === 'prompt' ? step.prompt : step.kind === 'preview' ? step.prompt : undefined;+ try {+ const p = prompt ? await importApi.previewText(reply) : file ? await importApi.previewFile(file, file.name) : null;+ if (!p) return;+ setPreview(p);+ setSkip(new Set());+ go({ kind: 'preview', from: prompt ? 'prompt' : 'upload', prompt });+ } catch (err) {+ setError(err);+ } finally {+ setBusy(false);+ }+ };++ const doImport = async () => {+ if (!preview) return;+ setBusy(true);+ setError(null);+ try {+ const a = await importApi.apply(preview.bundle, [...skip]);+ setApplied(a);+ setUndo({ kind: 'idle' });+ go({ kind: 'done' });+ onChanged();+ } catch (err) {+ setError(err);+ } finally {+ setBusy(false);+ }+ };++ const doUndo = async (force: boolean) => {+ if (!applied) return;+ setUndo({ kind: 'busy' });+ try {+ await importApi.undo(applied.import.id, force);+ setUndo({ kind: 'undone' });+ onChanged();+ } catch (err) {+ if (err instanceof ImportError && err.code === 'edited') setUndo({ kind: 'confirm_edited', names: err.names });+ else if (err instanceof ImportError && err.code === 'in_use') setUndo({ kind: 'in_use', names: err.names });+ else if (err instanceof ImportError && err.code === 'already_undone') setUndo({ kind: 'undone' });+ else setUndo({ kind: 'error', error: err });+ }+ };++ const back = () => {+ if (step.kind === 'prompt' || step.kind === 'upload') go({ kind: 'choose' });+ else if (step.kind === 'preview') go(step.from === 'prompt' && step.prompt ? { kind: 'prompt', prompt: step.prompt } : { kind: 'upload' });+ };++ const title =+ step.kind === 'prompt' ? `Bring a bot from ${step.prompt.label}` : step.kind === 'upload' ? 'Upload a file' : step.kind === 'preview' ? 'Check before importing' : step.kind === 'done' ? 'Import bots' : `Import bots into ${spaceName}`;++ let footer: React.ReactNode = null;+ if (step.kind === 'prompt' || step.kind === 'upload') {+ const ready = step.kind === 'prompt' ? reply.trim() !== '' && !textTooLong(reply) : !!file && !fileTooBig(file.size);+ footer = (+ <button type="button" onClick={check} disabled={!ready || busy} className={primary}>+ {busy && <Loader2 size={13} className="animate-spin motion-reduce:animate-none" />} {busy ? 'Reading…' : 'Preview'}+ </button>+ );+ } else if (step.kind === 'preview' && preview) {+ const n = preview.bundle.bots.filter((b) => !skip.has(b.ref)).length;+ const isNameRace = error instanceof ImportError && error.code === 'name_taken';+ footer = isNameRace ? (+ <button type="button" onClick={check} disabled={busy} className={primary}>+ Check again+ </button>+ ) : (+ <button type="button" onClick={doImport} disabled={!canImport(preview, skip) || busy} className={primary}>+ {busy && <Loader2 size={13} className="animate-spin motion-reduce:animate-none" />} {busy ? 'Importing…' : n > 0 ? `Import ${plural(n, 'bot')}` : 'Import'}+ </button>+ );+ } else if (step.kind === 'done' && applied) {+ footer = (+ <>+ {undo.kind !== 'undone' && undo.kind !== 'confirm_edited' && undo.kind !== 'in_use' && (+ <button type="button" onClick={() => doUndo(false)} disabled={undo.kind === 'busy'} className={btn}>+ {undo.kind === 'busy' ? <Loader2 size={13} className="animate-spin motion-reduce:animate-none" /> : <Undo2 size={13} />} Undo import+ </button>+ )}+ <button type="button" onClick={onClose} className={primary}>Done</button>+ </>+ );+ }++ return (+ <div className="fixed inset-0 z-50 bg-black/75 backdrop-blur-sm flex sm:items-center justify-center sm:p-4" onMouseDown={(e) => e.target === e.currentTarget && onClose()}>+ <div+ role="dialog"+ aria-modal="true"+ aria-labelledby="import-title"+ className="bg-zinc-900 sm:border border-zinc-800 sm:rounded-2xl w-full sm:max-w-xl h-full sm:h-auto sm:max-h-[90vh] flex flex-col text-zinc-100 shadow-2xl"+ >+ <div className="flex items-center gap-2 border-b border-zinc-800 px-4 py-3">+ {step.kind !== 'choose' && step.kind !== 'done' && (+ <button type="button" onClick={back} aria-label="Back" className="p-1.5 -ml-1 rounded-lg text-zinc-400 hover:text-zinc-100 hover:bg-zinc-800">+ <ArrowLeft size={17} />+ </button>+ )}+ <h2 id="import-title" className="flex-1 min-w-0 text-sm font-semibold truncate">{title}</h2>+ <button type="button" onClick={onClose} aria-label="Close" className="p-1.5 rounded-lg text-zinc-400 hover:text-zinc-100 hover:bg-zinc-800">+ <X size={18} />+ </button>+ </div>+ <div ref={bodyRef} className="flex-1 overflow-y-auto p-4 space-y-3">+ {step.kind === 'choose' && (+ <SourceList prompts={prompts} error={promptsError} onRetry={loadPrompts} onPick={(p) => go({ kind: 'prompt', prompt: p })} onUpload={() => go({ kind: 'upload' })} />+ )}+ {step.kind === 'prompt' && (+ <PromptStep prompt={step.prompt} reply={reply} onReply={setReply} copied={copied} onCopy={copy} />+ )}+ {step.kind === 'upload' && <UploadStep file={file} onFile={setFile} inputRef={fileRef} />}+ {step.kind === 'preview' && preview && (+ <PreviewView+ preview={preview}+ skip={skip}+ onToggle={(ref) =>+ setSkip((s) => {+ const next = new Set(s);+ if (next.has(ref)) next.delete(ref);+ else next.add(ref);+ return next;+ })+ }+ />+ )}+ {step.kind === 'done' && applied && <DoneView applied={applied} undo={undo} onUndo={doUndo} onKeep={() => setUndo({ kind: 'idle' })} />}+ {error != null && <ErrorBox error={error} />}+ </div>+ {footer && <div className="flex flex-wrap justify-end gap-2 border-t border-zinc-800 px-4 py-3">{footer}</div>}+ </div>+ </div>+ );+};++/** Recent imports in this space, each with Undo while it still applies. */+export const RecentImports: React.FC<{ records: ImportRecord[]; onUndo: (r: ImportRecord) => void; busyId: string | null }> = ({ records, onUndo, busyId }) => {+ if (records.length === 0) return <p className="text-[11px] text-zinc-500">No imports yet.</p>;+ return (+ <ul className="space-y-1.5">+ {records.slice(0, 10).map((r) => {+ const names = r.created.kwants.map((k) => k.name);+ return (+ <li key={r.id} className={`${card} flex items-center gap-3 p-2.5`}>+ <div className="flex-1 min-w-0">+ <p className="text-xs text-zinc-200 truncate">{names.length ? names.join(', ') : 'Skills only'}</p>+ <p className="text-[11px] text-zinc-500">+ {new Date(r.created_at).toLocaleString(undefined, { dateStyle: 'medium', timeStyle: 'short' })}+ {r.status === 'undone' ? ' · undone' : ''}+ </p>+ </div>+ {r.status === 'applied' && (+ <button type="button" onClick={() => onUndo(r)} disabled={busyId === r.id} className={btn} aria-label={`Undo import of ${names.join(', ') || 'skills'}`}>+ {busyId === r.id ? <Loader2 size={12} className="animate-spin motion-reduce:animate-none" /> : <Undo2 size={12} />} Undo+ </button>+ )}+ </li>+ );+ })}+ </ul>+ );+};diff --git a/frontend/src/components/SpaceSettings.tsx b/frontend/src/components/SpaceSettings.tsxindex 25fe4ac5..afb67ed4 100644--- a/frontend/src/components/SpaceSettings.tsx+++ b/frontend/src/components/SpaceSettings.tsx@@ -6,6 +6,8 @@ import {Bot,CalendarClock,Check,+ Download,+ FileUp,KeyRound,Loader2,Pencil,@@ -27,9 +29,11 @@ import { RoutinesPanel, type RoutineFocus } from './RoutinesPanel';import { HirePolicyPanel } from './HirePolicyPanel';import { ModernAvatar } from './ModernAvatar';import { SpaceTile } from './Spaces';+import { ImportDialog, RecentImports } from './ImportDialog';+import { ImportError, ImportRecord, downloadExport, importApi, importErrorText } from '../imports';import { memberIdsOf, type Channel, type Kwant, type Team } from './Sidebar';-export type SpaceSettingsTab = 'general' | 'accounts' | 'bots' | 'teams' | 'tools' | 'skills' | 'routines';+export type SpaceSettingsTab = 'general' | 'accounts' | 'bots' | 'teams' | 'tools' | 'skills' | 'routines' | 'import';const TABS: Array<{ id: SpaceSettingsTab; label: string; icon: React.ReactNode }> = [{ id: 'general', label: 'General', icon: <Settings2 size={15} /> },@@ -39,6 +43,7 @@ const TABS: Array<{ id: SpaceSettingsTab; label: string; icon: React.ReactNode }{ id: 'tools', label: 'Tools', icon: <Plug size={15} /> },{ id: 'skills', label: 'Skills', icon: <Sparkles size={15} /> },{ id: 'routines', label: 'Routines', icon: <CalendarClock size={15} /> },+ { id: 'import', label: 'Import & export', icon: <FileUp size={15} /> },];interface Props {@@ -66,8 +71,13 @@ interface Props {onOpenAppSettings: () => void;/** Set by a routine card's Edit or Pause: opens that routine in Routines. */routineFocus?: RoutineFocus | null;+ /** After an import or its undo: load bots, teams and chats again. */+ onImported?: () => void;}+/** What the tabs get on top of the props: opening the Import dialog. */+type TabProps = Props & { onOpenImport: () => void; importsSeq: number };+const card = 'rounded-xl border border-zinc-800 bg-zinc-950/60';const rowBtn ='flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg text-xs font-medium text-zinc-300 border border-zinc-700/60 bg-zinc-800/60 hover:bg-zinc-700/70 hover:text-zinc-100 transition-colors';@@ -77,6 +87,10 @@ const primaryBtn =/** Space settings: everything here belongs to the open space only. */export const SpaceSettings: React.FC<Props> = (p) => {const { space, tab, onTab, onClose } = p;+ const [importOpen, setImportOpen] = useState(false);+ // Bumped after the dialog imports or undoes, so the Import tab's list loads again.+ const [importsSeq, setImportsSeq] = useState(0);+ const tp: TabProps = { ...p, onOpenImport: () => setImportOpen(true), importsSeq };const closeRef = useRef(onClose);closeRef.current = onClose;useEffect(() => {@@ -147,7 +161,7 @@ export const SpaceSettings: React.FC<Props> = (p) => {</div>{tab === 'general' && <GeneralTab {...p} />}{tab === 'accounts' && <AccountsTab {...p} />}- {tab === 'bots' && <BotsTab {...p} />}+ {tab === 'bots' && <BotsTab {...tp} />}{tab === 'teams' && <TeamsTab {...p} />}{tab === 'tools' && (<div className={`${card} p-4 space-y-3`}>@@ -159,6 +173,7 @@ export const SpaceSettings: React.FC<Props> = (p) => {)}{tab === 'skills' && <SkillsTab {...p} />}{tab === 'routines' && <RoutinesPanel kwants={p.kwants} channels={p.channels} focus={p.routineFocus} />}+ {tab === 'import' && <ImportTab {...tp} />}<div className="md:hidden pt-2"><button type="button" onClick={p.onOpenAppSettings} className="flex items-center gap-2 text-xs text-zinc-400 hover:text-zinc-100"><Settings size={14} /> App settings (every space)@@ -166,10 +181,116 @@ export const SpaceSettings: React.FC<Props> = (p) => {</div></div></div>+ {importOpen && (+ <ImportDialog+ spaceName={space.name}+ onClose={() => setImportOpen(false)}+ onChanged={() => {+ setImportsSeq((n) => n + 1);+ p.onImported?.();+ }}+ />+ )}</div>);};+/** Export one bot or the whole space; shows a short error under the button if it fails. */+function useExport() {+ const [busy, setBusy] = useState<string | null>(null);+ const [error, setError] = useState<{ key: string; text: string } | null>(null);+ const run = async (key: string, kwantId?: string) => {+ setBusy(key);+ setError(null);+ try {+ await downloadExport(kwantId);+ } catch (err) {+ setError({ key, text: importErrorText(err).detail || 'The export didn’t work.' });+ } finally {+ setBusy(null);+ }+ };+ return { busy, error, run };+}++const ImportTab: React.FC<TabProps> = ({ space, kwants, onOpenImport, onImported, importsSeq }) => {+ const exp = useExport();+ const [records, setRecords] = useState<ImportRecord[] | null>(null);+ const [listError, setListError] = useState<unknown>(null);+ const [undoing, setUndoing] = useState<string | null>(null);+ const [confirm, setConfirm] = useState<{ record: ImportRecord; names: string[] } | null>(null);+ const [notice, setNotice] = useState<string | null>(null);+ const load = () => importApi.list().then((r) => { setRecords(r); setListError(null); }, setListError);+ useEffect(() => {+ load();+ }, [space.id, importsSeq]);++ const undo = async (r: ImportRecord, force = false) => {+ setUndoing(r.id);+ setConfirm(null);+ setNotice(null);+ try {+ await importApi.undo(r.id, force);+ setNotice('Import undone.');+ onImported?.();+ } catch (err) {+ if (err instanceof ImportError && err.code === 'edited') setConfirm({ record: r, names: err.names });+ else if (err instanceof ImportError && err.code === 'in_use')+ setNotice(`${err.names.join(', ') || 'Something it made'} has already been used, so this import can’t be undone in one step. Delete those bots yourself in Kwant bots.`);+ else setNotice(importErrorText(err).detail || importErrorText(err).title);+ } finally {+ setUndoing(null);+ load();+ }+ };++ return (+ <>+ <div className={`${card} p-4 space-y-3`}>+ <p className="text-xs font-medium text-zinc-200">Bring bots from another app</p>+ <p className="text-[11px] text-zinc-500">From Grok, ChatGPT, Claude or any other bot, or from a file. You check a preview first, and you can undo it.</p>+ <button type="button" onClick={onOpenImport} className={primaryBtn}>+ <FileUp size={13} /> Import bots+ </button>+ </div>+ <div className={`${card} p-4 space-y-3`}>+ <p className="text-xs font-medium text-zinc-200">Export {space.name}</p>+ <p className="text-[11px] text-zinc-500">+ Downloads {kwants.length === 1 ? 'its bot' : `its ${kwants.length} bots`}, teams and shared skills as one file you can import again. Chat history, files, tools and keys are never included.+ </p>+ <button type="button" onClick={() => exp.run('space')} disabled={exp.busy === 'space' || kwants.length === 0} className={rowBtn}>+ {exp.busy === 'space' ? <Loader2 size={13} className="animate-spin motion-reduce:animate-none" /> : <Download size={13} />} Export space+ </button>+ {exp.error && <p role="alert" className="text-[11px] text-rose-300">{exp.error.text}</p>}+ </div>+ <div className="space-y-2">+ <p className="text-xs font-medium text-zinc-300">Recent imports</p>+ {confirm && (+ <div role="alert" className="rounded-lg border border-amber-500/40 bg-amber-500/10 p-3 space-y-2">+ <p className="text-xs text-amber-100">+ {confirm.names.join(', ')} changed since the import. Undo anyway removes {confirm.names.length === 1 ? 'it' : 'them'} with your changes.+ </p>+ <div className="flex flex-wrap gap-2">+ <button type="button" onClick={() => setConfirm(null)} className={rowBtn}>Keep them</button>+ <button type="button" onClick={() => undo(confirm.record, true)} className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium text-white bg-rose-600 hover:bg-rose-500">+ Undo anyway+ </button>+ </div>+ </div>+ )}+ {notice && <p role="status" className="text-[11px] text-zinc-300">{notice}</p>}+ {listError ? (+ <p role="alert" className="text-[11px] text-rose-300">{importErrorText(listError).detail || 'Couldn’t load the imports.'}</p>+ ) : records ? (+ <RecentImports records={records} busyId={undoing} onUndo={(r) => undo(r)} />+ ) : (+ <p className="text-[11px] text-zinc-500">Loading…</p>+ )}+ </div>+ </>+ );+};+const GeneralTab: React.FC<Props> = ({ space, spaces, onSpaceSaved, onArchived }) => {const [name, setName] = useState(space.name);const [icon, setIcon] = useState(space.icon);@@ -335,16 +456,24 @@ const AccountsTab: React.FC<Props> = ({ space, focusClaudeSignIn, onProfilesChan);};-const BotsTab: React.FC<Props> = ({ space, kwants, onNewBot, onEditBot }) => (+const BotsTab: React.FC<TabProps> = ({ space, kwants, onNewBot, onEditBot, onOpenImport }) => {+ const exp = useExport();+ return (<div className="space-y-3">- <div className="flex items-center justify-between gap-3">+ <div className="flex flex-wrap items-center justify-between gap-3"><p className="text-xs text-zinc-400">{kwants.length} {kwants.length === 1 ? 'bot' : 'bots'} in {space.name}. Laya only picks from these.</p>- <button type="button" onClick={onNewBot} className={primaryBtn}>- <Plus size={13} /> New bot- </button>+ <div className="flex gap-2">+ <button type="button" onClick={onOpenImport} className={rowBtn}>+ <FileUp size={13} /> Import bots+ </button>+ <button type="button" onClick={onNewBot} className={primaryBtn}>+ <Plus size={13} /> New bot+ </button>+ </div></div>+ {exp.error && <p role="alert" className="text-[11px] text-rose-300">{exp.error.text}</p>}<ul className="space-y-1.5">{kwants.map((k) => (<li key={k.id} className={`${card} flex items-center gap-3 p-2.5`}>@@ -353,16 +482,21 @@ const BotsTab: React.FC<Props> = ({ space, kwants, onNewBot, onEditBot }) => (<p className="text-xs font-medium text-zinc-200 truncate">{k.name}</p><p className="text-[11px] text-zinc-500 truncate">{k.title}</p></div>+ <button type="button" onClick={() => exp.run(k.id, k.id)} disabled={exp.busy === k.id} className={rowBtn} aria-label={`Export ${k.name}`} title="Download as a file">+ {exp.busy === k.id ? <Loader2 size={12} className="animate-spin motion-reduce:animate-none" /> : <Download size={12} />}+ <span className="hidden sm:inline">Export</span>+ </button><button type="button" onClick={() => onEditBot(k)} className={rowBtn} aria-label={`Edit ${k.name}`}><Pencil size={12} /> Edit</button></li>))}</ul>- {kwants.length === 0 && <p className="text-xs text-zinc-500">No bots yet. New spaces start empty.</p>}+ {kwants.length === 0 && <p className="text-xs text-zinc-500">No bots yet. New spaces start empty. Make one, or import bots from another app.</p>}<HirePolicyPanel key={space.id} spaceId={space.id} spaceName={space.name} /></div>-);+ );+};const TeamsTab: React.FC<Props> = ({ space, teams, kwants, onNewTeam, onManageTeam }) => (<div className="space-y-3">diff --git a/frontend/src/imports.ts b/frontend/src/imports.tsnew file mode 100644index 00000000..7532e2f1--- /dev/null+++ b/frontend/src/imports.ts@@ -0,0 +1,315 @@+// Bring bots over from another app, and export them again (IMPORT-API.md). The export prompt+// text lives only on the server (src/import/prompts.rs); this file never copies it.++export type ImportSourceId = 'grok' | 'chatgpt' | 'claude' | 'other';++export interface ExportPrompt {+ id: ImportSourceId | string;+ label: string;+ where_to_send: string;+ prompt: string;+}++export interface BundleSkill {+ name: string;+ description: string;+ body: string;+}++export interface BundleRoutine {+ name: string;+ instructions: string;+ schedule: unknown;+ schedule_text?: string | null;+}++export interface BundleBot {+ ref: string;+ name: string;+ title?: string | null;+ persona_prompt?: string | null;+ soul?: string | null;+ avatar_hint?: string | null;+ model_hint?: string | null;+ starters?: string[];+ memories?: string[];+ skills?: BundleSkill[];+ routines?: BundleRoutine[];+ tool_hints?: string[];+ knowledge_files?: string[];+}++export interface BundleTeam {+ name: string;+ lead?: string | null;+ members: string[];+ instructions?: string | null;+}++export interface Bundle {+ format: string;+ source: { kind: string; label?: string | null; exported_at?: string | null };+ bots: BundleBot[];+ teams?: BundleTeam[];+ skills?: BundleSkill[];+ omitted?: string[];+}++export interface Notice {+ /** The bot's ref, absent for notices about the whole import. */+ bot?: string;+ message: string;+}++export interface Rename {+ ref: string;+ from: string;+ to: string;+}++export interface Preview {+ bundle: Bundle;+ warnings: Notice[];+ dropped: Notice[];+ problems: Notice[];+ renames: Rename[];+ can_apply: boolean;+}++export interface ImportRecord {+ id: string;+ space_id: string;+ source_kind: string;+ status: 'applied' | 'undone';+ created: {+ kwants: Array<{ ref: string; id: string; name: string; fingerprint?: string }>;+ skills: string[];+ routines: string[];+ teams: string[];+ channels: string[];+ memories: number;+ };+ created_at: string;+ undone_at: string | null;+}++export interface Applied {+ import: ImportRecord;+ warnings: Notice[];+ dropped: Notice[];+ renames: Rename[];+}++/** An import route's `{error, code}` reply, or a network failure (`code: 'network'`). */+export class ImportError extends Error {+ constructor(+ message: string,+ readonly code: string,+ readonly status: number,+ /** `edited` / `in_use`: the names involved. */+ readonly names: string[] = [],+ readonly problems: Notice[] = [],+ ) {+ super(message);+ }+}++/** Limits the server enforces, checked first so a big file fails before it uploads. */+export const IMPORT_LIMITS = { fileBytes: 20 * 1024 * 1024, textChars: 256 * 1024 } as const;++/** Files the "Upload a file" step accepts (the server sniffs the content anyway). */+export const IMPORT_ACCEPT = '.json,.md,.png,.zip,.txt';++const enc = encodeURIComponent;++async function call<T>(method: string, url: string, init: RequestInit = {}): Promise<T> {+ let res: Response;+ try {+ res = await fetch(url, { method, ...init });+ } catch {+ throw new ImportError('Couldn’t reach the server. Check your connection and try again.', 'network', 0);+ }+ if (!res.ok) {+ let data: any = null;+ try {+ data = await res.json();+ } catch {+ // no JSON body+ }+ const names = Array.isArray(data?.edited) ? data.edited : Array.isArray(data?.in_use) ? data.in_use : [];+ throw new ImportError(+ typeof data?.error === 'string' && data.error ? data.error : '',+ typeof data?.code === 'string' ? data.code : res.status === 413 ? 'too_large' : res.status === 404 ? 'not_found' : 'internal',+ res.status,+ names.filter((n: unknown): n is string => typeof n === 'string'),+ Array.isArray(data?.problems) ? data.problems : [],+ );+ }+ return res.json();+}++const json = (body: unknown): RequestInit => ({ headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });++export const importApi = {+ prompts: () => call<ExportPrompt[]>('GET', '/api/import/prompts'),+ previewText: (text: string) => call<Preview>('POST', '/api/import/preview', json({ text })),+ previewFile: (file: Blob, filename: string) =>+ call<Preview>('POST', `/api/import/preview?filename=${enc(filename)}`, {+ headers: { 'Content-Type': 'application/octet-stream' },+ body: file,+ }),+ apply: (bundle: Bundle, skip: string[]) => call<Applied>('POST', '/api/import/apply', json({ bundle, skip })),+ list: () => call<ImportRecord[]>('GET', '/api/imports'),+ undo: (id: string, force = false) => call<ImportRecord>('POST', `/api/imports/${enc(id)}/undo`, force ? json({ force: true }) : {}),+};++/** What to tell the person for an import error: a short heading, and the server's sentence (or ours). */+export function importErrorText(err: unknown): { title: string; detail: string } {+ const e = err instanceof ImportError ? err : null;+ const detail = e?.message || '';+ switch (e?.code) {+ case 'too_large':+ return { title: 'That’s too big to import', detail: detail || 'Files can be up to 20 MB, and pasted replies up to 256 KB.' };+ case 'unsupported':+ return {+ title: 'We can’t read that kind of file',+ detail: detail || 'Try a .json, .md, .png character card or .zip, or paste the reply your bot gave you.',+ };+ case 'invalid':+ return { title: 'Something in it isn’t right', detail: detail || 'It looks like a file we know, but part of it is broken.' };+ case 'empty':+ return { title: 'Nothing to import', detail: detail || 'It was empty, or every bot was left out.' };+ case 'problems':+ return { title: 'Fix these first', detail: detail || 'Some bots can’t be imported as they are.' };+ case 'name_taken':+ return { title: 'A name was just taken', detail: detail || 'Someone made a bot with the same name. Check the preview again.' };+ case 'not_found':+ return { title: 'That import is gone', detail: detail || 'It may have been in another space.' };+ case 'network':+ return { title: 'No connection', detail };+ default:+ return { title: 'Something went wrong', detail: 'The server couldn’t finish this. Try again in a moment.' };+ }+}++/** Client-side checks before anything is sent. */+export function fileTooBig(size: number): boolean {+ return size > IMPORT_LIMITS.fileBytes;+}+export function textTooLong(text: string): boolean {+ return text.length > IMPORT_LIMITS.textChars;+}++export interface PreviewBotRow {+ ref: string;+ name: string;+ /** The name before a clash rename, when it was renamed. */+ renamedFrom: string | null;+ title: string;+ excerpt: string;+ memories: number;+ skills: number;+ routines: number;+ warnings: string[];+ dropped: string[];+ problems: string[];+}++const EXCERPT = 180;++/** One row per bot for the preview, with its own notices, and the notices for the whole import. */+export function previewRows(p: Preview): { bots: PreviewBotRow[]; general: { warnings: string[]; dropped: string[]; problems: string[] } } {+ const refs = new Set(p.bundle.bots.map((b) => b.ref));+ const forBot = (list: Notice[], ref: string) => list.filter((n) => n.bot === ref).map((n) => n.message);+ const general = (list: Notice[]) => list.filter((n) => !n.bot || !refs.has(n.bot)).map((n) => n.message);+ const bots = p.bundle.bots.map((b) => {+ const rename = p.renames.find((r) => r.ref === b.ref);+ const text = (b.persona_prompt || b.soul || '').replace(/\s+/g, ' ').trim();+ return {+ ref: b.ref,+ name: rename?.to ?? b.name,+ renamedFrom: rename && rename.from !== rename.to ? rename.from : null,+ title: b.title ?? '',+ excerpt: text.length > EXCERPT ? `${text.slice(0, EXCERPT - 1).trimEnd()}…` : text,+ memories: b.memories?.length ?? 0,+ skills: b.skills?.length ?? 0,+ routines: b.routines?.length ?? 0,+ warnings: forBot(p.warnings, b.ref),+ dropped: forBot(p.dropped, b.ref),+ problems: forBot(p.problems, b.ref),+ };+ });+ return { bots, general: { warnings: general(p.warnings), dropped: general(p.dropped), problems: general(p.problems) } };+}++/** Whether Import can be pressed: the server says yes, and at least one bot (or shared skill) is left. */+export function canImport(p: Preview, skip: ReadonlySet<string>): boolean {+ if (!p.can_apply) return false;+ return p.bundle.bots.some((b) => !skip.has(b.ref)) || (p.bundle.skills?.length ?? 0) > 0;+}++const SOURCE_NAMES: Record<string, string> = {+ grok: 'Grok',+ chatgpt: 'ChatGPT',+ claude: 'Claude',+ 'claude-code': 'a Claude Code file',+ skill: 'a SKILL.md',+ 'character-card': 'a character card',+ grokbot: 'Grok Bot',+ openmaus: 'OpenMausBot',+ 'openmaus-grok': 'OpenMausBot',+ zip: 'a zip',+};++/** Where an import comes from, for "from …". `source.label` is often a bot name, so it isn't used. */+export const sourceName = (kind: string): string | null => SOURCE_NAMES[kind] ?? null;++export const plural = (n: number, one: string, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;++/** The file name from `Content-Disposition`, or a fallback. */+export function downloadName(header: string | null, fallback: string): string {+ if (header) {+ const star = /filename\*=UTF-8''([^;]+)/i.exec(header);+ if (star) {+ try {+ return decodeURIComponent(star[1].trim());+ } catch {+ // fall through to the plain name+ }+ }+ const plain = /filename="?([^";]+)"?/i.exec(header);+ if (plain) return plain[1].trim();+ }+ return fallback;+}++/** Downloads a bot (`kwantId`) or the whole open space as a bundle file. */+export async function downloadExport(kwantId?: string): Promise<string> {+ const url = kwantId ? `/api/kwants/${enc(kwantId)}/export` : '/api/export';+ let res: Response;+ try {+ res = await fetch(url);+ } catch {+ throw new ImportError('Couldn’t reach the server. Check your connection and try again.', 'network', 0);+ }+ if (!res.ok) {+ let msg = '';+ try {+ msg = (await res.json())?.error ?? '';+ } catch {+ // no JSON body+ }+ throw new ImportError(msg || 'The export didn’t work. Try again in a moment.', res.status === 404 ? 'not_found' : 'internal', res.status);+ }+ const name = downloadName(res.headers.get('content-disposition'), 'export.kwant.json');+ const blob = await res.blob();+ const href = URL.createObjectURL(blob);+ const a = document.createElement('a');+ a.href = href;+ a.download = name;+ document.body.appendChild(a);+ a.click();+ a.remove();+ setTimeout(() => URL.revokeObjectURL(href), 1000);+ return name;+}diff --git a/frontend/tests/importDialog.test.mjs b/frontend/tests/importDialog.test.mjsnew file mode 100644index 00000000..17ace9b6--- /dev/null+++ b/frontend/tests/importDialog.test.mjs@@ -0,0 +1,166 @@+import assert from 'node:assert/strict';+import test from 'node:test';+import { loadBundled } from './bundle.mjs';++const m = await loadBundled(`+ export * from './src/imports';+ export { SourceList, PreviewView, DoneView, ErrorBox, RecentImports } from './src/components/ImportDialog';+ export { renderToStaticMarkup } from 'react-dom/server.browser';+ export { createElement } from 'react';+`);+const html = (C, props) => m.renderToStaticMarkup(m.createElement(C, props));+const text = (s) => s.replace(/<[^>]+>/g, ' ').replace(/'|'/g, "'").replace(/"/g, '"').replace(/&/g, '&').replace(/\s+/g, ' ');++// Shaped like the server's preview in IMPORT-API.md.+const preview = (over = {}) => ({+ bundle: {+ format: 'kwant.bundle/1',+ source: { kind: 'openmaus', label: 'OpenMausBot', exported_at: null },+ bots: [+ { ref: 'lead', name: 'Ada', title: 'Tech lead', persona_prompt: 'Plan small steps.\n\nCheck the work. '.repeat(20), memories: ['a', 'b'], skills: [{ name: 'plan', description: '', body: 'x' }], routines: [] },+ { ref: 'qa', name: 'Rigel', title: 'QA', persona_prompt: 'Test it.', memories: [], skills: [], routines: [{ name: 'Friday', instructions: 'x', schedule: {} }] },+ ],+ teams: [{ name: 'Eng', lead: 'lead', members: ['lead', 'qa'] }],+ skills: [],+ omitted: ['Rooms'],+ },+ warnings: [{ bot: 'lead', message: 'We removed things that looked like API keys.' }, { message: 'Model set to auto.' }],+ dropped: [{ bot: 'qa', message: '1 conversation starter(s): no place for them yet.' }],+ problems: [],+ renames: [{ ref: 'lead', from: 'Ada', to: 'Ada-2' }],+ can_apply: true,+ ...over,+});++test('preview rows: renamed names, per-bot notices and a short excerpt', () => {+ const { bots, general } = m.previewRows(preview());+ assert.equal(bots[0].name, 'Ada-2');+ assert.equal(bots[0].renamedFrom, 'Ada');+ assert.equal(bots[1].renamedFrom, null);+ assert.deepEqual([bots[0].memories, bots[0].skills, bots[1].routines], [2, 1, 1]);+ assert.ok(bots[0].excerpt.length <= 180 && bots[0].excerpt.endsWith('…'));+ assert.ok(!bots[0].excerpt.includes('\n'));+ assert.deepEqual(bots[0].warnings, ['We removed things that looked like API keys.']);+ assert.deepEqual(bots[1].dropped, ['1 conversation starter(s): no place for them yet.']);+ assert.deepEqual(general.warnings, ['Model set to auto.']);+});++test('Import needs the server to agree and at least one bot left', () => {+ assert.equal(m.canImport(preview(), new Set()), true);+ assert.equal(m.canImport(preview(), new Set(['lead'])), true);+ assert.equal(m.canImport(preview(), new Set(['lead', 'qa'])), false);+ assert.equal(m.canImport(preview({ can_apply: false }), new Set()), false);+});++test('the preview shows the rename, the notices, the safety note and the count left', () => {+ const out = text(html(m.PreviewView, { preview: preview(), skip: new Set(['qa']), onToggle: () => {} }));+ assert.match(out, /1 bot will be created from OpenMausBot\./);+ // A bot name in source.label is not where it came from.+ const card = text(html(m.PreviewView, { preview: preview({ bundle: { ...preview().bundle, source: { kind: 'kwant', label: 'Recipe Pal' } } }), skip: new Set(), onToggle() {} }));+ assert.match(card, /2 bots will be created\. Untick/);+ assert.match(out, /Ada-2/);+ assert.match(out, /Renamed from Ada: that name is already taken here/);+ assert.match(out, /Worth a look/);+ assert.match(out, /Not brought over .*Rooms/);+ assert.match(out, /1 team and|1 team \(Eng\)/);+ assert.match(out, /start with no tools, their skills wait for your OK, and routines start paused/);+});++test('problems block the import and are shown first', () => {+ const p = preview({ problems: [{ bot: 'qa', message: 'Its instructions are over 16,000 characters.' }], can_apply: false });+ const out = text(html(m.PreviewView, { preview: p, skip: new Set(), onToggle: () => {} }));+ assert.match(out, /Must be fixed before importing .*over 16,000 characters/);+ assert.equal(m.canImport(p, new Set()), false);+});++test('Bring a bot from… lists the sources in the server order, then Upload a file', () => {+ const prompts = ['grok', 'chatgpt', 'claude', 'other'].map((id, i) => ({ id, label: ['Grok', 'ChatGPT', 'Claude', 'Another app'][i], where_to_send: '', prompt: 'p' }));+ const out = text(html(m.SourceList, { prompts, error: null, onPick: () => {}, onUpload: () => {}, onRetry: () => {} }));+ const order = ['Grok', 'ChatGPT', 'Claude', 'Another app', 'Upload a file'].map((w) => out.indexOf(w));+ assert.ok(order.every((n) => n >= 0), out);+ assert.deepEqual([...order].sort((a, b) => a - b), order);+ assert.match(text(html(m.SourceList, { prompts: null, error: null, onPick() {}, onUpload() {}, onRetry() {} })), /Loading/);+ const failed = text(html(m.SourceList, { prompts: null, error: new m.ImportError('', 'network', 0), onPick() {}, onUpload() {}, onRetry() {} }));+ assert.match(failed, /No connection.*Try again/);+});++test('every error code gets a plain heading, and the server’s sentence when it has one', () => {+ const E = (code, msg = '') => m.importErrorText(new m.ImportError(msg, code, 400));+ assert.equal(E('too_large').title, 'That’s too big to import');+ assert.match(E('too_large').detail, /20 MB/);+ assert.equal(E('unsupported').title, 'We can’t read that kind of file');+ assert.equal(E('invalid', 'This zip has a file path that points outside it.').detail, 'This zip has a file path that points outside it.');+ assert.equal(E('empty').title, 'Nothing to import');+ assert.equal(E('problems').title, 'Fix these first');+ assert.equal(E('name_taken').title, 'A name was just taken');+ assert.equal(E('not_found').title, 'That import is gone');+ // A database error never shows its details.+ assert.equal(E('internal', 'sqlite: disk I/O').detail, 'The server couldn’t finish this. Try again in a moment.');+ assert.equal(m.importErrorText(new Error('x')).title, 'Something went wrong');+ const box = text(html(m.ErrorBox, { error: new m.ImportError('', 'problems', 400, [], [{ message: 'Too many bots.' }]) }));+ assert.match(box, /Fix these first.*Too many bots/);+});++test('import errors keep the code and the names the server sends', async () => {+ const real = globalThis.fetch;+ try {+ globalThis.fetch = async () =>+ new Response(JSON.stringify({ code: 'edited', edited: ['Ada'], error: 'Ada changed since the import.' }), { status: 409 });+ await assert.rejects(m.importApi.undo('x'), (e) => e instanceof m.ImportError && e.code === 'edited' && e.names[0] === 'Ada');+ globalThis.fetch = async () => new Response('gateway', { status: 413 });+ await assert.rejects(m.importApi.previewFile(new Blob(['x']), 'a.zip'), (e) => e.code === 'too_large');+ globalThis.fetch = async () => {+ throw new TypeError('offline');+ };+ await assert.rejects(m.importApi.prompts(), (e) => e.code === 'network');+ const calls = [];+ globalThis.fetch = async (url, init) => {+ calls.push([url, init]);+ return new Response('{}', { status: 200 });+ };+ await m.importApi.previewFile(new Blob(['x']), 'my card.png');+ await m.importApi.undo('id1', true);+ assert.equal(calls[0][0], '/api/import/preview?filename=my%20card.png');+ assert.equal(calls[0][1].headers['Content-Type'], 'application/octet-stream');+ assert.equal(calls[1][1].body, '{"force":true}');+ } finally {+ globalThis.fetch = real;+ }+});++test('size checks match the server limits', () => {+ assert.equal(m.fileTooBig(20 * 1024 * 1024), false);+ assert.equal(m.fileTooBig(20 * 1024 * 1024 + 1), true);+ assert.equal(m.textTooLong('x'.repeat(256 * 1024 + 1)), true);+});++const applied = {+ import: {+ id: 'i1', space_id: 'spc_default', source_kind: 'openmaus', status: 'applied', created_at: '2026-10-19T00:00:00Z', undone_at: null,+ created: { kwants: [{ ref: 'lead', id: 'k1', name: 'Ada-2' }, { ref: 'qa', id: 'k2', name: 'Rigel' }], skills: ['s'], routines: ['r'], teams: ['t'], channels: ['c'], memories: 2 },+ },+ warnings: [], dropped: [], renames: [],+};++test('after Import: what was made, then each undo state', () => {+ const view = (undo) => text(html(m.DoneView, { applied, undo, onUndo() {}, onKeep() {} }));+ assert.match(view({ kind: 'idle' }), /Imported 2 bots Ada-2, Rigel.*1 team, 1 skill to review, 1 paused routine, 2 memories/);+ const edited = view({ kind: 'confirm_edited', names: ['Ada-2'] });+ assert.match(edited, /Ada-2 changed since the import\. Undo anyway removes it with your changes/);+ assert.match(edited, /Keep them.*Undo anyway/);+ assert.match(view({ kind: 'in_use', names: ['Rigel'] }), /Rigel has already been used, so this import can’t be undone in one step/);+ assert.match(view({ kind: 'undone' }), /Import undone.*Ada-2, Rigel were removed/);+});++test('recent imports offer Undo only while applied', () => {+ const out = html(m.RecentImports, { records: [applied.import, { ...applied.import, id: 'i2', status: 'undone' }], onUndo() {}, busyId: null });+ assert.equal((out.match(/aria-label="Undo import/g) ?? []).length, 1);+ assert.match(text(out), /undone/);+ assert.match(text(html(m.RecentImports, { records: [], onUndo() {}, busyId: null })), /No imports yet/);+});++test('the download name comes from Content-Disposition', () => {+ assert.equal(m.downloadName('attachment; filename="Ada-Fixture.kwant.json"', 'x'), 'Ada-Fixture.kwant.json');+ assert.equal(m.downloadName("attachment; filename*=UTF-8''Caf%C3%A9.kwant.json", 'x'), 'Café.kwant.json');+ assert.equal(m.downloadName(null, 'export.kwant.json'), 'export.kwant.json');+});