Ver Fonte

为 Tauri 版新增项目管理、资源下载与 MCP 服务

- 通过通用 cli_json / cli_stream 桥接复用 luatos-cli,避免为每个子命令重复编写 Rust 代码
- 新增项目、资源、MCP 三个页面,支持项目创建/导入/构建/分析/导出及 CDN 下载进度展示
- 内置 MCP 脚本并随应用打包,让 AI 客户端可直接调用烧录与项目管理工具
wenhongquan há 3 semanas atrás
pai
commit
c5638de9ea

+ 1 - 1
README.md

@@ -2,7 +2,7 @@
 
 - [Luatools v3.4.15 逆向分析与多端安装/烧录方案](./Luatools_v3_多端安装与烧录方案.md)
 - [macOS 烧录工具(Electron + luatos-cli)](./luatools-mac/README.md)
-- [macOS 烧录工具 Tauri 版(Rust + luatos-cli,arm64)](./luatools-tauri/README.md)
+- [macOS 烧录工具 Tauri 版(Rust + luatos-cli;含资源下载、项目管理、MCP)](./luatools-tauri/README.md)
 
 ## macOS 快速开始
 

+ 82 - 0
luatools-tauri/README.md

@@ -6,6 +6,7 @@
 - 界面:直接复用 `luatools-mac/renderer`(`ui/` 是副本,新增 `ui/api.js` 适配层)
 - 桥接:渲染层仍然只认 `window.api`;`ui/api.js` 把它实现成 Tauri `invoke` + 事件
 - 内核:`src-tauri/binaries/luatos-cli-{aarch64,x86_64}-apple-darwin`,打包时由 Tauri 放进 `Contents/MacOS/`
+- 新增:**资源下载**(LuatOS CDN)、**项目管理**(创建/导入 LuaTools .ini/构建/烧录)、**MCP 服务**(给 AI 客户端调用)
 - 体积:Electron 版 `.app` 约 498 MB / DMG 223 MB;Tauri 版通常 30 MB 上下(大头是 17 MB 的内核)
 
 ## 架构
@@ -25,9 +26,90 @@ Electron 主进程里的命令在 Rust 侧一一对应:
 | `soc_info` | `luatos-cli soc info --format json` |
 | `flash_start` | 组装参数、spawn sidecar、逐行转发 JSONL、结束后返回 |
 | `flash_cancel` | kill 子进程 |
+| `cli_json` | 通用 `luatos-cli --format json`(resource/project/serial/soc/guide) |
+| `cli_stream` / `stream_cancel` | 通用 JSONL 流式任务(资源下载、项目构建) |
+| `app_paths` | 应用数据/项目/资源目录 |
+| `scan_projects` / `delete_project` / `clone_project` | 项目目录管理 |
+| `list_files` / `read_text_file` / `write_text_file` | 项目文件树和 main.lua 编辑 |
+| `open_file_dialog` / `open_folder_dialog` / `save_file_dialog` / `reveal_path` | 原生文件对话框、Finder 定位 |
+| `mcp_info` | MCP 脚本路径 + 客户端配置 JSON |
 | `open_soc_dialog` / `open_script_dir_dialog` / `save_log` | 原生对话框 |
 | `open_external` | 打开文档/项目链接 |
 
+## 项目管理
+
+界面顶部切到「项目管理」:
+
+- **新建**:选择芯片族(Air8101 / Air1601 / Air1602 / Air8000 / Air6208 / Air101 / Air103 / Air724UG),
+  在应用数据目录的 `projects/<name>/` 创建 `luatos-project.toml`、`lua/main.lua` 和 README。
+- **导入**:支持 Luatools 的 `.ini` 工程,内部调用 `luatos-cli project import`,会转换成
+  `luatos-project.toml`;也支持 `.luatos` 归档。
+- **编辑**:左侧项目列表,右侧查看项目配置、文件树、直接编辑 `main.lua` 并保存。
+- **构建**:调用 `luatos-cli project build --dir <project>`,输出脚本文件系统镜像(默认 `build/script.bin`)。
+- **分析**:调用 `project analyze`,显示 Lua 语法、依赖、空间占用和分区信息。
+- **去烧录**:把项目的 `flash.soc_file` 和 `build.script_dirs[0]` 带入烧录页,直接全量烧录。
+- **设置固件**:选择 `.soc` 写入项目配置 `flash.soc_file`。
+- **导出**:导出 `.luatos` 归档。
+
+> `project build` 需要 `soc_script` 扩展库。第一次构建前,在项目页点「准备扩展库」
+> (会下载到 `<project>/resource/`),或在「资源下载」里下载 `public / soc_script`,
+> 或让 MCP 调用 `project_prepare(dir=...)` / `resource_download(category=public, sub=soc_script)`。
+
+## 资源下载
+
+界面顶部切到「资源下载」:
+
+- 从 LuatOS CDN 读取 `files.json`(`luatos-cli resource list`)。
+- 左侧是资源分类(`public`、Air8000、Air8101、Air1601…),右侧列出子项、版本和文件。
+- 「下载最新」/「下载此版本」调用 `luatos-cli resource download`,带 JSONL 进度、镜像回退和 SHA256 校验。
+- 默认下载到应用数据目录的 `resources/`,可以在页面上选择其他目录;下载完成后可在 Finder 中打开。
+- 支持的工具:固件 `.soc`、扩展库、文档包、驱动、量产工具等。
+
+## MCP 服务(给 AI 用)
+
+切到「MCP」页面可以看到自动生成的配置。把 JSON 加到 Claude Desktop / Cursor / Codex 等
+客户端的 MCP 配置里即可:
+
+```json
+{
+  "mcpServers": {
+    "luatos": {
+      "command": "node",
+      "args": ["/Applications/LuatOS Flasher.app/Contents/Resources/mcp/luatos-mcp.mjs"],
+      "env": {
+        "LUATOS_CLI": "/Applications/LuatOS Flasher.app/Contents/MacOS/luatos-cli"
+      }
+    }
+  }
+}
+```
+
+要求:Node.js 20+(App 本身是 Tauri,不依赖 Node;MCP 脚本是单独的 Node 进程)。
+如果 `node` 不在 PATH,把 `command` 改成 node 的绝对路径。
+
+MCP 工具:
+
+| 工具 | 作用 |
+|---|---|
+| `serial_list` | 列出串口 |
+| `guide_models` | 列出支持的芯片/型号 |
+| `firmware_info` | 解析 `.soc` |
+| `flash_firmware` | 烧录固件(全量/脚本) |
+| `resource_list` / `resource_download` | 列出/下载 LuatOS CDN 资源 |
+| `project_list` / `project_create` / `project_import` | 项目列表/创建/导入 |
+| `project_info` / `project_config` | 读取/修改项目配置 |
+| `project_prepare` | 下载 `public/soc_script` 到项目 `resource/` |
+| `project_analyze` / `project_build` / `project_deps` / `project_export` | 分析/构建/依赖/导出 |
+| `app_paths` | 返回默认项目/资源目录 |
+
+示例 AI 指令:
+
+```text
+列出串口,然后把 ~/Downloads/LuatOS-SoC_V2022_Air8101_101.soc 烧到 /dev/cu.usbmodem1234。
+下载 public/soc_script 资源到默认目录。
+创建一个 air8101 项目 air8101-demo,构建并烧录。
+```
+
 ## 开发
 
 ```bash

+ 651 - 0
luatools-tauri/src-tauri/mcp/luatos-mcp.mjs

@@ -0,0 +1,651 @@
+#!/usr/bin/env node
+/**
+ * LuatOS Flasher MCP server (stdio).
+ *
+ * This is a thin, AI-friendly wrapper around luatos-cli. It exposes serial,
+ * flashing, resource-download and project-management operations as MCP tools.
+ *
+ * Configure it in an MCP client, for example:
+ *
+ *   {
+ *     "mcpServers": {
+ *       "luatos": {
+ *         "command": "node",
+ *         "args": ["/Applications/LuatOS Flasher.app/Contents/Resources/mcp/luatos-mcp.mjs"],
+ *         "env": { "LUATOS_CLI": "/Applications/LuatOS Flasher.app/Contents/MacOS/luatos-cli" }
+ *       }
+ *     }
+ *   }
+ *
+ * stdout is reserved for JSON-RPC; diagnostics go to stderr.
+ */
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import readline from 'node:readline';
+import { execFile } from 'node:child_process';
+import { fileURLToPath } from 'node:url';
+
+const SERVER_NAME = 'luatos-mcp';
+const SERVER_VERSION = '0.1.0';
+const PROTOCOL_VERSION = '2024-11-05';
+const SCRIPT_DIR = path.dirname(fileURLToPath(import.meta.url));
+const IS_WINDOWS = process.platform === 'win32';
+
+function log(...args) {
+  console.error(`[${SERVER_NAME}]`, ...args);
+}
+
+function defaultAppDataDir() {
+  if (process.platform === 'darwin') {
+    return path.join(os.homedir(), 'Library', 'Application Support', 'com.luatos.flasher');
+  }
+  if (IS_WINDOWS) {
+    return path.join(process.env.APPDATA || path.join(os.homedir(), 'AppData', 'Roaming'), 'com.luatos.flasher');
+  }
+  return path.join(process.env.XDG_DATA_HOME || path.join(os.homedir(), '.local', 'share'), 'com.luatos.flasher');
+}
+
+function defaultProjectsDir() {
+  return path.join(defaultAppDataDir(), 'projects');
+}
+
+function defaultResourcesDir() {
+  return path.join(defaultAppDataDir(), 'resources');
+}
+
+function isFile(candidate) {
+  try {
+    return fs.statSync(candidate).isFile();
+  } catch {
+    return false;
+  }
+}
+
+function findCli() {
+  const envPath = process.env.LUATOS_CLI;
+  if (envPath && isFile(envPath)) return envPath;
+
+  const exe = IS_WINDOWS ? 'luatos-cli.exe' : 'luatos-cli';
+  const arch = process.arch === 'arm64' ? 'aarch64' : 'x86_64';
+  const candidates = [
+    path.join(SCRIPT_DIR, exe),
+    path.join(SCRIPT_DIR, '..', exe),
+    path.join(SCRIPT_DIR, '..', '..', 'MacOS', exe),
+    path.join(SCRIPT_DIR, '..', '..', 'Resources', 'bin', exe),
+    path.join(SCRIPT_DIR, '..', '..', 'binaries', `luatos-cli-${arch}-apple-darwin`),
+    path.join(SCRIPT_DIR, '..', '..', '..', 'luatools-mac', 'resources', IS_WINDOWS ? 'win' : 'bin', exe),
+    path.join(SCRIPT_DIR, '..', '..', '..', 'luatools-mac', 'resources', 'bin', exe),
+  ];
+  for (const candidate of candidates) {
+    if (isFile(candidate)) return candidate;
+  }
+  return exe; // rely on PATH
+}
+
+const CLI = findCli();
+
+function execCli(args, timeoutMs = 300_000) {
+  return new Promise((resolve) => {
+    const started = Date.now();
+    execFile(
+      CLI,
+      args,
+      {
+        timeout: timeoutMs,
+        maxBuffer: 64 * 1024 * 1024,
+        windowsHide: true,
+        env: { ...process.env, NO_COLOR: '1' },
+      },
+      (error, stdout, stderr) => {
+        const timedOut = Boolean(error && (error.killed || error.signal === 'SIGTERM'));
+        resolve({
+          ok: !error,
+          code: error && typeof error.code === 'number' ? error.code : error ? -1 : 0,
+          timedOut,
+          stdout: String(stdout || ''),
+          stderr: String(stderr || ''),
+          elapsed_ms: Date.now() - started,
+          error: error ? String(error.message || error) : null,
+        });
+      },
+    );
+  });
+}
+
+async function runJson(args, timeoutMs) {
+  const result = await execCli(['--format', 'json', ...args], timeoutMs);
+  if (result.timedOut) {
+    throw new Error(`luatos-cli 超时(${Math.round(timeoutMs / 1000)}s):${args.join(' ')}`);
+  }
+  if (!result.ok) {
+    throw new Error((result.stderr || result.stdout || result.error || `退出码 ${result.code}`).trim());
+  }
+  try {
+    return JSON.parse(result.stdout);
+  } catch (error) {
+    throw new Error(`无法解析 luatos-cli JSON 输出:${error.message}\n${result.stdout.slice(0, 1200)}`);
+  }
+}
+
+async function runJsonl(args, timeoutMs) {
+  const result = await execCli(['--format', 'jsonl', ...args], timeoutMs);
+  const events = [];
+  const lines = [];
+  for (const raw of result.stdout.split(/\r?\n/)) {
+    const line = raw.trim();
+    if (!line) continue;
+    lines.push(line);
+    if (line.startsWith('{')) {
+      try {
+        events.push(JSON.parse(line));
+        continue;
+      } catch {
+        // keep as a plain line
+      }
+    }
+  }
+  for (const raw of result.stderr.split(/\r?\n/)) {
+    const line = raw.trim();
+    if (line) lines.push(line);
+  }
+  return { ...result, events, lines };
+}
+
+function tail(lines, count = 160) {
+  return lines.slice(Math.max(0, lines.length - count)).join('\n');
+}
+
+function summarizeEvents(events) {
+  const result = [...events].reverse().find((event) => event.type === 'result') || null;
+  const progress = [...events].reverse().find((event) => event.type === 'progress') || null;
+  return { result, progress };
+}
+
+function formatSize(bytes) {
+  const value = Number(bytes) || 0;
+  const units = ['B', 'KB', 'MB', 'GB'];
+  let index = 0;
+  let size = value;
+  while (size >= 1024 && index < units.length - 1) {
+    size /= 1024;
+    index += 1;
+  }
+  return `${size.toFixed(index === 0 ? 0 : 1)} ${units[index]}`;
+}
+
+function scanProjects(root) {
+  fs.mkdirSync(root, { recursive: true });
+  const projects = [];
+  for (const entry of fs.readdirSync(root, { withFileTypes: true })) {
+    if (!entry.isDirectory()) continue;
+    const dir = path.join(root, entry.name);
+    if (!isFile(path.join(dir, 'luatos-project.toml'))) continue;
+    let modified = 0;
+    try {
+      modified = Math.floor(fs.statSync(dir).mtimeMs / 1000);
+    } catch {
+      // ignore
+    }
+    projects.push({ name: entry.name, path: dir, modified });
+  }
+  projects.sort((left, right) => right.modified - left.modified);
+  return projects;
+}
+
+function flashArgs(args) {
+  const soc = args.soc || args.soc_path;
+  if (!soc || !isFile(soc)) throw new Error('soc 固件文件不存在');
+  if (!args.port) throw new Error('port 不能为空');
+
+  const mode = args.mode === 'script' ? 'script' : 'run';
+  const command = ['flash', mode, '--soc', soc, '--port', args.port];
+  if (args.script_dir) command.push('--script', args.script_dir);
+  if (args.baud) command.push('--baud', String(args.baud));
+  if (mode === 'run' && Number(args.tail_log_secs) > 0) {
+    command.push('--tail-log-secs', String(Number(args.tail_log_secs)));
+  }
+  if (args.rts_reset) command.push('--rts-reset');
+  return command;
+}
+
+const TOOLS = [
+  {
+    name: 'serial_list',
+    description: '列出当前系统可用的串口(含 VID/PID/产品名)。',
+    inputSchema: { type: 'object', properties: {}, additionalProperties: false },
+  },
+  {
+    name: 'guide_models',
+    description: '列出 luatos-cli 支持的芯片/型号及推荐命令。',
+    inputSchema: { type: 'object', properties: {}, additionalProperties: false },
+  },
+  {
+    name: 'firmware_info',
+    description: '解析 .soc 固件,返回芯片、版本、分区和文件列表。',
+    inputSchema: {
+      type: 'object',
+      properties: { soc: { type: 'string', description: '.soc 文件路径' } },
+      required: ['soc'],
+    },
+  },
+  {
+    name: 'flash_firmware',
+    description:
+      '烧录 .soc 固件到设备。全量烧录用 mode=full;仅刷脚本区用 mode=script 并传 script_dir。该调用会等待烧录完成。',
+    inputSchema: {
+      type: 'object',
+      properties: {
+        soc: { type: 'string', description: '.soc 文件路径' },
+        port: { type: 'string', description: '串口,例如 /dev/cu.usbmodem1234 或 COM10' },
+        mode: { type: 'string', enum: ['full', 'script'], default: 'full' },
+        script_dir: { type: 'string', description: '脚本目录(mode=script 时必填)' },
+        baud: { type: ['string', 'number'], description: '可选烧录波特率' },
+        tail_log_secs: { type: 'number', description: '烧录后继续抓日志的秒数' },
+        rts_reset: { type: 'boolean', description: '烧录前发送 RTS 复位脉冲' },
+        timeout_secs: { type: 'number', description: '超时秒数,默认 900' },
+      },
+      required: ['soc', 'port'],
+    },
+  },
+  {
+    name: 'resource_list',
+    description: '列出 LuatOS CDN 资源分类;传 module 可列出该分类下的子项、版本和文件。',
+    inputSchema: {
+      type: 'object',
+      properties: { module: { type: 'string', description: '分类名,例如 Air8101、Air8000、public' } },
+    },
+  },
+  {
+    name: 'resource_download',
+    description:
+      '下载 LuatOS CDN 资源。例:category=public, sub=soc_script;或 category=Air8000, sub=V2032。会等待下载完成。',
+    inputSchema: {
+      type: 'object',
+      properties: {
+        category: { type: 'string', description: '资源大类,例如 public、Air8101' },
+        sub: { type: 'string', description: '子项名(如 soc_script)或版本过滤(如 V2032)' },
+        item: { type: 'string', description: '版本名或文件名过滤,可选' },
+        output: { type: 'string', description: '下载目录,默认应用资源目录' },
+        timeout_secs: { type: 'number', description: '超时秒数,默认 1800' },
+      },
+      required: ['category', 'sub'],
+    },
+  },
+  {
+    name: 'project_list',
+    description: '扫描项目根目录,列出 LuatOS 项目(含 luatos-project.toml 的目录)。',
+    inputSchema: {
+      type: 'object',
+      properties: { root: { type: 'string', description: '项目根目录,默认应用项目目录' } },
+    },
+  },
+  {
+    name: 'project_create',
+    description: '创建新的 LuatOS 项目(非交互式)。',
+    inputSchema: {
+      type: 'object',
+      properties: {
+        name: { type: 'string', description: '项目名' },
+        chip: { type: 'string', description: '芯片族,例如 bk72xx、air8101、air8000、air6208、ec7xx' },
+        dir: { type: 'string', description: '项目目录,默认 <项目根>/<name>' },
+      },
+      required: ['name', 'chip'],
+    },
+  },
+  {
+    name: 'project_import',
+    description: '导入 LuaTools .ini 工程或 .luatos 归档。',
+    inputSchema: {
+      type: 'object',
+      properties: {
+        file: { type: 'string', description: '.ini 或 .luatos 文件路径' },
+        dir: { type: 'string', description: '输出目录,默认 <项目根>/<文件名>' },
+      },
+      required: ['file'],
+    },
+  },
+  {
+    name: 'project_info',
+    description: '读取项目配置(芯片、版本、脚本目录、输出、flash 配置等)。',
+    inputSchema: {
+      type: 'object',
+      properties: { dir: { type: 'string', description: '项目目录' } },
+      required: ['dir'],
+    },
+  },
+  {
+    name: 'project_config',
+    description:
+      '读取或修改项目配置。省略 key 显示完整配置;只传 key 读取;key+value 修改。常用 key:build.script_dirs、build.script_files、build.output_dir、build.use_luac、flash.soc_file、flash.port。',
+    inputSchema: {
+      type: 'object',
+      properties: {
+        dir: { type: 'string', description: '项目目录' },
+        key: { type: 'string', description: '配置键' },
+        value: { type: 'string', description: '配置值' },
+      },
+      required: ['dir'],
+    },
+  },
+  {
+    name: 'project_analyze',
+    description: '完整分析项目:Lua 语法、依赖、空间占用、分区信息。',
+    inputSchema: {
+      type: 'object',
+      properties: {
+        dir: { type: 'string', description: '项目目录' },
+        soc: { type: 'string', description: '可选 .soc,覆盖项目配置用于分区信息' },
+      },
+      required: ['dir'],
+    },
+  },
+  {
+    name: 'project_prepare',
+    description:
+      '把 public/soc_script 扩展库下载到项目的 resource/ 目录。首次构建前调用一次;等同于界面上的“准备扩展库”。',
+    inputSchema: {
+      type: 'object',
+      properties: { dir: { type: 'string', description: '项目目录' } },
+      required: ['dir'],
+    },
+  },
+  {
+    name: 'project_build',
+    description: '按项目配置构建脚本文件系统镜像(script.bin)。',
+    inputSchema: {
+      type: 'object',
+      properties: { dir: { type: 'string', description: '项目目录' } },
+      required: ['dir'],
+    },
+  },
+  {
+    name: 'project_export',
+    description: '把项目导出为 .luatos 归档。',
+    inputSchema: {
+      type: 'object',
+      properties: {
+        dir: { type: 'string', description: '项目目录' },
+        output: { type: 'string', description: '输出 .luatos 路径,默认 <项目名>.luatos' },
+      },
+      required: ['dir'],
+    },
+  },
+  {
+    name: 'project_deps',
+    description: '分析项目 Lua 脚本依赖。',
+    inputSchema: {
+      type: 'object',
+      properties: { dir: { type: 'string', description: '项目目录' } },
+      required: ['dir'],
+    },
+  },
+  {
+    name: 'app_paths',
+    description: '返回应用的默认项目目录和资源下载目录。',
+    inputSchema: { type: 'object', properties: {}, additionalProperties: false },
+  },
+];
+
+async function callTool(name, args = {}) {
+  switch (name) {
+    case 'serial_list': {
+      const response = await runJson(['serial', 'list']);
+      return response.data ?? response;
+    }
+    case 'guide_models': {
+      const response = await runJson(['guide', 'models']);
+      return response.data ?? response;
+    }
+    case 'firmware_info': {
+      if (!args.soc || !isFile(args.soc)) throw new Error('soc 文件不存在');
+      const response = await runJson(['soc', 'info', args.soc]);
+      return response.data ?? response;
+    }
+    case 'flash_firmware': {
+      const command = flashArgs(args);
+      const timeout = Number(args.timeout_secs) > 0 ? Number(args.timeout_secs) * 1000 : 900_000;
+      const result = await runJsonl(command, timeout);
+      const { result: finalEvent } = summarizeEvents(result.events);
+      return {
+        ok: result.ok && result.code === 0,
+        code: result.code,
+        timed_out: result.timedOut,
+        result: finalEvent,
+        log_tail: tail(result.lines),
+      };
+    }
+    case 'resource_list': {
+      const command = ['resource', 'list'];
+      if (args.module) command.push(args.module);
+      const response = await runJson(command);
+      return response.data ?? response;
+    }
+    case 'resource_download': {
+      if (!args.category || !args.sub) throw new Error('category 和 sub 不能为空');
+      const output = args.output || defaultResourcesDir();
+      fs.mkdirSync(output, { recursive: true });
+      const command = ['resource', 'download', args.category, args.sub];
+      if (args.item) command.push(args.item);
+      command.push('--output', output);
+      const timeout = Number(args.timeout_secs) > 0 ? Number(args.timeout_secs) * 1000 : 1_800_000;
+      const result = await runJsonl(command, timeout);
+      const { result: finalEvent } = summarizeEvents(result.events);
+      return {
+        ok: result.ok && result.code === 0,
+        code: result.code,
+        timed_out: result.timedOut,
+        output,
+        result: finalEvent,
+        log_tail: tail(result.lines),
+      };
+    }
+    case 'project_list': {
+      const root = args.root || defaultProjectsDir();
+      return { root, projects: scanProjects(root) };
+    }
+    case 'project_create': {
+      if (!args.name || !args.chip) throw new Error('name 和 chip 不能为空');
+      const root = defaultProjectsDir();
+      const dir = args.dir || path.join(root, args.name);
+      fs.mkdirSync(path.dirname(dir), { recursive: true });
+      const response = await runJson(['project', 'new', args.name, '--chip', args.chip, '--dir', dir]);
+      return response.data ?? response;
+    }
+    case 'project_import': {
+      if (!args.file || !isFile(args.file)) throw new Error('导入文件不存在');
+      const root = defaultProjectsDir();
+      const base = path.basename(args.file, path.extname(args.file));
+      const dir = args.dir || path.join(root, base);
+      fs.mkdirSync(path.dirname(dir), { recursive: true });
+      const response = await runJson(['project', 'import', args.file, '--dir', dir]);
+      return response.data ?? response;
+    }
+    case 'project_info': {
+      requireDir(args.dir);
+      const response = await runJson(['project', 'info', '--dir', args.dir]);
+      return response.data ?? response;
+    }
+    case 'project_config': {
+      requireDir(args.dir);
+      const command = ['project', 'config', '--dir', args.dir];
+      if (args.key) command.push(args.key);
+      if (args.value !== undefined && args.value !== null) command.push(String(args.value));
+      const response = await runJson(command);
+      return response.data ?? response;
+    }
+    case 'project_analyze': {
+      requireDir(args.dir);
+      const command = ['project', 'analyze', '--dir', args.dir];
+      if (args.soc) command.push('--soc', args.soc);
+      const response = await runJson(command, 600_000);
+      return response.data ?? response;
+    }
+    case 'project_prepare': {
+      requireDir(args.dir);
+      const output = path.join(args.dir, 'resource');
+      fs.mkdirSync(output, { recursive: true });
+      const result = await runJsonl(
+        ['resource', 'download', 'public', 'soc_script', '--output', output],
+        300_000,
+      );
+      const { result: finalEvent } = summarizeEvents(result.events);
+      return {
+        ok: result.ok && result.code === 0,
+        code: result.code,
+        output,
+        result: finalEvent,
+        log_tail: tail(result.lines, 40),
+      };
+    }
+    case 'project_build': {
+      requireDir(args.dir);
+      const result = await runJsonl(['project', 'build', '--dir', args.dir], 600_000);
+      const { result: finalEvent } = summarizeEvents(result.events);
+      return {
+        ok: result.ok && result.code === 0,
+        code: result.code,
+        result: finalEvent,
+        log_tail: tail(result.lines),
+      };
+    }
+    case 'project_export': {
+      requireDir(args.dir);
+      const output = args.output || path.join(args.dir, `${path.basename(args.dir)}.luatos`);
+      const response = await runJson(['project', 'export', '--dir', args.dir, '-o', output], 300_000);
+      return response.data ?? response;
+    }
+    case 'project_deps': {
+      requireDir(args.dir);
+      const response = await runJson(['project', 'deps', '--dir', args.dir]);
+      return response.data ?? response;
+    }
+    case 'app_paths': {
+      return {
+        app_data: defaultAppDataDir(),
+        projects: defaultProjectsDir(),
+        resources: defaultResourcesDir(),
+        luatos_cli: CLI,
+      };
+    }
+    default:
+      throw new Error(`未知工具:${name}`);
+  }
+}
+
+function requireDir(dir) {
+  if (!dir) throw new Error('dir 不能为空');
+  if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) {
+    throw new Error(`项目目录不存在:${dir}`);
+  }
+}
+
+function textContent(value) {
+  if (typeof value === 'string') return value;
+  return JSON.stringify(value, null, 2);
+}
+
+function send(payload) {
+  process.stdout.write(`${JSON.stringify(payload)}\n`);
+}
+
+function sendResult(id, result) {
+  send({ jsonrpc: '2.0', id, result });
+}
+
+function sendError(id, code, message) {
+  send({ jsonrpc: '2.0', id, error: { code, message } });
+}
+
+async function handleRequest(request) {
+  const { id, method, params } = request;
+
+  if (method === 'initialize') {
+    sendResult(id, {
+      protocolVersion: PROTOCOL_VERSION,
+      capabilities: { tools: {} },
+      serverInfo: { name: SERVER_NAME, version: SERVER_VERSION },
+    });
+    return;
+  }
+
+  if (method === 'ping') {
+    sendResult(id, {});
+    return;
+  }
+
+  if (method === 'tools/list') {
+    sendResult(id, { tools: TOOLS });
+    return;
+  }
+
+  if (method === 'tools/call') {
+    const name = params?.name;
+    const args = params?.arguments || {};
+    if (!name) {
+      sendError(id, -32602, '缺少工具名称');
+      return;
+    }
+    try {
+      const value = await callTool(name, args);
+      const failed = value && typeof value === 'object' && value.ok === false;
+      sendResult(id, {
+        content: [{ type: 'text', text: textContent(value) }],
+        isError: failed,
+      });
+    } catch (error) {
+      sendResult(id, {
+        content: [{ type: 'text', text: String(error.message || error) }],
+        isError: true,
+      });
+    }
+    return;
+  }
+
+  if (method === 'resources/list') {
+    sendResult(id, { resources: [] });
+    return;
+  }
+
+  if (method === 'prompts/list') {
+    sendResult(id, { prompts: [] });
+    return;
+  }
+
+  sendError(id, -32601, `未知方法:${method}`);
+}
+
+const rl = readline.createInterface({ input: process.stdin, crlfDelay: Infinity });
+let queue = Promise.resolve();
+
+rl.on('line', (line) => {
+  const trimmed = line.trim();
+  if (!trimmed) return;
+
+  let request;
+  try {
+    request = JSON.parse(trimmed);
+  } catch (error) {
+    log('无法解析 JSON-RPC:', error.message);
+    return;
+  }
+
+  // Notifications have no id and must not receive a response.
+  if (request.id === undefined || request.id === null) {
+    if (request.method === 'notifications/initialized') log('client initialized');
+    return;
+  }
+
+  queue = queue
+    .then(() => handleRequest(request))
+    .catch((error) => {
+      log('处理请求失败:', error);
+      sendError(request.id, -32603, String(error.message || error));
+    });
+});
+
+rl.on('close', () => {
+  log('stdin closed, exiting');
+});
+
+log(`ready; cli=${CLI}; node=${process.version}`);

+ 568 - 1
luatools-tauri/src-tauri/src/lib.rs

@@ -1,3 +1,5 @@
+use std::collections::HashMap;
+use std::fs;
 use std::path::{Path, PathBuf};
 use std::sync::Mutex;
 use std::time::Duration;
@@ -5,7 +7,7 @@ use std::time::Duration;
 use serde::{Deserialize, Serialize};
 use serde_json::{json, Value};
 use tauri::menu::{AboutMetadata, MenuBuilder, MenuItemBuilder, PredefinedMenuItem, SubmenuBuilder};
-use tauri::{AppHandle, Emitter, State};
+use tauri::{AppHandle, Emitter, Manager, State};
 use tauri_plugin_dialog::DialogExt;
 use tauri_plugin_opener::OpenerExt;
 use tauri_plugin_shell::process::CommandEvent;
@@ -15,6 +17,12 @@ struct FlashState {
     child: Mutex<Option<tauri_plugin_shell::process::CommandChild>>,
 }
 
+/// Long-running, generic `luatos-cli --format jsonl` jobs (resource download,
+/// project build, ...), keyed by a caller-provided kind such as "resource".
+struct CliStreamState {
+    children: Mutex<HashMap<String, tauri_plugin_shell::process::CommandChild>>,
+}
+
 #[derive(Debug, Deserialize)]
 #[serde(rename_all = "camelCase")]
 struct FlashOptions {
@@ -232,6 +240,40 @@ fn emit_chunk(app: &AppHandle, chunk: &str, source: &str) {
     }
 }
 
+fn emit_chunk_named(app: &AppHandle, kind: &str, chunk: &str, source: &str) {
+    let event_name = format!("{kind}:event");
+    let line_name = format!("{kind}:line");
+
+    for line in chunk.lines() {
+        let trimmed = line.trim();
+        if trimmed.is_empty() {
+            continue;
+        }
+
+        if source == "stdout" && trimmed.starts_with('{') {
+            if let Ok(value) = serde_json::from_str::<Value>(trimmed) {
+                let _ = app.emit(&event_name, value);
+                continue;
+            }
+        }
+
+        let _ = app.emit(&line_name, json!({ "line": trimmed, "source": source }));
+    }
+}
+
+/// Only expose read-only / local-management commands to the renderer through
+/// the generic bridge. Flashing keeps its dedicated command.
+fn cli_command_allowed(args: &[String]) -> bool {
+    matches!(
+        args.first().map(String::as_str),
+        Some("serial" | "soc" | "resource" | "project" | "guide" | "device" | "log")
+    )
+}
+
+fn json_error(message: impl Into<String>) -> Value {
+    json!({ "ok": false, "error": message.into() })
+}
+
 #[tauri::command]
 async fn cli_info(app: AppHandle) -> Value {
     let path = cli_display_path();
@@ -533,6 +575,511 @@ fn selftest_report(app: AppHandle, payload: Value) {
     });
 }
 
+#[tauri::command]
+async fn cli_json(app: AppHandle, args: Vec<String>) -> Value {
+    if !cli_command_allowed(&args) {
+        return json_error("不允许的 luatos-cli 子命令");
+    }
+
+    let mut full: Vec<String> = vec!["--format".into(), "json".into()];
+    full.extend(args);
+    let refs: Vec<&str> = full.iter().map(String::as_str).collect();
+
+    match run_json(&app, &refs, Duration::from_secs(300)).await {
+        Ok(mut value) => {
+            if let Some(object) = value.as_object_mut() {
+                object.insert("ok".to_string(), Value::Bool(true));
+            }
+            value
+        }
+        Err(error) => json_error(error),
+    }
+}
+
+/// Generic streaming bridge for `luatos-cli --format jsonl`.
+///
+/// The renderer passes `kind = "resource"` / `"project"` and the CLI args; the
+/// backend emits `<kind>:event`, `<kind>:line` and `<kind>:exit`.
+#[tauri::command]
+async fn cli_stream(
+    app: AppHandle,
+    state: State<'_, CliStreamState>,
+    kind: String,
+    args: Vec<String>,
+) -> Result<Value, String> {
+    let safe_kind = !kind.is_empty()
+        && kind
+            .chars()
+            .all(|character| character.is_ascii_alphanumeric() || character == '-' || character == '_');
+    if !safe_kind {
+        return Ok(json_error("非法的任务类型"));
+    }
+    if !cli_command_allowed(&args) {
+        return Ok(json_error("不允许的 luatos-cli 子命令"));
+    }
+    if state.children.lock().unwrap().contains_key(&kind) {
+        return Ok(json_error(format!("{kind} 任务正在运行")));
+    }
+
+    let mut full: Vec<String> = vec!["--format".into(), "jsonl".into()];
+    full.extend(args);
+    let command = build_command(&app, &full)?;
+    let (mut receiver, child) = command
+        .spawn()
+        .map_err(|error| format!("无法启动 luatos-cli:{error}"))?;
+    state.children.lock().unwrap().insert(kind.clone(), child);
+
+    let mut code: Option<i32> = None;
+    let mut signal: Option<i32> = None;
+    let mut spawn_error: Option<String> = None;
+
+    while let Some(event) = receiver.recv().await {
+        match event {
+            CommandEvent::Stdout(bytes) => {
+                emit_chunk_named(&app, &kind, &String::from_utf8_lossy(&bytes), "stdout")
+            }
+            CommandEvent::Stderr(bytes) => {
+                emit_chunk_named(&app, &kind, &String::from_utf8_lossy(&bytes), "stderr")
+            }
+            CommandEvent::Error(error) => spawn_error = Some(error),
+            CommandEvent::Terminated(payload) => {
+                code = payload.code;
+                signal = payload.signal;
+            }
+            _ => {}
+        }
+    }
+
+    state.children.lock().unwrap().remove(&kind);
+    let signal_text = signal.map(signal_name);
+    let _ = app.emit(
+        &format!("{kind}:exit"),
+        json!({
+            "code": code.unwrap_or(-1),
+            "signal": signal_text,
+            "error": spawn_error,
+        }),
+    );
+
+    Ok(json!({
+        "ok": spawn_error.is_none() && code == Some(0),
+        "code": code,
+        "signal": signal_text,
+        "error": spawn_error,
+    }))
+}
+
+#[tauri::command]
+fn stream_cancel(state: State<'_, CliStreamState>, kind: String) -> Value {
+    let child = state.children.lock().unwrap().remove(&kind);
+    match child {
+        Some(child) => match child.kill() {
+            Ok(_) => json!({ "ok": true }),
+            Err(error) => json_error(error.to_string()),
+        },
+        None => json_error(format!("{kind} 没有正在运行的任务")),
+    }
+}
+
+fn app_subdir(app: &AppHandle, name: &str) -> PathBuf {
+    let base = app
+        .path()
+        .app_data_dir()
+        .unwrap_or_else(|_| PathBuf::from("."));
+    let dir = base.join(name);
+    let _ = fs::create_dir_all(&dir);
+    dir
+}
+
+#[tauri::command]
+fn app_paths(app: AppHandle) -> Value {
+    let base = app
+        .path()
+        .app_data_dir()
+        .unwrap_or_else(|_| PathBuf::from("."));
+    let projects = app_subdir(&app, "projects");
+    let resources = app_subdir(&app, "resources");
+    json!({
+        "ok": true,
+        "appData": base.display().to_string(),
+        "projects": projects.display().to_string(),
+        "resources": resources.display().to_string(),
+    })
+}
+
+#[tauri::command]
+fn read_text_file(path: String) -> Value {
+    let file_path = Path::new(&path);
+    if !file_path.is_file() {
+        return json_error("文件不存在");
+    }
+    let metadata = match fs::metadata(file_path) {
+        Ok(metadata) => metadata,
+        Err(error) => return json_error(error.to_string()),
+    };
+    if metadata.len() > 4 * 1024 * 1024 {
+        return json_error("文件太大(超过 4MB)");
+    }
+    match fs::read(file_path) {
+        Ok(data) => json!({
+            "ok": true,
+            "content": String::from_utf8_lossy(&data).to_string(),
+        }),
+        Err(error) => json_error(error.to_string()),
+    }
+}
+
+#[tauri::command]
+fn write_text_file(path: String, content: String) -> Value {
+    let file_path = Path::new(&path);
+    if let Some(parent) = file_path.parent() {
+        if let Err(error) = fs::create_dir_all(parent) {
+            return json_error(error.to_string());
+        }
+    }
+    match fs::write(file_path, content) {
+        Ok(_) => json!({ "ok": true }),
+        Err(error) => json_error(error.to_string()),
+    }
+}
+
+fn collect_files(root: &Path, current: &Path, output: &mut Vec<Value>, count: &mut usize) {
+    if *count >= 4000 {
+        return;
+    }
+    let entries = match fs::read_dir(current) {
+        Ok(entries) => entries,
+        Err(_) => return,
+    };
+    for entry in entries.flatten() {
+        let name = entry.file_name().to_string_lossy().to_string();
+        if matches!(name.as_str(), ".git" | "node_modules" | "target" | ".DS_Store") {
+            continue;
+        }
+        let path = entry.path();
+        let metadata = match entry.metadata() {
+            Ok(metadata) => metadata,
+            Err(_) => continue,
+        };
+        let relative = path
+            .strip_prefix(root)
+            .unwrap_or(path.as_path())
+            .to_string_lossy()
+            .replace('\\', "/");
+        if metadata.is_dir() {
+            output.push(json!({
+                "path": relative,
+                "name": name,
+                "isDir": true,
+                "size": 0,
+            }));
+            collect_files(root, &path, output, count);
+        } else {
+            output.push(json!({
+                "path": relative,
+                "name": name,
+                "isDir": false,
+                "size": metadata.len(),
+            }));
+        }
+        *count += 1;
+        if *count >= 4000 {
+            return;
+        }
+    }
+}
+
+#[tauri::command]
+fn list_files(path: String) -> Value {
+    let root = Path::new(&path);
+    if !root.is_dir() {
+        return json_error("目录不存在");
+    }
+    let mut output = Vec::new();
+    let mut count = 0usize;
+    collect_files(root, root, &mut output, &mut count);
+    json!({ "ok": true, "files": output })
+}
+
+#[tauri::command]
+fn scan_projects(root: String) -> Value {
+    let root_path = Path::new(&root);
+    if !root_path.is_dir() {
+        return json_error("项目目录不存在");
+    }
+
+    let mut projects = Vec::new();
+    if let Ok(entries) = fs::read_dir(root_path) {
+        for entry in entries.flatten() {
+            let path = entry.path();
+            if path.is_dir() && path.join("luatos-project.toml").is_file() {
+                let name = entry.file_name().to_string_lossy().to_string();
+                let modified = fs::metadata(&path)
+                    .and_then(|metadata| metadata.modified())
+                    .ok()
+                    .and_then(|time| time.duration_since(std::time::UNIX_EPOCH).ok())
+                    .map(|duration| duration.as_secs())
+                    .unwrap_or(0);
+                projects.push(json!({
+                    "name": name,
+                    "path": path.display().to_string(),
+                    "modified": modified,
+                }));
+            }
+        }
+    }
+    projects.sort_by(|left, right| {
+        right["modified"]
+            .as_u64()
+            .cmp(&left["modified"].as_u64())
+    });
+
+    json!({ "ok": true, "projects": projects })
+}
+
+#[tauri::command]
+fn delete_project(dir: String) -> Value {
+    let path = Path::new(&dir);
+    if !path.join("luatos-project.toml").is_file() {
+        return json_error("不是有效的 LuatOS 项目目录");
+    }
+    match fs::remove_dir_all(path) {
+        Ok(_) => json!({ "ok": true }),
+        Err(error) => json_error(error.to_string()),
+    }
+}
+
+fn copy_dir_all(source: &Path, destination: &Path) -> std::io::Result<()> {
+    fs::create_dir_all(destination)?;
+    for entry in fs::read_dir(source)? {
+        let entry = entry?;
+        let file_type = entry.file_type()?;
+        let target = destination.join(entry.file_name());
+        if file_type.is_dir() {
+            copy_dir_all(&entry.path(), &target)?;
+        } else {
+            fs::copy(entry.path(), &target)?;
+        }
+    }
+    Ok(())
+}
+
+#[tauri::command]
+fn clone_project(src: String, dst: String) -> Value {
+    let source = Path::new(&src);
+    let destination = Path::new(&dst);
+    if !source.join("luatos-project.toml").is_file() {
+        return json_error("源项目无效");
+    }
+    if destination.exists() {
+        return json_error("目标目录已存在");
+    }
+    match copy_dir_all(source, destination) {
+        Ok(_) => json!({ "ok": true }),
+        Err(error) => json_error(error.to_string()),
+    }
+}
+
+#[tauri::command]
+fn create_dir(path: String) -> Value {
+    match fs::create_dir_all(&path) {
+        Ok(_) => json!({ "ok": true }),
+        Err(error) => json_error(error.to_string()),
+    }
+}
+
+#[tauri::command]
+fn path_exists(path: String) -> Value {
+    json!({ "ok": true, "exists": Path::new(&path).exists() })
+}
+
+#[tauri::command]
+fn reveal_path(path: String) -> Value {
+    let target = Path::new(&path);
+    if !target.exists() {
+        return json_error("路径不存在");
+    }
+
+    #[cfg(target_os = "macos")]
+    let result = if target.is_file() {
+        std::process::Command::new("open")
+            .arg("-R")
+            .arg(target)
+            .spawn()
+    } else {
+        std::process::Command::new("open").arg(target).spawn()
+    };
+
+    #[cfg(target_os = "windows")]
+    let result = if target.is_file() {
+        std::process::Command::new("explorer")
+            .arg(format!("/select,{}", target.display()))
+            .spawn()
+    } else {
+        std::process::Command::new("explorer").arg(target).spawn()
+    };
+
+    #[cfg(all(not(target_os = "macos"), not(target_os = "windows")))]
+    let result = std::process::Command::new("xdg-open")
+        .arg(if target.is_dir() {
+            target
+        } else {
+            target.parent().unwrap_or(target)
+        })
+        .spawn();
+
+    match result {
+        Ok(_) => json!({ "ok": true }),
+        Err(error) => json_error(error.to_string()),
+    }
+}
+
+#[tauri::command]
+async fn open_file_dialog(app: AppHandle, filters: Vec<String>) -> Option<String> {
+    let filter_refs: Vec<&str> = filters.iter().map(String::as_str).collect();
+    let (tx, rx) = tokio::sync::oneshot::channel();
+
+    let mut builder = app.dialog().file().set_title("选择文件");
+    if filter_refs.is_empty() {
+        builder = builder.add_filter("所有文件", &["*"]);
+    } else {
+        builder = builder.add_filter("文件", &filter_refs);
+    }
+    builder.pick_file(move |path| {
+        let _ = tx.send(path);
+    });
+
+    rx.await.ok().flatten().and_then(file_path_string)
+}
+
+#[tauri::command]
+async fn open_folder_dialog(app: AppHandle) -> Option<String> {
+    let (tx, rx) = tokio::sync::oneshot::channel();
+    app.dialog()
+        .file()
+        .set_title("选择目录")
+        .pick_folder(move |path| {
+            let _ = tx.send(path);
+        });
+
+    rx.await.ok().flatten().and_then(file_path_string)
+}
+
+#[tauri::command]
+async fn save_file_dialog(
+    app: AppHandle,
+    default_name: Option<String>,
+    filters: Vec<String>,
+) -> Option<String> {
+    let filter_refs: Vec<&str> = filters.iter().map(String::as_str).collect();
+    let (tx, rx) = tokio::sync::oneshot::channel();
+
+    let mut builder = app.dialog().file().set_title("保存文件");
+    if let Some(name) = default_name {
+        if !name.trim().is_empty() {
+            builder = builder.set_file_name(&name);
+        }
+    }
+    if filter_refs.is_empty() {
+        builder = builder.add_filter("所有文件", &["*"]);
+    } else {
+        builder = builder.add_filter("文件", &filter_refs);
+    }
+    builder.save_file(move |path| {
+        let _ = tx.send(path);
+    });
+
+    rx.await.ok().flatten().and_then(file_path_string)
+}
+
+fn find_named_file(root: &Path, file_name: &str, depth: usize) -> Option<PathBuf> {
+    if depth == 0 {
+        return None;
+    }
+    let entries = fs::read_dir(root).ok()?;
+    for entry in entries.flatten() {
+        let path = entry.path();
+        if path.is_file()
+            && path
+                .file_name()
+                .and_then(|name| name.to_str())
+                .map(|name| name == file_name)
+                .unwrap_or(false)
+        {
+            return Some(path);
+        }
+        if path.is_dir() {
+            if let Some(found) = find_named_file(&path, file_name, depth - 1) {
+                return Some(found);
+            }
+        }
+    }
+    None
+}
+
+#[tauri::command]
+fn mcp_info(app: AppHandle) -> Value {
+    let mut candidates = Vec::new();
+    let mut resource_root: Option<PathBuf> = None;
+    if let Ok(resource_dir) = app.path().resource_dir() {
+        candidates.push(resource_dir.join("mcp").join("luatos-mcp.mjs"));
+        candidates.push(
+            resource_dir
+                .join("resources")
+                .join("mcp")
+                .join("luatos-mcp.mjs"),
+        );
+        resource_root = Some(resource_dir);
+    }
+    candidates.push(
+        PathBuf::from(env!("CARGO_MANIFEST_DIR"))
+            .join("mcp")
+            .join("luatos-mcp.mjs"),
+    );
+
+    let script = candidates
+        .into_iter()
+        .find(|path| path.is_file())
+        .or_else(|| {
+            resource_root
+                .as_deref()
+                .and_then(|root| find_named_file(root, "luatos-mcp.mjs", 4))
+        })
+        .map(|path| path.display().to_string())
+        .unwrap_or_default();
+
+    let cli = cli_display_path();
+    let node_version = std::process::Command::new("node")
+        .arg("--version")
+        .output()
+        .ok()
+        .filter(|output| output.status.success())
+        .map(|output| String::from_utf8_lossy(&output.stdout).trim().to_string())
+        .unwrap_or_default();
+
+    let config = if script.is_empty() {
+        Value::Null
+    } else {
+        json!({
+            "mcpServers": {
+                "luatos": {
+                    "command": "node",
+                    "args": [script.clone()],
+                    "env": { "LUATOS_CLI": cli.clone() }
+                }
+            }
+        })
+    };
+
+    json!({
+        "ok": !script.is_empty(),
+        "script": script,
+        "cli": cli,
+        "node": node_version,
+        "config": config,
+    })
+}
+
 fn build_app_menu(app: &tauri::App) -> tauri::Result<tauri::menu::Menu<tauri::Wry>> {
     let about = PredefinedMenuItem::about(
         app,
@@ -601,6 +1148,9 @@ pub fn run() {
         .manage(FlashState {
             child: Mutex::new(None),
         })
+        .manage(CliStreamState {
+            children: Mutex::new(HashMap::new()),
+        })
         .setup(|app| {
             let menu = build_app_menu(app)?;
             app.set_menu(menu)?;
@@ -638,6 +1188,23 @@ pub fn run() {
             open_script_dir_dialog,
             save_log,
             open_external,
+            cli_json,
+            cli_stream,
+            stream_cancel,
+            app_paths,
+            read_text_file,
+            write_text_file,
+            list_files,
+            scan_projects,
+            delete_project,
+            clone_project,
+            create_dir,
+            path_exists,
+            reveal_path,
+            open_file_dialog,
+            open_folder_dialog,
+            save_file_dialog,
+            mcp_info,
             selftest_config,
             js_log,
             selftest_report

+ 1 - 0
luatools-tauri/src-tauri/tauri.conf.json

@@ -42,6 +42,7 @@
       "icons/icon.ico"
     ],
     "externalBin": ["binaries/luatos-cli"],
+    "resources": ["mcp/luatos-mcp.mjs"],
     "macOS": {
       "minimumSystemVersion": "12.0"
     }

+ 27 - 0
luatools-tauri/ui/api.js

@@ -52,6 +52,33 @@
     saveLog: (content) => invoke('save_log', { content }),
     openExternal: (url) => invoke('open_external', { url }),
 
+    // Generic bridge for resource download / project management.
+    runCliJson: (args) => invoke('cli_json', { args }),
+    startCliStream: (kind, args) => invoke('cli_stream', { kind, args }),
+    cancelCliStream: (kind) => invoke('stream_cancel', { kind }),
+    onCliEvent: (kind, callback) =>
+      listen(`${kind}:event`, (event) => callback(event.payload)),
+    onCliLine: (kind, callback) =>
+      listen(`${kind}:line`, (event) => callback(event.payload)),
+    onCliExit: (kind, callback) =>
+      listen(`${kind}:exit`, (event) => callback(event.payload)),
+
+    appPaths: () => invoke('app_paths'),
+    readTextFile: (path) => invoke('read_text_file', { path }),
+    writeTextFile: (path, content) => invoke('write_text_file', { path, content }),
+    listFiles: (path) => invoke('list_files', { path }),
+    scanProjects: (root) => invoke('scan_projects', { root }),
+    deleteProject: (dir) => invoke('delete_project', { dir }),
+    cloneProject: (src, dst) => invoke('clone_project', { src, dst }),
+    createDir: (path) => invoke('create_dir', { path }),
+    pathExists: (path) => invoke('path_exists', { path }),
+    revealPath: (path) => invoke('reveal_path', { path }),
+    openFileDialog: (filters) => invoke('open_file_dialog', { filters }),
+    openFolderDialog: () => invoke('open_folder_dialog'),
+    saveFileDialog: (defaultName, filters) =>
+      invoke('save_file_dialog', { defaultName, filters }),
+    mcpInfo: () => invoke('mcp_info'),
+
     // WKWebView does not expose File.path. Drag & drop is handled below via
     // Tauri's native drag-drop event, and file picking goes through Rust.
     getPathForFile: (file) => (file && file.path) || '',

+ 190 - 1
luatools-tauri/ui/index.html

@@ -36,7 +36,14 @@
         </div>
       </header>
 
-      <main class="layout">
+      <nav class="tabs" id="tabs" aria-label="功能导航">
+        <button type="button" class="tab active" data-view="flash">烧录</button>
+        <button type="button" class="tab" data-view="projects">项目管理</button>
+        <button type="button" class="tab" data-view="resources">资源下载</button>
+        <button type="button" class="tab" data-view="mcp">MCP</button>
+      </nav>
+
+      <main id="view-flash" class="layout view active">
         <section class="column">
           <section class="card">
             <div class="card-head">
@@ -161,6 +168,158 @@
         </section>
       </main>
 
+      <main id="view-projects" class="page view hidden">
+        <div class="page-head">
+          <div>
+            <h2>项目管理</h2>
+            <p>创建 LuatOS 工程、导入 LuaTools .ini、构建脚本并直接烧录。</p>
+          </div>
+          <div class="page-actions">
+            <button id="btn-project-new" class="primary small" type="button">新建项目</button>
+            <button id="btn-project-import" class="secondary small" type="button">导入 .ini</button>
+            <button id="btn-project-root" class="ghost small" type="button">项目目录</button>
+          </div>
+        </div>
+
+        <div class="project-layout">
+          <aside class="card project-list-card">
+            <div class="card-head">
+              <h2>项目</h2>
+              <span id="project-count" class="muted"></span>
+            </div>
+            <input id="project-filter" class="select" type="text" placeholder="过滤项目…" />
+            <div id="project-list" class="project-list"></div>
+          </aside>
+
+          <section class="card project-detail-card">
+            <div id="project-empty" class="empty">还没有选择项目</div>
+            <div id="project-content" class="hidden">
+              <div class="detail-head">
+                <div class="detail-title">
+                  <h2 id="project-name">—</h2>
+                  <p id="project-meta" class="muted"></p>
+                </div>
+                <div class="page-actions">
+                  <button id="btn-project-build" class="primary small" type="button">构建</button>
+                  <button id="btn-project-libs" class="ghost small" type="button">准备扩展库</button>
+                  <button id="btn-project-analyze" class="secondary small" type="button">分析</button>
+                  <button id="btn-project-soc" class="ghost small" type="button">设置固件</button>
+                  <button id="btn-project-flash" class="secondary small" type="button">去烧录</button>
+                  <button id="btn-project-export" class="ghost small" type="button">导出</button>
+                  <button id="btn-project-reveal" class="ghost small" type="button">打开目录</button>
+                  <button id="btn-project-delete" class="ghost small danger-text" type="button">删除</button>
+                </div>
+              </div>
+
+              <div class="project-grid">
+                <div class="project-info-card">
+                  <div class="card-head"><h2>项目配置</h2></div>
+                  <dl id="project-info" class="info-list"></dl>
+                </div>
+                <div class="project-editor-card">
+                  <div class="card-head">
+                    <h2 id="project-editor-title">main.lua</h2>
+                    <div class="log-actions">
+                      <button id="btn-project-save" class="ghost small" type="button">保存</button>
+                    </div>
+                  </div>
+                  <textarea id="project-editor" class="code-editor" spellcheck="false"></textarea>
+                </div>
+              </div>
+
+              <div class="sub-card">
+                <div class="card-head">
+                  <h2>脚本文件</h2>
+                  <div class="page-actions">
+                    <button id="btn-project-add-dir" class="secondary small" type="button">添加目录</button>
+                    <button id="btn-project-add-file" class="secondary small" type="button">添加文件</button>
+                  </div>
+                </div>
+                <div id="project-files" class="file-list"></div>
+              </div>
+
+              <pre id="project-log" class="log project-log" aria-live="polite"></pre>
+            </div>
+          </section>
+        </div>
+      </main>
+
+      <main id="view-resources" class="page view hidden">
+        <div class="page-head">
+          <div>
+            <h2>资源下载</h2>
+            <p>从 LuatOS CDN 下载固件、扩展库、工具和资料包,支持 SHA256 校验。</p>
+          </div>
+          <div class="page-actions">
+            <button id="btn-res-refresh" class="secondary small" type="button">刷新清单</button>
+            <button id="btn-res-choose" class="ghost small" type="button">选择目录</button>
+            <button id="btn-res-output" class="ghost small" type="button">下载目录</button>
+          </div>
+        </div>
+
+        <div class="resource-layout">
+          <aside class="card resource-categories-card">
+            <div class="card-head">
+              <h2>资源分类</h2>
+              <span id="res-category-count" class="muted"></span>
+            </div>
+            <div id="res-categories" class="resource-categories"></div>
+          </aside>
+
+          <section class="card resource-detail-card">
+            <div class="card-head">
+              <h2 id="res-title">选择分类</h2>
+              <span id="res-output-path" class="muted path-inline"></span>
+            </div>
+            <div id="res-detail" class="resource-detail">
+              <div class="empty">从左侧选择资源分类</div>
+            </div>
+          </section>
+        </div>
+
+        <section class="card resource-progress-card">
+          <div class="progress-head">
+            <span id="res-stage">等待下载</span>
+            <span id="res-percent">0%</span>
+          </div>
+          <div class="bar" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0">
+            <div id="res-bar-fill"></div>
+          </div>
+          <pre id="res-log" class="log resource-log" aria-live="polite"></pre>
+        </section>
+      </main>
+
+      <main id="view-mcp" class="page view hidden">
+        <div class="page-head">
+          <div>
+            <h2>MCP 服务</h2>
+            <p>把烧录、资源下载和项目管理能力暴露给 Claude Desktop、Cursor、Codex 等 AI 客户端。</p>
+          </div>
+          <div class="page-actions">
+            <button id="btn-mcp-copy" class="primary small" type="button">复制配置</button>
+            <button id="btn-mcp-refresh" class="secondary small" type="button">重新检测</button>
+          </div>
+        </div>
+
+        <section class="card mcp-card">
+          <div class="card-head">
+            <h2>客户端配置</h2>
+            <span id="mcp-status" class="muted"></span>
+          </div>
+          <p class="hint">把下面这段 JSON 加到 MCP 客户端配置里。需要 Node.js 20+;如果 <code>node</code> 不在 PATH,请把 <code>command</code> 改成 node 的绝对路径。</p>
+          <pre id="mcp-config" class="code-block"></pre>
+          <div class="mcp-meta">
+            <span>脚本:<code id="mcp-script">—</code></span>
+            <span>内核:<code id="mcp-cli">—</code></span>
+          </div>
+        </section>
+
+        <section class="card mcp-card">
+          <div class="card-head"><h2>可用工具</h2></div>
+          <div id="mcp-tools" class="mcp-tools"></div>
+        </section>
+      </main>
+
       <footer class="footer">
         <span>内核:<a id="cli-link" href="https://github.com/wendal/luatos-cli" target="_blank" rel="noreferrer">luatos-cli</a> · 固件:LuatOS</span>
         <span id="cli-path" class="muted">未检测到烧录内核</span>
@@ -186,7 +345,37 @@
       </div>
     </div>
 
+    <div id="project-modal" class="modal hidden" role="dialog" aria-modal="true" aria-labelledby="project-modal-title">
+      <div class="modal-card">
+        <h2 id="project-modal-title">新建项目</h2>
+        <label class="field">
+          <span>项目名称</span>
+          <input id="project-name-input" type="text" placeholder="例如 air8101-demo" />
+        </label>
+        <label class="field">
+          <span>芯片族</span>
+          <select id="project-chip" class="select">
+            <option value="air8101">Air8101 / BK7258</option>
+            <option value="air1601">Air1601 / CCM4211</option>
+            <option value="air1602">Air1602 / CCM4211</option>
+            <option value="air8000">Air8000 / EC7xx</option>
+            <option value="air6208">Air6208 / XT804</option>
+            <option value="air101">Air101 / XT804</option>
+            <option value="air103">Air103 / XT804</option>
+            <option value="air724ug">Air724UG / UIS8910</option>
+          </select>
+        </label>
+        <p class="hint">项目会创建在默认项目目录,包含 <code>luatos-project.toml</code>、<code>lua/main.lua</code> 和 README。</p>
+        <p id="project-modal-error" class="error"></p>
+        <div class="modal-actions">
+          <button id="btn-project-create" class="primary" type="button">创建</button>
+          <button id="btn-project-cancel" class="secondary" type="button">取消</button>
+        </div>
+      </div>
+    </div>
+
     <script src="./api.js"></script>
     <script src="./app.js"></script>
+    <script src="./views.js"></script>
   </body>
 </html>

+ 501 - 0
luatools-tauri/ui/styles.css

@@ -920,3 +920,504 @@ button:disabled {
     transition-duration: 0.01ms !important;
   }
 }
+
+/* ── Navigation tabs ─────────────────────────────────────────────── */
+.tabs {
+  display: flex;
+  gap: 4px;
+  padding: 0 22px;
+  border-bottom: 1px solid rgba(148, 163, 184, 0.08);
+  background: rgba(8, 13, 26, 0.35);
+  flex: 0 0 auto;
+}
+
+.tab {
+  height: 38px;
+  padding: 0 16px;
+  border: 0;
+  border-bottom: 2px solid transparent;
+  border-radius: 0;
+  background: transparent;
+  color: var(--muted);
+  font-size: 12.5px;
+  font-weight: 600;
+  cursor: pointer;
+}
+
+.tab:hover {
+  color: var(--text);
+  background: rgba(148, 163, 184, 0.05);
+}
+
+.tab.active {
+  color: var(--cyan);
+  border-bottom-color: var(--cyan);
+}
+
+.view {
+  display: none;
+}
+
+.view.active {
+  display: flex;
+}
+
+#view-flash.active {
+  display: grid;
+}
+
+.page {
+  flex: 1;
+  min-height: 0;
+  overflow: auto;
+  padding: 16px 22px 14px;
+  flex-direction: column;
+  gap: 14px;
+}
+
+.page-head {
+  display: flex;
+  align-items: flex-start;
+  justify-content: space-between;
+  gap: 18px;
+}
+
+.page-head h2 {
+  margin: 0;
+  font-size: 18px;
+  font-weight: 650;
+  letter-spacing: 0.2px;
+}
+
+.page-head p {
+  margin: 5px 0 0;
+  font-size: 12px;
+  color: var(--muted);
+  line-height: 1.6;
+}
+
+.page-actions {
+  display: flex;
+  align-items: center;
+  gap: 8px;
+  flex-wrap: wrap;
+  justify-content: flex-end;
+}
+
+.page-actions .small {
+  height: 32px;
+}
+
+.danger-text {
+  color: #fecdd3 !important;
+}
+
+.danger-text:hover {
+  background: rgba(251, 113, 133, 0.1) !important;
+}
+
+/* ── Project management ──────────────────────────────────────────── */
+.project-layout,
+.resource-layout {
+  display: grid;
+  grid-template-columns: 270px minmax(0, 1fr);
+  gap: 14px;
+  min-height: 0;
+  flex: 1;
+}
+
+.project-list-card,
+.resource-categories-card {
+  display: flex;
+  flex-direction: column;
+  min-height: 0;
+  padding-bottom: 10px;
+}
+
+.project-list-card .select {
+  margin-bottom: 10px;
+}
+
+.project-list,
+.resource-categories {
+  display: flex;
+  flex-direction: column;
+  gap: 4px;
+  overflow: auto;
+  min-height: 0;
+}
+
+.project-item,
+.resource-category {
+  display: flex;
+  flex-direction: column;
+  align-items: flex-start;
+  gap: 3px;
+  width: 100%;
+  height: auto;
+  min-height: 48px;
+  padding: 9px 10px;
+  border-radius: 9px;
+  border: 1px solid transparent;
+  background: transparent;
+  color: var(--text);
+  text-align: left;
+  cursor: pointer;
+}
+
+.project-item:hover,
+.resource-category:hover {
+  background: rgba(148, 163, 184, 0.06);
+}
+
+.project-item.active,
+.resource-category.active {
+  border-color: rgba(34, 211, 238, 0.28);
+  background: rgba(34, 211, 238, 0.08);
+}
+
+.project-item strong,
+.resource-category strong {
+  font-size: 12.5px;
+  font-weight: 600;
+  color: #dbeafe;
+}
+
+.project-item span,
+.resource-category span {
+  font-size: 10.5px;
+  color: var(--faint);
+  max-width: 100%;
+  overflow: hidden;
+  text-overflow: ellipsis;
+  white-space: nowrap;
+}
+
+.project-detail-card,
+.resource-detail-card {
+  display: flex;
+  flex-direction: column;
+  min-height: 0;
+  overflow: hidden;
+}
+
+.project-detail-card > .hidden {
+  display: none;
+}
+
+.empty {
+  display: grid;
+  place-items: center;
+  min-height: 240px;
+  color: var(--faint);
+  font-size: 13px;
+}
+
+.detail-head {
+  display: flex;
+  align-items: flex-start;
+  justify-content: space-between;
+  gap: 14px;
+  padding-bottom: 12px;
+  border-bottom: 1px solid var(--border);
+  margin-bottom: 12px;
+}
+
+.detail-title {
+  min-width: 0;
+}
+
+.detail-title h2 {
+  margin: 0;
+  font-size: 17px;
+  color: #e0e7ff;
+}
+
+.detail-title p {
+  margin: 4px 0 0;
+  font-size: 11.5px;
+  color: var(--muted);
+  word-break: break-all;
+}
+
+.project-grid {
+  display: grid;
+  grid-template-columns: minmax(260px, 0.8fr) minmax(0, 1.2fr);
+  gap: 12px;
+  min-height: 0;
+}
+
+.project-info-card,
+.project-editor-card,
+.sub-card {
+  border: 1px solid var(--border);
+  border-radius: 11px;
+  background: rgba(8, 13, 26, 0.42);
+  padding: 12px;
+  min-height: 0;
+}
+
+.info-list {
+  margin: 0;
+  display: grid;
+  grid-template-columns: 112px minmax(0, 1fr);
+  gap: 7px 10px;
+  font-size: 11.5px;
+}
+
+.info-list dt {
+  color: var(--faint);
+}
+
+.info-list dd {
+  margin: 0;
+  color: #dbeafe;
+  word-break: break-all;
+}
+
+.code-editor {
+  width: 100%;
+  height: 300px;
+  resize: vertical;
+  min-height: 220px;
+  border-radius: 9px;
+  border: 1px solid var(--border-strong);
+  background: rgba(4, 8, 17, 0.9);
+  color: #dbeafe;
+  padding: 12px;
+  font-family: var(--mono);
+  font-size: 12px;
+  line-height: 1.65;
+  outline: none;
+  tab-size: 2;
+}
+
+.code-editor:focus {
+  border-color: rgba(34, 211, 238, 0.55);
+  box-shadow: 0 0 0 3px rgba(34, 211, 238, 0.08);
+}
+
+.sub-card {
+  margin-top: 12px;
+}
+
+.file-list {
+  max-height: 180px;
+  overflow: auto;
+  display: flex;
+  flex-direction: column;
+  gap: 2px;
+}
+
+.file-row {
+  display: grid;
+  grid-template-columns: 18px minmax(0, 1fr) 80px;
+  gap: 8px;
+  align-items: center;
+  padding: 5px 7px;
+  border-radius: 6px;
+  font-size: 11.5px;
+  color: #cbd5e1;
+  cursor: pointer;
+}
+
+.file-row:hover {
+  background: rgba(148, 163, 184, 0.07);
+}
+
+.file-row.active {
+  background: rgba(34, 211, 238, 0.08);
+  color: #a5f3fc;
+}
+
+.file-row .size {
+  text-align: right;
+  color: var(--faint);
+  font-family: var(--mono);
+  font-size: 10.5px;
+}
+
+.project-log,
+.resource-log {
+  height: 150px;
+  margin-top: 12px;
+  flex: 0 0 auto;
+}
+
+/* ── Resource download ───────────────────────────────────────────── */
+.resource-detail {
+  flex: 1;
+  min-height: 0;
+  overflow: auto;
+  display: flex;
+  flex-direction: column;
+  gap: 10px;
+}
+
+.resource-child {
+  border: 1px solid var(--border);
+  border-radius: 10px;
+  background: rgba(8, 13, 26, 0.38);
+  padding: 11px 12px;
+}
+
+.resource-child-head {
+  display: flex;
+  align-items: flex-start;
+  justify-content: space-between;
+  gap: 12px;
+}
+
+.resource-child-head h3 {
+  margin: 0;
+  font-size: 12.5px;
+  color: #dbeafe;
+}
+
+.resource-child-head p {
+  margin: 3px 0 0;
+  font-size: 10.5px;
+  color: var(--faint);
+}
+
+.resource-versions {
+  margin-top: 9px;
+  display: flex;
+  flex-direction: column;
+  gap: 8px;
+}
+
+.resource-version {
+  border-top: 1px solid rgba(148, 163, 184, 0.1);
+  padding-top: 8px;
+}
+
+.resource-version-head {
+  display: flex;
+  align-items: center;
+  justify-content: space-between;
+  gap: 10px;
+  font-size: 11.5px;
+  color: #c7d2fe;
+}
+
+.resource-files {
+  margin-top: 6px;
+  display: flex;
+  flex-direction: column;
+  gap: 2px;
+}
+
+.resource-file {
+  display: grid;
+  grid-template-columns: minmax(0, 1fr) 92px;
+  gap: 8px;
+  font-size: 10.5px;
+  color: var(--faint);
+  padding: 2px 0;
+}
+
+.resource-file span:first-child {
+  overflow: hidden;
+  text-overflow: ellipsis;
+  white-space: nowrap;
+}
+
+.resource-file span:last-child {
+  text-align: right;
+  font-family: var(--mono);
+}
+
+.resource-progress-card {
+  flex: 0 0 auto;
+}
+
+.resource-progress-card .resource-log {
+  height: 120px;
+}
+
+.path-inline {
+  max-width: 55%;
+  overflow: hidden;
+  text-overflow: ellipsis;
+  white-space: nowrap;
+  font-family: var(--mono);
+  font-size: 10.5px;
+}
+
+/* ── MCP page ────────────────────────────────────────────────────── */
+.mcp-card {
+  flex: 0 0 auto;
+}
+
+.code-block {
+  margin: 10px 0 0;
+  padding: 14px;
+  border-radius: 10px;
+  border: 1px solid rgba(148, 163, 184, 0.12);
+  background: rgba(4, 8, 17, 0.86);
+  color: #bae6fd;
+  font-family: var(--mono);
+  font-size: 11.5px;
+  line-height: 1.6;
+  overflow: auto;
+  max-height: 260px;
+  white-space: pre-wrap;
+  word-break: break-word;
+}
+
+.mcp-meta {
+  display: flex;
+  flex-direction: column;
+  gap: 5px;
+  margin-top: 10px;
+  font-size: 10.5px;
+  color: var(--faint);
+}
+
+.mcp-tools {
+  display: flex;
+  flex-wrap: wrap;
+  gap: 7px;
+}
+
+.mcp-tool {
+  padding: 7px 9px;
+  border-radius: 8px;
+  border: 1px solid var(--border);
+  background: rgba(8, 13, 26, 0.5);
+  font-family: var(--mono);
+  font-size: 10.5px;
+  color: #c7d2fe;
+}
+
+@media (max-width: 1100px) {
+  .project-layout,
+  .resource-layout {
+    grid-template-columns: 220px minmax(0, 1fr);
+  }
+
+  .project-grid {
+    grid-template-columns: 1fr;
+  }
+}
+
+@media (max-width: 860px) {
+  .project-layout,
+  .resource-layout {
+    grid-template-columns: 1fr;
+  }
+
+  .project-list-card,
+  .resource-categories-card {
+    max-height: 230px;
+  }
+
+  .page-head {
+    flex-direction: column;
+  }
+
+  .detail-head {
+    flex-direction: column;
+  }
+}

+ 906 - 0
luatools-tauri/ui/views.js

@@ -0,0 +1,906 @@
+'use strict';
+
+/**
+ * Projects / resources / MCP views.
+ *
+ * The flashing view lives in app.js. This file only uses the shared
+ * window.api bridge and never assumes a browser (WKWebView) has Node access.
+ */
+(() => {
+  const api = window.api;
+  if (!api) {
+    console.error('window.api 不存在,项目管理/资源下载不可用');
+    return;
+  }
+
+  const $ = (selector) => document.querySelector(selector);
+  const $$ = (selector) => Array.from(document.querySelectorAll(selector));
+
+  const state = {
+    current: 'flash',
+    paths: null,
+    projects: [],
+    activeProject: null,
+    projectInfo: null,
+    activeFile: null,
+    resources: { categories: [], activeCategory: null, detail: null, output: '', busy: false },
+    mcp: null,
+  };
+
+  function toast(message, kind = '') {
+    const el = $('#toast');
+    if (!el) return;
+    el.textContent = message;
+    el.className = `toast ${kind}`.trim();
+    clearTimeout(toast._timer);
+    toast._timer = setTimeout(() => el.classList.add('hidden'), 3200);
+  }
+
+  function escapeHtml(value) {
+    return String(value)
+      .replaceAll('&', '&amp;')
+      .replaceAll('<', '&lt;')
+      .replaceAll('>', '&gt;')
+      .replaceAll('"', '&quot;');
+  }
+
+  function formatSize(bytes) {
+    const value = Number(bytes) || 0;
+    const units = ['B', 'KB', 'MB', 'GB'];
+    let index = 0;
+    let size = value;
+    while (size >= 1024 && index < units.length - 1) {
+      size /= 1024;
+      index += 1;
+    }
+    return `${size.toFixed(index === 0 ? 0 : 1)} ${units[index]}`;
+  }
+
+  function baseName(filePath) {
+    return String(filePath).split(/[\\/]/).pop() || filePath;
+  }
+
+  function isAbsolutePath(value) {
+    return /^[\\/]/.test(value) || /^[A-Za-z]:[\\/]/.test(value);
+  }
+
+  function joinPath(root, relative) {
+    if (!relative) return root;
+    if (isAbsolutePath(relative)) return relative;
+    return `${root.replace(/[\\/]+$/, '')}/${relative}`;
+  }
+
+  function relativeToProject(filePath) {
+    if (!state.activeProject) return filePath;
+    const root = state.activeProject.replace(/[\\/]+$/, '');
+    if (filePath.startsWith(`${root}/`) || filePath.startsWith(`${root}\\`)) {
+      return filePath.slice(root.length + 1).replaceAll('\\', '/');
+    }
+    return filePath;
+  }
+
+  async function ensurePaths() {
+    if (state.paths) return state.paths;
+    const result = await api.appPaths();
+    if (!result?.ok) throw new Error(result?.error || '无法读取应用目录');
+    state.paths = result;
+    return result;
+  }
+
+  /* ── Navigation ─────────────────────────────────────────────── */
+
+  const VIEWS = ['flash', 'projects', 'resources', 'mcp'];
+
+  function showView(name) {
+    if (!VIEWS.includes(name)) return;
+    state.current = name;
+    $$('#tabs .tab').forEach((tab) => {
+      tab.classList.toggle('active', tab.dataset.view === name);
+    });
+    for (const view of VIEWS) {
+      const el = $(`#view-${view}`);
+      if (!el) continue;
+      el.classList.toggle('active', view === name);
+      el.classList.toggle('hidden', view !== name);
+    }
+    const flashTop = $('#btn-flash-top');
+    if (flashTop) flashTop.style.display = name === 'flash' ? '' : 'none';
+
+    if (name === 'projects') loadProjects().catch((error) => toast(error.message, 'err'));
+    if (name === 'resources') loadResources().catch((error) => toast(error.message, 'err'));
+    if (name === 'mcp') loadMcp().catch((error) => toast(error.message, 'err'));
+  }
+
+  /* ── Projects ───────────────────────────────────────────────── */
+
+  function projectLog(text, level = 'info') {
+    const log = $('#project-log');
+    if (!log) return;
+    const line = document.createElement('span');
+    line.className = 'line';
+    const time = document.createElement('span');
+    time.className = 't';
+    time.textContent = new Date().toTimeString().slice(0, 8);
+    const body = document.createElement('span');
+    body.className = level;
+    body.textContent = text;
+    line.append(time, body);
+    log.appendChild(line);
+    log.scrollTop = log.scrollHeight;
+  }
+
+  function projectClearLog() {
+    const log = $('#project-log');
+    if (log) log.textContent = '';
+  }
+
+  function renderProjects() {
+    const list = $('#project-list');
+    if (!list) return;
+    const filter = ($('#project-filter')?.value || '').trim().toLowerCase();
+    const projects = state.projects.filter((project) =>
+      !filter || project.name.toLowerCase().includes(filter) || project.path.toLowerCase().includes(filter),
+    );
+
+    list.textContent = '';
+    if (!projects.length) {
+      const empty = document.createElement('div');
+      empty.className = 'empty';
+      empty.style.minHeight = '120px';
+      empty.textContent = state.projects.length ? '没有匹配的项目' : '还没有项目';
+      list.appendChild(empty);
+    } else {
+      for (const project of projects) {
+        const button = document.createElement('button');
+        button.type = 'button';
+        button.className = `project-item${project.path === state.activeProject ? ' active' : ''}`;
+        const name = document.createElement('strong');
+        name.textContent = project.name;
+        const path = document.createElement('span');
+        path.textContent = project.path;
+        button.append(name, path);
+        button.addEventListener('click', () => {
+          openProject(project.path).catch((error) => toast(error.message, 'err'));
+        });
+        list.appendChild(button);
+      }
+    }
+    $('#project-count').textContent = `${state.projects.length} 个`;
+  }
+
+  async function loadProjects() {
+    const paths = await ensurePaths();
+    const result = await api.scanProjects(paths.projects);
+    if (!result?.ok) throw new Error(result?.error || '扫描项目失败');
+    state.projects = result.projects || [];
+    renderProjects();
+    if (!state.activeProject && state.projects.length) {
+      await openProject(state.projects[0].path);
+    }
+  }
+
+  async function openProject(projectPath) {
+    const result = await api.runCliJson(['project', 'info', '--dir', projectPath]);
+    if (!result?.ok) throw new Error(result?.error || '读取项目失败');
+    const project = result.data;
+    state.activeProject = projectPath;
+    state.projectInfo = project;
+    state.activeFile = null;
+
+    $('#project-empty').classList.add('hidden');
+    $('#project-content').classList.remove('hidden');
+    $('#project-name').textContent = project.project?.name || baseName(projectPath);
+    $('#project-meta').textContent = `${project.project?.chip || 'unknown'} · ${project.project?.version || ''} · ${projectPath}`;
+    $('#project-editor').value = '';
+
+    renderProjectInfo(project);
+    renderProjects();
+    updateProjectLibState().catch(() => {});
+    projectClearLog();
+    projectLog(`打开项目:${projectPath}`, 'ok');
+
+    const files = await loadProjectFiles(projectPath);
+    const main = files.find((file) => !file.isDir && file.name.toLowerCase() === 'main.lua');
+    if (main) {
+      await openProjectFile(main.path);
+    } else {
+      $('#project-editor-title').textContent = 'main.lua';
+      $('#project-editor').value = '-- 这个项目里没有找到 main.lua\n';
+    }
+  }
+
+  function renderProjectInfo(project) {
+    const info = $('#project-info');
+    if (!info) return;
+    info.textContent = '';
+    const rows = [
+      ['芯片', project.project?.chip],
+      ['版本', project.project?.version],
+      ['脚本目录', (project.build?.script_dirs || []).join(', ') || '—'],
+      ['脚本文件', (project.build?.script_files || []).join(', ') || '—'],
+      ['输出目录', project.build?.output_dir || 'build/'],
+      ['使用 luac', project.build?.use_luac ? '是' : '否'],
+      ['SOC 固件', project.flash?.soc_file || '未设置'],
+      ['串口', project.flash?.port || '未设置'],
+    ];
+    for (const [label, value] of rows) {
+      const dt = document.createElement('dt');
+      dt.textContent = label;
+      const dd = document.createElement('dd');
+      dd.textContent = value || '—';
+      info.append(dt, dd);
+    }
+  }
+
+  async function loadProjectFiles(projectPath) {
+    const result = await api.listFiles(projectPath);
+    if (!result?.ok) throw new Error(result?.error || '读取项目文件失败');
+    const files = (result.files || []).filter(
+      (file) =>
+        !file.path.startsWith('.git/') &&
+        !file.path.startsWith('node_modules/') &&
+        !file.path.startsWith('resource/') &&
+        !file.path.startsWith('build/'),
+    );
+    const container = $('#project-files');
+    container.textContent = '';
+    for (const file of files) {
+      if (file.isDir) continue;
+      const row = document.createElement('div');
+      row.className = 'file-row';
+      row.dataset.path = file.path;
+      const icon = document.createElement('span');
+      icon.textContent = file.name.endsWith('.lua') ? '◈' : '•';
+      const name = document.createElement('span');
+      name.textContent = file.path;
+      const size = document.createElement('span');
+      size.className = 'size';
+      size.textContent = formatSize(file.size);
+      row.append(icon, name, size);
+      if (file.name.endsWith('.lua') || file.name.endsWith('.luac') || file.name.endsWith('.txt')) {
+        row.addEventListener('click', () => {
+          openProjectFile(file.path).catch((error) => toast(error.message, 'err'));
+        });
+      }
+      container.appendChild(row);
+    }
+    if (!container.children.length) {
+      const empty = document.createElement('div');
+      empty.className = 'muted';
+      empty.textContent = '没有脚本文件';
+      container.appendChild(empty);
+    }
+    return files;
+  }
+
+  async function openProjectFile(relativePath) {
+    if (!state.activeProject) return;
+    const fullPath = joinPath(state.activeProject, relativePath);
+    const result = await api.readTextFile(fullPath);
+    if (!result?.ok) throw new Error(result?.error || '读取文件失败');
+    state.activeFile = fullPath;
+    $('#project-editor').value = result.content || '';
+    $('#project-editor-title').textContent = relativePath;
+    $$('#project-files .file-row').forEach((row) => {
+      row.classList.toggle('active', row.dataset.path === relativePath);
+    });
+  }
+
+  async function saveProjectFile() {
+    if (!state.activeFile) {
+      toast('没有打开文件', 'err');
+      return;
+    }
+    const result = await api.writeTextFile(state.activeFile, $('#project-editor').value);
+    if (result?.ok) {
+      toast('已保存', 'ok');
+      projectLog(`保存:${state.activeFile}`, 'ok');
+    } else {
+      toast(result?.error || '保存失败', 'err');
+    }
+  }
+
+  function parseConfigList(value) {
+    return String(value || '')
+      .split(',')
+      .map((item) => item.trim())
+      .filter(Boolean);
+  }
+
+  async function updateProjectConfig(key, value) {
+    if (!state.activeProject) return;
+    const result = await api.runCliJson([
+      'project',
+      'config',
+      '--dir',
+      state.activeProject,
+      key,
+      value,
+    ]);
+    if (!result?.ok) throw new Error(result?.error || '修改项目配置失败');
+    await openProject(state.activeProject);
+  }
+
+  async function addProjectDir() {
+    const selected = await api.openFolderDialog();
+    if (!selected) return;
+    const current = state.projectInfo?.build?.script_dirs || [];
+    const relative = relativeToProject(selected);
+    if (current.includes(relative)) {
+      toast('该目录已在项目中', 'warn');
+      return;
+    }
+    await updateProjectConfig('build.script_dirs', [...current, relative].join(','));
+    toast('已添加脚本目录', 'ok');
+  }
+
+  async function addProjectFile() {
+    const selected = await api.openFileDialog(['lua', 'luac', 'txt']);
+    if (!selected) return;
+    const current = state.projectInfo?.build?.script_files || [];
+    const relative = relativeToProject(selected);
+    if (current.includes(relative)) {
+      toast('该文件已在项目中', 'warn');
+      return;
+    }
+    await updateProjectConfig('build.script_files', [...current, relative].join(','));
+    toast('已添加脚本文件', 'ok');
+  }
+
+  function showProjectModal() {
+    $('#project-modal-error').textContent = '';
+    $('#project-name-input').value = '';
+    $('#project-modal').classList.remove('hidden');
+    setTimeout(() => $('#project-name-input').focus(), 30);
+  }
+
+  async function createProject() {
+    const name = $('#project-name-input').value.trim();
+    const chip = $('#project-chip').value;
+    if (!name) {
+      $('#project-modal-error').textContent = '请输入项目名称';
+      return;
+    }
+    if (!/^[A-Za-z0-9_.-]+$/.test(name)) {
+      $('#project-modal-error').textContent = '项目名只能包含字母、数字、下划线、点和短横线';
+      return;
+    }
+    const paths = await ensurePaths();
+    const dir = `${paths.projects}/${name}`;
+    const button = $('#btn-project-create');
+    button.disabled = true;
+    try {
+      const result = await api.runCliJson(['project', 'new', name, '--chip', chip, '--dir', dir]);
+      if (!result?.ok) throw new Error(result?.error || '创建项目失败');
+      $('#project-modal').classList.add('hidden');
+      await loadProjects();
+      await openProject(dir);
+      toast(`项目已创建:${name}`, 'ok');
+    } catch (error) {
+      $('#project-modal-error').textContent = error.message || String(error);
+    } finally {
+      button.disabled = false;
+    }
+  }
+
+  async function importProject() {
+    const file = await api.openFileDialog(['ini', 'luatos']);
+    if (!file) return;
+    const paths = await ensurePaths();
+    const directoryName = baseName(file).replace(/\.(ini|luatos)$/i, '');
+    const dir = `${paths.projects}/${directoryName}`;
+    const result = await api.runCliJson(['project', 'import', file, '--dir', dir]);
+    if (!result?.ok) {
+      toast(result?.error || '导入失败', 'err');
+      return;
+    }
+    await loadProjects();
+    await openProject(dir);
+    toast('项目已导入', 'ok');
+  }
+
+  async function deleteActiveProject() {
+    if (!state.activeProject) return;
+    const name = state.projectInfo?.project?.name || baseName(state.activeProject);
+    if (!window.confirm(`确定删除项目“${name}”?此操作会删除整个项目目录,不可撤销。`)) return;
+    const result = await api.deleteProject(state.activeProject);
+    if (!result?.ok) {
+      toast(result?.error || '删除失败', 'err');
+      return;
+    }
+    state.activeProject = null;
+    state.projectInfo = null;
+    state.activeFile = null;
+    $('#project-content').classList.add('hidden');
+    $('#project-empty').classList.remove('hidden');
+    await loadProjects();
+    toast('项目已删除', 'ok');
+  }
+
+  async function analyzeProject() {
+    if (!state.activeProject) return;
+    projectClearLog();
+    projectLog('开始分析项目…', 'cmd');
+    const result = await api.runCliJson(['project', 'analyze', '--dir', state.activeProject]);
+    if (!result?.ok) {
+      projectLog(result?.error || '分析失败', 'err');
+      toast('分析失败', 'err');
+      return;
+    }
+    projectLog(JSON.stringify(result.data, null, 2), 'info');
+    toast('分析完成', 'ok');
+  }
+
+  async function prepareProjectLibraries() {
+    if (!state.activeProject) return;
+    const output = joinPath(state.activeProject, 'resource');
+    projectLog('下载 public/soc_script 到项目 resource/ …', 'cmd');
+    const button = $('#btn-project-libs');
+    button.disabled = true;
+    try {
+      const result = await api.startCliStream('project', [
+        'resource',
+        'download',
+        'public',
+        'soc_script',
+        '--output',
+        output,
+      ]);
+      if (result?.ok) {
+        toast('扩展库已下载', 'ok');
+        projectLog('扩展库已就绪,可以点击“构建”', 'ok');
+        await updateProjectLibState();
+      } else {
+        toast(result?.error || '扩展库下载失败', 'err');
+      }
+    } finally {
+      button.disabled = false;
+    }
+  }
+
+  async function updateProjectLibState() {
+    if (!state.activeProject) return;
+    const button = $('#btn-project-libs');
+    const exists = await api.pathExists(joinPath(state.activeProject, 'resource/public/soc_script'));
+    if (button) {
+      button.textContent = exists?.exists ? '扩展库已就绪' : '准备扩展库';
+      button.classList.toggle('secondary', Boolean(exists?.exists));
+      button.classList.toggle('ghost', !exists?.exists);
+    }
+  }
+
+  async function buildProject() {
+    if (!state.activeProject) return;
+    projectClearLog();
+    projectLog('开始构建…', 'cmd');
+    const button = $('#btn-project-build');
+    button.disabled = true;
+    try {
+      const result = await api.startCliStream('project', ['project', 'build', '--dir', state.activeProject]);
+      if (result?.ok) {
+        toast('构建完成', 'ok');
+      } else {
+        toast(result?.error || '构建失败', 'err');
+      }
+    } catch (error) {
+      projectLog(error.message || String(error), 'err');
+      toast('构建失败', 'err');
+    } finally {
+      button.disabled = false;
+    }
+  }
+
+  async function exportProject() {
+    if (!state.activeProject) return;
+    const name = state.projectInfo?.project?.name || 'project';
+    const output = await api.saveFileDialog(`${name}.luatos`, ['luatos']);
+    if (!output) return;
+    const result = await api.runCliJson(['project', 'export', '--dir', state.activeProject, '-o', output]);
+    if (result?.ok) {
+      toast(`已导出:${output}`, 'ok');
+    } else {
+      toast(result?.error || '导出失败', 'err');
+    }
+  }
+
+  async function setProjectSoc() {
+    if (!state.activeProject) return;
+    const selected = await api.openFileDialog(['soc']);
+    if (!selected) return;
+    await updateProjectConfig('flash.soc_file', selected);
+    toast('已设置项目固件', 'ok');
+  }
+
+  async function projectToFlash() {
+    if (!state.projectInfo) return;
+    const soc = state.projectInfo.flash?.soc_file;
+    if (!soc) {
+      toast('项目还没有设置 SOC 固件,请在项目配置里设置 flash.soc_file', 'err');
+      return;
+    }
+    const socPath = joinPath(state.activeProject, soc);
+    const scriptRelative = state.projectInfo.build?.script_dirs?.[0] || 'lua/';
+    const scriptDir = joinPath(state.activeProject, scriptRelative);
+    await window.__luatos.loadSoc(socPath);
+    window.__luatos.state.scriptDir = scriptDir;
+    const input = $('#script-dir');
+    if (input) input.value = scriptDir;
+    window.__luatos.updateFlashButton();
+    showView('flash');
+    toast('已带入项目固件和脚本目录', 'ok');
+  }
+
+  function bindProjectEvents() {
+    $('#btn-project-new').addEventListener('click', showProjectModal);
+    $('#btn-project-cancel').addEventListener('click', () => $('#project-modal').classList.add('hidden'));
+    $('#btn-project-create').addEventListener('click', () => {
+      createProject().catch((error) => {
+        $('#project-modal-error').textContent = error.message || String(error);
+      });
+    });
+    $('#btn-project-import').addEventListener('click', () => importProject().catch((error) => toast(error.message, 'err')));
+    $('#btn-project-root').addEventListener('click', async () => {
+      const paths = await ensurePaths();
+      await api.revealPath(paths.projects);
+    });
+    $('#project-filter').addEventListener('input', renderProjects);
+    $('#btn-project-save').addEventListener('click', () => saveProjectFile().catch((error) => toast(error.message, 'err')));
+    $('#btn-project-add-dir').addEventListener('click', () => addProjectDir().catch((error) => toast(error.message, 'err')));
+    $('#btn-project-add-file').addEventListener('click', () => addProjectFile().catch((error) => toast(error.message, 'err')));
+    $('#btn-project-build').addEventListener('click', () => buildProject().catch((error) => toast(error.message, 'err')));
+    $('#btn-project-libs').addEventListener('click', () => prepareProjectLibraries().catch((error) => toast(error.message, 'err')));
+    $('#btn-project-analyze').addEventListener('click', () => analyzeProject().catch((error) => toast(error.message, 'err')));
+    $('#btn-project-soc').addEventListener('click', () => setProjectSoc().catch((error) => toast(error.message, 'err')));
+    $('#btn-project-flash').addEventListener('click', () => projectToFlash().catch((error) => toast(error.message, 'err')));
+    $('#btn-project-reveal').addEventListener('click', () => {
+      if (state.activeProject) api.revealPath(state.activeProject);
+    });
+    $('#btn-project-delete').addEventListener('click', () => deleteActiveProject().catch((error) => toast(error.message, 'err')));
+    $('#btn-project-export').addEventListener('click', () => exportProject().catch((error) => toast(error.message, 'err')));
+
+    api.onCliEvent('project', (event) => {
+      if (!event || typeof event !== 'object') return;
+      if (event.type === 'progress') {
+        const message = event.message || event.stage || '';
+        if (message) projectLog(message, event.error ? 'err' : 'info');
+      } else if (event.type === 'resource_download') {
+        if (event.event === 'start_file') {
+          projectLog(`[${Number(event.index || 0) + 1}/${event.total || 1}] 下载 ${event.filename}(${formatSize(event.size)})`, 'cmd');
+        } else if (event.event === 'verified') {
+          projectLog(`SHA256 校验通过:${event.filename}`, 'ok');
+        } else if (event.event === 'extracted') {
+          projectLog(`已解压:${event.filename} → ${event.dest_dir}`, 'ok');
+        } else if (event.event === 'file_failed' || event.event === 'hash_mismatch') {
+          projectLog(`下载失败:${event.filename}`, 'err');
+        }
+      } else if (event.type === 'message') {
+        projectLog(event.message || '', event.level === 'error' ? 'err' : event.level === 'warn' ? 'warn' : 'info');
+      } else if (event.type === 'error') {
+        projectLog(event.message || '构建错误', 'err');
+      } else if (event.type === 'result') {
+        projectLog(event.status === 'ok' ? '构建成功' : `构建返回:${event.status}`, event.status === 'ok' ? 'ok' : 'err');
+      }
+    });
+    api.onCliLine('project', ({ line, source }) => {
+      if (line) projectLog(line, source === 'stderr' ? 'muted' : 'info');
+    });
+    api.onCliExit('project', ({ code, signal, error }) => {
+      if (error) projectLog(error, 'err');
+      else projectLog(`构建结束(code=${code}${signal ? `, signal=${signal}` : ''})`, code === 0 ? 'ok' : 'err');
+    });
+  }
+
+  /* ── Resources ──────────────────────────────────────────────── */
+
+  function resLog(text, level = 'info') {
+    const log = $('#res-log');
+    if (!log) return;
+    const line = document.createElement('span');
+    line.className = 'line';
+    const time = document.createElement('span');
+    time.className = 't';
+    time.textContent = new Date().toTimeString().slice(0, 8);
+    const body = document.createElement('span');
+    body.className = level;
+    body.textContent = text;
+    line.append(time, body);
+    log.appendChild(line);
+    log.scrollTop = log.scrollHeight;
+  }
+
+  function resClearLog() {
+    const log = $('#res-log');
+    if (log) log.textContent = '';
+  }
+
+  function setResProgress(percent, stage, message) {
+    const value = Math.max(0, Math.min(100, Number(percent) || 0));
+    $('#res-bar-fill').style.width = `${value}%`;
+    $('#res-percent').textContent = `${Math.round(value)}%`;
+    if (stage) $('#res-stage').textContent = stage;
+    if (message) resLog(message, 'info');
+  }
+
+  function renderResourceCategories() {
+    const container = $('#res-categories');
+    container.textContent = '';
+    $('#res-category-count').textContent = `${state.resources.categories.length} 类`;
+    for (const category of state.resources.categories) {
+      const button = document.createElement('button');
+      button.type = 'button';
+      button.className = `resource-category${category.name === state.resources.activeCategory ? ' active' : ''}`;
+      const name = document.createElement('strong');
+      name.textContent = category.name;
+      const desc = document.createElement('span');
+      desc.textContent = category.desc || '';
+      button.append(name, desc);
+      button.addEventListener('click', () => {
+        openResourceCategory(category.name).catch((error) => toast(error.message, 'err'));
+      });
+      container.appendChild(button);
+    }
+  }
+
+  async function loadResources() {
+    const paths = await ensurePaths();
+    state.resources.output = paths.resources;
+    $('#res-output-path').textContent = paths.resources;
+    const result = await api.runCliJson(['resource', 'list']);
+    if (!result?.ok) throw new Error(result?.error || '读取资源清单失败');
+    state.resources.categories = Array.isArray(result.data) ? result.data : [];
+    renderResourceCategories();
+    if (state.resources.activeCategory) {
+      await openResourceCategory(state.resources.activeCategory);
+    }
+  }
+
+  function renderResourceDetail(detail) {
+    const container = $('#res-detail');
+    container.textContent = '';
+    if (!detail?.childrens?.length) {
+      const empty = document.createElement('div');
+      empty.className = 'empty';
+      empty.textContent = '这个分类没有可下载内容';
+      container.appendChild(empty);
+      return;
+    }
+
+    for (const child of detail.childrens) {
+      const card = document.createElement('section');
+      card.className = 'resource-child';
+      const head = document.createElement('div');
+      head.className = 'resource-child-head';
+      const titleBox = document.createElement('div');
+      const title = document.createElement('h3');
+      title.textContent = child.name;
+      const desc = document.createElement('p');
+      desc.textContent = child.desc || '';
+      titleBox.append(title, desc);
+      const latest = document.createElement('button');
+      latest.type = 'button';
+      latest.className = 'primary small';
+      latest.textContent = '下载最新';
+      latest.addEventListener('click', () => {
+        downloadResource(detail.name, child.name, null, child.name).catch((error) => toast(error.message, 'err'));
+      });
+      head.append(titleBox, latest);
+      card.appendChild(head);
+
+      const versions = document.createElement('div');
+      versions.className = 'resource-versions';
+      for (const version of child.versions || []) {
+        const versionBox = document.createElement('div');
+        versionBox.className = 'resource-version';
+        const versionHead = document.createElement('div');
+        versionHead.className = 'resource-version-head';
+        const versionTitle = document.createElement('span');
+        versionTitle.textContent = version.name;
+        const download = document.createElement('button');
+        download.type = 'button';
+        download.className = 'secondary small';
+        download.textContent = '下载此版本';
+        download.addEventListener('click', () => {
+          downloadResource(detail.name, child.name, version.name, `${child.name} ${version.name}`).catch((error) =>
+            toast(error.message, 'err'),
+          );
+        });
+        versionHead.append(versionTitle, download);
+
+        const files = document.createElement('div');
+        files.className = 'resource-files';
+        for (const file of version.files || []) {
+          const row = document.createElement('div');
+          row.className = 'resource-file';
+          const name = document.createElement('span');
+          name.textContent = file.filename;
+          const size = document.createElement('span');
+          size.textContent = formatSize(file.size);
+          row.append(name, size);
+          files.appendChild(row);
+        }
+
+        versionBox.append(versionHead, files);
+        versions.appendChild(versionBox);
+      }
+      card.appendChild(versions);
+      container.appendChild(card);
+    }
+  }
+
+  async function openResourceCategory(name) {
+    state.resources.activeCategory = name;
+    renderResourceCategories();
+    const result = await api.runCliJson(['resource', 'list', name]);
+    if (!result?.ok) throw new Error(result?.error || '读取分类失败');
+    const detail = result.data;
+    state.resources.detail = detail;
+    $('#res-title').textContent = `${detail.name || name} · ${detail.desc || ''}`;
+    renderResourceDetail(detail);
+  }
+
+  async function downloadResource(category, sub, item, label) {
+    if (state.resources.busy) {
+      toast('已有下载任务正在运行', 'warn');
+      return;
+    }
+    const output = state.resources.output;
+    state.resources.busy = true;
+    resClearLog();
+    setResProgress(0, `准备下载 ${label}`, `目标目录:${output}`);
+    try {
+      const args = ['resource', 'download', category, sub];
+      if (item) args.push(item);
+      args.push('--output', output);
+      const result = await api.startCliStream('resource', args);
+      if (result?.ok) {
+        toast('资源下载完成', 'ok');
+      } else {
+        toast(result?.error || '资源下载失败', 'err');
+      }
+    } finally {
+      state.resources.busy = false;
+    }
+  }
+
+  function bindResourceEvents() {
+    $('#btn-res-refresh').addEventListener('click', () => loadResources().catch((error) => toast(error.message, 'err')));
+    $('#btn-res-choose').addEventListener('click', async () => {
+      const selected = await api.openFolderDialog();
+      if (selected) {
+        state.resources.output = selected;
+        $('#res-output-path').textContent = selected;
+        toast('下载目录已更新', 'ok');
+      }
+    });
+    $('#btn-res-output').addEventListener('click', async () => {
+      const paths = await ensurePaths();
+      await api.revealPath(state.resources.output || paths.resources);
+    });
+
+    api.onCliEvent('resource', (event) => {
+      if (!event || typeof event !== 'object') return;
+      if (event.type === 'resource_download') {
+        if (event.event === 'start_file') {
+          const index = Number(event.index || 0) + 1;
+          const total = Number(event.total || 1);
+          state.resources.currentSize = Number(event.size || 0);
+          setResProgress(0, `[${index}/${total}] ${event.filename}`, `开始下载 ${event.filename}(${formatSize(event.size)})`);
+        } else if (event.event === 'progress') {
+          const total = state.resources.currentSize || 1;
+          setResProgress((Number(event.downloaded || 0) / total) * 100, '', '');
+        } else if (event.event === 'verified') {
+          setResProgress(100, '', `SHA256 校验通过:${event.filename}`);
+        } else if (event.event === 'extracted') {
+          resLog(`已解压:${event.filename} → ${event.dest_dir}`, 'ok');
+        } else if (event.event === 'file_failed') {
+          resLog(`下载失败:${event.filename}`, 'err');
+        } else if (event.event === 'hash_mismatch') {
+          resLog(`SHA256 不匹配:${event.filename}`, 'err');
+        } else if (event.event === 'mirror_failed') {
+          resLog(`镜像失败:${event.mirror_url}(${event.filename})`, 'warn');
+        }
+      } else if (event.type === 'message') {
+        resLog(event.message || '', event.level === 'error' ? 'err' : event.level === 'warn' ? 'warn' : 'info');
+      } else if (event.type === 'error') {
+        resLog(event.message || '下载错误', 'err');
+      } else if (event.type === 'result') {
+        resLog(`下载结束:${event.status}`, event.status === 'ok' ? 'ok' : 'warn');
+      }
+    });
+    api.onCliLine('resource', ({ line, source }) => {
+      if (line) resLog(line, source === 'stderr' ? 'muted' : 'info');
+    });
+    api.onCliExit('resource', ({ code, signal, error }) => {
+      if (error) resLog(error, 'err');
+      else resLog(`下载进程结束(code=${code}${signal ? `, signal=${signal}` : ''})`, code === 0 ? 'ok' : 'err');
+    });
+  }
+
+  /* ── MCP ────────────────────────────────────────────────────── */
+
+  const MCP_TOOL_NAMES = [
+    'serial_list',
+    'guide_models',
+    'firmware_info',
+    'flash_firmware',
+    'resource_list',
+    'resource_download',
+    'project_list',
+    'project_create',
+    'project_import',
+    'project_info',
+    'project_config',
+    'project_analyze',
+    'project_prepare',
+    'project_build',
+    'project_export',
+    'project_deps',
+    'app_paths',
+  ];
+
+  async function loadMcp() {
+    const result = await api.mcpInfo();
+    state.mcp = result;
+    const config = $('#mcp-config');
+    const status = $('#mcp-status');
+    const tools = $('#mcp-tools');
+
+    tools.textContent = '';
+    for (const name of MCP_TOOL_NAMES) {
+      const chip = document.createElement('span');
+      chip.className = 'mcp-tool';
+      chip.textContent = name;
+      tools.appendChild(chip);
+    }
+
+    if (!result?.ok) {
+      status.textContent = '未找到 MCP 脚本';
+      config.textContent = '请确认 App 包内的 Resources/mcp/luatos-mcp.mjs 存在,或重新构建。';
+      $('#mcp-script').textContent = result?.script || '—';
+      $('#mcp-cli').textContent = result?.cli || '—';
+      return;
+    }
+
+    status.textContent = result.node ? `Node ${result.node}` : '未检测到 node';
+    config.textContent = JSON.stringify(result.config, null, 2);
+    $('#mcp-script').textContent = result.script || '—';
+    $('#mcp-cli').textContent = result.cli || '—';
+  }
+
+  async function copyMcpConfig() {
+    const text = $('#mcp-config').textContent;
+    if (!text) return;
+    try {
+      await navigator.clipboard.writeText(text);
+      toast('MCP 配置已复制', 'ok');
+    } catch {
+      const area = document.createElement('textarea');
+      area.value = text;
+      document.body.appendChild(area);
+      area.select();
+      document.execCommand('copy');
+      area.remove();
+      toast('MCP 配置已复制', 'ok');
+    }
+  }
+
+  /* ── Init ───────────────────────────────────────────────────── */
+
+  function init() {
+    $$('#tabs .tab').forEach((tab) => {
+      tab.addEventListener('click', () => showView(tab.dataset.view));
+    });
+    bindProjectEvents();
+    bindResourceEvents();
+    $('#btn-mcp-copy').addEventListener('click', () => copyMcpConfig().catch((error) => toast(error.message, 'err')));
+    $('#btn-mcp-refresh').addEventListener('click', () => loadMcp().catch((error) => toast(error.message, 'err')));
+
+    document.addEventListener('keydown', (event) => {
+      if (event.key === 'Escape') {
+        $('#project-modal')?.classList.add('hidden');
+      }
+    });
+  }
+
+  init();
+})();