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
0.8.0 A4: import UI (Found on this computer, Folder, GitHub link) (#459)
Oleksandr Ivanchenko587635af7aa5
diff --git a/frontend/src/components/GetStarted.tsx b/frontend/src/components/GetStarted.tsxindex fda705ef..9d9d276c 100644--- a/frontend/src/components/GetStarted.tsx+++ b/frontend/src/components/GetStarted.tsx@@ -3,12 +3,13 @@// The step logic is in ../gettingStarted.ts and the install in ../gettingStartedInstall.ts; this file// only draws them. Text comes from code, never from data as HTML.import React, { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react';-import { AlertCircle, Check, Clock, Copy, ExternalLink, Info, KeyRound, RotateCw, Server, WifiOff } from 'lucide-react';+import { AlertCircle, Check, Clock, Copy, ExternalLink, HardDrive, Info, KeyRound, RotateCw, Server, WifiOff } from 'lucide-react';import { ModernAvatar } from './ModernAvatar';import { TemplateGlyph } from './TeamPreviewSheet';import { NewKeyAccountForm } from './EngineAccounts';import { useReadyTeams } from './ReadyTeams';-import { ImportDialog } from './ImportDialog';+import { ImportDialog, useLocalSources } from './ImportDialog';+import { tickable } from '../importSources';import type { WelcomeBot } from './FirstRunWelcome';import { useMedia } from '../useMedia';import { PHONE_QUERY } from '../layout';@@ -766,6 +767,10 @@ const TeamStep: React.FC<{const [importing, setImporting] = useState(false);const imported = useRef(false);const importTile = useRef<HTMLButtonElement>(null);+ // Desktop app only: one look at the usual places, for the "N found" line and the dialog.+ const localSources = useLocalSources();+ const [local] = localSources;+ const found = local.kind === 'ready' ? tickable(local.sources).length : 0;const closeImport = () => {setImporting(false);// An import that went in (even if undone in the dialog) counts; Cancel or Close leaves step 3 as it was.@@ -821,7 +826,7 @@ const TeamStep: React.FC<{type="button"data-import-botsaria-haspopup="dialog"- aria-label="Bring your bots: from Grok Bot, ChatGPT or Claude, or from a file. You check a preview first. Import"+ aria-label={`Bring your bots: from Grok Bot, ChatGPT or Claude, a file, a folder or a GitHub link. You check a preview first.${found > 0 ? ` ${found} found on this computer.` : ''} Import`}onClick={() => {imported.current = false;setImporting(true);@@ -829,7 +834,13 @@ const TeamStep: React.FC<{className={`${tile} h-full flex flex-col gap-1 border-dashed border-zinc-600 bg-transparent hover:border-zinc-500`}><span className="text-sm font-semibold text-zinc-100">Bring your bots</span>- <span className="text-[12.5px] leading-[18px] text-zinc-300">From Grok Bot, ChatGPT or Claude, or from a file. You check a preview first.</span>+ <span className="text-[12.5px] leading-[18px] text-zinc-300">From Grok Bot, ChatGPT or Claude, a file, a folder or a GitHub link. You check a preview first.</span>+ {found > 0 && (+ <span className="flex items-center gap-1.5 text-xs text-sky-200" data-found-line>+ <HardDrive size={13} className="text-sky-300 shrink-0" aria-hidden="true" />+ <span className="font-semibold">{found} found on this computer</span>+ </span>+ )}<span className="mt-auto text-right text-xs text-sky-300" aria-hidden="true">Import ›</span>@@ -839,6 +850,7 @@ const TeamStep: React.FC<{{importing && (<ImportDialogspaceName={spaceName}+ localSources={localSources}onClose={closeImport}onChanged={() => {imported.current = true;diff --git a/frontend/src/components/ImportDialog.tsx b/frontend/src/components/ImportDialog.tsxindex fd6b9fc2..c5a291e1 100644--- a/frontend/src/components/ImportDialog.tsx+++ b/frontend/src/components/ImportDialog.tsx@@ -1,5 +1,5 @@import React, { useEffect, useId, useRef, useState } from 'react';-import { AlertTriangle, ArrowLeft, Check, ChevronRight, ClipboardCopy, FileUp, Info, Loader2, Undo2, Upload, X } from 'lucide-react';+import { AlertTriangle, ArrowLeft, Check, ChevronRight, ClipboardCopy, FileUp, Folder, Info, Link as LinkIcon, Loader2, Undo2, Upload, X } from 'lucide-react';import {Applied,ExportPrompt,@@ -21,6 +21,25 @@ import {} from '../imports';import { useEscapeLayer } from '../escape';import { pickProblem, uploadFor } from '../importZip';+import {+ type FolderPlan,+ type GithubInfo,+ type LocalOrigin,+ type LocalSource,+ type PickedEntry,+ folderPickSupported,+ folderPlan,+ folderZip,+ githubFromLine,+ githubLinkOk,+ isAttribution,+ localErrorText,+ localOrigin,+} from '../importSources';+import { inDesktopApp } from '../externalLinks';+import { useMedia } from '../useMedia';+import { PHONE_QUERY } from '../layout';+import { FolderStep, FoundChooseRow, FoundStep, GithubSourceBlock, GithubStep, type LocalState, foundPrimaryLabel } from './ImportSources';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';@@ -57,17 +76,26 @@ export const ErrorBox: React.FC<{ error: unknown; children?: React.ReactNode }>);};+const row = `${card} w-full flex items-center gap-3 p-3 min-h-[60px] sm:min-h-0 text-left hover:border-zinc-600 transition-colors`;+export const SourceList: React.FC<{prompts: ExportPrompt[] | null;error: unknown;onPick: (p: ExportPrompt) => void;onUpload: () => void;onRetry: () => void;-}> = ({ prompts, error, onPick, onUpload, onRetry }) => (+ /** Found on this computer: `off` in the web app, where the group isn't drawn at all. */+ local?: LocalState;+ onFound?: () => void;+ /** Null where this browser can't pick a folder (the row is hidden). */+ onFolder?: (() => void) | null;+ onGithub?: () => void;+}> = ({ prompts, error, onPick, onUpload, onRetry, local = { kind: 'off' }, onFound, onFolder = null, onGithub }) => (<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>+ {onFound && <FoundChooseRow state={local} onOpen={onFound} card={card} />}<h3 className="text-xs font-semibold text-zinc-300">Bring a bot from…</h3>{error ? (<ErrorBox error={error}>@@ -81,7 +109,7 @@ export const SourceList: React.FC<{<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`}>+ <button type="button" onClick={() => onPick(p)} className={row}><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>@@ -92,14 +120,43 @@ export const SourceList: React.FC<{))}</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">One or several files: Claude Code subagents or SKILL.md, character cards, or Grok Bot, OpenMausBot or .kwant.json exports</span>- </span>- <ChevronRight size={16} className="text-zinc-500 shrink-0" aria-hidden="true" />- </button>+ <h3 className="text-xs font-semibold text-zinc-300">Or bring files</h3>+ <ul className="space-y-1.5">+ <li>+ <button type="button" onClick={onUpload} className={row}>+ <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">One or several files: Claude Code subagents or SKILL.md, character cards, or Grok Bot, OpenMausBot or .kwant.json exports</span>+ </span>+ <ChevronRight size={16} className="text-zinc-500 shrink-0" aria-hidden="true" />+ </button>+ </li>+ {onFolder && (+ <li>+ <button type="button" onClick={onFolder} className={row} data-folder-row>+ <Folder 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">Folder</span>+ <span className="block text-[11px] text-zinc-500">A skills folder, or an OpenClaw, Hermes or Codex workspace</span>+ </span>+ <ChevronRight size={16} className="text-zinc-500 shrink-0" aria-hidden="true" />+ </button>+ </li>+ )}+ {onGithub && (+ <li>+ <button type="button" onClick={onGithub} className={row} data-github-row>+ <LinkIcon 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">GitHub link</span>+ <span className="block text-[11px] text-zinc-500">A public repo of bots or skills. You see its licence first</span>+ </span>+ <ChevronRight size={16} className="text-zinc-500 shrink-0" aria-hidden="true" />+ </button>+ </li>+ )}+ </ul></div>);@@ -265,20 +322,58 @@ export const PreviewView: React.FC<{onToggle: (ref: string) => void;/** Several picked files went up as one zip: say "from N files", not "from a zip". */pickedFiles?: number;-}> = ({ preview, skip, onToggle, pickedFiles = 0 }) => {+ /** A picked folder: "from <name>". */+ folderName?: string;+ /** Found on this computer: where the bots and shared skills came from, when that's certain. */+ local?: { ticked: LocalSource[]; origin: LocalOrigin };+ /** A GitHub link: the source block above everything. */+ github?: GithubInfo;+ spaceName?: string;+}> = ({ preview, skip, onToggle, pickedFiles = 0, folderName, local, github, spaceName = 'this space' }) => {const { bots, general } = previewRows(preview);const teams = preview.bundle.teams ?? [];const shared = preview.bundle.skills ?? [];const packed = pickedFiles > 1;- const omitted = (preview.bundle.omitted ?? []).map((t) => (packed ? t.replace(/^Files in the zip that weren't read:/, "Files that weren't read:") : t));+ const omitted = (preview.bundle.omitted ?? [])+ .filter((t) => !github || !isAttribution(t))+ .map((t) => (packed || folderName ? t.replace(/^Files in the zip that weren't read:/, "Files that weren't read:") : t));const kept = bots.filter((b) => !skip.has(b.ref)).length;- const from = packed ? `${pickedFiles} files` : sourceName(preview.bundle.source.kind);+ const from = folderName+ ? folderName+ : packed+ ? `${pickedFiles} files`+ : local+ ? `${plural(local.ticked.length, 'source')} on this computer`+ : github+ ? null+ : sourceName(preview.bundle.source.kind);+ const botFrom = local?.origin.botSource;+ const skillFrom = local?.origin.skillSource;+ const skillsOnly = bots.length === 0 && shared.length > 0;+ const SHOWN = 8;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>+ {github && <GithubSourceBlock github={github} />}+ {skillsOnly ? (+ <p className="text-xs text-zinc-300">+ No bots in this one. <strong className="font-semibold text-zinc-100">{plural(shared.length, 'skill')}</strong> will be added to {spaceName}.+ </p>+ ) : (+ <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>+ )}+ {skillsOnly && (+ <div className={`${card} p-3`}>+ <ul className="flex flex-wrap items-center gap-1.5" aria-label="Skills">+ {shared.slice(0, SHOWN).map((k, i) => (+ <li key={`${k.name}-${i}`} className="font-mono text-[11px] text-zinc-300 border border-zinc-700 rounded-full px-2 py-0.5">{k.name}</li>+ ))}+ {shared.length > SHOWN && <li className="text-[11px] text-zinc-500">and {shared.length - SHOWN} more</li>}+ </ul>+ </div>+ )}<Notes items={general.problems} tone="problem" label="Must be fixed before importing" /><ul className="space-y-2">{bots.map((b) => {@@ -295,6 +390,11 @@ export const PreviewView: React.FC<{</span>)}{b.title && <span className="block text-[11px] text-zinc-500">{b.title}</span>}+ {botFrom && (+ <span className="block text-[11px] text-zinc-500 break-all">+ From {botFrom.label} · <span className="font-mono">{botFrom.path}</span>+ </span>+ )}</span></label>{b.excerpt && <p className="text-[11px] text-zinc-400 italic break-words">“{b.excerpt}”</p>}@@ -308,7 +408,11 @@ export const PreviewView: React.FC<{);})}</ul>- {(teams.length > 0 || shared.length > 0) && (+ {!skillsOnly && skillFrom && teams.length === 0 && shared.length > 0 ? (+ <p className="text-[11px] text-zinc-400">+ Also: {plural(shared.length, 'shared skill')} from <span className="font-mono">{skillFrom.path}</span>.+ </p>+ ) : !skillsOnly && (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(', ')})` : ''}.@@ -333,9 +437,16 @@ export type UndoState =| { 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 }) => {+export const DoneView: React.FC<{ applied: Applied; undo: UndoState; onUndo: (force: boolean) => void; onKeep: () => void; github?: GithubInfo }> = ({+ applied,+ undo,+ onUndo,+ onKeep,+ github,+}) => {const c = applied.import.created;const names = c.kwants.map((k) => k.name);+ const skillsOnly = names.length === 0 && c.skills.length > 0;if (undo.kind === 'undone') {return (<div className="space-y-2" role="status">@@ -348,7 +459,7 @@ export const DoneView: React.FC<{ applied: Applied; undo: UndoState; onUndo: (fo}const extras = [c.teams.length ? plural(c.teams.length, 'team') : '',- c.skills.length ? `${plural(c.skills.length, 'skill')} to review` : '',+ c.skills.length && !skillsOnly ? `${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);@@ -356,14 +467,24 @@ export const DoneView: React.FC<{ applied: Applied; undo: UndoState; onUndo: (fo<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')}+ <Check size={16} className="text-emerald-400" /> Imported {skillsOnly ? plural(c.skills.length, 'skill') : plural(names.length, 'bot')}</p>+ {github && (+ <p className="text-[11px] text-zinc-400 break-words" data-github-done>+ {githubFromLine(github)} They wait for your OK in Settings › This space › Skills.+ </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 Settings › This space when you’re ready. Skills and routines are there to review.</p>- <p className="text-[11px] text-zinc-400">Tools you add to this space later will be on for these bots too.</p>+ {!skillsOnly && (+ <>+ <p className="text-[11px] text-zinc-400">Give them an account and tools in Settings › This space when you’re ready. Skills and routines are there to review.</p>+ <p className="text-[11px] text-zinc-400">Tools you add to this space later will be on for these bots too.</p>+ </>+ )}+ {skillsOnly && !github && <p className="text-[11px] text-zinc-400">They wait for your OK in Settings › This space › Skills.</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">@@ -387,19 +508,59 @@ export const DoneView: React.FC<{ applied: Applied; undo: UndoState; onUndo: (fo);};-type Step = { kind: 'choose' } | { kind: 'prompt'; prompt: ExportPrompt } | { kind: 'upload' } | { kind: 'preview'; from: 'prompt' | 'upload'; prompt?: ExportPrompt } | { kind: 'done' };+type From = 'prompt' | 'upload' | 'found' | 'folder' | 'github';+type Step =+ | { kind: 'choose' }+ | { kind: 'prompt'; prompt: ExportPrompt }+ | { kind: 'upload' }+ | { kind: 'found' }+ | { kind: 'folder' }+ | { kind: 'github' }+ | { kind: 'preview'; from: From; prompt?: ExportPrompt }+ /** `github`: the source of the applied preview, only when it came from a GitHub link (Ada's #459 review). */+ | { kind: 'done'; github?: GithubInfo };interface Props {spaceName: string;onClose: () => void;/** After Import or Undo, so the sidebar and lists load again. */onChanged: () => void;+ /** Found on this computer, already asked for by the opener (Get started step 3), so it isn't asked twice. */+ localSources?: LocalSources;}+export type LocalSources = [LocalState, () => Promise<LocalSource[] | null>];+const FOCUSABLE = 'button:not([disabled]), textarea:not([disabled]), input:not([disabled]), select:not([disabled]), a[href], [tabindex]:not([tabindex="-1"])';-/** "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 }) => {+/** Found on this computer, as `GET /api/import/local` says (`off` in the web app or with `available: false`). */+export function useLocalSources(enabled: boolean = inDesktopApp()): LocalSources {+ const [state, setState] = useState<LocalState>(enabled ? { kind: 'loading' } : { kind: 'off' });+ const load = async () => {+ if (!enabled) return null;+ setState({ kind: 'loading' });+ try {+ const l = await importApi.local();+ if (!l.available) {+ setState({ kind: 'off' });+ return null;+ }+ setState({ kind: 'ready', sources: l.sources });+ return l.sources;+ } catch (err) {+ setState({ kind: 'error', error: err });+ return null;+ }+ };+ useEffect(() => {+ void load();+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, []);+ return [state, load];+}++/** "Import bots": pick a source, paste a reply, upload files, a folder or a GitHub link, check the preview, import, undo. */+export const ImportDialog: React.FC<Props> = ({ spaceName, onClose, onChanged, localSources }) => {const [step, setStep] = useState<Step>({ kind: 'choose' });const [prompts, setPrompts] = useState<ExportPrompt[] | null>(null);const [promptsError, setPromptsError] = useState<unknown>(null);@@ -412,11 +573,27 @@ export const ImportDialog: React.FC<Props> = ({ spaceName, onClose, onChanged })const [error, setError] = useState<unknown>(null);const [applied, setApplied] = useState<Applied | null>(null);const [undo, setUndo] = useState<UndoState>({ kind: 'idle' });+ // Found on this computer.+ const own = useLocalSources(!localSources && inDesktopApp());+ const [local, reloadLocal] = localSources ?? own;+ const [ticked, setTicked] = useState<Set<string>>(new Set());+ const [localError, setLocalError] = useState<{ title: string; detail: string } | null>(null);+ const [previewLocal, setPreviewLocal] = useState<{ ticked: LocalSource[]; origin: LocalOrigin } | null>(null);+ // Folder.+ const [plan, setPlan] = useState<FolderPlan | null>(null);+ const [folderUnsupported, setFolderUnsupported] = useState(false);+ // GitHub link.+ const [ghUrl, setGhUrl] = useState('');+ const [ghChecked, setGhChecked] = useState(false);+ const [github, setGithub] = useState<GithubInfo | null>(null);+ const phone = useMedia(PHONE_QUERY);const fileRef = useRef<HTMLInputElement>(null);+ const folderRef = useRef<HTMLInputElement>(null);const bodyRef = useRef<HTMLDivElement>(null);const dialogRef = useRef<HTMLDivElement>(null);const closeRef = useRef(onClose);closeRef.current = onClose;+ const canFolder = folderPickSupported();const loadPrompts = () => {setPromptsError(null);@@ -442,11 +619,12 @@ export const ImportDialog: React.FC<Props> = ({ spaceName, onClose, onChanged })// 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();+ bodyRef.current?.querySelector<HTMLElement>('button, textarea, input:not([type="file"]), [tabindex="0"]')?.focus();}, [step.kind]);const go = (s: Step) => {setError(null);+ setLocalError(null);setStep(s);};@@ -463,12 +641,67 @@ export const ImportDialog: React.FC<Props> = ({ spaceName, onClose, onChanged })}};+ const foundList = local.kind === 'ready' ? local.sources : [];+ const tickedSources = foundList.filter((s) => ticked.has(s.id) && !s.too_large);++ const showPreview = (p: Preview, from: From, prompt?: ExportPrompt) => {+ setPreview(p);+ setSkip(new Set());+ if (from !== 'github') setGithub(null);+ go({ kind: 'preview', from, prompt });+ };+const check = async () => {setBusy(true);setError(null);// From the preview ("Check again" after a name was taken), read the same input again.+ const from: From = step.kind === 'preview' ? step.from : step.kind === 'prompt' ? 'prompt' : step.kind === 'found' ? 'found' : step.kind === 'folder' ? 'folder' : step.kind === 'github' ? 'github' : 'upload';const prompt = step.kind === 'prompt' ? step.prompt : step.kind === 'preview' ? step.prompt : undefined;try {+ if (from === 'found') {+ setLocalError(null);+ const picked = tickedSources;+ if (picked.length === 0) return;+ try {+ const p = await importApi.localPreview(picked.map((s) => s.id));+ setPreviewLocal({ ticked: picked, origin: localOrigin(picked) });+ showPreview(p, 'found');+ } catch (err) {+ const text = localErrorText(err, picked);+ if (step.kind === 'preview') go({ kind: 'found' });+ setLocalError(text);+ // A source went away: look again and drop the ticks that vanished.+ if (err instanceof ImportError && err.code === 'not_found') {+ const now = await reloadLocal();+ if (now) setTicked((t) => new Set([...t].filter((id) => now.some((s) => s.id === id && !s.too_large))));+ }+ }+ return;+ }+ if (from === 'github') {+ setGhChecked(true);+ if (!githubLinkOk(ghUrl)) return;+ const p = await importApi.githubPreview(ghUrl);+ setGithub(p.github);+ showPreview(p, 'github');+ return;+ }+ if (from === 'folder') {+ if (!plan || plan.problem || plan.kept.length === 0) return;+ setFolderUnsupported(false);+ const up = await folderZip(plan);+ try {+ showPreview(await importApi.previewFile(up.body, up.filename), 'folder');+ } catch (err) {+ if (err instanceof ImportError && err.code === 'unsupported') {+ if (step.kind === 'preview') go({ kind: 'folder' });+ setFolderUnsupported(true);+ return;+ }+ throw err;+ }+ return;+ }let p = null;if (prompt) p = await importApi.previewText(reply);else if (files.length > 0 && !pickProblem(files)) {@@ -477,9 +710,7 @@ export const ImportDialog: React.FC<Props> = ({ spaceName, onClose, onChanged })p = await importApi.previewFile(up.body, up.filename);}if (!p) return;- setPreview(p);- setSkip(new Set());- go({ kind: 'preview', from: prompt ? 'prompt' : 'upload', prompt });+ showPreview(p, prompt ? 'prompt' : 'upload', prompt);} catch (err) {setError(err);} finally {@@ -492,10 +723,11 @@ export const ImportDialog: React.FC<Props> = ({ spaceName, onClose, onChanged })setBusy(true);setError(null);try {+ const fromGithub = step.kind === 'preview' && step.from === 'github' && github ? github : undefined;const a = await importApi.apply(preview.bundle, [...skip]);setApplied(a);setUndo({ kind: 'idle' });- go({ kind: 'done' });+ go({ kind: 'done', github: fromGithub });onChanged();} catch (err) {setError(err);@@ -520,13 +752,38 @@ export const ImportDialog: React.FC<Props> = ({ spaceName, onClose, onChanged })};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' });+ if (step.kind === 'github') setGithub(null);+ if (step.kind === 'prompt' || step.kind === 'upload' || step.kind === 'found' || step.kind === 'folder' || step.kind === 'github') go({ kind: 'choose' });+ else if (step.kind === 'preview') go(step.from === 'prompt' && step.prompt ? { kind: 'prompt', prompt: step.prompt } : { kind: step.from === 'prompt' ? 'upload' : step.from });+ };++ const pickFolder = () => folderRef.current?.click();+ const openFolder = () => {+ go({ kind: 'folder' });+ };+ const onFolderPicked = (entries: PickedEntry[]) => {+ setFolderUnsupported(false);+ setError(null);+ setPlan(entries.length ? folderPlan(entries) : null);};- 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}`;+ const TITLES: Partial<Record<Step['kind'], string>> = {+ upload: 'Upload a file',+ found: 'Found on this computer',+ folder: 'Bring a folder',+ github: 'Bring from a GitHub link',+ preview: 'Check before importing',+ done: 'Import bots',+ };+ const title = step.kind === 'prompt' ? `Bring a bot from ${step.prompt.label}` : TITLES[step.kind] ?? `Import bots into ${spaceName}`;+ const fb = phone ? 'flex-1 min-h-11 text-sm justify-center' : '';+ const cancel = (+ <button type="button" onClick={onClose} className={`${btn} ${fb}`}>+ Cancel+ </button>+ );+ const spin = <Loader2 size={13} className="animate-spin motion-reduce:animate-none" aria-hidden="true" />;let footer: React.ReactNode = null;if (step.kind === 'prompt' || step.kind === 'upload') {const ready =@@ -536,35 +793,84 @@ export const ImportDialog: React.FC<Props> = ({ spaceName, onClose, onChanged })? !pickProblem(files): files.length === 1 && !fileTooBig(files[0].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'}+ <>+ {cancel}+ <button type="button" onClick={check} disabled={!ready || busy} className={`${primary} ${fb}`}>+ {busy && spin} {busy ? 'Reading…' : 'Preview'}+ </button>+ </>+ );+ } else if (step.kind === 'found') {+ const nothing = local.kind === 'ready' && local.sources.length === 0;+ footer = nothing ? (+ <button type="button" onClick={back} className={`${btn} ${fb}`}>+ Back</button>+ ) : (+ <>+ {cancel}+ <button type="button" onClick={check} disabled={tickedSources.length === 0 || busy || local.kind !== 'ready'} className={`${primary} ${fb}`} data-found-primary>+ {busy && spin} {foundPrimaryLabel(tickedSources.length, busy)}+ </button>+ </>+ );+ } else if (step.kind === 'folder') {+ footer = (+ <>+ {plan ? (+ <button type="button" onClick={pickFolder} className={`${btn} ${fb}`}>+ Change folder+ </button>+ ) : (+ cancel+ )}+ <button type="button" onClick={check} disabled={!plan || !!plan.problem || plan.kept.length === 0 || busy} className={`${primary} ${fb}`}>+ {busy && spin} {busy ? 'Reading…' : 'Preview'}+ </button>+ </>+ );+ } else if (step.kind === 'github') {+ const ok = !!githubLinkOk(ghUrl);+ footer = (+ <>+ {cancel}+ <button type="button" onClick={check} disabled={busy || ghUrl.trim() === '' || (ghChecked && !ok)} className={`${primary} ${fb}`}>+ {busy && spin} {busy ? 'Fetching…' : error != null ? 'Try again' : 'Preview'}+ </button>+ </>);} else if (step.kind === 'preview' && preview) {const n = preview.bundle.bots.filter((b) => !skip.has(b.ref)).length;+ const k = preview.bundle.skills?.length ?? 0;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>+ footer = (+ <>+ {cancel}+ {isNameRace ? (+ <button type="button" onClick={check} disabled={busy} className={`${primary} ${fb}`}>+ Check again+ </button>+ ) : (+ <button type="button" onClick={doImport} disabled={!canImport(preview, skip) || busy} className={`${primary} ${fb}`}>+ {busy && spin} {busy ? 'Importing…' : n > 0 ? `Import ${plural(n, 'bot')}` : preview.bundle.bots.length === 0 && k > 0 ? `Import ${plural(k, 'skill')}` : '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 type="button" onClick={() => doUndo(false)} disabled={undo.kind === 'busy'} className={`${btn} ${fb}`}>+ {undo.kind === 'busy' ? spin : <Undo2 size={13} />} Undo import</button>)}- <button type="button" onClick={onClose} className={primary}>Done</button>+ <button type="button" onClick={onClose} className={`${primary} ${fb}`}>Done</button></>);}+ const iconBtn = phone ? 'w-11 h-11 flex items-center justify-center' : 'p-1.5';return (<div className="kw-dialog 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@@ -575,29 +881,77 @@ export const ImportDialog: React.FC<Props> = ({ spaceName, onClose, onChanged })aria-labelledby="import-title"className="kw-dialog-panel 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">+ <div className={`flex items-center gap-2 border-b border-zinc-800 px-4 ${phone ? 'h-14 px-2' : '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">+ <button type="button" onClick={back} aria-label="Back" className={`${iconBtn} -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">+ <button type="button" onClick={onClose} aria-label="Close" className={`${iconBtn} 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' })} />+ <SourceList+ prompts={prompts}+ error={promptsError}+ onRetry={loadPrompts}+ onPick={(p) => go({ kind: 'prompt', prompt: p })}+ onUpload={() => go({ kind: 'upload' })}+ local={local}+ onFound={local.kind === 'off' ? undefined : () => go({ kind: 'found' })}+ onFolder={canFolder ? openFolder : null}+ onGithub={() => go({ kind: 'github' })}+ />)}{step.kind === 'prompt' && (<PromptStep prompt={step.prompt} reply={reply} onReply={setReply} copied={copied} onCopy={copy} />)}{step.kind === 'upload' && <UploadStep files={files} onFiles={setFiles} inputRef={fileRef} />}+ {step.kind === 'found' && (+ <FoundStep+ state={local}+ ticked={ticked}+ onToggle={(id) =>+ setTicked((t) => {+ const next = new Set(t);+ if (next.has(id)) next.delete(id);+ else next.add(id);+ return next;+ })+ }+ reading={busy}+ previewError={localError}+ onRetry={() => void reloadLocal()}+ onFolder={canFolder ? openFolder : null}+ onUpload={() => go({ kind: 'upload' })}+ />+ )}+ {step.kind === 'folder' && <FolderStep plan={plan} onPicked={onFolderPicked} inputRef={folderRef} unsupported={folderUnsupported} />}+ {step.kind === 'github' && (+ <GithubStep+ url={ghUrl}+ onUrl={(u) => {+ setGhUrl(u);+ setError(null);+ }}+ checked={ghChecked}+ onCheck={() => setGhChecked(true)}+ fetching={busy}+ error={error}+ phone={phone}+ />+ )}{step.kind === 'preview' && preview && (<PreviewViewpreview={preview}pickedFiles={step.from === 'upload' ? files.length : 0}+ folderName={step.from === 'folder' ? plan?.name : undefined}+ local={step.from === 'found' && previewLocal ? previewLocal : undefined}+ github={step.from === 'github' && github ? github : undefined}+ spaceName={spaceName}skip={skip}onToggle={(ref) =>setSkip((s) => {@@ -609,8 +963,10 @@ export const ImportDialog: React.FC<Props> = ({ spaceName, onClose, onChanged })}/>)}- {step.kind === 'done' && applied && <DoneView applied={applied} undo={undo} onUndo={doUndo} onKeep={() => setUndo({ kind: 'idle' })} />}- {error != null && <ErrorBox error={error} />}+ {step.kind === 'done' && applied && (+ <DoneView applied={applied} undo={undo} onUndo={doUndo} onKeep={() => setUndo({ kind: 'idle' })} github={step.github && applied.import.created.kwants.length === 0 ? step.github : undefined} />+ )}+ {error != null && step.kind !== 'github' && <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>diff --git a/frontend/src/components/ImportSources.tsx b/frontend/src/components/ImportSources.tsxnew file mode 100644index 00000000..dae4b5cf--- /dev/null+++ b/frontend/src/components/ImportSources.tsx@@ -0,0 +1,467 @@+// The three 0.8.0 import sources (Mira's a4-import.md): Found on this computer (F1–F4, F6), a folder+// (D1–D4) and a GitHub link (G1–G4), plus the GitHub source block on the preview (G5/G6).+import React, { useId, useState } from 'react';+import { ChevronRight, ExternalLink, FileUp, Folder, HardDrive, Info, Link as LinkIcon, Loader2, Scale } from 'lucide-react';+import { plural } from '../imports';+import {+ type FolderPlan,+ type GithubInfo,+ type LocalSource,+ type PickedEntry,+ NOT_GITHUB,+ USUAL_PLACES,+ countsLine,+ foundHint,+ formatBytes,+ githubErrorText,+ githubLicenceUrl,+ githubLinkOk,+ githubRefLine,+ githubRepoUrl,+ licenceLine,+} from '../importSources';++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 card = 'rounded-xl border border-zinc-800 bg-zinc-950/60';+const pill = 'font-mono text-[11px] bg-zinc-900/70 rounded px-1.5 py-px text-zinc-400 break-all';+const ring = 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sky-400 focus-visible:ring-offset-2 focus-visible:ring-offset-zinc-900';+const spin = 'animate-spin motion-reduce:animate-none';++/** Mira's ErrorBox look with copy written from the error code. */+export const CopyErrorBox: React.FC<{ title: string; detail?: string; children?: React.ReactNode }> = ({ title, detail, children }) => (+ <div role="alert" className="rounded-lg border border-rose-500/40 bg-rose-500/10 p-3 space-y-1.5">+ <p className="text-xs font-medium text-rose-200">{title}</p>+ {detail && <p className="text-xs text-rose-100/80">{detail}</p>}+ {children}+ </div>+);++const SafeLine: React.FC<{ children: React.ReactNode }> = ({ children }) => (+ <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>{children}</span>+ </p>+);++// ------------------------------------------------------------------ Found on this computer++export type LocalState =+ | { kind: 'off' }+ | { kind: 'loading' }+ | { kind: 'ready'; sources: LocalSource[] }+ | { kind: 'error'; error: unknown };++const LOOKING = 'Looking in 5 usual places…';++/** One source row: a label around a real checkbox, the counts, and the names on request. */+const FoundRow: React.FC<{ s: LocalSource; on: boolean; disabled: boolean; onToggle: () => void }> = ({ s, on, disabled, onToggle }) => {+ const [open, setOpen] = useState(false);+ const namesId = useId();+ const off = s.too_large;+ return (+ <li className={`${card} ${on ? 'border-sky-500/45' : ''}`} data-source={s.id}>+ <label className={`flex items-start gap-2.5 p-3 min-h-[60px] ${off || disabled ? 'cursor-default' : 'cursor-pointer'}`}>+ <input+ type="checkbox"+ checked={on}+ disabled={off || disabled}+ onChange={onToggle}+ className={`mt-1 accent-sky-500 rounded ${ring} ${off ? 'opacity-[.55]' : ''}`}+ />+ <span className="flex-1 min-w-0">+ <span className={`flex flex-wrap items-baseline gap-x-2 gap-y-0.5 ${off ? 'opacity-[.55]' : ''}`}>+ <span className="text-sm font-medium text-zinc-100">{s.label}</span>+ <span className={pill}>{s.path}</span>+ </span>+ {off ? (+ <span className="block mt-0.5 text-[11px] text-rose-300">+ Too big to bring from here. Use <strong className="font-medium text-zinc-100">Folder</strong> to pick just the parts you want.+ </span>+ ) : (+ <span className="block mt-0.5 text-[11px] text-zinc-500">{countsLine(s) || 'Nothing counted yet'}</span>+ )}+ </span>+ </label>+ {!off && s.names.length > 0 && (+ <div className="px-3 pb-2.5 -mt-1 pl-[34px]">+ <button type="button" onClick={() => setOpen((v) => !v)} aria-expanded={open} aria-controls={namesId} className={`text-[11px] text-sky-300 hover:text-sky-200 rounded ${ring}`}>+ {open ? 'Hide names' : 'Show names'}+ </button>+ {open && (+ <ul id={namesId} className="mt-1 flex flex-wrap gap-x-2 gap-y-0.5 font-mono text-[11px] text-zinc-400">+ {s.names.slice(0, 50).map((n) => (+ <li key={n} className="break-all">{n}</li>+ ))}+ </ul>+ )}+ </div>+ )}+ </li>+ );+};++export const FoundStep: React.FC<{+ state: LocalState;+ ticked: ReadonlySet<string>;+ onToggle: (id: string) => void;+ /** F6: reading the ticked sources. */+ reading: boolean;+ /** An error from the preview request (F2 with an ErrorBox). */+ previewError: { title: string; detail: string } | null;+ onRetry: () => void;+ onFolder: (() => void) | null;+ onUpload: () => void;+}> = ({ state, ticked, onToggle, reading, previewError, onRetry, onFolder, onUpload }) => {+ if (state.kind === 'loading' || state.kind === 'off') {+ return (+ <div className="space-y-3" data-found-state="loading">+ <p role="status" className="flex items-center gap-2 text-xs text-zinc-400">+ <Loader2 size={13} className={spin} aria-hidden="true" /> {LOOKING}+ </p>+ <ul className="space-y-2" aria-hidden="true">+ {[0, 1, 2].map((i) => (+ <li key={i} className={`${card} p-3 flex items-start gap-2.5`}>+ <span className="mt-0.5 w-3.5 h-3.5 rounded border border-zinc-700" />+ <span className="flex-1 space-y-1.5">+ <span className="block h-3 w-40 rounded bg-zinc-800" />+ <span className="block h-2.5 w-24 rounded bg-zinc-800/70" />+ </span>+ </li>+ ))}+ </ul>+ <SafeLine>Only folder names and counts. This takes a second.</SafeLine>+ </div>+ );+ }+ if (state.kind === 'error') {+ return (+ <div className="space-y-3" data-found-state="error">+ <CopyErrorBox title="Couldn’t look on this computer" detail={errorReason(state.error)}>+ <button type="button" onClick={onRetry} className={btn}>Try again</button>+ </CopyErrorBox>+ <p className="text-xs text-zinc-400">You can still pick a folder or upload a file.</p>+ <div className="flex flex-wrap gap-2">+ {onFolder && (+ <button type="button" onClick={onFolder} className={btn}>+ <Folder size={13} aria-hidden="true" /> Pick a folder+ </button>+ )}+ <button type="button" onClick={onUpload} className={btn}>+ <FileUp size={13} aria-hidden="true" /> Upload a file+ </button>+ </div>+ </div>+ );+ }+ if (state.sources.length === 0) {+ return (+ <div className="space-y-3 text-center py-2" data-found-state="nothing">+ <HardDrive size={24} className="mx-auto text-zinc-500" aria-hidden="true" />+ <p className="text-sm font-medium text-zinc-100">No bots or skills in the usual places</p>+ <p className="text-xs text-zinc-400">kwant looked in:</p>+ <ul className="flex flex-wrap justify-center gap-1.5">+ {USUAL_PLACES.map((p) => (+ <li key={p} className={pill}>{p}</li>+ ))}+ </ul>+ {onFolder ? (+ <>+ <p className="text-xs text-zinc-400">If yours live somewhere else, pick the folder.</p>+ <button type="button" onClick={onFolder} className={`${btn} inline-flex mx-auto`}>+ <Folder size={13} aria-hidden="true" /> Pick a folder+ </button>+ </>+ ) : (+ <>+ <p className="text-xs text-zinc-400">If yours live somewhere else, zip the folder and upload it.</p>+ <button type="button" onClick={onUpload} className={`${btn} inline-flex mx-auto`}>+ <FileUp size={13} aria-hidden="true" /> Upload a file+ </button>+ </>+ )}+ </div>+ );+ }+ return (+ <div className="space-y-3" data-found-state={reading ? 'reading' : 'found'}>+ <p className="text-xs text-zinc-300">+ kwant looked in 5 usual places and read only folder names and counts. Tick what to bring. Nothing inside is read until you press Preview.+ </p>+ {previewError && <CopyErrorBox title={previewError.title} detail={previewError.detail} />}+ <ul className="space-y-2" aria-label="Found on this computer">+ {state.sources.map((s) => (+ <FoundRow key={s.id} s={s} on={ticked.has(s.id)} disabled={reading} onToggle={() => onToggle(s.id)} />+ ))}+ </ul>+ <SafeLine>Read-only. kwant never follows a link out of these folders, and never brings keys or tokens, even when a folder has them.</SafeLine>+ </div>+ );+};++const errorReason = (err: unknown) =>+ (err as { code?: string } | null)?.code === 'network' ? 'kwant couldn’t reach its server. Nothing was read.' : 'Nothing was read. Try again in a moment.';++/** The "Preview N sources" label (F2) and "Reading N sources…" (F6). */+export const foundPrimaryLabel = (n: number, reading: boolean) =>+ reading ? `Reading ${plural(n, 'source')}…` : n > 0 ? `Preview ${plural(n, 'source')}` : 'Preview';++// ------------------------------------------------------------------ Folder++const WhatWorks: React.FC = () => (+ <ul className="text-[11px] text-zinc-500 space-y-0.5 list-disc pl-5">+ <li>A skills folder (SKILL.md files)</li>+ <li>An OpenClaw, Hermes or Codex workspace (SOUL.md, AGENTS.md, skills/)</li>+ <li>A Paperclip company (COMPANY.md, agents/*.md)</li>+ <li>Up to 20 MB once packed. Only files an import reads are sent. Sign-in files, keys and .env stay on this computer.</li>+ </ul>+);++/** Reads a dropped folder (DataTransfer entries) into picked entries with relative paths. */+async function readDropped(items: DataTransferItemList): Promise<PickedEntry[] | null> {+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ const roots: any[] = [...items].map((i) => (i as DataTransferItem & { webkitGetAsEntry?: () => any }).webkitGetAsEntry?.()).filter(Boolean);+ if (roots.length !== 1 || !roots[0].isDirectory) return null;+ const out: PickedEntry[] = [];+ const walk = async (entry: any, prefix: string): Promise<void> => {+ if (entry.isFile) {+ const file: File = await new Promise((res, rej) => entry.file(res, rej));+ out.push({ path: `${prefix}${entry.name}`, size: file.size, file });+ return;+ }+ const reader = entry.createReader();+ for (;;) {+ const batch: any[] = await new Promise((res, rej) => reader.readEntries(res, rej));+ if (batch.length === 0) break;+ for (const e of batch) await walk(e, `${prefix}${entry.name}/`);+ }+ };+ await walk(roots[0], '');+ return out;+}++/** Files from `<input webkitdirectory>`: their relative paths include the picked folder. */+export const entriesFromFiles = (files: ReadonlyArray<File>): PickedEntry[] =>+ files.map((f) => ({ path: (f as File & { webkitRelativePath?: string }).webkitRelativePath || f.name, size: f.size, file: f }));++export const FolderStep: React.FC<{+ plan: FolderPlan | null;+ onPicked: (entries: PickedEntry[]) => void;+ inputRef: React.RefObject<HTMLInputElement>;+ /** 415 from the server (D4). */+ unsupported: boolean;+}> = ({ plan, onPicked, inputRef, unsupported }) => {+ const [over, setOver] = useState(false);+ const [dropNote, setDropNote] = useState<string | null>(null);+ const dirProps = { webkitdirectory: '', directory: '' } as Record<string, string>;+ return (+ <div className="space-y-3">+ {unsupported && (+ <CopyErrorBox title="Nothing kwant can bring in this folder" detail="kwant looked for SOUL.md, AGENTS.md, SKILL.md and agents/*.md and found none." />+ )}+ {!plan && !unsupported && <WhatWorks />}+ <div+ onDragOver={(e) => {+ e.preventDefault();+ setOver(true);+ }}+ onDragLeave={() => setOver(false)}+ onDrop={async (e) => {+ e.preventDefault();+ setOver(false);+ const got = await readDropped(e.dataTransfer.items).catch(() => null);+ if (got) {+ setDropNote(null);+ onPicked(got);+ } else setDropNote('Drop one folder here. For files, use Upload a file.');+ }}+ className={`rounded-xl border-2 border-dashed p-6 text-center space-y-2 ${over ? 'border-sky-500 bg-sky-500/5' : plan?.problem ? 'border-rose-500/50' : 'border-zinc-700'}`}+ >+ <Folder size={22} className="mx-auto text-zinc-500" aria-hidden="true" />+ {plan ? (+ <p className="text-xs text-zinc-300 break-words" data-picked>+ <strong className="font-semibold text-zinc-100">{plan.name}</strong>+ <span className="block text-[11px] text-zinc-500">+ {plural(plan.kept.length, 'file')} · {formatBytes(plan.keptBytes)}+ </span>+ </p>+ ) : (+ <p className="text-xs text-zinc-300">Drop a folder here, or</p>+ )}+ <button type="button" onClick={() => inputRef.current?.click()} className={`${btn} inline-flex`}>+ {plan ? 'Choose another' : 'Choose a folder'}+ </button>+ <input+ ref={inputRef}+ type="file"+ multiple+ {...dirProps}+ tabIndex={-1}+ aria-hidden="true"+ className="sr-only"+ onChange={(e) => {+ const files = [...(e.target.files ?? [])];+ if (files.length) onPicked(entriesFromFiles(files));+ e.target.value = '';+ }}+ />+ {dropNote && <p className="text-[11px] text-rose-300" role="alert">{dropNote}</p>}+ </div>+ {plan?.problem && (+ <p className="text-xs text-rose-300" role="alert" data-folder-problem>+ {plan.problem}+ </p>+ )}+ {plan && plan.left.length > 0 && (+ <div>+ <p className="text-[11px] font-medium text-zinc-400">Left out before packing</p>+ <ul className="list-disc pl-5 text-[11px] text-zinc-500">+ {plan.left.map((l) => (+ <li key={l.label}>+ {l.label}: {plural(l.count, 'file')}+ </li>+ ))}+ </ul>+ </div>+ )}+ {(plan || unsupported) && <WhatWorks />}+ </div>+ );+};++// ------------------------------------------------------------------ GitHub link++export const GithubStep: React.FC<{+ url: string;+ onUrl: (s: string) => void;+ /** Checked once the field was left or Preview was tried (G2). */+ checked: boolean;+ onCheck: () => void;+ fetching: boolean;+ error: unknown;+ phone: boolean;+}> = ({ url, onUrl, checked, onCheck, fetching, error, phone }) => {+ const id = useId();+ const bad = checked && url.trim() !== '' && !githubLinkOk(url);+ const notGithub = bad || (error as { code?: string } | null)?.code === 'not_github';+ const text = error && !notGithub ? githubErrorText(error) : null;+ return (+ <div className="space-y-3">+ <div>+ <label htmlFor={id} className="block text-xs font-medium text-zinc-300 mb-1">Link to a public GitHub repo</label>+ <input+ id={id}+ type="url"+ inputMode="url"+ autoComplete="off"+ spellCheck={false}+ autoFocus+ value={url}+ disabled={fetching}+ onChange={(e) => onUrl(e.target.value)}+ onBlur={onCheck}+ placeholder="https://github.com/owner/repo"+ aria-invalid={notGithub || undefined}+ aria-describedby={`${id}-help`}+ className={`w-full bg-zinc-950 border rounded-lg px-3 py-2 font-mono ${phone ? 'text-base' : 'text-xs'} text-zinc-100 focus:outline-none ${notGithub ? 'border-rose-500/70 focus:border-rose-400' : 'border-zinc-800 focus:border-sky-500'}`}+ />+ {notGithub && (+ <p className="mt-1 text-[11px] text-rose-300" role="alert">+ {NOT_GITHUB}+ </p>+ )}+ <p id={`${id}-help`} className="mt-1.5 text-[11px] text-zinc-500">+ A repo, a branch or a folder in it. kwant downloads it from github.com only, up to 20 MB.+ </p>+ <p className="mt-0.5 text-[11px] text-zinc-500">+ Example: <span className="font-mono">github.com/owner/repo/tree/main/skills</span>+ </p>+ </div>+ {fetching && (+ <p role="status" className="flex items-center gap-2 text-xs text-zinc-400">+ <Loader2 size={13} className={spin} aria-hidden="true" /> Downloading from github.com…+ </p>+ )}+ {text && <CopyErrorBox title={text.title} detail={text.detail} />}+ </div>+ );+};++/** G5/G6: the repo, ref and licence above the preview. */+export const GithubSourceBlock: React.FC<{ github: GithubInfo }> = ({ github: g }) => {+ const lic = licenceLine(g.licence);+ const licUrl = githubLicenceUrl(g);+ return (+ <div className={`${card} p-3 space-y-1.5`} data-github-source>+ <div className="flex items-center gap-2">+ <LinkIcon size={14} className="shrink-0 text-sky-300" aria-hidden="true" />+ <span className="flex-1 min-w-0 font-mono text-[12.5px] text-zinc-100 break-all">+ {g.owner}/{g.repo}+ </span>+ <a+ href={githubRepoUrl(g)}+ target="_blank"+ rel="noopener noreferrer"+ aria-label={`Open ${g.owner}/${g.repo} on GitHub`}+ className={`shrink-0 flex items-center gap-1 text-xs text-sky-300 hover:text-sky-200 rounded ${ring}`}+ >+ Open <ExternalLink size={12} aria-hidden="true" />+ </a>+ </div>+ <p className="pl-[22px] font-mono text-[11px] text-zinc-500 break-all">{githubRefLine(g)}</p>+ <p className="pl-[22px] flex flex-wrap items-center gap-x-2 gap-y-1">+ <span className={`kw-chip ${lic.warn ? 'kw-chip-warn' : ''} inline-flex items-center gap-1`} data-licence>+ <Scale size={12} aria-hidden="true" /> {lic.chip}+ </span>+ {lic.line && <span className="text-[11px] text-zinc-400">{lic.line}</span>}+ {g.licence && !g.licence.spdx && licUrl && (+ <a href={licUrl} target="_blank" rel="noopener noreferrer" className={`text-[11px] text-sky-300 hover:text-sky-200 underline underline-offset-2 rounded ${ring}`}>+ Read it+ </a>+ )}+ </p>+ </div>+ );+};++/** The choose step's "On this computer" group (C1, C2, C4). Not rendered in the web app (C3). */+export const FoundChooseRow: React.FC<{ state: LocalState; onOpen: () => void; card: string }> = ({ state, onOpen, card: rowCard }) => {+ if (state.kind === 'off') return null;+ const found = state.kind === 'ready' ? state.sources.filter((s) => !s.too_large) : [];+ const n = found.length;+ const hint =+ state.kind === 'loading'+ ? null+ : state.kind === 'error'+ ? 'Couldn’t look just now. Open to try again'+ : n === 0+ ? 'Nothing in the usual places. See where kwant looked'+ : `${foundHint(found)} · nothing is read yet`;+ const lit = state.kind === 'ready' && n > 0;+ return (+ <>+ <h3 className="text-xs font-semibold text-zinc-300">On this computer</h3>+ <button+ type="button"+ onClick={onOpen}+ data-found-row={state.kind === 'ready' ? (n ? 'found' : 'nothing') : state.kind}+ aria-label={lit ? `Found on this computer, ${n} found` : undefined}+ className={`${rowCard} w-full flex items-center gap-3 p-3 min-h-[60px] sm:min-h-0 text-left transition-colors ${lit ? 'border-sky-500/45 bg-sky-500/[.07] hover:border-sky-400/60' : 'hover:border-zinc-600'}`}+ >+ <HardDrive size={18} className={`shrink-0 ${lit ? 'text-sky-300' : 'text-zinc-400'}`} aria-hidden="true" />+ <span className="flex-1 min-w-0">+ <span className="block text-sm font-medium text-zinc-100">Found on this computer</span>+ {hint === null ? (+ <span role="status" className="flex items-center gap-1.5 text-[11px] text-zinc-500">+ <Loader2 size={11} className={spin} aria-hidden="true" /> {LOOKING}+ </span>+ ) : (+ <span className="block text-[11px] text-zinc-500">{hint}</span>+ )}+ </span>+ {lit && <span className="kw-chip kw-chip-accent shrink-0">{n} found</span>}+ <ChevronRight size={16} className="text-zinc-500 shrink-0" aria-hidden="true" />+ </button>+ </>+ );+};diff --git a/frontend/src/importSources.ts b/frontend/src/importSources.tsnew file mode 100644index 00000000..855a8a8f--- /dev/null+++ b/frontend/src/importSources.ts@@ -0,0 +1,412 @@+// 0.8.0 import sources (release-080/import-contract.md §2–§4, Mira's a4-import.md): Found on this+// computer, a picked folder, and a GitHub link. Pure helpers only; the steps are in ImportSources.tsx.++import { ImportError, Preview, importErrorText, plural } from './imports';+import { PICK_LIMITS, storedZip, zipOverhead } from './importZip';++// ------------------------------------------------------------------ Found on this computer++export interface LocalSource {+ id: string;+ kind: string;+ label: string;+ /** As the server shows it: `~/.codex`, or `~\.codex` on Windows. Shown exactly as sent. */+ path: string;+ bots: number;+ skills: number;+ /** Memory files (MEMORY.md, USER.md), not entries. */+ memories: number;+ names: string[];+ too_large: boolean;+}++export interface LocalList {+ available: boolean;+ reason?: string;+ sources: LocalSource[];+}++/** The five usual places the server looks (shown when nothing was found). */+export const USUAL_PLACES = ['~/.openclaw', '~/.hermes', '~/.claude/agents', '~/.claude/skills', '~/.codex'] as const;++/** Sources that can be ticked: not too big. */+export const tickable = (list: ReadonlyArray<LocalSource>) => list.filter((s) => !s.too_large);++/** "OpenClaw, Claude Code and Codex", or "OpenClaw, Hermes Agent, Codex and 2 more". */+export function foundHint(list: ReadonlyArray<LocalSource>): string {+ const labels = [...new Set(list.map((s) => s.label))];+ if (labels.length === 0) return '';+ if (labels.length === 1) return labels[0];+ if (labels.length <= 3) return `${labels.slice(0, -1).join(', ')} and ${labels[labels.length - 1]}`;+ return `${labels.slice(0, 3).join(', ')} and ${labels.length - 3} more`;+}++/** "1 bot · 3 skills · 2 memory files", leaving out zeros. */+export function countsLine(s: Pick<LocalSource, 'bots' | 'skills' | 'memories'>): string {+ return [s.bots ? plural(s.bots, 'bot') : '', s.skills ? plural(s.skills, 'skill') : '', s.memories ? plural(s.memories, 'memory file') : '']+ .filter(Boolean)+ .join(' · ');+}++/** The ErrorBox copy for `POST /api/import/local/preview`, from its code. Nothing raw reaches the person. */+export function localErrorText(err: unknown, ticked: ReadonlyArray<LocalSource>): { title: string; detail: string } {+ const code = err instanceof ImportError ? err.code : '';+ const label = ticked.map((s) => s.label).join(' or ') || 'these';+ switch (code) {+ case 'not_found':+ return { title: 'One of these isn’t there any more. kwant looked again.', detail: '' };+ case 'too_large':+ return { title: 'Together these are too big (over 500 files or 50 MB). Tick fewer.', detail: '' };+ case 'unsupported':+ return { title: `kwant found nothing it can bring in ${label}.`, detail: '' };+ case 'invalid':+ return { title: `kwant couldn’t read ${label}.`, detail: '' };+ case 'network':+ case 'person_cancelled':+ return importErrorText(err);+ default:+ return { title: 'Couldn’t read these. Nothing was imported.', detail: '' };+ }+}++/** The ErrorBox copy when the list itself couldn't load (F4). */+export function localListErrorText(err: unknown): { title: string; detail: string } {+ const code = err instanceof ImportError ? err.code : '';+ return {+ title: 'Couldn’t look on this computer',+ detail: code === 'network' ? 'kwant couldn’t reach its server. Nothing was read.' : 'Nothing was read. Try again in a moment.',+ };+}++export interface LocalOrigin {+ /** Every bot came from this one source: "From OpenClaw · ~/.openclaw/workspace" on each bot. */+ botSource: LocalSource | null;+ /** The shared skills all came from this source: "Also: 7 shared skills from ~/.claude/skills." */+ skillSource: LocalSource | null;+}++/**+ * Where the preview's bots and shared skills came from, when the ticked sources say it for sure (the+ * preview doesn't name a source per bot): one ticked source with bots, one with only skills.+ */+export function localOrigin(ticked: ReadonlyArray<LocalSource>): LocalOrigin {+ const withBots = ticked.filter((s) => s.bots > 0);+ const skillsOnly = ticked.filter((s) => s.bots === 0 && s.skills > 0);+ return { botSource: withBots.length === 1 ? withBots[0] : null, skillSource: skillsOnly.length === 1 ? skillsOnly[0] : null };+}++// ------------------------------------------------------------------ Folder++/** Can this browser pick a folder? iOS Safari can't, even where the property exists. */+export function folderPickSupported(+ proto: object | undefined = typeof HTMLInputElement !== 'undefined' ? HTMLInputElement.prototype : undefined,+ nav: { userAgent?: string; maxTouchPoints?: number } | undefined = typeof navigator !== 'undefined' ? navigator : undefined,+): boolean {+ if (!proto || !('webkitdirectory' in proto)) return false;+ const ua = nav?.userAgent ?? '';+ if (/iPhone|iPad|iPod/.test(ua)) return false;+ // iPadOS asks for the desktop site: a "Macintosh" with a touch screen.+ if (/Macintosh/.test(ua) && (nav?.maxTouchPoints ?? 0) > 1) return false;+ return true;+}++export interface PickedEntry {+ /** Relative path including the picked folder's own name: "support-skills/seo/SKILL.md". */+ path: string;+ size: number;+ file: Blob;+}++/**+ * What a picked folder may send. The folder is zipped and uploaded to the server, which may be remote,+ * so only files an import format reads are packed: the same allowlist as `wanted_in_repo`+ * (src/import/archive.rs) plus the OpenClaw extras of `wanted` (src/import/local.rs). Key stores are+ * refused first, by name, so a sign-in file never leaves this computer even if it looks like a .json.+ */+const READ_NAMES = new Set([+ 'skill.md', 'agents.md', 'agents.override.md', 'soul.md', 'identity.md', 'user.md', 'memory.md', 'company.md',+ 'team.md', 'task.md', 'employee.json', 'schedule.md', '.paperclip.yaml', '.bundled_manifest', 'boot.md', 'bootstrap.md',+]);+/** The only hidden files kept (Paperclip and Hermes markers). */+const READ_DOTFILES = new Set(['.paperclip.yaml', '.bundled_manifest']);+const NOT_BOT_JSON = new Set(['package.json', 'package-lock.json', 'tsconfig.json']);+/** Sign-in and settings files of OpenClaw, Hermes and Codex (Ada's #455 review): never packed. */+const KEY_STORE_FILES = new Set(['openclaw.json', 'auth.json', 'config.toml', 'config.yaml', 'state.db']);+const KEY_STORE_DIRS = new Set(['credentials', 'sessions']);+/**+ * Key-bearing files that are never sent, at any depth (Ada's #459 review): per-agent auth profiles,+ * OAuth and token files, Claude and MCP settings (their env blocks hold API keys), Google client secrets.+ */+const SECRET_NAME_EXACT = new Set(['settings.json', 'settings.local.json', 'mcp.json', '.credentials.json']);+const SECRET_JSON_PREFIXES = ['auth-profiles', 'oauth', 'credentials', 'token'];+const SECRET_NAME_PREFIXES = ['client_secret', 'service-account'];+/** Any other file whose name says it holds a secret. Notes and pictures (.md, .png) are judged by content, not name. */+const SECRET_WORDS = /(auth|oauth|credential|secret|token|passw|api[-_]?key|private)/i;+/** A picked app folder (its own name), packed as an app home. */+const APP_HOME_NAMES = new Set(['.openclaw', '.hermes', '.codex', '.claude', 'openclaw', 'hermes']);++const isKeyStore = (base: string) =>+ base.startsWith('.env') || KEY_STORE_FILES.has(base) || base.startsWith('state.db') || base === '.credentials.json';++function isSecretName(base: string, dirs: string[]): boolean {+ if (SECRET_NAME_EXACT.has(base) || SECRET_NAME_PREFIXES.some((p) => base.startsWith(p))) return true;+ if (base.endsWith('.json') && SECRET_JSON_PREFIXES.some((p) => base.startsWith(p))) return true;+ // OpenClaw's agents/<id>/agent/ holds auth-profiles.json and models.json.+ if (dirs.some((d, i) => d === 'agent' && i >= 2 && dirs[i - 2] === 'agents')) return true;+ return !base.endsWith('.md') && !base.endsWith('.png') && SECRET_WORDS.test(base);+}++const isLicence = (base: string) => {+ const stem = base.split('.')[0];+ return ['license', 'licence', 'copying'].includes(stem) && (base === stem || base.endsWith('.md') || base.endsWith('.txt'));+};++/**+ * Whether some format reads this file (lowercased path below the picked folder). Inside an app home+ * (an OpenClaw, Hermes, Codex or Claude folder) only what `wanted` (src/import/local.rs) reads goes, and+ * no .json at all; elsewhere any bot .json goes, as `wanted_in_repo` reads character cards,+ * conversations.json and employee.json.+ */+function formatReads(inner: string[], appHome: boolean): boolean {+ const base = inner[inner.length - 1] ?? '';+ const parent = inner[inner.length - 2] ?? '';+ if (base.endsWith('.json')) return !appHome && !NOT_BOT_JSON.has(base);+ if (READ_NAMES.has(base) || isLicence(base)) return true;+ return base.endsWith('.md') && ['agents', 'memories', 'memory'].includes(parent);+}++/**+ * The folders of a pick that are an app's home: the picked folder when it is named like one, and any+ * folder holding an app's key store (openclaw.json, auth.json, config.toml, config.yaml, .env*, state.db*,+ * .credentials.json, credentials/, sessions/). Lowercased paths below the picked folder, "" for the pick itself.+ */+export function appHomes(paths: ReadonlyArray<string>): string[] {+ const homes = new Set<string>();+ for (const path of paths) {+ const parts = path.split(/[\\/]/).filter(Boolean);+ if (APP_HOME_NAMES.has((parts[0] ?? '').toLowerCase())) homes.add('');+ const inner = parts.slice(1).map((p) => p.toLowerCase());+ const dirs = inner.slice(0, -1);+ if (isKeyStore(inner[inner.length - 1] ?? '')) homes.add(dirs.join('/'));+ const k = dirs.findIndex((d) => KEY_STORE_DIRS.has(d));+ if (k >= 0) homes.add(dirs.slice(0, k).join('/'));+ }+ return [...homes];+}++const inHome = (dirs: string[], homes: ReadonlyArray<string>) => {+ const at = dirs.join('/');+ return homes.some((h) => h === '' || at === h || at.startsWith(`${h}/`));+};++type LeftKind = 'secrets' | 'git' | 'node_modules' | 'keys' | 'hidden' | 'unread' | 'big';+const LEFT_LABELS: Record<LeftKind, string> = {+ secrets: 'Sign-in and settings files (never sent)',+ git: '.git/',+ node_modules: 'node_modules/',+ keys: 'Keys (.pem, .key, id_rsa)',+ hidden: 'Other hidden files',+ unread: 'Files no import reads',+ big: 'Files over 4 MB',+};+const LEFT_ORDER: LeftKind[] = ['secrets', 'keys', 'git', 'node_modules', 'hidden', 'big', 'unread'];++/** Why a file is left out before packing, or null to keep it. */+export function leftOutKind(path: string, size: number, homes: ReadonlyArray<string> = appHomes([path])): LeftKind | null {+ const parts = path.split(/[\\/]/).filter(Boolean);+ // Below the picked folder, which may itself be hidden (".openclaw").+ const inner = parts.slice(1).map((p) => p.toLowerCase());+ const base = inner[inner.length - 1] ?? '';+ const dirs = inner.slice(0, -1);+ if (dirs.includes('.git')) return 'git';+ if (dirs.includes('node_modules')) return 'node_modules';+ if (isKeyStore(base) || dirs.some((d) => KEY_STORE_DIRS.has(d)) || isSecretName(base, dirs)) return 'secrets';+ if (base.endsWith('.pem') || base.endsWith('.key') || base.startsWith('id_rsa')) return 'keys';+ if (dirs.some((d) => d.startsWith('.')) || (base.startsWith('.') && !READ_DOTFILES.has(base))) return 'hidden';+ if (!formatReads(inner, inHome(dirs, homes))) return 'unread';+ if (size > PICK_LIMITS.fileBytes) return 'big';+ return null;+}++/** A Codex `config.toml` that isn't in a hidden folder: sent by name only (see `markers`). */+const isCodexMarker = (path: string) => {+ const inner = path.split(/[\\/]/).filter(Boolean).slice(1);+ return inner[inner.length - 1]?.toLowerCase() === 'config.toml' && !inner.slice(0, -1).some((d) => d.startsWith('.') || d === 'node_modules');+};++export interface FolderPlan {+ /** The picked folder's name. */+ name: string;+ kept: PickedEntry[];+ keptBytes: number;+ /** Bytes of the zip that would be sent. */+ packedBytes: number;+ left: Array<{ label: string; count: number }>;+ /** Why it can't be sent (rose, role=alert), or null. */+ problem: string | null;+ /**+ * Codex `config.toml` files, sent as empty entries: the server only checks the name is there next to+ * AGENTS.md (formats.rs `codex_roots`) and never opens it, so its contents (which can hold keys) never+ * leave this computer.+ */+ markers: string[];+}++export const formatBytes = (n: number): string =>+ n < 1024 * 1024 ? `${Math.max(1, Math.round(n / 1024))} KB` : `${(n / (1024 * 1024)).toFixed(1).replace(/\.0$/, '')} MB`;++/** What a picked folder becomes: what's kept, what's left out (and why), and whether it fits. */+export function folderPlan(entries: ReadonlyArray<PickedEntry>): FolderPlan {+ const name = entries[0]?.path.split(/[\\/]/)[0] || 'folder';+ const kept: PickedEntry[] = [];+ const markers: string[] = [];+ const counts = new Map<LeftKind, number>();+ const homes = appHomes(entries.map((e) => e.path));+ for (const e of entries) {+ const why = leftOutKind(e.path, e.size, homes);+ if (isCodexMarker(e.path)) markers.push(e.path);+ if (why) counts.set(why, (counts.get(why) ?? 0) + 1);+ else kept.push(e);+ }+ const keptBytes = kept.reduce((n, e) => n + e.size, 0);+ const packedBytes = keptBytes + zipOverhead([...kept.map((e) => e.path), ...markers]);+ const left = LEFT_ORDER.filter((k) => counts.has(k)).map((k) => ({ label: LEFT_LABELS[k], count: counts.get(k)! }));+ const hasSkills = kept.some((e) => e.path.split('/').slice(1, -1).includes('skills'));+ const smaller = `Pick a smaller part of it${hasSkills ? ', such as its skills folder' : ''}.`;+ let problem: string | null = null;+ if (entries.length > 0 && kept.length === 0) problem = 'Nothing in that folder can be brought in: no SKILL.md, AGENTS.md, SOUL.md, agents/*.md or bot .json.';+ else if (packedBytes > PICK_LIMITS.zipBytes)+ problem = `That folder is ${Math.ceil(packedBytes / (1024 * 1024))} MB once packed, over the 20 MB limit. ${smaller}`;+ else if (kept.length > PICK_LIMITS.files) problem = `That folder has ${kept.length} readable files, over the 500 limit. ${smaller}`;+ return { name, kept, keptBytes, packedBytes, left, problem, markers };+}++/** The zip a folder plan sends: kept files with their relative paths, plus empty Codex markers. */+export async function folderZip(plan: FolderPlan): Promise<{ body: Blob; filename: string }> {+ const data = await Promise.all(plan.kept.map(async (e) => new Uint8Array(await e.file.arrayBuffer())));+ const zip = storedZip([+ ...plan.kept.map((e, i) => ({ name: e.path.replace(/\\/g, '/'), data: data[i] })),+ ...plan.markers.map((m) => ({ name: m.replace(/\\/g, '/'), data: new Uint8Array(0) })),+ ]);+ return { body: new Blob([zip.buffer as ArrayBuffer], { type: 'application/zip' }), filename: `${plan.name}.zip` };+}++// ------------------------------------------------------------------ GitHub link++export interface GithubLicence {+ spdx: string | null;+ name: string;+ file: string;+}++export interface GithubInfo {+ owner: string;+ repo: string;+ ref: string;+ path: string | null;+ commit: string | null;+ licence: GithubLicence | null;+}++export type GithubPreview = Preview & { github: GithubInfo };++const SEG = /^[A-Za-z0-9._-]{1,100}$/;++/**+ * The client's check of a GitHub link (contract §3): github.com or www.github.com over https (or no+ * scheme), no user or port, and one of the three shapes. Null when it looks fine; the server checks again.+ */+export function githubLinkOk(raw: string): { owner: string; repo: string } | null {+ const s = raw.trim();+ if (!s) return null;+ let u: URL;+ try {+ u = new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(s) ? s : `https://${s}`);+ } catch {+ return null;+ }+ if (u.protocol !== 'https:' || u.username || u.password || u.port) return null;+ if (!['github.com', 'www.github.com'].includes(u.hostname.toLowerCase())) return null;+ if (/%2e|%2f|%5c|\\/i.test(s)) return null;+ const parts = u.pathname.replace(/\/+$/, '').split('/').slice(1);+ if (parts.length < 2 || parts.some((p) => p === '' || p === '.' || p === '..')) return null;+ const [owner, rawRepo, kind, ref, ...rest] = parts;+ const repo = rawRepo.replace(/\.git$/, '');+ if (!SEG.test(owner) || !SEG.test(repo)) return null;+ if (parts.length === 2) return { owner, repo };+ if (kind === 'tree' && ref && SEG.test(ref)) return { owner, repo };+ if (kind === 'blob' && ref && SEG.test(ref) && rest.length > 0) return { owner, repo };+ return null;+}++/** The server's 20 MB line (src/import/github.rs), in the app's typography. */+export const GITHUB_OVER_20MB = 'This repository is larger than 20 MB, so kwant can’t fetch it. Download the folder you want, zip it and import the zip instead.';++export const NOT_GITHUB = 'Only github.com links work here. kwant doesn’t fetch from other sites.';++/** The ErrorBox copy for `POST /api/import/github/preview` (G4), from its code. */+export function githubErrorText(err: unknown): { title: string; detail: string } {+ const code = err instanceof ImportError ? err.code : '';+ switch (code) {+ case 'not_found':+ return { title: 'No public repo at that link', detail: 'It may be private, or the branch or link may be wrong. Only public repos work for now.' };+ case 'too_large':+ // The whole download was over 20 MB (#455 11efe7d2): a folder link wouldn't help, a zip does.+ if (err instanceof ImportError && /larger than 20 MB/.test(err.message))+ return { title: 'That repo is too big', detail: GITHUB_OVER_20MB };+ return { title: 'That repo is too big', detail: 'Link to the folder you need instead, like …/tree/main/skills. (20 MB, or over 500 readable files.)' };+ case 'unsupported':+ return { title: 'Nothing kwant can bring here', detail: 'No SKILL.md, AGENTS.md or bot files at that link.' };+ case 'redirect':+ return { title: 'GitHub sent kwant somewhere else', detail: 'kwant never follows a redirect. Check the link, or try the repo’s new address.' };+ case 'invalid':+ return { title: 'That download wasn’t a safe zip', detail: 'Nothing was imported.' };+ case 'fetch_failed':+ return { title: 'GitHub didn’t answer', detail: 'Check your connection and try again. Nothing was imported.' };+ case 'not_github':+ return { title: NOT_GITHUB, detail: '' };+ case 'network':+ case 'person_cancelled':+ return importErrorText(err);+ default:+ return { title: 'Something went wrong', detail: 'Nothing was imported. Try again in a moment.' };+ }+}++/** "main · commit 3f2a91c · /skills", or "default branch" for HEAD. */+export function githubRefLine(g: Pick<GithubInfo, 'ref' | 'commit' | 'path'>): string {+ return [g.ref === 'HEAD' ? 'default branch' : g.ref, g.commit ? `commit ${g.commit.slice(0, 7)}` : '', g.path ? `/${g.path.replace(/^\/+/, '')}` : '']+ .filter(Boolean)+ .join(' · ');+}++/** The licence chip and its one plain-words line. `warn` is the amber "No licence" chip. */+export function licenceLine(l: GithubLicence | null): { chip: string; line: string; warn: boolean } {+ if (!l) return { chip: 'No licence', line: '', warn: true };+ const s = (l.spdx ?? '').toUpperCase();+ if (!l.spdx) return { chip: 'Unknown licence', line: 'Read the licence before you share these.', warn: false };+ let line = '';+ if (/^(MIT|BSD|ISC|APACHE|UNLICENSE|CC0)/.test(s)) line = 'Free to reuse. Keep the author’s notice.';+ else if (/^(GPL|LGPL|AGPL|MPL)/.test(s)) line = `If you share these on, share them under ${l.spdx} too.`;+ else if (/^CC-BY-SA/.test(s)) line = 'Free to reuse with credit, under the same licence.';+ else if (/^CC-BY/.test(s)) line = 'Free to reuse with credit.';+ return { chip: `${l.spdx} licence`, line, warn: false };+}++export const githubRepoUrl = (g: Pick<GithubInfo, 'owner' | 'repo'>) => `https://github.com/${encodeURIComponent(g.owner)}/${encodeURIComponent(g.repo)}`;++/** The licence file on github.com, at the fetched commit when known. */+export function githubLicenceUrl(g: GithubInfo): string | null {+ if (!g.licence?.file) return null;+ const at = g.commit || g.ref || 'HEAD';+ const dir = g.path ? `${g.path.replace(/^\/+|\/+$/g, '')}/` : '';+ const file = g.licence.file.includes('/') ? g.licence.file : `${dir}${g.licence.file}`;+ return `${githubRepoUrl(g)}/blob/${encodeURIComponent(at)}/${file.split('/').map(encodeURIComponent).join('/')}`;+}++/** "From github.com/owner/repo (MIT)" for the Done step. */+export const githubFromLine = (g: GithubInfo) =>+ `From github.com/${g.owner}/${g.repo}${g.licence ? ` (${g.licence.spdx ?? g.licence.name})` : ''}.`;++/** The server's attribution lines in `omitted` ("From github.com/…"): the source block already says it. */+export const isAttribution = (line: string) => /^From github\.com\//.test(line);diff --git a/frontend/src/imports.ts b/frontend/src/imports.tsindex 054987ff..57cfbf6f 100644--- a/frontend/src/imports.ts+++ b/frontend/src/imports.ts@@ -163,6 +163,10 @@ export const importApi = {}),apply: (bundle: Bundle, skip: string[]) => call<Applied>('POST', '/api/import/apply', json({ bundle, skip })),list: () => call<ImportRecord[]>('GET', '/api/imports'),+ /** Found on this computer: names and counts only. The desktop app gets `available: true`. */+ local: () => call<import('./importSources').LocalList>('GET', '/api/import/local'),+ localPreview: (sources: string[]) => call<Preview>('POST', '/api/import/local/preview', json({ sources })),+ githubPreview: (url: string) => call<import('./importSources').GithubPreview>('POST', '/api/import/github/preview', json({ url: url.trim() })),undo: (id: string, force = false) => call<ImportRecord>('POST', `/api/imports/${enc(id)}/undo`, force ? json({ force: true }) : {}),};@@ -264,6 +268,12 @@ const SOURCE_NAMES: Record<string, string> = {openmaus: 'OpenMausBot','openmaus-grok': 'OpenMausBot',zip: 'a zip',+ openclaw: 'OpenClaw',+ hermes: 'Hermes Agent',+ codex: 'Codex',+ paperclip: 'a Paperclip company',+ 'ai-employees': 'an ai-employees kit',+ local: 'this computer','plain-text': 'pasted text',};diff --git a/frontend/tests/gettingStarted.test.mjs b/frontend/tests/gettingStarted.test.mjsindex 8289f7df..236329d6 100644--- a/frontend/tests/gettingStarted.test.mjs+++ b/frontend/tests/gettingStarted.test.mjs@@ -374,8 +374,11 @@ test('step 3: "Bring your bots" sits next to Keep the starter bots and opens theconst tile = r.host.querySelector('[data-import-bots]');assert.ok(tile, 'the tile is in step 3');assert.equal(tile.closest('ul'), r.host.querySelector('[data-keep-starter]').closest('ul'));- assert.match(tile.textContent, /^Bring your botsFrom Grok Bot, ChatGPT or Claude, or from a file\. You check a preview first\./);- assert.match(tile.getAttribute('aria-label'), /^Bring your bots: /);+ assert.match(tile.textContent, /^Bring your botsFrom Grok Bot, ChatGPT or Claude, a file, a folder or a GitHub link\. You check a preview first\./);+ assert.equal(tile.getAttribute('aria-label'), 'Bring your bots: from Grok Bot, ChatGPT or Claude, a file, a folder or a GitHub link. You check a preview first. Import');+ // The web app never asks what is on this computer.+ assert.equal(tile.querySelector('[data-found-line]'), null);+ assert.ok(!r0.calls.some(([, u]) => u === '/api/import/local'));assert.equal(tile.getAttribute('aria-haspopup'), 'dialog');assert.equal(document.querySelector('[role="dialog"]'), null);tile.click();@@ -391,6 +394,59 @@ test('step 3: "Bring your bots" sits next to Keep the starter bots and opens the}});+// 0.8.0 A4: "N found on this computer" under the tile, desktop app only, from one look at the usual places.+async function step3Found(local, { desktop = true } = {}) {+ const real = g.fetch;+ const r0 = importRoutes();+ const calls = r0.calls;+ g.fetch = g.window.fetch = async (url, init = {}) => {+ if (String(url) === '/api/import/local') {+ calls.push([init.method ?? 'GET', String(url)]);+ if (local === 'fail') return new Response('{"error":"boom"}', { status: 500, headers: { 'Content-Type': 'application/json' } });+ if (local === 'hang') return new Promise(() => {});+ return new Response(JSON.stringify(local), { status: 200, headers: { 'Content-Type': 'application/json' } });+ }+ return r0.fetch(url, init);+ };+ if (desktop) g.window.__KWANT_APP__ = 'mac';+ try {+ const r = mountStep3('imp-found');+ await settle();+ const tile = r.host.querySelector('[data-import-bots]');+ return { r, tile, calls, line: tile.querySelector('[data-found-line]') };+ } finally {+ delete g.window.__KWANT_APP__;+ g.fetch = g.window.fetch = real;+ }+}+const src = (id, over = {}) => ({ id, kind: id, label: id, path: `~/.${id}`, bots: 1, skills: 0, memories: 0, names: [], too_large: false, ...over });++test('step 3 (desktop): "N found on this computer" counts sources that are not too big', async () => {+ const { r, tile, line, calls } = await step3Found({ available: true, sources: [src('openclaw'), src('hermes'), src('codex', { too_large: true })] });+ assert.ok(line, 'the found line shows');+ assert.equal(line.textContent, '2 found on this computer');+ assert.match(tile.getAttribute('aria-label'), /You check a preview first\. 2 found on this computer\. Import$/);+ assert.equal(calls.filter(([, u]) => u === '/api/import/local').length, 1, 'one look');+ // The dialog reuses that look instead of asking again.+ g.window.__KWANT_APP__ = 'mac';+ tile.click();+ await settle();+ delete g.window.__KWANT_APP__;+ assert.match(document.querySelector('[role="dialog"]').textContent, /2 found/);+ assert.equal(calls.filter(([, u]) => u === '/api/import/local').length, 1, 'still one look');+ r.done();+});++test('step 3 (desktop): no found line while looking, on failure, with nothing tickable, or with available:false', async () => {+ for (const local of ['hang', 'fail', { available: true, sources: [] }, { available: true, sources: [src('codex', { too_large: true })] }, { available: false, reason: 'no home', sources: [] }]) {+ const { r, line, tile } = await step3Found(local);+ assert.equal(line, null, JSON.stringify(local));+ assert.doesNotMatch(tile.getAttribute('aria-label'), /found/);+ assert.equal(tile.querySelector('.animate-spin'), null, 'never a spinner on the tile');+ r.done();+ }+});+test('step 3: closing the importer without importing leaves step 3 open and focus on the tile', async () => {const real = g.fetch;g.fetch = g.window.fetch = importRoutes().fetch;diff --git a/frontend/tests/importA4.test.mjs b/frontend/tests/importA4.test.mjsnew file mode 100644index 00000000..53fd72fe--- /dev/null+++ b/frontend/tests/importA4.test.mjs@@ -0,0 +1,515 @@+// 0.8.0 A4: the import dialog's three new sources (Mira's release-080/designs/a4-import.md), one test per+// state: choose C1–C4, Found on this computer F1–F6, Folder D1–D4, GitHub link G1–G7. The server is+// mocked with contract-shaped demo data (tests/importA4Demo.mjs).+import assert from 'node:assert/strict';+import test from 'node:test';+import { JSDOM } from 'jsdom';+import { loadBundled } from './bundle.mjs';+import * as demo from './importA4Demo.mjs';++const dom = new JSDOM('<!doctype html><html><body></body></html>', { url: 'http://localhost/', pretendToBeVisual: true });+const g = globalThis;+for (const k of ['window', 'document', 'navigator', 'HTMLElement', 'HTMLInputElement', 'Element', 'Node', 'Event', 'MouseEvent', 'KeyboardEvent', 'requestAnimationFrame', 'cancelAnimationFrame', 'getComputedStyle', 'localStorage', 'sessionStorage']) {+ if (!(k in dom.window)) continue;+ Object.defineProperty(g, k, { value: dom.window[k], configurable: true, writable: true });+}+g.window.matchMedia = (q) => ({ matches: false, media: q, addEventListener() {}, removeEventListener() {} });++const m = await loadBundled(`+ export { default as React } from 'react';+ export { createRoot } from 'react-dom/client';+ export { flushSync } from 'react-dom';+ export { ImportDialog, SourceList, PreviewView, DoneView } from './src/components/ImportDialog';+ export { foundPrimaryLabel } from './src/components/ImportSources';+ export * from './src/importSources';+ export { ImportError } from './src/imports';+ export { renderToStaticMarkup } from 'react-dom/server.browser';+`);+const { React, createRoot, flushSync } = m;+const h = React.createElement;+const settle = async (n = 8) => {+ for (let i = 0; i < n; i++) await new Promise((r) => setTimeout(r, 0));+};+const text = (s) => s.replace(/<[^>]+>/g, ' ').replace(/'|'/g, "'").replace(/"/g, '"').replace(/&/g, '&').replace(/\s+/g, ' ');+const html = (C, props) => text(m.renderToStaticMarkup(h(C, props)));+const btn = (root, re) => [...root.querySelectorAll('button')].find((b) => re.test(b.textContent.trim()));+const json = (b, status = 200) => new Response(JSON.stringify(b), { status, headers: { 'Content-Type': 'application/json' } });+const fail = (status, code, error = '') => json({ error, code }, status);++/** Routes for the import API; `over` replaces any route by its path. */+function server(over = {}) {+ const calls = [];+ const routes = {+ 'GET /api/import/prompts': () => json([{ id: 'grok', label: 'Grok', where_to_send: 'Open Grok.', prompt: 'Export yourself.' }]),+ 'GET /api/import/local': () => json(demo.localList()),+ 'POST /api/import/local/preview': () => json(demo.localPreview()),+ 'POST /api/import/github/preview': () => json(demo.githubPreview()),+ 'POST /api/import/preview': () => json(demo.folderPreview()),+ 'POST /api/import/apply': (init) => json(demo.applied(JSON.parse(init.body).bundle ? { bundle: JSON.parse(init.body).bundle } : demo.githubPreview())),+ ...over,+ };+ const fetch = async (url, init = {}) => {+ const method = init.method ?? 'GET';+ const path = String(url).split('?')[0];+ calls.push({ method, url: String(url), body: init.body });+ const r = routes[`${method} ${path}`];+ return r ? r(init, calls.filter((c) => `${c.method} ${c.url.split('?')[0]}` === `${method} ${path}`).length) : json({}, 404);+ };+ return { calls, fetch, count: (key) => calls.filter((c) => `${c.method} ${c.url.split('?')[0]}` === key).length };+}++let cleanup = [];+async function open({ desktop = false, folders = false, over = {} } = {}) {+ const s = server(over);+ g.fetch = g.window.fetch = s.fetch;+ if (desktop) g.window.__KWANT_APP__ = 'mac';+ else delete g.window.__KWANT_APP__;+ if (folders) Object.defineProperty(g.HTMLInputElement.prototype, 'webkitdirectory', { value: false, configurable: true, writable: true });+ else delete g.HTMLInputElement.prototype.webkitdirectory;+ const host = document.createElement('div');+ document.body.appendChild(host);+ const root = createRoot(host);+ const changed = [];+ flushSync(() => root.render(h(m.ImportDialog, { spaceName: 'Home', onClose() {}, onChanged: () => changed.push(1) })));+ cleanup.push(() => (root.unmount(), host.remove()));+ await settle();+ const dlg = () => document.querySelector('[role="dialog"]');+ return { s, dlg, changed, click: async (re) => (btn(dlg(), re).click(), settle()) };+}+test.afterEach(() => {+ cleanup.forEach((f) => f());+ cleanup = [];+ delete g.window.__KWANT_APP__;+});++const footer = (dlg) => dlg().lastElementChild;+const primaryOf = (dlg) => [...footer(dlg).querySelectorAll('button')].pop();++// ------------------------------------------------------------------ choose (C1–C4)++test('C3 web app: no "On this computer" group and no look at the usual places; folder row needs folder picking', async () => {+ const d = await open();+ assert.equal(d.dlg().querySelector('[data-found-row]'), null);+ assert.doesNotMatch(d.dlg().textContent, /On this computer/);+ assert.equal(d.s.count('GET /api/import/local'), 0);+ assert.equal(d.dlg().querySelector('[data-folder-row]'), null, 'hidden where the browser can’t pick folders');+ assert.ok(d.dlg().querySelector('[data-github-row]'));+ assert.match(d.dlg().textContent, /Or bring files.*Upload a file.*GitHub link/);+});++test('C1 found: the lit row with names and "N found"; Folder row when folders can be picked', async () => {+ const d = await open({ desktop: true, folders: true });+ const row = d.dlg().querySelector('[data-found-row]');+ assert.equal(row.dataset.foundRow, 'found');+ assert.match(row.className, /border-sky-500\/45/);+ assert.equal(row.getAttribute('aria-label'), 'Found on this computer, 2 found');+ assert.match(row.textContent, /OpenClaw and Claude Code skills · nothing is read yet/);+ assert.ok(d.dlg().querySelector('[data-folder-row]'));+ assert.equal(d.s.count('GET /api/import/local'), 1);+});++test('C2 loading, C4 nothing, and a failed look', async () => {+ let d = await open({ desktop: true, over: { 'GET /api/import/local': () => new Promise(() => {}) } });+ let row = d.dlg().querySelector('[data-found-row]');+ assert.equal(row.dataset.foundRow, 'loading');+ assert.match(row.querySelector('[role="status"]').textContent, /Looking in 5 usual places…/);+ cleanup.forEach((f) => f());+ cleanup = [];+ d = await open({ desktop: true, over: { 'GET /api/import/local': () => json({ available: true, sources: [] }) } });+ row = d.dlg().querySelector('[data-found-row]');+ assert.equal(row.dataset.foundRow, 'nothing');+ assert.doesNotMatch(row.className, /border-sky-500/);+ assert.match(row.textContent, /Nothing in the usual places\. See where kwant looked/);+ cleanup.forEach((f) => f());+ cleanup = [];+ d = await open({ desktop: true, over: { 'GET /api/import/local': () => fail(500, 'internal') } });+ assert.match(d.dlg().querySelector('[data-found-row]').textContent, /Couldn’t look just now/);+});++test('available:false in the desktop app hides the group like the web app', async () => {+ const d = await open({ desktop: true, over: { 'GET /api/import/local': () => json({ available: false, reason: 'No home folder', sources: [] }) } });+ assert.equal(d.dlg().querySelector('[data-found-row]'), null);+});++// ------------------------------------------------------------------ Found on this computer (F1–F6)++test('F1 loading: status, skeleton rows, Preview disabled', async () => {+ const d = await open({ desktop: true, over: { 'GET /api/import/local': () => new Promise(() => {}) } });+ await d.click(/^Found on this computer/);+ assert.match(d.dlg().querySelector('h2').textContent, /Found on this computer/);+ assert.equal(d.dlg().querySelector('[data-found-state]').dataset.foundState, 'loading');+ assert.match(d.dlg().querySelector('[role="status"]').textContent, /Looking in 5 usual places/);+ assert.equal(primaryOf(d.dlg).disabled, true);+});++test('F2 found: rows start unticked, too_large is disabled with the Folder hint, ticking counts sources', async () => {+ const d = await open({ desktop: true });+ await d.click(/^Found on this computer/);+ const boxes = [...d.dlg().querySelectorAll('input[type="checkbox"]')];+ assert.equal(boxes.length, 3);+ assert.ok(boxes.every((b) => !b.checked), 'all rows start unticked');+ assert.equal(boxes[2].disabled, true, 'too big');+ assert.match(d.dlg().textContent, /Too big to bring from here\. Use Folder to pick just the parts you want\./);+ assert.match(d.dlg().textContent, /1 bot · 3 skills · 2 memory files/);+ assert.match(d.dlg().textContent, /~\/\.openclaw\/workspace/, 'path as sent');+ assert.match(d.dlg().textContent, /Read-only\. kwant never follows a link out of these folders/);+ assert.equal(primaryOf(d.dlg).textContent.trim(), 'Preview');+ assert.equal(primaryOf(d.dlg).disabled, true);+ assert.ok(btn(footer(d.dlg), /^Cancel$/));+ boxes[0].click();+ boxes[1].click();+ await settle();+ assert.equal(primaryOf(d.dlg).textContent.trim(), 'Preview 2 sources');+ assert.equal(primaryOf(d.dlg).disabled, false);+ // Names on request.+ const show = btn(d.dlg(), /^Show names$/);+ assert.equal(show.getAttribute('aria-expanded'), 'false');+ show.click();+ await settle();+ assert.match(d.dlg().textContent, /seo.*support.*triage/);+});++test('F6 reading, then F5 preview: per-bot source and the shared-skills line', async () => {+ let release;+ const d = await open({ desktop: true, over: { 'POST /api/import/local/preview': () => new Promise((r) => (release = () => r(json(demo.localPreview())))) } });+ await d.click(/^Found on this computer/);+ const boxes = [...d.dlg().querySelectorAll('input[type="checkbox"]')];+ boxes[0].click();+ boxes[1].click();+ await settle();+ primaryOf(d.dlg).click();+ await settle();+ assert.match(primaryOf(d.dlg).textContent, /Reading 2 sources…/);+ assert.equal(primaryOf(d.dlg).disabled, true);+ assert.ok([...d.dlg().querySelectorAll('input[type="checkbox"]')].every((b) => b.disabled), 'ticks locked while reading');+ const sent = JSON.parse(d.s.calls.find((c) => c.url === '/api/import/local/preview').body);+ assert.deepEqual(sent, { sources: ['openclaw', 'claude-skills'] });+ release();+ await settle();+ const out = d.dlg().textContent;+ assert.match(d.dlg().querySelector('h2').textContent, /Check before importing/);+ assert.match(out, /1 bot will be created from 2 sources on this computer/);+ assert.match(out, /From OpenClaw · ~\/\.openclaw\/workspace/);+ assert.match(out, /Also: 7 shared skills from ~\/\.claude\/skills\./);+ assert.match(out, /openclaw\.json and credentials\/: never opened/);+ assert.equal(primaryOf(d.dlg).textContent.trim(), 'Import 1 bot');+ // Back keeps the ticks.+ await d.click(/^$/); // Back is the icon button first in the header+ assert.equal(d.dlg().querySelector('h2').textContent, 'Found on this computer');+ assert.equal([...d.dlg().querySelectorAll('input[type="checkbox"]')].filter((b) => b.checked).length, 2);+});++test('F2 errors: too_large keeps the ticks; not_found looks again and drops a vanished source', async () => {+ let d = await open({ desktop: true, over: { 'POST /api/import/local/preview': () => fail(413, 'too_large', 'over 50 MB') } });+ await d.click(/^Found on this computer/);+ d.dlg().querySelectorAll('input[type="checkbox"]')[0].click();+ await settle();+ primaryOf(d.dlg).click();+ await settle();+ assert.match(d.dlg().querySelector('[role="alert"]').textContent, /Together these are too big \(over 500 files or 50 MB\)\. Tick fewer\./);+ assert.doesNotMatch(d.dlg().textContent, /over 50 MB/, 'nothing raw');+ assert.equal(d.dlg().querySelectorAll('input[type="checkbox"]')[0].checked, true);+ cleanup.forEach((f) => f());+ cleanup = [];++ d = await open({+ desktop: true,+ over: {+ 'GET /api/import/local': (_i, n) => json(n === 1 ? demo.localList() : demo.localList({ sources: demo.localList().sources.slice(1) })),+ 'POST /api/import/local/preview': () => fail(404, 'not_found', 'gone'),+ },+ });+ await d.click(/^Found on this computer/);+ const boxes = d.dlg().querySelectorAll('input[type="checkbox"]');+ boxes[0].click();+ boxes[1].click();+ await settle();+ primaryOf(d.dlg).click();+ await settle(12);+ assert.match(d.dlg().textContent, /One of these isn’t there any more\. kwant looked again\./);+ assert.equal(d.s.count('GET /api/import/local'), 2, 'looked again');+ const now = [...d.dlg().querySelectorAll('input[type="checkbox"]')];+ assert.equal(now.length, 2, 'the vanished row is gone');+ assert.equal(now.filter((b) => b.checked).length, 1);+ assert.equal(primaryOf(d.dlg).textContent.trim(), 'Preview 1 source');+});++test('F3 nothing: the five places, Pick a folder, footer Back', async () => {+ const d = await open({ desktop: true, folders: true, over: { 'GET /api/import/local': () => json({ available: true, sources: [] }) } });+ await d.click(/^Found on this computer/);+ assert.equal(d.dlg().querySelector('[data-found-state]').dataset.foundState, 'nothing');+ for (const p of m.USUAL_PLACES) assert.ok(d.dlg().textContent.includes(p), p);+ assert.deepEqual([...footer(d.dlg).querySelectorAll('button')].map((b) => b.textContent.trim()), ['Back']);+ await d.click(/^Pick a folder$/);+ assert.equal(d.dlg().querySelector('h2').textContent, 'Bring a folder');+});++test('F4 error: Couldn’t look, Try again looks again, and the other ways stay open', async () => {+ const d = await open({ desktop: true, folders: true, over: { 'GET /api/import/local': (_i, n) => (n === 1 ? fail(500, 'internal', 'raw boom') : json(demo.localList())) } });+ await d.click(/^Found on this computer/);+ assert.equal(d.dlg().querySelector('[data-found-state]').dataset.foundState, 'error');+ assert.match(d.dlg().textContent, /Couldn’t look on this computer/);+ assert.match(d.dlg().textContent, /You can still pick a folder or upload a file\./);+ assert.doesNotMatch(d.dlg().textContent, /raw boom/);+ await d.click(/^Try again$/);+ assert.equal(d.dlg().querySelector('[data-found-state]').dataset.foundState, 'found');+});++// ------------------------------------------------------------------ Folder (D1–D4)++function pickFolder(dlg, list) {+ const input = dlg().querySelector('input[type="file"]');+ assert.ok(input.hasAttribute('webkitdirectory'));+ const files = list.map(([path, body]) => {+ const f = new File([body], path.split('/').pop());+ Object.defineProperty(f, 'webkitRelativePath', { value: path });+ return f;+ });+ Object.defineProperty(input, 'files', { value: files, configurable: true });+ input.dispatchEvent(new window.Event('change', { bubbles: true }));+}+const zipNames = (bytes) => {+ const names = [];+ for (let i = 0; i + 46 <= bytes.length; i++)+ if (bytes[i] === 0x50 && bytes[i + 1] === 0x4b && bytes[i + 2] === 0x01 && bytes[i + 3] === 0x02) {+ const n = bytes[i + 28] | (bytes[i + 29] << 8);+ names.push(new TextDecoder().decode(bytes.slice(i + 46, i + 46 + n)));+ }+ return names.sort();+};++test('D1 empty → D2 picked: what works, left-out list, then a zip of only readable files as <folder>.zip', async () => {+ const d = await open({ folders: true });+ await d.click(/^Folder/);+ assert.equal(d.dlg().querySelector('h2').textContent, 'Bring a folder');+ assert.match(d.dlg().textContent, /A skills folder.*Up to 20 MB once packed/);+ assert.equal(primaryOf(d.dlg).disabled, true);+ pickFolder(d.dlg, demo.folderFiles());+ await settle();+ assert.match(d.dlg().querySelector('[data-picked]').textContent, /molty-workspace4 files · 1 KB/);+ assert.match(d.dlg().textContent, /Left out before packing/);+ assert.match(d.dlg().textContent, /Sign-in and settings files \(never sent\): 2 files/);+ assert.ok(btn(footer(d.dlg), /^Change folder$/));+ primaryOf(d.dlg).click();+ await settle(12);+ const call = d.s.calls.find((c) => c.url.startsWith('/api/import/preview'));+ assert.equal(call.url, '/api/import/preview?filename=molty-workspace.zip');+ const names = zipNames(new Uint8Array(await call.body.arrayBuffer()));+ assert.deepEqual(names, ['molty-workspace/AGENTS.md', 'molty-workspace/IDENTITY.md', 'molty-workspace/SOUL.md', 'molty-workspace/skills/triage/SKILL.md']);+ assert.match(d.dlg().textContent, /1 bot will be created from molty-workspace/);+ assert.match(d.dlg().textContent, /Files that weren't read: notes\.txt/);+});++test('D3 too big: checked before sending, rose alert, Preview disabled', async () => {+ const d = await open({ folders: true });+ await d.click(/^Folder/);+ const many = Array.from({ length: 501 }, (_, i) => [`big/skills/s${i}/SKILL.md`, 'x']);+ pickFolder(d.dlg, many);+ await settle();+ const alert = d.dlg().querySelector('[data-folder-problem]');+ assert.equal(alert.getAttribute('role'), 'alert');+ assert.match(alert.textContent, /That folder has 501 readable files, over the 500 limit\. Pick a smaller part of it, such as its skills folder\./);+ assert.equal(primaryOf(d.dlg).disabled, true);+ assert.equal(d.s.count('POST /api/import/preview'), 0);+});++test('D4 nothing recognised (415): the copy box and what works, no raw text', async () => {+ const d = await open({ folders: true, over: { 'POST /api/import/preview': () => fail(415, 'unsupported', 'raw: no format matched') } });+ await d.click(/^Folder/);+ pickFolder(d.dlg, [['notes/agents/readme.md', 'hi']]);+ await settle();+ primaryOf(d.dlg).click();+ await settle(12);+ assert.match(d.dlg().textContent, /Nothing kwant can bring in this folder/);+ assert.match(d.dlg().textContent, /looked for SOUL\.md, AGENTS\.md, SKILL\.md and agents\/\*\.md/);+ assert.doesNotMatch(d.dlg().textContent, /raw:/);+ assert.equal(d.dlg().querySelector('h2').textContent, 'Bring a folder');+});++// ------------------------------------------------------------------ GitHub link (G1–G7)++function typeUrl(dlg, value) {+ const input = dlg().querySelector('input[type="url"]');+ Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value').set.call(input, value);+ input.dispatchEvent(new window.Event('input', { bubbles: true }));+ return input;+}++test('G1 → G2: the empty field, then a non-GitHub link gets the rose line and blocks Preview', async () => {+ const d = await open();+ await d.click(/^GitHub link/);+ assert.equal(d.dlg().querySelector('h2').textContent, 'Bring from a GitHub link');+ const input = d.dlg().querySelector('input[type="url"]');+ assert.equal(input.getAttribute('inputmode'), 'url');+ assert.equal(input.getAttribute('autocomplete'), 'off');+ assert.equal(input.getAttribute('spellcheck'), 'false');+ assert.equal(document.activeElement, input, 'autofocused');+ assert.equal(primaryOf(d.dlg).disabled, true);+ typeUrl(d.dlg, 'https://gitlab.com/a/b');+ await settle();+ primaryOf(d.dlg).click();+ await settle();+ assert.match(d.dlg().querySelector('[role="alert"]').textContent, /Only github\.com links work here\. kwant doesn’t fetch from other sites\./);+ assert.equal(input.getAttribute('aria-invalid'), 'true');+ assert.equal(primaryOf(d.dlg).disabled, true);+ assert.equal(d.s.count('POST /api/import/github/preview'), 0);+});++test('G3 fetching → G4 error → Try again', async () => {+ let release;+ const d = await open({ over: { 'POST /api/import/github/preview': (_i, n) => (n === 1 ? new Promise((r) => (release = () => r(fail(404, 'not_found', 'raw 404')))) : json(demo.githubPreview())) } });+ await d.click(/^GitHub link/);+ typeUrl(d.dlg, 'github.com/example-team/support-skills');+ await settle();+ primaryOf(d.dlg).click();+ await settle();+ assert.match(d.dlg().querySelector('[role="status"]').textContent, /Downloading from github\.com…/);+ assert.equal(primaryOf(d.dlg).textContent.trim(), 'Fetching…');+ assert.equal(primaryOf(d.dlg).disabled, true);+ assert.deepEqual(JSON.parse(d.s.calls.find((c) => c.url === '/api/import/github/preview').body), { url: 'github.com/example-team/support-skills' });+ release();+ await settle();+ assert.match(d.dlg().textContent, /No public repo at that link/);+ assert.match(d.dlg().textContent, /Only public repos work for now\./);+ assert.doesNotMatch(d.dlg().textContent, /raw 404/);+ assert.equal(primaryOf(d.dlg).textContent.trim(), 'Try again');+ primaryOf(d.dlg).click();+ await settle(12);+ assert.equal(d.dlg().querySelector('h2').textContent, 'Check before importing');+});++test('every GitHub error code gets Mira’s words', () => {+ const want = {+ not_found: 'No public repo at that link',+ too_large: 'That repo is too big',+ unsupported: 'Nothing kwant can bring here',+ redirect: 'GitHub sent kwant somewhere else',+ invalid: 'That download wasn’t a safe zip',+ fetch_failed: 'GitHub didn’t answer',+ };+ for (const [code, title] of Object.entries(want)) assert.equal(m.githubErrorText(new m.ImportError('raw', code, 422)).title, title, code);+});++test('GitHub too_large: over 20 MB says to zip the folder; the 500-file case keeps the folder-link advice', () => {+ const big = m.githubErrorText(new m.ImportError("This repository is larger than 20 MB, so kwant can't fetch it. Download the folder you want, zip it and import the zip instead.", 'too_large', 413));+ assert.equal(big.title, 'That repo is too big');+ assert.equal(big.detail, 'This repository is larger than 20 MB, so kwant can’t fetch it. Download the folder you want, zip it and import the zip instead.');+ const many = m.githubErrorText(new m.ImportError('too many files', 'too_large', 413));+ assert.match(many.detail, /Link to the folder you need instead/);+});++test('G5 preview with MIT: source block, chip, skill chips, Import N skills; the attribution isn’t repeated', async () => {+ const d = await open();+ await d.click(/^GitHub link/);+ typeUrl(d.dlg, 'https://github.com/example-team/support-skills');+ await settle();+ primaryOf(d.dlg).click();+ await settle(12);+ const block = d.dlg().querySelector('[data-github-source]');+ assert.match(block.textContent, /example-team\/support-skills/);+ assert.match(block.textContent, /default branch · commit 3f2a91c/);+ assert.equal(block.querySelector('a').getAttribute('href'), 'https://github.com/example-team/support-skills');+ assert.equal(block.querySelector('a').getAttribute('rel'), 'noopener noreferrer');+ const chip = block.querySelector('[data-licence]');+ assert.match(chip.textContent, /MIT licence/);+ assert.doesNotMatch(chip.className, /kw-chip-warn/);+ assert.match(block.textContent, /Free to reuse\. Keep the author’s notice\./);+ const out = d.dlg().textContent;+ assert.match(out, /No bots in this one\. 12 skills will be added to Home\./);+ assert.match(out, /and 4 more/);+ assert.equal(d.dlg().querySelectorAll('ul[aria-label="Skills"] li.font-mono').length, 8);+ assert.match(out, /scripts\/: 6 files that run code/);+ assert.doesNotMatch(out, /From github\.com\/example-team/, 'attribution is in the source block, not Not brought over');+ assert.equal(primaryOf(d.dlg).textContent.trim(), 'Import 12 skills');+ assert.equal(primaryOf(d.dlg).disabled, false);+ // G7 done.+ primaryOf(d.dlg).click();+ await settle(12);+ assert.match(d.dlg().textContent, /Imported 12 skills/);+ assert.match(d.dlg().querySelector('[data-github-done]').textContent, /From github\.com\/example-team\/support-skills \(MIT\)\. They wait for your OK in Settings › This space › Skills\./);+ assert.ok(btn(footer(d.dlg), /Undo import/));+ assert.equal(d.changed.length, 1);+});++test('GitHub preview, Back, then a skills-only folder: Done has no GitHub line and no licence chip (Ada’s #459 review)', async () => {+ const skillsOnly = () => {+ const p = demo.githubPreview();+ delete p.github;+ p.bundle.source = { kind: 'skills', label: 'support-skills', exported_at: null };+ p.bundle.omitted = [];+ return json(p);+ };+ const d = await open({ folders: true, over: { 'POST /api/import/preview': skillsOnly } });+ await d.click(/^GitHub link/);+ typeUrl(d.dlg, 'https://github.com/example-team/support-skills');+ await settle();+ primaryOf(d.dlg).click();+ await settle(12);+ assert.ok(d.dlg().querySelector('[data-github-source]'), 'GitHub preview shown first');+ const back = async () => (d.dlg().querySelector('button[aria-label="Back"]').click(), settle());+ await back();+ await back();+ await d.click(/^Folder/);+ pickFolder(d.dlg, [['my-skills/triage/SKILL.md', '---\nname: triage\n---\n'], ['my-skills/seo/SKILL.md', '---\nname: seo\n---\n']]);+ await settle();+ primaryOf(d.dlg).click();+ await settle(12);+ assert.equal(d.dlg().querySelector('[data-github-source]'), null, 'folder preview has no GitHub block');+ primaryOf(d.dlg).click();+ await settle(12);+ assert.match(d.dlg().textContent, /Imported 12 skills/);+ assert.doesNotMatch(d.dlg().textContent, /From github\.com/);+ assert.equal(d.dlg().querySelector('[data-github-done]'), null);+ assert.equal(d.dlg().querySelector('[data-licence]'), null);+ assert.doesNotMatch(d.dlg().textContent, /MIT/);+});++test('G6 no licence: amber chip and the warning in Worth a look, never blocking', () => {+ const p = demo.githubPreview({ licence: null });+ const out = html(m.PreviewView, { preview: p, github: p.github, skip: new Set(), onToggle() {}, spaceName: 'Home' });+ const raw = m.renderToStaticMarkup(h(m.PreviewView, { preview: p, github: p.github, skip: new Set(), onToggle() {}, spaceName: 'Home' }));+ assert.match(raw, /kw-chip kw-chip-warn[^"]*" data-licence/);+ assert.match(out, /No licence/);+ assert.match(out, /Worth a look.*no licence file/);+});++test('unknown licence: plain chip and a link to read it', () => {+ const p = demo.githubPreview({ licence: { spdx: null, name: 'Custom', file: 'LICENSE.md' }, ref: 'main', path: 'skills' });+ const raw = m.renderToStaticMarkup(h(m.PreviewView, { preview: p, github: p.github, skip: new Set(), onToggle() {} }));+ const out = text(raw);+ assert.match(out, /Unknown licence/);+ assert.match(out, /Read the licence before you share these\./);+ assert.match(raw, /href="https:\/\/github\.com\/example-team\/support-skills\/blob\/3f2a91c08d5e4b7a9c1f2e3d4c5b6a7980716253\/[^"]*LICENSE\.md"/);+ assert.match(out, /main · commit 3f2a91c · \/skills/);+});++// ------------------------------------------------------------------ pure helpers++test('githubLinkOk takes the contract’s three shapes on github.com only', () => {+ for (const ok of ['https://github.com/a/b', 'github.com/a/b', 'https://www.github.com/a/b.git', 'github.com/a/b/tree/main', 'github.com/a/b/tree/main/skills/x', 'github.com/a/b/blob/main/SKILL.md'])+ assert.ok(m.githubLinkOk(ok), ok);+ for (const bad of ['http://github.com/a/b', 'https://gitlab.com/a/b', 'https://github.com.evil.com/a/b', 'https://[email protected]/a/b', 'https://github.com:8443/a/b', 'github.com/a', 'github.com/a/b/issues/1', 'github.com/a/b/tree/main/%2e%2e', 'github.com/a/b\\c', ''])+ assert.equal(m.githubLinkOk(bad), null, bad);+});++test('found helpers: hint, counts, primary label, origin', () => {+ const s = demo.localList().sources;+ assert.equal(m.foundHint(s.slice(0, 2)), 'OpenClaw and Claude Code skills');+ assert.equal(m.countsLine(s[0]), '1 bot · 3 skills · 2 memory files');+ assert.equal(m.countsLine({ bots: 0, skills: 7, memories: 0 }), '7 skills');+ assert.equal(m.foundPrimaryLabel(0, false), 'Preview');+ assert.equal(m.foundPrimaryLabel(1, false), 'Preview 1 source');+ assert.equal(m.foundPrimaryLabel(2, true), 'Reading 2 sources…');+ const o = m.localOrigin(s.slice(0, 2));+ assert.equal(o.botSource.id, 'openclaw');+ assert.equal(o.skillSource.id, 'claude-skills');+ assert.equal(m.localOrigin([s[0], { ...s[0], id: 'x' }]).botSource, null, 'two bot sources: not certain');+});++test('folder picking is off on iPhone and iPad, even where the property exists', () => {+ const proto = { webkitdirectory: false };+ assert.equal(m.folderPickSupported(proto, { userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)', maxTouchPoints: 0 }), true);+ assert.equal(m.folderPickSupported(proto, { userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X)' }), false);+ assert.equal(m.folderPickSupported(proto, { userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)', maxTouchPoints: 5 }), false);+ assert.equal(m.folderPickSupported({}, { userAgent: 'x' }), false);+});diff --git a/frontend/tests/importA4Demo.mjs b/frontend/tests/importA4Demo.mjsnew file mode 100644index 00000000..0c3be1f3--- /dev/null+++ b/frontend/tests/importA4Demo.mjs@@ -0,0 +1,114 @@+// Demo data for A4 (0.8.0 import UI), shaped like release-080/import-contract.md. Shared by+// importA4.test.mjs and the screenshot script. Made-up names only; no real accounts.+export const skill = (name) => ({ name, description: `${name} skill`, body: `# ${name}\n` });++export const localList = (over = {}) => ({+ available: true,+ sources: [+ { id: 'openclaw', kind: 'openclaw', label: 'OpenClaw', path: '~/.openclaw/workspace', bots: 1, skills: 3, memories: 2, names: ['seo', 'support', 'triage'], too_large: false },+ { id: 'claude-skills', kind: 'claude-skills', label: 'Claude Code skills', path: '~/.claude/skills', bots: 0, skills: 7, memories: 0, names: ['changelog', 'deploy', 'fix', 'plan', 'review', 'seo-audit', 'triage'], too_large: false },+ { id: 'codex', kind: 'codex', label: 'Codex', path: '~/.codex', bots: 1, skills: 40, memories: 0, names: [], too_large: true },+ ],+ ...over,+});++export const bot = (ref, name, title) => ({ ref, name, title, persona_prompt: `You are ${name}. Keep answers short and kind.`, memories: ['Likes tidy notes.'], skills: [skill('triage')], routines: [] });++export const localPreview = () => ({+ bundle: {+ format: 'kwant.bundle/1',+ source: { kind: 'local', label: 'this computer', exported_at: null },+ bots: [bot('molty', 'Molty', 'Support lead')],+ teams: [],+ skills: ['changelog', 'deploy', 'fix', 'plan', 'review', 'seo-audit', 'triage'].map(skill),+ omitted: ['openclaw.json and credentials/: never opened, so no keys or tokens', 'Daily logs in memory/: 14 files'],+ },+ warnings: [],+ dropped: [],+ problems: [],+ renames: [],+ can_apply: true,+});++const SKILLS12 = ['billing-faq', 'escalate', 'first-reply', 'refunds', 'tone-check', 'triage', 'macros', 'sla-watch', 'handover', 'csat', 'bug-report', 'close-ticket'];++export const githubInfo = (over = {}) => ({+ owner: 'example-team',+ repo: 'support-skills',+ ref: 'HEAD',+ path: null,+ commit: '3f2a91c08d5e4b7a9c1f2e3d4c5b6a7980716253',+ licence: { spdx: 'MIT', name: 'MIT License', file: 'LICENSE' },+ ...over,+});++export const githubPreview = (over = {}) => {+ const github = githubInfo(over);+ const lic = github.licence ? github.licence.spdx ?? github.licence.name : 'no licence';+ return {+ bundle: {+ format: 'kwant.bundle/1',+ source: { kind: 'github', label: `${github.owner}/${github.repo}`, exported_at: null },+ bots: [],+ teams: [],+ skills: SKILLS12.map(skill),+ omitted: [`From github.com/${github.owner}/${github.repo} (${lic})`, 'scripts/: 6 files that run code'],+ },+ warnings: github.licence ? [] : [{ message: 'This repo has no licence file. You may not have the right to reuse or share these skills.' }],+ dropped: [],+ problems: [],+ renames: [],+ can_apply: true,+ github,+ };+};++export const folderPreview = () => ({+ bundle: {+ format: 'kwant.bundle/1',+ source: { kind: 'openclaw', label: 'OpenClaw', exported_at: null },+ bots: [bot('molty', 'Molty', 'Support lead')],+ teams: [],+ skills: [],+ omitted: ["Files in the zip that weren't read: notes.txt"],+ },+ warnings: [],+ dropped: [],+ problems: [],+ renames: [],+ can_apply: true,+});++export const applied = (preview) => ({+ import: {+ id: 'imp-demo',+ space_id: 'home',+ source_kind: preview.bundle.source.kind,+ status: 'applied',+ created: {+ kwants: preview.bundle.bots.map((b, i) => ({ ref: b.ref, id: `k${i}`, name: b.name })),+ skills: [...preview.bundle.bots.flatMap((b) => b.skills.map((s) => s.name)), ...preview.bundle.skills.map((s) => s.name)],+ routines: [],+ teams: [],+ channels: [],+ memories: 0,+ },+ created_at: '2026-11-09T07:00:00Z',+ undone_at: null,+ },+ warnings: [],+ dropped: [],+ renames: [],+});++/** A picked folder as `<input webkitdirectory>` gives it (relative paths include the folder). */+export const folderFiles = (name = 'molty-workspace') => [+ [`${name}/SOUL.md`, 'Be kind.'],+ [`${name}/IDENTITY.md`, '- **Name:** Molty'],+ [`${name}/AGENTS.md`, 'Work in small steps.'],+ [`${name}/skills/triage/SKILL.md`, '---\nname: triage\n---\n'],+ [`${name}/notes.txt`, 'random'],+ [`${name}/.env`, 'OPENAI_API_KEY=sk-demo-not-real'],+ [`${name}/.git/HEAD`, 'ref: refs/heads/main'],+ [`${name}/openclaw.json`, '{"apiKey":"sk-demo-not-real"}'],+];diff --git a/frontend/tests/importFolderPack.test.mjs b/frontend/tests/importFolderPack.test.mjsnew file mode 100644index 00000000..2c57e16b--- /dev/null+++ b/frontend/tests/importFolderPack.test.mjs@@ -0,0 +1,208 @@+// A picked folder is zipped and sent to the server, which may be remote (Ada's review of #455, "Note for+// Pixel"; release-080/ada-review-455.md). Only files an import format reads are packed, hidden folders+// below the picked one are skipped, and key stores never leave the computer.+import assert from 'node:assert/strict';+import test from 'node:test';+import { loadBundled } from './bundle.mjs';++const m = await loadBundled(`export { folderPlan, folderZip, leftOutKind } from './src/importSources';`);++const pick = (files) => files.map(([path, body = 'x']) => ({ path, size: body.length, file: new Blob([body]) }));+const kept = (plan) => plan.kept.map((e) => e.path).sort();+const zipNames = async (plan) => {+ const { body } = await m.folderZip(plan);+ const bytes = new Uint8Array(await body.arrayBuffer());+ // Central directory: signature 0x02014b50, name length at +28, name at +46.+ const names = [];+ for (let i = 0; i + 46 <= bytes.length; i++) {+ if (bytes[i] === 0x50 && bytes[i + 1] === 0x4b && bytes[i + 2] === 0x01 && bytes[i + 3] === 0x02) {+ const n = bytes[i + 28] | (bytes[i + 29] << 8);+ names.push(new TextDecoder().decode(bytes.slice(i + 46, i + 46 + n)));+ }+ }+ return { names, text: new TextDecoder('latin1').decode(bytes) };+};+const KEY = 'sk-live-DO-NOT-SEND-1234567890';++test('OpenClaw: openclaw.json, credentials/ and sessions/ are never packed', async () => {+ const plan = m.folderPlan(+ pick([+ ['.openclaw/openclaw.json', `{"apiKey":"${KEY}"}`],+ ['.openclaw/credentials/oauth.json', `{"token":"${KEY}"}`],+ ['.openclaw/agents/main/sessions/s1.json', `{"m":"${KEY}"}`],+ ['.openclaw/agents/main/sessions/s1.md', KEY],+ ['.openclaw/workspace/SOUL.md', 'be kind'],+ ['.openclaw/workspace/memory/2026-11-01.md', 'note'],+ ['.openclaw/workspace/skills/seo/SKILL.md', '# seo'],+ ['.openclaw/workspace/notes.txt', 'random'],+ ['.openclaw/workspace/avatar.png', 'png'],+ ]),+ );+ assert.deepEqual(kept(plan), [+ '.openclaw/workspace/SOUL.md',+ '.openclaw/workspace/memory/2026-11-01.md',+ '.openclaw/workspace/skills/seo/SKILL.md',+ ]);+ const { names, text } = await zipNames(plan);+ assert.ok(!names.some((n) => /openclaw\.json|credentials\/|sessions\//.test(n)), names.join(', '));+ assert.ok(!text.includes(KEY));+ assert.ok(plan.left.some((l) => /never sent/i.test(l.label)), JSON.stringify(plan.left));+});++test('Codex: auth.json is never packed; config.toml goes only as an empty name', async () => {+ const plan = m.folderPlan(+ pick([+ ['.codex/auth.json', `{"OPENAI_API_KEY":"${KEY}"}`],+ ['.codex/config.toml', `api_key = "${KEY}"`],+ ['.codex/AGENTS.md', 'do it'],+ ['.codex/sessions/2026/11/09/rollout.jsonl', KEY],+ ['.codex/skills/fix/SKILL.md', '# fix'],+ ]),+ );+ assert.deepEqual(kept(plan), ['.codex/AGENTS.md', '.codex/skills/fix/SKILL.md']);+ const { names, text } = await zipNames(plan);+ assert.ok(names.includes('.codex/config.toml'), 'Codex marker kept by name');+ assert.ok(!names.some((n) => /auth\.json|sessions\//.test(n)), names.join(', '));+ assert.ok(!text.includes(KEY), 'no key bytes in the zip');+});++test('Hermes: .env, state.db and config.yaml stay; memories and skills go', () => {+ const plan = m.folderPlan(+ pick([+ ['.hermes/.env', `OPENAI_API_KEY=${KEY}`],+ ['.hermes/state.db', KEY],+ ['.hermes/state.db-wal', KEY],+ ['.hermes/config.yaml', `key: ${KEY}`],+ ['.hermes/auth.json', KEY],+ ['.hermes/SOUL.md', 'soul'],+ ['.hermes/memories/MEMORY.md', 'm'],+ ['.hermes/memories/USER.md', 'u'],+ ['.hermes/skills/.bundled_manifest', 'a'],+ ['.hermes/skills/web/search/SKILL.md', 's'],+ ]),+ );+ assert.deepEqual(kept(plan), [+ '.hermes/SOUL.md',+ '.hermes/memories/MEMORY.md',+ '.hermes/memories/USER.md',+ '.hermes/skills/.bundled_manifest',+ '.hermes/skills/web/search/SKILL.md',+ ]);+});++test('hidden folders below the picked one, and project files, are skipped', () => {+ const plan = m.folderPlan(+ pick([+ ['team/.git/config', 'x'],+ ['team/.cache/skills/x/SKILL.md', 'x'],+ ['team/.claude/agents/hidden.md', 'x'],+ ['team/node_modules/a/package.json', '{}'],+ ['team/package.json', '{}'],+ ['team/tsconfig.json', '{}'],+ ['team/README.md', 'read me'],+ ['team/src/index.ts', 'x'],+ ['team/.paperclip.yaml', 'routines: []'],+ ['team/COMPANY.md', 'c'],+ ['team/agents/ceo/AGENTS.md', 'a'],+ ['team/agents/reviewer.md', 'r'],+ ['team/employees/ada/employee.json', '{}'],+ ['team/export.json', '{}'],+ ['team/LICENSE', 'MIT'],+ ]),+ );+ assert.deepEqual(kept(plan), [+ 'team/.paperclip.yaml',+ 'team/COMPANY.md',+ 'team/LICENSE',+ 'team/agents/ceo/AGENTS.md',+ 'team/agents/reviewer.md',+ 'team/employees/ada/employee.json',+ 'team/export.json',+ ]);+});++test('key-store names are refused at any depth and in any case', () => {+ for (const p of ['x/OpenClaw.json', 'x/a/AUTH.json', 'x/Credentials/a.md', 'x/a/Sessions/b.md', 'x/.env.local', 'x/a/state.db'])+ assert.notEqual(m.leftOutKind(p, 1), null, p);+});++// Ada's review of #459, must-fix 1: every key-bearing file her probe saw packed.+const PROBE = 'sk-ant-PROBE';+const KEY_FILES = [+ '.openclaw/openclaw.json',+ '.openclaw/agents/main/agent/auth-profiles.json',+ '.openclaw/agents/main/agent/models.json',+ '.openclaw/identity/device.json',+ '.openclaw/devices/paired.json',+ '.openclaw/cron/jobs.json',+ '.openclaw/.claude/settings.json',+ '.openclaw/.claude/settings.local.json',+ '.openclaw/credentials.json',+ '.openclaw/token.json',+ '.openclaw/client_secret_123.json',+ '.openclaw/service-account.json',+ '.openclaw/mcp.json',+ '.openclaw/.hermes/gateway_state.json',+ '.openclaw/workspace/settings.json',+ '.openclaw/workspace/oauth-cache.json',+];++test('a picked app folder never packs its key files: only the .md files local import reads', async () => {+ const plan = m.folderPlan(+ pick([+ ...KEY_FILES.map((p) => [p, `{"key":"${PROBE}"}`]),+ ['.openclaw/workspace/SOUL.md', 'be kind'],+ ['.openclaw/workspace/skills/x/SKILL.md', '# x'],+ ['.openclaw/workspace/memory/api-key-rotation.md', 'rotate monthly'],+ ['.openclaw/workspace/export.json', '{"name":"not read in an app home"}'],+ ]),+ );+ assert.deepEqual(kept(plan), [+ '.openclaw/workspace/SOUL.md',+ '.openclaw/workspace/memory/api-key-rotation.md',+ '.openclaw/workspace/skills/x/SKILL.md',+ ]);+ const { names, text } = await zipNames(plan);+ for (const f of KEY_FILES) assert.ok(!names.includes(f), f);+ assert.ok(!names.some((n) => n.endsWith('.json')), names.join(', '));+ assert.ok(!text.includes(PROBE), 'no sk-ant-PROBE bytes in the zip');+ assert.ok(plan.left.some((l) => /never sent/i.test(l.label)), JSON.stringify(plan.left));+});++test('a picked .claude never packs settings.json; its agents and skills go', async () => {+ const plan = m.folderPlan(+ pick([+ ['.claude/settings.json', `{"env":{"ANTHROPIC_API_KEY":"${PROBE}"}}`],+ ['.claude/settings.local.json', `{"env":{"K":"${PROBE}"}}`],+ ['.claude/.credentials.json', PROBE],+ ['.claude/agents/reviewer.md', 'r'],+ ['.claude/skills/oauth-helper/SKILL.md', 's'],+ ]),+ );+ assert.deepEqual(kept(plan), ['.claude/agents/reviewer.md', '.claude/skills/oauth-helper/SKILL.md']);+ assert.ok(!(await zipNames(plan)).text.includes(PROBE));+});++test('a generic folder drops named key files but keeps bot .json (employee.json, conversations.json)', async () => {+ const plan = m.folderPlan(+ pick([+ ['team/credentials.json', PROBE],+ ['team/token.json', PROBE],+ ['team/client_secret_1.json', PROBE],+ ['team/service-account-prod.json', PROBE],+ ['team/my-api_key.txt', PROBE],+ ['team/private.yaml', PROBE],+ ['team/employees/ada/employee.json', '{"name":"Ada"}'],+ ['team/employees/ada/memory/api-key-rotation.md', 'rotate'],+ ['team/conversations.json', '[]'],+ ]),+ );+ assert.deepEqual(kept(plan), [+ 'team/conversations.json',+ 'team/employees/ada/employee.json',+ 'team/employees/ada/memory/api-key-rotation.md',+ ]);+ const { text } = await zipNames(plan);+ assert.ok(!text.includes(PROBE), 'no sk-ant-PROBE bytes in the zip');+ assert.equal(plan.left.find((l) => /never sent/i.test(l.label))?.count, 6, JSON.stringify(plan.left));+});diff --git a/frontend/tests/wording.test.mjs b/frontend/tests/wording.test.mjsindex b41dc209..5177eda9 100644--- a/frontend/tests/wording.test.mjs+++ b/frontend/tests/wording.test.mjs@@ -21,12 +21,14 @@ const BAD = /\b(kwants?|kwnt|agents?)\b/i;// Agent Maestro, the VS Code extension's own name (a Custom API preset), and "coding agent", what// Claude Code, Codex and Cursor are called in Settings → Coding agents (0.7.4).const ALLOWED = /\bkwant bots?\b|\bcoding agents?\b|\b(?:exec kwnt )?kwnt (?:token|signin-link)\b|~\/\.kwnt\/api-token/gi;-const MAESTRO = /\bAgent Maestro\b/g;+const MAESTRO = /\bAgent Maestro\b|\bHermes Agent\b/g;// T/D preview sheet (0.7.7): Mira's review-396-397 must-fix 7 and Ada's deviation-4 ruling keep "kwant"// as the subject in these three sentences only.// Run Claude inside the VM (0.7.7): Mira's ui-check-450 must-fix 2 names kwant, the program on the computer,// in these settings and chat-notice sentences ("Restart kwant" is what a person on a phone has to do).-const RULED = /\bso kwant can read\b|\bmanifests kwant knows\b|\bnames kwant knows\b|\bkwant’s (?:browser|log|own data|tools)\b|\bkwant (?:adds it|couldn’t|won’t share|keeps|is running as root|can’t pass)\b|\b[Rr]estart kwant\b|\bStart kwant as\b/g;+// Import from this computer, a folder or a GitHub link (0.8.0 A4): Mira's a4-import.md names kwant, the program+// that looks and fetches, in these sentences.+const RULED = /\bso kwant can read\b|\bmanifests kwant knows\b|\bnames kwant knows\b|\bkwant’s (?:browser|log|own data|tools)\b|\bkwant (?:adds it|couldn’t|won’t share|keeps|is running as root|can’t pass|can’t fetch)\b|\b[Rr]estart kwant\b|\bStart kwant as\b|\bkwant (?:looked|never follows|downloads it|found nothing|doesn’t fetch)\b|\bNothing kwant can bring\b|\bwhere kwant looked\b|\bsent kwant somewhere\b/g;/** Whether a literal reads like text a person sees (a sentence, or a capitalised word). */const looksVisible = (text, node) => {