Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
feat(settings): rebuild the import page as one workbench per kind
vastsa10523469fc59
diff --git a/apps/desktop/src/features/settings/SettingsPage.tsx b/apps/desktop/src/features/settings/SettingsPage.tsxindex acd22ecf5..32b6d1df8 100644--- a/apps/desktop/src/features/settings/SettingsPage.tsx+++ b/apps/desktop/src/features/settings/SettingsPage.tsx@@ -51,11 +51,8 @@ import {SettingsCard,SettingsRow,} from "./primitives";-import {- AgentInstructionsSection,- ImportSection,- UpdatesRow,-} from "./agent-sections";+import { AgentInstructionsSection, UpdatesRow } from "./agent-sections";+import { ImportSection } from "./import-page";import { PromptEnhancementCard } from "./prompt-enhancement-card";import { CloseBehaviorSection, DeveloperSection } from "./developer-sections";import { PluginScenicThemesDestination } from "../../components/settings/PluginScenicThemesDestination";diff --git a/apps/desktop/src/features/settings/agent-sections.tsx b/apps/desktop/src/features/settings/agent-sections.tsxindex 175901992..bcbcf3abb 100644--- a/apps/desktop/src/features/settings/agent-sections.tsx+++ b/apps/desktop/src/features/settings/agent-sections.tsx@@ -1,31 +1,11 @@-import { useCallback, useEffect, useMemo, useState, type ReactNode } from "react";+import { useCallback, useEffect, useState, type ReactNode } from "react";import { useTranslation } from "react-i18next";import type { AgentInstructionFile } from "@pi-desktop/shared";-import { useAppStore } from "../../stores/app-store";import { api } from "../../lib/api";-import type {- ImportCandidate,- ModelConfigImportCandidate,- ExternalSkillCandidate,- ExternalSkillImportItem,- ExternalSkillScanResult,- ExternalSkillSourceKind,- ExternalMcpCandidate,- ExternalMcpImportItem,- ExternalMcpScanResult,- ExternalMcpSourceKind,-} from "../../lib/api";import { useUpdateState } from "../../hooks/use-update-state";-import {- DEFAULT_IMPORT_GROUP_BY,- formatImportDate,- groupImportCandidates,- type ImportGroupBy,-} from "../../lib/import-groups";-import { Badge, Button, cx } from "../../components/ui";-import { IconChevronLeft, IconFileText } from "../../components/icons";+import { Button } from "../../components/ui";+import { IconFileText } from "../../components/icons";import { ReleaseNotesDialog } from "../../components/ReleaseNotesDialog";-import { SettingsMenuSelect } from "../../components/settings/SettingsMenuSelect";import { SettingsCard, SettingsRow } from "./primitives";export function AgentInstructionsSection() {@@ -203,890 +183,3 @@ export function UpdatesRow({ currentVersion }: { currentVersion?: string }) {);}-export function ImportSection() {- return (- <div className="settings-stack">- <SessionImportPanel />- <ModelConfigImportPanel />- <SkillsScanImportPanel />- <McpScanImportPanel />- </div>- );-}--export function SessionImportPanel() {- const { t, i18n } = useTranslation();- const refreshSessions = useAppStore((s) => s.refreshSessions);- const showToast = useAppStore((s) => s.showToast);- const [candidates, setCandidates] = useState<ImportCandidate[] | null>(null);- const [selected, setSelected] = useState<Set<string>>(new Set());- const [groupBy, setGroupBy] = useState<ImportGroupBy>(DEFAULT_IMPORT_GROUP_BY);- const [expandedGroups, setExpandedGroups] = useState<Set<string>>(new Set());- const [scanning, setScanning] = useState(false);- const [importing, setImporting] = useState(false);-- const keyOf = (c: ImportCandidate) => `${c.source}:${c.externalId}`;-- const scan = async () => {- setScanning(true);- try {- const res = await api.scanImportSessions();- setCandidates(res.sessions);- setSelected(new Set());- setExpandedGroups(new Set());- } catch (e) {- showToast(e instanceof Error ? e.message : String(e), { variant: "error" });- } finally {- setScanning(false);- }- };-- const runImport = async () => {- if (!candidates) return;- const items = candidates.filter((c) => selected.has(keyOf(c)));- if (items.length === 0) return;- setImporting(true);- try {- const res = await api.runImportSessions(items);- await refreshSessions({ revealImportedProjects: true });- showToast(- t("settings.importResult", {- imported: res.imported,- skipped: res.skipped,- failed: res.failed,- }),- { variant: res.failed > 0 ? "error" : "success" },- );- } catch (e) {- showToast(e instanceof Error ? e.message : String(e), { variant: "error" });- } finally {- setImporting(false);- }- };-- const importLabels = useMemo(- () => ({- noProject: t("settings.importNoProject"),- sources: {- "claude-code": t("settings.importSourceClaudeCode"),- opencode: t("settings.importSourceOpenCode"),- codex: t("settings.importSourceCodex"),- pi: t("settings.importSourcePi"),- },- }),- [t],- );-- const groups = useMemo(- () => groupImportCandidates(candidates ?? [], groupBy, importLabels),- [candidates, groupBy, importLabels],- );-- const allKeys = useMemo(() => (candidates ?? []).map(keyOf), [candidates]);- const allSelected = allKeys.length > 0 && allKeys.every((k) => selected.has(k));-- const toggleKeys = (keys: string[], on: boolean) => {- setSelected((prev) => {- const next = new Set(prev);- for (const k of keys) {- if (on) next.add(k);- else next.delete(k);- }- return next;- });- };-- return (- <>- <SettingsCard title={t("settings.importTitle")}>- <SettingsRow title={t("settings.importScan")}>- <Button variant="secondary" disabled={scanning} onClick={() => void scan()}>- {scanning ? t("settings.importScanning") : t("settings.importScan")}- </Button>- </SettingsRow>- </SettingsCard>-- {candidates !== null && (- <SettingsCard>- {candidates.length === 0 ? (- <div className="settings-empty">{t("settings.importNone")}</div>- ) : (- <>- <div className="import-toolbar">- <label className="import-select-all">- <input- type="checkbox"- aria-label={t("settings.importSelectAll")}- checked={allSelected}- onChange={(e) => toggleKeys(allKeys, e.target.checked)}- />- <span>- {t("settings.importFound", { count: candidates.length })}- {selected.size > 0- ? ` · ${t("settings.importSelectedCount", { count: selected.size })}`- : ""}- </span>- </label>- <div className="import-toolbar-actions">- <label className="import-group-by">- <span>{t("settings.importGroupBy")}</span>- <SettingsMenuSelect- className="import-group-select"- label={t("settings.importGroupBy")}- value={groupBy}- onChange={(id) => {- setGroupBy(id as ImportGroupBy);- setExpandedGroups(new Set());- }}- options={[- { id: "source", label: t("settings.importGroupBySource") },- { id: "path", label: t("settings.importGroupByPath") },- ]}- />- </label>- <Button- variant="primary"- disabled={importing || selected.size === 0}- onClick={() => void runImport()}- >- {importing- ? t("settings.importing")- : t("settings.importSelected", { count: selected.size })}- </Button>- </div>- </div>-- <div className="import-groups">- {groups.map((group, groupIndex) => {- const groupKeys = group.items.map(keyOf);- const groupSelected = groupKeys.filter((k) => selected.has(k)).length;- const isCollapsed = !expandedGroups.has(group.id);- const groupBodyId = `import-group-body-${groupIndex}`;- return (- <div key={group.id} className="import-group">- <div className="import-group-header">- <input- type="checkbox"- aria-label={t("settings.importSelectGroup", { name: group.name })}- checked={groupSelected === groupKeys.length}- ref={(el) => {- if (el)- el.indeterminate =- groupSelected > 0 && groupSelected < groupKeys.length;- }}- onChange={(e) => toggleKeys(groupKeys, e.target.checked)}- />- <button- type="button"- className="import-group-toggle"- aria-controls={groupBodyId}- aria-expanded={!isCollapsed}- onClick={() =>- setExpandedGroups((prev) => {- const next = new Set(prev);- if (next.has(group.id)) next.delete(group.id);- else next.add(group.id);- return next;- })- }- >- <span- className={cx("import-group-chevron", isCollapsed && "collapsed")}- aria-hidden- >- <IconChevronLeft size={13} />- </span>- <span className="import-group-name">{group.name}</span>- {group.projectPath ? (- <span className="import-group-path">{group.projectPath}</span>- ) : null}- <span className="import-group-count">- {t("settings.importSessionCount", { count: group.items.length })}- </span>- </button>- </div>- {!isCollapsed && (- <div id={groupBodyId} className="import-group-body">- {group.items.map((c) => {- const k = keyOf(c);- return (- <label key={k} className="import-row">- <input- type="checkbox"- checked={selected.has(k)}- onChange={(e) => toggleKeys([k], e.target.checked)}- />- <span className="import-row-main">- <span className="import-row-title">{c.title}</span>- <span className="import-row-meta">- {c.messageCount === null- ? t("settings.importMessagesUnknown")- : t("settings.importMessages", {- count: c.messageCount,- })}- {" · "}- {formatImportDate(- c.updatedAt,- i18n.resolvedLanguage || i18n.language,- )}- </span>- </span>- <Badge tone="neutral">{importLabels.sources[c.source]}</Badge>- </label>- );- })}- </div>- )}- </div>- );- })}- </div>- </>- )}- </SettingsCard>- )}- </>- );-}--function hostOf(baseUrl: string | null): string {- if (!baseUrl) return "";- try {- return new URL(baseUrl).host || baseUrl;- } catch {- return baseUrl.replace(/^https?:\/\//, "").split("/")[0] || baseUrl;- }-}--export function ModelConfigImportPanel() {- const { t } = useTranslation();- const refreshProviders = useAppStore((s) => s.refreshProviders);- const showToast = useAppStore((s) => s.showToast);- const [candidates, setCandidates] = useState<ModelConfigImportCandidate[] | null>(null);- const [selected, setSelected] = useState<Set<string>>(new Set());- const [expandedGroups, setExpandedGroups] = useState<Set<string>>(new Set());- const [scanning, setScanning] = useState(false);- const [importing, setImporting] = useState(false);-- const keyOf = (c: ModelConfigImportCandidate) => `${c.source}:${c.externalId}`;-- const scan = async () => {- setScanning(true);- try {- const res = await api.scanImportModelConfigs();- setCandidates(res.providers);- setSelected(new Set());- setExpandedGroups(new Set());- } catch (e) {- showToast(e instanceof Error ? e.message : String(e), { variant: "error" });- } finally {- setScanning(false);- }- };-- const runImport = async () => {- if (!candidates) return;- const items = candidates.filter((c) => selected.has(keyOf(c)));- if (items.length === 0) return;- setImporting(true);- try {- const res = await api.runImportModelConfigs(items);- await refreshProviders();- showToast(- t("settings.importResult", {- imported: res.imported,- skipped: res.skipped,- failed: res.failed,- }),- { variant: res.failed > 0 ? "error" : "success" },- );- } catch (e) {- showToast(e instanceof Error ? e.message : String(e), { variant: "error" });- } finally {- setImporting(false);- }- };-- const sourceLabels = useMemo(- () => ({- "claude-code": t("settings.importSourceClaudeCode"),- opencode: t("settings.importSourceOpenCode"),- codex: t("settings.importSourceCodex"),- pi: t("settings.importSourcePi"),- "cc-switch": t("settings.importSourceCcSwitch"),- }),- [t],- );-- const groups = useMemo(() => {- if (!candidates) return [];- const grouped = new Map<ModelConfigImportCandidate["source"], ModelConfigImportCandidate[]>();- for (const candidate of candidates) {- const items = grouped.get(candidate.source) ?? [];- items.push(candidate);- grouped.set(candidate.source, items);- }- return [...grouped.entries()].map(([source, items]) => ({- id: source,- name: sourceLabels[source],- items,- }));- }, [candidates, sourceLabels]);-- const allKeys = useMemo(() => (candidates ?? []).map(keyOf), [candidates]);- const allSelected = allKeys.length > 0 && allKeys.every((k) => selected.has(k));-- const toggleKeys = (keys: string[], on: boolean) => {- setSelected((prev) => {- const next = new Set(prev);- for (const k of keys) {- if (on) next.add(k);- else next.delete(k);- }- return next;- });- };-- return (- <>- <SettingsCard title={t("settings.importModelsTitle")}>- <SettingsRow- title={t("settings.importScan")}- description={t("settings.importModelsScanDesc")}- >- <Button variant="secondary" disabled={scanning} onClick={() => void scan()}>- {scanning ? t("settings.importScanning") : t("settings.importScan")}- </Button>- </SettingsRow>- </SettingsCard>-- {candidates !== null && (- <SettingsCard>- {candidates.length === 0 ? (- <div className="settings-empty">{t("settings.importModelsNone")}</div>- ) : (- <>- <div className="import-toolbar">- <label className="import-select-all">- <input- type="checkbox"- aria-label={t("settings.importModelsSelectAll")}- checked={allSelected}- onChange={(e) => toggleKeys(allKeys, e.target.checked)}- />- <span>- {t("settings.importModelsFound", { count: candidates.length })}- {selected.size > 0- ? ` · ${t("settings.importSelectedCount", { count: selected.size })}`- : ""}- </span>- </label>- <div className="import-toolbar-actions">- <Button- variant="primary"- disabled={importing || selected.size === 0}- onClick={() => void runImport()}- >- {importing- ? t("settings.importing")- : t("settings.importSelected", { count: selected.size })}- </Button>- </div>- </div>-- <div className="import-groups">- {groups.map((group, groupIndex) => {- const groupKeys = group.items.map(keyOf);- const groupSelected = groupKeys.filter((k) => selected.has(k)).length;- const isCollapsed = !expandedGroups.has(group.id);- const groupBodyId = `import-model-group-body-${groupIndex}`;- return (- <div key={group.id} className="import-group">- <div className="import-group-header">- <input- type="checkbox"- aria-label={t("settings.importModelsSelectGroup", { name: group.name })}- checked={groupSelected === groupKeys.length}- ref={(el) => {- if (el)- el.indeterminate =- groupSelected > 0 && groupSelected < groupKeys.length;- }}- onChange={(e) => toggleKeys(groupKeys, e.target.checked)}- />- <button- type="button"- className="import-group-toggle"- aria-controls={groupBodyId}- aria-expanded={!isCollapsed}- onClick={() =>- setExpandedGroups((prev) => {- const next = new Set(prev);- if (next.has(group.id)) next.delete(group.id);- else next.add(group.id);- return next;- })- }- >- <span- className={cx("import-group-chevron", isCollapsed && "collapsed")}- aria-hidden- >- <IconChevronLeft size={13} />- </span>- <span className="import-group-name">{group.name}</span>- <span className="import-group-count">- {t("settings.importModelsFound", { count: group.items.length })}- </span>- </button>- </div>- {!isCollapsed && (- <div id={groupBodyId} className="import-group-body">- {group.items.map((c) => {- const k = keyOf(c);- const host = hostOf(c.baseUrl);- return (- <label key={k} className="import-row">- <input- type="checkbox"- checked={selected.has(k)}- onChange={(e) => toggleKeys([k], e.target.checked)}- />- <span className="import-row-main">- <span className="import-row-title">{c.name}</span>- <span className="import-row-meta">- {t("settings.importModelsCount", { count: c.modelIds.length })}- {host ? ` · ${host}` : ""}- </span>- </span>- <Badge tone={c.hasSecret ? "success" : "warning"}>- {c.hasSecret- ? t("settings.importModelsHasKey")- : t("settings.importModelsNoKey")}- </Badge>- </label>- );- })}- </div>- )}- </div>- );- })}- </div>- </>- )}- </SettingsCard>- )}- </>- );-}--/**- * Developer mode gate: the console stays unreachable until the toggle is on,- * which is also what unlocks F12 and the macOS View ▸ developer tools item- * (enforced in the main process, not here).- */--// ----------------------------------------------------------------------------// Scan skills / MCP servers from other agent tools on this machine.-// -----------------------------------------------------------------------------const SKILL_SOURCE_KEY: Record<ExternalSkillSourceKind, string> = {- "claude-user": "settings.importAgentScanSourceClaudeUser",- "claude-project": "settings.importAgentScanSourceClaudeProject",- "pi-user": "settings.importAgentScanSourcePiUser",- "pi-project": "settings.importAgentScanSourcePiProject",-};--const MCP_SOURCE_KEY: Record<ExternalMcpSourceKind, string> = {- "claude-desktop": "settings.importAgentScanSourceClaudeDesktop",- "claude-code": "settings.importAgentScanSourceClaudeCode",- "cursor-global": "settings.importAgentScanSourceCursorGlobal",- "cursor-project": "settings.importAgentScanSourceCursorProject",- codex: "settings.importAgentScanSourceCodex",- opencode: "settings.importAgentScanSourceOpenCode",- "chatgpt-desktop": "settings.importAgentScanSourceChatgpt",-};--function groupBySource<C extends { source: string }>(- candidates: C[],-): Array<{ id: string; items: C[] }> {- const map = new Map<string, C[]>();- for (const c of candidates) {- const bucket = map.get(c.source);- if (bucket) bucket.push(c);- else map.set(c.source, [c]);- }- return Array.from(map.entries()).map(([id, items]) => ({ id, items }));-}--export function SkillsScanImportPanel() {- const { t } = useTranslation();- const showToast = useAppStore((s) => s.showToast);- const [result, setResult] = useState<ExternalSkillScanResult | null>(null);- const [selected, setSelected] = useState<Set<string>>(new Set());- const [mode, setMode] = useState<"copy" | "link">("copy");- const [scanning, setScanning] = useState(false);- const [importing, setImporting] = useState(false);-- const keyOf = (c: ExternalSkillCandidate) => `${c.source}:${c.sourcePath}`;-- const scan = async () => {- setScanning(true);- try {- const res = await api.scanExternalSkills();- setResult(res);- setSelected(new Set());- } catch (e) {- showToast(e instanceof Error ? e.message : String(e), { variant: "error" });- } finally {- setScanning(false);- }- };-- const runImport = async () => {- if (!result) return;- const items: ExternalSkillImportItem[] = result.candidates- .filter((c) => selected.has(keyOf(c)))- .map((c) => ({- source: c.source,- sourcePath: c.sourcePath,- shape: c.shape,- rootDir: c.rootDir,- id: c.id,- name: c.name,- description: c.description,- }));- if (items.length === 0) return;- setImporting(true);- try {- const res = await api.runExternalSkillsImport({- level: "global",- mode,- items,- });- showToast(- t("settings.importAgentScanResult", {- imported: res.imported.length,- skipped: res.skipped.length,- failed: res.failed.length,- }),- { variant: res.failed.length > 0 ? "error" : "success" },- );- // Refresh scan so already-imported rows disappear next round.- await scan();- } catch (e) {- showToast(e instanceof Error ? e.message : String(e), { variant: "error" });- } finally {- setImporting(false);- }- };-- const toggle = (k: string, on: boolean) =>- setSelected((prev) => {- const next = new Set(prev);- if (on) next.add(k);- else next.delete(k);- return next;- });-- const groups = useMemo(() => groupBySource(result?.candidates ?? []), [result]);- const allKeys = useMemo(- () => (result?.candidates ?? []).map(keyOf),- [result],- );- const allSelected = allKeys.length > 0 && allKeys.every((k) => selected.has(k));-- return (- <>- <SettingsCard title={t("settings.importAgentSkillsTitle")}>- <div className="settings-description">- {t("settings.importAgentSkillsDesc")}- </div>- <SettingsRow title={t("settings.importScan")}>- <Button variant="secondary" disabled={scanning} onClick={() => void scan()}>- {scanning ? t("settings.importScanning") : t("settings.importScan")}- </Button>- </SettingsRow>- <SettingsRow title={t("settings.importAgentScanMode")}>- <SettingsMenuSelect- label={t("settings.importAgentScanMode")}- value={mode}- onChange={(id) => setMode(id as "copy" | "link")}- options={[- { id: "copy", label: t("settings.importAgentScanModeCopy") },- { id: "link", label: t("settings.importAgentScanModeLink") },- ]}- />- <div className="settings-hint">- {t("settings.importAgentScanModeHint")}- </div>- </SettingsRow>- </SettingsCard>-- {result !== null && (- <SettingsCard>- {result.candidates.length === 0 ? (- <div className="settings-empty">{t("settings.importAgentScanNone")}</div>- ) : (- <>- <div className="import-toolbar">- <label className="import-select-all">- <input- type="checkbox"- checked={allSelected}- aria-label={t("settings.importSelectAll")}- onChange={(e) => {- const on = e.target.checked;- setSelected(on ? new Set(allKeys) : new Set());- }}- />- <span>- {t("settings.importAgentScanFoundSkills", {- count: result.candidates.length,- })}- {selected.size > 0- ? ` · ${t("settings.importSelectedCount", { count: selected.size })}`- : ""}- </span>- </label>- <Button- variant="primary"- disabled={importing || selected.size === 0}- onClick={() => void runImport()}- >- {importing- ? t("settings.importing")- : t("settings.importSelected", { count: selected.size })}- </Button>- </div>- <div className="import-groups">- {groups.map((g) => (- <div key={g.id} className="import-group">- <div className="import-group-header">- <span className="import-group-title">- {t(- SKILL_SOURCE_KEY[g.id as ExternalSkillSourceKind] ??- "settings.importSourcePi",- )}- </span>- <Badge tone="neutral">{g.items.length}</Badge>- </div>- <div className="import-group-body">- {g.items.map((c) => {- const k = keyOf(c);- return (- <label key={k} className="import-row">- <input- type="checkbox"- checked={selected.has(k)}- onChange={(e) => toggle(k, e.target.checked)}- />- <span className="import-row-main">- <span className="import-row-title">{c.name || c.id}</span>- <span className="import-row-meta">- {c.description || c.sourcePath}- </span>- </span>- <Badge- tone={c.shape === "dir" ? "success" : "neutral"}- >- {c.shape === "dir"- ? t("settings.importAgentScanShapeDir")- : t("settings.importAgentScanShapeFile")}- </Badge>- </label>- );- })}- </div>- </div>- ))}- </div>- </>- )}- </SettingsCard>- )}- </>- );-}--export function McpScanImportPanel() {- const { t } = useTranslation();- const showToast = useAppStore((s) => s.showToast);- const [result, setResult] = useState<ExternalMcpScanResult | null>(null);- const [selected, setSelected] = useState<Set<string>>(new Set());- const [scanning, setScanning] = useState(false);- const [importing, setImporting] = useState(false);-- const keyOf = (c: ExternalMcpCandidate) => `${c.source}:${c.id}`;-- const scan = async () => {- setScanning(true);- try {- const res = await api.scanExternalMcp();- setResult(res);- setSelected(new Set());- } catch (e) {- showToast(e instanceof Error ? e.message : String(e), { variant: "error" });- } finally {- setScanning(false);- }- };-- const runImport = async () => {- if (!result) return;- const items: ExternalMcpImportItem[] = result.candidates- .filter((c) => selected.has(keyOf(c)))- .map((c) => ({- source: c.source,- sourcePath: c.sourcePath,- id: c.id,- rawKey: c.rawKey,- label: c.label,- description: c.description,- transport: c.transport,- command: c.command,- args: c.args,- env: c.env,- url: c.url,- headers: c.headers,- disabled: c.disabled,- }));- if (items.length === 0) return;- setImporting(true);- try {- const res = await api.runExternalMcpImport({ items });- showToast(- t("settings.importAgentScanResult", {- imported: res.imported.length,- skipped: res.skipped.length,- failed: res.failed.length,- }),- { variant: res.failed.length > 0 ? "error" : "success" },- );- await scan();- } catch (e) {- showToast(e instanceof Error ? e.message : String(e), { variant: "error" });- } finally {- setImporting(false);- }- };-- const toggle = (k: string, on: boolean) =>- setSelected((prev) => {- const next = new Set(prev);- if (on) next.add(k);- else next.delete(k);- return next;- });-- const groups = useMemo(() => groupBySource(result?.candidates ?? []), [result]);- const allKeys = useMemo(- () => (result?.candidates ?? []).map(keyOf),- [result],- );- const allSelected = allKeys.length > 0 && allKeys.every((k) => selected.has(k));-- return (- <>- <SettingsCard title={t("settings.importAgentMcpTitle")}>- <div className="settings-description">- {t("settings.importAgentMcpDesc")}- </div>- <SettingsRow title={t("settings.importScan")}>- <Button variant="secondary" disabled={scanning} onClick={() => void scan()}>- {scanning ? t("settings.importScanning") : t("settings.importScan")}- </Button>- </SettingsRow>- </SettingsCard>-- {result !== null && (- <SettingsCard>- {result.candidates.length === 0 ? (- <div className="settings-empty">{t("settings.importAgentScanNone")}</div>- ) : (- <>- <div className="import-toolbar">- <label className="import-select-all">- <input- type="checkbox"- checked={allSelected}- aria-label={t("settings.importSelectAll")}- onChange={(e) => {- const on = e.target.checked;- setSelected(on ? new Set(allKeys) : new Set());- }}- />- <span>- {t("settings.importAgentScanFoundMcp", {- count: result.candidates.length,- })}- {selected.size > 0- ? ` · ${t("settings.importSelectedCount", { count: selected.size })}`- : ""}- </span>- </label>- <Button- variant="primary"- disabled={importing || selected.size === 0}- onClick={() => void runImport()}- >- {importing- ? t("settings.importing")- : t("settings.importSelected", { count: selected.size })}- </Button>- </div>- <div className="import-groups">- {groups.map((g) => (- <div key={g.id} className="import-group">- <div className="import-group-header">- <span className="import-group-title">- {t(- MCP_SOURCE_KEY[g.id as ExternalMcpSourceKind] ??- "settings.importSourcePi",- )}- </span>- <Badge tone="neutral">{g.items.length}</Badge>- </div>- <div className="import-group-body">- {g.items.map((c) => {- const k = keyOf(c);- return (- <label key={k} className="import-row">- <input- type="checkbox"- checked={selected.has(k)}- onChange={(e) => toggle(k, e.target.checked)}- />- <span className="import-row-main">- <span className="import-row-title">- {c.label || c.id}- </span>- <span className="import-row-meta">- {c.description ||- c.command ||- c.url ||- c.sourcePath}- </span>- </span>- <Badge- tone={c.transport === "http" ? "warning" : "neutral"}- >- {c.transport === "http"- ? t("settings.importAgentScanTransportHttp")- : t("settings.importAgentScanTransportStdio")}- </Badge>- </label>- );- })}- </div>- </div>- ))}- </div>- </>- )}- </SettingsCard>- )}- </>- );-}diff --git a/apps/desktop/src/features/settings/import-page.tsx b/apps/desktop/src/features/settings/import-page.tsxnew file mode 100644index 000000000..3fefcfd4b--- /dev/null+++ b/apps/desktop/src/features/settings/import-page.tsx@@ -0,0 +1,1130 @@+/**+ * Settings ▸ Import.+ *+ * One workbench for everything this machine can hand over: sessions, provider+ * and model configuration, skills, and MCP servers. A tab per kind means a+ * scan result survives a switch; the active kind owns one toolbar (select-all+ * with both counts, its own options, rescan, import selected) and one list+ * panel whose group headers are quiet label lines and whose rows are+ * individual tiles — the same rhythm as the agent capability destinations.+ *+ * Every kind keeps its own explicit scan: switching tabs never starts one.+ */+import { useEffect, useMemo, useRef, useState, type ReactNode } from "react";+import { useTranslation } from "react-i18next";+import type {+ ExternalMcpCandidate,+ ExternalMcpImportItem,+ ExternalMcpScanResult,+ ExternalMcpSourceKind,+ ExternalSkillCandidate,+ ExternalSkillImportItem,+ ExternalSkillScanResult,+ ExternalSkillSourceKind,+ ImportCandidate,+ ModelConfigImportCandidate,+} from "../../lib/api";+import { api } from "../../lib/api";+import { useAppStore } from "../../stores/app-store";+import {+ DEFAULT_IMPORT_GROUP_BY,+ formatImportDate,+ groupImportCandidates,+ type ImportGroupBy,+} from "../../lib/import-groups";+import { Badge, Button, cx } from "../../components/ui";+import { IconChevronLeft, IconDownload } from "../../components/icons";+import { SettingsMenuSelect } from "../../components/settings/SettingsMenuSelect";++type ImportKind = "sessions" | "models" | "skills" | "mcp";++/**+ * Tab labels reuse the sessions / models / skills / MCP labels the sidebar and+ * the settings rail already ship, so the switcher adds no catalog entries and+ * cannot drift from the destination it mirrors.+ */+const IMPORT_KINDS: readonly { id: ImportKind; labelKey: string }[] = [+ { id: "sessions", labelKey: "nav.sessions" },+ { id: "models", labelKey: "settings.nav.models" },+ { id: "skills", labelKey: "settings.nav.skills" },+ { id: "mcp", labelKey: "settings.nav.mcp" },+];++export function ImportSection() {+ const { t } = useTranslation();+ const [kind, setKind] = useState<ImportKind>("sessions");++ return (+ <div className="import-page">+ <div+ className="settings-segment import-segment"+ role="tablist"+ aria-label={t("settings.import")}+ >+ {IMPORT_KINDS.map((entry) => (+ <button+ key={entry.id}+ type="button"+ role="tab"+ id={`import-tab-${entry.id}`}+ aria-selected={kind === entry.id}+ aria-controls={`import-panel-${entry.id}`}+ className={cx(+ "settings-segment-item",+ "import-segment-btn",+ kind === entry.id && "active",+ )}+ onClick={() => setKind(entry.id)}+ >+ {t(entry.labelKey)}+ </button>+ ))}+ </div>++ {IMPORT_KINDS.map((entry) => (+ <div+ key={entry.id}+ className="import-view"+ id={`import-panel-${entry.id}`}+ role="tabpanel"+ aria-labelledby={`import-tab-${entry.id}`}+ hidden={kind !== entry.id}+ >+ <ImportKindPanel kind={entry.id} />+ </div>+ ))}+ </div>+ );+}++/**+ * The four workbenches stay mounted: `hidden` only takes one out of view, so a+ * scan result and its selection survive a tab switch.+ */+function ImportKindPanel({ kind }: { kind: ImportKind }) {+ if (kind === "sessions") return <SessionImportPanel />;+ if (kind === "models") return <ModelConfigImportPanel />;+ if (kind === "skills") return <SkillsScanImportPanel />;+ return <McpScanImportPanel />;+}++/* ---------------------------------------------------------------------------+ * Shared page anatomy+ * ------------------------------------------------------------------------- */++/**+ * The only action row on a kind: both counts behind the select-all control,+ * kind options and the two actions on the right. `found` is the kind's own+ * localized sentence, so the row never needs a per-kind copy of itself.+ */+function ImportToolbar({+ found,+ selectedCount,+ allSelected,+ selectAllLabel,+ onToggleAll,+ scanning,+ importing,+ onScan,+ onImport,+ options,+}: {+ found: string;+ selectedCount: number;+ allSelected: boolean;+ selectAllLabel: string;+ onToggleAll: (on: boolean) => void;+ scanning: boolean;+ importing: boolean;+ onScan: () => void;+ onImport: () => void;+ /** Kind-specific control in front of the actions, e.g. grouping or mode. */+ options?: ReactNode;+}) {+ const { t } = useTranslation();+ const selectAllRef = useRef<HTMLInputElement>(null);++ useEffect(() => {+ const node = selectAllRef.current;+ if (node) node.indeterminate = selectedCount > 0 && !allSelected;+ }, [selectedCount, allSelected]);++ return (+ <div className="import-toolbar">+ <label className="import-select-all">+ <input+ ref={selectAllRef}+ type="checkbox"+ checked={allSelected}+ aria-label={selectAllLabel}+ onChange={(event) => onToggleAll(event.target.checked)}+ />+ <span className="import-count">+ <span className="import-count-found">{found}</span>+ {selectedCount > 0 ? (+ <span className="import-count-selected">+ {t("settings.importSelectedCount", { count: selectedCount })}+ </span>+ ) : null}+ </span>+ </label>+ <div className="import-toolbar-actions">+ {options}+ <Button+ variant="secondary"+ disabled={scanning}+ aria-busy={scanning || undefined}+ onClick={onScan}+ >+ {scanning ? t("settings.importScanning") : t("settings.importScan")}+ </Button>+ <Button+ variant="primary"+ disabled={importing || selectedCount === 0}+ aria-busy={importing || undefined}+ onClick={onImport}+ >+ {importing+ ? t("settings.importing")+ : t("settings.importSelected", { count: selectedCount })}+ </Button>+ </div>+ </div>+ );+}++/** A labelled menu select inside the toolbar, for grouping or import mode. */+function ImportOption({+ label,+ value,+ options,+ onChange,+}: {+ label: string;+ value: string;+ options: { id: string; label: string }[];+ onChange: (id: string) => void;+}) {+ return (+ <label className="import-option">+ <span className="import-option-label">{label}</span>+ <SettingsMenuSelect+ className="import-option-select"+ label={label}+ value={value}+ options={options}+ onChange={onChange}+ />+ </label>+ );+}++/** One group: a quiet label line that also discloses its rows. */+function ImportGroup({+ bodyId,+ name,+ path,+ count,+ countLabel,+ expanded,+ onToggle,+ selection,+ children,+}: {+ bodyId: string;+ name: string;+ /** Exact project path, or the resolved config path, when the group has one. */+ path?: string | null;+ count: number;+ countLabel: string;+ expanded: boolean;+ onToggle: () => void;+ /** Kinds whose groups are selectable render the leading checkbox. */+ selection?: {+ label: string;+ checked: boolean;+ indeterminate: boolean;+ onChange: (on: boolean) => void;+ };+ children: ReactNode;+}) {+ return (+ <section className="import-group">+ <div className="import-group-header">+ {selection ? (+ <input+ type="checkbox"+ checked={selection.checked}+ aria-label={selection.label}+ ref={(node) => {+ if (node) node.indeterminate = selection.indeterminate;+ }}+ onChange={(event) => selection.onChange(event.target.checked)}+ />+ ) : null}+ <button+ type="button"+ className="import-group-toggle"+ aria-controls={bodyId}+ aria-expanded={expanded}+ onClick={onToggle}+ >+ <span+ className={cx("import-group-chevron", !expanded && "collapsed")}+ aria-hidden+ >+ <IconChevronLeft size={13} />+ </span>+ <span className="import-group-name">{name}</span>+ {path ? (+ <code className="import-group-path" title={path}>+ {path}+ </code>+ ) : null}+ <span className="import-group-count" title={countLabel}>+ {count}+ </span>+ </button>+ </div>+ {expanded ? (+ <div id={bodyId} className="import-group-body">+ {children}+ </div>+ ) : null}+ </section>+ );+}++/**+ * One candidate. The checkbox, the identity, and the row's own badge are the+ * whole anatomy, so every kind reads the same way.+ */+function ImportRow({+ title,+ meta,+ checked,+ onChange,+ badge,+}: {+ title: string;+ meta: ReactNode;+ checked: boolean;+ onChange: (on: boolean) => void;+ badge?: ReactNode;+}) {+ return (+ <label className="import-row">+ <input+ type="checkbox"+ checked={checked}+ onChange={(event) => onChange(event.target.checked)}+ />+ <span className="import-row-main">+ <span className="import-row-title">{title}</span>+ <span className="import-row-meta">{meta}</span>+ </span>+ {badge}+ </label>+ );+}++/**+ * Pre-scan state: what the scan will look at, and the action that starts it.+ * Empty states carry no filler, so a kind without a description shows only the+ * glyph and the action.+ */+function ImportIdle({+ description,+ note,+ onScan,+ scanning,+}: {+ description?: string;+ note?: string;+ onScan: () => void;+ scanning: boolean;+}) {+ const { t } = useTranslation();+ return (+ <div className="settings-panel import-panel">+ <div className="import-idle">+ <span className="import-idle-glyph" aria-hidden>+ <IconDownload size={20} />+ </span>+ {description ? <p className="import-idle-copy">{description}</p> : null}+ {note ? <p className="import-idle-note">{note}</p> : null}+ <Button variant="secondary" disabled={scanning} onClick={onScan}>+ {scanning ? t("settings.importScanning") : t("settings.importScan")}+ </Button>+ </div>+ </div>+ );+}++/** The result surface: rows when a scan found something, a line when it did not. */+function ImportResults({ message, children }: { message?: string; children?: ReactNode }) {+ return (+ <div className="settings-panel import-panel">+ {message ? <p className="import-empty">{message}</p> : children}+ </div>+ );+}++/**+ * Clears a selection when the underlying candidate set is replaced.+ * `keyOf` stays with the caller so every kind keeps its own identity rule.+ */+function toggleKey(previous: Set<string>, key: string, on: boolean): Set<string> {+ const next = new Set(previous);+ if (on) next.add(key);+ else next.delete(key);+ return next;+}+++/**+ * Group disclosure. Groups start expanded — the found candidates are the+ * answer to a scan — and every kind's label line discloses its own rows, so all+ * four read the same way.+ */+function useGroupDisclosure() {+ const [collapsed, setCollapsed] = useState<Set<string>>(new Set());+ return {+ isExpanded: (id: string) => !collapsed.has(id),+ toggle: (id: string) =>+ setCollapsed((previous) =>+ previous.has(id)+ ? new Set([...previous].filter((entry) => entry !== id))+ : new Set([...previous, id]),+ ),+ reset: () => setCollapsed(new Set()),+ };+}+/* ---------------------------------------------------------------------------+ * Sessions+ * ------------------------------------------------------------------------- */++export function SessionImportPanel() {+ const { t, i18n } = useTranslation();+ const refreshSessions = useAppStore((s) => s.refreshSessions);+ const showToast = useAppStore((s) => s.showToast);+ const [candidates, setCandidates] = useState<ImportCandidate[] | null>(null);+ const [selected, setSelected] = useState<Set<string>>(new Set());+ const [groupBy, setGroupBy] = useState<ImportGroupBy>(DEFAULT_IMPORT_GROUP_BY);+ const disclosure = useGroupDisclosure();+ const [scanning, setScanning] = useState(false);+ const [importing, setImporting] = useState(false);++ const keyOf = (candidate: ImportCandidate) =>+ `${candidate.source}:${candidate.externalId}`;++ const scan = async () => {+ setScanning(true);+ try {+ const res = await api.scanImportSessions();+ setCandidates(res.sessions);+ setSelected(new Set());+ disclosure.reset();+ } catch (e) {+ showToast(e instanceof Error ? e.message : String(e), { variant: "error" });+ } finally {+ setScanning(false);+ }+ };++ const runImport = async () => {+ if (!candidates) return;+ const items = candidates.filter((candidate) => selected.has(keyOf(candidate)));+ if (items.length === 0) return;+ setImporting(true);+ try {+ const res = await api.runImportSessions(items);+ await refreshSessions({ revealImportedProjects: true });+ showToast(+ t("settings.importResult", {+ imported: res.imported,+ skipped: res.skipped,+ failed: res.failed,+ }),+ { variant: res.failed > 0 ? "error" : "success" },+ );+ } catch (e) {+ showToast(e instanceof Error ? e.message : String(e), { variant: "error" });+ } finally {+ setImporting(false);+ }+ };++ const importLabels = useMemo(+ () => ({+ noProject: t("settings.importNoProject"),+ sources: {+ "claude-code": t("settings.importSourceClaudeCode"),+ opencode: t("settings.importSourceOpenCode"),+ codex: t("settings.importSourceCodex"),+ pi: t("settings.importSourcePi"),+ } as Record<ImportCandidate["source"], string>,+ }),+ [t],+ );++ const groups = useMemo(+ () => groupImportCandidates(candidates ?? [], groupBy, importLabels),+ [candidates, groupBy, importLabels],+ );++ const allKeys = useMemo(() => (candidates ?? []).map(keyOf), [candidates]);+ const allSelected = allKeys.length > 0 && allKeys.every((k) => selected.has(k));++ const toggleKeys = (keys: string[], on: boolean) => {+ setSelected((previous) => {+ const next = new Set(previous);+ for (const key of keys) {+ if (on) next.add(key);+ else next.delete(key);+ }+ return next;+ });+ };++ return (+ <div className="import-workbench">+ {candidates === null ? (+ <ImportIdle+ note={importLabels.sources && [+ importLabels.sources["claude-code"],+ importLabels.sources.opencode,+ importLabels.sources.codex,+ importLabels.sources.pi,+ ].join(" · ")}+ onScan={() => void scan()}+ scanning={scanning}+ />+ ) : (+ <>+ <ImportToolbar+ found={t("settings.importFound", { count: candidates.length })}+ selectedCount={selected.size}+ allSelected={allSelected}+ selectAllLabel={t("settings.importSelectAll")}+ onToggleAll={(on) => toggleKeys(allKeys, on)}+ scanning={scanning}+ importing={importing}+ onScan={() => void scan()}+ onImport={() => void runImport()}+ options={+ <ImportOption+ label={t("settings.importGroupBy")}+ value={groupBy}+ onChange={(id) => {+ setGroupBy(id as ImportGroupBy);+ disclosure.reset();+ }}+ options={[+ { id: "source", label: t("settings.importGroupBySource") },+ { id: "path", label: t("settings.importGroupByPath") },+ ]}+ />+ }+ />+ <ImportResults+ message={+ candidates.length === 0 ? t("settings.importNone") : undefined+ }+ >+ <div className="import-groups">+ {groups.map((group, groupIndex) => {+ const groupKeys = group.items.map(keyOf);+ const groupSelected = groupKeys.filter((k) => selected.has(k)).length;+ const bodyId = `import-session-group-${groupIndex}`;+ return (+ <ImportGroup+ key={group.id}+ bodyId={bodyId}+ name={group.name}+ path={group.projectPath}+ count={group.items.length}+ countLabel={t("settings.importSessionCount", {+ count: group.items.length,+ })}+ expanded={disclosure.isExpanded(group.id)}+ onToggle={() => disclosure.toggle(group.id)}+ selection={{+ label: t("settings.importSelectGroup", { name: group.name }),+ checked: groupSelected === groupKeys.length,+ indeterminate:+ groupSelected > 0 && groupSelected < groupKeys.length,+ onChange: (on) => toggleKeys(groupKeys, on),+ }}+ >+ {group.items.map((candidate) => {+ const key = keyOf(candidate);+ return (+ <ImportRow+ key={key}+ title={candidate.title}+ meta={`${+ candidate.messageCount === null+ ? t("settings.importMessagesUnknown")+ : t("settings.importMessages", {+ count: candidate.messageCount,+ })+ } · ${formatImportDate(+ candidate.updatedAt,+ i18n.resolvedLanguage || i18n.language,+ )}`}+ checked={selected.has(key)}+ onChange={(on) => setSelected((previous) => toggleKey(previous, key, on))}+ badge={+ <Badge tone="neutral">+ {importLabels.sources[candidate.source]}+ </Badge>+ }+ />+ );+ })}+ </ImportGroup>+ );+ })}+ </div>+ </ImportResults>+ </>+ )}+ </div>+ );+}++/* ---------------------------------------------------------------------------+ * Provider and model configuration+ * ------------------------------------------------------------------------- */++function hostOf(baseUrl: string | null): string {+ if (!baseUrl) return "";+ try {+ return new URL(baseUrl).host || baseUrl;+ } catch {+ return baseUrl.replace(/^https?:\/\//, "").split("/")[0] || baseUrl;+ }+}++export function ModelConfigImportPanel() {+ const { t } = useTranslation();+ const refreshProviders = useAppStore((s) => s.refreshProviders);+ const showToast = useAppStore((s) => s.showToast);+ const [candidates, setCandidates] = useState<ModelConfigImportCandidate[] | null>(+ null,+ );+ const [selected, setSelected] = useState<Set<string>>(new Set());+ const disclosure = useGroupDisclosure();+ const [scanning, setScanning] = useState(false);+ const [importing, setImporting] = useState(false);++ const keyOf = (candidate: ModelConfigImportCandidate) =>+ `${candidate.source}:${candidate.externalId}`;++ const scan = async () => {+ setScanning(true);+ try {+ const res = await api.scanImportModelConfigs();+ setCandidates(res.providers);+ setSelected(new Set());+ disclosure.reset();+ } catch (e) {+ showToast(e instanceof Error ? e.message : String(e), { variant: "error" });+ } finally {+ setScanning(false);+ }+ };++ const runImport = async () => {+ if (!candidates) return;+ const items = candidates.filter((candidate) => selected.has(keyOf(candidate)));+ if (items.length === 0) return;+ setImporting(true);+ try {+ const res = await api.runImportModelConfigs(items);+ await refreshProviders();+ showToast(+ t("settings.importResult", {+ imported: res.imported,+ skipped: res.skipped,+ failed: res.failed,+ }),+ { variant: res.failed > 0 ? "error" : "success" },+ );+ } catch (e) {+ showToast(e instanceof Error ? e.message : String(e), { variant: "error" });+ } finally {+ setImporting(false);+ }+ };++ const sourceLabels: Record<ModelConfigImportCandidate["source"], string> = useMemo(+ () => ({+ "claude-code": t("settings.importSourceClaudeCode"),+ opencode: t("settings.importSourceOpenCode"),+ codex: t("settings.importSourceCodex"),+ pi: t("settings.importSourcePi"),+ "cc-switch": t("settings.importSourceCcSwitch"),+ }),+ [t],+ );++ const groups = useMemo(() => {+ if (!candidates) return [];+ const grouped = new Map<+ ModelConfigImportCandidate["source"],+ ModelConfigImportCandidate[]+ >();+ for (const candidate of candidates) {+ const items = grouped.get(candidate.source) ?? [];+ items.push(candidate);+ grouped.set(candidate.source, items);+ }+ return [...grouped.entries()].map(([source, items]) => ({+ id: source,+ name: sourceLabels[source],+ items,+ }));+ }, [candidates, sourceLabels]);++ const allKeys = useMemo(() => (candidates ?? []).map(keyOf), [candidates]);+ const allSelected = allKeys.length > 0 && allKeys.every((k) => selected.has(k));++ const toggleKeys = (keys: string[], on: boolean) => {+ setSelected((previous) => {+ const next = new Set(previous);+ for (const key of keys) {+ if (on) next.add(key);+ else next.delete(key);+ }+ return next;+ });+ };++ return (+ <div className="import-workbench">+ {candidates === null ? (+ <ImportIdle+ description={t("settings.importModelsScanDesc")}+ onScan={() => void scan()}+ scanning={scanning}+ />+ ) : (+ <>+ <ImportToolbar+ found={t("settings.importModelsFound", { count: candidates.length })}+ selectedCount={selected.size}+ allSelected={allSelected}+ selectAllLabel={t("settings.importModelsSelectAll")}+ onToggleAll={(on) => toggleKeys(allKeys, on)}+ scanning={scanning}+ importing={importing}+ onScan={() => void scan()}+ onImport={() => void runImport()}+ />+ <ImportResults+ message={+ candidates.length === 0 ? t("settings.importModelsNone") : undefined+ }+ >+ <div className="import-groups">+ {groups.map((group, groupIndex) => {+ const groupKeys = group.items.map(keyOf);+ const groupSelected = groupKeys.filter((k) => selected.has(k)).length;+ const bodyId = `import-model-group-${groupIndex}`;+ return (+ <ImportGroup+ key={group.id}+ bodyId={bodyId}+ name={group.name}+ count={group.items.length}+ countLabel={t("settings.importModelsFound", {+ count: group.items.length,+ })}+ expanded={disclosure.isExpanded(group.id)}+ onToggle={() => disclosure.toggle(group.id)}+ selection={{+ label: t("settings.importModelsSelectGroup", { name: group.name }),+ checked: groupSelected === groupKeys.length,+ indeterminate:+ groupSelected > 0 && groupSelected < groupKeys.length,+ onChange: (on) => toggleKeys(groupKeys, on),+ }}+ >+ {group.items.map((candidate) => {+ const key = keyOf(candidate);+ const host = hostOf(candidate.baseUrl);+ return (+ <ImportRow+ key={key}+ title={candidate.name}+ meta={`${t("settings.importModelsCount", {+ count: candidate.modelIds.length,+ })}${host ? ` · ${host}` : ""}`}+ checked={selected.has(key)}+ onChange={(on) => setSelected((previous) => toggleKey(previous, key, on))}+ badge={+ <Badge tone={candidate.hasSecret ? "success" : "warning"}>+ {candidate.hasSecret+ ? t("settings.importModelsHasKey")+ : t("settings.importModelsNoKey")}+ </Badge>+ }+ />+ );+ })}+ </ImportGroup>+ );+ })}+ </div>+ </ImportResults>+ </>+ )}+ </div>+ );+}++/* ---------------------------------------------------------------------------+ * Skills and MCP servers scanned from the other agent tools on this machine+ * ------------------------------------------------------------------------- */++const SKILL_SOURCE_KEY: Record<ExternalSkillSourceKind, string> = {+ "claude-user": "settings.importAgentScanSourceClaudeUser",+ "claude-project": "settings.importAgentScanSourceClaudeProject",+ "pi-user": "settings.importAgentScanSourcePiUser",+ "pi-project": "settings.importAgentScanSourcePiProject",+};++const MCP_SOURCE_KEY: Record<ExternalMcpSourceKind, string> = {+ "claude-desktop": "settings.importAgentScanSourceClaudeDesktop",+ "claude-code": "settings.importAgentScanSourceClaudeCode",+ "cursor-global": "settings.importAgentScanSourceCursorGlobal",+ "cursor-project": "settings.importAgentScanSourceCursorProject",+ codex: "settings.importAgentScanSourceCodex",+ opencode: "settings.importAgentScanSourceOpenCode",+ "chatgpt-desktop": "settings.importAgentScanSourceChatgpt",+};++function groupBySource<C extends { source: string }>(+ candidates: C[],+): Array<{ id: string; items: C[] }> {+ const map = new Map<string, C[]>();+ for (const candidate of candidates) {+ const bucket = map.get(candidate.source);+ if (bucket) bucket.push(candidate);+ else map.set(candidate.source, [candidate]);+ }+ return Array.from(map.entries()).map(([id, items]) => ({ id, items }));+}++export function SkillsScanImportPanel() {+ const { t } = useTranslation();+ const showToast = useAppStore((s) => s.showToast);+ const [result, setResult] = useState<ExternalSkillScanResult | null>(null);+ const [selected, setSelected] = useState<Set<string>>(new Set());+ const disclosure = useGroupDisclosure();+ const [mode, setMode] = useState<"copy" | "link">("copy");+ const [scanning, setScanning] = useState(false);+ const [importing, setImporting] = useState(false);++ const keyOf = (candidate: ExternalSkillCandidate) =>+ `${candidate.source}:${candidate.sourcePath}`;++ const scan = async () => {+ setScanning(true);+ try {+ const res = await api.scanExternalSkills();+ setResult(res);+ setSelected(new Set());+ disclosure.reset();+ } catch (e) {+ showToast(e instanceof Error ? e.message : String(e), { variant: "error" });+ } finally {+ setScanning(false);+ }+ };++ const runImport = async () => {+ if (!result) return;+ const items: ExternalSkillImportItem[] = result.candidates+ .filter((candidate) => selected.has(keyOf(candidate)))+ .map((candidate) => ({+ source: candidate.source,+ sourcePath: candidate.sourcePath,+ shape: candidate.shape,+ rootDir: candidate.rootDir,+ id: candidate.id,+ name: candidate.name,+ description: candidate.description,+ }));+ if (items.length === 0) return;+ setImporting(true);+ try {+ const res = await api.runExternalSkillsImport({+ level: "global",+ mode,+ items,+ });+ showToast(+ t("settings.importAgentScanResult", {+ imported: res.imported.length,+ skipped: res.skipped.length,+ failed: res.failed.length,+ }),+ { variant: res.failed.length > 0 ? "error" : "success" },+ );+ // Refresh the scan so already-imported rows disappear next round.+ await scan();+ } catch (e) {+ showToast(e instanceof Error ? e.message : String(e), { variant: "error" });+ } finally {+ setImporting(false);+ }+ };++ const groups = useMemo(() => groupBySource(result?.candidates ?? []), [result]);+ const allKeys = useMemo(+ () => (result?.candidates ?? []).map(keyOf),+ [result],+ );+ const allSelected = allKeys.length > 0 && allKeys.every((k) => selected.has(k));++ return (+ <div className="import-workbench">+ {result === null ? (+ <ImportIdle+ description={t("settings.importAgentSkillsDesc")}+ onScan={() => void scan()}+ scanning={scanning}+ />+ ) : (+ <>+ <ImportToolbar+ found={t("settings.importAgentScanFoundSkills", {+ count: result.candidates.length,+ })}+ selectedCount={selected.size}+ allSelected={allSelected}+ selectAllLabel={t("settings.importSelectAll")}+ onToggleAll={(on) => setSelected(on ? new Set(allKeys) : new Set())}+ scanning={scanning}+ importing={importing}+ onScan={() => void scan()}+ onImport={() => void runImport()}+ options={+ <ImportOption+ label={t("settings.importAgentScanMode")}+ value={mode}+ onChange={(id) => setMode(id as "copy" | "link")}+ options={[+ { id: "copy", label: t("settings.importAgentScanModeCopy") },+ { id: "link", label: t("settings.importAgentScanModeLink") },+ ]}+ />+ }+ />+ <p className="import-hint">{t("settings.importAgentScanModeHint")}</p>+ <ImportResults+ message={+ result.candidates.length === 0+ ? t("settings.importAgentScanNone")+ : undefined+ }+ >+ <div className="import-groups">+ {groups.map((group, groupIndex) => (+ <ImportGroup+ key={group.id}+ bodyId={`import-skill-group-${groupIndex}`}+ name={t(+ SKILL_SOURCE_KEY[group.id as ExternalSkillSourceKind] ??+ "settings.importSourcePi",+ )}+ count={group.items.length}+ countLabel={t("settings.importAgentScanFoundSkills", {+ count: group.items.length,+ })}+ expanded={disclosure.isExpanded(group.id)}+ onToggle={() => disclosure.toggle(group.id)}+ >+ {group.items.map((candidate) => {+ const key = keyOf(candidate);+ return (+ <ImportRow+ key={key}+ title={candidate.name || candidate.id}+ meta={candidate.description || candidate.sourcePath}+ checked={selected.has(key)}+ onChange={(on) => setSelected((previous) => toggleKey(previous, key, on))}+ badge={+ <Badge tone="neutral">+ {candidate.shape === "dir"+ ? t("settings.importAgentScanShapeDir")+ : t("settings.importAgentScanShapeFile")}+ </Badge>+ }+ />+ );+ })}+ </ImportGroup>+ ))}+ </div>+ </ImportResults>+ </>+ )}+ </div>+ );+}++export function McpScanImportPanel() {+ const { t } = useTranslation();+ const showToast = useAppStore((s) => s.showToast);+ const [result, setResult] = useState<ExternalMcpScanResult | null>(null);+ const [selected, setSelected] = useState<Set<string>>(new Set());+ const disclosure = useGroupDisclosure();+ const [scanning, setScanning] = useState(false);+ const [importing, setImporting] = useState(false);++ const keyOf = (candidate: ExternalMcpCandidate) =>+ `${candidate.source}:${candidate.id}`;++ const scan = async () => {+ setScanning(true);+ try {+ const res = await api.scanExternalMcp();+ setResult(res);+ setSelected(new Set());+ disclosure.reset();+ } catch (e) {+ showToast(e instanceof Error ? e.message : String(e), { variant: "error" });+ } finally {+ setScanning(false);+ }+ };++ const runImport = async () => {+ if (!result) return;+ const items: ExternalMcpImportItem[] = result.candidates+ .filter((candidate) => selected.has(keyOf(candidate)))+ .map((candidate) => ({+ source: candidate.source,+ sourcePath: candidate.sourcePath,+ id: candidate.id,+ rawKey: candidate.rawKey,+ label: candidate.label,+ description: candidate.description,+ transport: candidate.transport,+ command: candidate.command,+ args: candidate.args,+ env: candidate.env,+ url: candidate.url,+ headers: candidate.headers,+ disabled: candidate.disabled,+ }));+ if (items.length === 0) return;+ setImporting(true);+ try {+ const res = await api.runExternalMcpImport({ items });+ showToast(+ t("settings.importAgentScanResult", {+ imported: res.imported.length,+ skipped: res.skipped.length,+ failed: res.failed.length,+ }),+ { variant: res.failed.length > 0 ? "error" : "success" },+ );+ await scan();+ } catch (e) {+ showToast(e instanceof Error ? e.message : String(e), { variant: "error" });+ } finally {+ setImporting(false);+ }+ };++ const groups = useMemo(() => groupBySource(result?.candidates ?? []), [result]);+ const allKeys = useMemo(+ () => (result?.candidates ?? []).map(keyOf),+ [result],+ );+ const allSelected = allKeys.length > 0 && allKeys.every((k) => selected.has(k));++ return (+ <div className="import-workbench">+ {result === null ? (+ <ImportIdle+ description={t("settings.importAgentMcpDesc")}+ onScan={() => void scan()}+ scanning={scanning}+ />+ ) : (+ <>+ <ImportToolbar+ found={t("settings.importAgentScanFoundMcp", {+ count: result.candidates.length,+ })}+ selectedCount={selected.size}+ allSelected={allSelected}+ selectAllLabel={t("settings.importSelectAll")}+ onToggleAll={(on) => setSelected(on ? new Set(allKeys) : new Set())}+ scanning={scanning}+ importing={importing}+ onScan={() => void scan()}+ onImport={() => void runImport()}+ />+ <ImportResults+ message={+ result.candidates.length === 0+ ? t("settings.importAgentScanNone")+ : undefined+ }+ >+ <div className="import-groups">+ {groups.map((group, groupIndex) => (+ <ImportGroup+ key={group.id}+ bodyId={`import-mcp-group-${groupIndex}`}+ name={t(+ MCP_SOURCE_KEY[group.id as ExternalMcpSourceKind] ??+ "settings.importSourcePi",+ )}+ count={group.items.length}+ countLabel={t("settings.importAgentScanFoundMcp", {+ count: group.items.length,+ })}+ expanded={disclosure.isExpanded(group.id)}+ onToggle={() => disclosure.toggle(group.id)}+ >+ {group.items.map((candidate) => {+ const key = keyOf(candidate);+ return (+ <ImportRow+ key={key}+ title={candidate.label || candidate.id}+ meta={+ candidate.description ||+ candidate.command ||+ candidate.url ||+ candidate.sourcePath+ }+ checked={selected.has(key)}+ onChange={(on) => setSelected((previous) => toggleKey(previous, key, on))}+ badge={+ <Badge tone="neutral">+ {candidate.transport === "http"+ ? t("settings.importAgentScanTransportHttp")+ : t("settings.importAgentScanTransportStdio")}+ </Badge>+ }+ />+ );+ })}+ </ImportGroup>+ ))}+ </div>+ </ImportResults>+ </>+ )}+ </div>+ );+}diff --git a/apps/desktop/src/styles/sessions.css b/apps/desktop/src/styles/sessions.cssindex 803489ba1..ef248a58e 100644--- a/apps/desktop/src/styles/sessions.css+++ b/apps/desktop/src/styles/sessions.css@@ -5,64 +5,162 @@sidebar-threads.css.*/-/* Session import (settings) */+/* -------------------------------------------------------------------------+ * Settings > Import. One workbench per kind — sessions, model configuration,+ * skills, MCP servers: a segmented kind switcher, one toolbar (select-all with+ * both counts, kind options, rescan, import selected), then one list panel+ * whose group headers are quiet label lines and whose rows are individual+ * tiles. The rhythm matches the agent capability destinations.+ */++.import-page {+ display: flex;+ min-width: 0;+ flex-direction: column;+ gap: 14px;+}++/*+ Kind switcher. The shared `.settings-segment` already carries both theme+ pairs and the raised active pill; only the page-scale pills are local.+ Compound selectors on purpose: providers.css defines `.settings-segment-item`+ further down the cascade, so a bare `.import-segment-btn` would lose to it.+*/+.settings-segment.import-segment {+ align-self: flex-start;+ max-width: 100%;+ flex-wrap: wrap;+}++.settings-segment-item.import-segment-btn {+ padding: 5px 12px;+ font-size: var(--text-sm);+ font-weight: var(--font-weight-medium);+ white-space: nowrap;+}++/* Tab panels stay mounted so a scan result survives a switch. */+.import-view {+ display: flex;+ min-width: 0;+ flex-direction: column;+}++.import-view[hidden] {+ display: none;+}++.import-workbench {+ display: flex;+ min-width: 0;+ flex-direction: column;+ gap: 10px;+}++/* One action row per kind: both counts on the left, options and actions right. */.import-toolbar {display: flex;+ min-width: 0;flex-wrap: wrap;align-items: center;- justify-content: space-between;- gap: 12px;- padding: 10px 14px 6px;+ gap: 8px 12px;+ padding: 0 1px;}.import-select-all {- display: flex;+ display: inline-flex;+ min-width: 0;align-items: center;gap: 8px;cursor: pointer;+}++.import-count {+ display: inline-flex;+ min-width: 0;+ align-items: baseline;+ gap: 8px;color: var(--ds-text-primary);- font-size: var(--text-md);+ font-size: var(--text-sm);+}++.import-count-selected {+ color: var(--ds-text-muted);+ font-variant-numeric: tabular-nums;}-.import-toolbar-actions,-.import-group-by {+.import-count-selected::before {+ color: var(--ds-text-faint);+ content: "· ";+}++.import-toolbar-actions {display: flex;+ flex: 0 0 auto;align-items: center;+ gap: 8px;+ margin-left: auto;}-.import-toolbar-actions {- gap: 10px;+/*+ The shared `.btn` runs a step larger than the selects beside it, so give it+ toolbar geometry here rather than resizing every other page. `min-height`+ instead of `height` so a wrapped label grows the button instead of spilling+ out of it.+*/+.import-toolbar-actions > .btn {+ min-height: 28px;+ padding: 4px 11px;+ font-size: var(--text-sm);}-.import-group-by {+.import-option {+ display: inline-flex;+ min-width: 0;+ align-items: center;gap: 7px;+}++.import-option-label {color: var(--ds-text-muted);font-size: var(--text-sm);white-space: nowrap;}-.import-group-select .settings-menu-select-trigger {+.import-option-select .settings-menu-select-trigger {height: 28px;}+/* Import mode leaves the one-line toolbar alone but stays readable. */+.import-hint {+ margin: -4px 1px 0;+ max-width: 92ch;+ color: var(--ds-text-muted);+ font-size: var(--text-2xs);+ line-height: var(--leading-body);+}++/* D297: the list dissolves into the page — each row is its own tile. */+.settings-panel.import-panel {+ gap: 6px;+ background: transparent;+ overflow: visible;+}+.import-groups {display: flex;+ min-width: 0;flex-direction: column;+ gap: 12px;}-/* Groups are separated by space; each header is a soft band, not a rule. */-.import-group + .import-group {- margin-top: 6px;-}-+/* Quiet label line above its rows: which source, where it lives, how many. */.import-group-header {display: flex;+ min-width: 0;align-items: center;gap: 8px;- margin: 0 6px;- border-radius: var(--radius-sm);- padding: 8px 8px;- background: var(--ds-tile);+ padding: 0 10px 6px;}.import-group-toggle {@@ -79,6 +177,11 @@text-align: left;}+.import-group-toggle:focus-visible {+ outline: none;+ box-shadow: 0 0 0 2px color-mix(in oklab, var(--ds-accent) 22%, transparent);+}+.import-group-chevron {display: inline-flex;flex-shrink: 0;@@ -92,36 +195,53 @@}.import-group-name {- flex-shrink: 0;- color: var(--ds-text-primary);- font-size: var(--text-md-plus);+ flex: 0 0 auto;+ color: var(--ds-text-secondary);+ font-size: var(--text-2xs);font-weight: var(--font-weight-strong);+ letter-spacing: var(--tracking-wide);+ text-transform: uppercase;+ white-space: nowrap;}.import-group-path {min-width: 0;+ flex: 1;overflow: hidden;- text-overflow: ellipsis;- white-space: nowrap;color: var(--ds-text-muted);font-family: var(--font-mono);- font-size: var(--text-xs-plus);+ font-size: var(--text-2xs);+ text-overflow: ellipsis;+ white-space: nowrap;}.import-group-count {- margin-left: auto;- flex-shrink: 0;+ flex: 0 0 auto;+ border-radius: var(--radius-full);+ background: color-mix(in oklab, var(--ds-text-primary) 8%, transparent);+ padding: 1px 7px;color: var(--ds-text-muted);- font-size: var(--text-sm);+ font-size: var(--text-3xs);+ font-variant-numeric: tabular-nums;+ line-height: var(--leading-normal);+}++.import-group-body {+ display: flex;+ min-width: 0;+ flex-direction: column;+ gap: 4px;}+/* One candidate: checkbox, identity, badge. */.import-row {display: flex;+ min-width: 0;align-items: center;gap: 10px;- margin: 0 6px;- border-radius: var(--radius-sm);- padding: 8px 8px 8px 28px;+ border-radius: var(--radius-md);+ background: var(--ds-tile);+ padding: 6px 10px;cursor: pointer;transition: background var(--motion-duration-fast) var(--motion-ease-out);}@@ -130,6 +250,25 @@background: var(--ds-tile-hover);}+/* Selection is tonal, never a color: the checkbox already says which rows. */+.import-row:has(input:checked) {+ background: var(--ds-tile-deep);+}++.import-row:has(input:focus-visible),+.import-group-header > input:focus-visible {+ outline: none;+ box-shadow: 0 0 0 2px color-mix(in oklab, var(--ds-accent) 22%, transparent);+}++.import-row > input[type="checkbox"],+.import-group-header > input[type="checkbox"] {+ width: 14px;+ height: 14px;+ flex: 0 0 auto;+ margin: 0;+}+.import-row-main {display: flex;min-width: 0;@@ -140,15 +279,62 @@.import-row-title {overflow: hidden;+ color: var(--ds-text-primary);+ font-size: var(--text-md);+ font-weight: var(--font-weight-medium);+ line-height: var(--leading-compact);text-overflow: ellipsis;white-space: nowrap;- color: var(--ds-text-primary);- font-size: var(--text-md-plus);}.import-row-meta {+ overflow: hidden;color: var(--ds-text-muted);- font-size: var(--text-xs-plus);+ font-size: var(--text-2xs);+ line-height: var(--leading-normal);+ text-overflow: ellipsis;+ white-space: nowrap;+}++/* Pre-scan state: what the scan reads, then the action that starts it. */+.import-idle {+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: 10px;+ border-radius: var(--radius-lg);+ background: var(--ds-tile);+ padding: 26px 20px;+ text-align: center;+}++.import-idle-glyph {+ display: inline-flex;+ color: var(--ds-text-faint);+}++.import-idle-copy {+ margin: 0;+ max-width: 62ch;+ color: var(--ds-text-secondary);+ font-size: var(--text-sm);+ line-height: var(--leading-body);+}++.import-idle-note {+ margin: 0;+ color: var(--ds-text-faint);+ font-size: var(--text-2xs);+}++/* A scan that found nothing keeps its action in the toolbar above. */+.import-empty {+ margin: 0;+ border-radius: var(--radius-lg);+ background: var(--ds-tile);+ padding: 16px 14px;+ color: var(--ds-text-muted);+ font-size: var(--text-sm);}/* Sidebar session management controls */@@ -495,7 +681,9 @@/* CJK has no case and wide tracking splits glyphs unnaturally. */:lang(zh-CN) .sidebar-list-label,:lang(zh-CN) .dest-section-label,-:lang(zh-CN) .shortcut-group-label {+:lang(zh-CN) .shortcut-group-label,+:lang(zh-CN) .import-group-name,+:lang(zh-TW) .import-group-name {letter-spacing: var(--tracking-normal);text-transform: none;}diff --git a/apps/desktop/test/project-import-archive.test.mjs b/apps/desktop/test/project-import-archive.test.mjsindex d5e3931e8..d2ecd8a63 100644--- a/apps/desktop/test/project-import-archive.test.mjs+++ b/apps/desktop/test/project-import-archive.test.mjs@@ -7,7 +7,7 @@ const [appSource, projectSlice, sessionSlice, importSource] = await Promise.all(readAppSource(),readStoreModule("slices/project-slice.ts"),readStoreModule("slices/session-slice.ts"),- readFile(new URL("../src/features/settings/agent-sections.tsx", import.meta.url), "utf8"),+ readFile(new URL("../src/features/settings/import-page.tsx", import.meta.url), "utf8"),]);test("session imports restore archived projects only for newly added sessions", () => {diff --git a/apps/desktop/test/settings-import-page.test.mjs b/apps/desktop/test/settings-import-page.test.mjsnew file mode 100644index 000000000..d5a98b2cd--- /dev/null+++ b/apps/desktop/test/settings-import-page.test.mjs@@ -0,0 +1,116 @@+/**+ * Settings ▸ Import page contract.+ *+ * Source-oriented like the neighboring settings suites: the import destination+ * is one workbench per kind (sessions, model configuration, skills, MCP), and+ * the regressions this guards are structural — four stacked scan cards coming+ * back, a hidden tab panel that the author's own `display: flex` keeps laid+ * out, rows losing their tile/typography tokens, or a kind losing the scan that+ * belongs to it.+ */+import { readSettingsSourceSync } from "./helpers/source-contracts.mjs";+import { loadStylesSync } from "./helpers/styles.mjs";+import assert from "node:assert/strict";+import test from "node:test";++const settings = readSettingsSourceSync();+const styles = loadStylesSync();++const start = settings.indexOf(" * Settings ▸ Import.");+assert.ok(start > 0, "import page module missing from the settings domain");+const end = settings.indexOf("\n/* features/settings/", start);+const page = settings.slice(start, end === -1 ? undefined : end);++function cssRule(selector) {+ const from = styles.indexOf(`\n${selector} {`);+ assert.ok(from >= 0, `${selector} rule missing`);+ return styles.slice(from, styles.indexOf("}", from));+}++test("import is one workbench per kind instead of four stacked scan cards", () => {+ // One tab strip owns the four kinds; each kind gets one panel behind it.+ assert.match(page, /role="tablist"/);+ assert.match(page, /aria-controls={`import-panel-\$\{entry\.id\}`}/);+ assert.match(page, /aria-labelledby={`import-tab-\$\{entry\.id\}`}/);++ // One toolbar and one idle state per kind — not per section or per step.+ assert.equal((page.match(/<ImportToolbar/g) ?? []).length, 4);+ assert.equal((page.match(/<ImportIdle/g) ?? []).length, 4);++ // The retired anatomy: a lone Scan card per kind, a bare empty div, a tinted+ // group strip, and a second copy of the settings row scaffold.+ assert.doesNotMatch(page, /settings-empty/);+ assert.doesNotMatch(page, /<SettingsCard/);+ assert.doesNotMatch(page, /import-group-title/);+ assert.doesNotMatch(page, /settings-description/);+});++test("every kind keeps its own scan and its state across a tab switch", () => {+ for (const call of [+ "scanImportSessions",+ "scanImportModelConfigs",+ "scanExternalSkills",+ "scanExternalMcp",+ ]) {+ assert.match(page, new RegExp(`api\\.${call}\\(`), `${call} missing`);+ }+ // No kind may start another kind's scan.+ assert.match(page, /api\.scanImportSessions\(\)/);+ assert.match(page, /api\.scanExternalMcp\(\)/);++ // Panels stay mounted and only `hidden` takes the inactive one out of view.+ assert.match(page, /hidden={kind !== entry\.id}/);+ assert.match(cssRule(".import-view[hidden]"), /display:\s*none/);+});++test("import rows are tiles with token typography and quiet group labels", () => {+ assert.match(cssRule(".import-row"), /background:\s*var\(--ds-tile\)/);+ assert.match(cssRule(".import-row:hover"), /var\(--ds-tile-hover\)/);+ assert.match(+ cssRule(".import-row:has(input:checked)"),+ /var\(--ds-tile-deep\)/,+ "selection must stay tonal",+ );+ assert.match(cssRule(".import-row-title"), /font-size:\s*var\(--text-md\)/);+ assert.match(cssRule(".import-row-meta"), /font-size:\s*var\(--text-2xs\)/);++ // The group header is a quiet label line, not a tinted 13.5px band.+ const label = cssRule(".import-group-name");+ assert.match(label, /font-size:\s*var\(--text-2xs\)/);+ assert.match(label, /text-transform:\s*uppercase/);+ assert.doesNotMatch(cssRule(".import-group-header"), /background:/);++ // Latin micro-style relaxes where CJK has no case and wide tracking.+ assert.match(styles, /:lang\(zh-CN\) \.import-group-name/);+ assert.match(styles, /:lang\(zh-TW\) \.import-group-name/);++ // The list dissolves so each row is its own tile (D297).+ const panel = cssRule(".settings-panel.import-panel");+ assert.match(panel, /background:\s*transparent/);+ assert.match(cssRule(".import-idle"), /background:\s*var\(--ds-tile\)/);+ assert.match(cssRule(".import-empty"), /background:\s*var\(--ds-tile\)/);+});++test("the toolbar is one dense row: counts left, options and actions right", () => {+ assert.match(page, /className="import-select-all"/);+ assert.match(page, /className="import-count"/);+ assert.match(page, /import-count-selected/);+ assert.match(cssRule(".import-toolbar-actions"), /margin-left:\s*auto/);+ assert.match(cssRule(".import-toolbar-actions > .btn"), /min-height:\s*28px/);+ assert.match(cssRule(".import-option-select .settings-menu-select-trigger"), /height:\s*28px/);+ // The kind options stay real menu selects, never platform-drawn selectors.+ assert.match(page, /<SettingsMenuSelect/);+ assert.doesNotMatch(page, /<select/);+});++test("every kind's group label line discloses its own rows", () => {+ // One shared hook and four kinds: a group header may not become a label with+ // no disclosure, and no kind may keep a private copy of the state.+ assert.equal((page.match(/useGroupDisclosure\(\)/g) ?? []).length, 5);+ assert.equal(+ (page.match(/onToggle=\{\(\) => disclosure\.toggle\(/g) ?? []).length,+ 4,+ );+ assert.doesNotMatch(page, /onToggle=\{\(\) => undefined\}/);+ assert.doesNotMatch(page, /collapsedGroups/);+});diff --git a/docs/spec/04-ux/06-settings-ia.md b/docs/spec/04-ux/06-settings-ia.mdindex db9787cd0..450c6ad6f 100644--- a/docs/spec/04-ux/06-settings-ia.md+++ b/docs/spec/04-ux/06-settings-ia.md@@ -538,12 +538,13 @@ system while preserving their different data ownership:menu and are resolved after the global layer.### Import-- Scan supported local agent stores for **sessions** and **model configuration**- through two independent cards on the same destination. Neither scan runs- automatically (D007 / D342).+- Scan supported local agent stores for **sessions**, **model configuration**,+ **skills**, and **MCP servers** through one workbench per kind behind the+ page's kind switcher. Every kind keeps its own explicit scan: none of them+ runs automatically, and switching kinds never starts one (D007 / D342).- Sessions: review candidates through `SessionImportPanel`. Source andproject-path grouping behavior follows- [08-component-spec §18](08-component-spec.md#18-sessionimportpanel).+ [08-component-spec §18](08-component-spec.md#18-import-destination).The Group-by control is the same in-app menu select as the Appearance andPermissions pickers, not a platform-drawn `<select>`.- Model configuration: review provider drafts through@@ -556,6 +557,9 @@ system while preserving their different data ownership:(same normalized base URL, API style, and credential) is skipped; profileswith different credentials at one endpoint remain separate. If the app hasno default model yet, the first newly created provider becomes the default.+- Skills and MCP servers reuse the agent capability scanners and their source+ labels. The skills kind carries the import mode (copy or symlink); the MCP+ kind writes into the same MCP list the MCP destination manages.### Project archive- Reuses the durable Projects index as a settings-scale management surfacediff --git a/docs/spec/04-ux/07-ui-design-system.md b/docs/spec/04-ux/07-ui-design-system.mdindex 1ac641d1c..e3e8a1600 100644--- a/docs/spec/04-ux/07-ui-design-system.md+++ b/docs/spec/04-ux/07-ui-design-system.md@@ -1318,4 +1318,11 @@ Full component contract and usage rules: [08-component-spec.md §17](08-componenper D092, the content cards fill the pane width available from the currentwindow instead of retaining D070's fixed 720px cap — the earlier in-shell200px rail and broad grouped directory are superseded+- **Import**: four kinds (sessions / models / skills / MCP) behind one+ page-scale segmented switcher, composed like the agent capability pages: a+ quiet pre-scan next-action state per kind, one toolbar per kind (select-all+ with both counts, the kind's own option, re-scan, import selected), and one+ list whose group headers are quiet label lines and whose candidates are+ individual tiles. No per-kind scan card, no tinted group band, no second+ copy of the settings row scaffold- Light destination cards use white elevated plates (not flat gray fills)diff --git a/docs/spec/04-ux/08-component-spec.md b/docs/spec/04-ux/08-component-spec.mdindex 9b2d6538b..acd30986d 100644--- a/docs/spec/04-ux/08-component-spec.md+++ b/docs/spec/04-ux/08-component-spec.md@@ -3206,34 +3206,54 @@ dismissToast(id: number); // ToastHost internal / tests----## 18. SessionImportPanel+## 18. Import destination### 18.1 Purpose-Scan supported local agent stores, review discovered sessions in manageable-groups, select candidates, and start an explicit import.+Scan supported local agent stores for the four things this machine can hand+over — sessions, provider/model configuration, skills, and MCP servers — then+review the candidates, select them, and start an explicit import.### 18.2 Anatomy+One workbench per kind behind a segmented kind switcher; every kind owns its+own scan, selection, and import action.+```text-[Found N sessions] [Group by: Source ▾] [Import selected (N)]-──────────────────────────────────────────────────────────────────-[ ] [›] Claude Code N sessions-[ ] [›] Codex N sessions+[ Sessions | Models | Skills | MCP ] ← kind switcher+[ ] Found 12 · 6 selected Group by: Source ▾ [Scan] [Import selected (6)]+───────────────────────────────────────────────────────────────────────────+CLAUDE CODE ~/code/pi 4+[ ] Refactor the importer 12 messages · Jan 5, 2026 [Claude Code]```-- The grouping control supports **Project path** and **Source**.-- Source is the default grouping.-- In project-path mode, exact paths remain visible in group headers.-- Sessions without a project path appear in a final **No project** group.-- Each group header includes group selection, disclosure, label, and count.-- Import source names, grouping controls, counts, results, and accessible names- come from the shared i18n catalog. Candidate dates use the active app locale.+- The switcher reuses the labels the sidebar and the settings rail already ship+ (`nav.sessions`, `settings.nav.models`, `settings.nav.skills`,+ `settings.nav.mcp`), so the page adds no catalog entries of its own.+- Each kind carries its own toolbar: the select-all checkbox with both the+ "found" sentence and the selected count, the kind's own option (session+ grouping, skills import mode), re-scan, and Import selected.+- Before a kind's first scan its panel shows a quiet next-action state: what the+ scan reads plus the Scan action. Switching tabs never starts a scan+ (D007 / D342).+- Group headers are quiet label lines — source or project name, the resolved+ path in mono, and a count pill — not tinted bands; the candidates below them+ are individual tiles.+- The grouping control supports **Project path** and **Source**. Source is the+ default. In project-path mode, exact paths remain visible in group headers,+ and sessions without a project path appear in a final **No project** group.+- Import source names, grouping and mode controls, counts, results, and+ accessible names come from the shared i18n catalog. Candidate dates use the+ active app locale.### 18.3 States and interactions- A successful scan replaces the prior candidate set, clears selection, and- leaves every group collapsed.+ shows every group expanded: the found candidates are the answer to the scan,+ so they are not hidden behind a second click.+- Every kind scans on its own: a session scan never starts a model-config,+ skills, or MCP scan, and switching tabs preserves the result and the+ selection of the kind left behind (inactive panels stay mounted and hidden).- A successful import creates or reuses one durable Projects-index entry foreach distinct non-empty project path and refreshes sessions/projects.- When a successful core or plugin import adds a project-bound session under an@@ -3245,20 +3265,29 @@ groups, select candidates, and start an explicit import.sessions. Import never creates a physical filesystem directory.- Re-importing an existing source session skips it without duplicating itsproject entry.-- Changing the grouping mode preserves candidate selection but collapses every- newly formed group.+- Changing the grouping mode preserves candidate selection and shows every+ newly formed group expanded.- Expanding or collapsing one group does not affect the others.- Group and global checkboxes support checked, unchecked, and indeterminate- selection states as applicable.+ selection states; the global checkbox reports a partial selection as+ indeterminate.- Candidates inside each group and groups themselves are ordered newest first;the path-less group remains last in project-path mode.### 18.4 Accessibility+- The kind switcher is a `tablist` of `tab` controls, each carrying+ `aria-selected` and `aria-controls` that names its panel. Every panel is a+ `tabpanel` labelled by its tab, and an inactive panel is `hidden` rather than+ visually covered.- Each disclosure button exposes `aria-expanded` and references its body with`aria-controls`.-- Global and group checkboxes have localized accessible names.-- The grouping selector has a visible label and is keyboard-operable.+- Global and group checkboxes have localized accessible names and carry the+ indeterminate state.+- The grouping and import-mode selectors are the shared in-app menu selects+ with visible labels and keyboard operation, never a platform-drawn+ `<select>`.+- Group count pills carry the localized count sentence as their title.- Projects-row disclosure and action-menu buttons expose localized,project-specific accessible names.@@ -3268,17 +3297,17 @@ Scan the same local agent stores for provider and model settings, reviewcandidates grouped by source, select them, and start an explicit import.```text-[Found N providers] [Import selected (N)]-──────────────────────────────────────────────────────────────────-[ ] [›] Claude Code N providers-[ ] [›] OpenCode N providers-[ ] [›] CC Switch N providers+[ ] Found 3 · 1 selected [Scan] [Import selected (1)]+───────────────────────────────────────────────────────────────────────────+CLAUDE CODE 1+[ ] acme-gateway 4 models · api.acme.dev [API key]```-- The card is independent of session import: its own Scan, selection, and- Import selected action. A session scan never starts a model-config scan.+- The kind is independent of session import: its own scan, selection, and+ Import selected action. A session scan never starts a model-config scan, and+ the two are shown one at a time behind the switcher.- Source grouping is the only grouping. A successful scan replaces the prior- candidate set, clears selection, and leaves every group collapsed.+ candidate set, clears selection, and shows every group expanded.- Each row shows the provider name, model count, host, an API key / No APIkey badge, and the source. The raw secret never reaches the renderer.- Import creates one `providers.create` row per selected candidate. An@@ -3290,7 +3319,6 @@ candidates grouped by source, select them, and start an explicit import.a different credential remains visible.- If `settings.defaultProviderId` is empty after a successful create, thefirst new provider becomes the global default.----## 19. ProviderStudio (Settings → Agent)diff --git a/docs/zh-CN/spec/04-ux/06-settings-ia.md b/docs/zh-CN/spec/04-ux/06-settings-ia.mdindex dd72fc4b8..05dd4d951 100644--- a/docs/zh-CN/spec/04-ux/06-settings-ia.md+++ b/docs/zh-CN/spec/04-ux/06-settings-ia.md@@ -229,12 +229,14 @@ Token 用量**不是设置目的地**(D335 / ADR 0173)。已完成回合历菜单并在全局层之后解决。### 导入-- 扫描支持的本地智能体存储中的**会话**和**模型配置**,同一目的地两个独立卡片。扫描都不会自动运行(D007 / D342)。-- 会话:通过 `SessionImportPanel` 审核候选人。来源与项目路径分组见- [08-组件规范 §18](/zh-CN/spec/04-ux/08-component-spec#_18-sessionimportpanel)+- 通过页面自身的类型切换器之后每个类型一个工作台,扫描受支持的本地代理存储中的**会话**、**模型配置**、**技能**和 **MCP 服务器**。每个类型都保留各自的显式扫描:它们都不会自动运行,切换类型也绝不会启动扫描(D007 / D342)。+- 会话:通过 `SessionImportPanel` 审核候选项。来源与项目路径分组行为见+ [08-组件规范 §18](/zh-CN/spec/04-ux/08-component-spec#18-导入目的地)。+ Group-by 控件与外观和权限选择器一样,是同一个应用内菜单选择器,而不是平台绘制的 `<select>`。- 模型配置:通过 `ModelConfigImportPanel` 审核提供商草稿- ([08-组件规范 §18.5](/zh-CN/spec/04-ux/08-component-spec#_18-5-modelconfigimportpanel))。- 配置里保存的 API 密钥写入宿主密钥库;订阅/OAuth 登录不复制。CC Switch(`~/.cc-switch`)作为独立来源扫描已保存的配置档案,不只是当前生效的 live 文件。等价提供商(规范化 base URL + API 风格 + 相同凭据)再次导入时跳过;同一端点的不同凭据保持为独立提供商。若应用尚无默认模型,则将本次新建的第一个提供商设为默认。+ ([08-组件规范 §18.5](/zh-CN/spec/04-ux/08-component-spec#185-modelconfigimportpanel))。+ 这些配置里保存的 API 密钥会复制到宿主密钥库;订阅/OAuth 登录不复制。CC Switch(`~/.cc-switch`)作为独立来源扫描,因此可导入已保存的配置档案,而不只是当前生效的 live 文件。再次导入等价提供商(规范化 base URL、API 风格和相同凭据)时跳过;同一端点不同凭据的配置档案保持独立。若应用尚无默认模型,则本次新建的第一个提供商成为默认。+- 技能和 MCP 服务器复用智能体能力扫描器及其来源标签。技能类型携带导入模式(复制或符号链接);MCP 类型写入 MCP 目的地所管理的同一个 MCP 列表。### 项目档案- 重用持久项目索引作为设置规模管理界面diff --git a/docs/zh-CN/spec/04-ux/07-ui-design-system.md b/docs/zh-CN/spec/04-ux/07-ui-design-system.mdindex c89580103..b70ecabe9 100644--- a/docs/zh-CN/spec/04-ux/07-ui-design-system.md+++ b/docs/zh-CN/spec/04-ux/07-ui-design-system.md@@ -1186,4 +1186,9 @@ Linux 保留淡入淡出和滑动退出。根据 D092,内容卡填充当前可用的窗格宽度窗口而不是保留 D070 的固定 720px 上限 - 早期的 in-shell200px 轨道和广泛的分组目录被取代+- **导入**:四种类型(会话 / 模型 / 技能 / MCP)位于一个页面级分段切换器之后,+ 其构成与智能体能力页面一致:每个类型一个安静的扫描前下一步操作状态、+ 每个类型一个工具栏(全选连同两个计数、该类型自己的选项、重新扫描、导入所选),+ 以及一个列表,其分组标题是安静的标签行、候选项是独立磁贴。没有按类型划分的+ 扫描卡片、没有着色的分组条带,也没有第二份设置行脚手架副本- 浅色目的地卡使用白色高架板(不是平坦的灰色填充)diff --git a/docs/zh-CN/spec/04-ux/08-component-spec.md b/docs/zh-CN/spec/04-ux/08-component-spec.mdindex 9208c7ac5..b6ef28b46 100644--- a/docs/zh-CN/spec/04-ux/08-component-spec.md+++ b/docs/zh-CN/spec/04-ux/08-component-spec.md@@ -2367,55 +2367,76 @@ dismissToast(id: number); // ToastHost internal / tests----## 18. SessionImportPanel+## 18. 导入目的地### 18.1 目的-扫描支持的本地代理商店,以可管理的方式查看发现的会话-组、选择候选者并开始显式导入。+扫描受支持的本地代理存储,找出这台机器能够移交的四样内容——会话、+提供商/模型配置、技能和 MCP 服务器——然后审查候选项、选中它们并+发起一次显式导入。### 18.2 解剖学+每个类型一个工作台,位于分段式类型切换器之后;每个类型拥有自己的+扫描、选择和导入操作。+```text-[Found N sessions] [Group by: Source ▾] [Import selected (N)]-──────────────────────────────────────────────────────────────────-[ ] [›] Claude Code N sessions-[ ] [›] Codex N sessions+[ Sessions | Models | Skills | MCP ] ← 类型切换器+[ ] Found 12 · 6 selected Group by: Source ▾ [Scan] [Import selected (6)]+───────────────────────────────────────────────────────────────────────────+CLAUDE CODE ~/code/pi 4+[ ] Refactor the importer 12 messages · Jan 5, 2026 [Claude Code]```-- 分组控件支持**项目路径**和**来源**。-- 来源是默认分组。-- 在项目路径模式下,精确路径在组标题中保持可见。-- 没有项目路径的会话出现在最终的**无项目**组中。-- 每个组标题包括组选择、公开、标签和计数。-- 导入源名称、分组控件、计数、结果和可访问名称- 来自共享的 i18n 目录。候选日期使用活动的应用程序区域设置。+- 切换器复用侧边栏和设置导航栏已经发布的标签(`nav.sessions`、+ `settings.nav.models`、`settings.nav.skills`、`settings.nav.mcp`),+ 因此该页面不新增自己的目录条目。+- 每个类型都带自己的工具栏:全选复选框连同“found”文案和已选数量、+ 该类型自己的选项(会话分组、技能导入模式)、重新扫描,以及 Import selected。+- 在某个类型首次扫描之前,其面板会显示一个安静的下一步操作状态:扫描会读取+ 什么,以及 Scan 操作。切换选项卡绝不会启动扫描(D007 / D342)。+- 分组标题是安静的标签行——来源或项目名称、以等宽字体显示的解析路径,+ 以及一个计数胶囊——而不是着色条带;它们下方的候选项是独立磁贴。+- 分组控件支持**项目路径**和**来源**。来源是默认值。在项目路径模式下,+ 精确路径在分组标题中保持可见,没有项目路径的会话出现在最后的+ **无项目**分组中。+- 导入来源名称、分组与模式控件、计数、结果和可访问名称都来自共享的+ i18n 目录。候选项日期使用当前应用区域设置。### 18.3 状态和交互-- 成功的扫描会替换先前的候选集,清除选择,并且- 让每组都崩溃了。-- 成功的导入会创建或重复使用一个持久的项目索引条目- 每个不同的非空项目路径并刷新 sessions/projects。-- 无路径导入不会创建项目条目并保留在临时状态下- 会话。导入永远不会创建物理文件系统目录。-- 重新导入现有源会话会跳过它,而不重复它- 项目进入。-- 更改分组模式可以保留候选选择,但会折叠每个- 新成立的团体。-- 展开或折叠一组不会影响其他组。-- 组和全局复选框支持选中、未选中和不确定- 选择状态适用。-- 每个组内的候选人以及组本身都按最新的排在最前面;- 无路径组在项目路径模式下保持在最后。+- 一次成功的扫描会替换先前的候选集合、清空选择,并让每个分组保持展开:+ 找到的候选项就是扫描的答案,所以它们不会被藏在第二次点击之后。+- 每个类型各自扫描:会话扫描绝不会启动模型配置、技能或 MCP 扫描,+ 切换选项卡会保留离开的那个类型的结果和选择(非活动面板保持挂载并隐藏)。+- 一次成功的导入会为每个不同的非空项目路径创建或重复使用一个持久的项目索引条目+ 并刷新 sessions/projects。+- 当一次成功的核心或插件导入在已归档项目下新增一个绑定项目的会话时,+ 渲染器会在刷新之后恢复该项目的展示状态,使该项目和导入的会话在默认+ 侧边栏中可见。这只适用于新增的绑定会话;普通刷新、无路径会话和被跳过的+ 导入都会保留归档状态。+- 无路径导入不会创建项目条目并保留在临时+ 会话下。导入永远不会创建物理文件系统目录。+- 重新导入现有来源会话会跳过它,而不会重复其项目条目。+- 更改分组模式会保留候选选择,并让每个新形成的分组保持展开。+- 展开或折叠一个分组不会影响其他分组。+- 分组和全局复选框支持选中、未选中和不确定+ 选择状态;全局复选框将部分选择报告为不确定。+- 每个分组内的候选项以及分组本身都按最新优先排序;+ 无路径分组在项目路径模式下保持在最后。### 18.4 辅助功能+- 类型切换器是一个由 `tab` 控件组成的 `tablist`,每个控件都带有+ `aria-selected` 和命名其面板的 `aria-controls`。每个面板都是一个由其选项卡+ 标记的 `tabpanel`;非活动面板是 `hidden`,而不是被视觉覆盖。- 每个公开按钮都会公开 `aria-expanded` 并引用其主体`aria-controls`。-- 全局和组复选框具有本地化的可访问名称。-- 分组选择器具有可见标签并且可通过键盘操作。-- 项目行公开和操作菜单按钮公开本地化、+- 全局和分组复选框具有本地化的可访问名称,并携带不确定状态。+- 分组和导入模式选择器是共享的应用内菜单选择器,具有可见标签并可通过键盘操作,+ 绝不是平台绘制的 `<select>`。+- 分组计数胶囊以其标题携带本地化的计数文案。+- 项目行公开按钮和操作菜单按钮公开本地化、项目特定的可访问名称。### 18.5 ModelConfigImportPanel@@ -2424,18 +2445,17 @@ dismissToast(id: number); // ToastHost internal / tests选中它们,然后发起一次显式导入。```text-[Found N providers] [Import selected (N)]-──────────────────────────────────────────────────────────────────-[ ] [›] Claude Code N providers-[ ] [›] OpenCode N providers-[ ] [›] CC Switch N providers+[ ] Found 3 · 1 selected [Scan] [Import selected (1)]+───────────────────────────────────────────────────────────────────────────+CLAUDE CODE 1+[ ] acme-gateway 4 models · api.acme.dev [API key]```-- 该卡片独立于会话导入:它有自己的扫描、选择和"导入所选"操作。会话扫描- 绝不会触发模型配置扫描。+- 该类型独立于会话导入:它有自己的扫描、选择和 Import selected 操作。+ 会话扫描绝不会启动模型配置扫描,两者在切换器之后一次只显示一个。- 按来源分组是唯一的分组方式。一次成功的扫描会替换先前的候选集合、清空- 选择,并让所有分组保持折叠。-- 每一行显示提供商名称、模型数量、主机、"有 API key / 无 API key"徽章,+ 选择,并让所有分组保持展开。+- 每一行显示提供商名称、模型数量、主机、“有 API key / 无 API key”徽章,以及来源。原始密钥绝不会到达渲染器。- 导入会为每个选中的候选项创建一条 `providers.create` 记录。若已存在base URL 归一化结果、API 风格和凭据都相同的提供商,则跳过;同一端点的