diff --git a/docs/en/ui-guidelines.md b/docs/en/ui-guidelines.md index 187e7b8b..872e7742 100644 --- a/docs/en/ui-guidelines.md +++ b/docs/en/ui-guidelines.md @@ -111,9 +111,8 @@ Examples: | Plugin | Platform | Highlight | | --- | --- | --- | -| [`process-monitor`](../../extensions/process-monitor/src/index.ts) | Cross-platform | Full-width list + single-line status bar | +| [`process-monitor`](../../extensions/process-monitor/src/index.ts) | Cross-platform | Full-width list + dropdown filter + single-line status bar + kill action | | [`clipboard-manager`](../../extensions/clipboard-manager/src/index.tsx) | Cross-platform | Right-hand preview of actual clipboard content | -| [`kill-process`](../../extensions/kill-process/src/index.tsx) | Windows only | Dropdown filter + status bar + kill action | ### Layout 2: Left Navigation + Right Checkable Detail List diff --git a/docs/ui-guidelines.md b/docs/ui-guidelines.md index bb782919..99b4eec9 100644 --- a/docs/ui-guidelines.md +++ b/docs/ui-guidelines.md @@ -113,9 +113,8 @@ ZTools 是「呼出即用、用完即走」的效率工具:用户按下快捷 | 插件 | 平台 | 看点 | | --- | --- | --- | -| [`process-monitor`](../extensions/process-monitor/src/index.ts) | 跨平台 | 全宽列表 + 单行状态条 | +| [`process-monitor`](../extensions/process-monitor/src/index.ts) | 跨平台 | 全宽列表 + 下拉筛选 + 单行状态条 + 结束进程动作 | | [`clipboard-manager`](../extensions/clipboard-manager/src/index.tsx) | 跨平台 | 右侧预览剪贴板内容本身 | -| [`kill-process`](../extensions/kill-process/src/index.tsx) | 仅 Windows | 下拉筛选 + 状态条 + 结束进程动作 | ### 布局二:左侧导航 + 右侧可勾选明细 diff --git a/extensions/ai-image/plugin.json b/extensions/ai-image/plugin.json index 8cf86d2b..835db35b 100644 --- a/extensions/ai-image/plugin.json +++ b/extensions/ai-image/plugin.json @@ -2,7 +2,8 @@ "id": "ai-image", "name": "AI 图片修复", "description": "把 PNG、JPG、BMP 图片按 2 倍或 4 倍放大像素尺寸(普通插值放大,不是 AI,不提升清晰度),支持选择文件、文件夹或拖放导入,输出到原图所在目录且不覆盖已有文件。AI 超分辨率、去背景、人像修复暂不可用", - "version": "2.0.13", + "version": "2.0.14", + "minAppVersion": "1.1.8.0", "draft": true, "draftReason": "AI 超分辨率、去背景、人像修复需要客户端提供本地 AI 推理能力(模型与推理组件),当前客户端的图片处理接口只能做普通插值放大;等客户端提供该能力并在 Windows 上实测通过后再发布", "author": "ZTools Team", diff --git a/extensions/ai-image/src/i18n.ts b/extensions/ai-image/src/i18n.ts index 531c1c5c..adf889a7 100644 --- a/extensions/ai-image/src/i18n.ts +++ b/extensions/ai-image/src/i18n.ts @@ -90,6 +90,9 @@ const rawT = createTranslator( dropdownUnavailable: "{title}(暂不可用)", btnPickFiles: "选择文件", btnPickFolder: "选择文件夹", + btnRunBatch: "开始处理 ({count})", + btnProcessing: "处理中…", + tagProcessing: "处理中", wbTitle: "处理参数", wbScaleLabel: "放大倍率", wbScale2x: "2 倍", @@ -198,6 +201,9 @@ const rawT = createTranslator( dropdownUnavailable: "{title} (Unavailable)", btnPickFiles: "Select Files", btnPickFolder: "Select Folder", + btnRunBatch: "Process ({count})", + btnProcessing: "Processing…", + tagProcessing: "Processing", wbTitle: "Parameters", wbScaleLabel: "Scale Factor", wbScale2x: "2x", diff --git a/extensions/ai-image/src/index.ts b/extensions/ai-image/src/index.ts index dbd39ad6..d9e5c775 100644 --- a/extensions/ai-image/src/index.ts +++ b/extensions/ai-image/src/index.ts @@ -484,7 +484,9 @@ export function AiImageCommand() { const volRatio = Math.max(10, Math.min(100, Math.round((f.sizeBytes / maxKnownBytes) * 100))) accessories.push({ progress: { value: volRatio } }) } - if (outcome) { + if (isItemProcessing) { + accessories.push({ tag: { value: t('tagProcessing') } }) + } else if (outcome) { accessories.push( outcome.ok ? { tag: { value: outcome.resolution ? t('tagOutputWithRes', { res: outcome.resolution }) : t('tagOutput') } } @@ -628,28 +630,52 @@ export function AiImageCommand() { }), filterBar: FilterBar({ summaryText, - actions: [ - { - id: 'pick-files', - label: t('btnPickFiles'), - title: t('btnPickFiles'), - icon: Icon.Document, - style: 'secondary', - onAction: () => { - void handlePickFiles() - } - }, - { - id: 'pick-folder', - label: t('btnPickFolder'), - title: t('btnPickFolder'), - icon: Icon.Folder, - style: 'secondary', - onAction: () => { - void handlePickFolder() - } - } - ] + actions: + selectedFiles.length > 0 && activeEngine.available + ? [ + { + id: 'pick-files', + label: t('btnPickFiles'), + title: t('btnPickFiles'), + icon: Icon.Document, + style: 'secondary', + onAction: () => { + void handlePickFiles() + } + }, + { + id: 'run-batch', + label: isProcessing ? t('btnProcessing') : t('btnRunBatch', { count: selectedFiles.length }), + title: isProcessing ? t('btnProcessing') : t('btnRunBatch', { count: selectedFiles.length }), + style: 'primary', + disabled: isProcessing, + onAction: () => { + void runBatch(selectedFiles, true) + } + } + ] + : [ + { + id: 'pick-files', + label: t('btnPickFiles'), + title: t('btnPickFiles'), + icon: Icon.Document, + style: 'secondary', + onAction: () => { + void handlePickFiles() + } + }, + { + id: 'pick-folder', + label: t('btnPickFolder'), + title: t('btnPickFolder'), + icon: Icon.Folder, + style: 'secondary', + onAction: () => { + void handlePickFolder() + } + } + ] }), workbenchPanel: { title: t('wbTitle'), diff --git a/extensions/ai-image/src/native-ipc.ts b/extensions/ai-image/src/native-ipc.ts index 51576b99..13643277 100644 --- a/extensions/ai-image/src/native-ipc.ts +++ b/extensions/ai-image/src/native-ipc.ts @@ -174,11 +174,13 @@ function normalizeMethodResult(method: string, payload: DynamicBridge): DynamicB if (method === 'system_get_battery_status') { // 宿主约定 percent 超出 0-100(如 255)表示无电池或电量未知,不能改写成 100% + // 若宿主明确给出 hasBattery 布尔值,必须原样保留,仅在缺失时按合法电量推算 const rawPct = payload.percent - const hasBattery = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const validPct = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const hasBattery = typeof payload.hasBattery === 'boolean' ? payload.hasBattery : validPct return { ...payload, - percent: hasBattery ? rawPct : null, + percent: validPct ? rawPct : null, hasBattery } } @@ -489,6 +491,8 @@ export interface RealDirectoryScanResult extends Iterable approximate?: boolean /** 宿主实际遍历的条目数 */ visitedEntries?: number + /** 目录本身不存在(ENOENT) */ + missing?: boolean /** 读取失败的真实原因;已有文件仍可使用,但不能当作完整结果。 */ error?: string } @@ -497,6 +501,7 @@ interface ScanResultMeta { truncated?: boolean approximate?: boolean visitedEntries?: number + missing?: boolean } export interface ScanDirectoryTreeOptions { @@ -504,6 +509,10 @@ export interface ScanDirectoryTreeOptions { maxFiles?: number collectTopN?: number filterExt?: RegExp + /** 为 true 时,目录本身不存在(ENOENT)按空目录处理,不返回 error(权限拒绝/读取失败仍照常报错) */ + ignoreMissing?: boolean + /** Top-N 保留与排序方式:默认按体积降序,下载/录屏等时效场景可传 mtime-desc */ + sortBy?: 'size-desc' | 'mtime-desc' hostOverride?: DynamicBridge } @@ -519,8 +528,9 @@ function normalizeIndexedFileEntry(f: DynamicBridge): RealIndexedFileEntry { const sz = Number(f?.size ?? f?.sizeBytes ?? 0) const isDir = Boolean(f?.is_dir || f?.isDir || f?.isDirectory) const rawMtime = Number(f?.mtime ?? f?.mtimeMs ?? 0) - const mtimeMs = rawMtime > 1e11 ? rawMtime : rawMtime > 0 ? rawMtime * 1000 : Date.now() - const mtimeSec = rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime + const validMtime = Number.isFinite(rawMtime) && rawMtime > 0 + const mtimeMs = validMtime ? (rawMtime > 1e11 ? rawMtime : rawMtime * 1000) : 0 + const mtimeSec = validMtime ? (rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime) : 0 if (p && sz >= 0) realFileSizeCache.set(p, sz) return { name, @@ -551,6 +561,7 @@ function makeScanResult( subdirs, ...(meta.truncated ? { truncated: true } : {}), ...(meta.approximate ? { approximate: true } : {}), + ...(meta.missing ? { missing: true } : {}), ...(typeof meta.visitedEntries === 'number' ? { visitedEntries: meta.visitedEntries } : {}), [Symbol.iterator]() { return files[Symbol.iterator]() @@ -609,13 +620,40 @@ export async function scanRealDirectoryTree( return result.error ? { ...result.scan, error: result.error } : result.scan } +/** 仅当正则明确声明了扩展名(含 `\.`)时提取后缀列表,避免把 `thumbcache|iconcache` 等文件名关键词误拆成假扩展名 */ +function extractExtensionTokensFromFilter(filterExt: RegExp): string[] { + const src = filterExt.source + if (!src.includes('\\.')) return [] + const afterDot = src.slice(src.indexOf('\\.') + 2) + const rawTokens = afterDot.match(/[a-z0-9]{1,8}/gi) || [] + const seen = new Set() + const out: string[] = [] + for (const token of rawTokens) { + const lower = token.toLowerCase() + if (!lower || seen.has(lower)) continue + seen.add(lower) + out.push(lower) + } + return out +} + +function isMissingDirectoryError(res: { error?: string; errorCode?: string; errorDetails?: Record }): boolean { + if (res.errorDetails?.reason === 'ENOENT' || res.errorCode === 'ENOENT') return true + const msg = String(res.error || '') + return /Directory does not exist|ENOENT/i.test(msg) +} + /** 一次界面扫描的错误汇总;多个目录并行扫描时保留可读目录的结果。 */ export function createDirectoryScanner(hostOverride?: DynamicBridge) { const failures = new Map() return { async scan(dir: string, options: number | ScanDirectoryTreeOptions = 160) { const result = await scanRealDirectoryTree(dir, options, hostOverride) - const error = result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') + const ignoreMissing = typeof options === 'object' && options !== null && options.ignoreMissing === true + const error = + result.missing && ignoreMissing + ? '' + : result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') if (error) failures.set(dir, error) else failures.delete(dir) return result @@ -648,26 +686,38 @@ async function scanDirectoryTreeWithError( const safeLimit = Math.min(200, Math.max(1, Math.floor(rawLimit || 160))) const hostOverride = opts.hostOverride const filterExt = opts.filterExt + const ignoreMissing = opts.ignoreMissing === true const dirQuery = `dir:${targetDir}` try { let rawPayload: DynamicBridge = null + const searchParams: Record = { + query: dirQuery, + limit: safeLimit, + ...(opts.sortBy ? { sortBy: opts.sortBy } : {}) + } const res = await callHostTransport( 'system_search_files', - { query: dirQuery, limit: safeLimit }, + searchParams, hostOverride ) - if (res.ok && res.data) { + if (res.ok && res.data && res.data.degraded !== true) { rawPayload = res.data + } else if (!res.ok && ignoreMissing && isMissingDirectoryError(res)) { + const missingScan = makeScanResult([], 0, 0, [], { missing: true }) + return { scan: missingScan } } - if (!rawPayload && !hostOverride && typeof window !== 'undefined') { + if (!rawPayload && !hostOverride && res.errorCode === 'METHOD_NOT_AVAILABLE' && typeof window !== 'undefined') { const w = window as DynamicBridge if (typeof w.__ztoolsLauncher?.searchFiles === 'function') { const rawOuter = await w.__ztoolsLauncher.searchFiles(dirQuery, safeLimit) - rawPayload = + const candidate = rawOuter && typeof rawOuter === 'object' && 'data' in rawOuter && rawOuter.data ? rawOuter.data : rawOuter + if (candidate && candidate.degraded !== true && candidate.success !== false) { + rawPayload = candidate + } } } @@ -678,29 +728,32 @@ async function scanDirectoryTreeWithError( let files: RealIndexedFileEntry[] = rawPayload.files.map(normalizeIndexedFileEntry) if (filterExt instanceof RegExp) { files = files.filter(f => !f.isDir && (filterExt.test(f.name) || filterExt.test(f.ext))) - // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索目标扩展名 + // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索明确声明的目标扩展名 if (files.length === 0 && !hostOverride) { - const extTokens = (filterExt.source.match(/[a-z0-9]{2,5}/gi) || []) - .filter(t => !['thumbcache', 'iconcache'].includes(t.toLowerCase())) - .slice(0, 4) - // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 - const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() - const extraLists = await Promise.all( - extTokens.map(ext => searchRealIndexedFiles(`.${ext.toLowerCase()}`, 30, hostOverride)) - ) - const seen = new Set() - for (const list of extraLists) { - for (const item of list) { - if (!item.isDir && item.size > 0 && !seen.has(item.path)) { - if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { - seen.add(item.path) - files.push(item) + const extTokens = extractExtensionTokensFromFilter(filterExt) + if (extTokens.length > 0) { + // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 + const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() + const extraLists = await Promise.all( + extTokens.map(ext => searchRealIndexedFiles(`.${ext}`, 30, hostOverride)) + ) + const seen = new Set() + for (const list of extraLists) { + for (const item of list) { + if (!item.isDir && item.size > 0 && !seen.has(item.path)) { + if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { + seen.add(item.path) + files.push(item) + } } } } } } } + // 先基于过滤后的完整命中集合计算总文件数与总字节数,再按 collectTopN 裁剪样本列表 + const matchedCount = files.length + const matchedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) if (typeof opts.collectTopN === 'number' && opts.collectTopN > 0 && files.length > opts.collectTopN) { files = files.slice(0, opts.collectTopN) } @@ -714,11 +767,10 @@ async function scanDirectoryTreeWithError( ...(s.approximate === true ? { approximate: true } : {}) })) : [] - const computedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) const totalFilesCount = - filterExt instanceof RegExp ? files.length : Number(rawPayload.total_matches ?? files.length) + filterExt instanceof RegExp ? matchedCount : Number(rawPayload.total_matches ?? matchedCount) const totalBytesCount = - filterExt instanceof RegExp ? computedBytes : Number(rawPayload.total_bytes ?? computedBytes) + filterExt instanceof RegExp ? matchedBytes : Number(rawPayload.total_bytes ?? matchedBytes) const visited = Number(rawPayload.visited_entries) return { scan: makeScanResult(files, totalFilesCount, totalBytesCount, subdirs, { @@ -1817,8 +1869,6 @@ export async function writeRealClipboardText(text: string, hostOverride?: Dynami const payload = { text: String(text || '') } const res = await callHostTransport('clipboard_copy_text', payload, hostOverride) if (res.ok) return true - const fallbackRes = await callHostTransport('clipboard_write_text', payload, hostOverride) - if (fallbackRes.ok) return true try { if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) { await navigator.clipboard.writeText(String(text || '')) diff --git a/extensions/ai-image/tests/ai-image.ui.test.mjs b/extensions/ai-image/tests/ai-image.ui.test.mjs index 67515c43..f0eeed1d 100644 --- a/extensions/ai-image/tests/ai-image.ui.test.mjs +++ b/extensions/ai-image/tests/ai-image.ui.test.mjs @@ -386,7 +386,11 @@ test('ai-image UI: 导入中清空后结果被丢弃且不弹导入成功提示' }) }) - const importPromise = view.tree().props.filterBar.props.actions[1].onAction() + // 已有选中图片且引擎可用时,顶栏第 2 按钮切换为主操作「开始处理」,此时通过动作面板触发「选择文件夹…」 + assert.equal(view.tree().props.filterBar.props.actions[1].id, 'run-batch') + const pickFolderAction = view.actions().find(a => a.props.title === '选择文件夹…') + assert.ok(pickFolderAction, '动作面板应保留「选择文件夹…」入口') + const importPromise = pickFolderAction.props.onAction() await tick() assert.match(summary(view), /正在导入/) diff --git a/extensions/ai-video/README.md b/extensions/ai-video/README.md index 0915d5c9..b794fdb2 100644 --- a/extensions/ai-video/README.md +++ b/extensions/ai-video/README.md @@ -1,13 +1,13 @@ # AI 视频增强 -列出“视频”“下载”“桌面”文件夹里的视频,把勾选的视频交给客户端重新编码为 mp4。目前客户端只用 ffmpeg 做普通转码,界面上列出的补帧、超分、降噪模型都不会执行。 +把手动导入的视频交给客户端重新编码为 mp4。目前客户端只用 ffmpeg 做普通转码,界面上列出的补帧、超分、降噪模型都不会执行。 ## 使用 - 命令:在启动框搜索“AI 视频增强”打开。 -- 列表列出这三个文件夹(含子文件夹)里的 mp4、mkv、mov、avi、flv、webm、wmv、ts、m4v 文件:每个文件夹只从扫描到的较大文件里挑选,最多 40 个,不保证列全。列表按体积从大到小排列,扫描后默认全部勾选。 -- Enter:确认后处理全部勾选的视频;Ctrl+Enter:在资源管理器中定位文件;Ctrl+K:打开动作面板,可只处理当前视频。 -- 输出文件名为 `<原文件名>_processed.mp4`,保存在扫描到该视频的那个文件夹(“视频”“下载”或“桌面”)的第一层;原文件不改动。 +- 打开后初始列表为空,通过顶部「选择文件」「选择文件夹」或直接拖入/粘贴导入 mp4、mkv、mov、avi、flv、webm、wmv、ts、m4v 视频或 png、jpg、jpeg、webp 参考图(文件夹支持递归导入其中的匹配文件)。 +- `Enter`:确认后处理全部勾选的视频;`Ctrl+Enter`:在资源管理器中定位文件;`Ctrl+K`:打开动作面板,可只处理当前视频、从列表移除(`Ctrl+Backspace`,不删除磁盘文件)、全选(`Ctrl+A`)或清空列表(`Ctrl+Shift+Backspace`)。 +- 输出文件名为 `<原文件名>_<目标帧率>_<目标分辨率>.mp4`,保存在原视频所在目录;原文件不改动。 - 已存在的同名输出文件会被覆盖,转换失败时会被删除。 - 界面上选择的模型、目标帧率、目标分辨率、编码器和“场景切换防伪影保护”目前都不生效。 - 需要自行安装 ffmpeg,并能在命令行直接运行;找不到 ffmpeg 时提示“本机未检测到 ffmpeg”。单个文件转换超过 60 秒会中止并报错。 diff --git a/extensions/ai-video/plugin.json b/extensions/ai-video/plugin.json index bb5f96f7..6203f247 100644 --- a/extensions/ai-video/plugin.json +++ b/extensions/ai-video/plugin.json @@ -2,7 +2,8 @@ "id": "ai-video", "name": "AI 视频增强", "description": "本地 AI 视频画质超清放大、60/120 帧流畅补帧与低清视频画质修复", - "version": "2.0.9", + "version": "2.0.10", + "minAppVersion": "1.1.8.0", "draft": true, "draftReason": "尚未接入 RIFE、Real-CUGAN 等 AI 视频处理引擎;现有宿主只能普通转码,不能兑现补帧、超分和降噪。完成模型执行、取消与产物验证后再启用", "author": "ZTools Team", @@ -15,7 +16,10 @@ "permissions": [ "fs", "video", - "system" + "system", + "dialog", + "shell", + "clipboard" ], "requireAdmin": false, "nativeComponents": [], @@ -28,5 +32,14 @@ } ], "revoked": true, - "revokedReason": "AI 视频补帧、超分与降噪引擎尚未接入,当前版本无法完成所列处理任务,暂时下架。" + "revokedReason": "AI 视频补帧、超分与降噪引擎尚未接入,当前版本无法完成所列处理任务,暂时下架。", + "categoryId": "media", + "defaultLocale": "zh-CN", + "i18n": { + "en-US": { + "name": "AI Video Enhancer", + "description": "Local AI video super-resolution upscaling, 60/120 FPS frame interpolation, and low-quality video restoration.", + "revokedReason": "AI video frame interpolation, super-resolution, and denoising engines are not yet integrated; this version cannot perform the advertised tasks and has been temporarily revoked." + } + } } diff --git a/extensions/multi-download/src/file-import.ts b/extensions/ai-video/src/file-import.ts similarity index 84% rename from extensions/multi-download/src/file-import.ts rename to extensions/ai-video/src/file-import.ts index fc49b2ca..ef7929eb 100644 --- a/extensions/multi-download/src/file-import.ts +++ b/extensions/ai-video/src/file-import.ts @@ -89,11 +89,11 @@ const FILE_IMPORT_MESSAGES: Record `${count} already in list`, - noteIgnoredUnsupported: (count) => `ignored ${count} unsupported ${count === 1 ? 'file' : 'files'}`, + noteIgnoredUnsupported: (count) => `ignored ${count} unsupported file(s)`, noteTruncated: 'too many files, only partially imported', - noteFailedDirs: (count) => `${count} ${count === 1 ? 'subfolder' : 'subfolders'} could not be read`, + noteFailedDirs: (count) => `${count} subfolder(s) could not be read`, noteSep: '; ', - addedFilesTitle: (count) => `Added ${count} ${count === 1 ? 'file' : 'files'}`, + addedFilesTitle: (count) => `Added ${count} file(s)`, allAlreadyInListTitle: 'These files are already in the list', noImportableFilesTitle: 'No importable files found', supportedFormats: (formats) => `Supports ${formats}` @@ -109,13 +109,7 @@ function fileImportStrings() { export type FileImportTransport = ( method: string, params: Record -) => Promise<{ - ok: boolean - data?: unknown - error?: string - errorCode?: string - errorDetails?: Record -}> +) => Promise<{ ok: boolean; data?: unknown; error?: string }> export interface FileImportRules { /** 允许的扩展名('.png' 或 'png',不区分大小写);不传或为空表示不限 */ @@ -244,95 +238,23 @@ export function isVolumeRoot(p: string): boolean { return /^[A-Za-z]:[\\/]?$/.test(trimmed) || trimmed === '/' } -function extractFileErrorMeta(error: unknown): { code: string; hostCode: string; text: string } { - if (typeof error === 'string') return { code: '', hostCode: '', text: error.trim() } - if (error instanceof Error) { - const rec = asRecord(error) - const code = typeof rec?.errorCode === 'string' ? rec.errorCode.trim() : typeof rec?.code === 'string' ? rec.code.trim() : '' - const details = asRecord(rec?.errorDetails) ?? asRecord(rec?.details) - const hostCode = typeof details?.hostCode === 'string' ? details.hostCode.trim() : '' - return { code, hostCode, text: error.message.trim() } - } - const rec = asRecord(error) - if (!rec) return { code: '', hostCode: '', text: String(error ?? '').trim() } - const nestedErr = asRecord(rec.error) - const code = - (typeof rec.errorCode === 'string' && rec.errorCode.trim()) || - (typeof rec.code === 'string' && rec.code.trim()) || - (typeof nestedErr?.errorCode === 'string' && nestedErr.errorCode.trim()) || - (typeof nestedErr?.code === 'string' && nestedErr.code.trim()) || - '' - const details = asRecord(rec.errorDetails) ?? asRecord(rec.details) ?? asRecord(nestedErr?.details) - const hostCode = typeof details?.hostCode === 'string' ? details.hostCode.trim() : '' - const text = - (typeof rec.error === 'string' && rec.error.trim()) || - (typeof nestedErr?.message === 'string' && nestedErr.message.trim()) || - (typeof rec.message === 'string' && rec.message.trim()) || - '' - return { code, hostCode, text } -} - -/** 把宿主常见错误翻译成用户看得懂的提示:优先按 code / details.hostCode 分支,无码时兼容老宿主中文文案 */ -export function friendlyFileError(error: unknown, fallback?: string): string { +/** 把宿主常见错误翻译成用户看得懂的提示 */ +export function friendlyFileError(error: unknown): string { const s = fileImportStrings() - const { code, hostCode, text } = extractFileErrorMeta(error) - const upperCode = code.toUpperCase() - const upperHostCode = hostCode.toUpperCase() - - if (upperHostCode === 'CAPABILITY_LIMIT_EXCEEDED' || upperCode === 'CAPABILITY_LIMIT_EXCEEDED') { - return s.tooManyCapabilities - } - if ( - upperHostCode === 'PATH_NOT_AUTHORIZED' || - upperHostCode === 'FILE_AUTH_EXPIRED' || - upperHostCode === 'CAPABILITY_WINDOW_CLOSED' || - upperHostCode === 'AUTH_EXPIRED' || - upperCode === 'PATH_NOT_AUTHORIZED' || - upperCode === 'FILE_AUTH_EXPIRED' - ) { - return s.authExpired - } - if ( - upperHostCode === 'DIRECTORY_ENTRIES_LIMIT_EXCEEDED' || - upperHostCode === 'DIR_ENTRIES_LIMIT' || - upperCode === 'DIRECTORY_ENTRIES_LIMIT_EXCEEDED' - ) { - return s.dirEntriesLimit - } - if ( - upperCode === 'METHOD_NOT_FOUND' || - upperCode === 'METHOD_NOT_AVAILABLE' || - upperHostCode === 'METHOD_NOT_FOUND' || - upperHostCode === 'METHOD_NOT_AVAILABLE' - ) { - return s.upgradeRequired - } - if (/METHOD_NOT_FOUND|METHOD_NOT_AVAILABLE|is not a function/.test(text)) { - return s.upgradeRequired - } - - // 通用外壳错误码(如 NATIVE_CALL_FAILED / HOST_CALL_ERROR)未命中专用语义码时,降级兼容老宿主中文提示 - // i18n-allow: legacy host fallback + const text = error instanceof Error ? error.message : String(error ?? '') if (/capability\s*数量超过上限/i.test(text)) { return s.tooManyCapabilities } - // i18n-allow: legacy host fallback if (/路径未由当前窗口授权|文件授权窗口已关闭/.test(text)) { return s.authExpired } - // i18n-allow: legacy host fallback if (/目录条目超过\s*10000/.test(text)) { return s.dirEntriesLimit } - // i18n-allow: legacy host fallback - if (/未知方法/.test(text)) { + if (/METHOD_NOT_FOUND|METHOD_NOT_AVAILABLE|未知方法|is not a function/.test(text)) { return s.upgradeRequired } - - if (text && (getLocale() === 'zh-CN' || !/[\u4e00-\u9fa5]/.test(text))) { - return text - } - return fallback || s.fileOperationFailed + return text || s.fileOperationFailed } interface ResolvedRules { @@ -463,7 +385,7 @@ export async function collectFolderFiles( const entries = res.ok ? parseDirectoryListing(dir, res.data) : null if (!entries) { const s = fileImportStrings() - const error = res.ok ? s.invalidDirPayload : friendlyFileError(res, s.readFolderFailed) + const error = friendlyFileError(res.ok ? s.invalidDirPayload : res.error || s.readFolderFailed) if (dir === root) return emptyResult({ error }) result.failedDirs.push({ path: dir, error }) continue @@ -586,7 +508,7 @@ export async function pickFiles( params.filters = `${options.filterName || s.supportedFilesFilter}|${resolved.extensions.map((e) => e.slice(1)).join(';')}` } const res = await transport('window_show_open_dialog', params) - if (!res.ok) return emptyResult({ error: friendlyFileError(res, fileImportStrings().openFileDialogFailed) }) + if (!res.ok) return emptyResult({ error: friendlyFileError(res.error || fileImportStrings().openFileDialogFailed) }) if (asRecord(res.data)?.canceled === true) return emptyResult({ canceled: true }) const paths = extractDialogPaths(res.data) if (paths.length === 0) return emptyResult({ error: fileImportStrings().openFileDialogNoPaths }) @@ -603,7 +525,7 @@ export async function pickFolder( const params: Record = { title: options.title } if (options.defaultPath) params.defaultPath = options.defaultPath const res = await transport('window_show_select_folder_dialog', params) - if (!res.ok) return { canceled: false, error: friendlyFileError(res, fileImportStrings().openFolderDialogFailed) } + if (!res.ok) return { canceled: false, error: friendlyFileError(res.error || fileImportStrings().openFolderDialogFailed) } const record = asRecord(res.data) if (record?.canceled === true) return { canceled: true } const folderPath = typeof record?.folderPath === 'string' ? record.folderPath.trim() : '' @@ -793,25 +715,10 @@ export function adaptPreloadTransport( ): FileImportTransport { const dialogTimeout = options.dialogTimeoutMs ?? 300_000 const fileTimeout = options.fileTimeoutMs ?? 30_000 - const extractErr = (error: unknown): { error: string; errorCode?: string; errorDetails?: Record } => { + const extractErr = (error: unknown): string => { const rec = asRecord(error) - if (rec) { - const errorCode = - typeof rec.errorCode === 'string' && rec.errorCode.trim() - ? rec.errorCode.trim() - : typeof rec.code === 'string' && rec.code.trim() - ? rec.code.trim() - : undefined - const errorDetails = asRecord(rec.errorDetails) ?? asRecord(rec.details) ?? undefined - return { - error: String(rec.message || rec.code || fileImportStrings().clientCallFailed), - ...(errorCode ? { errorCode } : {}), - ...(errorDetails ? { errorDetails } : {}) - } - } - return { - error: typeof error === 'string' && error.trim() ? error.trim() : fileImportStrings().clientCallFailed - } + if (rec) return String(rec.message || rec.code || fileImportStrings().clientCallFailed) + return typeof error === 'string' && error.trim() ? error.trim() : fileImportStrings().clientCallFailed } return async (method, params) => { if (!caller) return { ok: false, error: options.notInClientMessage } @@ -820,41 +727,17 @@ export function adaptPreloadTransport( const raw = await caller(method, params, timeoutMs) const rec = asRecord(raw) if (!rec) return { ok: false, error: fileImportStrings().clientInvalidResult } - if (rec.success === false) return { ok: false, ...extractErr(rec.error) } + if (rec.success === false) return { ok: false, error: extractErr(rec.error) } const outer = 'data' in rec ? rec.data : rec const outerRec = asRecord(outer) if (!outerRec) return { ok: true, data: outer } - if (outerRec.success === false) return { ok: false, ...extractErr(outerRec.error) } + if (outerRec.success === false) return { ok: false, error: extractErr(outerRec.error) } const inner = asRecord(outerRec.data) ?? outerRec - if (inner.success === false || inner.ok === false) return { ok: false, ...extractErr(inner.error) } + if (inner.success === false || inner.ok === false) return { ok: false, error: extractErr(inner.error) } return { ok: true, data: inner } } catch (error) { - const errRec = asRecord(error) - const code = - typeof errRec?.errorCode === 'string' && errRec.errorCode.trim() - ? errRec.errorCode.trim() - : typeof errRec?.code === 'string' && errRec.code.trim() - ? errRec.code.trim() - : '' - const details = asRecord(errRec?.errorDetails) ?? asRecord(errRec?.details) const message = error instanceof Error ? error.message : String(error) - const isUnsupportedByCode = code === 'METHOD_NOT_FOUND' || code === 'METHOD_NOT_AVAILABLE' - const isUnsupportedByEn = /^Client does not support /i.test(message) - // i18n-allow: legacy host fallback - const isUnsupportedByLegacyZh = !code && /^客户端不支持 /.test(message) - if (isUnsupportedByCode || isUnsupportedByEn || isUnsupportedByLegacyZh) { - return { - ok: false, - error: `METHOD_NOT_AVAILABLE: ${method}`, - ...(isUnsupportedByCode ? { errorCode: 'METHOD_NOT_AVAILABLE' } : {}) - } - } - return { - ok: false, - error: message, - ...(code ? { errorCode: code } : {}), - ...(details ? { errorDetails: details } : {}) - } + return { ok: false, error: /^(?:客户端不支持 |Client does not support )/i.test(message) ? `METHOD_NOT_AVAILABLE: ${method}` : message } } } } diff --git a/extensions/ai-video/src/host-compat.ts b/extensions/ai-video/src/host-compat.ts new file mode 100644 index 00000000..88139614 --- /dev/null +++ b/extensions/ai-video/src/host-compat.ts @@ -0,0 +1,126 @@ +/** + * 旧版客户端兼容:插件运行在比自己更旧的 ZTools 里时,给出明确的升级提示或安全的退路。 + * + * - 插件里的 `@ztools/declarative-ui` 由客户端在运行时提供,SDK 里新增的方法在旧客户端上并不存在; + * - 宿主接口在旧客户端上不存在时返回「未知方法」,这里统一换成用户看得懂的升级提示。 + */ + +export const HOST_UPGRADE_HINT = '当前 ZTools 版本过低,请升级到最新版本后再试' + +/** 宿主是否因为不认识这个接口而失败(旧客户端) */ +export function isHostMethodMissing(error: unknown): boolean { + const text = error instanceof Error ? error.message : String(error ?? '') + return /METHOD_NOT_FOUND|METHOD_NOT_AVAILABLE|未知方法|is not a function/.test(text) +} + +/** 生成「某功能需要新版客户端」的报错 */ +export function hostUpgradeError(feature: string): Error { + return new Error(`${feature}需要新版 ZTools,${HOST_UPGRADE_HINT}`) +} + +export interface UpdatableStorage { + getItem(key: string): Promise + setItem(key: string, value: unknown): Promise + updateItem?: (key: string, update: (current: unknown) => T) => Promise +} + +/** + * 读出最新值、修改后写回。 + * 客户端提供 updateItem 时用它保证多窗口不互相覆盖;旧客户端没有时退回读后写(与旧版插件行为一致)。 + */ +export async function updateStorageItem( + storage: UpdatableStorage, + key: string, + update: (current: unknown) => T +): Promise { + if (typeof storage.updateItem === 'function') return storage.updateItem(key, update) + const current = await storage.getItem(key) + const next = update(current) + if (JSON.stringify(next) !== JSON.stringify(current)) await storage.setItem(key, next) + return next +} + +export interface CompatFileInputConfig { + /** 允许的扩展名列表(如 ['.png', '.jpg']),不填表示允许任意扩展名 */ + extensions?: string[] + /** 是否允许接收文件夹(默认 false) */ + allowDirectories?: boolean + /** 是否允许将剪贴板纯位图(截图)落盘为临时 PNG 接收(默认 false) */ + allowClipboardImage?: boolean + /** 拖放遮罩提示文案 */ + dropTitle?: string + dropSubtitle?: string + /** 双模粘贴(文件优先,纯文本回退):当焦点位于空搜索框或非输入区域且剪贴板仅含文本时触发 */ + onTextPaste?: (text: string) => boolean | void | Promise +} + +export interface CompatFileInputPayload { + files: string[] + source: 'drop' | 'paste' | 'launch' + targetFieldId?: string + rejectedCount?: number +} + +/** + * 从宿主事件信封、FileInputPayload 或裸路径数组中安全提取规范化非空文件路径列表 + */ +export function extractCompatInputFiles(payload: unknown): string[] { + if (Array.isArray(payload)) { + return payload + .map((item) => { + if (typeof item === 'string') return item.trim() + if (item && typeof item === 'object' && typeof (item as { path?: unknown }).path === 'string') { + return String((item as { path: string }).path).trim() + } + return '' + }) + .filter(Boolean) + } + if (!payload || typeof payload !== 'object') return [] + const record = payload as Record + const inner = record.payload && typeof record.payload === 'object' ? (record.payload as Record) : record + if (Array.isArray(inner.files)) return extractCompatInputFiles(inner.files) + if (Array.isArray(inner.paths)) return extractCompatInputFiles(inner.paths) + return [] +} + +/** + * 判断当前宿主渲染器是否已原生支持栈顶 单点消费路由。 + * - 新版宿主会注入 window.__ztoolsDeclarativeFeatures.fileInput === true; + * - 旧版宿主未注入该标记时,插件可保留原有的 plugin_files_dropped 事件订阅作为回退,避免新旧宿主双重触发。 + */ +export function isDeclarativeFileInputSupported(): boolean { + if (typeof window === 'undefined') return true + const w = window as unknown as { __ztoolsDeclarativeFeatures?: { fileInput?: boolean } } + return w.__ztoolsDeclarativeFeatures?.fileInput === true +} + +/** + * 生成可直接展开到 /
/ 的属性对象。 + * 旧版客户端会静默忽略未知的 descriptor.props.fileInput / onFileInput 属性而不报错; + * 新版客户端由 DeclarativeView 栈顶单点消费拖放与 Ctrl+V / ⌘V 粘贴输入。 + */ +export function createCompatFileInputProps( + onFiles: (files: string[], payload: CompatFileInputPayload) => void | Promise, + config?: CompatFileInputConfig +): { + fileInput: CompatFileInputConfig + onFileInput: (payload: CompatFileInputPayload | string[]) => void +} { + return { + fileInput: config ? { ...config } : {}, + onFileInput: (raw: CompatFileInputPayload | string[]) => { + const files = extractCompatInputFiles(raw) + if (files.length === 0) return + const normalizedPayload: CompatFileInputPayload = Array.isArray(raw) + ? { files, source: 'drop' } + : { + files, + source: raw?.source || 'drop', + ...(typeof raw?.targetFieldId === 'string' && raw.targetFieldId ? { targetFieldId: raw.targetFieldId } : {}), + ...(typeof raw?.rejectedCount === 'number' ? { rejectedCount: raw.rejectedCount } : {}) + } + void onFiles(files, normalizedPayload) + } + } +} diff --git a/extensions/ai-video/src/index.ts b/extensions/ai-video/src/index.ts index cf996529..7cf19764 100644 --- a/extensions/ai-video/src/index.ts +++ b/extensions/ai-video/src/index.ts @@ -6,22 +6,39 @@ import { Clipboard, useState, useEffect, + useRef, showToast, Toast, confirmAlert, FilterBar } from '@ztools/declarative-ui' +import type { ListItemAccessory } from '@ztools/declarative-ui' +import { + FileImportResult, + NormalizedFileInput, + createImportInputProps, + isVolumeRoot, + mergeByPath, + normalizeFileInput, + summarizeImport +} from './file-import.js' +import { isDeclarativeFileInputSupported } from './host-compat.js' import { AI_VIDEO_MODELS, - INITIAL_AI_VIDEO_FILES, + AI_VIDEO_SUPPORTED_TEXT, + AiVideoBatchResult, AiVideoFileItem, - AiVideoModelPreset, - fetchAiVideoWorkspace, + collectAiVideoFolderFiles, + executeAiVideoBatch, + expandAiVideoInputPaths, + formatAiVideoError, formatBytes, + importedFileToAiVideoItem, + isAiVideoHostReady, openAiVideoLocation, - runAiVideoBatch + pickAiVideoFolder, + selectAiVideoFiles } from './logic.js' -import { isRealElectronHost } from './native-ipc.js' export * from './logic.js' @@ -37,6 +54,39 @@ const FPS_LABEL_MAP: Record = { source: '保持原帧率' } +interface LegacyEventBridge { + ztools?: { + events?: { + on?: (eventName: string, handler: (raw: unknown) => void) => (() => void) | void + } + } +} + +interface ImportProgressState { + active: boolean + visitedDirs: number + matchedFiles: number +} + +const IDLE_IMPORT_STATE: ImportProgressState = { active: false, visitedDirs: 0, matchedFiles: 0 } + +function renderVideoSize(sizeBytes: number | null): string { + return sizeBytes === null ? '大小未识别' : formatBytes(sizeBytes) +} + +function summarizeSelectedVideoSize(selected: readonly AiVideoFileItem[]): string { + if (selected.length === 0) return '0 B' + let sum = 0 + let known = false + for (const item of selected) { + if (item.sizeBytes !== null) { + sum += item.sizeBytes + known = true + } + } + return known ? formatBytes(sum) : '大小未识别' +} + export function AiVideoCommand() { const [searchText, setSearchText] = useState('') const [activeModelId, setActiveModelId] = useState(AI_VIDEO_MODELS[0].id) @@ -44,86 +94,319 @@ export function AiVideoCommand() { const [targetResolution, setTargetResolution] = useState<'4k_2160p' | '2k_1440p' | '1080p_fhd'>('4k_2160p') const [videoEncoder, setVideoEncoder] = useState<'hevc_nvenc' | 'h264' | 'av1'>('hevc_nvenc') const [sceneChangeProtection, setSceneChangeProtection] = useState(true) - const isRealHost = isRealElectronHost() - const initialFiles = isRealHost ? [] : INITIAL_AI_VIDEO_FILES - const [files, setFiles] = useState(initialFiles) - const [checkedIds, setCheckedIds] = useState(initialFiles.map(f => f.id)) - const [models, setModels] = useState(AI_VIDEO_MODELS) - const [, setScannedDirs] = useState([]) - const [isLoading, setIsLoading] = useState(false) - - async function refreshWorkspace(showIndicator = false) { - if (showIndicator) setIsLoading(true) + const [files, setFiles] = useState([]) + const [checkedIds, setCheckedIds] = useState([]) + const [importState, setImportState] = useState(IDLE_IMPORT_STATE) + const [isProcessing, setIsProcessing] = useState(false) + const [processingIds, setProcessingIds] = useState([]) + + const filesRef = useRef([]) + const mountedRef = useRef(true) + const processingRef = useRef(false) + const processingSetRef = useRef>(new Set()) + const batchTokenRef = useRef(0) + const abortRef = useRef(null) + + const syncFiles = (compute: (current: AiVideoFileItem[]) => AiVideoFileItem[]) => { + const updated = compute(filesRef.current) + filesRef.current = updated + setFiles(updated) + return updated + } + + const runImportPipeline = async ( + task: (ctx: { token: number; signal: AbortSignal; report: (p: { visitedDirs: number; matchedFiles: number }) => void }) => Promise, + markBusyImmediately: boolean + ) => { + if (!isAiVideoHostReady()) { + showToast({ style: Toast.Style.Failure, title: '导入失败', message: '需要在 ZTools 客户端中使用' }) + return + } + abortRef.current?.abort() + const controller = new AbortController() + abortRef.current = controller + const token = ++batchTokenRef.current + if (markBusyImmediately) { + setImportState({ active: true, visitedDirs: 0, matchedFiles: 0 }) + } + const report = (p: { visitedDirs: number; matchedFiles: number }) => { + if (mountedRef.current && batchTokenRef.current === token) { + setImportState({ active: true, visitedDirs: p.visitedDirs, matchedFiles: p.matchedFiles }) + } + } try { - const ws = await fetchAiVideoWorkspace() - setFiles(ws.files) - setCheckedIds(ws.files.map(f => f.id)) - setModels(ws.models) - setScannedDirs(ws.scannedDirs) - if (showIndicator) { + const result = await task({ token, signal: controller.signal, report }) + if (!result || !mountedRef.current || batchTokenRef.current !== token) return + if (result.canceled) return + if (result.error) { + const failed = summarizeImport(result, { added: 0 }, AI_VIDEO_SUPPORTED_TEXT) + if (failed) showToast({ style: Toast.Style.Failure, title: failed.title, message: failed.message }) + return + } + const incoming = result.files.map(importedFileToAiVideoItem) + const { merged, added, duplicates } = mergeByPath(filesRef.current, incoming, item => item.path) + if (added.length > 0) { + filesRef.current = merged + setFiles(merged) + setCheckedIds(prev => Array.from(new Set([...prev, ...added.map(item => item.id)]))) + } + const summary = summarizeImport(result, { added: added.length, duplicates }, AI_VIDEO_SUPPORTED_TEXT) + if (summary) { showToast({ - style: Toast.Style.Success, - title: 'AI 视频工作台已刷新', - message: `已就绪 ${ws.files.length} 个视频素材 · AI 处理引擎尚未接入` + style: summary.ok ? Toast.Style.Success : Toast.Style.Failure, + title: summary.title, + message: summary.message }) } + } catch (err) { + if (mountedRef.current && batchTokenRef.current === token) { + showToast({ style: Toast.Style.Failure, title: '导入失败', message: formatAiVideoError(err) }) + } } finally { - setIsLoading(false) + if (mountedRef.current && batchTokenRef.current === token) { + setImportState(IDLE_IMPORT_STATE) + } } } + const onPickVideoFiles = () => + runImportPipeline(async () => selectAiVideoFiles(), false) + + const onPickVideoFolder = () => + runImportPipeline(async ({ token, signal, report }) => { + const picked = await pickAiVideoFolder() + if (!mountedRef.current || batchTokenRef.current !== token) return null + if (picked.canceled) return null + if (picked.error || !picked.folderPath) { + return { + files: [], + ignored: 0, + truncated: false, + failedDirs: [], + canceled: false, + error: picked.error || '没有选择文件夹' + } + } + if (isVolumeRoot(picked.folderPath)) { + const ok = await confirmAlert({ + title: `确认导入整个磁盘「${picked.folderPath}」?`, + message: '磁盘根目录文件数量较多,将递归最多 5 层导入前 500 个支持的视频与参考图。', + primaryAction: { title: '继续导入', style: 'default' } + }) + if (!ok || !mountedRef.current || batchTokenRef.current !== token) return null + } + setImportState({ active: true, visitedDirs: 0, matchedFiles: 0 }) + return collectAiVideoFolderFiles(picked.folderPath, { signal, onProgress: report }) + }, false) + + const onInputDropOrPaste = (input: NormalizedFileInput) => + runImportPipeline( + async ({ signal, report }) => + expandAiVideoInputPaths(input.paths, { knownDirectories: input.directories, signal, onProgress: report }), + true + ) + useEffect(() => { - refreshWorkspace(false) + mountedRef.current = true + const win = typeof window !== 'undefined' ? (window as unknown as LegacyEventBridge) : undefined + const unsubscribe = !isDeclarativeFileInputSupported() + ? win?.ztools?.events?.on?.('plugin_files_dropped', raw => { + const normalized = normalizeFileInput(raw) + if (normalized.paths.length > 0) void onInputDropOrPaste(normalized) + }) + : undefined + return () => { + mountedRef.current = false + batchTokenRef.current += 1 + abortRef.current?.abort() + abortRef.current = null + if (typeof unsubscribe === 'function') unsubscribe() + } }, []) - const activeModel = models.find(m => m.id === activeModelId) || AI_VIDEO_MODELS[0] + const fileInputProps = createImportInputProps( + input => { + void onInputDropOrPaste(input) + }, + { + allowClipboardImage: true, + dropTitle: '拖入或粘贴视频 / 参考图 / 文件夹', + dropSubtitle: '支持 MP4、MKV、MOV、AVI、WEBM 等视频与参考图,文件夹自动递归导入' + } + ) + + const activeModel = AI_VIDEO_MODELS.find(m => m.id === activeModelId) || AI_VIDEO_MODELS[0] + + const removeSingleItem = (itemId: string) => { + if (processingSetRef.current.has(itemId)) return + syncFiles(prev => prev.filter(item => item.id !== itemId)) + setCheckedIds(prev => prev.filter(id => id !== itemId)) + } + + const clearVideoQueue = () => { + if (processingRef.current) { + showToast({ style: Toast.Style.Failure, title: '正在处理,完成后再清空' }) + return + } + batchTokenRef.current += 1 + abortRef.current?.abort() + abortRef.current = null + setImportState(IDLE_IMPORT_STATE) + syncFiles(() => []) + setCheckedIds([]) + } + + const applyBatchOutputs = (res: AiVideoBatchResult) => { + if (!mountedRef.current || res.outputs.length === 0) return + const byInputPath = new Map(res.outputs.map(o => [o.inputPath, o])) + syncFiles(prev => + prev.map(item => { + const hit = byInputPath.get(item.path) + return hit ? { ...item, outputPath: hit.outputPath, outputSizeBytes: hit.sizeBytes } : item + }) + ) + } - async function handleRunBatchChecked() { - const selected = files.filter(f => checkedIds.includes(f.id)) - if (selected.length === 0) { + const executeTargets = async (targets: AiVideoFileItem[], askConfirm: boolean) => { + if (processingRef.current) { + showToast({ style: Toast.Style.Failure, title: '正在处理,请等当前任务完成' }) + return + } + if (targets.length === 0) { showToast({ style: Toast.Style.Failure, title: '请先勾选待增强的视频文件' }) return } - const ok = await confirmAlert({ - title: `确认对 ${selected.length} 个视频执行「${activeModel.title}」?`, - message: `引擎: ${activeModel.modelEngine} · 帧率: ${FPS_LABEL_MAP[targetFps]} · 分辨率: ${RES_LABEL_MAP[targetResolution]}`, - primaryAction: { title: '开始批量 AI 视频增强', style: 'default' } - }) - if (!ok) return - - const res = await runAiVideoBatch(selected, { - modelId: activeModel.id, - targetFps, - targetResolution, - videoEncoder, - sceneChangeProtection - }) + if (askConfirm) { + const ok = await confirmAlert({ + title: `确认对 ${targets.length} 个视频执行「${activeModel.title}」?`, + message: `引擎: ${activeModel.modelEngine} · 帧率: ${FPS_LABEL_MAP[targetFps]} · 分辨率: ${RES_LABEL_MAP[targetResolution]}`, + primaryAction: { title: '开始批量 AI 视频增强', style: 'default' } + }) + if (!ok) return + } + + const ids = targets.map(t => t.id) + processingRef.current = true + processingSetRef.current = new Set(ids) + setIsProcessing(true) + setProcessingIds(ids) + + let res: AiVideoBatchResult + try { + res = await executeAiVideoBatch( + targets, + { + modelId: activeModel.id, + targetFps, + targetResolution, + videoEncoder, + sceneChangeProtection + }, + undefined, + { + shouldProcess: item => mountedRef.current && filesRef.current.some(cur => cur.id === item.id) + } + ) + } catch (err) { + if (mountedRef.current) { + showToast({ style: Toast.Style.Failure, title: 'AI 视频增强失败', message: formatAiVideoError(err) }) + } + return + } finally { + processingRef.current = false + processingSetRef.current = new Set() + if (mountedRef.current) { + setIsProcessing(false) + setProcessingIds([]) + } + } + + if (!mountedRef.current) return + applyBatchOutputs(res) + if (!res.ok) { - showToast({ style: Toast.Style.Failure, title: 'AI 视频增强失败', message: res.error || '推理引擎返回错误' }) + showToast({ + style: Toast.Style.Failure, + title: targets.length === 1 ? `增强 ${targets[0].name} 失败` : 'AI 视频增强失败', + message: res.error || '推理引擎返回错误' + }) return } - showToast({ - style: Toast.Style.Success, - title: `已提交 ${res.processedCount} 个 AI 视频增强任务`, - message: `${activeModel.tag} · ${FPS_LABEL_MAP[targetFps]} · ${RES_LABEL_MAP[targetResolution]}` - }) + + if (targets.length === 1) { + const outRes = targetResolution === '4k_2160p' ? '4K' : targetResolution === '2k_1440p' ? '2K' : '1080P' + const outFps = targetFps === 'source' ? '原帧率' : targetFps.toUpperCase() + showToast({ + style: Toast.Style.Success, + title: `已启动 ${targets[0].name} AI 补帧与超分`, + message: `${activeModel.tag} (${outRes} ${outFps})` + }) + } else { + showToast({ + style: Toast.Style.Success, + title: `已提交 ${res.processedCount} 个 AI 视频增强任务`, + message: `${activeModel.tag} · ${FPS_LABEL_MAP[targetFps]} · ${RES_LABEL_MAP[targetResolution]}` + }) + } } const selectedFiles = files.filter(f => checkedIds.includes(f.id)) - const totalBytes = selectedFiles.reduce((s, f) => s + f.sizeBytes, 0) + const totalSizeText = summarizeSelectedVideoSize(selectedFiles) const q = searchText.trim().toLowerCase() const filteredFiles = files.filter( f => !q || f.name.toLowerCase().includes(q) || f.path.toLowerCase().includes(q) ) + const allFilteredChecked = filteredFiles.length > 0 && filteredFiles.every(f => checkedIds.includes(f.id)) + const someFilteredChecked = filteredFiles.some(f => checkedIds.includes(f.id)) + + const toggleSelectAll = () => { + if (filteredFiles.length === 0) return + const visibleIds = filteredFiles.map(f => f.id) + if (allFilteredChecked) { + const drop = new Set(visibleIds) + setCheckedIds(prev => prev.filter(id => !drop.has(id))) + } else { + setCheckedIds(prev => Array.from(new Set([...prev, ...visibleIds]))) + } + } - const maxVidBytes = Math.max(1, filteredFiles[0]?.sizeBytes || 1) + let summaryText = `队列已选 ${selectedFiles.length}/${files.length} 个视频 (${totalSizeText}) · 模型: ${activeModel.tag} · 输出 ${RES_LABEL_MAP[targetResolution]} @ ${FPS_LABEL_MAP[targetFps]} · 清空列表 Ctrl+Shift+Backspace` + if (importState.active) { + summaryText = `正在导入:已读取 ${importState.visitedDirs} 个文件夹,找到 ${importState.matchedFiles} 个文件` + } else if (isProcessing) { + summaryText = '正在处理视频…' + } else if (files.length === 0) { + summaryText = '尚未添加文件 · 可选择文件、文件夹,或直接拖入' + } + + const emptyText = !isAiVideoHostReady() + ? '需要在 ZTools 客户端中使用' + : importState.active + ? '正在导入视频…' + : q + ? '当前队列暂无匹配视频' + : '尚未添加文件 · 可选择文件、文件夹,或直接拖入 / 粘贴视频或参考图' + + const maxKnownBytes = filteredFiles.reduce((max, f) => Math.max(max, f.sizeBytes ?? 0), 0) const rightQueueItems = filteredFiles.map(f => { const isChecked = checkedIds.includes(f.id) - const volRatio = Math.max(10, Math.min(100, Math.round((f.sizeBytes / maxVidBytes) * 100))) + const isItemRunning = processingIds.includes(f.id) const sourceFpsStr = f.sourceFps === null ? '帧率未读取' : `${f.sourceFps}fps` const outFpsStr = targetFps === 'source' ? '原帧率' : targetFps.toUpperCase() const outResShort = targetResolution === '4k_2160p' ? '4K' : targetResolution === '2k_1440p' ? '2K' : '1080P' + const accessories: ListItemAccessory[] = [] + if (f.sizeBytes !== null && maxKnownBytes > 0) { + const volRatio = Math.max(10, Math.min(100, Math.round((f.sizeBytes / maxKnownBytes) * 100))) + accessories.push({ progress: { value: volRatio } }) + } + accessories.push({ + tag: { + value: f.outputPath ? `已输出 · ${outResShort}` : `→ ${outResShort} · ${outFpsStr}` + } + }) + accessories.push({ text: renderVideoSize(f.sizeBytes) }) + return List.Item({ id: f.id, title: f.name, @@ -131,67 +414,38 @@ export function AiVideoCommand() { checkable: true, checked: isChecked, onCheckChange: c => { - if (c) { - setCheckedIds(Array.from(new Set([...checkedIds, f.id]))) - } else { - setCheckedIds(checkedIds.filter(id => id !== f.id)) - } + setCheckedIds(c ? Array.from(new Set([...checkedIds, f.id])) : checkedIds.filter(id => id !== f.id)) }, icon: { source: Icon.Video }, - accessories: [ - { - progress: { - value: volRatio - } - }, - { - tag: { - value: `→ ${outResShort} · ${outFpsStr}` - } - }, - { text: formatBytes(f.sizeBytes) } - ], + accessories, actions: ActionPanel({ title: f.name, children: [ Action({ - title: `开始批量 AI 视频增强 (${checkedIds.length}项)`, + title: `开始批量 AI 视频增强 (${selectedFiles.length}项)`, icon: Icon.Bolt, - onAction: handleRunBatchChecked + onAction: () => { + void executeTargets(selectedFiles, true) + } }), Action({ title: '在资源管理器定位', icon: Icon.Folder, - onAction: () => { - openAiVideoLocation(f.path) + onAction: async () => { + const target = f.outputPath || f.path + const ok = await openAiVideoLocation(target) + if (!ok) { + showToast({ style: Toast.Style.Failure, title: '无法在资源管理器定位', message: target }) + } } }), Action({ title: `仅对当前视频执行「${activeModel.tag}」`, icon: Icon.Play, - onAction: async () => { - const res = await runAiVideoBatch([f], { - modelId: activeModel.id, - targetFps, - targetResolution, - videoEncoder, - sceneChangeProtection - }) - if (!res.ok) { - showToast({ - style: Toast.Style.Failure, - title: `增强 ${f.name} 失败`, - message: res.error || '推理引擎返回异常' - }) - return - } - showToast({ - style: Toast.Style.Success, - title: `已启动 ${f.name} AI 补帧与超分`, - message: `${activeModel.tag} (${outResShort} ${outFpsStr})` - }) + onAction: () => { + void executeTargets([f], false) } }), Action({ @@ -202,6 +456,50 @@ export function AiVideoCommand() { await Clipboard.copy(cmd) showToast({ style: Toast.Style.Success, title: '已复制 AI 视频推理命令' }) } + }), + ActionPanel.Section({ + title: '列表', + children: [ + ...(isItemRunning + ? [] + : [ + Action({ + title: '从列表移除', + icon: Icon.Minus, + shortcut: { modifiers: ['ctrl'], key: 'backspace' }, + onAction: () => removeSingleItem(f.id) + }) + ]), + Action({ + title: '选择文件…', + icon: Icon.Document, + shortcut: { modifiers: ['ctrl'], key: 'o' }, + onAction: () => { + void onPickVideoFiles() + } + }), + Action({ + title: '选择文件夹…', + icon: Icon.Folder, + shortcut: { modifiers: ['ctrl', 'shift'], key: 'o' }, + onAction: () => { + void onPickVideoFolder() + } + }), + Action({ + title: allFilteredChecked ? '取消全选' : '全选', + icon: Icon.Checkmark, + shortcut: { modifiers: ['ctrl'], key: 'a' }, + onAction: toggleSelectAll + }), + Action({ + title: '清空列表', + icon: Icon.Trash, + style: Action.Style.Destructive, + shortcut: { modifiers: ['ctrl', 'shift'], key: 'backspace' }, + onAction: clearVideoQueue + }) + ] }) ] }) @@ -209,10 +507,47 @@ export function AiVideoCommand() { }) return List({ + ...fileInputProps, searchBarPlaceholder: '搜索待增强视频、目录或 AI 视频模型 (RIFE 60fps / 120fps / Real-CUGAN 4K)...', onSearchTextChange: setSearchText, isShowingDetail: false, - isLoading, + isLoading: importState.active || isProcessing, + actions: ActionPanel({ + children: [ + Action({ + title: '选择文件…', + icon: Icon.Document, + shortcut: { modifiers: ['ctrl'], key: 'o' }, + onAction: () => { + void onPickVideoFiles() + } + }), + Action({ + title: '选择文件夹…', + icon: Icon.Folder, + shortcut: { modifiers: ['ctrl', 'shift'], key: 'o' }, + onAction: () => { + void onPickVideoFolder() + } + }), + ...(files.length > 0 + ? [ + ActionPanel.Section({ + title: '列表', + children: [ + Action({ + title: '清空列表', + icon: Icon.Trash, + style: Action.Style.Destructive, + shortcut: { modifiers: ['ctrl', 'shift'], key: 'backspace' }, + onAction: clearVideoQueue + }) + ] + }) + ] + : []) + ] + }), searchBarAccessory: List.Dropdown({ tooltip: '选择 4 大 AI 视频模型', value: activeModelId, @@ -225,14 +560,27 @@ export function AiVideoCommand() { ) }), filterBar: FilterBar({ - summaryText: `队列已选 ${checkedIds.length}/${files.length} 个视频 (${formatBytes(totalBytes)}) · 模型: ${activeModel.tag} · 输出 ${RES_LABEL_MAP[targetResolution]} @ ${FPS_LABEL_MAP[targetFps]}`, + summaryText, actions: [ { - id: 'rescan-ai-video', - label: '重新扫描队列', - title: '重新扫描队列', + id: 'pick-files', + label: '选择文件', + title: '选择文件', + icon: Icon.Document, style: 'secondary', - onAction: () => refreshWorkspace(true) + onAction: () => { + void onPickVideoFiles() + } + }, + { + id: 'pick-folder', + label: '选择文件夹', + title: '选择文件夹', + icon: Icon.Folder, + style: 'secondary', + onAction: () => { + void onPickVideoFolder() + } } ] }), @@ -298,29 +646,30 @@ export function AiVideoCommand() { { label: '目标帧率', value: FPS_LABEL_MAP[targetFps] || '60 FPS' }, { label: '目标分辨率', value: RES_LABEL_MAP[targetResolution] || '4K UHD' }, { label: '硬件编码器', value: videoEncoder.toUpperCase() }, - { label: '已选队列', value: `${checkedIds.length} / ${files.length} 项` } + { label: '已选队列', value: `${selectedFiles.length} / ${files.length} 项` } ] } }, subList: { - title: '待增强视频文件队列 (按体积降序,勾选或按 ↵ 立即开始 AI 补帧与超分)', - subtitle: `${filteredFiles.length} 项 · 原始 ${formatBytes(totalBytes)} · 目标 ${RES_LABEL_MAP[targetResolution]} @ ${FPS_LABEL_MAP[targetFps]}`, + title: '待增强视频文件队列 (勾选或按 ↵ 立即开始 AI 补帧与超分)', + subtitle: `${filteredFiles.length} 项 · 原始 ${totalSizeText} · 目标 ${RES_LABEL_MAP[targetResolution]} @ ${FPS_LABEL_MAP[targetFps]}`, checkable: filteredFiles.length > 0, - checked: - filteredFiles.length > 0 && filteredFiles.every(f => checkedIds.includes(f.id)) - ? true - : filteredFiles.some(f => checkedIds.includes(f.id)) - ? 'indeterminate' - : false, + checked: allFilteredChecked ? true : someFilteredChecked ? 'indeterminate' : false, onCheckChange: checked => { - setCheckedIds(checked ? filteredFiles.map(f => f.id) : []) + const visibleIds = filteredFiles.map(f => f.id) + if (checked) { + setCheckedIds(prev => Array.from(new Set([...prev, ...visibleIds]))) + } else { + const drop = new Set(visibleIds) + setCheckedIds(prev => prev.filter(id => !drop.has(id))) + } }, - emptyText: '当前队列暂无匹配视频', + emptyText, items: rightQueueItems }, children: [ List.Section({ - title: `本机待增强视频队列 (${filteredFiles.length})`, + title: `待增强视频队列 (${filteredFiles.length})`, children: rightQueueItems }) ] @@ -328,4 +677,3 @@ export function AiVideoCommand() { } export default AiVideoCommand - diff --git a/extensions/ai-video/src/logic.ts b/extensions/ai-video/src/logic.ts index 2f75d23f..702d661c 100644 --- a/extensions/ai-video/src/logic.ts +++ b/extensions/ai-video/src/logic.ts @@ -1,16 +1,26 @@ /** * AI 视频补帧 (RIFE 60/120fps) 与画质超分增强业务逻辑层 (AiVideo Logic) - * 真实扫描本机 Videos / Downloads / Desktop 目录下的视频媒体文件,对接 AiVideoPlugin 引擎 + * 按导入规则接入视频与首帧参考图,校验参数并调用 AiVideoPlugin / 宿主增强接口 */ +import { + FileImportOptions, + FileImportResult, + FileImportRules, + FileImportTransport, + ImportedFile, + collectFolderFiles, + expandInputPaths, + friendlyFileError, + pickFiles, + pickFolder +} from './file-import.js' import { callHostTransport, formatBytes, getRealFileSize, - getRealSystemPath, invokePluginService, isRealElectronHost, - scanRealDirectoryTree, showRealItemInFolder } from './native-ipc.js' @@ -31,7 +41,8 @@ export interface AiVideoFileItem { path: string parentDir: string extension: string - sizeBytes: number + /** 字节数;宿主未返回时为 null(界面显示「大小未识别」) */ + sizeBytes: number | null sourceFps: number | null sourceResolution: string outputSizeBytes?: number @@ -81,13 +92,17 @@ export interface AiVideoBatchResult { fromFallback?: boolean } -function isStrictRealHost(hostOverride?: unknown): boolean { +export type AiVideoHostOverride = Parameters[2] + +export function isAiVideoHostReady(hostOverride?: unknown): boolean { if (isRealElectronHost(hostOverride)) return true if (hostOverride !== undefined && hostOverride !== null) return true return false } -export const FORBIDDEN_VIDEO_PATH = new RegExp('\\\\Windows\\\\System32|\\.\\.\\\\|\\.\\./', 'i') +export const HOST_UNAVAILABLE_ERROR = 'HOST_UNAVAILABLE: 需要在 ZTools 客户端中运行' + +export const FORBIDDEN_VIDEO_PATH = /(?:^|[\\/])Windows[\\/]System32(?:[\\/]|$)|\.\.[\\/]/i export const AI_VIDEO_MODELS: AiVideoModelPreset[] = [ { @@ -124,70 +139,61 @@ export const AI_VIDEO_MODELS: AiVideoModelPreset[] = [ } ] -export const INITIAL_AI_VIDEO_FILES: AiVideoFileItem[] = [ - { - id: 'ai-vid-1', - name: 'Gameplay_Cyberpunk_Benchmark_30fps_Raw.mp4', - path: 'D:\\Videos\\Captures\\Gameplay_Cyberpunk_Benchmark_30fps_Raw.mp4', - parentDir: 'D:\\Videos\\Captures', - extension: '.mp4', - sizeBytes: 680 * 1024 * 1024, - sourceFps: 30, - sourceResolution: '1920×1080' - }, - { - id: 'ai-vid-2', - name: 'Anime_Trailer_Opening_24fps_1080p.mkv', - path: 'D:\\Videos\\Anime\\Anime_Trailer_Opening_24fps_1080p.mkv', - parentDir: 'D:\\Videos\\Anime', - extension: '.mkv', - sizeBytes: 340 * 1024 * 1024, - sourceFps: 24, - sourceResolution: '1920×1080' - }, - { - id: 'ai-vid-3', - name: 'Vintage_Tech_Keynote_Archive_720p.mov', - path: 'D:\\Workspace\\Videos\\Vintage_Tech_Keynote_Archive_720p.mov', - parentDir: 'D:\\Workspace\\Videos', - extension: '.mov', - sizeBytes: 420 * 1024 * 1024, - sourceFps: 30, - sourceResolution: '1280×720' - }, - { - id: 'ai-vid-4', - name: 'Night_City_Drone_Aerial_LowLight.mp4', - path: 'D:\\Workspace\\Downloads\\Night_City_Drone_Aerial_LowLight.mp4', - parentDir: 'D:\\Workspace\\Downloads', - extension: '.mp4', - sizeBytes: 510 * 1024 * 1024, - sourceFps: 30, - sourceResolution: '1920×1080' - }, - { - id: 'ai-vid-5', - name: 'UI_Motion_Design_Prototype_30fps.webm', - path: 'D:\\Videos\\Prototypes\\UI_Motion_Design_Prototype_30fps.webm', - parentDir: 'D:\\Videos\\Prototypes', - extension: '.webm', - sizeBytes: 145 * 1024 * 1024, - sourceFps: 30, - sourceResolution: '1920×1080' - }, - { - id: 'ai-vid-6', - name: 'Product_Unboxing_B_Roll_Clip.mp4', - path: 'D:\\Videos\\Studio\\Product_Unboxing_B_Roll_Clip.mp4', - parentDir: 'D:\\Videos\\Studio', - extension: '.mp4', - sizeBytes: 275 * 1024 * 1024, - sourceFps: 24, - sourceResolution: '1920×1080' +export const AI_VIDEO_EXTENSIONS = [ + '.png', + '.jpg', + '.jpeg', + '.webp', + '.mp4', + '.mov', + '.mkv', + '.avi', + '.flv', + '.webm', + '.wmv', + '.ts', + '.m4v' +] as const + +export const AI_VIDEO_SUPPORTED_TEXT = 'MP4 / MKV / MOV / AVI / WEBM 等视频与 PNG / JPG / WEBP 参考图' + +export const AI_VIDEO_INPUT_EXT_REGEX = /\.(?:png|jpg|jpeg|webp|mp4|mov|mkv|avi|flv|webm|wmv|ts|m4v)$/i + +/** 排除本插件按「原名_帧率_分辨率.mp4」规则生成的增强输出文件 */ +export function isAiVideoOutputFile(name: string): boolean { + return /_(?:60fps|120fps|source)_(?:4k_2160p|2k_1440p|1080p_fhd)\.mp4$/i.test(String(name || '').trim()) +} + +export const AI_VIDEO_IMPORT_RULES: FileImportRules = { + extensions: AI_VIDEO_EXTENSIONS, + forbiddenPath: FORBIDDEN_VIDEO_PATH, + excludeFile: isAiVideoOutputFile +} + +export function createAiVideoTransport(hostOverride?: AiVideoHostOverride): FileImportTransport { + return (method, params) => callHostTransport(method, params, hostOverride) +} + +export function formatAiVideoError(error: unknown): string { + const raw = error instanceof Error ? error.message : String(error ?? '') + if (/NO_WINDOW_ENV|HOST_UNAVAILABLE/i.test(raw)) { + return '需要在 ZTools 客户端中使用' } -] + return friendlyFileError(error) +} -const VIDEO_EXT_REGEX = /\.(?:mp4|mkv|mov|avi|flv|webm|wmv|ts|m4v)$/i +export function importedFileToAiVideoItem(file: ImportedFile): AiVideoFileItem { + return { + id: `ai-vid-${file.path}`, + name: file.name, + path: file.path, + parentDir: file.parentDir, + extension: file.extension || '.mp4', + sizeBytes: file.sizeBytes, + sourceFps: null, + sourceResolution: '分辨率未读取' + } +} export function validateAiVideoPayload(config: Partial): { valid: boolean; error?: string } { if (!config || typeof config !== 'object') { @@ -202,128 +208,60 @@ export function validateAiVideoPayload(config: Partial): { v return { valid: true } } -export type AiVideoQueueSnapshot = AiVideoFileItem[] & { - scannedDirs: string[] - files: AiVideoFileItem[] - items: AiVideoFileItem[] - models: AiVideoModelPreset[] -} - -export async function fetchAiVideoQueue(hostOverride?: unknown): Promise { - const strictReal = isStrictRealHost(hostOverride) - const [videosDir, downloadsDir, desktopDir] = await Promise.all([ - getRealSystemPath('videos', hostOverride), - getRealSystemPath('downloads', hostOverride), - getRealSystemPath('desktop', hostOverride) - ]) - - const scannedDirs = [videosDir, downloadsDir, desktopDir].filter(Boolean) - const discovered: AiVideoFileItem[] = [] - const seenPaths = new Set() - - for (const dir of scannedDirs) { - const scanRes = await scanRealDirectoryTree(dir, { - maxDepth: 2, - maxFiles: 200, - collectTopN: 40, - filterExt: VIDEO_EXT_REGEX, - hostOverride - }) - for (const f of scanRes.files) { - if (f.sizeBytes <= 0) continue - const normPath = f.path.toLowerCase() - if (seenPaths.has(normPath)) continue - seenPaths.add(normPath) - const dot = f.name.lastIndexOf('.') - const ext = dot > 0 ? f.name.slice(dot).toLowerCase() : '.mp4' - discovered.push({ - id: `ai-vid-${discovered.length}-${f.path}`, - name: f.name, - path: f.path, - parentDir: f.path.replace(/[^\\/]+$/, ''), - extension: ext, - sizeBytes: f.sizeBytes, - sourceFps: null, - sourceResolution: '分辨率未读取' - }) - } - } - - discovered.sort((a, b) => b.sizeBytes - a.sizeBytes) - - // 真实宿主下只展示真实扫描到的视频文件,严禁在 < 4 时拼接 INITIAL_AI_VIDEO_FILES - const files = strictReal - ? discovered - : discovered.length > 0 - ? discovered - : [...INITIAL_AI_VIDEO_FILES] - - return Object.assign([...files], { - scannedDirs, - files, - items: files, - models: [...AI_VIDEO_MODELS] - }) -} - -export const fetchAiVideoWorkspace = fetchAiVideoQueue - export async function executeAiVideoBatch( files: AiVideoFileItem[], config: AiVideoBatchConfig, - hostOverride?: unknown + hostOverride?: AiVideoHostOverride, + options?: { shouldProcess?: (item: AiVideoFileItem) => boolean } ): Promise { + const baseFail = (error: string): AiVideoBatchResult => ({ + ok: false, + processedCount: 0, + modelId: config?.modelId || '', + targetFps: config?.targetFps || '60fps', + targetResolution: config?.targetResolution || '4k_2160p', + videoEncoder: config?.videoEncoder || 'hevc_nvenc', + totalOutputBytes: 0, + outputs: [], + error, + fromFallback: false + }) + if (!Array.isArray(files) || files.length === 0) { - return { - ok: false, - processedCount: 0, - modelId: config?.modelId || '', - targetFps: config?.targetFps || '60fps', - targetResolution: config?.targetResolution || '4k_2160p', - videoEncoder: config?.videoEncoder || 'hevc_nvenc', - totalOutputBytes: 0, - outputs: [], - error: 'EMPTY_QUEUE: 待增强视频队列不能为空' - } + return baseFail('EMPTY_QUEUE: 待增强视频队列不能为空') } const check = validateAiVideoPayload(config) if (!check.valid) { - return { - ok: false, - processedCount: 0, - modelId: config.modelId, - targetFps: config.targetFps, - targetResolution: config.targetResolution, - videoEncoder: config.videoEncoder, - totalOutputBytes: 0, - outputs: [], - error: check.error - } + return baseFail(check.error || 'INVALID_CONFIG') } for (const f of files) { if (!f?.path || FORBIDDEN_VIDEO_PATH.test(f.path)) { - return { - ok: false, - processedCount: 0, - modelId: config.modelId, - targetFps: config.targetFps, - targetResolution: config.targetResolution, - videoEncoder: config.videoEncoder, - totalOutputBytes: 0, - outputs: [], - error: 'SECURITY_INTERCEPTED: 视频路径不可包含系统受保护路径或路径穿越' - } + return baseFail('SECURITY_INTERCEPTED: 视频路径不可包含系统受保护路径或路径穿越') + } + if (!AI_VIDEO_INPUT_EXT_REGEX.test(f.path)) { + return baseFail(`UNSUPPORTED_INPUT: 不支持的文件格式 ${f.name || f.path}`) } } - const strictReal = isStrictRealHost(hostOverride) + if (!isAiVideoHostReady(hostOverride)) { + return baseFail(HOST_UNAVAILABLE_ERROR) + } + + const activeTargets = options?.shouldProcess ? files.filter(options.shouldProcess) : files + if (activeTargets.length === 0) { + return baseFail('EMPTY_QUEUE: 待增强视频队列已清空') + } + const outputs: AiVideoProcessedItemResult[] = [] let totalOutputBytes = 0 let lastError = '' - for (const f of files) { + for (const f of activeTargets) { + if (options?.shouldProcess && !options.shouldProcess(f)) { + continue + } const outputDir = config.outputDir || f.parentDir || '' const defaultOutputPath = f.path.replace( /(\.[^.\\/]+)?$/, @@ -365,10 +303,8 @@ export async function executeAiVideoBatch( if (!Number.isFinite(realSize) || realSize <= 0) { realSize = await getRealFileSize(outPath, hostOverride) } - // 必须有真实的产出文件大小或明确的成功产物校验,绝不在无文件产出时假报成功 + // 必须有真实产出文件大小,绝不在无文件产出时假报成功 if (realSize > 0) { - f.outputSizeBytes = realSize - f.outputPath = outPath totalOutputBytes += realSize outputs.push({ inputPath: f.path, @@ -380,7 +316,8 @@ export async function executeAiVideoBatch( } } - lastError = pluginRes.error || (pluginRes.data && pluginRes.data.error) || '' + const rawErr = pluginRes.error || (pluginRes.data && pluginRes.data.error) || '' + if (rawErr) lastError = formatAiVideoError(rawErr) } if (outputs.length > 0) { @@ -397,109 +334,64 @@ export async function executeAiVideoBatch( } } - const ipcRes = await callHostTransport( - 'ai_video_enhance_batch', - { - files: files.map(f => f.path), - ...config - }, - hostOverride - ) - - if (ipcRes.ok && ipcRes.data?.ok !== false) { - for (let i = 0; i < files.length; i++) { - const f = files[i] - const itemRes = Array.isArray(ipcRes.data?.results) - ? ipcRes.data.results[i] ?? ipcRes.data.results[0] - : ipcRes.data - const outPath = - itemRes?.outputPath || - ipcRes.data?.outputPath || - f.path.replace(/(\.[^.\\/]+)?$/, `_${config.targetFps}_${config.targetResolution}.mp4`) - const realSize = - Number( - itemRes?.outputBytes ?? - itemRes?.sizeBytes ?? - itemRes?.outputSizeBytes ?? - ipcRes.data?.sizeBytes ?? - ipcRes.data?.outputSizeBytes ?? - 0 - ) || (await getRealFileSize(outPath, hostOverride)) - if (!strictReal || realSize > 0) { - const finalSize = realSize > 0 ? realSize : f.sizeBytes - totalOutputBytes += finalSize - outputs.push({ - inputPath: f.path, - outputPath: outPath, - sizeBytes: finalSize, - ok: true - }) - } - } - if (outputs.length > 0) { - return { - ok: true, - processedCount: outputs.length, - modelId: config.modelId, - targetFps: config.targetFps, - targetResolution: config.targetResolution, - videoEncoder: config.videoEncoder, - totalOutputBytes, - outputs, - fromFallback: false - } - } - } - - if (strictReal) { - const errMsg = - lastError || - ipcRes.error || - 'AI_VIDEO_ENHANCE_FAILED: AI 视频补帧/超分引擎未能生成有效输出文件' - return { - ok: false, - processedCount: 0, - modelId: config.modelId, - targetFps: config.targetFps, - targetResolution: config.targetResolution, - videoEncoder: config.videoEncoder, - totalOutputBytes: 0, - outputs: [], - error: errMsg, - fromFallback: false - } - } - - for (const f of files) { - const outPath = f.path.replace( - /(\.[^.\\/]+)?$/, - `_${config.targetFps}_${config.targetResolution}.mp4` - ) - totalOutputBytes += f.sizeBytes - outputs.push({ - inputPath: f.path, - outputPath: outPath, - sizeBytes: f.sizeBytes, - ok: true - }) + const remainingTargets = options?.shouldProcess ? activeTargets.filter(options.shouldProcess) : activeTargets + if (remainingTargets.length === 0) { + return baseFail('EMPTY_QUEUE: 待增强视频队列已清空') } - return { - ok: true, - processedCount: files.length, - modelId: config.modelId, - targetFps: config.targetFps, - targetResolution: config.targetResolution, - videoEncoder: config.videoEncoder, - totalOutputBytes, - outputs, - fromFallback: true - } + // AiVideoPlugin 不可用或全部处理失败时直接返回真实失败原因,不再调用不存在的宿主兜底接口 + const errMsg = + lastError || + 'AI_VIDEO_ENHANCE_FAILED: AI 视频补帧/超分引擎未能生成有效输出文件' + return baseFail(errMsg) } export const runAiVideoBatch = executeAiVideoBatch -export async function openAiVideoLocation(fullPath: string, hostOverride?: unknown): Promise { +export async function openAiVideoLocation(fullPath: string, hostOverride?: AiVideoHostOverride): Promise { if (!fullPath) return false return showRealItemInFolder(fullPath, hostOverride) } + +function normalizeImportResult(result: FileImportResult): FileImportResult { + if (!result.error) return result + return { ...result, error: formatAiVideoError(result.error) } +} + +export async function selectAiVideoFiles(hostOverride?: AiVideoHostOverride): Promise { + const res = await pickFiles(createAiVideoTransport(hostOverride), AI_VIDEO_IMPORT_RULES, { + title: '选择视频或参考图', + filterName: '视频与参考图' + }) + return normalizeImportResult(res) +} + +export async function pickAiVideoFolder(hostOverride?: AiVideoHostOverride): Promise<{ + canceled: boolean + folderPath?: string + error?: string +}> { + const res = await pickFolder(createAiVideoTransport(hostOverride), { title: '选择视频文件夹' }) + if (res.error) { + return { ...res, error: formatAiVideoError(res.error) } + } + return res +} + +export async function collectAiVideoFolderFiles( + folderPath: string, + options: FileImportOptions = {}, + hostOverride?: AiVideoHostOverride +): Promise { + const res = await collectFolderFiles(createAiVideoTransport(hostOverride), folderPath, AI_VIDEO_IMPORT_RULES, options) + return normalizeImportResult(res) +} + +export async function expandAiVideoInputPaths( + paths: readonly string[], + options: FileImportOptions & { knownDirectories?: readonly string[] } = {}, + hostOverride?: AiVideoHostOverride +): Promise { + const res = await expandInputPaths(createAiVideoTransport(hostOverride), paths, AI_VIDEO_IMPORT_RULES, options) + return normalizeImportResult(res) +} diff --git a/extensions/ai-video/src/native-ipc.ts b/extensions/ai-video/src/native-ipc.ts index 390ea999..b8c547d6 100644 --- a/extensions/ai-video/src/native-ipc.ts +++ b/extensions/ai-video/src/native-ipc.ts @@ -1,4 +1,102 @@ +import { getLocale } from '@ztools/declarative-ui' + type DynamicBridge = ReturnType + +const NATIVE_IPC_MESSAGES: Record string + dirEntrySep: string + dirErrorColon: string + deepScanUnavailable: string + pathEmpty: string + invalidMethodEmpty: string + invalidMethodFormat: string + invalidParamsObject: string + paramTooLong: (key: string) => string + paramOutOfRange: (key: string) => string + methodParamEmpty: string + invalidMethodType: string + malformedDllResponse: string + unknownDllError: string + hostIpcFailed: (pluginName: string, method: string) => string + hostUnavailable: (pluginName: string, method: string) => string + callFailed: string + movedToTrash: string + deleteFailed: string + revealedInFolder: string + revealFailed: string + opened: string + openFailed: string + pluginCallNotReady: string +}> = { + 'zh-CN': { + ipcCallFailed: 'IPC 调用返回失败', + ipcInnerFailed: 'IPC 内部调用失败', + scanIncomplete: '扫描结果不完整', + dirReadFailed: (details, moreCount) => + `目录读取失败或不完整:${details}${moreCount > 0 ? `;另有 ${moreCount} 个目录` : ''}`, + dirEntrySep: ';', + dirErrorColon: ':', + deepScanUnavailable: '深度扫描不可用,仅列出一级目录,结果不完整', + pathEmpty: '路径不能为空', + invalidMethodEmpty: 'INVALID_METHOD: 调用方法名不能为空', + invalidMethodFormat: 'INVALID_METHOD_FORMAT: 方法名包含非法字符或超长', + invalidParamsObject: 'INVALID_PARAMS: 参数必须为非空对象', + paramTooLong: (key) => `PARAM_TOO_LONG: 参数 ${key} 超过最大长度限制`, + paramOutOfRange: (key) => `PARAM_OUT_OF_RANGE: 数值参数 ${key} 越界或非有限数`, + methodParamEmpty: 'method 参数不能为空', + invalidMethodType: 'INVALID_METHOD: method 不能为空且必须为字符串', + malformedDllResponse: 'MALFORMED_DLL_RESPONSE: 原生组件返回了损坏的 JSON 数据', + unknownDllError: '原生组件返回未知错误', + hostIpcFailed: (pluginName, method) => `HOST_IPC_FAILED: ${pluginName}.${method} 调用失败`, + hostUnavailable: (pluginName, method) => `HOST_UNAVAILABLE: ${pluginName}.${method} 宿主接口未就绪`, + callFailed: '调用失败', + movedToTrash: '已移入回收站', + deleteFailed: '删除失败', + revealedInFolder: '已定位文件', + revealFailed: '定位失败', + opened: '已打开', + openFailed: '打开失败', + pluginCallNotReady: '插件调用未就绪' + }, + 'en-US': { + ipcCallFailed: 'IPC call failed', + ipcInnerFailed: 'Internal IPC call failed', + scanIncomplete: 'Incomplete scan results', + dirReadFailed: (details, moreCount) => + `Directory read failed or incomplete: ${details}${moreCount > 0 ? `; and ${moreCount} more` : ''}`, + dirEntrySep: '; ', + dirErrorColon: ': ', + deepScanUnavailable: 'Deep scan unavailable; only top-level directory listed (incomplete)', + pathEmpty: 'Path cannot be empty', + invalidMethodEmpty: 'INVALID_METHOD: Method name cannot be empty', + invalidMethodFormat: 'INVALID_METHOD_FORMAT: Method name contains invalid characters or is too long', + invalidParamsObject: 'INVALID_PARAMS: Parameters must be a non-null object', + paramTooLong: (key) => `PARAM_TOO_LONG: Parameter "${key}" exceeds maximum length`, + paramOutOfRange: (key) => `PARAM_OUT_OF_RANGE: Numeric parameter "${key}" is out of range or non-finite`, + methodParamEmpty: 'Method parameter cannot be empty', + invalidMethodType: 'INVALID_METHOD: Method must be a non-empty string', + malformedDllResponse: 'MALFORMED_DLL_RESPONSE: Native component returned malformed JSON', + unknownDllError: 'Native component returned an unknown error', + hostIpcFailed: (pluginName, method) => `HOST_IPC_FAILED: ${pluginName}.${method} call failed`, + hostUnavailable: (pluginName, method) => `HOST_UNAVAILABLE: ${pluginName}.${method} host interface not ready`, + callFailed: 'Call failed', + movedToTrash: 'Moved to Trash', + deleteFailed: 'Delete failed', + revealedInFolder: 'Revealed in folder', + revealFailed: 'Failed to reveal item', + opened: 'Opened', + openFailed: 'Failed to open', + pluginCallNotReady: 'Plugin invocation not ready' + } +} + +function ipcStrings() { + const locale = getLocale() + return NATIVE_IPC_MESSAGES[locale] ?? NATIVE_IPC_MESSAGES['en-US'] +} /** * ZTools 真实宿主 IPC 与系统能力桥接层 (Real Host IPC Bridge) * @@ -76,11 +174,13 @@ function normalizeMethodResult(method: string, payload: DynamicBridge): DynamicB if (method === 'system_get_battery_status') { // 宿主约定 percent 超出 0-100(如 255)表示无电池或电量未知,不能改写成 100% + // 若宿主明确给出 hasBattery 布尔值,必须原样保留,仅在缺失时按合法电量推算 const rawPct = payload.percent - const hasBattery = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const validPct = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const hasBattery = typeof payload.hasBattery === 'boolean' ? payload.hasBattery : validPct return { ...payload, - percent: hasBattery ? rawPct : null, + percent: validPct ? rawPct : null, hasBattery } } @@ -100,9 +200,35 @@ function normalizeMethodResult(method: string, payload: DynamicBridge): DynamicB return payload } -function unwrapTransportResponse(method: string, raw: DynamicBridge): { ok: boolean; data?: DynamicBridge; error?: string } { +function extractIpcErrorMeta(errObj: DynamicBridge): { + errorCode?: string + errorDetails?: Record +} { + if (!errObj || typeof errObj !== 'object') return {} + const errorCode = + typeof errObj.errorCode === 'string' && errObj.errorCode.trim() + ? errObj.errorCode.trim() + : typeof errObj.code === 'string' && errObj.code.trim() + ? errObj.code.trim() + : undefined + const rawDetails = + errObj.errorDetails && typeof errObj.errorDetails === 'object' && !Array.isArray(errObj.errorDetails) + ? (errObj.errorDetails as Record) + : errObj.details && typeof errObj.details === 'object' && !Array.isArray(errObj.details) + ? (errObj.details as Record) + : undefined + return { + ...(errorCode ? { errorCode } : {}), + ...(rawDetails ? { errorDetails: rawDetails } : {}) + } +} + +function unwrapTransportResponse( + method: string, + raw: DynamicBridge +): { ok: boolean; data?: DynamicBridge; error?: string; errorCode?: string; errorDetails?: Record } { if (raw === null || raw === undefined) { - return { ok: false, error: 'EMPTY_IPC_RESPONSE' } + return { ok: false, error: 'EMPTY_IPC_RESPONSE', errorCode: 'EMPTY_IPC_RESPONSE' } } if (typeof raw !== 'object') { return { ok: true, data: raw } @@ -112,8 +238,8 @@ function unwrapTransportResponse(method: string, raw: DynamicBridge): { ok: bool const errMsg = typeof errObj === 'object' && errObj !== null ? String(errObj.message || errObj.code || JSON.stringify(errObj)) - : String(errObj || 'IPC 调用返回失败') - return { ok: false, error: errMsg } + : String(errObj || ipcStrings().ipcCallFailed) + return { ok: false, error: errMsg, ...extractIpcErrorMeta(raw), ...extractIpcErrorMeta(errObj) } } const firstLayer = 'data' in raw && raw.data !== undefined ? raw.data : raw @@ -123,8 +249,8 @@ function unwrapTransportResponse(method: string, raw: DynamicBridge): { ok: bool const errMsg = typeof errObj === 'object' && errObj !== null ? String(errObj.message || errObj.code || JSON.stringify(errObj)) - : String(errObj || 'IPC 内部调用失败') - return { ok: false, error: errMsg } + : String(errObj || ipcStrings().ipcInnerFailed) + return { ok: false, error: errMsg, ...extractIpcErrorMeta(firstLayer), ...extractIpcErrorMeta(errObj) } } if ('data' in firstLayer && firstLayer.data !== undefined) { return { ok: true, data: normalizeMethodResult(method, firstLayer.data) } @@ -141,7 +267,7 @@ export async function callHostTransport( method: string, params: Record = {}, hostOverride?: DynamicBridge -): Promise<{ ok: boolean; data?: T; error?: string }> { +): Promise<{ ok: boolean; data?: T; error?: string; errorCode?: string; errorDetails?: Record }> { const normalizedParams = normalizeMethodParams(method, params) // 1. 测试注入的 hostOverride 优先 @@ -150,24 +276,24 @@ export async function callHostTransport( try { const res = await hostOverride[method](normalizedParams) const unwrapped = unwrapTransportResponse(method, res) - return unwrapped as { ok: boolean; data?: T; error?: string } + return unwrapped as { ok: boolean; data?: T; error?: string; errorCode?: string; errorDetails?: Record } } catch (err: DynamicBridge) { - return { ok: false, error: err instanceof Error ? err.message : String(err) } + return { ok: false, error: err instanceof Error ? err.message : String(err), ...extractIpcErrorMeta(err) } } } if (typeof hostOverride?.transport?.call === 'function') { try { const res = await hostOverride.transport.call(method, normalizedParams) const unwrapped = unwrapTransportResponse(method, res) - return unwrapped as { ok: boolean; data?: T; error?: string } + return unwrapped as { ok: boolean; data?: T; error?: string; errorCode?: string; errorDetails?: Record } } catch (err: DynamicBridge) { - return { ok: false, error: err instanceof Error ? err.message : String(err) } + return { ok: false, error: err instanceof Error ? err.message : String(err), ...extractIpcErrorMeta(err) } } } } if (typeof window === 'undefined') { - return { ok: false, error: 'NO_WINDOW_ENV' } + return { ok: false, error: 'NO_WINDOW_ENV', errorCode: 'NO_WINDOW_ENV' } } const w = window as DynamicBridge @@ -178,22 +304,22 @@ export async function callHostTransport( try { const messageId = nextMessageId(method.replace(/[^A-Za-z0-9_]/g, '_').slice(0, 24)) const raw = await fn({ messageId, params: normalizedParams }) - return unwrapTransportResponse(method, raw) as { ok: boolean; data?: T; error?: string } + return unwrapTransportResponse(method, raw) as { ok: boolean; data?: T; error?: string; errorCode?: string; errorDetails?: Record } } catch (err: DynamicBridge) { - return { ok: false, error: err instanceof Error ? err.message : String(err) } + return { ok: false, error: err instanceof Error ? err.message : String(err), ...extractIpcErrorMeta(err) } } } if (typeof w.ztools?.transport?.call === 'function') { try { const raw = await w.ztools.transport.call(method, normalizedParams) - return unwrapTransportResponse(method, raw) as { ok: boolean; data?: T; error?: string } + return unwrapTransportResponse(method, raw) as { ok: boolean; data?: T; error?: string; errorCode?: string; errorDetails?: Record } } catch (err: DynamicBridge) { - return { ok: false, error: err instanceof Error ? err.message : String(err) } + return { ok: false, error: err instanceof Error ? err.message : String(err), ...extractIpcErrorMeta(err) } } } - return { ok: false, error: `METHOD_NOT_AVAILABLE: ${method}` } + return { ok: false, error: `METHOD_NOT_AVAILABLE: ${method}`, errorCode: 'METHOD_NOT_AVAILABLE' } } export interface RealDiskDriveInfo { @@ -365,6 +491,8 @@ export interface RealDirectoryScanResult extends Iterable approximate?: boolean /** 宿主实际遍历的条目数 */ visitedEntries?: number + /** 读取失败的真实原因;已有文件仍可使用,但不能当作完整结果。 */ + error?: string } interface ScanResultMeta { @@ -479,7 +607,28 @@ export async function scanRealDirectoryTree( limitOrOptions: number | ScanDirectoryTreeOptions = 160, hostOverrideArg?: DynamicBridge ): Promise { - return (await scanDirectoryTreeWithError(dirPath, limitOrOptions, hostOverrideArg)).scan + const result = await scanDirectoryTreeWithError(dirPath, limitOrOptions, hostOverrideArg) + return result.error ? { ...result.scan, error: result.error } : result.scan +} + +/** 一次界面扫描的错误汇总;多个目录并行扫描时保留可读目录的结果。 */ +export function createDirectoryScanner(hostOverride?: DynamicBridge) { + const failures = new Map() + return { + async scan(dir: string, options: number | ScanDirectoryTreeOptions = 160) { + const result = await scanRealDirectoryTree(dir, options, hostOverride) + const error = result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') + if (error) failures.set(dir, error) + else failures.delete(dir) + return result + }, + get error(): string | undefined { + if (!failures.size) return undefined + const s = ipcStrings() + const details = [...failures].slice(0, 3).map(([dir, error]) => `${dir}${s.dirErrorColon}${error}`).join(s.dirEntrySep) + return s.dirReadFailed(details, Math.max(0, failures.size - 3)) + } + } } /** scanRealDirectoryTree 的实现:额外带回读取失败原因(目录不存在 / 为空 / 无权限 / 载荷异常) */ @@ -526,10 +675,7 @@ async function scanDirectoryTreeWithError( if ( rawPayload && - Array.isArray(rawPayload.files) && - (rawPayload.files.length > 0 || - Number(rawPayload.total_matches || 0) > 0 || - (Array.isArray(rawPayload.subdirs) && rawPayload.subdirs.length > 0)) + Array.isArray(rawPayload.files) ) { let files: RealIndexedFileEntry[] = rawPayload.files.map(normalizeIndexedFileEntry) if (filterExt instanceof RegExp) { @@ -581,11 +727,12 @@ async function scanDirectoryTreeWithError( truncated: rawPayload.truncated === true, approximate: rawPayload.approximate === true, ...(Number.isFinite(visited) && visited >= 0 ? { visitedEntries: visited } : {}) - }) + }), + ...(typeof rawPayload.scan_error === 'string' && rawPayload.scan_error ? { error: rawPayload.scan_error } : {}) } } - // dir: 扫描无结果(目录不存在 / 为空 / 测试替身未实现)时,退回 filesystem_get_directory_contents 读取一级目录 + // 深度扫描失败或回执无效时,仅以一级目录读取补回可见结果;不冒充完整目录树。 const listing = await listDirectoryViaFilesystem(targetDir, hostOverride, { withSizes: true, limit: safeLimit }) if (listing.ok && listing.entries.length > 0) { const files: RealIndexedFileEntry[] = [] @@ -597,14 +744,16 @@ async function scanDirectoryTreeWithError( files.push(entry) totalBytes += entry.isDir ? 0 : entry.size } - return { scan: makeScanResult(files, files.length, totalBytes, []) } + const incomplete = listing.entries.some(entry => entry.isDir) || listing.entries.length >= safeLimit + return { + scan: makeScanResult(files, files.filter(file => !file.isDir).length, totalBytes, [], { approximate: incomplete }), + ...(incomplete ? { error: res.error || ipcStrings().deepScanUnavailable } : {}) + } } - return { scan: empty, error: listing.ok ? DIRECTORY_EMPTY_OR_UNREADABLE : listing.error } - } catch { - // ignore + return listing.ok ? { scan: empty } : { scan: empty, error: listing.error || 'DIRECTORY_READ_FAILED' } + } catch (error) { + return { scan: empty, error: error instanceof Error ? error.message : String(error) } } - - return { scan: empty, error: DIRECTORY_EMPTY_OR_UNREADABLE } } @@ -868,10 +1017,15 @@ export async function openRealPath( export async function trashRealItem( fullPath: string, hostOverride?: DynamicBridge -): Promise<{ ok: boolean; error?: string }> { - if (!fullPath) return { ok: false, error: '路径不能为空' } +): Promise<{ ok: boolean; error?: string; errorCode?: string; errorDetails?: Record }> { + if (!fullPath) return { ok: false, error: ipcStrings().pathEmpty } const res = await callHostTransport('shell_trash_item', { fullPath }, hostOverride) - return { ok: res.ok, error: res.error } + return { + ok: res.ok, + error: res.error, + ...(!res.ok && res.errorCode ? { errorCode: res.errorCode } : {}), + ...(!res.ok && res.errorDetails ? { errorDetails: res.errorDetails } : {}) + } } export interface NativeInvocationResult { @@ -880,6 +1034,8 @@ export interface NativeInvocationResult { message: string data?: T error?: string + errorCode?: string + errorDetails?: Record } export interface DllCapabilityResponse { @@ -888,11 +1044,64 @@ export interface DllCapabilityResponse { data: T | null message?: string error?: string + errorCode?: string + errorDetails?: Record pluginName: string method: string fromFallback?: boolean } +/** 声明式能力菜单项及其调用回执,供相同宿主协议的插件共用。 */ +export interface CapabilityActionItem { + id: string + title: string + subtitle: string + tag: string + method: string + params: Record +} + +export type PluginInvocationResult = Pick< + DllCapabilityResponse, 'ok' | 'pluginName' | 'method' | 'error' | 'errorCode' | 'errorDetails' | 'fromFallback' +> & { data?: unknown } + +/** 多个原生能力插件共用的参数边界校验;保护目标由各插件按自身业务提供。 */ +export function validateNativeCapabilityPayload( + method: string, + params: unknown, + forbiddenPattern: RegExp, + forbiddenReason: string +): { valid: boolean; error?: string } { + const s = ipcStrings() + if (typeof method !== 'string' || method.trim().length === 0) { + return { valid: false, error: s.invalidMethodEmpty } + } + if (method.length > 128 || !/^[A-Za-z0-9_]+$/.test(method.trim())) { + return { valid: false, error: s.invalidMethodFormat } + } + if (params === null || params === undefined || typeof params !== 'object' || Array.isArray(params)) { + return { valid: false, error: s.invalidParamsObject } + } + + const record = params as Record + for (const [key, val] of Object.entries(record)) { + if (typeof val === 'string') { + if (val.length > 4096) { + return { valid: false, error: s.paramTooLong(key) } + } + if (forbiddenPattern.test(val)) { + return { valid: false, error: `SECURITY_INTERCEPTED: ${forbiddenReason}` } + } + } else if (typeof val === 'number') { + if (!Number.isFinite(val) || val < -1000 || val > 100_000_000) { + return { valid: false, error: s.paramOutOfRange(key) } + } + } + } + + return { valid: true } +} + export async function invokeDllPluginCapability( pluginName: string, method: string, @@ -900,13 +1109,14 @@ export async function invokeDllPluginCapability( hostBridge?: DynamicBridge, offlineFallback?: () => T | Promise ): Promise> { + const s = ipcStrings() if (!method || typeof method !== 'string' || method.trim().length === 0) { return { ok: false, code: -1, data: null, - message: 'method 参数不能为空', - error: 'INVALID_METHOD: method 不能为空且必须为字符串', + message: s.methodParamEmpty, + error: s.invalidMethodType, pluginName, method: String(method || '') } @@ -920,7 +1130,7 @@ export async function invokeDllPluginCapability( try { parsed = JSON.parse(raw) } catch { - throw new Error('MALFORMED_DLL_RESPONSE: 原生组件返回了损坏的 JSON 数据') + throw new Error(s.malformedDllResponse) } } if (parsed && typeof parsed === 'object') { @@ -932,19 +1142,23 @@ export async function invokeDllPluginCapability( data: null, message: errMsg, error: errMsg, + ...extractIpcErrorMeta(parsed), + ...extractIpcErrorMeta(parsed.error), pluginName, method: trimmedMethod, fromFallback: false } } if ('ok' in parsed && parsed.ok === false) { - const errMsg = `DLL_ERROR: ${String(parsed.error || parsed.message || '原生组件返回未知错误')}` + const errMsg = `DLL_ERROR: ${String(parsed.error || parsed.message || s.unknownDllError)}` return { ok: false, code: typeof parsed.code === 'number' ? parsed.code : -1, data: null, message: errMsg, error: errMsg, + ...extractIpcErrorMeta(parsed), + ...extractIpcErrorMeta(parsed.error), pluginName, method: trimmedMethod, fromFallback: false @@ -983,6 +1197,7 @@ export async function invokeDllPluginCapability( data: null, message: errMsg, error: errMsg, + ...extractIpcErrorMeta(err), pluginName, method: trimmedMethod, fromFallback: false @@ -1039,13 +1254,15 @@ export async function invokeDllPluginCapability( isExplicitTransportFailure ) { const errMsg = - ipcRes.error || `HOST_IPC_FAILED: ${pluginName}.${trimmedMethod} 调用失败` + ipcRes.error || s.hostIpcFailed(pluginName, trimmedMethod) return { ok: false, code: -1, data: null, message: errMsg, error: errMsg, + ...(ipcRes.errorCode ? { errorCode: ipcRes.errorCode } : {}), + ...(ipcRes.errorDetails ? { errorDetails: ipcRes.errorDetails } : {}), pluginName, method: trimmedMethod, fromFallback: false @@ -1064,13 +1281,15 @@ export async function invokeDllPluginCapability( } } - const unavailableMsg = `HOST_UNAVAILABLE: ${pluginName}.${trimmedMethod} 宿主接口未就绪` + const unavailableMsg = s.hostUnavailable(pluginName, trimmedMethod) return { ok: false, code: -1, data: null, message: unavailableMsg, error: unavailableMsg, + ...(ipcRes.errorCode ? { errorCode: ipcRes.errorCode } : {}), + ...(ipcRes.errorDetails ? { errorDetails: ipcRes.errorDetails } : {}), pluginName, method: trimmedMethod, fromFallback: true @@ -1245,9 +1464,11 @@ export async function invokeHostCapability( return { ok: mockRes.ok, code: mockRes.ok ? 0 : -1, - message: mockRes.ok ? 'OK' : mockRes.error || '调用失败', + message: mockRes.ok ? 'OK' : mockRes.error || ipcStrings().callFailed, data: mockRes.data, - error: mockRes.error + error: mockRes.error, + ...(!mockRes.ok && mockRes.errorCode ? { errorCode: mockRes.errorCode } : {}), + ...(!mockRes.ok && mockRes.errorDetails ? { errorDetails: mockRes.errorDetails } : {}) } } @@ -1274,17 +1495,31 @@ export async function invokeHostCapability( if (capability === 'filesystem.deleteItem') { const targetPath = String(params.path || params.fullPath || '') const tr = await trashRealItem(targetPath, hostOverride) + const s = ipcStrings() return { ok: tr.ok, code: tr.ok ? 0 : -1, - message: tr.ok ? '已移入回收站' : tr.error || '删除失败', - error: tr.error + message: tr.ok ? s.movedToTrash : tr.error || s.deleteFailed, + error: tr.error, + ...(!tr.ok && tr.errorCode ? { errorCode: tr.errorCode } : {}), + ...(!tr.ok && tr.errorDetails ? { errorDetails: tr.errorDetails } : {}) } } if (capability === 'system.showItemInFolder') { const targetPath = String(params.path || params.fullPath || '') - const ok = await showRealItemInFolder(targetPath, hostOverride) - return { ok, code: ok ? 0 : -1, message: ok ? '已定位文件' : '定位失败' } + const s = ipcStrings() + if (!targetPath) { + return { ok: false, code: -1, message: s.revealFailed } + } + const res = await callHostTransport('shell_show_item_in_folder', { fullPath: targetPath }, hostOverride) + return { + ok: res.ok, + code: res.ok ? 0 : -1, + message: res.ok ? s.revealedInFolder : res.error || s.revealFailed, + ...(!res.ok && res.error ? { error: res.error } : {}), + ...(!res.ok && res.errorCode ? { errorCode: res.errorCode } : {}), + ...(!res.ok && res.errorDetails ? { errorDetails: res.errorDetails } : {}) + } } if (capability === 'filesystem.openItem' || capability === 'system.openUrl') { const target = String(params.path || params.url || params.fullPath || '') @@ -1294,12 +1529,15 @@ export async function invokeHostCapability( capability === 'system.openUrl' ? { url: target } : { fullPath: target }, hostOverride ) + const s = ipcStrings() return { ok: res.ok, code: res.ok ? 0 : -1, - message: res.ok ? '已打开' : res.error || '打开失败', + message: res.ok ? s.opened : res.error || s.openFailed, data: res.data, - error: res.error + error: res.error, + ...(!res.ok && res.errorCode ? { errorCode: res.errorCode } : {}), + ...(!res.ok && res.errorDetails ? { errorDetails: res.errorDetails } : {}) } } @@ -1330,9 +1568,11 @@ export async function invokeHostCapability( return { ok: res.ok, code: res.ok ? 0 : -1, - message: res.ok ? 'OK' : res.error || '调用失败', + message: res.ok ? 'OK' : res.error || ipcStrings().callFailed, data: res.data, - error: res.error + error: res.error, + ...(!res.ok && res.errorCode ? { errorCode: res.errorCode } : {}), + ...(!res.ok && res.errorDetails ? { errorDetails: res.errorDetails } : {}) } } @@ -1342,6 +1582,7 @@ export async function invokePluginService( params: Record = {}, hostOverride?: DynamicBridge ): Promise> { + const s = ipcStrings() // 1. 若测试注入了专门拦截 plugin_invoke 的 mock,支持调用 if (hostOverride && typeof hostOverride.plugin_invoke === 'function') { const mockRes = await callHostTransport( @@ -1352,9 +1593,11 @@ export async function invokePluginService( return { ok: mockRes.ok, code: mockRes.ok ? 0 : -1, - message: mockRes.ok ? 'OK' : mockRes.error || '插件调用未就绪', + message: mockRes.ok ? 'OK' : mockRes.error || s.pluginCallNotReady, data: mockRes.data, - error: mockRes.error + error: mockRes.error, + ...(!mockRes.ok && mockRes.errorCode ? { errorCode: mockRes.errorCode } : {}), + ...(!mockRes.ok && mockRes.errorDetails ? { errorDetails: mockRes.errorDetails } : {}) } } @@ -1371,7 +1614,8 @@ export async function invokePluginService( ok: false, code: -1, message: inner.error, - error: inner.error + error: inner.error, + ...extractIpcErrorMeta(inner) } } return { @@ -1408,8 +1652,10 @@ export async function invokePluginService( return { ok: false, code: -1, - message: String(raw.error || '调用失败'), - error: String(raw.error || '调用失败') + message: String(raw.error || s.callFailed), + error: String(raw.error || s.callFailed), + ...extractIpcErrorMeta(raw), + ...extractIpcErrorMeta(raw.error) } } const data = raw && typeof raw === 'object' && 'data' in raw ? raw.data : raw @@ -1419,7 +1665,8 @@ export async function invokePluginService( ok: false, code: -1, message: err instanceof Error ? err.message : String(err), - error: err instanceof Error ? err.message : String(err) + error: err instanceof Error ? err.message : String(err), + ...extractIpcErrorMeta(err) } } } @@ -1427,8 +1674,10 @@ export async function invokePluginService( return { ok: false, code: -1, - message: dllRes.error || '插件调用未就绪', - error: dllRes.error || '插件调用未就绪' + message: dllRes.error || s.pluginCallNotReady, + error: dllRes.error || s.pluginCallNotReady, + ...(dllRes.errorCode ? { errorCode: dllRes.errorCode } : {}), + ...(dllRes.errorDetails ? { errorDetails: dllRes.errorDetails } : {}) } } @@ -1570,8 +1819,6 @@ export async function writeRealClipboardText(text: string, hostOverride?: Dynami const payload = { text: String(text || '') } const res = await callHostTransport('clipboard_copy_text', payload, hostOverride) if (res.ok) return true - const fallbackRes = await callHostTransport('clipboard_write_text', payload, hostOverride) - if (fallbackRes.ok) return true try { if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) { await navigator.clipboard.writeText(String(text || '')) diff --git a/extensions/ai-video/tests/ai-video.host.test.mjs b/extensions/ai-video/tests/ai-video.host.test.mjs index bbc1025e..e68cf330 100644 --- a/extensions/ai-video/tests/ai-video.host.test.mjs +++ b/extensions/ai-video/tests/ai-video.host.test.mjs @@ -1,14 +1,11 @@ -// 本插件现行代码的宿主集成测试(从 packages/declarative-ui/tests/real-layout3-plugins.test.mjs 按插件拆出,导入改为本插件的 dist/) import test from 'node:test' import assert from 'node:assert/strict' -import crypto from 'node:crypto' import fs from 'node:fs' +import os from 'node:os' import path from 'node:path' -import { fileURLToPath } from 'node:url' +import { getLocale, setRuntimeLocale } from '@ztools/declarative-ui' import * as aiVideo from '../dist/index.js' -const __dirname = path.dirname(fileURLToPath(import.meta.url)) -const SRC_EXAMPLES_DIR = path.resolve(__dirname, '../src') async function withRealElectronWindow(handlers, fn) { const prevWindow = globalThis.window const calls = [] @@ -44,51 +41,98 @@ async function withRealElectronWindow(handlers, fn) { } } -test('ai-video: 真实宿主扫描、AiVideoPlugin.enhanceVideo 真实文件校验与无产出拦截', async () => { +const VALID_CONFIG = { + modelId: 'rife-v4-6', + targetFps: '60fps', + targetResolution: '4k_2160p', + videoEncoder: 'hevc_nvenc', + sceneChangeProtection: true +} + +test('ai-video: 已删除 INITIAL_AI_VIDEO_FILES 与挂载扫描函数,selectAiVideoFiles 对齐全部支持格式并过滤不支持文件', async () => { + assert.equal(aiVideo.INITIAL_AI_VIDEO_FILES, undefined) + assert.equal(aiVideo.fetchAiVideoQueue, undefined) + assert.equal(aiVideo.fetchAiVideoWorkspace, undefined) + await withRealElectronWindow( { - system_get_path: ({ name }) => (name === 'videos' ? 'D:\\RealClips' : ''), - system_search_files: ({ query }) => { - if (query === 'dir:D:\\RealClips') { - return { - files: [ - { name: 'clip.mp4', path: 'D:\\RealClips\\nested\\clip.mp4', is_dir: false, size: 8000000, mtime: 1700000000 } + window_show_open_dialog: params => { + assert.equal( + params.filters, + '视频与参考图|png;jpg;jpeg;webp;mp4;mov;mkv;avi;flv;webm;wmv;ts;m4v' + ) + return { + success: true, + data: { + canceled: false, + filePaths: [ + 'D:\\RealClips\\nested\\clip.mkv', + 'D:\\RealClips\\first_frame.webp', + 'D:\\RealClips\\notes.txt' ] } } - return { files: [] } }, + filesystem_get_file_size: ({ path: filePath }) => ({ + success: true, + data: { success: true, size: filePath.endsWith('.mkv') ? 8000000 : 256000 } + }), dllplugin_call: ({ plugin, func }) => { assert.equal(plugin, 'AiVideoPlugin') assert.equal(func, 'enhanceVideo') return { ok: true, - outputPath: 'D:\\RealClips\\clip_60fps_4k_2160p.mp4', + outputPath: 'D:\\RealClips\\nested\\clip_60fps_4k_2160p.mp4', sizeBytes: 19500000 } } }, async () => { - const queue = await aiVideo.fetchAiVideoQueue() - assert.equal(queue.files.length, 1, '真实宿主下严禁拼接 INITIAL_AI_VIDEO_FILES') - assert.equal(queue.files[0].sourceFps, null) - assert.equal(queue.files[0].sourceResolution, '分辨率未读取') - assert.equal(queue.files[0].parentDir, 'D:\\RealClips\\nested\\') - - const res = await aiVideo.executeAiVideoBatch(queue.files, { - modelId: 'rife-v4-6', - targetFps: '60fps', - targetResolution: '4k_2160p', - videoEncoder: 'hevc_nvenc', - sceneChangeProtection: true - }) + const imported = await aiVideo.selectAiVideoFiles() + assert.equal(imported.error, undefined) + assert.equal(imported.ignored, 1, 'notes.txt 应被统一过滤') + assert.deepEqual( + imported.files.map(f => f.name), + ['clip.mkv', 'first_frame.webp'] + ) + + const item = aiVideo.importedFileToAiVideoItem(imported.files[0]) + assert.equal(item.sourceFps, null) + assert.equal(item.sourceResolution, '分辨率未读取') + assert.equal(item.parentDir, 'D:\\RealClips\\nested') + + const res = await aiVideo.executeAiVideoBatch([item], VALID_CONFIG) assert.equal(res.ok, true) assert.equal(res.processedCount, 1) assert.equal(res.totalOutputBytes, 19500000) + assert.equal(res.fromFallback, false) } ) +}) - // 异常测试:当插件未生成有效文件(sizeBytes === 0)时严禁假报成功 +test('ai-video: 无产出文件或无客户端时严禁假报成功', async () => { + // 1. 无真实客户端时拒绝执行 + assert.equal(globalThis.window, undefined) + const noHostPick = await aiVideo.selectAiVideoFiles() + assert.deepEqual(noHostPick.files, []) + assert.match(noHostPick.error, /需要在 ZTools 客户端中使用/) + + const sampleItem = { + id: 'v1', + name: 'clip.mp4', + path: 'D:\\RealClips\\clip.mp4', + parentDir: 'D:\\RealClips', + extension: '.mp4', + sizeBytes: 8000000, + sourceFps: 30, + sourceResolution: '1920×1080' + } + const noHostExec = await aiVideo.executeAiVideoBatch([sampleItem], VALID_CONFIG) + assert.equal(noHostExec.ok, false) + assert.equal(noHostExec.fromFallback, false) + assert.match(noHostExec.error, /HOST_UNAVAILABLE/) + + // 2. 真实宿主下产出文件大小为 0 时严禁假报成功 await withRealElectronWindow( { dllplugin_call: () => ({ ok: true, outputPath: 'D:\\RealClips\\non_existent.mp4', sizeBytes: 0 }), @@ -96,41 +140,178 @@ test('ai-video: 真实宿主扫描、AiVideoPlugin.enhanceVideo 真实文件校 filesystem_stat: () => ({ size: 0 }) }, async () => { - const failRes = await aiVideo.executeAiVideoBatch( + const failRes = await aiVideo.executeAiVideoBatch([sampleItem], VALID_CONFIG) + assert.equal(failRes.ok, false, '无有效产出文件时严禁假报成功') + assert.equal(failRes.fromFallback, false) + } + ) +}) + +test('ai-video: 文件夹收集、输出文件排除与路径分隔符保留', async () => { + const tmpRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'ztools-ai-video-host-')) + try { + const dotted = path.join(tmpRoot, 'v1.5_素材') + fs.mkdirSync(dotted, { recursive: true }) + fs.writeFileSync(path.join(dotted, 'raw.m4v'), 'video') + fs.writeFileSync(path.join(dotted, 'frame.png'), 'img') + fs.writeFileSync(path.join(dotted, 'raw_60fps_4k_2160p.mp4'), 'output') + fs.writeFileSync(path.join(dotted, 'readme.txt'), 'skip') + + await withRealElectronWindow( + { + filesystem_get_directory_contents: ({ path: dir }) => { + const files = fs.readdirSync(dir, { withFileTypes: true }).map(ent => { + const st = fs.statSync(path.join(dir, ent.name)) + return { name: ent.name, size: ent.isDirectory() ? 0 : st.size, isDirectory: ent.isDirectory(), lastModified: st.mtime.toISOString() } + }) + return { success: true, data: { success: true, files } } + }, + filesystem_directory_exists: ({ path: target }) => ({ + success: true, + data: { success: true, exists: fs.existsSync(target) && fs.statSync(target).isDirectory() } + }) + }, + async () => { + const collected = await aiVideo.collectAiVideoFolderFiles(tmpRoot) + assert.equal(collected.error, undefined) + assert.deepEqual( + collected.files.map(f => f.name), + ['frame.png', 'raw.m4v'] + ) + assert.equal(collected.ignored, 2) + + const expanded = await aiVideo.expandAiVideoInputPaths([dotted]) + assert.deepEqual( + expanded.files.map(f => f.name), + ['frame.png', 'raw.m4v'] + ) + } + ) + + // Windows / POSIX 根目录父路径保留分隔符 + const winRootItem = aiVideo.importedFileToAiVideoItem({ + path: 'D:\\clip.avi', + name: 'clip.avi', + parentDir: 'D:\\', + extension: '.avi', + sizeBytes: 100, + lastModifiedMs: null + }) + const posixRootItem = aiVideo.importedFileToAiVideoItem({ + path: '/clip.avi', + name: 'clip.avi', + parentDir: '/', + extension: '.avi', + sizeBytes: 100, + lastModifiedMs: null + }) + assert.equal(winRootItem.parentDir, 'D:\\') + assert.equal(posixRootItem.parentDir, '/') + } finally { + fs.rmSync(tmpRoot, { recursive: true, force: true }) + } +}) + +test('ai-video: 受保护路径拦截、格式拒绝、错误翻译与 shouldProcess 跳过已移除条目', async t => { + const prevLocale = getLocale() + setRuntimeLocale('zh-CN') + t.after(() => setRuntimeLocale(prevLocale)) + + await withRealElectronWindow( + { + dllplugin_call: ({ params }) => { + if (params.inputPath.endsWith('expired.mp4')) { + throw new Error('路径未由当前窗口授权') + } + return { ok: true, outputPath: 'D:\\Out\\ok.mp4', sizeBytes: 12345 } + } + }, + async calls => { + const secRes = await aiVideo.executeAiVideoBatch( [ { - id: 'v1', - name: 'clip.mp4', - path: 'D:\\RealClips\\clip.mp4', - parentDir: 'D:\\RealClips', + id: 's1', + name: 'sys.mp4', + path: 'C:\\Windows\\System32\\sys.mp4', + parentDir: 'C:\\Windows\\System32', extension: '.mp4', - sizeBytes: 8000000, - sourceFps: 30, - sourceResolution: '1920×1080' + sizeBytes: 100, + sourceFps: null, + sourceResolution: '分辨率未读取' } ], - { - modelId: 'rife-v4-6', - targetFps: '60fps', - targetResolution: '4k_2160p', - videoEncoder: 'hevc_nvenc', - sceneChangeProtection: true - } + VALID_CONFIG ) - assert.equal(failRes.ok, false, '无有效产出文件时严禁假报成功') + assert.equal(secRes.ok, false) + assert.match(secRes.error, /SECURITY_INTERCEPTED/) + + const badExt = await aiVideo.executeAiVideoBatch( + [ + { + id: 'b1', + name: 'doc.txt', + path: 'D:\\doc.txt', + parentDir: 'D:\\', + extension: '.txt', + sizeBytes: 100, + sourceFps: null, + sourceResolution: '分辨率未读取' + } + ], + VALID_CONFIG + ) + assert.equal(badExt.ok, false) + assert.match(badExt.error, /UNSUPPORTED_INPUT/) + + const authRes = await aiVideo.executeAiVideoBatch( + [ + { + id: 'e1', + name: 'expired.mp4', + path: 'D:\\expired.mp4', + parentDir: 'D:\\', + extension: '.mp4', + sizeBytes: 100, + sourceFps: null, + sourceResolution: '分辨率未读取' + } + ], + VALID_CONFIG + ) + assert.equal(authRes.ok, false) + assert.match(authRes.error, /文件授权已过期或未授权/) + assert.equal(calls.some(c => c.channel === 'ai_video_enhance_batch'), false) + + const skipRes = await aiVideo.executeAiVideoBatch( + [ + { + id: 'k1', + name: 'keep.mp4', + path: 'D:\\keep.mp4', + parentDir: 'D:\\', + extension: '.mp4', + sizeBytes: 100, + sourceFps: null, + sourceResolution: '分辨率未读取' + }, + { + id: 'r1', + name: 'removed.mp4', + path: 'D:\\removed.mp4', + parentDir: 'D:\\', + extension: '.mp4', + sizeBytes: 100, + sourceFps: null, + sourceResolution: '分辨率未读取' + } + ], + VALID_CONFIG, + undefined, + { shouldProcess: item => item.name !== 'removed.mp4' } + ) + assert.equal(skipRes.ok, true) + assert.equal(skipRes.processedCount, 1) + assert.equal(skipRes.outputs[0].inputPath, 'D:\\keep.mp4') } ) }) - - -test('视频父目录保留 Windows 和 POSIX 根目录分隔符', async () => { - for (const root of ['D:\\', '/']) { - await withRealElectronWindow({ - system_get_path: ({ name }) => name === 'videos' ? root : '', - system_search_files: () => ({ files: [{ name: 'clip.avi', path: root + 'clip.avi', size: 100, is_dir: false }] }) - }, async () => { - const queue = await aiVideo.fetchAiVideoQueue(); - assert.equal(queue.files[0].parentDir, root); - }); - } -}); diff --git a/extensions/ai-video/tests/ai-video.ui.test.mjs b/extensions/ai-video/tests/ai-video.ui.test.mjs new file mode 100644 index 00000000..fa52d534 --- /dev/null +++ b/extensions/ai-video/tests/ai-video.ui.test.mjs @@ -0,0 +1,274 @@ +import test from 'node:test' +import assert from 'node:assert/strict' +import fs from 'node:fs' +import os from 'node:os' +import path from 'node:path' +import { createHost, installDirectoryHost, mount, tick } from '../../shared/test-harness.mjs' +import AiVideoCommand from '../dist/index.js' + +const COLORFUL_EMOJI = /[\u{1F300}-\u{1FAFF}\u{2600}-\u{27BF}]/u + +function makeTempDir(spec) { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ztools-ai-video-ui-')) + for (const [rel, content] of Object.entries(spec)) { + const full = path.join(root, rel) + fs.mkdirSync(path.dirname(full), { recursive: true }) + fs.writeFileSync(full, content) + } + return root +} + +const summary = view => view.tree().props.filterBar.props.summaryText + +test('ai-video UI: 挂载零扫描、无演示假数据、顶栏恰为 2 个导入按钮,无彩色 Emoji', async () => { + const host = createHost() + const view = await mount(AiVideoCommand, host) + + assert.equal(host.ipcCalls.length, 0, '挂载后不应调用任何系统路径或目录扫描 IPC') + const tree = view.tree() + assert.deepEqual(tree.props.subList.items, []) + assert.equal(summary(view), '尚未添加文件 · 可选择文件、文件夹,或直接拖入') + + const topActions = tree.props.filterBar.props.actions + assert.equal(topActions.length, 2) + assert.deepEqual( + topActions.map(a => a.title), + ['选择文件', '选择文件夹'] + ) + assert.deepEqual( + view.actions().map(a => a.props.title), + ['选择文件…', '选择文件夹…'] + ) + assert.ok(!COLORFUL_EMOJI.test(view.text()), '界面不能包含彩色 Emoji') + view.unmount() +}) + +test('ai-video UI: 选择文件支持取消、报错、13 种扩展名与大小未识别提示', async () => { + const host = createHost() + const view = await mount(AiVideoCommand, host) + + // 取消 + host.ipc.window_show_open_dialog = async () => ({ canceled: true }) + await view.run(undefined, '选择文件…') + assert.equal(host.toasts.length, 0) + + // 报错 + host.ipc.window_show_open_dialog = async () => { + throw new Error('当前窗口的文件 capability 数量超过上限') + } + await view.run(undefined, '选择文件…') + assert.equal(host.lastToast().style, 'FAILURE') + assert.match(host.lastToast().message, /改用「选择文件夹」/) + + // 选入 mkv、webp(无 size 返回)并过滤掉不支持的 txt + host.ipc.window_show_open_dialog = async params => { + assert.equal( + params.filters, + '视频与参考图|png;jpg;jpeg;webp;mp4;mov;mkv;avi;flv;webm;wmv;ts;m4v' + ) + return { + canceled: false, + filePaths: ['D:\\RealClips\\demo.mkv', 'D:\\RealClips\\ref.webp', 'D:\\RealClips\\readme.txt'] + } + } + await view.run(undefined, '选择文件…') + await tick(10) + const items = view.tree().props.subList.items + assert.deepEqual( + items.map(i => i.props.title), + ['demo.mkv', 'ref.webp'] + ) + assert.ok(items[0].props.accessories.some(a => a.text === '大小未识别')) + assert.match(summary(view), /清空列表 Ctrl\+Shift\+Backspace/) + assert.match(host.lastToast().message, /忽略 1 个不支持的文件/) + view.unmount() +}) + +test('ai-video UI: 选择文件夹支持递归过滤、排除输出文件、截断提示,以及拖入文件夹与去重', async () => { + const tmpDir = makeTempDir({ + 'clip.mp4': 'video1', + 'sub/movie.ts': 'video2', + 'sub/first_frame.png': 'img', + 'clip_60fps_4k_2160p.mp4': 'out', + 'skip.docx': 'doc' + }) + const manyDir = makeTempDir( + Object.fromEntries(Array.from({ length: 505 }, (_, i) => [`clip_${String(i + 1).padStart(3, '0')}.mp4`, 'v'])) + ) + + try { + const host = createHost() + await installDirectoryHost(host, { authorized: [tmpDir, manyDir] }) + const view = await mount(AiVideoCommand, host) + + // 选择文件夹 + host.ipc.window_show_select_folder_dialog = async () => ({ canceled: false, folderPath: tmpDir }) + await view.tree().props.filterBar.props.actions[1].onAction() + await tick(15) + assert.equal(host.ipcCalls.some(([m]) => m === 'window_show_open_dialog'), false) + assert.deepEqual( + view.tree().props.subList.items.map(i => i.props.title), + ['clip.mp4', 'first_frame.png', 'movie.ts'] + ) + assert.match(host.lastToast().message, /忽略 2 个不支持的文件/) + + // 重复拖入同一文件去重,拖入不带 directories 的旧版客户端文件夹也展开 + const subDir = path.join(tmpDir, 'sub') + await view.dropFiles([path.join(tmpDir, 'clip.mp4').toUpperCase()], { directories: [] }) + await tick(10) + assert.equal(view.tree().props.subList.items.length, 3) + assert.equal(host.lastToast().title, '这些文件已在列表中') + + // 清空后测试旧版路径拖放(不传 directories)与新事件回退 + await view.run(view.item(`ai-vid-${path.join(tmpDir, 'clip.mp4')}`), '清空列表') + host.ipc.filesystem_directory_exists = async ({ path: target }) => ({ + success: true, + exists: fs.existsSync(target) && fs.statSync(target).isDirectory() + }) + await view.dropFiles([subDir]) + await tick(15) + assert.equal(host.ipcCalls.some(([m]) => m === 'filesystem_directory_exists'), true) + assert.deepEqual( + view.tree().props.subList.items.map(i => i.props.title), + ['first_frame.png', 'movie.ts'] + ) + + // 超过 500 个截断提示 + await view.run(view.item(`ai-vid-${path.join(subDir, 'movie.ts')}`), '清空列表') + host.ipc.window_show_select_folder_dialog = async () => ({ canceled: false, folderPath: manyDir }) + await view.tree().props.filterBar.props.actions[1].onAction() + await tick(20) + assert.equal(view.tree().props.subList.items.length, 500) + assert.match(host.lastToast().message, /文件较多,只导入了一部分/) + view.unmount() + } finally { + fs.rmSync(tmpDir, { recursive: true, force: true }) + fs.rmSync(manyDir, { recursive: true, force: true }) + } +}) + +test('ai-video UI: 从列表移除、清空列表、处理中清空被拒绝、处理中移除条目不被写回,以及导入中清空丢弃结果', async () => { + const host = createHost() + host.ipc.filesystem_get_file_size = async () => ({ success: true, size: 8000000 }) + const view = await mount(AiVideoCommand, host) + + await view.pasteFiles(['D:\\RealClips\\a.mp4', 'D:\\RealClips\\b.mov']) + await tick(15) + + // 挂起处理 A + let releaseEnhance + host.ipc.dllplugin_call = ({ params }) => + new Promise(resolve => { + releaseEnhance = () => + resolve({ + ok: true, + outputPath: 'D:\\RealClips\\a_60fps_4k_2160p.mp4', + sizeBytes: 12000000, + inputPath: params.inputPath + }) + }) + + const runItemAction = (id, title) => + view.actions(view.item(id)).find(a => a.props.title === title).props.onAction() + + const enhancing = runItemAction('ai-vid-D:\\RealClips\\a.mp4', '仅对当前视频执行「RIFE v4.6 补帧」') + await tick() + + assert.equal( + view.actions(view.item('ai-vid-D:\\RealClips\\a.mp4')).some(a => a.props.title === '从列表移除'), + false, + '正在处理中的条目不提供从列表移除' + ) + assert.equal( + view.actions(view.item('ai-vid-D:\\RealClips\\b.mov')).some(a => a.props.title === '从列表移除'), + true + ) + + // 处理中清空列表被拒绝 + await runItemAction('ai-vid-D:\\RealClips\\a.mp4', '清空列表') + assert.equal(host.lastToast().title, '正在处理,完成后再清空') + assert.equal(view.tree().props.subList.items.length, 2) + + // 处理中移除未锁定的 B(不碰磁盘),待 A 完成后 B 不会回到列表 + await runItemAction('ai-vid-D:\\RealClips\\b.mov', '从列表移除') + assert.deepEqual( + view.tree().props.subList.items.map(i => i.props.title), + ['a.mp4'] + ) + assert.equal(host.ipcCalls.some(([m]) => m === 'shell_trash_item'), false) + + releaseEnhance() + await enhancing + await tick() + assert.deepEqual( + view.tree().props.subList.items.map(i => i.props.title), + ['a.mp4'] + ) + assert.ok(view.item('ai-vid-D:\\RealClips\\a.mp4').props.accessories.some(a => a.tag?.value === '已输出 · 4K')) + + // 导入中清空后结果丢弃 + let releaseDir + host.ipc.window_show_select_folder_dialog = async () => ({ canceled: false, folderPath: 'D:\\Clips' }) + host.ipc.filesystem_get_directory_contents = () => + new Promise(resolve => { + releaseDir = () => + resolve({ + success: true, + files: [{ name: 'late.mp4', size: 9999, isDirectory: false, lastModified: new Date().toISOString() }] + }) + }) + const importing = view.tree().props.filterBar.props.actions[1].onAction() + await tick() + assert.match(summary(view), /正在导入/) + + host.toasts.length = 0 + await runItemAction('ai-vid-D:\\RealClips\\a.mp4', '清空列表') + assert.equal(view.tree().props.subList.items.length, 0) + + releaseDir() + await importing + await tick(10) + assert.equal(view.tree().props.subList.items.length, 0) + assert.equal(host.toasts.length, 0) + view.unmount() +}) + +test('ai-video UI: 非客户端环境下提示需要在 ZTools 客户端中使用', async () => { + const host = createHost() + delete globalThis.window + const view = await mount(AiVideoCommand, host) + assert.equal(view.tree().props.subList.emptyText, '需要在 ZTools 客户端中使用') + await view.run(undefined, '选择文件…') + assert.equal(host.lastToast().style, 'FAILURE') + assert.equal(host.lastToast().message, '需要在 ZTools 客户端中使用') + view.unmount() +}) + +test('ai-video UI: 旧版客户端走 plugin_files_dropped 回退导入,组件卸载后处理回调不再写回', async () => { + const host = createHost() + globalThis.window.__ztoolsDeclarativeFeatures = {} + const view = await mount(AiVideoCommand, host) + host.emitEvent('plugin_files_dropped', { payload: { files: ['D:\\RealClips\\legacy.avi'] } }) + await tick(15) + assert.deepEqual( + view.tree().props.subList.items.map(i => i.props.title), + ['legacy.avi'] + ) + + let release + host.ipc.dllplugin_call = () => + new Promise(resolve => { + release = () => resolve({ ok: true, outputPath: 'D:\\RealClips\\legacy_60fps_4k_2160p.mp4', sizeBytes: 50000 }) + }) + const pending = view + .actions(view.item('ai-vid-D:\\RealClips\\legacy.avi')) + .find(a => a.props.title === '仅对当前视频执行「RIFE v4.6 补帧」') + .props.onAction() + await tick() + host.toasts.length = 0 + view.unmount() + release() + await pending + await tick() + assert.equal(host.toasts.length, 0, '组件卸载后处理回调不得继续弹 Toast 或写回状态') +}) diff --git a/extensions/archive-manager/README.en.md b/extensions/archive-manager/README.en.md new file mode 100644 index 00000000..8243815f --- /dev/null +++ b/extensions/archive-manager/README.en.md @@ -0,0 +1,23 @@ +# ZIP Archive Manager + +Browse files inside local ZIP archives without extracting them first; extract the entire archive or only checked files. + +## Usage + +- Commands: Browse ZIP archive contents and extract all or selected files (keywords such as `unzip`, `zip`, `archive`, `extract zip`, `inspect zip`), and Extract office documents from a ZIP archive (`extract docs`, `archive docs`, `unzip documents`). Both commands open the same view; "Extract office documents from a ZIP archive" filters for office documents by default. The "Pre-extraction Check" section in the left pane shows the target extraction location and whether any out-of-bounds paths or encrypted entries exist. +- The list starts empty. Import `.zip` files or folders containing `.zip` files via **Select File** or **Select Folder** at the top (or press `Ctrl+O` / `Ctrl+Shift+O`), or drag and drop / paste files and folders directly. Switch between archives using the dropdown next to the search box. Filter by file type in the left pane; the right pane lists archive entries by uncompressed size and supports searching by filename, path, or CRC32. Filenames automatically detect UTF-8 and GBK encodings. When reading fails, the reason is shown directly in the right pane. +- Press `Enter` on an entry in the right pane: extracts the entire archive if nothing is checked, or extracts only the checked files if any are checked. `Ctrl+Enter` reveals the archive in File Explorer; `Ctrl+S` extracts only the current file; `Ctrl+T` verifies the archive; `Ctrl+Backspace` removes the current archive from the list (without deleting the file on disk); `Ctrl+Shift+Backspace` clears the list; `Ctrl+K` opens the action panel (verify, copy path in archive, move to Recycle Bin, etc.). +- Full extraction: if the archive contains a single top-level folder, it extracts directly into the archive's parent directory; otherwise it extracts into a same-named folder next to the archive. Extracting selected files places them into a same-named folder while preserving their internal paths. A confirmation prompt shows the target folder before extraction; existing files with the same name at the destination will be overwritten. +- Entries containing `../` or absolute paths are flagged and rejected from extraction. Archives containing encrypted entries do not support extraction yet and will display a notice. +- "Verify" reads the archive directory, checks for out-of-bounds paths and encrypted entries, and computes the SHA-256 hash of the entire file without extracting or checking individual entry CRC32 values. +- Moving the original archive to the Recycle Bin requires confirmation. +- Currently supports ZIP only; 7Z, RAR, and TAR are not supported, and archive creation is not provided. + +## Platforms & Requirements + +- Supported: Windows only +- Built into the client; no separate installation required. + +## Network & Data + +- Works offline; data stays on your local device. diff --git a/extensions/archive-manager/plugin.json b/extensions/archive-manager/plugin.json index 63ffbd8a..551213db 100644 --- a/extensions/archive-manager/plugin.json +++ b/extensions/archive-manager/plugin.json @@ -1,8 +1,9 @@ { "id": "archive-manager", "name": "解压与压缩", - "description": "选择或拖入 ZIP 压缩包直接查看包内文件,可整包解压或只提取勾选的文件;只支持 ZIP,不提供压缩打包", - "version": "1.1.11", + "description": "通过宿主归档薄原语浏览、解压与压缩打包归档文件:支持整包或勾选条目解压、密码输入、自定义压缩级别打包 ZIP,并在宿主支持 7z-family 扩展时开放 7z/RAR/加密归档与引擎按需准备", + "version": "2.0.0", + "minAppVersion": "1.3.0.4", "author": "ZTools Team", "entry": "dist/index.js", "icon": "icon.svg", @@ -17,24 +18,43 @@ ], "keywords": [ "zip", + "7z", + "rar", "archive", "unzip", "extract", + "compress", "解压", + "压缩", + "打包", "压缩包", - "查看压缩包" + "解包", + "tar", + "归档", + "文件压缩", + "看压缩包" ], "features": [ { "code": "archive-inspect", - "explain": "查看 ZIP 压缩包内容并解压或提取", + "explain": "查看压缩包内容并解压或提取", "mode": "view", "cmds": [ "解压", "压缩包", "查看压缩包", "zip", - "校验压缩包" + "7z" + ] + }, + { + "code": "archive-create", + "explain": "选择文件或文件夹压缩打包为 ZIP / 7z", + "mode": "view", + "cmds": [ + "压缩打包", + "创建压缩包", + "打包zip" ] }, { @@ -47,6 +67,11 @@ ] } ], + "requiredCapabilities": [ + "archive.list", + "archive.extract", + "archive.create" + ], "permissions": [ "fs", "dialog", @@ -63,33 +88,45 @@ "arch": "any" } ], - "minAppVersion": "1.1.8.9", "defaultLocale": "zh-CN", "i18n": { "en-US": { - "name": "ZIP Archive Manager", - "description": "Select or drop ZIP archives to browse contents and extract all or selected files. Supports ZIP inspection and extraction only (no archive creation).", + "name": "Archive Manager", + "description": "Browse, extract, and create archives via host archive primitives: extract all or selected entries with password support, pack files/folders to ZIP with configurable compression level, and unlock 7z/RAR/encrypted archives when 7z-family extension is available.", "keywords": [ "zip", + "7z", + "rar", "archive", "unzip", "extract", - "decompress", - "files" + "compress", + "pack", + "tar", + "package", + "unarchive" ], "features": { "archive-inspect": { - "explain": "Browse ZIP archive contents and extract all or selected files", + "explain": "Browse archive contents and extract all or selected files", "cmds": [ "unzip", "zip", "archive", - "extract zip", - "inspect zip" + "extract archive", + "inspect archive" + ] + }, + "archive-create": { + "explain": "Pack selected files or folders into a ZIP / 7z archive", + "cmds": [ + "create archive", + "compress files", + "pack zip" ] }, "archive-docs": { - "explain": "Extract office documents from a ZIP archive", + "explain": "Extract office documents from an archive", "cmds": [ "extract docs", "archive docs", diff --git a/extensions/archive-manager/src/i18n.ts b/extensions/archive-manager/src/i18n.ts index dc0c7662..643ef7b3 100644 --- a/extensions/archive-manager/src/i18n.ts +++ b/extensions/archive-manager/src/i18n.ts @@ -1,289 +1,208 @@ -import { createTranslator } from "@ztools/declarative-ui"; +import { createTranslator } from '@ztools/declarative-ui' -const rawT = createTranslator( - { - "zh-CN": { - sizeUnknown: "大小未识别", - notInClient: "需要在 ZTools 客户端中使用", - forbiddenReason: "归档提取目标路径不可指向系统受保护目录或包含路径穿越 (Zip Slip)", - catAll: "全部包内文件", - catDocs: "办公文档 (.pdf/.docx/.xlsx)", - catMedia: "图片与媒体 (.png/.jpg/.mp4)", - catCode: "源码与配置 (.ts/.json/.sql)", - catExec: "可执行程序 (.exe/.msi)", - catOther: "其他文件", - catLabelFolder: "文件夹", - catLabelDocs: "办公文档", - catLabelMedia: "图片与媒体", - catLabelCode: "源码与配置", - catLabelExec: "可执行程序", - catLabelOther: "其他文件", - errInvalidMethodEmpty: "INVALID_METHOD: 调用方法名不能为空", - errInvalidMethodFormat: "INVALID_METHOD_FORMAT: 方法名包含非法字符或超长", - errInvalidParamsObject: "INVALID_PARAMS: 参数必须为非空对象", - errParamTooLong: "PARAM_TOO_LONG: 参数 {key} 超过最大长度限制", - errSecurityIntercepted: "SECURITY_INTERCEPTED: {reason}", - errValidationFailed: "参数校验失败", - errArchivePathEmpty: "压缩包路径不能为空", - errInspectFailed: "透视压缩包失败", - errExtractFailed: "解压提取失败", - verifyInvalidTitle: "校验结果无法识别", - verifyInvalidMsg: "客户端没有返回压缩包的 SHA-256", - verifyShaText: "SHA-256:{prefix}…", - verifyRiskTitle: "发现 {count} 个越界条目", - verifyRiskMsg: "含 ../ 或绝对路径的条目不会被提取 · {sha}", - verifyOkTitle: "已读取压缩包目录,没有越界路径", - verifyOkMsg: "{count} 个文件{enc} · {sha} · 未逐个校验文件 CRC32", - verifyEncryptedPart: " · 含加密条目,暂不支持解压", - extractFailedTitle: "解压失败", - extractFailedDefaultMsg: "客户端没有说明原因", - extractEmptyTitle: "没有解压出任何文件", - extractBlockedMsg: "{count} 个越界条目被拒绝", - extractMissingMsg: "所选条目可能已不在压缩包里", - extractBlockedSuffix: " · {count} 个越界条目未提取", - extractOkTitle: "已解压 {count} 个文件{blocked}", - corruptOrNotZip: "文件可能已损坏或不是 ZIP 格式", - readArchiveFailedTitle: "读取压缩包失败", - readArchiveOkTitle: "已读取压缩包目录", - readArchiveOkMsg: "{count} 个文件 · 解压后 {size}", - importFailedTitle: "导入失败", - pickFilesTitle: "选择 ZIP 压缩包", - pickFilesFilterName: "ZIP 压缩包", - pickFolderTitle: "选择包含 ZIP 压缩包的文件夹", - noFolderSelected: "没有选择文件夹", - confirmRootTitle: "导入整个磁盘 {path} 中的 ZIP 压缩包?", - confirmRootMsg: "将读取该磁盘下 5 层以内的文件夹,最多导入 500 个压缩包,可能需要一些时间。", - confirmRootAction: "继续导入", - dropTitle: "拖入 ZIP 压缩包或文件夹", - dropSubtitle: "文件夹内 5 层以内的 .zip 文件会一并导入", - removeBusy: "正在处理,完成后再移除", - clearBusy: "正在处理,完成后再清空", - encryptedTitle: "暂不支持解压加密的压缩包", - encryptedMsg: "这个压缩包含加密条目,客户端目前不能解压", - confirmExtractSelectedTitle: "提取 {count} 个文件?", - confirmExtractAllTitle: "解压全部文件?", - confirmExtractMsg: "解压到:{target}\n目标位置已有同名文件会被覆盖。", - confirmExtractBtn: "提取", - confirmExtractAllBtn: "解压", - noArchiveToExtractTitle: "没有可解压的压缩包", - noArchiveReadErrorMsg: "读取压缩包失败:{error}", - noArchiveHintMsg: "请先导入或选择一个能读取的 ZIP 压缩包", - extractingProgress: "正在解压…", - noEntriesToExtractTitle: "没有可提取的文件", - noEntriesToExtractMsg: "所选条目为空,或路径含 ../ 等越界写法", - extractingSelectedProgress: "正在提取 {count} 个文件…", - verifyFailedTitle: "校验失败", - verifyFailedDefaultMsg: "压缩包可能已损坏或不是 ZIP 格式", - revealFailedTitle: "无法在资源管理器中定位", - trashBusy: "正在解压,完成后再移入回收站", - confirmTrashTitle: "将原压缩包移入回收站?", - confirmTrashMsg: "{path}\n可以从回收站恢复。", - confirmTrashAction: "移入回收站", - trashSuccessTitle: "已将压缩包移入回收站", - trashFailedTitle: "移入回收站失败", - trashInUseMsg: "压缩包可能正被占用", - searchPlaceholderShort: "搜索包内文件名或路径", - sectionArchives: "压缩包", - clientRequiredSub: "读取和解压压缩包由 Windows 版 ZTools 客户端完成", - actionPickFilesEllipsis: "选择文件…", - actionPickFolderEllipsis: "选择文件夹…", - actionRemove: "从列表移除", - actionClearList: "清空列表", - actionDeselectAll: "取消全选", - actionSelectAll: "全选当前列表", - actionExtractSelected: "提取已勾选的 {count} 个文件", - actionExtractAll: "解压全部", - actionRevealArchive: "在资源管理器中定位压缩包", - actionExtractSingle: "只提取这个文件({name})", - actionVerifyArchive: "校验压缩包(目录、越界路径与 SHA-256)", - actionCopyPathCrc: "复制包内路径与 CRC32", - copyFailedTitle: "复制失败", - copiedPathTitle: "已复制包内路径", - actionTrashArchive: "将原压缩包移入回收站", - sectionList: "列表", - tagUnsafePath: "越界路径,不提取", - noArchiveSelected: "未选择压缩包", - summaryImporting: "正在导入:已读取 {dirs} 个文件夹,找到 {files} 个文件", - summaryEmpty: "尚未添加压缩包 · 可选择文件、文件夹,或直接拖入", - summaryInspectError: "{name} · 读取失败:{error} · 清空列表 Ctrl+Shift+Backspace", - summaryNormal: "{name} ({size}) · {count} 个文件 · 解压后 {uncomp}{checked} · 清空列表 Ctrl+Shift+Backspace", - summaryCheckedPart: " · 已勾选 {count} 个", - emptyImporting: "正在导入…", - emptyNoArchives: "尚未添加 ZIP 压缩包 · 可选择文件、文件夹,或直接拖入", - emptyInspectError: "读取压缩包失败:{error}", - emptyLoading: "正在读取压缩包…", - emptyNoFiles: "这个压缩包里没有文件", - emptyNoMatch: "当前分类下没有匹配的文件", - diagRootTitle: "解压位置", - diagRootSingleSub: "包内只有一个顶层文件夹:解压到压缩包所在目录", - diagRootFolderSub: "解压到压缩包旁的同名文件夹", - diagRootSingleTag: "单个顶层文件夹", - diagRootFolderTag: "同名文件夹", - diagSecurityTitle: "越界路径与加密检查", - diagSecurityRiskSub: "{count} 个条目含 ../ 或绝对路径,不会被提取", - diagSecurityEncSub: "没有越界路径;含加密条目,暂不支持解压", - diagSecuritySafeSub: "没有越界路径", - diagSecurityRiskTag: "{count} 个越界", - diagSecurityEncTag: "含加密条目", - diagSecuritySafeTag: "无越界", - diagVerifyPanelTitle: "校验", - searchPlaceholder: "搜索包内文件名、后缀或路径", - dropdownTooltip: "切换压缩包 (.zip)", - btnPickFiles: "选择文件", - btnPickFolder: "选择文件夹", - subListTitleChecked: "包内文件(已勾选 {count} 个,按 ↵ 提取所选文件)", - subListTitleDefault: "包内文件(按解压后大小排列,按 ↵ 解压全部,或勾选后只提取所选文件)", - subListSubtitle: "{count} 个 · 解压后共 {size}", - sectionFilterByCategory: "按文件类型筛选", - itemCountText: "{count} 项", - actionFilterCategory: "筛选查看「{name}」", - sectionPreCheck: "解压前检查" - }, - "en-US": { - sizeUnknown: "Size unknown", - notInClient: "Requires the ZTools client", - forbiddenReason: "Extract target path cannot point to a protected system directory or contain path traversal (Zip Slip)", - catAll: "All Files", - catDocs: "Documents (.pdf/.docx/.xlsx)", - catMedia: "Images & Media (.png/.jpg/.mp4)", - catCode: "Code & Config (.ts/.json/.sql)", - catExec: "Executables (.exe/.msi)", - catOther: "Other Files", - catLabelFolder: "Folder", - catLabelDocs: "Documents", - catLabelMedia: "Images & Media", - catLabelCode: "Code & Config", - catLabelExec: "Executables", - catLabelOther: "Other", - errInvalidMethodEmpty: "INVALID_METHOD: Method name cannot be empty", - errInvalidMethodFormat: "INVALID_METHOD_FORMAT: Method name contains invalid characters or is too long", - errInvalidParamsObject: "INVALID_PARAMS: Parameters must be a non-null object", - errParamTooLong: "PARAM_TOO_LONG: Parameter {key} exceeds maximum length", - errSecurityIntercepted: "SECURITY_INTERCEPTED: {reason}", - errValidationFailed: "Parameter validation failed", - errArchivePathEmpty: "Archive path cannot be empty", - errInspectFailed: "Failed to inspect archive", - errExtractFailed: "Extraction failed", - verifyInvalidTitle: "Unrecognized Verification Result", - verifyInvalidMsg: "Client did not return archive SHA-256", - verifyShaText: "SHA-256: {prefix}…", - verifyRiskTitle: "Found {count} unsafe path [[count:entry|entries]]", - verifyRiskMsg: "Entries with ../ or absolute paths will not be extracted · {sha}", - verifyOkTitle: "Archive directory verified; no unsafe paths", - verifyOkMsg: "{count} [[count:file|files]]{enc} · {sha} · Per-file CRC32 not extracted", - verifyEncryptedPart: " · Contains encrypted entries (extraction unsupported)", - extractFailedTitle: "Extraction Failed", - extractFailedDefaultMsg: "No reason returned by client", - extractEmptyTitle: "No files extracted", - extractBlockedMsg: "{count} unsafe [[count:entry|entries]] blocked", - extractMissingMsg: "Selected entries may no longer exist in the archive", - extractBlockedSuffix: " · {count} unsafe [[count:entry|entries]] skipped", - extractOkTitle: "Extracted {count} [[count:file|files]]{blocked}", - corruptOrNotZip: "File may be corrupted or not a valid ZIP archive", - readArchiveFailedTitle: "Failed to Read Archive", - readArchiveOkTitle: "Archive Loaded", - readArchiveOkMsg: "{count} [[count:file|files]] · {size} uncompressed", - importFailedTitle: "Import Failed", - pickFilesTitle: "Select ZIP Archives", - pickFilesFilterName: "ZIP Archives", - pickFolderTitle: "Select Folder Containing ZIP Archives", - noFolderSelected: "No folder selected", - confirmRootTitle: "Import ZIP archives from entire drive {path}?", - confirmRootMsg: "Will scan up to 5 folder levels and import at most 500 archives. This may take a while.", - confirmRootAction: "Continue Import", - dropTitle: "Drop ZIP archives or folders", - dropSubtitle: ".zip files within 5 folder levels will be imported", - removeBusy: "Processing in progress; remove after completion", - clearBusy: "Processing in progress; clear after completion", - encryptedTitle: "Encrypted archives not supported", - encryptedMsg: "This archive contains encrypted entries which cannot be extracted yet", - confirmExtractSelectedTitle: "Extract {count} [[count:file|files]]?", - confirmExtractAllTitle: "Extract all files?", - confirmExtractMsg: "Extract to: {target}\nExisting files with the same name will be overwritten.", - confirmExtractBtn: "Extract", - confirmExtractAllBtn: "Extract All", - noArchiveToExtractTitle: "No archive to extract", - noArchiveReadErrorMsg: "Failed to read archive: {error}", - noArchiveHintMsg: "Please import or select a readable ZIP archive first", - extractingProgress: "Extracting…", - noEntriesToExtractTitle: "No extractable files", - noEntriesToExtractMsg: "Selection is empty or contains unsafe paths like ../", - extractingSelectedProgress: "Extracting {count} [[count:file|files]]…", - verifyFailedTitle: "Verification Failed", - verifyFailedDefaultMsg: "Archive may be corrupted or not a valid ZIP file", - revealFailedTitle: "Unable to Reveal in Explorer", - trashBusy: "Extracting in progress; move to trash after completion", - confirmTrashTitle: "Move original archive to Trash?", - confirmTrashMsg: "{path}\nYou can restore it from the Trash.", - confirmTrashAction: "Move to Trash", - trashSuccessTitle: "Moved archive to Trash", - trashFailedTitle: "Failed to Move to Trash", - trashInUseMsg: "Archive may be in use", - searchPlaceholderShort: "Search filename or path in archive", - sectionArchives: "Archives", - clientRequiredSub: "Reading and extracting archives requires the Windows ZTools client", - actionPickFilesEllipsis: "Select Files…", - actionPickFolderEllipsis: "Select Folder…", - actionRemove: "Remove from List", - actionClearList: "Clear List", - actionDeselectAll: "Deselect All", - actionSelectAll: "Select All", - actionExtractSelected: "Extract {count} Selected", - actionExtractAll: "Extract All", - actionRevealArchive: "Reveal Archive in Explorer", - actionExtractSingle: "Extract Only ({name})", - actionVerifyArchive: "Verify Archive (Entries, Paths & SHA-256)", - actionCopyPathCrc: "Copy Entry Path & CRC32", - copyFailedTitle: "Copy Failed", - copiedPathTitle: "Copied Entry Path", - actionTrashArchive: "Move Archive to Trash", - sectionList: "List", - tagUnsafePath: "Unsafe path, skipped", - noArchiveSelected: "No archive selected", - summaryImporting: "Importing: {dirs} [[dirs:folder|folders]] scanned, {files} [[files:file|files]] found", - summaryEmpty: "No archives added · Select files, folder, or drop here", - summaryInspectError: "{name} · Read failed: {error} · Clear Ctrl+Shift+Backspace", - summaryNormal: "{name} ({size}) · {count} [[count:file|files]] · {uncomp} uncompressed{checked} · Clear Ctrl+Shift+Backspace", - summaryCheckedPart: " · {count} checked", - emptyImporting: "Importing…", - emptyNoArchives: "No ZIP archives added · Select files, folder, or drop here", - emptyInspectError: "Failed to read archive: {error}", - emptyLoading: "Reading archive…", - emptyNoFiles: "This archive contains no files", - emptyNoMatch: "No matching files in this category", - diagRootTitle: "Extract Target", - diagRootSingleSub: "Single root folder detected: extracts directly to archive folder", - diagRootFolderSub: "Extracts into a folder named after the archive", - diagRootSingleTag: "Single Root Folder", - diagRootFolderTag: "Named Folder", - diagSecurityTitle: "Path & Encryption Check", - diagSecurityRiskSub: "{count} [[count:entry contains|entries contain]] ../ or absolute paths and will be skipped", - diagSecurityEncSub: "No unsafe paths; contains encrypted entries (extraction unsupported)", - diagSecuritySafeSub: "No unsafe paths", - diagSecurityRiskTag: "{count} unsafe", - diagSecurityEncTag: "Encrypted", - diagSecuritySafeTag: "Safe", - diagVerifyPanelTitle: "Verify", - searchPlaceholder: "Search filename, extension, or path in archive", - dropdownTooltip: "Switch Archive (.zip)", - btnPickFiles: "Select Files", - btnPickFolder: "Select Folder", - subListTitleChecked: "Archive Entries ({count} checked, press ↵ to extract selected)", - subListTitleDefault: "Archive Entries (Sorted by size; press ↵ to extract all or check items)", - subListSubtitle: "{count} [[count:item|items]] · {size} uncompressed", - sectionFilterByCategory: "Filter by Type", - itemCountText: "{count} [[count:item|items]]", - actionFilterCategory: "Filter \"{name}\"", - sectionPreCheck: "Pre-Extract Check" - } +const MESSAGES = { + 'zh-CN': { + sizeUnknown: '大小未识别', + forbiddenReason: '严禁写入系统保护目录或包含目录穿越的路径', + catAll: '全部条目', + catDocs: '文档资料', + catMedia: '图片与媒体', + catCode: '代码与配置', + catExec: '可执行与脚本', + catOther: '其他文件', + catLabelFolder: '文件夹', + catLabelDocs: '文档', + catLabelMedia: '媒体', + catLabelCode: '代码', + catLabelExec: '可执行', + catLabelOther: '其他', + errArchivePathEmpty: '请先选择有效的归档文件', + errInspectFailed: '读取归档目录失败', + errExtractFailed: '解压归档失败', + errCreateFailed: '创建归档失败', + errNoPackSources: '请先添加至少 1 个待打包文件或目录', + err7zNotSupported: '当前宿主尚未启用 7z-family 扩展,请先准备归档扩展引擎或改选 ZIP 格式', + errPasswordNeeds7z: '加密归档需要宿主启用 7z-family 扩展', + errNoTaskToCancel: '当前没有正在运行的归档任务', + errEnsureFailed: '准备归档扩展引擎失败', + errUnsupportedEngine: '当前宿主暂不支持该归档原语', + modeBrowse: '浏览与解压', + modePack: '压缩打包', + wbTitle: '归档工作台', + wbModeLabel: '工作模式', + wbPasswordLabel: '解压 / 打包密码 (可选)', + wbFormatLabel: '打包格式', + wbLevelLabel: '压缩级别', + wbCardTitle: '归档引擎状态', + badgeReady: '就绪', + badgeProvision: '可下载 7zz 扩展', + badgeRunning: '处理中', + cardNote7zReady: '已启用 7z-family 扩展:支持 ZIP / 7z / RAR / TAR 浏览解压及加密打包。', + cardNoteZipOnly: '当前仅启用标准 ZIP(零外部依赖);如需 7z / RAR 或加密归档,请按需准备扩展引擎(7zz)。', + levelStore: '仅存储 (0)', + levelFast: '快速压缩 (1)', + levelNormal: '标准压缩 (5)', + levelMax: '极限压缩 (9)', + actionPickArchive: '打开归档文件...', + actionAddPackFiles: '添加待打包文件...', + actionAddPackFolder: '添加待打包目录...', + actionExtractAll: '整包解压', + actionExtractSelected: '提取勾选 ({count})', + btnExtractSelected: '提取所选 ({count})', + btnExtractAll: '解压全部', + btnExtracting: '解压中…', + actionCreateArchive: '开始打包 ({count})', + actionEnsure7z: '按需准备 7zz 扩展', + actionCancelTask: '取消当前任务', + actionRevealInFolder: '在文件夹中显示', + actionCopyEntryPath: '复制条目路径', + actionToggleAll: '全选 / 取消全选', + actionRemoveSource: '移除此源', + actionClearList: '清空列表', + actionTrashArchive: '移入回收站', + toastInspectOk: '读取归档成功', + toastInspectOkMsg: '共 {count} 个文件 · 原始体积 {size}', + toastInspectFail: '读取归档失败', + toastExtractOk: '解压完成', + toastExtractOkMsg: '已提取 {count} 个文件至 {dir}', + toastExtractFail: '解压失败', + toastCreateOk: '归档打包完成', + toastCreateOkMsg: '已打包 {count} 项({size}):{path}', + toastCreateFail: '归档打包失败', + toastEnsureOk: '7zz 归档扩展已就绪', + toastEnsureFail: '准备 7zz 扩展失败', + toastCancelOk: '已取消当前归档任务', + toastCancelFail: '取消任务失败', + toastCopied: '已复制路径', + toastRevealFail: '无法打开文件位置', + pickArchiveTitle: '选择压缩包文件', + pickArchiveFilter: '压缩包文件', + pickPackFilesTitle: '选择要打包的文件', + pickPackFoldersTitle: '选择要打包的目录', + saveArchiveTitle: '选择压缩包保存路径', + pickExtractDirTitle: '选择解压目标文件夹', + searchPlaceholder: '搜索归档条目或待打包文件...', + dropTitle: '拖入压缩包(浏览解压)或文件/目录(压缩打包)', + dropSubtitle: '标准 ZIP 开箱即用;启用 7z-family 后支持 7z / RAR / 加密归档', + summaryBrowse: '浏览解压 · {archive} · {entries} 个文件', + summaryPack: '压缩打包 · 已选 {count} 个源 · 目标 {format}', + subListBrowseTitle: '归档条目 ({count})', + subListPackTitle: '待打包源文件 ({count})', + emptyBrowse: '请选择或拖入压缩包以浏览内部条目', + emptyPack: '请点击「添加待打包文件/目录」加入需要压缩的内容', + emptyNoMatch: '没有匹配的条目', + noArchiveSelected: '未选择压缩包', + tagEncrypted: '加密', + tagTraversalRisk: '路径越界已拦截', + panelTitle: '解压与压缩', + sectionTitle: '条目列表 ({count})', + metric7zExt: '7z / RAR / 加密扩展', + metricExtReady: '已支持', + metricExtHidden: '未启用 (仅 ZIP)', + metricTotalSize: '归档总原始大小', + metricPackSources: '待打包项' + }, + 'en-US': { + sizeUnknown: 'Unknown size', + forbiddenReason: 'Protected system directories or traversal paths are blocked', + catAll: 'All Entries', + catDocs: 'Documents', + catMedia: 'Media', + catCode: 'Code & Config', + catExec: 'Executables & Scripts', + catOther: 'Other', + catLabelFolder: 'Folder', + catLabelDocs: 'Doc', + catLabelMedia: 'Media', + catLabelCode: 'Code', + catLabelExec: 'Exec', + catLabelOther: 'Other', + errArchivePathEmpty: 'Select a valid archive file first', + errInspectFailed: 'Failed to inspect archive', + errExtractFailed: 'Failed to extract archive', + errCreateFailed: 'Failed to create archive', + errNoPackSources: 'Add at least 1 file or folder to pack first', + err7zNotSupported: 'Host 7z-family extension is unavailable; provision 7zz or use ZIP format', + errPasswordNeeds7z: 'Encrypted archives require the host 7z-family extension', + errNoTaskToCancel: 'No active archive task to cancel', + errEnsureFailed: 'Failed to provision archive extension', + errUnsupportedEngine: 'Host does not support this archive primitive', + modeBrowse: 'Browse & Extract', + modePack: 'Create Archive', + wbTitle: 'Archive Workbench', + wbModeLabel: 'Workflow', + wbPasswordLabel: 'Password (optional)', + wbFormatLabel: 'Archive Format', + wbLevelLabel: 'Compression Level', + wbCardTitle: 'Archive Engine', + badgeReady: 'Ready', + badgeProvision: '7zz Available', + badgeRunning: 'Working', + cardNote7zReady: '7z-family extension active: browse/extract ZIP, 7z, RAR, TAR and create encrypted archives.', + cardNoteZipOnly: 'Built-in standard ZIP mode active (zero external downloads). Provision 7zz extension to unlock 7z/RAR/encryption.', + levelStore: 'Store (0)', + levelFast: 'Fast (1)', + levelNormal: 'Normal (5)', + levelMax: 'Maximum (9)', + actionPickArchive: 'Open Archive...', + actionAddPackFiles: 'Add Files to Pack...', + actionAddPackFolder: 'Add Folders to Pack...', + actionExtractAll: 'Extract All', + actionExtractSelected: 'Extract Selected ({count})', + btnExtractSelected: 'Extract Selected ({count})', + btnExtractAll: 'Extract All', + btnExtracting: 'Extracting…', + actionCreateArchive: 'Create Archive ({count})', + actionEnsure7z: 'Provision 7zz Extension', + actionCancelTask: 'Cancel Active Task', + actionRevealInFolder: 'Reveal in Folder', + actionCopyEntryPath: 'Copy Entry Path', + actionToggleAll: 'Toggle Select All', + actionRemoveSource: 'Remove Source', + actionClearList: 'Clear List', + actionTrashArchive: 'Move to Trash', + toastInspectOk: 'Archive loaded', + toastInspectOkMsg: '{count} file(s) · Uncompressed {size}', + toastInspectFail: 'Failed to load archive', + toastExtractOk: 'Extraction completed', + toastExtractOkMsg: 'Extracted {count} file(s) to {dir}', + toastExtractFail: 'Extraction failed', + toastCreateOk: 'Archive created', + toastCreateOkMsg: 'Packed {count} item(s) ({size}): {path}', + toastCreateFail: 'Archive creation failed', + toastEnsureOk: '7zz archive extension ready', + toastEnsureFail: 'Failed to provision 7zz', + toastCancelOk: 'Active archive task cancelled', + toastCancelFail: 'Failed to cancel task', + toastCopied: 'Copied path', + toastRevealFail: 'Failed to reveal in folder', + pickArchiveTitle: 'Select Archive File', + pickArchiveFilter: 'Archive Files', + pickPackFilesTitle: 'Select Files to Pack', + pickPackFoldersTitle: 'Select Folders to Pack', + saveArchiveTitle: 'Save Archive As', + pickExtractDirTitle: 'Choose Extraction Folder', + searchPlaceholder: 'Filter archive entries or sources...', + dropTitle: 'Drop archives to inspect/extract, or files/folders to pack', + dropSubtitle: 'Standard ZIP works out of the box; 7z/RAR/encryption unlock with 7z-family', + summaryBrowse: 'Browse · {archive} · {entries} file(s)', + summaryPack: 'Pack · {count} source(s) · {format}', + subListBrowseTitle: 'Archive Entries ({count})', + subListPackTitle: 'Pack Sources ({count})', + emptyBrowse: 'Select or drop an archive to inspect its entries', + emptyPack: 'Add files or folders to create a new archive', + emptyNoMatch: 'No matching entries', + noArchiveSelected: 'No archive selected', + tagEncrypted: 'Encrypted', + tagTraversalRisk: 'Path Traversal Blocked', + panelTitle: 'Archive Manager', + sectionTitle: 'Entries ({count})', + metric7zExt: '7z / RAR / Encryption', + metricExtReady: 'Enabled', + metricExtHidden: 'ZIP Only', + metricTotalSize: 'Uncompressed Size', + metricPackSources: 'Sources to Pack' } -) -export const t: typeof rawT = (key, params) => { - const out = rawT(key, params) - if (!out.includes('[[')) return out - return out.replace(/\[\[([A-Za-z0-9_.-]+):([^|\]]+)\|([^\]]+)\]\]/g, (_m, k: string, one: string, other: string) => { - const v = params?.[k] - const n = typeof v === 'number' ? v : Number(String(v ?? '').replace(/,/g, '')) - return n === 1 ? one : other - }) } + +export const t = createTranslator(MESSAGES, { defaultLocale: 'en-US' }) diff --git a/extensions/archive-manager/src/index.ts b/extensions/archive-manager/src/index.ts index 0a9daa23..bdc8887b 100644 --- a/extensions/archive-manager/src/index.ts +++ b/extensions/archive-manager/src/index.ts @@ -1,95 +1,58 @@ +/** + * 解压与压缩(布局三:左侧工作模式与参数工作台 + 右侧归档条目 / 待打包源文件队列) + * + * - 支持两种工作模式:浏览与解压(tool_archive_list / tool_archive_extract)与压缩打包(tool_archive_create) + * - 按宿主 optionalExtensions 自动探测 7z-family:无扩展时自动隐藏 7z 格式与加密选项,并提供按需下载 7zz 引导 + */ import { List, ActionPanel, Action, Icon, - Color, Clipboard, useState, useEffect, useRef, showToast, Toast, - confirmAlert, FilterBar, useLocale } from '@ztools/declarative-ui' import { t } from './i18n.js' import { - ArchiveCandidateItem, - ArchiveEntryItem, - ARCHIVE_IMPORT_RULES, - ARCHIVE_SUPPORTED_TEXT, + buildArchiveImportRules, + buildDefaultPackOutputPath, + cancelActiveArchiveTask, createArchiveImportTransport, - describeExtractTarget, + createArchivePackage, + ensureArchiveExtensionEngine, + extractArchiveEntries, + findCapability, formatBytes, - getArchiveCategoryGroups, + getAvailableCreateFormats, getCategoryLabel, + getCompressionLevelOptions, + has7zFamilyExtension, inspectArchiveEntries, - extractArchiveEntries, - invokeNativeCapability, openArchiveLocation, - summarizeExtractResult, - summarizeVerifyResult, - toArchiveCandidateItem, - trashArchiveFile + pickAnySourcesDialog, + pickSaveArchiveDialog, + queryRuntimeCapabilities, + trashArchiveFile, + type ArchiveCreateFormat, + type ArchiveEntryItem, + type ToolRuntimeCapabilitiesSnapshot } from './logic.js' import { - FileImportResult, NormalizedFileInput, - collectFolderFiles, createImportInputProps, - expandInputPaths, - friendlyFileError, - isVolumeRoot, - mergeByPath, - normalizeFileInput, - pathKey, pickFiles, - pickFolder, - summarizeImport + pickFolder } from './file-import.js' -import { isRealElectronHost } from './native-ipc.js' -import { isDeclarativeFileInputSupported } from './host-compat.js' -import { resolveErrorMessage } from './error-i18n.js' export * from './logic.js' -interface ArchiveMeta { - archiveSizeBytes: number - totalUncompressedBytes: number - compressionRatio: number - isEncrypted: boolean - traversalRiskCount: number - hasSingleRootFolder: boolean - singleRootFolderName: string | null -} - -interface ImportScanProgress { - visitedDirs: number - matchedFiles: number -} - -const EMPTY_META: ArchiveMeta = { - archiveSizeBytes: 0, - totalUncompressedBytes: 0, - compressionRatio: 0, - isEncrypted: false, - traversalRiskCount: 0, - hasSingleRootFolder: false, - singleRootFolderName: null -} - -const SHORTCUT_OPEN_FILES = { modifiers: ['ctrl'] as ('ctrl')[], key: 'o' } -const SHORTCUT_OPEN_FOLDER = { modifiers: ['ctrl', 'shift'] as ('ctrl' | 'shift')[], key: 'o' } -import { ARCHIVE_CATEGORY } from './archive-categories.zh-data.js' - -const SHORTCUT_REMOVE_ITEM = { modifiers: ['ctrl'] as ('ctrl')[], key: 'backspace' } -const SHORTCUT_CLEAR_ALL = { modifiers: ['ctrl', 'shift'] as ('ctrl' | 'shift')[], key: 'backspace' } - -function errorText(err: unknown): string { - return err instanceof Error ? err.message : String(err) -} +type WorkflowMode = 'browse' | 'pack' function readLaunchFeature(): string { const scope = ((globalThis as Record).window || globalThis) as { @@ -102,839 +65,483 @@ function readLaunchFeature(): string { export function ArchiveManagerCommand() { useLocale() - const categoryGroups = getArchiveCategoryGroups() - const initialCategory = readLaunchFeature() === 'archive-docs' ? ARCHIVE_CATEGORY.DOCS : 'ALL' - const isRealHost = isRealElectronHost() + const initialMode: WorkflowMode = readLaunchFeature() === 'archive-create' ? 'pack' : 'browse' const transport = createArchiveImportTransport() + + const [mode, setMode] = useState(initialMode) const [searchText, setSearchText] = useState('') - const [archives, setArchives] = useState([]) - const [selectedArchivePath, setSelectedArchivePath] = useState('') - const [selectedCategory, setSelectedCategory] = useState(initialCategory) + const [capabilities, setCapabilities] = useState(null) + const [activeArchivePath, setActiveArchivePath] = useState('') const [entries, setEntries] = useState([]) - const [inspectError, setInspectError] = useState('') const [checkedEntryIds, setCheckedEntryIds] = useState([]) - const [archiveMeta, setArchiveMeta] = useState(EMPTY_META) - const [isLoading, setIsLoading] = useState(false) - const [isImporting, setIsImporting] = useState(false) - const [importProgress, setImportProgress] = useState(null) - const [isExtracting, setIsExtracting] = useState(false) + const [totalUncompressedBytes, setTotalUncompressedBytes] = useState(0) + const [archivePassword, setArchivePassword] = useState('') - // 切换压缩包与清空/移除时只采用最后一次读取的结果,避免慢结果回写已移除的包 - const inspectSeqRef = useRef(0) - const importSeqRef = useRef(0) - const importAbortRef = useRef(null) - const extractingRef = useRef(false) - const archivesRef = useRef(archives) - archivesRef.current = archives - const selectedArchivePathRef = useRef(selectedArchivePath) - selectedArchivePathRef.current = selectedArchivePath + const [packSources, setPackSources] = useState([]) + const [packFormat, setPackFormat] = useState('zip') + const [compressionLevel, setCompressionLevel] = useState('5') + const [isBusy, setIsBusy] = useState(false) + const [isExtracting, setIsExtracting] = useState(false) - function resetInspectionState() { - inspectSeqRef.current += 1 - setIsLoading(false) - setEntries([]) - setCheckedEntryIds([]) - setArchiveMeta(EMPTY_META) - setInspectError('') - } + const mountedRef = useRef(true) - async function loadArchiveInspection(targetPath: string, showIndicator = false) { - if (!targetPath) return - const seq = ++inspectSeqRef.current - setIsLoading(true) - // 先清掉上一个压缩包的内容,读取失败时不能把旧内容当成当前压缩包显示 - setEntries([]) - setCheckedEntryIds([]) - setArchiveMeta(EMPTY_META) - setInspectError('') - try { - const res = await inspectArchiveEntries(targetPath) - if (seq !== inspectSeqRef.current) return - if (pathKey(selectedArchivePathRef.current) !== pathKey(targetPath)) return - if (!archivesRef.current.some((a) => pathKey(a.path) === pathKey(targetPath))) return - if (!res.ok) { - const reason = resolveErrorMessage(res, t('corruptOrNotZip')) - setInspectError(reason) - await showToast({ style: Toast.Style.Failure, title: t('readArchiveFailedTitle'), message: reason }) - return + async function refreshCapabilities() { + const res = await queryRuntimeCapabilities() + if (mountedRef.current && res.ok && res.data) { + setCapabilities(res.data) + if (!has7zFamilyExtension(res.data)) { + setPackFormat('zip') } - setEntries(res.entries) - setArchiveMeta({ - archiveSizeBytes: res.archiveSizeBytes, - totalUncompressedBytes: res.totalUncompressedBytes, - compressionRatio: res.compressionRatio, - isEncrypted: res.isEncrypted, - traversalRiskCount: res.traversalRiskCount, - hasSingleRootFolder: res.hasSingleRootFolder, - singleRootFolderName: res.singleRootFolderName - }) - if (showIndicator) { - await showToast({ - style: Toast.Style.Success, - title: t('readArchiveOkTitle'), - message: t('readArchiveOkMsg', { count: res.entries.length, size: formatBytes(res.totalUncompressedBytes) }) - }) - } - } catch (err) { - if (seq !== inspectSeqRef.current) return - const msg = errorText(err) - setInspectError(msg) - await showToast({ style: Toast.Style.Failure, title: t('readArchiveFailedTitle'), message: msg }) - } finally { - if (seq === inspectSeqRef.current) setIsLoading(false) } } - function applyImportedArchives(result: FileImportResult) { - const incoming = result.files.map(toArchiveCandidateItem) - const { merged, added, duplicates } = mergeByPath(archivesRef.current, incoming, (item) => item.path) - const hadSelection = Boolean(selectedArchivePathRef.current) - - if (added.length > 0) { - archivesRef.current = merged - setArchives(merged) - } - - const summary = summarizeImport(result, { added: added.length, duplicates }, ARCHIVE_SUPPORTED_TEXT) - if (summary) { - void showToast({ - style: summary.ok ? Toast.Style.Success : Toast.Style.Failure, - title: summary.title, - message: summary.message - }) + useEffect(() => { + mountedRef.current = true + void refreshCapabilities() + return () => { + mountedRef.current = false } + }, []) - // 导入前没有选中任何压缩包时,自动选中新导入的第 1 个并读取包内条目 - if (!hadSelection && added.length > 0) { - const firstPath = added[0]!.path - selectedArchivePathRef.current = firstPath - setSelectedArchivePath(firstPath) - void loadArchiveInspection(firstPath, false) - } - } + const has7z = has7zFamilyExtension(capabilities) + const createCap = findCapability(capabilities, 'archive.create') + const canProvision7z = !has7z && createCap?.status === 'needs_provisioning' + const formatOptions = getAvailableCreateFormats(capabilities) - async function executeArchiveImport( - runner: (signal: AbortSignal, onProgress: (p: ImportScanProgress) => void) => Promise - ) { - importAbortRef.current?.abort() - const controller = new AbortController() - importAbortRef.current = controller - const batchSeq = ++importSeqRef.current - setIsImporting(true) - setImportProgress(null) + async function loadArchive(archivePath: string) { + if (!archivePath) return + setIsBusy(true) try { - const result = await runner(controller.signal, (p) => { - if (batchSeq === importSeqRef.current) setImportProgress(p) + const res = await inspectArchiveEntries(archivePath, { password: archivePassword || undefined }) + if (!mountedRef.current) return + if (!res.ok) { + setEntries([]) + setTotalUncompressedBytes(0) + showToast({ style: Toast.Style.Failure, title: t('toastInspectFail'), message: res.error }) + return + } + setActiveArchivePath(res.archivePath) + setEntries(res.entries) + setCheckedEntryIds([]) + setTotalUncompressedBytes(res.totalUncompressedBytes) + showToast({ + style: Toast.Style.Success, + title: t('toastInspectOk'), + message: t('toastInspectOkMsg', { count: res.entries.length, size: formatBytes(res.totalUncompressedBytes) }) }) - if (batchSeq !== importSeqRef.current) return - applyImportedArchives(result) - } catch (err) { - if (batchSeq !== importSeqRef.current) return - await showToast({ style: Toast.Style.Failure, title: t('importFailedTitle'), message: friendlyFileError(err) }) } finally { - if (batchSeq === importSeqRef.current) { - importAbortRef.current = null - setIsImporting(false) - setImportProgress(null) - } + if (mountedRef.current) setIsBusy(false) } } - function handlePickFiles() { - void executeArchiveImport(() => - pickFiles(transport, ARCHIVE_IMPORT_RULES, { - title: t('pickFilesTitle'), - filterName: t('pickFilesFilterName') - }) - ) + async function handlePickArchive() { + const rules = buildArchiveImportRules(capabilities) + const res = await pickFiles(transport, rules, { + title: t('pickArchiveTitle'), + filterName: t('pickArchiveFilter') + }) + if (res.files.length > 0) { + setMode('browse') + await loadArchive(res.files[0]!.path) + } } - function handlePickFolder() { - void executeArchiveImport(async (signal, onProgress) => { - const picked = await pickFolder(transport, { title: t('pickFolderTitle') }) - if (picked.canceled) return { files: [], ignored: 0, truncated: false, failedDirs: [], canceled: true } - if (picked.error || !picked.folderPath) { - return { - files: [], - ignored: 0, - truncated: false, - failedDirs: [], - canceled: false, - error: resolveErrorMessage(picked, t('noFolderSelected')) - } - } - if (isVolumeRoot(picked.folderPath)) { - const ok = await confirmAlert({ - title: t('confirmRootTitle', { path: picked.folderPath }), - message: t('confirmRootMsg'), - primaryAction: { title: t('confirmRootAction'), style: 'default' } - }) - if (!ok) return { files: [], ignored: 0, truncated: false, failedDirs: [], canceled: true } - } - return collectFolderFiles(transport, picked.folderPath, ARCHIVE_IMPORT_RULES, { signal, onProgress }) + async function handleAddPackSources(directories: boolean) { + const picked = await pickAnySourcesDialog({ + title: directories ? t('pickPackFoldersTitle') : t('pickPackFilesTitle'), + directories }) + if (picked.canceled || picked.paths.length === 0) return + setMode('pack') + setPackSources((prev) => Array.from(new Set([...prev, ...picked.paths]))) } function handleFileInput(input: NormalizedFileInput) { - void executeArchiveImport((signal, onProgress) => - expandInputPaths(transport, input.paths, ARCHIVE_IMPORT_RULES, { - knownDirectories: input.directories, - signal, - onProgress - }) - ) - } - - const handleFileInputRef = useRef(handleFileInput) - handleFileInputRef.current = handleFileInput - - useEffect(() => { - let removeDropListener: (() => void) | undefined - if (!isDeclarativeFileInputSupported()) { - const w = typeof window !== 'undefined' ? (window as unknown as Record) : null - const eventsApi = ( - w?.ztools as - | { - events?: { - on?: (ev: string, cb: (payload: unknown) => void) => unknown - off?: (ev: string, cb: (payload: unknown) => void) => void - } - } - | undefined - )?.events - if (eventsApi && typeof eventsApi.on === 'function') { - const onDrop = (envelope: unknown) => { - const input = normalizeFileInput(envelope) - if (input.paths.length > 0) handleFileInputRef.current(input) - } - const dispose = eventsApi.on('plugin_files_dropped', onDrop) - removeDropListener = () => { - if (typeof dispose === 'function') { - ;(dispose as () => void)() - } else if (typeof eventsApi.off === 'function') { - eventsApi.off('plugin_files_dropped', onDrop) - } - } - } - } - - return () => { - importSeqRef.current += 1 - inspectSeqRef.current += 1 - importAbortRef.current?.abort() - removeDropListener?.() - } - }, []) - - const fileInputProps = createImportInputProps( - (input) => handleFileInputRef.current(input), - { - dropTitle: t('dropTitle'), - dropSubtitle: t('dropSubtitle') - } - ) - - async function handleSelectArchive(nextPath: string) { - if (!nextPath) return - selectedArchivePathRef.current = nextPath - setSelectedArchivePath(nextPath) - setSelectedCategory('ALL') - await loadArchiveInspection(nextPath, true) - } - - function removeArchiveCandidate(targetPath: string) { - const key = pathKey(targetPath) - const idx = archivesRef.current.findIndex((a) => pathKey(a.path) === key) - if (idx < 0) return - const nextArchives = archivesRef.current.filter((_, i) => i !== idx) - archivesRef.current = nextArchives - setArchives(nextArchives) - - if (pathKey(selectedArchivePathRef.current) !== key) return - if (nextArchives.length === 0) { - selectedArchivePathRef.current = '' - setSelectedArchivePath('') - resetInspectionState() + if (input.paths.length === 0) return + if (mode === 'pack') { + setPackSources((prev) => Array.from(new Set([...prev, ...input.paths]))) return } - const nextArchive = nextArchives[Math.min(idx, nextArchives.length - 1)]! - selectedArchivePathRef.current = nextArchive.path - setSelectedArchivePath(nextArchive.path) - setSelectedCategory('ALL') - void loadArchiveInspection(nextArchive.path, false) - } - - function handleRemoveCurrentArchive() { - if (extractingRef.current) { - void showToast({ style: Toast.Style.Failure, title: t('removeBusy') }) - return + const first = input.paths[0]! + if (/\.(?:zip|7z|rar|tar)$/i.test(first)) { + void loadArchive(first) + } else { + setMode('pack') + setPackSources((prev) => Array.from(new Set([...prev, ...input.paths]))) } - const current = selectedArchivePathRef.current - if (!current) return - removeArchiveCandidate(current) } - function handleClearList() { - if (extractingRef.current) { - void showToast({ style: Toast.Style.Failure, title: t('clearBusy') }) + async function handleExtract(selectedOnly: boolean) { + if (!activeArchivePath) { + showToast({ style: Toast.Style.Failure, title: t('toastExtractFail'), message: t('errArchivePathEmpty') }) return } - importSeqRef.current += 1 - importAbortRef.current?.abort() - importAbortRef.current = null - setIsImporting(false) - setImportProgress(null) - archivesRef.current = [] - setArchives([]) - selectedArchivePathRef.current = '' - setSelectedArchivePath('') - resetInspectionState() - } - - const checkedSet = new Set(checkedEntryIds) - const checkedEntries = entries.filter((e) => checkedSet.has(e.id) && !e.hasPathTraversalRisk) - - /** 解压会覆盖目标位置的同名文件,执行前必须让用户确认目标文件夹 */ - async function confirmExtract(selective: boolean, count: number): Promise { - if (archiveMeta.isEncrypted) { - await showToast({ - style: Toast.Style.Failure, - title: t('encryptedTitle'), - message: t('encryptedMsg') - }) - return false - } - const target = describeExtractTarget(selectedArchivePath, archiveMeta, selective) - return confirmAlert({ - title: selective ? t('confirmExtractSelectedTitle', { count }) : t('confirmExtractAllTitle'), - message: t('confirmExtractMsg', { target }), - primaryAction: { title: selective ? t('confirmExtractBtn') : t('confirmExtractAllBtn') } - }) - } + const pickedDir = await pickFolder(transport, { title: t('pickExtractDirTitle') }) + if (pickedDir.canceled) return + const selectedNames = selectedOnly + ? entries.filter((e) => checkedEntryIds.includes(e.id)).map((e) => e.entryName) + : undefined - async function runExtract(options: { entryNames?: string[]; smartUnwrap: boolean }, progressTitle: string) { - extractingRef.current = true + setIsBusy(true) setIsExtracting(true) - let progressToast: { hide: () => Promise } | null = null try { - progressToast = await showToast({ - style: Toast.Style.Animated, - title: progressTitle, - message: selectedArchivePath.split(/[\\/]/).pop() || '' + const res = await extractArchiveEntries(activeArchivePath, { + outputDir: pickedDir.folderPath || undefined, + entries: selectedNames && selectedNames.length > 0 ? selectedNames : undefined, + password: has7z && archivePassword ? archivePassword : undefined }) - const res = await extractArchiveEntries(selectedArchivePath, options) - await progressToast?.hide() - const summary = summarizeExtractResult(res) - await showToast({ - style: summary.ok ? Toast.Style.Success : Toast.Style.Failure, - title: summary.title, - ...(summary.message ? { message: summary.message } : {}) - }) - } catch (err) { - await progressToast?.hide() - await showToast({ style: Toast.Style.Failure, title: t('extractFailedTitle'), message: errorText(err) }) + if (!mountedRef.current) return + if (!res.ok) { + showToast({ style: Toast.Style.Failure, title: t('toastExtractFail'), message: res.error }) + } else { + showToast({ + style: Toast.Style.Success, + title: t('toastExtractOk'), + message: t('toastExtractOkMsg', { count: res.extractedCount, dir: res.targetDir }) + }) + } } finally { - extractingRef.current = false - setIsExtracting(false) - } - } - - async function handleExtractAll() { - if (extractingRef.current) return - if (!selectedArchivePath || inspectError || entries.length === 0) { - await showToast({ - style: Toast.Style.Failure, - title: t('noArchiveToExtractTitle'), - message: inspectError ? t('noArchiveReadErrorMsg', { error: inspectError }) : t('noArchiveHintMsg') - }) - return + if (mountedRef.current) { + setIsExtracting(false) + setIsBusy(false) + } } - if (!(await confirmExtract(false, entries.length))) return - await runExtract({ smartUnwrap: true }, t('extractingProgress')) } - async function handleExtractSelectedEntries(targetEntries: ArchiveEntryItem[]) { - if (!selectedArchivePath || extractingRef.current) return - const safeTargets = targetEntries.filter((e) => !e.hasPathTraversalRisk) - if (safeTargets.length === 0) { - await showToast({ - style: Toast.Style.Failure, - title: t('noEntriesToExtractTitle'), - message: t('noEntriesToExtractMsg') - }) + async function handleCreateArchive() { + if (packSources.length === 0) { + showToast({ style: Toast.Style.Failure, title: t('toastCreateFail'), message: t('errNoPackSources') }) return } - if (!(await confirmExtract(true, safeTargets.length))) return - await runExtract( - { entryNames: safeTargets.map((e) => e.entryName), smartUnwrap: false }, - t('extractingSelectedProgress', { count: safeTargets.length }) - ) - } + const defaultOut = buildDefaultPackOutputPath(packSources[0]!, packFormat) + const saved = await pickSaveArchiveDialog({ + title: t('saveArchiveTitle'), + defaultPath: defaultOut, + format: packFormat + }) + if (saved.canceled) return - async function handleVerifyArchive() { - if (!selectedArchivePath) return - let res: Awaited> + setIsBusy(true) try { - res = await invokeNativeCapability('VerifyArchive', { archivePath: selectedArchivePath }) - } catch (err) { - await showToast({ style: Toast.Style.Failure, title: t('verifyFailedTitle'), message: errorText(err) }) - return - } - if (!res.ok) { - await showToast({ - style: Toast.Style.Failure, - title: t('verifyFailedTitle'), - message: resolveErrorMessage(res, t('verifyFailedDefaultMsg')) + const res = await createArchivePackage(packSources, { + outputPath: saved.filePath || defaultOut, + format: packFormat, + compressionLevel: Number(compressionLevel), + password: has7z && archivePassword ? archivePassword : undefined, + capabilities }) - return - } - const summary = summarizeVerifyResult(res.data) - await showToast({ - style: summary.ok ? Toast.Style.Success : Toast.Style.Failure, - title: summary.title, - message: summary.message - }) - } - - async function handleRevealArchive() { - if (!selectedArchivePath) return - const ok = await openArchiveLocation(selectedArchivePath) - if (!ok) { - await showToast({ style: Toast.Style.Failure, title: t('revealFailedTitle'), message: selectedArchivePath }) + if (!mountedRef.current) return + if (!res.ok) { + showToast({ style: Toast.Style.Failure, title: t('toastCreateFail'), message: res.error }) + } else { + showToast({ + style: Toast.Style.Success, + title: t('toastCreateOk'), + message: t('toastCreateOkMsg', { + count: res.entryCount, + size: formatBytes(res.outputBytes), + path: res.outputPath + }) + }) + } + } finally { + if (mountedRef.current) setIsBusy(false) } } - async function handleTrashArchive() { - const targetPath = selectedArchivePath - if (!targetPath) return - if (extractingRef.current) { - await showToast({ style: Toast.Style.Failure, title: t('trashBusy') }) - return - } - const ok = await confirmAlert({ - title: t('confirmTrashTitle'), - message: t('confirmTrashMsg', { path: targetPath }), - primaryAction: { title: t('confirmTrashAction'), style: 'destructive' } - }) - if (!ok) return - const tr = await trashArchiveFile(targetPath) - if (tr.ok) { - await showToast({ style: Toast.Style.Success, title: t('trashSuccessTitle') }) - removeArchiveCandidate(targetPath) - } else { - await showToast({ - style: Toast.Style.Failure, - title: t('trashFailedTitle'), - message: resolveErrorMessage(tr, t('trashInUseMsg')) - }) + async function handleEnsure7z() { + setIsBusy(true) + try { + const res = await ensureArchiveExtensionEngine() + if (!mountedRef.current) return + if (!res.ok) { + showToast({ style: Toast.Style.Failure, title: t('toastEnsureFail'), message: res.error }) + } else { + showToast({ style: Toast.Style.Success, title: t('toastEnsureOk') }) + } + await refreshCapabilities() + } finally { + if (mountedRef.current) setIsBusy(false) } } - if (!isRealHost) { - return List({ - searchBarPlaceholder: t('searchPlaceholderShort'), - children: [ - List.Section({ - title: t('sectionArchives'), - children: [ - List.Item({ - id: 'archive-client-required', - title: t('notInClient'), - subtitle: t('clientRequiredSub'), - icon: { source: Icon.Info } - }) - ] - }) - ] - }) - } - - const pickFilesAction = () => - Action({ - title: t('actionPickFilesEllipsis'), - icon: Icon.Plus, - shortcut: SHORTCUT_OPEN_FILES, - onAction: handlePickFiles - }) - const pickFolderAction = () => - Action({ - title: t('actionPickFolderEllipsis'), - icon: Icon.Folder, - shortcut: SHORTCUT_OPEN_FOLDER, - onAction: handlePickFolder - }) - const removeArchiveAction = () => - Action({ - title: t('actionRemove'), - icon: Icon.Minus, - shortcut: SHORTCUT_REMOVE_ITEM, - onAction: handleRemoveCurrentArchive + async function handleCancel() { + const res = await cancelActiveArchiveTask() + showToast({ + style: res.ok ? Toast.Style.Success : Toast.Style.Failure, + title: res.ok ? t('toastCancelOk') : t('toastCancelFail'), + message: res.ok ? res.taskId : res.error }) - const clearListAction = () => - Action({ - title: t('actionClearList'), - icon: Icon.Trash, - style: Action.Style.Destructive, - shortcut: SHORTCUT_CLEAR_ALL, - onAction: handleClearList - }) - - const categoryCounts = new Map() - for (const grp of categoryGroups) { - categoryCounts.set(grp.id, { count: 0, bytes: 0 }) - } - for (const e of entries) { - const allStat = categoryCounts.get('ALL')! - allStat.count += 1 - allStat.bytes += e.uncompressedSize - const catStat = categoryCounts.get(e.category) ?? { count: 0, bytes: 0 } - catStat.count += 1 - catStat.bytes += e.uncompressedSize - categoryCounts.set(e.category, catStat) } const q = searchText.trim().toLowerCase() - const filteredEntries = entries.filter((e) => { - if (selectedCategory !== 'ALL' && e.category !== selectedCategory) return false - if (!q) return true - return ( - e.name.toLowerCase().includes(q) || - e.entryName.toLowerCase().includes(q) || - e.category.toLowerCase().includes(q) || - e.crc32.toLowerCase().includes(q) - ) - }) - - const maxEntryBytes = Math.max(1, filteredEntries[0]?.uncompressedSize || 1) - const hasChecked = checkedEntries.length > 0 - const safeFilteredEntries = filteredEntries.filter((item) => !item.hasPathTraversalRisk) - const allSafeChecked = safeFilteredEntries.length > 0 && safeFilteredEntries.every((item) => checkedSet.has(item.id)) - - const toggleAllAction = () => - Action({ - title: allSafeChecked ? t('actionDeselectAll') : t('actionSelectAll'), - icon: Icon.CheckCircle, - shortcut: { modifiers: ['ctrl'], key: 'a' }, - onAction: () => { - setCheckedEntryIds(allSafeChecked ? [] : safeFilteredEntries.map((item) => item.id)) - } - }) - - const rightSubListItems = filteredEntries.map((entry) => { - const isChecked = checkedSet.has(entry.id) - const volRatio = Math.max(8, Math.min(100, Math.round((entry.uncompressedSize / maxEntryBytes) * 100))) - const panelChildren: Array | ReturnType> = [ - hasChecked - ? Action({ - title: t('actionExtractSelected', { count: checkedEntries.length }), - icon: Icon.Download, - onAction: () => handleExtractSelectedEntries(checkedEntries) - }) - : Action({ - title: t('actionExtractAll'), - icon: Icon.Download, - onAction: handleExtractAll - }), - Action({ - title: t('actionRevealArchive'), - icon: Icon.Folder, - onAction: handleRevealArchive - }), - Action({ - title: t('actionExtractSingle', { name: entry.name }), - icon: Icon.Document, - shortcut: { modifiers: ['ctrl'], key: 's' }, - onAction: () => handleExtractSelectedEntries([entry]) - }) - ] - if (hasChecked) { - panelChildren.push( - Action({ - title: t('actionExtractAll'), - icon: Icon.Download, - shortcut: { modifiers: ['ctrl'], key: 'e' }, - onAction: handleExtractAll - }) - ) - } - panelChildren.push( - Action({ - title: t('actionVerifyArchive'), - icon: Icon.CheckCircle, - shortcut: { modifiers: ['ctrl'], key: 't' }, - onAction: handleVerifyArchive - }), - Action({ - title: t('actionCopyPathCrc'), - icon: Icon.CopyClipboard, - shortcut: { modifiers: ['ctrl', 'shift'], key: 'c' }, - onAction: async () => { - const info = `${entry.entryName} (CRC32: ${entry.crc32}, ${formatBytes(entry.uncompressedSize)})` - try { - await Clipboard.copy(info) - } catch (err) { - await showToast({ style: Toast.Style.Failure, title: t('copyFailedTitle'), message: errorText(err) }) - return - } - await showToast({ style: Toast.Style.Success, title: t('copiedPathTitle'), message: info }) - } - }), - Action({ - title: t('actionTrashArchive'), - icon: Icon.Trash, - style: Action.Style.Destructive, - shortcut: { modifiers: [], key: 'delete' }, - onAction: handleTrashArchive - }), - ActionPanel.Section({ - title: t('sectionList'), - children: [ - ...(isExtracting ? [] : [removeArchiveAction()]), - pickFilesAction(), - pickFolderAction(), - toggleAllAction(), - clearListAction() - ] - }) - ) + const visibleEntries = entries.filter((e) => !q || e.name.toLowerCase().includes(q) || e.entryName.toLowerCase().includes(q)) + const visiblePackSources = packSources.filter((p) => !q || p.toLowerCase().includes(q)) + const hasChecked = checkedEntryIds.length > 0 + const browseItems = visibleEntries.map((entry) => { + const isChecked = checkedEntryIds.includes(entry.id) return List.Item({ id: entry.id, title: entry.name, - subtitle: `${entry.entryName} · CRC32: ${entry.crc32}`, + subtitle: entry.entryName, + icon: { source: Icon.Document }, checkable: !entry.hasPathTraversalRisk, checked: isChecked, - onCheckChange: (checked) => { + onCheckChange: () => { if (entry.hasPathTraversalRisk) return - if (checked) { - setCheckedEntryIds(Array.from(new Set([...checkedEntryIds, entry.id]))) - } else { - setCheckedEntryIds(checkedEntryIds.filter((id) => id !== entry.id)) - } - }, - icon: { - source: entry.hasPathTraversalRisk ? Icon.ExclamationMark : Icon.Document, - tintColor: entry.hasPathTraversalRisk ? Color.Red : Color.SecondaryText + setCheckedEntryIds((prev) => (prev.includes(entry.id) ? prev.filter((id) => id !== entry.id) : [...prev, entry.id])) }, accessories: [ - { progress: { value: volRatio } }, - entry.hasPathTraversalRisk - ? { tag: { value: t('tagUnsafePath'), color: Color.Red } } - : { tag: { value: `${getCategoryLabel(entry.category)} -${entry.compressionRatio}%` } }, + ...(entry.hasPathTraversalRisk ? [{ tag: t('tagTraversalRisk') }] : []), + ...(entry.isEncrypted ? [{ tag: t('tagEncrypted') }] : []), + { tag: getCategoryLabel(entry.category) }, { text: formatBytes(entry.uncompressedSize) } ], - actions: ActionPanel({ title: entry.name, children: panelChildren }) + actions: ActionPanel({ + title: entry.name, + children: [ + Action({ + title: hasChecked ? t('actionExtractSelected', { count: checkedEntryIds.length }) : t('actionExtractAll'), + icon: Icon.Download, + onAction: () => handleExtract(hasChecked) + }), + Action({ + title: t('actionCopyEntryPath'), + icon: Icon.CopyClipboard, + onAction: async () => { + await Clipboard.copy(entry.entryName) + showToast({ style: Toast.Style.Success, title: t('toastCopied') }) + } + }), + Action({ + title: t('actionRevealInFolder'), + icon: Icon.Folder, + onAction: async () => { + if (!(await openArchiveLocation(activeArchivePath))) { + showToast({ style: Toast.Style.Failure, title: t('toastRevealFail') }) + } + } + }) + ] + }) }) }) - const currentArchive = archives.find((a) => pathKey(a.path) === pathKey(selectedArchivePath)) - const currentArchiveName = - currentArchive?.name || selectedArchivePath.split(/[\\/]/).pop() || t('noArchiveSelected') - const displayArchiveSizeBytes = - archiveMeta.archiveSizeBytes > 0 ? archiveMeta.archiveSizeBytes : currentArchive?.sizeBytes ?? null - - const summaryText = isImporting - ? t('summaryImporting', { dirs: importProgress?.visitedDirs ?? 0, files: importProgress?.matchedFiles ?? 0 }) - : archives.length === 0 - ? t('summaryEmpty') - : inspectError - ? t('summaryInspectError', { name: currentArchiveName, error: inspectError }) - : t('summaryNormal', { - name: currentArchiveName, - size: formatBytes(displayArchiveSizeBytes), - count: entries.length, - uncomp: formatBytes(archiveMeta.totalUncompressedBytes), - checked: hasChecked ? t('summaryCheckedPart', { count: checkedEntries.length }) : '' - }) - - const emptyText = isImporting - ? t('emptyImporting') - : archives.length === 0 - ? t('emptyNoArchives') - : inspectError - ? t('emptyInspectError', { error: inspectError }) - : isLoading - ? t('emptyLoading') - : entries.length === 0 - ? t('emptyNoFiles') - : t('emptyNoMatch') - - const diagnosticItems = - entries.length > 0 - ? [ - List.Item({ - id: 'diag-root-mode', - title: t('diagRootTitle'), - subtitle: archiveMeta.hasSingleRootFolder ? t('diagRootSingleSub') : t('diagRootFolderSub'), - icon: { source: Icon.Folder, tintColor: Color.SecondaryText }, - accessories: [{ tag: { value: archiveMeta.hasSingleRootFolder ? t('diagRootSingleTag') : t('diagRootFolderTag') } }], - actions: ActionPanel({ - title: t('diagRootTitle'), - children: [Action({ title: t('actionExtractAll'), icon: Icon.Download, onAction: handleExtractAll })] - }) + const packItems = visiblePackSources.map((srcPath) => { + const name = srcPath.split(/[\\/]/).pop() || srcPath + return List.Item({ + id: `pack:${srcPath}`, + title: name, + subtitle: srcPath, + icon: { source: Icon.Folder }, + actions: ActionPanel({ + title: name, + children: [ + Action({ title: t('actionCreateArchive', { count: packSources.length }), icon: Icon.Download, onAction: handleCreateArchive }), + Action({ + title: t('actionRemoveSource'), + icon: Icon.Trash, + onAction: () => setPackSources((prev) => prev.filter((p) => p !== srcPath)) }), - List.Item({ - id: 'diag-security', - title: t('diagSecurityTitle'), - subtitle: - archiveMeta.traversalRiskCount > 0 - ? t('diagSecurityRiskSub', { count: archiveMeta.traversalRiskCount }) - : archiveMeta.isEncrypted - ? t('diagSecurityEncSub') - : t('diagSecuritySafeSub'), - icon: { - source: archiveMeta.traversalRiskCount > 0 ? Icon.ExclamationMark : Icon.CheckCircle, - tintColor: archiveMeta.traversalRiskCount > 0 ? Color.Red : Color.SecondaryText - }, - accessories: [ - archiveMeta.traversalRiskCount > 0 - ? { tag: { value: t('diagSecurityRiskTag', { count: archiveMeta.traversalRiskCount }), color: Color.Red } } - : { tag: { value: archiveMeta.isEncrypted ? t('diagSecurityEncTag') : t('diagSecuritySafeTag') } } - ], - actions: ActionPanel({ - title: t('diagVerifyPanelTitle'), - children: [ - Action({ - title: t('actionVerifyArchive'), - icon: Icon.CheckCircle, - onAction: handleVerifyArchive - }) - ] - }) - }) + Action({ title: t('actionClearList'), icon: Icon.Trash, onAction: () => setPackSources([]) }) ] - : [] + }) + }) + }) - const listActions = ActionPanel({ - children: [ - pickFilesAction(), - pickFolderAction(), - ...(archives.length > 0 - ? [ - ActionPanel.Section({ - title: t('sectionList'), - children: [...(selectedArchivePath && !isExtracting ? [removeArchiveAction()] : []), clearListAction()] - }) - ] - : []) - ] + type ArchiveWorkbenchField = NonNullable[0]>['workbenchPanel']>['fields']>[number] + const workbenchFields: ArchiveWorkbenchField[] = [ + { + id: 'arc-mode', + label: t('wbModeLabel'), + type: 'select', + value: mode, + onChange: (val: string) => { + if (val === 'browse' || val === 'pack') setMode(val) + }, + options: [ + { label: t('modeBrowse'), value: 'browse' }, + { label: t('modePack'), value: 'pack' } + ] + } + ] + + if (mode === 'pack') { + workbenchFields.push( + { + id: 'arc-format', + label: t('wbFormatLabel'), + type: 'select', + value: packFormat, + onChange: (val: string) => { + if (formatOptions.some((o) => o.value === val)) setPackFormat(val as ArchiveCreateFormat) + }, + options: formatOptions + }, + { + id: 'arc-level', + label: t('wbLevelLabel'), + type: 'select', + value: compressionLevel, + onChange: setCompressionLevel, + options: getCompressionLevelOptions() + } + ) + } + + // 仅当宿主具备 7z-family 扩展时才展示加密密码输入框(否则降级隐藏) + if (has7z) { + workbenchFields.push({ + id: 'arc-password', + label: t('wbPasswordLabel'), + type: 'text', + value: archivePassword, + onChange: setArchivePassword + }) + } + + const activeItems = mode === 'pack' ? packItems : browseItems + const fileInputProps = createImportInputProps(handleFileInput, { + dropTitle: t('dropTitle'), + dropSubtitle: t('dropSubtitle') }) + const extractActionLabel = isExtracting + ? t('btnExtracting') + : hasChecked + ? t('btnExtractSelected', { count: checkedEntryIds.length }) + : t('btnExtractAll') + return List({ - ...fileInputProps, searchBarPlaceholder: t('searchPlaceholder'), onSearchTextChange: setSearchText, isShowingDetail: false, - isLoading: isImporting || isLoading || isExtracting, - actions: listActions, - searchBarAccessory: List.Dropdown({ - tooltip: t('dropdownTooltip'), - value: selectedArchivePath, - onChange: (val) => { - if (val) void handleSelectArchive(val) - }, - children: archives.map((arc) => - List.Dropdown.Item({ - title: `${arc.name} (${formatBytes(arc.sizeBytes)})`, - value: arc.path - }) - ) - }), + isLoading: isBusy, + ...fileInputProps, filterBar: FilterBar({ - summaryText, - actions: [ - { - id: 'pick-files', - label: t('btnPickFiles'), - title: t('btnPickFiles'), - style: 'secondary', - onAction: handlePickFiles - }, - { - id: 'pick-folder', - label: t('btnPickFolder'), - title: t('btnPickFolder'), - style: 'secondary', - onAction: handlePickFolder - } - ] + summaryText: + mode === 'pack' + ? t('summaryPack', { count: packSources.length, format: packFormat.toUpperCase() }) + : t('summaryBrowse', { + archive: activeArchivePath ? activeArchivePath.split(/[\\/]/).pop() || activeArchivePath : t('noArchiveSelected'), + entries: entries.length + }), + actions: + mode === 'pack' + ? [ + { + id: 'arc-primary', + label: t('actionCreateArchive', { count: packSources.length }), + title: t('actionCreateArchive', { count: packSources.length }), + style: 'primary', + disabled: isBusy, + onAction: () => { + void handleCreateArchive() + } + }, + { + id: 'arc-secondary', + label: t('actionAddPackFiles'), + title: t('actionAddPackFiles'), + style: 'secondary', + onAction: () => { + void handleAddPackSources(false) + } + } + ] + : activeArchivePath && entries.length > 0 + ? [ + { + id: 'pick-files', + label: t('actionPickArchive'), + title: t('actionPickArchive'), + style: 'secondary', + onAction: () => { + void handlePickArchive() + } + }, + { + id: 'extract-action', + label: extractActionLabel, + title: extractActionLabel, + style: 'primary', + disabled: isExtracting || isBusy, + onAction: () => { + void handleExtract(hasChecked) + } + } + ] + : [ + { + id: 'pick-files', + label: t('actionPickArchive'), + title: t('actionPickArchive'), + style: 'secondary', + onAction: () => { + void handlePickArchive() + } + }, + { + id: 'pick-folder', + label: t('actionAddPackFolder'), + title: t('actionAddPackFolder'), + style: 'secondary', + onAction: () => { + void handleAddPackSources(true) + } + } + ] }), + workbenchPanel: { + title: t('wbTitle'), + subtitle: mode === 'pack' ? t('modePack') : t('modeBrowse'), + fields: workbenchFields, + previewCard: { + title: t('wbCardTitle'), + badge: isBusy ? t('badgeRunning') : canProvision7z ? t('badgeProvision') : t('badgeReady'), + subtitle: has7z ? t('cardNote7zReady') : t('cardNoteZipOnly'), + metrics: [ + { label: t('metric7zExt'), value: has7z ? t('metricExtReady') : t('metricExtHidden') }, + mode === 'pack' + ? { label: t('metricPackSources'), value: String(packSources.length) } + : { label: t('metricTotalSize'), value: formatBytes(totalUncompressedBytes) } + ] + } + }, subList: { - title: hasChecked - ? t('subListTitleChecked', { count: checkedEntries.length }) - : t('subListTitleDefault'), - subtitle: t('subListSubtitle', { count: filteredEntries.length, size: formatBytes(archiveMeta.totalUncompressedBytes) }), - checkable: filteredEntries.length > 0, - checked: - filteredEntries.length > 0 && filteredEntries.every((e) => checkedSet.has(e.id)) - ? true - : filteredEntries.some((e) => checkedSet.has(e.id)) - ? 'indeterminate' - : false, - onCheckChange: (checked) => { - const safeIds = filteredEntries.filter((e) => !e.hasPathTraversalRisk).map((e) => e.id) - setCheckedEntryIds(checked ? safeIds : []) - }, - emptyText, - items: rightSubListItems + title: mode === 'pack' ? t('subListPackTitle', { count: visiblePackSources.length }) : t('subListBrowseTitle', { count: visibleEntries.length }), + emptyText: q ? t('emptyNoMatch') : mode === 'pack' ? t('emptyPack') : t('emptyBrowse'), + items: activeItems }, + actions: ActionPanel({ + title: t('panelTitle'), + children: [ + Action({ title: t('actionPickArchive'), icon: Icon.Folder, onAction: handlePickArchive }), + Action({ title: t('actionAddPackFiles'), icon: Icon.Plus, onAction: () => handleAddPackSources(false) }), + Action({ title: t('actionAddPackFolder'), icon: Icon.Folder, onAction: () => handleAddPackSources(true) }), + Action({ title: t('actionEnsure7z'), icon: Icon.Download, onAction: handleEnsure7z }), + Action({ title: t('actionCancelTask'), icon: Icon.XMarkCircle, onAction: handleCancel }), + ...(activeArchivePath + ? [ + Action({ + title: t('actionTrashArchive'), + icon: Icon.Trash, + style: Action.Style.Destructive, + shortcut: { modifiers: ['ctrl', 'shift'], key: 'delete' }, + onAction: async () => { + await trashArchiveFile(activeArchivePath) + } + }) + ] + : []) + ] + }), children: [ List.Section({ - title: t('sectionFilterByCategory'), - children: categoryGroups.map((grp) => { - const stat = categoryCounts.get(grp.id) || { count: 0, bytes: 0 } - const isSelected = selectedCategory === grp.id - return List.Item({ - id: `nav-cat-${grp.id}`, - title: grp.name, - subtitle: formatBytes(stat.bytes), - icon: { - source: isSelected ? Icon.CheckCircle : Icon.Folder, - tintColor: Color.SecondaryText - }, - accessories: [{ text: t('itemCountText', { count: stat.count }) }], - actions: ActionPanel({ - title: grp.name, - children: [ - Action({ - title: t('actionFilterCategory', { name: grp.name }), - icon: Icon.Filter, - onAction: () => setSelectedCategory(grp.id) - }), - Action({ - title: t('actionExtractAll'), - icon: Icon.Download, - onAction: handleExtractAll - }), - ...(archives.length > 0 && selectedArchivePath - ? [ - Action({ - title: t('actionVerifyArchive'), - icon: Icon.CheckCircle, - shortcut: { modifiers: ['ctrl'], key: 't' }, - onAction: handleVerifyArchive - }) - ] - : []), - ...(archives.length > 0 - ? [ - ActionPanel.Section({ - title: t('sectionList'), - children: [ - ...(isExtracting ? [] : [removeArchiveAction()]), - pickFilesAction(), - pickFolderAction(), - clearListAction() - ] - }) - ] - : []) - ] - }) - }) - }) - }), - ...(diagnosticItems.length > 0 ? [List.Section({ title: t('sectionPreCheck'), children: diagnosticItems })] : []) + title: t('sectionTitle', { count: activeItems.length }), + children: activeItems + }) ] }) } diff --git a/extensions/archive-manager/src/logic.ts b/extensions/archive-manager/src/logic.ts index f86c3b07..09fad921 100644 --- a/extensions/archive-manager/src/logic.ts +++ b/extensions/archive-manager/src/logic.ts @@ -1,19 +1,31 @@ /** - * ZIP 压缩包查看与解压业务逻辑 + * 解压与压缩业务逻辑层(Wave 3 薄原语域:archive.list / archive.extract / archive.create) * - * 1. 经客户端读取 .zip 目录:文件列表、CRC32、压缩率与文件分类(文件名由客户端识别 UTF-8 / GBK 编码) - * 2. 整包解压(只有一个顶层文件夹时解压到压缩包所在目录,否则解压到同名文件夹)或只提取勾选的文件 - * 3. 含 `../` 或绝对路径的条目不提取;含加密条目的压缩包客户端拒绝解压 + * - 支持浏览归档清单(ZIP,以及 7z-family 扩展启用时的 7z / RAR / TAR)与路径穿越拦截 + * - 支持整包或勾选条目解压、密码输入与自定义输出目录 + * - 全新压缩打包工作流:支持多文件/目录打包为 ZIP,以及 7z-family 启用时的 7z / 加密归档与压缩级别 + * - 支持按需准备 7zz 扩展引擎(tool_runtime_ensure)与取消长任务(tool_task_cancel) */ import { + asRecord, callHostTransport, - formatBytes as formatByteCount, - invokeDllPluginCapability, + cancelRuntimeTask, + ensureRuntimeCapability, + findCapability, + formatByteCount, + hasCapabilityExtension, + nextMessageId, + pickAnySourcesDialog, + pickSaveArchiveDialog, + queryRuntimeCapabilities, showRealItemInFolder, - trashRealItem -} from './native-ipc.js' + trashRealItem, + type ToolCapabilityStatus, + type ToolRuntimeCapabilitiesSnapshot +} from './tool-runtime.js' import { + friendlyFileError, pathKey, type FileImportRules, type FileImportTransport, @@ -23,7 +35,19 @@ import { t } from './i18n.js' import { resolveErrorMessage } from './error-i18n.js' import { ARCHIVE_CATEGORY } from './archive-categories.zh-data.js' -/** 显示文件大小;宿主未返回时如实显示“大小未识别” */ +export { + pickAnySourcesDialog, + pickSaveArchiveDialog, + queryRuntimeCapabilities, + findCapability, + hasCapabilityExtension, + type ToolCapabilityStatus, + type ToolRuntimeCapabilitiesSnapshot +} + +export type ArchiveCreateFormat = 'zip' | '7z' | 'tar' +export type ArchiveCompressionLevel = 0 | 1 | 5 | 9 + export function formatBytes(bytes: number | null | undefined): string { return typeof bytes === 'number' && Number.isFinite(bytes) && bytes >= 0 ? formatByteCount(bytes) : t('sizeUnknown') } @@ -34,7 +58,6 @@ export interface ArchiveCandidateItem { path: string parentDir: string extension: string - /** 字节数;宿主没有返回时为 null(界面显示“大小未识别”) */ sizeBytes: number | null mtime: number | null } @@ -47,50 +70,101 @@ export interface ArchiveEntryItem { uncompressedSize: number compressedSize: number compressionRatio: number - crc32: string isDirectory: boolean isEncrypted: boolean hasPathTraversalRisk: boolean - lastModified: string + mtimeMs: number | null } export interface ArchiveInspectionResult { ok: boolean archivePath: string archiveName: string - archiveSizeBytes: number + format: string totalEntries: number fileCount: number totalUncompressedBytes: number totalCompressedBytes: number - compressionRatio: number encryptedCount: number isEncrypted: boolean traversalRiskCount: number - hasSingleRootFolder: boolean - singleRootFolderName: string | null entries: ArchiveEntryItem[] error?: string } -export interface NativeInvocationResult { +export interface ArchiveExtractResult { ok: boolean - pluginName: string - method: string - data?: unknown + taskId: string + targetDir: string + extractedCount: number + totalBytes: number + blockedEntries: string[] error?: string - fromFallback?: boolean } -export const DLL_PLUGIN_NAME = 'ArchiveManagerPlugin' -export function getNotInClientMessage(): string { - return t('notInClient') +export interface ArchiveCreateResult { + ok: boolean + taskId: string + outputPath: string + outputBytes: number + entryCount: number + format: string + error?: string } + export const FORBIDDEN_TARGET_PATTERN = new RegExp('\\\\Windows\\\\System32|\\.\\.\\\\|\\.\\./', 'i') + +let activeArchiveTaskId = '' + +export function getActiveArchiveTaskId(): string { + return activeArchiveTaskId +} + +export function resetArchiveRuntimeState(): void { + activeArchiveTaskId = '' +} + export function getForbiddenReason(): string { return t('forbiddenReason') } +/** 探测宿主是否启用了 7z-family 可选扩展(支持 7z / RAR / 加密归档) */ +export function has7zFamilyExtension(snapshot: ToolRuntimeCapabilitiesSnapshot | null | undefined): boolean { + return ( + hasCapabilityExtension(snapshot, 'archive.create', '7z-family') || + hasCapabilityExtension(snapshot, 'archive.extract', '7z-family') || + hasCapabilityExtension(snapshot, 'archive.list', '7z-family') + ) +} + +/** 按能力探测动态返回支持的浏览/解压扩展名 */ +export function getSupportedArchiveExtensions(snapshot: ToolRuntimeCapabilitiesSnapshot | null | undefined): string[] { + return has7zFamilyExtension(snapshot) ? ['.zip', '.7z', '.rar', '.tar'] : ['.zip'] +} + +/** 按能力探测动态返回压缩打包支持的格式(无 7z-family 时自动降级隐藏 7z) */ +export function getAvailableCreateFormats( + snapshot: ToolRuntimeCapabilitiesSnapshot | null | undefined +): Array<{ value: ArchiveCreateFormat; label: string }> { + if (has7zFamilyExtension(snapshot)) { + return [ + { value: 'zip', label: 'ZIP' }, + { value: '7z', label: '7Z' }, + { value: 'tar', label: 'TAR' } + ] + } + return [{ value: 'zip', label: 'ZIP' }] +} + +export function getCompressionLevelOptions(): Array<{ value: string; label: string }> { + return [ + { value: '0', label: t('levelStore') }, + { value: '1', label: t('levelFast') }, + { value: '5', label: t('levelNormal') }, + { value: '9', label: t('levelMax') } + ] +} + export function getArchiveCategoryGroups(): Array<{ id: string; name: string }> { return [ { id: 'ALL', name: t('catAll') }, @@ -121,15 +195,12 @@ export function getCategoryLabel(category: string): string { } } -/** - * 校验包内相对路径是否存在 Zip Slip (`../` 或绝对路径) 越界风险 - */ +/** 校验包内相对路径是否存在 Zip Slip(`..` 或绝对路径)越界风险 */ export function isUnsafeEntryPath(entryName: string): boolean { const norm = String(entryName || '').replace(/\\/g, '/') if (!norm || norm.includes('\0')) return true if (norm.startsWith('/') || /^[A-Za-z]:/.test(norm)) return true - const segments = norm.split('/') - return segments.some((seg) => seg === '..') + return norm.split('/').some((seg) => seg === '..') } export function classifyEntryCategory(fileName: string, isDirectory = false): string { @@ -142,29 +213,7 @@ export function classifyEntryCategory(fileName: string, isDirectory = false): st if (['.png', '.jpg', '.jpeg', '.webp', '.gif', '.bmp', '.svg', '.mp4', '.mov', '.mp3', '.wav'].includes(ext)) { return ARCHIVE_CATEGORY.MEDIA } - if ( - [ - '.ts', - '.tsx', - '.js', - '.mjs', - '.cjs', - '.json', - '.py', - '.rs', - '.go', - '.java', - '.c', - '.cpp', - '.cs', - '.html', - '.css', - '.sql', - '.xml', - '.yaml', - '.yml' - ].includes(ext) - ) { + if (['.ts', '.tsx', '.js', '.mjs', '.json', '.py', '.rs', '.go', '.java', '.c', '.cpp', '.html', '.css', '.sql', '.xml', '.yaml', '.yml'].includes(ext)) { return ARCHIVE_CATEGORY.CODE } if (['.exe', '.msi', '.dll', '.bat', '.cmd', '.ps1', '.sh'].includes(ext)) { @@ -173,67 +222,17 @@ export function classifyEntryCategory(fileName: string, isDirectory = false): st return ARCHIVE_CATEGORY.OTHER } -export function validateInvocationPayload( - method: string, - params: unknown -): { valid: boolean; error?: string } { - if (typeof method !== 'string' || method.trim().length === 0) { - return { valid: false, error: t('errInvalidMethodEmpty') } - } - if (method.length > 128 || !/^[A-Za-z0-9_]+$/.test(method.trim())) { - return { valid: false, error: t('errInvalidMethodFormat') } - } - if (params === null || params === undefined || typeof params !== 'object' || Array.isArray(params)) { - return { valid: false, error: t('errInvalidParamsObject') } - } - - const record = params as Record - for (const [key, val] of Object.entries(record)) { - if (typeof val === 'string') { - if (val.length > 4096) { - return { valid: false, error: t('errParamTooLong', { key }) } - } - if ((key === 'targetDir' || key === 'outputDir' || key === 'outputPath') && FORBIDDEN_TARGET_PATTERN.test(val)) { - return { valid: false, error: t('errSecurityIntercepted', { reason: t('forbiddenReason') }) } - } - } - } - return { valid: true } +export function createArchiveImportTransport(hostOverride?: unknown): FileImportTransport { + return (method, params) => callHostTransport(method, params, hostOverride) } -export async function invokeNativeCapability( - method: string, - params: Record, - hostBridge?: unknown -): Promise { - const check = validateInvocationPayload(method, params) - if (!check.valid) { - throw new Error(resolveErrorMessage(check, t('errValidationFailed'))) - } - const res = await invokeDllPluginCapability(DLL_PLUGIN_NAME, method, params, hostBridge) +export function buildArchiveImportRules(snapshot: ToolRuntimeCapabilitiesSnapshot | null | undefined): FileImportRules { return { - ok: res.ok, - pluginName: DLL_PLUGIN_NAME, - method: method.trim(), - data: res.data ?? undefined, - error: res.error, - fromFallback: res.fromFallback + extensions: getSupportedArchiveExtensions(snapshot), + forbiddenPath: FORBIDDEN_TARGET_PATTERN } } -export const ARCHIVE_EXTENSIONS = ['.zip'] as const -export const ARCHIVE_SUPPORTED_TEXT = '.zip' - -/** ZIP 导入规则:递归最多 5 层、500 个文件,跳过系统核心与路径穿越目录 */ -export const ARCHIVE_IMPORT_RULES: FileImportRules = { - extensions: ARCHIVE_EXTENSIONS, - forbiddenPath: FORBIDDEN_TARGET_PATTERN -} - -export function createArchiveImportTransport(hostOverride?: unknown): FileImportTransport { - return (method, params) => callHostTransport(method, params, hostOverride) -} - export function toArchiveCandidateItem(file: ImportedFile): ArchiveCandidateItem { return { id: `arc:${pathKey(file.path)}`, @@ -246,274 +245,343 @@ export function toArchiveCandidateItem(file: ImportedFile): ArchiveCandidateItem } } +export function parentDirOf(p: string): string { + const clean = String(p || '').replace(/[\\/]+$/, '') + const idx = Math.max(clean.lastIndexOf('\\'), clean.lastIndexOf('/')) + return idx > 0 ? clean.slice(0, idx) : clean +} + +export function buildDefaultExtractDir(archivePath: string): string { + const sep = archivePath.includes('\\') ? '\\' : '/' + const parent = parentDirOf(archivePath) + const fileName = archivePath.split(/[\\/]/).pop() || 'archive' + const dot = fileName.lastIndexOf('.') + const stem = dot > 0 ? fileName.slice(0, dot) : fileName + return `${parent}${sep}${stem}_extracted` +} + +export function buildDefaultPackOutputPath(firstSourcePath: string, format: ArchiveCreateFormat, now: Date = new Date()): string { + const sep = firstSourcePath.includes('\\') ? '\\' : '/' + const parent = parentDirOf(firstSourcePath) + const baseName = firstSourcePath.split(/[\\/]/).pop() || 'archive' + const dot = baseName.lastIndexOf('.') + const stem = dot > 0 ? baseName.slice(0, dot) : baseName + const pad2 = (n: number) => String(n).padStart(2, '0') + const stamp = `${now.getFullYear()}${pad2(now.getMonth() + 1)}${pad2(now.getDate())}_${pad2(now.getHours())}${pad2(now.getMinutes())}${pad2(now.getSeconds())}` + return `${parent}${sep}${stem}_${stamp}.${format}` +} + +/** 按需下载并准备 7zz 归档扩展引擎 */ +export async function ensureArchiveExtensionEngine( + hostOverride?: unknown +): Promise<{ ok: boolean; provisioned: string[]; error?: string }> { + const primitives = ['archive.list', 'archive.extract', 'archive.create'] as const + const provisioned: string[] = [] + for (const primitiveId of primitives) { + const res = await ensureRuntimeCapability(primitiveId, hostOverride) + if (!res.ok) { + return { ok: false, provisioned, error: resolveErrorMessage(res, t('errEnsureFailed')) } + } + if (res.data?.status === 'unsupported') { + return { ok: false, provisioned, error: t('errUnsupportedEngine') } + } + if (res.data?.provisioned) provisioned.push(primitiveId) + } + return { ok: true, provisioned } +} + +/** 取消正在运行的解压或打包任务 */ +export async function cancelActiveArchiveTask( + explicitTaskId?: string, + hostOverride?: unknown +): Promise<{ ok: boolean; taskId: string; cancelled: boolean; error?: string }> { + const targetTaskId = String(explicitTaskId || activeArchiveTaskId || '').trim() + if (!targetTaskId) { + return { ok: false, taskId: '', cancelled: false, error: t('errNoTaskToCancel') } + } + const res = await cancelRuntimeTask(targetTaskId, hostOverride) + if (!res.ok) { + return { ok: false, taskId: targetTaskId, cancelled: false, error: resolveErrorMessage(res, t('toastCancelFail')) } + } + if (targetTaskId === activeArchiveTaskId) activeArchiveTaskId = '' + return { ok: true, taskId: targetTaskId, cancelled: Boolean(res.data?.cancelled ?? true) } +} + +/** 浏览归档内容清单(tool_archive_list) */ export async function inspectArchiveEntries( archivePath: string, + options: { password?: string } = {}, hostOverride?: unknown ): Promise { - if (!archivePath || !archivePath.trim()) { + const cleanPath = String(archivePath || '').trim() + const archiveName = cleanPath.split(/[\\/]/).pop() || cleanPath + if (!cleanPath || FORBIDDEN_TARGET_PATTERN.test(cleanPath)) { return { ok: false, - archivePath: '', - archiveName: '', - archiveSizeBytes: 0, + archivePath: cleanPath, + archiveName, + format: 'unknown', totalEntries: 0, fileCount: 0, totalUncompressedBytes: 0, totalCompressedBytes: 0, - compressionRatio: 0, encryptedCount: 0, isEncrypted: false, traversalRiskCount: 0, - hasSingleRootFolder: false, - singleRootFolderName: null, entries: [], - error: t('errArchivePathEmpty') + error: cleanPath ? t('forbiddenReason') : t('errArchivePathEmpty') } } - const res = await invokeNativeCapability( - 'ListArchiveEntries', - { archivePath: archivePath.trim() }, - hostOverride - ) - if (!res.ok || !res.data || typeof res.data !== 'object') { + const params: Record = { + archive: { path: cleanPath }, + ...(options.password ? { password: options.password } : {}) + } + const res = await callHostTransport('tool_archive_list', params, hostOverride) + if (!res.ok) { return { ok: false, - archivePath, - archiveName: archivePath.split(/[\\/]/).pop() || archivePath, - archiveSizeBytes: 0, + archivePath: cleanPath, + archiveName, + format: 'unknown', totalEntries: 0, fileCount: 0, totalUncompressedBytes: 0, totalCompressedBytes: 0, - compressionRatio: 0, encryptedCount: 0, isEncrypted: false, traversalRiskCount: 0, - hasSingleRootFolder: false, - singleRootFolderName: null, entries: [], - error: resolveErrorMessage(res, t('errInspectFailed')) + error: friendlyFileError(resolveErrorMessage(res, t('errInspectFailed'))) } } - const raw = res.data as Record - const rawEntries = Array.isArray(raw.entries) ? (raw.entries as Array>) : [] + const raw = asRecord(res.data) + const rawEntries = Array.isArray(raw?.entries) ? raw.entries.map(asRecord).filter((e): e is Record => Boolean(e)) : [] const entries: ArchiveEntryItem[] = rawEntries - .filter((e) => !e.isDirectory) + .filter((e) => !Boolean(e.isDirectory)) .map((e, idx) => { - const entryName = String(e.entryName ?? e.name ?? '') - const baseName = String(e.name ?? (entryName.split('/').pop() || entryName)) - const uncomp = Number(e.uncompressedSize ?? 0) - const comp = Number(e.compressedSize ?? 0) - const hasRisk = Boolean(e.hasPathTraversalRisk) || isUnsafeEntryPath(entryName) + const entryName = String(e.path ?? e.entryName ?? '') + const baseName = entryName.split(/[\\/]/).pop() || entryName + const uncomp = Number(e.sizeBytes ?? e.uncompressedSize ?? 0) + const comp = Number(e.compressedBytes ?? e.compressedSize ?? 0) + const safeUncomp = Number.isFinite(uncomp) && uncomp >= 0 ? uncomp : 0 + const safeComp = Number.isFinite(comp) && comp >= 0 ? comp : 0 + const ratio = safeUncomp > 0 ? Math.max(0, Math.round((1 - safeComp / safeUncomp) * 100)) : 0 + const mtimeVal = Number(e.mtimeMs) return { id: `entry-${idx}-${entryName}`, entryName, name: baseName, - category: String(e.category ?? classifyEntryCategory(baseName, false)), - uncompressedSize: uncomp, - compressedSize: comp, - compressionRatio: Number(e.compressionRatio ?? (uncomp > 0 ? Math.round((1 - comp / uncomp) * 100) : 0)), - crc32: String(e.crc32 ?? '00000000'), + category: classifyEntryCategory(baseName, false), + uncompressedSize: safeUncomp, + compressedSize: safeComp, + compressionRatio: ratio, isDirectory: false, - isEncrypted: Boolean(e.isEncrypted), - hasPathTraversalRisk: hasRisk, - lastModified: String(e.lastModified ?? '') + isEncrypted: Boolean(e.encrypted ?? e.isEncrypted), + hasPathTraversalRisk: isUnsafeEntryPath(entryName), + mtimeMs: Number.isFinite(mtimeVal) && mtimeVal > 0 ? mtimeVal : null } }) - .sort((a, b) => b.uncompressedSize - a.uncompressedSize) const traversalRiskCount = entries.filter((e) => e.hasPathTraversalRisk).length const encryptedCount = entries.filter((e) => e.isEncrypted).length + const totalUncompressedBytes = Number(raw?.totalUncompressedBytes ?? entries.reduce((acc, e) => acc + e.uncompressedSize, 0)) + const totalCompressedBytes = entries.reduce((acc, e) => acc + e.compressedSize, 0) return { ok: true, - archivePath: String(raw.archivePath ?? archivePath), - archiveName: String(raw.archiveName ?? (archivePath.split(/[\\/]/).pop() || archivePath)), - archiveSizeBytes: Number(raw.archiveSizeBytes ?? 0), - totalEntries: Number(raw.totalEntries ?? entries.length), + archivePath: cleanPath, + archiveName, + format: typeof raw?.format === 'string' ? raw.format : 'zip', + totalEntries: Number(raw?.totalEntries ?? entries.length), fileCount: entries.length, - totalUncompressedBytes: Number( - raw.totalUncompressedBytes ?? entries.reduce((acc, e) => acc + e.uncompressedSize, 0) - ), - totalCompressedBytes: Number( - raw.totalCompressedBytes ?? entries.reduce((acc, e) => acc + e.compressedSize, 0) - ), - compressionRatio: Number(raw.compressionRatio ?? 0), + totalUncompressedBytes: Number.isFinite(totalUncompressedBytes) && totalUncompressedBytes >= 0 ? totalUncompressedBytes : 0, + totalCompressedBytes, encryptedCount, - isEncrypted: Boolean(raw.isEncrypted) || encryptedCount > 0, - traversalRiskCount: Math.max(Number(raw.traversalRiskCount ?? 0), traversalRiskCount), - hasSingleRootFolder: Boolean(raw.hasSingleRootFolder), - singleRootFolderName: typeof raw.singleRootFolderName === 'string' ? raw.singleRootFolderName : null, + isEncrypted: Boolean(raw?.encrypted) || encryptedCount > 0, + traversalRiskCount, entries } } +/** 解压归档(整包或勾选条目,tool_archive_extract) */ export async function extractArchiveEntries( archivePath: string, options: { - entryNames?: string[] - targetDir?: string - smartUnwrap?: boolean - flattenSelected?: boolean + outputDir?: string + entries?: string[] + password?: string + overwrite?: boolean } = {}, hostOverride?: unknown -): Promise<{ - ok: boolean - targetDir?: string - extractedCount: number - extractedFiles: string[] - blockedEntries: string[] - error?: string -}> { - if (Array.isArray(options.entryNames) && options.entryNames.some((n) => isUnsafeEntryPath(n))) { +): Promise { + const cleanArchive = String(archivePath || '').trim() + if (!cleanArchive || FORBIDDEN_TARGET_PATTERN.test(cleanArchive)) { return { ok: false, + taskId: '', + targetDir: '', extractedCount: 0, - extractedFiles: [], - blockedEntries: options.entryNames.filter((n) => isUnsafeEntryPath(n)), - error: `ZIP_SLIP_BLOCKED: ${t('forbiddenReason')}` + totalBytes: 0, + blockedEntries: [], + error: cleanArchive ? t('forbiddenReason') : t('errArchivePathEmpty') } } - - const res = await invokeNativeCapability( - 'ExtractArchiveEntries', - { - archivePath, - ...(options.entryNames && options.entryNames.length > 0 ? { entryNames: options.entryNames } : {}), - ...(options.targetDir ? { targetDir: options.targetDir } : {}), - smartUnwrap: options.smartUnwrap !== false, - flattenSelected: Boolean(options.flattenSelected) - }, - hostOverride - ) - - if (!res.ok) { + const outputDir = options.outputDir?.trim() || buildDefaultExtractDir(cleanArchive) + if (FORBIDDEN_TARGET_PATTERN.test(outputDir)) { return { ok: false, + taskId: '', + targetDir: outputDir, extractedCount: 0, - extractedFiles: [], + totalBytes: 0, blockedEntries: [], - error: resolveErrorMessage(res, t('errExtractFailed')) + error: t('forbiddenReason') + } + } + if (Array.isArray(options.entries)) { + const blocked = options.entries.filter((n) => isUnsafeEntryPath(n)) + if (blocked.length > 0) { + return { + ok: false, + taskId: '', + targetDir: outputDir, + extractedCount: 0, + totalBytes: 0, + blockedEntries: blocked, + error: `ZIP_SLIP_BLOCKED: ${t('forbiddenReason')}` + } } } - const payload = (res.data ?? {}) as Record - return { - ok: true, - targetDir: typeof payload.targetDir === 'string' ? payload.targetDir : undefined, - extractedCount: Number(payload.extractedCount ?? 0), - extractedFiles: Array.isArray(payload.extractedFiles) ? payload.extractedFiles.map(String) : [], - blockedEntries: Array.isArray(payload.blockedEntries) ? payload.blockedEntries.map(String) : [] + const taskId = nextMessageId('arc_extract') + const params: Record = { + taskId, + archive: { path: cleanArchive }, + outputDir: { path: outputDir }, + overwrite: Boolean(options.overwrite) } -} + if (options.password) params.password = options.password + if (options.entries && options.entries.length > 0) params.entries = options.entries -export async function openArchiveLocation(targetPath: string, hostOverride?: unknown): Promise { - return showRealItemInFolder(targetPath, hostOverride) + activeArchiveTaskId = taskId + try { + const res = await callHostTransport('tool_archive_extract', params, hostOverride) + if (!res.ok) { + return { + ok: false, + taskId, + targetDir: outputDir, + extractedCount: 0, + totalBytes: 0, + blockedEntries: [], + error: friendlyFileError(resolveErrorMessage(res, t('errExtractFailed'))) + } + } + const data = asRecord(res.data) + const extractedCount = Number(data?.extractedCount ?? 0) + const totalBytes = Number(data?.totalBytes ?? 0) + return { + ok: true, + taskId: typeof data?.taskId === 'string' && data.taskId ? data.taskId : taskId, + targetDir: typeof data?.outputDir === 'string' && data.outputDir ? data.outputDir : outputDir, + extractedCount: Number.isFinite(extractedCount) && extractedCount >= 0 ? extractedCount : 0, + totalBytes: Number.isFinite(totalBytes) && totalBytes >= 0 ? totalBytes : 0, + blockedEntries: [] + } + } finally { + if (activeArchiveTaskId === taskId) activeArchiveTaskId = '' + } } -export async function trashArchiveFile( - archivePath: string, +/** 压缩打包文件/目录为归档(tool_archive_create) */ +export async function createArchivePackage( + sourcePaths: readonly string[], + options: { + outputPath?: string + format?: ArchiveCreateFormat + compressionLevel?: number + password?: string + overwrite?: boolean + capabilities?: ToolRuntimeCapabilitiesSnapshot | null + } = {}, hostOverride?: unknown -): Promise<{ ok: boolean; error?: string }> { - if (!archivePath || FORBIDDEN_TARGET_PATTERN.test(archivePath)) { - return { ok: false, error: t('forbiddenReason') } +): Promise { + const validSources = sourcePaths + .map((p) => String(p || '').trim()) + .filter((p) => p.length > 0 && !FORBIDDEN_TARGET_PATTERN.test(p)) + if (validSources.length === 0) { + return { ok: false, taskId: '', outputPath: '', outputBytes: 0, entryCount: 0, format: 'zip', error: t('errNoPackSources') } } - return trashRealItem(archivePath, hostOverride) -} -function pathSeparatorOf(p: string): string { - return p.includes('\\') ? '\\' : '/' -} - -export function parentDirOf(p: string): string { - const clean = String(p || '').replace(/[\\/]+$/, '') - const idx = Math.max(clean.lastIndexOf('\\'), clean.lastIndexOf('/')) - return idx > 0 ? clean.slice(0, idx) : clean -} - -/** - * 与客户端的解压规则一致,给出文件实际会写到哪个文件夹,用于解压前的确认提示: - * - 整包解压且包内只有一个顶层文件夹:解压到压缩包所在目录,文件落在这个顶层文件夹里 - * - 其余情况(含只提取勾选的文件):解压到压缩包旁的同名文件夹 - */ -export function describeExtractTarget( - archivePath: string, - meta: { hasSingleRootFolder: boolean; singleRootFolderName: string | null }, - selective: boolean -): string { - const sep = pathSeparatorOf(archivePath) - const parent = parentDirOf(archivePath) - const fileName = String(archivePath || '').split(/[\\/]/).pop() || '' - const dot = fileName.lastIndexOf('.') - const baseName = dot > 0 ? fileName.slice(0, dot) : fileName - if (!selective && meta.hasSingleRootFolder && meta.singleRootFolderName) { - return `${parent}${sep}${meta.singleRootFolderName}` + const format: ArchiveCreateFormat = options.format === '7z' || options.format === 'tar' ? options.format : 'zip' + const has7z = options.capabilities ? has7zFamilyExtension(options.capabilities) : true + if (format === '7z' && !has7z) { + return { ok: false, taskId: '', outputPath: '', outputBytes: 0, entryCount: 0, format, error: t('err7zNotSupported') } + } + const password = String(options.password || '').trim() + if (password && !has7z) { + return { ok: false, taskId: '', outputPath: '', outputBytes: 0, entryCount: 0, format, error: t('errPasswordNeeds7z') } } - return `${parent}${sep}${baseName}` -} -export interface VerifySummary { - ok: boolean - title: string - message: string -} + const outputPath = options.outputPath?.trim() || buildDefaultPackOutputPath(validSources[0]!, format) + if (FORBIDDEN_TARGET_PATTERN.test(outputPath)) { + return { ok: false, taskId: '', outputPath, outputBytes: 0, entryCount: 0, format, error: t('forbiddenReason') } + } -/** - * 客户端的“校验”只读取压缩包目录、检查越界路径与加密标记,并计算整个文件的 SHA-256, - * 不会逐个解压校验各文件的 CRC32。提示文字按这个事实写。 - */ -export function summarizeVerifyResult(data: unknown): VerifySummary { - const record = (data && typeof data === 'object' ? data : {}) as Record - const sha = typeof record.sha256 === 'string' ? record.sha256 : '' - if (!/^[0-9a-f]{64}$/i.test(sha)) { - return { ok: false, title: t('verifyInvalidTitle'), message: t('verifyInvalidMsg') } + const levelRaw = options.compressionLevel + const compressionLevel = + typeof levelRaw === 'number' && Number.isInteger(levelRaw) && levelRaw >= 0 && levelRaw <= 9 ? levelRaw : 5 + + const taskId = nextMessageId('arc_create') + const params: Record = { + taskId, + inputs: validSources.map((p) => ({ path: p })), + output: { path: outputPath }, + format, + compressionLevel, + overwrite: Boolean(options.overwrite) } - const risk = Math.max(0, Number(record.traversalRiskCount ?? 0) || 0) - const fileCount = Math.max(0, Number(record.fileCount ?? 0) || 0) - const encrypted = Boolean(record.isEncrypted) - const shaText = t('verifyShaText', { prefix: sha.slice(0, 16) }) - if (risk > 0) { + if (password) params.password = password + + activeArchiveTaskId = taskId + try { + const res = await callHostTransport('tool_archive_create', params, hostOverride) + if (!res.ok) { + return { + ok: false, + taskId, + outputPath, + outputBytes: 0, + entryCount: 0, + format, + error: friendlyFileError(resolveErrorMessage(res, t('errCreateFailed'))) + } + } + const data = asRecord(res.data) + const outputBytes = Number(data?.outputBytes ?? 0) + const entryCount = Number(data?.entryCount ?? 0) return { - ok: false, - title: t('verifyRiskTitle', { count: risk }), - message: t('verifyRiskMsg', { sha: shaText }) + ok: true, + taskId: typeof data?.taskId === 'string' && data.taskId ? data.taskId : taskId, + outputPath, + outputBytes: Number.isFinite(outputBytes) && outputBytes >= 0 ? outputBytes : 0, + entryCount: Number.isFinite(entryCount) && entryCount >= 0 ? entryCount : 0, + format: typeof data?.format === 'string' && data.format ? data.format : format } - } - return { - ok: true, - title: t('verifyOkTitle'), - message: t('verifyOkMsg', { - count: fileCount, - enc: encrypted ? t('verifyEncryptedPart') : '', - sha: shaText - }) + } finally { + if (activeArchiveTaskId === taskId) activeArchiveTaskId = '' } } -export function summarizeExtractResult(res: { - ok: boolean - extractedCount: number - blockedEntries: string[] - targetDir?: string - error?: string -}): VerifySummary { - if (!res.ok) return { ok: false, title: t('extractFailedTitle'), message: resolveErrorMessage(res, t('extractFailedDefaultMsg')) } - if (res.extractedCount <= 0) { - return { - ok: false, - title: t('extractEmptyTitle'), - message: - res.blockedEntries.length > 0 - ? t('extractBlockedMsg', { count: res.blockedEntries.length }) - : t('extractMissingMsg') - } - } - const blocked = res.blockedEntries.length > 0 ? t('extractBlockedSuffix', { count: res.blockedEntries.length }) : '' - return { - ok: true, - title: t('extractOkTitle', { count: res.extractedCount, blocked }), - message: res.targetDir || '' +export async function openArchiveLocation(targetPath: string, hostOverride?: unknown): Promise { + return showRealItemInFolder(targetPath, hostOverride) +} + +export async function trashArchiveFile(archivePath: string, hostOverride?: unknown): Promise<{ ok: boolean; error?: string }> { + if (!archivePath || FORBIDDEN_TARGET_PATTERN.test(archivePath)) { + return { ok: false, error: t('forbiddenReason') } } + return trashRealItem(archivePath, hostOverride) } diff --git a/extensions/archive-manager/src/native-ipc.ts b/extensions/archive-manager/src/native-ipc.ts deleted file mode 100644 index 51576b99..00000000 --- a/extensions/archive-manager/src/native-ipc.ts +++ /dev/null @@ -1,1852 +0,0 @@ -import { getLocale } from '@ztools/declarative-ui' - -type DynamicBridge = ReturnType - -const NATIVE_IPC_MESSAGES: Record string - dirEntrySep: string - dirErrorColon: string - deepScanUnavailable: string - pathEmpty: string - invalidMethodEmpty: string - invalidMethodFormat: string - invalidParamsObject: string - paramTooLong: (key: string) => string - paramOutOfRange: (key: string) => string - methodParamEmpty: string - invalidMethodType: string - malformedDllResponse: string - unknownDllError: string - hostIpcFailed: (pluginName: string, method: string) => string - hostUnavailable: (pluginName: string, method: string) => string - callFailed: string - movedToTrash: string - deleteFailed: string - revealedInFolder: string - revealFailed: string - opened: string - openFailed: string - pluginCallNotReady: string -}> = { - 'zh-CN': { - ipcCallFailed: 'IPC 调用返回失败', - ipcInnerFailed: 'IPC 内部调用失败', - scanIncomplete: '扫描结果不完整', - dirReadFailed: (details, moreCount) => - `目录读取失败或不完整:${details}${moreCount > 0 ? `;另有 ${moreCount} 个目录` : ''}`, - dirEntrySep: ';', - dirErrorColon: ':', - deepScanUnavailable: '深度扫描不可用,仅列出一级目录,结果不完整', - pathEmpty: '路径不能为空', - invalidMethodEmpty: 'INVALID_METHOD: 调用方法名不能为空', - invalidMethodFormat: 'INVALID_METHOD_FORMAT: 方法名包含非法字符或超长', - invalidParamsObject: 'INVALID_PARAMS: 参数必须为非空对象', - paramTooLong: (key) => `PARAM_TOO_LONG: 参数 ${key} 超过最大长度限制`, - paramOutOfRange: (key) => `PARAM_OUT_OF_RANGE: 数值参数 ${key} 越界或非有限数`, - methodParamEmpty: 'method 参数不能为空', - invalidMethodType: 'INVALID_METHOD: method 不能为空且必须为字符串', - malformedDllResponse: 'MALFORMED_DLL_RESPONSE: 原生组件返回了损坏的 JSON 数据', - unknownDllError: '原生组件返回未知错误', - hostIpcFailed: (pluginName, method) => `HOST_IPC_FAILED: ${pluginName}.${method} 调用失败`, - hostUnavailable: (pluginName, method) => `HOST_UNAVAILABLE: ${pluginName}.${method} 宿主接口未就绪`, - callFailed: '调用失败', - movedToTrash: '已移入回收站', - deleteFailed: '删除失败', - revealedInFolder: '已定位文件', - revealFailed: '定位失败', - opened: '已打开', - openFailed: '打开失败', - pluginCallNotReady: '插件调用未就绪' - }, - 'en-US': { - ipcCallFailed: 'IPC call failed', - ipcInnerFailed: 'Internal IPC call failed', - scanIncomplete: 'Incomplete scan results', - dirReadFailed: (details, moreCount) => - `Directory read failed or incomplete: ${details}${moreCount > 0 ? `; and ${moreCount} more` : ''}`, - dirEntrySep: '; ', - dirErrorColon: ': ', - deepScanUnavailable: 'Deep scan unavailable; only top-level directory listed (incomplete)', - pathEmpty: 'Path cannot be empty', - invalidMethodEmpty: 'INVALID_METHOD: Method name cannot be empty', - invalidMethodFormat: 'INVALID_METHOD_FORMAT: Method name contains invalid characters or is too long', - invalidParamsObject: 'INVALID_PARAMS: Parameters must be a non-null object', - paramTooLong: (key) => `PARAM_TOO_LONG: Parameter "${key}" exceeds maximum length`, - paramOutOfRange: (key) => `PARAM_OUT_OF_RANGE: Numeric parameter "${key}" is out of range or non-finite`, - methodParamEmpty: 'Method parameter cannot be empty', - invalidMethodType: 'INVALID_METHOD: Method must be a non-empty string', - malformedDllResponse: 'MALFORMED_DLL_RESPONSE: Native component returned malformed JSON', - unknownDllError: 'Native component returned an unknown error', - hostIpcFailed: (pluginName, method) => `HOST_IPC_FAILED: ${pluginName}.${method} call failed`, - hostUnavailable: (pluginName, method) => `HOST_UNAVAILABLE: ${pluginName}.${method} host interface not ready`, - callFailed: 'Call failed', - movedToTrash: 'Moved to Trash', - deleteFailed: 'Delete failed', - revealedInFolder: 'Revealed in folder', - revealFailed: 'Failed to reveal item', - opened: 'Opened', - openFailed: 'Failed to open', - pluginCallNotReady: 'Plugin invocation not ready' - } -} - -function ipcStrings() { - const locale = getLocale() - return NATIVE_IPC_MESSAGES[locale] ?? NATIVE_IPC_MESSAGES['en-US'] -} -/** - * ZTools 真实宿主 IPC 与系统能力桥接层 (Real Host IPC Bridge) - * - * 严格遵循《ZTools Declarative UI 2.0 架构与 35 款原生插件全量升级规范》5.1 真实环境铁律: - * - 在真实 Electron 宿主环境中,100% 走通 Preload (__ztoolsElectron.transport.methods / window.ztools / __ztoolsLauncher) 真实调用链路 - * - 严禁在真实环境中因参数格式或嵌套响应结构差异而回退到假数据 - */ - -let ipcReqSeq = 1 -const realFileSizeCache = new Map() - -export function nextMessageId(prefix = 'ipc'): string { - ipcReqSeq = (ipcReqSeq + 1) % 1_000_000 - return `${prefix}_${Date.now()}_${ipcReqSeq}` -} - -/** - * 判断当前是否处于真实的 ZTools Electron 渲染进程宿主环境 - */ -export function isRealElectronHost(hostOverride?: unknown): boolean { - if (hostOverride) return false - if (typeof window === 'undefined') return false - const w = window as DynamicBridge - return Boolean( - w.__ztoolsElectron?.transport?.methods || - w.ztools?.transport?.call || - w.ztools?.transport?.methods - ) -} - -function normalizeMethodParams(method: string, params: Record): Record { - if (!params || typeof params !== 'object') return {} - const next = { ...params } - if (method === 'system_get_disk_usage') { - const rawDrive = String(next.drive || next.path || 'C:\\').trim() - if (rawDrive.startsWith('/')) { - next.drive = rawDrive - } else { - const match = rawDrive.match(/^([A-Za-z]):/) - next.drive = match ? `${match[1].toUpperCase()}:\\` : rawDrive.replace(/\//g, '\\') - } - delete next.path - } - return next -} - -function normalizeMethodResult(method: string, payload: DynamicBridge): DynamicBridge { - if (!payload || typeof payload !== 'object') return payload - - if (method === 'system_get_disk_usage') { - const avail = typeof payload.available === 'number' - ? payload.available - : typeof payload.free === 'number' - ? payload.free - : Math.max(0, Number(payload.total || 0) - Number(payload.used || 0)) - return { - ...payload, - available: avail, - free: avail - } - } - - if (method === 'system_get_hardware_summary') { - const cpuModel = - typeof payload.cpuModel === 'string' && payload.cpuModel.trim() - ? payload.cpuModel.trim() - : Array.isArray(payload.cpuModels) && payload.cpuModels.length > 0 - ? String(payload.cpuModels[0]).trim() - : 'x86_64 Processor' - return { - ...payload, - cpuModel - } - } - - if (method === 'system_get_battery_status') { - // 宿主约定 percent 超出 0-100(如 255)表示无电池或电量未知,不能改写成 100% - const rawPct = payload.percent - const hasBattery = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 - return { - ...payload, - percent: hasBattery ? rawPct : null, - hasBattery - } - } - - if (method === 'screen_get_all_displays') { - const list = Array.isArray(payload) - ? payload - : Array.isArray(payload.displays) - ? payload.displays - : [] - return list.map((d: DynamicBridge) => ({ - ...d, - label: d?.label || d?.name || `Display #${d?.id ?? 1}` - })) - } - - return payload -} - -function extractIpcErrorMeta(errObj: DynamicBridge): { - errorCode?: string - errorDetails?: Record -} { - if (!errObj || typeof errObj !== 'object') return {} - const errorCode = - typeof errObj.errorCode === 'string' && errObj.errorCode.trim() - ? errObj.errorCode.trim() - : typeof errObj.code === 'string' && errObj.code.trim() - ? errObj.code.trim() - : undefined - const rawDetails = - errObj.errorDetails && typeof errObj.errorDetails === 'object' && !Array.isArray(errObj.errorDetails) - ? (errObj.errorDetails as Record) - : errObj.details && typeof errObj.details === 'object' && !Array.isArray(errObj.details) - ? (errObj.details as Record) - : undefined - return { - ...(errorCode ? { errorCode } : {}), - ...(rawDetails ? { errorDetails: rawDetails } : {}) - } -} - -function unwrapTransportResponse( - method: string, - raw: DynamicBridge -): { ok: boolean; data?: DynamicBridge; error?: string; errorCode?: string; errorDetails?: Record } { - if (raw === null || raw === undefined) { - return { ok: false, error: 'EMPTY_IPC_RESPONSE', errorCode: 'EMPTY_IPC_RESPONSE' } - } - if (typeof raw !== 'object') { - return { ok: true, data: raw } - } - if (raw.success === false) { - const errObj = raw.error - const errMsg = - typeof errObj === 'object' && errObj !== null - ? String(errObj.message || errObj.code || JSON.stringify(errObj)) - : String(errObj || ipcStrings().ipcCallFailed) - return { ok: false, error: errMsg, ...extractIpcErrorMeta(raw), ...extractIpcErrorMeta(errObj) } - } - - const firstLayer = 'data' in raw && raw.data !== undefined ? raw.data : raw - if (firstLayer && typeof firstLayer === 'object' && !Array.isArray(firstLayer)) { - if (firstLayer.success === false) { - const errObj = firstLayer.error - const errMsg = - typeof errObj === 'object' && errObj !== null - ? String(errObj.message || errObj.code || JSON.stringify(errObj)) - : String(errObj || ipcStrings().ipcInnerFailed) - return { ok: false, error: errMsg, ...extractIpcErrorMeta(firstLayer), ...extractIpcErrorMeta(errObj) } - } - if ('data' in firstLayer && firstLayer.data !== undefined) { - return { ok: true, data: normalizeMethodResult(method, firstLayer.data) } - } - } - - return { ok: true, data: normalizeMethodResult(method, firstLayer) } -} - -/** - * 调用 Electron Preload Transport 方法(自动封装合法的 alphanumeric messageId 与双层解包) - */ -export async function callHostTransport( - method: string, - params: Record = {}, - hostOverride?: DynamicBridge -): Promise<{ ok: boolean; data?: T; error?: string; errorCode?: string; errorDetails?: Record }> { - const normalizedParams = normalizeMethodParams(method, params) - - // 1. 测试注入的 hostOverride 优先 - if (hostOverride) { - if (typeof hostOverride[method] === 'function') { - try { - const res = await hostOverride[method](normalizedParams) - const unwrapped = unwrapTransportResponse(method, res) - return unwrapped as { ok: boolean; data?: T; error?: string; errorCode?: string; errorDetails?: Record } - } catch (err: DynamicBridge) { - return { ok: false, error: err instanceof Error ? err.message : String(err), ...extractIpcErrorMeta(err) } - } - } - if (typeof hostOverride?.transport?.call === 'function') { - try { - const res = await hostOverride.transport.call(method, normalizedParams) - const unwrapped = unwrapTransportResponse(method, res) - return unwrapped as { ok: boolean; data?: T; error?: string; errorCode?: string; errorDetails?: Record } - } catch (err: DynamicBridge) { - return { ok: false, error: err instanceof Error ? err.message : String(err), ...extractIpcErrorMeta(err) } - } - } - } - - if (typeof window === 'undefined') { - return { ok: false, error: 'NO_WINDOW_ENV', errorCode: 'NO_WINDOW_ENV' } - } - - const w = window as DynamicBridge - const methods = w.__ztoolsElectron?.transport?.methods || w.ztools?.transport?.methods - const fn = methods?.[method] - - if (typeof fn === 'function') { - try { - const messageId = nextMessageId(method.replace(/[^A-Za-z0-9_]/g, '_').slice(0, 24)) - const raw = await fn({ messageId, params: normalizedParams }) - return unwrapTransportResponse(method, raw) as { ok: boolean; data?: T; error?: string; errorCode?: string; errorDetails?: Record } - } catch (err: DynamicBridge) { - return { ok: false, error: err instanceof Error ? err.message : String(err), ...extractIpcErrorMeta(err) } - } - } - - if (typeof w.ztools?.transport?.call === 'function') { - try { - const raw = await w.ztools.transport.call(method, normalizedParams) - return unwrapTransportResponse(method, raw) as { ok: boolean; data?: T; error?: string; errorCode?: string; errorDetails?: Record } - } catch (err: DynamicBridge) { - return { ok: false, error: err instanceof Error ? err.message : String(err), ...extractIpcErrorMeta(err) } - } - } - - return { ok: false, error: `METHOD_NOT_AVAILABLE: ${method}`, errorCode: 'METHOD_NOT_AVAILABLE' } -} - -export interface RealDiskDriveInfo { - drive: string - totalBytes: number - usedBytes: number - availableBytes: number - usagePercent: number -} - -/** - * 探测本机全部真实挂载磁盘分区 (C:\ ~ Z:\ 或 macOS/POSIX 挂载点 '/') - */ -export async function probeRealDiskDrives( - candidateLetters: string[] = ['C', 'D', 'E', 'F', 'G'], - hostOverride?: DynamicBridge -): Promise { - const drives: RealDiskDriveInfo[] = [] - const results = await Promise.all( - candidateLetters.map(async (letter) => { - const raw = String(letter || '').trim() - const isPosix = raw.startsWith('/') - const drivePath = isPosix ? raw : `${raw.replace(/:\\?$/, '').toUpperCase()}:\\` - const res = await callHostTransport<{ - total: number - used: number - available: number - free?: number - percent: number - }>('system_get_disk_usage', { drive: drivePath }, hostOverride) - if (res.ok && res.data && typeof res.data.total === 'number' && res.data.total > 0) { - const availableBytes = - typeof res.data.available === 'number' - ? res.data.available - : typeof res.data.free === 'number' - ? res.data.free - : Math.max(0, res.data.total - res.data.used) - return { - drive: isPosix ? raw : `${raw.replace(/:\\?$/, '').toUpperCase()}:`, - totalBytes: res.data.total, - usedBytes: res.data.used, - availableBytes, - usagePercent: res.data.percent - } - } - return null - }) - ) - - for (const item of results) { - if (item) drives.push(item) - } - - if (drives.length === 0 && !candidateLetters.includes('/')) { - const posixRes = await callHostTransport<{ - total: number - used: number - available: number - free?: number - percent: number - }>('system_get_disk_usage', { drive: '/' }, hostOverride) - if (posixRes.ok && posixRes.data && typeof posixRes.data.total === 'number' && posixRes.data.total > 0) { - const availableBytes = - typeof posixRes.data.available === 'number' - ? posixRes.data.available - : typeof posixRes.data.free === 'number' - ? posixRes.data.free - : Math.max(0, posixRes.data.total - posixRes.data.used) - drives.push({ - drive: '/', - totalBytes: posixRes.data.total, - usedBytes: posixRes.data.used, - availableBytes, - usagePercent: posixRes.data.percent - }) - } - } - - return drives -} - -/** - * 获取本机真实系统特殊路径(支持 home 派生标准子目录兜底,自动兼容 Windows 与 macOS/POSIX) - */ -export async function getRealSystemPath( - name: 'home' | 'appData' | 'userData' | 'desktop' | 'documents' | 'downloads' | 'music' | 'pictures' | 'videos' | 'temp' | 'cache', - hostOverride?: DynamicBridge -): Promise { - const res = await callHostTransport('system_get_path', { name }, hostOverride) - if (res.ok && res.data) { - if (typeof res.data === 'string' && res.data.trim().length > 0) { - return res.data.trim() - } - if (typeof res.data.path === 'string' && res.data.path.trim().length > 0) { - return res.data.path.trim() - } - } - - if (name !== 'home') { - const home = await getRealSystemPath('home', hostOverride) - if (home) { - const isPosix = home.startsWith('/') - const subMap: Record = isPosix - ? { - desktop: `${home}/Desktop`, - documents: `${home}/Documents`, - downloads: `${home}/Downloads`, - music: `${home}/Music`, - pictures: `${home}/Pictures`, - videos: `${home}/Videos`, - appData: `${home}/Library/Application Support`, - userData: `${home}/Library/Application Support/ZTools`, - temp: '/tmp', - cache: `${home}/Library/Caches` - } - : { - desktop: `${home}\\Desktop`, - documents: `${home}\\Documents`, - downloads: `${home}\\Downloads`, - music: `${home}\\Music`, - pictures: `${home}\\Pictures`, - videos: `${home}\\Videos`, - appData: `${home}\\AppData\\Roaming`, - userData: `${home}\\AppData\\Roaming\\ZTools`, - temp: `${home}\\AppData\\Local\\Temp`, - cache: `${home}\\AppData\\Local` - } - if (subMap[name]) return subMap[name] - } - } - - return '' -} - -export type RealDriveUsageInfo = RealDiskDriveInfo - -export interface RealIndexedFileEntry { - name: string - path: string - ext: string - isDir: boolean - isDirectory: boolean - size: number - sizeBytes: number - mtime: number - mtimeMs: number - lastModifiedMs: number -} - -export interface RealDirectorySubdirSummary { - name: string - path: string - fileCount: number - totalBytes: number - mtime: number - /** 体积不是完整统计(宿主扫描截断且独立统计超时 / 无权限),totalBytes 只是下限 */ - approximate?: boolean -} - -export interface RealDirectoryScanResult extends Iterable { - files: RealIndexedFileEntry[] - totalFiles: number - fileCount: number - totalBytes: number - subdirs: RealDirectorySubdirSummary[] - /** 宿主扫描达到条目上限后停止:files / totalFiles 只是已遍历部分的抽样 */ - truncated?: boolean - /** totalBytes 为近似值(下限) */ - approximate?: boolean - /** 宿主实际遍历的条目数 */ - visitedEntries?: number - /** 读取失败的真实原因;已有文件仍可使用,但不能当作完整结果。 */ - error?: string -} - -interface ScanResultMeta { - truncated?: boolean - approximate?: boolean - visitedEntries?: number -} - -export interface ScanDirectoryTreeOptions { - maxDepth?: number - maxFiles?: number - collectTopN?: number - filterExt?: RegExp - hostOverride?: DynamicBridge -} - -function extractFileExt(fileNameOrPath: string): string { - const base = String(fileNameOrPath || '').split(/[\\/]/).pop() || '' - const dotIdx = base.lastIndexOf('.') - return dotIdx > 0 ? base.slice(dotIdx).toLowerCase() : '' -} - -function normalizeIndexedFileEntry(f: DynamicBridge): RealIndexedFileEntry { - const p = String(f?.path || '') - const name = String(f?.name || p.split(/[\\/]/).pop() || '') - const sz = Number(f?.size ?? f?.sizeBytes ?? 0) - const isDir = Boolean(f?.is_dir || f?.isDir || f?.isDirectory) - const rawMtime = Number(f?.mtime ?? f?.mtimeMs ?? 0) - const mtimeMs = rawMtime > 1e11 ? rawMtime : rawMtime > 0 ? rawMtime * 1000 : Date.now() - const mtimeSec = rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime - if (p && sz >= 0) realFileSizeCache.set(p, sz) - return { - name, - path: p, - ext: extractFileExt(name || p), - isDir, - isDirectory: isDir, - size: sz, - sizeBytes: sz, - mtime: mtimeSec, - mtimeMs, - lastModifiedMs: mtimeMs - } -} - -function makeScanResult( - files: RealIndexedFileEntry[], - totalFiles: number, - totalBytes: number, - subdirs: RealDirectorySubdirSummary[], - meta: ScanResultMeta = {} -): RealDirectoryScanResult { - return { - files, - totalFiles, - fileCount: totalFiles, - totalBytes, - subdirs, - ...(meta.truncated ? { truncated: true } : {}), - ...(meta.approximate ? { approximate: true } : {}), - ...(typeof meta.visitedEntries === 'number' ? { visitedEntries: meta.visitedEntries } : {}), - [Symbol.iterator]() { - return files[Symbol.iterator]() - } - } -} - -/** - * 调用客户端的原生文件索引组件 (ztools-indexer) 检索文件 - */ -export async function searchRealIndexedFiles( - query: string, - limit = 40, - hostOverride?: DynamicBridge -): Promise { - if (!query || !query.trim()) return [] - const q = query.trim() - const safeLimit = Math.min(200, Math.max(1, Math.floor(limit || 40))) - - try { - const res = await callHostTransport<{ files?: DynamicBridge[] }>( - 'system_search_files', - { query: q, limit: safeLimit }, - hostOverride - ) - if (res.ok && res.data && Array.isArray(res.data.files)) { - return res.data.files.map(normalizeIndexedFileEntry) - } - - if (!hostOverride && typeof window !== 'undefined') { - const w = window as DynamicBridge - if (typeof w.__ztoolsLauncher?.searchFiles === 'function') { - const rawOuter = await w.__ztoolsLauncher.searchFiles(q, safeLimit) - const raw = rawOuter && typeof rawOuter === 'object' && 'data' in rawOuter && rawOuter.data ? rawOuter.data : rawOuter - if (raw && Array.isArray(raw.files)) { - return raw.files.map(normalizeIndexedFileEntry) - } - } - } - } catch { - // ignore - } - return [] -} - -/** - * 深度扫描指定真实物理目录树(支持符号链接穿透,如 AppData\Roaming\Tencent -> D:\Local\Roaming\Tencent) - * 返回该目录下 Top 文件列表、全树真实文件总数、全树真实总字节数与一级子目录汇总 - */ -export async function scanRealDirectoryTree( - dirPath: string, - limitOrOptions: number | ScanDirectoryTreeOptions = 160, - hostOverrideArg?: DynamicBridge -): Promise { - const result = await scanDirectoryTreeWithError(dirPath, limitOrOptions, hostOverrideArg) - return result.error ? { ...result.scan, error: result.error } : result.scan -} - -/** 一次界面扫描的错误汇总;多个目录并行扫描时保留可读目录的结果。 */ -export function createDirectoryScanner(hostOverride?: DynamicBridge) { - const failures = new Map() - return { - async scan(dir: string, options: number | ScanDirectoryTreeOptions = 160) { - const result = await scanRealDirectoryTree(dir, options, hostOverride) - const error = result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') - if (error) failures.set(dir, error) - else failures.delete(dir) - return result - }, - get error(): string | undefined { - if (!failures.size) return undefined - const s = ipcStrings() - const details = [...failures].slice(0, 3).map(([dir, error]) => `${dir}${s.dirErrorColon}${error}`).join(s.dirEntrySep) - return s.dirReadFailed(details, Math.max(0, failures.size - 3)) - } - } -} - -/** scanRealDirectoryTree 的实现:额外带回读取失败原因(目录不存在 / 为空 / 无权限 / 载荷异常) */ -async function scanDirectoryTreeWithError( - dirPath: string, - limitOrOptions: number | ScanDirectoryTreeOptions, - hostOverrideArg?: DynamicBridge -): Promise<{ scan: RealDirectoryScanResult; error?: string }> { - const empty = makeScanResult([], 0, 0, []) - if (!dirPath || !dirPath.trim()) return { scan: empty, error: 'EMPTY_DIRECTORY_PATH' } - const targetDir = dirPath.trim() - - const opts: ScanDirectoryTreeOptions = - typeof limitOrOptions === 'number' - ? { maxFiles: limitOrOptions, hostOverride: hostOverrideArg } - : { ...limitOrOptions, hostOverride: limitOrOptions?.hostOverride ?? hostOverrideArg } - - const rawLimit = opts.maxFiles ?? opts.collectTopN ?? 160 - const safeLimit = Math.min(200, Math.max(1, Math.floor(rawLimit || 160))) - const hostOverride = opts.hostOverride - const filterExt = opts.filterExt - const dirQuery = `dir:${targetDir}` - - try { - let rawPayload: DynamicBridge = null - const res = await callHostTransport( - 'system_search_files', - { query: dirQuery, limit: safeLimit }, - hostOverride - ) - if (res.ok && res.data) { - rawPayload = res.data - } - if (!rawPayload && !hostOverride && typeof window !== 'undefined') { - const w = window as DynamicBridge - if (typeof w.__ztoolsLauncher?.searchFiles === 'function') { - const rawOuter = await w.__ztoolsLauncher.searchFiles(dirQuery, safeLimit) - rawPayload = - rawOuter && typeof rawOuter === 'object' && 'data' in rawOuter && rawOuter.data - ? rawOuter.data - : rawOuter - } - } - - if ( - rawPayload && - Array.isArray(rawPayload.files) - ) { - let files: RealIndexedFileEntry[] = rawPayload.files.map(normalizeIndexedFileEntry) - if (filterExt instanceof RegExp) { - files = files.filter(f => !f.isDir && (filterExt.test(f.name) || filterExt.test(f.ext))) - // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索目标扩展名 - if (files.length === 0 && !hostOverride) { - const extTokens = (filterExt.source.match(/[a-z0-9]{2,5}/gi) || []) - .filter(t => !['thumbcache', 'iconcache'].includes(t.toLowerCase())) - .slice(0, 4) - // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 - const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() - const extraLists = await Promise.all( - extTokens.map(ext => searchRealIndexedFiles(`.${ext.toLowerCase()}`, 30, hostOverride)) - ) - const seen = new Set() - for (const list of extraLists) { - for (const item of list) { - if (!item.isDir && item.size > 0 && !seen.has(item.path)) { - if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { - seen.add(item.path) - files.push(item) - } - } - } - } - } - } - if (typeof opts.collectTopN === 'number' && opts.collectTopN > 0 && files.length > opts.collectTopN) { - files = files.slice(0, opts.collectTopN) - } - const subdirs: RealDirectorySubdirSummary[] = Array.isArray(rawPayload.subdirs) - ? rawPayload.subdirs.map((s: DynamicBridge) => ({ - name: String(s.name || ''), - path: String(s.path || ''), - fileCount: Number(s.file_count ?? s.fileCount ?? 0), - totalBytes: Number(s.total_bytes ?? s.totalBytes ?? 0), - mtime: Number(s.mtime || 0), - ...(s.approximate === true ? { approximate: true } : {}) - })) - : [] - const computedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) - const totalFilesCount = - filterExt instanceof RegExp ? files.length : Number(rawPayload.total_matches ?? files.length) - const totalBytesCount = - filterExt instanceof RegExp ? computedBytes : Number(rawPayload.total_bytes ?? computedBytes) - const visited = Number(rawPayload.visited_entries) - return { - scan: makeScanResult(files, totalFilesCount, totalBytesCount, subdirs, { - truncated: rawPayload.truncated === true, - approximate: rawPayload.approximate === true, - ...(Number.isFinite(visited) && visited >= 0 ? { visitedEntries: visited } : {}) - }), - ...(typeof rawPayload.scan_error === 'string' && rawPayload.scan_error ? { error: rawPayload.scan_error } : {}) - } - } - - // 深度扫描失败或回执无效时,仅以一级目录读取补回可见结果;不冒充完整目录树。 - const listing = await listDirectoryViaFilesystem(targetDir, hostOverride, { withSizes: true, limit: safeLimit }) - if (listing.ok && listing.entries.length > 0) { - const files: RealIndexedFileEntry[] = [] - let totalBytes = 0 - for (const entry of listing.entries) { - if (filterExt instanceof RegExp && !filterExt.test(entry.name) && !filterExt.test(entry.ext)) { - continue - } - files.push(entry) - totalBytes += entry.isDir ? 0 : entry.size - } - const incomplete = listing.entries.some(entry => entry.isDir) || listing.entries.length >= safeLimit - return { - scan: makeScanResult(files, files.filter(file => !file.isDir).length, totalBytes, [], { approximate: incomplete }), - ...(incomplete ? { error: res.error || ipcStrings().deepScanUnavailable } : {}) - } - } - return listing.ok ? { scan: empty } : { scan: empty, error: listing.error || 'DIRECTORY_READ_FAILED' } - } catch (error) { - return { scan: empty, error: error instanceof Error ? error.message : String(error) } - } -} - - -/** 目录读取不到任何条目(不存在 / 为空 / 无权限)时的错误码 */ -export const DIRECTORY_EMPTY_OR_UNREADABLE = 'DIRECTORY_EMPTY_OR_UNREADABLE' - -export interface RealDirectoryListingResult { - /** 目录内条目的完整路径;读取失败时为空数组 */ - entries: string[] - /** 读取失败或目录为空时的错误码 / 宿主错误信息 */ - error?: string -} - -export interface RealDirectChildrenResult { - /** 目录的直接子项(子目录在前),按路径去重 */ - entries: RealIndexedFileEntry[] - /** 宿主扫描达到条目上限,可能只返回了部分直接子项 */ - partial: boolean - error?: string -} - -function stripTrailingSeparators(p: string): string { - const trimmed = p.replace(/[\\/]+$/, '') - return trimmed || p.slice(0, 1) -} - -function isWindowsStylePath(p: string): boolean { - return /^[A-Za-z]:/.test(p) || p.startsWith('\\\\') || (p.includes('\\') && !p.includes('/')) -} - -function comparablePath(p: string): string { - const stripped = stripTrailingSeparators(String(p || '').trim()) - return isWindowsStylePath(stripped) ? stripped.replace(/\//g, '\\').toLowerCase() : stripped -} - -function parentDirOf(p: string): string { - const stripped = stripTrailingSeparators(String(p || '')) - const idx = Math.max(stripped.lastIndexOf('/'), stripped.lastIndexOf('\\')) - if (idx < 0) return '' - if (idx === 0) return stripped.slice(0, 1) - const parent = stripped.slice(0, idx) - return /^[A-Za-z]:$/.test(parent) ? `${parent}\\` : parent -} - -function isDirectChildPath(dirPath: string, candidate: string): boolean { - if (!candidate) return false - return comparablePath(parentDirOf(candidate)) === comparablePath(dirPath) -} - -function joinChildPath(dirPath: string, name: string): string { - const sep = isWindowsStylePath(dirPath) ? '\\' : '/' - const base = dirPath.replace(/[\\/]+$/, '') - return `${base}${sep}${name}` -} - -/** - * 通过 filesystem_get_directory_contents 读取一级目录(需宿主授权)。 - * 宿主真实返回 { success, files: [{ name, size, isDirectory, lastModified }] }(name 为文件名); - * 兼容旧测试替身返回的完整路径字符串数组。 - */ -async function listDirectoryViaFilesystem( - dirPath: string, - hostOverride: DynamicBridge, - options: { withSizes?: boolean; limit?: number } = {} -): Promise<{ ok: boolean; entries: RealIndexedFileEntry[]; error?: string }> { - const res = await callHostTransport('filesystem_get_directory_contents', { path: dirPath }, hostOverride) - if (!res.ok) return { ok: false, entries: [], error: res.error || 'DIRECTORY_READ_FAILED' } - const data = res.data - const rawList: unknown[] | null = Array.isArray(data) ? data : Array.isArray(data?.files) ? data.files : null - if (!rawList) return { ok: false, entries: [], error: 'INVALID_DIRECTORY_PAYLOAD' } - - const limit = Math.max(1, Math.floor(options.limit ?? 1000)) - const nowSec = Math.floor(Date.now() / 1000) - const entries: RealIndexedFileEntry[] = [] - const seen = new Set() - for (const item of rawList) { - if (entries.length >= limit) break - let entry: RealIndexedFileEntry | null = null - if (typeof item === 'string') { - const itemPath = item.trim() - if (!itemPath) continue - const name = itemPath.split(/[\\/]/).pop() || itemPath - const sz = options.withSizes ? await getRealFileSize(itemPath, hostOverride) : 0 - entry = normalizeIndexedFileEntry({ - name, - path: itemPath, - isDir: sz === 0 && !name.includes('.'), - size: sz, - mtime: nowSec - }) - } else if (item && typeof item === 'object' && typeof (item as DynamicBridge).name === 'string') { - const raw = item as DynamicBridge - const rawName = raw.name.trim() - if (!rawName || rawName === '.' || rawName === '..') continue - // 只接受文件名,或确实位于该目录下的完整路径,拒绝越界路径 - const fullPath = /[\\/]/.test(rawName) ? rawName : joinChildPath(dirPath, rawName) - if (!isDirectChildPath(dirPath, fullPath)) continue - const isDir = Boolean(raw.isDirectory ?? raw.isDir ?? raw.is_dir) - const parsedMtime = Date.parse(String(raw.lastModified || '')) - entry = normalizeIndexedFileEntry({ - name: fullPath.split(/[\\/]/).pop() || rawName, - path: fullPath, - isDir, - size: isDir ? 0 : Math.max(0, Number(raw.size) || 0), - mtime: Number.isFinite(parsedMtime) ? parsedMtime : nowSec - }) - } - if (!entry || seen.has(entry.path)) continue - seen.add(entry.path) - entries.push(entry) - } - return { ok: true, entries } -} - -/** - * 读取真实目录下的条目路径(真实宿主中优先走 dir: 扫描:一级子目录 + 全树 Top-N 大文件),并返回失败原因。 - * 目录不存在、为空或无权限时返回空列表与错误码,绝不用全盘关键词搜索结果冒充目录内容。 - */ -export async function listRealDirectoryContentsResult( - dirPath: string, - hostOverride?: DynamicBridge -): Promise { - if (!dirPath || !dirPath.trim()) return { entries: [], error: 'EMPTY_DIRECTORY_PATH' } - const targetDir = dirPath.trim() - - if (!hostOverride && isRealElectronHost()) { - const tree = await scanRealDirectoryTree(targetDir, 60) - const paths: string[] = [] - for (const s of tree.subdirs) { - if (s.path) paths.push(s.path) - } - for (const f of tree.files) { - if (f.path) paths.push(f.path) - } - if (paths.length > 0) return { entries: Array.from(new Set(paths)) } - } - - const listing = await listDirectoryViaFilesystem(targetDir, hostOverride) - if (!listing.ok) return { entries: [], error: listing.error } - if (listing.entries.length === 0) return { entries: [], error: DIRECTORY_EMPTY_OR_UNREADABLE } - return { entries: listing.entries.map(e => e.path) } -} - -/** - * 读取真实目录下的条目路径(保持旧签名:失败时返回空数组,需要失败原因请用 listRealDirectoryContentsResult) - */ -export async function listRealDirectoryContents( - dirPath: string, - hostOverride?: DynamicBridge -): Promise { - return (await listRealDirectoryContentsResult(dirPath, hostOverride)).entries -} - -/** - * 只列出目录的直接子项(子目录 + 直接位于该目录下的文件),用于文件夹预览、按目录改名等场景。 - * dir: 扫描结果中只保留 subdirs 与父目录等于 dirPath 的文件;扫描达到上限时 partial=true,由插件如实提示「仅显示部分」。 - */ -export async function listDirectChildren( - dirPath: string, - hostOverride?: DynamicBridge -): Promise { - if (!dirPath || !dirPath.trim()) return { entries: [], partial: false, error: 'EMPTY_DIRECTORY_PATH' } - const targetDir = dirPath.trim() - const scanLimit = 200 - const entries: RealIndexedFileEntry[] = [] - const seen = new Set() - const push = (entry: RealIndexedFileEntry) => { - const key = comparablePath(entry.path) - if (!entry.path || seen.has(key)) return - seen.add(key) - entries.push(entry) - } - - const { scan: tree, error } = await scanDirectoryTreeWithError(targetDir, { maxFiles: scanLimit, hostOverride }) - for (const s of tree.subdirs) { - if (!s.path || !isDirectChildPath(targetDir, s.path)) continue - push( - normalizeIndexedFileEntry({ - name: s.name || s.path.split(/[\\/]/).pop(), - path: s.path, - isDir: true, - size: s.totalBytes, - mtime: s.mtime - }) - ) - } - let directFileCount = 0 - for (const f of tree.files) { - if (!isDirectChildPath(targetDir, f.path)) continue - directFileCount++ - push(f) - } - // 宿主 total_matches 是全树文件数、subdirs[].file_count 是各子目录全树文件数,差值即直接子文件数; - // 拿到的直接子文件少于它就说明被 Top-N 截断了。计数不可用时按是否达到扫描上限判断 - const expectedDirectFiles = tree.totalFiles - tree.subdirs.reduce((sum, d) => sum + (Number(d.fileCount) || 0), 0) - const partial = - Number.isFinite(expectedDirectFiles) && expectedDirectFiles >= 0 - ? directFileCount < expectedDirectFiles - : tree.files.length >= scanLimit - if (entries.length > 0) { - return { entries, partial } - } - - if (tree.files.length > 0) { - // dir: 扫描只返回了深层文件(直接子文件被 Top-N 截掉),如实标注部分结果 - return { entries: [], partial: true, error: DIRECTORY_EMPTY_OR_UNREADABLE } - } - return { entries: [], partial: false, error: error || DIRECTORY_EMPTY_OR_UNREADABLE } -} - -/** - * 获取真实文件字节大小(优先用扫描结果里的大小,再走 filesystem_get_file_size);读不到时返回 0 - */ -export async function getRealFileSize( - filePath: string, - hostOverride?: DynamicBridge -): Promise { - if (!filePath) return 0 - if (!hostOverride && realFileSizeCache.has(filePath)) { - const cached = realFileSizeCache.get(filePath)! - if (cached > 0) return cached - } - const res = await callHostTransport('filesystem_get_file_size', { path: filePath }, hostOverride) - // 客户端返回 { success, size }(目录时 size 为 -1),旧的测试替身直接返回数字 - const size = typeof res.data === 'number' ? res.data : res.data?.size - if (res.ok && typeof size === 'number' && Number.isFinite(size) && size >= 0) { - realFileSizeCache.set(filePath, size) - return size - } - return 0 -} - -/** - * 在访达 / 资源管理器中定位并高亮文件或目录。 - * 定位失败直接返回 false,不能改用“打开”:对可执行文件那等于运行它。 - */ -export async function showRealItemInFolder( - fullPath: string, - hostOverride?: DynamicBridge -): Promise { - if (!fullPath) return false - const res = await callHostTransport('shell_show_item_in_folder', { fullPath }, hostOverride) - return res.ok -} - -/** - * 使用系统默认程序打开文件或目录 - */ -export async function openRealPath( - fullPath: string, - hostOverride?: DynamicBridge -): Promise { - if (!fullPath) return false - const res = await callHostTransport('shell_open_path', { fullPath }, hostOverride) - return res.ok -} - -/** - * 将真实文件或目录移入系统回收站(安全可恢复删除) - */ -export async function trashRealItem( - fullPath: string, - hostOverride?: DynamicBridge -): Promise<{ ok: boolean; error?: string; errorCode?: string; errorDetails?: Record }> { - if (!fullPath) return { ok: false, error: ipcStrings().pathEmpty } - const res = await callHostTransport('shell_trash_item', { fullPath }, hostOverride) - return { - ok: res.ok, - error: res.error, - ...(!res.ok && res.errorCode ? { errorCode: res.errorCode } : {}), - ...(!res.ok && res.errorDetails ? { errorDetails: res.errorDetails } : {}) - } -} - -export interface NativeInvocationResult { - ok: boolean - code: number - message: string - data?: T - error?: string - errorCode?: string - errorDetails?: Record -} - -export interface DllCapabilityResponse { - ok: boolean - code: number - data: T | null - message?: string - error?: string - errorCode?: string - errorDetails?: Record - pluginName: string - method: string - fromFallback?: boolean -} - -/** 声明式能力菜单项及其调用回执,供相同宿主协议的插件共用。 */ -export interface CapabilityActionItem { - id: string - title: string - subtitle: string - tag: string - method: string - params: Record -} - -export type PluginInvocationResult = Pick< - DllCapabilityResponse, 'ok' | 'pluginName' | 'method' | 'error' | 'errorCode' | 'errorDetails' | 'fromFallback' -> & { data?: unknown } - -/** 多个原生能力插件共用的参数边界校验;保护目标由各插件按自身业务提供。 */ -export function validateNativeCapabilityPayload( - method: string, - params: unknown, - forbiddenPattern: RegExp, - forbiddenReason: string -): { valid: boolean; error?: string } { - const s = ipcStrings() - if (typeof method !== 'string' || method.trim().length === 0) { - return { valid: false, error: s.invalidMethodEmpty } - } - if (method.length > 128 || !/^[A-Za-z0-9_]+$/.test(method.trim())) { - return { valid: false, error: s.invalidMethodFormat } - } - if (params === null || params === undefined || typeof params !== 'object' || Array.isArray(params)) { - return { valid: false, error: s.invalidParamsObject } - } - - const record = params as Record - for (const [key, val] of Object.entries(record)) { - if (typeof val === 'string') { - if (val.length > 4096) { - return { valid: false, error: s.paramTooLong(key) } - } - if (forbiddenPattern.test(val)) { - return { valid: false, error: `SECURITY_INTERCEPTED: ${forbiddenReason}` } - } - } else if (typeof val === 'number') { - if (!Number.isFinite(val) || val < -1000 || val > 100_000_000) { - return { valid: false, error: s.paramOutOfRange(key) } - } - } - } - - return { valid: true } -} - -export async function invokeDllPluginCapability( - pluginName: string, - method: string, - params: Record = {}, - hostBridge?: DynamicBridge, - offlineFallback?: () => T | Promise -): Promise> { - const s = ipcStrings() - if (!method || typeof method !== 'string' || method.trim().length === 0) { - return { - ok: false, - code: -1, - data: null, - message: s.methodParamEmpty, - error: s.invalidMethodType, - pluginName, - method: String(method || '') - } - } - - const trimmedMethod = method.trim() - - const unwrapDllRawPayload = (raw: unknown, unwrapDataProperty: boolean): DllCapabilityResponse => { - let parsed: DynamicBridge = raw - if (typeof raw === 'string') { - try { - parsed = JSON.parse(raw) - } catch { - throw new Error(s.malformedDllResponse) - } - } - if (parsed && typeof parsed === 'object') { - if ('error' in parsed && parsed.error !== undefined && parsed.error !== null && parsed.error !== '') { - const errMsg = `DLL_ERROR: ${String(parsed.error)}` - return { - ok: false, - code: typeof parsed.code === 'number' ? parsed.code : -1, - data: null, - message: errMsg, - error: errMsg, - ...extractIpcErrorMeta(parsed), - ...extractIpcErrorMeta(parsed.error), - pluginName, - method: trimmedMethod, - fromFallback: false - } - } - if ('ok' in parsed && parsed.ok === false) { - const errMsg = `DLL_ERROR: ${String(parsed.error || parsed.message || s.unknownDllError)}` - return { - ok: false, - code: typeof parsed.code === 'number' ? parsed.code : -1, - data: null, - message: errMsg, - error: errMsg, - ...extractIpcErrorMeta(parsed), - ...extractIpcErrorMeta(parsed.error), - pluginName, - method: trimmedMethod, - fromFallback: false - } - } - const dataPayload = unwrapDataProperty && 'data' in parsed && parsed.data !== undefined ? parsed.data : parsed - return { - ok: true, - code: typeof parsed.code === 'number' ? parsed.code : 0, - data: dataPayload as T, - message: typeof parsed.message === 'string' ? parsed.message : undefined, - pluginName, - method: trimmedMethod, - fromFallback: false - } - } - return { - ok: true, - code: 0, - data: (parsed ?? null) as T, - pluginName, - method: trimmedMethod, - fromFallback: false - } - } - - const wrapCaughtDllError = (err: unknown): DllCapabilityResponse => { - const message = err instanceof Error ? err.message : String(err) - if (message.startsWith('MALFORMED_DLL_RESPONSE:')) { - throw err - } - const errMsg = `NATIVE_CALL_FAILED: ${message}` - return { - ok: false, - code: -1, - data: null, - message: errMsg, - error: errMsg, - ...extractIpcErrorMeta(err), - pluginName, - method: trimmedMethod, - fromFallback: false - } - } - - if (hostBridge && typeof hostBridge.invokeNative === 'function') { - try { - const raw = await hostBridge.invokeNative(pluginName, trimmedMethod, params) - return unwrapDllRawPayload(raw, true) - } catch (err: unknown) { - return wrapCaughtDllError(err) - } - } - - const runtimeHost = (hostBridge ?? (globalThis as Record).ztools) as - | { dllplugin?: { call?: (plugin: string, fn: string, payload: unknown) => Promise | unknown } } - | undefined - - const callFn = runtimeHost?.dllplugin?.call - if (typeof callFn === 'function') { - try { - const raw = await callFn.call(runtimeHost?.dllplugin, pluginName, trimmedMethod, params) - return unwrapDllRawPayload(raw, false) - } catch (err: unknown) { - return wrapCaughtDllError(err) - } - } - - const ipcRes = await callHostTransport( - 'dllplugin_call', - { - plugin: pluginName, - func: trimmedMethod, - params - }, - hostBridge - ) - - if (ipcRes.ok && ipcRes.data !== undefined && ipcRes.data !== null) { - return unwrapDllRawPayload(ipcRes.data, false) - } - - const isExplicitTransportFailure = - typeof ipcRes.error === 'string' && - ipcRes.error.length > 0 && - ipcRes.error !== 'NO_WINDOW_ENV' && - !ipcRes.error.startsWith('METHOD_NOT_AVAILABLE:') - - if ( - isRealElectronHost(hostBridge) || - isRealElectronHost() || - Boolean((hostBridge as DynamicBridge)?.__isRealHost) || - isExplicitTransportFailure - ) { - const errMsg = - ipcRes.error || s.hostIpcFailed(pluginName, trimmedMethod) - return { - ok: false, - code: -1, - data: null, - message: errMsg, - error: errMsg, - ...(ipcRes.errorCode ? { errorCode: ipcRes.errorCode } : {}), - ...(ipcRes.errorDetails ? { errorDetails: ipcRes.errorDetails } : {}), - pluginName, - method: trimmedMethod, - fromFallback: false - } - } - - if (typeof offlineFallback === 'function') { - const fallbackData = await offlineFallback() - return { - ok: true, - code: 0, - data: fallbackData, - pluginName, - method: trimmedMethod, - fromFallback: true - } - } - - const unavailableMsg = s.hostUnavailable(pluginName, trimmedMethod) - return { - ok: false, - code: -1, - data: null, - message: unavailableMsg, - error: unavailableMsg, - ...(ipcRes.errorCode ? { errorCode: ipcRes.errorCode } : {}), - ...(ipcRes.errorDetails ? { errorDetails: ipcRes.errorDetails } : {}), - pluginName, - method: trimmedMethod, - fromFallback: true - } -} - -export function formatBytes(bytes: number, decimals = 1): string { - const num = Number(bytes) - if (!Number.isFinite(num) || num <= 0) return '0 B' - if (num < 1024) return `${Math.round(num)} B` - const units = ['B', 'KB', 'MB', 'GB', 'TB'] - let val = num - let idx = 0 - while (val >= 1024 && idx < units.length - 1) { - val /= 1024 - idx += 1 - } - const safeDecimals = Math.max(0, Math.floor(decimals)) - return `${val >= 100 ? val.toFixed(0) : val.toFixed(safeDecimals)} ${units[idx]}` -} - -export function joinWinPath(...segments: string[]): string { - return segments - .filter(s => typeof s === 'string' && s.trim().length > 0) - .map((s, i) => (i === 0 ? s.replace(/[\\/]+$/, '') : s.replace(/^[\\/]+|[\\/]+$/g, ''))) - .join('\\') -} - -export interface RealEnvPaths { - home: string - userProfile: string - appData: string - localAppData: string - temp: string - downloads: string - documents: string - desktop: string - pictures: string - videos: string - music: string -} - -export async function getRealEnvPaths(hostOverride?: DynamicBridge): Promise { - const [homeRaw, appData, downloads, documents, desktop, pictures, videos, music] = await Promise.all([ - getRealSystemPath('home', hostOverride), - getRealSystemPath('appData', hostOverride), - getRealSystemPath('downloads', hostOverride), - getRealSystemPath('documents', hostOverride), - getRealSystemPath('desktop', hostOverride), - getRealSystemPath('pictures', hostOverride), - getRealSystemPath('videos', hostOverride), - getRealSystemPath('music', hostOverride) - ]) - const home = homeRaw || 'C:\\Users\\Default' - const isPosix = home.startsWith('/') - const tempRes = hostOverride ? await getRealSystemPath('temp', hostOverride) : '' - if (isPosix) { - return { - home, - userProfile: home, - appData: appData || `${home}/Library/Application Support`, - localAppData: `${home}/Library/Application Support`, - temp: tempRes || '/tmp', - downloads: downloads || `${home}/Downloads`, - documents: documents || `${home}/Documents`, - desktop: desktop || `${home}/Desktop`, - pictures: pictures || `${home}/Pictures`, - videos: videos || `${home}/Videos`, - music: music || `${home}/Music` - } - } - return { - home, - userProfile: home, - appData: appData || `${home}\\AppData\\Roaming`, - localAppData: `${home}\\AppData\\Local`, - temp: tempRes || `${home}\\AppData\\Local\\Temp`, - downloads: downloads || `${home}\\Downloads`, - documents: documents || `${home}\\Documents`, - desktop: desktop || `${home}\\Desktop`, - pictures: pictures || `${home}\\Pictures`, - videos: videos || `${home}\\Videos`, - music: music || `${home}\\Music` - } -} - -export const resolveRealSpecialPaths = getRealEnvPaths - -export async function readRealDirectory( - dirPath: string, - hostOverride?: DynamicBridge -): Promise { - if (!dirPath) return [] - const tree = await scanRealDirectoryTree(dirPath, { maxFiles: 120, hostOverride }) - const entries: RealIndexedFileEntry[] = [] - for (const s of tree.subdirs) { - entries.push( - normalizeIndexedFileEntry({ - name: s.name, - path: s.path, - isDir: true, - isDirectory: true, - size: s.totalBytes, - mtime: s.mtime - }) - ) - } - for (const f of tree.files) { - entries.push(f) - } - // scanRealDirectoryTree 已在 dir: 扫描无结果时退回一级目录读取;仍为空即目录不存在 / 为空 / 无权限,如实返回空列表 - return entries -} - -export async function moveRealFilesToTrash( - paths: string[], - hostOverride?: DynamicBridge -): Promise<{ - ok: boolean - trashedCount: number - deletedCount: number - failedPaths: string[] - error?: string -}> { - let deletedCount = 0 - const failedPaths: string[] = [] - let lastError: string | undefined - for (const p of paths) { - if (!p) continue - const res = await trashRealItem(p, hostOverride) - if (res.ok) { - deletedCount += 1 - } else { - failedPaths.push(p) - if (res.error) lastError = res.error - } - } - return { - ok: deletedCount > 0 || paths.length === 0, - trashedCount: deletedCount, - deletedCount, - failedPaths, - error: lastError - } -} - -const CAPABILITY_TO_PLUGIN_MAP: Record = { - 'mover.relocateWithJunction': { plugin: 'MoverPlugin', func: 'relocateWithJunction' }, - 'mover.scanCandidates': { plugin: 'MoverPlugin', func: 'scanCandidates' }, - 'recovery.restoreFile': { plugin: 'DataRecoveryPlugin', func: 'restoreFile' }, - 'recovery.scanDeletedFiles': { plugin: 'DataRecoveryPlugin', func: 'scanDeletedFiles' }, - 'shredder.secureWipeFile': { plugin: 'ShredderPlugin', func: 'secureWipeFile' }, - 'shredder.scanCandidates': { plugin: 'ShredderPlugin', func: 'scanCandidates' }, - 'backup.createSnapshotArchive': { plugin: 'SystemBackupPlugin', func: 'createSnapshotArchive' }, - 'backup.restoreSnapshotArchive': { plugin: 'SystemBackupPlugin', func: 'restoreSnapshotArchive' }, - 'backup.scanSnapshots': { plugin: 'SystemBackupPlugin', func: 'scanSnapshots' }, - 'sqlite.execute': { plugin: 'SqlitePlugin', func: 'execute' }, - 'sqlite.query': { plugin: 'SqlitePlugin', func: 'executeQuery' }, - 'sqlite.inspectWorkspace': { plugin: 'SqlitePlugin', func: 'inspectWorkspace' } -} - -export async function invokeHostCapability( - capability: string, - params: Record = {}, - hostOverride?: DynamicBridge -): Promise> { - const normalizedMethod = capability.replace(/\./g, '_') - - // 若测试显式注入了对应 normalizedMethod 的 mock 函数,优先调用测试桩 - if (hostOverride && typeof hostOverride[normalizedMethod] === 'function') { - const mockRes = await callHostTransport(normalizedMethod, params, hostOverride) - return { - ok: mockRes.ok, - code: mockRes.ok ? 0 : -1, - message: mockRes.ok ? 'OK' : mockRes.error || ipcStrings().callFailed, - data: mockRes.data, - error: mockRes.error, - ...(!mockRes.ok && mockRes.errorCode ? { errorCode: mockRes.errorCode } : {}), - ...(!mockRes.ok && mockRes.errorDetails ? { errorDetails: mockRes.errorDetails } : {}) - } - } - - if (capability === 'system.info') { - const drives = await probeRealDiskDrives(['C', 'D', 'E', 'F'], hostOverride) - return { - ok: true, - code: 0, - message: 'OK', - data: { - storage: drives.map(d => ({ - mount: d.drive, - fs: d.drive, - size: d.totalBytes, - total: d.totalBytes, - used: d.usedBytes, - available: d.availableBytes, - free: d.availableBytes, - percent: d.usagePercent - })) - } as unknown as T - } - } - if (capability === 'filesystem.deleteItem') { - const targetPath = String(params.path || params.fullPath || '') - const tr = await trashRealItem(targetPath, hostOverride) - const s = ipcStrings() - return { - ok: tr.ok, - code: tr.ok ? 0 : -1, - message: tr.ok ? s.movedToTrash : tr.error || s.deleteFailed, - error: tr.error, - ...(!tr.ok && tr.errorCode ? { errorCode: tr.errorCode } : {}), - ...(!tr.ok && tr.errorDetails ? { errorDetails: tr.errorDetails } : {}) - } - } - if (capability === 'system.showItemInFolder') { - const targetPath = String(params.path || params.fullPath || '') - const s = ipcStrings() - if (!targetPath) { - return { ok: false, code: -1, message: s.revealFailed } - } - const res = await callHostTransport('shell_show_item_in_folder', { fullPath: targetPath }, hostOverride) - return { - ok: res.ok, - code: res.ok ? 0 : -1, - message: res.ok ? s.revealedInFolder : res.error || s.revealFailed, - ...(!res.ok && res.error ? { error: res.error } : {}), - ...(!res.ok && res.errorCode ? { errorCode: res.errorCode } : {}), - ...(!res.ok && res.errorDetails ? { errorDetails: res.errorDetails } : {}) - } - } - if (capability === 'filesystem.openItem' || capability === 'system.openUrl') { - const target = String(params.path || params.url || params.fullPath || '') - const method = capability === 'system.openUrl' ? 'shell_open_external' : 'shell_open_path' - const res = await callHostTransport( - method, - capability === 'system.openUrl' ? { url: target } : { fullPath: target }, - hostOverride - ) - const s = ipcStrings() - return { - ok: res.ok, - code: res.ok ? 0 : -1, - message: res.ok ? s.opened : res.error || s.openFailed, - data: res.data, - error: res.error, - ...(!res.ok && res.errorCode ? { errorCode: res.errorCode } : {}), - ...(!res.ok && res.errorDetails ? { errorDetails: res.errorDetails } : {}) - } - } - - const pluginMapping = CAPABILITY_TO_PLUGIN_MAP[capability] - if (pluginMapping) { - const dllRes = await invokePluginService( - pluginMapping.plugin, - pluginMapping.func, - params, - hostOverride - ) - if (dllRes.ok) return dllRes - if (hostOverride) { - const fallbackMock = await callHostTransport(normalizedMethod, params, hostOverride) - if (fallbackMock.ok) { - return { - ok: true, - code: 0, - message: 'OK', - data: fallbackMock.data - } - } - } - return dllRes - } - - const res = await callHostTransport(normalizedMethod, params, hostOverride) - return { - ok: res.ok, - code: res.ok ? 0 : -1, - message: res.ok ? 'OK' : res.error || ipcStrings().callFailed, - data: res.data, - error: res.error, - ...(!res.ok && res.errorCode ? { errorCode: res.errorCode } : {}), - ...(!res.ok && res.errorDetails ? { errorDetails: res.errorDetails } : {}) - } -} - -export async function invokePluginService( - pluginName: string, - action: string, - params: Record = {}, - hostOverride?: DynamicBridge -): Promise> { - const s = ipcStrings() - // 1. 若测试注入了专门拦截 plugin_invoke 的 mock,支持调用 - if (hostOverride && typeof hostOverride.plugin_invoke === 'function') { - const mockRes = await callHostTransport( - 'plugin_invoke', - { plugin: pluginName, action, params }, - hostOverride - ) - return { - ok: mockRes.ok, - code: mockRes.ok ? 0 : -1, - message: mockRes.ok ? 'OK' : mockRes.error || s.pluginCallNotReady, - data: mockRes.data, - error: mockRes.error, - ...(!mockRes.ok && mockRes.errorCode ? { errorCode: mockRes.errorCode } : {}), - ...(!mockRes.ok && mockRes.errorDetails ? { errorDetails: mockRes.errorDetails } : {}) - } - } - - // 2. 优先走真实 Electron IPC 的 dllplugin_call 通道 - const dllRes = await callHostTransport( - 'dllplugin_call', - { plugin: pluginName, func: action, params }, - hostOverride - ) - if (dllRes.ok) { - const inner = dllRes.data - if (inner && typeof inner === 'object' && typeof inner.error === 'string' && inner.error.length > 0 && inner.ok !== true) { - return { - ok: false, - code: -1, - message: inner.error, - error: inner.error, - ...extractIpcErrorMeta(inner) - } - } - return { - ok: true, - code: 0, - message: 'OK', - data: inner as T - } - } - - // 3. 兼容单元测试中通过 transport.call('plugin_invoke') 注入的测试桩 - if (hostOverride) { - const legacyRes = await callHostTransport( - 'plugin_invoke', - { plugin: pluginName, action, params }, - hostOverride - ) - if (legacyRes.ok) { - return { - ok: true, - code: 0, - message: 'OK', - data: legacyRes.data - } - } - } - - // 4. 兼容旧版 globalThis.ztools.dllplugin.call - const g = globalThis as DynamicBridge - if (!hostOverride && typeof g?.ztools?.dllplugin?.call === 'function') { - try { - const raw = await g.ztools.dllplugin.call(pluginName, action, params) - if (raw && typeof raw === 'object' && raw.ok === false) { - return { - ok: false, - code: -1, - message: String(raw.error || s.callFailed), - error: String(raw.error || s.callFailed), - ...extractIpcErrorMeta(raw), - ...extractIpcErrorMeta(raw.error) - } - } - const data = raw && typeof raw === 'object' && 'data' in raw ? raw.data : raw - return { ok: true, code: 0, message: 'OK', data: data as T } - } catch (err: DynamicBridge) { - return { - ok: false, - code: -1, - message: err instanceof Error ? err.message : String(err), - error: err instanceof Error ? err.message : String(err), - ...extractIpcErrorMeta(err) - } - } - } - - return { - ok: false, - code: -1, - message: dllRes.error || s.pluginCallNotReady, - error: dllRes.error || s.pluginCallNotReady, - ...(dllRes.errorCode ? { errorCode: dllRes.errorCode } : {}), - ...(dllRes.errorDetails ? { errorDetails: dllRes.errorDetails } : {}) - } -} - -const SHA256_K = new Uint32Array([ - 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, - 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, - 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, - 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, - 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, - 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, - 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, - 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 -]) - -function rotr32(x: number, n: number): number { - return (x >>> n) | (x << (32 - n)) -} - -/** - * 标准 FIPS 180-4 SHA-256 真实字节摘要算法(返回 64 位小写 Hex) - */ -export function computeRealSha256Hex(input: string | Uint8Array): string { - const bytes = - typeof input === 'string' ? new TextEncoder().encode(input) : new Uint8Array(input || []) - const bitLen = bytes.length * 8 - const padLen = ((bytes.length + 9 + 63) & ~63) - const buf = new Uint8Array(padLen) - buf.set(bytes, 0) - buf[bytes.length] = 0x80 - const view = new DataView(buf.buffer) - view.setUint32(padLen - 8, Math.floor(bitLen / 0x100000000), false) - view.setUint32(padLen - 4, bitLen >>> 0, false) - - let h0 = 0x6a09e667 - let h1 = 0xbb67ae85 - let h2 = 0x3c6ef372 - let h3 = 0xa54ff53a - let h4 = 0x510e527f - let h5 = 0x9b05688c - let h6 = 0x1f83d9ab - let h7 = 0x5be0cd19 - - const w = new Uint32Array(64) - for (let offset = 0; offset < padLen; offset += 64) { - for (let i = 0; i < 16; i++) { - w[i] = view.getUint32(offset + i * 4, false) - } - for (let i = 16; i < 64; i++) { - const s0 = rotr32(w[i - 15], 7) ^ rotr32(w[i - 15], 18) ^ (w[i - 15] >>> 3) - const s1 = rotr32(w[i - 2], 17) ^ rotr32(w[i - 2], 19) ^ (w[i - 2] >>> 10) - w[i] = (w[i - 16] + s0 + w[i - 7] + s1) >>> 0 - } - - let a = h0 - let b = h1 - let c = h2 - let d = h3 - let e = h4 - let f = h5 - let g = h6 - let h = h7 - - for (let i = 0; i < 64; i++) { - const S1 = rotr32(e, 6) ^ rotr32(e, 11) ^ rotr32(e, 25) - const ch = (e & f) ^ (~e & g) - const temp1 = (h + S1 + ch + SHA256_K[i] + w[i]) >>> 0 - const S0 = rotr32(a, 2) ^ rotr32(a, 13) ^ rotr32(a, 22) - const maj = (a & b) ^ (a & c) ^ (b & c) - const temp2 = (S0 + maj) >>> 0 - - h = g - g = f - f = e - e = (d + temp1) >>> 0 - d = c - c = b - b = a - a = (temp1 + temp2) >>> 0 - } - - h0 = (h0 + a) >>> 0 - h1 = (h1 + b) >>> 0 - h2 = (h2 + c) >>> 0 - h3 = (h3 + d) >>> 0 - h4 = (h4 + e) >>> 0 - h5 = (h5 + f) >>> 0 - h6 = (h6 + g) >>> 0 - h7 = (h7 + h) >>> 0 - } - - return [h0, h1, h2, h3, h4, h5, h6, h7] - .map(v => (v >>> 0).toString(16).padStart(8, '0')) - .join('') -} - -/** - * 读取本地文件真实字节并计算标准 SHA-256:宿主 filesearch_sha256(只接受 path 字段)优先,Windows 上再试 FileComparePlugin。 - * 都拿不到时返回空字符串,由调用方提示失败;不再把文件按 UTF-8 文本读出来再算(二进制文件会算出错误的值)。 - */ -export async function computeRealFileSha256( - filePath: string, - hostOverride?: DynamicBridge -): Promise { - if (!filePath || !filePath.trim()) return '' - const target = filePath.trim() - - const shaRes = await callHostTransport('filesearch_sha256', { fullPath: target }, hostOverride) - if (shaRes.ok && shaRes.data) { - const hash = typeof shaRes.data === 'string' ? shaRes.data : String(shaRes.data?.sha256 || shaRes.data?.hash || '') - if (/^[0-9a-f]{64}$/i.test(hash)) return hash.toLowerCase() - } - - const dllRes = await invokePluginService('FileComparePlugin', 'computeFileSha256', { path: target }, hostOverride) - if (dllRes.ok && dllRes.data) { - const hash = typeof dllRes.data === 'string' ? dllRes.data : String(dllRes.data?.sha256 || dllRes.data?.hash || '') - if (/^[0-9a-f]{64}$/i.test(hash)) return hash.toLowerCase() - } - - return '' -} - -export async function readRealClipboardText(hostOverride?: DynamicBridge): Promise { - const res = await callHostTransport('clipboard_read_text', {}, hostOverride) - if (res.ok && res.data !== undefined && res.data !== null) { - if (typeof res.data === 'string') return res.data - if (typeof res.data?.text === 'string') return res.data.text - } - try { - if (typeof navigator !== 'undefined' && navigator.clipboard?.readText) { - return await navigator.clipboard.readText() - } - } catch { - // ignore - } - return '' -} - -export async function writeRealClipboardText(text: string, hostOverride?: DynamicBridge): Promise { - const payload = { text: String(text || '') } - const res = await callHostTransport('clipboard_copy_text', payload, hostOverride) - if (res.ok) return true - const fallbackRes = await callHostTransport('clipboard_write_text', payload, hostOverride) - if (fallbackRes.ok) return true - try { - if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) { - await navigator.clipboard.writeText(String(text || '')) - return true - } - } catch { - // ignore - } - return false -} - -export async function showRealToast( - title: string, - style: 'success' | 'failure' | 'info' = 'info' -): Promise { - try { - const { showToast, Toast } = await import('@ztools/declarative-ui') - await showToast({ - title, - style: - style === 'success' - ? Toast.Style.Success - : style === 'failure' - ? Toast.Style.Failure - : Toast.Style.Animated - }) - } catch { - // ignore - } -} - diff --git a/extensions/archive-manager/src/tool-runtime.ts b/extensions/archive-manager/src/tool-runtime.ts new file mode 100644 index 00000000..29670de2 --- /dev/null +++ b/extensions/archive-manager/src/tool-runtime.ts @@ -0,0 +1,637 @@ +/** + * 宿主薄原语与基础系统能力传输层(唯一权威公共源文件,纯标准 IPC,零原生 DLL 依赖) + * + * 修改本文件后需同步复制到各使用插件的 src/tool-runtime.ts, + * 构建脚本 build-declarative.mjs 会在编译前校验副本与本文件一字不差。 + */ + +import { getHostTransport } from '@ztools/declarative-ui' + +export type ToolCapabilityStatus = 'ready' | 'needs_provisioning' | 'unsupported' + +export interface ToolCapabilityDescriptor { + readonly primitiveId: string + readonly domain: string + readonly summary: string + readonly ipcMethods: readonly string[] + readonly requiredPermissions: readonly string[] + readonly status: ToolCapabilityStatus + readonly optionalExtensions: readonly string[] +} + +export interface ToolRuntimeCapabilitiesSnapshot { + readonly contractVersion: number + readonly platform: 'windows' | 'macos' | 'other' + readonly domains: readonly string[] + readonly capabilities: readonly ToolCapabilityDescriptor[] +} + +export interface ToolRuntimeEnsureResult { + readonly primitiveId: string + readonly status: ToolCapabilityStatus + readonly provisioned: boolean +} + +export interface ToolCapabilitiesEnsureResult { + readonly ok: boolean + readonly status: ToolCapabilityStatus + readonly provisioned: boolean + readonly failedPrimitiveId?: string + readonly error?: string + readonly errorCode?: string + readonly errorDetails?: Record +} + +export interface ToolTaskCancelResult { + readonly taskId: string + readonly cancelled: boolean +} + +export interface ToolPathSlot { + readonly grantId?: string + readonly relativePath?: string + readonly path?: string +} + +export interface ToolProgressEvent { + readonly taskId: string + readonly primitiveId?: string + readonly phase: 'provisioning' | 'running' | 'finalizing' | 'completed' | 'cancelled' | 'failed' + readonly percent?: number + readonly transferredBytes?: number + readonly totalBytes?: number + readonly speedBytesPerSec?: number + readonly stage?: string + readonly errorCode?: string + readonly retryable?: boolean + readonly userAction?: string + readonly message?: string + readonly timestamp?: number +} + +export type MediaTranscodeRunResult = + | { readonly status: 'done'; readonly outputBytes: number; readonly durationMs: number } + | { readonly status: 'cancelled' } + | { + readonly status: 'failed' + readonly error?: string + readonly errorCode?: string + readonly errorDetails?: Record + } + +export interface HostTransportResult { + ok: boolean + data?: T + error?: string + errorCode?: string + errorDetails?: Record +} + +export interface HostCallOptions { + timeoutMs?: number +} + +type TransportMethodFn = (req: { messageId: string; params: Record; timeoutMs?: number }) => Promise + +interface WindowHostBridge { + __ztoolsElectron?: { + transport?: { + methods?: Record + } + } + ztools?: { + transport?: { + methods?: Record + call?: (method: string, params: Record, options?: { timeoutMs?: number }) => Promise + } + events?: { + subscribe?: (event: string) => Promise | void + on?: (event: string, cb: (payload: unknown) => void) => (() => void) | void + off?: (event: string, cb: (payload: unknown) => void) => void + } + } +} + +interface HostOverrideLike { + transport?: { + call?: (method: string, params: Record, options?: { timeoutMs?: number }) => Promise + } + [method: string]: unknown +} + +let reqSeq = 1 + +export function nextMessageId(prefix = 'tool'): string { + reqSeq = (reqSeq + 1) % 1_000_000 + return `${prefix}_${Date.now()}_${reqSeq}` +} + +export function asRecord(value: unknown): Record | null { + return value && typeof value === 'object' && !Array.isArray(value) + ? (value as Record) + : null +} + +function extractErrorMeta(errObj: unknown): { + errorCode?: string + errorDetails?: Record +} { + const rec = asRecord(errObj) + if (!rec) return {} + const errorCode = + typeof rec.errorCode === 'string' && rec.errorCode.trim() + ? rec.errorCode.trim() + : typeof rec.code === 'string' && rec.code.trim() + ? rec.code.trim() + : undefined + const rawDetails = asRecord(rec.errorDetails) ?? asRecord(rec.details) ?? undefined + return { + ...(errorCode ? { errorCode } : {}), + ...(rawDetails ? { errorDetails: rawDetails } : {}) + } +} + +function toTransportError(err: unknown): HostTransportResult { + return { + ok: false, + error: err instanceof Error ? err.message : String(err), + ...extractErrorMeta(err) + } +} + +function buildFailureResult(rec: Record, fallbackMsg: string): HostTransportResult { + const errObj = asRecord(rec.error) + const errMsg = errObj + ? String(errObj.message || errObj.code || JSON.stringify(errObj)) + : String(rec.error || rec.message || fallbackMsg) + return { ok: false, error: errMsg, ...extractErrorMeta(rec), ...extractErrorMeta(errObj) } +} + +function unwrapTransportResponse(raw: unknown): HostTransportResult { + if (raw === null || raw === undefined) { + return { ok: false, error: 'EMPTY_IPC_RESPONSE', errorCode: 'EMPTY_IPC_RESPONSE' } + } + if (typeof raw !== 'object') { + return { ok: true, data: raw as T } + } + const outer = asRecord(raw) + if (!outer) { + return { ok: true, data: raw as T } + } + if (outer.success === false || outer.ok === false) { + return buildFailureResult(outer, 'IPC_CALL_FAILED') + } + + const firstLayer = 'data' in outer && outer.data !== undefined ? outer.data : outer + const inner = asRecord(firstLayer) + if (inner) { + if (inner.success === false || inner.ok === false) { + return buildFailureResult(inner, 'IPC_INNER_FAILED') + } + if ('data' in inner && inner.data !== undefined) { + return { ok: true, data: inner.data as T } + } + } + + return { ok: true, data: firstLayer as T } +} + +/** 判断当前是否处于真实的 ZTools Electron 渲染进程宿主环境 */ +export function isRealElectronHost(hostOverride?: unknown): boolean { + if (hostOverride) return true + if (typeof window === 'undefined') return false + const w = window as unknown as WindowHostBridge + return Boolean( + w.__ztoolsElectron?.transport?.methods || + w.ztools?.transport?.call || + w.ztools?.transport?.methods + ) +} + +/** 统一调用宿主 IPC 传输层(优先测试桩,其次 declarative-ui 宿主通道与 preload 通道) */ +export async function callHostTransport( + method: string, + params: Record = {}, + hostOverride?: unknown, + options?: HostCallOptions +): Promise> { + const override = asRecord(hostOverride) as HostOverrideLike | null + if (override) { + const directFn = override[method] + if (typeof directFn === 'function') { + try { + return unwrapTransportResponse(await (directFn as (p: Record) => Promise)(params)) + } catch (err) { + return toTransportError(err) + } + } + if (typeof override.transport?.call === 'function') { + try { + return unwrapTransportResponse(await override.transport.call(method, params, options)) + } catch (err) { + return toTransportError(err) + } + } + return { ok: false, error: `METHOD_NOT_AVAILABLE: ${method}`, errorCode: 'METHOD_NOT_AVAILABLE' } + } + + // 优先走 declarative-ui 运行时注入的带归属令牌通道 + if (typeof getHostTransport === 'function') { + const transport = getHostTransport() + if (transport) { + try { + const callOpts = typeof options?.timeoutMs === 'number' ? { timeoutMs: options.timeoutMs } : undefined + return unwrapTransportResponse(await transport.call(method, params, callOpts)) + } catch (err) { + return toTransportError(err) + } + } + } + + if (typeof window === 'undefined') { + return { ok: false, error: 'NO_WINDOW_ENV', errorCode: 'NO_WINDOW_ENV' } + } + + const w = window as unknown as WindowHostBridge + const methods = w.__ztoolsElectron?.transport?.methods || w.ztools?.transport?.methods + const fn = methods?.[method] + if (typeof fn === 'function') { + try { + const messageId = nextMessageId(method.replace(/[^A-Za-z0-9_]/g, '_').slice(0, 24)) + const payload = { + messageId, + params, + ...(typeof options?.timeoutMs === 'number' ? { timeoutMs: options.timeoutMs } : {}) + } + return unwrapTransportResponse(await fn(payload)) + } catch (err) { + return toTransportError(err) + } + } + + if (typeof w.ztools?.transport?.call === 'function') { + try { + return unwrapTransportResponse(await w.ztools.transport.call(method, params, options)) + } catch (err) { + return toTransportError(err) + } + } + + return { ok: false, error: `METHOD_NOT_AVAILABLE: ${method}`, errorCode: 'METHOD_NOT_AVAILABLE' } +} + +/** 探测宿主薄原语能力快照(tool_runtime_capabilities) */ +export async function queryRuntimeCapabilities( + hostOverride?: unknown +): Promise> { + const res = await callHostTransport('tool_runtime_capabilities', {}, hostOverride) + if (!res.ok) return res as HostTransportResult + const rec = asRecord(res.data) + if (!rec || !Array.isArray(rec.capabilities)) { + return { + ok: false, + error: 'INVALID_CAPABILITIES_SNAPSHOT', + errorCode: 'INVALID_CAPABILITIES_SNAPSHOT' + } + } + const capabilities: ToolCapabilityDescriptor[] = [] + for (const rawCap of rec.capabilities) { + const cap = asRecord(rawCap) + if (!cap || typeof cap.primitiveId !== 'string') continue + const rawStatus = cap.status + const status: ToolCapabilityStatus = + rawStatus === 'ready' || rawStatus === 'needs_provisioning' || rawStatus === 'unsupported' + ? rawStatus + : 'unsupported' + const optionalExtensions = Array.isArray(cap.optionalExtensions) + ? cap.optionalExtensions.filter((e): e is string => typeof e === 'string' && e.trim().length > 0) + : [] + capabilities.push({ + primitiveId: cap.primitiveId, + domain: typeof cap.domain === 'string' ? cap.domain : '', + summary: typeof cap.summary === 'string' ? cap.summary : '', + ipcMethods: Array.isArray(cap.ipcMethods) ? cap.ipcMethods.filter((m): m is string => typeof m === 'string') : [], + requiredPermissions: Array.isArray(cap.requiredPermissions) + ? cap.requiredPermissions.filter((p): p is string => typeof p === 'string') + : [], + status, + optionalExtensions + }) + } + const platform = + rec.platform === 'windows' || rec.platform === 'macos' || rec.platform === 'other' + ? rec.platform + : 'other' + return { + ok: true, + data: { + contractVersion: typeof rec.contractVersion === 'number' ? rec.contractVersion : 1, + platform, + domains: Array.isArray(rec.domains) ? rec.domains.filter((d): d is string => typeof d === 'string') : [], + capabilities + } + } +} + +export function findCapability( + snapshot: ToolRuntimeCapabilitiesSnapshot | null | undefined, + primitiveId: string +): ToolCapabilityDescriptor | null { + if (!snapshot) return null + return snapshot.capabilities.find((c) => c.primitiveId === primitiveId) ?? null +} + +export function hasCapabilityExtension( + snapshot: ToolRuntimeCapabilitiesSnapshot | null | undefined, + primitiveId: string, + extensionName: string +): boolean { + const cap = findCapability(snapshot, primitiveId) + return Boolean(cap && cap.optionalExtensions.includes(extensionName)) +} + +/** 按需拉取并准备指定薄原语运行组件(tool_runtime_ensure) */ +export async function ensureRuntimeCapability( + primitiveId: string, + hostOverride?: unknown +): Promise> { + return callHostTransport('tool_runtime_ensure', { primitiveId }, hostOverride) +} + +/** 顺序按需准备多个薄原语运行组件,任一项未就绪即中止并聚合 provisioned 标记 */ +export async function ensureRuntimeCapabilities( + primitiveIds: readonly string[], + hostOverride?: unknown +): Promise { + let provisionedAny = false + for (const primitiveId of primitiveIds) { + const res = await ensureRuntimeCapability(primitiveId, hostOverride) + if (!res.ok || !res.data || res.data.status !== 'ready') { + return { + ok: false, + status: res.data?.status ?? 'unsupported', + provisioned: provisionedAny, + failedPrimitiveId: primitiveId, + error: res.error, + errorCode: res.errorCode, + errorDetails: res.errorDetails + } + } + if (res.data.provisioned) provisionedAny = true + } + return { ok: true, status: 'ready', provisioned: provisionedAny } +} + +/** 取消正在执行的宿主薄原语任务(tool_task_cancel) */ +export async function cancelRuntimeTask( + taskId: string, + hostOverride?: unknown +): Promise> { + return callHostTransport('tool_task_cancel', { taskId }, hostOverride) +} + +/** 判断错误码是否表示用户主动取消任务 */ +export function isTaskCancelledCode(errorCode?: string): boolean { + const code = (errorCode || '').trim().toUpperCase() + return code === 'TOOL_TASK_CANCELLED' || code === 'CANCELLED' || code === 'OPERATION_CANCELLED' +} + +/** 执行单个媒体转码任务(tool_media_transcode_run),统一处理取消与产物字节数校验 */ +export async function runMediaTranscodeTask( + payload: Record, + hostOverride?: unknown +): Promise { + const res = await callHostTransport('tool_media_transcode_run', payload, hostOverride) + if (!res.ok) { + if (isTaskCancelledCode(res.errorCode)) { + return { status: 'cancelled' } + } + return { + status: 'failed', + error: res.error, + errorCode: res.errorCode, + errorDetails: res.errorDetails + } + } + const rec = asRecord(res.data) + const outputBytes = Number(rec?.outputBytes) + const durationMs = Number(rec?.durationMs) + if (!Number.isFinite(outputBytes) || outputBytes <= 0) { + return { status: 'failed', error: 'EMPTY_OUTPUT', errorCode: 'EMPTY_OUTPUT' } + } + return { + status: 'done', + outputBytes, + durationMs: Number.isFinite(durationMs) && durationMs >= 0 ? durationMs : 0 + } +} + +/** 订阅宿主推送的 tool_runtime_progress 任务进度事件 */ +export function subscribeRuntimeProgress( + handler: (event: ToolProgressEvent) => void +): () => void { + if (typeof window === 'undefined') return () => undefined + const w = window as unknown as WindowHostBridge + const eventsApi = w.ztools?.events + if (!eventsApi || typeof eventsApi.on !== 'function') return () => undefined + + try { + void eventsApi.subscribe?.('tool_runtime_progress') + } catch (err) { + // 某些测试桩或旧渲染层可能未提供 subscribe,继续注册 on 监听 + void err + } + + const listener = (raw: unknown) => { + const outer = asRecord(raw) + if (!outer) return + const inner = asRecord(outer.payload) ?? outer + if (typeof inner.taskId !== 'string' || typeof inner.phase !== 'string') return + handler(inner as unknown as ToolProgressEvent) + } + + const off = eventsApi.on('tool_runtime_progress', listener) + return () => { + if (typeof off === 'function') { + off() + } else if (typeof eventsApi.off === 'function') { + eventsApi.off('tool_runtime_progress', listener) + } + } +} + +/** 订阅旧版宿主 plugin_files_dropped 拖拽回退事件并返回卸载函数 */ +export function subscribeLegacyFileDrop(onDrop: (envelope: unknown) => void): () => void { + if (typeof window === 'undefined') return () => undefined + const w = window as unknown as WindowHostBridge + const eventsApi = w.ztools?.events + if (!eventsApi || typeof eventsApi.on !== 'function') return () => undefined + + const off = eventsApi.on('plugin_files_dropped', onDrop) + return () => { + if (typeof off === 'function') { + off() + } else if (typeof eventsApi.off === 'function') { + eventsApi.off('plugin_files_dropped', onDrop) + } + } +} + +/** 字节数格式化 */ +export function formatBytes(bytes: number): string { + if (!Number.isFinite(bytes) || bytes < 0) return '0 B' + if (bytes < 1024) return `${Math.round(bytes)} B` + const units = ['KB', 'MB', 'GB', 'TB'] + let value = bytes / 1024 + let idx = 0 + while (value >= 1024 && idx < units.length - 1) { + value /= 1024 + idx += 1 + } + return `${value >= 100 ? value.toFixed(0) : value >= 10 ? value.toFixed(1) : value.toFixed(2)} ${units[idx]}` +} + +/** 字节数格式化别名(兼容 archive-manager 等插件既有导出名) */ +export function formatByteCount(bytes: number): string { + return formatBytes(bytes) +} + +/** 获取系统标准目录路径(支持 Windows 与 macOS) */ +export async function getRealSystemPath( + name: 'home' | 'desktop' | 'documents' | 'downloads' | 'music' | 'pictures' | 'videos' | 'temp', + hostOverride?: unknown +): Promise { + const res = await callHostTransport('system_get_path', { name }, hostOverride) + if (res.ok && res.data) { + if (typeof res.data === 'string' && res.data.trim()) return res.data.trim() + const rec = asRecord(res.data) + if (rec && typeof rec.path === 'string' && rec.path.trim()) return rec.path.trim() + } + return '' +} + +/** 读取剪贴板文本 */ +export async function readRealClipboardText(hostOverride?: unknown): Promise { + const res = await callHostTransport('clipboard_read_text', {}, hostOverride) + if (res.ok && res.data !== undefined && res.data !== null) { + if (typeof res.data === 'string') return res.data + const rec = asRecord(res.data) + if (rec && typeof rec.text === 'string') return rec.text + } + return '' +} + +/** 写入剪贴板文本 */ +export async function writeRealClipboardText(text: string, hostOverride?: unknown): Promise { + const res = await callHostTransport('clipboard_copy_text', { text: String(text || '') }, hostOverride) + return res.ok +} + +/** 在系统文件管理器中显示文件 */ +export async function showRealItemInFolder(fullPath: string, hostOverride?: unknown): Promise { + if (!fullPath) return false + const res = await callHostTransport('shell_show_item_in_folder', { fullPath }, hostOverride) + return res.ok +} + +/** 用系统默认应用打开文件或文件夹 */ +export async function openRealPath(fullPath: string, hostOverride?: unknown): Promise { + if (!fullPath) return false + const res = await callHostTransport('shell_open_path', { fullPath }, hostOverride) + return res.ok +} + +/** 将文件或目录移入系统回收站 */ +export async function trashRealItem(fullPath: string, hostOverride?: unknown): Promise<{ ok: boolean; error?: string }> { + if (!fullPath) return { ok: false, error: 'EMPTY_PATH' } + const res = await callHostTransport('shell_trash_item', { fullPath }, hostOverride) + return res.ok ? { ok: true } : { ok: false, error: res.error } +} + +/** 通过 window_show_open_dialog 选择输出目录(兼容 Windows 与 macOS) */ +export async function pickOutputDirectoryDialog( + options: { title: string; defaultPath?: string }, + hostOverride?: unknown +): Promise<{ canceled: boolean; directoryPath?: string; error?: string; errorCode?: string }> { + const params: Record = { + title: options.title, + properties: ['openDirectory', 'createDirectory'] + } + if (options.defaultPath) params.defaultPath = options.defaultPath + const res = await callHostTransport('window_show_open_dialog', params, hostOverride) + if (!res.ok) { + return { canceled: false, error: res.error || 'OPEN_DIALOG_FAILED', errorCode: res.errorCode } + } + const rec = asRecord(res.data) + if (!rec) return { canceled: false, error: 'INVALID_DIALOG_RESULT' } + if (rec.canceled === true) return { canceled: true } + const firstPath = + (Array.isArray(rec.filePaths) && typeof rec.filePaths[0] === 'string' && rec.filePaths[0].trim()) || + (typeof rec.filePath === 'string' && rec.filePath.trim()) || + (typeof rec.folderPath === 'string' && rec.folderPath.trim()) || + '' + if (!firstPath) return { canceled: false, error: 'NO_DIRECTORY_SELECTED' } + return { canceled: false, directoryPath: firstPath } +} + +/** 通用文件/目录选择对话框(支持自定义 properties 与 filters) */ +export async function openDialogSelectPaths( + options: { + title: string + properties: Array<'openFile' | 'openDirectory' | 'multiSelections' | 'createDirectory'> + filters?: Array<{ name: string; extensions: string[] }> + }, + hostOverride?: unknown +): Promise<{ canceled: boolean; paths: string[]; error?: string }> { + const params: Record = { + title: options.title, + properties: options.properties, + ...(options.filters ? { filters: options.filters } : {}) + } + const res = await callHostTransport('window_show_open_dialog', params, hostOverride) + if (!res.ok) return { canceled: false, paths: [], error: res.error || 'OPEN_DIALOG_FAILED' } + const rec = asRecord(res.data) + if (!rec) return { canceled: false, paths: [], error: 'INVALID_DIALOG_RESPONSE' } + if (rec.canceled === true) return { canceled: true, paths: [] } + const paths = Array.isArray(rec.filePaths) + ? rec.filePaths.filter((p): p is string => typeof p === 'string' && p.trim().length > 0).map((p) => p.trim()) + : typeof rec.filePath === 'string' && rec.filePath.trim() + ? [rec.filePath.trim()] + : [] + return { canceled: false, paths } +} + +/** 选择待归档的源文件或目录列表(多选) */ +export async function pickAnySourcesDialog( + options: { title: string; directories?: boolean }, + hostOverride?: unknown +): Promise<{ canceled: boolean; paths: string[]; error?: string }> { + return openDialogSelectPaths( + { + title: options.title, + properties: options.directories ? ['openDirectory', 'multiSelections'] : ['openFile', 'multiSelections'] + }, + hostOverride + ) +} + +/** 保存归档文件对话框(zip / 7z / tar) */ +export async function pickSaveArchiveDialog( + options: { title: string; defaultPath?: string; format: 'zip' | '7z' | 'tar' }, + hostOverride?: unknown +): Promise<{ canceled: boolean; filePath?: string; error?: string }> { + const ext = options.format === '7z' ? '7z' : options.format === 'tar' ? 'tar' : 'zip' + const params: Record = { + title: options.title, + filters: [{ name: `${ext.toUpperCase()} Archive`, extensions: [ext] }] + } + if (options.defaultPath) params.defaultPath = options.defaultPath + const res = await callHostTransport('window_show_save_dialog', params, hostOverride) + if (!res.ok) return { canceled: false, error: res.error || 'SAVE_DIALOG_FAILED' } + const rec = asRecord(res.data) + if (!rec) return { canceled: false, error: 'INVALID_SAVE_DIALOG' } + if (rec.canceled === true) return { canceled: true } + const filePath = typeof rec.filePath === 'string' ? rec.filePath.trim() : '' + if (!filePath) return { canceled: true } + return { canceled: false, filePath } +} diff --git a/extensions/archive-manager/tests/archive-manager.host.test.mjs b/extensions/archive-manager/tests/archive-manager.host.test.mjs index 016932d9..ed83f29f 100644 --- a/extensions/archive-manager/tests/archive-manager.host.test.mjs +++ b/extensions/archive-manager/tests/archive-manager.host.test.mjs @@ -1,210 +1,143 @@ import test from 'node:test' import assert from 'node:assert/strict' +import fs from 'node:fs' +import path from 'node:path' +import { fileURLToPath } from 'node:url' import { setRuntimeLocale } from '@ztools/declarative-ui' +import * as archive from '../dist/index.js' setRuntimeLocale('zh-CN') -const archiveManager = await import('../dist/index.js') - -async function withRealElectronWindow(handlers, fn) { - const prevWindow = globalThis.window - const calls = [] - const transportMethods = {} - - for (const [channel, impl] of Object.entries(handlers)) { - transportMethods[channel] = async (envelope) => { - const actualParams = - envelope && typeof envelope === 'object' && 'params' in envelope && 'messageId' in envelope - ? envelope.params - : envelope - calls.push({ channel, payload: actualParams }) - return impl(actualParams) - } - } - - globalThis.window = { - __ztoolsElectron: { - transport: { - methods: transportMethods - } - } - } - - try { - return await fn(calls) - } finally { - if (prevWindow === undefined) { - delete globalThis.window - } else { - globalThis.window = prevWindow - } +const pluginDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..') + +function makeCaps(with7z) { + const exts = with7z ? ['7z-family'] : [] + return { + contractVersion: 1, + platform: 'windows', + domains: ['archive'], + capabilities: [ + { primitiveId: 'archive.list', domain: 'archive', summary: 'list', ipcMethods: ['tool_archive_list'], requiredPermissions: ['fs'], status: 'ready', optionalExtensions: exts }, + { primitiveId: 'archive.extract', domain: 'archive', summary: 'extract', ipcMethods: ['tool_archive_extract'], requiredPermissions: ['fs'], status: 'ready', optionalExtensions: exts }, + { primitiveId: 'archive.create', domain: 'archive', summary: 'create', ipcMethods: ['tool_archive_create'], requiredPermissions: ['fs'], status: with7z ? 'ready' : 'needs_provisioning', optionalExtensions: exts } + ] } } -test('archive-manager host integration: 压缩包目录树透视、分类识别、按需提取与单根目录防套娃(已移除启动扫盘)', async () => { - assert.equal(typeof archiveManager.fetchRealArchiveCandidates, 'undefined', '不再导出启动扫描候选列表函数') - assert.deepEqual(archiveManager.ARCHIVE_IMPORT_RULES.extensions, ['.zip']) - assert.equal(archiveManager.formatBytes(null), '大小未识别') - assert.equal(archiveManager.formatBytes(undefined), '大小未识别') - - const candidate = archiveManager.toArchiveCandidateItem({ - path: 'D:\\ArchiveWorkspace\\downloads\\2026Q3_标书全套.zip', - name: '2026Q3_标书全套.zip', - parentDir: 'D:\\ArchiveWorkspace\\downloads', - extension: '.zip', - sizeBytes: null, - lastModifiedMs: null - }) - assert.equal(candidate.sizeBytes, null) - assert.equal(candidate.name, '2026Q3_标书全套.zip') - - await withRealElectronWindow( - { - dllplugin_call: ({ plugin, func, params }) => { - if (func === 'ListArchiveEntries') { - return { - ok: true, - plugin, - archivePath: params.archivePath, - archiveName: '2026Q3_标书全套.zip', - archiveSizeBytes: 10485760, - totalEntries: 2, - fileCount: 2, - totalUncompressedBytes: 16777216, - totalCompressedBytes: 10485760, - compressionRatio: 38, - encryptedCount: 0, - isEncrypted: false, - traversalRiskCount: 0, - hasSingleRootFolder: true, - singleRootFolderName: '2026Q3_标书', - entries: [ - { - entryName: '2026Q3_标书/商务报价明细.xlsx', - name: '商务报价明细.xlsx', - uncompressedSize: 12582912, - compressedSize: 8388608, - compressionRatio: 33, - crc32: 'A1B2C3D4', - isDirectory: false, - isEncrypted: false, - hasPathTraversalRisk: false - }, - { - entryName: '2026Q3_标书/架构图.png', - name: '架构图.png', - uncompressedSize: 4194304, - compressedSize: 2097152, - compressionRatio: 50, - crc32: 'E5F60718', - isDirectory: false, - isEncrypted: false, - hasPathTraversalRisk: false - } - ] - } - } - if (func === 'ExtractArchiveEntries') { - return { - ok: true, - targetDir: 'D:\\ArchiveWorkspace\\downloads\\2026Q3_标书', - extractedCount: Array.isArray(params.entryNames) ? params.entryNames.length : 2, - extractedFiles: ['D:\\ArchiveWorkspace\\downloads\\2026Q3_标书\\商务报价明细.xlsx'], - blockedEntries: [] - } +function makeArchiveHost() { + const calls = [] + const host = { + tool_archive_list: async (params) => { + calls.push({ method: 'tool_archive_list', params }) + return { + success: true, + data: { + format: 'zip', + encrypted: false, + totalEntries: 2, + totalUncompressedBytes: 3000, + entries: [ + { path: 'docs/readme.md', sizeBytes: 1000, compressedBytes: 400, isDirectory: false, encrypted: false }, + { path: '../evil.txt', sizeBytes: 2000, compressedBytes: 800, isDirectory: false, encrypted: false } + ] } - return { ok: true } } }, - async () => { - const inspected = await archiveManager.inspectArchiveEntries(candidate.path) - assert.equal(inspected.ok, true) - assert.equal(inspected.fileCount, 2) - assert.equal(inspected.entries[0].category, '办公文档') - assert.equal(inspected.entries[1].category, '图片与媒体') - - const extracted = await archiveManager.extractArchiveEntries(candidate.path, { - entryNames: ['2026Q3_标书/商务报价明细.xlsx'] - }) - assert.equal(extracted.ok, true) - assert.equal(extracted.extractedCount, 1) + tool_archive_extract: async (params) => { + calls.push({ method: 'tool_archive_extract', params }) + return { + success: true, + data: { taskId: params.taskId, extractedCount: 1, totalBytes: 1000, outputDir: params.outputDir.path } + } + }, + tool_archive_create: async (params) => { + calls.push({ method: 'tool_archive_create', params }) + return { + success: true, + data: { taskId: params.taskId, outputBytes: 2450, entryCount: params.inputs.length, format: params.format } + } + }, + tool_runtime_ensure: async (params) => { + calls.push({ method: 'tool_runtime_ensure', params }) + return { success: true, data: { primitiveId: params.primitiveId, status: 'ready', provisioned: true } } + }, + tool_task_cancel: async (params) => { + calls.push({ method: 'tool_task_cancel', params }) + return { success: true, data: { taskId: params.taskId, cancelled: true } } } - ) -}) - -test('archive-manager beyond happy path: Zip Slip 恶意路径穿越拦截、损坏归档、加密流拦截与空路径校验', async () => { - // 1. Zip Slip 恶意路径预检识别 - assert.equal(archiveManager.isUnsafeEntryPath('../../Windows/System32/cmd.exe'), true) - assert.equal(archiveManager.isUnsafeEntryPath('..\\..\\evil.dll'), true) - assert.equal(archiveManager.isUnsafeEntryPath('/etc/passwd'), true) - assert.equal(archiveManager.isUnsafeEntryPath('C:\\Windows\\win.ini'), true) - assert.equal(archiveManager.isUnsafeEntryPath('docs/2026/report.pdf'), false) - - // 2. 提取包含 Zip Slip 条目时直接拦截,不向底层发送写盘指令 - const blockedRes = await archiveManager.extractArchiveEntries('D:\\test.zip', { - entryNames: ['../../Windows/System32/evil.dll'] - }) - assert.equal(blockedRes.ok, false) - assert.match(String(blockedRes.error), /ZIP_SLIP_BLOCKED/) - assert.equal(blockedRes.blockedEntries.length, 1) + } + return { host, calls } +} - // 3. 空压缩包路径报错 - const emptyInspect = await archiveManager.inspectArchiveEntries(' ') - assert.equal(emptyInspect.ok, false) - assert.match(String(emptyInspect.error), /不能为空/) +test('archive-manager: 清单与源码彻底去 DLL 化,声明 archive.* 原语且一期仅 Windows', () => { + const manifest = JSON.parse(fs.readFileSync(path.join(pluginDir, 'plugin.json'), 'utf8')) + assert.deepEqual(manifest.requiredCapabilities, ['archive.list', 'archive.extract', 'archive.create']) + assert.equal(manifest.minAppVersion, '1.3.0.4') + assert.deepEqual(manifest.nativeComponents, []) + assert.deepEqual(manifest.targets.map((t) => t.id), ['windows-electron-any']) + assert.ok(manifest.permissions.includes('fs')) + assert.ok(manifest.permissions.includes('dialog')) + const logicSrc = fs.readFileSync(path.join(pluginDir, 'src/logic.ts'), 'utf8') + assert.equal(logicSrc.includes('dllplugin_call'), false) + assert.equal(logicSrc.includes('ArchiveManagerPlugin'), false) +}) - // 4. 目标目录指向受保护系统路径时抛错拦截 - await assert.rejects( - () => - archiveManager.invokeNativeCapability('ExtractArchiveEntries', { - archivePath: 'D:\\a.zip', - targetDir: 'C:\\Windows\\System32\\drivers' - }), - /SECURITY_INTERCEPTED/ +test('archive-manager: 列表、路径穿越拦截、解压与全新压缩打包工作流', async () => { + const { host, calls } = makeArchiveHost() + + const inspected = await archive.inspectArchiveEntries('D:\\Work\\bundle.zip', {}, host) + assert.equal(inspected.ok, true) + assert.equal(inspected.traversalRiskCount, 1) + assert.equal(inspected.entries[1].hasPathTraversalRisk, true) + + // 越界条目解压必须直接拦截,绝不发给宿主 + const blockedExtract = await archive.extractArchiveEntries('D:\\Work\\bundle.zip', { entries: ['../evil.txt'] }, host) + assert.equal(blockedExtract.ok, false) + assert.deepEqual(blockedExtract.blockedEntries, ['../evil.txt']) + assert.equal(calls.some((c) => c.method === 'tool_archive_extract'), false) + + // 正常勾选条目解压 + const okExtract = await archive.extractArchiveEntries( + 'D:\\Work\\bundle.zip', + { entries: ['docs/readme.md'], outputDir: 'D:\\Work\\out', password: 'secret' }, + host ) - - // 5. 宿主返回加密归档或损坏归档报错时如实向上传递 - await withRealElectronWindow( - { - dllplugin_call: () => ({ - ok: false, - error: 'ENCRYPTED_ARCHIVE: 该压缩包包含加密条目,当前暂不支持无密码提取' - }) - }, - async () => { - const encRes = await archiveManager.extractArchiveEntries('D:\\encrypted.zip') - assert.equal(encRes.ok, false) - assert.match(String(encRes.error), /ENCRYPTED_ARCHIVE/) - } + assert.equal(okExtract.ok, true) + assert.equal(okExtract.extractedCount, 1) + + // 全新压缩打包工作流(含 compressionLevel、7z 与密码) + const created = await archive.createArchivePackage( + ['D:\\Work\\a.txt', 'D:\\Work\\dir'], + { outputPath: 'D:\\Work\\pack.7z', format: '7z', compressionLevel: 9, password: 'pw', capabilities: makeCaps(true) }, + host ) + assert.equal(created.ok, true) + assert.equal(created.outputBytes, 2450) + const createCall = calls.find((c) => c.method === 'tool_archive_create') + assert.equal(createCall.params.format, '7z') + assert.equal(createCall.params.compressionLevel, 9) + assert.equal(createCall.params.password, 'pw') }) -test('解压落点与提示文字:与客户端规则一致,校验与解压结果按实际返回描述', () => { - const meta = { hasSingleRootFolder: true, singleRootFolderName: 'proj' } - assert.equal(archiveManager.describeExtractTarget('D:\\Downloads\\proj-v1.zip', meta, false), 'D:\\Downloads\\proj') - assert.equal(archiveManager.describeExtractTarget('D:\\Downloads\\proj-v1.zip', meta, true), 'D:\\Downloads\\proj-v1') - assert.equal( - archiveManager.describeExtractTarget('D:\\Downloads\\a.tar.zip', { hasSingleRootFolder: false, singleRootFolderName: null }, false), - 'D:\\Downloads\\a.tar' - ) - assert.equal(archiveManager.parentDirOf('D:\\Downloads\\x.zip'), 'D:\\Downloads') +test('archive-manager: 无 7z-family 特性时降级隐藏 7z/加密选项,并支持按需准备 7zz 与取消任务', async () => { + const { host, calls } = makeArchiveHost() + const zipOnlyCaps = makeCaps(false) + + assert.equal(archive.has7zFamilyExtension(zipOnlyCaps), false) + assert.deepEqual(archive.getAvailableCreateFormats(zipOnlyCaps).map((f) => f.value), ['zip']) + assert.deepEqual(archive.getSupportedArchiveExtensions(zipOnlyCaps), ['.zip']) + + // 无 7z-family 时拒绝创建 7z 与加密归档 + const blocked7z = await archive.createArchivePackage(['D:\\Work\\a.txt'], { format: '7z', capabilities: zipOnlyCaps }, host) + assert.equal(blocked7z.ok, false) + const blockedPwd = await archive.createArchivePackage(['D:\\Work\\a.txt'], { format: 'zip', password: '123', capabilities: zipOnlyCaps }, host) + assert.equal(blockedPwd.ok, false) - const sha = 'c'.repeat(64) - assert.equal(archiveManager.summarizeVerifyResult({ sha256: sha, fileCount: 3, traversalRiskCount: 0, isEncrypted: true }).ok, true) - assert.match(archiveManager.summarizeVerifyResult({ sha256: sha, fileCount: 3, isEncrypted: true }).message, /含加密条目,暂不支持解压/) - assert.equal(archiveManager.summarizeVerifyResult({ sha256: 'short' }).ok, false) - assert.equal(archiveManager.summarizeVerifyResult(null).title, '校验结果无法识别') - assert.equal(archiveManager.summarizeVerifyResult({ sha256: sha, traversalRiskCount: 2 }).title, '发现 2 个越界条目') + // 按需准备与取消任务 + const ensured = await archive.ensureArchiveExtensionEngine(host) + assert.equal(ensured.ok, true) + assert.equal(calls.filter((c) => c.method === 'tool_runtime_ensure').length, 3) - assert.deepEqual(archiveManager.summarizeExtractResult({ ok: false, extractedCount: 0, blockedEntries: [], error: 'ENCRYPTED_ARCHIVE' }), { - ok: false, - title: '解压失败', - message: '客户端没有说明原因' - }) - assert.deepEqual(archiveManager.summarizeExtractResult({ ok: false, extractedCount: 0, blockedEntries: [], error: '压缩包包含加密条目' }), { - ok: false, - title: '解压失败', - message: '压缩包包含加密条目' - }) - assert.equal(archiveManager.summarizeExtractResult({ ok: true, extractedCount: 0, blockedEntries: ['../x'] }).message, '1 个越界条目被拒绝') - assert.equal(archiveManager.summarizeExtractResult({ ok: true, extractedCount: 4, blockedEntries: [], targetDir: 'D:\\out' }).title, '已解压 4 个文件') + const cancelled = await archive.cancelActiveArchiveTask('arc_task_7', host) + assert.equal(cancelled.ok, true) + assert.equal(cancelled.cancelled, true) }) diff --git a/extensions/archive-manager/tests/archive-manager.ui.test.mjs b/extensions/archive-manager/tests/archive-manager.ui.test.mjs index f80d593f..a675c138 100644 --- a/extensions/archive-manager/tests/archive-manager.ui.test.mjs +++ b/extensions/archive-manager/tests/archive-manager.ui.test.mjs @@ -1,644 +1,36 @@ import test from 'node:test' import assert from 'node:assert/strict' -import fs from 'node:fs' -import os from 'node:os' -import path from 'node:path' -import { Toast } from '@ztools/declarative-ui' -import { createHost, installDirectoryHost, mount, tick } from '../../shared/test-harness.mjs' +import { setRuntimeLocale } from '@ztools/declarative-ui' +import { createHost, mount, tick } from '../../shared/test-harness.mjs' import ArchiveManagerCommand from '../dist/index.js' +setRuntimeLocale('zh-CN') const host = createHost() -const ARCHIVE = 'D:\\TestArchives\\downloads\\bid_package.zip' -const ARCHIVE_B = 'D:\\TestArchives\\downloads\\extra_bundle.zip' -const SHA = 'ab'.repeat(32) - -function entry(entryName, extra = {}) { - return { - entryName, - name: entryName.split('/').pop(), - uncompressedSize: 6291456, - compressedSize: 4194304, - compressionRatio: 33, - crc32: '11223344', - isDirectory: false, - isEncrypted: false, - hasPathTraversalRisk: false, - ...extra - } -} - -/** - * 模拟真实宿主文件能力与 ArchiveManagerPlugin 原生调用 - */ -function installArchiveHost({ listing = {}, listError = null, extract = null, verify = null, sizes = {} } = {}) { - const calls = { extract: [], verify: 0, trash: [], inspect: [] } - host.ipc.filesystem_directory_exists = async () => ({ success: true, exists: false }) - host.ipc.filesystem_get_file_size = async ({ path: filePath }) => { - if (filePath in sizes) return { success: true, size: sizes[filePath] } - return { success: true, size: 5242880 } - } - host.ipc.dllplugin_call = async ({ func, params }) => { - if (func === 'ListArchiveEntries') { - calls.inspect.push(params.archivePath) - if (typeof listError === 'function') { - const err = listError(params.archivePath) - if (err) return { ok: false, error: err } - } else if (listError) { - return { ok: false, error: listError } - } - const extraListing = typeof listing === 'function' ? listing(params.archivePath) : listing - const fileName = String(params.archivePath || '').split(/[\\/]/).pop() || 'bid_package.zip' - return { - ok: true, - archivePath: params.archivePath, - archiveName: fileName, - archiveSizeBytes: 5242880, - totalEntries: 2, - fileCount: 2, - totalUncompressedBytes: 8388608, - totalCompressedBytes: 5242880, - compressionRatio: 37, - encryptedCount: 0, - isEncrypted: false, - traversalRiskCount: 1, - hasSingleRootFolder: false, - singleRootFolderName: null, - entries: [ - entry('标书正本.pdf', { category: '办公文档' }), - entry('../../evil_autorun.exe', { name: 'evil_autorun.exe', category: '可执行程序', uncompressedSize: 2097152, hasPathTraversalRisk: true }) - ], - ...extraListing - } - } - if (func === 'ExtractArchiveEntries') { - calls.extract.push(params) - if (extract) return extract(params) - return { - ok: true, - targetDir: 'D:\\TestArchives\\downloads\\bid_package', - extractedCount: Array.isArray(params.entryNames) ? params.entryNames.length : 1, - extractedFiles: ['D:\\TestArchives\\downloads\\bid_package\\标书正本.pdf'], - blockedEntries: Array.isArray(params.entryNames) ? [] : ['../../evil_autorun.exe'] - } - } - if (func === 'VerifyArchive') { - calls.verify++ - if (verify) return verify(params) - return { ok: true, sha256: SHA, totalEntries: 2, fileCount: 2, traversalRiskCount: 0, isEncrypted: false, verified: true } - } - return { ok: false, error: `未模拟 ${func}` } - } - host.ipc.shell_trash_item = async ({ fullPath }) => { - calls.trash.push(fullPath) - return { success: true } - } - return calls -} - -function makeTempTree(spec) { - const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ztools-archive-test-')) - for (const [rel, content] of Object.entries(spec)) { - const full = path.join(root, rel) - fs.mkdirSync(path.dirname(full), { recursive: true }) - fs.writeFileSync(full, content) - } - return root -} - -async function importArchiveViaPaste(view, paths = [ARCHIVE]) { - await view.pasteFiles(paths, { directories: [] }) - await tick(15) -} - -const pdfItem = (view) => view.item((it) => it.props.title === '标书正本.pdf') -const dropdownItems = (tree) => { - const dd = tree.props.searchBarAccessory - return dd?.children ?? dd?.props?.children ?? [] -} test.beforeEach(() => { host.reset() - delete globalThis.__ztoolsLaunchContext }) -test('启动零扫盘:初始为空状态、顶栏恰为 2 个按钮且无扫盘/读包 IPC 调用', async () => { - installArchiveHost() - const view = await mount(ArchiveManagerCommand, host) - await tick(10) - - const forbiddenMethods = new Set([ - 'system_get_path', - 'system_list_common_folders', - 'system_search_files', - 'filesystem_get_directory_contents', - 'dllplugin_call' - ]) - assert.equal( - host.ipcCalls.some(([method]) => forbiddenMethods.has(method)), - false, - `挂载时不应调用扫描或读包 IPC,实际调用:${JSON.stringify(host.ipcCalls)}` - ) - - const tree = view.tree() - assert.equal(dropdownItems(tree).length, 0) - assert.equal(tree.props.subList.items.length, 0) - assert.match(tree.props.filterBar.props.summaryText, /尚未添加压缩包/) - assert.match(tree.props.subList.emptyText, /尚未添加 ZIP 压缩包/) - - const barActions = tree.props.filterBar.props.actions - assert.deepEqual( - barActions.map((a) => ({ id: a.id, label: a.label })), - [ - { id: 'pick-files', label: '选择文件' }, - { id: 'pick-folder', label: '选择文件夹' } - ] - ) - - const rootActions = view.actions() - assert.equal(rootActions[0].props.title, '选择文件…') - assert.deepEqual(rootActions[0].props.shortcut, { modifiers: ['ctrl'], key: 'o' }) - assert.equal(rootActions[1].props.title, '选择文件夹…') - assert.deepEqual(rootActions[1].props.shortcut, { modifiers: ['ctrl', 'shift'], key: 'o' }) - view.unmount() -}) - -test('选择文件:取消不改变列表、宿主报错如实提示、多选导入自动选中第 1 个且再次导入不切换当前包', async () => { - const calls = installArchiveHost() - const view = await mount(ArchiveManagerCommand, host) - await tick(10) - - const pickFilesBtn = () => view.tree().props.filterBar.props.actions.find((a) => a.id === 'pick-files') - - // 1. 取消选择 - host.ipc.window_show_open_dialog = async () => ({ canceled: true }) - await pickFilesBtn().onAction() - await tick(10) - assert.equal(dropdownItems(view.tree()).length, 0) - assert.equal(host.toasts.length, 0) - - // 2. 宿主报 capability 超限错误时翻译为友好提示 - host.ipc.window_show_open_dialog = async () => { - throw new Error('当前窗口的文件 capability 数量超过上限') - } - await pickFilesBtn().onAction() - await tick(10) - assert.equal(host.lastToast().style, Toast.Style.Failure) - assert.match(host.lastToast().message, /改用「选择文件夹」/) - - // 3. 选择多个 ZIP + 1 个不支持文件:过滤不支持格式,只导入第 1 个前无选中包时自动选中并预览第 1 个 - host.ipc.window_show_open_dialog = async (params) => { - assert.equal(params.filters, 'ZIP 压缩包|zip') - assert.deepEqual(params.properties, ['openFile', 'multiSelections']) - return { - canceled: false, - filePaths: [{ path: ARCHIVE }, { path: ARCHIVE_B }, { path: 'D:\\TestArchives\\downloads\\notes.txt' }] +test('archive-manager UI: 挂载后探测能力,无 7z-family 时隐藏密码输入框,零 dllplugin_call', async () => { + host.ipc.tool_runtime_capabilities = () => ({ + success: true, + data: { + contractVersion: 1, + platform: 'windows', + domains: ['archive'], + capabilities: [ + { primitiveId: 'archive.create', domain: 'archive', summary: 'create', ipcMethods: ['tool_archive_create'], requiredPermissions: ['fs'], status: 'needs_provisioning', optionalExtensions: [] } + ] } - } - await pickFilesBtn().onAction() - await tick(15) - assert.equal(view.tree().props.searchBarAccessory.props.value, ARCHIVE) - assert.deepEqual( - dropdownItems(view.tree()).map((i) => i.props.value), - [ARCHIVE, ARCHIVE_B] - ) - assert.equal(calls.inspect.length, 1) - assert.equal(calls.inspect[0], ARCHIVE) - assert.equal(host.lastToast().title, '已添加 2 个文件') - - // 4. 已有选中压缩包时再导入新包,只追加候选、不切走当前包 - const ARCHIVE_C = 'D:\\TestArchives\\downloads\\third.zip' - host.ipc.window_show_open_dialog = async () => ({ canceled: false, filePaths: [ARCHIVE_C] }) - await pickFilesBtn().onAction() - await tick(15) - assert.equal(view.tree().props.searchBarAccessory.props.value, ARCHIVE) - assert.deepEqual( - dropdownItems(view.tree()).map((i) => i.props.value), - [ARCHIVE, ARCHIVE_B, ARCHIVE_C] - ) - assert.equal(calls.inspect.length, 1, '已有当前压缩包时新增导入不应切换当前包') - - view.unmount() -}) - -test('选择文件夹:递归收集 .zip、过滤非 ZIP 与空文件、整盘确认与数量截断提示', async () => { - const root = makeTempTree({ - 'a.zip': 'zip-a', - 'sub/deep/b.ZIP': 'zip-b', - 'sub/readme.txt': 'text', - 'empty.zip': '', - 'archive.rar': 'rar' }) + const view = await mount(ArchiveManagerCommand) try { - installArchiveHost() - await installDirectoryHost(host, { authorized: [root] }) - const view = await mount(ArchiveManagerCommand, host) await tick(10) - - const pickFolderBtn = () => view.tree().props.filterBar.props.actions.find((a) => a.id === 'pick-folder') - - // 1. 选整盘根目录时先弹确认框,取消则不读目录 - host.ipc.window_show_select_folder_dialog = async () => ({ canceled: false, folderPath: 'D:\\' }) - host.setConfirm(false) - await pickFolderBtn().onAction() - await tick(10) - assert.match(host.confirms.at(-1).title, /整个磁盘/) - assert.equal(host.ipcCalls.some(([m]) => m === 'filesystem_get_directory_contents'), false) - - // 2. 选择普通目录:递归收集 .zip 并自动打开第 1 个 - host.setConfirm(true) - host.ipc.window_show_select_folder_dialog = async () => ({ canceled: false, folderPath: root }) - await pickFolderBtn().onAction() - await tick(20) - - const values = dropdownItems(view.tree()).map((i) => i.props.value) - assert.deepEqual(values, [path.join(root, 'a.zip'), path.join(root, 'sub', 'deep', 'b.ZIP')]) - assert.equal(view.tree().props.searchBarAccessory.props.value, path.join(root, 'a.zip')) - assert.equal(host.lastToast().title, '已添加 2 个文件') - assert.match(host.lastToast().message, /忽略 3 个不支持的文件/) - view.unmount() - } finally { - fs.rmSync(root, { recursive: true, force: true }) - } - - // 3. 超过 500 个 .zip 时触发截断提示 - const bigSpec = {} - for (let i = 0; i < 502; i++) { - bigSpec[`item_${String(i).padStart(3, '0')}.zip`] = 'x' - } - const bigRoot = makeTempTree(bigSpec) - try { - host.reset() - installArchiveHost() - await installDirectoryHost(host, { authorized: [bigRoot] }) - host.ipc.window_show_select_folder_dialog = async () => ({ canceled: false, folderPath: bigRoot }) - const view = await mount(ArchiveManagerCommand, host) - await tick(10) - await view.tree().props.filterBar.props.actions.find((a) => a.id === 'pick-folder').onAction() - await tick(30) - assert.equal(dropdownItems(view.tree()).length, 500) - assert.equal(host.lastToast().title, '已添加 500 个文件') - assert.match(host.lastToast().message, /文件较多,只导入了一部分/) - view.unmount() + const fields = view.tree()?.props?.workbenchPanel?.fields || [] + assert.ok(Array.isArray(fields) && fields.length > 0) + assert.equal(fields.some((f) => f.id === 'arc-password'), false) + assert.equal(host.ipcCalls.some(([m]) => m === 'dllplugin_call'), false) } finally { - fs.rmSync(bigRoot, { recursive: true, force: true }) - } -}) - -test('拖入文件夹与旧版客户端兼容:支持带 directories、不带 directories 以及 plugin_files_dropped 展开文件夹', async () => { - const root = makeTempTree({ - 'v1.0_release/app.zip': 'zip1', - 'nested/pack.zip': 'zip2', - 'nested/ignore.7z': '7z' - }) - try { - installArchiveHost() - await installDirectoryHost(host, { authorized: [root] }) - host.ipc.filesystem_directory_exists = async ({ path: target }) => ({ - success: true, - exists: fs.existsSync(target) && fs.statSync(target).isDirectory() - }) - - // 1. 新版宿主带 directories 拖入文件夹(无需调 directory_exists) - const view = await mount(ArchiveManagerCommand, host) - await tick(10) - await view.dropFiles([root], { directories: [root] }) - await tick(20) - assert.equal(host.ipcCalls.some(([m]) => m === 'filesystem_directory_exists'), false) - assert.deepEqual( - dropdownItems(view.tree()).map((i) => i.props.value), - [path.join(root, 'nested', 'pack.zip'), path.join(root, 'v1.0_release', 'app.zip')] - ) - - // 2. 重复拖入大小写不同的相同文件(按路径去重,不重复添加) - // Windows 路径不区分大小写,换成大写仍算同一个文件;macOS / Linux 区分大小写,用原路径验证去重 - const dupZip = path.join(root, 'nested', 'pack.zip') - await view.dropFiles([process.platform === 'win32' ? dupZip.toUpperCase() : dupZip], { directories: [] }) - await tick(15) - assert.equal(host.lastToast().title, '这些文件已在列表中') - assert.equal(dropdownItems(view.tree()).length, 2) view.unmount() - - // 3. 旧版客户端不带 directories,通过 plugin_files_dropped 拖入文件夹也能展开 - host.reset() - installArchiveHost() - await installDirectoryHost(host, { authorized: [root] }) - host.ipc.filesystem_directory_exists = async ({ path: target }) => ({ - success: true, - exists: fs.existsSync(target) && fs.statSync(target).isDirectory() - }) - let droppedListener = null - globalThis.window.__ztoolsDeclarativeFeatures = { fileInput: false } - globalThis.window.ztools = { - ...(globalThis.window.ztools || {}), - events: { - on(event, cb) { - if (event === 'plugin_files_dropped') droppedListener = cb - return () => { - if (droppedListener === cb) droppedListener = null - } - } - } - } - const legacyView = await mount(ArchiveManagerCommand, host) - await tick(10) - assert.equal(typeof droppedListener, 'function') - droppedListener({ payload: { files: [root] } }) - await tick(25) - assert.equal(host.ipcCalls.some(([m]) => m === 'filesystem_directory_exists'), true) - assert.equal(dropdownItems(legacyView.tree()).length, 2) - legacyView.unmount() - globalThis.window.__ztoolsDeclarativeFeatures = { fileInput: true } - assert.equal(droppedListener, null) - } finally { - fs.rmSync(root, { recursive: true, force: true }) - } -}) - -test('从列表移除与清空列表:不删磁盘文件,移除自动切到下一个;清空重置空态;解压中清空被拒绝', async () => { - const calls = installArchiveHost() - const view = await mount(ArchiveManagerCommand, host) - await tick(10) - - await importArchiveViaPaste(view, [ARCHIVE, ARCHIVE_B]) - assert.equal(view.tree().props.searchBarAccessory.props.value, ARCHIVE) - assert.equal(dropdownItems(view.tree()).length, 2) - assert.match(view.tree().props.filterBar.props.summaryText, /清空列表 Ctrl\+Shift\+Backspace/) - - // 1. 从列表移除第 1 个压缩包:不删除磁盘文件,自动切到第 2 个 - await view.run(pdfItem(view), '从列表移除') - await tick(15) - assert.equal(calls.trash.length, 0, '从列表移除不得删除磁盘文件') - assert.equal(view.tree().props.searchBarAccessory.props.value, ARCHIVE_B) - assert.deepEqual(dropdownItems(view.tree()).map((i) => i.props.value), [ARCHIVE_B]) - - // 2. 解压进行中时清空列表被拒绝,不清空也不丢进度 - let releaseExtract - const gate = new Promise((resolve) => (releaseExtract = resolve)) - installArchiveHost({ - extract: async () => { - await gate - return { ok: true, targetDir: 'D:\\out', extractedCount: 1, extractedFiles: ['D:\\out\\a.pdf'], blockedEntries: [] } - } - }) - host.setConfirm(true) - const extractAction = view.actions(pdfItem(view)).find((a) => a.props.title === '解压全部') - const extractPromise = extractAction.props.onAction() - await tick(10) - const clearAction = view.actions(pdfItem(view)).find((a) => a.props.title === '清空列表') - assert.equal(clearAction.props.style, 'destructive') - await clearAction.props.onAction() - await tick(5) - assert.equal(host.lastToast().title, '正在处理,完成后再清空') - assert.equal(dropdownItems(view.tree()).length, 1) - releaseExtract() - await extractPromise - await tick(10) - - // 3. 非处理中点清空列表:彻底回到空态 - await view.run(pdfItem(view), '清空列表') - await tick(10) - assert.equal(dropdownItems(view.tree()).length, 0) - assert.equal(view.tree().props.subList.items.length, 0) - assert.match(view.tree().props.filterBar.props.summaryText, /尚未添加压缩包/) - assert.equal(calls.trash.length, 0) - - // 4. 仅剩 1 个时「从列表移除」回到空态 - await importArchiveViaPaste(view, [ARCHIVE]) - assert.equal(dropdownItems(view.tree()).length, 1) - await view.run(pdfItem(view), '从列表移除') - await tick(10) - assert.equal(dropdownItems(view.tree()).length, 0) - assert.equal(view.tree().props.subList.items.length, 0) - - view.unmount() -}) - -test('[竞态] 导入文件夹进行中清空列表,异步返回结果被丢弃且不弹导入提示', async () => { - installArchiveHost() - let releaseSlow - const slowGate = new Promise((resolve) => (releaseSlow = resolve)) - const view2 = await mount(ArchiveManagerCommand, host) - await importArchiveViaPaste(view2, [ARCHIVE]) - const toastCountBefore = host.toasts.length - - host.ipc.window_show_select_folder_dialog = async () => ({ canceled: false, folderPath: 'D:\\SlowFolder' }) - host.ipc.filesystem_get_directory_contents = async () => { - await slowGate - return { success: true, files: [{ name: 'ghost.zip', size: 2048, isDirectory: false }] } - } - const slowImport = view2.tree().props.filterBar.props.actions.find((a) => a.id === 'pick-folder').onAction() - await tick(10) - assert.match(view2.tree().props.filterBar.props.summaryText, /正在导入:/) - - await view2.run(pdfItem(view2), '清空列表') - await tick(5) - assert.equal(dropdownItems(view2.tree()).length, 0) - - releaseSlow() - await slowImport - await tick(15) - assert.equal(dropdownItems(view2.tree()).length, 0, '清空后过期导入的结果必须丢弃') - assert.equal(host.toasts.length, toastCountBefore, '过期导入不应弹出提示') - view2.unmount() -}) - -test('布局二:左侧分类 + 右侧包内文件,越界条目标红且不可勾选;没有示例数据', async () => { - installArchiveHost() - const view = await mount(ArchiveManagerCommand, host) - await importArchiveViaPaste(view, [ARCHIVE]) - - const tree = view.tree() - assert.equal(tree.type, 'List') - assert.equal(tree.props.isShowingDetail, false) - assert.ok(tree.props.subList) - assert.equal(/[\u{1F300}-\u{1FAFF}]/u.test(view.text()), false) - assert.equal(view.text().includes('华东区'), false, '不再出现内置的示例压缩包') - - const evil = view.item((it) => it.props.title === 'evil_autorun.exe') - assert.equal(evil.props.checkable, false) - assert.ok(view.text().includes('越界路径,不提取')) - assert.match(view.item('diag-security').props.subtitle, /1 个条目含 \.\.\/ 或绝对路径,不会被提取/) - view.unmount() -}) - -test('勾选后提取:先确认目标文件夹并提示会覆盖同名文件,确认后才调用;取消则不解压', async () => { - const calls = installArchiveHost() - const view = await mount(ArchiveManagerCommand, host) - await importArchiveViaPaste(view, [ARCHIVE]) - - assert.equal(view.actions(pdfItem(view))[0].props.title, '解压全部') - pdfItem(view).props.onCheckChange(true) - await tick(5) - assert.equal(view.actions(pdfItem(view))[0].props.title, '提取已勾选的 1 个文件') - - host.setConfirm(false) - await view.run(pdfItem(view), '提取已勾选的 1 个文件') - assert.equal(calls.extract.length, 0, '取消确认不解压') - const confirm = host.confirms.at(-1) - assert.equal(confirm.title, '提取 1 个文件?') - assert.match(confirm.message, /解压到:D:\\TestArchives\\downloads\\bid_package/) - assert.match(confirm.message, /同名文件会被覆盖/) - - host.setConfirm(true) - await view.run(pdfItem(view), '提取已勾选的 1 个文件') - assert.equal(calls.extract.length, 1) - assert.deepEqual(calls.extract[0].entryNames, ['标书正本.pdf']) - assert.equal(calls.extract[0].smartUnwrap, false) - assert.equal(host.lastToast().title, '已解压 1 个文件') - view.unmount() -}) - -test('整包解压:单个顶层文件夹时确认框写明实际落点;越界条目未提取时如实写出', async () => { - const calls = installArchiveHost({ listing: { hasSingleRootFolder: true, singleRootFolderName: '标书', traversalRiskCount: 0 } }) - const view = await mount(ArchiveManagerCommand, host) - await importArchiveViaPaste(view, [ARCHIVE]) - await view.run(pdfItem(view), '解压全部') - assert.match(host.confirms.at(-1).message, /解压到:D:\\TestArchives\\downloads\\标书\n/) - assert.equal(calls.extract[0].smartUnwrap, true) - assert.equal(calls.extract[0].entryNames, undefined) - assert.equal(host.lastToast().title, '已解压 1 个文件 · 1 个越界条目未提取') - view.unmount() -}) - -test('[故障注入] 客户端报告解压 0 个文件或失败时提示失败,不用勾选数量冒充结果', async () => { - installArchiveHost({ extract: () => ({ ok: true, targetDir: 'D:\\x', extractedCount: 0, extractedFiles: [], blockedEntries: [] }) }) - const view = await mount(ArchiveManagerCommand, host) - await importArchiveViaPaste(view, [ARCHIVE]) - await view.run(pdfItem(view), '只提取这个文件(标书正本.pdf)') - assert.equal(host.lastToast().title, '没有解压出任何文件') - assert.equal(host.lastToast().style, Toast.Style.Failure) - view.unmount() - - host.reset() - installArchiveHost({ extract: () => ({ ok: false, error: 'EPERM: operation not permitted' }) }) - const view2 = await mount(ArchiveManagerCommand, host) - await importArchiveViaPaste(view2, [ARCHIVE]) - await view2.run(pdfItem(view2), '解压全部') - assert.equal(host.lastToast().title, '解压失败') - assert.match(host.lastToast().message, /解压提取失败/) - view2.unmount() -}) - -test('[边界] 含加密条目的压缩包:直接提示不支持解压,不弹确认、不调用解压', async () => { - const calls = installArchiveHost({ listing: { isEncrypted: true, encryptedCount: 1, traversalRiskCount: 0, entries: [entry('a.pdf', { isEncrypted: true })] } }) - const view = await mount(ArchiveManagerCommand, host) - await importArchiveViaPaste(view, [ARCHIVE]) - assert.match(view.item('diag-security').props.subtitle, /含加密条目,暂不支持解压/) - await view.run(view.item((it) => it.props.title === 'a.pdf'), '解压全部') - assert.equal(host.confirms.length, 0) - assert.equal(calls.extract.length, 0) - assert.equal(host.lastToast().title, '暂不支持解压加密的压缩包') - view.unmount() -}) - -test('校验保留在 ActionPanel 中:如实说明只读目录、查越界与算 SHA-256;故障时分别如实提示', async () => { - installArchiveHost() - const view = await mount(ArchiveManagerCommand, host) - await importArchiveViaPaste(view, [ARCHIVE]) - - await view.run(pdfItem(view), '校验压缩包(目录、越界路径与 SHA-256)') - const t = host.lastToast() - assert.equal(t.style, Toast.Style.Success) - assert.equal(t.title, '已读取压缩包目录,没有越界路径') - assert.match(t.message, /SHA-256:abababababababab…/) - assert.match(t.message, /未逐个校验文件 CRC32/) - assert.equal(host.toasts.some((x) => /CRC32 与安全校验通过/.test(x.title)), false) - view.unmount() - - const cases = [ - [() => ({ ok: true, sha256: SHA, fileCount: 2, traversalRiskCount: 3 }), '发现 3 个越界条目'], - [() => ({ ok: true, fileCount: 2, traversalRiskCount: 0 }), '校验结果无法识别'], - [() => ({ ok: false, error: '压缩包损坏或格式不受支持: invalid central directory' }), '校验失败'] - ] - for (const [verify, title] of cases) { - host.reset() - installArchiveHost({ verify }) - const v = await mount(ArchiveManagerCommand, host) - await importArchiveViaPaste(v, [ARCHIVE]) - await v.run(pdfItem(v), '校验压缩包(目录、越界路径与 SHA-256)') - assert.equal(host.lastToast().title, title) - assert.equal(host.lastToast().style, Toast.Style.Failure) - v.unmount() - } -}) - -test('[故障注入] 读取压缩包失败:清空包内列表,状态条与空状态写明原因,可通过动作移除/清空', async () => { - const calls = installArchiveHost({ listError: '压缩包损坏或格式不受支持: end of central directory record signature not found' }) - const view = await mount(ArchiveManagerCommand, host) - await importArchiveViaPaste(view, [ARCHIVE]) - - const tree = view.tree() - assert.equal(tree.props.subList.items.length, 0) - assert.match(tree.props.subList.emptyText, /读取压缩包失败:.*central directory/) - assert.match(tree.props.filterBar.props.summaryText, /读取失败/) - assert.equal(host.toasts.some((t) => t.title === '读取压缩包失败'), true) - - await view.run(view.item('nav-cat-ALL'), '解压全部') - assert.equal(calls.extract.length, 0) - assert.equal(host.lastToast().title, '没有可解压的压缩包') - - // 损坏包也可直接从列表移除回到空态 - await view.run(undefined, '从列表移除') - await tick(10) - assert.equal(dropdownItems(view.tree()).length, 0) - view.unmount() -}) - -test('移入回收站:必须确认,取消不执行;确认后从列表移除;失败如实提示', async () => { - const calls = installArchiveHost() - const view = await mount(ArchiveManagerCommand, host) - await importArchiveViaPaste(view, [ARCHIVE, ARCHIVE_B]) - - host.setConfirm(false) - await view.run(pdfItem(view), '将原压缩包移入回收站') - assert.equal(calls.trash.length, 0) - assert.equal(host.confirms.at(-1).primaryAction.style, 'destructive') - - host.setConfirm(true) - await view.run(pdfItem(view), '将原压缩包移入回收站') - await tick(10) - assert.deepEqual(calls.trash, [ARCHIVE]) - assert.equal(view.tree().props.searchBarAccessory.props.value, ARCHIVE_B) - - host.ipc.shell_trash_item = async () => { - throw Object.assign(new Error('文件正被另一个程序使用'), { code: 'EBUSY' }) - } - await view.run(pdfItem(view), '将原压缩包移入回收站') - assert.equal(host.lastToast().title, '移入回收站失败') - assert.match(host.lastToast().message, /正被另一个程序使用/) - view.unmount() -}) - -test('[故障注入] 在资源管理器中定位失败时提示,不静默', async () => { - installArchiveHost() - const view = await mount(ArchiveManagerCommand, host) - await importArchiveViaPaste(view, [ARCHIVE]) - await view.run(pdfItem(view), '在资源管理器中定位压缩包') - assert.equal(host.lastToast().title, '无法在资源管理器中定位') - view.unmount() -}) - -test('“提取压缩包内办公文档”命令默认筛选办公文档', async () => { - installArchiveHost() - globalThis.__ztoolsLaunchContext = { pluginId: 'archive-manager', featureCode: 'archive-docs' } - const view = await mount(ArchiveManagerCommand, host) - await importArchiveViaPaste(view, [ARCHIVE]) - const titles = view.tree().props.subList.items.map((i) => i.props.title) - assert.deepEqual(titles, ['标书正本.pdf']) - view.unmount() -}) - -test('不在客户端里运行:只显示“需要在 ZTools 客户端中使用”,不扫描、不显示示例', async () => { - const saved = globalThis.__ztoolsElectron - delete globalThis.__ztoolsElectron - try { - const view = await mount(ArchiveManagerCommand, host) - await tick(5) - const items = view.items() - assert.equal(items.length, 1) - assert.equal(items[0].props.title, '需要在 ZTools 客户端中使用') - view.unmount() - } finally { - globalThis.__ztoolsElectron = saved } }) diff --git a/extensions/audio-device/README.en.md b/extensions/audio-device/README.en.md new file mode 100644 index 00000000..8faf9196 --- /dev/null +++ b/extensions/audio-device/README.en.md @@ -0,0 +1,21 @@ +# Audio Device Switcher + +View macOS audio output and input devices, switch the system default device, and adjust device volume and mute state. + +## Usage + +- Commands: Type `audio`, `speaker`, or `headphone` in the launcher to open the device list; type `mic` or `microphone` to show input devices only; type `mute` or `unmute` to directly toggle the mute state of the current default output device (no-view mode; both `mute` and `unmute` act as a toggle). +- Use the top dropdown to filter by All Devices, Output Devices, Input Devices, or Favorites; use the search box to find devices by name or connection type (such as Bluetooth, USB, or HDMI). +- `Enter`: Set the selected device as the system default output or input device; `⌘K`: Open the action panel to mute/unmute, set volume (0–100), increase/decrease volume by 10%, mark as favorite, or view device info. +- Unsupported actions (setting as default, software volume, or mute) are hidden for that device. Devices that are already the default no longer show "Set as Default"; pressing `Enter` on them directly toggles mute (or sets volume if mute is unsupported). +- After every switch, volume change, or mute toggle, the plugin reads back the system state to verify the change and reports the failure reason if it did not take effect (e.g., "System did not switch to the selected device" or "Device volume did not reach the requested value"). + +## Platforms & Requirements + +- Supported: macOS only +- Requires client version 1.1.8.5 or later. +- Reading and writing audio devices relies on the macOS audio component bundled with the client; when unavailable, the list displays "Unable to read audio devices" and the reason. + +## Network & Data + +- Works offline; "Favorite Devices" records are stored locally only. diff --git a/extensions/audio-device/plugin.json b/extensions/audio-device/plugin.json index 8d7d1d38..68a2c0cb 100644 --- a/extensions/audio-device/plugin.json +++ b/extensions/audio-device/plugin.json @@ -1,7 +1,7 @@ { "id": "audio-device", "name": "音频设备切换", - "version": "1.0.8", + "version": "1.0.9", "description": "秒级切换系统默认扬声器、耳机与麦克风,支持音量调节、快速静音,可按蓝牙、USB、显示器等连接方式搜索设备", "author": "ZTools Team", "entry": "dist/index.js", @@ -59,6 +59,12 @@ "platform": "macos", "runtime": "electron", "arch": "any" + }, + { + "id": "windows-electron-any", + "platform": "windows", + "runtime": "electron", + "arch": "any" } ], "minAppVersion": "1.1.8.5", @@ -74,7 +80,13 @@ "microphone", "volume", "mute", - "sound" + "sound", + "headphones", + "mic", + "output", + "input", + "switch audio", + "playback" ], "features": { "audio-switch": { @@ -117,5 +129,19 @@ { "path": "screenshots/01.png" } + ], + "keywords": [ + "音频", + "耳机", + "扬声器", + "音箱", + "麦克风", + "切耳机", + "声音输出", + "声音设备", + "切换声音", + "话筒", + "audio", + "speaker" ] } diff --git a/extensions/audio-device/src/index.tsx b/extensions/audio-device/src/index.tsx index 360e863f..73c1ee8b 100644 --- a/extensions/audio-device/src/index.tsx +++ b/extensions/audio-device/src/index.tsx @@ -29,7 +29,7 @@ export function AudioVolumeForm({ device, manager, onSaved }: { device: AudioDev finally { pending.current = false; if (mounted.current) setBusy(false) } } return }> - { if (!pending.current) setVolume(value) }} /> + { if (!pending.current) setVolume(value) }} /> } export function AudioDeviceDetailView({ device }: { device: AudioDevice }) { diff --git a/extensions/audio-device/src/native-ipc.ts b/extensions/audio-device/src/native-ipc.ts index 51576b99..13643277 100644 --- a/extensions/audio-device/src/native-ipc.ts +++ b/extensions/audio-device/src/native-ipc.ts @@ -174,11 +174,13 @@ function normalizeMethodResult(method: string, payload: DynamicBridge): DynamicB if (method === 'system_get_battery_status') { // 宿主约定 percent 超出 0-100(如 255)表示无电池或电量未知,不能改写成 100% + // 若宿主明确给出 hasBattery 布尔值,必须原样保留,仅在缺失时按合法电量推算 const rawPct = payload.percent - const hasBattery = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const validPct = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const hasBattery = typeof payload.hasBattery === 'boolean' ? payload.hasBattery : validPct return { ...payload, - percent: hasBattery ? rawPct : null, + percent: validPct ? rawPct : null, hasBattery } } @@ -489,6 +491,8 @@ export interface RealDirectoryScanResult extends Iterable approximate?: boolean /** 宿主实际遍历的条目数 */ visitedEntries?: number + /** 目录本身不存在(ENOENT) */ + missing?: boolean /** 读取失败的真实原因;已有文件仍可使用,但不能当作完整结果。 */ error?: string } @@ -497,6 +501,7 @@ interface ScanResultMeta { truncated?: boolean approximate?: boolean visitedEntries?: number + missing?: boolean } export interface ScanDirectoryTreeOptions { @@ -504,6 +509,10 @@ export interface ScanDirectoryTreeOptions { maxFiles?: number collectTopN?: number filterExt?: RegExp + /** 为 true 时,目录本身不存在(ENOENT)按空目录处理,不返回 error(权限拒绝/读取失败仍照常报错) */ + ignoreMissing?: boolean + /** Top-N 保留与排序方式:默认按体积降序,下载/录屏等时效场景可传 mtime-desc */ + sortBy?: 'size-desc' | 'mtime-desc' hostOverride?: DynamicBridge } @@ -519,8 +528,9 @@ function normalizeIndexedFileEntry(f: DynamicBridge): RealIndexedFileEntry { const sz = Number(f?.size ?? f?.sizeBytes ?? 0) const isDir = Boolean(f?.is_dir || f?.isDir || f?.isDirectory) const rawMtime = Number(f?.mtime ?? f?.mtimeMs ?? 0) - const mtimeMs = rawMtime > 1e11 ? rawMtime : rawMtime > 0 ? rawMtime * 1000 : Date.now() - const mtimeSec = rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime + const validMtime = Number.isFinite(rawMtime) && rawMtime > 0 + const mtimeMs = validMtime ? (rawMtime > 1e11 ? rawMtime : rawMtime * 1000) : 0 + const mtimeSec = validMtime ? (rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime) : 0 if (p && sz >= 0) realFileSizeCache.set(p, sz) return { name, @@ -551,6 +561,7 @@ function makeScanResult( subdirs, ...(meta.truncated ? { truncated: true } : {}), ...(meta.approximate ? { approximate: true } : {}), + ...(meta.missing ? { missing: true } : {}), ...(typeof meta.visitedEntries === 'number' ? { visitedEntries: meta.visitedEntries } : {}), [Symbol.iterator]() { return files[Symbol.iterator]() @@ -609,13 +620,40 @@ export async function scanRealDirectoryTree( return result.error ? { ...result.scan, error: result.error } : result.scan } +/** 仅当正则明确声明了扩展名(含 `\.`)时提取后缀列表,避免把 `thumbcache|iconcache` 等文件名关键词误拆成假扩展名 */ +function extractExtensionTokensFromFilter(filterExt: RegExp): string[] { + const src = filterExt.source + if (!src.includes('\\.')) return [] + const afterDot = src.slice(src.indexOf('\\.') + 2) + const rawTokens = afterDot.match(/[a-z0-9]{1,8}/gi) || [] + const seen = new Set() + const out: string[] = [] + for (const token of rawTokens) { + const lower = token.toLowerCase() + if (!lower || seen.has(lower)) continue + seen.add(lower) + out.push(lower) + } + return out +} + +function isMissingDirectoryError(res: { error?: string; errorCode?: string; errorDetails?: Record }): boolean { + if (res.errorDetails?.reason === 'ENOENT' || res.errorCode === 'ENOENT') return true + const msg = String(res.error || '') + return /Directory does not exist|ENOENT/i.test(msg) +} + /** 一次界面扫描的错误汇总;多个目录并行扫描时保留可读目录的结果。 */ export function createDirectoryScanner(hostOverride?: DynamicBridge) { const failures = new Map() return { async scan(dir: string, options: number | ScanDirectoryTreeOptions = 160) { const result = await scanRealDirectoryTree(dir, options, hostOverride) - const error = result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') + const ignoreMissing = typeof options === 'object' && options !== null && options.ignoreMissing === true + const error = + result.missing && ignoreMissing + ? '' + : result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') if (error) failures.set(dir, error) else failures.delete(dir) return result @@ -648,26 +686,38 @@ async function scanDirectoryTreeWithError( const safeLimit = Math.min(200, Math.max(1, Math.floor(rawLimit || 160))) const hostOverride = opts.hostOverride const filterExt = opts.filterExt + const ignoreMissing = opts.ignoreMissing === true const dirQuery = `dir:${targetDir}` try { let rawPayload: DynamicBridge = null + const searchParams: Record = { + query: dirQuery, + limit: safeLimit, + ...(opts.sortBy ? { sortBy: opts.sortBy } : {}) + } const res = await callHostTransport( 'system_search_files', - { query: dirQuery, limit: safeLimit }, + searchParams, hostOverride ) - if (res.ok && res.data) { + if (res.ok && res.data && res.data.degraded !== true) { rawPayload = res.data + } else if (!res.ok && ignoreMissing && isMissingDirectoryError(res)) { + const missingScan = makeScanResult([], 0, 0, [], { missing: true }) + return { scan: missingScan } } - if (!rawPayload && !hostOverride && typeof window !== 'undefined') { + if (!rawPayload && !hostOverride && res.errorCode === 'METHOD_NOT_AVAILABLE' && typeof window !== 'undefined') { const w = window as DynamicBridge if (typeof w.__ztoolsLauncher?.searchFiles === 'function') { const rawOuter = await w.__ztoolsLauncher.searchFiles(dirQuery, safeLimit) - rawPayload = + const candidate = rawOuter && typeof rawOuter === 'object' && 'data' in rawOuter && rawOuter.data ? rawOuter.data : rawOuter + if (candidate && candidate.degraded !== true && candidate.success !== false) { + rawPayload = candidate + } } } @@ -678,29 +728,32 @@ async function scanDirectoryTreeWithError( let files: RealIndexedFileEntry[] = rawPayload.files.map(normalizeIndexedFileEntry) if (filterExt instanceof RegExp) { files = files.filter(f => !f.isDir && (filterExt.test(f.name) || filterExt.test(f.ext))) - // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索目标扩展名 + // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索明确声明的目标扩展名 if (files.length === 0 && !hostOverride) { - const extTokens = (filterExt.source.match(/[a-z0-9]{2,5}/gi) || []) - .filter(t => !['thumbcache', 'iconcache'].includes(t.toLowerCase())) - .slice(0, 4) - // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 - const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() - const extraLists = await Promise.all( - extTokens.map(ext => searchRealIndexedFiles(`.${ext.toLowerCase()}`, 30, hostOverride)) - ) - const seen = new Set() - for (const list of extraLists) { - for (const item of list) { - if (!item.isDir && item.size > 0 && !seen.has(item.path)) { - if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { - seen.add(item.path) - files.push(item) + const extTokens = extractExtensionTokensFromFilter(filterExt) + if (extTokens.length > 0) { + // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 + const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() + const extraLists = await Promise.all( + extTokens.map(ext => searchRealIndexedFiles(`.${ext}`, 30, hostOverride)) + ) + const seen = new Set() + for (const list of extraLists) { + for (const item of list) { + if (!item.isDir && item.size > 0 && !seen.has(item.path)) { + if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { + seen.add(item.path) + files.push(item) + } } } } } } } + // 先基于过滤后的完整命中集合计算总文件数与总字节数,再按 collectTopN 裁剪样本列表 + const matchedCount = files.length + const matchedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) if (typeof opts.collectTopN === 'number' && opts.collectTopN > 0 && files.length > opts.collectTopN) { files = files.slice(0, opts.collectTopN) } @@ -714,11 +767,10 @@ async function scanDirectoryTreeWithError( ...(s.approximate === true ? { approximate: true } : {}) })) : [] - const computedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) const totalFilesCount = - filterExt instanceof RegExp ? files.length : Number(rawPayload.total_matches ?? files.length) + filterExt instanceof RegExp ? matchedCount : Number(rawPayload.total_matches ?? matchedCount) const totalBytesCount = - filterExt instanceof RegExp ? computedBytes : Number(rawPayload.total_bytes ?? computedBytes) + filterExt instanceof RegExp ? matchedBytes : Number(rawPayload.total_bytes ?? matchedBytes) const visited = Number(rawPayload.visited_entries) return { scan: makeScanResult(files, totalFilesCount, totalBytesCount, subdirs, { @@ -1817,8 +1869,6 @@ export async function writeRealClipboardText(text: string, hostOverride?: Dynami const payload = { text: String(text || '') } const res = await callHostTransport('clipboard_copy_text', payload, hostOverride) if (res.ok) return true - const fallbackRes = await callHostTransport('clipboard_write_text', payload, hostOverride) - if (fallbackRes.ok) return true try { if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) { await navigator.clipboard.writeText(String(text || '')) diff --git a/extensions/base64image/README.en.md b/extensions/base64image/README.en.md new file mode 100644 index 00000000..38236133 --- /dev/null +++ b/extensions/base64image/README.en.md @@ -0,0 +1,20 @@ +# Image Base64 Converter + +Convert image files or clipboard images to Base64, and restore Base64 strings, Data URLs, or SVG source code into an image preview. + +## Usage + +- Command: Image Base64 Converter (keywords such as `base64`, `dataurl`, `image`). +- After opening, press `Enter` to choose an image file (PNG, JPEG, GIF, WebP, or SVG, up to 10 MB per image), or press `⌘/Ctrl+Enter` to read from the clipboard (trying copied image files, clipboard images such as screenshots, and then text in order). +- You can also paste a Base64 string, `data:image/...;base64,` URL, or SVG source code directly into the input box; the right pane shows the image preview, format, and size, or explains why an input could not be recognized. +- Results are provided in five formats: Data URL, plain Base64, Markdown, HTML ``, and CSS background image. Press `Enter` to copy, `⌘/Ctrl+Enter` to save as a text file, or `⌘/Ctrl+K` to open the action panel. +- Results exceeding 8 MiB cannot be copied to the clipboard and can only be saved as a text file. Saving a restored preview directly as an image file is not provided. + +## Platforms & Requirements + +- Supported: Windows, macOS +- Built into the client; no separate installation required. + +## Network & Data + +- Works offline; data stays on your local device. diff --git a/extensions/base64image/plugin.json b/extensions/base64image/plugin.json index 203fd97c..5cbe0446 100644 --- a/extensions/base64image/plugin.json +++ b/extensions/base64image/plugin.json @@ -1,7 +1,8 @@ { "id": "base64image", "name": "图片 Base64", - "version": "1.0.7", + "version": "1.0.8", + "minAppVersion": "1.1.8.0", "description": "图片文件或截图与 Base64 编码双向互转,支持一键复制 Data URL 或还原预览图片", "author": "ZTools Team", "entry": "dist/index.js", @@ -32,7 +33,14 @@ "image", "datauri", "编码", - "解码" + "解码", + "图片转base64", + "base64图片", + "图片编码", + "base64转图片", + "图片转码", + "dataurl", + "图转码" ], "category": [ "开发工具" @@ -49,7 +57,13 @@ "dataurl", "encode", "decode", - "converter" + "converter", + "image to base64", + "base64 to image", + "data uri", + "img encode", + "img decode", + "picture encode" ], "screenshots": [ { diff --git a/extensions/batch-audio/README.en.md b/extensions/batch-audio/README.en.md new file mode 100644 index 00000000..ffacc5ec --- /dev/null +++ b/extensions/batch-audio/README.en.md @@ -0,0 +1,22 @@ +# Batch Audio Converter + +Select files, select a folder, or drag and drop audio files to convert checked tracks to the selected format using your local `ffmpeg`. + +## Usage + +- Command: Search for "Batch Audio Converter" in the launcher to open. +- Import via **Select File**, **Select Folder**, or dragging and dropping audio files or folders. Supports mp3, flac, wav, aac, m4a, ogg, wma, opus, and aiff formats (folders scan up to 5 levels deep, up to 500 tracks per batch). +- Select MP3, FLAC, WAV, AAC, M4A, or OGG under "Output Format" on the right. Conversion uses `ffmpeg`'s default encoding parameters; bitrate and compression level labels shown in the options (such as `320k` or `Level 8`) do not take effect. +- Merge mode (`BatchMergeAudio`) supports up to 100 files and a total size of up to 2 GiB per batch. +- `Enter`: Convert all checked files after confirmation; `Ctrl+Enter`: Reveal file in File Explorer; `Ctrl+O`: Select files; `Ctrl+Shift+O`: Select folder; `Ctrl+Backspace`: Remove from list; `Ctrl+Shift+Backspace`: Clear list (without touching files on disk); `Ctrl+K`: Open the action panel to process only the current file. +- Output files are named `_processed.` and saved in the same folder as the source file without modifying the original. Existing output files with the same name are overwritten, and partial output files are deleted if conversion fails. +- Currently performs format conversion only: processing modes in the top dropdown (loudness normalization, volume gain, silence trimming, head/tail trimming, fade in/out, equalizer, dynamic compression, noise reduction, merge, tag writing), as well as quality tiers, loudness standards, sample rate, silence trimming, and spectral noise reduction settings do not take effect; selecting "Merge" also converts each file individually. +- Requires `ffmpeg` to be installed locally and available on the command line; if `ffmpeg` cannot be found, it displays "ffmpeg not detected on this machine". Converting a single file times out and reports an error after 60 seconds. + +## Platforms & Requirements + +- Supported: Windows only + +## Network & Data + +- Works offline; data stays on your local device. diff --git a/extensions/batch-audio/package.json b/extensions/batch-audio/package.json index ecb0070d..30de13fa 100644 --- a/extensions/batch-audio/package.json +++ b/extensions/batch-audio/package.json @@ -1,12 +1,12 @@ { "name": "@ztools/plugin-batch-audio", - "version": "1.0.0", - "description": "支持 MP3/FLAC/WAV/AAC/OGG 批量格式转换、EBU R128 响度均衡、静音裁剪、淡入淡出与多轨合并", + "version": "2.1.0", + "description": "基于宿主 media.probe / media.transcode 薄原语的批量音频转换插件", "main": "dist/index.js", "types": "dist/index.d.ts", "scripts": { "build": "tsc", - "test": "node --test tests/batch-audio.test.mjs" + "test": "node --test tests/*.test.mjs" }, "dependencies": { "@ztools/declarative-ui": "workspace:*" diff --git a/extensions/batch-audio/plugin.json b/extensions/batch-audio/plugin.json index 46672c76..efa5e0a0 100644 --- a/extensions/batch-audio/plugin.json +++ b/extensions/batch-audio/plugin.json @@ -1,8 +1,9 @@ { "id": "batch-audio", "name": "音频转换", - "description": "支持选择文件、选择文件夹或拖入 MP3/FLAC/WAV/AAC 等音频文件,进行批量格式转换、音量均衡调节、静音片段裁剪与多段音频合并", - "version": "2.0.13", + "description": "支持选择文件、选择文件夹或拖入 MP3/FLAC/WAV/AAC/OGG 等音频文件,通过宿主媒体引擎进行音频探测、批量格式转换、采样率/码率/声道调节,以及按能力开放的音量增益、淡入淡出与变速处理", + "version": "2.1.0", + "minAppVersion": "1.3.0.0", "author": "ZTools Team", "entry": "dist/index.js", "icon": "icon.svg", @@ -14,11 +15,16 @@ "media", "productivity" ], + "requiredCapabilities": [ + "media.probe", + "media.transcode" + ], "permissions": [ "fs", - "audio", "dialog", - "shell" + "shell", + "media.read", + "media.process" ], "requireAdmin": false, "nativeComponents": [], @@ -30,12 +36,11 @@ "arch": "any" } ], - "minAppVersion": "1.1.8.9", "defaultLocale": "zh-CN", "i18n": { "en-US": { "name": "Batch Audio Converter", - "description": "Import MP3, FLAC, WAV, AAC, and other audio files via file picker, folder, or drag-and-drop for batch format conversion, volume normalization, silence trimming, and audio merging.", + "description": "Import MP3, FLAC, WAV, AAC, and OGG audio files via picker, folder, or drag-and-drop for probing, batch format conversion, sample rate/bitrate/channel tuning, plus capability-gated gain, fade, and speed adjustment.", "keywords": [ "audio", "convert", @@ -43,8 +48,14 @@ "flac", "wav", "aac", + "ogg", "batch", - "merge" + "audio convert", + "m4a", + "batch audio", + "sound converter", + "music format", + "transcode" ], "screenshots": [ { @@ -60,5 +71,18 @@ { "path": "screenshots/02-action-panel.png" } + ], + "keywords": [ + "音频转换", + "格式转换", + "转mp3", + "转wav", + "转flac", + "音乐转换", + "声音转换", + "批量转音频", + "音频压缩", + "mp3", + "m4a" ] } diff --git a/extensions/batch-audio/src/i18n.ts b/extensions/batch-audio/src/i18n.ts index 046e84f9..e4bbbd14 100644 --- a/extensions/batch-audio/src/i18n.ts +++ b/extensions/batch-audio/src/i18n.ts @@ -1,283 +1,284 @@ -import { createTranslator } from "@ztools/declarative-ui"; +import { createTranslator } from '@ztools/declarative-ui' const rawT = createTranslator( { - "zh-CN": { - forbiddenReason: "音频批处理输出路径不可指向系统受保护目录或包含路径穿越", - mergeLimitError: "合并最多支持 100 个文件、总大小 2 GiB,请减少勾选", - mode01Title: "01. 批量格式转码为 MP3 (320kbps CBR)", - mode01Sub: "使用 MP3 320kbps 编码,保留源音频文本元数据", - mode01Tag: "MP3 320k", - mode02Title: "02. 批量转码为无损 FLAC (Level 8)", - mode02Sub: "FLAC 无损编码,采样率按左侧选项设置", - mode02Tag: "无损 FLAC", - mode03Title: "03. EBU R128 广播级响度标准化 (-16 LUFS)", - mode03Sub: "自动平衡多首音频响度差异,防止破音失真 (Podcast/流媒体标准)", - mode03Tag: "R128 响度", - mode04Title: "04. 固定音量分贝增益放大 (+3.5 dB)", - mode04Sub: "针对录音音量偏小的会议/课程素材统一提升分贝增益", - mode04Tag: "音量增益", - mode05Title: "05. 首尾静音片段自动检测与切除 (-50dB)", - mode05Sub: "基于 BatchAudioSilenceParser 自动剔除录音首尾空白静音段", - mode05Tag: "切除静音", - mode06Title: "06. 音频去头去尾定时裁剪 (跳过首尾2秒)", - mode06Sub: "批量去除固定片头播报或片尾版权提示音", - mode06Tag: "去头去尾", - mode07Title: "07. 批量添加柔和淡入淡出过渡 (3秒)", - mode07Sub: "为背景配乐与铃声添加平滑 afade 首尾过渡曲线", - mode07Tag: "淡入淡出", - mode08Title: "08. 10 段频率均衡器 (EQ 人声与播客清晰增强)", - mode08Sub: "衰减 100Hz 以下低频轰鸣,提升 3kHz 人声清晰度频段", - mode08Tag: "EQ 均衡器", - mode09Title: "09. 动态范围压缩器 (Compressor 防忽大忽小)", - mode09Sub: "压制突发大音量峰值并抬升轻声细语细节", - mode09Tag: "动态压缩", - mode10Title: "10. 频谱背景降噪 (afftdn 空调/电流底噪消除)", - mode10Sub: "基于 FFT 频谱滤波消除环境白噪音与麦克风底噪", - mode10Tag: "频谱降噪", - mode11Title: "11. 多音频轨道无缝拼接合并", - mode11Sub: "按勾选顺序自动统一采样率并无缝合并为单一音频文件", - mode11Tag: "无缝合并", - mode12Title: "12. 批量音频 ID3v2 元数据与版权标签写入", - mode12Sub: "统一写入艺术家、专辑名称、年份与发行版权签名", - mode12Tag: "ID3 标签", - errInvalidMethod: "INVALID_METHOD: 不支持的音频处理模式", - errInvalidParams: "INVALID_PARAMS: 音频参数必须为对象", - errInvalidFilesEmpty: "INVALID_FILES: 请选择至少一首音频", - errInvalidFilesPath: "INVALID_FILES: 每个音频输入都必须是有效的绝对文件路径", - errMergeMinFiles: "INVALID_FILES: 合并需要至少两首音频", - errInvalidOutputPath: "INVALID_OUTPUT: {key} 必须为有效的绝对路径", - errMultiOutputSingle: "INVALID_OUTPUT: 多个独立任务不能共用一个输出文件", - errValidationFailed: "参数校验失败", - errHostUnconfirmed: "客户端未确认音频处理成功", - errMinAudioForRun: "合并需要至少两首音频,其他处理需要至少一首音频", - errNoValidOutput: "客户端没有返回有效的音频输出文件", - errItemJoinSep: "、", - errItemPrefix: "{names}:{msg}", - pickFolderTitle: "选择包含音频的文件夹", - noFolderSelected: "没有选择文件夹", - loudness16: "-16 LUFS (播客标准)", - loudness14: "-14 LUFS (流媒体标准)", - loudness23: "-23 LUFS (EBU 广播)", - loudnessKeep: "保持原响度", - importFailedTitle: "导入失败", - pickFilesTitle: "选择待处理的音频文件", - pickFilesFilterName: "音频文件", - confirmRootTitle: "导入整个磁盘 {path} 中的音频?", - confirmRootMsg: "将读取该磁盘下 5 层以内的文件夹,最多导入 500 首音频,可能需要一些时间。", - confirmRootAction: "继续导入", - dropTitle: "拖入音频或文件夹", - dropSubtitle: "文件夹内 5 层以内的音频会一并导入", - selectAudioFirst: "请先勾选待处理的音频文件", - mergeNeedTwo: "合并需要至少两首音频", - confirmRunTitle: "对 {count} 首音频执行「{tag}」?", - confirmRunMsg: "输出 {ext};新文件保存在源文件旁。合并按队列顺序处理。", - confirmRunAction: "开始处理", - runSummary: "完成 {completed} 首,失败 {failed} 首,生成 {outputs} 个文件", - runPartialTitle: "音频处理未全部完成", - runSuccessTitle: "音频处理已完成", - removeBusy: "该音频正在处理中,完成后再移除", - clearBusy: "正在处理,完成后再清空", - sizeUnknown: "大小未识别", - unknownSizeCount: "({count} 首大小未识别)", - actionPickFilesEllipsis: "选择文件…", - actionPickFolderEllipsis: "选择文件夹…", - actionRunBatch: "开始批量处理 ({count}项)", - actionRevealInFolder: "在资源管理器中定位文件", - actionRunSingle: "仅对当前音轨执行「{tag}」", - sectionList: "列表", - actionRemove: "从列表移除", - actionDeselectAll: "取消全选当前列表", - actionSelectAll: "全选当前列表", - actionClearList: "清空列表", - summaryImporting: "正在导入:已读取 {dirs} 个文件夹,找到 {files} 个文件", - summaryEmptyClient: "尚未添加音频 · 可选择文件、文件夹,或直接拖入", - hostRequired: "需要在 ZTools 客户端中使用", - summaryNormal: "{last}已选 {selected}/{total} 首音频 ({bytes}) · 清空列表 Ctrl+Shift+Backspace", - emptyNoMatch: "没有匹配的音频文件", - emptyDefault: "尚未添加音频 · 可选择文件、文件夹,或直接拖入", - searchPlaceholder: "搜索音频文件名、路径、处理模式或输出格式 (MP3 / FLAC / WAV / AAC)...", - queueActionsTitle: "音频转换队列操作", - dropdownTooltip: "选择 12 大音频处理预设模式", - dropdownItemTitle: "预设: {tag}", - btnPickFiles: "选择文件", - btnPickFolder: "选择文件夹", - wbTitle: "音频声学与转码参数工作台", - wbFormatLabel: "输出格式", - optMp3: "MP3 320k (全平台高音质)", - optFlac: "FLAC 无损 (Level 8 归档)", - optWav: "WAV PCM (未压缩母带)", - optAac: "AAC 256k (流媒体高效)", - optM4a: "M4A (Apple AAC)", - optOgg: "OGG Vorbis (游戏音轨)", - wbLoudnessLabel: "附加响度处理", - optLufs16: "EBU R128 -16 LUFS 播客", - optLufs14: "-14 LUFS 流媒体平台", - optLufs23: "-23 LUFS 广电标准", - optKeepRaw: "保持原响度 (不均衡)", - wbSampleRateLabel: "采样率", - opt48k: "48kHz (影视录音室级)", - opt44k: "44.1kHz (CD 标准音乐)", - optSourceRate: "保持原采样率", - wbStripSilenceLabel: "首尾静音自动切除", - wbDenoiseLabel: "频谱降噪 afftdn", - wbOutdirLabel: "输出位置", - wbOutdirValue: "源同级目录 (*_processed-唯一编号.{ext})", - previewTitle: "声学处理与输出体积预估", - previewSubtitle: "当前引擎: {title}", - metricRawSize: "原始总大小", - metricEstOut: "预计输出大小", - metricTargetLoudness: "目标响度", - metricSelectedCount: "已选音频数", - metricSelectedCountVal: "{selected} / {total} 首", - subListTitle: "待处理音频文件队列 (勾选后按 ↵ 开始处理)", - subListSubtitle: "{count} 首 · {bytes}", - sectionQueueTitle: "音频队列 ({count})", - sectionModesTitle: "12 大核心音频处理与声学工坊模式 ({count})", - actionSetActiveMode: "设为当前激活声学模式" + 'zh-CN': { + forbiddenReason: '音频批处理输出路径不可指向系统受保护目录或包含路径穿越', + hostRequired: '需要在 ZTools 客户端中使用', + engineChecking: '正在检测音频引擎…', + engineReady: '音频引擎就绪', + engineNeedsProvision: '需要下载音频引擎', + engineUnsupported: '当前客户端不支持音频引擎', + btnDownloadEngine: '下载音频引擎', + btnPickFiles: '选择文件', + btnPickFolder: '选择文件夹', + btnRunBatch: '开始处理 ({count})', + btnProcessing: '处理中…', + tagProcessing: '处理中', + btnCancelTask: '取消任务', + msgProvisionSuccess: '音频引擎已就绪', + errProvisionFailed: '下载音频引擎失败:{error}', + errProbeFailed: '探测音频信息失败:{error}', + errTranscodeFailed: '音频转换失败:{error}', + errCancelFailed: '取消任务失败:{error}', + errTaskCancelled: '已取消音频转换任务', + errHostDisconnected: '未连接 ZTools 客户端,无法执行音频转换', + errUnsupportedContainer: '不支持的输出音频格式:{format}', + errCannotGenUniqueName: '无法生成不覆盖已有文件的输出路径', + errSelectAudioFirst: '请先勾选待处理的音频文件', + errEngineNotReady: '音频引擎尚未就绪,请先下载音频引擎', + msgCancelled: '已发送取消请求', + pickFilesTitle: '选择待处理的音频文件', + pickFilesFilterName: '音频文件', + pickFolderTitle: '选择包含音频的文件夹', + noFolderSelected: '没有选择文件夹', + importFailedTitle: '导入失败', + confirmRootTitle: '导入整个磁盘 {path} 中的音频?', + confirmRootMsg: '将读取该磁盘下 5 层以内的文件夹,最多导入 500 首音频,可能需要一些时间。', + confirmRootAction: '继续导入', + dropTitle: '拖入音频或文件夹', + dropSubtitle: '文件夹内 5 层以内的音频会一并导入', + removeBusy: '该音频正在转换中,完成后再移除', + clearBusy: '正在转换中,请先取消或等待完成', + sizeUnknown: '大小未识别', + unknownSizeCount: '({count} 首大小未识别)', + durationUnknown: '时长未知', + summaryImporting: '正在导入:已读取 {dirs} 个文件夹,找到 {files} 个文件', + summaryEmptyClient: '{engine} · 尚未添加音频 · 可选择文件、文件夹或直接拖入', + summaryNormal: '{engine} · {last}已选 {selected}/{total} 首 ({bytes})', + emptyNoMatch: '没有匹配的音频文件', + emptyDefault: '尚未添加音频 · 可选择文件、文件夹,或直接拖入', + searchPlaceholder: '搜索音频文件名或目录…', + dropdownTooltip: '选择输出音频格式预设', + optMp3: 'MP3 (通用高音质)', + optFlac: 'FLAC (无损压缩)', + optWav: 'WAV (未压缩 PCM)', + optAac: 'AAC (高效压缩)', + optOgg: 'OGG (Opus 编码)', + wbTitle: '音频转换参数', + wbSubtitle: '基于宿主媒体薄原语 · 无覆盖输出', + wbFormatLabel: '输出格式', + wbBitrateLabel: '音频码率', + wbSampleRateLabel: '采样率', + wbChannelsLabel: '声道数', + wbGainLabel: '音量增益 (dB)', + wbFadeLabel: '首尾淡入淡出', + wbSpeedLabel: '播放变速', + wbEngineLabel: '引擎状态', + wbOutdirLabel: '输出位置', + wbOutdirValue: '源目录 (*_audio.{ext})', + bitrate320: '320 kbps', + bitrate256: '256 kbps', + bitrate192: '192 kbps', + bitrate128: '128 kbps', + bitrateLossless: '无损(不限码率)', + sampleKeep: '保持原采样率', + sample48k: '48 kHz', + sample44k: '44.1 kHz', + sample32k: '32 kHz', + chKeep: '保持原声道', + chStereo: '立体声 (2ch)', + chMono: '单声道 (1ch)', + gainNone: '不调整 (0 dB)', + gainPlus3: '+3 dB', + gainPlus6: '+6 dB', + gainMinus3: '-3 dB', + gainMinus6: '-6 dB', + fadeNone: '关闭', + fade1s: '淡入 1 秒 / 淡出 1 秒', + fade2s: '淡入 2 秒 / 淡出 2 秒', + fade3s: '淡入 3 秒 / 淡出 3 秒', + speed100: '原速 (1.0x)', + speed075: '0.75x 慢速', + speed125: '1.25x 加速', + speed150: '1.5x 加速', + speed200: '2.0x 倍速', + previewTitle: '音频批处理摘要', + previewBadgeReady: '已选 {count} 首', + previewBadgeNeedsProvision: '需下载引擎', + previewSubtitle: '输出 .{ext} · 原文件保持不变', + metricRawSize: '已选体积', + metricEngine: '引擎状态', + metricExtensions: '扩展特性', + metricSelectedCount: '队列进度', + metricSelectedCountVal: '{done} 完成 / {total} 总计', + extAudioFilters: '增益/淡入淡出', + extSpeed: '变速', + extNone: '基础转码', + subListTitle: '待处理音频队列(勾选后按 Enter 开始转换)', + subListSubtitle: '{count} 首 · {bytes}', + sectionQueueTitle: '音频队列 ({count})', + tagPending: '待转换', + tagRunning: '转换中 {percent}%', + tagDone: '已输出 {size}', + tagFailed: '失败', + tagCancelled: '已取消', + subDone: '输出:{name}', + subFailed: '失败:{error}', + subProbed: '{duration} · {meta}', + runSummary: '完成 {completed} 首,失败 {failed} 首{cancelled}', + runCancelledPart: ',已取消 {count} 首', + runSuccessTitle: '音频转换已完成', + runPartialTitle: '音频转换未全部完成', + actionDownloadEngine: '下载音频引擎', + actionRunBatch: '开始批量转换 ({count} 首)', + actionCancelCurrent: '取消当前转换任务', + actionProbeSingle: '重新探测音频元数据', + actionRunSingle: '仅转换此文件', + actionRevealInFolder: '在文件管理器中定位', + actionPickFilesEllipsis: '选择文件…', + actionPickFolderEllipsis: '选择文件夹…', + actionRemove: '从列表移除', + actionSelectAll: '全选当前列表', + actionDeselectAll: '取消全选当前列表', + actionClearList: '清空列表', + sectionList: '队列操作' }, - "en-US": { - forbiddenReason: "Output path cannot point to a protected system directory or contain path traversal", - mergeLimitError: "Merge supports up to 100 files and 2 GiB total; please reduce selection", - mode01Title: "01. Batch Transcode to MP3 (320kbps CBR)", - mode01Sub: "Encode with MP3 320kbps while preserving audio metadata", - mode01Tag: "MP3 320k", - mode02Title: "02. Batch Transcode to Lossless FLAC (Level 8)", - mode02Sub: "Lossless FLAC encoding using selected sample rate", - mode02Tag: "FLAC Lossless", - mode03Title: "03. EBU R128 Loudness Normalization (-16 LUFS)", - mode03Sub: "Balance volume across tracks and prevent clipping (Podcast/Streaming)", - mode03Tag: "R128 Loudnorm", - mode04Title: "04. Fixed Volume Gain Boost (+3.5 dB)", - mode04Sub: "Boost volume uniformly for quiet voice recordings or lectures", - mode04Tag: "Volume Gain", - mode05Title: "05. Auto Detect & Trim Silence (-50dB)", - mode05Sub: "Trim leading and trailing silence using BatchAudioSilenceParser", - mode05Tag: "Trim Silence", - mode06Title: "06. Fixed Head/Tail Trim (Skip First/Last 2s)", - mode06Sub: "Batch remove fixed intro announcements or outro bumpers", - mode06Tag: "Trim Ends", - mode07Title: "07. Smooth Fade In / Fade Out (3s)", - mode07Sub: "Apply smooth afade curves to background music and ringtones", - mode07Tag: "Fade In/Out", - mode08Title: "08. 10-Band EQ (Vocal & Podcast Clarity)", - mode08Sub: "Attenuate rumble below 100Hz and boost 3kHz vocal clarity", - mode08Tag: "Vocal EQ", - mode09Title: "09. Dynamic Range Compressor", - mode09Sub: "Tame sudden peaks and bring up quiet vocal details", - mode09Tag: "Compressor", - mode10Title: "10. Spectral Denoise (afftdn Noise Removal)", - mode10Sub: "Remove AC hum, mic hiss, and background noise via FFT filtering", - mode10Tag: "Denoise", - mode11Title: "11. Seamless Multi-Track Merge", - mode11Sub: "Unify sample rates and concatenate tracks in queue order", - mode11Tag: "Merge Audio", - mode12Title: "12. Batch ID3v2 Metadata & Copyright Tags", - mode12Sub: "Write artist, album, year, and copyright metadata uniformly", - mode12Tag: "ID3 Tags", - errInvalidMethod: "INVALID_METHOD: Unsupported audio processing mode", - errInvalidParams: "INVALID_PARAMS: Audio parameters must be an object", - errInvalidFilesEmpty: "INVALID_FILES: Please select at least one audio file", - errInvalidFilesPath: "INVALID_FILES: Every audio input must be a valid absolute file path", - errMergeMinFiles: "INVALID_FILES: Merging requires at least two audio files", - errInvalidOutputPath: "INVALID_OUTPUT: {key} must be a valid absolute path", - errMultiOutputSingle: "INVALID_OUTPUT: Multiple independent tasks cannot share one output file", - errValidationFailed: "Parameter validation failed", - errHostUnconfirmed: "Client did not confirm audio processing success", - errMinAudioForRun: "Merging requires at least two audio files; other modes require at least one", - errNoValidOutput: "Client did not return a valid audio output file", - errItemJoinSep: ", ", - errItemPrefix: "{names}: {msg}", - pickFolderTitle: "Select Folder Containing Audio Files", - noFolderSelected: "No folder selected", - loudness16: "-16 LUFS (Podcast)", - loudness14: "-14 LUFS (Streaming)", - loudness23: "-23 LUFS (Broadcast)", - loudnessKeep: "Keep Original", - importFailedTitle: "Import Failed", - pickFilesTitle: "Select Audio Files", - pickFilesFilterName: "Audio Files", - confirmRootTitle: "Import audio from entire drive {path}?", - confirmRootMsg: "Will scan up to 5 folder levels and import at most 500 audio files. This may take a while.", - confirmRootAction: "Continue Import", - dropTitle: "Drop audio files or folders", - dropSubtitle: "Audio files within 5 folder levels will be imported", - selectAudioFirst: "Please check audio files to process first", - mergeNeedTwo: "Merging requires at least two audio files", - confirmRunTitle: "Run \"{tag}\" on {count} audio [[count:file|files]]?", - confirmRunMsg: "Output {ext} next to source files. Merge follows queue order.", - confirmRunAction: "Start", - runSummary: "{completed} succeeded, {failed} failed, {outputs} [[outputs:file|files]] created", - runPartialTitle: "Audio Processing Partially Failed", - runSuccessTitle: "Audio Processing Completed", - removeBusy: "Track is processing; remove after completion", - clearBusy: "Processing in progress; clear after completion", - sizeUnknown: "Size unknown", - unknownSizeCount: " ({count} unknown size)", - actionPickFilesEllipsis: "Select Files…", - actionPickFolderEllipsis: "Select Folder…", - actionRunBatch: "Start Batch ({count} [[count:item|items]])", - actionRevealInFolder: "Reveal in Explorer", - actionRunSingle: "Run \"{tag}\" on This Track", - sectionList: "List", - actionRemove: "Remove from List", - actionDeselectAll: "Deselect All", - actionSelectAll: "Select All", - actionClearList: "Clear List", - summaryImporting: "Importing: {dirs} [[dirs:folder|folders]] scanned, {files} [[files:file|files]] found", - summaryEmptyClient: "No audio added · Select files, folder, or drop here", - hostRequired: "Requires the ZTools client", - summaryNormal: "{last}Selected {selected}/{total} ({bytes}) · Clear Ctrl+Shift+Backspace", - emptyNoMatch: "No matching audio files", - emptyDefault: "No audio added · Select files, folder, or drop here", - searchPlaceholder: "Search audio filename, path, mode, or format (MP3 / FLAC / WAV / AAC)...", - queueActionsTitle: "Audio Queue Actions", - dropdownTooltip: "Select Audio Processing Mode", - dropdownItemTitle: "Preset: {tag}", - btnPickFiles: "Select Files", - btnPickFolder: "Select Folder", - wbTitle: "Audio & Transcode Parameters", - wbFormatLabel: "Output Format", - optMp3: "MP3 320k (High Quality)", - optFlac: "FLAC Lossless (Level 8)", - optWav: "WAV PCM (Uncompressed)", - optAac: "AAC 256k (Streaming)", - optM4a: "M4A (Apple AAC)", - optOgg: "OGG Vorbis (Game Audio)", - wbLoudnessLabel: "Loudness Target", - optLufs16: "EBU R128 -16 LUFS Podcast", - optLufs14: "-14 LUFS Streaming", - optLufs23: "-23 LUFS Broadcast", - optKeepRaw: "Keep Original Loudness", - wbSampleRateLabel: "Sample Rate", - opt48k: "48kHz (Studio / Video)", - opt44k: "44.1kHz (CD Standard)", - optSourceRate: "Keep Source Rate", - wbStripSilenceLabel: "Auto Trim Silence", - wbDenoiseLabel: "Spectral Denoise (afftdn)", - wbOutdirLabel: "Output Location", - wbOutdirValue: "Source folder (*_processed-id.{ext})", - previewTitle: "Estimate & Output Preview", - previewSubtitle: "Engine: {title}", - metricRawSize: "Total Size", - metricEstOut: "Est. Output Size", - metricTargetLoudness: "Target Loudness", - metricSelectedCount: "Selected", - metricSelectedCountVal: "{selected} / {total}", - subListTitle: "Audio Queue (Check items and press ↵ to start)", - subListSubtitle: "{count} [[count:track|tracks]] · {bytes}", - sectionQueueTitle: "Audio Queue ({count})", - sectionModesTitle: "12 Audio Processing Modes ({count})", - actionSetActiveMode: "Set as Active Mode" + 'en-US': { + forbiddenReason: 'Output path cannot point to a protected system directory or contain path traversal', + hostRequired: 'Requires the ZTools client', + engineChecking: 'Checking audio engine...', + engineReady: 'Audio Engine Ready', + engineNeedsProvision: 'Audio Engine Download Required', + engineUnsupported: 'Audio Engine Unsupported', + btnDownloadEngine: 'Download Audio Engine', + btnPickFiles: 'Select Files', + btnPickFolder: 'Select Folder', + btnRunBatch: 'Process ({count})', + btnProcessing: 'Processing…', + tagProcessing: 'Processing', + btnCancelTask: 'Cancel Task', + msgProvisionSuccess: 'Audio engine is ready', + errProvisionFailed: 'Failed to download audio engine: {error}', + errProbeFailed: 'Failed to probe audio metadata: {error}', + errTranscodeFailed: 'Audio transcoding failed: {error}', + errCancelFailed: 'Failed to cancel task: {error}', + errTaskCancelled: 'Audio transcoding task cancelled', + errHostDisconnected: 'Not connected to ZTools client; unable to process audio', + errUnsupportedContainer: 'Unsupported output audio format: {format}', + errCannotGenUniqueName: 'Unable to generate a non-conflicting output path', + errSelectAudioFirst: 'Please check at least one audio file first', + errEngineNotReady: 'Audio engine is not ready; please download it first', + msgCancelled: 'Cancellation requested', + pickFilesTitle: 'Select Audio Files', + pickFilesFilterName: 'Audio Files', + pickFolderTitle: 'Select Folder Containing Audio Files', + noFolderSelected: 'No folder selected', + importFailedTitle: 'Import Failed', + confirmRootTitle: 'Import audio from entire drive {path}?', + confirmRootMsg: 'Scans up to 5 folder levels and imports up to 500 audio files. This may take a while.', + confirmRootAction: 'Continue Import', + dropTitle: 'Drop Audio Files or Folders', + dropSubtitle: 'Audio files within 5 folder levels will be imported', + removeBusy: 'Track is currently converting; wait until finished', + clearBusy: 'Conversion in progress; cancel or wait first', + sizeUnknown: 'Size unknown', + unknownSizeCount: ' ({count} unknown size)', + durationUnknown: 'Unknown duration', + summaryImporting: 'Importing: {dirs} [[dirs:folder|folders]] scanned, {files} [[files:file|files]] found', + summaryEmptyClient: '{engine} · No audio added · Select files, folder, or drop here', + summaryNormal: '{engine} · {last}Selected {selected}/{total} ({bytes})', + emptyNoMatch: 'No matching audio files', + emptyDefault: 'No audio added · Select files, folder, or drop here', + searchPlaceholder: 'Search audio filename or directory...', + dropdownTooltip: 'Select output audio format', + optMp3: 'MP3 (High Quality)', + optFlac: 'FLAC (Lossless)', + optWav: 'WAV (Uncompressed PCM)', + optAac: 'AAC (Efficient)', + optOgg: 'OGG (Opus)', + wbTitle: 'Audio Conversion Parameters', + wbSubtitle: 'Host media runtime · Non-destructive output', + wbFormatLabel: 'Output Format', + wbBitrateLabel: 'Audio Bitrate', + wbSampleRateLabel: 'Sample Rate', + wbChannelsLabel: 'Channels', + wbGainLabel: 'Audio Gain (dB)', + wbFadeLabel: 'Fade In / Out', + wbSpeedLabel: 'Playback Speed', + wbEngineLabel: 'Engine Status', + wbOutdirLabel: 'Output Location', + wbOutdirValue: 'Source folder (*_audio.{ext})', + bitrate320: '320 kbps', + bitrate256: '256 kbps', + bitrate192: '192 kbps', + bitrate128: '128 kbps', + bitrateLossless: 'Lossless (Auto)', + sampleKeep: 'Keep Original', + sample48k: '48 kHz', + sample44k: '44.1 kHz', + sample32k: '32 kHz', + chKeep: 'Keep Original', + chStereo: 'Stereo (2ch)', + chMono: 'Mono (1ch)', + gainNone: 'None (0 dB)', + gainPlus3: '+3 dB', + gainPlus6: '+6 dB', + gainMinus3: '-3 dB', + gainMinus6: '-6 dB', + fadeNone: 'Off', + fade1s: 'Fade In 1s / Out 1s', + fade2s: 'Fade In 2s / Out 2s', + fade3s: 'Fade In 3s / Out 3s', + speed100: 'Normal (1.0x)', + speed075: '0.75x Slower', + speed125: '1.25x Faster', + speed150: '1.5x Faster', + speed200: '2.0x Double', + previewTitle: 'Audio Batch Summary', + previewBadgeReady: '{count} selected', + previewBadgeNeedsProvision: 'Engine Required', + previewSubtitle: 'Output .{ext} · Originals stay untouched', + metricRawSize: 'Selected Size', + metricEngine: 'Engine', + metricExtensions: 'Extensions', + metricSelectedCount: 'Progress', + metricSelectedCountVal: '{done} done / {total} total', + extAudioFilters: 'Gain / Fade', + extSpeed: 'Speed', + extNone: 'Core Transcode', + subListTitle: 'Audio Queue (Check items and press Enter to convert)', + subListSubtitle: '{count} [[count:track|tracks]] · {bytes}', + sectionQueueTitle: 'Audio Queue ({count})', + tagPending: 'Pending', + tagRunning: 'Converting {percent}%', + tagDone: 'Saved {size}', + tagFailed: 'Failed', + tagCancelled: 'Cancelled', + subDone: 'Output: {name}', + subFailed: 'Failed: {error}', + subProbed: '{duration} · {meta}', + runSummary: '{completed} succeeded, {failed} failed{cancelled}', + runCancelledPart: ', {count} cancelled', + runSuccessTitle: 'Audio Conversion Completed', + runPartialTitle: 'Audio Conversion Partially Failed', + actionDownloadEngine: 'Download Audio Engine', + actionRunBatch: 'Start Conversion ({count})', + actionCancelCurrent: 'Cancel Current Task', + actionProbeSingle: 'Re-probe Audio Metadata', + actionRunSingle: 'Convert This File Only', + actionRevealInFolder: 'Reveal in File Manager', + actionPickFilesEllipsis: 'Select Files…', + actionPickFolderEllipsis: 'Select Folder…', + actionRemove: 'Remove from List', + actionSelectAll: 'Select All', + actionDeselectAll: 'Deselect All', + actionClearList: 'Clear List', + sectionList: 'Queue Actions' } - } + }, + { defaultLocale: 'en-US' } ) + export const t: typeof rawT = (key, params) => { const out = rawT(key, params) if (!out.includes('[[')) return out - return out.replace(/\[\[([A-Za-z0-9_.-]+):([^|\]]+)\|([^\]]+)\]\]/g, (_m, k: string, one: string, other: string) => { - const v = params?.[k] - const n = typeof v === 'number' ? v : Number(String(v ?? '').replace(/,/g, '')) - return n === 1 ? one : other - }) + return out.replace( + /\[\[([A-Za-z0-9_.-]+):([^|\]]+)\|([^\]]+)\]\]/g, + (_m, k: string, one: string, other: string) => { + const v = params?.[k] + const n = typeof v === 'number' ? v : Number(String(v ?? '').replace(/,/g, '')) + return n === 1 ? one : other + } + ) } diff --git a/extensions/batch-audio/src/index.ts b/extensions/batch-audio/src/index.ts index ca53af91..00f578d5 100644 --- a/extensions/batch-audio/src/index.ts +++ b/extensions/batch-audio/src/index.ts @@ -1,100 +1,150 @@ +/** + * 批量音频转换界面(标准布局三:左侧参数工作台 + 右侧音频队列) + * + * - 启动自动调用 tool_runtime_capabilities;needs_provisioning 时展示「下载音频引擎」引导并调用 tool_runtime_ensure + * - 导入文件自动调用 tool_media_probe 探测时长/采样率/声道 + * - 决策 7 特性探测门禁: + * * 增益(audioGainDb)与淡入淡出(audioFade)仅在 optionalExtensions 包含 'audio-filters' 时渲染和发送 + * * 变速(speedFactor)仅在 optionalExtensions 包含 'speed' 时渲染和发送 + * - 转换中支持通过 tool_task_cancel 实时取消当前任务 + */ + import { - List, - ActionPanel, Action, - Icon, + ActionPanel, Color, - useState, - useEffect, - useRef, - showToast, + Icon, + List, Toast, confirmAlert, - FilterBar, - useLocale + showToast, + useEffect, + useLocale, + useRef, + useState } from '@ztools/declarative-ui' import { t } from './i18n.js' +import { resolveErrorMessage } from './error-i18n.js' import { AUDIO_IMPORT_RULES, AUDIO_IMPORT_SUPPORTED_TEXT, - CapabilityActionItem, - RealAudioFileItem, - checkMergeAudioLimits, + cancelAudioTask, createAudioImportTransport, + ensureAudioEngine, + fileNameOf, formatBytes, - getAudioWorkshopModes, + formatDuration, + isRealElectronHost, openAudioFileLocation, pickAudioFolderWithConfirm, - processAudioSelection, - toAudioItem + probeAudioCapabilities, + probeAudioFiles, + processAudioBatch, + toAudioItem, + type AudioCapabilityState, + type AudioContainer, + type AudioTranscodeSettings, + type RealAudioFileItem } from './logic.js' -import { isRealElectronHost } from './native-ipc.js' import { isDeclarativeFileInputSupported } from './host-compat.js' import { - FileImportResult, - NormalizedFileInput, createImportInputProps, expandInputPaths, friendlyFileError, mergeByPath, normalizeFileInput, pickFiles, - summarizeImport + summarizeImport, + type FileImportResult, + type NormalizedFileInput } from './file-import.js' +import { subscribeLegacyFileDrop, subscribeRuntimeProgress } from './tool-runtime.js' export * from './logic.js' -const FORMAT_RATIO_MAP: Record = { - mp3_320k: 0.24, - flac_lossless: 0.58, - wav_pcm: 1.0, - aac_256k: 0.20, - m4a_aac: 0.22, - ogg_vorbis: 0.19 -} - -function getLoudnessLabels(): Record { - return { - lufs_16: t('loudness16'), - lufs_14: t('loudness14'), - lufs_23: t('loudness23'), - keep_raw: t('loudnessKeep') - } -} - export function BatchAudioCommand() { useLocale() - const workshopModes = getAudioWorkshopModes() - const loudnessLabels = getLoudnessLabels() + const inClient = isRealElectronHost() const transport = createAudioImportTransport() - const [searchText, setSearchText] = useState('') - const [activeModeId, setActiveModeId] = useState(workshopModes[0].id) - const [outputFormat, setOutputFormat] = useState<'mp3_320k' | 'flac_lossless' | 'wav_pcm' | 'aac_256k' | 'm4a_aac' | 'ogg_vorbis'>('mp3_320k') - const [loudnessTarget, setLoudnessTarget] = useState<'lufs_16' | 'lufs_14' | 'lufs_23' | 'keep_raw'>('keep_raw') - const [sampleRateMode, setSampleRateMode] = useState<'48000' | '44100' | 'source'>('source') - const [stripSilence, setStripSilence] = useState(false) - const [afftdnDenoise, setAfftdnDenoise] = useState(false) + + const [capability, setCapability] = useState({ + probeStatus: inClient ? 'needs_provisioning' : 'unsupported', + transcodeStatus: inClient ? 'needs_provisioning' : 'unsupported', + overallStatus: inClient ? 'needs_provisioning' : 'unsupported', + extensions: { audioFilters: false, speed: false } + }) + const [capChecked, setCapChecked] = useState(!inClient) + const [searchText, setSearchText] = useState('') + const [container, setContainer] = useState('mp3') + const [bitrateKbps, setBitrateKbps] = useState('320') + const [sampleRateHz, setSampleRateHz] = useState('keep') + const [channels, setChannels] = useState('keep') + const [gainDb, setGainDb] = useState('0') + const [fadeSec, setFadeSec] = useState('0') + const [speedFactor, setSpeedFactor] = useState('1') const [files, setFiles] = useState([]) const [checkedIds, setCheckedIds] = useState([]) - const [isImporting, setIsImporting] = useState(false) + const [isImporting, setIsImporting] = useState(false) const [importProgress, setImportProgress] = useState<{ visitedDirs: number; matchedFiles: number } | null>(null) - const processing = useRef(false) - const [isProcessing, setIsProcessing] = useState(false) - const [runningIds, setRunningIds] = useState([]) - const [lastResult, setLastResult] = useState('') - - const importBatchRef = useRef(0) + const [isProcessing, setIsProcessing] = useState(false) + const [isProvisioning, setIsProvisioning] = useState(false) + const [runningItemId, setRunningItemId] = useState(null) + const [lastResult, setLastResult] = useState('') + + const mountedRef = useRef(true) + const processingRef = useRef(false) + const stopRequestedRef = useRef(false) + const activeTaskIdRef = useRef(null) + const activeItemIdRef = useRef(null) + const importBatchRef = useRef(0) const importAbortRef = useRef(null) - const filesRef = useRef(files) + const filesRef = useRef([]) filesRef.current = files + const capabilityRef = useRef(capability) + capabilityRef.current = capability - async function runAudioImport( + const refreshCapabilities = async () => { + if (!inClient) { + setCapChecked(true) + return + } + const state = await probeAudioCapabilities() + if (!mountedRef.current) return + capabilityRef.current = state + setCapability(state) + setCapChecked(true) + } + + const probeAddedItems = async (items: readonly RealAudioFileItem[]) => { + if (!inClient || items.length === 0 || capabilityRef.current.probeStatus !== 'ready') return + const res = await probeAudioFiles(items.map((item) => item.path)) + if (!mountedRef.current || !res.ok) return + const probeMap = new Map() + items.forEach((item, index) => { + const meta = res.items[index] + if (meta) probeMap.set(item.id, meta) + }) + if (probeMap.size === 0) return + const next = filesRef.current.map((item) => { + const meta = probeMap.get(item.id) + if (!meta) return item + return { + ...item, + probe: meta, + ...(item.sizeBytes === null && meta.sizeBytes > 0 ? { sizeBytes: meta.sizeBytes } : {}) + } + }) + filesRef.current = next + setFiles(next) + } + + const runAudioImport = async ( loader: ( signal: AbortSignal, onProgress: (progress: { visitedDirs: number; matchedFiles: number }) => void ) => Promise - ) { + ) => { importAbortRef.current?.abort() const controller = new AbortController() importAbortRef.current = controller @@ -103,25 +153,26 @@ export function BatchAudioCommand() { setImportProgress(null) try { const result = await loader(controller.signal, (p) => { - if (batch === importBatchRef.current) setImportProgress(p) + if (mountedRef.current && batch === importBatchRef.current) setImportProgress(p) }) - if (batch !== importBatchRef.current) return + if (!mountedRef.current || batch !== importBatchRef.current) return const incoming = result.files.map(toAudioItem) - const { merged, added, duplicates } = mergeByPath(filesRef.current, incoming, f => f.path) + const { merged, added, duplicates } = mergeByPath(filesRef.current, incoming, (f) => f.path) if (added.length > 0) { filesRef.current = merged setFiles(merged) - setCheckedIds(prev => Array.from(new Set([...prev, ...added.map(f => f.id)]))) + setCheckedIds((prev) => Array.from(new Set([...prev, ...added.map((f) => f.id)]))) + void probeAddedItems(added) } const tip = summarizeImport(result, { added: added.length, duplicates }, AUDIO_IMPORT_SUPPORTED_TEXT) if (tip) { void showToast({ style: tip.ok ? Toast.Style.Success : Toast.Style.Failure, title: tip.title, message: tip.message }) } } catch (err) { - if (batch !== importBatchRef.current) return + if (!mountedRef.current || batch !== importBatchRef.current) return void showToast({ style: Toast.Style.Failure, title: t('importFailedTitle'), message: friendlyFileError(err) }) } finally { - if (batch === importBatchRef.current) { + if (mountedRef.current && batch === importBatchRef.current) { importAbortRef.current = null setIsImporting(false) setImportProgress(null) @@ -129,17 +180,17 @@ export function BatchAudioCommand() { } } - function handlePickAudioFiles() { + const handlePickAudioFiles = () => { void runAudioImport(() => pickFiles(transport, AUDIO_IMPORT_RULES, { title: t('pickFilesTitle'), filterName: t('pickFilesFilterName') }) ) } - function handlePickAudioFolder() { + const handlePickAudioFolder = () => { void runAudioImport((signal, onProgress) => pickAudioFolderWithConfirm( transport, - folderPath => + (folderPath) => confirmAlert({ title: t('confirmRootTitle', { path: folderPath }), message: t('confirmRootMsg'), @@ -150,7 +201,7 @@ export function BatchAudioCommand() { ) } - function handleAudioFileInput(input: NormalizedFileInput) { + const handleAudioFileInput = (input: NormalizedFileInput) => { void runAudioImport((signal, onProgress) => expandInputPaths(transport, input.paths, AUDIO_IMPORT_RULES, { knownDirectories: input.directories, @@ -160,130 +211,170 @@ export function BatchAudioCommand() { ) } + const updateActiveItemProgress = (percent: number) => { + const itemId = activeItemIdRef.current + if (!itemId) return + const clamped = Math.max(0, Math.min(100, Math.round(percent))) + const next = filesRef.current.map((entry) => + entry.id === itemId ? { ...entry, progressPercent: clamped } : entry + ) + filesRef.current = next + setFiles(next) + } + useEffect(() => { - let disposeDrop: (() => void) | undefined - if (!isDeclarativeFileInputSupported()) { - const w = typeof window !== 'undefined' ? (window as { ztools?: { events?: { on?: (event: string, cb: (env: unknown) => void) => (() => void) | void; off?: (event: string, cb: (env: unknown) => void) => void } } }) : null - const eventsApi = w?.ztools?.events - if (eventsApi && typeof eventsApi.on === 'function') { - const onDrop = (envelope: unknown) => { + mountedRef.current = true + void refreshCapabilities() + const unsubProgress = subscribeRuntimeProgress((event) => { + if (!mountedRef.current || event.taskId !== activeTaskIdRef.current) return + if (typeof event.percent === 'number' && Number.isFinite(event.percent)) { + updateActiveItemProgress(event.percent) + } + }) + const disposeDrop = isDeclarativeFileInputSupported() + ? undefined + : subscribeLegacyFileDrop((envelope) => { const input = normalizeFileInput(envelope) if (input.paths.length > 0) handleAudioFileInput(input) - } - const off = eventsApi.on('plugin_files_dropped', onDrop) - disposeDrop = () => { - if (typeof off === 'function') off() - else if (typeof eventsApi.off === 'function') eventsApi.off('plugin_files_dropped', onDrop) - } - } - } + }) return () => { + mountedRef.current = false importBatchRef.current += 1 importAbortRef.current?.abort() + unsubProgress() disposeDrop?.() } }, []) - const fileInputProps = createImportInputProps(handleAudioFileInput, { - dropTitle: t('dropTitle'), - dropSubtitle: t('dropSubtitle') - }) + const handleDownloadEngine = async () => { + if (!inClient || isProvisioning) return + setIsProvisioning(true) + try { + const res = await ensureAudioEngine() + if (!mountedRef.current) return + await showToast({ style: res.ok ? Toast.Style.Success : Toast.Style.Failure, title: res.message }) + await refreshCapabilities() + if (res.ok && filesRef.current.length > 0) { + const unprobed = filesRef.current.filter((item) => !item.probe) + if (unprobed.length > 0) void probeAddedItems(unprobed) + } + } finally { + if (mountedRef.current) setIsProvisioning(false) + } + } - const activePreset = workshopModes.find(p => p.id === activeModeId) || workshopModes[0] - const ratio = FORMAT_RATIO_MAP[outputFormat] ?? 0.24 - const outExt = outputFormat.split('_')[0] || 'mp3' + const buildCurrentSettings = (): AudioTranscodeSettings => { + const isLossless = container === 'flac' || container === 'wav' + return { + container, + ...(!isLossless ? { audioBitrateKbps: Number(bitrateKbps) } : {}), + ...(sampleRateHz !== 'keep' ? { audioSampleRateHz: Number(sampleRateHz) } : {}), + ...(channels !== 'keep' ? { audioChannels: Number(channels) } : {}), + ...(capability.extensions.audioFilters && Number(gainDb) !== 0 ? { audioGainDb: Number(gainDb) } : {}), + ...(capability.extensions.audioFilters && Number(fadeSec) > 0 ? { fadeSec: Number(fadeSec) } : {}), + ...(capability.extensions.speed && Number(speedFactor) !== 1 ? { speedFactor: Number(speedFactor) } : {}) + } + } - function selectPreset(id: string) { - setActiveModeId(id) - const selected = workshopModes.find(mode => mode.id === id) - if (selected?.params.format === 'flac') setOutputFormat('flac_lossless') - if (selected?.params.format === 'mp3') setOutputFormat('mp3_320k') + const handleCancelCurrentTask = async () => { + stopRequestedRef.current = true + const taskId = activeTaskIdRef.current + if (!taskId) return + const res = await cancelAudioTask(taskId) + if (!mountedRef.current) return + await showToast({ + style: res.ok ? Toast.Style.Success : Toast.Style.Failure, + title: res.ok ? t('msgCancelled') : resolveErrorMessage(res, t('errTaskCancelled')) + }) } - async function runFiles(preset: CapabilityActionItem, selected: RealAudioFileItem[]) { - if (processing.current) return - if (!selected.length) { - await showToast({ style: Toast.Style.Failure, title: t('selectAudioFirst') }) + const runConversion = async (targets: RealAudioFileItem[]) => { + if (processingRef.current) return + if (!inClient) { + await showToast({ style: Toast.Style.Failure, title: t('errHostDisconnected') }) return } - if (preset.method === 'BatchMergeAudio') { - if (selected.length < 2) { - await showToast({ style: Toast.Style.Failure, title: t('mergeNeedTwo') }) - return - } - const limitErr = checkMergeAudioLimits(selected) - if (limitErr) { - await showToast({ style: Toast.Style.Failure, title: limitErr }) - return - } + if (capabilityRef.current.overallStatus === 'needs_provisioning') { + await handleDownloadEngine() + return + } + if (capabilityRef.current.overallStatus !== 'ready') { + await showToast({ style: Toast.Style.Failure, title: t('errEngineNotReady') }) + return } - processing.current = true + if (targets.length === 0) { + await showToast({ style: Toast.Style.Failure, title: t('errSelectAudioFirst') }) + return + } + + processingRef.current = true + stopRequestedRef.current = false setIsProcessing(true) try { - const accepted = await confirmAlert({ - title: t('confirmRunTitle', { count: selected.length, tag: preset.tag }), - message: t('confirmRunMsg', { ext: outExt.toUpperCase() }), - primaryAction: { title: t('confirmRunAction'), style: 'default' } - }) - if (!accepted) return - const result = await processAudioSelection( - preset.method, - { - ...preset.params, - format: outExt, - bitrate: outExt === 'mp3' ? '320k' : '256k', - loudnessTarget, - sampleRateMode, - stripSilence, - afftdnDenoise + const settings = buildCurrentSettings() + const result = await processAudioBatch(targets, settings, capabilityRef.current.extensions, { + shouldSkip: (id) => !filesRef.current.some((item) => item.id === id), + shouldStop: () => stopRequestedRef.current, + onStart: (id, taskId) => { + activeItemIdRef.current = id + activeTaskIdRef.current = taskId + setRunningItemId(id) + const next = filesRef.current.map((item) => + item.id === id ? { ...item, progressPercent: 0 } : item + ) + filesRef.current = next + setFiles(next) }, - selected, - undefined, - { - shouldSkip: id => !filesRef.current.some(item => item.id === id), - onStart: ids => setRunningIds(ids), - onDone: ids => setRunningIds(prev => prev.filter(id => !ids.includes(id))) + onDone: (id, outcome) => { + if (activeItemIdRef.current === id) { + activeItemIdRef.current = null + activeTaskIdRef.current = null + } + setRunningItemId((curr) => (curr === id ? null : curr)) + const next = filesRef.current.map((item) => + item.id === id ? { ...item, outcome, progressPercent: undefined } : item + ) + filesRef.current = next + setFiles(next) } - ) + }) + if (!mountedRef.current) return const summary = t('runSummary', { completed: result.completed, failed: result.failed, - outputs: result.outputs.length + cancelled: result.cancelled > 0 ? t('runCancelledPart', { count: result.cancelled }) : '' }) setLastResult(summary) await showToast({ - style: result.failed ? Toast.Style.Failure : Toast.Style.Success, - title: result.failed ? t('runPartialTitle') : t('runSuccessTitle'), - message: result.errors.length ? `${summary}; ${result.errors[0]}` : summary + style: result.failed === 0 && result.cancelled === 0 ? Toast.Style.Success : Toast.Style.Failure, + title: result.failed === 0 && result.cancelled === 0 ? t('runSuccessTitle') : t('runPartialTitle'), + message: result.errors[0] ? `${summary}; ${result.errors[0]}` : summary }) } finally { - setRunningIds([]) - processing.current = false - setIsProcessing(false) + activeTaskIdRef.current = null + activeItemIdRef.current = null + processingRef.current = false + stopRequestedRef.current = false + if (mountedRef.current) { + setRunningItemId(null) + setIsProcessing(false) + } } } - async function handleRunBatchChecked() { - await runFiles(activePreset, files.filter(file => checkedIds.includes(file.id))) - } - - async function handleRunPreset(preset: CapabilityActionItem, targetFile: RealAudioFileItem) { - await runFiles(preset, [targetFile]) - } - - function handleRemoveItem(file: RealAudioFileItem) { - if (runningIds.includes(file.id)) { + const handleRemoveItem = (file: RealAudioFileItem) => { + if (runningItemId === file.id) { void showToast({ style: Toast.Style.Failure, title: t('removeBusy') }) return } - const next = filesRef.current.filter(item => item.id !== file.id) + const next = filesRef.current.filter((item) => item.id !== file.id) filesRef.current = next setFiles(next) - setCheckedIds(prev => prev.filter(id => id !== file.id)) + setCheckedIds((prev) => prev.filter((id) => id !== file.id)) } - function handleClearList() { - if (processing.current) { + const handleClearList = () => { + if (processingRef.current) { void showToast({ style: Toast.Style.Failure, title: t('clearBusy') }) return } @@ -298,34 +389,47 @@ export function BatchAudioCommand() { setLastResult('') } - const selectedFiles = files.filter(f => checkedIds.includes(f.id)) + const fileInputProps = createImportInputProps(handleAudioFileInput, { + dropTitle: t('dropTitle'), + dropSubtitle: t('dropSubtitle') + }) + + const q = searchText.trim().toLowerCase() + const filteredFiles = files.filter( + (f) => !q || f.name.toLowerCase().includes(q) || f.path.toLowerCase().includes(q) + ) + const selectedFiles = files.filter((f) => checkedIds.includes(f.id)) const totalKnownBytes = selectedFiles.reduce((s, f) => s + (f.sizeBytes ?? 0), 0) - const selectedUnknownCount = selectedFiles.filter(f => f.sizeBytes === null).length - const estimatedOutBytes = Math.round(totalKnownBytes * ratio) + const selectedUnknownCount = selectedFiles.filter((f) => f.sizeBytes === null).length const selectedBytesText = selectedFiles.length > 0 && selectedUnknownCount === selectedFiles.length ? t('sizeUnknown') : `${formatBytes(totalKnownBytes)}${selectedUnknownCount > 0 ? t('unknownSizeCount', { count: selectedUnknownCount }) : ''}` + const doneCount = files.filter((f) => f.outcome?.status === 'done').length + const allFilteredChecked = filteredFiles.length > 0 && filteredFiles.every((f) => checkedIds.includes(f.id)) - const q = searchText.trim().toLowerCase() - const filteredFiles = files.filter( - f => !q || f.name.toLowerCase().includes(q) || f.path.toLowerCase().includes(q) - ) - const filteredPresets = workshopModes.filter( - p => !q || p.title.toLowerCase().includes(q) || p.subtitle.toLowerCase().includes(q) || p.tag.toLowerCase().includes(q) - ) - - const allFilteredChecked = filteredFiles.length > 0 && filteredFiles.every(f => checkedIds.includes(f.id)) - - function toggleAllFiltered() { - const visibleIds = new Set(filteredFiles.map(f => f.id)) - setCheckedIds(prev => - allFilteredChecked - ? prev.filter(id => !visibleIds.has(id)) - : Array.from(new Set([...prev, ...visibleIds])) + const toggleAllFiltered = () => { + const visibleIds = new Set(filteredFiles.map((f) => f.id)) + setCheckedIds((prev) => + allFilteredChecked ? prev.filter((id) => !visibleIds.has(id)) : Array.from(new Set([...prev, ...visibleIds])) ) } + const engineStatusText = !capChecked + ? t('engineChecking') + : capability.overallStatus === 'ready' + ? t('engineReady') + : capability.overallStatus === 'needs_provisioning' + ? t('engineNeedsProvision') + : t('engineUnsupported') + + const enabledExtensionsText = (() => { + const parts: string[] = [] + if (capability.extensions.audioFilters) parts.push(t('extAudioFilters')) + if (capability.extensions.speed) parts.push(t('extSpeed')) + return parts.length > 0 ? parts.join(' · ') : t('extNone') + })() + const pickFilesAction = () => Action({ title: t('actionPickFilesEllipsis'), @@ -333,6 +437,7 @@ export function BatchAudioCommand() { shortcut: { modifiers: ['ctrl'], key: 'o' }, onAction: handlePickAudioFiles }) + const pickFolderAction = () => Action({ title: t('actionPickFolderEllipsis'), @@ -341,230 +446,409 @@ export function BatchAudioCommand() { onAction: handlePickAudioFolder }) - const maxAudioBytes = Math.max(1, ...filteredFiles.map(f => f.sizeBytes ?? 0)) - const rightQueueItems = filteredFiles.map(f => { + const rightQueueItems = filteredFiles.map((f) => { const isChecked = checkedIds.includes(f.id) - const isItemRunning = runningIds.includes(f.id) - const hasSize = f.sizeBytes !== null - const estOut = hasSize ? Math.round(f.sizeBytes! * ratio) : null + const isItemRunning = runningItemId === f.id const accessories: Array> = [] - if (hasSize) { - const volRatio = Math.max(10, Math.min(100, Math.round((f.sizeBytes! / maxAudioBytes) * 100))) - accessories.push({ progress: { value: volRatio } }) - accessories.push({ tag: { value: `→ .${outExt.toUpperCase()} ~${formatBytes(estOut!)}` } }) - accessories.push({ text: formatBytes(f.sizeBytes!) }) + + if (isItemRunning) { + const pct = typeof f.progressPercent === 'number' ? f.progressPercent : 0 + accessories.push({ progress: pct / 100 }) + accessories.push({ tag: { value: pct > 0 ? t('tagRunning', { percent: pct }) : t('tagProcessing') } }) + } else if (f.outcome?.status === 'done') { + accessories.push({ tag: { value: t('tagDone', { size: formatBytes(f.outcome.outputBytes) }) } }) + } else if (f.outcome?.status === 'failed') { + accessories.push({ tag: { value: t('tagFailed'), color: Color.Red } }) + } else if (f.outcome?.status === 'cancelled') { + accessories.push({ tag: { value: t('tagCancelled') } }) } else { - accessories.push({ tag: { value: `→ .${outExt.toUpperCase()}` } }) - accessories.push({ text: t('sizeUnknown') }) + accessories.push({ tag: { value: t('tagPending') } }) + } + accessories.push({ text: f.sizeBytes === null ? t('sizeUnknown') : formatBytes(f.sizeBytes) }) + + let subtitle = f.parentDir + if (f.outcome?.status === 'done') { + subtitle = t('subDone', { name: fileNameOf(f.outcome.outputPath) }) + } else if (f.outcome?.status === 'failed') { + subtitle = t('subFailed', { error: f.outcome.error }) + } else if (f.probe) { + const metaParts = [ + f.probe.codec?.toUpperCase(), + f.probe.sampleRateHz ? `${(f.probe.sampleRateHz / 1000).toFixed(1)}kHz` : '', + f.probe.channels ? `${f.probe.channels}ch` : '' + ].filter(Boolean) + subtitle = t('subProbed', { + duration: formatDuration(f.probe.durationSec), + meta: metaParts.join(' · ') || f.parentDir + }) } - const actionChildren: Array | ReturnType> = [ - Action({ - title: t('actionRunBatch', { count: selectedFiles.length }), - icon: Icon.Bolt, - onAction: handleRunBatchChecked - }), - Action({ - title: t('actionRevealInFolder'), - icon: Icon.Folder, - shortcut: { modifiers: ['ctrl'], key: 'enter' }, - onAction: () => { - void openAudioFileLocation(f.path) - } - }), - Action({ - title: t('actionRunSingle', { tag: activePreset.tag }), - icon: Icon.Play, - onAction: () => handleRunPreset(activePreset, f) - }), - ActionPanel.Section({ - title: t('sectionList'), - children: [ - ...(isItemRunning - ? [] - : [ - Action({ - title: t('actionRemove'), - icon: Icon.Minus, - shortcut: { modifiers: ['ctrl'], key: 'backspace' }, - onAction: () => handleRemoveItem(f) - }) - ]), - pickFilesAction(), - pickFolderAction(), - Action({ - title: allFilteredChecked ? t('actionDeselectAll') : t('actionSelectAll'), - icon: Icon.CheckCircle, - shortcut: { modifiers: ['ctrl'], key: 'a' }, - onAction: toggleAllFiltered - }), - Action({ - title: t('actionClearList'), - icon: Icon.Trash, - style: Action.Style.Destructive, - shortcut: { modifiers: ['ctrl', 'shift'], key: 'backspace' }, - onAction: handleClearList + const revealTarget = f.outcome?.status === 'done' ? f.outcome.outputPath : f.path + const primaryAction = isProcessing + ? Action({ + title: t('actionCancelCurrent'), + icon: Icon.Stop, + style: Action.Style.Destructive, + onAction: handleCancelCurrentTask + }) + : capability.overallStatus === 'needs_provisioning' + ? Action({ + title: t('actionDownloadEngine'), + icon: Icon.Download, + onAction: handleDownloadEngine + }) + : Action({ + title: t('actionRunBatch', { count: selectedFiles.length }), + icon: Icon.Bolt, + onAction: () => runConversion(selectedFiles) }) - ] - }) - ] return List.Item({ id: f.id, title: f.name, - subtitle: estOut !== null - ? `${f.parentDir} · ${f.extension.toUpperCase()} → .${outExt.toUpperCase()} (~${formatBytes(estOut)})` - : `${f.parentDir} · ${f.extension.toUpperCase()} → .${outExt.toUpperCase()}`, + subtitle, checkable: true, checked: isChecked, - onCheckChange: c => { - setCheckedIds(prev => (c ? Array.from(new Set([...prev, f.id])) : prev.filter(id => id !== f.id))) - }, - icon: { - source: Icon.Music + onCheckChange: (c) => { + setCheckedIds((prev) => (c ? Array.from(new Set([...prev, f.id])) : prev.filter((id) => id !== f.id))) }, + icon: { source: Icon.Music }, accessories, actions: ActionPanel({ title: f.name, - children: actionChildren + children: [ + primaryAction, + Action({ + title: t('actionRevealInFolder'), + icon: Icon.Folder, + shortcut: { modifiers: ['ctrl'], key: 'enter' }, + onAction: () => { + void openAudioFileLocation(revealTarget) + } + }), + ...(!isProcessing + ? [ + Action({ + title: t('actionRunSingle'), + icon: Icon.Play, + onAction: () => runConversion([f]) + }), + Action({ + title: t('actionProbeSingle'), + icon: Icon.Info, + onAction: () => probeAddedItems([f]) + }) + ] + : []), + ActionPanel.Section({ + title: t('sectionList'), + children: [ + ...(isItemRunning + ? [] + : [ + Action({ + title: t('actionRemove'), + icon: Icon.Minus, + shortcut: { modifiers: ['ctrl'], key: 'backspace' }, + onAction: () => handleRemoveItem(f) + }) + ]), + pickFilesAction(), + pickFolderAction(), + Action({ + title: allFilteredChecked ? t('actionDeselectAll') : t('actionSelectAll'), + icon: Icon.CheckCircle, + shortcut: { modifiers: ['ctrl'], key: 'a' }, + onAction: toggleAllFiltered + }), + Action({ + title: t('actionClearList'), + icon: Icon.Trash, + style: Action.Style.Destructive, + shortcut: { modifiers: ['ctrl', 'shift'], key: 'backspace' }, + onAction: handleClearList + }) + ] + }) + ] }) }) }) - const inClient = isRealElectronHost() + const isLossless = container === 'flac' || container === 'wav' + + // 构建左侧参数面板字段(严格按 optionalExtensions 探测动态展示高级滤镜与变速参数) + const workbenchFields: Array> = [ + { + id: 'wb-output-format', + label: t('wbFormatLabel'), + type: 'select', + value: container, + onChange: (val: unknown) => setContainer(String(val) as AudioContainer), + options: [ + { label: t('optMp3'), value: 'mp3' }, + { label: t('optFlac'), value: 'flac' }, + { label: t('optWav'), value: 'wav' }, + { label: t('optAac'), value: 'aac' }, + { label: t('optOgg'), value: 'ogg' } + ] + }, + isLossless + ? { + id: 'wb-bitrate', + label: t('wbBitrateLabel'), + type: 'info', + value: t('bitrateLossless') + } + : { + id: 'wb-bitrate', + label: t('wbBitrateLabel'), + type: 'select', + value: bitrateKbps, + onChange: (val: unknown) => setBitrateKbps(String(val)), + options: [ + { label: t('bitrate320'), value: '320' }, + { label: t('bitrate256'), value: '256' }, + { label: t('bitrate192'), value: '192' }, + { label: t('bitrate128'), value: '128' } + ] + }, + { + id: 'wb-samplerate', + label: t('wbSampleRateLabel'), + type: 'select', + value: sampleRateHz, + onChange: (val: unknown) => setSampleRateHz(String(val)), + options: [ + { label: t('sampleKeep'), value: 'keep' }, + { label: t('sample48k'), value: '48000' }, + { label: t('sample44k'), value: '44100' }, + { label: t('sample32k'), value: '32000' } + ] + }, + { + id: 'wb-channels', + label: t('wbChannelsLabel'), + type: 'select', + value: channels, + onChange: (val: unknown) => setChannels(String(val)), + options: [ + { label: t('chKeep'), value: 'keep' }, + { label: t('chStereo'), value: '2' }, + { label: t('chMono'), value: '1' } + ] + } + ] + + // 决策 7:仅宿主上报 'audio-filters' 时才在 UI 展示增益与淡入淡出控件 + if (capability.extensions.audioFilters) { + workbenchFields.push( + { + id: 'wb-audio-gain', + label: t('wbGainLabel'), + type: 'select', + value: gainDb, + onChange: (val: unknown) => setGainDb(String(val)), + options: [ + { label: t('gainNone'), value: '0' }, + { label: t('gainPlus3'), value: '3' }, + { label: t('gainPlus6'), value: '6' }, + { label: t('gainMinus3'), value: '-3' }, + { label: t('gainMinus6'), value: '-6' } + ] + }, + { + id: 'wb-audio-fade', + label: t('wbFadeLabel'), + type: 'select', + value: fadeSec, + onChange: (val: unknown) => setFadeSec(String(val)), + options: [ + { label: t('fadeNone'), value: '0' }, + { label: t('fade1s'), value: '1' }, + { label: t('fade2s'), value: '2' }, + { label: t('fade3s'), value: '3' } + ] + } + ) + } + + // 决策 7:仅宿主上报 'speed' 时才在 UI 展示变速控件 + if (capability.extensions.speed) { + workbenchFields.push({ + id: 'wb-speed', + label: t('wbSpeedLabel'), + type: 'select', + value: speedFactor, + onChange: (val: unknown) => setSpeedFactor(String(val)), + options: [ + { label: t('speed100'), value: '1' }, + { label: t('speed075'), value: '0.75' }, + { label: t('speed125'), value: '1.25' }, + { label: t('speed150'), value: '1.5' }, + { label: t('speed200'), value: '2' } + ] + }) + } + + workbenchFields.push( + { + id: 'wb-engine', + label: t('wbEngineLabel'), + type: 'info', + value: engineStatusText + }, + { + id: 'wb-outdir', + label: t('wbOutdirLabel'), + type: 'info', + value: t('wbOutdirValue', { ext: container }) + } + ) + const summaryText = isImporting ? t('summaryImporting', { dirs: importProgress?.visitedDirs ?? 0, files: importProgress?.matchedFiles ?? 0 }) - : files.length === 0 - ? inClient - ? t('summaryEmptyClient') - : t('hostRequired') - : t('summaryNormal', { - last: lastResult ? `${lastResult} · ` : '', - selected: selectedFiles.length, - total: files.length, - bytes: selectedBytesText - }) + : !inClient + ? t('hostRequired') + : files.length === 0 + ? t('summaryEmptyClient', { engine: engineStatusText }) + : t('summaryNormal', { + engine: engineStatusText, + last: lastResult ? `${lastResult} · ` : '', + selected: selectedFiles.length, + total: files.length, + bytes: selectedBytesText + }) - const emptyText = !inClient - ? t('hostRequired') - : q && files.length > 0 - ? t('emptyNoMatch') - : t('emptyDefault') + const filterBarActions = isProcessing + ? [ + { + id: 'run-batch', + label: t('btnProcessing'), + title: t('btnProcessing'), + style: 'primary' as const, + disabled: true, + onAction: () => {} + }, + { + id: 'cancel-task', + label: t('btnCancelTask'), + title: t('btnCancelTask'), + style: 'secondary' as const, + onAction: () => { + void handleCancelCurrentTask() + } + } + ] + : capability.overallStatus === 'needs_provisioning' + ? [ + { + id: 'download-engine', + label: t('btnDownloadEngine'), + title: t('btnDownloadEngine'), + style: 'primary' as const, + onAction: () => { + void handleDownloadEngine() + } + }, + { + id: 'pick-files', + label: t('btnPickFiles'), + title: t('btnPickFiles'), + style: 'secondary' as const, + onAction: handlePickAudioFiles + } + ] + : selectedFiles.length > 0 + ? [ + { + id: 'pick-files', + label: t('btnPickFiles'), + title: t('btnPickFiles'), + style: 'secondary' as const, + onAction: handlePickAudioFiles + }, + { + id: 'run-batch', + label: t('btnRunBatch', { count: selectedFiles.length }), + title: t('btnRunBatch', { count: selectedFiles.length }), + style: 'primary' as const, + disabled: isProcessing, + onAction: () => { + void runConversion(selectedFiles) + } + } + ] + : [ + { + id: 'pick-files', + label: t('btnPickFiles'), + title: t('btnPickFiles'), + style: 'secondary' as const, + onAction: handlePickAudioFiles + }, + { + id: 'pick-folder', + label: t('btnPickFolder'), + title: t('btnPickFolder'), + style: 'secondary' as const, + onAction: handlePickAudioFolder + } + ] return List({ ...fileInputProps, searchBarPlaceholder: t('searchPlaceholder'), onSearchTextChange: setSearchText, isShowingDetail: false, - isLoading: isImporting || isProcessing, + isLoading: isImporting || isProcessing || isProvisioning, actions: ActionPanel({ - title: t('queueActionsTitle'), - children: [pickFilesAction(), pickFolderAction()] + children: [ + ...(capability.overallStatus === 'needs_provisioning' + ? [ + Action({ + title: t('actionDownloadEngine'), + icon: Icon.Download, + onAction: handleDownloadEngine + }) + ] + : []), + pickFilesAction(), + pickFolderAction() + ] }), searchBarAccessory: List.Dropdown({ tooltip: t('dropdownTooltip'), - value: activeModeId, - onChange: val => selectPreset(val), - children: workshopModes.map(m => - List.Dropdown.Item({ - title: t('dropdownItemTitle', { tag: m.tag }), - value: m.id - }) - ) - }), - filterBar: FilterBar({ - summaryText, - actions: [ - { - id: 'pick-files', - label: t('btnPickFiles'), - title: t('btnPickFiles'), - style: 'secondary', - onAction: handlePickAudioFiles - }, - { - id: 'pick-folder', - label: t('btnPickFolder'), - title: t('btnPickFolder'), - style: 'secondary', - onAction: handlePickAudioFolder - } + value: container, + onChange: (val) => setContainer(val as AudioContainer), + children: [ + List.Dropdown.Item({ title: t('optMp3'), value: 'mp3' }), + List.Dropdown.Item({ title: t('optFlac'), value: 'flac' }), + List.Dropdown.Item({ title: t('optWav'), value: 'wav' }), + List.Dropdown.Item({ title: t('optAac'), value: 'aac' }), + List.Dropdown.Item({ title: t('optOgg'), value: 'ogg' }) ] }), + filterBar: { + summaryText, + actions: filterBarActions + }, workbenchPanel: { title: t('wbTitle'), - subtitle: activePreset.tag, - fields: [ - { - id: 'wb-output-format', - label: t('wbFormatLabel'), - type: 'select', - value: outputFormat, - onChange: val => setOutputFormat(val as typeof outputFormat), - options: [ - { label: t('optMp3'), value: 'mp3_320k' }, - { label: t('optFlac'), value: 'flac_lossless' }, - { label: t('optWav'), value: 'wav_pcm' }, - { label: t('optAac'), value: 'aac_256k' }, - { label: t('optM4a'), value: 'm4a_aac' }, - { label: t('optOgg'), value: 'ogg_vorbis' } - ] - }, - { - id: 'wb-loudness', - label: t('wbLoudnessLabel'), - type: 'select', - value: loudnessTarget, - onChange: val => setLoudnessTarget(val as typeof loudnessTarget), - options: [ - { label: t('optLufs16'), value: 'lufs_16' }, - { label: t('optLufs14'), value: 'lufs_14' }, - { label: t('optLufs23'), value: 'lufs_23' }, - { label: t('optKeepRaw'), value: 'keep_raw' } - ] - }, - { - id: 'wb-samplerate', - label: t('wbSampleRateLabel'), - type: 'select', - value: sampleRateMode, - onChange: val => setSampleRateMode(val as typeof sampleRateMode), - options: [ - { label: t('opt48k'), value: '48000' }, - { label: t('opt44k'), value: '44100' }, - { label: t('optSourceRate'), value: 'source' } - ] - }, - { - id: 'wb-strip-silence', - label: t('wbStripSilenceLabel'), - type: 'toggle', - value: stripSilence, - onChange: val => setStripSilence(Boolean(val)) - }, - { - id: 'wb-afftdn', - label: t('wbDenoiseLabel'), - type: 'toggle', - value: afftdnDenoise, - onChange: val => setAfftdnDenoise(Boolean(val)) - }, - { - id: 'wb-outdir', - label: t('wbOutdirLabel'), - type: 'info', - value: t('wbOutdirValue', { ext: outExt }) - } - ], + subtitle: t('wbSubtitle'), + fields: workbenchFields as never, previewCard: { title: t('previewTitle'), - badge: loudnessLabels[loudnessTarget] || '-16 LUFS', - subtitle: t('previewSubtitle', { title: activePreset.title }), + badge: + capability.overallStatus === 'needs_provisioning' + ? t('previewBadgeNeedsProvision') + : t('previewBadgeReady', { count: selectedFiles.length }), + subtitle: t('previewSubtitle', { ext: container.toUpperCase() }), metrics: [ { label: t('metricRawSize'), value: selectedBytesText }, - { label: t('metricEstOut'), value: selectedUnknownCount === selectedFiles.length && selectedFiles.length > 0 ? '—' : `~${formatBytes(estimatedOutBytes)}` }, - { label: t('metricTargetLoudness'), value: loudnessLabels[loudnessTarget] || '-16 LUFS' }, - { label: t('metricSelectedCount'), value: t('metricSelectedCountVal', { selected: selectedFiles.length, total: files.length }) } + { label: t('metricEngine'), value: engineStatusText }, + { label: t('metricExtensions'), value: enabledExtensionsText }, + { label: t('metricSelectedCount'), value: t('metricSelectedCountVal', { done: doneCount, total: files.length }) } ] } }, @@ -574,51 +858,20 @@ export function BatchAudioCommand() { checkable: filteredFiles.length > 0, checked: allFilteredChecked ? true - : filteredFiles.some(f => checkedIds.includes(f.id)) + : filteredFiles.some((f) => checkedIds.includes(f.id)) ? 'indeterminate' : false, onCheckChange: () => toggleAllFiltered(), - emptyText, + emptyText: !inClient ? t('hostRequired') : q && files.length > 0 ? t('emptyNoMatch') : t('emptyDefault'), items: rightQueueItems }, children: [ List.Section({ title: t('sectionQueueTitle', { count: filteredFiles.length }), children: rightQueueItems - }), - List.Section({ - title: t('sectionModesTitle', { count: filteredPresets.length }), - children: filteredPresets.map(p => - List.Item({ - id: p.id, - title: p.title, - subtitle: p.subtitle, - icon: { - source: Icon.SpeakerHigh, - tintColor: Color.SecondaryText - }, - accessories: [ - { tag: { value: p.tag } }, - { text: p.method } - ], - actions: ActionPanel({ - title: p.title, - children: [ - Action({ - title: t('actionSetActiveMode'), - icon: Icon.CheckCircle, - onAction: () => { - selectPreset(p.id) - } - }) - ] - }) - }) - ) }) ] }) } export default BatchAudioCommand - diff --git a/extensions/batch-audio/src/logic.ts b/extensions/batch-audio/src/logic.ts index 34d44b6b..871d2f1b 100644 --- a/extensions/batch-audio/src/logic.ts +++ b/extensions/batch-audio/src/logic.ts @@ -1,410 +1,523 @@ /** - * 批量音频转换、响度标准化与音效工坊业务逻辑层 (BatchAudio 2.0 Logic) - * 通过 Windows 原生插件提供 12 大核心音频批处理能力 - * 音频由用户通过选择文件、选择文件夹或拖入导入,对接 BatchAudioPlugin 与 FFmpeg 声学滤镜链 + * 批量音频转换业务逻辑层(基于宿主 media.probe / media.transcode 薄原语) + * + * - 零原生 DLL 依赖,严格走 tool_runtime_capabilities / tool_runtime_ensure / tool_media_probe / tool_media_transcode_run / tool_task_cancel + * - 决策 7 特性探测门禁: + * * audioGainDb / audioFade 仅当宿主 optionalExtensions 包含 'audio-filters' 时才允许展示与发送 + * * speedFactor 仅当宿主 optionalExtensions 包含 'speed' 时才允许展示与发送 */ -import { getHostTransport } from '@ztools/declarative-ui' import { + asRecord, callHostTransport, - invokeDllPluginCapability, - showRealItemInFolder -} from './native-ipc.js' + cancelRuntimeTask, + ensureRuntimeCapabilities, + findCapability, + formatBytes, + hasCapabilityExtension, + isRealElectronHost, + nextMessageId, + queryRuntimeCapabilities, + runMediaTranscodeTask, + showRealItemInFolder, + type ToolCapabilityStatus +} from './tool-runtime.js' import { collectFolderFiles, - friendlyFileError, isVolumeRoot, - pickFolder + pickFolder, + type FileImportOptions, + type FileImportResult, + type FileImportRules, + type FileImportTransport, + type ImportedFile } from './file-import.js' -import type { FileImportOptions, FileImportResult, FileImportRules, FileImportTransport, ImportedFile } from './file-import.js' -import { t } from './i18n.js' import { resolveErrorMessage } from './error-i18n.js' +import { t } from './i18n.js' -export { formatBytes } from './native-ipc.js' +export { formatBytes, isRealElectronHost } -export interface CapabilityActionItem { - id: string - title: string - subtitle: string - tag: string - method: string - params: Record - ffmpegFilter?: string +export const MEDIA_PROBE_PRIMITIVE_ID = 'media.probe' as const +export const MEDIA_TRANSCODE_PRIMITIVE_ID = 'media.transcode' as const +export const OUTPUT_SUFFIX = '_audio' + +export const FORBIDDEN_TARGET_PATTERN = + /(?:^|[\\/])Windows[\\/]System32(?:[\\/]|$)|(?:^|[\\/])\.\.(?:[\\/]|$)/i + +export const AUDIO_IMPORT_EXTENSIONS = ['.mp3', '.flac', '.wav', '.aac', '.m4a', '.ogg', '.wma', '.opus', '.aiff'] as const +export const AUDIO_IMPORT_SUPPORTED_TEXT = 'MP3 / FLAC / WAV / AAC / M4A / OGG / WMA / OPUS / AIFF' + +export const AUDIO_IMPORT_RULES: FileImportRules = { + extensions: AUDIO_IMPORT_EXTENSIONS, + forbiddenPath: FORBIDDEN_TARGET_PATTERN +} + +export type AudioContainer = 'mp3' | 'flac' | 'wav' | 'aac' | 'ogg' +export type AudioCodec = 'mp3' | 'flac' | 'pcm' | 'aac' | 'opus' + +export interface AudioExtensionsSupport { + audioFilters: boolean + speed: boolean } -export interface NativeInvocationResult { - ok: boolean - pluginName: string - method: string - data?: unknown +export interface AudioCapabilityState { + probeStatus: ToolCapabilityStatus + transcodeStatus: ToolCapabilityStatus + overallStatus: ToolCapabilityStatus + extensions: AudioExtensionsSupport error?: string - fromFallback?: boolean } +export interface AudioProbeMetadata { + displayName: string + container?: string + durationSec?: number + sizeBytes: number + bitrateBps?: number + codec?: string + sampleRateHz?: number + channels?: number +} + +export interface AudioTranscodeSettings { + container: AudioContainer + audioBitrateKbps?: number + audioSampleRateHz?: number + audioChannels?: number + /** 仅当 optionalExtensions 包含 'audio-filters' 时生效 */ + audioGainDb?: number + /** 仅当 optionalExtensions 包含 'audio-filters' 时生效 */ + fadeSec?: number + /** 仅当 optionalExtensions 包含 'speed' 时生效 */ + speedFactor?: number +} + +export type AudioItemOutcome = + | { status: 'done'; outputPath: string; outputBytes: number; durationMs: number } + | { status: 'cancelled' } + | { status: 'failed'; error: string } + export interface RealAudioFileItem { id: string name: string path: string parentDir: string extension: string - /** 字节数;宿主未授权读取或不可用时为 null(界面显示「大小未识别」) */ sizeBytes: number | null + probe?: AudioProbeMetadata + outcome?: AudioItemOutcome + progressPercent?: number } -export const DLL_PLUGIN_NAME = 'BatchAudioPlugin' -export const FORBIDDEN_TARGET_PATTERN = /(?:^|[\\/])Windows[\\/]System32(?:[\\/]|$)|(?:^|[\\/])\.\.(?:[\\/]|$)/i -export function getForbiddenReason(): string { - return t('forbiddenReason') -} -/** 合并模式(BatchMergeAudio)宿主上限:单次最多 100 个文件、总大小 2 GiB */ -export const MERGE_MAX_FILES = 100 -export const MERGE_MAX_TOTAL_BYTES = 2 * 1024 * 1024 * 1024 -export function getMergeLimitError(): string { - return t('mergeLimitError') -} - -/** - * 通过 Windows 原生插件提供 12 大核心音频处理模式 - */ -export function getAudioWorkshopModes(): CapabilityActionItem[] { - return [ - { - id: 'audio-convert-mp3', - title: t('mode01Title'), - subtitle: t('mode01Sub'), - tag: t('mode01Tag'), - method: 'BatchConvertFormat', - params: { format: 'mp3', bitrate: '320k', sampleRate: 44100 }, - ffmpegFilter: '-c:a libmp3lame -b:a 320k -ar 44100' - }, - { - id: 'audio-convert-flac', - title: t('mode02Title'), - subtitle: t('mode02Sub'), - tag: t('mode02Tag'), - method: 'BatchConvertFormat', - params: { format: 'flac', compressionLevel: 8 }, - ffmpegFilter: '-c:a flac -compression_level 8' - }, - { - id: 'audio-loudnorm', - title: t('mode03Title'), - subtitle: t('mode03Sub'), - tag: t('mode03Tag'), - method: 'BatchLoudnorm', - params: { targetI: -16, targetTp: -1.5, targetLra: 11 }, - ffmpegFilter: '-af "loudnorm=I=-16:TP=-1.5:LRA=11"' - }, - { - id: 'audio-gain', - title: t('mode04Title'), - subtitle: t('mode04Sub'), - tag: t('mode04Tag'), - method: 'BatchAdjustVolume', - params: { gainDb: 3.5 }, - ffmpegFilter: '-af "volume=3.5dB"' - }, - { - id: 'audio-silence', - title: t('mode05Title'), - subtitle: t('mode05Sub'), - tag: t('mode05Tag'), - method: 'BatchTrimAudio', - params: { stripSilence: true, thresholdDb: -50 }, - ffmpegFilter: '-af "silenceremove=start_periods=1:start_silence=0.3:start_threshold=-50dB,areverse,silenceremove=start_periods=1:start_silence=0.3:start_threshold=-50dB,areverse"' - }, - { - id: 'audio-trim-ends', - title: t('mode06Title'), - subtitle: t('mode06Sub'), - tag: t('mode06Tag'), - method: 'BatchTrimDuration', - params: { skipStartSec: 2, skipEndSec: 2 }, - ffmpegFilter: '-ss 00:00:02 -c:a copy' - }, - { - id: 'audio-fade', - title: t('mode07Title'), - subtitle: t('mode07Sub'), - tag: t('mode07Tag'), - method: 'BatchFadeInOut', - params: { fadeInSec: 3, fadeOutSec: 3 }, - ffmpegFilter: '-af "afade=t=in:st=0:d=3,afade=t=out:st=180:d=3"' - }, - { - id: 'audio-eq-vocal', - title: t('mode08Title'), - subtitle: t('mode08Sub'), - tag: t('mode08Tag'), - method: 'BatchEqualizer', - params: { preset: 'vocal_clarity', lowCutHz: 90, boost3kHzDb: 4 }, - ffmpegFilter: '-af "highpass=f=90,equalizer=f=3000:width_type=q:w=1.2:g=4"' - }, - { - id: 'audio-compressor', - title: t('mode09Title'), - subtitle: t('mode09Sub'), - tag: t('mode09Tag'), - method: 'BatchCompressor', - params: { thresholdDb: -18, ratio: 4, attackMs: 20, releaseMs: 250 }, - ffmpegFilter: '-af "acompressor=threshold=-18dB:ratio=4:attack=20:release=250"' - }, - { - id: 'audio-denoise', - title: t('mode10Title'), - subtitle: t('mode10Sub'), - tag: t('mode10Tag'), - method: 'BatchDenoise', - params: { noiseReductionDb: 14, noiseFloorDb: -45 }, - ffmpegFilter: '-af "afftdn=nr=14:nf=-45"' - }, - { - id: 'audio-merge', - title: t('mode11Title'), - subtitle: t('mode11Sub'), - tag: t('mode11Tag'), - method: 'BatchMergeAudio', - params: { normalizeBeforeMerge: true }, - ffmpegFilter: '-filter_complex "concat=n=2:v=0:a=1"' - }, - { - id: 'audio-id3', - title: t('mode12Title'), - subtitle: t('mode12Sub'), - tag: t('mode12Tag'), - method: 'BatchWriteMetadata', - params: { artist: 'ZTools Audio Studio', year: '2026' }, - ffmpegFilter: '-metadata artist="ZTools Audio Studio" -metadata date="2026"' - } - ] +export interface AudioBatchResult { + completed: number + failed: number + cancelled: number + outputs: string[] + errors: string[] } -export function getCapabilityItems(): CapabilityActionItem[] { - return getAudioWorkshopModes().map(item => ({ - ...item, - params: { ...item.params } - })) +const CONTAINER_CODEC_MAP: Readonly> = { + mp3: 'mp3', + flac: 'flac', + wav: 'pcm', + aac: 'aac', + ogg: 'opus' } -export function filterCapabilityItems(items: CapabilityActionItem[], query: string): CapabilityActionItem[] { - if (!Array.isArray(items)) return [] - const q = typeof query === 'string' ? query.trim().toLowerCase() : '' - if (!q) return items - return items.filter(item => { - if (!item || typeof item.title !== 'string') return false - return ( - item.title.toLowerCase().includes(q) || - item.subtitle.toLowerCase().includes(q) || - item.tag.toLowerCase().includes(q) || - item.method.toLowerCase().includes(q) - ) - }) +function splitAudioPath(filePath: string): { dirWithSep: string; dir: string; fileName: string; base: string; ext: string } { + const sepIdx = Math.max(filePath.lastIndexOf('\\'), filePath.lastIndexOf('/')) + const dirWithSep = sepIdx >= 0 ? filePath.slice(0, sepIdx + 1) : '' + const dir = sepIdx >= 0 ? filePath.slice(0, sepIdx) : '' + const fileName = sepIdx >= 0 ? filePath.slice(sepIdx + 1) : filePath + const dot = fileName.lastIndexOf('.') + const base = dot > 0 ? fileName.slice(0, dot) : fileName + const ext = dot > 0 ? fileName.slice(dot).toLowerCase() : '.mp3' + return { dirWithSep, dir: /^[A-Za-z]:$/.test(dir) ? `${dir}\\` : dir, fileName, base, ext } } -const AUDIO_METHODS = new Set([ - 'BatchConvertFormat', - 'BatchLoudnorm', - 'BatchAdjustVolume', - 'BatchTrimAudio', - 'BatchTrimDuration', - 'BatchFadeInOut', - 'BatchEqualizer', - 'BatchCompressor', - 'BatchDenoise', - 'BatchMergeAudio', - 'BatchWriteMetadata' -]) - -function isAudioPath(value: unknown): value is string { - return typeof value === 'string' && value.trim().length > 0 && value.length <= 4096 && - !value.includes('\0') && /^(?:[A-Za-z]:[\\/]|\\\\[^\\]+\\[^\\]+|\/)/.test(value) && - !/(?:^|[\\/])\.\.(?:[\\/]|$)/.test(value) +export function fileNameOf(filePath: string): string { + return splitAudioPath(filePath).fileName } -/** 这里只接受音频处理契约;数值滤镜范围由实际执行它的宿主统一校验。 */ -export function validateInvocationPayload(method: string, params: unknown): { valid: boolean; error?: string } { - const reject = (error: string) => ({ valid: false, error }) - if (!AUDIO_METHODS.has(method)) return reject(t('errInvalidMethod')) - if (!params || typeof params !== 'object' || Array.isArray(params)) return reject(t('errInvalidParams')) - const record = params as Record - const inputs = record.files === undefined ? [record.inputPath] : record.files - if (!Array.isArray(inputs) || !inputs.length) return reject(t('errInvalidFilesEmpty')) - for (const input of inputs) { - if (!isAudioPath(input)) return reject(t('errInvalidFilesPath')) - } - if (method === 'BatchMergeAudio' && inputs.length < 2) return reject(t('errMergeMinFiles')) - if (method === 'BatchMergeAudio' && inputs.length > MERGE_MAX_FILES) return reject(`INVALID_FILES: ${t('mergeLimitError')}`) - for (const key of ['outputDir', 'outputPath']) { - if (record[key] === undefined) continue - if (!isAudioPath(record[key])) return reject(t('errInvalidOutputPath', { key })) - if (FORBIDDEN_TARGET_PATTERN.test(record[key])) return reject(`SECURITY_INTERCEPTED: ${t('forbiddenReason')}`) - } - if (record.outputPath !== undefined && inputs.length > 1 && method !== 'BatchMergeAudio') { - return reject(t('errMultiOutputSingle')) - } - return { valid: true } +export function formatDuration(seconds: number | undefined): string { + if (typeof seconds !== 'number' || !Number.isFinite(seconds) || seconds < 0) return t('durationUnknown') + const total = Math.round(seconds) + const hrs = Math.floor(total / 3600) + const mins = Math.floor((total % 3600) / 60) + const secs = total % 60 + if (hrs > 0) { + return `${hrs}:${String(mins).padStart(2, '0')}:${String(secs).padStart(2, '0')}` + } + return `${String(mins).padStart(2, '0')}:${String(secs).padStart(2, '0')}` } -export async function invokeNativeCapability( - method: string, - params: Record, - hostBridge?: unknown -): Promise { - const check = validateInvocationPayload(method, params) - if (!check.valid) { - throw new Error(resolveErrorMessage(check, t('errValidationFailed'))) - } - const transport = hostBridge ? null : getHostTransport() - if (transport) { - try { - const raw = await transport.call>('dllplugin_call', { - plugin: DLL_PLUGIN_NAME, func: method, params - }, { timeoutMs: 300_000 }) - const data = raw?.data && typeof raw.data === 'object' ? raw.data as Record : raw - const ok = data?.ok === true && data.success !== false - return { ok, pluginName: DLL_PLUGIN_NAME, method, data, fromFallback: false, - ...(ok ? {} : { error: String(resolveErrorMessage(data, t('errHostUnconfirmed'))) }) } - } catch (err) { - return { ok: false, pluginName: DLL_PLUGIN_NAME, method, error: err instanceof Error ? err.message : String(err) } +/** 探测宿主 media.probe 与 media.transcode 能力及 optionalExtensions */ +export async function probeAudioCapabilities(hostOverride?: unknown): Promise { + if (!isRealElectronHost(hostOverride)) { + return { + probeStatus: 'unsupported', + transcodeStatus: 'unsupported', + overallStatus: 'unsupported', + extensions: { audioFilters: false, speed: false }, + error: t('errHostDisconnected') + } + } + const res = await queryRuntimeCapabilities(hostOverride) + if (!res.ok || !res.data) { + return { + probeStatus: 'unsupported', + transcodeStatus: 'unsupported', + overallStatus: 'unsupported', + extensions: { audioFilters: false, speed: false }, + error: resolveErrorMessage(res, t('errHostDisconnected')) } } - const res = await invokeDllPluginCapability(DLL_PLUGIN_NAME, method, params, hostBridge) + const probeCap = findCapability(res.data, MEDIA_PROBE_PRIMITIVE_ID) + const transcodeCap = findCapability(res.data, MEDIA_TRANSCODE_PRIMITIVE_ID) + const probeStatus: ToolCapabilityStatus = probeCap?.status ?? 'unsupported' + const transcodeStatus: ToolCapabilityStatus = transcodeCap?.status ?? 'unsupported' + + let overallStatus: ToolCapabilityStatus = 'ready' + if (probeStatus === 'unsupported' || transcodeStatus === 'unsupported') { + overallStatus = 'unsupported' + } else if (probeStatus === 'needs_provisioning' || transcodeStatus === 'needs_provisioning') { + overallStatus = 'needs_provisioning' + } + return { - ok: res.ok, - pluginName: DLL_PLUGIN_NAME, - method: method.trim(), - data: res.data ?? undefined, - error: res.error, - fromFallback: res.fromFallback + probeStatus, + transcodeStatus, + overallStatus, + extensions: { + audioFilters: hasCapabilityExtension(res.data, MEDIA_TRANSCODE_PRIMITIVE_ID, 'audio-filters'), + speed: hasCapabilityExtension(res.data, MEDIA_TRANSCODE_PRIMITIVE_ID, 'speed') + } } } -export interface AudioBatchResult { - completed: number - failed: number - outputs: string[] - errors: string[] +/** 按需下载并准备音频引擎组件(tool_runtime_ensure) */ +export async function ensureAudioEngine( + hostOverride?: unknown +): Promise<{ ok: boolean; status: ToolCapabilityStatus; provisioned: boolean; message: string }> { + if (!isRealElectronHost(hostOverride)) { + return { ok: false, status: 'unsupported', provisioned: false, message: t('errHostDisconnected') } + } + const result = await ensureRuntimeCapabilities([MEDIA_PROBE_PRIMITIVE_ID, MEDIA_TRANSCODE_PRIMITIVE_ID], hostOverride) + if (!result.ok) { + const errText = resolveErrorMessage(result, result.status || t('errHostDisconnected')) + return { + ok: false, + status: result.status, + provisioned: result.provisioned, + message: t('errProvisionFailed', { error: errText }) + } + } + return { ok: true, status: 'ready', provisioned: result.provisioned, message: t('msgProvisionSuccess') } +} + +/** 探测单文件或多文件音频元数据(tool_media_probe) */ +export async function probeAudioFiles( + filePaths: readonly string[], + hostOverride?: unknown +): Promise<{ ok: boolean; items: AudioProbeMetadata[]; error?: string }> { + if (!filePaths.length) return { ok: true, items: [] } + if (!isRealElectronHost(hostOverride)) { + return { ok: false, items: [], error: t('errHostDisconnected') } + } + const res = await callHostTransport( + 'tool_media_probe', + { inputs: filePaths.map((p) => ({ path: p })) }, + hostOverride + ) + if (!res.ok) { + return { + ok: false, + items: [], + error: t('errProbeFailed', { error: resolveErrorMessage(res, t('errHostDisconnected')) }) + } + } + const rec = asRecord(res.data) + const rawItems = Array.isArray(rec?.items) ? rec.items : [] + const items: AudioProbeMetadata[] = rawItems.map((raw) => { + const item = asRecord(raw) ?? {} + const streams = Array.isArray(item.streams) ? item.streams : [] + const audioStream = streams.map(asRecord).find((s) => s?.kind === 'audio') ?? null + const durationSec = typeof item.durationSec === 'number' && Number.isFinite(item.durationSec) ? item.durationSec : undefined + const sizeBytes = typeof item.sizeBytes === 'number' && Number.isFinite(item.sizeBytes) && item.sizeBytes >= 0 ? item.sizeBytes : 0 + const bitrateBps = typeof item.bitrateBps === 'number' && Number.isFinite(item.bitrateBps) ? item.bitrateBps : undefined + const sampleRateHz = + typeof audioStream?.sampleRateHz === 'number' && Number.isFinite(audioStream.sampleRateHz) + ? audioStream.sampleRateHz + : undefined + const channels = + typeof audioStream?.channels === 'number' && Number.isFinite(audioStream.channels) + ? audioStream.channels + : undefined + return { + displayName: typeof item.displayName === 'string' ? item.displayName : '', + ...(typeof item.container === 'string' ? { container: item.container } : {}), + ...(durationSec !== undefined ? { durationSec } : {}), + sizeBytes, + ...(bitrateBps !== undefined ? { bitrateBps } : {}), + ...(typeof audioStream?.codec === 'string' ? { codec: audioStream.codec } : {}), + ...(sampleRateHz !== undefined ? { sampleRateHz } : {}), + ...(channels !== undefined ? { channels } : {}) + } + }) + return { ok: true, items } } /** - * 合并模式执行前预检:单次最多 100 个文件、总计 2 GiB; - * 未知大小(null)计入文件数量,不计入已知体积总量。 + * 构建 tool_media_transcode_run 请求体。 + * 严格执行决策 7 特性探测门禁: + * - extensions.audioFilters 为 false 时,绝对不包含 audioGainDb / audioFade 键 + * - extensions.speed 为 false 时,绝对不包含 speedFactor 键 */ -export function checkMergeAudioLimits( - files: ReadonlyArray> -): string | null { - if (files.length > MERGE_MAX_FILES) return t('mergeLimitError') - let knownBytes = 0 - for (const file of files) { - if (typeof file.sizeBytes === 'number' && Number.isFinite(file.sizeBytes) && file.sizeBytes >= 0) { - knownBytes += file.sizeBytes +export function buildAudioTranscodeRequest( + inputPath: string, + outputPath: string, + settings: AudioTranscodeSettings, + extensions: AudioExtensionsSupport, + options: { taskId?: string; totalDurationSec?: number } = {} +): Record { + const codec = CONTAINER_CODEC_MAP[settings.container] + const isLossless = settings.container === 'flac' || settings.container === 'wav' + + const payload: Record = { + ...(options.taskId ? { taskId: options.taskId } : {}), + input: { path: inputPath }, + output: { path: outputPath }, + overwrite: false, + container: settings.container, + audioCodec: codec, + extractAudioOnly: true + } + + if (!isLossless && typeof settings.audioBitrateKbps === 'number' && Number.isFinite(settings.audioBitrateKbps) && settings.audioBitrateKbps > 0) { + payload.audioBitrateKbps = Math.round(settings.audioBitrateKbps) + } + if (typeof settings.audioSampleRateHz === 'number' && Number.isFinite(settings.audioSampleRateHz) && settings.audioSampleRateHz > 0) { + payload.audioSampleRateHz = Math.round(settings.audioSampleRateHz) + } + if (typeof settings.audioChannels === 'number' && Number.isInteger(settings.audioChannels) && settings.audioChannels >= 1) { + payload.audioChannels = settings.audioChannels + } + + // 严格门禁:仅当宿主声明支持 'audio-filters' 时发送音频增益与淡入淡出字段 + if (extensions.audioFilters) { + if (typeof settings.audioGainDb === 'number' && Number.isFinite(settings.audioGainDb) && settings.audioGainDb !== 0) { + payload.audioGainDb = settings.audioGainDb + } + if (typeof settings.fadeSec === 'number' && Number.isFinite(settings.fadeSec) && settings.fadeSec > 0) { + payload.audioFade = { + fadeInSec: settings.fadeSec, + fadeOutSec: settings.fadeSec, + ...(typeof options.totalDurationSec === 'number' && options.totalDurationSec > 0 + ? { totalDurationSec: options.totalDurationSec } + : {}) + } + } + } + + // 严格门禁:仅当宿主声明支持 'speed' 时发送变速字段 + if (extensions.speed) { + if (typeof settings.speedFactor === 'number' && Number.isFinite(settings.speedFactor) && settings.speedFactor > 0 && settings.speedFactor !== 1) { + payload.speedFactor = settings.speedFactor } } - if (knownBytes > MERGE_MAX_TOTAL_BYTES) return t('mergeLimitError') - return null + + return payload +} + +async function checkFileExists(filePath: string, hostOverride?: unknown): Promise<'exists' | 'missing' | 'unknown'> { + const res = await callHostTransport('filesystem_file_exists', { path: filePath }, hostOverride) + if (res.ok) { + if (typeof res.data === 'boolean') return res.data ? 'exists' : 'missing' + const rec = asRecord(res.data) + if (typeof rec?.exists === 'boolean') return rec.exists ? 'exists' : 'missing' + } + return 'unknown' +} + +export async function chooseAudioOutputPath( + sourcePath: string, + ext: AudioContainer, + reserved: Set, + hostOverride?: unknown +): Promise { + const { dirWithSep, base } = splitAudioPath(sourcePath) + const key = (p: string) => p.replace(/\//g, '\\').toLowerCase() + const sourceKey = key(sourcePath) + const usable = (candidate: string) => !reserved.has(key(candidate)) && key(candidate) !== sourceKey + const take = (candidate: string) => { + reserved.add(key(candidate)) + return candidate + } + + for (let n = 1; n <= 30; n++) { + const suffix = n === 1 ? OUTPUT_SUFFIX : `${OUTPUT_SUFFIX}_${n}` + const candidate = `${dirWithSep}${base}${suffix}.${ext}` + if (!usable(candidate)) continue + const state = await checkFileExists(candidate, hostOverride) + if (state === 'missing') return take(candidate) + if (state === 'unknown') break + } + + const stamp = String(Date.now()) + for (let n = 1; n <= 20; n++) { + const suffix = n === 1 ? `${OUTPUT_SUFFIX}_${stamp}` : `${OUTPUT_SUFFIX}_${stamp}_${n}` + const candidate = `${dirWithSep}${base}${suffix}.${ext}` + if (!usable(candidate)) continue + const state = await checkFileExists(candidate, hostOverride) + if (state === 'exists') continue + return take(candidate) + } + throw new Error(t('errCannotGenUniqueName')) +} + +/** 取消正在运行的音频转码任务(tool_task_cancel) */ +export async function cancelAudioTask( + taskId: string, + hostOverride?: unknown +): Promise<{ ok: boolean; cancelled: boolean; error?: string }> { + if (!isRealElectronHost(hostOverride)) { + return { ok: false, cancelled: false, error: t('errHostDisconnected') } + } + const res = await cancelRuntimeTask(taskId, hostOverride) + if (!res.ok) { + return { + ok: false, + cancelled: false, + error: t('errCancelFailed', { error: resolveErrorMessage(res, t('errHostDisconnected')) }) + } + } + return { ok: true, cancelled: res.data?.cancelled === true } +} + +/** 转换单个音频文件 */ +export async function transcodeAudioFile( + file: Pick, + settings: AudioTranscodeSettings, + extensions: AudioExtensionsSupport, + reserved: Set, + options: { taskId?: string; hostOverride?: unknown } = {} +): Promise { + if (!isRealElectronHost(options.hostOverride)) { + return { status: 'failed', error: t('errHostDisconnected') } + } + if (!(settings.container in CONTAINER_CODEC_MAP)) { + return { status: 'failed', error: t('errUnsupportedContainer', { format: settings.container }) } + } + if (FORBIDDEN_TARGET_PATTERN.test(file.path)) { + return { status: 'failed', error: t('forbiddenReason') } + } + + let outputPath: string + try { + outputPath = await chooseAudioOutputPath(file.path, settings.container, reserved, options.hostOverride) + } catch (err) { + return { status: 'failed', error: err instanceof Error ? err.message : String(err) } + } + + if (FORBIDDEN_TARGET_PATTERN.test(outputPath)) { + return { status: 'failed', error: t('forbiddenReason') } + } + + const taskId = options.taskId || nextMessageId('audio') + const payload = buildAudioTranscodeRequest(file.path, outputPath, settings, extensions, { + taskId, + totalDurationSec: file.probe?.durationSec + }) + + const transcodeRes = await runMediaTranscodeTask(payload, options.hostOverride) + if (transcodeRes.status === 'cancelled') return { status: 'cancelled' } + if (transcodeRes.status === 'failed') { + const reason = + transcodeRes.error === 'EMPTY_OUTPUT' + ? 'EMPTY_OUTPUT' + : resolveErrorMessage(transcodeRes, t('errHostDisconnected')) + return { status: 'failed', error: t('errTranscodeFailed', { error: reason }) } + } + return { + status: 'done', + outputPath, + outputBytes: transcodeRes.outputBytes, + durationMs: transcodeRes.durationMs + } } -/** 合并一次提交全部输入;独立任务逐个记录回执,支持跳过处理中移除的条目,部分失败不冒充全部完成。 */ -export async function processAudioSelection( - method: string, - params: Record, - files: RealAudioFileItem[], - hostOverride?: unknown, +/** 批量顺序转换选中音频,支持中途实时取消 */ +export async function processAudioBatch( + files: readonly RealAudioFileItem[], + settings: AudioTranscodeSettings, + extensions: AudioExtensionsSupport, options: { + hostOverride?: unknown shouldSkip?: (id: string) => boolean - onStart?: (ids: string[]) => void - onDone?: (ids: string[]) => void + shouldStop?: () => boolean + onStart?: (id: string, taskId: string) => void + onDone?: (id: string, outcome: AudioItemOutcome) => void } = {} ): Promise { - const result: AudioBatchResult = { completed: 0, failed: 0, outputs: [], errors: [] } - const merge = method === 'BatchMergeAudio' - if (!files.length || (merge && files.length < 2)) { - return { ...result, failed: files.length || 1, errors: [t('errMinAudioForRun')] } - } - if (merge) { - const limitError = checkMergeAudioLimits(files) - if (limitError) { - return { ...result, failed: files.length, errors: [limitError] } - } - } - const groups = merge ? [files] : files.map(file => [file]) - for (const group of groups) { - if (!merge && group.every(file => options.shouldSkip?.(file.id))) continue - const groupIds = group.map(file => file.id) - options.onStart?.(groupIds) - try { - const res = await invokeNativeCapability(method, { ...params, files: group.map(file => file.path) }, hostOverride) - const data = res.data as { results?: Array<{ outputPath?: unknown; sizeBytes?: unknown }>; errors?: unknown[] } | undefined - const output = data?.results?.[0] - if (!res.ok || data?.errors?.length || !output || typeof output.outputPath !== 'string' || !output.outputPath.trim() || !(Number(output.sizeBytes) > 0)) { - throw new Error(friendlyFileError(resolveErrorMessage(res, t('errNoValidOutput')))) - } - result.completed += group.length - result.outputs.push(output.outputPath) - } catch (err) { - result.failed += group.length - result.errors.push( - t('errItemPrefix', { - names: group.map(file => file.name).join(t('errItemJoinSep')), - msg: friendlyFileError(err) - }) - ) - } finally { - options.onDone?.(groupIds) + const result: AudioBatchResult = { completed: 0, failed: 0, cancelled: 0, outputs: [], errors: [] } + const reserved = new Set() + + for (const file of files) { + if (options.shouldStop?.()) break + if (options.shouldSkip?.(file.id)) continue + const taskId = nextMessageId('audio') + options.onStart?.(file.id, taskId) + const outcome = await transcodeAudioFile(file, settings, extensions, reserved, { + taskId, + hostOverride: options.hostOverride + }) + options.onDone?.(file.id, outcome) + if (outcome.status === 'done') { + result.completed += 1 + result.outputs.push(outcome.outputPath) + } else if (outcome.status === 'cancelled') { + result.cancelled += 1 + break + } else { + result.failed += 1 + result.errors.push(`${file.name}: ${outcome.error}`) } } return result } -export const AUDIO_IMPORT_EXTENSIONS = ['.mp3', '.flac', '.wav', '.aac', '.m4a', '.ogg', '.wma', '.opus', '.aiff'] as const -export const AUDIO_EXT_REGEX = /\.(?:mp3|flac|wav|aac|m4a|ogg|wma|opus|aiff)$/i -export const AUDIO_IMPORT_SUPPORTED_TEXT = 'MP3 / FLAC / WAV / AAC / M4A / OGG / WMA / OPUS / AIFF' - -/** 音频导入规则:递归 5 层、最多 500 个文件、跳过系统保护目录 */ -export const AUDIO_IMPORT_RULES: FileImportRules = { - extensions: AUDIO_IMPORT_EXTENSIONS, - forbiddenPath: FORBIDDEN_TARGET_PATTERN -} - -/** 把宿主调用包装为共享导入模块所需的 transport */ export function createAudioImportTransport(hostOverride?: unknown): FileImportTransport { return (method, params) => callHostTransport(method, params, hostOverride) } -/** 选择文件夹并收集音频(选中整个磁盘根目录时先请用户确认) */ export async function pickAudioFolderWithConfirm( transport: FileImportTransport, confirmVolumeRoot: (folderPath: string) => Promise, options: FileImportOptions = {} ): Promise { - const picked = await pickFolder(transport, { title: t('pickFolderTitle') }) - if (options.signal?.aborted || picked.canceled) { + const folder = await pickFolder(transport, { title: t('pickFolderTitle') }) + if (options.signal?.aborted || folder.canceled) { return { files: [], ignored: 0, truncated: false, failedDirs: [], canceled: true } } - if (picked.error || !picked.folderPath) { - return { files: [], ignored: 0, truncated: false, failedDirs: [], canceled: false, error: resolveErrorMessage(picked, t('noFolderSelected')) } - } - if (isVolumeRoot(picked.folderPath)) { - const confirmed = await confirmVolumeRoot(picked.folderPath) - if (options.signal?.aborted || !confirmed) { - return { files: [], ignored: 0, truncated: false, failedDirs: [], canceled: true } + if (folder.error || !folder.folderPath) { + return { + files: [], + ignored: 0, + truncated: false, + failedDirs: [], + canceled: false, + error: resolveErrorMessage(folder, t('noFolderSelected')) } } - return collectFolderFiles(transport, picked.folderPath, AUDIO_IMPORT_RULES, options) -} - -function splitAudioPath(filePath: string): { dir: string; fileName: string; ext: string } { - const sepIdx = Math.max(filePath.lastIndexOf('\\'), filePath.lastIndexOf('/')) - const dir = sepIdx >= 0 ? filePath.slice(0, sepIdx) : '' - const fileName = sepIdx >= 0 ? filePath.slice(sepIdx + 1) : filePath - const dot = fileName.lastIndexOf('.') - const ext = dot > 0 ? fileName.slice(dot).toLowerCase() : '.mp3' - return { dir, fileName, ext } + if (isVolumeRoot(folder.folderPath) && (!(await confirmVolumeRoot(folder.folderPath)) || options.signal?.aborted)) { + return { files: [], ignored: 0, truncated: false, failedDirs: [], canceled: true } + } + return collectFolderFiles(transport, folder.folderPath, AUDIO_IMPORT_RULES, options) } let audioItemSeq = 0 -/** 从路径构造音频队列项 */ export function makeAudioItem( id: string, filePath: string, @@ -422,7 +535,6 @@ export function makeAudioItem( } } -/** 把共享导入结果转为音频队列项 */ export function toAudioItem(file: ImportedFile): RealAudioFileItem { audioItemSeq += 1 return makeAudioItem(`aud-${audioItemSeq}-${file.path}`, file.path, file.sizeBytes, file.parentDir) diff --git a/extensions/batch-audio/src/native-ipc.ts b/extensions/batch-audio/src/native-ipc.ts deleted file mode 100644 index 51576b99..00000000 --- a/extensions/batch-audio/src/native-ipc.ts +++ /dev/null @@ -1,1852 +0,0 @@ -import { getLocale } from '@ztools/declarative-ui' - -type DynamicBridge = ReturnType - -const NATIVE_IPC_MESSAGES: Record string - dirEntrySep: string - dirErrorColon: string - deepScanUnavailable: string - pathEmpty: string - invalidMethodEmpty: string - invalidMethodFormat: string - invalidParamsObject: string - paramTooLong: (key: string) => string - paramOutOfRange: (key: string) => string - methodParamEmpty: string - invalidMethodType: string - malformedDllResponse: string - unknownDllError: string - hostIpcFailed: (pluginName: string, method: string) => string - hostUnavailable: (pluginName: string, method: string) => string - callFailed: string - movedToTrash: string - deleteFailed: string - revealedInFolder: string - revealFailed: string - opened: string - openFailed: string - pluginCallNotReady: string -}> = { - 'zh-CN': { - ipcCallFailed: 'IPC 调用返回失败', - ipcInnerFailed: 'IPC 内部调用失败', - scanIncomplete: '扫描结果不完整', - dirReadFailed: (details, moreCount) => - `目录读取失败或不完整:${details}${moreCount > 0 ? `;另有 ${moreCount} 个目录` : ''}`, - dirEntrySep: ';', - dirErrorColon: ':', - deepScanUnavailable: '深度扫描不可用,仅列出一级目录,结果不完整', - pathEmpty: '路径不能为空', - invalidMethodEmpty: 'INVALID_METHOD: 调用方法名不能为空', - invalidMethodFormat: 'INVALID_METHOD_FORMAT: 方法名包含非法字符或超长', - invalidParamsObject: 'INVALID_PARAMS: 参数必须为非空对象', - paramTooLong: (key) => `PARAM_TOO_LONG: 参数 ${key} 超过最大长度限制`, - paramOutOfRange: (key) => `PARAM_OUT_OF_RANGE: 数值参数 ${key} 越界或非有限数`, - methodParamEmpty: 'method 参数不能为空', - invalidMethodType: 'INVALID_METHOD: method 不能为空且必须为字符串', - malformedDllResponse: 'MALFORMED_DLL_RESPONSE: 原生组件返回了损坏的 JSON 数据', - unknownDllError: '原生组件返回未知错误', - hostIpcFailed: (pluginName, method) => `HOST_IPC_FAILED: ${pluginName}.${method} 调用失败`, - hostUnavailable: (pluginName, method) => `HOST_UNAVAILABLE: ${pluginName}.${method} 宿主接口未就绪`, - callFailed: '调用失败', - movedToTrash: '已移入回收站', - deleteFailed: '删除失败', - revealedInFolder: '已定位文件', - revealFailed: '定位失败', - opened: '已打开', - openFailed: '打开失败', - pluginCallNotReady: '插件调用未就绪' - }, - 'en-US': { - ipcCallFailed: 'IPC call failed', - ipcInnerFailed: 'Internal IPC call failed', - scanIncomplete: 'Incomplete scan results', - dirReadFailed: (details, moreCount) => - `Directory read failed or incomplete: ${details}${moreCount > 0 ? `; and ${moreCount} more` : ''}`, - dirEntrySep: '; ', - dirErrorColon: ': ', - deepScanUnavailable: 'Deep scan unavailable; only top-level directory listed (incomplete)', - pathEmpty: 'Path cannot be empty', - invalidMethodEmpty: 'INVALID_METHOD: Method name cannot be empty', - invalidMethodFormat: 'INVALID_METHOD_FORMAT: Method name contains invalid characters or is too long', - invalidParamsObject: 'INVALID_PARAMS: Parameters must be a non-null object', - paramTooLong: (key) => `PARAM_TOO_LONG: Parameter "${key}" exceeds maximum length`, - paramOutOfRange: (key) => `PARAM_OUT_OF_RANGE: Numeric parameter "${key}" is out of range or non-finite`, - methodParamEmpty: 'Method parameter cannot be empty', - invalidMethodType: 'INVALID_METHOD: Method must be a non-empty string', - malformedDllResponse: 'MALFORMED_DLL_RESPONSE: Native component returned malformed JSON', - unknownDllError: 'Native component returned an unknown error', - hostIpcFailed: (pluginName, method) => `HOST_IPC_FAILED: ${pluginName}.${method} call failed`, - hostUnavailable: (pluginName, method) => `HOST_UNAVAILABLE: ${pluginName}.${method} host interface not ready`, - callFailed: 'Call failed', - movedToTrash: 'Moved to Trash', - deleteFailed: 'Delete failed', - revealedInFolder: 'Revealed in folder', - revealFailed: 'Failed to reveal item', - opened: 'Opened', - openFailed: 'Failed to open', - pluginCallNotReady: 'Plugin invocation not ready' - } -} - -function ipcStrings() { - const locale = getLocale() - return NATIVE_IPC_MESSAGES[locale] ?? NATIVE_IPC_MESSAGES['en-US'] -} -/** - * ZTools 真实宿主 IPC 与系统能力桥接层 (Real Host IPC Bridge) - * - * 严格遵循《ZTools Declarative UI 2.0 架构与 35 款原生插件全量升级规范》5.1 真实环境铁律: - * - 在真实 Electron 宿主环境中,100% 走通 Preload (__ztoolsElectron.transport.methods / window.ztools / __ztoolsLauncher) 真实调用链路 - * - 严禁在真实环境中因参数格式或嵌套响应结构差异而回退到假数据 - */ - -let ipcReqSeq = 1 -const realFileSizeCache = new Map() - -export function nextMessageId(prefix = 'ipc'): string { - ipcReqSeq = (ipcReqSeq + 1) % 1_000_000 - return `${prefix}_${Date.now()}_${ipcReqSeq}` -} - -/** - * 判断当前是否处于真实的 ZTools Electron 渲染进程宿主环境 - */ -export function isRealElectronHost(hostOverride?: unknown): boolean { - if (hostOverride) return false - if (typeof window === 'undefined') return false - const w = window as DynamicBridge - return Boolean( - w.__ztoolsElectron?.transport?.methods || - w.ztools?.transport?.call || - w.ztools?.transport?.methods - ) -} - -function normalizeMethodParams(method: string, params: Record): Record { - if (!params || typeof params !== 'object') return {} - const next = { ...params } - if (method === 'system_get_disk_usage') { - const rawDrive = String(next.drive || next.path || 'C:\\').trim() - if (rawDrive.startsWith('/')) { - next.drive = rawDrive - } else { - const match = rawDrive.match(/^([A-Za-z]):/) - next.drive = match ? `${match[1].toUpperCase()}:\\` : rawDrive.replace(/\//g, '\\') - } - delete next.path - } - return next -} - -function normalizeMethodResult(method: string, payload: DynamicBridge): DynamicBridge { - if (!payload || typeof payload !== 'object') return payload - - if (method === 'system_get_disk_usage') { - const avail = typeof payload.available === 'number' - ? payload.available - : typeof payload.free === 'number' - ? payload.free - : Math.max(0, Number(payload.total || 0) - Number(payload.used || 0)) - return { - ...payload, - available: avail, - free: avail - } - } - - if (method === 'system_get_hardware_summary') { - const cpuModel = - typeof payload.cpuModel === 'string' && payload.cpuModel.trim() - ? payload.cpuModel.trim() - : Array.isArray(payload.cpuModels) && payload.cpuModels.length > 0 - ? String(payload.cpuModels[0]).trim() - : 'x86_64 Processor' - return { - ...payload, - cpuModel - } - } - - if (method === 'system_get_battery_status') { - // 宿主约定 percent 超出 0-100(如 255)表示无电池或电量未知,不能改写成 100% - const rawPct = payload.percent - const hasBattery = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 - return { - ...payload, - percent: hasBattery ? rawPct : null, - hasBattery - } - } - - if (method === 'screen_get_all_displays') { - const list = Array.isArray(payload) - ? payload - : Array.isArray(payload.displays) - ? payload.displays - : [] - return list.map((d: DynamicBridge) => ({ - ...d, - label: d?.label || d?.name || `Display #${d?.id ?? 1}` - })) - } - - return payload -} - -function extractIpcErrorMeta(errObj: DynamicBridge): { - errorCode?: string - errorDetails?: Record -} { - if (!errObj || typeof errObj !== 'object') return {} - const errorCode = - typeof errObj.errorCode === 'string' && errObj.errorCode.trim() - ? errObj.errorCode.trim() - : typeof errObj.code === 'string' && errObj.code.trim() - ? errObj.code.trim() - : undefined - const rawDetails = - errObj.errorDetails && typeof errObj.errorDetails === 'object' && !Array.isArray(errObj.errorDetails) - ? (errObj.errorDetails as Record) - : errObj.details && typeof errObj.details === 'object' && !Array.isArray(errObj.details) - ? (errObj.details as Record) - : undefined - return { - ...(errorCode ? { errorCode } : {}), - ...(rawDetails ? { errorDetails: rawDetails } : {}) - } -} - -function unwrapTransportResponse( - method: string, - raw: DynamicBridge -): { ok: boolean; data?: DynamicBridge; error?: string; errorCode?: string; errorDetails?: Record } { - if (raw === null || raw === undefined) { - return { ok: false, error: 'EMPTY_IPC_RESPONSE', errorCode: 'EMPTY_IPC_RESPONSE' } - } - if (typeof raw !== 'object') { - return { ok: true, data: raw } - } - if (raw.success === false) { - const errObj = raw.error - const errMsg = - typeof errObj === 'object' && errObj !== null - ? String(errObj.message || errObj.code || JSON.stringify(errObj)) - : String(errObj || ipcStrings().ipcCallFailed) - return { ok: false, error: errMsg, ...extractIpcErrorMeta(raw), ...extractIpcErrorMeta(errObj) } - } - - const firstLayer = 'data' in raw && raw.data !== undefined ? raw.data : raw - if (firstLayer && typeof firstLayer === 'object' && !Array.isArray(firstLayer)) { - if (firstLayer.success === false) { - const errObj = firstLayer.error - const errMsg = - typeof errObj === 'object' && errObj !== null - ? String(errObj.message || errObj.code || JSON.stringify(errObj)) - : String(errObj || ipcStrings().ipcInnerFailed) - return { ok: false, error: errMsg, ...extractIpcErrorMeta(firstLayer), ...extractIpcErrorMeta(errObj) } - } - if ('data' in firstLayer && firstLayer.data !== undefined) { - return { ok: true, data: normalizeMethodResult(method, firstLayer.data) } - } - } - - return { ok: true, data: normalizeMethodResult(method, firstLayer) } -} - -/** - * 调用 Electron Preload Transport 方法(自动封装合法的 alphanumeric messageId 与双层解包) - */ -export async function callHostTransport( - method: string, - params: Record = {}, - hostOverride?: DynamicBridge -): Promise<{ ok: boolean; data?: T; error?: string; errorCode?: string; errorDetails?: Record }> { - const normalizedParams = normalizeMethodParams(method, params) - - // 1. 测试注入的 hostOverride 优先 - if (hostOverride) { - if (typeof hostOverride[method] === 'function') { - try { - const res = await hostOverride[method](normalizedParams) - const unwrapped = unwrapTransportResponse(method, res) - return unwrapped as { ok: boolean; data?: T; error?: string; errorCode?: string; errorDetails?: Record } - } catch (err: DynamicBridge) { - return { ok: false, error: err instanceof Error ? err.message : String(err), ...extractIpcErrorMeta(err) } - } - } - if (typeof hostOverride?.transport?.call === 'function') { - try { - const res = await hostOverride.transport.call(method, normalizedParams) - const unwrapped = unwrapTransportResponse(method, res) - return unwrapped as { ok: boolean; data?: T; error?: string; errorCode?: string; errorDetails?: Record } - } catch (err: DynamicBridge) { - return { ok: false, error: err instanceof Error ? err.message : String(err), ...extractIpcErrorMeta(err) } - } - } - } - - if (typeof window === 'undefined') { - return { ok: false, error: 'NO_WINDOW_ENV', errorCode: 'NO_WINDOW_ENV' } - } - - const w = window as DynamicBridge - const methods = w.__ztoolsElectron?.transport?.methods || w.ztools?.transport?.methods - const fn = methods?.[method] - - if (typeof fn === 'function') { - try { - const messageId = nextMessageId(method.replace(/[^A-Za-z0-9_]/g, '_').slice(0, 24)) - const raw = await fn({ messageId, params: normalizedParams }) - return unwrapTransportResponse(method, raw) as { ok: boolean; data?: T; error?: string; errorCode?: string; errorDetails?: Record } - } catch (err: DynamicBridge) { - return { ok: false, error: err instanceof Error ? err.message : String(err), ...extractIpcErrorMeta(err) } - } - } - - if (typeof w.ztools?.transport?.call === 'function') { - try { - const raw = await w.ztools.transport.call(method, normalizedParams) - return unwrapTransportResponse(method, raw) as { ok: boolean; data?: T; error?: string; errorCode?: string; errorDetails?: Record } - } catch (err: DynamicBridge) { - return { ok: false, error: err instanceof Error ? err.message : String(err), ...extractIpcErrorMeta(err) } - } - } - - return { ok: false, error: `METHOD_NOT_AVAILABLE: ${method}`, errorCode: 'METHOD_NOT_AVAILABLE' } -} - -export interface RealDiskDriveInfo { - drive: string - totalBytes: number - usedBytes: number - availableBytes: number - usagePercent: number -} - -/** - * 探测本机全部真实挂载磁盘分区 (C:\ ~ Z:\ 或 macOS/POSIX 挂载点 '/') - */ -export async function probeRealDiskDrives( - candidateLetters: string[] = ['C', 'D', 'E', 'F', 'G'], - hostOverride?: DynamicBridge -): Promise { - const drives: RealDiskDriveInfo[] = [] - const results = await Promise.all( - candidateLetters.map(async (letter) => { - const raw = String(letter || '').trim() - const isPosix = raw.startsWith('/') - const drivePath = isPosix ? raw : `${raw.replace(/:\\?$/, '').toUpperCase()}:\\` - const res = await callHostTransport<{ - total: number - used: number - available: number - free?: number - percent: number - }>('system_get_disk_usage', { drive: drivePath }, hostOverride) - if (res.ok && res.data && typeof res.data.total === 'number' && res.data.total > 0) { - const availableBytes = - typeof res.data.available === 'number' - ? res.data.available - : typeof res.data.free === 'number' - ? res.data.free - : Math.max(0, res.data.total - res.data.used) - return { - drive: isPosix ? raw : `${raw.replace(/:\\?$/, '').toUpperCase()}:`, - totalBytes: res.data.total, - usedBytes: res.data.used, - availableBytes, - usagePercent: res.data.percent - } - } - return null - }) - ) - - for (const item of results) { - if (item) drives.push(item) - } - - if (drives.length === 0 && !candidateLetters.includes('/')) { - const posixRes = await callHostTransport<{ - total: number - used: number - available: number - free?: number - percent: number - }>('system_get_disk_usage', { drive: '/' }, hostOverride) - if (posixRes.ok && posixRes.data && typeof posixRes.data.total === 'number' && posixRes.data.total > 0) { - const availableBytes = - typeof posixRes.data.available === 'number' - ? posixRes.data.available - : typeof posixRes.data.free === 'number' - ? posixRes.data.free - : Math.max(0, posixRes.data.total - posixRes.data.used) - drives.push({ - drive: '/', - totalBytes: posixRes.data.total, - usedBytes: posixRes.data.used, - availableBytes, - usagePercent: posixRes.data.percent - }) - } - } - - return drives -} - -/** - * 获取本机真实系统特殊路径(支持 home 派生标准子目录兜底,自动兼容 Windows 与 macOS/POSIX) - */ -export async function getRealSystemPath( - name: 'home' | 'appData' | 'userData' | 'desktop' | 'documents' | 'downloads' | 'music' | 'pictures' | 'videos' | 'temp' | 'cache', - hostOverride?: DynamicBridge -): Promise { - const res = await callHostTransport('system_get_path', { name }, hostOverride) - if (res.ok && res.data) { - if (typeof res.data === 'string' && res.data.trim().length > 0) { - return res.data.trim() - } - if (typeof res.data.path === 'string' && res.data.path.trim().length > 0) { - return res.data.path.trim() - } - } - - if (name !== 'home') { - const home = await getRealSystemPath('home', hostOverride) - if (home) { - const isPosix = home.startsWith('/') - const subMap: Record = isPosix - ? { - desktop: `${home}/Desktop`, - documents: `${home}/Documents`, - downloads: `${home}/Downloads`, - music: `${home}/Music`, - pictures: `${home}/Pictures`, - videos: `${home}/Videos`, - appData: `${home}/Library/Application Support`, - userData: `${home}/Library/Application Support/ZTools`, - temp: '/tmp', - cache: `${home}/Library/Caches` - } - : { - desktop: `${home}\\Desktop`, - documents: `${home}\\Documents`, - downloads: `${home}\\Downloads`, - music: `${home}\\Music`, - pictures: `${home}\\Pictures`, - videos: `${home}\\Videos`, - appData: `${home}\\AppData\\Roaming`, - userData: `${home}\\AppData\\Roaming\\ZTools`, - temp: `${home}\\AppData\\Local\\Temp`, - cache: `${home}\\AppData\\Local` - } - if (subMap[name]) return subMap[name] - } - } - - return '' -} - -export type RealDriveUsageInfo = RealDiskDriveInfo - -export interface RealIndexedFileEntry { - name: string - path: string - ext: string - isDir: boolean - isDirectory: boolean - size: number - sizeBytes: number - mtime: number - mtimeMs: number - lastModifiedMs: number -} - -export interface RealDirectorySubdirSummary { - name: string - path: string - fileCount: number - totalBytes: number - mtime: number - /** 体积不是完整统计(宿主扫描截断且独立统计超时 / 无权限),totalBytes 只是下限 */ - approximate?: boolean -} - -export interface RealDirectoryScanResult extends Iterable { - files: RealIndexedFileEntry[] - totalFiles: number - fileCount: number - totalBytes: number - subdirs: RealDirectorySubdirSummary[] - /** 宿主扫描达到条目上限后停止:files / totalFiles 只是已遍历部分的抽样 */ - truncated?: boolean - /** totalBytes 为近似值(下限) */ - approximate?: boolean - /** 宿主实际遍历的条目数 */ - visitedEntries?: number - /** 读取失败的真实原因;已有文件仍可使用,但不能当作完整结果。 */ - error?: string -} - -interface ScanResultMeta { - truncated?: boolean - approximate?: boolean - visitedEntries?: number -} - -export interface ScanDirectoryTreeOptions { - maxDepth?: number - maxFiles?: number - collectTopN?: number - filterExt?: RegExp - hostOverride?: DynamicBridge -} - -function extractFileExt(fileNameOrPath: string): string { - const base = String(fileNameOrPath || '').split(/[\\/]/).pop() || '' - const dotIdx = base.lastIndexOf('.') - return dotIdx > 0 ? base.slice(dotIdx).toLowerCase() : '' -} - -function normalizeIndexedFileEntry(f: DynamicBridge): RealIndexedFileEntry { - const p = String(f?.path || '') - const name = String(f?.name || p.split(/[\\/]/).pop() || '') - const sz = Number(f?.size ?? f?.sizeBytes ?? 0) - const isDir = Boolean(f?.is_dir || f?.isDir || f?.isDirectory) - const rawMtime = Number(f?.mtime ?? f?.mtimeMs ?? 0) - const mtimeMs = rawMtime > 1e11 ? rawMtime : rawMtime > 0 ? rawMtime * 1000 : Date.now() - const mtimeSec = rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime - if (p && sz >= 0) realFileSizeCache.set(p, sz) - return { - name, - path: p, - ext: extractFileExt(name || p), - isDir, - isDirectory: isDir, - size: sz, - sizeBytes: sz, - mtime: mtimeSec, - mtimeMs, - lastModifiedMs: mtimeMs - } -} - -function makeScanResult( - files: RealIndexedFileEntry[], - totalFiles: number, - totalBytes: number, - subdirs: RealDirectorySubdirSummary[], - meta: ScanResultMeta = {} -): RealDirectoryScanResult { - return { - files, - totalFiles, - fileCount: totalFiles, - totalBytes, - subdirs, - ...(meta.truncated ? { truncated: true } : {}), - ...(meta.approximate ? { approximate: true } : {}), - ...(typeof meta.visitedEntries === 'number' ? { visitedEntries: meta.visitedEntries } : {}), - [Symbol.iterator]() { - return files[Symbol.iterator]() - } - } -} - -/** - * 调用客户端的原生文件索引组件 (ztools-indexer) 检索文件 - */ -export async function searchRealIndexedFiles( - query: string, - limit = 40, - hostOverride?: DynamicBridge -): Promise { - if (!query || !query.trim()) return [] - const q = query.trim() - const safeLimit = Math.min(200, Math.max(1, Math.floor(limit || 40))) - - try { - const res = await callHostTransport<{ files?: DynamicBridge[] }>( - 'system_search_files', - { query: q, limit: safeLimit }, - hostOverride - ) - if (res.ok && res.data && Array.isArray(res.data.files)) { - return res.data.files.map(normalizeIndexedFileEntry) - } - - if (!hostOverride && typeof window !== 'undefined') { - const w = window as DynamicBridge - if (typeof w.__ztoolsLauncher?.searchFiles === 'function') { - const rawOuter = await w.__ztoolsLauncher.searchFiles(q, safeLimit) - const raw = rawOuter && typeof rawOuter === 'object' && 'data' in rawOuter && rawOuter.data ? rawOuter.data : rawOuter - if (raw && Array.isArray(raw.files)) { - return raw.files.map(normalizeIndexedFileEntry) - } - } - } - } catch { - // ignore - } - return [] -} - -/** - * 深度扫描指定真实物理目录树(支持符号链接穿透,如 AppData\Roaming\Tencent -> D:\Local\Roaming\Tencent) - * 返回该目录下 Top 文件列表、全树真实文件总数、全树真实总字节数与一级子目录汇总 - */ -export async function scanRealDirectoryTree( - dirPath: string, - limitOrOptions: number | ScanDirectoryTreeOptions = 160, - hostOverrideArg?: DynamicBridge -): Promise { - const result = await scanDirectoryTreeWithError(dirPath, limitOrOptions, hostOverrideArg) - return result.error ? { ...result.scan, error: result.error } : result.scan -} - -/** 一次界面扫描的错误汇总;多个目录并行扫描时保留可读目录的结果。 */ -export function createDirectoryScanner(hostOverride?: DynamicBridge) { - const failures = new Map() - return { - async scan(dir: string, options: number | ScanDirectoryTreeOptions = 160) { - const result = await scanRealDirectoryTree(dir, options, hostOverride) - const error = result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') - if (error) failures.set(dir, error) - else failures.delete(dir) - return result - }, - get error(): string | undefined { - if (!failures.size) return undefined - const s = ipcStrings() - const details = [...failures].slice(0, 3).map(([dir, error]) => `${dir}${s.dirErrorColon}${error}`).join(s.dirEntrySep) - return s.dirReadFailed(details, Math.max(0, failures.size - 3)) - } - } -} - -/** scanRealDirectoryTree 的实现:额外带回读取失败原因(目录不存在 / 为空 / 无权限 / 载荷异常) */ -async function scanDirectoryTreeWithError( - dirPath: string, - limitOrOptions: number | ScanDirectoryTreeOptions, - hostOverrideArg?: DynamicBridge -): Promise<{ scan: RealDirectoryScanResult; error?: string }> { - const empty = makeScanResult([], 0, 0, []) - if (!dirPath || !dirPath.trim()) return { scan: empty, error: 'EMPTY_DIRECTORY_PATH' } - const targetDir = dirPath.trim() - - const opts: ScanDirectoryTreeOptions = - typeof limitOrOptions === 'number' - ? { maxFiles: limitOrOptions, hostOverride: hostOverrideArg } - : { ...limitOrOptions, hostOverride: limitOrOptions?.hostOverride ?? hostOverrideArg } - - const rawLimit = opts.maxFiles ?? opts.collectTopN ?? 160 - const safeLimit = Math.min(200, Math.max(1, Math.floor(rawLimit || 160))) - const hostOverride = opts.hostOverride - const filterExt = opts.filterExt - const dirQuery = `dir:${targetDir}` - - try { - let rawPayload: DynamicBridge = null - const res = await callHostTransport( - 'system_search_files', - { query: dirQuery, limit: safeLimit }, - hostOverride - ) - if (res.ok && res.data) { - rawPayload = res.data - } - if (!rawPayload && !hostOverride && typeof window !== 'undefined') { - const w = window as DynamicBridge - if (typeof w.__ztoolsLauncher?.searchFiles === 'function') { - const rawOuter = await w.__ztoolsLauncher.searchFiles(dirQuery, safeLimit) - rawPayload = - rawOuter && typeof rawOuter === 'object' && 'data' in rawOuter && rawOuter.data - ? rawOuter.data - : rawOuter - } - } - - if ( - rawPayload && - Array.isArray(rawPayload.files) - ) { - let files: RealIndexedFileEntry[] = rawPayload.files.map(normalizeIndexedFileEntry) - if (filterExt instanceof RegExp) { - files = files.filter(f => !f.isDir && (filterExt.test(f.name) || filterExt.test(f.ext))) - // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索目标扩展名 - if (files.length === 0 && !hostOverride) { - const extTokens = (filterExt.source.match(/[a-z0-9]{2,5}/gi) || []) - .filter(t => !['thumbcache', 'iconcache'].includes(t.toLowerCase())) - .slice(0, 4) - // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 - const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() - const extraLists = await Promise.all( - extTokens.map(ext => searchRealIndexedFiles(`.${ext.toLowerCase()}`, 30, hostOverride)) - ) - const seen = new Set() - for (const list of extraLists) { - for (const item of list) { - if (!item.isDir && item.size > 0 && !seen.has(item.path)) { - if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { - seen.add(item.path) - files.push(item) - } - } - } - } - } - } - if (typeof opts.collectTopN === 'number' && opts.collectTopN > 0 && files.length > opts.collectTopN) { - files = files.slice(0, opts.collectTopN) - } - const subdirs: RealDirectorySubdirSummary[] = Array.isArray(rawPayload.subdirs) - ? rawPayload.subdirs.map((s: DynamicBridge) => ({ - name: String(s.name || ''), - path: String(s.path || ''), - fileCount: Number(s.file_count ?? s.fileCount ?? 0), - totalBytes: Number(s.total_bytes ?? s.totalBytes ?? 0), - mtime: Number(s.mtime || 0), - ...(s.approximate === true ? { approximate: true } : {}) - })) - : [] - const computedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) - const totalFilesCount = - filterExt instanceof RegExp ? files.length : Number(rawPayload.total_matches ?? files.length) - const totalBytesCount = - filterExt instanceof RegExp ? computedBytes : Number(rawPayload.total_bytes ?? computedBytes) - const visited = Number(rawPayload.visited_entries) - return { - scan: makeScanResult(files, totalFilesCount, totalBytesCount, subdirs, { - truncated: rawPayload.truncated === true, - approximate: rawPayload.approximate === true, - ...(Number.isFinite(visited) && visited >= 0 ? { visitedEntries: visited } : {}) - }), - ...(typeof rawPayload.scan_error === 'string' && rawPayload.scan_error ? { error: rawPayload.scan_error } : {}) - } - } - - // 深度扫描失败或回执无效时,仅以一级目录读取补回可见结果;不冒充完整目录树。 - const listing = await listDirectoryViaFilesystem(targetDir, hostOverride, { withSizes: true, limit: safeLimit }) - if (listing.ok && listing.entries.length > 0) { - const files: RealIndexedFileEntry[] = [] - let totalBytes = 0 - for (const entry of listing.entries) { - if (filterExt instanceof RegExp && !filterExt.test(entry.name) && !filterExt.test(entry.ext)) { - continue - } - files.push(entry) - totalBytes += entry.isDir ? 0 : entry.size - } - const incomplete = listing.entries.some(entry => entry.isDir) || listing.entries.length >= safeLimit - return { - scan: makeScanResult(files, files.filter(file => !file.isDir).length, totalBytes, [], { approximate: incomplete }), - ...(incomplete ? { error: res.error || ipcStrings().deepScanUnavailable } : {}) - } - } - return listing.ok ? { scan: empty } : { scan: empty, error: listing.error || 'DIRECTORY_READ_FAILED' } - } catch (error) { - return { scan: empty, error: error instanceof Error ? error.message : String(error) } - } -} - - -/** 目录读取不到任何条目(不存在 / 为空 / 无权限)时的错误码 */ -export const DIRECTORY_EMPTY_OR_UNREADABLE = 'DIRECTORY_EMPTY_OR_UNREADABLE' - -export interface RealDirectoryListingResult { - /** 目录内条目的完整路径;读取失败时为空数组 */ - entries: string[] - /** 读取失败或目录为空时的错误码 / 宿主错误信息 */ - error?: string -} - -export interface RealDirectChildrenResult { - /** 目录的直接子项(子目录在前),按路径去重 */ - entries: RealIndexedFileEntry[] - /** 宿主扫描达到条目上限,可能只返回了部分直接子项 */ - partial: boolean - error?: string -} - -function stripTrailingSeparators(p: string): string { - const trimmed = p.replace(/[\\/]+$/, '') - return trimmed || p.slice(0, 1) -} - -function isWindowsStylePath(p: string): boolean { - return /^[A-Za-z]:/.test(p) || p.startsWith('\\\\') || (p.includes('\\') && !p.includes('/')) -} - -function comparablePath(p: string): string { - const stripped = stripTrailingSeparators(String(p || '').trim()) - return isWindowsStylePath(stripped) ? stripped.replace(/\//g, '\\').toLowerCase() : stripped -} - -function parentDirOf(p: string): string { - const stripped = stripTrailingSeparators(String(p || '')) - const idx = Math.max(stripped.lastIndexOf('/'), stripped.lastIndexOf('\\')) - if (idx < 0) return '' - if (idx === 0) return stripped.slice(0, 1) - const parent = stripped.slice(0, idx) - return /^[A-Za-z]:$/.test(parent) ? `${parent}\\` : parent -} - -function isDirectChildPath(dirPath: string, candidate: string): boolean { - if (!candidate) return false - return comparablePath(parentDirOf(candidate)) === comparablePath(dirPath) -} - -function joinChildPath(dirPath: string, name: string): string { - const sep = isWindowsStylePath(dirPath) ? '\\' : '/' - const base = dirPath.replace(/[\\/]+$/, '') - return `${base}${sep}${name}` -} - -/** - * 通过 filesystem_get_directory_contents 读取一级目录(需宿主授权)。 - * 宿主真实返回 { success, files: [{ name, size, isDirectory, lastModified }] }(name 为文件名); - * 兼容旧测试替身返回的完整路径字符串数组。 - */ -async function listDirectoryViaFilesystem( - dirPath: string, - hostOverride: DynamicBridge, - options: { withSizes?: boolean; limit?: number } = {} -): Promise<{ ok: boolean; entries: RealIndexedFileEntry[]; error?: string }> { - const res = await callHostTransport('filesystem_get_directory_contents', { path: dirPath }, hostOverride) - if (!res.ok) return { ok: false, entries: [], error: res.error || 'DIRECTORY_READ_FAILED' } - const data = res.data - const rawList: unknown[] | null = Array.isArray(data) ? data : Array.isArray(data?.files) ? data.files : null - if (!rawList) return { ok: false, entries: [], error: 'INVALID_DIRECTORY_PAYLOAD' } - - const limit = Math.max(1, Math.floor(options.limit ?? 1000)) - const nowSec = Math.floor(Date.now() / 1000) - const entries: RealIndexedFileEntry[] = [] - const seen = new Set() - for (const item of rawList) { - if (entries.length >= limit) break - let entry: RealIndexedFileEntry | null = null - if (typeof item === 'string') { - const itemPath = item.trim() - if (!itemPath) continue - const name = itemPath.split(/[\\/]/).pop() || itemPath - const sz = options.withSizes ? await getRealFileSize(itemPath, hostOverride) : 0 - entry = normalizeIndexedFileEntry({ - name, - path: itemPath, - isDir: sz === 0 && !name.includes('.'), - size: sz, - mtime: nowSec - }) - } else if (item && typeof item === 'object' && typeof (item as DynamicBridge).name === 'string') { - const raw = item as DynamicBridge - const rawName = raw.name.trim() - if (!rawName || rawName === '.' || rawName === '..') continue - // 只接受文件名,或确实位于该目录下的完整路径,拒绝越界路径 - const fullPath = /[\\/]/.test(rawName) ? rawName : joinChildPath(dirPath, rawName) - if (!isDirectChildPath(dirPath, fullPath)) continue - const isDir = Boolean(raw.isDirectory ?? raw.isDir ?? raw.is_dir) - const parsedMtime = Date.parse(String(raw.lastModified || '')) - entry = normalizeIndexedFileEntry({ - name: fullPath.split(/[\\/]/).pop() || rawName, - path: fullPath, - isDir, - size: isDir ? 0 : Math.max(0, Number(raw.size) || 0), - mtime: Number.isFinite(parsedMtime) ? parsedMtime : nowSec - }) - } - if (!entry || seen.has(entry.path)) continue - seen.add(entry.path) - entries.push(entry) - } - return { ok: true, entries } -} - -/** - * 读取真实目录下的条目路径(真实宿主中优先走 dir: 扫描:一级子目录 + 全树 Top-N 大文件),并返回失败原因。 - * 目录不存在、为空或无权限时返回空列表与错误码,绝不用全盘关键词搜索结果冒充目录内容。 - */ -export async function listRealDirectoryContentsResult( - dirPath: string, - hostOverride?: DynamicBridge -): Promise { - if (!dirPath || !dirPath.trim()) return { entries: [], error: 'EMPTY_DIRECTORY_PATH' } - const targetDir = dirPath.trim() - - if (!hostOverride && isRealElectronHost()) { - const tree = await scanRealDirectoryTree(targetDir, 60) - const paths: string[] = [] - for (const s of tree.subdirs) { - if (s.path) paths.push(s.path) - } - for (const f of tree.files) { - if (f.path) paths.push(f.path) - } - if (paths.length > 0) return { entries: Array.from(new Set(paths)) } - } - - const listing = await listDirectoryViaFilesystem(targetDir, hostOverride) - if (!listing.ok) return { entries: [], error: listing.error } - if (listing.entries.length === 0) return { entries: [], error: DIRECTORY_EMPTY_OR_UNREADABLE } - return { entries: listing.entries.map(e => e.path) } -} - -/** - * 读取真实目录下的条目路径(保持旧签名:失败时返回空数组,需要失败原因请用 listRealDirectoryContentsResult) - */ -export async function listRealDirectoryContents( - dirPath: string, - hostOverride?: DynamicBridge -): Promise { - return (await listRealDirectoryContentsResult(dirPath, hostOverride)).entries -} - -/** - * 只列出目录的直接子项(子目录 + 直接位于该目录下的文件),用于文件夹预览、按目录改名等场景。 - * dir: 扫描结果中只保留 subdirs 与父目录等于 dirPath 的文件;扫描达到上限时 partial=true,由插件如实提示「仅显示部分」。 - */ -export async function listDirectChildren( - dirPath: string, - hostOverride?: DynamicBridge -): Promise { - if (!dirPath || !dirPath.trim()) return { entries: [], partial: false, error: 'EMPTY_DIRECTORY_PATH' } - const targetDir = dirPath.trim() - const scanLimit = 200 - const entries: RealIndexedFileEntry[] = [] - const seen = new Set() - const push = (entry: RealIndexedFileEntry) => { - const key = comparablePath(entry.path) - if (!entry.path || seen.has(key)) return - seen.add(key) - entries.push(entry) - } - - const { scan: tree, error } = await scanDirectoryTreeWithError(targetDir, { maxFiles: scanLimit, hostOverride }) - for (const s of tree.subdirs) { - if (!s.path || !isDirectChildPath(targetDir, s.path)) continue - push( - normalizeIndexedFileEntry({ - name: s.name || s.path.split(/[\\/]/).pop(), - path: s.path, - isDir: true, - size: s.totalBytes, - mtime: s.mtime - }) - ) - } - let directFileCount = 0 - for (const f of tree.files) { - if (!isDirectChildPath(targetDir, f.path)) continue - directFileCount++ - push(f) - } - // 宿主 total_matches 是全树文件数、subdirs[].file_count 是各子目录全树文件数,差值即直接子文件数; - // 拿到的直接子文件少于它就说明被 Top-N 截断了。计数不可用时按是否达到扫描上限判断 - const expectedDirectFiles = tree.totalFiles - tree.subdirs.reduce((sum, d) => sum + (Number(d.fileCount) || 0), 0) - const partial = - Number.isFinite(expectedDirectFiles) && expectedDirectFiles >= 0 - ? directFileCount < expectedDirectFiles - : tree.files.length >= scanLimit - if (entries.length > 0) { - return { entries, partial } - } - - if (tree.files.length > 0) { - // dir: 扫描只返回了深层文件(直接子文件被 Top-N 截掉),如实标注部分结果 - return { entries: [], partial: true, error: DIRECTORY_EMPTY_OR_UNREADABLE } - } - return { entries: [], partial: false, error: error || DIRECTORY_EMPTY_OR_UNREADABLE } -} - -/** - * 获取真实文件字节大小(优先用扫描结果里的大小,再走 filesystem_get_file_size);读不到时返回 0 - */ -export async function getRealFileSize( - filePath: string, - hostOverride?: DynamicBridge -): Promise { - if (!filePath) return 0 - if (!hostOverride && realFileSizeCache.has(filePath)) { - const cached = realFileSizeCache.get(filePath)! - if (cached > 0) return cached - } - const res = await callHostTransport('filesystem_get_file_size', { path: filePath }, hostOverride) - // 客户端返回 { success, size }(目录时 size 为 -1),旧的测试替身直接返回数字 - const size = typeof res.data === 'number' ? res.data : res.data?.size - if (res.ok && typeof size === 'number' && Number.isFinite(size) && size >= 0) { - realFileSizeCache.set(filePath, size) - return size - } - return 0 -} - -/** - * 在访达 / 资源管理器中定位并高亮文件或目录。 - * 定位失败直接返回 false,不能改用“打开”:对可执行文件那等于运行它。 - */ -export async function showRealItemInFolder( - fullPath: string, - hostOverride?: DynamicBridge -): Promise { - if (!fullPath) return false - const res = await callHostTransport('shell_show_item_in_folder', { fullPath }, hostOverride) - return res.ok -} - -/** - * 使用系统默认程序打开文件或目录 - */ -export async function openRealPath( - fullPath: string, - hostOverride?: DynamicBridge -): Promise { - if (!fullPath) return false - const res = await callHostTransport('shell_open_path', { fullPath }, hostOverride) - return res.ok -} - -/** - * 将真实文件或目录移入系统回收站(安全可恢复删除) - */ -export async function trashRealItem( - fullPath: string, - hostOverride?: DynamicBridge -): Promise<{ ok: boolean; error?: string; errorCode?: string; errorDetails?: Record }> { - if (!fullPath) return { ok: false, error: ipcStrings().pathEmpty } - const res = await callHostTransport('shell_trash_item', { fullPath }, hostOverride) - return { - ok: res.ok, - error: res.error, - ...(!res.ok && res.errorCode ? { errorCode: res.errorCode } : {}), - ...(!res.ok && res.errorDetails ? { errorDetails: res.errorDetails } : {}) - } -} - -export interface NativeInvocationResult { - ok: boolean - code: number - message: string - data?: T - error?: string - errorCode?: string - errorDetails?: Record -} - -export interface DllCapabilityResponse { - ok: boolean - code: number - data: T | null - message?: string - error?: string - errorCode?: string - errorDetails?: Record - pluginName: string - method: string - fromFallback?: boolean -} - -/** 声明式能力菜单项及其调用回执,供相同宿主协议的插件共用。 */ -export interface CapabilityActionItem { - id: string - title: string - subtitle: string - tag: string - method: string - params: Record -} - -export type PluginInvocationResult = Pick< - DllCapabilityResponse, 'ok' | 'pluginName' | 'method' | 'error' | 'errorCode' | 'errorDetails' | 'fromFallback' -> & { data?: unknown } - -/** 多个原生能力插件共用的参数边界校验;保护目标由各插件按自身业务提供。 */ -export function validateNativeCapabilityPayload( - method: string, - params: unknown, - forbiddenPattern: RegExp, - forbiddenReason: string -): { valid: boolean; error?: string } { - const s = ipcStrings() - if (typeof method !== 'string' || method.trim().length === 0) { - return { valid: false, error: s.invalidMethodEmpty } - } - if (method.length > 128 || !/^[A-Za-z0-9_]+$/.test(method.trim())) { - return { valid: false, error: s.invalidMethodFormat } - } - if (params === null || params === undefined || typeof params !== 'object' || Array.isArray(params)) { - return { valid: false, error: s.invalidParamsObject } - } - - const record = params as Record - for (const [key, val] of Object.entries(record)) { - if (typeof val === 'string') { - if (val.length > 4096) { - return { valid: false, error: s.paramTooLong(key) } - } - if (forbiddenPattern.test(val)) { - return { valid: false, error: `SECURITY_INTERCEPTED: ${forbiddenReason}` } - } - } else if (typeof val === 'number') { - if (!Number.isFinite(val) || val < -1000 || val > 100_000_000) { - return { valid: false, error: s.paramOutOfRange(key) } - } - } - } - - return { valid: true } -} - -export async function invokeDllPluginCapability( - pluginName: string, - method: string, - params: Record = {}, - hostBridge?: DynamicBridge, - offlineFallback?: () => T | Promise -): Promise> { - const s = ipcStrings() - if (!method || typeof method !== 'string' || method.trim().length === 0) { - return { - ok: false, - code: -1, - data: null, - message: s.methodParamEmpty, - error: s.invalidMethodType, - pluginName, - method: String(method || '') - } - } - - const trimmedMethod = method.trim() - - const unwrapDllRawPayload = (raw: unknown, unwrapDataProperty: boolean): DllCapabilityResponse => { - let parsed: DynamicBridge = raw - if (typeof raw === 'string') { - try { - parsed = JSON.parse(raw) - } catch { - throw new Error(s.malformedDllResponse) - } - } - if (parsed && typeof parsed === 'object') { - if ('error' in parsed && parsed.error !== undefined && parsed.error !== null && parsed.error !== '') { - const errMsg = `DLL_ERROR: ${String(parsed.error)}` - return { - ok: false, - code: typeof parsed.code === 'number' ? parsed.code : -1, - data: null, - message: errMsg, - error: errMsg, - ...extractIpcErrorMeta(parsed), - ...extractIpcErrorMeta(parsed.error), - pluginName, - method: trimmedMethod, - fromFallback: false - } - } - if ('ok' in parsed && parsed.ok === false) { - const errMsg = `DLL_ERROR: ${String(parsed.error || parsed.message || s.unknownDllError)}` - return { - ok: false, - code: typeof parsed.code === 'number' ? parsed.code : -1, - data: null, - message: errMsg, - error: errMsg, - ...extractIpcErrorMeta(parsed), - ...extractIpcErrorMeta(parsed.error), - pluginName, - method: trimmedMethod, - fromFallback: false - } - } - const dataPayload = unwrapDataProperty && 'data' in parsed && parsed.data !== undefined ? parsed.data : parsed - return { - ok: true, - code: typeof parsed.code === 'number' ? parsed.code : 0, - data: dataPayload as T, - message: typeof parsed.message === 'string' ? parsed.message : undefined, - pluginName, - method: trimmedMethod, - fromFallback: false - } - } - return { - ok: true, - code: 0, - data: (parsed ?? null) as T, - pluginName, - method: trimmedMethod, - fromFallback: false - } - } - - const wrapCaughtDllError = (err: unknown): DllCapabilityResponse => { - const message = err instanceof Error ? err.message : String(err) - if (message.startsWith('MALFORMED_DLL_RESPONSE:')) { - throw err - } - const errMsg = `NATIVE_CALL_FAILED: ${message}` - return { - ok: false, - code: -1, - data: null, - message: errMsg, - error: errMsg, - ...extractIpcErrorMeta(err), - pluginName, - method: trimmedMethod, - fromFallback: false - } - } - - if (hostBridge && typeof hostBridge.invokeNative === 'function') { - try { - const raw = await hostBridge.invokeNative(pluginName, trimmedMethod, params) - return unwrapDllRawPayload(raw, true) - } catch (err: unknown) { - return wrapCaughtDllError(err) - } - } - - const runtimeHost = (hostBridge ?? (globalThis as Record).ztools) as - | { dllplugin?: { call?: (plugin: string, fn: string, payload: unknown) => Promise | unknown } } - | undefined - - const callFn = runtimeHost?.dllplugin?.call - if (typeof callFn === 'function') { - try { - const raw = await callFn.call(runtimeHost?.dllplugin, pluginName, trimmedMethod, params) - return unwrapDllRawPayload(raw, false) - } catch (err: unknown) { - return wrapCaughtDllError(err) - } - } - - const ipcRes = await callHostTransport( - 'dllplugin_call', - { - plugin: pluginName, - func: trimmedMethod, - params - }, - hostBridge - ) - - if (ipcRes.ok && ipcRes.data !== undefined && ipcRes.data !== null) { - return unwrapDllRawPayload(ipcRes.data, false) - } - - const isExplicitTransportFailure = - typeof ipcRes.error === 'string' && - ipcRes.error.length > 0 && - ipcRes.error !== 'NO_WINDOW_ENV' && - !ipcRes.error.startsWith('METHOD_NOT_AVAILABLE:') - - if ( - isRealElectronHost(hostBridge) || - isRealElectronHost() || - Boolean((hostBridge as DynamicBridge)?.__isRealHost) || - isExplicitTransportFailure - ) { - const errMsg = - ipcRes.error || s.hostIpcFailed(pluginName, trimmedMethod) - return { - ok: false, - code: -1, - data: null, - message: errMsg, - error: errMsg, - ...(ipcRes.errorCode ? { errorCode: ipcRes.errorCode } : {}), - ...(ipcRes.errorDetails ? { errorDetails: ipcRes.errorDetails } : {}), - pluginName, - method: trimmedMethod, - fromFallback: false - } - } - - if (typeof offlineFallback === 'function') { - const fallbackData = await offlineFallback() - return { - ok: true, - code: 0, - data: fallbackData, - pluginName, - method: trimmedMethod, - fromFallback: true - } - } - - const unavailableMsg = s.hostUnavailable(pluginName, trimmedMethod) - return { - ok: false, - code: -1, - data: null, - message: unavailableMsg, - error: unavailableMsg, - ...(ipcRes.errorCode ? { errorCode: ipcRes.errorCode } : {}), - ...(ipcRes.errorDetails ? { errorDetails: ipcRes.errorDetails } : {}), - pluginName, - method: trimmedMethod, - fromFallback: true - } -} - -export function formatBytes(bytes: number, decimals = 1): string { - const num = Number(bytes) - if (!Number.isFinite(num) || num <= 0) return '0 B' - if (num < 1024) return `${Math.round(num)} B` - const units = ['B', 'KB', 'MB', 'GB', 'TB'] - let val = num - let idx = 0 - while (val >= 1024 && idx < units.length - 1) { - val /= 1024 - idx += 1 - } - const safeDecimals = Math.max(0, Math.floor(decimals)) - return `${val >= 100 ? val.toFixed(0) : val.toFixed(safeDecimals)} ${units[idx]}` -} - -export function joinWinPath(...segments: string[]): string { - return segments - .filter(s => typeof s === 'string' && s.trim().length > 0) - .map((s, i) => (i === 0 ? s.replace(/[\\/]+$/, '') : s.replace(/^[\\/]+|[\\/]+$/g, ''))) - .join('\\') -} - -export interface RealEnvPaths { - home: string - userProfile: string - appData: string - localAppData: string - temp: string - downloads: string - documents: string - desktop: string - pictures: string - videos: string - music: string -} - -export async function getRealEnvPaths(hostOverride?: DynamicBridge): Promise { - const [homeRaw, appData, downloads, documents, desktop, pictures, videos, music] = await Promise.all([ - getRealSystemPath('home', hostOverride), - getRealSystemPath('appData', hostOverride), - getRealSystemPath('downloads', hostOverride), - getRealSystemPath('documents', hostOverride), - getRealSystemPath('desktop', hostOverride), - getRealSystemPath('pictures', hostOverride), - getRealSystemPath('videos', hostOverride), - getRealSystemPath('music', hostOverride) - ]) - const home = homeRaw || 'C:\\Users\\Default' - const isPosix = home.startsWith('/') - const tempRes = hostOverride ? await getRealSystemPath('temp', hostOverride) : '' - if (isPosix) { - return { - home, - userProfile: home, - appData: appData || `${home}/Library/Application Support`, - localAppData: `${home}/Library/Application Support`, - temp: tempRes || '/tmp', - downloads: downloads || `${home}/Downloads`, - documents: documents || `${home}/Documents`, - desktop: desktop || `${home}/Desktop`, - pictures: pictures || `${home}/Pictures`, - videos: videos || `${home}/Videos`, - music: music || `${home}/Music` - } - } - return { - home, - userProfile: home, - appData: appData || `${home}\\AppData\\Roaming`, - localAppData: `${home}\\AppData\\Local`, - temp: tempRes || `${home}\\AppData\\Local\\Temp`, - downloads: downloads || `${home}\\Downloads`, - documents: documents || `${home}\\Documents`, - desktop: desktop || `${home}\\Desktop`, - pictures: pictures || `${home}\\Pictures`, - videos: videos || `${home}\\Videos`, - music: music || `${home}\\Music` - } -} - -export const resolveRealSpecialPaths = getRealEnvPaths - -export async function readRealDirectory( - dirPath: string, - hostOverride?: DynamicBridge -): Promise { - if (!dirPath) return [] - const tree = await scanRealDirectoryTree(dirPath, { maxFiles: 120, hostOverride }) - const entries: RealIndexedFileEntry[] = [] - for (const s of tree.subdirs) { - entries.push( - normalizeIndexedFileEntry({ - name: s.name, - path: s.path, - isDir: true, - isDirectory: true, - size: s.totalBytes, - mtime: s.mtime - }) - ) - } - for (const f of tree.files) { - entries.push(f) - } - // scanRealDirectoryTree 已在 dir: 扫描无结果时退回一级目录读取;仍为空即目录不存在 / 为空 / 无权限,如实返回空列表 - return entries -} - -export async function moveRealFilesToTrash( - paths: string[], - hostOverride?: DynamicBridge -): Promise<{ - ok: boolean - trashedCount: number - deletedCount: number - failedPaths: string[] - error?: string -}> { - let deletedCount = 0 - const failedPaths: string[] = [] - let lastError: string | undefined - for (const p of paths) { - if (!p) continue - const res = await trashRealItem(p, hostOverride) - if (res.ok) { - deletedCount += 1 - } else { - failedPaths.push(p) - if (res.error) lastError = res.error - } - } - return { - ok: deletedCount > 0 || paths.length === 0, - trashedCount: deletedCount, - deletedCount, - failedPaths, - error: lastError - } -} - -const CAPABILITY_TO_PLUGIN_MAP: Record = { - 'mover.relocateWithJunction': { plugin: 'MoverPlugin', func: 'relocateWithJunction' }, - 'mover.scanCandidates': { plugin: 'MoverPlugin', func: 'scanCandidates' }, - 'recovery.restoreFile': { plugin: 'DataRecoveryPlugin', func: 'restoreFile' }, - 'recovery.scanDeletedFiles': { plugin: 'DataRecoveryPlugin', func: 'scanDeletedFiles' }, - 'shredder.secureWipeFile': { plugin: 'ShredderPlugin', func: 'secureWipeFile' }, - 'shredder.scanCandidates': { plugin: 'ShredderPlugin', func: 'scanCandidates' }, - 'backup.createSnapshotArchive': { plugin: 'SystemBackupPlugin', func: 'createSnapshotArchive' }, - 'backup.restoreSnapshotArchive': { plugin: 'SystemBackupPlugin', func: 'restoreSnapshotArchive' }, - 'backup.scanSnapshots': { plugin: 'SystemBackupPlugin', func: 'scanSnapshots' }, - 'sqlite.execute': { plugin: 'SqlitePlugin', func: 'execute' }, - 'sqlite.query': { plugin: 'SqlitePlugin', func: 'executeQuery' }, - 'sqlite.inspectWorkspace': { plugin: 'SqlitePlugin', func: 'inspectWorkspace' } -} - -export async function invokeHostCapability( - capability: string, - params: Record = {}, - hostOverride?: DynamicBridge -): Promise> { - const normalizedMethod = capability.replace(/\./g, '_') - - // 若测试显式注入了对应 normalizedMethod 的 mock 函数,优先调用测试桩 - if (hostOverride && typeof hostOverride[normalizedMethod] === 'function') { - const mockRes = await callHostTransport(normalizedMethod, params, hostOverride) - return { - ok: mockRes.ok, - code: mockRes.ok ? 0 : -1, - message: mockRes.ok ? 'OK' : mockRes.error || ipcStrings().callFailed, - data: mockRes.data, - error: mockRes.error, - ...(!mockRes.ok && mockRes.errorCode ? { errorCode: mockRes.errorCode } : {}), - ...(!mockRes.ok && mockRes.errorDetails ? { errorDetails: mockRes.errorDetails } : {}) - } - } - - if (capability === 'system.info') { - const drives = await probeRealDiskDrives(['C', 'D', 'E', 'F'], hostOverride) - return { - ok: true, - code: 0, - message: 'OK', - data: { - storage: drives.map(d => ({ - mount: d.drive, - fs: d.drive, - size: d.totalBytes, - total: d.totalBytes, - used: d.usedBytes, - available: d.availableBytes, - free: d.availableBytes, - percent: d.usagePercent - })) - } as unknown as T - } - } - if (capability === 'filesystem.deleteItem') { - const targetPath = String(params.path || params.fullPath || '') - const tr = await trashRealItem(targetPath, hostOverride) - const s = ipcStrings() - return { - ok: tr.ok, - code: tr.ok ? 0 : -1, - message: tr.ok ? s.movedToTrash : tr.error || s.deleteFailed, - error: tr.error, - ...(!tr.ok && tr.errorCode ? { errorCode: tr.errorCode } : {}), - ...(!tr.ok && tr.errorDetails ? { errorDetails: tr.errorDetails } : {}) - } - } - if (capability === 'system.showItemInFolder') { - const targetPath = String(params.path || params.fullPath || '') - const s = ipcStrings() - if (!targetPath) { - return { ok: false, code: -1, message: s.revealFailed } - } - const res = await callHostTransport('shell_show_item_in_folder', { fullPath: targetPath }, hostOverride) - return { - ok: res.ok, - code: res.ok ? 0 : -1, - message: res.ok ? s.revealedInFolder : res.error || s.revealFailed, - ...(!res.ok && res.error ? { error: res.error } : {}), - ...(!res.ok && res.errorCode ? { errorCode: res.errorCode } : {}), - ...(!res.ok && res.errorDetails ? { errorDetails: res.errorDetails } : {}) - } - } - if (capability === 'filesystem.openItem' || capability === 'system.openUrl') { - const target = String(params.path || params.url || params.fullPath || '') - const method = capability === 'system.openUrl' ? 'shell_open_external' : 'shell_open_path' - const res = await callHostTransport( - method, - capability === 'system.openUrl' ? { url: target } : { fullPath: target }, - hostOverride - ) - const s = ipcStrings() - return { - ok: res.ok, - code: res.ok ? 0 : -1, - message: res.ok ? s.opened : res.error || s.openFailed, - data: res.data, - error: res.error, - ...(!res.ok && res.errorCode ? { errorCode: res.errorCode } : {}), - ...(!res.ok && res.errorDetails ? { errorDetails: res.errorDetails } : {}) - } - } - - const pluginMapping = CAPABILITY_TO_PLUGIN_MAP[capability] - if (pluginMapping) { - const dllRes = await invokePluginService( - pluginMapping.plugin, - pluginMapping.func, - params, - hostOverride - ) - if (dllRes.ok) return dllRes - if (hostOverride) { - const fallbackMock = await callHostTransport(normalizedMethod, params, hostOverride) - if (fallbackMock.ok) { - return { - ok: true, - code: 0, - message: 'OK', - data: fallbackMock.data - } - } - } - return dllRes - } - - const res = await callHostTransport(normalizedMethod, params, hostOverride) - return { - ok: res.ok, - code: res.ok ? 0 : -1, - message: res.ok ? 'OK' : res.error || ipcStrings().callFailed, - data: res.data, - error: res.error, - ...(!res.ok && res.errorCode ? { errorCode: res.errorCode } : {}), - ...(!res.ok && res.errorDetails ? { errorDetails: res.errorDetails } : {}) - } -} - -export async function invokePluginService( - pluginName: string, - action: string, - params: Record = {}, - hostOverride?: DynamicBridge -): Promise> { - const s = ipcStrings() - // 1. 若测试注入了专门拦截 plugin_invoke 的 mock,支持调用 - if (hostOverride && typeof hostOverride.plugin_invoke === 'function') { - const mockRes = await callHostTransport( - 'plugin_invoke', - { plugin: pluginName, action, params }, - hostOverride - ) - return { - ok: mockRes.ok, - code: mockRes.ok ? 0 : -1, - message: mockRes.ok ? 'OK' : mockRes.error || s.pluginCallNotReady, - data: mockRes.data, - error: mockRes.error, - ...(!mockRes.ok && mockRes.errorCode ? { errorCode: mockRes.errorCode } : {}), - ...(!mockRes.ok && mockRes.errorDetails ? { errorDetails: mockRes.errorDetails } : {}) - } - } - - // 2. 优先走真实 Electron IPC 的 dllplugin_call 通道 - const dllRes = await callHostTransport( - 'dllplugin_call', - { plugin: pluginName, func: action, params }, - hostOverride - ) - if (dllRes.ok) { - const inner = dllRes.data - if (inner && typeof inner === 'object' && typeof inner.error === 'string' && inner.error.length > 0 && inner.ok !== true) { - return { - ok: false, - code: -1, - message: inner.error, - error: inner.error, - ...extractIpcErrorMeta(inner) - } - } - return { - ok: true, - code: 0, - message: 'OK', - data: inner as T - } - } - - // 3. 兼容单元测试中通过 transport.call('plugin_invoke') 注入的测试桩 - if (hostOverride) { - const legacyRes = await callHostTransport( - 'plugin_invoke', - { plugin: pluginName, action, params }, - hostOverride - ) - if (legacyRes.ok) { - return { - ok: true, - code: 0, - message: 'OK', - data: legacyRes.data - } - } - } - - // 4. 兼容旧版 globalThis.ztools.dllplugin.call - const g = globalThis as DynamicBridge - if (!hostOverride && typeof g?.ztools?.dllplugin?.call === 'function') { - try { - const raw = await g.ztools.dllplugin.call(pluginName, action, params) - if (raw && typeof raw === 'object' && raw.ok === false) { - return { - ok: false, - code: -1, - message: String(raw.error || s.callFailed), - error: String(raw.error || s.callFailed), - ...extractIpcErrorMeta(raw), - ...extractIpcErrorMeta(raw.error) - } - } - const data = raw && typeof raw === 'object' && 'data' in raw ? raw.data : raw - return { ok: true, code: 0, message: 'OK', data: data as T } - } catch (err: DynamicBridge) { - return { - ok: false, - code: -1, - message: err instanceof Error ? err.message : String(err), - error: err instanceof Error ? err.message : String(err), - ...extractIpcErrorMeta(err) - } - } - } - - return { - ok: false, - code: -1, - message: dllRes.error || s.pluginCallNotReady, - error: dllRes.error || s.pluginCallNotReady, - ...(dllRes.errorCode ? { errorCode: dllRes.errorCode } : {}), - ...(dllRes.errorDetails ? { errorDetails: dllRes.errorDetails } : {}) - } -} - -const SHA256_K = new Uint32Array([ - 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, - 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, - 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, - 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, - 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, - 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, - 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, - 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 -]) - -function rotr32(x: number, n: number): number { - return (x >>> n) | (x << (32 - n)) -} - -/** - * 标准 FIPS 180-4 SHA-256 真实字节摘要算法(返回 64 位小写 Hex) - */ -export function computeRealSha256Hex(input: string | Uint8Array): string { - const bytes = - typeof input === 'string' ? new TextEncoder().encode(input) : new Uint8Array(input || []) - const bitLen = bytes.length * 8 - const padLen = ((bytes.length + 9 + 63) & ~63) - const buf = new Uint8Array(padLen) - buf.set(bytes, 0) - buf[bytes.length] = 0x80 - const view = new DataView(buf.buffer) - view.setUint32(padLen - 8, Math.floor(bitLen / 0x100000000), false) - view.setUint32(padLen - 4, bitLen >>> 0, false) - - let h0 = 0x6a09e667 - let h1 = 0xbb67ae85 - let h2 = 0x3c6ef372 - let h3 = 0xa54ff53a - let h4 = 0x510e527f - let h5 = 0x9b05688c - let h6 = 0x1f83d9ab - let h7 = 0x5be0cd19 - - const w = new Uint32Array(64) - for (let offset = 0; offset < padLen; offset += 64) { - for (let i = 0; i < 16; i++) { - w[i] = view.getUint32(offset + i * 4, false) - } - for (let i = 16; i < 64; i++) { - const s0 = rotr32(w[i - 15], 7) ^ rotr32(w[i - 15], 18) ^ (w[i - 15] >>> 3) - const s1 = rotr32(w[i - 2], 17) ^ rotr32(w[i - 2], 19) ^ (w[i - 2] >>> 10) - w[i] = (w[i - 16] + s0 + w[i - 7] + s1) >>> 0 - } - - let a = h0 - let b = h1 - let c = h2 - let d = h3 - let e = h4 - let f = h5 - let g = h6 - let h = h7 - - for (let i = 0; i < 64; i++) { - const S1 = rotr32(e, 6) ^ rotr32(e, 11) ^ rotr32(e, 25) - const ch = (e & f) ^ (~e & g) - const temp1 = (h + S1 + ch + SHA256_K[i] + w[i]) >>> 0 - const S0 = rotr32(a, 2) ^ rotr32(a, 13) ^ rotr32(a, 22) - const maj = (a & b) ^ (a & c) ^ (b & c) - const temp2 = (S0 + maj) >>> 0 - - h = g - g = f - f = e - e = (d + temp1) >>> 0 - d = c - c = b - b = a - a = (temp1 + temp2) >>> 0 - } - - h0 = (h0 + a) >>> 0 - h1 = (h1 + b) >>> 0 - h2 = (h2 + c) >>> 0 - h3 = (h3 + d) >>> 0 - h4 = (h4 + e) >>> 0 - h5 = (h5 + f) >>> 0 - h6 = (h6 + g) >>> 0 - h7 = (h7 + h) >>> 0 - } - - return [h0, h1, h2, h3, h4, h5, h6, h7] - .map(v => (v >>> 0).toString(16).padStart(8, '0')) - .join('') -} - -/** - * 读取本地文件真实字节并计算标准 SHA-256:宿主 filesearch_sha256(只接受 path 字段)优先,Windows 上再试 FileComparePlugin。 - * 都拿不到时返回空字符串,由调用方提示失败;不再把文件按 UTF-8 文本读出来再算(二进制文件会算出错误的值)。 - */ -export async function computeRealFileSha256( - filePath: string, - hostOverride?: DynamicBridge -): Promise { - if (!filePath || !filePath.trim()) return '' - const target = filePath.trim() - - const shaRes = await callHostTransport('filesearch_sha256', { fullPath: target }, hostOverride) - if (shaRes.ok && shaRes.data) { - const hash = typeof shaRes.data === 'string' ? shaRes.data : String(shaRes.data?.sha256 || shaRes.data?.hash || '') - if (/^[0-9a-f]{64}$/i.test(hash)) return hash.toLowerCase() - } - - const dllRes = await invokePluginService('FileComparePlugin', 'computeFileSha256', { path: target }, hostOverride) - if (dllRes.ok && dllRes.data) { - const hash = typeof dllRes.data === 'string' ? dllRes.data : String(dllRes.data?.sha256 || dllRes.data?.hash || '') - if (/^[0-9a-f]{64}$/i.test(hash)) return hash.toLowerCase() - } - - return '' -} - -export async function readRealClipboardText(hostOverride?: DynamicBridge): Promise { - const res = await callHostTransport('clipboard_read_text', {}, hostOverride) - if (res.ok && res.data !== undefined && res.data !== null) { - if (typeof res.data === 'string') return res.data - if (typeof res.data?.text === 'string') return res.data.text - } - try { - if (typeof navigator !== 'undefined' && navigator.clipboard?.readText) { - return await navigator.clipboard.readText() - } - } catch { - // ignore - } - return '' -} - -export async function writeRealClipboardText(text: string, hostOverride?: DynamicBridge): Promise { - const payload = { text: String(text || '') } - const res = await callHostTransport('clipboard_copy_text', payload, hostOverride) - if (res.ok) return true - const fallbackRes = await callHostTransport('clipboard_write_text', payload, hostOverride) - if (fallbackRes.ok) return true - try { - if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) { - await navigator.clipboard.writeText(String(text || '')) - return true - } - } catch { - // ignore - } - return false -} - -export async function showRealToast( - title: string, - style: 'success' | 'failure' | 'info' = 'info' -): Promise { - try { - const { showToast, Toast } = await import('@ztools/declarative-ui') - await showToast({ - title, - style: - style === 'success' - ? Toast.Style.Success - : style === 'failure' - ? Toast.Style.Failure - : Toast.Style.Animated - }) - } catch { - // ignore - } -} - diff --git a/extensions/batch-audio/src/tool-runtime.ts b/extensions/batch-audio/src/tool-runtime.ts new file mode 100644 index 00000000..29670de2 --- /dev/null +++ b/extensions/batch-audio/src/tool-runtime.ts @@ -0,0 +1,637 @@ +/** + * 宿主薄原语与基础系统能力传输层(唯一权威公共源文件,纯标准 IPC,零原生 DLL 依赖) + * + * 修改本文件后需同步复制到各使用插件的 src/tool-runtime.ts, + * 构建脚本 build-declarative.mjs 会在编译前校验副本与本文件一字不差。 + */ + +import { getHostTransport } from '@ztools/declarative-ui' + +export type ToolCapabilityStatus = 'ready' | 'needs_provisioning' | 'unsupported' + +export interface ToolCapabilityDescriptor { + readonly primitiveId: string + readonly domain: string + readonly summary: string + readonly ipcMethods: readonly string[] + readonly requiredPermissions: readonly string[] + readonly status: ToolCapabilityStatus + readonly optionalExtensions: readonly string[] +} + +export interface ToolRuntimeCapabilitiesSnapshot { + readonly contractVersion: number + readonly platform: 'windows' | 'macos' | 'other' + readonly domains: readonly string[] + readonly capabilities: readonly ToolCapabilityDescriptor[] +} + +export interface ToolRuntimeEnsureResult { + readonly primitiveId: string + readonly status: ToolCapabilityStatus + readonly provisioned: boolean +} + +export interface ToolCapabilitiesEnsureResult { + readonly ok: boolean + readonly status: ToolCapabilityStatus + readonly provisioned: boolean + readonly failedPrimitiveId?: string + readonly error?: string + readonly errorCode?: string + readonly errorDetails?: Record +} + +export interface ToolTaskCancelResult { + readonly taskId: string + readonly cancelled: boolean +} + +export interface ToolPathSlot { + readonly grantId?: string + readonly relativePath?: string + readonly path?: string +} + +export interface ToolProgressEvent { + readonly taskId: string + readonly primitiveId?: string + readonly phase: 'provisioning' | 'running' | 'finalizing' | 'completed' | 'cancelled' | 'failed' + readonly percent?: number + readonly transferredBytes?: number + readonly totalBytes?: number + readonly speedBytesPerSec?: number + readonly stage?: string + readonly errorCode?: string + readonly retryable?: boolean + readonly userAction?: string + readonly message?: string + readonly timestamp?: number +} + +export type MediaTranscodeRunResult = + | { readonly status: 'done'; readonly outputBytes: number; readonly durationMs: number } + | { readonly status: 'cancelled' } + | { + readonly status: 'failed' + readonly error?: string + readonly errorCode?: string + readonly errorDetails?: Record + } + +export interface HostTransportResult { + ok: boolean + data?: T + error?: string + errorCode?: string + errorDetails?: Record +} + +export interface HostCallOptions { + timeoutMs?: number +} + +type TransportMethodFn = (req: { messageId: string; params: Record; timeoutMs?: number }) => Promise + +interface WindowHostBridge { + __ztoolsElectron?: { + transport?: { + methods?: Record + } + } + ztools?: { + transport?: { + methods?: Record + call?: (method: string, params: Record, options?: { timeoutMs?: number }) => Promise + } + events?: { + subscribe?: (event: string) => Promise | void + on?: (event: string, cb: (payload: unknown) => void) => (() => void) | void + off?: (event: string, cb: (payload: unknown) => void) => void + } + } +} + +interface HostOverrideLike { + transport?: { + call?: (method: string, params: Record, options?: { timeoutMs?: number }) => Promise + } + [method: string]: unknown +} + +let reqSeq = 1 + +export function nextMessageId(prefix = 'tool'): string { + reqSeq = (reqSeq + 1) % 1_000_000 + return `${prefix}_${Date.now()}_${reqSeq}` +} + +export function asRecord(value: unknown): Record | null { + return value && typeof value === 'object' && !Array.isArray(value) + ? (value as Record) + : null +} + +function extractErrorMeta(errObj: unknown): { + errorCode?: string + errorDetails?: Record +} { + const rec = asRecord(errObj) + if (!rec) return {} + const errorCode = + typeof rec.errorCode === 'string' && rec.errorCode.trim() + ? rec.errorCode.trim() + : typeof rec.code === 'string' && rec.code.trim() + ? rec.code.trim() + : undefined + const rawDetails = asRecord(rec.errorDetails) ?? asRecord(rec.details) ?? undefined + return { + ...(errorCode ? { errorCode } : {}), + ...(rawDetails ? { errorDetails: rawDetails } : {}) + } +} + +function toTransportError(err: unknown): HostTransportResult { + return { + ok: false, + error: err instanceof Error ? err.message : String(err), + ...extractErrorMeta(err) + } +} + +function buildFailureResult(rec: Record, fallbackMsg: string): HostTransportResult { + const errObj = asRecord(rec.error) + const errMsg = errObj + ? String(errObj.message || errObj.code || JSON.stringify(errObj)) + : String(rec.error || rec.message || fallbackMsg) + return { ok: false, error: errMsg, ...extractErrorMeta(rec), ...extractErrorMeta(errObj) } +} + +function unwrapTransportResponse(raw: unknown): HostTransportResult { + if (raw === null || raw === undefined) { + return { ok: false, error: 'EMPTY_IPC_RESPONSE', errorCode: 'EMPTY_IPC_RESPONSE' } + } + if (typeof raw !== 'object') { + return { ok: true, data: raw as T } + } + const outer = asRecord(raw) + if (!outer) { + return { ok: true, data: raw as T } + } + if (outer.success === false || outer.ok === false) { + return buildFailureResult(outer, 'IPC_CALL_FAILED') + } + + const firstLayer = 'data' in outer && outer.data !== undefined ? outer.data : outer + const inner = asRecord(firstLayer) + if (inner) { + if (inner.success === false || inner.ok === false) { + return buildFailureResult(inner, 'IPC_INNER_FAILED') + } + if ('data' in inner && inner.data !== undefined) { + return { ok: true, data: inner.data as T } + } + } + + return { ok: true, data: firstLayer as T } +} + +/** 判断当前是否处于真实的 ZTools Electron 渲染进程宿主环境 */ +export function isRealElectronHost(hostOverride?: unknown): boolean { + if (hostOverride) return true + if (typeof window === 'undefined') return false + const w = window as unknown as WindowHostBridge + return Boolean( + w.__ztoolsElectron?.transport?.methods || + w.ztools?.transport?.call || + w.ztools?.transport?.methods + ) +} + +/** 统一调用宿主 IPC 传输层(优先测试桩,其次 declarative-ui 宿主通道与 preload 通道) */ +export async function callHostTransport( + method: string, + params: Record = {}, + hostOverride?: unknown, + options?: HostCallOptions +): Promise> { + const override = asRecord(hostOverride) as HostOverrideLike | null + if (override) { + const directFn = override[method] + if (typeof directFn === 'function') { + try { + return unwrapTransportResponse(await (directFn as (p: Record) => Promise)(params)) + } catch (err) { + return toTransportError(err) + } + } + if (typeof override.transport?.call === 'function') { + try { + return unwrapTransportResponse(await override.transport.call(method, params, options)) + } catch (err) { + return toTransportError(err) + } + } + return { ok: false, error: `METHOD_NOT_AVAILABLE: ${method}`, errorCode: 'METHOD_NOT_AVAILABLE' } + } + + // 优先走 declarative-ui 运行时注入的带归属令牌通道 + if (typeof getHostTransport === 'function') { + const transport = getHostTransport() + if (transport) { + try { + const callOpts = typeof options?.timeoutMs === 'number' ? { timeoutMs: options.timeoutMs } : undefined + return unwrapTransportResponse(await transport.call(method, params, callOpts)) + } catch (err) { + return toTransportError(err) + } + } + } + + if (typeof window === 'undefined') { + return { ok: false, error: 'NO_WINDOW_ENV', errorCode: 'NO_WINDOW_ENV' } + } + + const w = window as unknown as WindowHostBridge + const methods = w.__ztoolsElectron?.transport?.methods || w.ztools?.transport?.methods + const fn = methods?.[method] + if (typeof fn === 'function') { + try { + const messageId = nextMessageId(method.replace(/[^A-Za-z0-9_]/g, '_').slice(0, 24)) + const payload = { + messageId, + params, + ...(typeof options?.timeoutMs === 'number' ? { timeoutMs: options.timeoutMs } : {}) + } + return unwrapTransportResponse(await fn(payload)) + } catch (err) { + return toTransportError(err) + } + } + + if (typeof w.ztools?.transport?.call === 'function') { + try { + return unwrapTransportResponse(await w.ztools.transport.call(method, params, options)) + } catch (err) { + return toTransportError(err) + } + } + + return { ok: false, error: `METHOD_NOT_AVAILABLE: ${method}`, errorCode: 'METHOD_NOT_AVAILABLE' } +} + +/** 探测宿主薄原语能力快照(tool_runtime_capabilities) */ +export async function queryRuntimeCapabilities( + hostOverride?: unknown +): Promise> { + const res = await callHostTransport('tool_runtime_capabilities', {}, hostOverride) + if (!res.ok) return res as HostTransportResult + const rec = asRecord(res.data) + if (!rec || !Array.isArray(rec.capabilities)) { + return { + ok: false, + error: 'INVALID_CAPABILITIES_SNAPSHOT', + errorCode: 'INVALID_CAPABILITIES_SNAPSHOT' + } + } + const capabilities: ToolCapabilityDescriptor[] = [] + for (const rawCap of rec.capabilities) { + const cap = asRecord(rawCap) + if (!cap || typeof cap.primitiveId !== 'string') continue + const rawStatus = cap.status + const status: ToolCapabilityStatus = + rawStatus === 'ready' || rawStatus === 'needs_provisioning' || rawStatus === 'unsupported' + ? rawStatus + : 'unsupported' + const optionalExtensions = Array.isArray(cap.optionalExtensions) + ? cap.optionalExtensions.filter((e): e is string => typeof e === 'string' && e.trim().length > 0) + : [] + capabilities.push({ + primitiveId: cap.primitiveId, + domain: typeof cap.domain === 'string' ? cap.domain : '', + summary: typeof cap.summary === 'string' ? cap.summary : '', + ipcMethods: Array.isArray(cap.ipcMethods) ? cap.ipcMethods.filter((m): m is string => typeof m === 'string') : [], + requiredPermissions: Array.isArray(cap.requiredPermissions) + ? cap.requiredPermissions.filter((p): p is string => typeof p === 'string') + : [], + status, + optionalExtensions + }) + } + const platform = + rec.platform === 'windows' || rec.platform === 'macos' || rec.platform === 'other' + ? rec.platform + : 'other' + return { + ok: true, + data: { + contractVersion: typeof rec.contractVersion === 'number' ? rec.contractVersion : 1, + platform, + domains: Array.isArray(rec.domains) ? rec.domains.filter((d): d is string => typeof d === 'string') : [], + capabilities + } + } +} + +export function findCapability( + snapshot: ToolRuntimeCapabilitiesSnapshot | null | undefined, + primitiveId: string +): ToolCapabilityDescriptor | null { + if (!snapshot) return null + return snapshot.capabilities.find((c) => c.primitiveId === primitiveId) ?? null +} + +export function hasCapabilityExtension( + snapshot: ToolRuntimeCapabilitiesSnapshot | null | undefined, + primitiveId: string, + extensionName: string +): boolean { + const cap = findCapability(snapshot, primitiveId) + return Boolean(cap && cap.optionalExtensions.includes(extensionName)) +} + +/** 按需拉取并准备指定薄原语运行组件(tool_runtime_ensure) */ +export async function ensureRuntimeCapability( + primitiveId: string, + hostOverride?: unknown +): Promise> { + return callHostTransport('tool_runtime_ensure', { primitiveId }, hostOverride) +} + +/** 顺序按需准备多个薄原语运行组件,任一项未就绪即中止并聚合 provisioned 标记 */ +export async function ensureRuntimeCapabilities( + primitiveIds: readonly string[], + hostOverride?: unknown +): Promise { + let provisionedAny = false + for (const primitiveId of primitiveIds) { + const res = await ensureRuntimeCapability(primitiveId, hostOverride) + if (!res.ok || !res.data || res.data.status !== 'ready') { + return { + ok: false, + status: res.data?.status ?? 'unsupported', + provisioned: provisionedAny, + failedPrimitiveId: primitiveId, + error: res.error, + errorCode: res.errorCode, + errorDetails: res.errorDetails + } + } + if (res.data.provisioned) provisionedAny = true + } + return { ok: true, status: 'ready', provisioned: provisionedAny } +} + +/** 取消正在执行的宿主薄原语任务(tool_task_cancel) */ +export async function cancelRuntimeTask( + taskId: string, + hostOverride?: unknown +): Promise> { + return callHostTransport('tool_task_cancel', { taskId }, hostOverride) +} + +/** 判断错误码是否表示用户主动取消任务 */ +export function isTaskCancelledCode(errorCode?: string): boolean { + const code = (errorCode || '').trim().toUpperCase() + return code === 'TOOL_TASK_CANCELLED' || code === 'CANCELLED' || code === 'OPERATION_CANCELLED' +} + +/** 执行单个媒体转码任务(tool_media_transcode_run),统一处理取消与产物字节数校验 */ +export async function runMediaTranscodeTask( + payload: Record, + hostOverride?: unknown +): Promise { + const res = await callHostTransport('tool_media_transcode_run', payload, hostOverride) + if (!res.ok) { + if (isTaskCancelledCode(res.errorCode)) { + return { status: 'cancelled' } + } + return { + status: 'failed', + error: res.error, + errorCode: res.errorCode, + errorDetails: res.errorDetails + } + } + const rec = asRecord(res.data) + const outputBytes = Number(rec?.outputBytes) + const durationMs = Number(rec?.durationMs) + if (!Number.isFinite(outputBytes) || outputBytes <= 0) { + return { status: 'failed', error: 'EMPTY_OUTPUT', errorCode: 'EMPTY_OUTPUT' } + } + return { + status: 'done', + outputBytes, + durationMs: Number.isFinite(durationMs) && durationMs >= 0 ? durationMs : 0 + } +} + +/** 订阅宿主推送的 tool_runtime_progress 任务进度事件 */ +export function subscribeRuntimeProgress( + handler: (event: ToolProgressEvent) => void +): () => void { + if (typeof window === 'undefined') return () => undefined + const w = window as unknown as WindowHostBridge + const eventsApi = w.ztools?.events + if (!eventsApi || typeof eventsApi.on !== 'function') return () => undefined + + try { + void eventsApi.subscribe?.('tool_runtime_progress') + } catch (err) { + // 某些测试桩或旧渲染层可能未提供 subscribe,继续注册 on 监听 + void err + } + + const listener = (raw: unknown) => { + const outer = asRecord(raw) + if (!outer) return + const inner = asRecord(outer.payload) ?? outer + if (typeof inner.taskId !== 'string' || typeof inner.phase !== 'string') return + handler(inner as unknown as ToolProgressEvent) + } + + const off = eventsApi.on('tool_runtime_progress', listener) + return () => { + if (typeof off === 'function') { + off() + } else if (typeof eventsApi.off === 'function') { + eventsApi.off('tool_runtime_progress', listener) + } + } +} + +/** 订阅旧版宿主 plugin_files_dropped 拖拽回退事件并返回卸载函数 */ +export function subscribeLegacyFileDrop(onDrop: (envelope: unknown) => void): () => void { + if (typeof window === 'undefined') return () => undefined + const w = window as unknown as WindowHostBridge + const eventsApi = w.ztools?.events + if (!eventsApi || typeof eventsApi.on !== 'function') return () => undefined + + const off = eventsApi.on('plugin_files_dropped', onDrop) + return () => { + if (typeof off === 'function') { + off() + } else if (typeof eventsApi.off === 'function') { + eventsApi.off('plugin_files_dropped', onDrop) + } + } +} + +/** 字节数格式化 */ +export function formatBytes(bytes: number): string { + if (!Number.isFinite(bytes) || bytes < 0) return '0 B' + if (bytes < 1024) return `${Math.round(bytes)} B` + const units = ['KB', 'MB', 'GB', 'TB'] + let value = bytes / 1024 + let idx = 0 + while (value >= 1024 && idx < units.length - 1) { + value /= 1024 + idx += 1 + } + return `${value >= 100 ? value.toFixed(0) : value >= 10 ? value.toFixed(1) : value.toFixed(2)} ${units[idx]}` +} + +/** 字节数格式化别名(兼容 archive-manager 等插件既有导出名) */ +export function formatByteCount(bytes: number): string { + return formatBytes(bytes) +} + +/** 获取系统标准目录路径(支持 Windows 与 macOS) */ +export async function getRealSystemPath( + name: 'home' | 'desktop' | 'documents' | 'downloads' | 'music' | 'pictures' | 'videos' | 'temp', + hostOverride?: unknown +): Promise { + const res = await callHostTransport('system_get_path', { name }, hostOverride) + if (res.ok && res.data) { + if (typeof res.data === 'string' && res.data.trim()) return res.data.trim() + const rec = asRecord(res.data) + if (rec && typeof rec.path === 'string' && rec.path.trim()) return rec.path.trim() + } + return '' +} + +/** 读取剪贴板文本 */ +export async function readRealClipboardText(hostOverride?: unknown): Promise { + const res = await callHostTransport('clipboard_read_text', {}, hostOverride) + if (res.ok && res.data !== undefined && res.data !== null) { + if (typeof res.data === 'string') return res.data + const rec = asRecord(res.data) + if (rec && typeof rec.text === 'string') return rec.text + } + return '' +} + +/** 写入剪贴板文本 */ +export async function writeRealClipboardText(text: string, hostOverride?: unknown): Promise { + const res = await callHostTransport('clipboard_copy_text', { text: String(text || '') }, hostOverride) + return res.ok +} + +/** 在系统文件管理器中显示文件 */ +export async function showRealItemInFolder(fullPath: string, hostOverride?: unknown): Promise { + if (!fullPath) return false + const res = await callHostTransport('shell_show_item_in_folder', { fullPath }, hostOverride) + return res.ok +} + +/** 用系统默认应用打开文件或文件夹 */ +export async function openRealPath(fullPath: string, hostOverride?: unknown): Promise { + if (!fullPath) return false + const res = await callHostTransport('shell_open_path', { fullPath }, hostOverride) + return res.ok +} + +/** 将文件或目录移入系统回收站 */ +export async function trashRealItem(fullPath: string, hostOverride?: unknown): Promise<{ ok: boolean; error?: string }> { + if (!fullPath) return { ok: false, error: 'EMPTY_PATH' } + const res = await callHostTransport('shell_trash_item', { fullPath }, hostOverride) + return res.ok ? { ok: true } : { ok: false, error: res.error } +} + +/** 通过 window_show_open_dialog 选择输出目录(兼容 Windows 与 macOS) */ +export async function pickOutputDirectoryDialog( + options: { title: string; defaultPath?: string }, + hostOverride?: unknown +): Promise<{ canceled: boolean; directoryPath?: string; error?: string; errorCode?: string }> { + const params: Record = { + title: options.title, + properties: ['openDirectory', 'createDirectory'] + } + if (options.defaultPath) params.defaultPath = options.defaultPath + const res = await callHostTransport('window_show_open_dialog', params, hostOverride) + if (!res.ok) { + return { canceled: false, error: res.error || 'OPEN_DIALOG_FAILED', errorCode: res.errorCode } + } + const rec = asRecord(res.data) + if (!rec) return { canceled: false, error: 'INVALID_DIALOG_RESULT' } + if (rec.canceled === true) return { canceled: true } + const firstPath = + (Array.isArray(rec.filePaths) && typeof rec.filePaths[0] === 'string' && rec.filePaths[0].trim()) || + (typeof rec.filePath === 'string' && rec.filePath.trim()) || + (typeof rec.folderPath === 'string' && rec.folderPath.trim()) || + '' + if (!firstPath) return { canceled: false, error: 'NO_DIRECTORY_SELECTED' } + return { canceled: false, directoryPath: firstPath } +} + +/** 通用文件/目录选择对话框(支持自定义 properties 与 filters) */ +export async function openDialogSelectPaths( + options: { + title: string + properties: Array<'openFile' | 'openDirectory' | 'multiSelections' | 'createDirectory'> + filters?: Array<{ name: string; extensions: string[] }> + }, + hostOverride?: unknown +): Promise<{ canceled: boolean; paths: string[]; error?: string }> { + const params: Record = { + title: options.title, + properties: options.properties, + ...(options.filters ? { filters: options.filters } : {}) + } + const res = await callHostTransport('window_show_open_dialog', params, hostOverride) + if (!res.ok) return { canceled: false, paths: [], error: res.error || 'OPEN_DIALOG_FAILED' } + const rec = asRecord(res.data) + if (!rec) return { canceled: false, paths: [], error: 'INVALID_DIALOG_RESPONSE' } + if (rec.canceled === true) return { canceled: true, paths: [] } + const paths = Array.isArray(rec.filePaths) + ? rec.filePaths.filter((p): p is string => typeof p === 'string' && p.trim().length > 0).map((p) => p.trim()) + : typeof rec.filePath === 'string' && rec.filePath.trim() + ? [rec.filePath.trim()] + : [] + return { canceled: false, paths } +} + +/** 选择待归档的源文件或目录列表(多选) */ +export async function pickAnySourcesDialog( + options: { title: string; directories?: boolean }, + hostOverride?: unknown +): Promise<{ canceled: boolean; paths: string[]; error?: string }> { + return openDialogSelectPaths( + { + title: options.title, + properties: options.directories ? ['openDirectory', 'multiSelections'] : ['openFile', 'multiSelections'] + }, + hostOverride + ) +} + +/** 保存归档文件对话框(zip / 7z / tar) */ +export async function pickSaveArchiveDialog( + options: { title: string; defaultPath?: string; format: 'zip' | '7z' | 'tar' }, + hostOverride?: unknown +): Promise<{ canceled: boolean; filePath?: string; error?: string }> { + const ext = options.format === '7z' ? '7z' : options.format === 'tar' ? 'tar' : 'zip' + const params: Record = { + title: options.title, + filters: [{ name: `${ext.toUpperCase()} Archive`, extensions: [ext] }] + } + if (options.defaultPath) params.defaultPath = options.defaultPath + const res = await callHostTransport('window_show_save_dialog', params, hostOverride) + if (!res.ok) return { canceled: false, error: res.error || 'SAVE_DIALOG_FAILED' } + const rec = asRecord(res.data) + if (!rec) return { canceled: false, error: 'INVALID_SAVE_DIALOG' } + if (rec.canceled === true) return { canceled: true } + const filePath = typeof rec.filePath === 'string' ? rec.filePath.trim() : '' + if (!filePath) return { canceled: true } + return { canceled: false, filePath } +} diff --git a/extensions/batch-audio/tests/batch-audio.audit-fixes.test.mjs b/extensions/batch-audio/tests/batch-audio.audit-fixes.test.mjs deleted file mode 100644 index 5bf5f246..00000000 --- a/extensions/batch-audio/tests/batch-audio.audit-fixes.test.mjs +++ /dev/null @@ -1,319 +0,0 @@ -import test from 'node:test' -import assert from 'node:assert/strict' -import fs from 'node:fs' -import os from 'node:os' -import path from 'node:path' -import { processAudioSelection, invokeNativeCapability, getCapabilityItems } from '../dist/logic.js' -import { createHost, installDirectoryHost, mount, tick } from '../../shared/test-harness.mjs' -import { getDeclarativeBridge, setDeclarativeBridge } from '@ztools/declarative-ui' -import { BatchAudioCommand } from '../dist/index.js' - -const files = [ - { id: 'a', name: 'a.wav', path: 'C:\\a.wav', parentDir: 'C:\\', extension: '.wav', sizeBytes: 1024 }, - { id: 'b', name: 'b.wav', path: 'C:\\b.wav', parentDir: 'C:\\', extension: '.wav', sizeBytes: 2048 } -] - -function makeTempTree(spec) { - const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ztools-batch-audio-')) - for (const [rel, content] of Object.entries(spec)) { - const full = path.join(root, rel) - fs.mkdirSync(path.dirname(full), { recursive: true }) - fs.writeFileSync(full, content) - } - return root -} - -function filterBarActions(ui) { - const fb = ui.tree().props.filterBar - return fb?.props?.actions ?? fb?.actions ?? [] -} - -function subItems(ui) { - return ui.tree().props.subList?.items ?? [] -} - -test('合并一次提交两输入,独立处理保留部分失败,空回执不算成功', async () => { - const calls = [] - const host = { - dllplugin_call: async ({ params }) => { - calls.push(params) - return { ok: true, results: [{ outputPath: 'C:\\out.wav', sizeBytes: 1234 }] } - } - } - const merged = await processAudioSelection('BatchMergeAudio', { format: 'wav' }, files, host) - assert.equal(calls.length, 1) - assert.deepEqual(calls[0].files, files.map(f => f.path)) - assert.equal(merged.completed, 2) - let n = 0 - const partial = await processAudioSelection('BatchLoudnorm', {}, files, { - dllplugin_call: async () => (++n === 1 ? { ok: true, results: [{ outputPath: 'C:\\out.mp3', sizeBytes: 12 }] } : { ok: false, error: 'failed' }) - }) - assert.equal(partial.completed, 1) - assert.equal(partial.failed, 1) - const empty = await processAudioSelection('BatchLoudnorm', {}, files.slice(0, 1), { dllplugin_call: async () => ({ ok: true }) }) - assert.equal(empty.failed, 1) -}) - -test('真实SDK音频调用使用长任务超时,并拒绝没有业务确认的回执', async () => { - createHost() - const bridge = getDeclarativeBridge() - const calls = [] - setDeclarativeBridge({ - ...bridge, - hostTransport: { - call: async (method, params, options) => { - calls.push({ method, params, options }) - return { success: true, data: { ok: true, success: true, results: [{ outputPath: 'C:\\out.mp3', sizeBytes: 100 }] } } - } - } - }) - const result = await invokeNativeCapability('BatchLoudnorm', { files: ['C:\\in.wav'] }) - assert.equal(result.ok, true) - assert.equal(calls[0].options.timeoutMs, 300000) - setDeclarativeBridge({ ...bridge, hostTransport: { call: async () => ({}) } }) - assert.equal((await invokeNativeCapability('BatchLoudnorm', { files: ['C:\\in.wav'] })).ok, false) - setDeclarativeBridge(bridge) -}) - -test('音频方法和文件参数在调用宿主前校验,数组中的无效路径不能被忽略', async () => { - let called = 0 - const host = { - dllplugin_call: async () => { - called++ - return { ok: true } - } - } - for (const params of [ - {}, - { files: [] }, - { files: 'C:\\in.wav' }, - { files: new Array(1) }, - { files: ['C:\\in.wav', 123] }, - { files: ['C:\\in.wav', ''] }, - { files: ['relative.wav'] }, - { files: ['C:\\music\\..\\in.wav'] }, - { files: ['C:\\in\0.wav'] }, - { files: [['C:\\in.wav']] }, - { files: ['C:\\in.wav'], outputDir: false }, - { files: ['C:\\in.wav'], outputPath: 'C:\\Windows\\System32\\out.wav' }, - { files: ['C:\\a.wav', 'C:\\b.wav'], outputPath: 'C:\\out.wav' } - ]) { - await assert.rejects(invokeNativeCapability('BatchLoudnorm', params, host), /INVALID_|SECURITY_INTERCEPTED/) - } - await assert.rejects(invokeNativeCapability('UnknownMethod', { files: ['C:\\in.wav'] }, host), /INVALID_METHOD/) - await assert.rejects(invokeNativeCapability('BatchMergeAudio', { files: ['C:\\in.wav'] }, host), /合并需要/) - const tooMany = Array.from({ length: 101 }, (_, i) => `C:\\a_${i}.wav`) - await assert.rejects(invokeNativeCapability('BatchMergeAudio', { files: tooMany }, host), /最多支持 100 个/) - assert.equal(called, 0) - for (const mode of getCapabilityItems()) { - await invokeNativeCapability(mode.method, { ...mode.params, files: ['C:\\音乐\\a.wav', '\\\\server\\music\\b.wav'] }, host) - } - await invokeNativeCapability('BatchLoudnorm', { inputPath: 'D:\\Media\\song.flac' }, host) - assert.equal(called, 13) -}) - -test('batch-audio UI 挂载零扫盘:任何环境初始均为空列表,顶栏恰为 2 个按钮', async () => { - const h = createHost() - const ui = await mount(BatchAudioCommand, h) - await tick(10) - const banned = new Set([ - 'system_get_path', - 'system_list_common_folders', - 'system_search_files', - 'filesystem_get_directory_contents', - 'dllplugin_call' - ]) - assert.deepEqual(h.ipcCalls.filter(([m]) => banned.has(m)), []) - assert.equal(subItems(ui).length, 0) - assert.deepEqual( - filterBarActions(ui).map(a => ({ id: a.id, label: a.label })), - [ - { id: 'pick-files', label: '选择文件' }, - { id: 'pick-folder', label: '选择文件夹' } - ] - ) - assert.deepEqual( - ui.actions().map(a => a.props.title), - ['选择文件…', '选择文件夹…'] - ) - ui.unmount() - - const prevWin = globalThis.window - delete globalThis.window - try { - const offClient = BatchAudioCommand() - assert.equal(offClient.props.subList.items.length, 0, '非客户端下也严禁展示假样例') - assert.match(offClient.props.subList.emptyText, /需要在 ZTools 客户端中使用/) - } finally { - globalThis.window = prevWin - } -}) - -test('batch-audio 支持选择文件、选择文件夹、拖入文件夹(新旧客户端回退)与粘贴去重', async () => { - const root = makeTempTree({ - 'track_a.flac': 'aa', - 'sub/voice.opus': 'bb', - 'sub/extra.aiff': 'cc', - 'readme.txt': 'tt' - }) - const subDir = path.join(root, 'sub') - - try { - const h = createHost() - await installDirectoryHost(h, { authorized: [root] }) - h.ipc.filesystem_get_file_size = async ({ path: p }) => ({ - success: true, - size: fs.existsSync(p) ? fs.statSync(p).size : 8192 - }) - h.ipc.window_show_open_dialog = async () => ({ - canceled: false, - filePaths: [{ path: path.join(root, 'track_a.flac') }, { path: path.join(root, 'readme.txt') }] - }) - - const ui = await mount(BatchAudioCommand, h) - await filterBarActions(ui).find(a => a.id === 'pick-files').onAction() - await tick(10) - assert.equal(subItems(ui).length, 1) - assert.equal(subItems(ui)[0].props.checked, true) - assert.equal(h.lastToast()?.title, '已添加 1 个文件') - - // 选择文件夹:整盘先弹窗确认;临时目录递归导入、去重 track_a.flac - h.setConfirm(false) - h.ipc.window_show_select_folder_dialog = async () => ({ canceled: false, folderPath: 'E:\\' }) - await filterBarActions(ui).find(a => a.id === 'pick-folder').onAction() - await tick(10) - assert.equal(h.confirms.length, 1) - - h.setConfirm(true) - h.ipc.window_show_select_folder_dialog = async () => ({ canceled: false, folderPath: root }) - await filterBarActions(ui).find(a => a.id === 'pick-folder').onAction() - await tick(15) - assert.deepEqual(subItems(ui).map(i => i.props.title), ['track_a.flac', 'extra.aiff', 'voice.opus']) - assert.equal(h.lastToast()?.title, '已添加 2 个文件') - - // 新版宿主带 directories 拖入文件夹(不再重复添加) - await ui.dropFiles([subDir], { directories: [subDir] }) - await tick(15) - assert.equal(h.lastToast()?.title, '这些文件已在列表中') - - // 粘贴音频并去重;读不到大小时显示「大小未识别」 - h.ipc.filesystem_get_file_size = async () => { - throw new Error('路径未由当前窗口授权') - } - await ui.pasteFiles([ - 'D:\\Pasted\\podcast_intro.mp3', - 'D:\\Pasted\\podcast_intro.mp3', - 'D:\\Pasted\\episode_main.wav' - ]) - await tick(15) - assert.equal(h.lastToast()?.title, '已添加 2 个文件') - const intro = ui.item(it => it.props.title === 'podcast_intro.mp3') - assert.ok(intro.props.accessories.some(a => a.text === '大小未识别')) - ui.unmount() - - // 旧版客户端 plugin_files_dropped 回退(含文件夹展开) - const legacyHost = createHost() - await installDirectoryHost(legacyHost, { authorized: [root] }) - legacyHost.ipc.filesystem_directory_exists = async ({ path: p }) => ({ - success: true, - exists: p.toLowerCase() === subDir.toLowerCase() - }) - let droppedListener = null - globalThis.window.__ztoolsDeclarativeFeatures = { fileInput: false } - globalThis.window.ztools = { - ...(globalThis.window.ztools || {}), - events: { - on(event, cb) { - if (event === 'plugin_files_dropped') droppedListener = cb - return () => { - if (droppedListener === cb) droppedListener = null - } - } - } - } - const legacyUi = await mount(BatchAudioCommand, legacyHost) - try { - assert.equal(typeof droppedListener, 'function') - droppedListener({ payload: { files: [subDir] } }) - await tick(20) - assert.deepEqual(subItems(legacyUi).map(i => i.props.title), ['extra.aiff', 'voice.opus']) - } finally { - legacyUi.unmount() - globalThis.window.__ztoolsDeclarativeFeatures = { fileInput: true } - } - assert.equal(droppedListener, null) - } finally { - fs.rmSync(root, { recursive: true, force: true }) - } -}) - -test('batch-audio UI 合并超限预检、移除、清空与处理中防护', async () => { - const GIB = 1024 * 1024 * 1024 - const h = createHost() - h.ipc.filesystem_get_file_size = async ({ path: p }) => ({ - success: true, - size: p.includes('big') ? GIB + 1 : 4096 - }) - let releaseDll - const dllGate = new Promise(r => (releaseDll = r)) - const dllCalls = [] - h.ipc.dllplugin_call = async ({ func, params }) => { - dllCalls.push({ func, params }) - await dllGate - return { ok: true, results: [{ outputPath: 'D:\\Audio\\out.mp3', sizeBytes: 1024 }] } - } - - const ui = await mount(BatchAudioCommand, h) - await ui.pasteFiles(['D:\\Audio\\big1.wav', 'D:\\Audio\\big2.wav', 'D:\\Audio\\small.mp3']) - await tick(15) - - // 切换到合并模式(total = 2 * (1 GiB + 1) > 2 GiB):直接提示超限,不弹确认框、不调宿主 - await ui.dropdown('audio-merge') - const first = subItems(ui)[0] - await ui.run(first, '开始批量处理 (3项)') - assert.equal(h.lastToast()?.title, '合并最多支持 100 个文件、总大小 2 GiB,请减少勾选') - assert.equal(h.confirms.length, 0) - assert.equal(dllCalls.length, 0) - - // 从列表移除一个大文件后再试(剩下 1 GiB + 1 + 4096 <= 2 GiB):允许进入处理流程 - await ui.run(ui.item(it => it.props.title === 'big2.wav'), '从列表移除') - assert.equal(subItems(ui).length, 2) - assert.equal(h.ipcCalls.some(([m]) => /trash|delete|unlink/i.test(m)), false) - - // 切回普通模式测处理中防护(处理中禁止移除、拒绝清空) - await ui.dropdown('audio-convert-mp3') - const runPromise = ui.run(subItems(ui)[0], '开始批量处理 (2项)') - await tick(5) - assert.equal(ui.actions(subItems(ui)[0]).some(a => a.props.title === '从列表移除'), false) - await ui.run(subItems(ui)[1], '清空列表') - assert.equal(h.lastToast()?.title, '正在处理,完成后再清空') - assert.equal(subItems(ui).length, 2) - - releaseDll() - await runPromise - await tick(10) - - // 空闲后清空列表与导入进行中清空丢弃 - await ui.run(subItems(ui)[0], '清空列表') - assert.equal(subItems(ui).length, 0) - - let releaseImport - const importGate = new Promise(r => (releaseImport = r)) - h.ipc.window_show_select_folder_dialog = async () => ({ canceled: false, folderPath: 'D:\\PendingAudio' }) - h.ipc.filesystem_get_directory_contents = async () => { - await importGate - return { success: true, files: [{ name: 'late.mp3', size: 1024, isDirectory: false }] } - } - await ui.pasteFiles(['D:\\Audio\\one.mp3']) - await tick(10) - const toastBefore = h.toasts.length - const folderTask = filterBarActions(ui).find(a => a.id === 'pick-folder').onAction() - await tick(5) - await ui.run(subItems(ui)[0], '清空列表') - releaseImport() - await folderTask - await tick(10) - assert.equal(subItems(ui).length, 0) - assert.equal(h.toasts.length, toastBefore) - ui.unmount() -}) diff --git a/extensions/batch-audio/tests/batch-audio.host.test.mjs b/extensions/batch-audio/tests/batch-audio.host.test.mjs index cd1c236b..c6d4c9d7 100644 --- a/extensions/batch-audio/tests/batch-audio.host.test.mjs +++ b/extensions/batch-audio/tests/batch-audio.host.test.mjs @@ -1,144 +1,160 @@ -// 本插件现行代码的宿主集成测试 +// 批量音频转换薄原语逻辑测试:覆盖能力探测、按需拉取、媒体探测、转码、取消与旧宿主特性降级门禁 import test from 'node:test' import assert from 'node:assert/strict' +import fs from 'node:fs' +import path from 'node:path' +import { fileURLToPath } from 'node:url' import { setRuntimeLocale } from '@ztools/declarative-ui' +import * as batchAudio from '../dist/logic.js' setRuntimeLocale('zh-CN') -const batchAudio = await import('../dist/index.js') -async function withRealElectronWindow(handlers, fn) { - const prevWindow = globalThis.window - const calls = [] - const transportMethods = {} +const __dirname = path.dirname(fileURLToPath(import.meta.url)) - for (const [channel, impl] of Object.entries(handlers)) { - transportMethods[channel] = async envelope => { - const actualParams = - envelope && typeof envelope === 'object' && 'params' in envelope && 'messageId' in envelope - ? envelope.params - : envelope - calls.push({ channel, payload: actualParams }) - return impl(actualParams) +function createHostStub(handlers = {}) { + const calls = [] + const dispatch = async (method, params) => { + calls.push({ method, params }) + if (typeof handlers[method] === 'function') { + return await handlers[method](params) } - } - - globalThis.window = { - __ztoolsElectron: { - transport: { - methods: transportMethods - } + if (method in handlers) { + return handlers[method] } + throw new Error(`CHANNEL_NOT_IMPLEMENTED: ${method}`) } - - try { - return await fn(calls) - } finally { - if (prevWindow === undefined) { - delete globalThis.window - } else { - globalThis.window = prevWindow - } + const stub = { calls, transport: { call: dispatch } } + for (const key of Object.keys(handlers)) { + stub[key] = (params) => dispatch(key, params) } + return stub } -test('batch-audio 对接 dllplugin_call,真实宿主拒绝 simulated:true 与超限合并预检', async () => { - await withRealElectronWindow( - { - dllplugin_call: ({ plugin, func, params }) => { - return { executed: true, plugin, func, files: params.files } - } - }, - async calls => { - assert.deepEqual( - [...batchAudio.AUDIO_IMPORT_EXTENSIONS], - ['.mp3', '.flac', '.wav', '.aac', '.m4a', '.ogg', '.wma', '.opus', '.aiff'] - ) - assert.equal(batchAudio.AUDIO_IMPORT_RULES.forbiddenPath?.test('C:\\Windows\\System32\\a.mp3'), true) +const callsOf = (host, method) => host.calls.filter((c) => c.method === method) - const aRes = await batchAudio.invokeNativeCapability('BatchLoudnorm', { - targetI: -16, - inputPath: 'D:\\Media\\song.flac' - }) - assert.equal(aRes.ok, true) - assert.equal(aRes.fromFallback, false) - assert.equal(aRes.data.plugin, 'BatchAudioPlugin') - assert.equal(calls.length, 1) - } - ) +test('batch-audio: plugin.json 符合薄原语规范且零 DLL 声明', () => { + const manifest = JSON.parse(fs.readFileSync(path.join(__dirname, '..', 'plugin.json'), 'utf8')) + assert.deepEqual(manifest.requiredCapabilities, ['media.probe', 'media.transcode']) + assert.ok(manifest.permissions.includes('media.read')) + assert.ok(manifest.permissions.includes('media.process')) + assert.equal(manifest.minAppVersion, '1.3.0.0') + assert.deepEqual(manifest.nativeComponents, []) + assert.deepEqual(manifest.targets.map((item) => item.id), ['windows-electron-any']) +}) - await withRealElectronWindow( - { - dllplugin_call: () => { - throw new Error('FFMPEG_BINARY_MISSING') - } - }, - async () => { - const aFail = await batchAudio.invokeNativeCapability('BatchLoudnorm', { - targetI: -16, - inputPath: 'D:\\Media\\song.flac' - }) - assert.equal(aFail.ok, false) - assert.equal(aFail.data?.simulated, undefined) - } +test('batch-audio: 探测到 needs_provisioning 后通过 tool_runtime_ensure 拉取音频引擎', async () => { + const host = createHostStub({ + tool_runtime_capabilities: () => ({ + contractVersion: 1, + platform: 'windows', + domains: ['media'], + capabilities: [ + { primitiveId: 'media.probe', domain: 'media', summary: '', ipcMethods: [], requiredPermissions: ['media.read'], status: 'needs_provisioning', optionalExtensions: [] }, + { primitiveId: 'media.transcode', domain: 'media', summary: '', ipcMethods: [], requiredPermissions: ['media.process'], status: 'needs_provisioning', optionalExtensions: ['audio-filters', 'speed'] } + ] + }), + tool_runtime_ensure: ({ primitiveId }) => ({ primitiveId, status: 'ready', provisioned: true }) + }) + + const cap = await batchAudio.probeAudioCapabilities(host) + assert.equal(cap.overallStatus, 'needs_provisioning') + assert.equal(cap.extensions.audioFilters, true) + assert.equal(cap.extensions.speed, true) + + const ensured = await batchAudio.ensureAudioEngine(host) + assert.equal(ensured.ok, true) + assert.equal(ensured.provisioned, true) + assert.deepEqual( + callsOf(host, 'tool_runtime_ensure').map((c) => c.params.primitiveId), + ['media.probe', 'media.transcode'] ) }) -test('batch-audio 合并模式预检:单次最多 100 个文件、总计 2 GiB;未知大小计入数量不计入总量,超限不调用宿主', async () => { - const GIB = 1024 * 1024 * 1024 - let dllCalled = 0 - const host = { - dllplugin_call: async () => { - dllCalled++ - return { ok: true, results: [{ outputPath: 'D:\\Audio\\merged.mp3', sizeBytes: 1024 }] } - } - } +test('batch-audio: 单文件探测 tool_media_probe、完整扩展转码 tool_media_transcode_run 与取消 tool_task_cancel', async () => { + const host = createHostStub({ + filesystem_file_exists: () => false, + tool_media_probe: ({ inputs }) => ({ + items: inputs.map((slot) => ({ + displayName: 'song.wav', + container: 'wav', + durationSec: 185.5, + sizeBytes: 12_345_678, + bitrateBps: 1_411_200, + streams: [{ index: 0, kind: 'audio', codec: 'pcm_s16le', sampleRateHz: 44100, channels: 2 }] + })) + }), + tool_media_transcode_run: (params) => ({ + taskId: params.taskId, + outputBytes: 4_567_890, + durationMs: 2100, + container: params.container + }), + tool_task_cancel: ({ taskId }) => ({ taskId, cancelled: true }) + }) - const makeList = (count, sizeBytes) => - Array.from({ length: count }, (_, i) => ({ - id: `f-${i}`, - name: `track_${i}.mp3`, - path: `D:\\Audio\\track_${i}.mp3`, - parentDir: 'D:\\Audio', - extension: '.mp3', - sizeBytes - })) + const probed = await batchAudio.probeAudioFiles(['D:\\Music\\song.wav'], host) + assert.equal(probed.ok, true) + assert.equal(probed.items[0].durationSec, 185.5) + assert.equal(probed.items[0].sampleRateHz, 44100) + assert.equal(probed.items[0].channels, 2) - // 1. 超过 100 个文件(全部未知大小也应拦下,因为未知大小计入数量) - const over100 = await batchAudio.processAudioSelection('BatchMergeAudio', { format: 'mp3' }, makeList(101, null), host) - assert.equal(over100.completed, 0) - assert.equal(over100.errors[0], '合并最多支持 100 个文件、总大小 2 GiB,请减少勾选') - assert.equal(dllCalled, 0) - - // 2. 总大小超过 2 GiB(2 GiB + 1 B) - const over2G = await batchAudio.processAudioSelection( - 'BatchMergeAudio', - { format: 'mp3' }, - [ - { id: '1', name: 'a.wav', path: 'D:\\Audio\\a.wav', parentDir: 'D:\\Audio', extension: '.wav', sizeBytes: GIB }, - { id: '2', name: 'b.wav', path: 'D:\\Audio\\b.wav', parentDir: 'D:\\Audio', extension: '.wav', sizeBytes: GIB + 1 } - ], - host + const outcome = await batchAudio.transcodeAudioFile( + { path: 'D:\\Music\\song.wav', probe: probed.items[0] }, + { + container: 'mp3', + audioBitrateKbps: 320, + audioSampleRateHz: 48000, + audioChannels: 2, + audioGainDb: 3, + fadeSec: 2, + speedFactor: 1.25 + }, + { audioFilters: true, speed: true }, + new Set(), + { taskId: 'aud_task_1', hostOverride: host } ) - assert.equal(over2G.completed, 0) - assert.equal(over2G.errors[0], '合并最多支持 100 个文件、总大小 2 GiB,请减少勾选') - assert.equal(dllCalled, 0) + assert.equal(outcome.status, 'done') + assert.equal(outcome.outputBytes, 4_567_890) + const sent = callsOf(host, 'tool_media_transcode_run')[0].params + assert.equal(sent.audioGainDb, 3) + assert.deepEqual(sent.audioFade, { fadeInSec: 2, fadeOutSec: 2, totalDurationSec: 185.5 }) + assert.equal(sent.speedFactor, 1.25) - // 3. 恰好 2 GiB + 1 个未知大小(总数 3 <= 100,已知总量 2 GiB <= 2 GiB):允许调用宿主 - const exact2GPlusUnknown = await batchAudio.processAudioSelection( - 'BatchMergeAudio', - { format: 'mp3' }, - [ - { id: '1', name: 'a.wav', path: 'D:\\Audio\\a.wav', parentDir: 'D:\\Audio', extension: '.wav', sizeBytes: GIB }, - { id: '2', name: 'b.wav', path: 'D:\\Audio\\b.wav', parentDir: 'D:\\Audio', extension: '.wav', sizeBytes: GIB }, - { id: '3', name: 'c.wav', path: 'D:\\Audio\\c.wav', parentDir: 'D:\\Audio', extension: '.wav', sizeBytes: null } - ], - host - ) - assert.equal(exact2GPlusUnknown.completed, 3) - assert.equal(dllCalled, 1) + const cancelled = await batchAudio.cancelAudioTask('aud_task_1', host) + assert.equal(cancelled.ok, true) + assert.equal(cancelled.cancelled, true) + assert.equal(callsOf(host, 'tool_task_cancel')[0].params.taskId, 'aud_task_1') +}) + +test('batch-audio 决策 7 降级: 旧宿主未上报 audio-filters 与 speed 时绝不发送任何新字段', async () => { + const host = createHostStub({ + filesystem_file_exists: () => false, + tool_media_transcode_run: (params) => ({ + taskId: params.taskId, + outputBytes: 1_234_567, + durationMs: 900, + container: params.container + }) + }) - // 4. 恰好 100 个文件:允许调用宿主 - const exact100 = await batchAudio.processAudioSelection('BatchMergeAudio', { format: 'mp3' }, makeList(100, 1024), host) - assert.equal(exact100.completed, 100) - assert.equal(dllCalled, 2) + const outcome = await batchAudio.transcodeAudioFile( + { path: 'D:\\Music\\legacy.wav' }, + { + container: 'flac', + audioSampleRateHz: 44100, + audioGainDb: 6, + fadeSec: 3, + speedFactor: 1.5 + }, + { audioFilters: false, speed: false }, + new Set(), + { taskId: 'aud_legacy_1', hostOverride: host } + ) + assert.equal(outcome.status, 'done') + const sent = callsOf(host, 'tool_media_transcode_run')[0].params + assert.equal(Object.hasOwn(sent, 'audioGainDb'), false, '旧宿主绝不能收到 audioGainDb') + assert.equal(Object.hasOwn(sent, 'audioFade'), false, '旧宿主绝不能收到 audioFade') + assert.equal(Object.hasOwn(sent, 'speedFactor'), false, '旧宿主绝不能收到 speedFactor') + assert.equal(sent.container, 'flac') + assert.equal(sent.audioCodec, 'flac') }) diff --git a/extensions/batch-audio/tests/batch-audio.ui.test.mjs b/extensions/batch-audio/tests/batch-audio.ui.test.mjs new file mode 100644 index 00000000..2c6f1049 --- /dev/null +++ b/extensions/batch-audio/tests/batch-audio.ui.test.mjs @@ -0,0 +1,66 @@ +// 批量音频转换界面测试:验证按需下载引导、特性探测动态显隐(audio-filters/speed)、以及零 Emoji/DLL +import test from 'node:test' +import assert from 'node:assert/strict' +import { setRuntimeLocale } from '@ztools/declarative-ui' +import { createHost, mount, tick } from '../../shared/test-harness.mjs' +import BatchAudioCommand from '../dist/index.js' + +setRuntimeLocale('zh-CN') + +function setupAudioHost(host, { status = 'ready', extensions = [] } = {}) { + host.ipc.tool_runtime_capabilities = async () => ({ + contractVersion: 1, + platform: 'windows', + domains: ['media'], + capabilities: [ + { primitiveId: 'media.probe', domain: 'media', summary: '', ipcMethods: ['tool_media_probe'], requiredPermissions: ['media.read'], status, optionalExtensions: [] }, + { primitiveId: 'media.transcode', domain: 'media', summary: '', ipcMethods: ['tool_media_transcode_run'], requiredPermissions: ['media.process'], status, optionalExtensions: extensions } + ] + }) + host.ipc.tool_runtime_ensure = async ({ primitiveId }) => ({ + primitiveId, + status: 'ready', + provisioned: true + }) +} + +const fieldIds = (view) => view.tree().props.workbenchPanel.fields.map((f) => f.id) + +test('batch-audio UI: 旧宿主未上报 audio-filters 与 speed 时,高级参数控件必须隐藏', async () => { + const host = createHost() + setupAudioHost(host, { status: 'ready', extensions: [] }) + const view = await mount(BatchAudioCommand, host) + await tick(25) + + try { + const ids = fieldIds(view) + assert.equal(ids.includes('wb-audio-gain'), false) + assert.equal(ids.includes('wb-audio-fade'), false) + assert.equal(ids.includes('wb-speed'), false) + assert.equal(/[\u{1F300}-\u{1FAFF}]/u.test(view.text()), false) + } finally { + view.unmount() + } +}) + +test('batch-audio UI: 新宿主上报 audio-filters 与 speed 时动态展示控件,needs_provisioning 展示下载引擎引导', async () => { + const host = createHost() + setupAudioHost(host, { status: 'needs_provisioning', extensions: ['audio-filters', 'speed'] }) + const view = await mount(BatchAudioCommand, host) + await tick(25) + + try { + const ids = fieldIds(view) + assert.equal(ids.includes('wb-audio-gain'), true) + assert.equal(ids.includes('wb-audio-fade'), true) + assert.equal(ids.includes('wb-speed'), true) + + const downloadBtn = view.tree().props.filterBar.actions.find((a) => a.id === 'download-engine') + assert.ok(downloadBtn, 'needs_provisioning 态应显示下载音频引擎按钮') + await downloadBtn.onAction() + await tick(25) + assert.ok(host.ipcCalls.some(([m]) => m === 'tool_runtime_ensure')) + } finally { + view.unmount() + } +}) diff --git a/extensions/batch-image/README.en.md b/extensions/batch-image/README.en.md new file mode 100644 index 00000000..a83b8bdc --- /dev/null +++ b/extensions/batch-image/README.en.md @@ -0,0 +1,25 @@ +# Batch Image Compressor + +Batch compress, resize, and convert PNG, JPG, WebP, BMP, GIF, TIFF, and AVIF images. Results are saved as new files in the original folder without modifying the source images. + +## Usage + +- Commands: Batch compress images (`compress image`, `image compressor`), compress attachments for forms and expenses (`300kb image`, `expense attachment`), batch convert PNG/WebP/BMP to JPG (`convert to jpg`, `webp to jpg`), and convert scanned documents to grayscale (`grayscale`, `scan to bw`). +- Import images or entire folders via **Select File** or **Select Folder** at the top (scans up to 5 levels deep, up to 500 images per batch, automatically skipping `*_opt` files produced by this plugin), or drag and drop into the window, paste, or choose **Add from Clipboard** in the action panel. +- Switch presets on the right side of the search bar: Standard Compression, Form/Expense Attachment (300 KB check), Batch Convert to JPG, Batch Convert to PNG, Max Edge 1920px, or Scan to Grayscale; further adjust output format, quality tier (High / Medium / Low), and dimension limits on the left. +- `Enter`: Process checked images; `Ctrl+Enter`: Reveal in File Explorer (reveals the output file after successful processing); `Ctrl+S`: Process only the current image; `Ctrl+Shift+C`: Copy output file path (after successful processing); `Ctrl+O`: Select files; `Ctrl+Shift+O`: Select folder; `Ctrl+Backspace`: Remove from list; `Ctrl+Shift+Backspace`: Clear list (without touching disk files); `Ctrl+A`: Select all or deselect all; `Delete`: Move original image to the Recycle Bin (with confirmation); `Ctrl+K`: Open the action panel. +- Results are saved as `_opt.`. If a file with the same name already exists, `_opt_2` or a timestamped suffix is used instead so existing files are not overwritten. +- Converting to JPG is lossy; when keeping PNG format, Medium and Low quality tiers reduce color depth (High does not). The Form/Expense Attachment preset converts to JPG at Low quality with a maximum edge of 1280px; it does not repeatedly re-compress to meet a target file size and instead flags images that remain over 300 KB after processing. +- When keeping the original format without resizing or grayscale conversion, images that become larger after re-encoding output the same content as the original; any output that is not smaller than the original is labeled "Not smaller". +- Transparent areas may turn black when converting to JPG; re-encoding does not preserve photo orientation tags, so some portrait photos may appear sideways after output. +- Processing WebP images requires `ffmpeg` to be installed locally. + +## Platforms & Requirements + +- Supported: Windows only +- Built into the client; no separate installation required. +- Windows implementation is pending verification on physical hardware. + +## Network & Data + +- Works offline; data stays on your local device. diff --git a/extensions/batch-image/plugin.json b/extensions/batch-image/plugin.json index 85d941d0..6414e431 100644 --- a/extensions/batch-image/plugin.json +++ b/extensions/batch-image/plugin.json @@ -1,8 +1,9 @@ { "id": "batch-image", - "name": "图片压缩", - "description": "批量压缩与转换 PNG/JPG/WebP/BMP/GIF/TIFF/AVIF 图片:支持选择文件、选择文件夹或拖入导入,三档画质重新编码、限制最长边、转 JPG/PNG、扫描件转灰度,报销附件场景会标出仍超过 300KB 的图片;结果另存为原图同目录的 *_opt 文件,不覆盖原图", - "version": "1.1.10", + "name": "图片压缩与工具", + "description": "通过宿主图像与文档薄原语提供单图深度检查与批量图片处理:单图查看尺寸、色彩空间与完整 EXIF/GPS 标签、一键抹除隐私 EXIF、转 Base64 复制、生成 ICO/Favicon;多图批量压缩、缩放、改格式(PNG/JPG/WebP/AVIF/BMP)与真实嵌图合并为 PDF,输出绝不覆盖原图", + "version": "2.0.0", + "minAppVersion": "1.3.0.4", "author": "ZTools Team", "entry": "dist/index.js", "icon": "icon.svg", @@ -18,23 +19,44 @@ "keywords": [ "image", "compress", + "exif", + "metadata", + "base64", + "ico", + "favicon", + "pdf", "png", "jpg", "webp", + "avif", "图片压缩", + "图片信息", + "清除exif", "格式转换", - "图片转jpg", - "图片缩放" + "多图合pdf", + "压缩图片", + "图片变小", + "图片转格式", + "转jpg", + "转png", + "转webp", + "批量压图", + "图片瘦身", + "改图片大小", + "报销压图" ], "features": [ { "code": "preset-lossless", - "explain": "图片批量压缩", + "explain": "图片批量压缩与单图元数据检查", "mode": "view", "cmds": [ "图片压缩", "压缩图片", - "图片瘦身" + "图片工具", + "图片元数据", + "查看exif", + "清除exif" ] }, { @@ -50,31 +72,38 @@ }, { "code": "preset-to-jpg", - "explain": "PNG/WebP/BMP 批量转 JPG", + "explain": "批量图片格式转换(JPG/PNG/WebP/AVIF/ICO)", "mode": "view", "cmds": [ "图片格式转换", "webp转jpg", "png转jpg", - "转jpg" + "生成ico", + "图片转base64" ] }, { - "code": "preset-doc-bw", - "explain": "扫描件转灰度", + "code": "preset-merge-pdf", + "explain": "将多张图片真实嵌入合并为 PDF", "mode": "view", "cmds": [ - "扫描件转灰度", - "图片转灰度", - "黑白扫描件" + "图片合pdf", + "多图转pdf" ] } ], + "requiredCapabilities": [ + "image.inspect", + "image.process", + "document.pdf.transform" + ], "permissions": [ + "media.read", + "media.process", "fs", + "dialog", "clipboard", - "shell", - "dialog" + "shell" ], "requireAdmin": false, "nativeComponents": [], @@ -86,30 +115,39 @@ "arch": "any" } ], - "minAppVersion": "1.1.8.9", "defaultLocale": "zh-CN", "i18n": { "en-US": { - "name": "Batch Image Compressor", - "description": "Batch compress and convert PNG, JPG, WebP, BMP, GIF, TIFF, and AVIF images with 3 quality tiers, max dimension limits, JPG/PNG conversion, and grayscale scanning. Flags images over 300 KB and saves as *_opt copies without overwriting originals.", + "name": "Batch Image & Inspector", + "description": "Inspect single images (dimensions, color space, EXIF/GPS tags, strip EXIF, copy Base64, generate ICO/Favicon) and batch compress, resize, convert (PNG/JPG/WebP/AVIF/BMP), or embed multiple images into a PDF via host thin primitives without overwriting originals.", "keywords": [ "image", + "inspector", + "exif", + "strip exif", + "base64", + "ico", + "favicon", "compress", "convert", "resize", - "png", - "jpg", - "webp", - "grayscale" + "images to pdf", + "compress image", + "image compressor", + "shrink photo", + "resize image", + "batch image", + "optimize photo", + "reduce size" ], "features": { "preset-lossless": { - "explain": "Batch compress images to reduce file size", + "explain": "Batch compress images and inspect EXIF metadata", "cmds": [ "compress image", - "image compressor", - "shrink image", - "optimize image" + "image inspector", + "strip exif", + "image metadata" ] }, "preset-gov-limit": { @@ -117,26 +155,22 @@ "cmds": [ "300kb image", "id photo compress", - "expense attachment", - "limit 300kb" + "expense attachment" ] }, "preset-to-jpg": { - "explain": "Batch convert PNG, WebP, and BMP images to JPG", + "explain": "Convert image formats (JPG/PNG/WebP/AVIF/ICO) or copy Base64", "cmds": [ - "convert to jpg", - "webp to jpg", - "png to jpg", - "image format" + "convert image", + "image to base64", + "favicon ico" ] }, - "preset-doc-bw": { - "explain": "Convert scanned documents to grayscale", + "preset-merge-pdf": { + "explain": "Embed multiple images into a single PDF", "cmds": [ - "grayscale", - "scan to bw", - "black and white", - "document grayscale" + "images to pdf", + "merge images pdf" ] } }, diff --git a/extensions/batch-image/src/i18n.ts b/extensions/batch-image/src/i18n.ts index 4252a137..bbb0ed00 100644 --- a/extensions/batch-image/src/i18n.ts +++ b/extensions/batch-image/src/i18n.ts @@ -1,297 +1,282 @@ -import { createTranslator } from "@ztools/declarative-ui"; +import { createTranslator } from '@ztools/declarative-ui' -const rawT = createTranslator( - { - "zh-CN": { - forbiddenReason: "图片批处理输出路径不可指向系统受保护目录或包含路径穿越", - qualityMedium: "中:画质 85,PNG 每通道保留 5 位色深", - qualityLow: "低:画质 70,PNG 每通道保留 4 位色深", - qualityHigh: "高:画质 95,PNG 不降色深", - resizeSource: "保持原始尺寸", - resizeMax1920: "最长边不超过 1920px", - resizeMax1280: "最长边不超过 1280px", - formatKeep: "保持原格式", - presetLosslessTitle: "常规压缩", - presetLosslessSub: "保持原格式与尺寸,按中档画质重新编码;JPG 与 PNG 都会有轻微画质损失", - presetLosslessTag: "常规压缩", - presetGovTitle: "报销/政务附件压缩(检查 300KB)", - presetGovSub: "转为 JPG、低档画质、最长边不超过 1280px,处理后标出仍超过 300KB 的图片", - presetGovTag: "附件 300KB", - presetJpgTitle: "批量转 JPG", - presetJpgSub: "转为 JPG 格式;带透明背景的图片转换后,透明区域可能变成黑色", - presetJpgTag: "转 JPG", - presetPngTitle: "批量转 PNG", - presetPngSub: "转为 PNG 格式并保留透明通道;由 JPG 转换时文件通常会变大", - presetPngTag: "转 PNG", - preset1920Title: "限制最长边 1920px", - preset1920Sub: "最长边超过 1920px 的图片按比例缩小,较小的图片保持原尺寸", - preset1920Tag: "限制尺寸", - presetGrayTitle: "扫描件转灰度", - presetGraySub: "把文档照片或扫描件转为灰度图", - presetGrayTag: "转灰度", - errInvalidMethodEmpty: "INVALID_METHOD: 调用方法名不能为空", - errInvalidMethodFormat: "INVALID_METHOD_FORMAT: 方法名包含非法字符或超长", - errInvalidParamsObject: "INVALID_PARAMS: 参数必须为非空对象", - errParamTooLong: "PARAM_TOO_LONG: 参数 {key} 超过最大长度限制", - errSecurityIntercepted: "SECURITY_INTERCEPTED: {reason}", - errParamOutOfRange: "PARAM_OUT_OF_RANGE: 数值参数 {key} 越界或非有限数", - errValidationFailed: "参数校验失败", - errCannotGenUniqueName: "无法为输出文件生成不重复的文件名", - errHostFailed: "宿主报告处理失败", - errHostNoResult: "宿主未返回处理结果,无法确认是否已生成输出文件", - errHostMissingOutput: "宿主返回的结果缺少输出文件路径或大小", - errUnknownExt: "无法识别图片扩展名,请指定输出格式", - errHostReturnFailed: "宿主图片处理返回失败", - tagPending: "待处理", - tagFailed: "失败", - tagOverLimit: "超过 {size}", - tagNotSmaller: "未变小 · {size}", - tagOutput: "已输出 {size}{pct}", - detailFailed: "失败原因:{error}", - dimsUnknown: "尺寸未识别", - detailOutput: "输出 {name} · {dims}", - importFailedTitle: "导入失败", - pickFilesTitle: "选择待处理的图片文件", - pickFilesFilterName: "图片文件", - pickFolderTitle: "选择包含图片的文件夹", - noFolderSelected: "没有选择文件夹", - confirmRootTitle: "导入整个磁盘 {path} 中的图片?", - confirmRootMsg: "将读取该磁盘下 5 层以内的文件夹,最多导入 500 张图片,可能需要一些时间。", - confirmRootAction: "继续导入", - selectAtLeastOne: "请先勾选至少 1 张图片", - processingBatchTitle: "正在处理 {count} 张图片...", - batchAllFailedTitle: "{total} 张图片全部处理失败", - batchSingleFailedTitle: "图片处理失败", - batchPartialTitle: "已处理 {done} 张,{failed} 张失败", - batchOverLimitTitle: "已处理 {done} 张,{overLimit} 张仍超过 {limit}", - batchOverLimitMsg: "超过限额的图片已在队列中标出", - batchSavedPart: ",节省 {size} (-{pct}%)", - batchNotSmallerPart: ";{count} 张未变小", - batchSuccessTitle: "已处理 {done} 张图片", - batchSuccessMsg: "输出共 {size}{saved}{notSmaller}。结果另存为 *_opt 文件,原图未改动", - processErrorTitle: "图片处理异常", - readClipboardFailed: "读取剪贴板失败", - noClipImagePathsTitle: "剪贴板中没有图片文件路径", - noClipImagePathsMsg: "在资源管理器中复制图片或「复制为路径」后再添加(支持 {supported})", - removeBusy: "该图片正在处理中,完成后再移除", - clearBusy: "正在处理,完成后再清空", - trashBusy: "该图片正在处理中,完成后再操作", - trashNoteHasOutput: "已生成的输出文件不受影响:{path}", - trashNoteNoOutput: "这张图片还没有生成输出文件。", - confirmTrashTitle: "确认将原图移入系统回收站?", - confirmTrashMsg: "文件名: {name}\n大小: {size}\n路径: {path}\n\n{note}", - sizeUnknownShort: "未识别", - confirmTrashAction: "移入回收站", - trashFailedTitle: "移入回收站失败", - trashInUseMsg: "文件可能正被占用", - trashSuccessTitle: "已将原图移入回收站", - revealFailedTitle: "无法在资源管理器中显示", - originalExtLabel: "原扩展名", - actionPickFilesEllipsis: "选择文件…", - actionPickFolderEllipsis: "选择文件夹…", - actionFromClipboard: "从剪贴板添加", - selectedUnknownPart: "({count} 张大小未识别)", - resultSummaryPart: " · 已输出 {done} 张,失败 {failed} 张", - sizeUnknown: "大小未识别", - actionRunSelected: "开始处理已选图片 ({count} 张)", - actionRevealOutput: "在资源管理器中显示输出文件", - actionRevealSource: "在资源管理器中显示原图", - actionRunSingle: "仅处理这张图片", - actionCopyOutputPath: "复制输出文件路径", - copiedOutputPathTitle: "已复制输出文件路径", - copyFailedTitle: "复制失败", - sectionList: "列表", - actionRemove: "从列表移除", - actionDeselectAll: "取消全选当前列表", - actionSelectAll: "全选当前列表", - actionClearList: "清空列表", - sectionFile: "文件", - actionTrashSource: "将原图移入系统回收站", - dropTitle: "拖入图片或文件夹", - dropSubtitle: "文件夹内 5 层以内的图片会一并导入", - summaryImporting: "正在导入:已读取 {dirs} 个文件夹,找到 {files} 个文件", - summaryEmptyClient: "尚未添加图片 · 可选择文件、文件夹,或直接拖入", - hostRequired: "需要在 ZTools 客户端中使用", - summaryNormal: "已选 {selected}/{total} 张 · 原图 {size}{result} · 清空列表 Ctrl+Shift+Backspace", - emptyNoMatch: "没有匹配的图片", - searchPlaceholder: "搜索图片名称、目录或后缀 ({supported})...", - queueActionsTitle: "图片压缩队列操作", - dropdownTooltip: "选择处理方案", - dropdownItemTitle: "方案: {tag}", - btnPickFiles: "选择文件", - btnPickFolder: "选择文件夹", - wbTitle: "处理参数", - wbFormatLabel: "输出格式", - wbQualityLabel: "画质档位", - wbScaleLabel: "尺寸约束", - wbOutdirLabel: "输出位置", - wbOutdirValue: "原图同目录,另存为 <文件名>_opt.{ext};已有同名文件时自动换名,不覆盖原图", - wbLimitsLabel: "已知限制", - wbLimitsValue: "WebP 图片需要本机已安装 ffmpeg;重新编码不保留照片方向标记,部分竖拍照片输出后可能显示为横向", - previewTitle: "处理结果", - previewBadgeDone: "已输出 {done} 张", - previewBadgePending: "未处理", - previewSubtitle: "当前方案: {title}", - metricSelected: "已选图片", - metricSelectedVal: "{selected} / {total} 张", - metricSelectedSize: "已选原图大小", - metricOutSize: "输出总大小", - metricSaved: "实际节省", - metricFailed: "失败", - metricFailedVal: "{count} 张", - subListTitle: "待处理图片 (勾选后按 Enter 开始处理)", - subListSubtitle: "{count} 张图片", - sectionQueueTitle: "待处理图片 ({count})" - }, - "en-US": { - forbiddenReason: "Output path cannot point to a protected system directory or contain path traversal", - qualityMedium: "Medium: Quality 85, PNG 5-bit per channel", - qualityLow: "Low: Quality 70, PNG 4-bit per channel", - qualityHigh: "High: Quality 95, PNG full depth", - resizeSource: "Keep Original Size", - resizeMax1920: "Max Edge 1920px", - resizeMax1280: "Max Edge 1280px", - formatKeep: "Keep Original", - presetLosslessTitle: "Standard Compress", - presetLosslessSub: "Keep format and dimensions; re-encode at medium quality (slight loss on JPG/PNG)", - presetLosslessTag: "Compress", - presetGovTitle: "Attachment Compress (Check 300KB)", - presetGovSub: "Convert to JPG, low quality, max 1280px; flags outputs still over 300KB", - presetGovTag: "Limit 300KB", - presetJpgTitle: "Batch Convert to JPG", - presetJpgSub: "Convert to JPG; transparent backgrounds may turn black", - presetJpgTag: "To JPG", - presetPngTitle: "Batch Convert to PNG", - presetPngSub: "Convert to PNG keeping transparency; file size may grow from JPG", - presetPngTag: "To PNG", - preset1920Title: "Resize Max Edge 1920px", - preset1920Sub: "Scale down images wider/taller than 1920px; smaller ones stay unchanged", - preset1920Tag: "Max 1920px", - presetGrayTitle: "Scan to Grayscale", - presetGraySub: "Convert document photos or scans to grayscale", - presetGrayTag: "Grayscale", - errInvalidMethodEmpty: "INVALID_METHOD: Method name cannot be empty", - errInvalidMethodFormat: "INVALID_METHOD_FORMAT: Method name contains invalid characters or is too long", - errInvalidParamsObject: "INVALID_PARAMS: Parameters must be a non-null object", - errParamTooLong: "PARAM_TOO_LONG: Parameter {key} exceeds maximum length", - errSecurityIntercepted: "SECURITY_INTERCEPTED: {reason}", - errParamOutOfRange: "PARAM_OUT_OF_RANGE: Numeric parameter {key} is out of range or non-finite", - errValidationFailed: "Parameter validation failed", - errCannotGenUniqueName: "Unable to generate a unique output filename", - errHostFailed: "Host reported processing failure", - errHostNoResult: "Host did not return processing result; cannot verify output file", - errHostMissingOutput: "Host result is missing output path or file size", - errUnknownExt: "Unrecognized image extension; please specify an output format", - errHostReturnFailed: "Host image processing failed", - tagPending: "Pending", - tagFailed: "Failed", - tagOverLimit: "Over {size}", - tagNotSmaller: "Not smaller · {size}", - tagOutput: "Saved {size}{pct}", - detailFailed: "Failed: {error}", - dimsUnknown: "Dimensions unknown", - detailOutput: "Saved {name} · {dims}", - importFailedTitle: "Import Failed", - pickFilesTitle: "Select Images", - pickFilesFilterName: "Image Files", - pickFolderTitle: "Select Image Folder", - noFolderSelected: "No folder selected", - confirmRootTitle: "Import images from entire drive {path}?", - confirmRootMsg: "Will scan up to 5 folder levels and import at most 500 images. This may take a while.", - confirmRootAction: "Continue Import", - selectAtLeastOne: "Please check at least 1 image", - processingBatchTitle: "Processing {count} [[count:image|images]]...", - batchAllFailedTitle: "[[total:{total} image|All {total} images]] failed", - batchSingleFailedTitle: "Image Processing Failed", - batchPartialTitle: "{done} succeeded, {failed} failed", - batchOverLimitTitle: "{done} processed, {overLimit} still over {limit}", - batchOverLimitMsg: "Images exceeding the limit are flagged in the queue", - batchSavedPart: ", saved {size} (-{pct}%)", - batchNotSmallerPart: "; {count} not smaller", - batchSuccessTitle: "Processed {done} [[done:image|images]]", - batchSuccessMsg: "Total output {size}{saved}{notSmaller}. Saved as *_opt; originals untouched", - processErrorTitle: "Image Processing Error", - readClipboardFailed: "Failed to Read Clipboard", - noClipImagePathsTitle: "No image file paths in clipboard", - noClipImagePathsMsg: "Copy image files or paths in Explorer first (supports {supported})", - removeBusy: "Image is processing; remove after completion", - clearBusy: "Processing in progress; clear after completion", - trashBusy: "Image is processing; try again after completion", - trashNoteHasOutput: "Generated output file is unaffected: {path}", - trashNoteNoOutput: "No output file has been generated for this image yet.", - confirmTrashTitle: "Move original image to Trash?", - confirmTrashMsg: "File: {name}\nSize: {size}\nPath: {path}\n\n{note}", - sizeUnknownShort: "Unknown", - confirmTrashAction: "Move to Trash", - trashFailedTitle: "Failed to Move to Trash", - trashInUseMsg: "File may be in use", - trashSuccessTitle: "Moved original image to Trash", - revealFailedTitle: "Unable to Reveal in Explorer", - originalExtLabel: "original", - actionPickFilesEllipsis: "Select Files…", - actionPickFolderEllipsis: "Select Folder…", - actionFromClipboard: "Add from Clipboard", - selectedUnknownPart: " ({count} unknown size)", - resultSummaryPart: " · {done} saved, {failed} failed", - sizeUnknown: "Size unknown", - actionRunSelected: "Process Selected ({count})", - actionRevealOutput: "Reveal Output in Explorer", - actionRevealSource: "Reveal Original in Explorer", - actionRunSingle: "Process This Image Only", - actionCopyOutputPath: "Copy Output Path", - copiedOutputPathTitle: "Copied Output Path", - copyFailedTitle: "Copy Failed", - sectionList: "List", - actionRemove: "Remove from List", - actionDeselectAll: "Deselect All", - actionSelectAll: "Select All", - actionClearList: "Clear List", - sectionFile: "File", - actionTrashSource: "Move Original to Trash", - dropTitle: "Drop images or folders", - dropSubtitle: "Images within 5 folder levels will be imported", - summaryImporting: "Importing: {dirs} [[dirs:folder|folders]] scanned, {files} [[files:file|files]] found", - summaryEmptyClient: "No images added · Select files, folder, or drop here", - hostRequired: "Requires the ZTools client", - summaryNormal: "Selected {selected}/{total} · {size}{result} · Clear Ctrl+Shift+Backspace", - emptyNoMatch: "No matching images", - searchPlaceholder: "Search image name, folder, or extension ({supported})...", - queueActionsTitle: "Image Queue Actions", - dropdownTooltip: "Select Preset", - dropdownItemTitle: "Preset: {tag}", - btnPickFiles: "Select Files", - btnPickFolder: "Select Folder", - wbTitle: "Parameters", - wbFormatLabel: "Output Format", - wbQualityLabel: "Quality Tier", - wbScaleLabel: "Resize Constraint", - wbOutdirLabel: "Output Location", - wbOutdirValue: "Source folder as _opt.{ext}; auto-renamed if exists (originals untouched)", - wbLimitsLabel: "Known Limits", - wbLimitsValue: "WebP requires local ffmpeg; re-encoding strips EXIF orientation tags", - previewTitle: "Results", - previewBadgeDone: "{done} saved", - previewBadgePending: "Pending", - previewSubtitle: "Preset: {title}", - metricSelected: "Selected", - metricSelectedVal: "{selected} / {total}", - metricSelectedSize: "Selected Size", - metricOutSize: "Output Size", - metricSaved: "Saved", - metricFailed: "Failed", - metricFailedVal: "{count}", - subListTitle: "Image Queue (Check items and press Enter to start)", - subListSubtitle: "{count} [[count:image|images]]", - sectionQueueTitle: "Image Queue ({count})" - } +const MESSAGES = { + 'zh-CN': { + forbiddenReason: '严禁向系统保护目录或目录穿越路径输出文件', + sizeUnknown: '大小未识别', + unknownValue: '未识别', + qualityLow: '高压缩 (70)', + qualityMedium: '均衡画质 (85)', + qualityHigh: '高清优先 (95)', + resizeSource: '保持原尺寸', + resizeMax1920: '宽度上限 1920px', + resizeMax1280: '宽度上限 1280px', + formatKeep: '保持原格式', + stripExifOn: '开启(抹除隐私 EXIF/GPS)', + stripExifOff: '关闭(保留元数据)', + rotateNone: '不旋转', + rotate90: '顺时针 90°', + rotate180: '旋转 180°', + rotate270: '逆时针 90° (270°)', + flipNone: '不翻转', + flipHorizontal: '水平翻转', + flipVertical: '垂直翻转', + presetLosslessTitle: '均衡压缩与隐私清理', + presetLosslessSub: '85 画质压缩并真实抹除 EXIF/GPS 隐私信息', + presetLosslessTag: '均衡压缩', + presetGovTitle: '报销/政务附件 (<=300KB)', + presetGovSub: '转为 JPEG、70 画质、限宽 1280px 并标出超限图片', + presetGovTag: '300KB 限制', + presetJpgTitle: '批量转 JPEG', + presetJpgSub: '统一转为通用 JPEG 格式', + presetJpgTag: '转 JPEG', + presetWebpTitle: '批量转 WebP', + presetWebpSub: '高效现代 WebP 压缩格式', + presetWebpTag: '转 WebP', + presetPngTitle: '批量转 PNG', + presetPngSub: '无损 PNG 格式输出', + presetPngTag: '转 PNG', + presetIcoTitle: '生成 ICO / Favicon', + presetIcoSub: '缩放至 256x256 并导出标准 ICO 图标', + presetIcoTag: '生成 ICO', + errUnknownExt: '无法识别图片扩展名', + errCannotGenUniqueName: '无法生成不冲突的输出路径', + errHostFailed: '宿主图片处理失败', + errInspectFailed: '读取图片元数据失败', + errMergePdfFailed: '多图合并 PDF 失败', + errBase64Missing: '宿主未返回有效的 Base64 Data URL', + errEnsureFailed: '准备图像引擎失败', + errUnsupportedEngine: '当前宿主暂不支持图像薄原语', + errNoTaskToCancel: '当前没有正在运行的图像任务', + errSelectAtLeastOne: '请先选择至少 1 张图片', + wbTitle: '图片压缩与工具', + wbSubtitleSingle: '单图深度检查模式 · EXIF / 转换 / Base64 / ICO', + wbSubtitleBatch: '批量处理模式 · 压缩 / 缩放 / 改格式 / 嵌图合 PDF', + wbPresetLabel: '快捷方案', + wbFormatLabel: '目标格式', + wbQualityLabel: '压缩画质', + wbResizeLabel: '尺寸缩放', + wbStripExifLabel: '隐私 EXIF 剥离', + wbRotateLabel: '旋转角度', + wbFlipLabel: '镜像翻转', + wbCardInspectorTitle: '单图深度检查', + wbCardBatchTitle: '批量与引擎状态', + badgeExifYes: '含 EXIF', + badgeExifNo: '无 EXIF', + badgeReady: '引擎就绪', + badgeProvision: '待准备引擎', + badgeRunning: '处理中', + metricResolution: '分辨率', + metricFormatColor: '格式 / 色彩', + metricSize: '体积', + metricExifTags: 'EXIF / GPS 标签', + metricSelected: '已选图片', + inspectorEmptyNote: '拖入或选择单张图片自动展示分辨率、色彩空间与 EXIF/GPS 标签;选择多张自动进入批量模式。', + inspectorExifSummary: '检测到 {count} 项 EXIF 元数据({preview}),可一键抹除隐私信息。', + inspectorNoExifNote: '未检测到 EXIF 隐私标签,可直接执行格式转换、转 Base64 或生成 ICO。', + batchNoteReady: '支持真实 stripExif 隐私擦除、批量改格式缩放与真实嵌图合并 PDF(绝不覆盖原图)。', + batchNoteProvision: '检测到图像引擎尚未下载,请点击「准备图像引擎」按需拉取校验。', + actionRunBatch: '开始处理 ({count})', + btnRunBatch: '开始处理 ({count})', + btnProcessing: '处理中…', + tagProcessing: '处理中', + summaryProcessing: '正在处理 {count} 张图片…', + actionStripExif: '一键抹除隐私 EXIF', + actionCopyBase64: '转 Base64 并复制', + actionMakeIco: '生成 ICO / Favicon', + actionMergePdf: '多图真实嵌图合 PDF ({count})', + actionInspectImage: '深度检查元数据 / EXIF', + actionEnsureEngine: '准备图像引擎', + actionCancelTask: '取消当前任务', + actionPickFiles: '选择图片...', + actionPickFolder: '选择文件夹...', + actionRevealOriginal: '定位原图', + actionRevealOutput: '定位输出文件', + actionToggleAll: '全选 / 取消全选', + actionRemoveItem: '从列表移除', + actionClearList: '清空列表', + actionTrashItem: '移入回收站', + toastInspectOk: '元数据读取完成', + toastInspectFail: '读取图片元数据失败', + toastStripExifOk: '已抹除隐私 EXIF', + toastStripExifFail: '抹除 EXIF 失败', + toastBase64Ok: '已复制 Base64 Data URL', + toastBase64Fail: '生成 Base64 失败', + toastIcoOk: 'ICO / Favicon 已生成', + toastIcoFail: '生成 ICO 失败', + toastMergePdfOk: '多图合并 PDF 完成', + toastMergePdfMsg: '已真实嵌入 {pages} 张图片({size}):{path}', + toastMergePdfFail: '多图合并 PDF 失败', + toastBatchDone: '处理完成(成功 {done},失败 {failed})', + toastBatchOverLimit: '已完成 {done} 张,但有 {overLimit} 张仍超过 300KB', + toastEnsureOk: '图像引擎已就绪', + toastEnsureFail: '图像引擎准备失败', + toastCancelOk: '已取消当前任务', + toastCancelFail: '取消任务失败', + toastImportFailed: '导入图片失败', + toastRevealFailed: '无法打开文件位置', + pickFilesTitle: '选择图片文件', + pickFilesFilter: '图片文件', + pickFolderTitle: '选择图片文件夹', + errNoFolderPicked: '未选择文件夹', + confirmRootTitle: '确定扫描整个根目录 {path} 吗?', + confirmRootMsg: '扫描磁盘根目录耗时较长,建议选择具体图片目录。', + confirmRootAction: '继续扫描', + dropTitle: '拖入单张(深度检查)或多张图片(批量处理 / 合 PDF)', + dropSubtitle: '支持 PNG / JPG / WebP / BMP / GIF / TIFF / AVIF,输出绝不覆盖原图', + searchPlaceholder: '搜索已导入图片...', + summaryText: '{mode} · 已选 {selected}/{total} 张', + modeSingle: '单图检查', + modeBatch: '批量处理', + subListTitle: '图片队列 ({count})', + subListSubtitle: '已选 {selected} 张 · 原图合计 {size}', + emptyQueue: '请选择或拖入单张或多张图片', + emptyNoMatch: '没有匹配的图片', + tagDone: '已完成', + tagOverLimit: '超 300KB', + tagFailed: '失败', + tagExifStripped: '已去 EXIF', + panelTitle: '图片压缩与工具', + sectionTitle: '图片列表 ({count})' + }, + 'en-US': { + forbiddenReason: 'Protected system directories or traversal paths are blocked', + sizeUnknown: 'Unknown size', + unknownValue: 'Unknown', + qualityLow: 'High Compression (70)', + qualityMedium: 'Balanced (85)', + qualityHigh: 'High Quality (95)', + resizeSource: 'Keep Original Size', + resizeMax1920: 'Max Width 1920px', + resizeMax1280: 'Max Width 1280px', + formatKeep: 'Keep Original Format', + stripExifOn: 'On (Strip EXIF/GPS)', + stripExifOff: 'Off (Keep Metadata)', + rotateNone: 'No Rotation', + rotate90: 'Rotate 90° CW', + rotate180: 'Rotate 180°', + rotate270: 'Rotate 270° CW', + flipNone: 'No Flip', + flipHorizontal: 'Flip Horizontal', + flipVertical: 'Flip Vertical', + presetLosslessTitle: 'Balanced Compress & Strip EXIF', + presetLosslessSub: 'Quality 85 compression with real EXIF/GPS privacy removal', + presetLosslessTag: 'Balanced', + presetGovTitle: 'Attachment Limit (<=300KB)', + presetGovSub: 'Convert to JPEG, quality 70, max width 1280px, flag files over 300KB', + presetGovTag: '300KB Limit', + presetJpgTitle: 'Batch to JPEG', + presetJpgSub: 'Convert images to standard JPEG', + presetJpgTag: 'To JPEG', + presetWebpTitle: 'Batch to WebP', + presetWebpSub: 'Modern compact WebP encoding', + presetWebpTag: 'To WebP', + presetPngTitle: 'Batch to PNG', + presetPngSub: 'Lossless PNG conversion', + presetPngTag: 'To PNG', + presetIcoTitle: 'Generate ICO / Favicon', + presetIcoSub: 'Resize to 256x256 and export standard ICO icon', + presetIcoTag: 'ICO Icon', + errUnknownExt: 'Unknown image file extension', + errCannotGenUniqueName: 'Could not generate a unique output filename', + errHostFailed: 'Host image processing failed', + errInspectFailed: 'Failed to inspect image metadata', + errMergePdfFailed: 'Failed to merge images into PDF', + errBase64Missing: 'Host did not return a Base64 Data URL', + errEnsureFailed: 'Failed to provision image engine', + errUnsupportedEngine: 'Host does not support image primitives', + errNoTaskToCancel: 'No active image task to cancel', + errSelectAtLeastOne: 'Select at least 1 image first', + wbTitle: 'Batch Image & Inspector', + wbSubtitleSingle: 'Single Inspector · EXIF / Convert / Base64 / ICO', + wbSubtitleBatch: 'Batch Mode · Compress / Resize / Convert / Merge PDF', + wbPresetLabel: 'Preset', + wbFormatLabel: 'Target Format', + wbQualityLabel: 'Quality', + wbResizeLabel: 'Resize', + wbStripExifLabel: 'Strip EXIF / GPS', + wbRotateLabel: 'Rotate', + wbFlipLabel: 'Flip', + wbCardInspectorTitle: 'Single Image Inspector', + wbCardBatchTitle: 'Batch & Engine Status', + badgeExifYes: 'Has EXIF', + badgeExifNo: 'No EXIF', + badgeReady: 'Ready', + badgeProvision: 'Needs Engine', + badgeRunning: 'Working', + metricResolution: 'Dimensions', + metricFormatColor: 'Format / Color', + metricSize: 'File Size', + metricExifTags: 'EXIF / GPS Tags', + metricSelected: 'Selected', + inspectorEmptyNote: 'Drop or pick a single image to inspect dimensions, color space, and EXIF/GPS tags; pick multiple for batch mode.', + inspectorExifSummary: 'Found {count} EXIF tag(s) ({preview}). One-click strip available.', + inspectorNoExifNote: 'No EXIF metadata detected. Convert format, copy Base64, or generate ICO directly.', + batchNoteReady: 'Real stripExif privacy cleanup, batch convert/resize, and real embedded images-to-PDF without overwriting originals.', + batchNoteProvision: 'Image engine is not provisioned yet. Click "Prepare Image Engine" to download on demand.', + actionRunBatch: 'Process Selected ({count})', + btnRunBatch: 'Process ({count})', + btnProcessing: 'Processing…', + tagProcessing: 'Processing', + summaryProcessing: 'Processing {count} image(s)…', + actionStripExif: 'Strip Privacy EXIF', + actionCopyBase64: 'Convert & Copy Base64', + actionMakeIco: 'Generate ICO / Favicon', + actionMergePdf: 'Merge Images to PDF ({count})', + actionInspectImage: 'Inspect Metadata / EXIF', + actionEnsureEngine: 'Prepare Image Engine', + actionCancelTask: 'Cancel Active Task', + actionPickFiles: 'Select Images...', + actionPickFolder: 'Select Folder...', + actionRevealOriginal: 'Reveal Original', + actionRevealOutput: 'Reveal Output', + actionToggleAll: 'Toggle Select All', + actionRemoveItem: 'Remove from Queue', + actionClearList: 'Clear Queue', + actionTrashItem: 'Move to Trash', + toastInspectOk: 'Metadata loaded', + toastInspectFail: 'Failed to inspect image', + toastStripExifOk: 'EXIF metadata stripped', + toastStripExifFail: 'Failed to strip EXIF', + toastBase64Ok: 'Copied Base64 Data URL', + toastBase64Fail: 'Failed to generate Base64', + toastIcoOk: 'ICO / Favicon generated', + toastIcoFail: 'Failed to generate ICO', + toastMergePdfOk: 'Images merged into PDF', + toastMergePdfMsg: 'Embedded {pages} image(s) ({size}): {path}', + toastMergePdfFail: 'Failed to merge images to PDF', + toastBatchDone: 'Finished ({done} succeeded, {failed} failed)', + toastBatchOverLimit: 'Processed {done} image(s); {overLimit} still exceed 300KB', + toastEnsureOk: 'Image engine ready', + toastEnsureFail: 'Failed to provision image engine', + toastCancelOk: 'Active task cancelled', + toastCancelFail: 'Failed to cancel task', + toastImportFailed: 'Failed to import images', + toastRevealFailed: 'Failed to reveal file', + pickFilesTitle: 'Select Images', + pickFilesFilter: 'Image Files', + pickFolderTitle: 'Select Image Folder', + errNoFolderPicked: 'No folder selected', + confirmRootTitle: 'Scan entire drive root {path}?', + confirmRootMsg: 'Scanning a drive root may take a long time.', + confirmRootAction: 'Continue', + dropTitle: 'Drop 1 image to inspect or multiple images to batch process / merge PDF', + dropSubtitle: 'Supports PNG / JPG / WebP / BMP / GIF / TIFF / AVIF. Originals are never overwritten.', + searchPlaceholder: 'Filter imported images...', + summaryText: '{mode} · Selected {selected}/{total}', + modeSingle: 'Single Inspect', + modeBatch: 'Batch Process', + subListTitle: 'Image Queue ({count})', + subListSubtitle: 'Selected {selected} · Originals {size}', + emptyQueue: 'Select or drop one or more images to begin', + emptyNoMatch: 'No matching images', + tagDone: 'Done', + tagOverLimit: '>300KB', + tagFailed: 'Failed', + tagExifStripped: 'EXIF Stripped', + panelTitle: 'Batch Image & Inspector', + sectionTitle: 'Images ({count})' } -) -export const t: typeof rawT = (key, params) => { - const out = rawT(key, params) - if (!out.includes('[[')) return out - return out.replace(/\[\[([A-Za-z0-9_.-]+):([^|\]]+)\|([^\]]+)\]\]/g, (_m, k: string, one: string, other: string) => { - const v = params?.[k] - const n = typeof v === 'number' ? v : Number(String(v ?? '').replace(/,/g, '')) - return n === 1 ? one : other - }) } + +export const t = createTranslator(MESSAGES, { defaultLocale: 'en-US' }) diff --git a/extensions/batch-image/src/index.ts b/extensions/batch-image/src/index.ts index 47c62d2b..fc67cf7f 100644 --- a/extensions/batch-image/src/index.ts +++ b/extensions/batch-image/src/index.ts @@ -1,9 +1,15 @@ +/** + * 图片压缩与工具(布局三:左侧单图深度检查 / 批量参数工作台 + 右侧图片队列) + * + * - 合并吸收 image-tool:选中/导入单张图片自动进入深度检查模式(展示尺寸、色彩空间、格式、体积与 EXIF/GPS 标签), + * 提供一键抹除隐私 EXIF、单图格式转换、转 Base64 复制、生成 ICO/Favicon + * - 多图模式:无缝切换批量压缩、缩放、改格式、旋转翻转与真实嵌图合并 PDF(images-to-pdf) + */ import { List, ActionPanel, Action, Icon, - Color, Clipboard, useState, useEffect, @@ -16,32 +22,38 @@ import { } from '@ztools/declarative-ui' import { t } from './i18n.js' import { - ImageProcessOutcome, - ImageProcessSettings, - OutputFormat, - QualityTier, - RealImageFileItem, - ResizePreset, IMAGE_IMPORT_RULES, IMAGE_IMPORT_SUPPORTED_TEXT, + cancelActiveImageTask, + convertImageToBase64, createImageImportTransport, - describeOutcomeDetail, - describeOutcomeTag, + ensureImageEngines, + findCapability, formatBytes, + generateImageIco, getFormatOptions, getImageWorkshopPresets, getQualityOptions, getResizeOptions, + inspectImageMetadata, + mergeImagesToPdf, openImageFileLocation, - parseClipboardImagePaths, processImageBatch, - readClipboardImageFilePaths, - summarizeOutcomes, + queryRuntimeCapabilities, + stripImageExif, toImageItem, - trashImageFileItem + trashImageFileItem, + type ImageFlipOption, + type ImageInspectMetadata, + type ImageProcessOutcome, + type ImageProcessSettings, + type ImageRotateOption, + type QualityTier, + type RealImageFileItem, + type ResizePreset, + type TargetFormatOption, + type ToolRuntimeCapabilitiesSnapshot } from './logic.js' -import { isRealElectronHost } from './native-ipc.js' -import { isDeclarativeFileInputSupported } from './host-compat.js' import { FileImportResult, NormalizedFileInput, @@ -51,7 +63,6 @@ import { friendlyFileError, isVolumeRoot, mergeByPath, - normalizeFileInput, pickFiles, pickFolder, summarizeImport @@ -60,49 +71,65 @@ import { resolveErrorMessage } from './error-i18n.js' export * from './logic.js' -/** 插件入口子命令 → 处理方案 */ -const FEATURE_TO_PRESET_ID: Record = { - 'preset-lossless': 'preset-smart-lossless', - 'preset-gov-limit': 'preset-extreme-300k', - 'preset-to-jpg': 'preset-to-jpg', - 'preset-doc-bw': 'preset-doc-grayscale' -} - -function errorText(err: unknown): string { - return err instanceof Error ? err.message : String(err) -} - export function BatchImageCommand() { useLocale() const presets = getImageWorkshopPresets() - const formatOptions = getFormatOptions() - const qualityOptions = getQualityOptions() - const resizeOptions = getResizeOptions() - const launchCtx = (((globalThis as Record).window || globalThis) as { __ztoolsLaunchContext?: { pluginId?: string; featureCode?: string } }).__ztoolsLaunchContext - const initialFeature = launchCtx && (!launchCtx.pluginId || launchCtx.pluginId === 'batch-image') ? String(launchCtx.featureCode || '').trim() : '' - const resolvedPresetId = FEATURE_TO_PRESET_ID[initialFeature] || initialFeature - const initialPreset = - presets.find((p) => p.id === resolvedPresetId) || presets[0]! const transport = createImageImportTransport() + const [searchText, setSearchText] = useState('') - const [activePresetId, setActivePresetId] = useState(initialPreset.id) - const [outputFormat, setOutputFormat] = useState(initialPreset.defaultFormat) - const [qualityTier, setQualityTier] = useState(initialPreset.defaultQuality) - const [resizePreset, setResizePreset] = useState(initialPreset.defaultResize) + const [capabilities, setCapabilities] = useState(null) + const [activePresetId, setActivePresetId] = useState(presets[0]!.id) + const [outputFormat, setOutputFormat] = useState(presets[0]!.defaultFormat) + const [qualityTier, setQualityTier] = useState(presets[0]!.defaultQuality) + const [resizePreset, setResizePreset] = useState(presets[0]!.defaultResize) + const [stripExif, setStripExif] = useState(true) + const [rotate, setRotate] = useState(0) + const [flip, setFlip] = useState('none') const [files, setFiles] = useState([]) const [checkedIds, setCheckedIds] = useState([]) - const [isImporting, setIsImporting] = useState(false) - const [importProgress, setImportProgress] = useState<{ visitedDirs: number; matchedFiles: number } | null>(null) + const [inspectedMeta, setInspectedMeta] = useState(null) + const [isBusy, setIsBusy] = useState(false) const [isRunning, setIsRunning] = useState(false) - const [runningIds, setRunningIds] = useState([]) + const [processingId, setProcessingId] = useState(null) - const runningRef = useRef(false) - const importSeqRef = useRef(0) - const importAbortRef = useRef(null) + const mountedRef = useRef(true) const filesRef = useRef(files) filesRef.current = files + async function refreshCapabilities() { + const res = await queryRuntimeCapabilities() + if (mountedRef.current && res.ok && res.data) { + setCapabilities(res.data) + } + } + + useEffect(() => { + mountedRef.current = true + void refreshCapabilities() + return () => { + mountedRef.current = false + } + }, []) + + async function inspectSingleFile(file: RealImageFileItem, announce = false) { + const res = await inspectImageMetadata(file.path) + if (!mountedRef.current) return + if (!res.ok || !res.metadata) { + if (announce) showToast({ style: Toast.Style.Failure, title: t('toastInspectFail'), message: res.error }) + return + } + setInspectedMeta(res.metadata) + setFiles((prev) => prev.map((f) => (f.id === file.id ? { ...f, metadata: res.metadata, sizeBytes: res.metadata!.sizeBytes } : f))) + if (announce) { + showToast({ + style: Toast.Style.Success, + title: t('toastInspectOk'), + message: `${res.metadata.width}x${res.metadata.height} · ${res.metadata.format}` + }) + } + } + function applyImportResult(result: FileImportResult) { const incoming = result.files.map(toImageItem) const { merged, added, duplicates } = mergeByPath(filesRef.current, incoming, (f) => f.path) @@ -110,10 +137,14 @@ export function BatchImageCommand() { filesRef.current = merged setFiles(merged) setCheckedIds((prev) => Array.from(new Set([...prev, ...added.map((f) => f.id)]))) + // 导入后若仅有一张图,自动触发单图深度检查 + if (merged.length === 1) { + void inspectSingleFile(merged[0]!, false) + } } const summary = summarizeImport(result, { added: added.length, duplicates }, IMAGE_IMPORT_SUPPORTED_TEXT) if (summary) { - void showToast({ + showToast({ style: summary.ok ? Toast.Style.Success : Toast.Style.Failure, title: summary.title, message: summary.message @@ -121,97 +152,47 @@ export function BatchImageCommand() { } } - async function runImport( - task: ( - signal: AbortSignal, - onProgress: (progress: { visitedDirs: number; matchedFiles: number }) => void - ) => Promise - ) { - importAbortRef.current?.abort() - const controller = new AbortController() - importAbortRef.current = controller - const seq = ++importSeqRef.current - setIsImporting(true) - setImportProgress(null) + async function runImport(task: () => Promise) { + setIsBusy(true) try { - const result = await task(controller.signal, (progress) => { - if (seq === importSeqRef.current) setImportProgress(progress) - }) - if (seq !== importSeqRef.current) return + const result = await task() + if (!mountedRef.current) return applyImportResult(result) } catch (err) { - if (seq !== importSeqRef.current) return - void showToast({ style: Toast.Style.Failure, title: t('importFailedTitle'), message: friendlyFileError(err) }) + if (!mountedRef.current) return + showToast({ style: Toast.Style.Failure, title: t('toastImportFailed'), message: friendlyFileError(err) }) } finally { - if (seq === importSeqRef.current) { - importAbortRef.current = null - setIsImporting(false) - setImportProgress(null) - } + if (mountedRef.current) setIsBusy(false) } } function handlePickFiles() { - void runImport(() => pickFiles(transport, IMAGE_IMPORT_RULES, { title: t('pickFilesTitle'), filterName: t('pickFilesFilterName') })) + void runImport(() => pickFiles(transport, IMAGE_IMPORT_RULES, { title: t('pickFilesTitle'), filterName: t('pickFilesFilter') })) } function handlePickFolder() { - void runImport(async (signal, onProgress) => { + void runImport(async () => { const picked = await pickFolder(transport, { title: t('pickFolderTitle') }) - if (signal.aborted || picked.canceled) { - return { files: [], ignored: 0, truncated: false, failedDirs: [], canceled: true } - } + if (picked.canceled) return { files: [], ignored: 0, truncated: false, failedDirs: [], canceled: true } if (picked.error || !picked.folderPath) { - return { files: [], ignored: 0, truncated: false, failedDirs: [], canceled: false, error: resolveErrorMessage(picked, t('noFolderSelected')) } + return { files: [], ignored: 0, truncated: false, failedDirs: [], canceled: false, error: resolveErrorMessage(picked, t('errNoFolderPicked')) } } if (isVolumeRoot(picked.folderPath)) { - const confirmed = await confirmAlert({ + const ok = await confirmAlert({ title: t('confirmRootTitle', { path: picked.folderPath }), message: t('confirmRootMsg'), primaryAction: { title: t('confirmRootAction'), style: 'default' } }) - if (signal.aborted || !confirmed) { - return { files: [], ignored: 0, truncated: false, failedDirs: [], canceled: true } - } + if (!ok) return { files: [], ignored: 0, truncated: false, failedDirs: [], canceled: true } } - return collectFolderFiles(transport, picked.folderPath, IMAGE_IMPORT_RULES, { signal, onProgress }) + return collectFolderFiles(transport, picked.folderPath, IMAGE_IMPORT_RULES) }) } function handleFileInput(input: NormalizedFileInput) { - void runImport((signal, onProgress) => - expandInputPaths(transport, input.paths, IMAGE_IMPORT_RULES, { - knownDirectories: input.directories, - signal, - onProgress - }) - ) + void runImport(() => expandInputPaths(transport, input.paths, IMAGE_IMPORT_RULES, { knownDirectories: input.directories })) } - useEffect(() => { - let disposeDrop: (() => void) | undefined - if (!isDeclarativeFileInputSupported()) { - const w = typeof window !== 'undefined' ? (window as { ztools?: { events?: { on?: (event: string, cb: (env: unknown) => void) => (() => void) | void; off?: (event: string, cb: (env: unknown) => void) => void } } }) : null - const eventsApi = w?.ztools?.events - if (eventsApi && typeof eventsApi.on === 'function') { - const onDrop = (envelope: unknown) => { - const input = normalizeFileInput(envelope) - if (input.paths.length > 0) handleFileInput(input) - } - const off = eventsApi.on('plugin_files_dropped', onDrop) - disposeDrop = () => { - if (typeof off === 'function') off() - else if (typeof eventsApi.off === 'function') eventsApi.off('plugin_files_dropped', onDrop) - } - } - } - return () => { - importSeqRef.current += 1 - importAbortRef.current?.abort() - disposeDrop?.() - } - }, []) - function handleSelectPreset(presetId: string) { setActivePresetId(presetId) const found = presets.find((p) => p.id === presetId) @@ -219,552 +200,502 @@ export function BatchImageCommand() { setOutputFormat(found.defaultFormat) setQualityTier(found.defaultQuality) setResizePreset(found.defaultResize) + setStripExif(found.stripExif) } } - const activePreset = presets.find((p) => p.id === activePresetId) || presets[0]! + const activePreset = presets.find((p) => p.id === activePresetId) ?? presets[0]! + const selectedFiles = files.filter((f) => checkedIds.includes(f.id)) + const isSingleMode = files.length === 1 || selectedFiles.length === 1 + const singleTarget = selectedFiles.length === 1 ? selectedFiles[0]! : files.length === 1 ? files[0]! : null + + const processCap = findCapability(capabilities, 'image.process') + const needsProvision = processCap?.status === 'needs_provisioning' - async function executeBatchProcess(targetFiles: RealImageFileItem[]) { - if (runningRef.current) return - if (targetFiles.length === 0) { - await showToast({ - style: Toast.Style.Failure, - title: t('selectAtLeastOne') - }) + async function handleBatchProcess(targets: RealImageFileItem[]) { + if (targets.length === 0) { + showToast({ style: Toast.Style.Failure, title: t('errSelectAtLeastOne') }) return } - const settings: ImageProcessSettings = { - method: activePreset.method, outputFormat, qualityTier, resizePreset, - grayscale: activePreset.grayscale, + stripExif, + rotate, + flip, sizeLimitBytes: activePreset.sizeLimitBytes } - - runningRef.current = true + setIsBusy(true) setIsRunning(true) - let progressToast: { hide: () => Promise } | null = null - const appliedOutcomes = new Map() try { - progressToast = await showToast({ - style: Toast.Style.Animated, - title: t('processingBatchTitle', { count: targetFiles.length }), - message: activePreset.title - }) - - await processImageBatch(targetFiles, settings, { - shouldSkip: (id: string) => !filesRef.current.some((item) => item.id === id), - onStart: (id: string) => { - setRunningIds([id]) + const outcomes = await processImageBatch(targets, settings, { + onStart: (id) => { + if (mountedRef.current) setProcessingId(id) }, - onItem: (id: string, outcome: ImageProcessOutcome) => { - setRunningIds((prev) => prev.filter((item) => item !== id)) - // 处理期间被用户移出列表的条目直接忽略,绝不重新写回列表 - if (!filesRef.current.some((item) => item.id === id)) return - appliedOutcomes.set(id, outcome) - const next = filesRef.current.map((item) => { - if (item.id !== id) return item - const knownSize = - item.sizeBytes ?? (outcome.status === 'done' ? outcome.originalBytes : null) - return { ...item, sizeBytes: knownSize, result: outcome } - }) - filesRef.current = next - setFiles(next) + onItem: (id, outcome) => { + if (!mountedRef.current) return + setProcessingId((curr) => (curr === id ? null : curr)) + setFiles((prev) => prev.map((item) => (item.id === id ? { ...item, result: outcome } : item))) } }) - - await progressToast?.hide() - if (appliedOutcomes.size === 0) return - const summary = summarizeOutcomes(appliedOutcomes.values()) - - if (summary.done === 0) { - await showToast({ - style: Toast.Style.Failure, - title: summary.total > 1 ? t('batchAllFailedTitle', { total: summary.total }) : t('batchSingleFailedTitle'), - message: summary.firstError || t('errHostReturnFailed') - }) - return - } - if (summary.failed > 0) { - await showToast({ - style: Toast.Style.Failure, - title: t('batchPartialTitle', { done: summary.done, failed: summary.failed }), - message: summary.firstError - }) - return + if (!mountedRef.current) return + let done = 0 + let failed = 0 + let overLimit = 0 + for (const o of outcomes.values()) { + if (o.status === 'done') { + done += 1 + if (o.overLimitBytes !== null) overLimit += 1 + } else { + failed += 1 + } } - if (summary.overLimit > 0 && settings.sizeLimitBytes) { - await showToast({ - style: Toast.Style.Failure, - title: t('batchOverLimitTitle', { - done: summary.done, - overLimit: summary.overLimit, - limit: formatBytes(settings.sizeLimitBytes) - }), - message: t('batchOverLimitMsg') + if (overLimit > 0) { + showToast({ style: Toast.Style.Failure, title: t('toastBatchOverLimit', { done, overLimit }) }) + } else { + showToast({ + style: failed === 0 ? Toast.Style.Success : Toast.Style.Failure, + title: t('toastBatchDone', { done, failed }) }) - return } - const savedText = - summary.comparableOriginalBytes > 0 - ? t('batchSavedPart', { size: formatBytes(summary.savedBytes), pct: summary.savePercent }) - : '' - const notSmallerText = summary.notSmaller > 0 ? t('batchNotSmallerPart', { count: summary.notSmaller }) : '' - await showToast({ - style: Toast.Style.Success, - title: t('batchSuccessTitle', { done: summary.done }), - message: t('batchSuccessMsg', { - size: formatBytes(summary.outputBytes), - saved: savedText, - notSmaller: notSmallerText - }) - }) - } catch (err) { - await progressToast?.hide() - await showToast({ - style: Toast.Style.Failure, - title: t('processErrorTitle'), - message: friendlyFileError(err) - }) } finally { - await progressToast?.hide() - setRunningIds([]) - runningRef.current = false - setIsRunning(false) + if (mountedRef.current) { + setProcessingId(null) + setIsRunning(false) + setIsBusy(false) + } } } - async function handleAddFromClipboard() { - let clipText = '' + async function handleStripExif(target: RealImageFileItem) { + setIsBusy(true) + setProcessingId(target.id) try { - clipText = await Clipboard.readText() - } catch (err) { - await showToast({ - style: Toast.Style.Failure, - title: t('readClipboardFailed'), - message: errorText(err) - }) - return - } - let paths = parseClipboardImagePaths(clipText) - if (paths.length === 0) { - paths = await readClipboardImageFilePaths() - } - if (paths.length === 0) { - await showToast({ - style: Toast.Style.Failure, - title: t('noClipImagePathsTitle'), - message: t('noClipImagePathsMsg', { supported: IMAGE_IMPORT_SUPPORTED_TEXT }) + const outcome = await stripImageExif(target) + if (!mountedRef.current) return + setFiles((prev) => prev.map((item) => (item.id === target.id ? { ...item, result: outcome } : item))) + showToast({ + style: outcome.status === 'done' ? Toast.Style.Success : Toast.Style.Failure, + title: outcome.status === 'done' ? t('toastStripExifOk') : t('toastStripExifFail'), + message: outcome.status === 'done' ? outcome.outputPath : outcome.error }) - return + } finally { + if (mountedRef.current) { + setProcessingId(null) + setIsBusy(false) + } } - void runImport((signal, onProgress) => - expandInputPaths(transport, paths, IMAGE_IMPORT_RULES, { signal, onProgress }) - ) } - function handleRemoveFromList(file: RealImageFileItem) { - if (runningIds.includes(file.id)) { - void showToast({ style: Toast.Style.Failure, title: t('removeBusy') }) - return + async function handleCopyBase64(target: RealImageFileItem) { + setIsBusy(true) + try { + const res = await convertImageToBase64(target) + if (!mountedRef.current) return + if (!res.ok || !res.dataUrl) { + showToast({ style: Toast.Style.Failure, title: t('toastBase64Fail'), message: res.error }) + } else { + await Clipboard.copy(res.dataUrl) + showToast({ style: Toast.Style.Success, title: t('toastBase64Ok') }) + } + } finally { + if (mountedRef.current) setIsBusy(false) } - const next = filesRef.current.filter((item) => item.id !== file.id) - filesRef.current = next - setFiles(next) - setCheckedIds((prev) => prev.filter((id) => id !== file.id)) } - function handleClearList() { - if (runningRef.current) { - void showToast({ style: Toast.Style.Failure, title: t('clearBusy') }) - return + async function handleGenerateIco(target: RealImageFileItem) { + setIsBusy(true) + setProcessingId(target.id) + try { + const outcome = await generateImageIco(target) + if (!mountedRef.current) return + setFiles((prev) => prev.map((item) => (item.id === target.id ? { ...item, result: outcome } : item))) + showToast({ + style: outcome.status === 'done' ? Toast.Style.Success : Toast.Style.Failure, + title: outcome.status === 'done' ? t('toastIcoOk') : t('toastIcoFail'), + message: outcome.status === 'done' ? outcome.outputPath : outcome.error + }) + } finally { + if (mountedRef.current) { + setProcessingId(null) + setIsBusy(false) + } } - importSeqRef.current += 1 - importAbortRef.current?.abort() - importAbortRef.current = null - setIsImporting(false) - setImportProgress(null) - filesRef.current = [] - setFiles([]) - setCheckedIds([]) } - async function handleTrashOriginalImage(file: RealImageFileItem) { - if (runningIds.includes(file.id)) { - await showToast({ style: Toast.Style.Failure, title: t('trashBusy') }) + async function handleMergePdf(targets: RealImageFileItem[]) { + if (targets.length === 0) { + showToast({ style: Toast.Style.Failure, title: t('errSelectAtLeastOne') }) return } - const outputNote = - file.result?.status === 'done' - ? t('trashNoteHasOutput', { path: file.result.outputPath }) - : t('trashNoteNoOutput') - const confirmed = await confirmAlert({ - title: t('confirmTrashTitle'), - message: t('confirmTrashMsg', { - name: file.name, - size: file.sizeBytes === null ? t('sizeUnknownShort') : formatBytes(file.sizeBytes), - path: file.path, - note: outputNote - }), - primaryAction: { title: t('confirmTrashAction'), style: 'destructive' } - }) - if (!confirmed) return - const res = await trashImageFileItem(file.path) - if (!res.ok) { - await showToast({ - style: Toast.Style.Failure, - title: t('trashFailedTitle'), - message: resolveErrorMessage(res, t('trashInUseMsg')) + setIsBusy(true) + try { + const res = await mergeImagesToPdf(targets) + if (!mountedRef.current) return + showToast({ + style: res.ok ? Toast.Style.Success : Toast.Style.Failure, + title: res.ok ? t('toastMergePdfOk') : t('toastMergePdfFail'), + message: res.ok + ? t('toastMergePdfMsg', { pages: res.pageCount, size: formatBytes(res.outputBytes), path: res.outputPath }) + : res.error }) - return + } finally { + if (mountedRef.current) setIsBusy(false) } - const next = filesRef.current.filter((item) => item.id !== file.id) - filesRef.current = next - setFiles(next) - setCheckedIds((prev) => prev.filter((id) => id !== file.id)) - await showToast({ - style: Toast.Style.Success, - title: t('trashSuccessTitle'), - message: file.name - }) } - async function handleRevealInFolder(file: RealImageFileItem) { - const target = file.result?.status === 'done' ? file.result.outputPath : file.path - const ok = await openImageFileLocation(target) - if (!ok) { - await showToast({ - style: Toast.Style.Failure, - title: t('revealFailedTitle'), - message: target + async function handleEnsureEngine() { + setIsBusy(true) + try { + const res = await ensureImageEngines() + if (!mountedRef.current) return + showToast({ + style: res.ok ? Toast.Style.Success : Toast.Style.Failure, + title: res.ok ? t('toastEnsureOk') : t('toastEnsureFail'), + message: res.error }) + await refreshCapabilities() + } finally { + if (mountedRef.current) setIsBusy(false) } } - const q = searchText.trim().toLowerCase() - const filteredFiles = files.filter( - (f) => - !q || - f.name.toLowerCase().includes(q) || - f.path.toLowerCase().includes(q) || - f.extension.toLowerCase().includes(q) - ) - - const selectedFiles = files.filter((f) => checkedIds.includes(f.id)) - const selectedKnownBytes = selectedFiles.reduce((acc, f) => acc + (f.sizeBytes ?? 0), 0) - const selectedUnknown = selectedFiles.filter((f) => f.sizeBytes === null).length - const resultSummary = summarizeOutcomes( - files.map((f) => f.result).filter((r): r is ImageProcessOutcome => Boolean(r)) - ) - const hasResults = resultSummary.total > 0 - - const maxImageBytes = Math.max(1, ...files.map((f) => f.sizeBytes ?? 0)) - const outExtLabel = outputFormat === 'keep' ? t('originalExtLabel') : outputFormat - const allFilteredChecked = filteredFiles.length > 0 && filteredFiles.every((item) => checkedIds.includes(item.id)) - - function toggleAllFiltered() { - const filteredIds = new Set(filteredFiles.map((item) => item.id)) - setCheckedIds((prev) => - allFilteredChecked - ? prev.filter((id) => !filteredIds.has(id)) - : Array.from(new Set([...prev, ...filteredIds])) - ) + async function handleCancel() { + const res = await cancelActiveImageTask() + showToast({ + style: res.ok ? Toast.Style.Success : Toast.Style.Failure, + title: res.ok ? t('toastCancelOk') : t('toastCancelFail'), + message: res.ok ? res.taskId : res.error + }) } - const pickFilesAction = () => - Action({ - title: t('actionPickFilesEllipsis'), - icon: Icon.Plus, - shortcut: { modifiers: ['ctrl'], key: 'o' }, - onAction: handlePickFiles - }) - const pickFolderAction = () => - Action({ - title: t('actionPickFolderEllipsis'), - icon: Icon.Folder, - shortcut: { modifiers: ['ctrl', 'shift'], key: 'o' }, - onAction: handlePickFolder - }) - const clipboardAction = () => - Action({ - title: t('actionFromClipboard'), - icon: Icon.Clipboard, - onAction: handleAddFromClipboard - }) + const q = searchText.trim().toLowerCase() + const visibleFiles = files.filter((f) => !q || f.name.toLowerCase().includes(q) || f.path.toLowerCase().includes(q)) + const allVisibleChecked = visibleFiles.length > 0 && visibleFiles.every((f) => checkedIds.includes(f.id)) + const selectedBytes = selectedFiles.reduce((s, f) => s + (f.sizeBytes ?? 0), 0) - const selectedSizeText = `${formatBytes(selectedKnownBytes)}${selectedUnknown > 0 ? t('selectedUnknownPart', { count: selectedUnknown }) : ''}` - const resultText = hasResults ? t('resultSummaryPart', { done: resultSummary.done, failed: resultSummary.failed }) : '' + function toggleAllVisible() { + const ids = visibleFiles.map((f) => f.id) + setCheckedIds((prev) => (allVisibleChecked ? prev.filter((id) => !ids.includes(id)) : Array.from(new Set([...prev, ...ids])))) + } - const rightQueueItems = filteredFiles.map((f) => { - const isChecked = checkedIds.includes(f.id) - const isProcessingItem = runningIds.includes(f.id) - const accessories: Array> = [] - if (f.sizeBytes !== null) { - accessories.push({ - progress: { value: Math.max(8, Math.min(100, Math.round((f.sizeBytes / maxImageBytes) * 100))) } - }) + const activeMeta = singleTarget?.metadata || (inspectedMeta && singleTarget && inspectedMeta.filePath === singleTarget.path ? inspectedMeta : null) + const exifKeys = activeMeta ? Object.keys(activeMeta.exif) : [] + + const items = visibleFiles.map((file) => { + const isChecked = checkedIds.includes(file.id) + const isProcessingItem = processingId === file.id + const outcome: ImageProcessOutcome | undefined = file.result + const accessories: Array<{ tag?: string; text?: string }> = [] + if (isProcessingItem) { + accessories.push({ tag: t('tagProcessing') }) + accessories.push({ text: file.sizeBytes === null ? t('sizeUnknown') : formatBytes(file.sizeBytes) }) + } else if (outcome?.status === 'done') { + if (outcome.overLimitBytes !== null) accessories.push({ tag: t('tagOverLimit') }) + else accessories.push({ tag: outcome.exifStripped ? t('tagExifStripped') : t('tagDone') }) + accessories.push({ text: formatBytes(outcome.outputBytes) }) + } else if (outcome?.status === 'failed') { + accessories.push({ tag: t('tagFailed') }) + } else { + accessories.push({ tag: file.extension.replace('.', '').toUpperCase() }) + accessories.push({ text: file.sizeBytes === null ? t('sizeUnknown') : formatBytes(file.sizeBytes) }) } - accessories.push({ tag: { value: describeOutcomeTag(f.result) } }) - accessories.push({ text: f.sizeBytes === null ? t('sizeUnknown') : formatBytes(f.sizeBytes) }) - - const doneResult = f.result?.status === 'done' ? f.result : null - const actionChildren: Array | ReturnType> = [ - Action({ - title: t('actionRunSelected', { count: selectedFiles.length }), - icon: Icon.Bolt, - onAction: () => executeBatchProcess(selectedFiles) - }), - Action({ - title: doneResult ? t('actionRevealOutput') : t('actionRevealSource'), - icon: Icon.Folder, - shortcut: { modifiers: ['ctrl'], key: 'enter' }, - onAction: () => handleRevealInFolder(f) - }), - Action({ - title: t('actionRunSingle'), - icon: Icon.Play, - shortcut: { modifiers: ['ctrl'], key: 's' }, - onAction: () => executeBatchProcess([f]) - }) - ] - if (doneResult) { - actionChildren.push( - Action({ - title: t('actionCopyOutputPath'), - icon: Icon.CopyClipboard, - shortcut: { modifiers: ['ctrl', 'shift'], key: 'c' }, - onAction: async () => { - try { - await Clipboard.copy(doneResult.outputPath) - await showToast({ style: Toast.Style.Success, title: t('copiedOutputPathTitle'), message: doneResult.outputPath }) - } catch (err) { - await showToast({ style: Toast.Style.Failure, title: t('copyFailedTitle'), message: errorText(err) }) - } - } - }) - ) - } - actionChildren.push( - ActionPanel.Section({ - title: t('sectionList'), + + return List.Item({ + id: file.id, + title: file.name, + subtitle: file.metadata ? `${file.metadata.width}x${file.metadata.height} · ${file.metadata.format}` : file.parentDir, + icon: { source: Icon.Image }, + checkable: true, + checked: isChecked, + onCheckChange: () => { + setCheckedIds((prev) => (prev.includes(file.id) ? prev.filter((id) => id !== file.id) : [...prev, file.id])) + }, + accessories, + actions: ActionPanel({ + title: file.name, children: [ - ...(isProcessingItem - ? [] - : [ + Action({ + title: t('actionRunBatch', { count: selectedFiles.length > 0 ? selectedFiles.length : 1 }), + icon: Icon.Play, + onAction: () => handleBatchProcess(selectedFiles.length > 0 ? selectedFiles : [file]) + }), + Action({ title: t('actionInspectImage'), icon: Icon.Info, onAction: () => inspectSingleFile(file, true) }), + Action({ title: t('actionStripExif'), icon: Icon.Shield, onAction: () => handleStripExif(file) }), + Action({ title: t('actionCopyBase64'), icon: Icon.CopyClipboard, onAction: () => handleCopyBase64(file) }), + Action({ title: t('actionMakeIco'), icon: Icon.Image, onAction: () => handleGenerateIco(file) }), + Action({ + title: t('actionMergePdf', { count: selectedFiles.length > 0 ? selectedFiles.length : 1 }), + icon: Icon.Document, + onAction: () => handleMergePdf(selectedFiles.length > 0 ? selectedFiles : [file]) + }), + ...(outcome?.status === 'done' + ? [ Action({ - title: t('actionRemove'), - icon: Icon.Minus, - shortcut: { modifiers: ['ctrl'], key: 'backspace' }, - onAction: () => handleRemoveFromList(f) + title: t('actionRevealOutput'), + icon: Icon.Folder, + onAction: async () => { + if (!(await openImageFileLocation(outcome.outputPath))) { + showToast({ style: Toast.Style.Failure, title: t('toastRevealFailed') }) + } + } }) - ]), - pickFilesAction(), - pickFolderAction(), - clipboardAction(), + ] + : []), + Action({ + title: t('actionRevealOriginal'), + icon: Icon.Folder, + onAction: async () => { + if (!(await openImageFileLocation(file.path))) { + showToast({ style: Toast.Style.Failure, title: t('toastRevealFailed') }) + } + } + }), Action({ - title: allFilteredChecked ? t('actionDeselectAll') : t('actionSelectAll'), - icon: Icon.CheckCircle, - shortcut: { modifiers: ['ctrl'], key: 'a' }, - onAction: toggleAllFiltered + title: t('actionRemoveItem'), + icon: Icon.Trash, + onAction: () => { + const next = filesRef.current.filter((f) => f.id !== file.id) + filesRef.current = next + setFiles(next) + setCheckedIds((prev) => prev.filter((id) => id !== file.id)) + } }), Action({ - title: t('actionClearList'), + title: t('actionTrashItem'), icon: Icon.Trash, style: Action.Style.Destructive, - shortcut: { modifiers: ['ctrl', 'shift'], key: 'backspace' }, - onAction: handleClearList + shortcut: { modifiers: ['ctrl', 'shift'], key: 'delete' }, + onAction: async () => { + await trashImageFileItem(file.path) + } }) ] }) - ) - if (!isProcessingItem) { - actionChildren.push( - ActionPanel.Section({ - title: t('sectionFile'), - children: [ - Action({ - title: t('actionTrashSource'), - icon: Icon.Trash, - style: Action.Style.Destructive, - shortcut: { modifiers: [], key: 'delete' }, - onAction: () => handleTrashOriginalImage(f) - }) - ] - }) - ) - } - - return List.Item({ - id: f.id, - title: f.name, - subtitle: describeOutcomeDetail(f.result, f.parentDir), - checkable: true, - checked: isChecked, - onCheckChange: (checked) => { - setCheckedIds((prev) => - checked ? Array.from(new Set([...prev, f.id])) : prev.filter((id) => id !== f.id) - ) - }, - icon: { - source: Icon.Image, - tintColor: Color.SecondaryText - }, - accessories, - actions: ActionPanel({ - title: f.name, - children: actionChildren - }) }) }) + const previewCard = isSingleMode && activeMeta + ? { + title: t('wbCardInspectorTitle'), + badge: activeMeta.hasExif ? t('badgeExifYes') : t('badgeExifNo'), + subtitle: activeMeta.hasExif + ? t('inspectorExifSummary', { + count: exifKeys.length, + preview: exifKeys + .slice(0, 3) + .map((k) => `${k}: ${String(activeMeta.exif[k])}`) + .join(', ') + }) + : t('inspectorNoExifNote'), + metrics: [ + { label: t('metricResolution'), value: `${activeMeta.width}x${activeMeta.height}` }, + { label: t('metricFormatColor'), value: `${activeMeta.format}${activeMeta.colorSpace ? ` / ${activeMeta.colorSpace}` : ''}` }, + { label: t('metricSize'), value: formatBytes(activeMeta.sizeBytes) }, + { label: t('metricExifTags'), value: String(exifKeys.length) } + ] + } + : { + title: t('wbCardBatchTitle'), + badge: isBusy ? t('badgeRunning') : needsProvision ? t('badgeProvision') : t('badgeReady'), + subtitle: needsProvision ? t('batchNoteProvision') : files.length === 0 ? t('inspectorEmptyNote') : t('batchNoteReady'), + metrics: [ + { label: t('metricSelected'), value: String(selectedFiles.length) }, + { label: t('metricSize'), value: formatBytes(selectedBytes) } + ] + } + const fileInputProps = createImportInputProps(handleFileInput, { - allowClipboardImage: true, dropTitle: t('dropTitle'), dropSubtitle: t('dropSubtitle') }) - const inClient = isRealElectronHost() - const summaryText = isImporting - ? t('summaryImporting', { dirs: importProgress?.visitedDirs ?? 0, files: importProgress?.matchedFiles ?? 0 }) - : files.length === 0 - ? inClient - ? t('summaryEmptyClient') - : t('hostRequired') - : t('summaryNormal', { - selected: selectedFiles.length, - total: files.length, - size: selectedSizeText, - result: resultText - }) - - const emptyText = !inClient - ? t('hostRequired') - : q && files.length > 0 - ? t('emptyNoMatch') - : t('summaryEmptyClient') - return List({ - ...fileInputProps, - searchBarPlaceholder: t('searchPlaceholder', { supported: IMAGE_IMPORT_SUPPORTED_TEXT }), + searchBarPlaceholder: t('searchPlaceholder'), onSearchTextChange: setSearchText, isShowingDetail: false, - isLoading: isImporting || isRunning, - actions: ActionPanel({ - title: t('queueActionsTitle'), - children: [pickFilesAction(), pickFolderAction(), clipboardAction()] - }), - searchBarAccessory: List.Dropdown({ - tooltip: t('dropdownTooltip'), - value: activePresetId, - onChange: (val) => handleSelectPreset(val), - children: presets.map((p) => - List.Dropdown.Item({ - title: t('dropdownItemTitle', { tag: p.tag }), - value: p.id - }) - ) - }), + isLoading: isBusy, + ...fileInputProps, filterBar: FilterBar({ - summaryText, - actions: [ - { - id: 'pick-files', - label: t('btnPickFiles'), - title: t('btnPickFiles'), - style: 'secondary', - onAction: handlePickFiles - }, - { - id: 'pick-folder', - label: t('btnPickFolder'), - title: t('btnPickFolder'), - style: 'secondary', - onAction: handlePickFolder - } - ] + summaryText: isRunning + ? t('summaryProcessing', { count: selectedFiles.length }) + : t('summaryText', { + mode: isSingleMode ? t('modeSingle') : t('modeBatch'), + selected: selectedFiles.length, + total: files.length + }), + actions: needsProvision + ? [ + { + id: 'img-primary', + label: t('actionEnsureEngine'), + title: t('actionEnsureEngine'), + style: 'primary', + onAction: () => { + void handleEnsureEngine() + } + }, + { + id: 'pick-files', + label: t('actionPickFiles'), + title: t('actionPickFiles'), + style: 'secondary', + onAction: handlePickFiles + } + ] + : selectedFiles.length > 0 + ? [ + { + id: 'pick-files', + label: t('actionPickFiles'), + title: t('actionPickFiles'), + style: 'secondary', + onAction: handlePickFiles + }, + { + id: 'run-batch', + label: isRunning ? t('btnProcessing') : t('btnRunBatch', { count: selectedFiles.length }), + title: isRunning ? t('btnProcessing') : t('btnRunBatch', { count: selectedFiles.length }), + style: 'primary', + disabled: isRunning || isBusy, + onAction: () => { + void handleBatchProcess(selectedFiles) + } + } + ] + : [ + { + id: 'pick-files', + label: t('actionPickFiles'), + title: t('actionPickFiles'), + style: 'secondary', + onAction: handlePickFiles + }, + { + id: 'pick-folder', + label: t('actionPickFolder'), + title: t('actionPickFolder'), + style: 'secondary', + onAction: handlePickFolder + } + ] }), workbenchPanel: { title: t('wbTitle'), - subtitle: activePreset.subtitle, + subtitle: isSingleMode ? t('wbSubtitleSingle') : t('wbSubtitleBatch'), fields: [ { - id: 'wb-format', + id: 'img-preset', + label: t('wbPresetLabel'), + type: 'select', + value: activePresetId, + onChange: handleSelectPreset, + options: presets.map((p) => ({ label: p.title, value: p.id })) + }, + { + id: 'img-format', label: t('wbFormatLabel'), type: 'select', value: outputFormat, - onChange: (val) => setOutputFormat(val as OutputFormat), - options: formatOptions + onChange: (val: string) => setOutputFormat(val as TargetFormatOption), + options: getFormatOptions() }, { - id: 'wb-quality', + id: 'img-quality', label: t('wbQualityLabel'), type: 'select', value: qualityTier, - onChange: (val) => setQualityTier(val as QualityTier), - options: qualityOptions + onChange: (val: string) => setQualityTier(val as QualityTier), + options: getQualityOptions() }, { - id: 'wb-scale', - label: t('wbScaleLabel'), + id: 'img-resize', + label: t('wbResizeLabel'), type: 'select', value: resizePreset, - onChange: (val) => setResizePreset(val as ResizePreset), - options: resizeOptions + onChange: (val: string) => setResizePreset(val as ResizePreset), + options: getResizeOptions() }, { - id: 'wb-outdir', - label: t('wbOutdirLabel'), - type: 'info', - value: t('wbOutdirValue', { ext: outExtLabel }) + id: 'img-strip-exif', + label: t('wbStripExifLabel'), + type: 'select', + value: stripExif ? 'on' : 'off', + onChange: (val: string) => setStripExif(val === 'on'), + options: [ + { label: t('stripExifOn'), value: 'on' }, + { label: t('stripExifOff'), value: 'off' } + ] }, { - id: 'wb-limits', - label: t('wbLimitsLabel'), - type: 'info', - value: t('wbLimitsValue') - } - ], - previewCard: { - title: t('previewTitle'), - badge: hasResults ? t('previewBadgeDone', { done: resultSummary.done }) : t('previewBadgePending'), - subtitle: t('previewSubtitle', { title: activePreset.title }), - metrics: [ - { label: t('metricSelected'), value: t('metricSelectedVal', { selected: selectedFiles.length, total: files.length }) }, - { label: t('metricSelectedSize'), value: selectedSizeText }, - { - label: t('metricOutSize'), - value: hasResults && resultSummary.done > 0 ? formatBytes(resultSummary.outputBytes) : '—' + id: 'img-rotate', + label: t('wbRotateLabel'), + type: 'select', + value: String(rotate), + onChange: (val: string) => { + const n = Number(val) + if (n === 0 || n === 90 || n === 180 || n === 270) setRotate(n) }, - { - label: t('metricSaved'), - value: - resultSummary.comparableOriginalBytes > 0 - ? `${formatBytes(resultSummary.savedBytes)} (-${resultSummary.savePercent}%)` - : '—' + options: [ + { label: t('rotateNone'), value: '0' }, + { label: t('rotate90'), value: '90' }, + { label: t('rotate180'), value: '180' }, + { label: t('rotate270'), value: '270' } + ] + }, + { + id: 'img-flip', + label: t('wbFlipLabel'), + type: 'select', + value: flip, + onChange: (val: string) => { + if (val === 'none' || val === 'horizontal' || val === 'vertical' || val === 'both') setFlip(val) }, - { label: t('metricFailed'), value: hasResults ? t('metricFailedVal', { count: resultSummary.failed }) : '—' } - ] - } + options: [ + { label: t('flipNone'), value: 'none' }, + { label: t('flipHorizontal'), value: 'horizontal' }, + { label: t('flipVertical'), value: 'vertical' } + ] + } + ], + previewCard }, subList: { - title: t('subListTitle'), - subtitle: t('subListSubtitle', { count: filteredFiles.length }), - checkable: filteredFiles.length > 0, - checked: allFilteredChecked - ? true - : filteredFiles.some((f) => checkedIds.includes(f.id)) - ? 'indeterminate' - : false, - onCheckChange: () => toggleAllFiltered(), - emptyText, - items: rightQueueItems + title: t('subListTitle', { count: visibleFiles.length }), + subtitle: t('subListSubtitle', { selected: selectedFiles.length, size: formatBytes(selectedBytes) }), + emptyText: q && files.length > 0 ? t('emptyNoMatch') : t('emptyQueue'), + checkable: visibleFiles.length > 0, + checked: allVisibleChecked ? true : selectedFiles.length > 0 ? 'indeterminate' : false, + onCheckChange: toggleAllVisible, + items }, + actions: ActionPanel({ + title: t('panelTitle'), + children: [ + Action({ title: t('actionRunBatch', { count: selectedFiles.length }), icon: Icon.Play, onAction: () => handleBatchProcess(selectedFiles) }), + Action({ title: t('actionMergePdf', { count: selectedFiles.length }), icon: Icon.Document, onAction: () => handleMergePdf(selectedFiles) }), + Action({ title: t('actionEnsureEngine'), icon: Icon.Download, onAction: handleEnsureEngine }), + Action({ title: t('actionCancelTask'), icon: Icon.XMarkCircle, onAction: handleCancel }), + Action({ title: t('actionPickFiles'), icon: Icon.Plus, onAction: handlePickFiles }), + Action({ title: t('actionPickFolder'), icon: Icon.Folder, onAction: handlePickFolder }), + Action({ title: t('actionToggleAll'), icon: Icon.CheckCircle, onAction: toggleAllVisible }), + Action({ + title: t('actionClearList'), + icon: Icon.Trash, + onAction: () => { + filesRef.current = [] + setFiles([]) + setCheckedIds([]) + setInspectedMeta(null) + } + }) + ] + }), children: [ List.Section({ - title: t('sectionQueueTitle', { count: filteredFiles.length }), - children: rightQueueItems + title: t('sectionTitle', { count: visibleFiles.length }), + children: items }) ] }) diff --git a/extensions/batch-image/src/logic.ts b/extensions/batch-image/src/logic.ts index 6cd72d10..47819f84 100644 --- a/extensions/batch-image/src/logic.ts +++ b/extensions/batch-image/src/logic.ts @@ -1,56 +1,80 @@ /** - * 批量图片压缩与格式转换:业务逻辑层 + * 图片压缩与工具业务逻辑层(Wave 3 薄原语域:image.inspect / image.process / document.pdf.transform) * - * - 图片由用户选择文件、选择文件夹、拖入或从剪贴板添加,插件不会自动扫描本机目录 - * - 6 个处理方案,参数映射到宿主图片处理接口真实支持的取值(画质 q70 / q85 / q95,缩放 source / max1920 / max1280) - * - 逐张调用宿主处理,每张图都显式指定输出路径:输出前避开已存在的同名文件,绝不覆盖原图 - * - 只展示宿主返回的真实结果(输出路径、体积、尺寸),读不到的信息标为未识别,不做估算 + * - 合并吸收原 image-tool 单图深度检查能力:真实尺寸、色彩空间、格式、体积与完整 EXIF/GPS 标签 + * - 一键单图快捷动作:真实抹除隐私 EXIF(stripExif: true)、格式转换、转 Base64 Data URL 复制、生成 ICO/Favicon + * - 多图批量模式:压缩画质、限宽缩放、格式转换、旋转/翻转、以及调用 tool_document_pdf_transform(images-to-pdf) 真实嵌图合并 PDF */ import { + asRecord, callHostTransport, + cancelRuntimeTask, + ensureRuntimeCapability, + findCapability, formatBytes, - invokeDllPluginCapability, + nextMessageId, + queryRuntimeCapabilities, showRealItemInFolder, - trashRealItem -} from './native-ipc.js' + trashRealItem, + type ToolCapabilityStatus, + type ToolRuntimeCapabilitiesSnapshot +} from './tool-runtime.js' import { friendlyFileError } from './file-import.js' import type { FileImportRules, FileImportTransport, ImportedFile } from './file-import.js' import { t } from './i18n.js' import { resolveErrorMessage } from './error-i18n.js' -export { formatBytes } from './native-ipc.js' +export { + formatBytes, + queryRuntimeCapabilities, + findCapability, + type ToolCapabilityStatus, + type ToolRuntimeCapabilitiesSnapshot +} -export type OutputFormat = 'keep' | 'jpg' | 'png' +export type ImageOutputFormat = 'png' | 'jpeg' | 'webp' | 'avif' | 'ico' | 'bmp' +export type TargetFormatOption = 'keep' | ImageOutputFormat export type QualityTier = 'q70' | 'q85' | 'q95' export type ResizePreset = 'source' | 'max1920' | 'max1280' +export type ImageRotateOption = 0 | 90 | 180 | 270 +export type ImageFlipOption = 'none' | 'horizontal' | 'vertical' | 'both' + +export interface ImageInspectMetadata { + filePath: string + displayName: string + format: string + width: number + height: number + sizeBytes: number + colorSpace: string | null + hasAlpha: boolean | null + hasExif: boolean + exif: Record +} export interface ImageWorkshopPreset { id: string title: string subtitle: string tag: string - method: string - defaultFormat: OutputFormat + defaultFormat: TargetFormatOption defaultQuality: QualityTier defaultResize: ResizePreset - grayscale: boolean - /** 输出体积上限(字节):宿主不会按体积反复压缩,处理后把超过上限的图片如实标出 */ + stripExif: boolean sizeLimitBytes?: number } export interface ImageProcessDone { status: 'done' outputPath: string - /** 原图大小;宿主未返回且插件也读不到时为 null */ originalBytes: number | null outputBytes: number - /** 输出尺寸;宿主读不到(ffmpeg 兜底编码)时为 0,界面显示「尺寸未识别」 */ width: number height: number - /** 输出不小于原图(保持格式且重新编码更大时,宿主会输出原图内容的副本) */ - notSmaller: boolean - /** 本次处理设定的体积上限;输出超过它时为该上限,否则为 null */ + format: string + exifStripped: boolean + base64DataUrl?: string overLimitBytes: number | null } @@ -67,39 +91,75 @@ export interface RealImageFileItem { path: string parentDir: string extension: string - /** 原图大小;读不到(例如从剪贴板添加且宿主未授权读取)时为 null */ sizeBytes: number | null + metadata?: ImageInspectMetadata result?: ImageProcessOutcome } -export interface NativeInvocationResult { - ok: boolean - pluginName: string - method: string - data?: unknown - error?: string - fromFallback?: boolean -} - export interface ImageProcessSettings { - method: string - outputFormat: OutputFormat + outputFormat: TargetFormatOption qualityTier: QualityTier resizePreset: ResizePreset - grayscale: boolean + stripExif: boolean + rotate?: ImageRotateOption + flip?: ImageFlipOption sizeLimitBytes?: number } -export const DLL_PLUGIN_NAME = 'BatchImagePlugin' -export const FORBIDDEN_TARGET_PATTERN = new RegExp('\\\\Windows\\\\System32|\\.\\.\\\\|\\.\\./', 'i') -export function getForbiddenReason(): string { - return t('forbiddenReason') +export interface MergeImagesToPdfResult { + ok: boolean + taskId: string + outputPath: string + outputBytes: number + pageCount: number + error?: string } + +export const FORBIDDEN_TARGET_PATTERN = new RegExp('\\\\Windows\\\\System32|\\.\\.\\\\|\\.\\./', 'i') export const IMAGE_SIZE_LIMIT_300KB = 300 * 1024 -/** 输出文件名后缀:<原文件名>_opt.<扩展名> */ export const OUTPUT_SUFFIX = '_opt' const MAX_NAME_ATTEMPTS = 20 +export const IMAGE_EXT_REGEX = /\.(?:png|jpg|jpeg|webp|bmp|gif|tiff|avif)$/i +export const IMAGE_IMPORT_EXTENSIONS = ['.png', '.jpg', '.jpeg', '.webp', '.bmp', '.gif', '.tiff', '.avif'] as const +export const DERIVED_OUTPUT_REGEX = /_(?:opt|noexif|ico)(?:_\d+){0,2}\.(?:png|jpg|jpeg|webp|bmp|gif|tiff|avif|ico)$/i +export const IMAGE_IMPORT_SUPPORTED_TEXT = 'PNG / JPG / WebP / BMP / GIF / TIFF / AVIF' + +export const IMAGE_IMPORT_RULES: FileImportRules = { + extensions: IMAGE_IMPORT_EXTENSIONS, + excludeFile: (name) => isDerivedOutputName(name), + forbiddenPath: FORBIDDEN_TARGET_PATTERN +} + +let activeImageTaskId = '' + +export function getActiveImageTaskId(): string { + return activeImageTaskId +} + +export function resetImageRuntimeState(): void { + activeImageTaskId = '' +} + +export function isDerivedOutputName(name: string): boolean { + return DERIVED_OUTPUT_REGEX.test(String(name || '')) +} + +export function createImageImportTransport(hostOverride?: unknown): FileImportTransport { + return (method, params) => callHostTransport(method, params, hostOverride) +} + +export function toImageItem(file: ImportedFile): RealImageFileItem { + return { + id: `img:${file.path.toLowerCase()}`, + name: file.name, + path: file.path, + parentDir: file.parentDir, + extension: file.extension.toLowerCase(), + sizeBytes: file.sizeBytes + } +} + export function getQualityOptions(): Array<{ label: string; value: QualityTier }> { return [ { label: t('qualityMedium'), value: 'q85' }, @@ -116,11 +176,15 @@ export function getResizeOptions(): Array<{ label: string; value: ResizePreset } ] } -export function getFormatOptions(): Array<{ label: string; value: OutputFormat }> { +export function getFormatOptions(): Array<{ label: string; value: TargetFormatOption }> { return [ { label: t('formatKeep'), value: 'keep' }, - { label: 'JPG', value: 'jpg' }, - { label: 'PNG', value: 'png' } + { label: 'JPEG', value: 'jpeg' }, + { label: 'PNG', value: 'png' }, + { label: 'WebP', value: 'webp' }, + { label: 'AVIF', value: 'avif' }, + { label: 'ICO', value: 'ico' }, + { label: 'BMP', value: 'bmp' } ] } @@ -131,22 +195,20 @@ export function getImageWorkshopPresets(): ImageWorkshopPreset[] { title: t('presetLosslessTitle'), subtitle: t('presetLosslessSub'), tag: t('presetLosslessTag'), - method: 'BatchCompressImage', defaultFormat: 'keep', defaultQuality: 'q85', defaultResize: 'source', - grayscale: false + stripExif: true }, { id: 'preset-extreme-300k', title: t('presetGovTitle'), subtitle: t('presetGovSub'), tag: t('presetGovTag'), - method: 'BatchCompressImage', - defaultFormat: 'jpg', + defaultFormat: 'jpeg', defaultQuality: 'q70', defaultResize: 'max1280', - grayscale: false, + stripExif: true, sizeLimitBytes: IMAGE_SIZE_LIMIT_300KB }, { @@ -154,203 +216,104 @@ export function getImageWorkshopPresets(): ImageWorkshopPreset[] { title: t('presetJpgTitle'), subtitle: t('presetJpgSub'), tag: t('presetJpgTag'), - method: 'BatchConvertFormat', - defaultFormat: 'jpg', + defaultFormat: 'jpeg', + defaultQuality: 'q85', + defaultResize: 'source', + stripExif: true + }, + { + id: 'preset-to-webp', + title: t('presetWebpTitle'), + subtitle: t('presetWebpSub'), + tag: t('presetWebpTag'), + defaultFormat: 'webp', defaultQuality: 'q85', defaultResize: 'source', - grayscale: false + stripExif: true }, { id: 'preset-to-png', title: t('presetPngTitle'), subtitle: t('presetPngSub'), tag: t('presetPngTag'), - method: 'BatchConvertFormat', defaultFormat: 'png', defaultQuality: 'q95', defaultResize: 'source', - grayscale: false + stripExif: true }, { - id: 'preset-scale-1920', - title: t('preset1920Title'), - subtitle: t('preset1920Sub'), - tag: t('preset1920Tag'), - method: 'BatchResizeResolution', - defaultFormat: 'keep', - defaultQuality: 'q85', - defaultResize: 'max1920', - grayscale: false - }, - { - id: 'preset-doc-grayscale', - title: t('presetGrayTitle'), - subtitle: t('presetGraySub'), - tag: t('presetGrayTag'), - method: 'BatchGrayscaleDoc', - defaultFormat: 'keep', - defaultQuality: 'q85', + id: 'preset-to-ico', + title: t('presetIcoTitle'), + subtitle: t('presetIcoSub'), + tag: t('presetIcoTag'), + defaultFormat: 'ico', + defaultQuality: 'q95', defaultResize: 'source', - grayscale: true + stripExif: true } ] } -export function getCapabilityItems(): ImageWorkshopPreset[] { - return getImageWorkshopPresets().map((item) => ({ ...item })) +function qualityTierToNumber(tier: QualityTier): number { + if (tier === 'q70') return 70 + if (tier === 'q95') return 95 + return 85 } -export function filterCapabilityItems(items: ImageWorkshopPreset[], query: string): ImageWorkshopPreset[] { - if (!Array.isArray(items)) return [] - const q = typeof query === 'string' ? query.trim().toLowerCase() : '' - if (!q) return items - return items.filter((item) => { - if (!item || typeof item.title !== 'string') return false - return ( - item.title.toLowerCase().includes(q) || - item.subtitle.toLowerCase().includes(q) || - item.tag.toLowerCase().includes(q) || - item.method.toLowerCase().includes(q) - ) - }) +function resizePresetToWidth(preset: ResizePreset): number | undefined { + if (preset === 'max1920') return 1920 + if (preset === 'max1280') return 1280 + return undefined } -export function validateInvocationPayload( - method: string, - params: unknown -): { valid: boolean; error?: string } { - if (typeof method !== 'string' || method.trim().length === 0) { - return { valid: false, error: t('errInvalidMethodEmpty') } - } - if (method.length > 128 || !/^[A-Za-z0-9_]+$/.test(method.trim())) { - return { valid: false, error: t('errInvalidMethodFormat') } - } - if (params === null || params === undefined || typeof params !== 'object' || Array.isArray(params)) { - return { valid: false, error: t('errInvalidParamsObject') } - } - - const record = params as Record - for (const [key, val] of Object.entries(record)) { - if (typeof val === 'string') { - if (val.length > 4096) { - return { valid: false, error: t('errParamTooLong', { key }) } - } - if (FORBIDDEN_TARGET_PATTERN.test(val)) { - return { valid: false, error: t('errSecurityIntercepted', { reason: t('forbiddenReason') }) } - } - } else if (typeof val === 'number') { - if (!Number.isFinite(val) || val < 0 || val > 100_000_000) { - return { valid: false, error: t('errParamOutOfRange', { key }) } - } - } - } - - return { valid: true } -} - -export async function invokeNativeCapability( - method: string, - params: Record, - hostBridge?: unknown -): Promise { - const check = validateInvocationPayload(method, params) - if (!check.valid) { - throw new Error(resolveErrorMessage(check, t('errValidationFailed'))) - } - const res = await invokeDllPluginCapability(DLL_PLUGIN_NAME, method, params, hostBridge) - return { - ok: res.ok, - pluginName: DLL_PLUGIN_NAME, - method: method.trim(), - data: res.data ?? undefined, - error: res.error, - fromFallback: res.fromFallback - } -} - -export const IMAGE_EXT_REGEX = /\.(?:png|jpg|jpeg|webp|bmp|gif|tiff|avif)$/i -/** 可导入的图片扩展名(与 IMAGE_EXT_REGEX 一致) */ -export const IMAGE_IMPORT_EXTENSIONS = ['.png', '.jpg', '.jpeg', '.webp', '.bmp', '.gif', '.tiff', '.avif'] as const -/** 本插件生成的输出文件(*_opt、*_opt_2、*_opt_<时间>),导入文件夹时不再重复列入 */ -export const DERIVED_OUTPUT_REGEX = /_opt(?:_\d+){0,2}\.(?:png|jpg|jpeg|webp|bmp|gif|tiff|avif)$/i - -/** 是否为本插件生成的输出文件 */ -export function isDerivedOutputName(name: string): boolean { - return DERIVED_OUTPUT_REGEX.test(String(name || '')) -} - -/** 界面说明支持的图片格式 */ -export const IMAGE_IMPORT_SUPPORTED_TEXT = 'PNG / JPG / WebP / BMP / GIF / TIFF / AVIF' - -/** 图片导入规则:仅接受支持的图片格式,排除本插件输出文件及系统受保护路径 */ -export const IMAGE_IMPORT_RULES: FileImportRules = { - extensions: IMAGE_IMPORT_EXTENSIONS, - excludeFile: (name) => isDerivedOutputName(name), - forbiddenPath: FORBIDDEN_TARGET_PATTERN -} - -/** 将宿主调用适配为共享导入模块所需的 transport */ -export function createImageImportTransport(hostOverride?: unknown): FileImportTransport { - return (method, params) => callHostTransport(method, params, hostOverride) -} - -function splitPath(filePath: string): { dir: string; fileName: string; base: string; ext: string } { +function splitPath(filePath: string): { dirWithSep: string; fileName: string; base: string; ext: string } { const sepIdx = Math.max(filePath.lastIndexOf('\\'), filePath.lastIndexOf('/')) - const dir = sepIdx >= 0 ? filePath.slice(0, sepIdx) : '' + const dirWithSep = sepIdx >= 0 ? filePath.slice(0, sepIdx + 1) : '' const fileName = sepIdx >= 0 ? filePath.slice(sepIdx + 1) : filePath const dot = fileName.lastIndexOf('.') const base = dot > 0 ? fileName.slice(0, dot) : fileName const ext = dot > 0 ? fileName.slice(dot).toLowerCase() : '' - return { dir, fileName, base, ext } + return { dirWithSep, fileName, base, ext } } -/** 输出扩展名:保持原格式时取原图扩展名(小写),否则取目标格式;识别不到扩展名返回 null */ -export function resolveTargetExtension(sourcePath: string, format: OutputFormat): string | null { - if (format === 'jpg') return '.jpg' - if (format === 'png') return '.png' +export function resolveOutputFormat(sourcePath: string, option: TargetFormatOption): ImageOutputFormat | null { + if (option !== 'keep') return option const { ext } = splitPath(sourcePath) - return ext || null + if (ext === '.jpg' || ext === '.jpeg') return 'jpeg' + if (ext === '.png') return 'png' + if (ext === '.webp') return 'webp' + if (ext === '.avif') return 'avif' + if (ext === '.bmp') return 'bmp' + if (ext === '.ico') return 'ico' + return 'png' } -/** 在原图同目录生成 <原文件名><后缀><扩展名> */ -export function buildOutputCandidate(sourcePath: string, targetExt: string, suffix: string): string { - const sepIdx = Math.max(sourcePath.lastIndexOf('\\'), sourcePath.lastIndexOf('/')) - const dirWithSep = sepIdx >= 0 ? sourcePath.slice(0, sepIdx + 1) : '' - const { base } = splitPath(sourcePath) - return `${dirWithSep}${base}${suffix}${targetExt}` +export function formatToExtension(format: ImageOutputFormat): string { + return format === 'jpeg' ? '.jpg' : `.${format}` } -/** 批次时间标记(YYYYMMDDHHmmss),用于无法确认同名文件时生成不重复的输出文件名 */ export function makeBatchTag(now: Date = new Date()): string { const pad = (n: number) => String(n).padStart(2, '0') return `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}` } -/** 查询文件是否存在:true / false 为宿主明确答复,null 表示无法确认(未授权、接口不可用、返回格式异常) */ async function probeFileExists(filePath: string, hostOverride?: unknown): Promise { const res = await callHostTransport('filesystem_file_exists', { path: filePath }, hostOverride) if (!res.ok) return null - const data = res.data as unknown - if (typeof data === 'boolean') return data - if (data && typeof data === 'object' && typeof (data as { exists?: unknown }).exists === 'boolean') { - return (data as { exists: boolean }).exists - } - return null + if (typeof res.data === 'boolean') return res.data + const rec = asRecord(res.data) + return rec && typeof rec.exists === 'boolean' ? rec.exists : null } -/** - * 选择不会覆盖已有文件的输出路径: - * 1. 依次尝试 <名>_opt、<名>_opt_2 …,宿主明确答复不存在才使用; - * 2. 宿主无法确认是否存在时,改用带批次时间标记的文件名(<名>_opt_<时间>),不使用可能已存在的普通名称; - * 同一批次内已分配的路径与原图路径都不会重复使用。 - */ export async function chooseOutputPath( sourcePath: string, targetExt: string, reserved: Set, batchTag: string, + suffixBase = OUTPUT_SUFFIX, hostOverride?: unknown ): Promise { + const { dirWithSep, base } = splitPath(sourcePath) const key = (p: string) => p.toLowerCase() const sourceKey = key(sourcePath) const take = (candidate: string) => { @@ -358,306 +321,317 @@ export async function chooseOutputPath( return candidate } for (let n = 1; n <= MAX_NAME_ATTEMPTS; n++) { - const candidate = buildOutputCandidate(sourcePath, targetExt, n === 1 ? OUTPUT_SUFFIX : `${OUTPUT_SUFFIX}_${n}`) + const suffix = n === 1 ? suffixBase : `${suffixBase}_${n}` + const candidate = `${dirWithSep}${base}${suffix}${targetExt}` if (reserved.has(key(candidate)) || key(candidate) === sourceKey) continue const exists = await probeFileExists(candidate, hostOverride) if (exists === false) return take(candidate) if (exists === null) break } for (let n = 1; n <= 1000; n++) { - const suffix = n === 1 ? `${OUTPUT_SUFFIX}_${batchTag}` : `${OUTPUT_SUFFIX}_${batchTag}_${n}` - const candidate = buildOutputCandidate(sourcePath, targetExt, suffix) + const suffix = n === 1 ? `${suffixBase}_${batchTag}` : `${suffixBase}_${batchTag}_${n}` + const candidate = `${dirWithSep}${base}${suffix}${targetExt}` if (!reserved.has(key(candidate)) && key(candidate) !== sourceKey) return take(candidate) } throw new Error(t('errCannotGenUniqueName')) } -/** 把宿主单张图片的处理结果解析为界面结果;缺少输出信息时按失败处理,不当作成功 */ -export function parseHostImageResult( - data: unknown, - fallbackOriginalBytes: number | null, - sizeLimitBytes?: number -): ImageProcessOutcome { - const payload = (data && typeof data === 'object' ? data : {}) as Record - const errors = Array.isArray(payload.errors) ? (payload.errors as Array>) : [] - if (errors.length > 0) { - const first = errors[0] - return { status: 'failed', error: resolveErrorMessage(first, t('errHostFailed')) } +/** 按需准备图像与 PDF 合成薄原语引擎 */ +export async function ensureImageEngines( + hostOverride?: unknown +): Promise<{ ok: boolean; provisioned: string[]; error?: string }> { + const primitives = ['image.inspect', 'image.process', 'document.pdf.transform'] as const + const provisioned: string[] = [] + for (const primitiveId of primitives) { + const res = await ensureRuntimeCapability(primitiveId, hostOverride) + if (!res.ok) { + return { ok: false, provisioned, error: resolveErrorMessage(res, t('errEnsureFailed')) } + } + if (res.data?.status === 'unsupported') { + return { ok: false, provisioned, error: t('errUnsupportedEngine') } + } + if (res.data?.provisioned) provisioned.push(primitiveId) } - const results = Array.isArray(payload.results) ? (payload.results as Array>) : [] - const r = results[0] - if (!r || typeof r !== 'object') { - return { status: 'failed', error: t('errHostNoResult') } + return { ok: true, provisioned } +} + +/** 取消正在运行的图像处理或 PDF 合并任务 */ +export async function cancelActiveImageTask( + explicitTaskId?: string, + hostOverride?: unknown +): Promise<{ ok: boolean; taskId: string; cancelled: boolean; error?: string }> { + const targetTaskId = String(explicitTaskId || activeImageTaskId || '').trim() + if (!targetTaskId) { + return { ok: false, taskId: '', cancelled: false, error: t('errNoTaskToCancel') } } - const outputPath = typeof r.outputPath === 'string' ? r.outputPath.trim() : '' - const outputBytes = Number(r.outputBytes ?? r.sizeBytes) - if (!outputPath || !Number.isFinite(outputBytes) || outputBytes <= 0) { - return { status: 'failed', error: t('errHostMissingOutput') } + const res = await cancelRuntimeTask(targetTaskId, hostOverride) + if (!res.ok) { + return { ok: false, taskId: targetTaskId, cancelled: false, error: resolveErrorMessage(res, t('toastCancelFail')) } } - const rawOriginal = Number(r.originalBytes) - const originalBytes = Number.isFinite(rawOriginal) && rawOriginal > 0 ? rawOriginal : fallbackOriginalBytes - const width = Number(r.width) - const height = Number(r.height) - const limit = typeof sizeLimitBytes === 'number' && sizeLimitBytes > 0 ? sizeLimitBytes : null + if (targetTaskId === activeImageTaskId) activeImageTaskId = '' + return { ok: true, taskId: targetTaskId, cancelled: Boolean(res.data?.cancelled ?? true) } +} + +/** 单图深度检查(合并自 image-tool):调 tool_image_inspect 获取真实尺寸、色彩空间、格式与 EXIF/GPS 标签 */ +export async function inspectImageMetadata( + filePath: string, + hostOverride?: unknown +): Promise<{ ok: boolean; metadata?: ImageInspectMetadata; error?: string }> { + const cleanPath = String(filePath || '').trim() + if (!cleanPath || FORBIDDEN_TARGET_PATTERN.test(cleanPath)) { + return { ok: false, error: t('forbiddenReason') } + } + const res = await callHostTransport('tool_image_inspect', { inputs: [{ path: cleanPath }] }, hostOverride) + if (!res.ok) { + return { ok: false, error: friendlyFileError(resolveErrorMessage(res, t('errInspectFailed'))) } + } + const rec = asRecord(res.data) + const items = Array.isArray(rec?.items) ? rec.items : [] + const first = asRecord(items[0]) + if (!first) { + return { ok: false, error: t('errInspectFailed') } + } + const exifRecord: Record = {} + const rawExif = asRecord(first.exif) + if (rawExif) { + for (const [k, v] of Object.entries(rawExif)) { + if (typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean') { + exifRecord[k] = v + } + } + } + const width = Number(first.width ?? 0) + const height = Number(first.height ?? 0) + const sizeBytes = Number(first.sizeBytes ?? 0) return { - status: 'done', - outputPath, - originalBytes, - outputBytes, - width: Number.isFinite(width) && width > 0 ? width : 0, - height: Number.isFinite(height) && height > 0 ? height : 0, - notSmaller: originalBytes !== null && outputBytes >= originalBytes, - overLimitBytes: limit !== null && outputBytes > limit ? limit : null + ok: true, + metadata: { + filePath: cleanPath, + displayName: typeof first.displayName === 'string' && first.displayName ? first.displayName : splitPath(cleanPath).fileName, + format: typeof first.format === 'string' && first.format ? first.format.toUpperCase() : t('unknownValue'), + width: Number.isFinite(width) && width >= 0 ? Math.round(width) : 0, + height: Number.isFinite(height) && height >= 0 ? Math.round(height) : 0, + sizeBytes: Number.isFinite(sizeBytes) && sizeBytes >= 0 ? sizeBytes : 0, + colorSpace: typeof first.colorSpace === 'string' && first.colorSpace ? first.colorSpace : null, + hasAlpha: typeof first.hasAlpha === 'boolean' ? first.hasAlpha : null, + hasExif: Boolean(first.hasExif) || Object.keys(exifRecord).length > 0, + exif: exifRecord + } } } -/** 处理一张图片:先选好不覆盖已有文件的输出路径,再以该路径调用宿主 */ +/** 单张图像处理核心函数(调 tool_image_process,真实透传 stripExif、toBase64、format、quality、width 等) */ export async function processImageFile( file: Pick, settings: ImageProcessSettings, reserved: Set, batchTag: string, - hostOverride?: unknown + hostOverride?: unknown, + extra: { suffix?: string; width?: number; height?: number; toBase64?: boolean } = {} ): Promise { - const targetExt = resolveTargetExtension(file.path, settings.outputFormat) - if (!targetExt) { - return { status: 'failed', error: t('errUnknownExt') } + if (!file.path || FORBIDDEN_TARGET_PATTERN.test(file.path)) { + return { status: 'failed', error: t('forbiddenReason') } } + const format = resolveOutputFormat(file.path, settings.outputFormat) + if (!format) return { status: 'failed', error: t('errUnknownExt') } + try { - const outputPath = await chooseOutputPath(file.path, targetExt, reserved, batchTag, hostOverride) - const res = await invokeNativeCapability( - settings.method, - { - files: [file.path], + const targetExt = formatToExtension(format) + const outputPath = await chooseOutputPath(file.path, targetExt, reserved, batchTag, extra.suffix || OUTPUT_SUFFIX, hostOverride) + const taskId = nextMessageId('img_proc') + const maxWidth = extra.width ?? resizePresetToWidth(settings.resizePreset) + const params: Record = { + taskId, + input: { path: file.path }, + output: { path: outputPath }, + overwrite: false, + format, + quality: qualityTierToNumber(settings.qualityTier), + stripExif: Boolean(settings.stripExif) + } + if (typeof maxWidth === 'number' && maxWidth > 0) { + params.width = maxWidth + params.keepAspectRatio = true + } + if (typeof extra.height === 'number' && extra.height > 0) { + params.height = extra.height + params.keepAspectRatio = true + } + if (settings.rotate === 90 || settings.rotate === 180 || settings.rotate === 270) params.rotate = settings.rotate + if (settings.flip && settings.flip !== 'none') params.flip = settings.flip + if (extra.toBase64) params.toBase64 = true + + activeImageTaskId = taskId + try { + const res = await callHostTransport('tool_image_process', params, hostOverride) + if (!res.ok) { + return { status: 'failed', error: friendlyFileError(resolveErrorMessage(res, t('errHostFailed'))) } + } + const data = asRecord(res.data) + if (!data) return { status: 'failed', error: t('errHostFailed') } + const outputBytes = Number(data.outputBytes) + if (!Number.isFinite(outputBytes) || outputBytes <= 0) { + return { status: 'failed', error: t('errHostFailed') } + } + const width = Number(data.width ?? 0) + const height = Number(data.height ?? 0) + const limit = typeof settings.sizeLimitBytes === 'number' && settings.sizeLimitBytes > 0 ? settings.sizeLimitBytes : null + return { + status: 'done', outputPath, - outputFormat: settings.outputFormat, - qualityTier: settings.qualityTier, - resizePreset: settings.resizePreset, - grayscale: settings.grayscale - }, - hostOverride - ) - if (!res.ok) { - return { status: 'failed', error: friendlyFileError(resolveErrorMessage(res, t('errHostReturnFailed'))) } + originalBytes: file.sizeBytes, + outputBytes, + width: Number.isFinite(width) && width > 0 ? Math.round(width) : 0, + height: Number.isFinite(height) && height > 0 ? Math.round(height) : 0, + format: typeof data.format === 'string' && data.format ? data.format : format, + exifStripped: Boolean(data.exifStripped), + ...(typeof data.base64DataUrl === 'string' && data.base64DataUrl ? { base64DataUrl: data.base64DataUrl } : {}), + overLimitBytes: limit !== null && outputBytes > limit ? limit : null + } + } finally { + if (activeImageTaskId === taskId) activeImageTaskId = '' } - return parseHostImageResult(res.data, file.sizeBytes, settings.sizeLimitBytes) } catch (err) { return { status: 'failed', error: friendlyFileError(err) } } } -/** - * 逐张处理;每张完成后回调一次,单张失败不影响其余图片。 - * shouldSkip 返回 true 的图片(如处理中被移出列表)不再调用宿主,也不产生结果。 - */ +/** 单图一键抹除隐私 EXIF(真实传 stripExif: true) */ +export async function stripImageExif( + file: Pick, + hostOverride?: unknown +): Promise { + return processImageFile( + file, + { outputFormat: 'keep', qualityTier: 'q95', resizePreset: 'source', stripExif: true }, + new Set(), + makeBatchTag(), + hostOverride, + { suffix: '_noexif' } + ) +} + +/** 单图转 Base64 Data URL(调 tool_image_process 传 toBase64: true) */ +export async function convertImageToBase64( + file: Pick, + hostOverride?: unknown +): Promise<{ ok: boolean; dataUrl?: string; outputPath?: string; error?: string }> { + const outcome = await processImageFile( + file, + { outputFormat: 'keep', qualityTier: 'q95', resizePreset: 'source', stripExif: true }, + new Set(), + makeBatchTag(), + hostOverride, + { suffix: '_b64', toBase64: true } + ) + if (outcome.status === 'failed') return { ok: false, error: outcome.error } + if (!outcome.base64DataUrl) return { ok: false, error: t('errBase64Missing') } + return { ok: true, dataUrl: outcome.base64DataUrl, outputPath: outcome.outputPath } +} + +/** 单图生成 ICO / Favicon(256x256) */ +export async function generateImageIco( + file: Pick, + hostOverride?: unknown +): Promise { + return processImageFile( + file, + { outputFormat: 'ico', qualityTier: 'q95', resizePreset: 'source', stripExif: true }, + new Set(), + makeBatchTag(), + hostOverride, + { suffix: '_ico', width: 256, height: 256 } + ) +} + +/** 批量顺序处理多张图片 */ export async function processImageBatch( - files: Array>, + files: readonly RealImageFileItem[], settings: ImageProcessSettings, - options: { - hostOverride?: unknown - batchTag?: string - onItem?: (id: string, outcome: ImageProcessOutcome) => void - onStart?: (id: string) => void + callbacks: { shouldSkip?: (id: string) => boolean - } = {} + onStart?: (id: string) => void + onItem?: (id: string, outcome: ImageProcessOutcome) => void + } = {}, + hostOverride?: unknown ): Promise> { const reserved = new Set() - const batchTag = options.batchTag || makeBatchTag() + const batchTag = makeBatchTag() const outcomes = new Map() for (const file of files) { - if (options.shouldSkip?.(file.id)) continue - options.onStart?.(file.id) - const outcome = await processImageFile(file, settings, reserved, batchTag, options.hostOverride) + if (callbacks.shouldSkip?.(file.id)) continue + callbacks.onStart?.(file.id) + const outcome = await processImageFile(file, settings, reserved, batchTag, hostOverride) outcomes.set(file.id, outcome) - options.onItem?.(file.id, outcome) + callbacks.onItem?.(file.id, outcome) } return outcomes } -export interface ImageBatchSummary { - total: number - done: number - failed: number - notSmaller: number - overLimit: number - outputBytes: number - /** 已知原图大小的成功项的原图总大小(节省比例的分母) */ - comparableOriginalBytes: number - savedBytes: number - savePercent: number - firstError: string -} - -export function summarizeOutcomes(outcomes: Iterable): ImageBatchSummary { - const summary: ImageBatchSummary = { - total: 0, - done: 0, - failed: 0, - notSmaller: 0, - overLimit: 0, - outputBytes: 0, - comparableOriginalBytes: 0, - savedBytes: 0, - savePercent: 0, - firstError: '' +/** 多图真实嵌图合并为 PDF(调 tool_document_pdf_transform operation: 'images-to-pdf') */ +export async function mergeImagesToPdf( + files: readonly Pick[], + options: { outputPath?: string } = {}, + hostOverride?: unknown +): Promise { + const paths = files + .map((f) => String(f.path || '').trim()) + .filter((p) => p.length > 0 && !FORBIDDEN_TARGET_PATTERN.test(p)) + if (paths.length === 0) { + return { ok: false, taskId: '', outputPath: '', outputBytes: 0, pageCount: 0, error: t('errSelectAtLeastOne') } } - for (const o of outcomes) { - summary.total += 1 - if (o.status === 'failed') { - summary.failed += 1 - if (!summary.firstError) summary.firstError = o.error - continue - } - summary.done += 1 - summary.outputBytes += o.outputBytes - if (o.notSmaller) summary.notSmaller += 1 - if (o.overLimitBytes !== null) summary.overLimit += 1 - if (o.originalBytes !== null) { - summary.comparableOriginalBytes += o.originalBytes - summary.savedBytes += Math.max(0, o.originalBytes - o.outputBytes) - } + const first = splitPath(paths[0]!) + const outputPath = options.outputPath?.trim() || `${first.dirWithSep}${first.base}_merged_${makeBatchTag()}.pdf` + if (FORBIDDEN_TARGET_PATTERN.test(outputPath)) { + return { ok: false, taskId: '', outputPath, outputBytes: 0, pageCount: 0, error: t('forbiddenReason') } } - summary.savePercent = - summary.comparableOriginalBytes > 0 ? Math.round((summary.savedBytes / summary.comparableOriginalBytes) * 100) : 0 - return summary -} -/** - * 从剪贴板文本解析图片路径:每行一个,去掉两端引号;只接受绝对路径与支持的图片扩展名 - */ -export function parseClipboardImagePaths(text: string, limit = 200): string[] { - if (typeof text !== 'string' || !text.trim()) return [] - const out: string[] = [] - const seen = new Set() - for (const line of text.split(/\r?\n/)) { - const cleaned = line.trim().replace(/^["']+|["']+$/g, '').trim() - if (!cleaned) continue - const isAbsolute = /^[A-Za-z]:[\\/]/.test(cleaned) || cleaned.startsWith('\\\\') || cleaned.startsWith('/') - if (!isAbsolute || !IMAGE_EXT_REGEX.test(cleaned)) continue - const key = cleaned.toLowerCase() - if (seen.has(key)) continue - seen.add(key) - out.push(cleaned) - if (out.length >= limit) break - } - return out -} - -/** 读取文件大小;宿主未授权或接口不可用时返回 null(界面显示「大小未识别」),不填默认值 */ -export async function readImageFileSize(filePath: string, hostOverride?: unknown): Promise { - const res = await callHostTransport('filesystem_get_file_size', { path: filePath }, hostOverride) - if (!res.ok) return null - const data = res.data as unknown - const size = - typeof data === 'number' - ? data - : data && typeof data === 'object' - ? Number((data as { size?: unknown }).size) - : NaN - return Number.isFinite(size) && size >= 0 ? size : null -} - -/** 从文件选择框或路径列表中提取合法的图片绝对路径 */ -export function extractSelectedImagePaths(raw: unknown, limit = 200): string[] { - if (!raw || typeof raw !== 'object') return [] - const record = raw as Record - if (record.canceled === true) return [] - const lines: string[] = [] - if (typeof record.filePath === 'string') { - lines.push(record.filePath) - } - if (Array.isArray(record.filePaths)) { - for (const item of record.filePaths) { - if (typeof item === 'string') { - lines.push(item) - } else if (item && typeof item === 'object' && typeof (item as { path?: unknown }).path === 'string') { - lines.push((item as { path: string }).path) + const taskId = nextMessageId('img_pdf') + activeImageTaskId = taskId + try { + const res = await callHostTransport( + 'tool_document_pdf_transform', + { + taskId, + operation: 'images-to-pdf', + inputs: paths.map((p) => ({ path: p })), + output: { path: outputPath }, + overwrite: false + }, + hostOverride + ) + if (!res.ok) { + return { + ok: false, + taskId, + outputPath, + outputBytes: 0, + pageCount: 0, + error: friendlyFileError(resolveErrorMessage(res, t('errMergePdfFailed'))) } } - } - return parseClipboardImagePaths(lines.join('\n'), limit) -} - -/** 从宿主 plugin_files_dropped 事件载荷中提取合法的图片绝对路径 */ -export function extractDroppedImagePaths(envelopeOrPayload: unknown, limit = 200): string[] { - if (!envelopeOrPayload || typeof envelopeOrPayload !== 'object') return [] - const obj = envelopeOrPayload as Record - const innerPayload = - obj.payload && typeof obj.payload === 'object' ? (obj.payload as Record) : obj - const rawFiles = Array.isArray(innerPayload.files) - ? innerPayload.files - : Array.isArray(obj.files) - ? obj.files - : [] - return extractSelectedImagePaths({ canceled: false, filePaths: rawFiles }, limit) -} - -/** 从系统剪贴板读取直接复制的图片文件列表(clipboard_read_files) */ -export async function readClipboardImageFilePaths(hostOverride?: unknown): Promise { - const res = await callHostTransport('clipboard_read_files', {}, hostOverride) - if (!res.ok || !res.data) return [] - const data = res.data as Record | unknown[] - const list = Array.isArray(data) - ? data - : Array.isArray((data as { files?: unknown }).files) - ? ((data as { files: unknown[] }).files) - : [] - return extractSelectedImagePaths({ canceled: false, filePaths: list }) -} - -let imageItemSeq = 0 - -/** 由路径构造队列项;大小由调用方传入(读不到时为 null) */ -export function makeImageItem(id: string, filePath: string, sizeBytes: number | null, parentDirOverride?: string): RealImageFileItem { - const { dir, fileName, ext } = splitPath(filePath) - return { - id, - name: fileName, - path: filePath, - parentDir: parentDirOverride ?? dir, - extension: ext, - sizeBytes + const data = asRecord(res.data) + const outputBytes = Number(data?.outputBytes ?? 0) + const pageCount = Number(data?.pageCount ?? paths.length) + return { + ok: true, + taskId: typeof data?.taskId === 'string' && data.taskId ? data.taskId : taskId, + outputPath, + outputBytes: Number.isFinite(outputBytes) && outputBytes >= 0 ? outputBytes : 0, + pageCount: Number.isFinite(pageCount) && pageCount >= 0 ? pageCount : paths.length + } + } finally { + if (activeImageTaskId === taskId) activeImageTaskId = '' } } -/** 把共享导入模块返回的文件转为图片队列项,使用单调递增编号防止移除后重加发生 id 冲突 */ -export function toImageItem(file: ImportedFile): RealImageFileItem { - imageItemSeq += 1 - return makeImageItem(`img-${imageItemSeq}-${file.path}`, file.path, file.sizeBytes, file.parentDir) -} - -export async function openImageFileLocation(filePath: string, hostOverride?: unknown): Promise { - return showRealItemInFolder(filePath, hostOverride) +export async function openImageFileLocation(targetPath: string, hostOverride?: unknown): Promise { + return showRealItemInFolder(targetPath, hostOverride) } -export async function trashImageFileItem( - filePath: string, - hostOverride?: unknown -): Promise<{ ok: boolean; error?: string }> { - if (!filePath || FORBIDDEN_TARGET_PATTERN.test(filePath)) { +export async function trashImageFileItem(targetPath: string, hostOverride?: unknown): Promise<{ ok: boolean; error?: string }> { + if (!targetPath || FORBIDDEN_TARGET_PATTERN.test(targetPath)) { return { ok: false, error: t('forbiddenReason') } } - return trashRealItem(filePath, hostOverride) -} - -/** 结果状态的短标签(列表行右侧) */ -export function describeOutcomeTag(result: ImageProcessOutcome | undefined): string { - if (!result) return t('tagPending') - if (result.status === 'failed') return t('tagFailed') - if (result.overLimitBytes !== null) return t('tagOverLimit', { size: formatBytes(result.overLimitBytes) }) - if (result.notSmaller) return t('tagNotSmaller', { size: formatBytes(result.outputBytes) }) - const pct = - result.originalBytes !== null && result.originalBytes > 0 - ? ` (-${Math.round(((result.originalBytes - result.outputBytes) / result.originalBytes) * 100)}%)` - : '' - return t('tagOutput', { size: formatBytes(result.outputBytes), pct }) -} - -/** 结果说明(列表行副标题) */ -export function describeOutcomeDetail(result: ImageProcessOutcome | undefined, parentDir: string): string { - if (!result) return parentDir - if (result.status === 'failed') return t('detailFailed', { error: result.error }) - const outName = splitPath(result.outputPath).fileName - const dims = result.width > 0 && result.height > 0 ? `${result.width}×${result.height}` : t('dimsUnknown') - return t('detailOutput', { name: outName, dims }) + return trashRealItem(targetPath, hostOverride) } diff --git a/extensions/batch-image/src/native-ipc.ts b/extensions/batch-image/src/native-ipc.ts deleted file mode 100644 index 51576b99..00000000 --- a/extensions/batch-image/src/native-ipc.ts +++ /dev/null @@ -1,1852 +0,0 @@ -import { getLocale } from '@ztools/declarative-ui' - -type DynamicBridge = ReturnType - -const NATIVE_IPC_MESSAGES: Record string - dirEntrySep: string - dirErrorColon: string - deepScanUnavailable: string - pathEmpty: string - invalidMethodEmpty: string - invalidMethodFormat: string - invalidParamsObject: string - paramTooLong: (key: string) => string - paramOutOfRange: (key: string) => string - methodParamEmpty: string - invalidMethodType: string - malformedDllResponse: string - unknownDllError: string - hostIpcFailed: (pluginName: string, method: string) => string - hostUnavailable: (pluginName: string, method: string) => string - callFailed: string - movedToTrash: string - deleteFailed: string - revealedInFolder: string - revealFailed: string - opened: string - openFailed: string - pluginCallNotReady: string -}> = { - 'zh-CN': { - ipcCallFailed: 'IPC 调用返回失败', - ipcInnerFailed: 'IPC 内部调用失败', - scanIncomplete: '扫描结果不完整', - dirReadFailed: (details, moreCount) => - `目录读取失败或不完整:${details}${moreCount > 0 ? `;另有 ${moreCount} 个目录` : ''}`, - dirEntrySep: ';', - dirErrorColon: ':', - deepScanUnavailable: '深度扫描不可用,仅列出一级目录,结果不完整', - pathEmpty: '路径不能为空', - invalidMethodEmpty: 'INVALID_METHOD: 调用方法名不能为空', - invalidMethodFormat: 'INVALID_METHOD_FORMAT: 方法名包含非法字符或超长', - invalidParamsObject: 'INVALID_PARAMS: 参数必须为非空对象', - paramTooLong: (key) => `PARAM_TOO_LONG: 参数 ${key} 超过最大长度限制`, - paramOutOfRange: (key) => `PARAM_OUT_OF_RANGE: 数值参数 ${key} 越界或非有限数`, - methodParamEmpty: 'method 参数不能为空', - invalidMethodType: 'INVALID_METHOD: method 不能为空且必须为字符串', - malformedDllResponse: 'MALFORMED_DLL_RESPONSE: 原生组件返回了损坏的 JSON 数据', - unknownDllError: '原生组件返回未知错误', - hostIpcFailed: (pluginName, method) => `HOST_IPC_FAILED: ${pluginName}.${method} 调用失败`, - hostUnavailable: (pluginName, method) => `HOST_UNAVAILABLE: ${pluginName}.${method} 宿主接口未就绪`, - callFailed: '调用失败', - movedToTrash: '已移入回收站', - deleteFailed: '删除失败', - revealedInFolder: '已定位文件', - revealFailed: '定位失败', - opened: '已打开', - openFailed: '打开失败', - pluginCallNotReady: '插件调用未就绪' - }, - 'en-US': { - ipcCallFailed: 'IPC call failed', - ipcInnerFailed: 'Internal IPC call failed', - scanIncomplete: 'Incomplete scan results', - dirReadFailed: (details, moreCount) => - `Directory read failed or incomplete: ${details}${moreCount > 0 ? `; and ${moreCount} more` : ''}`, - dirEntrySep: '; ', - dirErrorColon: ': ', - deepScanUnavailable: 'Deep scan unavailable; only top-level directory listed (incomplete)', - pathEmpty: 'Path cannot be empty', - invalidMethodEmpty: 'INVALID_METHOD: Method name cannot be empty', - invalidMethodFormat: 'INVALID_METHOD_FORMAT: Method name contains invalid characters or is too long', - invalidParamsObject: 'INVALID_PARAMS: Parameters must be a non-null object', - paramTooLong: (key) => `PARAM_TOO_LONG: Parameter "${key}" exceeds maximum length`, - paramOutOfRange: (key) => `PARAM_OUT_OF_RANGE: Numeric parameter "${key}" is out of range or non-finite`, - methodParamEmpty: 'Method parameter cannot be empty', - invalidMethodType: 'INVALID_METHOD: Method must be a non-empty string', - malformedDllResponse: 'MALFORMED_DLL_RESPONSE: Native component returned malformed JSON', - unknownDllError: 'Native component returned an unknown error', - hostIpcFailed: (pluginName, method) => `HOST_IPC_FAILED: ${pluginName}.${method} call failed`, - hostUnavailable: (pluginName, method) => `HOST_UNAVAILABLE: ${pluginName}.${method} host interface not ready`, - callFailed: 'Call failed', - movedToTrash: 'Moved to Trash', - deleteFailed: 'Delete failed', - revealedInFolder: 'Revealed in folder', - revealFailed: 'Failed to reveal item', - opened: 'Opened', - openFailed: 'Failed to open', - pluginCallNotReady: 'Plugin invocation not ready' - } -} - -function ipcStrings() { - const locale = getLocale() - return NATIVE_IPC_MESSAGES[locale] ?? NATIVE_IPC_MESSAGES['en-US'] -} -/** - * ZTools 真实宿主 IPC 与系统能力桥接层 (Real Host IPC Bridge) - * - * 严格遵循《ZTools Declarative UI 2.0 架构与 35 款原生插件全量升级规范》5.1 真实环境铁律: - * - 在真实 Electron 宿主环境中,100% 走通 Preload (__ztoolsElectron.transport.methods / window.ztools / __ztoolsLauncher) 真实调用链路 - * - 严禁在真实环境中因参数格式或嵌套响应结构差异而回退到假数据 - */ - -let ipcReqSeq = 1 -const realFileSizeCache = new Map() - -export function nextMessageId(prefix = 'ipc'): string { - ipcReqSeq = (ipcReqSeq + 1) % 1_000_000 - return `${prefix}_${Date.now()}_${ipcReqSeq}` -} - -/** - * 判断当前是否处于真实的 ZTools Electron 渲染进程宿主环境 - */ -export function isRealElectronHost(hostOverride?: unknown): boolean { - if (hostOverride) return false - if (typeof window === 'undefined') return false - const w = window as DynamicBridge - return Boolean( - w.__ztoolsElectron?.transport?.methods || - w.ztools?.transport?.call || - w.ztools?.transport?.methods - ) -} - -function normalizeMethodParams(method: string, params: Record): Record { - if (!params || typeof params !== 'object') return {} - const next = { ...params } - if (method === 'system_get_disk_usage') { - const rawDrive = String(next.drive || next.path || 'C:\\').trim() - if (rawDrive.startsWith('/')) { - next.drive = rawDrive - } else { - const match = rawDrive.match(/^([A-Za-z]):/) - next.drive = match ? `${match[1].toUpperCase()}:\\` : rawDrive.replace(/\//g, '\\') - } - delete next.path - } - return next -} - -function normalizeMethodResult(method: string, payload: DynamicBridge): DynamicBridge { - if (!payload || typeof payload !== 'object') return payload - - if (method === 'system_get_disk_usage') { - const avail = typeof payload.available === 'number' - ? payload.available - : typeof payload.free === 'number' - ? payload.free - : Math.max(0, Number(payload.total || 0) - Number(payload.used || 0)) - return { - ...payload, - available: avail, - free: avail - } - } - - if (method === 'system_get_hardware_summary') { - const cpuModel = - typeof payload.cpuModel === 'string' && payload.cpuModel.trim() - ? payload.cpuModel.trim() - : Array.isArray(payload.cpuModels) && payload.cpuModels.length > 0 - ? String(payload.cpuModels[0]).trim() - : 'x86_64 Processor' - return { - ...payload, - cpuModel - } - } - - if (method === 'system_get_battery_status') { - // 宿主约定 percent 超出 0-100(如 255)表示无电池或电量未知,不能改写成 100% - const rawPct = payload.percent - const hasBattery = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 - return { - ...payload, - percent: hasBattery ? rawPct : null, - hasBattery - } - } - - if (method === 'screen_get_all_displays') { - const list = Array.isArray(payload) - ? payload - : Array.isArray(payload.displays) - ? payload.displays - : [] - return list.map((d: DynamicBridge) => ({ - ...d, - label: d?.label || d?.name || `Display #${d?.id ?? 1}` - })) - } - - return payload -} - -function extractIpcErrorMeta(errObj: DynamicBridge): { - errorCode?: string - errorDetails?: Record -} { - if (!errObj || typeof errObj !== 'object') return {} - const errorCode = - typeof errObj.errorCode === 'string' && errObj.errorCode.trim() - ? errObj.errorCode.trim() - : typeof errObj.code === 'string' && errObj.code.trim() - ? errObj.code.trim() - : undefined - const rawDetails = - errObj.errorDetails && typeof errObj.errorDetails === 'object' && !Array.isArray(errObj.errorDetails) - ? (errObj.errorDetails as Record) - : errObj.details && typeof errObj.details === 'object' && !Array.isArray(errObj.details) - ? (errObj.details as Record) - : undefined - return { - ...(errorCode ? { errorCode } : {}), - ...(rawDetails ? { errorDetails: rawDetails } : {}) - } -} - -function unwrapTransportResponse( - method: string, - raw: DynamicBridge -): { ok: boolean; data?: DynamicBridge; error?: string; errorCode?: string; errorDetails?: Record } { - if (raw === null || raw === undefined) { - return { ok: false, error: 'EMPTY_IPC_RESPONSE', errorCode: 'EMPTY_IPC_RESPONSE' } - } - if (typeof raw !== 'object') { - return { ok: true, data: raw } - } - if (raw.success === false) { - const errObj = raw.error - const errMsg = - typeof errObj === 'object' && errObj !== null - ? String(errObj.message || errObj.code || JSON.stringify(errObj)) - : String(errObj || ipcStrings().ipcCallFailed) - return { ok: false, error: errMsg, ...extractIpcErrorMeta(raw), ...extractIpcErrorMeta(errObj) } - } - - const firstLayer = 'data' in raw && raw.data !== undefined ? raw.data : raw - if (firstLayer && typeof firstLayer === 'object' && !Array.isArray(firstLayer)) { - if (firstLayer.success === false) { - const errObj = firstLayer.error - const errMsg = - typeof errObj === 'object' && errObj !== null - ? String(errObj.message || errObj.code || JSON.stringify(errObj)) - : String(errObj || ipcStrings().ipcInnerFailed) - return { ok: false, error: errMsg, ...extractIpcErrorMeta(firstLayer), ...extractIpcErrorMeta(errObj) } - } - if ('data' in firstLayer && firstLayer.data !== undefined) { - return { ok: true, data: normalizeMethodResult(method, firstLayer.data) } - } - } - - return { ok: true, data: normalizeMethodResult(method, firstLayer) } -} - -/** - * 调用 Electron Preload Transport 方法(自动封装合法的 alphanumeric messageId 与双层解包) - */ -export async function callHostTransport( - method: string, - params: Record = {}, - hostOverride?: DynamicBridge -): Promise<{ ok: boolean; data?: T; error?: string; errorCode?: string; errorDetails?: Record }> { - const normalizedParams = normalizeMethodParams(method, params) - - // 1. 测试注入的 hostOverride 优先 - if (hostOverride) { - if (typeof hostOverride[method] === 'function') { - try { - const res = await hostOverride[method](normalizedParams) - const unwrapped = unwrapTransportResponse(method, res) - return unwrapped as { ok: boolean; data?: T; error?: string; errorCode?: string; errorDetails?: Record } - } catch (err: DynamicBridge) { - return { ok: false, error: err instanceof Error ? err.message : String(err), ...extractIpcErrorMeta(err) } - } - } - if (typeof hostOverride?.transport?.call === 'function') { - try { - const res = await hostOverride.transport.call(method, normalizedParams) - const unwrapped = unwrapTransportResponse(method, res) - return unwrapped as { ok: boolean; data?: T; error?: string; errorCode?: string; errorDetails?: Record } - } catch (err: DynamicBridge) { - return { ok: false, error: err instanceof Error ? err.message : String(err), ...extractIpcErrorMeta(err) } - } - } - } - - if (typeof window === 'undefined') { - return { ok: false, error: 'NO_WINDOW_ENV', errorCode: 'NO_WINDOW_ENV' } - } - - const w = window as DynamicBridge - const methods = w.__ztoolsElectron?.transport?.methods || w.ztools?.transport?.methods - const fn = methods?.[method] - - if (typeof fn === 'function') { - try { - const messageId = nextMessageId(method.replace(/[^A-Za-z0-9_]/g, '_').slice(0, 24)) - const raw = await fn({ messageId, params: normalizedParams }) - return unwrapTransportResponse(method, raw) as { ok: boolean; data?: T; error?: string; errorCode?: string; errorDetails?: Record } - } catch (err: DynamicBridge) { - return { ok: false, error: err instanceof Error ? err.message : String(err), ...extractIpcErrorMeta(err) } - } - } - - if (typeof w.ztools?.transport?.call === 'function') { - try { - const raw = await w.ztools.transport.call(method, normalizedParams) - return unwrapTransportResponse(method, raw) as { ok: boolean; data?: T; error?: string; errorCode?: string; errorDetails?: Record } - } catch (err: DynamicBridge) { - return { ok: false, error: err instanceof Error ? err.message : String(err), ...extractIpcErrorMeta(err) } - } - } - - return { ok: false, error: `METHOD_NOT_AVAILABLE: ${method}`, errorCode: 'METHOD_NOT_AVAILABLE' } -} - -export interface RealDiskDriveInfo { - drive: string - totalBytes: number - usedBytes: number - availableBytes: number - usagePercent: number -} - -/** - * 探测本机全部真实挂载磁盘分区 (C:\ ~ Z:\ 或 macOS/POSIX 挂载点 '/') - */ -export async function probeRealDiskDrives( - candidateLetters: string[] = ['C', 'D', 'E', 'F', 'G'], - hostOverride?: DynamicBridge -): Promise { - const drives: RealDiskDriveInfo[] = [] - const results = await Promise.all( - candidateLetters.map(async (letter) => { - const raw = String(letter || '').trim() - const isPosix = raw.startsWith('/') - const drivePath = isPosix ? raw : `${raw.replace(/:\\?$/, '').toUpperCase()}:\\` - const res = await callHostTransport<{ - total: number - used: number - available: number - free?: number - percent: number - }>('system_get_disk_usage', { drive: drivePath }, hostOverride) - if (res.ok && res.data && typeof res.data.total === 'number' && res.data.total > 0) { - const availableBytes = - typeof res.data.available === 'number' - ? res.data.available - : typeof res.data.free === 'number' - ? res.data.free - : Math.max(0, res.data.total - res.data.used) - return { - drive: isPosix ? raw : `${raw.replace(/:\\?$/, '').toUpperCase()}:`, - totalBytes: res.data.total, - usedBytes: res.data.used, - availableBytes, - usagePercent: res.data.percent - } - } - return null - }) - ) - - for (const item of results) { - if (item) drives.push(item) - } - - if (drives.length === 0 && !candidateLetters.includes('/')) { - const posixRes = await callHostTransport<{ - total: number - used: number - available: number - free?: number - percent: number - }>('system_get_disk_usage', { drive: '/' }, hostOverride) - if (posixRes.ok && posixRes.data && typeof posixRes.data.total === 'number' && posixRes.data.total > 0) { - const availableBytes = - typeof posixRes.data.available === 'number' - ? posixRes.data.available - : typeof posixRes.data.free === 'number' - ? posixRes.data.free - : Math.max(0, posixRes.data.total - posixRes.data.used) - drives.push({ - drive: '/', - totalBytes: posixRes.data.total, - usedBytes: posixRes.data.used, - availableBytes, - usagePercent: posixRes.data.percent - }) - } - } - - return drives -} - -/** - * 获取本机真实系统特殊路径(支持 home 派生标准子目录兜底,自动兼容 Windows 与 macOS/POSIX) - */ -export async function getRealSystemPath( - name: 'home' | 'appData' | 'userData' | 'desktop' | 'documents' | 'downloads' | 'music' | 'pictures' | 'videos' | 'temp' | 'cache', - hostOverride?: DynamicBridge -): Promise { - const res = await callHostTransport('system_get_path', { name }, hostOverride) - if (res.ok && res.data) { - if (typeof res.data === 'string' && res.data.trim().length > 0) { - return res.data.trim() - } - if (typeof res.data.path === 'string' && res.data.path.trim().length > 0) { - return res.data.path.trim() - } - } - - if (name !== 'home') { - const home = await getRealSystemPath('home', hostOverride) - if (home) { - const isPosix = home.startsWith('/') - const subMap: Record = isPosix - ? { - desktop: `${home}/Desktop`, - documents: `${home}/Documents`, - downloads: `${home}/Downloads`, - music: `${home}/Music`, - pictures: `${home}/Pictures`, - videos: `${home}/Videos`, - appData: `${home}/Library/Application Support`, - userData: `${home}/Library/Application Support/ZTools`, - temp: '/tmp', - cache: `${home}/Library/Caches` - } - : { - desktop: `${home}\\Desktop`, - documents: `${home}\\Documents`, - downloads: `${home}\\Downloads`, - music: `${home}\\Music`, - pictures: `${home}\\Pictures`, - videos: `${home}\\Videos`, - appData: `${home}\\AppData\\Roaming`, - userData: `${home}\\AppData\\Roaming\\ZTools`, - temp: `${home}\\AppData\\Local\\Temp`, - cache: `${home}\\AppData\\Local` - } - if (subMap[name]) return subMap[name] - } - } - - return '' -} - -export type RealDriveUsageInfo = RealDiskDriveInfo - -export interface RealIndexedFileEntry { - name: string - path: string - ext: string - isDir: boolean - isDirectory: boolean - size: number - sizeBytes: number - mtime: number - mtimeMs: number - lastModifiedMs: number -} - -export interface RealDirectorySubdirSummary { - name: string - path: string - fileCount: number - totalBytes: number - mtime: number - /** 体积不是完整统计(宿主扫描截断且独立统计超时 / 无权限),totalBytes 只是下限 */ - approximate?: boolean -} - -export interface RealDirectoryScanResult extends Iterable { - files: RealIndexedFileEntry[] - totalFiles: number - fileCount: number - totalBytes: number - subdirs: RealDirectorySubdirSummary[] - /** 宿主扫描达到条目上限后停止:files / totalFiles 只是已遍历部分的抽样 */ - truncated?: boolean - /** totalBytes 为近似值(下限) */ - approximate?: boolean - /** 宿主实际遍历的条目数 */ - visitedEntries?: number - /** 读取失败的真实原因;已有文件仍可使用,但不能当作完整结果。 */ - error?: string -} - -interface ScanResultMeta { - truncated?: boolean - approximate?: boolean - visitedEntries?: number -} - -export interface ScanDirectoryTreeOptions { - maxDepth?: number - maxFiles?: number - collectTopN?: number - filterExt?: RegExp - hostOverride?: DynamicBridge -} - -function extractFileExt(fileNameOrPath: string): string { - const base = String(fileNameOrPath || '').split(/[\\/]/).pop() || '' - const dotIdx = base.lastIndexOf('.') - return dotIdx > 0 ? base.slice(dotIdx).toLowerCase() : '' -} - -function normalizeIndexedFileEntry(f: DynamicBridge): RealIndexedFileEntry { - const p = String(f?.path || '') - const name = String(f?.name || p.split(/[\\/]/).pop() || '') - const sz = Number(f?.size ?? f?.sizeBytes ?? 0) - const isDir = Boolean(f?.is_dir || f?.isDir || f?.isDirectory) - const rawMtime = Number(f?.mtime ?? f?.mtimeMs ?? 0) - const mtimeMs = rawMtime > 1e11 ? rawMtime : rawMtime > 0 ? rawMtime * 1000 : Date.now() - const mtimeSec = rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime - if (p && sz >= 0) realFileSizeCache.set(p, sz) - return { - name, - path: p, - ext: extractFileExt(name || p), - isDir, - isDirectory: isDir, - size: sz, - sizeBytes: sz, - mtime: mtimeSec, - mtimeMs, - lastModifiedMs: mtimeMs - } -} - -function makeScanResult( - files: RealIndexedFileEntry[], - totalFiles: number, - totalBytes: number, - subdirs: RealDirectorySubdirSummary[], - meta: ScanResultMeta = {} -): RealDirectoryScanResult { - return { - files, - totalFiles, - fileCount: totalFiles, - totalBytes, - subdirs, - ...(meta.truncated ? { truncated: true } : {}), - ...(meta.approximate ? { approximate: true } : {}), - ...(typeof meta.visitedEntries === 'number' ? { visitedEntries: meta.visitedEntries } : {}), - [Symbol.iterator]() { - return files[Symbol.iterator]() - } - } -} - -/** - * 调用客户端的原生文件索引组件 (ztools-indexer) 检索文件 - */ -export async function searchRealIndexedFiles( - query: string, - limit = 40, - hostOverride?: DynamicBridge -): Promise { - if (!query || !query.trim()) return [] - const q = query.trim() - const safeLimit = Math.min(200, Math.max(1, Math.floor(limit || 40))) - - try { - const res = await callHostTransport<{ files?: DynamicBridge[] }>( - 'system_search_files', - { query: q, limit: safeLimit }, - hostOverride - ) - if (res.ok && res.data && Array.isArray(res.data.files)) { - return res.data.files.map(normalizeIndexedFileEntry) - } - - if (!hostOverride && typeof window !== 'undefined') { - const w = window as DynamicBridge - if (typeof w.__ztoolsLauncher?.searchFiles === 'function') { - const rawOuter = await w.__ztoolsLauncher.searchFiles(q, safeLimit) - const raw = rawOuter && typeof rawOuter === 'object' && 'data' in rawOuter && rawOuter.data ? rawOuter.data : rawOuter - if (raw && Array.isArray(raw.files)) { - return raw.files.map(normalizeIndexedFileEntry) - } - } - } - } catch { - // ignore - } - return [] -} - -/** - * 深度扫描指定真实物理目录树(支持符号链接穿透,如 AppData\Roaming\Tencent -> D:\Local\Roaming\Tencent) - * 返回该目录下 Top 文件列表、全树真实文件总数、全树真实总字节数与一级子目录汇总 - */ -export async function scanRealDirectoryTree( - dirPath: string, - limitOrOptions: number | ScanDirectoryTreeOptions = 160, - hostOverrideArg?: DynamicBridge -): Promise { - const result = await scanDirectoryTreeWithError(dirPath, limitOrOptions, hostOverrideArg) - return result.error ? { ...result.scan, error: result.error } : result.scan -} - -/** 一次界面扫描的错误汇总;多个目录并行扫描时保留可读目录的结果。 */ -export function createDirectoryScanner(hostOverride?: DynamicBridge) { - const failures = new Map() - return { - async scan(dir: string, options: number | ScanDirectoryTreeOptions = 160) { - const result = await scanRealDirectoryTree(dir, options, hostOverride) - const error = result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') - if (error) failures.set(dir, error) - else failures.delete(dir) - return result - }, - get error(): string | undefined { - if (!failures.size) return undefined - const s = ipcStrings() - const details = [...failures].slice(0, 3).map(([dir, error]) => `${dir}${s.dirErrorColon}${error}`).join(s.dirEntrySep) - return s.dirReadFailed(details, Math.max(0, failures.size - 3)) - } - } -} - -/** scanRealDirectoryTree 的实现:额外带回读取失败原因(目录不存在 / 为空 / 无权限 / 载荷异常) */ -async function scanDirectoryTreeWithError( - dirPath: string, - limitOrOptions: number | ScanDirectoryTreeOptions, - hostOverrideArg?: DynamicBridge -): Promise<{ scan: RealDirectoryScanResult; error?: string }> { - const empty = makeScanResult([], 0, 0, []) - if (!dirPath || !dirPath.trim()) return { scan: empty, error: 'EMPTY_DIRECTORY_PATH' } - const targetDir = dirPath.trim() - - const opts: ScanDirectoryTreeOptions = - typeof limitOrOptions === 'number' - ? { maxFiles: limitOrOptions, hostOverride: hostOverrideArg } - : { ...limitOrOptions, hostOverride: limitOrOptions?.hostOverride ?? hostOverrideArg } - - const rawLimit = opts.maxFiles ?? opts.collectTopN ?? 160 - const safeLimit = Math.min(200, Math.max(1, Math.floor(rawLimit || 160))) - const hostOverride = opts.hostOverride - const filterExt = opts.filterExt - const dirQuery = `dir:${targetDir}` - - try { - let rawPayload: DynamicBridge = null - const res = await callHostTransport( - 'system_search_files', - { query: dirQuery, limit: safeLimit }, - hostOverride - ) - if (res.ok && res.data) { - rawPayload = res.data - } - if (!rawPayload && !hostOverride && typeof window !== 'undefined') { - const w = window as DynamicBridge - if (typeof w.__ztoolsLauncher?.searchFiles === 'function') { - const rawOuter = await w.__ztoolsLauncher.searchFiles(dirQuery, safeLimit) - rawPayload = - rawOuter && typeof rawOuter === 'object' && 'data' in rawOuter && rawOuter.data - ? rawOuter.data - : rawOuter - } - } - - if ( - rawPayload && - Array.isArray(rawPayload.files) - ) { - let files: RealIndexedFileEntry[] = rawPayload.files.map(normalizeIndexedFileEntry) - if (filterExt instanceof RegExp) { - files = files.filter(f => !f.isDir && (filterExt.test(f.name) || filterExt.test(f.ext))) - // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索目标扩展名 - if (files.length === 0 && !hostOverride) { - const extTokens = (filterExt.source.match(/[a-z0-9]{2,5}/gi) || []) - .filter(t => !['thumbcache', 'iconcache'].includes(t.toLowerCase())) - .slice(0, 4) - // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 - const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() - const extraLists = await Promise.all( - extTokens.map(ext => searchRealIndexedFiles(`.${ext.toLowerCase()}`, 30, hostOverride)) - ) - const seen = new Set() - for (const list of extraLists) { - for (const item of list) { - if (!item.isDir && item.size > 0 && !seen.has(item.path)) { - if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { - seen.add(item.path) - files.push(item) - } - } - } - } - } - } - if (typeof opts.collectTopN === 'number' && opts.collectTopN > 0 && files.length > opts.collectTopN) { - files = files.slice(0, opts.collectTopN) - } - const subdirs: RealDirectorySubdirSummary[] = Array.isArray(rawPayload.subdirs) - ? rawPayload.subdirs.map((s: DynamicBridge) => ({ - name: String(s.name || ''), - path: String(s.path || ''), - fileCount: Number(s.file_count ?? s.fileCount ?? 0), - totalBytes: Number(s.total_bytes ?? s.totalBytes ?? 0), - mtime: Number(s.mtime || 0), - ...(s.approximate === true ? { approximate: true } : {}) - })) - : [] - const computedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) - const totalFilesCount = - filterExt instanceof RegExp ? files.length : Number(rawPayload.total_matches ?? files.length) - const totalBytesCount = - filterExt instanceof RegExp ? computedBytes : Number(rawPayload.total_bytes ?? computedBytes) - const visited = Number(rawPayload.visited_entries) - return { - scan: makeScanResult(files, totalFilesCount, totalBytesCount, subdirs, { - truncated: rawPayload.truncated === true, - approximate: rawPayload.approximate === true, - ...(Number.isFinite(visited) && visited >= 0 ? { visitedEntries: visited } : {}) - }), - ...(typeof rawPayload.scan_error === 'string' && rawPayload.scan_error ? { error: rawPayload.scan_error } : {}) - } - } - - // 深度扫描失败或回执无效时,仅以一级目录读取补回可见结果;不冒充完整目录树。 - const listing = await listDirectoryViaFilesystem(targetDir, hostOverride, { withSizes: true, limit: safeLimit }) - if (listing.ok && listing.entries.length > 0) { - const files: RealIndexedFileEntry[] = [] - let totalBytes = 0 - for (const entry of listing.entries) { - if (filterExt instanceof RegExp && !filterExt.test(entry.name) && !filterExt.test(entry.ext)) { - continue - } - files.push(entry) - totalBytes += entry.isDir ? 0 : entry.size - } - const incomplete = listing.entries.some(entry => entry.isDir) || listing.entries.length >= safeLimit - return { - scan: makeScanResult(files, files.filter(file => !file.isDir).length, totalBytes, [], { approximate: incomplete }), - ...(incomplete ? { error: res.error || ipcStrings().deepScanUnavailable } : {}) - } - } - return listing.ok ? { scan: empty } : { scan: empty, error: listing.error || 'DIRECTORY_READ_FAILED' } - } catch (error) { - return { scan: empty, error: error instanceof Error ? error.message : String(error) } - } -} - - -/** 目录读取不到任何条目(不存在 / 为空 / 无权限)时的错误码 */ -export const DIRECTORY_EMPTY_OR_UNREADABLE = 'DIRECTORY_EMPTY_OR_UNREADABLE' - -export interface RealDirectoryListingResult { - /** 目录内条目的完整路径;读取失败时为空数组 */ - entries: string[] - /** 读取失败或目录为空时的错误码 / 宿主错误信息 */ - error?: string -} - -export interface RealDirectChildrenResult { - /** 目录的直接子项(子目录在前),按路径去重 */ - entries: RealIndexedFileEntry[] - /** 宿主扫描达到条目上限,可能只返回了部分直接子项 */ - partial: boolean - error?: string -} - -function stripTrailingSeparators(p: string): string { - const trimmed = p.replace(/[\\/]+$/, '') - return trimmed || p.slice(0, 1) -} - -function isWindowsStylePath(p: string): boolean { - return /^[A-Za-z]:/.test(p) || p.startsWith('\\\\') || (p.includes('\\') && !p.includes('/')) -} - -function comparablePath(p: string): string { - const stripped = stripTrailingSeparators(String(p || '').trim()) - return isWindowsStylePath(stripped) ? stripped.replace(/\//g, '\\').toLowerCase() : stripped -} - -function parentDirOf(p: string): string { - const stripped = stripTrailingSeparators(String(p || '')) - const idx = Math.max(stripped.lastIndexOf('/'), stripped.lastIndexOf('\\')) - if (idx < 0) return '' - if (idx === 0) return stripped.slice(0, 1) - const parent = stripped.slice(0, idx) - return /^[A-Za-z]:$/.test(parent) ? `${parent}\\` : parent -} - -function isDirectChildPath(dirPath: string, candidate: string): boolean { - if (!candidate) return false - return comparablePath(parentDirOf(candidate)) === comparablePath(dirPath) -} - -function joinChildPath(dirPath: string, name: string): string { - const sep = isWindowsStylePath(dirPath) ? '\\' : '/' - const base = dirPath.replace(/[\\/]+$/, '') - return `${base}${sep}${name}` -} - -/** - * 通过 filesystem_get_directory_contents 读取一级目录(需宿主授权)。 - * 宿主真实返回 { success, files: [{ name, size, isDirectory, lastModified }] }(name 为文件名); - * 兼容旧测试替身返回的完整路径字符串数组。 - */ -async function listDirectoryViaFilesystem( - dirPath: string, - hostOverride: DynamicBridge, - options: { withSizes?: boolean; limit?: number } = {} -): Promise<{ ok: boolean; entries: RealIndexedFileEntry[]; error?: string }> { - const res = await callHostTransport('filesystem_get_directory_contents', { path: dirPath }, hostOverride) - if (!res.ok) return { ok: false, entries: [], error: res.error || 'DIRECTORY_READ_FAILED' } - const data = res.data - const rawList: unknown[] | null = Array.isArray(data) ? data : Array.isArray(data?.files) ? data.files : null - if (!rawList) return { ok: false, entries: [], error: 'INVALID_DIRECTORY_PAYLOAD' } - - const limit = Math.max(1, Math.floor(options.limit ?? 1000)) - const nowSec = Math.floor(Date.now() / 1000) - const entries: RealIndexedFileEntry[] = [] - const seen = new Set() - for (const item of rawList) { - if (entries.length >= limit) break - let entry: RealIndexedFileEntry | null = null - if (typeof item === 'string') { - const itemPath = item.trim() - if (!itemPath) continue - const name = itemPath.split(/[\\/]/).pop() || itemPath - const sz = options.withSizes ? await getRealFileSize(itemPath, hostOverride) : 0 - entry = normalizeIndexedFileEntry({ - name, - path: itemPath, - isDir: sz === 0 && !name.includes('.'), - size: sz, - mtime: nowSec - }) - } else if (item && typeof item === 'object' && typeof (item as DynamicBridge).name === 'string') { - const raw = item as DynamicBridge - const rawName = raw.name.trim() - if (!rawName || rawName === '.' || rawName === '..') continue - // 只接受文件名,或确实位于该目录下的完整路径,拒绝越界路径 - const fullPath = /[\\/]/.test(rawName) ? rawName : joinChildPath(dirPath, rawName) - if (!isDirectChildPath(dirPath, fullPath)) continue - const isDir = Boolean(raw.isDirectory ?? raw.isDir ?? raw.is_dir) - const parsedMtime = Date.parse(String(raw.lastModified || '')) - entry = normalizeIndexedFileEntry({ - name: fullPath.split(/[\\/]/).pop() || rawName, - path: fullPath, - isDir, - size: isDir ? 0 : Math.max(0, Number(raw.size) || 0), - mtime: Number.isFinite(parsedMtime) ? parsedMtime : nowSec - }) - } - if (!entry || seen.has(entry.path)) continue - seen.add(entry.path) - entries.push(entry) - } - return { ok: true, entries } -} - -/** - * 读取真实目录下的条目路径(真实宿主中优先走 dir: 扫描:一级子目录 + 全树 Top-N 大文件),并返回失败原因。 - * 目录不存在、为空或无权限时返回空列表与错误码,绝不用全盘关键词搜索结果冒充目录内容。 - */ -export async function listRealDirectoryContentsResult( - dirPath: string, - hostOverride?: DynamicBridge -): Promise { - if (!dirPath || !dirPath.trim()) return { entries: [], error: 'EMPTY_DIRECTORY_PATH' } - const targetDir = dirPath.trim() - - if (!hostOverride && isRealElectronHost()) { - const tree = await scanRealDirectoryTree(targetDir, 60) - const paths: string[] = [] - for (const s of tree.subdirs) { - if (s.path) paths.push(s.path) - } - for (const f of tree.files) { - if (f.path) paths.push(f.path) - } - if (paths.length > 0) return { entries: Array.from(new Set(paths)) } - } - - const listing = await listDirectoryViaFilesystem(targetDir, hostOverride) - if (!listing.ok) return { entries: [], error: listing.error } - if (listing.entries.length === 0) return { entries: [], error: DIRECTORY_EMPTY_OR_UNREADABLE } - return { entries: listing.entries.map(e => e.path) } -} - -/** - * 读取真实目录下的条目路径(保持旧签名:失败时返回空数组,需要失败原因请用 listRealDirectoryContentsResult) - */ -export async function listRealDirectoryContents( - dirPath: string, - hostOverride?: DynamicBridge -): Promise { - return (await listRealDirectoryContentsResult(dirPath, hostOverride)).entries -} - -/** - * 只列出目录的直接子项(子目录 + 直接位于该目录下的文件),用于文件夹预览、按目录改名等场景。 - * dir: 扫描结果中只保留 subdirs 与父目录等于 dirPath 的文件;扫描达到上限时 partial=true,由插件如实提示「仅显示部分」。 - */ -export async function listDirectChildren( - dirPath: string, - hostOverride?: DynamicBridge -): Promise { - if (!dirPath || !dirPath.trim()) return { entries: [], partial: false, error: 'EMPTY_DIRECTORY_PATH' } - const targetDir = dirPath.trim() - const scanLimit = 200 - const entries: RealIndexedFileEntry[] = [] - const seen = new Set() - const push = (entry: RealIndexedFileEntry) => { - const key = comparablePath(entry.path) - if (!entry.path || seen.has(key)) return - seen.add(key) - entries.push(entry) - } - - const { scan: tree, error } = await scanDirectoryTreeWithError(targetDir, { maxFiles: scanLimit, hostOverride }) - for (const s of tree.subdirs) { - if (!s.path || !isDirectChildPath(targetDir, s.path)) continue - push( - normalizeIndexedFileEntry({ - name: s.name || s.path.split(/[\\/]/).pop(), - path: s.path, - isDir: true, - size: s.totalBytes, - mtime: s.mtime - }) - ) - } - let directFileCount = 0 - for (const f of tree.files) { - if (!isDirectChildPath(targetDir, f.path)) continue - directFileCount++ - push(f) - } - // 宿主 total_matches 是全树文件数、subdirs[].file_count 是各子目录全树文件数,差值即直接子文件数; - // 拿到的直接子文件少于它就说明被 Top-N 截断了。计数不可用时按是否达到扫描上限判断 - const expectedDirectFiles = tree.totalFiles - tree.subdirs.reduce((sum, d) => sum + (Number(d.fileCount) || 0), 0) - const partial = - Number.isFinite(expectedDirectFiles) && expectedDirectFiles >= 0 - ? directFileCount < expectedDirectFiles - : tree.files.length >= scanLimit - if (entries.length > 0) { - return { entries, partial } - } - - if (tree.files.length > 0) { - // dir: 扫描只返回了深层文件(直接子文件被 Top-N 截掉),如实标注部分结果 - return { entries: [], partial: true, error: DIRECTORY_EMPTY_OR_UNREADABLE } - } - return { entries: [], partial: false, error: error || DIRECTORY_EMPTY_OR_UNREADABLE } -} - -/** - * 获取真实文件字节大小(优先用扫描结果里的大小,再走 filesystem_get_file_size);读不到时返回 0 - */ -export async function getRealFileSize( - filePath: string, - hostOverride?: DynamicBridge -): Promise { - if (!filePath) return 0 - if (!hostOverride && realFileSizeCache.has(filePath)) { - const cached = realFileSizeCache.get(filePath)! - if (cached > 0) return cached - } - const res = await callHostTransport('filesystem_get_file_size', { path: filePath }, hostOverride) - // 客户端返回 { success, size }(目录时 size 为 -1),旧的测试替身直接返回数字 - const size = typeof res.data === 'number' ? res.data : res.data?.size - if (res.ok && typeof size === 'number' && Number.isFinite(size) && size >= 0) { - realFileSizeCache.set(filePath, size) - return size - } - return 0 -} - -/** - * 在访达 / 资源管理器中定位并高亮文件或目录。 - * 定位失败直接返回 false,不能改用“打开”:对可执行文件那等于运行它。 - */ -export async function showRealItemInFolder( - fullPath: string, - hostOverride?: DynamicBridge -): Promise { - if (!fullPath) return false - const res = await callHostTransport('shell_show_item_in_folder', { fullPath }, hostOverride) - return res.ok -} - -/** - * 使用系统默认程序打开文件或目录 - */ -export async function openRealPath( - fullPath: string, - hostOverride?: DynamicBridge -): Promise { - if (!fullPath) return false - const res = await callHostTransport('shell_open_path', { fullPath }, hostOverride) - return res.ok -} - -/** - * 将真实文件或目录移入系统回收站(安全可恢复删除) - */ -export async function trashRealItem( - fullPath: string, - hostOverride?: DynamicBridge -): Promise<{ ok: boolean; error?: string; errorCode?: string; errorDetails?: Record }> { - if (!fullPath) return { ok: false, error: ipcStrings().pathEmpty } - const res = await callHostTransport('shell_trash_item', { fullPath }, hostOverride) - return { - ok: res.ok, - error: res.error, - ...(!res.ok && res.errorCode ? { errorCode: res.errorCode } : {}), - ...(!res.ok && res.errorDetails ? { errorDetails: res.errorDetails } : {}) - } -} - -export interface NativeInvocationResult { - ok: boolean - code: number - message: string - data?: T - error?: string - errorCode?: string - errorDetails?: Record -} - -export interface DllCapabilityResponse { - ok: boolean - code: number - data: T | null - message?: string - error?: string - errorCode?: string - errorDetails?: Record - pluginName: string - method: string - fromFallback?: boolean -} - -/** 声明式能力菜单项及其调用回执,供相同宿主协议的插件共用。 */ -export interface CapabilityActionItem { - id: string - title: string - subtitle: string - tag: string - method: string - params: Record -} - -export type PluginInvocationResult = Pick< - DllCapabilityResponse, 'ok' | 'pluginName' | 'method' | 'error' | 'errorCode' | 'errorDetails' | 'fromFallback' -> & { data?: unknown } - -/** 多个原生能力插件共用的参数边界校验;保护目标由各插件按自身业务提供。 */ -export function validateNativeCapabilityPayload( - method: string, - params: unknown, - forbiddenPattern: RegExp, - forbiddenReason: string -): { valid: boolean; error?: string } { - const s = ipcStrings() - if (typeof method !== 'string' || method.trim().length === 0) { - return { valid: false, error: s.invalidMethodEmpty } - } - if (method.length > 128 || !/^[A-Za-z0-9_]+$/.test(method.trim())) { - return { valid: false, error: s.invalidMethodFormat } - } - if (params === null || params === undefined || typeof params !== 'object' || Array.isArray(params)) { - return { valid: false, error: s.invalidParamsObject } - } - - const record = params as Record - for (const [key, val] of Object.entries(record)) { - if (typeof val === 'string') { - if (val.length > 4096) { - return { valid: false, error: s.paramTooLong(key) } - } - if (forbiddenPattern.test(val)) { - return { valid: false, error: `SECURITY_INTERCEPTED: ${forbiddenReason}` } - } - } else if (typeof val === 'number') { - if (!Number.isFinite(val) || val < -1000 || val > 100_000_000) { - return { valid: false, error: s.paramOutOfRange(key) } - } - } - } - - return { valid: true } -} - -export async function invokeDllPluginCapability( - pluginName: string, - method: string, - params: Record = {}, - hostBridge?: DynamicBridge, - offlineFallback?: () => T | Promise -): Promise> { - const s = ipcStrings() - if (!method || typeof method !== 'string' || method.trim().length === 0) { - return { - ok: false, - code: -1, - data: null, - message: s.methodParamEmpty, - error: s.invalidMethodType, - pluginName, - method: String(method || '') - } - } - - const trimmedMethod = method.trim() - - const unwrapDllRawPayload = (raw: unknown, unwrapDataProperty: boolean): DllCapabilityResponse => { - let parsed: DynamicBridge = raw - if (typeof raw === 'string') { - try { - parsed = JSON.parse(raw) - } catch { - throw new Error(s.malformedDllResponse) - } - } - if (parsed && typeof parsed === 'object') { - if ('error' in parsed && parsed.error !== undefined && parsed.error !== null && parsed.error !== '') { - const errMsg = `DLL_ERROR: ${String(parsed.error)}` - return { - ok: false, - code: typeof parsed.code === 'number' ? parsed.code : -1, - data: null, - message: errMsg, - error: errMsg, - ...extractIpcErrorMeta(parsed), - ...extractIpcErrorMeta(parsed.error), - pluginName, - method: trimmedMethod, - fromFallback: false - } - } - if ('ok' in parsed && parsed.ok === false) { - const errMsg = `DLL_ERROR: ${String(parsed.error || parsed.message || s.unknownDllError)}` - return { - ok: false, - code: typeof parsed.code === 'number' ? parsed.code : -1, - data: null, - message: errMsg, - error: errMsg, - ...extractIpcErrorMeta(parsed), - ...extractIpcErrorMeta(parsed.error), - pluginName, - method: trimmedMethod, - fromFallback: false - } - } - const dataPayload = unwrapDataProperty && 'data' in parsed && parsed.data !== undefined ? parsed.data : parsed - return { - ok: true, - code: typeof parsed.code === 'number' ? parsed.code : 0, - data: dataPayload as T, - message: typeof parsed.message === 'string' ? parsed.message : undefined, - pluginName, - method: trimmedMethod, - fromFallback: false - } - } - return { - ok: true, - code: 0, - data: (parsed ?? null) as T, - pluginName, - method: trimmedMethod, - fromFallback: false - } - } - - const wrapCaughtDllError = (err: unknown): DllCapabilityResponse => { - const message = err instanceof Error ? err.message : String(err) - if (message.startsWith('MALFORMED_DLL_RESPONSE:')) { - throw err - } - const errMsg = `NATIVE_CALL_FAILED: ${message}` - return { - ok: false, - code: -1, - data: null, - message: errMsg, - error: errMsg, - ...extractIpcErrorMeta(err), - pluginName, - method: trimmedMethod, - fromFallback: false - } - } - - if (hostBridge && typeof hostBridge.invokeNative === 'function') { - try { - const raw = await hostBridge.invokeNative(pluginName, trimmedMethod, params) - return unwrapDllRawPayload(raw, true) - } catch (err: unknown) { - return wrapCaughtDllError(err) - } - } - - const runtimeHost = (hostBridge ?? (globalThis as Record).ztools) as - | { dllplugin?: { call?: (plugin: string, fn: string, payload: unknown) => Promise | unknown } } - | undefined - - const callFn = runtimeHost?.dllplugin?.call - if (typeof callFn === 'function') { - try { - const raw = await callFn.call(runtimeHost?.dllplugin, pluginName, trimmedMethod, params) - return unwrapDllRawPayload(raw, false) - } catch (err: unknown) { - return wrapCaughtDllError(err) - } - } - - const ipcRes = await callHostTransport( - 'dllplugin_call', - { - plugin: pluginName, - func: trimmedMethod, - params - }, - hostBridge - ) - - if (ipcRes.ok && ipcRes.data !== undefined && ipcRes.data !== null) { - return unwrapDllRawPayload(ipcRes.data, false) - } - - const isExplicitTransportFailure = - typeof ipcRes.error === 'string' && - ipcRes.error.length > 0 && - ipcRes.error !== 'NO_WINDOW_ENV' && - !ipcRes.error.startsWith('METHOD_NOT_AVAILABLE:') - - if ( - isRealElectronHost(hostBridge) || - isRealElectronHost() || - Boolean((hostBridge as DynamicBridge)?.__isRealHost) || - isExplicitTransportFailure - ) { - const errMsg = - ipcRes.error || s.hostIpcFailed(pluginName, trimmedMethod) - return { - ok: false, - code: -1, - data: null, - message: errMsg, - error: errMsg, - ...(ipcRes.errorCode ? { errorCode: ipcRes.errorCode } : {}), - ...(ipcRes.errorDetails ? { errorDetails: ipcRes.errorDetails } : {}), - pluginName, - method: trimmedMethod, - fromFallback: false - } - } - - if (typeof offlineFallback === 'function') { - const fallbackData = await offlineFallback() - return { - ok: true, - code: 0, - data: fallbackData, - pluginName, - method: trimmedMethod, - fromFallback: true - } - } - - const unavailableMsg = s.hostUnavailable(pluginName, trimmedMethod) - return { - ok: false, - code: -1, - data: null, - message: unavailableMsg, - error: unavailableMsg, - ...(ipcRes.errorCode ? { errorCode: ipcRes.errorCode } : {}), - ...(ipcRes.errorDetails ? { errorDetails: ipcRes.errorDetails } : {}), - pluginName, - method: trimmedMethod, - fromFallback: true - } -} - -export function formatBytes(bytes: number, decimals = 1): string { - const num = Number(bytes) - if (!Number.isFinite(num) || num <= 0) return '0 B' - if (num < 1024) return `${Math.round(num)} B` - const units = ['B', 'KB', 'MB', 'GB', 'TB'] - let val = num - let idx = 0 - while (val >= 1024 && idx < units.length - 1) { - val /= 1024 - idx += 1 - } - const safeDecimals = Math.max(0, Math.floor(decimals)) - return `${val >= 100 ? val.toFixed(0) : val.toFixed(safeDecimals)} ${units[idx]}` -} - -export function joinWinPath(...segments: string[]): string { - return segments - .filter(s => typeof s === 'string' && s.trim().length > 0) - .map((s, i) => (i === 0 ? s.replace(/[\\/]+$/, '') : s.replace(/^[\\/]+|[\\/]+$/g, ''))) - .join('\\') -} - -export interface RealEnvPaths { - home: string - userProfile: string - appData: string - localAppData: string - temp: string - downloads: string - documents: string - desktop: string - pictures: string - videos: string - music: string -} - -export async function getRealEnvPaths(hostOverride?: DynamicBridge): Promise { - const [homeRaw, appData, downloads, documents, desktop, pictures, videos, music] = await Promise.all([ - getRealSystemPath('home', hostOverride), - getRealSystemPath('appData', hostOverride), - getRealSystemPath('downloads', hostOverride), - getRealSystemPath('documents', hostOverride), - getRealSystemPath('desktop', hostOverride), - getRealSystemPath('pictures', hostOverride), - getRealSystemPath('videos', hostOverride), - getRealSystemPath('music', hostOverride) - ]) - const home = homeRaw || 'C:\\Users\\Default' - const isPosix = home.startsWith('/') - const tempRes = hostOverride ? await getRealSystemPath('temp', hostOverride) : '' - if (isPosix) { - return { - home, - userProfile: home, - appData: appData || `${home}/Library/Application Support`, - localAppData: `${home}/Library/Application Support`, - temp: tempRes || '/tmp', - downloads: downloads || `${home}/Downloads`, - documents: documents || `${home}/Documents`, - desktop: desktop || `${home}/Desktop`, - pictures: pictures || `${home}/Pictures`, - videos: videos || `${home}/Videos`, - music: music || `${home}/Music` - } - } - return { - home, - userProfile: home, - appData: appData || `${home}\\AppData\\Roaming`, - localAppData: `${home}\\AppData\\Local`, - temp: tempRes || `${home}\\AppData\\Local\\Temp`, - downloads: downloads || `${home}\\Downloads`, - documents: documents || `${home}\\Documents`, - desktop: desktop || `${home}\\Desktop`, - pictures: pictures || `${home}\\Pictures`, - videos: videos || `${home}\\Videos`, - music: music || `${home}\\Music` - } -} - -export const resolveRealSpecialPaths = getRealEnvPaths - -export async function readRealDirectory( - dirPath: string, - hostOverride?: DynamicBridge -): Promise { - if (!dirPath) return [] - const tree = await scanRealDirectoryTree(dirPath, { maxFiles: 120, hostOverride }) - const entries: RealIndexedFileEntry[] = [] - for (const s of tree.subdirs) { - entries.push( - normalizeIndexedFileEntry({ - name: s.name, - path: s.path, - isDir: true, - isDirectory: true, - size: s.totalBytes, - mtime: s.mtime - }) - ) - } - for (const f of tree.files) { - entries.push(f) - } - // scanRealDirectoryTree 已在 dir: 扫描无结果时退回一级目录读取;仍为空即目录不存在 / 为空 / 无权限,如实返回空列表 - return entries -} - -export async function moveRealFilesToTrash( - paths: string[], - hostOverride?: DynamicBridge -): Promise<{ - ok: boolean - trashedCount: number - deletedCount: number - failedPaths: string[] - error?: string -}> { - let deletedCount = 0 - const failedPaths: string[] = [] - let lastError: string | undefined - for (const p of paths) { - if (!p) continue - const res = await trashRealItem(p, hostOverride) - if (res.ok) { - deletedCount += 1 - } else { - failedPaths.push(p) - if (res.error) lastError = res.error - } - } - return { - ok: deletedCount > 0 || paths.length === 0, - trashedCount: deletedCount, - deletedCount, - failedPaths, - error: lastError - } -} - -const CAPABILITY_TO_PLUGIN_MAP: Record = { - 'mover.relocateWithJunction': { plugin: 'MoverPlugin', func: 'relocateWithJunction' }, - 'mover.scanCandidates': { plugin: 'MoverPlugin', func: 'scanCandidates' }, - 'recovery.restoreFile': { plugin: 'DataRecoveryPlugin', func: 'restoreFile' }, - 'recovery.scanDeletedFiles': { plugin: 'DataRecoveryPlugin', func: 'scanDeletedFiles' }, - 'shredder.secureWipeFile': { plugin: 'ShredderPlugin', func: 'secureWipeFile' }, - 'shredder.scanCandidates': { plugin: 'ShredderPlugin', func: 'scanCandidates' }, - 'backup.createSnapshotArchive': { plugin: 'SystemBackupPlugin', func: 'createSnapshotArchive' }, - 'backup.restoreSnapshotArchive': { plugin: 'SystemBackupPlugin', func: 'restoreSnapshotArchive' }, - 'backup.scanSnapshots': { plugin: 'SystemBackupPlugin', func: 'scanSnapshots' }, - 'sqlite.execute': { plugin: 'SqlitePlugin', func: 'execute' }, - 'sqlite.query': { plugin: 'SqlitePlugin', func: 'executeQuery' }, - 'sqlite.inspectWorkspace': { plugin: 'SqlitePlugin', func: 'inspectWorkspace' } -} - -export async function invokeHostCapability( - capability: string, - params: Record = {}, - hostOverride?: DynamicBridge -): Promise> { - const normalizedMethod = capability.replace(/\./g, '_') - - // 若测试显式注入了对应 normalizedMethod 的 mock 函数,优先调用测试桩 - if (hostOverride && typeof hostOverride[normalizedMethod] === 'function') { - const mockRes = await callHostTransport(normalizedMethod, params, hostOverride) - return { - ok: mockRes.ok, - code: mockRes.ok ? 0 : -1, - message: mockRes.ok ? 'OK' : mockRes.error || ipcStrings().callFailed, - data: mockRes.data, - error: mockRes.error, - ...(!mockRes.ok && mockRes.errorCode ? { errorCode: mockRes.errorCode } : {}), - ...(!mockRes.ok && mockRes.errorDetails ? { errorDetails: mockRes.errorDetails } : {}) - } - } - - if (capability === 'system.info') { - const drives = await probeRealDiskDrives(['C', 'D', 'E', 'F'], hostOverride) - return { - ok: true, - code: 0, - message: 'OK', - data: { - storage: drives.map(d => ({ - mount: d.drive, - fs: d.drive, - size: d.totalBytes, - total: d.totalBytes, - used: d.usedBytes, - available: d.availableBytes, - free: d.availableBytes, - percent: d.usagePercent - })) - } as unknown as T - } - } - if (capability === 'filesystem.deleteItem') { - const targetPath = String(params.path || params.fullPath || '') - const tr = await trashRealItem(targetPath, hostOverride) - const s = ipcStrings() - return { - ok: tr.ok, - code: tr.ok ? 0 : -1, - message: tr.ok ? s.movedToTrash : tr.error || s.deleteFailed, - error: tr.error, - ...(!tr.ok && tr.errorCode ? { errorCode: tr.errorCode } : {}), - ...(!tr.ok && tr.errorDetails ? { errorDetails: tr.errorDetails } : {}) - } - } - if (capability === 'system.showItemInFolder') { - const targetPath = String(params.path || params.fullPath || '') - const s = ipcStrings() - if (!targetPath) { - return { ok: false, code: -1, message: s.revealFailed } - } - const res = await callHostTransport('shell_show_item_in_folder', { fullPath: targetPath }, hostOverride) - return { - ok: res.ok, - code: res.ok ? 0 : -1, - message: res.ok ? s.revealedInFolder : res.error || s.revealFailed, - ...(!res.ok && res.error ? { error: res.error } : {}), - ...(!res.ok && res.errorCode ? { errorCode: res.errorCode } : {}), - ...(!res.ok && res.errorDetails ? { errorDetails: res.errorDetails } : {}) - } - } - if (capability === 'filesystem.openItem' || capability === 'system.openUrl') { - const target = String(params.path || params.url || params.fullPath || '') - const method = capability === 'system.openUrl' ? 'shell_open_external' : 'shell_open_path' - const res = await callHostTransport( - method, - capability === 'system.openUrl' ? { url: target } : { fullPath: target }, - hostOverride - ) - const s = ipcStrings() - return { - ok: res.ok, - code: res.ok ? 0 : -1, - message: res.ok ? s.opened : res.error || s.openFailed, - data: res.data, - error: res.error, - ...(!res.ok && res.errorCode ? { errorCode: res.errorCode } : {}), - ...(!res.ok && res.errorDetails ? { errorDetails: res.errorDetails } : {}) - } - } - - const pluginMapping = CAPABILITY_TO_PLUGIN_MAP[capability] - if (pluginMapping) { - const dllRes = await invokePluginService( - pluginMapping.plugin, - pluginMapping.func, - params, - hostOverride - ) - if (dllRes.ok) return dllRes - if (hostOverride) { - const fallbackMock = await callHostTransport(normalizedMethod, params, hostOverride) - if (fallbackMock.ok) { - return { - ok: true, - code: 0, - message: 'OK', - data: fallbackMock.data - } - } - } - return dllRes - } - - const res = await callHostTransport(normalizedMethod, params, hostOverride) - return { - ok: res.ok, - code: res.ok ? 0 : -1, - message: res.ok ? 'OK' : res.error || ipcStrings().callFailed, - data: res.data, - error: res.error, - ...(!res.ok && res.errorCode ? { errorCode: res.errorCode } : {}), - ...(!res.ok && res.errorDetails ? { errorDetails: res.errorDetails } : {}) - } -} - -export async function invokePluginService( - pluginName: string, - action: string, - params: Record = {}, - hostOverride?: DynamicBridge -): Promise> { - const s = ipcStrings() - // 1. 若测试注入了专门拦截 plugin_invoke 的 mock,支持调用 - if (hostOverride && typeof hostOverride.plugin_invoke === 'function') { - const mockRes = await callHostTransport( - 'plugin_invoke', - { plugin: pluginName, action, params }, - hostOverride - ) - return { - ok: mockRes.ok, - code: mockRes.ok ? 0 : -1, - message: mockRes.ok ? 'OK' : mockRes.error || s.pluginCallNotReady, - data: mockRes.data, - error: mockRes.error, - ...(!mockRes.ok && mockRes.errorCode ? { errorCode: mockRes.errorCode } : {}), - ...(!mockRes.ok && mockRes.errorDetails ? { errorDetails: mockRes.errorDetails } : {}) - } - } - - // 2. 优先走真实 Electron IPC 的 dllplugin_call 通道 - const dllRes = await callHostTransport( - 'dllplugin_call', - { plugin: pluginName, func: action, params }, - hostOverride - ) - if (dllRes.ok) { - const inner = dllRes.data - if (inner && typeof inner === 'object' && typeof inner.error === 'string' && inner.error.length > 0 && inner.ok !== true) { - return { - ok: false, - code: -1, - message: inner.error, - error: inner.error, - ...extractIpcErrorMeta(inner) - } - } - return { - ok: true, - code: 0, - message: 'OK', - data: inner as T - } - } - - // 3. 兼容单元测试中通过 transport.call('plugin_invoke') 注入的测试桩 - if (hostOverride) { - const legacyRes = await callHostTransport( - 'plugin_invoke', - { plugin: pluginName, action, params }, - hostOverride - ) - if (legacyRes.ok) { - return { - ok: true, - code: 0, - message: 'OK', - data: legacyRes.data - } - } - } - - // 4. 兼容旧版 globalThis.ztools.dllplugin.call - const g = globalThis as DynamicBridge - if (!hostOverride && typeof g?.ztools?.dllplugin?.call === 'function') { - try { - const raw = await g.ztools.dllplugin.call(pluginName, action, params) - if (raw && typeof raw === 'object' && raw.ok === false) { - return { - ok: false, - code: -1, - message: String(raw.error || s.callFailed), - error: String(raw.error || s.callFailed), - ...extractIpcErrorMeta(raw), - ...extractIpcErrorMeta(raw.error) - } - } - const data = raw && typeof raw === 'object' && 'data' in raw ? raw.data : raw - return { ok: true, code: 0, message: 'OK', data: data as T } - } catch (err: DynamicBridge) { - return { - ok: false, - code: -1, - message: err instanceof Error ? err.message : String(err), - error: err instanceof Error ? err.message : String(err), - ...extractIpcErrorMeta(err) - } - } - } - - return { - ok: false, - code: -1, - message: dllRes.error || s.pluginCallNotReady, - error: dllRes.error || s.pluginCallNotReady, - ...(dllRes.errorCode ? { errorCode: dllRes.errorCode } : {}), - ...(dllRes.errorDetails ? { errorDetails: dllRes.errorDetails } : {}) - } -} - -const SHA256_K = new Uint32Array([ - 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, - 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, - 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, - 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, - 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, - 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, - 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, - 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 -]) - -function rotr32(x: number, n: number): number { - return (x >>> n) | (x << (32 - n)) -} - -/** - * 标准 FIPS 180-4 SHA-256 真实字节摘要算法(返回 64 位小写 Hex) - */ -export function computeRealSha256Hex(input: string | Uint8Array): string { - const bytes = - typeof input === 'string' ? new TextEncoder().encode(input) : new Uint8Array(input || []) - const bitLen = bytes.length * 8 - const padLen = ((bytes.length + 9 + 63) & ~63) - const buf = new Uint8Array(padLen) - buf.set(bytes, 0) - buf[bytes.length] = 0x80 - const view = new DataView(buf.buffer) - view.setUint32(padLen - 8, Math.floor(bitLen / 0x100000000), false) - view.setUint32(padLen - 4, bitLen >>> 0, false) - - let h0 = 0x6a09e667 - let h1 = 0xbb67ae85 - let h2 = 0x3c6ef372 - let h3 = 0xa54ff53a - let h4 = 0x510e527f - let h5 = 0x9b05688c - let h6 = 0x1f83d9ab - let h7 = 0x5be0cd19 - - const w = new Uint32Array(64) - for (let offset = 0; offset < padLen; offset += 64) { - for (let i = 0; i < 16; i++) { - w[i] = view.getUint32(offset + i * 4, false) - } - for (let i = 16; i < 64; i++) { - const s0 = rotr32(w[i - 15], 7) ^ rotr32(w[i - 15], 18) ^ (w[i - 15] >>> 3) - const s1 = rotr32(w[i - 2], 17) ^ rotr32(w[i - 2], 19) ^ (w[i - 2] >>> 10) - w[i] = (w[i - 16] + s0 + w[i - 7] + s1) >>> 0 - } - - let a = h0 - let b = h1 - let c = h2 - let d = h3 - let e = h4 - let f = h5 - let g = h6 - let h = h7 - - for (let i = 0; i < 64; i++) { - const S1 = rotr32(e, 6) ^ rotr32(e, 11) ^ rotr32(e, 25) - const ch = (e & f) ^ (~e & g) - const temp1 = (h + S1 + ch + SHA256_K[i] + w[i]) >>> 0 - const S0 = rotr32(a, 2) ^ rotr32(a, 13) ^ rotr32(a, 22) - const maj = (a & b) ^ (a & c) ^ (b & c) - const temp2 = (S0 + maj) >>> 0 - - h = g - g = f - f = e - e = (d + temp1) >>> 0 - d = c - c = b - b = a - a = (temp1 + temp2) >>> 0 - } - - h0 = (h0 + a) >>> 0 - h1 = (h1 + b) >>> 0 - h2 = (h2 + c) >>> 0 - h3 = (h3 + d) >>> 0 - h4 = (h4 + e) >>> 0 - h5 = (h5 + f) >>> 0 - h6 = (h6 + g) >>> 0 - h7 = (h7 + h) >>> 0 - } - - return [h0, h1, h2, h3, h4, h5, h6, h7] - .map(v => (v >>> 0).toString(16).padStart(8, '0')) - .join('') -} - -/** - * 读取本地文件真实字节并计算标准 SHA-256:宿主 filesearch_sha256(只接受 path 字段)优先,Windows 上再试 FileComparePlugin。 - * 都拿不到时返回空字符串,由调用方提示失败;不再把文件按 UTF-8 文本读出来再算(二进制文件会算出错误的值)。 - */ -export async function computeRealFileSha256( - filePath: string, - hostOverride?: DynamicBridge -): Promise { - if (!filePath || !filePath.trim()) return '' - const target = filePath.trim() - - const shaRes = await callHostTransport('filesearch_sha256', { fullPath: target }, hostOverride) - if (shaRes.ok && shaRes.data) { - const hash = typeof shaRes.data === 'string' ? shaRes.data : String(shaRes.data?.sha256 || shaRes.data?.hash || '') - if (/^[0-9a-f]{64}$/i.test(hash)) return hash.toLowerCase() - } - - const dllRes = await invokePluginService('FileComparePlugin', 'computeFileSha256', { path: target }, hostOverride) - if (dllRes.ok && dllRes.data) { - const hash = typeof dllRes.data === 'string' ? dllRes.data : String(dllRes.data?.sha256 || dllRes.data?.hash || '') - if (/^[0-9a-f]{64}$/i.test(hash)) return hash.toLowerCase() - } - - return '' -} - -export async function readRealClipboardText(hostOverride?: DynamicBridge): Promise { - const res = await callHostTransport('clipboard_read_text', {}, hostOverride) - if (res.ok && res.data !== undefined && res.data !== null) { - if (typeof res.data === 'string') return res.data - if (typeof res.data?.text === 'string') return res.data.text - } - try { - if (typeof navigator !== 'undefined' && navigator.clipboard?.readText) { - return await navigator.clipboard.readText() - } - } catch { - // ignore - } - return '' -} - -export async function writeRealClipboardText(text: string, hostOverride?: DynamicBridge): Promise { - const payload = { text: String(text || '') } - const res = await callHostTransport('clipboard_copy_text', payload, hostOverride) - if (res.ok) return true - const fallbackRes = await callHostTransport('clipboard_write_text', payload, hostOverride) - if (fallbackRes.ok) return true - try { - if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) { - await navigator.clipboard.writeText(String(text || '')) - return true - } - } catch { - // ignore - } - return false -} - -export async function showRealToast( - title: string, - style: 'success' | 'failure' | 'info' = 'info' -): Promise { - try { - const { showToast, Toast } = await import('@ztools/declarative-ui') - await showToast({ - title, - style: - style === 'success' - ? Toast.Style.Success - : style === 'failure' - ? Toast.Style.Failure - : Toast.Style.Animated - }) - } catch { - // ignore - } -} - diff --git a/extensions/batch-image/src/tool-runtime.ts b/extensions/batch-image/src/tool-runtime.ts new file mode 100644 index 00000000..29670de2 --- /dev/null +++ b/extensions/batch-image/src/tool-runtime.ts @@ -0,0 +1,637 @@ +/** + * 宿主薄原语与基础系统能力传输层(唯一权威公共源文件,纯标准 IPC,零原生 DLL 依赖) + * + * 修改本文件后需同步复制到各使用插件的 src/tool-runtime.ts, + * 构建脚本 build-declarative.mjs 会在编译前校验副本与本文件一字不差。 + */ + +import { getHostTransport } from '@ztools/declarative-ui' + +export type ToolCapabilityStatus = 'ready' | 'needs_provisioning' | 'unsupported' + +export interface ToolCapabilityDescriptor { + readonly primitiveId: string + readonly domain: string + readonly summary: string + readonly ipcMethods: readonly string[] + readonly requiredPermissions: readonly string[] + readonly status: ToolCapabilityStatus + readonly optionalExtensions: readonly string[] +} + +export interface ToolRuntimeCapabilitiesSnapshot { + readonly contractVersion: number + readonly platform: 'windows' | 'macos' | 'other' + readonly domains: readonly string[] + readonly capabilities: readonly ToolCapabilityDescriptor[] +} + +export interface ToolRuntimeEnsureResult { + readonly primitiveId: string + readonly status: ToolCapabilityStatus + readonly provisioned: boolean +} + +export interface ToolCapabilitiesEnsureResult { + readonly ok: boolean + readonly status: ToolCapabilityStatus + readonly provisioned: boolean + readonly failedPrimitiveId?: string + readonly error?: string + readonly errorCode?: string + readonly errorDetails?: Record +} + +export interface ToolTaskCancelResult { + readonly taskId: string + readonly cancelled: boolean +} + +export interface ToolPathSlot { + readonly grantId?: string + readonly relativePath?: string + readonly path?: string +} + +export interface ToolProgressEvent { + readonly taskId: string + readonly primitiveId?: string + readonly phase: 'provisioning' | 'running' | 'finalizing' | 'completed' | 'cancelled' | 'failed' + readonly percent?: number + readonly transferredBytes?: number + readonly totalBytes?: number + readonly speedBytesPerSec?: number + readonly stage?: string + readonly errorCode?: string + readonly retryable?: boolean + readonly userAction?: string + readonly message?: string + readonly timestamp?: number +} + +export type MediaTranscodeRunResult = + | { readonly status: 'done'; readonly outputBytes: number; readonly durationMs: number } + | { readonly status: 'cancelled' } + | { + readonly status: 'failed' + readonly error?: string + readonly errorCode?: string + readonly errorDetails?: Record + } + +export interface HostTransportResult { + ok: boolean + data?: T + error?: string + errorCode?: string + errorDetails?: Record +} + +export interface HostCallOptions { + timeoutMs?: number +} + +type TransportMethodFn = (req: { messageId: string; params: Record; timeoutMs?: number }) => Promise + +interface WindowHostBridge { + __ztoolsElectron?: { + transport?: { + methods?: Record + } + } + ztools?: { + transport?: { + methods?: Record + call?: (method: string, params: Record, options?: { timeoutMs?: number }) => Promise + } + events?: { + subscribe?: (event: string) => Promise | void + on?: (event: string, cb: (payload: unknown) => void) => (() => void) | void + off?: (event: string, cb: (payload: unknown) => void) => void + } + } +} + +interface HostOverrideLike { + transport?: { + call?: (method: string, params: Record, options?: { timeoutMs?: number }) => Promise + } + [method: string]: unknown +} + +let reqSeq = 1 + +export function nextMessageId(prefix = 'tool'): string { + reqSeq = (reqSeq + 1) % 1_000_000 + return `${prefix}_${Date.now()}_${reqSeq}` +} + +export function asRecord(value: unknown): Record | null { + return value && typeof value === 'object' && !Array.isArray(value) + ? (value as Record) + : null +} + +function extractErrorMeta(errObj: unknown): { + errorCode?: string + errorDetails?: Record +} { + const rec = asRecord(errObj) + if (!rec) return {} + const errorCode = + typeof rec.errorCode === 'string' && rec.errorCode.trim() + ? rec.errorCode.trim() + : typeof rec.code === 'string' && rec.code.trim() + ? rec.code.trim() + : undefined + const rawDetails = asRecord(rec.errorDetails) ?? asRecord(rec.details) ?? undefined + return { + ...(errorCode ? { errorCode } : {}), + ...(rawDetails ? { errorDetails: rawDetails } : {}) + } +} + +function toTransportError(err: unknown): HostTransportResult { + return { + ok: false, + error: err instanceof Error ? err.message : String(err), + ...extractErrorMeta(err) + } +} + +function buildFailureResult(rec: Record, fallbackMsg: string): HostTransportResult { + const errObj = asRecord(rec.error) + const errMsg = errObj + ? String(errObj.message || errObj.code || JSON.stringify(errObj)) + : String(rec.error || rec.message || fallbackMsg) + return { ok: false, error: errMsg, ...extractErrorMeta(rec), ...extractErrorMeta(errObj) } +} + +function unwrapTransportResponse(raw: unknown): HostTransportResult { + if (raw === null || raw === undefined) { + return { ok: false, error: 'EMPTY_IPC_RESPONSE', errorCode: 'EMPTY_IPC_RESPONSE' } + } + if (typeof raw !== 'object') { + return { ok: true, data: raw as T } + } + const outer = asRecord(raw) + if (!outer) { + return { ok: true, data: raw as T } + } + if (outer.success === false || outer.ok === false) { + return buildFailureResult(outer, 'IPC_CALL_FAILED') + } + + const firstLayer = 'data' in outer && outer.data !== undefined ? outer.data : outer + const inner = asRecord(firstLayer) + if (inner) { + if (inner.success === false || inner.ok === false) { + return buildFailureResult(inner, 'IPC_INNER_FAILED') + } + if ('data' in inner && inner.data !== undefined) { + return { ok: true, data: inner.data as T } + } + } + + return { ok: true, data: firstLayer as T } +} + +/** 判断当前是否处于真实的 ZTools Electron 渲染进程宿主环境 */ +export function isRealElectronHost(hostOverride?: unknown): boolean { + if (hostOverride) return true + if (typeof window === 'undefined') return false + const w = window as unknown as WindowHostBridge + return Boolean( + w.__ztoolsElectron?.transport?.methods || + w.ztools?.transport?.call || + w.ztools?.transport?.methods + ) +} + +/** 统一调用宿主 IPC 传输层(优先测试桩,其次 declarative-ui 宿主通道与 preload 通道) */ +export async function callHostTransport( + method: string, + params: Record = {}, + hostOverride?: unknown, + options?: HostCallOptions +): Promise> { + const override = asRecord(hostOverride) as HostOverrideLike | null + if (override) { + const directFn = override[method] + if (typeof directFn === 'function') { + try { + return unwrapTransportResponse(await (directFn as (p: Record) => Promise)(params)) + } catch (err) { + return toTransportError(err) + } + } + if (typeof override.transport?.call === 'function') { + try { + return unwrapTransportResponse(await override.transport.call(method, params, options)) + } catch (err) { + return toTransportError(err) + } + } + return { ok: false, error: `METHOD_NOT_AVAILABLE: ${method}`, errorCode: 'METHOD_NOT_AVAILABLE' } + } + + // 优先走 declarative-ui 运行时注入的带归属令牌通道 + if (typeof getHostTransport === 'function') { + const transport = getHostTransport() + if (transport) { + try { + const callOpts = typeof options?.timeoutMs === 'number' ? { timeoutMs: options.timeoutMs } : undefined + return unwrapTransportResponse(await transport.call(method, params, callOpts)) + } catch (err) { + return toTransportError(err) + } + } + } + + if (typeof window === 'undefined') { + return { ok: false, error: 'NO_WINDOW_ENV', errorCode: 'NO_WINDOW_ENV' } + } + + const w = window as unknown as WindowHostBridge + const methods = w.__ztoolsElectron?.transport?.methods || w.ztools?.transport?.methods + const fn = methods?.[method] + if (typeof fn === 'function') { + try { + const messageId = nextMessageId(method.replace(/[^A-Za-z0-9_]/g, '_').slice(0, 24)) + const payload = { + messageId, + params, + ...(typeof options?.timeoutMs === 'number' ? { timeoutMs: options.timeoutMs } : {}) + } + return unwrapTransportResponse(await fn(payload)) + } catch (err) { + return toTransportError(err) + } + } + + if (typeof w.ztools?.transport?.call === 'function') { + try { + return unwrapTransportResponse(await w.ztools.transport.call(method, params, options)) + } catch (err) { + return toTransportError(err) + } + } + + return { ok: false, error: `METHOD_NOT_AVAILABLE: ${method}`, errorCode: 'METHOD_NOT_AVAILABLE' } +} + +/** 探测宿主薄原语能力快照(tool_runtime_capabilities) */ +export async function queryRuntimeCapabilities( + hostOverride?: unknown +): Promise> { + const res = await callHostTransport('tool_runtime_capabilities', {}, hostOverride) + if (!res.ok) return res as HostTransportResult + const rec = asRecord(res.data) + if (!rec || !Array.isArray(rec.capabilities)) { + return { + ok: false, + error: 'INVALID_CAPABILITIES_SNAPSHOT', + errorCode: 'INVALID_CAPABILITIES_SNAPSHOT' + } + } + const capabilities: ToolCapabilityDescriptor[] = [] + for (const rawCap of rec.capabilities) { + const cap = asRecord(rawCap) + if (!cap || typeof cap.primitiveId !== 'string') continue + const rawStatus = cap.status + const status: ToolCapabilityStatus = + rawStatus === 'ready' || rawStatus === 'needs_provisioning' || rawStatus === 'unsupported' + ? rawStatus + : 'unsupported' + const optionalExtensions = Array.isArray(cap.optionalExtensions) + ? cap.optionalExtensions.filter((e): e is string => typeof e === 'string' && e.trim().length > 0) + : [] + capabilities.push({ + primitiveId: cap.primitiveId, + domain: typeof cap.domain === 'string' ? cap.domain : '', + summary: typeof cap.summary === 'string' ? cap.summary : '', + ipcMethods: Array.isArray(cap.ipcMethods) ? cap.ipcMethods.filter((m): m is string => typeof m === 'string') : [], + requiredPermissions: Array.isArray(cap.requiredPermissions) + ? cap.requiredPermissions.filter((p): p is string => typeof p === 'string') + : [], + status, + optionalExtensions + }) + } + const platform = + rec.platform === 'windows' || rec.platform === 'macos' || rec.platform === 'other' + ? rec.platform + : 'other' + return { + ok: true, + data: { + contractVersion: typeof rec.contractVersion === 'number' ? rec.contractVersion : 1, + platform, + domains: Array.isArray(rec.domains) ? rec.domains.filter((d): d is string => typeof d === 'string') : [], + capabilities + } + } +} + +export function findCapability( + snapshot: ToolRuntimeCapabilitiesSnapshot | null | undefined, + primitiveId: string +): ToolCapabilityDescriptor | null { + if (!snapshot) return null + return snapshot.capabilities.find((c) => c.primitiveId === primitiveId) ?? null +} + +export function hasCapabilityExtension( + snapshot: ToolRuntimeCapabilitiesSnapshot | null | undefined, + primitiveId: string, + extensionName: string +): boolean { + const cap = findCapability(snapshot, primitiveId) + return Boolean(cap && cap.optionalExtensions.includes(extensionName)) +} + +/** 按需拉取并准备指定薄原语运行组件(tool_runtime_ensure) */ +export async function ensureRuntimeCapability( + primitiveId: string, + hostOverride?: unknown +): Promise> { + return callHostTransport('tool_runtime_ensure', { primitiveId }, hostOverride) +} + +/** 顺序按需准备多个薄原语运行组件,任一项未就绪即中止并聚合 provisioned 标记 */ +export async function ensureRuntimeCapabilities( + primitiveIds: readonly string[], + hostOverride?: unknown +): Promise { + let provisionedAny = false + for (const primitiveId of primitiveIds) { + const res = await ensureRuntimeCapability(primitiveId, hostOverride) + if (!res.ok || !res.data || res.data.status !== 'ready') { + return { + ok: false, + status: res.data?.status ?? 'unsupported', + provisioned: provisionedAny, + failedPrimitiveId: primitiveId, + error: res.error, + errorCode: res.errorCode, + errorDetails: res.errorDetails + } + } + if (res.data.provisioned) provisionedAny = true + } + return { ok: true, status: 'ready', provisioned: provisionedAny } +} + +/** 取消正在执行的宿主薄原语任务(tool_task_cancel) */ +export async function cancelRuntimeTask( + taskId: string, + hostOverride?: unknown +): Promise> { + return callHostTransport('tool_task_cancel', { taskId }, hostOverride) +} + +/** 判断错误码是否表示用户主动取消任务 */ +export function isTaskCancelledCode(errorCode?: string): boolean { + const code = (errorCode || '').trim().toUpperCase() + return code === 'TOOL_TASK_CANCELLED' || code === 'CANCELLED' || code === 'OPERATION_CANCELLED' +} + +/** 执行单个媒体转码任务(tool_media_transcode_run),统一处理取消与产物字节数校验 */ +export async function runMediaTranscodeTask( + payload: Record, + hostOverride?: unknown +): Promise { + const res = await callHostTransport('tool_media_transcode_run', payload, hostOverride) + if (!res.ok) { + if (isTaskCancelledCode(res.errorCode)) { + return { status: 'cancelled' } + } + return { + status: 'failed', + error: res.error, + errorCode: res.errorCode, + errorDetails: res.errorDetails + } + } + const rec = asRecord(res.data) + const outputBytes = Number(rec?.outputBytes) + const durationMs = Number(rec?.durationMs) + if (!Number.isFinite(outputBytes) || outputBytes <= 0) { + return { status: 'failed', error: 'EMPTY_OUTPUT', errorCode: 'EMPTY_OUTPUT' } + } + return { + status: 'done', + outputBytes, + durationMs: Number.isFinite(durationMs) && durationMs >= 0 ? durationMs : 0 + } +} + +/** 订阅宿主推送的 tool_runtime_progress 任务进度事件 */ +export function subscribeRuntimeProgress( + handler: (event: ToolProgressEvent) => void +): () => void { + if (typeof window === 'undefined') return () => undefined + const w = window as unknown as WindowHostBridge + const eventsApi = w.ztools?.events + if (!eventsApi || typeof eventsApi.on !== 'function') return () => undefined + + try { + void eventsApi.subscribe?.('tool_runtime_progress') + } catch (err) { + // 某些测试桩或旧渲染层可能未提供 subscribe,继续注册 on 监听 + void err + } + + const listener = (raw: unknown) => { + const outer = asRecord(raw) + if (!outer) return + const inner = asRecord(outer.payload) ?? outer + if (typeof inner.taskId !== 'string' || typeof inner.phase !== 'string') return + handler(inner as unknown as ToolProgressEvent) + } + + const off = eventsApi.on('tool_runtime_progress', listener) + return () => { + if (typeof off === 'function') { + off() + } else if (typeof eventsApi.off === 'function') { + eventsApi.off('tool_runtime_progress', listener) + } + } +} + +/** 订阅旧版宿主 plugin_files_dropped 拖拽回退事件并返回卸载函数 */ +export function subscribeLegacyFileDrop(onDrop: (envelope: unknown) => void): () => void { + if (typeof window === 'undefined') return () => undefined + const w = window as unknown as WindowHostBridge + const eventsApi = w.ztools?.events + if (!eventsApi || typeof eventsApi.on !== 'function') return () => undefined + + const off = eventsApi.on('plugin_files_dropped', onDrop) + return () => { + if (typeof off === 'function') { + off() + } else if (typeof eventsApi.off === 'function') { + eventsApi.off('plugin_files_dropped', onDrop) + } + } +} + +/** 字节数格式化 */ +export function formatBytes(bytes: number): string { + if (!Number.isFinite(bytes) || bytes < 0) return '0 B' + if (bytes < 1024) return `${Math.round(bytes)} B` + const units = ['KB', 'MB', 'GB', 'TB'] + let value = bytes / 1024 + let idx = 0 + while (value >= 1024 && idx < units.length - 1) { + value /= 1024 + idx += 1 + } + return `${value >= 100 ? value.toFixed(0) : value >= 10 ? value.toFixed(1) : value.toFixed(2)} ${units[idx]}` +} + +/** 字节数格式化别名(兼容 archive-manager 等插件既有导出名) */ +export function formatByteCount(bytes: number): string { + return formatBytes(bytes) +} + +/** 获取系统标准目录路径(支持 Windows 与 macOS) */ +export async function getRealSystemPath( + name: 'home' | 'desktop' | 'documents' | 'downloads' | 'music' | 'pictures' | 'videos' | 'temp', + hostOverride?: unknown +): Promise { + const res = await callHostTransport('system_get_path', { name }, hostOverride) + if (res.ok && res.data) { + if (typeof res.data === 'string' && res.data.trim()) return res.data.trim() + const rec = asRecord(res.data) + if (rec && typeof rec.path === 'string' && rec.path.trim()) return rec.path.trim() + } + return '' +} + +/** 读取剪贴板文本 */ +export async function readRealClipboardText(hostOverride?: unknown): Promise { + const res = await callHostTransport('clipboard_read_text', {}, hostOverride) + if (res.ok && res.data !== undefined && res.data !== null) { + if (typeof res.data === 'string') return res.data + const rec = asRecord(res.data) + if (rec && typeof rec.text === 'string') return rec.text + } + return '' +} + +/** 写入剪贴板文本 */ +export async function writeRealClipboardText(text: string, hostOverride?: unknown): Promise { + const res = await callHostTransport('clipboard_copy_text', { text: String(text || '') }, hostOverride) + return res.ok +} + +/** 在系统文件管理器中显示文件 */ +export async function showRealItemInFolder(fullPath: string, hostOverride?: unknown): Promise { + if (!fullPath) return false + const res = await callHostTransport('shell_show_item_in_folder', { fullPath }, hostOverride) + return res.ok +} + +/** 用系统默认应用打开文件或文件夹 */ +export async function openRealPath(fullPath: string, hostOverride?: unknown): Promise { + if (!fullPath) return false + const res = await callHostTransport('shell_open_path', { fullPath }, hostOverride) + return res.ok +} + +/** 将文件或目录移入系统回收站 */ +export async function trashRealItem(fullPath: string, hostOverride?: unknown): Promise<{ ok: boolean; error?: string }> { + if (!fullPath) return { ok: false, error: 'EMPTY_PATH' } + const res = await callHostTransport('shell_trash_item', { fullPath }, hostOverride) + return res.ok ? { ok: true } : { ok: false, error: res.error } +} + +/** 通过 window_show_open_dialog 选择输出目录(兼容 Windows 与 macOS) */ +export async function pickOutputDirectoryDialog( + options: { title: string; defaultPath?: string }, + hostOverride?: unknown +): Promise<{ canceled: boolean; directoryPath?: string; error?: string; errorCode?: string }> { + const params: Record = { + title: options.title, + properties: ['openDirectory', 'createDirectory'] + } + if (options.defaultPath) params.defaultPath = options.defaultPath + const res = await callHostTransport('window_show_open_dialog', params, hostOverride) + if (!res.ok) { + return { canceled: false, error: res.error || 'OPEN_DIALOG_FAILED', errorCode: res.errorCode } + } + const rec = asRecord(res.data) + if (!rec) return { canceled: false, error: 'INVALID_DIALOG_RESULT' } + if (rec.canceled === true) return { canceled: true } + const firstPath = + (Array.isArray(rec.filePaths) && typeof rec.filePaths[0] === 'string' && rec.filePaths[0].trim()) || + (typeof rec.filePath === 'string' && rec.filePath.trim()) || + (typeof rec.folderPath === 'string' && rec.folderPath.trim()) || + '' + if (!firstPath) return { canceled: false, error: 'NO_DIRECTORY_SELECTED' } + return { canceled: false, directoryPath: firstPath } +} + +/** 通用文件/目录选择对话框(支持自定义 properties 与 filters) */ +export async function openDialogSelectPaths( + options: { + title: string + properties: Array<'openFile' | 'openDirectory' | 'multiSelections' | 'createDirectory'> + filters?: Array<{ name: string; extensions: string[] }> + }, + hostOverride?: unknown +): Promise<{ canceled: boolean; paths: string[]; error?: string }> { + const params: Record = { + title: options.title, + properties: options.properties, + ...(options.filters ? { filters: options.filters } : {}) + } + const res = await callHostTransport('window_show_open_dialog', params, hostOverride) + if (!res.ok) return { canceled: false, paths: [], error: res.error || 'OPEN_DIALOG_FAILED' } + const rec = asRecord(res.data) + if (!rec) return { canceled: false, paths: [], error: 'INVALID_DIALOG_RESPONSE' } + if (rec.canceled === true) return { canceled: true, paths: [] } + const paths = Array.isArray(rec.filePaths) + ? rec.filePaths.filter((p): p is string => typeof p === 'string' && p.trim().length > 0).map((p) => p.trim()) + : typeof rec.filePath === 'string' && rec.filePath.trim() + ? [rec.filePath.trim()] + : [] + return { canceled: false, paths } +} + +/** 选择待归档的源文件或目录列表(多选) */ +export async function pickAnySourcesDialog( + options: { title: string; directories?: boolean }, + hostOverride?: unknown +): Promise<{ canceled: boolean; paths: string[]; error?: string }> { + return openDialogSelectPaths( + { + title: options.title, + properties: options.directories ? ['openDirectory', 'multiSelections'] : ['openFile', 'multiSelections'] + }, + hostOverride + ) +} + +/** 保存归档文件对话框(zip / 7z / tar) */ +export async function pickSaveArchiveDialog( + options: { title: string; defaultPath?: string; format: 'zip' | '7z' | 'tar' }, + hostOverride?: unknown +): Promise<{ canceled: boolean; filePath?: string; error?: string }> { + const ext = options.format === '7z' ? '7z' : options.format === 'tar' ? 'tar' : 'zip' + const params: Record = { + title: options.title, + filters: [{ name: `${ext.toUpperCase()} Archive`, extensions: [ext] }] + } + if (options.defaultPath) params.defaultPath = options.defaultPath + const res = await callHostTransport('window_show_save_dialog', params, hostOverride) + if (!res.ok) return { canceled: false, error: res.error || 'SAVE_DIALOG_FAILED' } + const rec = asRecord(res.data) + if (!rec) return { canceled: false, error: 'INVALID_SAVE_DIALOG' } + if (rec.canceled === true) return { canceled: true } + const filePath = typeof rec.filePath === 'string' ? rec.filePath.trim() : '' + if (!filePath) return { canceled: true } + return { canceled: false, filePath } +} diff --git a/extensions/batch-image/tests/batch-image.host.test.mjs b/extensions/batch-image/tests/batch-image.host.test.mjs index a45f4527..7d7f921c 100644 --- a/extensions/batch-image/tests/batch-image.host.test.mjs +++ b/extensions/batch-image/tests/batch-image.host.test.mjs @@ -4,394 +4,153 @@ import fs from 'node:fs' import path from 'node:path' import { fileURLToPath } from 'node:url' import { setRuntimeLocale } from '@ztools/declarative-ui' +import * as batchImage from '../dist/index.js' setRuntimeLocale('zh-CN') -const batchImage = await import('../dist/index.js') - const pluginDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..') -const GOV_PRESET = batchImage.getImageWorkshopPresets().find((p) => p.id === 'preset-extreme-300k') -const DEFAULT_PRESET = batchImage.getImageWorkshopPresets()[0] - -function settingsOf(preset) { - return { - method: preset.method, - outputFormat: preset.defaultFormat, - qualityTier: preset.defaultQuality, - resizePreset: preset.defaultResize, - grayscale: preset.grayscale, - sizeLimitBytes: preset.sizeLimitBytes - } -} -async function withRealElectronWindow(handlers, fn) { - const prevWindow = globalThis.window +function makeImageHost() { const calls = [] - const transportMethods = {} - - for (const [channel, impl] of Object.entries(handlers)) { - transportMethods[channel] = async (envelope) => { - const actualParams = - envelope && typeof envelope === 'object' && 'params' in envelope && 'messageId' in envelope - ? envelope.params - : envelope - calls.push({ channel, payload: actualParams }) - return impl(actualParams) - } - } - - globalThis.window = { - __ztoolsElectron: { - transport: { - methods: transportMethods + const host = { + filesystem_file_exists: async () => ({ success: true, exists: false }), + tool_image_inspect: async (params) => { + calls.push({ method: 'tool_image_inspect', params }) + return { + success: true, + data: { + items: [ + { + displayName: 'photo.jpg', + format: 'jpeg', + width: 4032, + height: 3024, + sizeBytes: 1850000, + colorSpace: 'sRGB', + hasAlpha: false, + hasExif: true, + exif: { Make: 'Canon', GPSLatitude: '31.2304', DateTimeOriginal: '2026:10:01 10:00:00' } + } + ] + } } - } - } - - try { - return await fn(calls) - } finally { - if (prevWindow === undefined) { - delete globalThis.window - } else { - globalThis.window = prevWindow - } - } -} - -/** 与宿主 BatchImagePlugin 单张成功时的返回结构一致(路由层会再包一层 data) */ -function hostSuccess(call, { outputBytes = 120000, originalBytes = 400000, width = 1280, height = 720 } = {}) { - const record = { - ok: true, - success: true, - processedCount: 1, - outputPath: call.params.outputPath, - sizeBytes: outputBytes, - outputBytes, - savedBytes: Math.max(0, originalBytes - outputBytes), - results: [ - { - sourcePath: call.params.files[0], - outputPath: call.params.outputPath, - width, - height, - originalBytes, - sizeBytes: outputBytes, - outputBytes, - savedBytes: Math.max(0, originalBytes - outputBytes) + }, + tool_image_process: async (params) => { + calls.push({ method: 'tool_image_process', params }) + return { + success: true, + data: { + taskId: params.taskId, + outputBytes: 185000, + width: params.width || 1920, + height: params.height || 1080, + format: params.format || 'jpeg', + exifStripped: Boolean(params.stripExif), + ...(params.toBase64 ? { base64DataUrl: 'data:image/jpeg;base64,/9j/4AAQSkZJRg==' } : {}) + } } - ], - errors: [] - } - return { ...record, data: { ...record } } -} - -/** 与宿主单张失败时的返回结构一致 */ -function hostFailure(call, message) { - return { - ok: false, - success: false, - processedCount: 0, - results: [], - errors: [{ file: call.params.files[0], error: message }], - error: message - } -} - -function makeHost({ existing = [], exists = 'answer', process }) { - const calls = [] - const existingSet = new Set(existing.map((p) => p.toLowerCase())) - const host = { - dllplugin_call: async (call) => { - calls.push(call) - return process(call, calls.length) - } - } - if (exists === 'answer') { - host.filesystem_file_exists = async ({ path: p }) => ({ success: true, exists: existingSet.has(p.toLowerCase()) }) - } else if (exists === 'denied') { - host.filesystem_file_exists = async () => { - throw Object.assign(new Error('路径未由当前窗口授权'), { code: 'PERMISSION_DENIED' }) + }, + tool_document_pdf_transform: async (params) => { + calls.push({ method: 'tool_document_pdf_transform', params }) + return { + success: true, + data: { + taskId: params.taskId, + outputBytes: 512000, + pageCount: params.inputs.length, + outputFiles: [params.output.path] + } + } + }, + tool_runtime_ensure: async (params) => { + calls.push({ method: 'tool_runtime_ensure', params }) + return { success: true, data: { primitiveId: params.primitiveId, status: 'ready', provisioned: true } } + }, + tool_task_cancel: async (params) => { + calls.push({ method: 'tool_task_cancel', params }) + return { success: true, data: { taskId: params.taskId, cancelled: true } } } } return { host, calls } } -test('batch-image 导入规则与处理跳过:支持 8 种格式、排除 _opt 输出文件并支持 shouldSkip 跳过已移除条目', async () => { - assert.deepEqual( - [...batchImage.IMAGE_IMPORT_EXTENSIONS], - ['.png', '.jpg', '.jpeg', '.webp', '.bmp', '.gif', '.tiff', '.avif'] - ) - assert.equal(batchImage.IMAGE_IMPORT_RULES.excludeFile?.('photo_opt.png', 'D:\\Pics\\photo_opt.png'), true) - assert.equal(batchImage.IMAGE_IMPORT_RULES.excludeFile?.('photo_opt_2.jpg', 'D:\\Pics\\photo_opt_2.jpg'), true) - assert.equal(batchImage.IMAGE_IMPORT_RULES.excludeFile?.('photo_opt_20261116120000.avif', 'D:\\Pics\\photo_opt_20261116120000.avif'), true) - assert.equal(batchImage.IMAGE_IMPORT_RULES.excludeFile?.('my_opt_sample.png', 'D:\\Pics\\my_opt_sample.png'), false) - assert.equal(batchImage.IMAGE_IMPORT_RULES.forbiddenPath?.test('C:\\Windows\\System32\\a.png'), true) - - // shouldSkip 命中时不再调用宿主也不产出结果 - const { host, calls } = makeHost({ process: (call) => hostSuccess(call) }) - const started = [] - const outcomes = await batchImage.processImageBatch( - [ - { id: '1', path: 'D:\\Pics\\a.png', sizeBytes: 1000 }, - { id: '2', path: 'D:\\Pics\\b.png', sizeBytes: 1000 } - ], - settingsOf(DEFAULT_PRESET), - { - hostOverride: host, - shouldSkip: (id) => id === '2', - onStart: (id) => started.push(id) - } - ) - assert.deepEqual(started, ['1']) - assert.equal(calls.length, 1) - assert.equal(outcomes.has('1'), true) - assert.equal(outcomes.has('2'), false) +test('batch-image: 清单与源码彻底去 DLL 化,声明 image.* 与 document.pdf.transform 原语且一期仅 Windows', () => { + const manifest = JSON.parse(fs.readFileSync(path.join(pluginDir, 'plugin.json'), 'utf8')) + assert.deepEqual(manifest.requiredCapabilities, ['image.inspect', 'image.process', 'document.pdf.transform']) + assert.equal(manifest.minAppVersion, '1.3.0.4') + assert.deepEqual(manifest.nativeComponents, []) + assert.deepEqual(manifest.targets.map((t) => t.id), ['windows-electron-any']) + for (const perm of ['media.read', 'media.process', 'fs', 'dialog', 'clipboard']) { + assert.ok(manifest.permissions.includes(perm)) + } + const logicSrc = fs.readFileSync(path.join(pluginDir, 'src/logic.ts'), 'utf8') + assert.equal(logicSrc.includes('dllplugin_call'), false) + assert.equal(logicSrc.includes('BatchImagePlugin'), false) }) -test('batch-image beyond happy path: 参数异常、路径穿越拦截、损坏 JSON 与宿主故障注入', async () => { - // 1. 空方法名与非法字符拦截 - await assert.rejects( - () => batchImage.invokeNativeCapability('', { qualityTier: 'q85' }), - /INVALID_METHOD/ - ) - await assert.rejects( - () => batchImage.invokeNativeCapability('BatchCompress;rm -rf', { qualityTier: 'q85' }), - /INVALID_METHOD_FORMAT/ - ) - - // 2. 空值与数组参数拦截 - await assert.rejects( - () => batchImage.invokeNativeCapability('BatchCompressImage', null), - /INVALID_PARAMS/ - ) - await assert.rejects( - () => batchImage.invokeNativeCapability('BatchCompressImage', []), - /INVALID_PARAMS/ - ) - - // 3. 系统受保护路径与路径穿越拦截 - await assert.rejects( - () => - batchImage.invokeNativeCapability('BatchCompressImage', { - outputDir: 'C:\\Windows\\System32\\drivers' - }), - /SECURITY_INTERCEPTED/ - ) - await assert.rejects( - () => - batchImage.invokeNativeCapability('BatchCompressImage', { - outputDir: 'D:\\Pictures\\..\\..\\Windows\\System32' - }), - /SECURITY_INTERCEPTED/ - ) - - // 4. 负数与越界极值拦截 - await assert.rejects( - () => batchImage.invokeNativeCapability('BatchCompressImage', { maxEdge: -100 }), - /PARAM_OUT_OF_RANGE/ - ) - await assert.rejects( - () => batchImage.invokeNativeCapability('BatchCompressImage', { path: 'x'.repeat(5000) }), - /PARAM_TOO_LONG/ - ) - - // 5. 宿主 IPC 抛出磁盘满或解码失败时,严禁伪造成功或返回 simulated: true - await withRealElectronWindow( - { - dllplugin_call: () => { - throw new Error('ENOSPC: 磁盘空间不足,无法写入压缩图片') - } - }, - async () => { - const failRes = await batchImage.invokeNativeCapability('BatchCompressImage', { - qualityTier: 'q85' - }) - assert.equal(failRes.ok, false) - assert.match(String(failRes.error), /ENOSPC/) - assert.equal(failRes.data?.simulated, undefined) - } - ) +test('batch-image: 单图深度检查(合并自 image-tool)、真实 stripExif、转 Base64 与生成 ICO', async () => { + const { host, calls } = makeImageHost() + const photo = { path: 'D:\\Photos\\photo.jpg', sizeBytes: 1850000 } + + // 1. 单图深度检查(含尺寸、色彩空间、EXIF/GPS 标签) + const inspected = await batchImage.inspectImageMetadata(photo.path, host) + assert.equal(inspected.ok, true) + assert.equal(inspected.metadata.width, 4032) + assert.equal(inspected.metadata.colorSpace, 'sRGB') + assert.equal(inspected.metadata.hasExif, true) + assert.equal(inspected.metadata.exif.GPSLatitude, '31.2304') + + // 2. 一键抹除隐私 EXIF(真实断言 tool_image_process 传入 stripExif: true 且返回 exifStripped: true) + const stripped = await batchImage.stripImageExif(photo, host) + assert.equal(stripped.status, 'done') + assert.equal(stripped.exifStripped, true) + const stripCall = calls.find((c) => c.method === 'tool_image_process') + assert.equal(stripCall.params.stripExif, true) + assert.equal(stripCall.params.overwrite, false) + + // 3. 转 Base64 Data URL + const b64 = await batchImage.convertImageToBase64(photo, host) + assert.equal(b64.ok, true) + assert.match(b64.dataUrl, /^data:image\/jpeg;base64,/) + const b64Call = calls.filter((c) => c.method === 'tool_image_process')[1] + assert.equal(b64Call.params.toBase64, true) + + // 4. 生成 ICO / Favicon + const ico = await batchImage.generateImageIco(photo, host) + assert.equal(ico.status, 'done') + const icoCall = calls.filter((c) => c.method === 'tool_image_process')[2] + assert.equal(icoCall.params.format, 'ico') + assert.equal(icoCall.params.width, 256) + assert.equal(icoCall.params.height, 256) }) -test('batch-image 逐张处理:参数映射到宿主真实取值,输出前避开已存在与同批次重名的文件', async () => { - const { host, calls } = makeHost({ - existing: ['D:\\Pics\\photo_opt.jpg'], - process: (call, n) => hostSuccess(call, { outputBytes: n === 1 ? 120000 : 350000, originalBytes: 400000 }) - }) +test('batch-image: 多图批量处理与真实嵌图合并 PDF(调用 tool_document_pdf_transform images-to-pdf)', async () => { + const { host, calls } = makeImageHost() const files = [ - { id: 'a', path: 'D:\\Pics\\photo.png', sizeBytes: 400000 }, - { id: 'b', path: 'D:\\Pics\\photo.jpg', sizeBytes: 400000 } + { id: '1', name: 'a.png', path: 'D:\\Pics\\a.png', parentDir: 'D:\\Pics', extension: '.png', sizeBytes: 500000 }, + { id: '2', name: 'b.webp', path: 'D:\\Pics\\b.webp', parentDir: 'D:\\Pics', extension: '.webp', sizeBytes: 600000 } ] - const seen = [] - const outcomes = await batchImage.processImageBatch(files, settingsOf(GOV_PRESET), { - hostOverride: host, - onItem: (id) => seen.push(id) - }) - - assert.deepEqual(seen, ['a', 'b'], '每张完成后回调一次') - assert.equal(calls.length, 2, '每张图片单独调用一次宿主') - for (const call of calls) { - assert.equal(call.plugin, 'BatchImagePlugin') - assert.equal(call.params.files.length, 1) - assert.equal(call.params.qualityTier, 'q70', '画质档位必须是宿主识别的 q70 / q85 / q95') - assert.equal(call.params.resizePreset, 'max1280', '尺寸约束必须是宿主识别的缩放预设') - assert.equal(call.params.outputFormat, 'jpg') - assert.equal('stripExif' in call.params, false, '宿主不支持的参数不再发送') - assert.equal('maxEdge' in call.params, false) - } - assert.equal(calls[0].params.outputPath, 'D:\\Pics\\photo_opt_2.jpg', '已存在 photo_opt.jpg 时换名') - assert.equal(calls[1].params.outputPath, 'D:\\Pics\\photo_opt_3.jpg', '同一批次已分配的名称不再复用') - - const first = outcomes.get('a') - assert.equal(first.status, 'done') - assert.equal(first.outputPath, 'D:\\Pics\\photo_opt_2.jpg') - assert.equal(first.outputBytes, 120000) - assert.equal(first.overLimitBytes, null) - assert.equal(batchImage.describeOutcomeTag(first), '已输出 117 KB (-70%)') - - const second = outcomes.get('b') - assert.equal(second.status, 'done') - assert.equal(second.overLimitBytes, 300 * 1024, '超过 300KB 的输出必须如实标出') - assert.equal(batchImage.describeOutcomeTag(second), '超过 300 KB') - - const summary = batchImage.summarizeOutcomes(outcomes.values()) - assert.equal(summary.done, 2) - assert.equal(summary.failed, 0) - assert.equal(summary.overLimit, 1) - assert.equal(summary.outputBytes, 470000) - assert.equal(summary.savedBytes, 330000) -}) - -test('batch-image 输出命名:宿主无法确认同名文件时改用带批次时间的名称,绝不使用可能已存在的 _opt 名称', async () => { - for (const mode of ['denied', 'missing']) { - const { host, calls } = makeHost({ exists: mode, process: (call) => hostSuccess(call) }) - const outcomes = await batchImage.processImageBatch( - [ - { id: 'a', path: 'D:\\Pics\\scan.png', sizeBytes: 400000 }, - { id: 'b', path: 'D:\\Pics\\scan.PNG.bak.png', sizeBytes: 400000 } - ], - settingsOf(DEFAULT_PRESET), - { hostOverride: host, batchTag: '20261028120000' } - ) - assert.equal(calls[0].params.outputPath, 'D:\\Pics\\scan_opt_20261028120000.png', `${mode}: 应使用带时间标记的名称`) - assert.equal(calls[1].params.outputPath, 'D:\\Pics\\scan.PNG.bak_opt_20261028120000.png') - assert.equal(calls[0].params.qualityTier, 'q85') - assert.equal(calls[0].params.resizePreset, 'source') - assert.equal(calls[0].params.outputFormat, 'keep') - assert.equal(outcomes.get('a').status, 'done') - } - - // 同一批次两张图映射到同一个带时间标记的名称时追加序号 - const reserved = new Set() - const p1 = await batchImage.chooseOutputPath('D:\\x\\a.png', '.jpg', reserved, 'T1', {}) - const p2 = await batchImage.chooseOutputPath('D:\\x\\a.jpg', '.jpg', reserved, 'T1', {}) - assert.equal(p1, 'D:\\x\\a_opt_T1.jpg') - assert.equal(p2, 'D:\\x\\a_opt_T1_2.jpg') -}) - -test('batch-image 失败路径:单张失败如实记录并继续处理其余图片,宿主"成功"但无结果时不报成功', async () => { - const { host, calls } = makeHost({ - process: (call, n) => { - if (n === 1) return hostFailure(call, '图片编码转换失败: a.webp(GDI+:不支持编码 .webp 格式;ffmpeg:本机未检测到 ffmpeg)') - if (n === 2) return { ok: true, success: true, processedCount: 1, results: [], errors: [] } - if (n === 3) return { ok: true, success: true, results: [{ sourcePath: call.params.files[0], outputPath: '', outputBytes: 0 }] } - if (n === 4) throw new Error('ENOSPC: 磁盘空间不足') - return hostSuccess(call, { outputBytes: 500000, originalBytes: 500000, width: 0, height: 0 }) - } - }) - const files = ['a.webp', 'b.png', 'c.png', 'd.png', 'e.png'].map((name, i) => ({ - id: `f${i}`, - path: `D:\\Pics\\${name}`, - sizeBytes: 500000 - })) - const outcomes = await batchImage.processImageBatch(files, settingsOf(DEFAULT_PRESET), { hostOverride: host }) - assert.equal(calls.length, 5, '单张失败不能中断整批') - - const a = outcomes.get('f0') - assert.equal(a.status, 'failed') - assert.match(a.error, /本机未检测到 ffmpeg/) - assert.equal(batchImage.describeOutcomeTag(a), '失败') - assert.match(batchImage.describeOutcomeDetail(a, 'D:\\Pics'), /^失败原因:.*ffmpeg/) - - assert.equal(outcomes.get('f1').status, 'failed') - assert.match(outcomes.get('f1').error, /未返回处理结果/) - assert.equal(outcomes.get('f2').status, 'failed') - assert.match(outcomes.get('f2').error, /缺少输出文件路径或大小/) - assert.equal(outcomes.get('f3').status, 'failed') - assert.match(outcomes.get('f3').error, /ENOSPC/) - - const e = outcomes.get('f4') - assert.equal(e.status, 'done') - assert.equal(e.notSmaller, true, '输出不小于原图时标为未变小') - assert.match(batchImage.describeOutcomeTag(e), /^未变小/) - assert.match(batchImage.describeOutcomeDetail(e, 'D:\\Pics'), /尺寸未识别/, '宿主读不到尺寸时显示未识别,不填默认分辨率') - const summary = batchImage.summarizeOutcomes(outcomes.values()) - assert.equal(summary.done, 1) - assert.equal(summary.failed, 4) - assert.equal(summary.notSmaller, 1) - assert.match(summary.firstError, /ffmpeg/) - assert.equal(summary.savedBytes, 0) -}) - -test('batch-image 扩展名识别不到时不调用宿主,直接如实失败', async () => { - const { host, calls } = makeHost({ process: (call) => hostSuccess(call) }) - const outcome = await batchImage.processImageFile( - { path: 'D:\\Pics\\noext', sizeBytes: 100 }, - settingsOf(DEFAULT_PRESET), - new Set(), - 'T', + const outcomes = await batchImage.processImageBatch( + files, + { outputFormat: 'jpeg', qualityTier: 'q70', resizePreset: 'max1280', stripExif: true, rotate: 90, flip: 'horizontal' }, + {}, host ) - assert.equal(outcome.status, 'failed') - assert.match(outcome.error, /无法识别图片扩展名/) - assert.equal(calls.length, 0) - assert.equal(batchImage.resolveTargetExtension('D:\\a\\b.JPEG', 'keep'), '.jpeg') - assert.equal(batchImage.resolveTargetExtension('D:\\a\\b.JPEG', 'png'), '.png') -}) - -test('batch-image 剪贴板路径解析与文件大小读取:只认绝对路径图片,读不到大小标为 null', async () => { - const parsed = batchImage.parseClipboardImagePaths( - '"D:\\Shots\\a.png"\r\nrelative\\b.png\nD:\\Docs\\notes.txt\n \'E:\\c.JPG\' \n"D:\\Shots\\a.png"\n/Users/x/d.webp' - ) - assert.deepEqual(parsed, ['D:\\Shots\\a.png', 'E:\\c.JPG', '/Users/x/d.webp']) - assert.deepEqual(batchImage.parseClipboardImagePaths(''), []) - assert.deepEqual(batchImage.parseClipboardImagePaths('hello world'), []) - - assert.equal(await batchImage.readImageFileSize('D:\\a.png', { filesystem_get_file_size: async () => ({ success: true, size: 2048 }) }), 2048) - assert.equal(await batchImage.readImageFileSize('D:\\a.png', { filesystem_get_file_size: async () => 4096 }), 4096) - assert.equal( - await batchImage.readImageFileSize('D:\\a.png', { - filesystem_get_file_size: async () => { - throw new Error('路径未由当前窗口授权') - } - }), - null - ) - assert.equal(await batchImage.readImageFileSize('D:\\a.png', { filesystem_get_file_size: async () => ({ success: true }) }), null) -}) - -test('batch-image 能力声明:去掉宿主做不到的合并 PDF 与清除 EXIF,界面选项只含宿主支持的取值', () => { - const presets = batchImage.getImageWorkshopPresets() - const methods = presets.map((p) => p.method) - assert.equal(methods.includes('MergeImagesToPdf'), false) - const ids = presets.map((p) => p.id) - assert.equal(ids.includes('preset-merge-pdf'), false) - assert.equal(ids.includes('preset-strip-exif'), false) - assert.deepEqual(batchImage.getFormatOptions().map((o) => o.value), ['keep', 'jpg', 'png']) - assert.deepEqual(batchImage.getQualityOptions().map((o) => o.value).sort(), ['q70', 'q85', 'q95']) - assert.deepEqual(batchImage.getResizeOptions().map((o) => o.value), ['source', 'max1920', 'max1280']) - - const presetText = JSON.stringify(presets) - assert.equal(/无损瘦身|视觉无损|EXIF|PDF|去除.*阴影/.test(presetText), false, '方案说明不能保留做不到的说法') - - const manifest = JSON.parse(fs.readFileSync(path.join(pluginDir, 'plugin.json'), 'utf8')) - const codes = manifest.features.map((f) => f.code) - assert.equal(codes.includes('preset-merge-pdf'), false) - assert.equal(codes.includes('preset-strip-exif'), false) - assert.equal(/无损|PDF|隐私|EXIF|HEIC/i.test(manifest.description), false) - for (const f of manifest.features) { - assert.equal(/无损|pdf|exif|heic/i.test(`${f.explain} ${f.cmds.join(' ')}`), false, `${f.code} 不能声明做不到的能力`) - } - assert.equal(manifest.draft, undefined, '内置插件不能标草稿') + assert.equal(outcomes.size, 2) + const procCalls = calls.filter((c) => c.method === 'tool_image_process') + assert.equal(procCalls.length, 2) + assert.equal(procCalls[0].params.stripExif, true) + assert.equal(procCalls[0].params.rotate, 90) + assert.equal(procCalls[0].params.flip, 'horizontal') + assert.equal(procCalls[0].params.width, 1280) + + // 真实嵌图合 PDF(根除历史仅写文件名的假实现) + const pdfRes = await batchImage.mergeImagesToPdf(files, { outputPath: 'D:\\Pics\\album.pdf' }, host) + assert.equal(pdfRes.ok, true) + assert.equal(pdfRes.pageCount, 2) + assert.equal(pdfRes.outputBytes, 512000) + const pdfCall = calls.find((c) => c.method === 'tool_document_pdf_transform') + assert.equal(pdfCall.params.operation, 'images-to-pdf') + assert.deepEqual(pdfCall.params.inputs, [{ path: 'D:\\Pics\\a.png' }, { path: 'D:\\Pics\\b.webp' }]) + assert.deepEqual(pdfCall.params.output, { path: 'D:\\Pics\\album.pdf' }) }) diff --git a/extensions/batch-image/tests/batch-image.ui.test.mjs b/extensions/batch-image/tests/batch-image.ui.test.mjs index f9242cd7..633ed9f5 100644 --- a/extensions/batch-image/tests/batch-image.ui.test.mjs +++ b/extensions/batch-image/tests/batch-image.ui.test.mjs @@ -1,455 +1,36 @@ import test from 'node:test' import assert from 'node:assert/strict' -import fs from 'node:fs' -import os from 'node:os' -import path from 'node:path' -import { createHost, installDirectoryHost, mount, tick } from '../../shared/test-harness.mjs' +import { setRuntimeLocale } from '@ztools/declarative-ui' +import { createHost, mount, tick } from '../../shared/test-harness.mjs' import BatchImageCommand from '../dist/index.js' -const POSTER = 'D:\\TestMedia\\pictures\\design_poster_4k.png' -const RECEIPT = 'D:\\TestMedia\\pictures\\receipt_scan.jpg' +setRuntimeLocale('zh-CN') +const host = createHost() -function makeTempTree(spec) { - const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ztools-batch-image-')) - for (const [rel, content] of Object.entries(spec)) { - const full = path.join(root, rel) - fs.mkdirSync(path.dirname(full), { recursive: true }) - fs.writeFileSync(full, content) - } - return root -} - -/** 与宿主单张成功时的返回结构一致(路由层会再包一层 data) */ -function hostSuccess(params, { outputBytes = 380000, originalBytes = 1048576, width = 1920, height = 1080 } = {}) { - const record = { - ok: true, - success: true, - processedCount: 1, - outputPath: params.outputPath, - outputBytes, - results: [ - { - sourcePath: params.files[0], - outputPath: params.outputPath, - width, - height, - originalBytes, - sizeBytes: outputBytes, - outputBytes, - savedBytes: Math.max(0, originalBytes - outputBytes) - } - ], - errors: [] - } - return { ...record, data: { ...record } } -} - -function hostFailure(params, message) { - return { ok: false, success: false, processedCount: 0, results: [], errors: [{ file: params.files[0], error: message }], error: message } -} - -function tagOf(item) { - return item.props.accessories.find((a) => a.tag)?.tag?.value -} - -function filterBarActions(view) { - const fb = view.tree().props.filterBar - return fb?.props?.actions ?? fb?.actions ?? [] -} - -function summaryTextOf(view) { - const fb = view.tree().props.filterBar - return String(fb?.props?.summaryText ?? fb?.summaryText ?? '') -} - -function subItems(view) { - return view.tree().props.subList?.items ?? [] -} - -test('batch-image UI 挂载零扫盘:初始为空列表、顶栏恰为 2 个按钮、空状态动作顺序正确', async () => { - const host = createHost() - const view = await mount(BatchImageCommand, host) - await tick(10) - - const bannedMethods = new Set([ - 'system_get_path', - 'system_list_common_folders', - 'system_search_files', - 'filesystem_get_directory_contents', - 'dllplugin_call' - ]) - assert.deepEqual( - host.ipcCalls.filter(([m]) => bannedMethods.has(m)), - [], - '挂载时绝不能触发任何扫盘或原生处理调用' - ) - assert.equal(subItems(view).length, 0) - const actions = filterBarActions(view) - assert.deepEqual( - actions.map((a) => ({ id: a.id, label: a.label })), - [ - { id: 'pick-files', label: '选择文件' }, - { id: 'pick-folder', label: '选择文件夹' } - ] - ) - assert.match(summaryTextOf(view), /尚未添加图片/) - assert.deepEqual( - view.actions().map((a) => a.props.title), - ['选择文件…', '选择文件夹…', '从剪贴板添加'] - ) - assert.equal(/[\u{1F300}-\u{1FAFF}]/u.test(view.text()), false, 'UI 文本严禁包含彩色 Emoji') - view.unmount() - - // 不在 ZTools 客户端中时如实提示 - const prevWin = globalThis.window - delete globalThis.window - try { - const outOfClient = BatchImageCommand() - assert.match(outOfClient.props.subList.emptyText, /需要在 ZTools 客户端中使用/) - } finally { - globalThis.window = prevWin - } +test.beforeEach(() => { + host.reset() }) -test('batch-image UI 选择文件与选择文件夹:覆盖多选、取消、报错翻译、递归过滤、排除 _opt、整盘确认与截断提示', async () => { - const root = makeTempTree({ - 'a.png': 'aa', - 'b.avif': 'bb', - 'c.tiff': 'cc', - 'nested/d.webp': 'dd', - 'nested/a_opt.png': 'opt', - 'nested/a_opt_20261116120000.jpg': 'opt2', - 'readme.txt': 'txt' - }) - - try { - const host = createHost() - await installDirectoryHost(host, { authorized: [root] }) - host.ipc.filesystem_get_file_size = async ({ path: p }) => ({ - success: true, - size: fs.existsSync(p) ? fs.statSync(p).size : 4096 - }) - - const view = await mount(BatchImageCommand, host) - await tick(5) - - // 1. 选择文件取消不弹提示 - host.ipc.window_show_open_dialog = async () => ({ canceled: true }) - await filterBarActions(view).find((a) => a.id === 'pick-files').onAction() - await tick(10) - assert.equal(host.toasts.length, 0) - - // 2. 选择文件报错翻译 - host.ipc.window_show_open_dialog = async () => { - throw new Error('当前窗口的文件 capability 数量超过上限') - } - await filterBarActions(view).find((a) => a.id === 'pick-files').onAction() - await tick(10) - assert.equal(host.lastToast()?.title, '导入失败') - assert.match(String(host.lastToast()?.message), /改用「选择文件夹」/) - - // 3. 选择文件成功(同时验证向宿主传递全部 8 种扩展名过滤串) - const singleFile = path.join(root, 'a.png') - let openDialogParams = null - host.ipc.window_show_open_dialog = async (params) => { - openDialogParams = params - return { canceled: false, filePaths: [singleFile] } +test('batch-image UI: 挂载后探测能力,零 dllplugin_call', async () => { + host.ipc.tool_runtime_capabilities = () => ({ + success: true, + data: { + contractVersion: 1, + platform: 'windows', + domains: ['image', 'document'], + capabilities: [ + { primitiveId: 'image.inspect', domain: 'image', summary: 'inspect', ipcMethods: ['tool_image_inspect'], requiredPermissions: ['media.read'], status: 'ready', optionalExtensions: [] }, + { primitiveId: 'image.process', domain: 'image', summary: 'process', ipcMethods: ['tool_image_process'], requiredPermissions: ['media.process'], status: 'ready', optionalExtensions: [] } + ] } - await filterBarActions(view).find((a) => a.id === 'pick-files').onAction() - await tick(10) - assert.equal( - openDialogParams.filters, - '图片文件|png;jpg;jpeg;webp;bmp;gif;tiff;avif' - ) - assert.equal(host.lastToast()?.title, '已添加 1 个文件') - assert.equal(subItems(view).length, 1) - - // 4. 选择整个磁盘根目录时触发确认弹窗;取消不遍历 - host.setConfirm(false) - host.ipc.window_show_select_folder_dialog = async () => ({ canceled: false, folderPath: 'D:\\' }) - await filterBarActions(view).find((a) => a.id === 'pick-folder').onAction() - await tick(10) - assert.equal(host.confirms.length, 1) - assert.match(host.confirms[0].title, /导入整个磁盘/) - - // 5. 选择真实临时文件夹:去重 a.png、收集 avif/tiff/webp、排除 *_opt 输出和 txt - host.setConfirm(true) - host.ipc.window_show_select_folder_dialog = async () => ({ canceled: false, folderPath: root }) - await filterBarActions(view).find((a) => a.id === 'pick-folder').onAction() - await tick(15) - assert.equal(host.lastToast()?.title, '已添加 3 个文件') - assert.match(String(host.lastToast()?.message), /1 个已在列表中/) - assert.match(String(host.lastToast()?.message), /忽略 3 个不支持的文件/) - assert.deepEqual( - subItems(view).map((i) => i.props.title), - ['a.png', 'b.avif', 'c.tiff', 'd.webp'] - ) - assert.ok(subItems(view).every((i) => i.props.checked === true)) - assert.match(summaryTextOf(view), /清空列表 Ctrl\+Shift\+Backspace/) - - view.unmount() - - // 6. 超过 500 个文件时的数量截断提示 - const bigDir = 'D:\\BigImages' - const hostBig = createHost() - hostBig.ipc.window_show_select_folder_dialog = async () => ({ canceled: false, folderPath: bigDir }) - hostBig.ipc.filesystem_get_directory_contents = async () => ({ - success: true, - files: Array.from({ length: 505 }, (_, i) => ({ - name: `img_${i}.png`, - size: 1024, - isDirectory: false - })) - }) - const bigView = await mount(BatchImageCommand, hostBig) - await filterBarActions(bigView).find((a) => a.id === 'pick-folder').onAction() - await tick(20) - assert.equal(hostBig.lastToast()?.title, '已添加 500 个文件') - assert.match(String(hostBig.lastToast()?.message), /只导入了一部分/) - bigView.unmount() - } finally { - fs.rmSync(root, { recursive: true, force: true }) - } -}) - -test('batch-image UI 拖入文件夹(新旧客户端回退)、粘贴去重与从剪贴板添加', async () => { - const root = makeTempTree({ - 'v1.2_assets/drop1.png': '11', - 'v1.2_assets/drop1_opt.png': 'ignored', - 'single.gif': '22' }) - const dottedDir = path.join(root, 'v1.2_assets') - const singleFile = path.join(root, 'single.gif') - + const view = await mount(BatchImageCommand) try { - // 1. 新版宿主:fileInput 带 directories 展开,且不把扩展名交给宿主过滤 - const host = createHost() - await installDirectoryHost(host, { authorized: [root] }) - const view = await mount(BatchImageCommand, host) - await tick(5) - const fileInput = view.tree().props.fileInput - assert.equal(fileInput.allowDirectories, true) - assert.equal('extensions' in fileInput, false) - - await view.dropFiles([dottedDir, singleFile], { directories: [dottedDir] }) - await tick(15) - assert.deepEqual(subItems(view).map((i) => i.props.title), ['drop1.png', 'single.gif']) - assert.equal( - host.ipcCalls.some(([m]) => m === 'filesystem_directory_exists'), - false, - '有 directories 列表时不再逐个探测' - ) - - // 2. 旧版不带 directories 的 dropFiles 路径(经 filesystem_directory_exists 探测文件夹) - host.ipc.filesystem_directory_exists = async ({ path: p }) => ({ - success: true, - exists: p.toLowerCase() === dottedDir.toLowerCase() - }) - await view.dropFiles([dottedDir]) - await tick(15) - assert.equal(host.lastToast()?.title, '这些文件已在列表中') - - // 3. 从剪贴板添加(空路径提示、未授权大小标为未识别、已存在提示) - host.clipboard.text = '一段普通文字' - await view.run(undefined, '从剪贴板添加') await tick(10) - assert.equal(host.lastToast()?.title, '剪贴板中没有图片文件路径') - - host.clipboard.text = '"D:\\Shots\\new_shot.png"\r\nD:\\Shots\\readme.txt' - await view.run(undefined, '从剪贴板添加') - await tick(15) - assert.equal(host.lastToast()?.title, '已添加 1 个文件') - const added = view.item((it) => it.props.title === 'new_shot.png') - assert.equal(added.props.checked, true) - assert.ok(added.props.accessories.some((a) => a.text === '大小未识别')) - - // clipboard_read_files 兜底 - host.clipboard.text = '' - host.ipc.clipboard_read_files = async () => ({ files: ['D:\\Shots\\clip_file.bmp'] }) - host.ipc.filesystem_get_file_size = async () => ({ success: true, size: 2048 }) - await view.run(added, '从剪贴板添加') - await tick(15) - const clipFile = view.item((it) => it.props.title === 'clip_file.bmp') - assert.ok(clipFile.props.accessories.some((a) => a.text === '2.0 KB')) - - view.unmount() - - // 4. 旧版宿主 plugin_files_dropped 事件回退(含文件夹展开)与卸载清理 - const legacyHost = createHost() - await installDirectoryHost(legacyHost, { authorized: [root] }) - legacyHost.ipc.filesystem_directory_exists = async ({ path: p }) => ({ - success: true, - exists: p.toLowerCase() === dottedDir.toLowerCase() - }) - let droppedListener = null - globalThis.window.__ztoolsDeclarativeFeatures = { fileInput: false } - globalThis.window.ztools = { - ...(globalThis.window.ztools || {}), - events: { - on(event, cb) { - if (event === 'plugin_files_dropped') droppedListener = cb - return () => { - if (droppedListener === cb) droppedListener = null - } - } - } - } - const legacyView = await mount(BatchImageCommand, legacyHost) - try { - assert.equal(typeof droppedListener, 'function') - droppedListener({ payload: { files: [dottedDir] } }) - await tick(20) - assert.deepEqual(subItems(legacyView).map((i) => i.props.title), ['drop1.png']) - } finally { - legacyView.unmount() - globalThis.window.__ztoolsDeclarativeFeatures = { fileInput: true } - } - assert.equal(droppedListener, null) + assert.ok(view.tree()) + assert.equal(host.ipcCalls.some(([m]) => m === 'dllplugin_call'), false) + assert.ok(host.ipcCalls.some(([m]) => m === 'tool_runtime_capabilities')) } finally { - fs.rmSync(root, { recursive: true, force: true }) - } -}) - -test('batch-image UI 布局三渲染、逐张处理与失败路径', async () => { - const host = createHost() - host.ipc.filesystem_get_file_size = async ({ path: p }) => ({ - success: true, - size: p === POSTER ? 3145728 : 1048576 - }) - const existing = new Set([POSTER.replace('.png', '_opt.png').toLowerCase()]) - host.ipc.filesystem_file_exists = async ({ path: p }) => ({ success: true, exists: existing.has(p.toLowerCase()) }) - const dllCalls = [] - host.ipc.dllplugin_call = async ({ plugin, func, params }) => { - dllCalls.push({ plugin, func, params }) - await new Promise((r) => setTimeout(r, 10)) - return hostSuccess(params) - } - - const view = await mount(BatchImageCommand, host) - await view.dropFiles([POSTER, RECEIPT]) - await tick(15) - - const tree = view.tree() - assert.equal(tree.type, 'List') - assert.equal(tree.props.isShowingDetail, false) - assert.ok(tree.props.workbenchPanel) - assert.ok(tree.props.subList) - assert.equal(/PDF|预计/.test(view.text()), false) - assert.equal(tree.props.workbenchPanel.previewCard.badge, '未处理') - - const poster = view.item((it) => it.props.title === 'design_poster_4k.png') - assert.equal(tagOf(poster), '待处理') - - // 并发锁:连续触发两次只执行一批 - await Promise.all([ - view.run(poster, '开始处理已选图片 (2 张)'), - view.run(poster, '开始处理已选图片 (2 张)') - ]) - await tick(10) - assert.equal(dllCalls.length, 2) - const byFile = new Map(dllCalls.map((c) => [c.params.files[0], c.params.outputPath])) - assert.equal(byFile.get(POSTER), 'D:\\TestMedia\\pictures\\design_poster_4k_opt_2.png') - assert.equal(byFile.get(RECEIPT), 'D:\\TestMedia\\pictures\\receipt_scan_opt.jpg') - assert.equal(host.lastToast()?.title, '已处理 2 张图片') - - const posterDone = view.item((it) => it.props.title === 'design_poster_4k.png') - await view.run(posterDone, '复制输出文件路径') - assert.equal(host.clipboard.text, 'D:\\TestMedia\\pictures\\design_poster_4k_opt_2.png') - - // 全部失败、部分失败、超过 300KB - host.ipc.dllplugin_call = async ({ params }) => hostFailure(params, 'DECODE_FAILED: 图片文件头损坏') - await view.run(view.item((it) => it.props.title === 'design_poster_4k.png'), '开始处理已选图片 (2 张)') - assert.equal(host.lastToast()?.title, '2 张图片全部处理失败') - - host.ipc.dllplugin_call = async ({ params }) => - params.files[0] === POSTER ? hostSuccess(params) : hostFailure(params, '图片编码转换失败: receipt_scan.jpg') - await view.run(view.item((it) => it.props.title === 'design_poster_4k.png'), '开始处理已选图片 (2 张)') - assert.equal(host.lastToast()?.title, '已处理 1 张,1 张失败') - - host.ipc.filesystem_file_exists = async () => ({ success: true, exists: false }) - host.ipc.dllplugin_call = async ({ params }) => - hostSuccess(params, { outputBytes: params.files[0] === POSTER ? 400 * 1024 : 200 * 1024, originalBytes: 3145728 }) - await view.dropdown('preset-extreme-300k') - await view.run(view.item((it) => it.props.title === 'design_poster_4k.png'), '开始处理已选图片 (2 张)') - assert.equal(host.lastToast()?.title, '已处理 2 张,1 张仍超过 300 KB') - assert.equal(tagOf(view.item((it) => it.props.title === 'design_poster_4k.png')), '超过 300 KB') - - view.unmount() -}) - -test('batch-image UI 移除、清空、处理中防护(忽略已移除回执与拒绝清空)与导入中清空丢弃', async () => { - const host = createHost() - host.ipc.filesystem_get_file_size = async () => ({ success: true, size: 4096 }) - host.ipc.filesystem_file_exists = async () => ({ success: true, exists: false }) - - let releaseFirst - const firstGate = new Promise((r) => (releaseFirst = r)) - const calledFiles = [] - host.ipc.dllplugin_call = async ({ params }) => { - calledFiles.push(params.files[0]) - if (params.files[0] === POSTER) await firstGate - return hostSuccess(params) - } - - const view = await mount(BatchImageCommand, host) - await view.dropFiles([POSTER, RECEIPT, 'D:\\TestMedia\\pictures\\extra.png']) - await tick(10) - - // 从列表移除不删磁盘文件(无 recycle/delete IPC) - await view.run(view.item((it) => it.props.title === 'extra.png'), '从列表移除') - assert.equal(subItems(view).length, 2) - assert.equal(host.ipcCalls.some(([m]) => /trash|delete|unlink/i.test(m)), false) - - // 启动批处理 [POSTER, RECEIPT],在 POSTER 处理中时: - const posterNode = view.item((it) => it.props.title === 'design_poster_4k.png') - const runPromise = view.run(posterNode, '开始处理已选图片 (2 张)') - await tick(5) - - // 正在处理中的 POSTER 不提供「从列表移除」与「移入回收站」 - const processingActions = view.actions(view.item((it) => it.props.title === 'design_poster_4k.png')).map((a) => a.props.title) - assert.equal(processingActions.includes('从列表移除'), false) - assert.equal(processingActions.includes('将原图移入系统回收站'), false) - - // 处理中点「清空列表」被拒绝并不清空 - const receiptNode = view.item((it) => it.props.title === 'receipt_scan.jpg') - await view.run(receiptNode, '清空列表') - assert.equal(host.lastToast()?.title, '正在处理,完成后再清空') - assert.equal(subItems(view).length, 2) - - // 处理中移除尚未开始的 RECEIPT,随后放行 POSTER:RECEIPT 应被跳过不调用宿主 - await view.run(view.item((it) => it.props.title === 'receipt_scan.jpg'), '从列表移除') - assert.equal(subItems(view).length, 1) - - releaseFirst() - await runPromise - await tick(10) - assert.deepEqual(calledFiles, [POSTER], '处理中已移出列表的条目不能再调用宿主') - assert.equal(subItems(view).length, 1, '已移除的条目绝不能在回调里重新写回列表') - - // 空闲后清空列表 - await view.run(view.item((it) => it.props.title === 'design_poster_4k.png'), '清空列表') - assert.equal(subItems(view).length, 0) - - // 导入进行中清空列表:进行中的导入结果被丢弃且不弹提示 - let releaseImport - const importGate = new Promise((r) => (releaseImport = r)) - host.ipc.window_show_select_folder_dialog = async () => ({ canceled: false, folderPath: 'D:\\PendingFolder' }) - host.ipc.filesystem_get_directory_contents = async () => { - await importGate - return { success: true, files: [{ name: 'late.png', size: 1024, isDirectory: false }] } + view.unmount() } - await view.dropFiles([POSTER]) - await tick(10) - const toastCountBefore = host.toasts.length - const folderTask = filterBarActions(view).find((a) => a.id === 'pick-folder').onAction() - await tick(5) - await view.run(view.item((it) => it.props.title === 'design_poster_4k.png'), '清空列表') - assert.equal(subItems(view).length, 0) - releaseImport() - await folderTask - await tick(10) - assert.equal(view.items().length, 0, '导入进行中被清空后,后续结果必须丢弃') - assert.equal(host.toasts.length, toastCountBefore, '已作废的导入不能弹提示') - - view.unmount() }) diff --git a/extensions/batch-rename/README.en.md b/extensions/batch-rename/README.en.md new file mode 100644 index 00000000..26f518e0 --- /dev/null +++ b/extensions/batch-rename/README.en.md @@ -0,0 +1,23 @@ +# Batch File Renamer + +Select or drag and drop files or folders to batch rename filenames by rules; preview each original and new name before executing, and undo the last rename within this window. + +## Usage + +- Command: Search for "Batch File Renamer" in the launcher to open. +- Import files: Click **Select File** or **Select Folder** in the top bar or action panel, or drag and drop / paste files and folders into the window. Supports appending multiple batches with path deduplication, and newly imported files are checked by default. Selecting or dropping a folder imports only direct first-level child files without entering subfolders, skipping hidden files starting with `.` and system metadata files such as `desktop.ini`, `Thumbs.db`, and `Icon\r` (up to 500 items per import). +- Choose a rule on the left: append sequence number (`_01`, Chinese numerals, Roman numerals, numbered in list order), add prefix, add today's date prefix (`YYYYMMDD_`), add suffix before extension, remove first 3 characters, strip `()`, `[]`, `【】` and their contents (while replacing spaces with underscores), replace spaces and hyphens with underscores and convert to lowercase, or convert all to lowercase. Prefix and suffix rules use the text in the search box; if the search box is empty, names are not changed and the status bar prompts for input. +- Enter `old->new` in the search box for direct find-and-replace (renames the filename only, not the extension; also matches decomposed Unicode filenames on macOS such as Japanese dakuten or accented characters). Under other rules, the search box filters filenames. +- Shortcuts & action panel: `Enter` renames checked files (prompts for confirmation first); `⌘/Ctrl+Enter` reveals the file in File Explorer (Finder on macOS); `⌘/Ctrl+K` opens the action panel to rename only the current file (without confirmation), undo the last rename, remove from list (`⌘/Ctrl+Backspace`, without deleting disk files), select/deselect all (`⌘/Ctrl+A`), or clear the list (`⌘/Ctrl+Shift+Backspace`, without deleting disk files). +- Name conflicts are detected independently per directory: if a new name collides with an existing direct child in the same folder (case-insensitive and Unicode canonical/decomposed-insensitive), if multiple files in the same folder resolve to the same name, or if a new name is invalid (Windows additionally disallows `<>"|?*`, trailing dots or spaces, and reserved names such as `CON` or `NUL`), that item is marked "Name Conflict" and skipped. Identical names in different directories do not conflict, and renaming never overwrites existing files. +- Permissions: Folders imported via **Select Folder** receive write authorization directly. Items added via **Select File**, drag-and-drop, or paste start as "Read-only Preview"; before renaming, a folder authorization dialog prompts once per parent directory, and you must select the matching original directory to execute the rename (canceling or picking a different directory keeps them in read-only preview without modifying the files). +- Undo only applies to the most recent rename performed since opening the plugin. + +## Platforms & Requirements + +- Supported: Windows, macOS +- Requires client version 1.1.8.3 or later. + +## Network & Data + +- Works offline; data stays on your local device. diff --git a/extensions/batch-rename/plugin.json b/extensions/batch-rename/plugin.json index 85747bd3..905968dc 100644 --- a/extensions/batch-rename/plugin.json +++ b/extensions/batch-rename/plugin.json @@ -2,7 +2,8 @@ "id": "batch-rename", "name": "批量重命名", "description": "选择或拖入文件/文件夹批量改名:查找替换、加前缀 / 后缀 / 当天日期前缀、追加序号、去括号、下划线或全小写规范,执行前预览并确认,本次打开期间可撤销", - "version": "2.0.16", + "version": "2.0.17", + "minAppVersion": "1.1.8.0", "author": "ZTools Team", "entry": "dist/index.js", "icon": "icon.svg", @@ -41,7 +42,11 @@ "files", "prefix", "suffix", - "numbering" + "numbering", + "bulk rename", + "rename files", + "file renamer", + "find replace filename" ], "screenshots": [ { @@ -54,5 +59,17 @@ { "path": "screenshots/01.png" } + ], + "keywords": [ + "批量重命名", + "批量改名", + "重命名", + "改文件名", + "统一改名", + "加前缀", + "加后缀", + "加序号", + "替换文件名", + "文件改名" ] } diff --git a/extensions/batch-rename/src/i18n.ts b/extensions/batch-rename/src/i18n.ts index 4a73dd73..d726667f 100644 --- a/extensions/batch-rename/src/i18n.ts +++ b/extensions/batch-rename/src/i18n.ts @@ -151,6 +151,9 @@ const rawT = createTranslator( searchPlaceholder: "输入「旧词->新词」实时替换,或输入前缀/后缀参数、搜索文件名...", btnPickFiles: "选择文件", btnPickFolder: "选择文件夹", + btnRunRename: "执行重命名 ({count})", + btnRenaming: "重命名中…", + btnUndo: "撤销 ({count})", subListTitleWithCount: "原名 -> 新名实时对比预览 ({total} 项 · 待执行 {changed} 项)", subListTitleDefault: "原名 -> 新名实时对比预览", subListSubMultiDir: "共 {count} 个文件夹", @@ -308,6 +311,9 @@ const rawT = createTranslator( searchPlaceholder: "Type \"old->new\" to replace, or enter prefix/suffix or search filename...", btnPickFiles: "Select Files", btnPickFolder: "Select Folder", + btnRunRename: "Rename ({count})", + btnRenaming: "Renaming…", + btnUndo: "Undo ({count})", subListTitleWithCount: "Original -> New Preview ({total} [[total:item|items]] · {changed} ready)", subListTitleDefault: "Original -> New Preview", subListSubMultiDir: "{count} [[count:folder|folders]]", diff --git a/extensions/batch-rename/src/index.ts b/extensions/batch-rename/src/index.ts index 0e9bc8e2..eab1adcb 100644 --- a/extensions/batch-rename/src/index.ts +++ b/extensions/batch-rename/src/index.ts @@ -8,6 +8,7 @@ import { Action, ActionPanel, + Color, Icon, List, Toast, @@ -1036,8 +1037,6 @@ export function BatchRenameCommand() { summaryText = summaryParts.join(" · "); } - const maxSizeBytes = Math.max(1, ...previewItems.map((f) => f.sizeBytes ?? 0)); - const undoAction = () => Action({ title: t("actionUndo", { count: undoStack.length }), @@ -1097,7 +1096,6 @@ export function BatchRenameCommand() { const subListItems = previewItems.map((item) => { const sizeKnown = item.sizeBytes !== null; - const ratio = sizeKnown ? Math.min(1, item.sizeBytes! / maxSizeBytes) : 0; const statusLabel = item.conflict ? t("statusConflict") : item.changed @@ -1117,11 +1115,10 @@ export function BatchRenameCommand() { onCheckChange: () => toggleFileCheck(item.fullPath), onToggleCheck: () => toggleFileCheck(item.fullPath), accessories: [ - { progress: ratio }, { tag: { value: statusLabel, - color: item.conflict ? "red" : undefined + color: item.conflict ? Color.Red : undefined } }, { @@ -1202,24 +1199,75 @@ export function BatchRenameCommand() { isShowingDetail: false, filterBar: { summaryText, - actions: [ - { - id: "pick-files", - title: t("btnPickFiles"), - style: "secondary", - onAction: () => { - void handlePickFiles(); - } - }, - { - id: "pick-folder", - title: t("btnPickFolder"), - style: "secondary", - onAction: () => { - void handlePickFolder(); - } - } - ] + actions: + changedSelectedCount > 0 + ? [ + undoStack.length > 0 + ? { + id: "undo-rename", + title: t("btnUndo", { count: undoStack.length }), + style: "secondary", + disabled: isProcessing, + onAction: () => { + void handleUndoLastBatch(); + } + } + : { + id: "pick-files", + title: t("btnPickFiles"), + style: "secondary", + onAction: () => { + void handlePickFiles(); + } + }, + { + id: "run-rename", + title: isProcessing ? t("btnRenaming") : t("btnRunRename", { count: changedSelectedCount }), + style: "primary", + disabled: isProcessing, + onAction: () => { + void executeBatchRename(); + } + } + ] + : undoStack.length > 0 + ? [ + { + id: "pick-files", + title: t("btnPickFiles"), + style: "secondary", + onAction: () => { + void handlePickFiles(); + } + }, + { + id: "undo-rename", + title: t("btnUndo", { count: undoStack.length }), + style: "secondary", + disabled: isProcessing, + onAction: () => { + void handleUndoLastBatch(); + } + } + ] + : [ + { + id: "pick-files", + title: t("btnPickFiles"), + style: "secondary", + onAction: () => { + void handlePickFiles(); + } + }, + { + id: "pick-folder", + title: t("btnPickFolder"), + style: "secondary", + onAction: () => { + void handlePickFolder(); + } + } + ] }, actions: ActionPanel({ children: [ diff --git a/extensions/batch-rename/src/native-ipc.ts b/extensions/batch-rename/src/native-ipc.ts index 51576b99..13643277 100644 --- a/extensions/batch-rename/src/native-ipc.ts +++ b/extensions/batch-rename/src/native-ipc.ts @@ -174,11 +174,13 @@ function normalizeMethodResult(method: string, payload: DynamicBridge): DynamicB if (method === 'system_get_battery_status') { // 宿主约定 percent 超出 0-100(如 255)表示无电池或电量未知,不能改写成 100% + // 若宿主明确给出 hasBattery 布尔值,必须原样保留,仅在缺失时按合法电量推算 const rawPct = payload.percent - const hasBattery = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const validPct = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const hasBattery = typeof payload.hasBattery === 'boolean' ? payload.hasBattery : validPct return { ...payload, - percent: hasBattery ? rawPct : null, + percent: validPct ? rawPct : null, hasBattery } } @@ -489,6 +491,8 @@ export interface RealDirectoryScanResult extends Iterable approximate?: boolean /** 宿主实际遍历的条目数 */ visitedEntries?: number + /** 目录本身不存在(ENOENT) */ + missing?: boolean /** 读取失败的真实原因;已有文件仍可使用,但不能当作完整结果。 */ error?: string } @@ -497,6 +501,7 @@ interface ScanResultMeta { truncated?: boolean approximate?: boolean visitedEntries?: number + missing?: boolean } export interface ScanDirectoryTreeOptions { @@ -504,6 +509,10 @@ export interface ScanDirectoryTreeOptions { maxFiles?: number collectTopN?: number filterExt?: RegExp + /** 为 true 时,目录本身不存在(ENOENT)按空目录处理,不返回 error(权限拒绝/读取失败仍照常报错) */ + ignoreMissing?: boolean + /** Top-N 保留与排序方式:默认按体积降序,下载/录屏等时效场景可传 mtime-desc */ + sortBy?: 'size-desc' | 'mtime-desc' hostOverride?: DynamicBridge } @@ -519,8 +528,9 @@ function normalizeIndexedFileEntry(f: DynamicBridge): RealIndexedFileEntry { const sz = Number(f?.size ?? f?.sizeBytes ?? 0) const isDir = Boolean(f?.is_dir || f?.isDir || f?.isDirectory) const rawMtime = Number(f?.mtime ?? f?.mtimeMs ?? 0) - const mtimeMs = rawMtime > 1e11 ? rawMtime : rawMtime > 0 ? rawMtime * 1000 : Date.now() - const mtimeSec = rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime + const validMtime = Number.isFinite(rawMtime) && rawMtime > 0 + const mtimeMs = validMtime ? (rawMtime > 1e11 ? rawMtime : rawMtime * 1000) : 0 + const mtimeSec = validMtime ? (rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime) : 0 if (p && sz >= 0) realFileSizeCache.set(p, sz) return { name, @@ -551,6 +561,7 @@ function makeScanResult( subdirs, ...(meta.truncated ? { truncated: true } : {}), ...(meta.approximate ? { approximate: true } : {}), + ...(meta.missing ? { missing: true } : {}), ...(typeof meta.visitedEntries === 'number' ? { visitedEntries: meta.visitedEntries } : {}), [Symbol.iterator]() { return files[Symbol.iterator]() @@ -609,13 +620,40 @@ export async function scanRealDirectoryTree( return result.error ? { ...result.scan, error: result.error } : result.scan } +/** 仅当正则明确声明了扩展名(含 `\.`)时提取后缀列表,避免把 `thumbcache|iconcache` 等文件名关键词误拆成假扩展名 */ +function extractExtensionTokensFromFilter(filterExt: RegExp): string[] { + const src = filterExt.source + if (!src.includes('\\.')) return [] + const afterDot = src.slice(src.indexOf('\\.') + 2) + const rawTokens = afterDot.match(/[a-z0-9]{1,8}/gi) || [] + const seen = new Set() + const out: string[] = [] + for (const token of rawTokens) { + const lower = token.toLowerCase() + if (!lower || seen.has(lower)) continue + seen.add(lower) + out.push(lower) + } + return out +} + +function isMissingDirectoryError(res: { error?: string; errorCode?: string; errorDetails?: Record }): boolean { + if (res.errorDetails?.reason === 'ENOENT' || res.errorCode === 'ENOENT') return true + const msg = String(res.error || '') + return /Directory does not exist|ENOENT/i.test(msg) +} + /** 一次界面扫描的错误汇总;多个目录并行扫描时保留可读目录的结果。 */ export function createDirectoryScanner(hostOverride?: DynamicBridge) { const failures = new Map() return { async scan(dir: string, options: number | ScanDirectoryTreeOptions = 160) { const result = await scanRealDirectoryTree(dir, options, hostOverride) - const error = result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') + const ignoreMissing = typeof options === 'object' && options !== null && options.ignoreMissing === true + const error = + result.missing && ignoreMissing + ? '' + : result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') if (error) failures.set(dir, error) else failures.delete(dir) return result @@ -648,26 +686,38 @@ async function scanDirectoryTreeWithError( const safeLimit = Math.min(200, Math.max(1, Math.floor(rawLimit || 160))) const hostOverride = opts.hostOverride const filterExt = opts.filterExt + const ignoreMissing = opts.ignoreMissing === true const dirQuery = `dir:${targetDir}` try { let rawPayload: DynamicBridge = null + const searchParams: Record = { + query: dirQuery, + limit: safeLimit, + ...(opts.sortBy ? { sortBy: opts.sortBy } : {}) + } const res = await callHostTransport( 'system_search_files', - { query: dirQuery, limit: safeLimit }, + searchParams, hostOverride ) - if (res.ok && res.data) { + if (res.ok && res.data && res.data.degraded !== true) { rawPayload = res.data + } else if (!res.ok && ignoreMissing && isMissingDirectoryError(res)) { + const missingScan = makeScanResult([], 0, 0, [], { missing: true }) + return { scan: missingScan } } - if (!rawPayload && !hostOverride && typeof window !== 'undefined') { + if (!rawPayload && !hostOverride && res.errorCode === 'METHOD_NOT_AVAILABLE' && typeof window !== 'undefined') { const w = window as DynamicBridge if (typeof w.__ztoolsLauncher?.searchFiles === 'function') { const rawOuter = await w.__ztoolsLauncher.searchFiles(dirQuery, safeLimit) - rawPayload = + const candidate = rawOuter && typeof rawOuter === 'object' && 'data' in rawOuter && rawOuter.data ? rawOuter.data : rawOuter + if (candidate && candidate.degraded !== true && candidate.success !== false) { + rawPayload = candidate + } } } @@ -678,29 +728,32 @@ async function scanDirectoryTreeWithError( let files: RealIndexedFileEntry[] = rawPayload.files.map(normalizeIndexedFileEntry) if (filterExt instanceof RegExp) { files = files.filter(f => !f.isDir && (filterExt.test(f.name) || filterExt.test(f.ext))) - // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索目标扩展名 + // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索明确声明的目标扩展名 if (files.length === 0 && !hostOverride) { - const extTokens = (filterExt.source.match(/[a-z0-9]{2,5}/gi) || []) - .filter(t => !['thumbcache', 'iconcache'].includes(t.toLowerCase())) - .slice(0, 4) - // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 - const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() - const extraLists = await Promise.all( - extTokens.map(ext => searchRealIndexedFiles(`.${ext.toLowerCase()}`, 30, hostOverride)) - ) - const seen = new Set() - for (const list of extraLists) { - for (const item of list) { - if (!item.isDir && item.size > 0 && !seen.has(item.path)) { - if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { - seen.add(item.path) - files.push(item) + const extTokens = extractExtensionTokensFromFilter(filterExt) + if (extTokens.length > 0) { + // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 + const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() + const extraLists = await Promise.all( + extTokens.map(ext => searchRealIndexedFiles(`.${ext}`, 30, hostOverride)) + ) + const seen = new Set() + for (const list of extraLists) { + for (const item of list) { + if (!item.isDir && item.size > 0 && !seen.has(item.path)) { + if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { + seen.add(item.path) + files.push(item) + } } } } } } } + // 先基于过滤后的完整命中集合计算总文件数与总字节数,再按 collectTopN 裁剪样本列表 + const matchedCount = files.length + const matchedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) if (typeof opts.collectTopN === 'number' && opts.collectTopN > 0 && files.length > opts.collectTopN) { files = files.slice(0, opts.collectTopN) } @@ -714,11 +767,10 @@ async function scanDirectoryTreeWithError( ...(s.approximate === true ? { approximate: true } : {}) })) : [] - const computedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) const totalFilesCount = - filterExt instanceof RegExp ? files.length : Number(rawPayload.total_matches ?? files.length) + filterExt instanceof RegExp ? matchedCount : Number(rawPayload.total_matches ?? matchedCount) const totalBytesCount = - filterExt instanceof RegExp ? computedBytes : Number(rawPayload.total_bytes ?? computedBytes) + filterExt instanceof RegExp ? matchedBytes : Number(rawPayload.total_bytes ?? matchedBytes) const visited = Number(rawPayload.visited_entries) return { scan: makeScanResult(files, totalFilesCount, totalBytesCount, subdirs, { @@ -1817,8 +1869,6 @@ export async function writeRealClipboardText(text: string, hostOverride?: Dynami const payload = { text: String(text || '') } const res = await callHostTransport('clipboard_copy_text', payload, hostOverride) if (res.ok) return true - const fallbackRes = await callHostTransport('clipboard_write_text', payload, hostOverride) - if (fallbackRes.ok) return true try { if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) { await navigator.clipboard.writeText(String(text || '')) diff --git a/extensions/batch-rename/tests/batch-rename.directory.test.mjs b/extensions/batch-rename/tests/batch-rename.directory.test.mjs index 2b4ff192..f667da1a 100644 --- a/extensions/batch-rename/tests/batch-rename.directory.test.mjs +++ b/extensions/batch-rename/tests/batch-rename.directory.test.mjs @@ -325,7 +325,11 @@ test('从列表移除与清空列表不删除磁盘文件;导入进行中清 }) host2.ipc.filesystem_get_directory_contents = async () => secondGate const toastCountBefore = host2.toasts.length - const p2 = topActions(view2).find((a) => a.id === 'pick-folder').onAction() + // 已有待改名文件时,顶栏第 2 按钮切换为主操作「执行重命名」,此时通过动作面板触发「选择文件夹…」 + assert.equal(topActions(view2).some((a) => a.id === 'run-rename'), true) + const pickFolderAct = view2.actions(null).find((a) => a.props.title === '选择文件夹…') + assert.ok(pickFolderAct, '动作面板应始终保留「选择文件夹…」入口') + const p2 = pickFolderAct.props.onAction() await tick(5) await view2.run(subItems(view2)[0], '清空列表') assert.deepEqual(subItems(view2), []) diff --git a/extensions/batch-rename/tests/batch-rename.rename.test.mjs b/extensions/batch-rename/tests/batch-rename.rename.test.mjs index 3e45a056..abc94c1f 100644 --- a/extensions/batch-rename/tests/batch-rename.rename.test.mjs +++ b/extensions/batch-rename/tests/batch-rename.rename.test.mjs @@ -5,6 +5,7 @@ import assert from 'node:assert/strict' import fs from 'node:fs' import os from 'node:os' import path from 'node:path' +import { Color } from '@ztools/declarative-ui' import { createHost, mount, tick } from '../../shared/test-harness.mjs' import * as logic from '../dist/logic.js' import BatchRenameCommand from '../dist/index.js' @@ -378,7 +379,9 @@ test('e 项按目录独立冲突检测:不同目录同名文件不算冲突, const ctx = setupRenameHost({ folderDialog: [d1, d2] }) const view = await mount(BatchRenameCommand, ctx.host) await pickFolderViaTop(view) - await pickFolderViaTop(view) + // 已有待改名文件时顶栏切换为主操作「执行重命名」,继续追加第二个文件夹需走动作面板入口 + assert.equal(view.tree().props.filterBar.actions.some((a) => a.id === 'run-rename'), true) + await runAction(view, null, '选择文件夹…') await view.search('item->same') assert.match(summary(view), /待改名 2 项/) assert.doesNotMatch(summary(view), /同名冲突/) @@ -388,7 +391,7 @@ test('e 项按目录独立冲突检测:不同目录同名文件不算冲突, // 同目录与子目录 sub 同名拦截 await view.search('p->sub') - assert.equal(subItem(view, 'p').props.accessories.find((a) => a.tag?.color === 'red')?.tag?.value, '同名冲突') + assert.equal(subItem(view, 'p').props.accessories.find((a) => a.tag?.color === Color.Red)?.tag?.value, '同名冲突') assert.match(summary(view), /1 项同名冲突/) view.unmount() }) diff --git a/extensions/batch-text-convert/README.md b/extensions/batch-text-convert/README.md new file mode 100644 index 00000000..5a7c124b --- /dev/null +++ b/extensions/batch-text-convert/README.md @@ -0,0 +1,3 @@ +# 编码转换 + +已下架:已合并至内置「编码与加密」插件,请改用编码与加密。 diff --git a/extensions/batch-text-convert/package.json b/extensions/batch-text-convert/package.json index c559e1dc..0f9e7847 100644 --- a/extensions/batch-text-convert/package.json +++ b/extensions/batch-text-convert/package.json @@ -1,6 +1,6 @@ { "name": "@ztools/plugin-batch-text-convert", - "version": "1.0.2", + "version": "1.0.5", "description": "文本实时转为 Unicode 转义、UTF-8 Hex、Base64 与 URL 编码", "main": "dist/index.js", "types": "dist/index.d.ts", diff --git a/extensions/batch-text-convert/plugin.json b/extensions/batch-text-convert/plugin.json index d0845dfe..74ff7c8c 100644 --- a/extensions/batch-text-convert/plugin.json +++ b/extensions/batch-text-convert/plugin.json @@ -2,7 +2,8 @@ "id": "batch-text-convert", "name": "编码转换", "description": "把文本实时转为 Unicode 转义(\\uXXXX)、UTF-8 十六进制(Hex)、Base64 与 URL 编码,可读取剪贴板里的多行文本", - "version": "1.0.2", + "version": "1.0.5", + "minAppVersion": "1.1.8.0", "revoked": true, "revokedReason": "已合并至内置「编码与加密」插件,请改用编码与加密", "author": "ZTools Team", @@ -41,5 +42,14 @@ "百分号编码", "转义", "编码" - ] + ], + "categoryId": "developer", + "defaultLocale": "zh-CN", + "i18n": { + "en-US": { + "name": "Text Encoding Converter", + "description": "Convert text in real time to Unicode escapes (\\uXXXX), UTF-8 Hex, Base64, and URL encoding, with multi-line clipboard support.", + "revokedReason": "Merged into the built-in \"Codec\" plugin. Please use Codec instead." + } + } } diff --git a/extensions/batch-text-convert/tests/batch-text-convert.ui.test.mjs b/extensions/batch-text-convert/tests/batch-text-convert.ui.test.mjs index eb146749..13c3ce86 100644 --- a/extensions/batch-text-convert/tests/batch-text-convert.ui.test.mjs +++ b/extensions/batch-text-convert/tests/batch-text-convert.ui.test.mjs @@ -12,7 +12,7 @@ const sectionTitle = (view) => view.tree().children.find((c) => c.type === 'List const ids = (view) => view.items().map((i) => i.props.id) const encodedOf = (view, id) => view.item(id).props.title -test('[issue-1] 打开时搜索框为空,只显示引导项,不拿看不见的示例冒充结果', async () => { +test('打开时搜索框为空,只显示引导项,不拿看不见的示例冒充结果', async () => { const view = await mount(BatchTextConvertCommand) assert.equal(view.tree().props.searchText, '') assert.deepEqual(ids(view), ['empty-guide']) @@ -27,7 +27,7 @@ test('[issue-1] 打开时搜索框为空,只显示引导项,不拿看不见 assert.deepEqual(ids(view), ['empty-guide']) }) -test('[issue-1] 输入后显示 4 种结果,清空后回到同一个引导项(不出现“未找到”)', async () => { +test('输入后显示 4 种结果,清空后回到同一个引导项(不出现“未找到”)', async () => { const view = await mount(BatchTextConvertCommand) await view.search('你好') assert.deepEqual(ids(view), ['unicode-escape', 'utf8-hex', 'base64', 'url-encode']) @@ -39,7 +39,7 @@ test('[issue-1] 输入后显示 4 种结果,清空后回到同一个引导项 assert.equal(view.tree().props.searchText, '') }) -test('[issue-2] 清单描述与关键字只写真实能力,能按 base64 / hex / url 搜到,不再出现 GBK、ASCII、互转、批量', () => { +test('清单描述与关键字只写真实能力,能按 base64 / hex / url 搜到,不再出现 GBK、ASCII、互转、批量', () => { const manifest = JSON.parse(fs.readFileSync(new URL('../plugin.json', import.meta.url), 'utf8')) const pkg = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8')) for (const desc of [manifest.description, pkg.description]) { @@ -52,7 +52,7 @@ test('[issue-2] 清单描述与关键字只写真实能力,能按 base64 / hex assert.equal(pkg.version, manifest.version) }) -test('[issue-3] 次动作不再绑定 ctrl+c / ⌘C,任何动作都没有快捷键覆盖系统复制', async () => { +test('次动作不再绑定 ctrl+c / ⌘C,任何动作都没有快捷键覆盖系统复制', async () => { const view = await mount(BatchTextConvertCommand) await view.search('hello world') for (const item of view.items()) { @@ -65,7 +65,7 @@ test('[issue-3] 次动作不再绑定 ctrl+c / ⌘C,任何动作都没有快 assert.equal(host.lastToast().style, Toast.Style.Success) }) -test('[issue-7] 复制成功后才提示“已复制”,内容与列表显示一致', async () => { +test('复制成功后才提示“已复制”,内容与列表显示一致', async () => { const view = await mount(BatchTextConvertCommand) await view.search('a b') await view.run(view.item('url-encode'), '复制编码结果') @@ -75,7 +75,7 @@ test('[issue-7] 复制成功后才提示“已复制”,内容与列表显示 assert.match(host.lastToast().title, /已复制 URL 编码/) }) -test('[issue-7][故障] 宿主拒绝写入(超过 8 MiB)时提示复制失败,不提示成功、不抛未处理异常', async () => { +test('[故障] 宿主拒绝写入(超过 8 MiB)时提示复制失败,不提示成功、不抛未处理异常', async () => { const view = await mount(BatchTextConvertCommand) // 300 万个 a 的 Hex 结果约 9M 字符,超过宿主 8 MiB 上限 await view.search('a'.repeat(3_000_000)) @@ -88,7 +88,7 @@ test('[issue-7][故障] 宿主拒绝写入(超过 8 MiB)时提示复制失 assert.match(host.lastToast().message, /8 MiB/) }) -test('[issue-7][故障] 宿主 IPC 抛出非标准错误时,次动作同样提示失败', async () => { +test('[故障] 宿主 IPC 抛出非标准错误时,次动作同样提示失败', async () => { const view = await mount(BatchTextConvertCommand) await view.search('x') const bridge = getDeclarativeBridge() @@ -106,7 +106,7 @@ test('[issue-7][故障] 宿主 IPC 抛出非标准错误时,次动作同样提 assert.ok(!host.toasts.some((t) => t.style === Toast.Style.Success)) }) -test('[issue-v1] 读取剪贴板多行文本,保留 \\n 与 \\r\\n 后再编码,并提示含换行', async () => { +test('读取剪贴板多行文本,保留 \\n 与 \\r\\n 后再编码,并提示含换行', async () => { const view = await mount(BatchTextConvertCommand) const source = 'line1\nline2\r\nline3' host.clipboard.text = source @@ -130,7 +130,7 @@ test('[issue-v1] 读取剪贴板多行文本,保留 \\n 与 \\r\\n 后再编 assert.equal(encodedOf(view, 'url-encode'), 'line1line2line3x') }) -test('[issue-v1] 从任意结果行的动作面板也能读取剪贴板,替换当前输入', async () => { +test('从任意结果行的动作面板也能读取剪贴板,替换当前输入', async () => { const view = await mount(BatchTextConvertCommand) await view.search('old') host.clipboard.text = '{\n "a": 1\n}' @@ -138,7 +138,7 @@ test('[issue-v1] 从任意结果行的动作面板也能读取剪贴板,替换 assert.equal(encodedOf(view, 'url-encode'), encodeURIComponent('{\n "a": 1\n}')) }) -test('[issue-v1][故障] 剪贴板读取失败 / 为空 / 过长时提示原因,保留原输入', async () => { +test('[故障] 剪贴板读取失败 / 为空 / 过长时提示原因,保留原输入', async () => { const view = await mount(BatchTextConvertCommand) await view.search('keep') const bridge = getDeclarativeBridge() diff --git a/extensions/batch-video/package.json b/extensions/batch-video/package.json index 9db20011..2812a04a 100644 --- a/extensions/batch-video/package.json +++ b/extensions/batch-video/package.json @@ -1,7 +1,7 @@ { "name": "@ztools/plugin-batch-video", - "version": "1.0.0", - "description": "批量视频格式转换、转 GIF 与提取音频(调用本机 ffmpeg,按默认参数处理)", + "version": "2.1.0", + "description": "基于宿主 media.probe / media.transcode 薄原语的批量视频处理插件", "main": "dist/index.js", "types": "dist/index.d.ts", "scripts": { diff --git a/extensions/batch-video/plugin.json b/extensions/batch-video/plugin.json index b0aadc88..a55d6b48 100644 --- a/extensions/batch-video/plugin.json +++ b/extensions/batch-video/plugin.json @@ -1,10 +1,9 @@ { "id": "batch-video", "name": "视频转码", - "description": "支持选择文件、选择文件夹或拖入视频导入,批量转为 MP4、MKV、MOV、WebM 或 GIF,或提取音轨为 MP3、M4A、WAV;调用本机已安装的 ffmpeg 按默认参数处理,单个文件处理超过 60 秒会失败;结果另存到源文件所在目录,不覆盖已有文件", - "version": "2.0.12", - "draft": true, - "draftReason": "客户端的视频处理接口单个文件最多运行 60 秒(常见时长的视频转换会超时失败),只按输出扩展名使用 ffmpeg 默认参数(不能指定画质、分辨率、码率),并且要求用户自行安装 ffmpeg;等客户端提供可长时间运行、可取消、支持编码参数并自带 ffmpeg 的转码接口,并在 Windows 上实测通过后再发布", + "description": "支持选择文件、选择文件夹或拖入视频导入,通过宿主媒体引擎批量转码(MP4/MKV/MOV/WebM)、转 GIF、提取或去除音轨,支持编码器/码率/帧率/缩放/裁切/图片水印、长任务取消,以及按能力开放的旋转、翻转、裁剪与变速处理", + "version": "2.1.0", + "minAppVersion": "1.3.0.0", "author": "ZTools Team", "entry": "dist/index.js", "icon": "icon.svg", @@ -16,12 +15,17 @@ "media", "productivity" ], + "requiredCapabilities": [ + "media.probe", + "media.transcode" + ], "permissions": [ "fs", - "video", "dialog", "shell", - "clipboard" + "clipboard", + "media.read", + "media.process" ], "requireAdmin": false, "nativeComponents": [], @@ -37,14 +41,15 @@ "i18n": { "en-US": { "name": "Batch Video Transcoder", - "description": "Import videos via file picker, folder, or drag-and-drop to batch convert to MP4, MKV, MOV, WebM, or GIF, or extract audio to MP3, M4A, or WAV using local ffmpeg (60s timeout per file). Saves alongside originals without overwriting.", + "description": "Import videos via picker, folder, or drag-and-drop to batch transcode (MP4/MKV/MOV/WebM), create GIFs, extract or strip audio, tune codecs/bitrate/FPS/scaling/trim/watermarks, cancel long jobs, plus capability-gated rotate, flip, crop, and speed.", "keywords": [ "video", "transcode", "convert", - "ffmpeg", "mp4", + "mkv", "gif", + "watermark", "extract audio" ] } diff --git a/extensions/batch-video/src/i18n.ts b/extensions/batch-video/src/i18n.ts index f5dce9a6..ed16ad75 100644 --- a/extensions/batch-video/src/i18n.ts +++ b/extensions/batch-video/src/i18n.ts @@ -1,243 +1,374 @@ -import { createTranslator } from "@ztools/declarative-ui"; +import { createTranslator } from '@ztools/declarative-ui' const rawT = createTranslator( { - "zh-CN": { - forbiddenReason: "视频处理路径不可指向系统受保护目录或包含路径穿越", - taskConvertTitle: "转换视频格式", - taskConvertSub: "重新编码为所选格式,编码器、画质和分辨率由 ffmpeg 按格式默认决定", - taskConvertTag: "格式转换", - taskGifTitle: "转为 GIF 动图", - taskGifSub: "按原分辨率和帧率转为 GIF(ffmpeg 默认设置),较长或高分辨率的视频生成的 GIF 体积很大", - taskGifTag: "转 GIF", - taskAudioTitle: "提取音频", - taskAudioSub: "去掉画面,只保留音轨并编码为所选格式(ffmpeg 默认设置)", - taskAudioTag: "提取音频", - formatWavUncompressed: "WAV(未压缩)", - errParamTooLong: "PARAM_TOO_LONG: 参数 {key} 超过最大长度限制", - errSecurityIntercepted: "SECURITY_INTERCEPTED: {reason}", - errInvalidMethodEmpty: "INVALID_METHOD: 调用方法名不能为空", - errInvalidMethodFormat: "INVALID_METHOD_FORMAT: 方法名包含非法字符或超长", - errInvalidParamsObject: "INVALID_PARAMS: 参数必须为非空对象", - errParamOutOfRange: "PARAM_OUT_OF_RANGE: 数值参数 {key} 越界或非有限数", - errValidationFailed: "参数校验失败", - errCannotGenUniqueName: "无法为输出文件生成不重复的文件名,已跳过该文件以免覆盖已有文件", - errHostReturnFailed: "宿主视频处理返回失败", - errHostTimeout: "处理时间超过宿主限制(单个文件 {seconds} 秒)被中止,可复制 ffmpeg 命令在终端中运行", - errFfmpegMissing: "本机未检测到 ffmpeg:请先安装 ffmpeg,并确认在命令行中可以直接运行 ffmpeg", - errHostDisconnected: "未连接 ZTools 客户端,无法处理视频", - errHostFailed: "宿主报告处理失败", - errHostNoResult: "宿主未返回处理结果,无法确认是否已生成输出文件", - errHostMissingOutput: "宿主返回的结果缺少输出文件路径或大小", - errUnsupportedFormat: "「{title}」不支持输出格式 {format}", - formatUnselected: "(未选择)", - tagPending: "未处理", - tagDone: "已输出 {size}", - tagFailed: "失败", - subOutput: "输出:{name}", - subFailed: "失败:{error}", - pickFilesTitle: "选择待处理的视频文件", - pickFilesFilterName: "视频文件", - pickFolderTitle: "选择包含视频的文件夹", - noFolderSelected: "没有选择文件夹", - importFailedTitle: "导入失败", - confirmRootTitle: "导入整个磁盘 {path} 中的视频?", - confirmRootMsg: "将读取该磁盘下 5 层以内的文件夹,最多导入 500 个视频,可能需要一些时间。", - confirmRootAction: "继续导入", - dropTitle: "拖入视频或文件夹", - dropSubtitle: "文件夹内 5 层以内的视频会一并导入", - busyWait: "正在处理视频,请等当前任务完成或先停止", - selectVideoFirst: "请先勾选要处理的视频", - processingTitle: "正在处理 {count} 个视频...", - processingMsg: "{title} · {format},单个文件最长 {seconds} 秒", - stoppedNoProcessed: "已停止,没有处理任何视频", - allFailedTitle: "{total} 个视频全部处理失败", - singleFailedTitle: "视频处理失败", - stoppedDefaultMsg: "已按要求停止", - partialTitle: "已输出 {done} 个,失败 {failed} 个{notStarted}", - partialNotStarted: ",未处理 {count} 个", - successTitle: "已输出 {done} 个文件", - successMsg: "共 {size},另存到源文件所在目录(*{suffix}*),原文件未改动", - processErrorTitle: "视频处理异常", - stoppingTitle: "将在当前文件处理完成后停止", - removeBusy: "该视频正在处理中,完成后再移除", - clearBusy: "正在处理,完成后再清空", - revealFailedTitle: "无法在资源管理器中显示", - revealSourceToastTitle: "已显示源文件,输出文件在同一目录", - copyFailedTitle: "复制失败", - sizeUnknown: "大小未识别", - unknownSizePart: ",{count} 个大小未识别", - actionPickFilesEllipsis: "选择文件…", - actionPickFolderEllipsis: "选择文件夹…", - actionStopProcessing: "停止处理(当前文件完成后停止)", - actionStartSelected: "开始处理已选视频 ({count} 个)", - actionRevealOutput: "在资源管理器中显示输出文件", - actionReveal: "在资源管理器中显示", - actionRunSingle: "仅处理此文件", - actionCopyFfmpeg: "复制等效 ffmpeg 命令", - copiedFfmpegTitle: "已复制 ffmpeg 命令", - actionCopyOutputPath: "复制输出文件路径", - copiedOutputPathTitle: "已复制输出文件路径", - sectionList: "列表", - actionRemove: "从列表移除", - actionDeselectAll: "取消全选当前列表", - actionSelectAll: "全选当前列表", - actionClearList: "清空列表", - resultSummaryPart: " · 已输出 {done} 个,失败 {failed} 个", - summaryImporting: "正在导入:已读取 {dirs} 个文件夹,找到 {files} 个文件", - summaryEmptyClient: "尚未添加视频 · 可选择文件、文件夹,或直接拖入", - hostRequired: "需要在 ZTools 客户端中使用", - summaryNormal: "已选 {selected}/{total} 个视频({bytes}){result} · 清空列表 Ctrl+Shift+Backspace", - emptyNoMatch: "没有匹配的视频文件", - searchPlaceholder: "搜索队列中的视频文件名或目录...", - dropdownTooltip: "选择处理任务", - dropdownItemTitle: "任务:{tag}", - btnPickFiles: "选择文件", - btnPickFolder: "选择文件夹", - wbTitle: "处理参数", - wbFormatLabel: "输出格式", - wbCodecLabel: "编码参数", - wbCodecValue: "ffmpeg 默认", - wbOutdirLabel: "输出位置", - wbOutdirValue: "源目录 *{suffix}*.{ext}", - wbLimitLabel: "单个文件时限", - wbLimitValue: "{seconds} 秒", - previewTitleResults: "处理结果", - previewTitleInfo: "处理说明", - previewBadgeResults: "成功 {done} / 失败 {failed}", - previewBadgePending: "尚未处理", - previewSubtitle: "{subtitle}。需要本机已安装 ffmpeg。输出文件名为「原名{suffix}」,同名文件已存在或无法确认时自动加序号或时间,不覆盖已有文件,也不修改原文件。", - metricDone: "已输出", - metricCountVal: "{count} 个", - metricFailed: "失败", - metricOutSize: "输出总大小", - metricSourceSize: "对应原文件", - subListTitle: "待处理视频(勾选后按 ↵ 开始处理)", - subListSubtitle: "{count} 个", - sectionQueueTitle: "待处理视频 ({count})" + 'zh-CN': { + forbiddenReason: '视频处理路径不可指向系统受保护目录或包含路径穿越', + hostRequired: '需要在 ZTools 客户端中使用', + engineChecking: '正在检测视频引擎…', + engineReady: '视频引擎就绪', + engineNeedsProvision: '需要下载视频引擎', + engineUnsupported: '当前客户端不支持视频引擎', + btnDownloadEngine: '下载视频引擎', + btnPickFiles: '选择文件', + btnPickFolder: '选择文件夹', + btnRunBatch: '开始转换 ({count})', + btnStopProcessing: '停止处理', + tagProcessing: '处理中', + btnCancelTask: '取消当前任务', + msgProvisionSuccess: '视频引擎已就绪', + msgCancelled: '已发送取消请求', + errProvisionFailed: '下载视频引擎失败:{error}', + errProbeFailed: '探测视频信息失败:{error}', + errTranscodeFailed: '视频转码失败:{error}', + errCancelFailed: '取消任务失败:{error}', + errHostDisconnected: '未连接 ZTools 客户端,无法处理视频', + errCannotGenUniqueName: '无法为输出文件生成不重复的文件名,已跳过该文件以免覆盖已有文件', + errUnsupportedFormat: '「{title}」不支持输出格式 {format}', + errInvalidTrim: '时间裁切参数无效(需为非负秒数,且结束时间大于开始时间)', + errInvalidCrop: '区域裁剪参数格式无效,请按 x,y,width,height 填写正整数', + errEngineNotReady: '视频引擎尚未就绪,请先下载视频引擎', + taskConvertTitle: '转换视频格式', + taskConvertSub: '支持自定义编码器、码率、帧率、缩放、时间裁切与图片水印', + taskConvertTag: '格式转换', + taskGifTitle: '转为 GIF 动图', + taskGifSub: '可设置缩放尺寸、帧率与时间裁切,控制动图体积', + taskGifTag: '转 GIF', + taskAudioTitle: '提取音频', + taskAudioSub: '提取视频中的音轨并转为 MP3 / AAC / FLAC / WAV / OGG', + taskAudioTag: '提取音频', + formatWavUncompressed: 'WAV(未压缩)', + tagPending: '待处理', + tagRunning: '转码中 {percent}%', + tagDone: '已输出 {size}', + tagFailed: '失败', + tagCancelled: '已取消', + subOutput: '输出:{name}', + subFailed: '失败:{error}', + subProbed: '{duration} · {meta}', + durationUnknown: '时长未知', + pickFilesTitle: '选择待处理的视频文件', + pickFilesFilterName: '视频文件', + pickFolderTitle: '选择包含视频的文件夹', + pickWatermarkTitle: '选择图片水印文件', + pickWatermarkFilter: '图片文件', + noFolderSelected: '没有选择文件夹', + importFailedTitle: '导入失败', + confirmRootTitle: '导入整个磁盘 {path} 中的视频?', + confirmRootMsg: '将读取该磁盘下 5 层以内的文件夹,最多导入 500 个视频,可能需要一些时间。', + confirmRootAction: '继续导入', + dropTitle: '拖入视频或文件夹', + dropSubtitle: '文件夹内 5 层以内的视频会一并导入', + busyWait: '正在处理视频,请等待当前任务完成或先取消', + selectVideoFirst: '请先勾选要处理的视频', + stoppedNoProcessed: '已取消,没有处理任何视频', + allFailedTitle: '{total} 个视频全部处理失败', + singleFailedTitle: '视频处理失败', + partialTitle: '已输出 {done} 个,失败 {failed} 个{cancelled}', + partialCancelledPart: ',已取消 {count} 个', + successTitle: '已输出 {done} 个文件', + successMsg: '共 {size},另存到源文件所在目录(*{suffix}*),原文件未改动', + removeBusy: '该视频正在处理中,完成后再移除', + clearBusy: '正在处理,请先取消或等待完成', + revealFailedTitle: '无法在文件管理器中显示', + revealSourceToastTitle: '已显示源文件,输出文件在同一目录', + copyFailedTitle: '复制失败', + copiedOutputPathTitle: '已复制输出文件路径', + watermarkClearedTitle: '已清除图片水印', + watermarkSetTitle: '已设置图片水印', + sizeUnknown: '大小未识别', + unknownSizePart: ',{count} 个大小未识别', + actionDownloadEngine: '下载视频引擎', + actionCancelProcessing: '取消当前转码任务', + actionStartSelected: '开始处理已选视频 ({count} 个)', + actionRevealOutput: '在文件管理器中显示输出文件', + actionReveal: '在文件管理器中显示', + actionRunSingle: '仅处理此文件', + actionProbeSingle: '重新探测视频元数据', + actionPickWatermark: '选择图片水印…', + actionClearWatermark: '清除图片水印', + actionCopyOutputPath: '复制输出文件路径', + actionPickFilesEllipsis: '选择文件…', + actionPickFolderEllipsis: '选择文件夹…', + sectionList: '队列与工具', + actionRemove: '从列表移除', + actionDeselectAll: '取消全选当前列表', + actionSelectAll: '全选当前列表', + actionClearList: '清空列表', + resultSummaryPart: ' · 已输出 {done} 个,失败 {failed} 个', + summaryImporting: '正在导入:已读取 {dirs} 个文件夹,找到 {files} 个文件', + summaryEmptyClient: '{engine} · 尚未添加视频 · 可选择文件、文件夹,或直接拖入', + summaryNormal: '{engine} · 已选 {selected}/{total} 个视频({bytes}){result}', + emptyNoMatch: '没有匹配的视频文件', + searchPlaceholder: '搜索队列中的视频文件名或目录…', + dropdownTooltip: '选择视频处理任务模式', + dropdownItemTitle: '模式:{tag}', + wbTitle: '视频转码参数', + wbFormatLabel: '输出格式', + wbVideoCodecLabel: '视频编码器', + wbBitrateLabel: '视频码率', + wbFpsLabel: '帧率 (FPS)', + wbScaleLabel: '画面缩放', + wbStripAudioLabel: '去除音轨 (静音)', + wbTrimStartLabel: '裁切起点 (秒)', + wbTrimEndLabel: '裁切终点 (秒)', + wbWatermarkPosLabel: '水印位置', + wbWatermarkFileLabel: '图片水印文件', + wbWatermarkUnset: '未设置(可在动作面板选择)', + wbRotateLabel: '画面旋转', + wbFlipLabel: '画面翻转', + wbCropLabel: '区域裁剪 (x,y,w,h)', + wbSpeedLabel: '视频变速', + wbEngineLabel: '引擎状态', + wbOutdirLabel: '输出位置', + wbOutdirValue: '源目录 *{suffix}*.{ext}', + codecAuto: '自动', + codecH264: 'H.264 (AVC)', + codecHevc: 'H.265 (HEVC)', + codecVp9: 'VP9', + codecAv1: 'AV1', + codecCopy: '直接复制视频流', + bitrateAuto: '自动码率', + bitrate1500: '1500 kbps (紧凑)', + bitrate3000: '3000 kbps (标准)', + bitrate6000: '6000 kbps (高清)', + bitrate12000: '12000 kbps (高码率)', + fpsSource: '保持原帧率', + fps15: '15 FPS', + fps24: '24 FPS', + fps30: '30 FPS', + fps60: '60 FPS', + scaleSource: '保持原分辨率', + scale1080: '宽度 1920 (1080p)', + scale720: '宽度 1280 (720p)', + scale480: '宽度 854 (480p)', + wmTopLeft: '左上角', + wmTopRight: '右上角', + wmBottomLeft: '左下角', + wmBottomRight: '右下角', + wmCenter: '居中', + rotateNone: '不旋转', + rotate90: '顺时针 90°', + rotate180: '旋转 180°', + rotate270: '顺时针 270°', + flipNone: '不翻转', + flipHorizontal: '水平镜像', + flipVertical: '垂直翻转', + flipBoth: '水平 + 垂直', + speed100: '原速 (1.0x)', + speed050: '0.5x 慢放', + speed075: '0.75x 慢放', + speed125: '1.25x 快放', + speed150: '1.5x 快放', + speed200: '2.0x 倍速', + previewTitleResults: '批处理结果', + previewTitleInfo: '视频引擎摘要', + previewBadgeResults: '成功 {done} / 失败 {failed}', + previewBadgeNeedsProvision: '需下载引擎', + previewBadgePending: '就绪', + previewSubtitle: '{subtitle} · 输出文件名自动追加 {suffix},不覆盖已有文件', + metricDone: '已输出', + metricCountVal: '{count} 个', + metricFailed: '失败', + metricOutSize: '输出总大小', + metricExtensions: '扩展特性', + extGeometry: '旋转/翻转/裁剪', + extSpeed: '变速', + extNone: '基础转码', + subListTitle: '待处理视频(勾选后按 Enter 开始处理)', + subListSubtitle: '{count} 个', + sectionQueueTitle: '待处理视频 ({count})' }, - "en-US": { - forbiddenReason: "Output path cannot point to a protected system directory or contain path traversal", - taskConvertTitle: "Convert Video Format", - taskConvertSub: "Re-encode to selected format using ffmpeg default codec, quality, and resolution", - taskConvertTag: "Convert", - taskGifTitle: "Convert to GIF", - taskGifSub: "Convert at original resolution and frame rate (long/HD videos produce large GIFs)", - taskGifTag: "To GIF", - taskAudioTitle: "Extract Audio", - taskAudioSub: "Strip video and encode audio track to selected format (ffmpeg defaults)", - taskAudioTag: "Extract Audio", - formatWavUncompressed: "WAV (Uncompressed)", - errParamTooLong: "PARAM_TOO_LONG: Parameter {key} exceeds maximum length", - errSecurityIntercepted: "SECURITY_INTERCEPTED: {reason}", - errInvalidMethodEmpty: "INVALID_METHOD: Method name cannot be empty", - errInvalidMethodFormat: "INVALID_METHOD_FORMAT: Method name contains invalid characters or is too long", - errInvalidParamsObject: "INVALID_PARAMS: Parameters must be a non-null object", - errParamOutOfRange: "PARAM_OUT_OF_RANGE: Numeric parameter {key} is out of range or non-finite", - errValidationFailed: "Parameter validation failed", - errCannotGenUniqueName: "Unable to generate a unique output filename; skipped to avoid overwriting", - errHostReturnFailed: "Host video processing failed", - errHostTimeout: "Processing timed out ({seconds}s limit per file); copy the ffmpeg command to run in terminal", - errFfmpegMissing: "ffmpeg not found: please install ffmpeg and ensure it is available on PATH", - errHostDisconnected: "Not connected to ZTools client; unable to process video", - errHostFailed: "Host reported processing failure", - errHostNoResult: "Host did not return processing result; cannot verify output file", - errHostMissingOutput: "Host result is missing output path or file size", - errUnsupportedFormat: "\"{title}\" does not support output format {format}", - formatUnselected: "(unselected)", - tagPending: "Pending", - tagDone: "Saved {size}", - tagFailed: "Failed", - subOutput: "Output: {name}", - subFailed: "Failed: {error}", - pickFilesTitle: "Select Video Files", - pickFilesFilterName: "Video Files", - pickFolderTitle: "Select Folder Containing Videos", - noFolderSelected: "No folder selected", - importFailedTitle: "Import Failed", - confirmRootTitle: "Import videos from entire drive {path}?", - confirmRootMsg: "Will scan up to 5 folder levels and import at most 500 videos. This may take a while.", - confirmRootAction: "Continue Import", - dropTitle: "Drop videos or folders", - dropSubtitle: "Videos within 5 folder levels will be imported", - busyWait: "Processing in progress; please wait or stop first", - selectVideoFirst: "Please check videos to process first", - processingTitle: "Processing {count} [[count:video|videos]]...", - processingMsg: "{title} · {format}, max {seconds}s per file", - stoppedNoProcessed: "Stopped; no videos processed", - allFailedTitle: "[[total:{total} video|All {total} videos]] failed", - singleFailedTitle: "Video Processing Failed", - stoppedDefaultMsg: "Stopped as requested", - partialTitle: "{done} saved, {failed} failed{notStarted}", - partialNotStarted: ", {count} skipped", - successTitle: "Saved {done} [[done:file|files]]", - successMsg: "{size} total, saved next to source (*{suffix}*); originals untouched", - processErrorTitle: "Video Processing Error", - stoppingTitle: "Stopping after current file finishes", - removeBusy: "Video is processing; remove after completion", - clearBusy: "Processing in progress; clear after completion", - revealFailedTitle: "Unable to Reveal in Explorer", - revealSourceToastTitle: "Revealed source file; output is in the same folder", - copyFailedTitle: "Copy Failed", - sizeUnknown: "Size unknown", - unknownSizePart: ", {count} unknown size", - actionPickFilesEllipsis: "Select Files…", - actionPickFolderEllipsis: "Select Folder…", - actionStopProcessing: "Stop (After Current File)", - actionStartSelected: "Process Selected ({count})", - actionRevealOutput: "Reveal Output in Explorer", - actionReveal: "Reveal in Explorer", - actionRunSingle: "Process This File Only", - actionCopyFfmpeg: "Copy Equivalent ffmpeg Command", - copiedFfmpegTitle: "Copied ffmpeg Command", - actionCopyOutputPath: "Copy Output Path", - copiedOutputPathTitle: "Copied Output Path", - sectionList: "List", - actionRemove: "Remove from List", - actionDeselectAll: "Deselect All", - actionSelectAll: "Select All", - actionClearList: "Clear List", - resultSummaryPart: " · {done} saved, {failed} failed", - summaryImporting: "Importing: {dirs} [[dirs:folder|folders]] scanned, {files} [[files:file|files]] found", - summaryEmptyClient: "No videos added · Select files, folder, or drop here", - hostRequired: "Requires the ZTools client", - summaryNormal: "Selected {selected}/{total} ({bytes}){result} · Clear Ctrl+Shift+Backspace", - emptyNoMatch: "No matching videos", - searchPlaceholder: "Search video filename or folder...", - dropdownTooltip: "Select Task", - dropdownItemTitle: "Task: {tag}", - btnPickFiles: "Select Files", - btnPickFolder: "Select Folder", - wbTitle: "Parameters", - wbFormatLabel: "Output Format", - wbCodecLabel: "Codec Settings", - wbCodecValue: "ffmpeg defaults", - wbOutdirLabel: "Output Location", - wbOutdirValue: "Source folder *{suffix}*.{ext}", - wbLimitLabel: "Per-File Timeout", - wbLimitValue: "{seconds}s", - previewTitleResults: "Results", - previewTitleInfo: "Notes", - previewBadgeResults: "{done} saved / {failed} failed", - previewBadgePending: "Pending", - previewSubtitle: "{subtitle}. Requires local ffmpeg. Outputs are named {suffix} with auto-suffix to avoid overwriting originals.", - metricDone: "Saved", - metricCountVal: "{count}", - metricFailed: "Failed", - metricOutSize: "Output Size", - metricSourceSize: "Source Size", - subListTitle: "Video Queue (Check items and press ↵ to start)", - subListSubtitle: "{count} [[count:item|items]]", - sectionQueueTitle: "Video Queue ({count})" + 'en-US': { + forbiddenReason: 'Output path cannot point to a protected system directory or contain path traversal', + hostRequired: 'Requires the ZTools client', + engineChecking: 'Checking video engine...', + engineReady: 'Video Engine Ready', + engineNeedsProvision: 'Video Engine Download Required', + engineUnsupported: 'Video Engine Unsupported', + btnDownloadEngine: 'Download Video Engine', + btnPickFiles: 'Select Files', + btnPickFolder: 'Select Folder', + btnRunBatch: 'Start ({count})', + btnStopProcessing: 'Stop', + tagProcessing: 'Processing', + btnCancelTask: 'Cancel Current Task', + msgProvisionSuccess: 'Video engine is ready', + msgCancelled: 'Cancellation requested', + errProvisionFailed: 'Failed to download video engine: {error}', + errProbeFailed: 'Failed to probe video metadata: {error}', + errTranscodeFailed: 'Video transcoding failed: {error}', + errCancelFailed: 'Failed to cancel task: {error}', + errHostDisconnected: 'Not connected to ZTools client; unable to process video', + errCannotGenUniqueName: 'Unable to generate a unique output filename; skipped to avoid overwriting', + errUnsupportedFormat: '"{title}" does not support output format {format}', + errInvalidTrim: 'Invalid trim range (must be non-negative seconds with end > start)', + errInvalidCrop: 'Invalid crop format; enter positive integers as x,y,width,height', + errEngineNotReady: 'Video engine is not ready; please download it first', + taskConvertTitle: 'Convert Video Format', + taskConvertSub: 'Custom video codec, bitrate, FPS, scaling, trim, and image watermark', + taskConvertTag: 'Convert', + taskGifTitle: 'Convert to GIF', + taskGifSub: 'Scale, limit FPS, and trim segments to control GIF file size', + taskGifTag: 'To GIF', + taskAudioTitle: 'Extract Audio', + taskAudioSub: 'Extract audio track into MP3 / AAC / FLAC / WAV / OGG', + taskAudioTag: 'Extract Audio', + formatWavUncompressed: 'WAV (Uncompressed)', + tagPending: 'Pending', + tagRunning: 'Encoding {percent}%', + tagDone: 'Saved {size}', + tagFailed: 'Failed', + tagCancelled: 'Cancelled', + subOutput: 'Output: {name}', + subFailed: 'Failed: {error}', + subProbed: '{duration} · {meta}', + durationUnknown: 'Unknown duration', + pickFilesTitle: 'Select Video Files', + pickFilesFilterName: 'Video Files', + pickFolderTitle: 'Select Folder Containing Videos', + pickWatermarkTitle: 'Select Watermark Image', + pickWatermarkFilter: 'Image Files', + noFolderSelected: 'No folder selected', + importFailedTitle: 'Import Failed', + confirmRootTitle: 'Import videos from entire drive {path}?', + confirmRootMsg: 'Scans up to 5 folder levels and imports at most 500 videos. This may take a while.', + confirmRootAction: 'Continue Import', + dropTitle: 'Drop Videos or Folders', + dropSubtitle: 'Videos within 5 folder levels will be imported', + busyWait: 'Processing in progress; please wait or cancel first', + selectVideoFirst: 'Please check videos to process first', + stoppedNoProcessed: 'Cancelled; no videos processed', + allFailedTitle: '[[total:{total} video|All {total} videos]] failed', + singleFailedTitle: 'Video Processing Failed', + partialTitle: '{done} saved, {failed} failed{cancelled}', + partialCancelledPart: ', {count} cancelled', + successTitle: 'Saved {done} [[done:file|files]]', + successMsg: '{size} total, saved next to originals (*{suffix}*); source files untouched', + removeBusy: 'Video is processing; remove after completion', + clearBusy: 'Processing in progress; cancel or wait first', + revealFailedTitle: 'Unable to Reveal in File Manager', + revealSourceToastTitle: 'Revealed source file; output is in the same folder', + copyFailedTitle: 'Copy Failed', + copiedOutputPathTitle: 'Copied Output Path', + watermarkClearedTitle: 'Watermark Cleared', + watermarkSetTitle: 'Watermark Image Selected', + sizeUnknown: 'Size unknown', + unknownSizePart: ', {count} unknown size', + actionDownloadEngine: 'Download Video Engine', + actionCancelProcessing: 'Cancel Current Transcode Task', + actionStartSelected: 'Process Selected ({count})', + actionRevealOutput: 'Reveal Output in File Manager', + actionReveal: 'Reveal in File Manager', + actionRunSingle: 'Process This File Only', + actionProbeSingle: 'Re-probe Video Metadata', + actionPickWatermark: 'Choose Watermark Image…', + actionClearWatermark: 'Clear Watermark Image', + actionCopyOutputPath: 'Copy Output Path', + actionPickFilesEllipsis: 'Select Files…', + actionPickFolderEllipsis: 'Select Folder…', + sectionList: 'Queue & Tools', + actionRemove: 'Remove from List', + actionDeselectAll: 'Deselect All', + actionSelectAll: 'Select All', + actionClearList: 'Clear List', + resultSummaryPart: ' · {done} saved, {failed} failed', + summaryImporting: 'Importing: {dirs} [[dirs:folder|folders]] scanned, {files} [[files:file|files]] found', + summaryEmptyClient: '{engine} · No videos added · Select files, folder, or drop here', + summaryNormal: '{engine} · Selected {selected}/{total} ({bytes}){result}', + emptyNoMatch: 'No matching videos', + searchPlaceholder: 'Search video filename or folder...', + dropdownTooltip: 'Select video processing mode', + dropdownItemTitle: 'Mode: {tag}', + wbTitle: 'Transcode Parameters', + wbFormatLabel: 'Output Format', + wbVideoCodecLabel: 'Video Codec', + wbBitrateLabel: 'Video Bitrate', + wbFpsLabel: 'Frame Rate (FPS)', + wbScaleLabel: 'Resolution Scale', + wbStripAudioLabel: 'Strip Audio (Mute)', + wbTrimStartLabel: 'Trim Start (sec)', + wbTrimEndLabel: 'Trim End (sec)', + wbWatermarkPosLabel: 'Watermark Position', + wbWatermarkFileLabel: 'Watermark Image', + wbWatermarkUnset: 'Not set (select in action panel)', + wbRotateLabel: 'Rotate', + wbFlipLabel: 'Flip', + wbCropLabel: 'Crop (x,y,w,h)', + wbSpeedLabel: 'Playback Speed', + wbEngineLabel: 'Engine Status', + wbOutdirLabel: 'Output Location', + wbOutdirValue: 'Source folder *{suffix}*.{ext}', + codecAuto: 'Auto', + codecH264: 'H.264 (AVC)', + codecHevc: 'H.265 (HEVC)', + codecVp9: 'VP9', + codecAv1: 'AV1', + codecCopy: 'Stream Copy', + bitrateAuto: 'Auto Bitrate', + bitrate1500: '1500 kbps (Compact)', + bitrate3000: '3000 kbps (Standard)', + bitrate6000: '6000 kbps (HD)', + bitrate12000: '12000 kbps (High)', + fpsSource: 'Keep Original FPS', + fps15: '15 FPS', + fps24: '24 FPS', + fps30: '30 FPS', + fps60: '60 FPS', + scaleSource: 'Keep Original Size', + scale1080: 'Width 1920 (1080p)', + scale720: 'Width 1280 (720p)', + scale480: 'Width 854 (480p)', + wmTopLeft: 'Top Left', + wmTopRight: 'Top Right', + wmBottomLeft: 'Bottom Left', + wmBottomRight: 'Bottom Right', + wmCenter: 'Center', + rotateNone: 'None', + rotate90: '90° CW', + rotate180: '180°', + rotate270: '270° CW', + flipNone: 'None', + flipHorizontal: 'Horizontal', + flipVertical: 'Vertical', + flipBoth: 'Horizontal + Vertical', + speed100: 'Normal (1.0x)', + speed050: '0.5x Slower', + speed075: '0.75x Slower', + speed125: '1.25x Faster', + speed150: '1.5x Faster', + speed200: '2.0x Double', + previewTitleResults: 'Results', + previewTitleInfo: 'Video Engine Summary', + previewBadgeResults: '{done} saved / {failed} failed', + previewBadgeNeedsProvision: 'Engine Required', + previewBadgePending: 'Ready', + previewSubtitle: '{subtitle} · Output appends {suffix} without overwriting existing files', + metricDone: 'Saved', + metricCountVal: '{count}', + metricFailed: 'Failed', + metricOutSize: 'Output Size', + metricExtensions: 'Extensions', + extGeometry: 'Rotate / Flip / Crop', + extSpeed: 'Speed', + extNone: 'Core Transcode', + subListTitle: 'Video Queue (Check items and press Enter to start)', + subListSubtitle: '{count} [[count:item|items]]', + sectionQueueTitle: 'Video Queue ({count})' } - } + }, + { defaultLocale: 'en-US' } ) + export const t: typeof rawT = (key, params) => { const out = rawT(key, params) if (!out.includes('[[')) return out - return out.replace(/\[\[([A-Za-z0-9_.-]+):([^|\]]+)\|([^\]]+)\]\]/g, (_m, k: string, one: string, other: string) => { - const v = params?.[k] - const n = typeof v === 'number' ? v : Number(String(v ?? '').replace(/,/g, '')) - return n === 1 ? one : other - }) + return out.replace( + /\[\[([A-Za-z0-9_.-]+):([^|\]]+)\|([^\]]+)\]\]/g, + (_m, k: string, one: string, other: string) => { + const v = params?.[k] + const n = typeof v === 'number' ? v : Number(String(v ?? '').replace(/,/g, '')) + return n === 1 ? one : other + } + ) } diff --git a/extensions/batch-video/src/index.ts b/extensions/batch-video/src/index.ts index b227d5d1..3631f119 100644 --- a/extensions/batch-video/src/index.ts +++ b/extensions/batch-video/src/index.ts @@ -1,96 +1,179 @@ +/** + * 批量视频处理界面(标准布局三:左侧参数工作台 + 右侧视频队列) + * + * - 启动调用 tool_runtime_capabilities,needs_provisioning 展示「下载视频引擎」并调 tool_runtime_ensure + * - 导入视频后自动调用 tool_media_probe 探测分辨率/帧率/编码/时长 + * - 支持格式转换、编码器、码率、帧率、缩放、时间裁切、抽音轨、去音轨、转 GIF、图片水印 + * - 决策 7 特性探测: + * * rotate / flip / crop 仅在 optionalExtensions 包含 'geometry' 时渲染并发送 + * * speedFactor 仅在 optionalExtensions 包含 'speed' 时渲染并发送 + * - 长任务运行中支持 tool_task_cancel 实时取消并接收 tool_runtime_progress 实时进度 + */ + import { - List, - ActionPanel, Action, - Icon, + ActionPanel, Clipboard, - useState, - useEffect, - useRef, - showToast, + Color, + Icon, + List, Toast, confirmAlert, - FilterBar, - useLocale + showToast, + useEffect, + useLocale, + useRef, + useState } from '@ztools/declarative-ui' import { t } from './i18n.js' +import { resolveErrorMessage } from './error-i18n.js' import { - RealVideoFileItem, - VideoProcessOutcome, - VideoTaskId, - HOST_FFMPEG_LIMIT_SECONDS, OUTPUT_SUFFIX, VIDEO_IMPORT_RULES, VIDEO_IMPORT_SUPPORTED_TEXT, - buildFfmpegCommand, + cancelVideoTask, createVideoImportTransport, - describeOutcomeSubtitle, - describeOutcomeTag, + ensureVideoEngine, fileNameOf, formatBytes, + formatDuration, getVideoTask, getVideoTasks, + isRealElectronHost, + parseCropExpression, pickVideoFolderWithConfirm, + probeVideoCapabilities, + probeVideoFiles, processVideoBatch, resolveOutputFormat, revealVideoInFolder, selectVideoFiles, + selectWatermarkImage, summarizeOutcomes, - toVideoItem + toVideoItem, + type MediaContainerFormat, + type MediaFlipMode, + type MediaRotateDegrees, + type MediaVideoCodec, + type MediaWatermarkPosition, + type RealVideoFileItem, + type VideoCapabilityState, + type VideoProcessOutcome, + type VideoProcessSettings, + type VideoTaskId } from './logic.js' -import { isRealElectronHost } from './native-ipc.js' import { isDeclarativeFileInputSupported } from './host-compat.js' import { - FileImportResult, - NormalizedFileInput, createImportInputProps, expandInputPaths, friendlyFileError, mergeByPath, normalizeFileInput, - summarizeImport + summarizeImport, + type FileImportResult, + type NormalizedFileInput } from './file-import.js' +import { subscribeLegacyFileDrop, subscribeRuntimeProgress } from './tool-runtime.js' export * from './logic.js' -const DEFAULT_FORMATS: Record = { +const DEFAULT_FORMATS: Record = { 'convert-video': 'mp4', 'to-gif': 'gif', 'extract-audio': 'mp3' } -function errorText(err: unknown): string { - return err instanceof Error ? err.message : String(err) -} - export function BatchVideoCommand() { useLocale() + const inClient = isRealElectronHost() const videoTasks = getVideoTasks() const transport = createVideoImportTransport() - const [searchText, setSearchText] = useState('') - const [taskId, setTaskId] = useState(videoTasks[0]!.id) - const [formatByTask, setFormatByTask] = useState>(DEFAULT_FORMATS) + + const [capability, setCapability] = useState({ + probeStatus: inClient ? 'needs_provisioning' : 'unsupported', + transcodeStatus: inClient ? 'needs_provisioning' : 'unsupported', + overallStatus: inClient ? 'needs_provisioning' : 'unsupported', + extensions: { geometry: false, speed: false } + }) + const [capChecked, setCapChecked] = useState(!inClient) + const [searchText, setSearchText] = useState('') + const [taskId, setTaskId] = useState('convert-video') + const [formatByTask, setFormatByTask] = useState>(DEFAULT_FORMATS) + const [videoCodec, setVideoCodec] = useState('auto') + const [videoBitrateKbps, setVideoBitrateKbps] = useState('auto') + const [frameRate, setFrameRate] = useState('source') + const [scaleWidth, setScaleWidth] = useState('source') + const [stripAudio, setStripAudio] = useState(false) + const [trimStartText, setTrimStartText] = useState('') + const [trimEndText, setTrimEndText] = useState('') + const [watermarkPath, setWatermarkPath] = useState('') + const [watermarkPosition, setWatermarkPosition] = useState('bottom-right') + const [rotateDeg, setRotateDeg] = useState('0') + const [flipMode, setFlipMode] = useState('none') + const [cropText, setCropText] = useState('') + const [speedFactor, setSpeedFactor] = useState('1') + const [files, setFiles] = useState([]) const [checkedIds, setCheckedIds] = useState([]) - const [isImporting, setIsImporting] = useState(false) + const [isImporting, setIsImporting] = useState(false) const [importProgress, setImportProgress] = useState<{ visitedDirs: number; matchedFiles: number } | null>(null) - const [running, setRunning] = useState(false) - const [runningIds, setRunningIds] = useState([]) + const [running, setRunning] = useState(false) + const [isProvisioning, setIsProvisioning] = useState(false) + const [runningItemId, setRunningItemId] = useState(null) - const runningRef = useRef(false) - const stopRef = useRef(false) - const importTicketRef = useRef(0) + const mountedRef = useRef(true) + const runningRef = useRef(false) + const stopRef = useRef(false) + const activeTaskIdRef = useRef(null) + const activeItemIdRef = useRef(null) + const importTicketRef = useRef(0) const importAbortRef = useRef(null) - const filesRef = useRef(files) + const filesRef = useRef([]) filesRef.current = files - const stopToastRef = useRef<{ hide: () => Promise | void } | null>(null) + const capabilityRef = useRef(capability) + capabilityRef.current = capability + + const refreshCapabilities = async () => { + if (!inClient) { + setCapChecked(true) + return + } + const state = await probeVideoCapabilities() + if (!mountedRef.current) return + capabilityRef.current = state + setCapability(state) + setCapChecked(true) + } + + const probeAddedItems = async (items: readonly RealVideoFileItem[]) => { + if (!inClient || items.length === 0 || capabilityRef.current.probeStatus !== 'ready') return + const res = await probeVideoFiles(items.map((item) => item.path)) + if (!mountedRef.current || !res.ok) return + const map = new Map() + items.forEach((item, index) => { + const meta = res.items[index] + if (meta) map.set(item.id, meta) + }) + if (map.size === 0) return + const next = filesRef.current.map((item) => { + const meta = map.get(item.id) + if (!meta) return item + return { + ...item, + probe: meta, + ...(item.sizeBytes === null && meta.sizeBytes > 0 ? { sizeBytes: meta.sizeBytes } : {}) + } + }) + filesRef.current = next + setFiles(next) + } - async function importWithTicket( + const importWithTicket = async ( executor: ( signal: AbortSignal, onProgress: (progress: { visitedDirs: number; matchedFiles: number }) => void ) => Promise - ) { + ) => { importAbortRef.current?.abort() const controller = new AbortController() importAbortRef.current = controller @@ -98,16 +181,17 @@ export function BatchVideoCommand() { setIsImporting(true) setImportProgress(null) try { - const result = await executor(controller.signal, progress => { - if (ticket === importTicketRef.current) setImportProgress(progress) + const result = await executor(controller.signal, (progress) => { + if (mountedRef.current && ticket === importTicketRef.current) setImportProgress(progress) }) - if (ticket !== importTicketRef.current) return + if (!mountedRef.current || ticket !== importTicketRef.current) return const incoming = result.files.map(toVideoItem) - const { merged, added, duplicates } = mergeByPath(filesRef.current, incoming, item => item.path) + const { merged, added, duplicates } = mergeByPath(filesRef.current, incoming, (item) => item.path) if (added.length > 0) { filesRef.current = merged setFiles(merged) - setCheckedIds(prev => Array.from(new Set([...prev, ...added.map(item => item.id)]))) + setCheckedIds((prev) => Array.from(new Set([...prev, ...added.map((item) => item.id)]))) + void probeAddedItems(added) } const notice = summarizeImport(result, { added: added.length, duplicates }, VIDEO_IMPORT_SUPPORTED_TEXT) if (notice) { @@ -118,10 +202,10 @@ export function BatchVideoCommand() { }) } } catch (err) { - if (ticket !== importTicketRef.current) return + if (!mountedRef.current || ticket !== importTicketRef.current) return void showToast({ style: Toast.Style.Failure, title: t('importFailedTitle'), message: friendlyFileError(err) }) } finally { - if (ticket === importTicketRef.current) { + if (mountedRef.current && ticket === importTicketRef.current) { importAbortRef.current = null setIsImporting(false) setImportProgress(null) @@ -129,15 +213,15 @@ export function BatchVideoCommand() { } } - function handleAddVideoFiles() { + const handleAddVideoFiles = () => { void importWithTicket(() => selectVideoFiles()) } - function handleAddVideoFolder() { + const handleAddVideoFolder = () => { void importWithTicket((signal, onProgress) => pickVideoFolderWithConfirm( transport, - folderPath => + (folderPath) => confirmAlert({ title: t('confirmRootTitle', { path: folderPath }), message: t('confirmRootMsg'), @@ -148,7 +232,7 @@ export function BatchVideoCommand() { ) } - function handleVideoFileInput(input: NormalizedFileInput) { + const handleVideoFileInput = (input: NormalizedFileInput) => { void importWithTicket((signal, onProgress) => expandInputPaths(transport, input.paths, VIDEO_IMPORT_RULES, { knownDirectories: input.directories, @@ -158,103 +242,199 @@ export function BatchVideoCommand() { ) } + const handlePickWatermark = async () => { + const res = await selectWatermarkImage() + if (res.canceled || res.files.length === 0) return + const path = res.files[0].path + setWatermarkPath(path) + await showToast({ style: Toast.Style.Success, title: t('watermarkSetTitle'), message: fileNameOf(path) }) + } + + const handleDownloadEngine = async () => { + if (!inClient || isProvisioning) return + setIsProvisioning(true) + try { + const res = await ensureVideoEngine() + if (!mountedRef.current) return + await showToast({ style: res.ok ? Toast.Style.Success : Toast.Style.Failure, title: res.message }) + await refreshCapabilities() + if (res.ok && filesRef.current.length > 0) { + const unprobed = filesRef.current.filter((item) => !item.probe) + if (unprobed.length > 0) void probeAddedItems(unprobed) + } + } finally { + if (mountedRef.current) setIsProvisioning(false) + } + } + useEffect(() => { - let disposeDrop: (() => void) | undefined - if (!isDeclarativeFileInputSupported()) { - const w = typeof window !== 'undefined' ? (window as { ztools?: { events?: { on?: (event: string, cb: (env: unknown) => void) => (() => void) | void; off?: (event: string, cb: (env: unknown) => void) => void } } }) : null - const eventsApi = w?.ztools?.events - if (eventsApi && typeof eventsApi.on === 'function') { - const onDrop = (envelope: unknown) => { + mountedRef.current = true + void refreshCapabilities() + + const unsubProgress = subscribeRuntimeProgress((event) => { + if (!mountedRef.current || !activeTaskIdRef.current || event.taskId !== activeTaskIdRef.current) return + const itemId = activeItemIdRef.current + if (!itemId || typeof event.percent !== 'number' || !Number.isFinite(event.percent)) return + const clamped = Math.max(0, Math.min(100, Math.round(event.percent))) + const next = filesRef.current.map((item) => + item.id === itemId ? { ...item, progressPercent: clamped } : item + ) + filesRef.current = next + setFiles(next) + }) + + const disposeDrop = isDeclarativeFileInputSupported() + ? undefined + : subscribeLegacyFileDrop((envelope) => { const parsed = normalizeFileInput(envelope) if (parsed.paths.length > 0) handleVideoFileInput(parsed) - } - const off = eventsApi.on('plugin_files_dropped', onDrop) - disposeDrop = () => { - if (typeof off === 'function') off() - else if (typeof eventsApi.off === 'function') eventsApi.off('plugin_files_dropped', onDrop) - } - } - } + }) + return () => { + mountedRef.current = false importTicketRef.current += 1 importAbortRef.current?.abort() + unsubProgress() disposeDrop?.() } }, []) - const fileInputProps = createImportInputProps(handleVideoFileInput, { - dropTitle: t('dropTitle'), - dropSubtitle: t('dropSubtitle') - }) - const activeTask = getVideoTask(taskId) const activeFormat = resolveOutputFormat(activeTask, formatByTask[taskId]) || activeTask.formats[0]!.value - async function executeBatch(targets: RealVideoFileItem[]) { + const handleCancelCurrentTask = async () => { + stopRef.current = true + const currentTaskId = activeTaskIdRef.current + if (!currentTaskId) return + const res = await cancelVideoTask(currentTaskId) + if (!mountedRef.current) return + await showToast({ + style: res.ok ? Toast.Style.Success : Toast.Style.Failure, + title: res.ok ? t('msgCancelled') : resolveErrorMessage(res, t('stoppedNoProcessed')) + }) + } + + const executeBatch = async (targets: RealVideoFileItem[]) => { if (runningRef.current) { await showToast({ style: Toast.Style.Failure, title: t('busyWait') }) return } + if (!inClient) { + await showToast({ style: Toast.Style.Failure, title: t('errHostDisconnected') }) + return + } + if (capabilityRef.current.overallStatus === 'needs_provisioning') { + await handleDownloadEngine() + return + } + if (capabilityRef.current.overallStatus !== 'ready') { + await showToast({ style: Toast.Style.Failure, title: t('errEngineNotReady') }) + return + } if (targets.length === 0) { await showToast({ style: Toast.Style.Failure, title: t('selectVideoFirst') }) return } - const settings = { taskId, format: activeFormat } + + // 校验时间裁切参数 + const rawStart = trimStartText.trim() + const rawEnd = trimEndText.trim() + const parsedStart = rawStart ? Number(rawStart) : undefined + const parsedEnd = rawEnd ? Number(rawEnd) : undefined + if ( + (parsedStart !== undefined && (!Number.isFinite(parsedStart) || parsedStart < 0)) || + (parsedEnd !== undefined && (!Number.isFinite(parsedEnd) || parsedEnd <= 0)) || + (parsedStart !== undefined && parsedEnd !== undefined && parsedEnd <= parsedStart) + ) { + await showToast({ style: Toast.Style.Failure, title: t('errInvalidTrim') }) + return + } + + // 校验区域裁剪参数(仅在支持 geometry 时) + const cropParsed = capabilityRef.current.extensions.geometry ? parseCropExpression(cropText) : { valid: true } + if (!cropParsed.valid) { + await showToast({ style: Toast.Style.Failure, title: t('errInvalidCrop') }) + return + } + + const settings: VideoProcessSettings = { + taskId, + format: activeFormat, + ...(videoCodec !== 'auto' ? { videoCodec: videoCodec as MediaVideoCodec } : {}), + ...(videoBitrateKbps !== 'auto' ? { videoBitrateKbps: Number(videoBitrateKbps) } : {}), + ...(frameRate !== 'source' ? { frameRate: Number(frameRate) } : {}), + ...(scaleWidth !== 'source' ? { scaleWidth: Number(scaleWidth) } : {}), + ...(stripAudio ? { stripAudio: true } : {}), + ...(parsedStart !== undefined ? { trimStartSec: parsedStart } : {}), + ...(parsedEnd !== undefined ? { trimEndSec: parsedEnd } : {}), + ...(watermarkPath ? { watermarkPath, watermarkPosition } : {}), + ...(capabilityRef.current.extensions.geometry && rotateDeg !== '0' + ? { rotate: Number(rotateDeg) as MediaRotateDegrees } + : {}), + ...(capabilityRef.current.extensions.geometry && flipMode !== 'none' + ? { flip: flipMode as MediaFlipMode } + : {}), + ...(capabilityRef.current.extensions.geometry && cropParsed.crop ? { crop: cropParsed.crop } : {}), + ...(capabilityRef.current.extensions.speed && Number(speedFactor) !== 1 + ? { speedFactor: Number(speedFactor) } + : {}) + } + runningRef.current = true stopRef.current = false setRunning(true) - let progressToast: { hide: () => Promise | void } | null = null const appliedOutcomes = new Map() try { - progressToast = await showToast({ - style: Toast.Style.Animated, - title: t('processingTitle', { count: targets.length }), - message: t('processingMsg', { - title: activeTask.title, - format: activeFormat.toUpperCase(), - seconds: HOST_FFMPEG_LIMIT_SECONDS - }) - }) - await processVideoBatch(targets, settings, { - shouldSkip: id => !filesRef.current.some(item => item.id === id), - onStart: id => setRunningIds([id]), - onItem: (id: string, outcome: VideoProcessOutcome) => { - setRunningIds(prev => prev.filter(item => item !== id)) - if (!filesRef.current.some(item => item.id === id)) return - appliedOutcomes.set(id, outcome) - const next = filesRef.current.map(item => (item.id === id ? { ...item, result: outcome } : item)) + await processVideoBatch(targets, settings, capabilityRef.current.extensions, { + shouldSkip: (id) => !filesRef.current.some((item) => item.id === id), + shouldStop: () => stopRef.current, + onStart: (id, tid) => { + activeItemIdRef.current = id + activeTaskIdRef.current = tid + setRunningItemId(id) + const next = filesRef.current.map((item) => + item.id === id ? { ...item, progressPercent: 0 } : item + ) filesRef.current = next setFiles(next) }, - shouldStop: () => stopRef.current + onItem: (id, outcome) => { + if (activeItemIdRef.current === id) { + activeItemIdRef.current = null + activeTaskIdRef.current = null + } + setRunningItemId((curr) => (curr === id ? null : curr)) + appliedOutcomes.set(id, outcome) + const next = filesRef.current.map((item) => + item.id === id ? { ...item, result: outcome, progressPercent: undefined } : item + ) + filesRef.current = next + setFiles(next) + } }) - await progressToast?.hide() - if (appliedOutcomes.size === 0 && !stopRef.current) return + if (!mountedRef.current) return const summary = summarizeOutcomes(appliedOutcomes.values()) - const notStarted = targets.length - summary.total - + if (summary.done === 0 && summary.failed === 0) { + await showToast({ style: Toast.Style.Failure, title: t('stoppedNoProcessed') }) + return + } if (summary.done === 0) { await showToast({ style: Toast.Style.Failure, - title: - summary.total === 0 - ? t('stoppedNoProcessed') - : summary.total > 1 - ? t('allFailedTitle', { total: summary.total }) - : t('singleFailedTitle'), - message: summary.firstError || t('stoppedDefaultMsg') + title: summary.total > 1 ? t('allFailedTitle', { total: summary.total }) : t('singleFailedTitle'), + message: summary.firstError }) return } - if (summary.failed > 0 || notStarted > 0) { + if (summary.failed > 0 || summary.cancelled > 0) { await showToast({ style: Toast.Style.Failure, title: t('partialTitle', { done: summary.done, failed: summary.failed, - notStarted: notStarted > 0 ? t('partialNotStarted', { count: notStarted }) : '' + cancelled: summary.cancelled > 0 ? t('partialCancelledPart', { count: summary.cancelled }) : '' }), - message: summary.firstError || t('stoppedDefaultMsg') + message: summary.firstError }) return } @@ -263,37 +443,30 @@ export function BatchVideoCommand() { title: t('successTitle', { done: summary.done }), message: t('successMsg', { size: formatBytes(summary.outputBytes), suffix: OUTPUT_SUFFIX }) }) - } catch (err) { - await showToast({ style: Toast.Style.Failure, title: t('processErrorTitle'), message: friendlyFileError(err) }) } finally { - await progressToast?.hide() - await stopToastRef.current?.hide() - stopToastRef.current = null - setRunningIds([]) + activeTaskIdRef.current = null + activeItemIdRef.current = null runningRef.current = false stopRef.current = false - setRunning(false) + if (mountedRef.current) { + setRunningItemId(null) + setRunning(false) + } } } - async function requestStop() { - if (!runningRef.current) return - stopRef.current = true - stopToastRef.current = await showToast({ style: Toast.Style.Animated, title: t('stoppingTitle') }) - } - - function handleRemoveVideo(file: RealVideoFileItem) { - if (runningIds.includes(file.id)) { + const handleRemoveVideo = (file: RealVideoFileItem) => { + if (runningItemId === file.id) { void showToast({ style: Toast.Style.Failure, title: t('removeBusy') }) return } - const next = filesRef.current.filter(item => item.id !== file.id) + const next = filesRef.current.filter((item) => item.id !== file.id) filesRef.current = next setFiles(next) - setCheckedIds(prev => prev.filter(id => id !== file.id)) + setCheckedIds((prev) => prev.filter((id) => id !== file.id)) } - function handleClearVideos() { + const handleClearVideos = () => { if (runningRef.current) { void showToast({ style: Toast.Style.Failure, title: t('clearBusy') }) return @@ -308,7 +481,7 @@ export function BatchVideoCommand() { setCheckedIds([]) } - async function handleReveal(file: RealVideoFileItem) { + const handleReveal = async (file: RealVideoFileItem) => { const shown = await revealVideoInFolder(file) if (shown === 'failed') { await showToast({ style: Toast.Style.Failure, title: t('revealFailedTitle'), message: file.path }) @@ -323,41 +496,51 @@ export function BatchVideoCommand() { } } - async function copyText(text: string, title: string) { - try { - await Clipboard.copy(text) - await showToast({ style: Toast.Style.Success, title, message: text }) - } catch (err) { - await showToast({ style: Toast.Style.Failure, title: t('copyFailedTitle'), message: errorText(err) }) - } - } + const fileInputProps = createImportInputProps(handleVideoFileInput, { + dropTitle: t('dropTitle'), + dropSubtitle: t('dropSubtitle') + }) const q = searchText.trim().toLowerCase() - const filteredFiles = files.filter(f => !q || f.name.toLowerCase().includes(q) || f.path.toLowerCase().includes(q)) - const selectedFiles = files.filter(f => checkedIds.includes(f.id)) + const filteredFiles = files.filter( + (f) => !q || f.name.toLowerCase().includes(q) || f.path.toLowerCase().includes(q) + ) + const selectedFiles = files.filter((f) => checkedIds.includes(f.id)) const selectedKnownBytes = selectedFiles.reduce((sum, f) => sum + (f.sizeBytes ?? 0), 0) - const selectedUnknownCount = selectedFiles.filter(f => f.sizeBytes === null).length + const selectedUnknownCount = selectedFiles.filter((f) => f.sizeBytes === null).length const selectedBytesText = selectedFiles.length > 0 && selectedUnknownCount === selectedFiles.length ? t('sizeUnknown') : `${formatBytes(selectedKnownBytes)}${selectedUnknownCount > 0 ? t('unknownSizePart', { count: selectedUnknownCount }) : ''}` - const doneFiles = files.filter(f => f.result?.status === 'done') - const doneKnownSourceBytes = doneFiles.reduce((sum, f) => sum + (f.sizeBytes ?? 0), 0) + const resultSummary = summarizeOutcomes( - files.map(f => f.result).filter((r): r is VideoProcessOutcome => Boolean(r)) + files.map((f) => f.result).filter((r): r is VideoProcessOutcome => Boolean(r)) ) const hasResults = resultSummary.total > 0 - const allFilteredChecked = filteredFiles.length > 0 && filteredFiles.every(f => checkedIds.includes(f.id)) - const maxVideoBytes = Math.max(1, ...files.map(f => f.sizeBytes ?? 0)) - - /** 勾选 / 取消勾选当前搜索结果里的全部视频,不影响搜索结果以外已勾选的项 */ - function setFilteredChecked(checked: boolean) { - const filteredIds = new Set(filteredFiles.map(f => f.id)) - setCheckedIds(prev => - checked ? Array.from(new Set([...prev, ...filteredIds])) : prev.filter(id => !filteredIds.has(id)) + const allFilteredChecked = filteredFiles.length > 0 && filteredFiles.every((f) => checkedIds.includes(f.id)) + + const setFilteredChecked = (checked: boolean) => { + const filteredIds = new Set(filteredFiles.map((f) => f.id)) + setCheckedIds((prev) => + checked ? Array.from(new Set([...prev, ...filteredIds])) : prev.filter((id) => !filteredIds.has(id)) ) } + const engineStatusText = !capChecked + ? t('engineChecking') + : capability.overallStatus === 'ready' + ? t('engineReady') + : capability.overallStatus === 'needs_provisioning' + ? t('engineNeedsProvision') + : t('engineUnsupported') + + const extensionsSummaryText = (() => { + const parts: string[] = [] + if (capability.extensions.geometry) parts.push(t('extGeometry')) + if (capability.extensions.speed) parts.push(t('extSpeed')) + return parts.length > 0 ? parts.join(' · ') : t('extNone') + })() + const pickFilesAction = () => Action({ title: t('actionPickFilesEllipsis'), @@ -365,6 +548,7 @@ export function BatchVideoCommand() { shortcut: { modifiers: ['ctrl'], key: 'o' }, onAction: handleAddVideoFiles }) + const pickFolderAction = () => Action({ title: t('actionPickFolderEllipsis'), @@ -373,234 +557,542 @@ export function BatchVideoCommand() { onAction: handleAddVideoFolder }) - const rightQueueItems = filteredFiles.map(f => { + const rightQueueItems = filteredFiles.map((f) => { const doneResult = f.result?.status === 'done' ? f.result : null - const isItemRunning = runningIds.includes(f.id) + const isItemRunning = runningItemId === f.id const accessories: Array> = [] - if (f.sizeBytes !== null) { - accessories.push({ progress: { value: Math.max(8, Math.min(100, Math.round((f.sizeBytes / maxVideoBytes) * 100))) } }) + if (isItemRunning) { + const pct = typeof f.progressPercent === 'number' ? f.progressPercent : 0 + accessories.push({ progress: pct / 100 }) + accessories.push({ tag: { value: pct > 0 ? t('tagRunning', { percent: pct }) : t('tagProcessing') } }) + } else if (f.result?.status === 'done') { + accessories.push({ tag: { value: t('tagDone', { size: formatBytes(f.result.outputBytes) }) } }) + } else if (f.result?.status === 'failed') { + accessories.push({ tag: { value: t('tagFailed'), color: Color.Red } }) + } else if (f.result?.status === 'cancelled') { + accessories.push({ tag: { value: t('tagCancelled') } }) + } else { + accessories.push({ tag: { value: t('tagPending') } }) } - accessories.push({ tag: { value: describeOutcomeTag(f.result) } }) accessories.push({ text: f.sizeBytes === null ? t('sizeUnknown') : formatBytes(f.sizeBytes) }) - const actionChildren: Array | ReturnType> = [ - running + let subtitle = f.parentDir + if (f.result?.status === 'done') { + subtitle = t('subOutput', { name: fileNameOf(f.result.outputPath) }) + } else if (f.result?.status === 'failed') { + subtitle = t('subFailed', { error: f.result.error }) + } else if (f.probe) { + const meta = [ + f.probe.width && f.probe.height ? `${f.probe.width}x${f.probe.height}` : '', + f.probe.videoCodec?.toUpperCase(), + f.probe.frameRate ? `${Math.round(f.probe.frameRate)}fps` : '' + ] + .filter(Boolean) + .join(' · ') + subtitle = t('subProbed', { duration: formatDuration(f.probe.durationSec), meta: meta || f.parentDir }) + } + + const primaryAction = running + ? Action({ + title: t('actionCancelProcessing'), + icon: Icon.Stop, + style: Action.Style.Destructive, + onAction: handleCancelCurrentTask + }) + : capability.overallStatus === 'needs_provisioning' ? Action({ - title: t('actionStopProcessing'), - icon: Icon.Stop, - onAction: requestStop + title: t('actionDownloadEngine'), + icon: Icon.Download, + onAction: handleDownloadEngine }) : Action({ title: t('actionStartSelected', { count: selectedFiles.length }), icon: Icon.Bolt, onAction: () => executeBatch(selectedFiles) - }), - Action({ - title: doneResult ? t('actionRevealOutput') : t('actionReveal'), - icon: Icon.Folder, - shortcut: { modifiers: ['ctrl'], key: 'enter' }, - onAction: () => handleReveal(f) - }), - Action({ - title: t('actionRunSingle'), - icon: Icon.Play, - onAction: () => executeBatch([f]) - }), - Action({ - title: t('actionCopyFfmpeg'), - icon: Icon.Terminal, - onAction: () => copyText(buildFfmpegCommand(f.path, activeFormat), t('copiedFfmpegTitle')) - }) - ] - if (doneResult) { - actionChildren.push( - Action({ - title: t('actionCopyOutputPath'), - icon: Icon.CopyClipboard, - onAction: () => copyText(doneResult.outputPath, t('copiedOutputPathTitle')) - }) - ) - } - actionChildren.push( - ActionPanel.Section({ - title: t('sectionList'), - children: [ - ...(isItemRunning - ? [] - : [ - Action({ - title: t('actionRemove'), - icon: Icon.Minus, - shortcut: { modifiers: ['ctrl'], key: 'backspace' }, - onAction: () => handleRemoveVideo(f) - }) - ]), - pickFilesAction(), - pickFolderAction(), - Action({ - title: allFilteredChecked ? t('actionDeselectAll') : t('actionSelectAll'), - icon: Icon.CheckCircle, - shortcut: { modifiers: ['ctrl'], key: 'a' }, - onAction: () => setFilteredChecked(!allFilteredChecked) - }), - Action({ - title: t('actionClearList'), - icon: Icon.Trash, - style: Action.Style.Destructive, - shortcut: { modifiers: ['ctrl', 'shift'], key: 'backspace' }, - onAction: handleClearVideos }) - ] - }) - ) return List.Item({ id: f.id, title: f.name, - subtitle: describeOutcomeSubtitle(f), + subtitle, checkable: true, checked: checkedIds.includes(f.id), - onCheckChange: c => { - setCheckedIds(prev => (c ? Array.from(new Set([...prev, f.id])) : prev.filter(id => id !== f.id))) - }, - icon: { - source: Icon.Video + onCheckChange: (c) => { + setCheckedIds((prev) => (c ? Array.from(new Set([...prev, f.id])) : prev.filter((id) => id !== f.id))) }, + icon: { source: Icon.Video }, accessories, actions: ActionPanel({ title: f.name, - children: actionChildren + children: [ + primaryAction, + Action({ + title: doneResult ? t('actionRevealOutput') : t('actionReveal'), + icon: Icon.Folder, + shortcut: { modifiers: ['ctrl'], key: 'enter' }, + onAction: () => handleReveal(f) + }), + ...(!running + ? [ + Action({ + title: t('actionRunSingle'), + icon: Icon.Play, + onAction: () => executeBatch([f]) + }), + Action({ + title: t('actionProbeSingle'), + icon: Icon.Info, + onAction: () => probeAddedItems([f]) + }) + ] + : []), + ...(doneResult + ? [ + Action({ + title: t('actionCopyOutputPath'), + icon: Icon.Clipboard, + onAction: async () => { + try { + await Clipboard.copy(doneResult.outputPath) + await showToast({ style: Toast.Style.Success, title: t('copiedOutputPathTitle') }) + } catch (err) { + await showToast({ + style: Toast.Style.Failure, + title: t('copyFailedTitle'), + message: err instanceof Error ? err.message : String(err) + }) + } + } + }) + ] + : []), + ActionPanel.Section({ + title: t('sectionList'), + children: [ + ...(taskId === 'convert-video' + ? [ + Action({ + title: t('actionPickWatermark'), + icon: Icon.Image, + onAction: handlePickWatermark + }), + ...(watermarkPath + ? [ + Action({ + title: t('actionClearWatermark'), + icon: Icon.XMarkCircle, + onAction: () => { + setWatermarkPath('') + void showToast({ style: Toast.Style.Success, title: t('watermarkClearedTitle') }) + } + }) + ] + : []) + ] + : []), + ...(isItemRunning + ? [] + : [ + Action({ + title: t('actionRemove'), + icon: Icon.Minus, + shortcut: { modifiers: ['ctrl'], key: 'backspace' }, + onAction: () => handleRemoveVideo(f) + }) + ]), + pickFilesAction(), + pickFolderAction(), + Action({ + title: allFilteredChecked ? t('actionDeselectAll') : t('actionSelectAll'), + icon: Icon.CheckCircle, + shortcut: { modifiers: ['ctrl'], key: 'a' }, + onAction: () => setFilteredChecked(!allFilteredChecked) + }), + Action({ + title: t('actionClearList'), + icon: Icon.Trash, + style: Action.Style.Destructive, + shortcut: { modifiers: ['ctrl', 'shift'], key: 'backspace' }, + onAction: handleClearVideos + }) + ] + }) + ] }) }) }) - const inClient = isRealElectronHost() + // 构建左侧工作台字段(严格按 optionalExtensions 动态开放 geometry / speed 高级参数) + const workbenchFields: Array> = [ + activeTask.formats.length > 1 + ? { + id: 'wb-format', + label: t('wbFormatLabel'), + type: 'select', + value: activeFormat, + onChange: (val: unknown) => { + const next = resolveOutputFormat(activeTask, String(val)) + if (next) setFormatByTask((prev) => ({ ...prev, [taskId]: next })) + }, + options: activeTask.formats.map((opt) => ({ label: opt.label, value: opt.value })) + } + : { + id: 'wb-format', + label: t('wbFormatLabel'), + type: 'info', + value: activeTask.formats[0]!.label + } + ] + + if (taskId === 'convert-video') { + workbenchFields.push( + { + id: 'wb-video-codec', + label: t('wbVideoCodecLabel'), + type: 'select', + value: videoCodec, + onChange: (val: unknown) => setVideoCodec(String(val)), + options: [ + { label: t('codecAuto'), value: 'auto' }, + { label: t('codecH264'), value: 'h264' }, + { label: t('codecHevc'), value: 'hevc' }, + { label: t('codecVp9'), value: 'vp9' }, + { label: t('codecAv1'), value: 'av1' }, + { label: t('codecCopy'), value: 'copy' } + ] + }, + { + id: 'wb-video-bitrate', + label: t('wbBitrateLabel'), + type: 'select', + value: videoBitrateKbps, + onChange: (val: unknown) => setVideoBitrateKbps(String(val)), + options: [ + { label: t('bitrateAuto'), value: 'auto' }, + { label: t('bitrate1500'), value: '1500' }, + { label: t('bitrate3000'), value: '3000' }, + { label: t('bitrate6000'), value: '6000' }, + { label: t('bitrate12000'), value: '12000' } + ] + }, + { + id: 'wb-strip-audio', + label: t('wbStripAudioLabel'), + type: 'toggle', + value: stripAudio, + onChange: (val: unknown) => setStripAudio(Boolean(val)) + } + ) + } + + if (taskId !== 'extract-audio') { + workbenchFields.push( + { + id: 'wb-fps', + label: t('wbFpsLabel'), + type: 'select', + value: frameRate, + onChange: (val: unknown) => setFrameRate(String(val)), + options: [ + { label: t('fpsSource'), value: 'source' }, + { label: t('fps15'), value: '15' }, + { label: t('fps24'), value: '24' }, + { label: t('fps30'), value: '30' }, + { label: t('fps60'), value: '60' } + ] + }, + { + id: 'wb-scale', + label: t('wbScaleLabel'), + type: 'select', + value: scaleWidth, + onChange: (val: unknown) => setScaleWidth(String(val)), + options: [ + { label: t('scaleSource'), value: 'source' }, + { label: t('scale1080'), value: '1920' }, + { label: t('scale720'), value: '1280' }, + { label: t('scale480'), value: '854' } + ] + } + ) + } + + workbenchFields.push( + { + id: 'wb-trim-start', + label: t('wbTrimStartLabel'), + type: 'text', + value: trimStartText, + onChange: (val: unknown) => setTrimStartText(String(val)) + }, + { + id: 'wb-trim-end', + label: t('wbTrimEndLabel'), + type: 'text', + value: trimEndText, + onChange: (val: unknown) => setTrimEndText(String(val)) + } + ) + + if (taskId === 'convert-video') { + workbenchFields.push({ + id: 'wb-watermark-file', + label: t('wbWatermarkFileLabel'), + type: 'info', + value: watermarkPath ? fileNameOf(watermarkPath) : t('wbWatermarkUnset') + }) + if (watermarkPath) { + workbenchFields.push({ + id: 'wb-watermark-pos', + label: t('wbWatermarkPosLabel'), + type: 'select', + value: watermarkPosition, + onChange: (val: unknown) => setWatermarkPosition(String(val) as MediaWatermarkPosition), + options: [ + { label: t('wmTopLeft'), value: 'top-left' }, + { label: t('wmTopRight'), value: 'top-right' }, + { label: t('wmBottomLeft'), value: 'bottom-left' }, + { label: t('wmBottomRight'), value: 'bottom-right' }, + { label: t('wmCenter'), value: 'center' } + ] + }) + } + } + + // 决策 7:仅宿主上报 'geometry' 时渲染旋转、翻转、裁剪字段 + if (capability.extensions.geometry && taskId !== 'extract-audio') { + workbenchFields.push( + { + id: 'wb-rotate', + label: t('wbRotateLabel'), + type: 'select', + value: rotateDeg, + onChange: (val: unknown) => setRotateDeg(String(val)), + options: [ + { label: t('rotateNone'), value: '0' }, + { label: t('rotate90'), value: '90' }, + { label: t('rotate180'), value: '180' }, + { label: t('rotate270'), value: '270' } + ] + }, + { + id: 'wb-flip', + label: t('wbFlipLabel'), + type: 'select', + value: flipMode, + onChange: (val: unknown) => setFlipMode(String(val)), + options: [ + { label: t('flipNone'), value: 'none' }, + { label: t('flipHorizontal'), value: 'horizontal' }, + { label: t('flipVertical'), value: 'vertical' }, + { label: t('flipBoth'), value: 'both' } + ] + }, + { + id: 'wb-crop', + label: t('wbCropLabel'), + type: 'text', + value: cropText, + onChange: (val: unknown) => setCropText(String(val)) + } + ) + } + + // 决策 7:仅宿主上报 'speed' 时渲染视频变速字段 + if (capability.extensions.speed) { + workbenchFields.push({ + id: 'wb-speed', + label: t('wbSpeedLabel'), + type: 'select', + value: speedFactor, + onChange: (val: unknown) => setSpeedFactor(String(val)), + options: [ + { label: t('speed100'), value: '1' }, + { label: t('speed050'), value: '0.5' }, + { label: t('speed075'), value: '0.75' }, + { label: t('speed125'), value: '1.25' }, + { label: t('speed150'), value: '1.5' }, + { label: t('speed200'), value: '2' } + ] + }) + } + + workbenchFields.push( + { + id: 'wb-engine', + label: t('wbEngineLabel'), + type: 'info', + value: engineStatusText + }, + { + id: 'wb-outdir', + label: t('wbOutdirLabel'), + type: 'info', + value: t('wbOutdirValue', { suffix: OUTPUT_SUFFIX, ext: activeFormat }) + } + ) + const resultText = hasResults ? t('resultSummaryPart', { done: resultSummary.done, failed: resultSummary.failed }) : '' const summaryText = isImporting ? t('summaryImporting', { dirs: importProgress?.visitedDirs ?? 0, files: importProgress?.matchedFiles ?? 0 }) - : files.length === 0 - ? inClient - ? t('summaryEmptyClient') - : t('hostRequired') - : t('summaryNormal', { - selected: selectedFiles.length, - total: files.length, - bytes: selectedBytesText, - result: resultText - }) + : !inClient + ? t('hostRequired') + : files.length === 0 + ? t('summaryEmptyClient', { engine: engineStatusText }) + : t('summaryNormal', { + engine: engineStatusText, + selected: selectedFiles.length, + total: files.length, + bytes: selectedBytesText, + result: resultText + }) - const emptyText = !inClient - ? t('hostRequired') - : q && files.length > 0 - ? t('emptyNoMatch') - : t('summaryEmptyClient') + const filterBarActions = running + ? [ + { + id: 'pick-files', + label: t('btnPickFiles'), + title: t('btnPickFiles'), + style: 'secondary' as const, + onAction: handleAddVideoFiles + }, + { + id: 'stop-batch', + label: t('btnStopProcessing'), + title: t('btnStopProcessing'), + style: 'destructive' as const, + onAction: () => { + void handleCancelCurrentTask() + } + } + ] + : capability.overallStatus === 'needs_provisioning' + ? [ + { + id: 'download-engine', + label: t('btnDownloadEngine'), + title: t('btnDownloadEngine'), + style: 'primary' as const, + onAction: () => { + void handleDownloadEngine() + } + }, + { + id: 'pick-files', + label: t('btnPickFiles'), + title: t('btnPickFiles'), + style: 'secondary' as const, + onAction: handleAddVideoFiles + } + ] + : selectedFiles.length > 0 + ? [ + { + id: 'pick-files', + label: t('btnPickFiles'), + title: t('btnPickFiles'), + style: 'secondary' as const, + onAction: handleAddVideoFiles + }, + { + id: 'run-batch', + label: t('btnRunBatch', { count: selectedFiles.length }), + title: t('btnRunBatch', { count: selectedFiles.length }), + style: 'primary' as const, + onAction: () => { + void executeBatch(selectedFiles) + } + } + ] + : [ + { + id: 'pick-files', + label: t('btnPickFiles'), + title: t('btnPickFiles'), + style: 'secondary' as const, + onAction: handleAddVideoFiles + }, + { + id: 'pick-folder', + label: t('btnPickFolder'), + title: t('btnPickFolder'), + style: 'secondary' as const, + onAction: handleAddVideoFolder + } + ] return List({ ...fileInputProps, searchBarPlaceholder: t('searchPlaceholder'), onSearchTextChange: setSearchText, isShowingDetail: false, - isLoading: isImporting || running, + isLoading: isImporting || running || isProvisioning, actions: ActionPanel({ - children: [pickFilesAction(), pickFolderAction()] + children: [ + ...(capability.overallStatus === 'needs_provisioning' + ? [ + Action({ + title: t('actionDownloadEngine'), + icon: Icon.Download, + onAction: handleDownloadEngine + }) + ] + : []), + pickFilesAction(), + pickFolderAction() + ] }), searchBarAccessory: List.Dropdown({ tooltip: t('dropdownTooltip'), value: taskId, - onChange: val => setTaskId(getVideoTask(val).id), - children: videoTasks.map(task => + onChange: (val) => setTaskId(getVideoTask(val).id), + children: videoTasks.map((task) => List.Dropdown.Item({ title: t('dropdownItemTitle', { tag: task.tag }), value: task.id }) ) }), - filterBar: FilterBar({ + filterBar: { summaryText, - actions: [ - { - id: 'pick-files', - label: t('btnPickFiles'), - title: t('btnPickFiles'), - style: 'secondary', - onAction: handleAddVideoFiles - }, - { - id: 'pick-folder', - label: t('btnPickFolder'), - title: t('btnPickFolder'), - style: 'secondary', - onAction: handleAddVideoFolder - } - ] - }), + actions: filterBarActions + }, workbenchPanel: { title: t('wbTitle'), subtitle: activeTask.tag, - fields: [ - activeTask.formats.length > 1 - ? { - id: 'wb-format', - label: t('wbFormatLabel'), - type: 'select', - value: activeFormat, - onChange: val => { - const next = resolveOutputFormat(activeTask, String(val)) - if (next) setFormatByTask(prev => ({ ...prev, [taskId]: next })) - }, - options: activeTask.formats.map(opt => ({ label: opt.label, value: opt.value })) - } - : { - id: 'wb-format', - label: t('wbFormatLabel'), - type: 'info', - value: activeTask.formats[0]!.label - }, - { - id: 'wb-codec', - label: t('wbCodecLabel'), - type: 'info', - value: t('wbCodecValue') - }, - { - id: 'wb-outdir', - label: t('wbOutdirLabel'), - type: 'info', - value: t('wbOutdirValue', { suffix: OUTPUT_SUFFIX, ext: activeFormat }) - }, - { - id: 'wb-limit', - label: t('wbLimitLabel'), - type: 'info', - value: t('wbLimitValue', { seconds: HOST_FFMPEG_LIMIT_SECONDS }) - } - ], + fields: workbenchFields as never, previewCard: { title: hasResults ? t('previewTitleResults') : t('previewTitleInfo'), - badge: hasResults ? t('previewBadgeResults', { done: resultSummary.done, failed: resultSummary.failed }) : t('previewBadgePending'), + badge: + capability.overallStatus === 'needs_provisioning' + ? t('previewBadgeNeedsProvision') + : hasResults + ? t('previewBadgeResults', { done: resultSummary.done, failed: resultSummary.failed }) + : t('previewBadgePending'), subtitle: t('previewSubtitle', { subtitle: activeTask.subtitle, suffix: OUTPUT_SUFFIX }), metrics: [ { label: t('metricDone'), value: t('metricCountVal', { count: resultSummary.done }) }, { label: t('metricFailed'), value: t('metricCountVal', { count: resultSummary.failed }) }, { label: t('metricOutSize'), value: resultSummary.done > 0 ? formatBytes(resultSummary.outputBytes) : '—' }, - { - label: t('metricSourceSize'), - value: resultSummary.done > 0 && doneKnownSourceBytes > 0 ? formatBytes(doneKnownSourceBytes) : '—' - } + { label: t('metricExtensions'), value: extensionsSummaryText } ] } }, subList: { title: t('subListTitle'), - subtitle: t('metricCountVal', { count: filteredFiles.length }), + subtitle: t('subListSubtitle', { count: filteredFiles.length }), checkable: filteredFiles.length > 0, checked: allFilteredChecked ? true - : filteredFiles.some(f => checkedIds.includes(f.id)) + : filteredFiles.some((f) => checkedIds.includes(f.id)) ? 'indeterminate' : false, - onCheckChange: checked => setFilteredChecked(Boolean(checked)), - emptyText, + onCheckChange: (checked) => setFilteredChecked(Boolean(checked)), + emptyText: !inClient + ? t('hostRequired') + : q && files.length > 0 + ? t('emptyNoMatch') + : t('summaryEmptyClient', { engine: engineStatusText }), items: rightQueueItems }, children: [ diff --git a/extensions/batch-video/src/logic.ts b/extensions/batch-video/src/logic.ts index f82c6f1e..87282125 100644 --- a/extensions/batch-video/src/logic.ts +++ b/extensions/batch-video/src/logic.ts @@ -1,39 +1,88 @@ /** - * 批量视频转换:业务逻辑层 + * 批量视频处理业务逻辑层(基于宿主 media.probe / media.transcode 薄原语) * - * - 视频由用户通过选择文件、选择文件夹或拖入导入(不自动扫描本机目录) - * - 三类任务:转换视频格式(MP4 / MKV / MOV / WebM)、转 GIF、提取音频(MP3 / M4A / WAV) - * - 逐个文件调用宿主媒体处理接口:宿主用本机已安装的 ffmpeg,按输出文件扩展名使用 ffmpeg 默认参数编码, - * 不接受画质、分辨率、码率等参数,单个文件最多运行 60 秒 - * - 每个文件都显式指定输出路径,并在输出前避开已存在的同名文件:宿主处理失败时会删除输出位置上的文件, - * 输出路径绝不能指向用户已有的文件 - * - 只展示宿主返回的真实结果(输出路径、大小),不做体积估算 + * - 纯宿主薄原语架构:由主进程统一管理长耗时转码生命周期与取消,无客户端短超时截断 + * - 支持格式转换、编码器、码率、帧率、缩放、时间裁切、抽音轨、去音轨、转 GIF、图片水印 + * - 决策 7 特性探测门禁: + * * rotate / flip / crop 仅在宿主 optionalExtensions 包含 'geometry' 时才展示并发送 + * * speedFactor 仅在宿主 optionalExtensions 包含 'speed' 时才展示并发送 + * - 支持 tool_runtime_ensure 按需拉取引擎与 tool_task_cancel 长任务取消 */ -import { - callHostTransport, - formatBytes, - invokeDllPluginCapability, - nextMessageId -} from './native-ipc.js' +import { t } from './i18n.js' +import { resolveErrorMessage } from './error-i18n.js' import { collectFolderFiles, - friendlyFileError, isVolumeRoot, pickFiles, pickFolder } from './file-import.js' -import type { FileImportOptions, FileImportResult, FileImportRules, FileImportTransport, ImportedFile } from './file-import.js' -import { t } from './i18n.js' -import { extractErrorCode, extractHostCode, resolveErrorMessage } from './error-i18n.js' +import type { + FileImportOptions, + FileImportResult, + FileImportRules, + FileImportTransport, + ImportedFile +} from './file-import.js' +import { + asRecord, + callHostTransport, + cancelRuntimeTask, + ensureRuntimeCapabilities, + findCapability, + formatBytes, + hasCapabilityExtension, + isRealElectronHost, + nextMessageId, + queryRuntimeCapabilities, + runMediaTranscodeTask, + showRealItemInFolder, + type ToolCapabilityStatus +} from './tool-runtime.js' + +export { formatBytes, isRealElectronHost } + +export const MEDIA_PROBE_PRIMITIVE_ID = 'media.probe' as const +export const MEDIA_TRANSCODE_PRIMITIVE_ID = 'media.transcode' as const +export const OUTPUT_SUFFIX = '_ztools' -export { formatBytes } from './native-ipc.js' +export const FORBIDDEN_TARGET_PATTERN = + /(?:^|[\\/])Windows[\\/]System32(?:[\\/]|$)|(?:^|[\\/])\.\.(?:[\\/]|$)/i + +export const INPUT_VIDEO_EXTENSIONS = ['.mp4', '.mkv', '.mov', '.avi', '.flv', '.webm', '.wmv', '.ts', '.m4v'] as const +export const VIDEO_IMPORT_SUPPORTED_TEXT = 'MP4 / MKV / MOV / AVI / FLV / WebM / WMV / TS / M4V' +export const DERIVED_OUTPUT_REGEX = /_ztools(?:_\d+){0,2}\.[a-z0-9]+$/i export type VideoTaskId = 'convert-video' | 'to-gif' | 'extract-audio' +export type MediaContainerFormat = 'mp4' | 'mkv' | 'mov' | 'webm' | 'mp3' | 'aac' | 'flac' | 'wav' | 'ogg' | 'gif' +export type MediaVideoCodec = 'h264' | 'hevc' | 'vp9' | 'av1' | 'copy' +export type MediaAudioCodec = 'aac' | 'mp3' | 'opus' | 'flac' | 'pcm' | 'copy' +export type MediaWatermarkPosition = 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right' | 'center' +export type MediaRotateDegrees = 90 | 180 | 270 +export type MediaFlipMode = 'horizontal' | 'vertical' | 'both' + +export interface MediaCropOption { + x: number + y: number + width: number + height: number +} + +export interface VideoExtensionsSupport { + geometry: boolean + speed: boolean +} + +export interface VideoCapabilityState { + probeStatus: ToolCapabilityStatus + transcodeStatus: ToolCapabilityStatus + overallStatus: ToolCapabilityStatus + extensions: VideoExtensionsSupport + error?: string +} export interface OutputFormatOption { - /** 输出扩展名(小写,不带点) */ - value: string + value: MediaContainerFormat label: string } @@ -42,64 +91,107 @@ export interface VideoTask { title: string subtitle: string tag: string - /** 宿主媒体接口的方法名 */ - method: string formats: OutputFormatOption[] } -export interface NativeInvocationResult { - ok: boolean - pluginName: string - method: string - data?: unknown - error?: string - fromFallback?: boolean -} - -export interface VideoProcessDone { - status: 'done' - outputPath: string - outputBytes: number -} - -export interface VideoProcessFailed { - status: 'failed' - error: string +export interface VideoProbeMetadata { + displayName: string + container?: string + durationSec?: number + sizeBytes: number + bitrateBps?: number + videoCodec?: string + audioCodec?: string + width?: number + height?: number + frameRate?: number } -export type VideoProcessOutcome = VideoProcessDone | VideoProcessFailed +export interface VideoProcessSettings { + taskId: VideoTaskId + format: MediaContainerFormat + videoCodec?: MediaVideoCodec + audioCodec?: MediaAudioCodec + videoBitrateKbps?: number + audioBitrateKbps?: number + frameRate?: number + scaleWidth?: number + scaleHeight?: number + stripAudio?: boolean + trimStartSec?: number + trimEndSec?: number + watermarkPath?: string + watermarkPosition?: MediaWatermarkPosition + watermarkOpacity?: number + watermarkMarginPx?: number + /** 仅当 optionalExtensions 包含 'geometry' 时发送 */ + rotate?: MediaRotateDegrees + /** 仅当 optionalExtensions 包含 'geometry' 时发送 */ + flip?: MediaFlipMode + /** 仅当 optionalExtensions 包含 'geometry' 时发送 */ + crop?: MediaCropOption + /** 仅当 optionalExtensions 包含 'speed' 时发送 */ + speedFactor?: number +} + +export type VideoProcessOutcome = + | { status: 'done'; outputPath: string; outputBytes: number; durationMs: number } + | { status: 'cancelled' } + | { status: 'failed'; error: string } export interface RealVideoFileItem { id: string name: string path: string - /** 文件实际所在目录 */ parentDir: string extension: string - /** 文件大小;读不到时为 null(界面显示「大小未识别」) */ sizeBytes: number | null + probe?: VideoProbeMetadata result?: VideoProcessOutcome + progressPercent?: number } -export interface VideoProcessSettings { - taskId: VideoTaskId - /** 输出扩展名,必须是该任务支持的格式 */ - format: string +export interface VideoBatchSummary { + total: number + done: number + failed: number + cancelled: number + outputBytes: number + firstError: string } -export const DLL_PLUGIN_NAME = 'BatchVideoPlugin' -export const FORBIDDEN_TARGET_PATTERN = new RegExp('\\\\Windows\\\\System32|\\.\\.\\\\|\\.\\./', 'i') -export function getForbiddenReason(): string { - return t('forbiddenReason') +const AUDIO_FORMAT_CODEC: Readonly> = { + mp3: 'mp3', + aac: 'aac', + flac: 'flac', + wav: 'pcm', + ogg: 'opus' +} + +function splitPath(filePath: string): { dirWithSep: string; dir: string; fileName: string; base: string; ext: string } { + const sepIdx = Math.max(filePath.lastIndexOf('\\'), filePath.lastIndexOf('/')) + const dirWithSep = sepIdx >= 0 ? filePath.slice(0, sepIdx + 1) : '' + const dir = sepIdx > 0 ? filePath.slice(0, sepIdx) : dirWithSep + const fileName = sepIdx >= 0 ? filePath.slice(sepIdx + 1) : filePath + const dot = fileName.lastIndexOf('.') + const base = dot > 0 ? fileName.slice(0, dot) : fileName + const ext = dot > 0 ? fileName.slice(dot).toLowerCase() : '' + return { dirWithSep, dir: /^[A-Za-z]:$/.test(dir) ? `${dir}\\` : dir, fileName, base, ext } +} + +export function fileNameOf(filePath: string): string { + return splitPath(filePath).fileName +} + +export function formatDuration(seconds: number | undefined): string { + if (typeof seconds !== 'number' || !Number.isFinite(seconds) || seconds < 0) return t('durationUnknown') + const total = Math.round(seconds) + const hrs = Math.floor(total / 3600) + const mins = Math.floor((total % 3600) / 60) + const secs = total % 60 + if (hrs > 0) return `${hrs}:${String(mins).padStart(2, '0')}:${String(secs).padStart(2, '0')}` + return `${String(mins).padStart(2, '0')}:${String(secs).padStart(2, '0')}` } -/** 宿主对单个文件运行 ffmpeg 的时限(秒),超时后宿主中止 ffmpeg 并删除未完成的输出 */ -export const HOST_FFMPEG_LIMIT_SECONDS = 60 -/** 等待宿主返回处理结果的时限:在宿主 ffmpeg 时限之外留出检测 ffmpeg、写盘与回传的时间 */ -export const TRANSCODE_IPC_TIMEOUT_MS = 75_000 -/** 输出文件名后缀:<原文件名>_ztools.<扩展名> */ -export const OUTPUT_SUFFIX = '_ztools' -const MAX_PLAIN_NAME_ATTEMPTS = 20 -const MAX_TAGGED_NAME_ATTEMPTS = 50 export function getVideoTasks(): VideoTask[] { return [ @@ -108,7 +200,6 @@ export function getVideoTasks(): VideoTask[] { title: t('taskConvertTitle'), subtitle: t('taskConvertSub'), tag: t('taskConvertTag'), - method: 'BatchConvertFormat', formats: [ { value: 'mp4', label: 'MP4' }, { value: 'mkv', label: 'MKV' }, @@ -121,7 +212,6 @@ export function getVideoTasks(): VideoTask[] { title: t('taskGifTitle'), subtitle: t('taskGifSub'), tag: t('taskGifTag'), - method: 'BatchConvertToGif', formats: [{ value: 'gif', label: 'GIF' }] }, { @@ -129,11 +219,12 @@ export function getVideoTasks(): VideoTask[] { title: t('taskAudioTitle'), subtitle: t('taskAudioSub'), tag: t('taskAudioTag'), - method: 'BatchExtractAudio', formats: [ { value: 'mp3', label: 'MP3' }, - { value: 'm4a', label: 'M4A' }, - { value: 'wav', label: t('formatWavUncompressed') } + { value: 'aac', label: 'AAC' }, + { value: 'flac', label: 'FLAC' }, + { value: 'wav', label: t('formatWavUncompressed') }, + { value: 'ogg', label: 'OGG' } ] } ] @@ -141,175 +232,263 @@ export function getVideoTasks(): VideoTask[] { export function getVideoTask(id: string): VideoTask { const tasks = getVideoTasks() - return tasks.find(task => task.id === id) || tasks[0]! + return tasks.find((task) => task.id === id) || tasks[0]! } -/** 任务支持该输出格式时返回规范化的扩展名,否则返回 null */ -export function resolveOutputFormat(task: VideoTask, format: string): string | null { +export function resolveOutputFormat(task: VideoTask, format: string): MediaContainerFormat | null { const value = String(format || '').trim().toLowerCase().replace(/^\./, '') - return task.formats.some(f => f.value === value) ? value : null + const matched = task.formats.find((f) => f.value === value) + return matched ? matched.value : null } -function isRecord(value: unknown): value is Record { - return typeof value === 'object' && value !== null && !Array.isArray(value) -} +/** 解析裁剪文本 "x,y,width,height" */ +export function parseCropExpression(raw: string): { valid: boolean; crop?: MediaCropOption } { + const trimmed = String(raw || '').trim() + if (!trimmed) return { valid: true } + const parts = trimmed.split(/[,\s]+/).map((s) => Number(s)) + if (parts.length !== 4 || parts.some((n) => !Number.isInteger(n))) { + return { valid: false } + } + const [x, y, width, height] = parts + if (x < 0 || y < 0 || width <= 0 || height <= 0) { + return { valid: false } + } + return { valid: true, crop: { x, y, width, height } } +} + +/** 探测宿主 media.probe 与 media.transcode 能力及 optionalExtensions */ +export async function probeVideoCapabilities(hostOverride?: unknown): Promise { + if (!isRealElectronHost(hostOverride)) { + return { + probeStatus: 'unsupported', + transcodeStatus: 'unsupported', + overallStatus: 'unsupported', + extensions: { geometry: false, speed: false }, + error: t('errHostDisconnected') + } + } + const res = await queryRuntimeCapabilities(hostOverride) + if (!res.ok || !res.data) { + return { + probeStatus: 'unsupported', + transcodeStatus: 'unsupported', + overallStatus: 'unsupported', + extensions: { geometry: false, speed: false }, + error: resolveErrorMessage(res, t('errHostDisconnected')) + } + } + const probeCap = findCapability(res.data, MEDIA_PROBE_PRIMITIVE_ID) + const transcodeCap = findCapability(res.data, MEDIA_TRANSCODE_PRIMITIVE_ID) + const probeStatus: ToolCapabilityStatus = probeCap?.status ?? 'unsupported' + const transcodeStatus: ToolCapabilityStatus = transcodeCap?.status ?? 'unsupported' + + let overallStatus: ToolCapabilityStatus = 'ready' + if (probeStatus === 'unsupported' || transcodeStatus === 'unsupported') { + overallStatus = 'unsupported' + } else if (probeStatus === 'needs_provisioning' || transcodeStatus === 'needs_provisioning') { + overallStatus = 'needs_provisioning' + } -function errorText(err: unknown): string { - return err instanceof Error ? err.message : String(err) + return { + probeStatus, + transcodeStatus, + overallStatus, + extensions: { + geometry: hasCapabilityExtension(res.data, MEDIA_TRANSCODE_PRIMITIVE_ID, 'geometry'), + speed: hasCapabilityExtension(res.data, MEDIA_TRANSCODE_PRIMITIVE_ID, 'speed') + } + } } -function checkStringParam(key: string, val: string): string | null { - if (val.length > 4096) return t('errParamTooLong', { key }) - if (FORBIDDEN_TARGET_PATTERN.test(val)) return t('errSecurityIntercepted', { reason: t('forbiddenReason') }) - return null +/** 按需下载并准备视频引擎(tool_runtime_ensure) */ +export async function ensureVideoEngine( + hostOverride?: unknown +): Promise<{ ok: boolean; status: ToolCapabilityStatus; provisioned: boolean; message: string }> { + if (!isRealElectronHost(hostOverride)) { + return { ok: false, status: 'unsupported', provisioned: false, message: t('errHostDisconnected') } + } + const ensured = await ensureRuntimeCapabilities([MEDIA_PROBE_PRIMITIVE_ID, MEDIA_TRANSCODE_PRIMITIVE_ID], hostOverride) + if (!ensured.ok) { + const reason = resolveErrorMessage(ensured, ensured.status || t('errHostDisconnected')) + return { + ok: false, + status: ensured.status, + provisioned: ensured.provisioned, + message: t('errProvisionFailed', { error: reason }) + } + } + return { ok: true, status: 'ready', provisioned: ensured.provisioned, message: t('msgProvisionSuccess') } } -export function validateInvocationPayload(method: string, params: unknown): { valid: boolean; error?: string } { - if (typeof method !== 'string' || method.trim().length === 0) { - return { valid: false, error: t('errInvalidMethodEmpty') } +/** 探测视频文件元数据(tool_media_probe) */ +export async function probeVideoFiles( + filePaths: readonly string[], + hostOverride?: unknown +): Promise<{ ok: boolean; items: VideoProbeMetadata[]; error?: string }> { + if (!filePaths.length) return { ok: true, items: [] } + if (!isRealElectronHost(hostOverride)) { + return { ok: false, items: [], error: t('errHostDisconnected') } } - if (method.length > 128 || !/^[A-Za-z0-9_]+$/.test(method.trim())) { - return { valid: false, error: t('errInvalidMethodFormat') } + const res = await callHostTransport( + 'tool_media_probe', + { inputs: filePaths.map((p) => ({ path: p })) }, + hostOverride + ) + if (!res.ok) { + return { + ok: false, + items: [], + error: t('errProbeFailed', { error: resolveErrorMessage(res, t('errHostDisconnected')) }) + } } - if (!isRecord(params)) { - return { valid: false, error: t('errInvalidParamsObject') } + const rec = asRecord(res.data) + const rawItems = Array.isArray(rec?.items) ? rec.items : [] + const items: VideoProbeMetadata[] = rawItems.map((raw) => { + const item = asRecord(raw) ?? {} + const streams = Array.isArray(item.streams) ? item.streams.map(asRecord) : [] + const videoStream = streams.find((s) => s?.kind === 'video') ?? null + const audioStream = streams.find((s) => s?.kind === 'audio') ?? null + const durationSec = typeof item.durationSec === 'number' && Number.isFinite(item.durationSec) ? item.durationSec : undefined + const sizeBytes = typeof item.sizeBytes === 'number' && Number.isFinite(item.sizeBytes) && item.sizeBytes >= 0 ? item.sizeBytes : 0 + const bitrateBps = typeof item.bitrateBps === 'number' && Number.isFinite(item.bitrateBps) ? item.bitrateBps : undefined + return { + displayName: typeof item.displayName === 'string' ? item.displayName : '', + ...(typeof item.container === 'string' ? { container: item.container } : {}), + ...(durationSec !== undefined ? { durationSec } : {}), + sizeBytes, + ...(bitrateBps !== undefined ? { bitrateBps } : {}), + ...(typeof videoStream?.codec === 'string' ? { videoCodec: videoStream.codec } : {}), + ...(typeof audioStream?.codec === 'string' ? { audioCodec: audioStream.codec } : {}), + ...(typeof videoStream?.width === 'number' ? { width: videoStream.width } : {}), + ...(typeof videoStream?.height === 'number' ? { height: videoStream.height } : {}), + ...(typeof videoStream?.frameRate === 'number' ? { frameRate: videoStream.frameRate } : {}) + } + }) + return { ok: true, items } +} + +/** + * 构建 tool_media_transcode_run 请求载荷。 + * 严格执行决策 7 特性探测门禁: + * - extensions.geometry 为 false 时,绝不包含 rotate / flip / crop 键 + * - extensions.speed 为 false 时,绝不包含 speedFactor 键 + */ +export function buildVideoTranscodeRequest( + inputPath: string, + outputPath: string, + settings: VideoProcessSettings, + extensions: VideoExtensionsSupport, + taskId?: string +): Record { + const payload: Record = { + ...(taskId ? { taskId } : {}), + input: { path: inputPath }, + output: { path: outputPath }, + overwrite: false, + container: settings.format } - for (const [key, val] of Object.entries(params)) { - if (typeof val === 'string') { - const problem = checkStringParam(key, val) - if (problem) return { valid: false, error: problem } - } else if (Array.isArray(val)) { - for (const item of val) { - if (typeof item !== 'string') continue - const problem = checkStringParam(key, item) - if (problem) return { valid: false, error: problem } + if (settings.taskId === 'extract-audio') { + payload.extractAudioOnly = true + const codec = settings.audioCodec ?? AUDIO_FORMAT_CODEC[settings.format] + if (codec) payload.audioCodec = codec + if (typeof settings.audioBitrateKbps === 'number' && settings.audioBitrateKbps > 0) { + payload.audioBitrateKbps = Math.round(settings.audioBitrateKbps) + } + } else { + if (settings.taskId === 'convert-video' && settings.videoCodec) { + payload.videoCodec = settings.videoCodec + } + if (settings.taskId === 'convert-video' && settings.audioCodec && !settings.stripAudio) { + payload.audioCodec = settings.audioCodec + } + if (settings.taskId === 'convert-video' && typeof settings.videoBitrateKbps === 'number' && settings.videoBitrateKbps > 0) { + payload.videoBitrateKbps = Math.round(settings.videoBitrateKbps) + } + if (typeof settings.frameRate === 'number' && settings.frameRate > 0) { + payload.frameRate = settings.frameRate + } + if (settings.taskId === 'convert-video' && settings.stripAudio === true) { + payload.stripAudio = true + } + if ( + (typeof settings.scaleWidth === 'number' && settings.scaleWidth > 0) || + (typeof settings.scaleHeight === 'number' && settings.scaleHeight > 0) + ) { + payload.scale = { + ...(typeof settings.scaleWidth === 'number' && settings.scaleWidth > 0 ? { width: Math.round(settings.scaleWidth) } : {}), + ...(typeof settings.scaleHeight === 'number' && settings.scaleHeight > 0 ? { height: Math.round(settings.scaleHeight) } : {}), + keepAspectRatio: true } - } else if (typeof val === 'number') { - if (!Number.isFinite(val) || val < -1000 || val > 100_000_000) { - return { valid: false, error: t('errParamOutOfRange', { key }) } + } + if (settings.watermarkPath && settings.watermarkPath.trim() && settings.taskId === 'convert-video') { + payload.watermark = { + imageSlot: { path: settings.watermarkPath.trim() }, + position: settings.watermarkPosition ?? 'bottom-right', + opacity: settings.watermarkOpacity ?? 0.85, + marginPx: settings.watermarkMarginPx ?? 16 } } } - return { valid: true } -} - -type TransportMethod = (request: Record) => Promise + // 时间裁切(允许 startSec === 0) + const hasStart = typeof settings.trimStartSec === 'number' && Number.isFinite(settings.trimStartSec) && settings.trimStartSec >= 0 + const hasEnd = typeof settings.trimEndSec === 'number' && Number.isFinite(settings.trimEndSec) && settings.trimEndSec > 0 + if (hasStart || hasEnd) { + payload.trim = { + ...(hasStart ? { startSec: settings.trimStartSec } : {}), + ...(hasEnd ? { endSec: settings.trimEndSec } : {}) + } + } -/** - * 宿主通道默认 10 秒超时,而转码要等 ffmpeg 跑完(宿主上限 60 秒):给 dllplugin_call 显式设置等待时限。 - * 当前环境没有宿主通道(未连接客户端)时返回 undefined,由调用方按宿主不可用报告失败。 - */ -function createLongRunningBridge(): Record | undefined { - if (typeof window === 'undefined') return undefined - const w = window as unknown as { - __ztoolsElectron?: { transport?: { methods?: Record } } - ztools?: { transport?: { methods?: Record } } - } - const methods = w.__ztoolsElectron?.transport?.methods || w.ztools?.transport?.methods - const call = methods?.dllplugin_call - if (typeof call !== 'function') return undefined - return { - __isRealHost: true, - dllplugin_call: (params: Record) => - (call as TransportMethod)({ - messageId: nextMessageId('dllplugin_call'), - params, - timeoutMs: TRANSCODE_IPC_TIMEOUT_MS - }) - } -} - -export async function invokeNativeCapability( - method: string, - params: Record, - hostBridge?: unknown -): Promise { - const check = validateInvocationPayload(method, params) - if (!check.valid) { - throw new Error(resolveErrorMessage(check, t('errValidationFailed'))) - } - const bridge = hostBridge ?? createLongRunningBridge() - const res = await invokeDllPluginCapability(DLL_PLUGIN_NAME, method, params, bridge) - return { - ok: res.ok, - pluginName: DLL_PLUGIN_NAME, - method: method.trim(), - data: res.data ?? undefined, - error: res.error, - fromFallback: res.fromFallback + // 决策 7 严格门禁:仅宿主上报 'geometry' 时允许发送 rotate / flip / crop + if (extensions.geometry && settings.taskId !== 'extract-audio') { + if (settings.rotate === 90 || settings.rotate === 180 || settings.rotate === 270) { + payload.rotate = settings.rotate + } + if (settings.flip === 'horizontal' || settings.flip === 'vertical' || settings.flip === 'both') { + payload.flip = settings.flip + } + if (settings.crop) { + payload.crop = { ...settings.crop } + } } -} -function splitPath(filePath: string): { dirWithSep: string; dir: string; fileName: string; base: string; ext: string } { - const sepIdx = Math.max(filePath.lastIndexOf('\\'), filePath.lastIndexOf('/')) - const dirWithSep = sepIdx >= 0 ? filePath.slice(0, sepIdx + 1) : '' - const dir = sepIdx > 0 ? filePath.slice(0, sepIdx) : dirWithSep - const fileName = sepIdx >= 0 ? filePath.slice(sepIdx + 1) : filePath - const dot = fileName.lastIndexOf('.') - const base = dot > 0 ? fileName.slice(0, dot) : fileName - const ext = dot > 0 ? fileName.slice(dot).toLowerCase() : '' - return { dirWithSep, dir: /^[A-Za-z]:$/.test(dir) ? `${dir}\\` : dir, fileName, base, ext } -} + // 决策 7 严格门禁:仅宿主上报 'speed' 时允许发送 speedFactor + if (extensions.speed) { + if ( + typeof settings.speedFactor === 'number' && + Number.isFinite(settings.speedFactor) && + settings.speedFactor > 0 && + settings.speedFactor !== 1 + ) { + payload.speedFactor = settings.speedFactor + } + } -export function fileNameOf(filePath: string): string { - return splitPath(filePath).fileName + return payload } -/** 在源文件同目录生成 <原文件名><后缀>.<扩展名> */ export function buildOutputCandidate(sourcePath: string, ext: string, suffix: string): string { const { dirWithSep, base } = splitPath(sourcePath) return `${dirWithSep}${base}${suffix}.${ext}` } -/** 批次时间标记(YYYYMMDDHHmmss),宿主无法确认同名文件是否存在时用于生成不重复的文件名 */ export function makeBatchTag(now: Date = new Date()): string { const pad = (n: number) => String(n).padStart(2, '0') return `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}` } -export type PathExistence = 'exists' | 'missing' | 'unknown' - -function probeFoundFile(data: unknown): boolean { - if (!isRecord(data) || !Array.isArray(data.items)) return false - return data.items.some(item => isRecord(item) && typeof item.path === 'string' && item.path.length > 0) -} - -/** - * 查询目标路径上是否已有文件: - * 1. filesystem_file_exists 明确答复存在 / 不存在时直接采用(该接口要求读取授权,输出位置通常没有授权,会返回失败); - * 2. 再用宿主媒体接口读取该路径的文件信息,能读到说明文件已存在;读不到不能断定不存在,返回 unknown。 - */ -export async function checkPathExists(filePath: string, hostOverride?: unknown): Promise { +async function checkPathExists(filePath: string, hostOverride?: unknown): Promise<'exists' | 'missing' | 'unknown'> { const res = await callHostTransport('filesystem_file_exists', { path: filePath }, hostOverride) if (res.ok) { - const data = res.data - const exists = - typeof data === 'boolean' - ? data - : isRecord(data) && typeof data.exists === 'boolean' - ? data.exists - : null - if (exists === true) return 'exists' - if (exists === false) return 'missing' - } - let probe: NativeInvocationResult - try { - probe = await invokeNativeCapability('Probe', { files: [filePath] }, hostOverride) - } catch { - // 路径没通过参数校验或宿主返回了损坏的数据:无法确认,交给调用方按「无法确认」处理 - return 'unknown' + if (typeof res.data === 'boolean') return res.data ? 'exists' : 'missing' + const rec = asRecord(res.data) + if (typeof rec?.exists === 'boolean') return rec.exists ? 'exists' : 'missing' } - return probe.ok && probeFoundFile(probe.data) ? 'exists' : 'unknown' + return 'unknown' } -/** - * 选择不会覆盖已有文件的输出路径: - * 1. 依次尝试 <名>_ztools、<名>_ztools_2 …,宿主明确答复不存在才使用;答复已存在就换下一个; - * 2. 宿主无法确认时,改用带批次时间标记的文件名(<名>_ztools_<时间>),仍先确认它不是已有文件; - * 同一批次内已分配的路径与源文件路径都不会重复使用。实在找不到可用名称时抛错,该文件不处理。 - */ export async function chooseOutputPath( sourcePath: string, ext: string, @@ -325,7 +504,7 @@ export async function chooseOutputPath( return candidate } - for (let n = 1; n <= MAX_PLAIN_NAME_ATTEMPTS; n++) { + for (let n = 1; n <= 20; n++) { const candidate = buildOutputCandidate(sourcePath, ext, n === 1 ? OUTPUT_SUFFIX : `${OUTPUT_SUFFIX}_${n}`) if (!usable(candidate)) continue const state = await checkPathExists(candidate, hostOverride) @@ -333,7 +512,7 @@ export async function chooseOutputPath( if (state === 'unknown') break } - for (let n = 1; n <= MAX_TAGGED_NAME_ATTEMPTS; n++) { + for (let n = 1; n <= 50; n++) { const suffix = n === 1 ? `${OUTPUT_SUFFIX}_${batchTag}` : `${OUTPUT_SUFFIX}_${batchTag}_${n}` const candidate = buildOutputCandidate(sourcePath, ext, suffix) if (!usable(candidate)) continue @@ -344,99 +523,73 @@ export async function chooseOutputPath( throw new Error(t('errCannotGenUniqueName')) } -/** 把宿主错误整理成一句可读的提示:优先按结构化错误码识别超时与缺少 ffmpeg,其余取当前语言可读尾部 */ -export function summarizeHostError(raw: unknown): string { - const code = extractErrorCode(raw).toUpperCase() - const hostCode = extractHostCode(raw).toUpperCase() - const text = String(raw ?? '') - .replace(/^(?:DLL_ERROR|NATIVE_CALL_FAILED):\s*/, '') - .trim() - // i18n-allow: legacy host fallback - if (code === 'REQUEST_TIMEOUT' || hostCode === 'REQUEST_TIMEOUT' || /\bREQUEST_TIMEOUT\b|Call timeout|timed out/i.test(text) || /命令执行超时|调用超时/.test(text)) { - return t('errHostTimeout', { seconds: HOST_FFMPEG_LIMIT_SECONDS }) - } - // i18n-allow: legacy host fallback - if (code === 'FFMPEG_NOT_FOUND' || hostCode === 'FFMPEG_NOT_FOUND' || /\bffmpeg\b.*(?:not found|missing|unavailable)/i.test(text) || /未检测到\s*ffmpeg/i.test(text)) { - return t('errFfmpegMissing') - } - if ( - code === 'HOST_UNAVAILABLE' || code === 'NO_WINDOW_ENV' || code === 'METHOD_NOT_AVAILABLE' || - hostCode === 'HOST_UNAVAILABLE' || hostCode === 'NO_WINDOW_ENV' || hostCode === 'METHOD_NOT_AVAILABLE' || - /\b(?:HOST_UNAVAILABLE|NO_WINDOW_ENV|METHOD_NOT_AVAILABLE)\b/.test(text) - ) { - return t('errHostDisconnected') - } - if (!text) return t('errHostReturnFailed') - const translated = friendlyFileError(text) - if (translated !== text) { - return translated - } - const lines = text - .split(/\r?\n/) - .map(line => line.trim()) - .filter(Boolean) - const tail = lines.slice(-2).join(' / ') || text - return tail.length > 300 ? `${tail.slice(0, 300)}…` : tail -} - -/** 把宿主单个文件的处理结果解析为界面结果;缺少输出信息时按失败处理,不当作成功 */ -export function parseHostVideoResult(data: unknown): VideoProcessOutcome { - const payload = isRecord(data) ? data : {} - const errors = Array.isArray(payload.errors) ? payload.errors : [] - if (errors.length > 0) { - const first = isRecord(errors[0]) ? errors[0] : {} - return { status: 'failed', error: summarizeHostError(resolveErrorMessage(first, t('errHostFailed'))) } - } - const results = Array.isArray(payload.results) ? payload.results : [] - const r = results[0] - if (!isRecord(r)) { - return { status: 'failed', error: t('errHostNoResult') } - } - const outputPath = typeof r.outputPath === 'string' ? r.outputPath.trim() : '' - const outputBytes = Number(r.outputBytes ?? r.sizeBytes) - if (!outputPath || !Number.isFinite(outputBytes) || outputBytes <= 0) { - return { status: 'failed', error: t('errHostMissingOutput') } - } - return { status: 'done', outputPath, outputBytes } -} - -/** 处理一个文件:先选好不覆盖已有文件的输出路径,再以该路径调用宿主 */ +/** 取消正在运行的视频转码任务(tool_task_cancel) */ +export async function cancelVideoTask( + taskId: string, + hostOverride?: unknown +): Promise<{ ok: boolean; cancelled: boolean; error?: string }> { + if (!isRealElectronHost(hostOverride)) { + return { ok: false, cancelled: false, error: t('errHostDisconnected') } + } + const res = await cancelRuntimeTask(taskId, hostOverride) + if (!res.ok) { + return { + ok: false, + cancelled: false, + error: t('errCancelFailed', { error: resolveErrorMessage(res, t('errHostDisconnected')) }) + } + } + return { ok: true, cancelled: res.data?.cancelled === true } +} + +/** 处理单个视频文件 */ export async function processVideoFile( file: Pick, settings: VideoProcessSettings, + extensions: VideoExtensionsSupport, reserved: Set, batchTag: string, - hostOverride?: unknown + options: { taskId?: string; hostOverride?: unknown } = {} ): Promise { + if (!isRealElectronHost(options.hostOverride)) { + return { status: 'failed', error: t('errHostDisconnected') } + } const task = getVideoTask(settings.taskId) const ext = resolveOutputFormat(task, settings.format) if (!ext) { - return { status: 'failed', error: t('errUnsupportedFormat', { title: task.title, format: settings.format || t('formatUnselected') }) } + return { status: 'failed', error: t('errUnsupportedFormat', { title: task.title, format: settings.format }) } } + if (FORBIDDEN_TARGET_PATTERN.test(file.path)) { + return { status: 'failed', error: t('forbiddenReason') } + } + + let outputPath: string try { - const outputPath = await chooseOutputPath(file.path, ext, reserved, batchTag, hostOverride) - const res = await invokeNativeCapability( - task.method, - { files: [file.path], outputPath, format: ext }, - hostOverride - ) - if (!res.ok) { - return { status: 'failed', error: summarizeHostError(res.error) } - } - return parseHostVideoResult(res.data) + outputPath = await chooseOutputPath(file.path, ext, reserved, batchTag, options.hostOverride) } catch (err) { - return { status: 'failed', error: summarizeHostError(errorText(err)) } + return { status: 'failed', error: err instanceof Error ? err.message : String(err) } + } + + const taskId = options.taskId || nextMessageId('video') + const payload = buildVideoTranscodeRequest(file.path, outputPath, { ...settings, format: ext }, extensions, taskId) + const runRes = await runMediaTranscodeTask(payload, options.hostOverride) + if (runRes.status === 'cancelled') return { status: 'cancelled' } + if (runRes.status === 'failed') { + const detail = runRes.error === 'EMPTY_OUTPUT' ? 'EMPTY_OUTPUT' : resolveErrorMessage(runRes, t('errHostDisconnected')) + return { status: 'failed', error: t('errTranscodeFailed', { error: detail }) } } + return { status: 'done', outputPath, outputBytes: runRes.outputBytes, durationMs: runRes.durationMs } } -/** 逐个处理;每个文件完成后回调一次,单个失败不影响其余文件;shouldSkip/shouldStop 命中时不再调用宿主 */ +/** 顺序批处理视频队列,支持中途实时取消 */ export async function processVideoBatch( files: Array>, settings: VideoProcessSettings, + extensions: VideoExtensionsSupport, options: { hostOverride?: unknown batchTag?: string - onStart?: (id: string) => void + onStart?: (id: string, taskId: string) => void onItem?: (id: string, outcome: VideoProcessOutcome) => void shouldSkip?: (id: string) => boolean shouldStop?: () => boolean @@ -445,32 +598,32 @@ export async function processVideoBatch( const reserved = new Set() const batchTag = options.batchTag || makeBatchTag() const outcomes = new Map() + for (const file of files) { if (options.shouldStop?.()) break if (options.shouldSkip?.(file.id)) continue - options.onStart?.(file.id) - const outcome = await processVideoFile(file, settings, reserved, batchTag, options.hostOverride) + const taskId = nextMessageId('video') + options.onStart?.(file.id, taskId) + const outcome = await processVideoFile(file, settings, extensions, reserved, batchTag, { + taskId, + hostOverride: options.hostOverride + }) outcomes.set(file.id, outcome) options.onItem?.(file.id, outcome) + if (outcome.status === 'cancelled') break } return outcomes } -export interface VideoBatchSummary { - total: number - done: number - failed: number - outputBytes: number - firstError: string -} - export function summarizeOutcomes(outcomes: Iterable): VideoBatchSummary { - const summary: VideoBatchSummary = { total: 0, done: 0, failed: 0, outputBytes: 0, firstError: '' } + const summary: VideoBatchSummary = { total: 0, done: 0, failed: 0, cancelled: 0, outputBytes: 0, firstError: '' } for (const outcome of outcomes) { summary.total += 1 if (outcome.status === 'done') { summary.done += 1 summary.outputBytes += outcome.outputBytes + } else if (outcome.status === 'cancelled') { + summary.cancelled += 1 } else { summary.failed += 1 if (!summary.firstError) summary.firstError = outcome.error @@ -479,38 +632,13 @@ export function summarizeOutcomes(outcomes: Iterable): Vide return summary } -/** 与宿主处理等效的 ffmpeg 命令;带 -n,目标文件已存在时 ffmpeg 直接退出,不会覆盖 */ -export function buildFfmpegCommand(sourcePath: string, ext: string): string { - return `ffmpeg -n -i "${sourcePath}" "${buildOutputCandidate(sourcePath, ext, OUTPUT_SUFFIX)}"` -} - -export function describeOutcomeTag(result: VideoProcessOutcome | undefined): string { - if (!result) return t('tagPending') - if (result.status === 'done') return t('tagDone', { size: formatBytes(result.outputBytes) }) - return t('tagFailed') -} - -export function describeOutcomeSubtitle(file: Pick): string { - const result = file.result - if (!result) return file.parentDir - if (result.status === 'done') return t('subOutput', { name: fileNameOf(result.outputPath) }) - return t('subFailed', { error: result.error }) -} - -export const INPUT_VIDEO_EXTENSIONS = ['.mp4', '.mkv', '.mov', '.avi', '.flv', '.webm', '.wmv', '.ts', '.m4v'] as const -export const VIDEO_IMPORT_SUPPORTED_TEXT = 'MP4 / MKV / MOV / AVI / FLV / WebM / WMV / TS / M4V' -/** 本插件生成的输出文件(*_ztools、*_ztools_2、*_ztools_<时间>、*_ztools_<时间>_2),导入时不再列入队列 */ -export const DERIVED_OUTPUT_REGEX = /_ztools(?:_\d+){0,2}\.[a-z0-9]+$/i - -/** 是否为本插件生成的派生输出文件 */ export function isDerivedOutputName(name: string): boolean { return DERIVED_OUTPUT_REGEX.test(String(name || '')) } -/** 视频导入规则:排除本插件生成的输出文件与系统核心路径 */ export const VIDEO_IMPORT_RULES: FileImportRules = { extensions: INPUT_VIDEO_EXTENSIONS, - excludeFile: name => isDerivedOutputName(name), + excludeFile: (name) => isDerivedOutputName(name), forbiddenPath: FORBIDDEN_TARGET_PATTERN } @@ -542,7 +670,6 @@ export function toVideoItem(file: ImportedFile): RealVideoFileItem { return makeVideoItem(`vid-${videoItemSeq}-${file.path}`, file.path, file.sizeBytes, file.parentDir) } -/** 弹出文件选择框选择视频文件(使用共享导入模块生成合规字符串过滤串) */ export async function selectVideoFiles(hostOverride?: unknown): Promise { return pickFiles(createVideoImportTransport(hostOverride), VIDEO_IMPORT_RULES, { title: t('pickFilesTitle'), @@ -550,46 +677,41 @@ export async function selectVideoFiles(hostOverride?: unknown): Promise { + return pickFiles( + createVideoImportTransport(hostOverride), + { extensions: ['.png', '.jpg', '.jpeg', '.webp'], forbiddenPath: FORBIDDEN_TARGET_PATTERN }, + { title: t('pickWatermarkTitle'), filterName: t('pickWatermarkFilter'), multiple: false } + ) +} + +function emptyVideoImport(canceled: boolean, error?: string): FileImportResult { + return { files: [], ignored: 0, truncated: false, failedDirs: [], canceled, ...(error ? { error } : {}) } +} + export async function pickVideoFolderWithConfirm( transport: FileImportTransport, confirmVolumeRoot: (folderPath: string) => Promise, options: FileImportOptions = {} ): Promise { const picked = await pickFolder(transport, { title: t('pickFolderTitle') }) - if (options.signal?.aborted || picked.canceled) { - return { files: [], ignored: 0, truncated: false, failedDirs: [], canceled: true } - } + if (options.signal?.aborted || picked.canceled) return emptyVideoImport(true) if (picked.error || !picked.folderPath) { - return { files: [], ignored: 0, truncated: false, failedDirs: [], canceled: false, error: resolveErrorMessage(picked, t('noFolderSelected')) } + return emptyVideoImport(false, resolveErrorMessage(picked, t('noFolderSelected'))) } - if (isVolumeRoot(picked.folderPath)) { - const confirmed = await confirmVolumeRoot(picked.folderPath) - if (options.signal?.aborted || !confirmed) { - return { files: [], ignored: 0, truncated: false, failedDirs: [], canceled: true } - } + if (isVolumeRoot(picked.folderPath) && (!(await confirmVolumeRoot(picked.folderPath)) || options.signal?.aborted)) { + return emptyVideoImport(true) } return collectFolderFiles(transport, picked.folderPath, VIDEO_IMPORT_RULES, options) } -/** 在资源管理器中显示文件(只定位,不会用默认程序打开文件);宿主拒绝时返回 false */ -export async function showFileInFolder(fullPath: string, hostOverride?: unknown): Promise { - if (!fullPath) return false - const res = await callHostTransport('shell_show_item_in_folder', { fullPath }, hostOverride) - return res.ok -} - -/** - * 定位处理结果:优先显示输出文件;输出文件没有访问授权时改为显示源文件(输出文件在同一目录)。 - * 返回实际显示的是哪一个,两者都失败时返回 failed。 - */ export async function revealVideoInFolder( file: Pick, hostOverride?: unknown ): Promise<'output' | 'source' | 'failed'> { - if (file.result?.status === 'done' && (await showFileInFolder(file.result.outputPath, hostOverride))) { + if (file.result?.status === 'done' && (await showRealItemInFolder(file.result.outputPath, hostOverride))) { return 'output' } - if (await showFileInFolder(file.path, hostOverride)) return 'source' + if (await showRealItemInFolder(file.path, hostOverride)) return 'source' return 'failed' } diff --git a/extensions/batch-video/src/native-ipc.ts b/extensions/batch-video/src/native-ipc.ts deleted file mode 100644 index 51576b99..00000000 --- a/extensions/batch-video/src/native-ipc.ts +++ /dev/null @@ -1,1852 +0,0 @@ -import { getLocale } from '@ztools/declarative-ui' - -type DynamicBridge = ReturnType - -const NATIVE_IPC_MESSAGES: Record string - dirEntrySep: string - dirErrorColon: string - deepScanUnavailable: string - pathEmpty: string - invalidMethodEmpty: string - invalidMethodFormat: string - invalidParamsObject: string - paramTooLong: (key: string) => string - paramOutOfRange: (key: string) => string - methodParamEmpty: string - invalidMethodType: string - malformedDllResponse: string - unknownDllError: string - hostIpcFailed: (pluginName: string, method: string) => string - hostUnavailable: (pluginName: string, method: string) => string - callFailed: string - movedToTrash: string - deleteFailed: string - revealedInFolder: string - revealFailed: string - opened: string - openFailed: string - pluginCallNotReady: string -}> = { - 'zh-CN': { - ipcCallFailed: 'IPC 调用返回失败', - ipcInnerFailed: 'IPC 内部调用失败', - scanIncomplete: '扫描结果不完整', - dirReadFailed: (details, moreCount) => - `目录读取失败或不完整:${details}${moreCount > 0 ? `;另有 ${moreCount} 个目录` : ''}`, - dirEntrySep: ';', - dirErrorColon: ':', - deepScanUnavailable: '深度扫描不可用,仅列出一级目录,结果不完整', - pathEmpty: '路径不能为空', - invalidMethodEmpty: 'INVALID_METHOD: 调用方法名不能为空', - invalidMethodFormat: 'INVALID_METHOD_FORMAT: 方法名包含非法字符或超长', - invalidParamsObject: 'INVALID_PARAMS: 参数必须为非空对象', - paramTooLong: (key) => `PARAM_TOO_LONG: 参数 ${key} 超过最大长度限制`, - paramOutOfRange: (key) => `PARAM_OUT_OF_RANGE: 数值参数 ${key} 越界或非有限数`, - methodParamEmpty: 'method 参数不能为空', - invalidMethodType: 'INVALID_METHOD: method 不能为空且必须为字符串', - malformedDllResponse: 'MALFORMED_DLL_RESPONSE: 原生组件返回了损坏的 JSON 数据', - unknownDllError: '原生组件返回未知错误', - hostIpcFailed: (pluginName, method) => `HOST_IPC_FAILED: ${pluginName}.${method} 调用失败`, - hostUnavailable: (pluginName, method) => `HOST_UNAVAILABLE: ${pluginName}.${method} 宿主接口未就绪`, - callFailed: '调用失败', - movedToTrash: '已移入回收站', - deleteFailed: '删除失败', - revealedInFolder: '已定位文件', - revealFailed: '定位失败', - opened: '已打开', - openFailed: '打开失败', - pluginCallNotReady: '插件调用未就绪' - }, - 'en-US': { - ipcCallFailed: 'IPC call failed', - ipcInnerFailed: 'Internal IPC call failed', - scanIncomplete: 'Incomplete scan results', - dirReadFailed: (details, moreCount) => - `Directory read failed or incomplete: ${details}${moreCount > 0 ? `; and ${moreCount} more` : ''}`, - dirEntrySep: '; ', - dirErrorColon: ': ', - deepScanUnavailable: 'Deep scan unavailable; only top-level directory listed (incomplete)', - pathEmpty: 'Path cannot be empty', - invalidMethodEmpty: 'INVALID_METHOD: Method name cannot be empty', - invalidMethodFormat: 'INVALID_METHOD_FORMAT: Method name contains invalid characters or is too long', - invalidParamsObject: 'INVALID_PARAMS: Parameters must be a non-null object', - paramTooLong: (key) => `PARAM_TOO_LONG: Parameter "${key}" exceeds maximum length`, - paramOutOfRange: (key) => `PARAM_OUT_OF_RANGE: Numeric parameter "${key}" is out of range or non-finite`, - methodParamEmpty: 'Method parameter cannot be empty', - invalidMethodType: 'INVALID_METHOD: Method must be a non-empty string', - malformedDllResponse: 'MALFORMED_DLL_RESPONSE: Native component returned malformed JSON', - unknownDllError: 'Native component returned an unknown error', - hostIpcFailed: (pluginName, method) => `HOST_IPC_FAILED: ${pluginName}.${method} call failed`, - hostUnavailable: (pluginName, method) => `HOST_UNAVAILABLE: ${pluginName}.${method} host interface not ready`, - callFailed: 'Call failed', - movedToTrash: 'Moved to Trash', - deleteFailed: 'Delete failed', - revealedInFolder: 'Revealed in folder', - revealFailed: 'Failed to reveal item', - opened: 'Opened', - openFailed: 'Failed to open', - pluginCallNotReady: 'Plugin invocation not ready' - } -} - -function ipcStrings() { - const locale = getLocale() - return NATIVE_IPC_MESSAGES[locale] ?? NATIVE_IPC_MESSAGES['en-US'] -} -/** - * ZTools 真实宿主 IPC 与系统能力桥接层 (Real Host IPC Bridge) - * - * 严格遵循《ZTools Declarative UI 2.0 架构与 35 款原生插件全量升级规范》5.1 真实环境铁律: - * - 在真实 Electron 宿主环境中,100% 走通 Preload (__ztoolsElectron.transport.methods / window.ztools / __ztoolsLauncher) 真实调用链路 - * - 严禁在真实环境中因参数格式或嵌套响应结构差异而回退到假数据 - */ - -let ipcReqSeq = 1 -const realFileSizeCache = new Map() - -export function nextMessageId(prefix = 'ipc'): string { - ipcReqSeq = (ipcReqSeq + 1) % 1_000_000 - return `${prefix}_${Date.now()}_${ipcReqSeq}` -} - -/** - * 判断当前是否处于真实的 ZTools Electron 渲染进程宿主环境 - */ -export function isRealElectronHost(hostOverride?: unknown): boolean { - if (hostOverride) return false - if (typeof window === 'undefined') return false - const w = window as DynamicBridge - return Boolean( - w.__ztoolsElectron?.transport?.methods || - w.ztools?.transport?.call || - w.ztools?.transport?.methods - ) -} - -function normalizeMethodParams(method: string, params: Record): Record { - if (!params || typeof params !== 'object') return {} - const next = { ...params } - if (method === 'system_get_disk_usage') { - const rawDrive = String(next.drive || next.path || 'C:\\').trim() - if (rawDrive.startsWith('/')) { - next.drive = rawDrive - } else { - const match = rawDrive.match(/^([A-Za-z]):/) - next.drive = match ? `${match[1].toUpperCase()}:\\` : rawDrive.replace(/\//g, '\\') - } - delete next.path - } - return next -} - -function normalizeMethodResult(method: string, payload: DynamicBridge): DynamicBridge { - if (!payload || typeof payload !== 'object') return payload - - if (method === 'system_get_disk_usage') { - const avail = typeof payload.available === 'number' - ? payload.available - : typeof payload.free === 'number' - ? payload.free - : Math.max(0, Number(payload.total || 0) - Number(payload.used || 0)) - return { - ...payload, - available: avail, - free: avail - } - } - - if (method === 'system_get_hardware_summary') { - const cpuModel = - typeof payload.cpuModel === 'string' && payload.cpuModel.trim() - ? payload.cpuModel.trim() - : Array.isArray(payload.cpuModels) && payload.cpuModels.length > 0 - ? String(payload.cpuModels[0]).trim() - : 'x86_64 Processor' - return { - ...payload, - cpuModel - } - } - - if (method === 'system_get_battery_status') { - // 宿主约定 percent 超出 0-100(如 255)表示无电池或电量未知,不能改写成 100% - const rawPct = payload.percent - const hasBattery = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 - return { - ...payload, - percent: hasBattery ? rawPct : null, - hasBattery - } - } - - if (method === 'screen_get_all_displays') { - const list = Array.isArray(payload) - ? payload - : Array.isArray(payload.displays) - ? payload.displays - : [] - return list.map((d: DynamicBridge) => ({ - ...d, - label: d?.label || d?.name || `Display #${d?.id ?? 1}` - })) - } - - return payload -} - -function extractIpcErrorMeta(errObj: DynamicBridge): { - errorCode?: string - errorDetails?: Record -} { - if (!errObj || typeof errObj !== 'object') return {} - const errorCode = - typeof errObj.errorCode === 'string' && errObj.errorCode.trim() - ? errObj.errorCode.trim() - : typeof errObj.code === 'string' && errObj.code.trim() - ? errObj.code.trim() - : undefined - const rawDetails = - errObj.errorDetails && typeof errObj.errorDetails === 'object' && !Array.isArray(errObj.errorDetails) - ? (errObj.errorDetails as Record) - : errObj.details && typeof errObj.details === 'object' && !Array.isArray(errObj.details) - ? (errObj.details as Record) - : undefined - return { - ...(errorCode ? { errorCode } : {}), - ...(rawDetails ? { errorDetails: rawDetails } : {}) - } -} - -function unwrapTransportResponse( - method: string, - raw: DynamicBridge -): { ok: boolean; data?: DynamicBridge; error?: string; errorCode?: string; errorDetails?: Record } { - if (raw === null || raw === undefined) { - return { ok: false, error: 'EMPTY_IPC_RESPONSE', errorCode: 'EMPTY_IPC_RESPONSE' } - } - if (typeof raw !== 'object') { - return { ok: true, data: raw } - } - if (raw.success === false) { - const errObj = raw.error - const errMsg = - typeof errObj === 'object' && errObj !== null - ? String(errObj.message || errObj.code || JSON.stringify(errObj)) - : String(errObj || ipcStrings().ipcCallFailed) - return { ok: false, error: errMsg, ...extractIpcErrorMeta(raw), ...extractIpcErrorMeta(errObj) } - } - - const firstLayer = 'data' in raw && raw.data !== undefined ? raw.data : raw - if (firstLayer && typeof firstLayer === 'object' && !Array.isArray(firstLayer)) { - if (firstLayer.success === false) { - const errObj = firstLayer.error - const errMsg = - typeof errObj === 'object' && errObj !== null - ? String(errObj.message || errObj.code || JSON.stringify(errObj)) - : String(errObj || ipcStrings().ipcInnerFailed) - return { ok: false, error: errMsg, ...extractIpcErrorMeta(firstLayer), ...extractIpcErrorMeta(errObj) } - } - if ('data' in firstLayer && firstLayer.data !== undefined) { - return { ok: true, data: normalizeMethodResult(method, firstLayer.data) } - } - } - - return { ok: true, data: normalizeMethodResult(method, firstLayer) } -} - -/** - * 调用 Electron Preload Transport 方法(自动封装合法的 alphanumeric messageId 与双层解包) - */ -export async function callHostTransport( - method: string, - params: Record = {}, - hostOverride?: DynamicBridge -): Promise<{ ok: boolean; data?: T; error?: string; errorCode?: string; errorDetails?: Record }> { - const normalizedParams = normalizeMethodParams(method, params) - - // 1. 测试注入的 hostOverride 优先 - if (hostOverride) { - if (typeof hostOverride[method] === 'function') { - try { - const res = await hostOverride[method](normalizedParams) - const unwrapped = unwrapTransportResponse(method, res) - return unwrapped as { ok: boolean; data?: T; error?: string; errorCode?: string; errorDetails?: Record } - } catch (err: DynamicBridge) { - return { ok: false, error: err instanceof Error ? err.message : String(err), ...extractIpcErrorMeta(err) } - } - } - if (typeof hostOverride?.transport?.call === 'function') { - try { - const res = await hostOverride.transport.call(method, normalizedParams) - const unwrapped = unwrapTransportResponse(method, res) - return unwrapped as { ok: boolean; data?: T; error?: string; errorCode?: string; errorDetails?: Record } - } catch (err: DynamicBridge) { - return { ok: false, error: err instanceof Error ? err.message : String(err), ...extractIpcErrorMeta(err) } - } - } - } - - if (typeof window === 'undefined') { - return { ok: false, error: 'NO_WINDOW_ENV', errorCode: 'NO_WINDOW_ENV' } - } - - const w = window as DynamicBridge - const methods = w.__ztoolsElectron?.transport?.methods || w.ztools?.transport?.methods - const fn = methods?.[method] - - if (typeof fn === 'function') { - try { - const messageId = nextMessageId(method.replace(/[^A-Za-z0-9_]/g, '_').slice(0, 24)) - const raw = await fn({ messageId, params: normalizedParams }) - return unwrapTransportResponse(method, raw) as { ok: boolean; data?: T; error?: string; errorCode?: string; errorDetails?: Record } - } catch (err: DynamicBridge) { - return { ok: false, error: err instanceof Error ? err.message : String(err), ...extractIpcErrorMeta(err) } - } - } - - if (typeof w.ztools?.transport?.call === 'function') { - try { - const raw = await w.ztools.transport.call(method, normalizedParams) - return unwrapTransportResponse(method, raw) as { ok: boolean; data?: T; error?: string; errorCode?: string; errorDetails?: Record } - } catch (err: DynamicBridge) { - return { ok: false, error: err instanceof Error ? err.message : String(err), ...extractIpcErrorMeta(err) } - } - } - - return { ok: false, error: `METHOD_NOT_AVAILABLE: ${method}`, errorCode: 'METHOD_NOT_AVAILABLE' } -} - -export interface RealDiskDriveInfo { - drive: string - totalBytes: number - usedBytes: number - availableBytes: number - usagePercent: number -} - -/** - * 探测本机全部真实挂载磁盘分区 (C:\ ~ Z:\ 或 macOS/POSIX 挂载点 '/') - */ -export async function probeRealDiskDrives( - candidateLetters: string[] = ['C', 'D', 'E', 'F', 'G'], - hostOverride?: DynamicBridge -): Promise { - const drives: RealDiskDriveInfo[] = [] - const results = await Promise.all( - candidateLetters.map(async (letter) => { - const raw = String(letter || '').trim() - const isPosix = raw.startsWith('/') - const drivePath = isPosix ? raw : `${raw.replace(/:\\?$/, '').toUpperCase()}:\\` - const res = await callHostTransport<{ - total: number - used: number - available: number - free?: number - percent: number - }>('system_get_disk_usage', { drive: drivePath }, hostOverride) - if (res.ok && res.data && typeof res.data.total === 'number' && res.data.total > 0) { - const availableBytes = - typeof res.data.available === 'number' - ? res.data.available - : typeof res.data.free === 'number' - ? res.data.free - : Math.max(0, res.data.total - res.data.used) - return { - drive: isPosix ? raw : `${raw.replace(/:\\?$/, '').toUpperCase()}:`, - totalBytes: res.data.total, - usedBytes: res.data.used, - availableBytes, - usagePercent: res.data.percent - } - } - return null - }) - ) - - for (const item of results) { - if (item) drives.push(item) - } - - if (drives.length === 0 && !candidateLetters.includes('/')) { - const posixRes = await callHostTransport<{ - total: number - used: number - available: number - free?: number - percent: number - }>('system_get_disk_usage', { drive: '/' }, hostOverride) - if (posixRes.ok && posixRes.data && typeof posixRes.data.total === 'number' && posixRes.data.total > 0) { - const availableBytes = - typeof posixRes.data.available === 'number' - ? posixRes.data.available - : typeof posixRes.data.free === 'number' - ? posixRes.data.free - : Math.max(0, posixRes.data.total - posixRes.data.used) - drives.push({ - drive: '/', - totalBytes: posixRes.data.total, - usedBytes: posixRes.data.used, - availableBytes, - usagePercent: posixRes.data.percent - }) - } - } - - return drives -} - -/** - * 获取本机真实系统特殊路径(支持 home 派生标准子目录兜底,自动兼容 Windows 与 macOS/POSIX) - */ -export async function getRealSystemPath( - name: 'home' | 'appData' | 'userData' | 'desktop' | 'documents' | 'downloads' | 'music' | 'pictures' | 'videos' | 'temp' | 'cache', - hostOverride?: DynamicBridge -): Promise { - const res = await callHostTransport('system_get_path', { name }, hostOverride) - if (res.ok && res.data) { - if (typeof res.data === 'string' && res.data.trim().length > 0) { - return res.data.trim() - } - if (typeof res.data.path === 'string' && res.data.path.trim().length > 0) { - return res.data.path.trim() - } - } - - if (name !== 'home') { - const home = await getRealSystemPath('home', hostOverride) - if (home) { - const isPosix = home.startsWith('/') - const subMap: Record = isPosix - ? { - desktop: `${home}/Desktop`, - documents: `${home}/Documents`, - downloads: `${home}/Downloads`, - music: `${home}/Music`, - pictures: `${home}/Pictures`, - videos: `${home}/Videos`, - appData: `${home}/Library/Application Support`, - userData: `${home}/Library/Application Support/ZTools`, - temp: '/tmp', - cache: `${home}/Library/Caches` - } - : { - desktop: `${home}\\Desktop`, - documents: `${home}\\Documents`, - downloads: `${home}\\Downloads`, - music: `${home}\\Music`, - pictures: `${home}\\Pictures`, - videos: `${home}\\Videos`, - appData: `${home}\\AppData\\Roaming`, - userData: `${home}\\AppData\\Roaming\\ZTools`, - temp: `${home}\\AppData\\Local\\Temp`, - cache: `${home}\\AppData\\Local` - } - if (subMap[name]) return subMap[name] - } - } - - return '' -} - -export type RealDriveUsageInfo = RealDiskDriveInfo - -export interface RealIndexedFileEntry { - name: string - path: string - ext: string - isDir: boolean - isDirectory: boolean - size: number - sizeBytes: number - mtime: number - mtimeMs: number - lastModifiedMs: number -} - -export interface RealDirectorySubdirSummary { - name: string - path: string - fileCount: number - totalBytes: number - mtime: number - /** 体积不是完整统计(宿主扫描截断且独立统计超时 / 无权限),totalBytes 只是下限 */ - approximate?: boolean -} - -export interface RealDirectoryScanResult extends Iterable { - files: RealIndexedFileEntry[] - totalFiles: number - fileCount: number - totalBytes: number - subdirs: RealDirectorySubdirSummary[] - /** 宿主扫描达到条目上限后停止:files / totalFiles 只是已遍历部分的抽样 */ - truncated?: boolean - /** totalBytes 为近似值(下限) */ - approximate?: boolean - /** 宿主实际遍历的条目数 */ - visitedEntries?: number - /** 读取失败的真实原因;已有文件仍可使用,但不能当作完整结果。 */ - error?: string -} - -interface ScanResultMeta { - truncated?: boolean - approximate?: boolean - visitedEntries?: number -} - -export interface ScanDirectoryTreeOptions { - maxDepth?: number - maxFiles?: number - collectTopN?: number - filterExt?: RegExp - hostOverride?: DynamicBridge -} - -function extractFileExt(fileNameOrPath: string): string { - const base = String(fileNameOrPath || '').split(/[\\/]/).pop() || '' - const dotIdx = base.lastIndexOf('.') - return dotIdx > 0 ? base.slice(dotIdx).toLowerCase() : '' -} - -function normalizeIndexedFileEntry(f: DynamicBridge): RealIndexedFileEntry { - const p = String(f?.path || '') - const name = String(f?.name || p.split(/[\\/]/).pop() || '') - const sz = Number(f?.size ?? f?.sizeBytes ?? 0) - const isDir = Boolean(f?.is_dir || f?.isDir || f?.isDirectory) - const rawMtime = Number(f?.mtime ?? f?.mtimeMs ?? 0) - const mtimeMs = rawMtime > 1e11 ? rawMtime : rawMtime > 0 ? rawMtime * 1000 : Date.now() - const mtimeSec = rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime - if (p && sz >= 0) realFileSizeCache.set(p, sz) - return { - name, - path: p, - ext: extractFileExt(name || p), - isDir, - isDirectory: isDir, - size: sz, - sizeBytes: sz, - mtime: mtimeSec, - mtimeMs, - lastModifiedMs: mtimeMs - } -} - -function makeScanResult( - files: RealIndexedFileEntry[], - totalFiles: number, - totalBytes: number, - subdirs: RealDirectorySubdirSummary[], - meta: ScanResultMeta = {} -): RealDirectoryScanResult { - return { - files, - totalFiles, - fileCount: totalFiles, - totalBytes, - subdirs, - ...(meta.truncated ? { truncated: true } : {}), - ...(meta.approximate ? { approximate: true } : {}), - ...(typeof meta.visitedEntries === 'number' ? { visitedEntries: meta.visitedEntries } : {}), - [Symbol.iterator]() { - return files[Symbol.iterator]() - } - } -} - -/** - * 调用客户端的原生文件索引组件 (ztools-indexer) 检索文件 - */ -export async function searchRealIndexedFiles( - query: string, - limit = 40, - hostOverride?: DynamicBridge -): Promise { - if (!query || !query.trim()) return [] - const q = query.trim() - const safeLimit = Math.min(200, Math.max(1, Math.floor(limit || 40))) - - try { - const res = await callHostTransport<{ files?: DynamicBridge[] }>( - 'system_search_files', - { query: q, limit: safeLimit }, - hostOverride - ) - if (res.ok && res.data && Array.isArray(res.data.files)) { - return res.data.files.map(normalizeIndexedFileEntry) - } - - if (!hostOverride && typeof window !== 'undefined') { - const w = window as DynamicBridge - if (typeof w.__ztoolsLauncher?.searchFiles === 'function') { - const rawOuter = await w.__ztoolsLauncher.searchFiles(q, safeLimit) - const raw = rawOuter && typeof rawOuter === 'object' && 'data' in rawOuter && rawOuter.data ? rawOuter.data : rawOuter - if (raw && Array.isArray(raw.files)) { - return raw.files.map(normalizeIndexedFileEntry) - } - } - } - } catch { - // ignore - } - return [] -} - -/** - * 深度扫描指定真实物理目录树(支持符号链接穿透,如 AppData\Roaming\Tencent -> D:\Local\Roaming\Tencent) - * 返回该目录下 Top 文件列表、全树真实文件总数、全树真实总字节数与一级子目录汇总 - */ -export async function scanRealDirectoryTree( - dirPath: string, - limitOrOptions: number | ScanDirectoryTreeOptions = 160, - hostOverrideArg?: DynamicBridge -): Promise { - const result = await scanDirectoryTreeWithError(dirPath, limitOrOptions, hostOverrideArg) - return result.error ? { ...result.scan, error: result.error } : result.scan -} - -/** 一次界面扫描的错误汇总;多个目录并行扫描时保留可读目录的结果。 */ -export function createDirectoryScanner(hostOverride?: DynamicBridge) { - const failures = new Map() - return { - async scan(dir: string, options: number | ScanDirectoryTreeOptions = 160) { - const result = await scanRealDirectoryTree(dir, options, hostOverride) - const error = result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') - if (error) failures.set(dir, error) - else failures.delete(dir) - return result - }, - get error(): string | undefined { - if (!failures.size) return undefined - const s = ipcStrings() - const details = [...failures].slice(0, 3).map(([dir, error]) => `${dir}${s.dirErrorColon}${error}`).join(s.dirEntrySep) - return s.dirReadFailed(details, Math.max(0, failures.size - 3)) - } - } -} - -/** scanRealDirectoryTree 的实现:额外带回读取失败原因(目录不存在 / 为空 / 无权限 / 载荷异常) */ -async function scanDirectoryTreeWithError( - dirPath: string, - limitOrOptions: number | ScanDirectoryTreeOptions, - hostOverrideArg?: DynamicBridge -): Promise<{ scan: RealDirectoryScanResult; error?: string }> { - const empty = makeScanResult([], 0, 0, []) - if (!dirPath || !dirPath.trim()) return { scan: empty, error: 'EMPTY_DIRECTORY_PATH' } - const targetDir = dirPath.trim() - - const opts: ScanDirectoryTreeOptions = - typeof limitOrOptions === 'number' - ? { maxFiles: limitOrOptions, hostOverride: hostOverrideArg } - : { ...limitOrOptions, hostOverride: limitOrOptions?.hostOverride ?? hostOverrideArg } - - const rawLimit = opts.maxFiles ?? opts.collectTopN ?? 160 - const safeLimit = Math.min(200, Math.max(1, Math.floor(rawLimit || 160))) - const hostOverride = opts.hostOverride - const filterExt = opts.filterExt - const dirQuery = `dir:${targetDir}` - - try { - let rawPayload: DynamicBridge = null - const res = await callHostTransport( - 'system_search_files', - { query: dirQuery, limit: safeLimit }, - hostOverride - ) - if (res.ok && res.data) { - rawPayload = res.data - } - if (!rawPayload && !hostOverride && typeof window !== 'undefined') { - const w = window as DynamicBridge - if (typeof w.__ztoolsLauncher?.searchFiles === 'function') { - const rawOuter = await w.__ztoolsLauncher.searchFiles(dirQuery, safeLimit) - rawPayload = - rawOuter && typeof rawOuter === 'object' && 'data' in rawOuter && rawOuter.data - ? rawOuter.data - : rawOuter - } - } - - if ( - rawPayload && - Array.isArray(rawPayload.files) - ) { - let files: RealIndexedFileEntry[] = rawPayload.files.map(normalizeIndexedFileEntry) - if (filterExt instanceof RegExp) { - files = files.filter(f => !f.isDir && (filterExt.test(f.name) || filterExt.test(f.ext))) - // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索目标扩展名 - if (files.length === 0 && !hostOverride) { - const extTokens = (filterExt.source.match(/[a-z0-9]{2,5}/gi) || []) - .filter(t => !['thumbcache', 'iconcache'].includes(t.toLowerCase())) - .slice(0, 4) - // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 - const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() - const extraLists = await Promise.all( - extTokens.map(ext => searchRealIndexedFiles(`.${ext.toLowerCase()}`, 30, hostOverride)) - ) - const seen = new Set() - for (const list of extraLists) { - for (const item of list) { - if (!item.isDir && item.size > 0 && !seen.has(item.path)) { - if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { - seen.add(item.path) - files.push(item) - } - } - } - } - } - } - if (typeof opts.collectTopN === 'number' && opts.collectTopN > 0 && files.length > opts.collectTopN) { - files = files.slice(0, opts.collectTopN) - } - const subdirs: RealDirectorySubdirSummary[] = Array.isArray(rawPayload.subdirs) - ? rawPayload.subdirs.map((s: DynamicBridge) => ({ - name: String(s.name || ''), - path: String(s.path || ''), - fileCount: Number(s.file_count ?? s.fileCount ?? 0), - totalBytes: Number(s.total_bytes ?? s.totalBytes ?? 0), - mtime: Number(s.mtime || 0), - ...(s.approximate === true ? { approximate: true } : {}) - })) - : [] - const computedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) - const totalFilesCount = - filterExt instanceof RegExp ? files.length : Number(rawPayload.total_matches ?? files.length) - const totalBytesCount = - filterExt instanceof RegExp ? computedBytes : Number(rawPayload.total_bytes ?? computedBytes) - const visited = Number(rawPayload.visited_entries) - return { - scan: makeScanResult(files, totalFilesCount, totalBytesCount, subdirs, { - truncated: rawPayload.truncated === true, - approximate: rawPayload.approximate === true, - ...(Number.isFinite(visited) && visited >= 0 ? { visitedEntries: visited } : {}) - }), - ...(typeof rawPayload.scan_error === 'string' && rawPayload.scan_error ? { error: rawPayload.scan_error } : {}) - } - } - - // 深度扫描失败或回执无效时,仅以一级目录读取补回可见结果;不冒充完整目录树。 - const listing = await listDirectoryViaFilesystem(targetDir, hostOverride, { withSizes: true, limit: safeLimit }) - if (listing.ok && listing.entries.length > 0) { - const files: RealIndexedFileEntry[] = [] - let totalBytes = 0 - for (const entry of listing.entries) { - if (filterExt instanceof RegExp && !filterExt.test(entry.name) && !filterExt.test(entry.ext)) { - continue - } - files.push(entry) - totalBytes += entry.isDir ? 0 : entry.size - } - const incomplete = listing.entries.some(entry => entry.isDir) || listing.entries.length >= safeLimit - return { - scan: makeScanResult(files, files.filter(file => !file.isDir).length, totalBytes, [], { approximate: incomplete }), - ...(incomplete ? { error: res.error || ipcStrings().deepScanUnavailable } : {}) - } - } - return listing.ok ? { scan: empty } : { scan: empty, error: listing.error || 'DIRECTORY_READ_FAILED' } - } catch (error) { - return { scan: empty, error: error instanceof Error ? error.message : String(error) } - } -} - - -/** 目录读取不到任何条目(不存在 / 为空 / 无权限)时的错误码 */ -export const DIRECTORY_EMPTY_OR_UNREADABLE = 'DIRECTORY_EMPTY_OR_UNREADABLE' - -export interface RealDirectoryListingResult { - /** 目录内条目的完整路径;读取失败时为空数组 */ - entries: string[] - /** 读取失败或目录为空时的错误码 / 宿主错误信息 */ - error?: string -} - -export interface RealDirectChildrenResult { - /** 目录的直接子项(子目录在前),按路径去重 */ - entries: RealIndexedFileEntry[] - /** 宿主扫描达到条目上限,可能只返回了部分直接子项 */ - partial: boolean - error?: string -} - -function stripTrailingSeparators(p: string): string { - const trimmed = p.replace(/[\\/]+$/, '') - return trimmed || p.slice(0, 1) -} - -function isWindowsStylePath(p: string): boolean { - return /^[A-Za-z]:/.test(p) || p.startsWith('\\\\') || (p.includes('\\') && !p.includes('/')) -} - -function comparablePath(p: string): string { - const stripped = stripTrailingSeparators(String(p || '').trim()) - return isWindowsStylePath(stripped) ? stripped.replace(/\//g, '\\').toLowerCase() : stripped -} - -function parentDirOf(p: string): string { - const stripped = stripTrailingSeparators(String(p || '')) - const idx = Math.max(stripped.lastIndexOf('/'), stripped.lastIndexOf('\\')) - if (idx < 0) return '' - if (idx === 0) return stripped.slice(0, 1) - const parent = stripped.slice(0, idx) - return /^[A-Za-z]:$/.test(parent) ? `${parent}\\` : parent -} - -function isDirectChildPath(dirPath: string, candidate: string): boolean { - if (!candidate) return false - return comparablePath(parentDirOf(candidate)) === comparablePath(dirPath) -} - -function joinChildPath(dirPath: string, name: string): string { - const sep = isWindowsStylePath(dirPath) ? '\\' : '/' - const base = dirPath.replace(/[\\/]+$/, '') - return `${base}${sep}${name}` -} - -/** - * 通过 filesystem_get_directory_contents 读取一级目录(需宿主授权)。 - * 宿主真实返回 { success, files: [{ name, size, isDirectory, lastModified }] }(name 为文件名); - * 兼容旧测试替身返回的完整路径字符串数组。 - */ -async function listDirectoryViaFilesystem( - dirPath: string, - hostOverride: DynamicBridge, - options: { withSizes?: boolean; limit?: number } = {} -): Promise<{ ok: boolean; entries: RealIndexedFileEntry[]; error?: string }> { - const res = await callHostTransport('filesystem_get_directory_contents', { path: dirPath }, hostOverride) - if (!res.ok) return { ok: false, entries: [], error: res.error || 'DIRECTORY_READ_FAILED' } - const data = res.data - const rawList: unknown[] | null = Array.isArray(data) ? data : Array.isArray(data?.files) ? data.files : null - if (!rawList) return { ok: false, entries: [], error: 'INVALID_DIRECTORY_PAYLOAD' } - - const limit = Math.max(1, Math.floor(options.limit ?? 1000)) - const nowSec = Math.floor(Date.now() / 1000) - const entries: RealIndexedFileEntry[] = [] - const seen = new Set() - for (const item of rawList) { - if (entries.length >= limit) break - let entry: RealIndexedFileEntry | null = null - if (typeof item === 'string') { - const itemPath = item.trim() - if (!itemPath) continue - const name = itemPath.split(/[\\/]/).pop() || itemPath - const sz = options.withSizes ? await getRealFileSize(itemPath, hostOverride) : 0 - entry = normalizeIndexedFileEntry({ - name, - path: itemPath, - isDir: sz === 0 && !name.includes('.'), - size: sz, - mtime: nowSec - }) - } else if (item && typeof item === 'object' && typeof (item as DynamicBridge).name === 'string') { - const raw = item as DynamicBridge - const rawName = raw.name.trim() - if (!rawName || rawName === '.' || rawName === '..') continue - // 只接受文件名,或确实位于该目录下的完整路径,拒绝越界路径 - const fullPath = /[\\/]/.test(rawName) ? rawName : joinChildPath(dirPath, rawName) - if (!isDirectChildPath(dirPath, fullPath)) continue - const isDir = Boolean(raw.isDirectory ?? raw.isDir ?? raw.is_dir) - const parsedMtime = Date.parse(String(raw.lastModified || '')) - entry = normalizeIndexedFileEntry({ - name: fullPath.split(/[\\/]/).pop() || rawName, - path: fullPath, - isDir, - size: isDir ? 0 : Math.max(0, Number(raw.size) || 0), - mtime: Number.isFinite(parsedMtime) ? parsedMtime : nowSec - }) - } - if (!entry || seen.has(entry.path)) continue - seen.add(entry.path) - entries.push(entry) - } - return { ok: true, entries } -} - -/** - * 读取真实目录下的条目路径(真实宿主中优先走 dir: 扫描:一级子目录 + 全树 Top-N 大文件),并返回失败原因。 - * 目录不存在、为空或无权限时返回空列表与错误码,绝不用全盘关键词搜索结果冒充目录内容。 - */ -export async function listRealDirectoryContentsResult( - dirPath: string, - hostOverride?: DynamicBridge -): Promise { - if (!dirPath || !dirPath.trim()) return { entries: [], error: 'EMPTY_DIRECTORY_PATH' } - const targetDir = dirPath.trim() - - if (!hostOverride && isRealElectronHost()) { - const tree = await scanRealDirectoryTree(targetDir, 60) - const paths: string[] = [] - for (const s of tree.subdirs) { - if (s.path) paths.push(s.path) - } - for (const f of tree.files) { - if (f.path) paths.push(f.path) - } - if (paths.length > 0) return { entries: Array.from(new Set(paths)) } - } - - const listing = await listDirectoryViaFilesystem(targetDir, hostOverride) - if (!listing.ok) return { entries: [], error: listing.error } - if (listing.entries.length === 0) return { entries: [], error: DIRECTORY_EMPTY_OR_UNREADABLE } - return { entries: listing.entries.map(e => e.path) } -} - -/** - * 读取真实目录下的条目路径(保持旧签名:失败时返回空数组,需要失败原因请用 listRealDirectoryContentsResult) - */ -export async function listRealDirectoryContents( - dirPath: string, - hostOverride?: DynamicBridge -): Promise { - return (await listRealDirectoryContentsResult(dirPath, hostOverride)).entries -} - -/** - * 只列出目录的直接子项(子目录 + 直接位于该目录下的文件),用于文件夹预览、按目录改名等场景。 - * dir: 扫描结果中只保留 subdirs 与父目录等于 dirPath 的文件;扫描达到上限时 partial=true,由插件如实提示「仅显示部分」。 - */ -export async function listDirectChildren( - dirPath: string, - hostOverride?: DynamicBridge -): Promise { - if (!dirPath || !dirPath.trim()) return { entries: [], partial: false, error: 'EMPTY_DIRECTORY_PATH' } - const targetDir = dirPath.trim() - const scanLimit = 200 - const entries: RealIndexedFileEntry[] = [] - const seen = new Set() - const push = (entry: RealIndexedFileEntry) => { - const key = comparablePath(entry.path) - if (!entry.path || seen.has(key)) return - seen.add(key) - entries.push(entry) - } - - const { scan: tree, error } = await scanDirectoryTreeWithError(targetDir, { maxFiles: scanLimit, hostOverride }) - for (const s of tree.subdirs) { - if (!s.path || !isDirectChildPath(targetDir, s.path)) continue - push( - normalizeIndexedFileEntry({ - name: s.name || s.path.split(/[\\/]/).pop(), - path: s.path, - isDir: true, - size: s.totalBytes, - mtime: s.mtime - }) - ) - } - let directFileCount = 0 - for (const f of tree.files) { - if (!isDirectChildPath(targetDir, f.path)) continue - directFileCount++ - push(f) - } - // 宿主 total_matches 是全树文件数、subdirs[].file_count 是各子目录全树文件数,差值即直接子文件数; - // 拿到的直接子文件少于它就说明被 Top-N 截断了。计数不可用时按是否达到扫描上限判断 - const expectedDirectFiles = tree.totalFiles - tree.subdirs.reduce((sum, d) => sum + (Number(d.fileCount) || 0), 0) - const partial = - Number.isFinite(expectedDirectFiles) && expectedDirectFiles >= 0 - ? directFileCount < expectedDirectFiles - : tree.files.length >= scanLimit - if (entries.length > 0) { - return { entries, partial } - } - - if (tree.files.length > 0) { - // dir: 扫描只返回了深层文件(直接子文件被 Top-N 截掉),如实标注部分结果 - return { entries: [], partial: true, error: DIRECTORY_EMPTY_OR_UNREADABLE } - } - return { entries: [], partial: false, error: error || DIRECTORY_EMPTY_OR_UNREADABLE } -} - -/** - * 获取真实文件字节大小(优先用扫描结果里的大小,再走 filesystem_get_file_size);读不到时返回 0 - */ -export async function getRealFileSize( - filePath: string, - hostOverride?: DynamicBridge -): Promise { - if (!filePath) return 0 - if (!hostOverride && realFileSizeCache.has(filePath)) { - const cached = realFileSizeCache.get(filePath)! - if (cached > 0) return cached - } - const res = await callHostTransport('filesystem_get_file_size', { path: filePath }, hostOverride) - // 客户端返回 { success, size }(目录时 size 为 -1),旧的测试替身直接返回数字 - const size = typeof res.data === 'number' ? res.data : res.data?.size - if (res.ok && typeof size === 'number' && Number.isFinite(size) && size >= 0) { - realFileSizeCache.set(filePath, size) - return size - } - return 0 -} - -/** - * 在访达 / 资源管理器中定位并高亮文件或目录。 - * 定位失败直接返回 false,不能改用“打开”:对可执行文件那等于运行它。 - */ -export async function showRealItemInFolder( - fullPath: string, - hostOverride?: DynamicBridge -): Promise { - if (!fullPath) return false - const res = await callHostTransport('shell_show_item_in_folder', { fullPath }, hostOverride) - return res.ok -} - -/** - * 使用系统默认程序打开文件或目录 - */ -export async function openRealPath( - fullPath: string, - hostOverride?: DynamicBridge -): Promise { - if (!fullPath) return false - const res = await callHostTransport('shell_open_path', { fullPath }, hostOverride) - return res.ok -} - -/** - * 将真实文件或目录移入系统回收站(安全可恢复删除) - */ -export async function trashRealItem( - fullPath: string, - hostOverride?: DynamicBridge -): Promise<{ ok: boolean; error?: string; errorCode?: string; errorDetails?: Record }> { - if (!fullPath) return { ok: false, error: ipcStrings().pathEmpty } - const res = await callHostTransport('shell_trash_item', { fullPath }, hostOverride) - return { - ok: res.ok, - error: res.error, - ...(!res.ok && res.errorCode ? { errorCode: res.errorCode } : {}), - ...(!res.ok && res.errorDetails ? { errorDetails: res.errorDetails } : {}) - } -} - -export interface NativeInvocationResult { - ok: boolean - code: number - message: string - data?: T - error?: string - errorCode?: string - errorDetails?: Record -} - -export interface DllCapabilityResponse { - ok: boolean - code: number - data: T | null - message?: string - error?: string - errorCode?: string - errorDetails?: Record - pluginName: string - method: string - fromFallback?: boolean -} - -/** 声明式能力菜单项及其调用回执,供相同宿主协议的插件共用。 */ -export interface CapabilityActionItem { - id: string - title: string - subtitle: string - tag: string - method: string - params: Record -} - -export type PluginInvocationResult = Pick< - DllCapabilityResponse, 'ok' | 'pluginName' | 'method' | 'error' | 'errorCode' | 'errorDetails' | 'fromFallback' -> & { data?: unknown } - -/** 多个原生能力插件共用的参数边界校验;保护目标由各插件按自身业务提供。 */ -export function validateNativeCapabilityPayload( - method: string, - params: unknown, - forbiddenPattern: RegExp, - forbiddenReason: string -): { valid: boolean; error?: string } { - const s = ipcStrings() - if (typeof method !== 'string' || method.trim().length === 0) { - return { valid: false, error: s.invalidMethodEmpty } - } - if (method.length > 128 || !/^[A-Za-z0-9_]+$/.test(method.trim())) { - return { valid: false, error: s.invalidMethodFormat } - } - if (params === null || params === undefined || typeof params !== 'object' || Array.isArray(params)) { - return { valid: false, error: s.invalidParamsObject } - } - - const record = params as Record - for (const [key, val] of Object.entries(record)) { - if (typeof val === 'string') { - if (val.length > 4096) { - return { valid: false, error: s.paramTooLong(key) } - } - if (forbiddenPattern.test(val)) { - return { valid: false, error: `SECURITY_INTERCEPTED: ${forbiddenReason}` } - } - } else if (typeof val === 'number') { - if (!Number.isFinite(val) || val < -1000 || val > 100_000_000) { - return { valid: false, error: s.paramOutOfRange(key) } - } - } - } - - return { valid: true } -} - -export async function invokeDllPluginCapability( - pluginName: string, - method: string, - params: Record = {}, - hostBridge?: DynamicBridge, - offlineFallback?: () => T | Promise -): Promise> { - const s = ipcStrings() - if (!method || typeof method !== 'string' || method.trim().length === 0) { - return { - ok: false, - code: -1, - data: null, - message: s.methodParamEmpty, - error: s.invalidMethodType, - pluginName, - method: String(method || '') - } - } - - const trimmedMethod = method.trim() - - const unwrapDllRawPayload = (raw: unknown, unwrapDataProperty: boolean): DllCapabilityResponse => { - let parsed: DynamicBridge = raw - if (typeof raw === 'string') { - try { - parsed = JSON.parse(raw) - } catch { - throw new Error(s.malformedDllResponse) - } - } - if (parsed && typeof parsed === 'object') { - if ('error' in parsed && parsed.error !== undefined && parsed.error !== null && parsed.error !== '') { - const errMsg = `DLL_ERROR: ${String(parsed.error)}` - return { - ok: false, - code: typeof parsed.code === 'number' ? parsed.code : -1, - data: null, - message: errMsg, - error: errMsg, - ...extractIpcErrorMeta(parsed), - ...extractIpcErrorMeta(parsed.error), - pluginName, - method: trimmedMethod, - fromFallback: false - } - } - if ('ok' in parsed && parsed.ok === false) { - const errMsg = `DLL_ERROR: ${String(parsed.error || parsed.message || s.unknownDllError)}` - return { - ok: false, - code: typeof parsed.code === 'number' ? parsed.code : -1, - data: null, - message: errMsg, - error: errMsg, - ...extractIpcErrorMeta(parsed), - ...extractIpcErrorMeta(parsed.error), - pluginName, - method: trimmedMethod, - fromFallback: false - } - } - const dataPayload = unwrapDataProperty && 'data' in parsed && parsed.data !== undefined ? parsed.data : parsed - return { - ok: true, - code: typeof parsed.code === 'number' ? parsed.code : 0, - data: dataPayload as T, - message: typeof parsed.message === 'string' ? parsed.message : undefined, - pluginName, - method: trimmedMethod, - fromFallback: false - } - } - return { - ok: true, - code: 0, - data: (parsed ?? null) as T, - pluginName, - method: trimmedMethod, - fromFallback: false - } - } - - const wrapCaughtDllError = (err: unknown): DllCapabilityResponse => { - const message = err instanceof Error ? err.message : String(err) - if (message.startsWith('MALFORMED_DLL_RESPONSE:')) { - throw err - } - const errMsg = `NATIVE_CALL_FAILED: ${message}` - return { - ok: false, - code: -1, - data: null, - message: errMsg, - error: errMsg, - ...extractIpcErrorMeta(err), - pluginName, - method: trimmedMethod, - fromFallback: false - } - } - - if (hostBridge && typeof hostBridge.invokeNative === 'function') { - try { - const raw = await hostBridge.invokeNative(pluginName, trimmedMethod, params) - return unwrapDllRawPayload(raw, true) - } catch (err: unknown) { - return wrapCaughtDllError(err) - } - } - - const runtimeHost = (hostBridge ?? (globalThis as Record).ztools) as - | { dllplugin?: { call?: (plugin: string, fn: string, payload: unknown) => Promise | unknown } } - | undefined - - const callFn = runtimeHost?.dllplugin?.call - if (typeof callFn === 'function') { - try { - const raw = await callFn.call(runtimeHost?.dllplugin, pluginName, trimmedMethod, params) - return unwrapDllRawPayload(raw, false) - } catch (err: unknown) { - return wrapCaughtDllError(err) - } - } - - const ipcRes = await callHostTransport( - 'dllplugin_call', - { - plugin: pluginName, - func: trimmedMethod, - params - }, - hostBridge - ) - - if (ipcRes.ok && ipcRes.data !== undefined && ipcRes.data !== null) { - return unwrapDllRawPayload(ipcRes.data, false) - } - - const isExplicitTransportFailure = - typeof ipcRes.error === 'string' && - ipcRes.error.length > 0 && - ipcRes.error !== 'NO_WINDOW_ENV' && - !ipcRes.error.startsWith('METHOD_NOT_AVAILABLE:') - - if ( - isRealElectronHost(hostBridge) || - isRealElectronHost() || - Boolean((hostBridge as DynamicBridge)?.__isRealHost) || - isExplicitTransportFailure - ) { - const errMsg = - ipcRes.error || s.hostIpcFailed(pluginName, trimmedMethod) - return { - ok: false, - code: -1, - data: null, - message: errMsg, - error: errMsg, - ...(ipcRes.errorCode ? { errorCode: ipcRes.errorCode } : {}), - ...(ipcRes.errorDetails ? { errorDetails: ipcRes.errorDetails } : {}), - pluginName, - method: trimmedMethod, - fromFallback: false - } - } - - if (typeof offlineFallback === 'function') { - const fallbackData = await offlineFallback() - return { - ok: true, - code: 0, - data: fallbackData, - pluginName, - method: trimmedMethod, - fromFallback: true - } - } - - const unavailableMsg = s.hostUnavailable(pluginName, trimmedMethod) - return { - ok: false, - code: -1, - data: null, - message: unavailableMsg, - error: unavailableMsg, - ...(ipcRes.errorCode ? { errorCode: ipcRes.errorCode } : {}), - ...(ipcRes.errorDetails ? { errorDetails: ipcRes.errorDetails } : {}), - pluginName, - method: trimmedMethod, - fromFallback: true - } -} - -export function formatBytes(bytes: number, decimals = 1): string { - const num = Number(bytes) - if (!Number.isFinite(num) || num <= 0) return '0 B' - if (num < 1024) return `${Math.round(num)} B` - const units = ['B', 'KB', 'MB', 'GB', 'TB'] - let val = num - let idx = 0 - while (val >= 1024 && idx < units.length - 1) { - val /= 1024 - idx += 1 - } - const safeDecimals = Math.max(0, Math.floor(decimals)) - return `${val >= 100 ? val.toFixed(0) : val.toFixed(safeDecimals)} ${units[idx]}` -} - -export function joinWinPath(...segments: string[]): string { - return segments - .filter(s => typeof s === 'string' && s.trim().length > 0) - .map((s, i) => (i === 0 ? s.replace(/[\\/]+$/, '') : s.replace(/^[\\/]+|[\\/]+$/g, ''))) - .join('\\') -} - -export interface RealEnvPaths { - home: string - userProfile: string - appData: string - localAppData: string - temp: string - downloads: string - documents: string - desktop: string - pictures: string - videos: string - music: string -} - -export async function getRealEnvPaths(hostOverride?: DynamicBridge): Promise { - const [homeRaw, appData, downloads, documents, desktop, pictures, videos, music] = await Promise.all([ - getRealSystemPath('home', hostOverride), - getRealSystemPath('appData', hostOverride), - getRealSystemPath('downloads', hostOverride), - getRealSystemPath('documents', hostOverride), - getRealSystemPath('desktop', hostOverride), - getRealSystemPath('pictures', hostOverride), - getRealSystemPath('videos', hostOverride), - getRealSystemPath('music', hostOverride) - ]) - const home = homeRaw || 'C:\\Users\\Default' - const isPosix = home.startsWith('/') - const tempRes = hostOverride ? await getRealSystemPath('temp', hostOverride) : '' - if (isPosix) { - return { - home, - userProfile: home, - appData: appData || `${home}/Library/Application Support`, - localAppData: `${home}/Library/Application Support`, - temp: tempRes || '/tmp', - downloads: downloads || `${home}/Downloads`, - documents: documents || `${home}/Documents`, - desktop: desktop || `${home}/Desktop`, - pictures: pictures || `${home}/Pictures`, - videos: videos || `${home}/Videos`, - music: music || `${home}/Music` - } - } - return { - home, - userProfile: home, - appData: appData || `${home}\\AppData\\Roaming`, - localAppData: `${home}\\AppData\\Local`, - temp: tempRes || `${home}\\AppData\\Local\\Temp`, - downloads: downloads || `${home}\\Downloads`, - documents: documents || `${home}\\Documents`, - desktop: desktop || `${home}\\Desktop`, - pictures: pictures || `${home}\\Pictures`, - videos: videos || `${home}\\Videos`, - music: music || `${home}\\Music` - } -} - -export const resolveRealSpecialPaths = getRealEnvPaths - -export async function readRealDirectory( - dirPath: string, - hostOverride?: DynamicBridge -): Promise { - if (!dirPath) return [] - const tree = await scanRealDirectoryTree(dirPath, { maxFiles: 120, hostOverride }) - const entries: RealIndexedFileEntry[] = [] - for (const s of tree.subdirs) { - entries.push( - normalizeIndexedFileEntry({ - name: s.name, - path: s.path, - isDir: true, - isDirectory: true, - size: s.totalBytes, - mtime: s.mtime - }) - ) - } - for (const f of tree.files) { - entries.push(f) - } - // scanRealDirectoryTree 已在 dir: 扫描无结果时退回一级目录读取;仍为空即目录不存在 / 为空 / 无权限,如实返回空列表 - return entries -} - -export async function moveRealFilesToTrash( - paths: string[], - hostOverride?: DynamicBridge -): Promise<{ - ok: boolean - trashedCount: number - deletedCount: number - failedPaths: string[] - error?: string -}> { - let deletedCount = 0 - const failedPaths: string[] = [] - let lastError: string | undefined - for (const p of paths) { - if (!p) continue - const res = await trashRealItem(p, hostOverride) - if (res.ok) { - deletedCount += 1 - } else { - failedPaths.push(p) - if (res.error) lastError = res.error - } - } - return { - ok: deletedCount > 0 || paths.length === 0, - trashedCount: deletedCount, - deletedCount, - failedPaths, - error: lastError - } -} - -const CAPABILITY_TO_PLUGIN_MAP: Record = { - 'mover.relocateWithJunction': { plugin: 'MoverPlugin', func: 'relocateWithJunction' }, - 'mover.scanCandidates': { plugin: 'MoverPlugin', func: 'scanCandidates' }, - 'recovery.restoreFile': { plugin: 'DataRecoveryPlugin', func: 'restoreFile' }, - 'recovery.scanDeletedFiles': { plugin: 'DataRecoveryPlugin', func: 'scanDeletedFiles' }, - 'shredder.secureWipeFile': { plugin: 'ShredderPlugin', func: 'secureWipeFile' }, - 'shredder.scanCandidates': { plugin: 'ShredderPlugin', func: 'scanCandidates' }, - 'backup.createSnapshotArchive': { plugin: 'SystemBackupPlugin', func: 'createSnapshotArchive' }, - 'backup.restoreSnapshotArchive': { plugin: 'SystemBackupPlugin', func: 'restoreSnapshotArchive' }, - 'backup.scanSnapshots': { plugin: 'SystemBackupPlugin', func: 'scanSnapshots' }, - 'sqlite.execute': { plugin: 'SqlitePlugin', func: 'execute' }, - 'sqlite.query': { plugin: 'SqlitePlugin', func: 'executeQuery' }, - 'sqlite.inspectWorkspace': { plugin: 'SqlitePlugin', func: 'inspectWorkspace' } -} - -export async function invokeHostCapability( - capability: string, - params: Record = {}, - hostOverride?: DynamicBridge -): Promise> { - const normalizedMethod = capability.replace(/\./g, '_') - - // 若测试显式注入了对应 normalizedMethod 的 mock 函数,优先调用测试桩 - if (hostOverride && typeof hostOverride[normalizedMethod] === 'function') { - const mockRes = await callHostTransport(normalizedMethod, params, hostOverride) - return { - ok: mockRes.ok, - code: mockRes.ok ? 0 : -1, - message: mockRes.ok ? 'OK' : mockRes.error || ipcStrings().callFailed, - data: mockRes.data, - error: mockRes.error, - ...(!mockRes.ok && mockRes.errorCode ? { errorCode: mockRes.errorCode } : {}), - ...(!mockRes.ok && mockRes.errorDetails ? { errorDetails: mockRes.errorDetails } : {}) - } - } - - if (capability === 'system.info') { - const drives = await probeRealDiskDrives(['C', 'D', 'E', 'F'], hostOverride) - return { - ok: true, - code: 0, - message: 'OK', - data: { - storage: drives.map(d => ({ - mount: d.drive, - fs: d.drive, - size: d.totalBytes, - total: d.totalBytes, - used: d.usedBytes, - available: d.availableBytes, - free: d.availableBytes, - percent: d.usagePercent - })) - } as unknown as T - } - } - if (capability === 'filesystem.deleteItem') { - const targetPath = String(params.path || params.fullPath || '') - const tr = await trashRealItem(targetPath, hostOverride) - const s = ipcStrings() - return { - ok: tr.ok, - code: tr.ok ? 0 : -1, - message: tr.ok ? s.movedToTrash : tr.error || s.deleteFailed, - error: tr.error, - ...(!tr.ok && tr.errorCode ? { errorCode: tr.errorCode } : {}), - ...(!tr.ok && tr.errorDetails ? { errorDetails: tr.errorDetails } : {}) - } - } - if (capability === 'system.showItemInFolder') { - const targetPath = String(params.path || params.fullPath || '') - const s = ipcStrings() - if (!targetPath) { - return { ok: false, code: -1, message: s.revealFailed } - } - const res = await callHostTransport('shell_show_item_in_folder', { fullPath: targetPath }, hostOverride) - return { - ok: res.ok, - code: res.ok ? 0 : -1, - message: res.ok ? s.revealedInFolder : res.error || s.revealFailed, - ...(!res.ok && res.error ? { error: res.error } : {}), - ...(!res.ok && res.errorCode ? { errorCode: res.errorCode } : {}), - ...(!res.ok && res.errorDetails ? { errorDetails: res.errorDetails } : {}) - } - } - if (capability === 'filesystem.openItem' || capability === 'system.openUrl') { - const target = String(params.path || params.url || params.fullPath || '') - const method = capability === 'system.openUrl' ? 'shell_open_external' : 'shell_open_path' - const res = await callHostTransport( - method, - capability === 'system.openUrl' ? { url: target } : { fullPath: target }, - hostOverride - ) - const s = ipcStrings() - return { - ok: res.ok, - code: res.ok ? 0 : -1, - message: res.ok ? s.opened : res.error || s.openFailed, - data: res.data, - error: res.error, - ...(!res.ok && res.errorCode ? { errorCode: res.errorCode } : {}), - ...(!res.ok && res.errorDetails ? { errorDetails: res.errorDetails } : {}) - } - } - - const pluginMapping = CAPABILITY_TO_PLUGIN_MAP[capability] - if (pluginMapping) { - const dllRes = await invokePluginService( - pluginMapping.plugin, - pluginMapping.func, - params, - hostOverride - ) - if (dllRes.ok) return dllRes - if (hostOverride) { - const fallbackMock = await callHostTransport(normalizedMethod, params, hostOverride) - if (fallbackMock.ok) { - return { - ok: true, - code: 0, - message: 'OK', - data: fallbackMock.data - } - } - } - return dllRes - } - - const res = await callHostTransport(normalizedMethod, params, hostOverride) - return { - ok: res.ok, - code: res.ok ? 0 : -1, - message: res.ok ? 'OK' : res.error || ipcStrings().callFailed, - data: res.data, - error: res.error, - ...(!res.ok && res.errorCode ? { errorCode: res.errorCode } : {}), - ...(!res.ok && res.errorDetails ? { errorDetails: res.errorDetails } : {}) - } -} - -export async function invokePluginService( - pluginName: string, - action: string, - params: Record = {}, - hostOverride?: DynamicBridge -): Promise> { - const s = ipcStrings() - // 1. 若测试注入了专门拦截 plugin_invoke 的 mock,支持调用 - if (hostOverride && typeof hostOverride.plugin_invoke === 'function') { - const mockRes = await callHostTransport( - 'plugin_invoke', - { plugin: pluginName, action, params }, - hostOverride - ) - return { - ok: mockRes.ok, - code: mockRes.ok ? 0 : -1, - message: mockRes.ok ? 'OK' : mockRes.error || s.pluginCallNotReady, - data: mockRes.data, - error: mockRes.error, - ...(!mockRes.ok && mockRes.errorCode ? { errorCode: mockRes.errorCode } : {}), - ...(!mockRes.ok && mockRes.errorDetails ? { errorDetails: mockRes.errorDetails } : {}) - } - } - - // 2. 优先走真实 Electron IPC 的 dllplugin_call 通道 - const dllRes = await callHostTransport( - 'dllplugin_call', - { plugin: pluginName, func: action, params }, - hostOverride - ) - if (dllRes.ok) { - const inner = dllRes.data - if (inner && typeof inner === 'object' && typeof inner.error === 'string' && inner.error.length > 0 && inner.ok !== true) { - return { - ok: false, - code: -1, - message: inner.error, - error: inner.error, - ...extractIpcErrorMeta(inner) - } - } - return { - ok: true, - code: 0, - message: 'OK', - data: inner as T - } - } - - // 3. 兼容单元测试中通过 transport.call('plugin_invoke') 注入的测试桩 - if (hostOverride) { - const legacyRes = await callHostTransport( - 'plugin_invoke', - { plugin: pluginName, action, params }, - hostOverride - ) - if (legacyRes.ok) { - return { - ok: true, - code: 0, - message: 'OK', - data: legacyRes.data - } - } - } - - // 4. 兼容旧版 globalThis.ztools.dllplugin.call - const g = globalThis as DynamicBridge - if (!hostOverride && typeof g?.ztools?.dllplugin?.call === 'function') { - try { - const raw = await g.ztools.dllplugin.call(pluginName, action, params) - if (raw && typeof raw === 'object' && raw.ok === false) { - return { - ok: false, - code: -1, - message: String(raw.error || s.callFailed), - error: String(raw.error || s.callFailed), - ...extractIpcErrorMeta(raw), - ...extractIpcErrorMeta(raw.error) - } - } - const data = raw && typeof raw === 'object' && 'data' in raw ? raw.data : raw - return { ok: true, code: 0, message: 'OK', data: data as T } - } catch (err: DynamicBridge) { - return { - ok: false, - code: -1, - message: err instanceof Error ? err.message : String(err), - error: err instanceof Error ? err.message : String(err), - ...extractIpcErrorMeta(err) - } - } - } - - return { - ok: false, - code: -1, - message: dllRes.error || s.pluginCallNotReady, - error: dllRes.error || s.pluginCallNotReady, - ...(dllRes.errorCode ? { errorCode: dllRes.errorCode } : {}), - ...(dllRes.errorDetails ? { errorDetails: dllRes.errorDetails } : {}) - } -} - -const SHA256_K = new Uint32Array([ - 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, - 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, - 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, - 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, - 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, - 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, - 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, - 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 -]) - -function rotr32(x: number, n: number): number { - return (x >>> n) | (x << (32 - n)) -} - -/** - * 标准 FIPS 180-4 SHA-256 真实字节摘要算法(返回 64 位小写 Hex) - */ -export function computeRealSha256Hex(input: string | Uint8Array): string { - const bytes = - typeof input === 'string' ? new TextEncoder().encode(input) : new Uint8Array(input || []) - const bitLen = bytes.length * 8 - const padLen = ((bytes.length + 9 + 63) & ~63) - const buf = new Uint8Array(padLen) - buf.set(bytes, 0) - buf[bytes.length] = 0x80 - const view = new DataView(buf.buffer) - view.setUint32(padLen - 8, Math.floor(bitLen / 0x100000000), false) - view.setUint32(padLen - 4, bitLen >>> 0, false) - - let h0 = 0x6a09e667 - let h1 = 0xbb67ae85 - let h2 = 0x3c6ef372 - let h3 = 0xa54ff53a - let h4 = 0x510e527f - let h5 = 0x9b05688c - let h6 = 0x1f83d9ab - let h7 = 0x5be0cd19 - - const w = new Uint32Array(64) - for (let offset = 0; offset < padLen; offset += 64) { - for (let i = 0; i < 16; i++) { - w[i] = view.getUint32(offset + i * 4, false) - } - for (let i = 16; i < 64; i++) { - const s0 = rotr32(w[i - 15], 7) ^ rotr32(w[i - 15], 18) ^ (w[i - 15] >>> 3) - const s1 = rotr32(w[i - 2], 17) ^ rotr32(w[i - 2], 19) ^ (w[i - 2] >>> 10) - w[i] = (w[i - 16] + s0 + w[i - 7] + s1) >>> 0 - } - - let a = h0 - let b = h1 - let c = h2 - let d = h3 - let e = h4 - let f = h5 - let g = h6 - let h = h7 - - for (let i = 0; i < 64; i++) { - const S1 = rotr32(e, 6) ^ rotr32(e, 11) ^ rotr32(e, 25) - const ch = (e & f) ^ (~e & g) - const temp1 = (h + S1 + ch + SHA256_K[i] + w[i]) >>> 0 - const S0 = rotr32(a, 2) ^ rotr32(a, 13) ^ rotr32(a, 22) - const maj = (a & b) ^ (a & c) ^ (b & c) - const temp2 = (S0 + maj) >>> 0 - - h = g - g = f - f = e - e = (d + temp1) >>> 0 - d = c - c = b - b = a - a = (temp1 + temp2) >>> 0 - } - - h0 = (h0 + a) >>> 0 - h1 = (h1 + b) >>> 0 - h2 = (h2 + c) >>> 0 - h3 = (h3 + d) >>> 0 - h4 = (h4 + e) >>> 0 - h5 = (h5 + f) >>> 0 - h6 = (h6 + g) >>> 0 - h7 = (h7 + h) >>> 0 - } - - return [h0, h1, h2, h3, h4, h5, h6, h7] - .map(v => (v >>> 0).toString(16).padStart(8, '0')) - .join('') -} - -/** - * 读取本地文件真实字节并计算标准 SHA-256:宿主 filesearch_sha256(只接受 path 字段)优先,Windows 上再试 FileComparePlugin。 - * 都拿不到时返回空字符串,由调用方提示失败;不再把文件按 UTF-8 文本读出来再算(二进制文件会算出错误的值)。 - */ -export async function computeRealFileSha256( - filePath: string, - hostOverride?: DynamicBridge -): Promise { - if (!filePath || !filePath.trim()) return '' - const target = filePath.trim() - - const shaRes = await callHostTransport('filesearch_sha256', { fullPath: target }, hostOverride) - if (shaRes.ok && shaRes.data) { - const hash = typeof shaRes.data === 'string' ? shaRes.data : String(shaRes.data?.sha256 || shaRes.data?.hash || '') - if (/^[0-9a-f]{64}$/i.test(hash)) return hash.toLowerCase() - } - - const dllRes = await invokePluginService('FileComparePlugin', 'computeFileSha256', { path: target }, hostOverride) - if (dllRes.ok && dllRes.data) { - const hash = typeof dllRes.data === 'string' ? dllRes.data : String(dllRes.data?.sha256 || dllRes.data?.hash || '') - if (/^[0-9a-f]{64}$/i.test(hash)) return hash.toLowerCase() - } - - return '' -} - -export async function readRealClipboardText(hostOverride?: DynamicBridge): Promise { - const res = await callHostTransport('clipboard_read_text', {}, hostOverride) - if (res.ok && res.data !== undefined && res.data !== null) { - if (typeof res.data === 'string') return res.data - if (typeof res.data?.text === 'string') return res.data.text - } - try { - if (typeof navigator !== 'undefined' && navigator.clipboard?.readText) { - return await navigator.clipboard.readText() - } - } catch { - // ignore - } - return '' -} - -export async function writeRealClipboardText(text: string, hostOverride?: DynamicBridge): Promise { - const payload = { text: String(text || '') } - const res = await callHostTransport('clipboard_copy_text', payload, hostOverride) - if (res.ok) return true - const fallbackRes = await callHostTransport('clipboard_write_text', payload, hostOverride) - if (fallbackRes.ok) return true - try { - if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) { - await navigator.clipboard.writeText(String(text || '')) - return true - } - } catch { - // ignore - } - return false -} - -export async function showRealToast( - title: string, - style: 'success' | 'failure' | 'info' = 'info' -): Promise { - try { - const { showToast, Toast } = await import('@ztools/declarative-ui') - await showToast({ - title, - style: - style === 'success' - ? Toast.Style.Success - : style === 'failure' - ? Toast.Style.Failure - : Toast.Style.Animated - }) - } catch { - // ignore - } -} - diff --git a/extensions/batch-video/src/tool-runtime.ts b/extensions/batch-video/src/tool-runtime.ts new file mode 100644 index 00000000..29670de2 --- /dev/null +++ b/extensions/batch-video/src/tool-runtime.ts @@ -0,0 +1,637 @@ +/** + * 宿主薄原语与基础系统能力传输层(唯一权威公共源文件,纯标准 IPC,零原生 DLL 依赖) + * + * 修改本文件后需同步复制到各使用插件的 src/tool-runtime.ts, + * 构建脚本 build-declarative.mjs 会在编译前校验副本与本文件一字不差。 + */ + +import { getHostTransport } from '@ztools/declarative-ui' + +export type ToolCapabilityStatus = 'ready' | 'needs_provisioning' | 'unsupported' + +export interface ToolCapabilityDescriptor { + readonly primitiveId: string + readonly domain: string + readonly summary: string + readonly ipcMethods: readonly string[] + readonly requiredPermissions: readonly string[] + readonly status: ToolCapabilityStatus + readonly optionalExtensions: readonly string[] +} + +export interface ToolRuntimeCapabilitiesSnapshot { + readonly contractVersion: number + readonly platform: 'windows' | 'macos' | 'other' + readonly domains: readonly string[] + readonly capabilities: readonly ToolCapabilityDescriptor[] +} + +export interface ToolRuntimeEnsureResult { + readonly primitiveId: string + readonly status: ToolCapabilityStatus + readonly provisioned: boolean +} + +export interface ToolCapabilitiesEnsureResult { + readonly ok: boolean + readonly status: ToolCapabilityStatus + readonly provisioned: boolean + readonly failedPrimitiveId?: string + readonly error?: string + readonly errorCode?: string + readonly errorDetails?: Record +} + +export interface ToolTaskCancelResult { + readonly taskId: string + readonly cancelled: boolean +} + +export interface ToolPathSlot { + readonly grantId?: string + readonly relativePath?: string + readonly path?: string +} + +export interface ToolProgressEvent { + readonly taskId: string + readonly primitiveId?: string + readonly phase: 'provisioning' | 'running' | 'finalizing' | 'completed' | 'cancelled' | 'failed' + readonly percent?: number + readonly transferredBytes?: number + readonly totalBytes?: number + readonly speedBytesPerSec?: number + readonly stage?: string + readonly errorCode?: string + readonly retryable?: boolean + readonly userAction?: string + readonly message?: string + readonly timestamp?: number +} + +export type MediaTranscodeRunResult = + | { readonly status: 'done'; readonly outputBytes: number; readonly durationMs: number } + | { readonly status: 'cancelled' } + | { + readonly status: 'failed' + readonly error?: string + readonly errorCode?: string + readonly errorDetails?: Record + } + +export interface HostTransportResult { + ok: boolean + data?: T + error?: string + errorCode?: string + errorDetails?: Record +} + +export interface HostCallOptions { + timeoutMs?: number +} + +type TransportMethodFn = (req: { messageId: string; params: Record; timeoutMs?: number }) => Promise + +interface WindowHostBridge { + __ztoolsElectron?: { + transport?: { + methods?: Record + } + } + ztools?: { + transport?: { + methods?: Record + call?: (method: string, params: Record, options?: { timeoutMs?: number }) => Promise + } + events?: { + subscribe?: (event: string) => Promise | void + on?: (event: string, cb: (payload: unknown) => void) => (() => void) | void + off?: (event: string, cb: (payload: unknown) => void) => void + } + } +} + +interface HostOverrideLike { + transport?: { + call?: (method: string, params: Record, options?: { timeoutMs?: number }) => Promise + } + [method: string]: unknown +} + +let reqSeq = 1 + +export function nextMessageId(prefix = 'tool'): string { + reqSeq = (reqSeq + 1) % 1_000_000 + return `${prefix}_${Date.now()}_${reqSeq}` +} + +export function asRecord(value: unknown): Record | null { + return value && typeof value === 'object' && !Array.isArray(value) + ? (value as Record) + : null +} + +function extractErrorMeta(errObj: unknown): { + errorCode?: string + errorDetails?: Record +} { + const rec = asRecord(errObj) + if (!rec) return {} + const errorCode = + typeof rec.errorCode === 'string' && rec.errorCode.trim() + ? rec.errorCode.trim() + : typeof rec.code === 'string' && rec.code.trim() + ? rec.code.trim() + : undefined + const rawDetails = asRecord(rec.errorDetails) ?? asRecord(rec.details) ?? undefined + return { + ...(errorCode ? { errorCode } : {}), + ...(rawDetails ? { errorDetails: rawDetails } : {}) + } +} + +function toTransportError(err: unknown): HostTransportResult { + return { + ok: false, + error: err instanceof Error ? err.message : String(err), + ...extractErrorMeta(err) + } +} + +function buildFailureResult(rec: Record, fallbackMsg: string): HostTransportResult { + const errObj = asRecord(rec.error) + const errMsg = errObj + ? String(errObj.message || errObj.code || JSON.stringify(errObj)) + : String(rec.error || rec.message || fallbackMsg) + return { ok: false, error: errMsg, ...extractErrorMeta(rec), ...extractErrorMeta(errObj) } +} + +function unwrapTransportResponse(raw: unknown): HostTransportResult { + if (raw === null || raw === undefined) { + return { ok: false, error: 'EMPTY_IPC_RESPONSE', errorCode: 'EMPTY_IPC_RESPONSE' } + } + if (typeof raw !== 'object') { + return { ok: true, data: raw as T } + } + const outer = asRecord(raw) + if (!outer) { + return { ok: true, data: raw as T } + } + if (outer.success === false || outer.ok === false) { + return buildFailureResult(outer, 'IPC_CALL_FAILED') + } + + const firstLayer = 'data' in outer && outer.data !== undefined ? outer.data : outer + const inner = asRecord(firstLayer) + if (inner) { + if (inner.success === false || inner.ok === false) { + return buildFailureResult(inner, 'IPC_INNER_FAILED') + } + if ('data' in inner && inner.data !== undefined) { + return { ok: true, data: inner.data as T } + } + } + + return { ok: true, data: firstLayer as T } +} + +/** 判断当前是否处于真实的 ZTools Electron 渲染进程宿主环境 */ +export function isRealElectronHost(hostOverride?: unknown): boolean { + if (hostOverride) return true + if (typeof window === 'undefined') return false + const w = window as unknown as WindowHostBridge + return Boolean( + w.__ztoolsElectron?.transport?.methods || + w.ztools?.transport?.call || + w.ztools?.transport?.methods + ) +} + +/** 统一调用宿主 IPC 传输层(优先测试桩,其次 declarative-ui 宿主通道与 preload 通道) */ +export async function callHostTransport( + method: string, + params: Record = {}, + hostOverride?: unknown, + options?: HostCallOptions +): Promise> { + const override = asRecord(hostOverride) as HostOverrideLike | null + if (override) { + const directFn = override[method] + if (typeof directFn === 'function') { + try { + return unwrapTransportResponse(await (directFn as (p: Record) => Promise)(params)) + } catch (err) { + return toTransportError(err) + } + } + if (typeof override.transport?.call === 'function') { + try { + return unwrapTransportResponse(await override.transport.call(method, params, options)) + } catch (err) { + return toTransportError(err) + } + } + return { ok: false, error: `METHOD_NOT_AVAILABLE: ${method}`, errorCode: 'METHOD_NOT_AVAILABLE' } + } + + // 优先走 declarative-ui 运行时注入的带归属令牌通道 + if (typeof getHostTransport === 'function') { + const transport = getHostTransport() + if (transport) { + try { + const callOpts = typeof options?.timeoutMs === 'number' ? { timeoutMs: options.timeoutMs } : undefined + return unwrapTransportResponse(await transport.call(method, params, callOpts)) + } catch (err) { + return toTransportError(err) + } + } + } + + if (typeof window === 'undefined') { + return { ok: false, error: 'NO_WINDOW_ENV', errorCode: 'NO_WINDOW_ENV' } + } + + const w = window as unknown as WindowHostBridge + const methods = w.__ztoolsElectron?.transport?.methods || w.ztools?.transport?.methods + const fn = methods?.[method] + if (typeof fn === 'function') { + try { + const messageId = nextMessageId(method.replace(/[^A-Za-z0-9_]/g, '_').slice(0, 24)) + const payload = { + messageId, + params, + ...(typeof options?.timeoutMs === 'number' ? { timeoutMs: options.timeoutMs } : {}) + } + return unwrapTransportResponse(await fn(payload)) + } catch (err) { + return toTransportError(err) + } + } + + if (typeof w.ztools?.transport?.call === 'function') { + try { + return unwrapTransportResponse(await w.ztools.transport.call(method, params, options)) + } catch (err) { + return toTransportError(err) + } + } + + return { ok: false, error: `METHOD_NOT_AVAILABLE: ${method}`, errorCode: 'METHOD_NOT_AVAILABLE' } +} + +/** 探测宿主薄原语能力快照(tool_runtime_capabilities) */ +export async function queryRuntimeCapabilities( + hostOverride?: unknown +): Promise> { + const res = await callHostTransport('tool_runtime_capabilities', {}, hostOverride) + if (!res.ok) return res as HostTransportResult + const rec = asRecord(res.data) + if (!rec || !Array.isArray(rec.capabilities)) { + return { + ok: false, + error: 'INVALID_CAPABILITIES_SNAPSHOT', + errorCode: 'INVALID_CAPABILITIES_SNAPSHOT' + } + } + const capabilities: ToolCapabilityDescriptor[] = [] + for (const rawCap of rec.capabilities) { + const cap = asRecord(rawCap) + if (!cap || typeof cap.primitiveId !== 'string') continue + const rawStatus = cap.status + const status: ToolCapabilityStatus = + rawStatus === 'ready' || rawStatus === 'needs_provisioning' || rawStatus === 'unsupported' + ? rawStatus + : 'unsupported' + const optionalExtensions = Array.isArray(cap.optionalExtensions) + ? cap.optionalExtensions.filter((e): e is string => typeof e === 'string' && e.trim().length > 0) + : [] + capabilities.push({ + primitiveId: cap.primitiveId, + domain: typeof cap.domain === 'string' ? cap.domain : '', + summary: typeof cap.summary === 'string' ? cap.summary : '', + ipcMethods: Array.isArray(cap.ipcMethods) ? cap.ipcMethods.filter((m): m is string => typeof m === 'string') : [], + requiredPermissions: Array.isArray(cap.requiredPermissions) + ? cap.requiredPermissions.filter((p): p is string => typeof p === 'string') + : [], + status, + optionalExtensions + }) + } + const platform = + rec.platform === 'windows' || rec.platform === 'macos' || rec.platform === 'other' + ? rec.platform + : 'other' + return { + ok: true, + data: { + contractVersion: typeof rec.contractVersion === 'number' ? rec.contractVersion : 1, + platform, + domains: Array.isArray(rec.domains) ? rec.domains.filter((d): d is string => typeof d === 'string') : [], + capabilities + } + } +} + +export function findCapability( + snapshot: ToolRuntimeCapabilitiesSnapshot | null | undefined, + primitiveId: string +): ToolCapabilityDescriptor | null { + if (!snapshot) return null + return snapshot.capabilities.find((c) => c.primitiveId === primitiveId) ?? null +} + +export function hasCapabilityExtension( + snapshot: ToolRuntimeCapabilitiesSnapshot | null | undefined, + primitiveId: string, + extensionName: string +): boolean { + const cap = findCapability(snapshot, primitiveId) + return Boolean(cap && cap.optionalExtensions.includes(extensionName)) +} + +/** 按需拉取并准备指定薄原语运行组件(tool_runtime_ensure) */ +export async function ensureRuntimeCapability( + primitiveId: string, + hostOverride?: unknown +): Promise> { + return callHostTransport('tool_runtime_ensure', { primitiveId }, hostOverride) +} + +/** 顺序按需准备多个薄原语运行组件,任一项未就绪即中止并聚合 provisioned 标记 */ +export async function ensureRuntimeCapabilities( + primitiveIds: readonly string[], + hostOverride?: unknown +): Promise { + let provisionedAny = false + for (const primitiveId of primitiveIds) { + const res = await ensureRuntimeCapability(primitiveId, hostOverride) + if (!res.ok || !res.data || res.data.status !== 'ready') { + return { + ok: false, + status: res.data?.status ?? 'unsupported', + provisioned: provisionedAny, + failedPrimitiveId: primitiveId, + error: res.error, + errorCode: res.errorCode, + errorDetails: res.errorDetails + } + } + if (res.data.provisioned) provisionedAny = true + } + return { ok: true, status: 'ready', provisioned: provisionedAny } +} + +/** 取消正在执行的宿主薄原语任务(tool_task_cancel) */ +export async function cancelRuntimeTask( + taskId: string, + hostOverride?: unknown +): Promise> { + return callHostTransport('tool_task_cancel', { taskId }, hostOverride) +} + +/** 判断错误码是否表示用户主动取消任务 */ +export function isTaskCancelledCode(errorCode?: string): boolean { + const code = (errorCode || '').trim().toUpperCase() + return code === 'TOOL_TASK_CANCELLED' || code === 'CANCELLED' || code === 'OPERATION_CANCELLED' +} + +/** 执行单个媒体转码任务(tool_media_transcode_run),统一处理取消与产物字节数校验 */ +export async function runMediaTranscodeTask( + payload: Record, + hostOverride?: unknown +): Promise { + const res = await callHostTransport('tool_media_transcode_run', payload, hostOverride) + if (!res.ok) { + if (isTaskCancelledCode(res.errorCode)) { + return { status: 'cancelled' } + } + return { + status: 'failed', + error: res.error, + errorCode: res.errorCode, + errorDetails: res.errorDetails + } + } + const rec = asRecord(res.data) + const outputBytes = Number(rec?.outputBytes) + const durationMs = Number(rec?.durationMs) + if (!Number.isFinite(outputBytes) || outputBytes <= 0) { + return { status: 'failed', error: 'EMPTY_OUTPUT', errorCode: 'EMPTY_OUTPUT' } + } + return { + status: 'done', + outputBytes, + durationMs: Number.isFinite(durationMs) && durationMs >= 0 ? durationMs : 0 + } +} + +/** 订阅宿主推送的 tool_runtime_progress 任务进度事件 */ +export function subscribeRuntimeProgress( + handler: (event: ToolProgressEvent) => void +): () => void { + if (typeof window === 'undefined') return () => undefined + const w = window as unknown as WindowHostBridge + const eventsApi = w.ztools?.events + if (!eventsApi || typeof eventsApi.on !== 'function') return () => undefined + + try { + void eventsApi.subscribe?.('tool_runtime_progress') + } catch (err) { + // 某些测试桩或旧渲染层可能未提供 subscribe,继续注册 on 监听 + void err + } + + const listener = (raw: unknown) => { + const outer = asRecord(raw) + if (!outer) return + const inner = asRecord(outer.payload) ?? outer + if (typeof inner.taskId !== 'string' || typeof inner.phase !== 'string') return + handler(inner as unknown as ToolProgressEvent) + } + + const off = eventsApi.on('tool_runtime_progress', listener) + return () => { + if (typeof off === 'function') { + off() + } else if (typeof eventsApi.off === 'function') { + eventsApi.off('tool_runtime_progress', listener) + } + } +} + +/** 订阅旧版宿主 plugin_files_dropped 拖拽回退事件并返回卸载函数 */ +export function subscribeLegacyFileDrop(onDrop: (envelope: unknown) => void): () => void { + if (typeof window === 'undefined') return () => undefined + const w = window as unknown as WindowHostBridge + const eventsApi = w.ztools?.events + if (!eventsApi || typeof eventsApi.on !== 'function') return () => undefined + + const off = eventsApi.on('plugin_files_dropped', onDrop) + return () => { + if (typeof off === 'function') { + off() + } else if (typeof eventsApi.off === 'function') { + eventsApi.off('plugin_files_dropped', onDrop) + } + } +} + +/** 字节数格式化 */ +export function formatBytes(bytes: number): string { + if (!Number.isFinite(bytes) || bytes < 0) return '0 B' + if (bytes < 1024) return `${Math.round(bytes)} B` + const units = ['KB', 'MB', 'GB', 'TB'] + let value = bytes / 1024 + let idx = 0 + while (value >= 1024 && idx < units.length - 1) { + value /= 1024 + idx += 1 + } + return `${value >= 100 ? value.toFixed(0) : value >= 10 ? value.toFixed(1) : value.toFixed(2)} ${units[idx]}` +} + +/** 字节数格式化别名(兼容 archive-manager 等插件既有导出名) */ +export function formatByteCount(bytes: number): string { + return formatBytes(bytes) +} + +/** 获取系统标准目录路径(支持 Windows 与 macOS) */ +export async function getRealSystemPath( + name: 'home' | 'desktop' | 'documents' | 'downloads' | 'music' | 'pictures' | 'videos' | 'temp', + hostOverride?: unknown +): Promise { + const res = await callHostTransport('system_get_path', { name }, hostOverride) + if (res.ok && res.data) { + if (typeof res.data === 'string' && res.data.trim()) return res.data.trim() + const rec = asRecord(res.data) + if (rec && typeof rec.path === 'string' && rec.path.trim()) return rec.path.trim() + } + return '' +} + +/** 读取剪贴板文本 */ +export async function readRealClipboardText(hostOverride?: unknown): Promise { + const res = await callHostTransport('clipboard_read_text', {}, hostOverride) + if (res.ok && res.data !== undefined && res.data !== null) { + if (typeof res.data === 'string') return res.data + const rec = asRecord(res.data) + if (rec && typeof rec.text === 'string') return rec.text + } + return '' +} + +/** 写入剪贴板文本 */ +export async function writeRealClipboardText(text: string, hostOverride?: unknown): Promise { + const res = await callHostTransport('clipboard_copy_text', { text: String(text || '') }, hostOverride) + return res.ok +} + +/** 在系统文件管理器中显示文件 */ +export async function showRealItemInFolder(fullPath: string, hostOverride?: unknown): Promise { + if (!fullPath) return false + const res = await callHostTransport('shell_show_item_in_folder', { fullPath }, hostOverride) + return res.ok +} + +/** 用系统默认应用打开文件或文件夹 */ +export async function openRealPath(fullPath: string, hostOverride?: unknown): Promise { + if (!fullPath) return false + const res = await callHostTransport('shell_open_path', { fullPath }, hostOverride) + return res.ok +} + +/** 将文件或目录移入系统回收站 */ +export async function trashRealItem(fullPath: string, hostOverride?: unknown): Promise<{ ok: boolean; error?: string }> { + if (!fullPath) return { ok: false, error: 'EMPTY_PATH' } + const res = await callHostTransport('shell_trash_item', { fullPath }, hostOverride) + return res.ok ? { ok: true } : { ok: false, error: res.error } +} + +/** 通过 window_show_open_dialog 选择输出目录(兼容 Windows 与 macOS) */ +export async function pickOutputDirectoryDialog( + options: { title: string; defaultPath?: string }, + hostOverride?: unknown +): Promise<{ canceled: boolean; directoryPath?: string; error?: string; errorCode?: string }> { + const params: Record = { + title: options.title, + properties: ['openDirectory', 'createDirectory'] + } + if (options.defaultPath) params.defaultPath = options.defaultPath + const res = await callHostTransport('window_show_open_dialog', params, hostOverride) + if (!res.ok) { + return { canceled: false, error: res.error || 'OPEN_DIALOG_FAILED', errorCode: res.errorCode } + } + const rec = asRecord(res.data) + if (!rec) return { canceled: false, error: 'INVALID_DIALOG_RESULT' } + if (rec.canceled === true) return { canceled: true } + const firstPath = + (Array.isArray(rec.filePaths) && typeof rec.filePaths[0] === 'string' && rec.filePaths[0].trim()) || + (typeof rec.filePath === 'string' && rec.filePath.trim()) || + (typeof rec.folderPath === 'string' && rec.folderPath.trim()) || + '' + if (!firstPath) return { canceled: false, error: 'NO_DIRECTORY_SELECTED' } + return { canceled: false, directoryPath: firstPath } +} + +/** 通用文件/目录选择对话框(支持自定义 properties 与 filters) */ +export async function openDialogSelectPaths( + options: { + title: string + properties: Array<'openFile' | 'openDirectory' | 'multiSelections' | 'createDirectory'> + filters?: Array<{ name: string; extensions: string[] }> + }, + hostOverride?: unknown +): Promise<{ canceled: boolean; paths: string[]; error?: string }> { + const params: Record = { + title: options.title, + properties: options.properties, + ...(options.filters ? { filters: options.filters } : {}) + } + const res = await callHostTransport('window_show_open_dialog', params, hostOverride) + if (!res.ok) return { canceled: false, paths: [], error: res.error || 'OPEN_DIALOG_FAILED' } + const rec = asRecord(res.data) + if (!rec) return { canceled: false, paths: [], error: 'INVALID_DIALOG_RESPONSE' } + if (rec.canceled === true) return { canceled: true, paths: [] } + const paths = Array.isArray(rec.filePaths) + ? rec.filePaths.filter((p): p is string => typeof p === 'string' && p.trim().length > 0).map((p) => p.trim()) + : typeof rec.filePath === 'string' && rec.filePath.trim() + ? [rec.filePath.trim()] + : [] + return { canceled: false, paths } +} + +/** 选择待归档的源文件或目录列表(多选) */ +export async function pickAnySourcesDialog( + options: { title: string; directories?: boolean }, + hostOverride?: unknown +): Promise<{ canceled: boolean; paths: string[]; error?: string }> { + return openDialogSelectPaths( + { + title: options.title, + properties: options.directories ? ['openDirectory', 'multiSelections'] : ['openFile', 'multiSelections'] + }, + hostOverride + ) +} + +/** 保存归档文件对话框(zip / 7z / tar) */ +export async function pickSaveArchiveDialog( + options: { title: string; defaultPath?: string; format: 'zip' | '7z' | 'tar' }, + hostOverride?: unknown +): Promise<{ canceled: boolean; filePath?: string; error?: string }> { + const ext = options.format === '7z' ? '7z' : options.format === 'tar' ? 'tar' : 'zip' + const params: Record = { + title: options.title, + filters: [{ name: `${ext.toUpperCase()} Archive`, extensions: [ext] }] + } + if (options.defaultPath) params.defaultPath = options.defaultPath + const res = await callHostTransport('window_show_save_dialog', params, hostOverride) + if (!res.ok) return { canceled: false, error: res.error || 'SAVE_DIALOG_FAILED' } + const rec = asRecord(res.data) + if (!rec) return { canceled: false, error: 'INVALID_SAVE_DIALOG' } + if (rec.canceled === true) return { canceled: true } + const filePath = typeof rec.filePath === 'string' ? rec.filePath.trim() : '' + if (!filePath) return { canceled: true } + return { canceled: false, filePath } +} diff --git a/extensions/batch-video/tests/batch-video.host.test.mjs b/extensions/batch-video/tests/batch-video.host.test.mjs index b1bd9243..e745720d 100644 --- a/extensions/batch-video/tests/batch-video.host.test.mjs +++ b/extensions/batch-video/tests/batch-video.host.test.mjs @@ -1,83 +1,190 @@ -// 本插件现行代码的宿主集成测试 +// 批量视频处理薄原语逻辑测试:覆盖探测、全参数转码、长任务取消、按需拉取引擎及旧宿主特性降级门禁 import test from 'node:test' import assert from 'node:assert/strict' +import fs from 'node:fs' +import path from 'node:path' +import { fileURLToPath } from 'node:url' import { setRuntimeLocale } from '@ztools/declarative-ui' +import * as batchVideo from '../dist/logic.js' setRuntimeLocale('zh-CN') -const batchVideo = await import('../dist/index.js') -async function withRealElectronWindow(handlers, fn) { - const prevWindow = globalThis.window - const calls = [] - const transportMethods = {} +const __dirname = path.dirname(fileURLToPath(import.meta.url)) - for (const [channel, impl] of Object.entries(handlers)) { - transportMethods[channel] = async envelope => { - const actualParams = - envelope && typeof envelope === 'object' && 'params' in envelope && 'messageId' in envelope - ? envelope.params - : envelope - calls.push({ channel, payload: actualParams }) - return impl(actualParams) +function createHostStub(handlers = {}) { + const calls = [] + const dispatch = async (method, params) => { + calls.push({ method, params }) + if (typeof handlers[method] === 'function') { + return await handlers[method](params) } - } - - globalThis.window = { - __ztoolsElectron: { - transport: { - methods: transportMethods - } + if (method in handlers) { + return handlers[method] } + throw new Error(`CHANNEL_NOT_IMPLEMENTED: ${method}`) } - - try { - return await fn(calls) - } finally { - if (prevWindow === undefined) { - delete globalThis.window - } else { - globalThis.window = prevWindow - } + const stub = { calls, transport: { call: dispatch } } + for (const key of Object.keys(handlers)) { + stub[key] = (params) => dispatch(key, params) } + return stub } -test('batch-video 导入规则、selectVideoFiles 过滤串修复与 dllplugin_call 宿主集成', async () => { - await withRealElectronWindow( +const callsOf = (host, method) => host.calls.filter((c) => c.method === method) + +test('batch-video: plugin.json 移除 draft、声明 media.probe/media.transcode 且零 DLL/超时硬限制', () => { + const manifest = JSON.parse(fs.readFileSync(path.join(__dirname, '..', 'plugin.json'), 'utf8')) + assert.deepEqual(manifest.requiredCapabilities, ['media.probe', 'media.transcode']) + assert.ok(manifest.permissions.includes('media.read')) + assert.ok(manifest.permissions.includes('media.process')) + assert.equal(manifest.minAppVersion, '1.3.0.0') + assert.equal(manifest.draft, undefined) + assert.equal(manifest.draftReason, undefined) + assert.deepEqual(manifest.nativeComponents, []) + assert.deepEqual(manifest.targets.map((item) => item.id), ['windows-electron-any']) + assert.equal('TRANSCODE_IPC_TIMEOUT_MS' in batchVideo, false) +}) + +test('batch-video: 探测能力并支持 tool_runtime_ensure 按需拉取视频引擎', async () => { + const host = createHostStub({ + tool_runtime_capabilities: () => ({ + contractVersion: 1, + platform: 'windows', + domains: ['media'], + capabilities: [ + { primitiveId: 'media.probe', domain: 'media', summary: '', ipcMethods: [], requiredPermissions: ['media.read'], status: 'needs_provisioning', optionalExtensions: [] }, + { primitiveId: 'media.transcode', domain: 'media', summary: '', ipcMethods: [], requiredPermissions: ['media.process'], status: 'needs_provisioning', optionalExtensions: ['geometry', 'speed'] } + ] + }), + tool_runtime_ensure: ({ primitiveId }) => ({ primitiveId, status: 'ready', provisioned: true }) + }) + + const cap = await batchVideo.probeVideoCapabilities(host) + assert.equal(cap.overallStatus, 'needs_provisioning') + assert.equal(cap.extensions.geometry, true) + assert.equal(cap.extensions.speed, true) + + const ensured = await batchVideo.ensureVideoEngine(host) + assert.equal(ensured.ok, true) + assert.deepEqual( + callsOf(host, 'tool_runtime_ensure').map((c) => c.params.primitiveId), + ['media.probe', 'media.transcode'] + ) +}) + +test('batch-video: 视频探测、全参数转码(含编码器/缩放/裁切/水印/geometry/speed)与取消', async () => { + const host = createHostStub({ + filesystem_file_exists: () => false, + tool_media_probe: () => ({ + items: [ + { + displayName: 'clip.mov', + container: 'mov', + durationSec: 64.2, + sizeBytes: 50_000_000, + streams: [ + { index: 0, kind: 'video', codec: 'h264', width: 1920, height: 1080, frameRate: 30 }, + { index: 1, kind: 'audio', codec: 'aac', sampleRateHz: 48000, channels: 2 } + ] + } + ] + }), + tool_media_transcode_run: (params) => ({ + taskId: params.taskId, + outputBytes: 18_000_000, + durationMs: 4200, + container: params.container + }), + tool_task_cancel: ({ taskId }) => ({ taskId, cancelled: true }) + }) + + const probed = await batchVideo.probeVideoFiles(['D:\\Videos\\clip.mov'], host) + assert.equal(probed.ok, true) + assert.equal(probed.items[0].width, 1920) + assert.equal(probed.items[0].height, 1080) + + const outcome = await batchVideo.processVideoFile( + { path: 'D:\\Videos\\clip.mov' }, { - window_show_open_dialog: () => ({ - canceled: false, - filePaths: ['D:\\Media\\a.mp4', 'D:\\Media\\a_ztools.mp4', 'D:\\Media\\anim.gif'] - }), - filesystem_get_file_size: () => ({ success: true, size: 123456 }), - dllplugin_call: ({ plugin, func, params }) => { - return { executed: true, plugin, func, inputPath: params.inputPath } - } + taskId: 'convert-video', + format: 'mp4', + videoCodec: 'hevc', + videoBitrateKbps: 6000, + frameRate: 30, + scaleWidth: 1280, + stripAudio: true, + trimStartSec: 0, + trimEndSec: 30, + watermarkPath: 'D:\\Assets\\logo.png', + watermarkPosition: 'top-right', + rotate: 90, + flip: 'horizontal', + crop: { x: 10, y: 20, width: 800, height: 600 }, + speedFactor: 1.5 }, - async calls => { - const selected = await batchVideo.selectVideoFiles() - const dialogCall = calls.find(c => c.channel === 'window_show_open_dialog') - assert.equal(typeof dialogCall.payload.filters, 'string', 'filters 必须是字符串,不能再是对象数组') - assert.equal(dialogCall.payload.filters, '视频文件|mp4;mkv;mov;avi;flv;webm;wmv;ts;m4v') - assert.deepEqual(selected.files.map(f => f.name), ['a.mp4']) - assert.equal(selected.ignored, 2, '应排除 _ztools 派生输出与 .gif 输入') - - const vRes = await batchVideo.invokeNativeCapability('BatchCompressVideo', { crf: 23, inputPath: 'D:\\Media\\a.mp4' }) - assert.equal(vRes.ok, true) - assert.equal(vRes.fromFallback, false) - assert.equal(vRes.data.plugin, 'BatchVideoPlugin') - } + { geometry: true, speed: true }, + new Set(), + '20261127120000', + { taskId: 'vid_job_1', hostOverride: host } ) + assert.equal(outcome.status, 'done') + assert.equal(outcome.outputBytes, 18_000_000) - await withRealElectronWindow( + const sent = callsOf(host, 'tool_media_transcode_run')[0].params + assert.equal(sent.videoCodec, 'hevc') + assert.equal(sent.videoBitrateKbps, 6000) + assert.equal(sent.frameRate, 30) + assert.equal(sent.stripAudio, true) + assert.deepEqual(sent.scale, { width: 1280, keepAspectRatio: true }) + assert.deepEqual(sent.trim, { startSec: 0, endSec: 30 }) + assert.deepEqual(sent.watermark, { + imageSlot: { path: 'D:\\Assets\\logo.png' }, + position: 'top-right', + opacity: 0.85, + marginPx: 16 + }) + assert.equal(sent.rotate, 90) + assert.equal(sent.flip, 'horizontal') + assert.deepEqual(sent.crop, { x: 10, y: 20, width: 800, height: 600 }) + assert.equal(sent.speedFactor, 1.5) + + const cancelRes = await batchVideo.cancelVideoTask('vid_job_1', host) + assert.equal(cancelRes.ok, true) + assert.equal(cancelRes.cancelled, true) +}) + +test('batch-video 决策 7 降级: 旧宿主未上报 geometry 与 speed 时绝不发送 rotate/flip/crop/speedFactor', async () => { + const host = createHostStub({ + filesystem_file_exists: () => false, + tool_media_transcode_run: (params) => ({ + taskId: params.taskId, + outputBytes: 9_000_000, + durationMs: 1500, + container: params.container + }) + }) + + const outcome = await batchVideo.processVideoFile( + { path: 'D:\\Videos\\legacy.mp4' }, { - dllplugin_call: () => { - throw new Error('FFMPEG_BINARY_MISSING') - } + taskId: 'convert-video', + format: 'mp4', + videoCodec: 'h264', + rotate: 180, + flip: 'vertical', + crop: { x: 0, y: 0, width: 640, height: 360 }, + speedFactor: 2 }, - async () => { - const vFail = await batchVideo.invokeNativeCapability('BatchCompressVideo', { crf: 23 }) - assert.equal(vFail.ok, false) - assert.equal(vFail.data?.simulated, undefined) - } + { geometry: false, speed: false }, + new Set(), + '20261127120000', + { taskId: 'vid_legacy_1', hostOverride: host } ) + assert.equal(outcome.status, 'done') + const sent = callsOf(host, 'tool_media_transcode_run')[0].params + assert.equal(Object.hasOwn(sent, 'rotate'), false) + assert.equal(Object.hasOwn(sent, 'flip'), false) + assert.equal(Object.hasOwn(sent, 'crop'), false) + assert.equal(Object.hasOwn(sent, 'speedFactor'), false) + assert.equal(sent.videoCodec, 'h264') }) diff --git a/extensions/batch-video/tests/batch-video.output.test.mjs b/extensions/batch-video/tests/batch-video.output.test.mjs index 5c730114..3e64646f 100644 --- a/extensions/batch-video/tests/batch-video.output.test.mjs +++ b/extensions/batch-video/tests/batch-video.output.test.mjs @@ -1,577 +1,80 @@ -// 输出路径防覆盖、宿主结果解析、失败如实上报与界面文案的测试(宿主行为按客户端内置媒体处理接口模拟) +// 批量视频输出防覆盖与界面特性降级测试 import test from 'node:test' import assert from 'node:assert/strict' -import fs from 'node:fs' -import path from 'node:path' -import { fileURLToPath } from 'node:url' import { setRuntimeLocale } from '@ztools/declarative-ui' +import { createHost, mount, tick } from '../../shared/test-harness.mjs' +import * as batchVideo from '../dist/logic.js' +import BatchVideoCommand from '../dist/index.js' setRuntimeLocale('zh-CN') -const batchVideo = await import('../dist/index.js') -const __dirname = path.dirname(fileURLToPath(import.meta.url)) -const BATCH_TAG = '20261028120000' -const key = p => String(p).replace(/\//g, '\\').toLowerCase() - -/** - * 模拟客户端: - * - filesystem_file_exists:answer 模式按磁盘答复;deny 模式按输出位置没有读取授权返回失败(客户端实际情况) - * - dllplugin_call Probe:文件存在时返回文件信息,不存在时返回「宿主内部错误」 - * - 其余 dllplugin_call:与客户端一样以 -y 写 outputPath,失败时删除 outputPath 上的文件(记录被删掉的已有文件) - * 返回值套上客户端 IPC 信封({ success, data }),走插件真实的解包逻辑 - */ -async function withHost(options, fn) { - const prevWindow = globalThis.window - const disk = new Set((options.existing || []).map(key)) - const envelopes = [] - const deletedExisting = [] - const transcodeCalls = [] - const hostResult = record => ({ success: true, data: { ...record, data: { ...record } } }) - const hostError = message => ({ success: false, error: { code: 'INTERNAL_ERROR', message } }) - - const methods = { - filesystem_file_exists: async envelope => { - envelopes.push({ method: 'filesystem_file_exists', envelope }) - if (options.fileExists === 'answer') { - return { success: true, data: { success: true, exists: disk.has(key(envelope.params.path)) } } - } - return { success: false, error: { code: 'PERMISSION_DENIED', message: '路径未由当前窗口授权' } } - }, - dllplugin_call: async envelope => { - envelopes.push({ method: 'dllplugin_call', envelope }) - const { func, params } = envelope.params - if (func === 'Probe') { - const target = params.files[0] - if (!disk.has(key(target))) return hostError('宿主内部错误') - return hostResult({ ok: true, success: true, items: [{ path: target, sizeBytes: 1 }] }) - } - transcodeCalls.push({ func, params, timeoutMs: envelope.timeoutMs }) - const outputPath = params.outputPath - const behavior = options.transcode ? options.transcode({ func, params }) : { ok: true, bytes: 4096 } - if (behavior.raw) return behavior.raw - if (behavior.ok) { - disk.add(key(outputPath)) - const result = { sourcePath: params.files[0], outputPath, engine: 'ffmpeg', sizeBytes: behavior.bytes, outputBytes: behavior.bytes } - return hostResult({ ok: true, success: true, processedCount: 1, outputPath, sizeBytes: behavior.bytes, outputBytes: behavior.bytes, results: [result], errors: [] }) - } - if (disk.has(key(outputPath))) { - disk.delete(key(outputPath)) - deletedExisting.push(outputPath) - } - const errors = [{ file: params.files[0], error: behavior.error }] - return hostResult({ ok: false, success: false, processedCount: 0, outputPath: '', results: [], errors, error: behavior.error }) - }, - shell_show_item_in_folder: async envelope => { - envelopes.push({ method: 'shell_show_item_in_folder', envelope }) - const allowed = (options.revealAllowed || []).map(key) - return allowed.includes(key(envelope.params.fullPath)) - ? { success: true, data: { success: true } } - : { success: false, error: { code: 'PERMISSION_DENIED', message: '路径未由当前窗口授权' } } - }, - shell_open_path: async envelope => { - envelopes.push({ method: 'shell_open_path', envelope }) - return { success: true, data: { success: true } } - }, - ...(options.extraMethods || {}) - } - - globalThis.window = { __ztoolsElectron: { transport: { methods } } } - try { - return await fn({ disk, envelopes, deletedExisting, transcodeCalls }) - } finally { - if (prevWindow === undefined) delete globalThis.window - else globalThis.window = prevWindow - } -} - -const convertMp4 = { taskId: 'convert-video', format: 'mp4' } - -test('输出路径:宿主能答复时依次换名,避开已存在的 <名>_ztools 与 <名>_ztools_2', async () => { - await withHost( - { fileExists: 'answer', existing: ['D:\\v\\clip_ztools.mp4', 'D:\\v\\clip_ztools_2.mp4'] }, - async () => { - const out = await batchVideo.chooseOutputPath('D:\\v\\clip.mov', 'mp4', new Set(), BATCH_TAG) - assert.equal(out, 'D:\\v\\clip_ztools_3.mp4') - } - ) -}) - -test('输出路径:宿主无法确认时改用批次时间标记文件名,且仍避开读得到的已有文件', async () => { - await withHost( - { - fileExists: 'deny', - existing: ['D:\\v\\clip_ztools.mp4', `D:\\v\\clip_ztools_${BATCH_TAG}.mp4`] - }, - async () => { - const out = await batchVideo.chooseOutputPath('D:\\v\\clip.mov', 'mp4', new Set(), BATCH_TAG) - assert.equal(out, `D:\\v\\clip_ztools_${BATCH_TAG}_2.mp4`) - } - ) -}) - -test('输出路径:所有候选名都已存在时拒绝处理该文件,不退回可能覆盖的名称', async () => { - const existing = [`D:\\v\\clip_ztools_${BATCH_TAG}.mp4`] - for (let n = 2; n <= 50; n++) existing.push(`D:\\v\\clip_ztools_${BATCH_TAG}_${n}.mp4`) - await withHost({ fileExists: 'deny', existing }, async ({ transcodeCalls }) => { - await assert.rejects( - batchVideo.chooseOutputPath('D:\\v\\clip.mov', 'mp4', new Set(), BATCH_TAG), - /无法为输出文件生成不重复的文件名/ - ) - const outcome = await batchVideo.processVideoFile({ path: 'D:\\v\\clip.mov' }, convertMp4, new Set(), BATCH_TAG) - assert.equal(outcome.status, 'failed') - assert.match(outcome.error, /不重复的文件名/) - assert.equal(transcodeCalls.length, 0, '找不到安全的输出路径时不能调用宿主') +function setupVideoHost(host, { status = 'ready', extensions = [] } = {}) { + host.ipc.tool_runtime_capabilities = async () => ({ + contractVersion: 1, + platform: 'windows', + domains: ['media'], + capabilities: [ + { primitiveId: 'media.probe', domain: 'media', summary: '', ipcMethods: ['tool_media_probe'], requiredPermissions: ['media.read'], status, optionalExtensions: [] }, + { primitiveId: 'media.transcode', domain: 'media', summary: '', ipcMethods: ['tool_media_transcode_run'], requiredPermissions: ['media.process'], status, optionalExtensions: extensions } + ] }) -}) - -test('同一批次中同名不同扩展名的源文件不会写到同一个输出文件', async () => { - await withHost({ fileExists: 'answer' }, async ({ transcodeCalls }) => { - const outcomes = await batchVideo.processVideoBatch( - [ - { id: 'a', path: 'D:\\v\\talk.mov' }, - { id: 'b', path: 'D:\\v\\talk.mkv' } - ], - convertMp4, - { batchTag: BATCH_TAG } - ) - assert.deepEqual( - transcodeCalls.map(c => c.params.outputPath), - ['D:\\v\\talk_ztools.mp4', 'D:\\v\\talk_ztools_2.mp4'] - ) - assert.equal(outcomes.get('a').status, 'done') - assert.equal(outcomes.get('b').status, 'done') + host.ipc.tool_runtime_ensure = async ({ primitiveId }) => ({ + primitiveId, + status: 'ready', + provisioned: true }) -}) - -test('端到端:宿主 ffmpeg 失败时不会删掉用户已有的同名文件,失败如实上报', async () => { - const userFile = 'D:\\v\\lecture_ztools.mp4' - await withHost( - { - fileExists: 'deny', - existing: [userFile], - transcode: () => ({ ok: false, error: 'ffmpeg version 6.1\nlecture.mov: Invalid data found when processing input' }) - }, - async ({ disk, deletedExisting, transcodeCalls }) => { - const outcome = await batchVideo.processVideoFile( - { path: 'D:\\v\\lecture.mov' }, - convertMp4, - new Set(), - BATCH_TAG - ) - assert.equal(outcome.status, 'failed') - assert.match(outcome.error, /Invalid data found when processing input/) - assert.equal(transcodeCalls.length, 1) - const call = transcodeCalls[0] - assert.equal(call.func, 'BatchConvertFormat') - assert.deepEqual(call.params.files, ['D:\\v\\lecture.mov']) - assert.equal(call.params.format, 'mp4') - assert.notEqual(key(call.params.outputPath), key(userFile), '输出路径不能指向已有文件') - assert.equal(call.params.outputPath, `D:\\v\\lecture_ztools_${BATCH_TAG}.mp4`) - assert.equal(call.timeoutMs, batchVideo.TRANSCODE_IPC_TIMEOUT_MS, '转码调用必须显式设置长于默认 10 秒的等待时限') - assert.deepEqual(deletedExisting, []) - assert.ok(disk.has(key(userFile)), '用户已有文件必须保留') - } - ) -}) +} -test('成功时只采用宿主返回的真实输出路径与大小', async () => { - await withHost({ fileExists: 'answer', transcode: () => ({ ok: true, bytes: 7340032 }) }, async () => { - const outcome = await batchVideo.processVideoFile({ path: 'D:\\v\\clip.mov' }, convertMp4, new Set(), BATCH_TAG) - assert.deepEqual(outcome, { status: 'done', outputPath: 'D:\\v\\clip_ztools.mp4', outputBytes: 7340032 }) - assert.equal(batchVideo.describeOutcomeTag(outcome), `已输出 ${batchVideo.formatBytes(7340032)}`) - assert.equal( - batchVideo.describeOutcomeSubtitle({ parentDir: 'D:\\v', result: outcome }), - '输出:clip_ztools.mp4' - ) - }) -}) +const fieldIds = (view) => view.tree().props.workbenchPanel.fields.map((f) => f.id) -test('宿主返回成功但没有处理结果(例如没收到输入文件)时按失败处理,不当作成功', async () => { - const emptySuccess = { - success: true, - data: { ok: true, success: true, processedCount: 0, outputPath: '', results: [], data: { ok: true, success: true, processedCount: 0, outputPath: '', results: [] } } +test('batch-video 输出路径: 已存在同名文件时自动递增后缀,永不覆盖源文件或已有文件', async () => { + const existing = new Set(['d:\\videos\\demo_ztools.mp4', 'd:\\videos\\demo_ztools_2.mp4']) + const host = { + filesystem_file_exists: async ({ path: p }) => existing.has(p.toLowerCase()) } - await withHost({ fileExists: 'answer', transcode: () => ({ raw: emptySuccess }) }, async () => { - const outcome = await batchVideo.processVideoFile({ path: 'D:\\v\\clip.mov' }, convertMp4, new Set(), BATCH_TAG) - assert.equal(outcome.status, 'failed') - assert.match(outcome.error, /宿主未返回处理结果/) - }) - assert.equal(batchVideo.parseHostVideoResult({ results: [{ outputPath: 'D:\\v\\x.mp4', outputBytes: 0 }] }).status, 'failed') - assert.equal(batchVideo.parseHostVideoResult(null).status, 'failed') -}) - -test('超时、缺少 ffmpeg、宿主异常的错误整理成可读提示', async () => { - await withHost( - { fileExists: 'answer', transcode: () => ({ ok: false, error: 'frame= 1200 fps=20\n命令执行超时(60000 ms)' }) }, - async () => { - const outcome = await batchVideo.processVideoFile({ path: 'D:\\v\\long.mp4' }, convertMp4, new Set(), BATCH_TAG) - assert.equal(outcome.status, 'failed') - assert.match(outcome.error, /60 秒/) - assert.match(outcome.error, /ffmpeg 命令/) - } - ) - await withHost( - { fileExists: 'answer', transcode: () => ({ ok: false, error: '本机未检测到 ffmpeg,无法执行音视频转码处理' }) }, - async () => { - const outcome = await batchVideo.processVideoFile({ path: 'D:\\v\\a.mp4' }, convertMp4, new Set(), BATCH_TAG) - assert.equal(outcome.status, 'failed') - assert.match(outcome.error, /安装 ffmpeg/) - } - ) - await withHost( - { fileExists: 'answer', transcode: () => ({ raw: { success: false, error: { code: 'REQUEST_TIMEOUT', message: '调用超时' } } }) }, - async () => { - const outcome = await batchVideo.processVideoFile({ path: 'D:\\v\\a.mp4' }, convertMp4, new Set(), BATCH_TAG) - assert.equal(outcome.status, 'failed') - assert.match(outcome.error, /超过宿主限制/) - } - ) - await withHost({ fileExists: 'answer', transcode: () => { throw new Error('IPC_BROKEN') } }, async () => { - const outcome = await batchVideo.processVideoFile({ path: 'D:\\v\\a.mp4' }, convertMp4, new Set(), BATCH_TAG) - assert.equal(outcome.status, 'failed') - assert.match(outcome.error, /IPC_BROKEN/) - }) - const longErr = `${'x'.repeat(500)}` - assert.ok(batchVideo.summarizeHostError(longErr).length <= 301) - assert.equal(batchVideo.summarizeHostError(''), '宿主视频处理返回失败') -}) - -test('提取音频、转 GIF 使用对应的方法与扩展名;任务不支持的格式不调用宿主', async () => { - await withHost({ fileExists: 'answer' }, async ({ transcodeCalls }) => { - const audio = await batchVideo.processVideoFile( - { path: 'D:\\v\\talk.mp4' }, - { taskId: 'extract-audio', format: 'mp3' }, - new Set(), - BATCH_TAG - ) - assert.equal(audio.status, 'done') - const gif = await batchVideo.processVideoFile( - { path: 'D:\\v\\talk.mp4' }, - { taskId: 'to-gif', format: 'gif' }, - new Set(), - BATCH_TAG - ) - assert.equal(gif.status, 'done') - assert.deepEqual( - transcodeCalls.map(c => [c.func, c.params.outputPath, c.params.format]), - [ - ['BatchExtractAudio', 'D:\\v\\talk_ztools.mp3', 'mp3'], - ['BatchConvertToGif', 'D:\\v\\talk_ztools.gif', 'gif'] - ] - ) - - const bad = await batchVideo.processVideoFile( - { path: 'D:\\v\\talk.mp4' }, - { taskId: 'convert-video', format: 'gif' }, - new Set(), - BATCH_TAG - ) - assert.equal(bad.status, 'failed') - assert.match(bad.error, /不支持输出格式/) - assert.equal(transcodeCalls.length, 2) - }) + const reserved = new Set() + const out = await batchVideo.chooseOutputPath('D:\\Videos\\demo.mp4', 'mp4', reserved, '20261127120000', host) + assert.equal(out, 'D:\\Videos\\demo_ztools_3.mp4') + assert.equal(batchVideo.isDerivedOutputName('demo_ztools_3.mp4'), true) }) -test('批量处理:单个失败不影响其余文件,请求停止后不再开始下一个', async () => { - let stop = false - const seen = [] - await withHost( - { - fileExists: 'answer', - transcode: ({ params }) => (params.files[0].endsWith('bad.mov') ? { ok: false, error: 'Conversion failed!' } : { ok: true, bytes: 2048 }) - }, - async ({ transcodeCalls }) => { - const outcomes = await batchVideo.processVideoBatch( - [ - { id: '1', path: 'D:\\v\\bad.mov' }, - { id: '2', path: 'D:\\v\\good.mov' }, - { id: '3', path: 'D:\\v\\later.mov' } - ], - convertMp4, - { - batchTag: BATCH_TAG, - shouldStop: () => stop, - onItem: (id, outcome) => { - seen.push([id, outcome.status]) - if (id === '2') stop = true - } - } - ) - assert.deepEqual(seen, [['1', 'failed'], ['2', 'done']]) - assert.equal(outcomes.has('3'), false) - assert.equal(transcodeCalls.length, 2) - const summary = batchVideo.summarizeOutcomes(outcomes.values()) - assert.deepEqual(summary, { total: 2, done: 1, failed: 1, outputBytes: 2048, firstError: 'Conversion failed!' }) - } - ) -}) +test('batch-video UI: 旧宿主未上报 geometry/speed 时隐藏旋转/翻转/裁剪/变速字段', async () => { + const host = createHost() + setupVideoHost(host, { status: 'ready', extensions: [] }) + const view = await mount(BatchVideoCommand, host) + await tick(25) -test('未连接客户端时处理失败,不会报成功', async () => { - const prevWindow = globalThis.window - delete globalThis.window try { - const outcome = await batchVideo.processVideoFile({ path: 'D:\\v\\clip.mov' }, convertMp4, new Set(), BATCH_TAG) - assert.equal(outcome.status, 'failed') - assert.match(outcome.error, /未连接 ZTools 客户端/) + const ids = fieldIds(view) + assert.equal(ids.includes('wb-rotate'), false) + assert.equal(ids.includes('wb-flip'), false) + assert.equal(ids.includes('wb-crop'), false) + assert.equal(ids.includes('wb-speed'), false) + assert.equal(/[\u{1F300}-\u{1FAFF}]/u.test(view.text()), false) } finally { - if (prevWindow !== undefined) globalThis.window = prevWindow + view.unmount() } }) -test('导入规则:支持 9 种视频扩展名,排除本插件 _ztools 输出文件、.gif 与系统保护路径', async () => { - assert.deepEqual( - [...batchVideo.INPUT_VIDEO_EXTENSIONS], - ['.mp4', '.mkv', '.mov', '.avi', '.flv', '.webm', '.wmv', '.ts', '.m4v'] - ) - assert.equal(batchVideo.VIDEO_IMPORT_RULES.excludeFile?.('trip_ztools.mp4', 'D:\\v\\trip_ztools.mp4'), true) - assert.equal(batchVideo.VIDEO_IMPORT_RULES.excludeFile?.(`talk_ztools_${BATCH_TAG}_2.mkv`, `D:\\v\\talk_ztools_${BATCH_TAG}_2.mkv`), true) - assert.equal(batchVideo.VIDEO_IMPORT_RULES.excludeFile?.('my_ztools_demo.mov', 'D:\\v\\my_ztools_demo.mov'), false) - assert.equal(batchVideo.VIDEO_IMPORT_RULES.forbiddenPath?.test('C:\\Windows\\System32\\a.mp4'), true) -}) +test('batch-video UI: 新宿主上报 geometry/speed 时动态展示字段,needs_provisioning 展示下载引擎引导', async () => { + const host = createHost() + setupVideoHost(host, { status: 'needs_provisioning', extensions: ['geometry', 'speed'] }) + const view = await mount(BatchVideoCommand, host) + await tick(25) -test('等效 ffmpeg 命令带 -n,目标已存在时不覆盖', () => { - assert.equal( - batchVideo.buildFfmpegCommand('D:\\v\\clip.mov', 'mp4'), - 'ffmpeg -n -i "D:\\v\\clip.mov" "D:\\v\\clip_ztools.mp4"' - ) -}) - -test('定位结果:输出文件没有访问授权时改为显示源文件,不会用默认程序打开文件', async () => { - const file = { path: 'D:\\v\\clip.mov', result: { status: 'done', outputPath: 'D:\\v\\clip_ztools.mp4', outputBytes: 10 } } - await withHost({ revealAllowed: ['D:\\v\\clip.mov'] }, async ({ envelopes }) => { - assert.equal(await batchVideo.revealVideoInFolder(file), 'source') - assert.equal(envelopes.some(e => e.method === 'shell_open_path'), false) - }) - await withHost({ revealAllowed: ['D:\\v\\clip_ztools.mp4'] }, async () => { - assert.equal(await batchVideo.revealVideoInFolder(file), 'output') - }) - await withHost({ revealAllowed: [] }, async () => { - assert.equal(await batchVideo.revealVideoInFolder(file), 'failed') - }) -}) - -function collectStrings(node, out = []) { - if (typeof node === 'string') out.push(node) - else if (Array.isArray(node)) node.forEach(n => collectStrings(n, out)) - else if (node && typeof node === 'object') Object.values(node).forEach(v => collectStrings(v, out)) - return out -} - -test('界面:不显示体积估算与假示例文件,未连接客户端时初始为空并如实提示', () => { - const prevWindow = globalThis.window - delete globalThis.window try { - const view = batchVideo.BatchVideoCommand() - assert.equal(view.type, 'List') - const text = collectStrings(view).join('\n') - for (const banned of ['预计', '节省', 'NVENC', 'CRF', 'HEVC', 'GPU', '画幅裁剪', '水印', '倍速', 'Product_Launch_4K']) { - assert.equal(text.includes(banned), false, `界面不应出现「${banned}」`) - } - const props = view.props || {} - assert.equal(props.subList.items.length, 0) - assert.match(props.subList.emptyText, /需要在 ZTools 客户端中使用/) - const fieldIds = (props.workbenchPanel?.fields || []).map(f => f.id) - assert.deepEqual(fieldIds, ['wb-format', 'wb-codec', 'wb-outdir', 'wb-limit']) - const formatField = props.workbenchPanel.fields[0] - assert.deepEqual(formatField.options.map(o => o.value), ['mp4', 'mkv', 'mov', 'webm']) + const ids = fieldIds(view) + assert.equal(ids.includes('wb-rotate'), true) + assert.equal(ids.includes('wb-flip'), true) + assert.equal(ids.includes('wb-crop'), true) + assert.equal(ids.includes('wb-speed'), true) + + const downloadBtn = view.tree().props.filterBar.actions.find((a) => a.id === 'download-engine') + assert.ok(downloadBtn, 'needs_provisioning 态应显示下载视频引擎按钮') + await downloadBtn.onAction() + await tick(25) + assert.ok(host.ipcCalls.some(([m]) => m === 'tool_runtime_ensure')) } finally { - if (prevWindow !== undefined) globalThis.window = prevWindow - } -}) - -test('清单:标为草稿并写明原因,描述不再声称压缩与调分辨率', () => { - const manifest = JSON.parse(fs.readFileSync(path.resolve(__dirname, '../plugin.json'), 'utf8')) - assert.equal(manifest.draft, true) - assert.ok(typeof manifest.draftReason === 'string' && manifest.draftReason.length > 20) - assert.equal(/压缩|分辨率/.test(manifest.description), false) - assert.ok(manifest.permissions.includes('dialog')) -}) - -test('batch-video UI:挂载零扫盘、选择文件/文件夹、拖入文件夹(含回退)、移除清空与处理中防护', async () => { - const os = await import('node:os') - const { createHost, installDirectoryHost, mount, tick } = await import('../../shared/test-harness.mjs') - const tmpRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'ztools-batch-video-')) - const write = (rel, content) => { - const p = path.join(tmpRoot, rel) - fs.mkdirSync(path.dirname(p), { recursive: true }) - fs.writeFileSync(p, content) - return p - } - - try { - const clipA = write('clip_a.mp4', 'aaa') - write('sub/clip_b.mkv', 'bbb') - write('sub/clip_a_ztools.mp4', 'derived') - write('sub/anim.gif', 'gif') - write('readme.txt', 'txt') - const subDir = path.join(tmpRoot, 'sub') - - const host = createHost() - await installDirectoryHost(host, { authorized: [tmpRoot] }) - host.ipc.filesystem_get_file_size = async ({ path: p }) => ({ - success: true, - size: fs.existsSync(p) ? fs.statSync(p).size : 2048000 - }) - - const view = await mount(batchVideo.BatchVideoCommand, host) - await tick(10) - - const banned = new Set([ - 'system_get_path', - 'system_list_common_folders', - 'system_search_files', - 'filesystem_get_directory_contents', - 'dllplugin_call' - ]) - assert.deepEqual(host.ipcCalls.filter(([m]) => banned.has(m)), []) - assert.equal(view.tree().props.subList.items.length, 0) - const fbActions = view.tree().props.filterBar.props?.actions ?? view.tree().props.filterBar.actions - assert.deepEqual( - fbActions.map(a => ({ id: a.id, label: a.label })), - [ - { id: 'pick-files', label: '选择文件' }, - { id: 'pick-folder', label: '选择文件夹' } - ] - ) - - // 选择文件取消 & 报错翻译 & 成功导入(验证 filters 为字符串) - host.ipc.window_show_open_dialog = async () => ({ canceled: true }) - await fbActions.find(a => a.id === 'pick-files').onAction() - await tick(10) - assert.equal(host.toasts.length, 0) - - let openParams = null - host.ipc.window_show_open_dialog = async params => { - openParams = params - return { canceled: false, filePaths: [clipA] } - } - await fbActions.find(a => a.id === 'pick-files').onAction() - await tick(10) - assert.equal(openParams.filters, '视频文件|mp4;mkv;mov;avi;flv;webm;wmv;ts;m4v') - assert.deepEqual(view.tree().props.subList.items.map(i => i.props.title), ['clip_a.mp4']) - - // 选择文件夹(整盘确认 + 递归收集 + 排除 _ztools 与 .gif + 去重 clip_a.mp4) - host.setConfirm(false) - host.ipc.window_show_select_folder_dialog = async () => ({ canceled: false, folderPath: 'D:\\' }) - await fbActions.find(a => a.id === 'pick-folder').onAction() - await tick(10) - assert.equal(host.confirms.length, 1) - - host.setConfirm(true) - host.ipc.window_show_select_folder_dialog = async () => ({ canceled: false, folderPath: tmpRoot }) - await fbActions.find(a => a.id === 'pick-folder').onAction() - await tick(15) - assert.deepEqual(view.tree().props.subList.items.map(i => i.props.title), ['clip_a.mp4', 'clip_b.mkv']) - - // 拖入文件夹(新版带 directories 与去重) - await view.dropFiles([subDir], { directories: [subDir] }) - await tick(10) - assert.equal(host.lastToast()?.title, '这些文件已在列表中') - - // 粘贴导入未知大小文件显示「大小未识别」 - host.ipc.filesystem_get_file_size = async () => { - throw new Error('路径未由当前窗口授权') - } - await view.pasteFiles(['D:\\Videos\\pasted.mov']) - await tick(15) - const pasted = view.item(it => it.props.title === 'pasted.mov') - assert.ok(pasted.props.accessories.some(a => a.text === '大小未识别')) - - // 从列表移除不碰磁盘 - await view.run(pasted, '从列表移除') - assert.equal(view.tree().props.subList.items.length, 2) - assert.equal(host.ipcCalls.some(([m]) => /trash|delete|unlink/i.test(m)), false) - - // 处理中移除尚未开始的 clip_b.mkv、拒绝清空列表、跳过已移除项不调宿主 - let releaseFirst - const firstGate = new Promise(r => (releaseFirst = r)) - const dllFiles = [] - host.ipc.filesystem_file_exists = async () => ({ success: true, exists: false }) - host.ipc.dllplugin_call = async ({ params }) => { - dllFiles.push(params.files[0]) - if (params.files[0] === clipA) await firstGate - return { - ok: true, - success: true, - processedCount: 1, - outputPath: params.outputPath, - outputBytes: 1024, - results: [{ sourcePath: params.files[0], outputPath: params.outputPath, outputBytes: 1024 }], - errors: [] - } - } - const batchPromise = view.run(view.tree().props.subList.items[0], '开始处理已选视频 (2 个)') - await tick(5) - assert.equal( - view.actions(view.tree().props.subList.items[0]).some(a => a.props.title === '从列表移除'), - false - ) - await view.run(view.tree().props.subList.items[1], '清空列表') - assert.equal(host.lastToast()?.title, '正在处理,完成后再清空') - await view.run(view.tree().props.subList.items[1], '从列表移除') - assert.equal(view.tree().props.subList.items.length, 1) - releaseFirst() - await batchPromise - await tick(10) - assert.deepEqual(dllFiles, [clipA]) - assert.equal(view.tree().props.subList.items.length, 1) - - // 清空列表 + 导入进行中清空丢弃结果 - await view.run(view.tree().props.subList.items[0], '清空列表') - assert.equal(view.tree().props.subList.items.length, 0) - - let releaseImport - const importGate = new Promise(r => (releaseImport = r)) - host.ipc.window_show_select_folder_dialog = async () => ({ canceled: false, folderPath: 'D:\\PendingVid' }) - host.ipc.filesystem_get_directory_contents = async () => { - await importGate - return { success: true, files: [{ name: 'late.mp4', size: 1024, isDirectory: false }] } - } - await view.pasteFiles([clipA]) - await tick(10) - const toastBefore = host.toasts.length - const pendingTask = fbActions.find(a => a.id === 'pick-folder').onAction() - await tick(5) - await view.run(view.tree().props.subList.items[0], '清空列表') - releaseImport() - await pendingTask - await tick(10) - assert.equal(view.tree().props.subList.items.length, 0) - assert.equal(host.toasts.length, toastBefore) view.unmount() - - // 旧版客户端 plugin_files_dropped 回退(含文件夹展开) - const legacyHost = createHost() - await installDirectoryHost(legacyHost, { authorized: [tmpRoot] }) - legacyHost.ipc.filesystem_directory_exists = async ({ path: p }) => ({ - success: true, - exists: p.toLowerCase() === subDir.toLowerCase() - }) - let droppedListener = null - globalThis.window.__ztoolsDeclarativeFeatures = { fileInput: false } - globalThis.window.ztools = { - ...(globalThis.window.ztools || {}), - events: { - on(event, cb) { - if (event === 'plugin_files_dropped') droppedListener = cb - return () => { - if (droppedListener === cb) droppedListener = null - } - } - } - } - const legacyView = await mount(batchVideo.BatchVideoCommand, legacyHost) - try { - assert.equal(typeof droppedListener, 'function') - droppedListener({ payload: { files: [subDir] } }) - await tick(20) - assert.deepEqual(legacyView.tree().props.subList.items.map(i => i.props.title), ['clip_b.mkv']) - } finally { - legacyView.unmount() - globalThis.window.__ztoolsDeclarativeFeatures = { fileInput: true } - } - assert.equal(droppedListener, null) - } finally { - fs.rmSync(tmpRoot, { recursive: true, force: true }) } }) diff --git a/extensions/boost/README.en.md b/extensions/boost/README.en.md new file mode 100644 index 00000000..dac85a2d --- /dev/null +++ b/extensions/boost/README.en.md @@ -0,0 +1,21 @@ +# System Boost & Startup + +List top memory-consuming processes, startup items in the Windows Startup folders, and files in the temp folder; confirm checked items to terminate processes or move startup shortcuts and temporary files to the Recycle Bin. + +## Usage + +- Command: Search for "System Boost & Startup" in the launcher to open. +- The list includes: the top 30 processes by memory usage; items in the current user and all-users Startup folders; running processes whose names match common auto-start applications (such as OneDrive, Steam, and WeChat); and the first 15 files in the temporary folder (`%TEMP%`). +- Processes labeled "Auto-start Resident" are matched solely by process name or path; the plugin does not read Registry, Task Scheduler, or Windows Service startup entries and cannot disable those startup items. Ending such a process only affects the current session and does not prevent it from starting on future boots. +- No items are checked by default after scanning; you must check items manually. If parts of the scan fail (e.g., process list or memory usage), the top status bar displays the reason. +- `Enter`: Opens a confirmation dialog showing how many processes will be terminated and how many files will be moved; after confirmation, only checked items are processed (Startup folder items and temporary files are moved to the Recycle Bin, while processes are force-terminated and unsaved data inside them will be lost). Nothing happens if nothing is checked; failed items report their reason individually without falling back to other items. +- `Ctrl+Enter`: Reveals the item in File Explorer (for processes whose path cannot be read, this action is omitted and `Ctrl+Enter` instead prompts to end the process, also requiring confirmation); `Ctrl+K`: Opens the action panel to terminate an individual process (with confirmation). +- Protected processes (such as `System`, `csrss`, `lsass`, `svchost`, `wininit`, `explorer`, `dwm`, `ZTools`, processes flagged as system processes by the client, and processes under `C:\Windows`) cannot be checked or terminated (including under "Auto-start Resident"). Items in the common Startup folder (under `C:\ProgramData`) apply to all users and cannot be removed by the plugin. + +## Platforms & Requirements + +- Supported: Windows only + +## Network & Data + +- Works offline; data stays on your local device. diff --git a/extensions/boost/plugin.json b/extensions/boost/plugin.json index cdf3f97a..8e13849d 100644 --- a/extensions/boost/plugin.json +++ b/extensions/boost/plugin.json @@ -3,6 +3,9 @@ "name": "开机启动项", "description": "列出内存占用最高的进程、“启动”文件夹里的开机启动项和临时文件,勾选并确认后结束进程,或把启动项和临时文件移入回收站", "version": "2.0.11", + "minAppVersion": "1.1.8.0", + "revoked": true, + "revokedReason": "功能已分别由「进程监控」(process-monitor)、「启动管理」(startup-manager) 与「垃圾清理」(cleaner) 覆盖,请改用对应插件", "author": "ZTools Team", "entry": "dist/index.js", "icon": "icon.svg", @@ -31,13 +34,19 @@ "en-US": { "name": "System Boost & Startup", "description": "List top memory-consuming processes, Startup folder items, and temporary files. Confirm to terminate selected processes or move startup entries and temp files to the Recycle Bin.", + "revokedReason": "Features are now covered by \"Process & Port Monitor\" (process-monitor), \"Startup Manager\" (startup-manager), and \"System Cleaner\" (cleaner). Please use those plugins instead.", "keywords": [ "boost", "startup", "memory", "temp files", "cleanup", - "processes" + "processes", + "speed up", + "ram", + "optimize", + "performance", + "lag" ], "screenshots": [ { @@ -53,5 +62,16 @@ { "path": "screenshots/02-action-panel.png" } + ], + "keywords": [ + "开机启动项", + "加速", + "清理内存", + "内存加速", + "电脑卡顿", + "优化加速", + "释放内存", + "系统加速", + "启动项" ] } diff --git a/extensions/boost/src/native-ipc.ts b/extensions/boost/src/native-ipc.ts index 51576b99..b8c547d6 100644 --- a/extensions/boost/src/native-ipc.ts +++ b/extensions/boost/src/native-ipc.ts @@ -174,11 +174,13 @@ function normalizeMethodResult(method: string, payload: DynamicBridge): DynamicB if (method === 'system_get_battery_status') { // 宿主约定 percent 超出 0-100(如 255)表示无电池或电量未知,不能改写成 100% + // 若宿主明确给出 hasBattery 布尔值,必须原样保留,仅在缺失时按合法电量推算 const rawPct = payload.percent - const hasBattery = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const validPct = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const hasBattery = typeof payload.hasBattery === 'boolean' ? payload.hasBattery : validPct return { ...payload, - percent: hasBattery ? rawPct : null, + percent: validPct ? rawPct : null, hasBattery } } @@ -1817,8 +1819,6 @@ export async function writeRealClipboardText(text: string, hostOverride?: Dynami const payload = { text: String(text || '') } const res = await callHostTransport('clipboard_copy_text', payload, hostOverride) if (res.ok) return true - const fallbackRes = await callHostTransport('clipboard_write_text', payload, hostOverride) - if (fallbackRes.ok) return true try { if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) { await navigator.clipboard.writeText(String(text || '')) diff --git a/extensions/browser-bookmarks/README.en.md b/extensions/browser-bookmarks/README.en.md new file mode 100644 index 00000000..c8315aca --- /dev/null +++ b/extensions/browser-bookmarks/README.en.md @@ -0,0 +1,23 @@ +# Browser Bookmarks + +Read-only aggregation of web bookmarks across local browser profiles; search by title, pinyin, URL, or folder name to open or copy bookmarks. + +## Usage + +- Commands: Search bookmarks across all detected local browsers (keywords such as `bookmarks`, `browser bookmarks`, `favorites`), plus separate commands for Microsoft Edge (`edge bookmarks`), Google Chrome (`chrome bookmarks`), Mozilla Firefox (`firefox bookmarks`), and domestic browsers (`qq bookmarks`, `360 bookmarks` — 360 Safe, 360 Extreme, and QQ Browser on Windows; 360 Extreme and QQ Browser on macOS). Missing bookmarks or read failures for the chosen browser are explained individually. +- Search by title, full pinyin or initials, URL, or folder name; enter `domain:example.com` to filter by domain. Filter by browser on the right side of the search box. +- `Enter` opens the webpage, `⌘/Ctrl+Enter` copies the URL, and `⌘/Ctrl+K` also lets you copy a Markdown link or title. +- Displays 200 items at a time, with "Show More" at the bottom to load more; searching always covers all loaded bookmarks. +- Use "Refresh Bookmarks" to re-read from disk. If some sources fail to load, open "Read Details" to view the reasons; if all sources fail, previous results are retained with a notice that the list was not updated. +- Supported browsers: Chrome, Edge, Brave, Firefox, QQ Browser, 360 Extreme Browser, and 360 Safe Browser on Windows; Chrome, Edge, Brave, Firefox, Safari, QQ Browser, and 360 Extreme Browser on macOS. Reads profiles under default data directories, plus custom profiles registered in `profiles.ini` for Firefox. Bookmarks stored only in the cloud and not yet synced locally cannot be read. +- Lists HTTP / HTTPS webpages only and never executes bookmarklet scripts; URLs containing embedded usernames or passwords are not opened directly by the client and can only be copied. Firefox databases are opened in read-only mode, including unmerged WAL logs. Safari bookmarks are protected by macOS privacy permissions and require Full Disk Access for ZTools in **System Settings → Privacy & Security → Full Disk Access**; when permission is missing, "Read Details" explains why and the failure item provides "Copy Full Disk Access Settings Path" (the client only allows opening web links and cannot jump directly to System Settings). Filtering by other browsers is unaffected by Safari permissions and only reports whether that browser has bookmarks. +- Limits: up to 16 MiB per bookmark file, 1 GiB per Firefox database, and 20,000 items or 7 MiB total results; sources exceeding these limits report an explicit error and are not treated as completely loaded. + +## Platforms & Requirements + +- Supported: Windows, macOS +- Requires client version 1.1.8.5 or later. + +## Network & Data + +- Works offline; reads local bookmark files in read-only mode and never modifies browser favorites. diff --git a/extensions/browser-bookmarks/plugin.json b/extensions/browser-bookmarks/plugin.json index 0e9bf0d5..32ddf197 100644 --- a/extensions/browser-bookmarks/plugin.json +++ b/extensions/browser-bookmarks/plugin.json @@ -1,7 +1,8 @@ { "id": "browser-bookmarks", "name": "网页书签", - "version": "1.0.5", + "version": "1.0.6", + "minAppVersion": "1.1.8.0", "description": "只读聚合本机浏览器的多个配置,支持中文、拼音、网址与文件夹检索,打开或复制书签;无法读取的来源会明确提示", "author": "ZTools Team", "entry": "dist/index.js", @@ -93,7 +94,11 @@ "edge", "firefox", "favorites", - "search" + "search", + "browser bookmarks", + "safari", + "saved links", + "web bookmarks" ], "features": { "bookmarks-all": { @@ -146,5 +151,16 @@ { "path": "screenshots/01.png" } + ], + "keywords": [ + "书签", + "收藏夹", + "网页书签", + "浏览器书签", + "chrome书签", + "edge书签", + "找网址", + "搜书签", + "bookmarks" ] } diff --git a/extensions/browser-bookmarks/src/index.tsx b/extensions/browser-bookmarks/src/index.tsx index 80cdfa64..c55696de 100644 --- a/extensions/browser-bookmarks/src/index.tsx +++ b/extensions/browser-bookmarks/src/index.tsx @@ -60,7 +60,7 @@ export default function BrowserBookmarks({ initialFilter = 'all', platform = det // 客户端只打开不含用户名、密码的网址(shell_open_external 会拒绝),这类书签只提供复制 ? : } - {!hasCredentials(item.url) && } + {!hasCredentials(item.url) && } } />)} diff --git a/extensions/browser-bookmarks/tests/index.test.mjs b/extensions/browser-bookmarks/tests/index.test.mjs index dd44560d..8de15906 100644 --- a/extensions/browser-bookmarks/tests/index.test.mjs +++ b/extensions/browser-bookmarks/tests/index.test.mjs @@ -15,7 +15,7 @@ test('五个命令分别筛选,全宽列表和主次动作保持契约', async const view = await open(code) assert.equal(view.items().length, expected); assert.equal(view.tree().props.isShowingDetail, false) const actions = view.actions(view.items()[0]); assert.equal(actions[0].type, 'Action.OpenInBrowser'); assert.equal(actions[1].props.title, '复制链接') - assert.deepEqual(actions[1].props.shortcut, { modifiers: ['cmd'], key: 'enter' }) + assert.deepEqual(actions[1].props.shortcut, { modifiers: ['ctrl'], key: 'enter' }) await view.run(view.items()[0], '复制链接'); assert.equal(host.clipboard.text, items[0].url) } assert.ok(host.ipcCalls.every(([method]) => method !== 'dllplugin_call')) diff --git a/extensions/browser-history/README.en.md b/extensions/browser-history/README.en.md new file mode 100644 index 00000000..494f48aa --- /dev/null +++ b/extensions/browser-history/README.en.md @@ -0,0 +1,10 @@ +# Browser History + +Read-only local search across Chrome, Edge, Brave, Arc, Firefox, and Safari (macOS) browsing history. + +## Highlights + +- **Transparent Privacy**: Displays a clear first-run read-only notice before reading local browser profiles; no browsing data is uploaded or modified. +- **Fast Filtering**: Filter by keyword, `domain:` host prefix, browser, and time range (`24h`, `7d`, `30d`, or `all`). +- **Safe Actions**: Open validated `http://` and `https://` links on Enter (URLs with embedded credentials are restricted to copy-only), or copy URL, title, and Markdown links. +- **Safari Guidance**: Shows clear Full Disk Access instructions on macOS whenever Safari `History.db` access is restricted. diff --git a/extensions/browser-history/README.md b/extensions/browser-history/README.md index c6a1559c..d45e5bb7 100644 --- a/extensions/browser-history/README.md +++ b/extensions/browser-history/README.md @@ -1,3 +1,10 @@ # 浏览器历史记录 -已下架:功能未完成(只有示例数据)。 +只读聚合搜索本机 Chrome、Edge、Brave、Arc、Firefox 与 Safari(macOS)的浏览器历史记录。 + +## 核心能力 + +- **隐私透明**:首次使用前明确告知本机只读访问范围,所有数据均在本地检索,不上传任何记录、不修改浏览器数据库。 +- **多维度筛选**:支持关键词与 `domain:` 域名过滤、按浏览器筛选以及 `24h` / `7d` / `30d` / 全部时间范围筛选。 +- **安全直达**:回车打开经过 `http://` / `https://` 白名单校验的网页链接,含登录凭据的链接仅提供复制;支持一键复制 URL、标题与 Markdown 链接。 +- **Safari 权限引导**:macOS 上读取 Safari 历史记录受限时会明确给出「完全磁盘访问权限」开启指引。 diff --git a/extensions/browser-history/icon.svg b/extensions/browser-history/icon.svg new file mode 100644 index 00000000..1dec7077 --- /dev/null +++ b/extensions/browser-history/icon.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/extensions/browser-history/plugin.json b/extensions/browser-history/plugin.json index 86a025b1..03aa54f8 100644 --- a/extensions/browser-history/plugin.json +++ b/extensions/browser-history/plugin.json @@ -1,22 +1,107 @@ { "id": "browser-history", "name": "浏览器历史记录", - "description": "Chrome / Edge 浏览器历史记录搜索", - "version": "1.0.0", - "revoked": true, - "revokedReason": "功能未完成(只有示例数据)", + "description": "只读聚合搜索本机 Chrome、Edge、Brave、Arc、Firefox 与 Safari 浏览器历史记录,支持按关键词、域名、浏览器与时间范围快速检索并安全打开或复制链接", + "version": "1.1.0", + "minAppVersion": "1.3.0.2", "author": "ZTools Team", "entry": "dist/index.js", "icon": "icon.svg", - "category": "browser", - "permissions": [], + "category": [ + "网络工具" + ], + "categoryId": "network", + "keywords": [ + "历史记录", + "浏览历史", + "浏览器历史", + "history", + "chrome", + "edge", + "firefox", + "safari", + "brave", + "arc" + ], + "permissions": [ + "fs", + "shell", + "clipboard" + ], + "requireAdmin": false, + "nativeComponents": [], + "features": [ + { + "code": "history-all", + "explain": "聚合搜索全部本机浏览器的历史访问记录", + "cmds": [ + "浏览器历史", + "历史记录", + "浏览记录", + "browser history", + "history" + ] + }, + { + "code": "history-today", + "explain": "快速查看最近 24 小时内的浏览历史记录", + "cmds": [ + "今日浏览记录", + "最近浏览", + "today history", + "recent history" + ] + } + ], "targets": [ { "id": "windows-electron-any", "platform": "windows", "runtime": "electron", "arch": "any" + }, + { + "id": "macos-electron-any", + "platform": "macos", + "runtime": "electron", + "arch": "any" } ], - "nativeComponents": [] + "defaultLocale": "zh-CN", + "i18n": { + "en-US": { + "name": "Browser History", + "description": "Read-only search across local Chrome, Edge, Brave, Arc, Firefox, and Safari browsing history by keyword, domain, browser, and time range to safely open or copy links.", + "keywords": [ + "history", + "browser history", + "browsing history", + "chrome", + "edge", + "brave", + "arc", + "firefox", + "safari" + ], + "features": { + "history-all": { + "explain": "Search browsing history across all detected local browsers", + "cmds": [ + "browser history", + "browsing history", + "search history", + "history" + ] + }, + "history-today": { + "explain": "Browse history visited in the last 24 hours", + "cmds": [ + "today history", + "recent history", + "last 24h history" + ] + } + } + } + } } diff --git a/extensions/browser-history/src/error-i18n.ts b/extensions/browser-history/src/error-i18n.ts new file mode 100644 index 00000000..d97366d1 --- /dev/null +++ b/extensions/browser-history/src/error-i18n.ts @@ -0,0 +1,213 @@ +/** + * 声明式插件通用错误本地化解析器(R7 双轨平滑迁移共享底座)。 + * + * 规则: + * 1. 优先按结构化错误码(errorDetails.hostCode / details.hostCode / errorCode / code)查表: + * 先查插件传入的 codeMap,再查标准宿主错误码双语表; + * 2. 对称展示规则:中文模式(zh-CN)原文含 CJK 才直接展示,英文模式(en-US)原文不含 CJK 才直接展示, + * 既保留宿主精确本地化消息,又拦截英文技术原文裸露到中文界面、拦截中文原文裸露到英文界面; + * 3. 原文语言不匹配时优先使用标准宿主错误码译文,否则回退到插件本地 t(...) 兜底文案。 + */ + +import { getLocale } from '@ztools/declarative-ui' + +const CJK_REGEX = /[\u4e00-\u9fa5]/ + +const HOST_ERROR_CODE_MESSAGES: Record>> = { + 'zh-CN': { + INVALID_REQUEST: '请求参数无效', + METHOD_NOT_FOUND: '当前 ZTools 版本过低或不支持此接口,请升级客户端后重试', + METHOD_NOT_AVAILABLE: '当前 ZTools 版本过低或不支持此接口,请升级客户端后重试', + PERMISSION_DENIED: '权限不足,无法执行该操作', + REQUEST_TIMEOUT: '请求执行超时,请稍后重试', + CALLER_DESTROYED: '调用窗口已关闭,操作已中止', + APP_STOPPING: '应用正在退出,操作已取消', + CANCELLED: '操作已取消', + OPERATION_CANCELLED: '操作已取消', + NOT_SUPPORTED: '当前环境不支持此操作', + PLATFORM_NOT_SUPPORTED: '当前操作系统不支持此功能', + NETWORK_ERROR: '网络请求失败,请检查网络连接', + RESPONSE_TOO_LARGE: '响应数据超出大小限制', + FILE_ERROR: '文件操作失败', + FILE_NOT_FOUND: '目标文件或目录不存在', + FILE_TOO_LARGE: '文件大小超出限制', + FILE_ALREADY_EXISTS: '目标文件已存在', + DISK_FULL: '磁盘空间不足', + SHELL_ERROR: '系统命令或外部应用启动失败', + PROCESS_ERROR: '进程操作失败', + PROCESS_PROTECTED: '目标进程受系统保护,无法操作', + PROCESS_NOT_FOUND: '未找到目标进程', + PROCESS_ACCESS_DENIED: '无权访问或操作目标进程', + SCREEN_ERROR: '屏幕或窗口操作失败', + CLIPBOARD_ERROR: '剪贴板读写失败', + DATABASE_LOCKED: '本地数据库正被占用,请稍后重试', + DATABASE_KEY_NOT_FOUND: '未找到指定的数据项', + DATA_CORRUPT: '本地数据格式损坏或校验失败', + STORAGE_ERROR: '本地存储读写失败', + PLUGIN_BUSY: '插件正忙,请稍后重试', + PLUGIN_PERMISSION_REQUIRED: '插件缺少所需权限声明', + DLL_ERROR: '原生组件执行失败', + NATIVE_HOST_UNAVAILABLE: '原生宿主组件不可用', + NATIVE_HOST_ERROR: '原生宿主执行失败', + SERVICE_UNAVAILABLE: '系统提权服务不可用', + INTERNAL_ERROR: '宿主内部错误' + }, + 'en-US': { + INVALID_REQUEST: 'Invalid request parameters', + METHOD_NOT_FOUND: 'Your ZTools version is too old or does not support this API. Please upgrade and try again.', + METHOD_NOT_AVAILABLE: 'Your ZTools version is too old or does not support this API. Please upgrade and try again.', + PERMISSION_DENIED: 'Permission denied', + REQUEST_TIMEOUT: 'Request timed out. Please try again later.', + CALLER_DESTROYED: 'The caller window was closed and the operation was aborted', + APP_STOPPING: 'Application is exiting; operation cancelled', + CANCELLED: 'Operation cancelled', + OPERATION_CANCELLED: 'Operation cancelled', + NOT_SUPPORTED: 'This operation is not supported in the current environment', + PLATFORM_NOT_SUPPORTED: 'This feature is not supported on the current operating system', + NETWORK_ERROR: 'Network request failed. Please check your connection.', + RESPONSE_TOO_LARGE: 'Response payload exceeds size limit', + FILE_ERROR: 'File operation failed', + FILE_NOT_FOUND: 'Target file or directory not found', + FILE_TOO_LARGE: 'File size exceeds limit', + FILE_ALREADY_EXISTS: 'Target file already exists', + DISK_FULL: 'Insufficient disk space', + SHELL_ERROR: 'Failed to launch system command or external application', + PROCESS_ERROR: 'Process operation failed', + PROCESS_PROTECTED: 'Target process is protected by the system', + PROCESS_NOT_FOUND: 'Target process not found', + PROCESS_ACCESS_DENIED: 'Access denied for target process', + SCREEN_ERROR: 'Screen or window operation failed', + CLIPBOARD_ERROR: 'Failed to read or write clipboard', + DATABASE_LOCKED: 'Local database is locked. Please try again later.', + DATABASE_KEY_NOT_FOUND: 'Requested item was not found', + DATA_CORRUPT: 'Local data is corrupted or failed validation', + STORAGE_ERROR: 'Local storage operation failed', + PLUGIN_BUSY: 'Plugin is busy. Please try again later.', + PLUGIN_PERMISSION_REQUIRED: 'Plugin is missing required permission declaration', + DLL_ERROR: 'Native component execution failed', + NATIVE_HOST_UNAVAILABLE: 'Native host component is unavailable', + NATIVE_HOST_ERROR: 'Native host execution failed', + SERVICE_UNAVAILABLE: 'Elevated system service is unavailable', + INTERNAL_ERROR: 'Internal host error' + } +} + +function asObj(value: unknown): Record | null { + return value && typeof value === 'object' && !Array.isArray(value) + ? (value as Record) + : null +} + +function pickNonEmptyString(value: unknown): string { + return typeof value === 'string' && value.trim().length > 0 ? value.trim() : '' +} + +/** 从错误对象或宿主响应信封中提取结构化错误码(优先 errorCode,再 code) */ +export function extractErrorCode(source: unknown): string { + const rec = asObj(source) + if (!rec) return '' + const direct = pickNonEmptyString(rec.errorCode) || pickNonEmptyString(rec.code) + if (direct) return direct + const nestedErr = asObj(rec.error) + if (nestedErr) { + return pickNonEmptyString(nestedErr.errorCode) || pickNonEmptyString(nestedErr.code) + } + const nestedData = asObj(rec.data) + if (nestedData) { + return pickNonEmptyString(nestedData.errorCode) || pickNonEmptyString(nestedData.code) + } + return '' +} + +/** 从错误对象或宿主响应信封中提取 details.hostCode */ +export function extractHostCode(source: unknown): string { + const rec = asObj(source) + if (!rec) return '' + const directDetails = asObj(rec.errorDetails) || asObj(rec.details) + const fromDirect = directDetails ? pickNonEmptyString(directDetails.hostCode) : '' + if (fromDirect) return fromDirect + const nestedErr = asObj(rec.error) + if (nestedErr) { + const nestedDetails = asObj(nestedErr.errorDetails) || asObj(nestedErr.details) + const fromNested = nestedDetails ? pickNonEmptyString(nestedDetails.hostCode) : '' + if (fromNested) return fromNested + } + return '' +} + +/** 从错误对象、宿主响应或字符串中提取原始错误文案 */ +export function extractRawErrorText(source: unknown): string { + if (typeof source === 'string') return source.trim() + if (source instanceof Error) return source.message.trim() + const rec = asObj(source) + if (!rec) return '' + if ('error' in rec) { + if (typeof rec.error === 'string') return rec.error.trim() + const nestedErr = asObj(rec.error) + if (nestedErr) { + return pickNonEmptyString(nestedErr.message) || pickNonEmptyString(nestedErr.error) + } + return '' + } + return pickNonEmptyString(rec.message) +} + +/** 判断某段文本在当前 locale 下是否可直接展示给用户(对称规则:zh-CN 需含 CJK,en-US 需不含 CJK) */ +export function isDisplayableInCurrentLocale(text: string): boolean { + if (!text) return false + const locale = getLocale() + if (locale === 'zh-CN') return CJK_REGEX.test(text) + return !CJK_REGEX.test(text) +} + +/** + * 将宿主响应、异常对象或原始错误字符串安全解析为当前语言的提示文案: + * 1. 若对象属于成功响应且无 error,直接返回 fallback(避免误读成功态 message/code); + * 2. 优先按 hostCode / errorCode / code 查插件自定义 codeMap; + * 3. 若存在标准宿主错误码且无原文或原文语言不匹配,按当前语言查标准词典; + * 4. 若原始文案非空且符合当前语种(中文模式含 CJK,英文模式不含 CJK),保留原始文案; + * 5. 其余情况一律回退到插件本地传入的 fallback(即 t('...'))。 + */ +export function resolveErrorMessage( + source: unknown, + fallback: string, + codeMap?: Readonly> +): string { + if (source === null || source === undefined || source === '') { + return fallback + } + const rec = asObj(source) + if (rec && 'error' in rec && rec.ok === true && !rec.error) { + return fallback + } + + const hostCode = extractHostCode(source) + const code = extractErrorCode(source) + const rawText = extractRawErrorText(source) + + // 非失败响应容器若既无 error 文案也无 errorCode,直接返回 fallback(如 snapshot.error || t('empty')) + if (rec && 'error' in rec && !rawText && !rec.errorCode && rec.ok !== false && rec.success !== false) { + return fallback + } + + const locale = getLocale() + const dict = HOST_ERROR_CODE_MESSAGES[locale] ?? HOST_ERROR_CODE_MESSAGES['en-US'] + + if (codeMap) { + if (hostCode && codeMap[hostCode]) return codeMap[hostCode] + if (code && codeMap[code]) return codeMap[code] + } + + if (hostCode && dict[hostCode]) { + if (!rawText || !isDisplayableInCurrentLocale(rawText)) return dict[hostCode] + } + if (code && dict[code]) { + if (!rawText || !isDisplayableInCurrentLocale(rawText)) return dict[code] + } + + if (rawText && isDisplayableInCurrentLocale(rawText)) { + return rawText + } + + return fallback +} diff --git a/extensions/browser-history/src/history-client.ts b/extensions/browser-history/src/history-client.ts new file mode 100644 index 00000000..070f126c --- /dev/null +++ b/extensions/browser-history/src/history-client.ts @@ -0,0 +1,271 @@ +import { LocalStorage, getLocale } from '@ztools/declarative-ui' +import { resolveErrorMessage } from './error-i18n.js' +import { t } from './i18n.js' +import type { + HistoryBrowser, + HistoryItem, + HistoryPermissionWarning, + HistoryQueryParams, + HistoryQueryResponse, + HostPlatform +} from './types.js' + +export const PRIVACY_CONSENT_STORAGE_KEY = 'browser_history_privacy_consent_v1' +const SUPPORTED_BROWSERS: readonly HistoryBrowser[] = ['chrome', 'edge', 'brave', 'arc', 'firefox', 'safari'] + +interface HostBridge { + transport?: { + methods?: Record< + string, + (req: { + messageId: string + params: Record + timeoutMs?: number + }) => Promise<{ success?: boolean; data?: unknown; error?: { code?: string; message?: string } }> + > + } +} + +let reqSeq = 0 +function nextId(prefix = 'bh'): string { + reqSeq = (reqSeq + 1) % 1_000_000 + return `${prefix}_${Date.now()}_${reqSeq}` +} + +function isObject(value: unknown): value is Record { + return Boolean(value && typeof value === 'object' && !Array.isArray(value)) +} + +/** 识别当前宿主平台(用于按平台显示 Safari 选项) */ +export function detectPlatform(nav?: { platform?: string; userAgent?: string }): HostPlatform { + const source = nav ?? (typeof navigator !== 'undefined' ? navigator : undefined) + const text = `${source?.platform ?? ''} ${source?.userAgent ?? ''}`.toLowerCase() + if (text.includes('mac')) return 'mac' + if (text.includes('win')) return 'windows' + return 'unknown' +} + +export function browserFilterOptions(platform: HostPlatform): ReadonlyArray { + const all: ReadonlyArray = [ + ['chrome', 'Chrome'], + ['edge', 'Edge'], + ['brave', 'Brave'], + ['arc', 'Arc'], + ['firefox', 'Firefox'], + ['safari', 'Safari'] + ] + if (platform === 'windows') { + return all.filter(([id]) => id !== 'safari') + } + return all +} + +/** 严格协议白名单校验:仅放行 http:// 与 https:// */ +export function isSafeHttpUrl(rawUrl: string): boolean { + if (typeof rawUrl !== 'string' || !rawUrl.trim()) return false + try { + const parsed = new URL(rawUrl) + return parsed.protocol === 'http:' || parsed.protocol === 'https:' + } catch { + return false + } +} + +/** 检测 URL 是否内嵌账号或密码(含凭据的链接禁止直接调起系统浏览器) */ +export function hasUrlCredentials(rawUrl: string): boolean { + try { + const parsed = new URL(rawUrl) + return Boolean(parsed.username || parsed.password) + } catch { + return false + } +} + +/** 构造安全转义后的 Markdown 链接 */ +export function formatHistoryMarkdown(item: Pick): string { + const safeTitle = item.title + .replace(/[\r\n]+/g, ' ') + .replace(/[\\[\]<>]/g, (ch) => `\\${ch}`) + const safeUrl = item.url.replace(/>/g, '%3E').replace(/\s/g, '%20') + return `[${safeTitle}](<${safeUrl}>)` +} + +/** 格式化本地访问时间 */ +export function formatVisitedAt(visitedAt: number | null | undefined): string { + if (typeof visitedAt !== 'number' || !Number.isFinite(visitedAt) || visitedAt <= 0) { + return t('timeUnknown') + } + try { + return new Intl.DateTimeFormat(getLocale(), { + month: '2-digit', + day: '2-digit', + hour: '2-digit', + minute: '2-digit' + }).format(new Date(visitedAt)) + } catch { + return new Date(visitedAt).toISOString().slice(0, 16).replace('T', ' ') + } +} + +/** 检测告警中是否包含 macOS Safari 完全磁盘访问权限受限 */ +export function hasSafariPermissionWarning(warnings: readonly HistoryPermissionWarning[]): boolean { + return warnings.some( + (w) => w.browser === 'safari' && (w.code === 'FULL_DISK_ACCESS_REQUIRED' || w.code === 'PERMISSION_DENIED') + ) +} + +/** 读取用户首次隐私告知确认态 */ +export async function readPrivacyConsent(): Promise { + const stored = await LocalStorage.getItem(PRIVACY_CONSENT_STORAGE_KEY) + return stored === 'accepted' || stored === true +} + +/** 持久化用户隐私告知确认态 */ +export async function savePrivacyConsent(accepted: boolean): Promise { + if (accepted) { + await LocalStorage.setItem(PRIVACY_CONSENT_STORAGE_KEY, 'accepted') + } else { + await LocalStorage.removeItem(PRIVACY_CONSENT_STORAGE_KEY) + } +} + +/** 校验并净化宿主返回的浏览器历史查询结果(严禁放行非法协议与畸形数据) */ +export function validateHistoryResponse(raw: unknown): HistoryQueryResponse { + if (!isObject(raw) || raw.success !== true || !Array.isArray(raw.items)) { + throw new Error(t('invalidHostResult')) + } + const items: HistoryItem[] = [] + const seenIds = new Set() + for (const entry of raw.items) { + if (!isObject(entry)) continue + const id = typeof entry.id === 'string' && entry.id.trim() ? entry.id.trim() : '' + const url = typeof entry.url === 'string' ? entry.url : '' + const browser = entry.browser as HistoryBrowser + const visitedAt = Number(entry.visitedAt) + const visitCount = Number(entry.visitCount) + if (!id || seenIds.has(id) || !SUPPORTED_BROWSERS.includes(browser) || !isSafeHttpUrl(url)) { + continue + } + if (!Number.isFinite(visitedAt) || visitedAt <= 0) continue + seenIds.add(id) + const parsed = new URL(url) + const title = typeof entry.title === 'string' && entry.title.trim() ? entry.title.trim() : parsed.hostname + const browserLabel = + typeof entry.browserLabel === 'string' && entry.browserLabel.trim() ? entry.browserLabel.trim() : browser + const profile = typeof entry.profile === 'string' && entry.profile.trim() ? entry.profile.trim() : 'Default' + items.push({ + id, + title, + url, + hostname: parsed.hostname, + browser, + browserLabel, + profile, + visitedAt, + visitCount: Number.isFinite(visitCount) && visitCount >= 0 ? Math.floor(visitCount) : 1 + }) + } + + const warnings = Array.isArray(raw.warnings) + ? raw.warnings.filter((w): w is string => typeof w === 'string' && w.trim().length > 0) + : [] + + const permissionWarnings: HistoryPermissionWarning[] = [] + if (Array.isArray(raw.permissionWarnings)) { + for (const w of raw.permissionWarnings) { + if (!isObject(w)) continue + const browser = w.browser as HistoryBrowser + if (!SUPPORTED_BROWSERS.includes(browser)) continue + const code = typeof w.code === 'string' ? w.code : 'READ_ERROR' + const validCode = + code === 'FULL_DISK_ACCESS_REQUIRED' || + code === 'PERMISSION_DENIED' || + code === 'DATABASE_CORRUPT' || + code === 'DATABASE_BUSY' || + code === 'READ_ERROR' + ? code + : 'READ_ERROR' + permissionWarnings.push({ + browser, + browserLabel: typeof w.browserLabel === 'string' && w.browserLabel ? w.browserLabel : browser, + profile: typeof w.profile === 'string' && w.profile ? w.profile : 'Default', + code: validCode, + message: typeof w.message === 'string' ? w.message : '', + ...(typeof w.guidance === 'string' && w.guidance ? { guidance: w.guidance } : {}) + }) + } + } + + const browsersDetected = Array.isArray(raw.browsersDetected) + ? raw.browsersDetected.filter((b): b is HistoryBrowser => SUPPORTED_BROWSERS.includes(b as HistoryBrowser)) + : [] + + const sourcesRead = + typeof raw.sourcesRead === 'number' && Number.isSafeInteger(raw.sourcesRead) && raw.sourcesRead >= 0 + ? raw.sourcesRead + : 0 + const totalMatched = + typeof raw.totalMatched === 'number' && Number.isSafeInteger(raw.totalMatched) && raw.totalMatched >= 0 + ? raw.totalMatched + : items.length + + return { + items, + totalMatched, + sourcesRead, + browsersDetected, + warnings, + permissionWarnings + } +} + +async function callHost( + method: string, + params: Record, + timeoutMs = 20000 +): Promise { + const bridge = (globalThis as unknown as { __ztoolsElectron?: HostBridge }).__ztoolsElectron + const fn = bridge?.transport?.methods?.[method] + if (typeof fn !== 'function') { + throw new Error(t('upgradeClientRequired')) + } + const response = await fn({ messageId: nextId(method.slice(0, 16)), params, timeoutMs }) + if (!isObject(response) || response.success !== true) { + const errMsg = resolveErrorMessage(response?.error ?? response, t('readFailedFallback')) + const err = new Error(errMsg) as Error & { code?: string } + if (isObject(response?.error) && typeof response.error.code === 'string') { + err.code = response.error.code + } + throw err + } + return response.data +} + +/** 调用宿主 `browser_history_query`(支持 AbortSignal 自动发送取消通知) */ +export async function queryBrowserHistory( + params: HistoryQueryParams, + signal?: AbortSignal +): Promise { + const operationId = nextId('hist') + const onAbort = () => { + void callHost('browser_history_cancel', { operationId }, 5000).catch(() => { + // 取消通知失败不影响已中止的前端态 + }) + } + signal?.addEventListener('abort', onAbort, { once: true }) + try { + const raw = await callHost('browser_history_query', { + operationId, + query: params.query, + browser: params.browser, + timeRange: params.timeRange, + limit: params.limit ?? 200 + }) + if (signal?.aborted) { + throw new Error('CANCELLED') + } + return validateHistoryResponse(raw) + } finally { + signal?.removeEventListener('abort', onAbort) + } +} diff --git a/extensions/browser-history/src/i18n.ts b/extensions/browser-history/src/i18n.ts new file mode 100644 index 00000000..09d7483d --- /dev/null +++ b/extensions/browser-history/src/i18n.ts @@ -0,0 +1,127 @@ +import { createTranslator } from '@ztools/declarative-ui' + +const MESSAGES = { + 'zh-CN': { + navTitle: '浏览器历史记录', + consentNavTitle: '隐私告知与只读访问说明', + consentMarkdown: + '# 本地浏览器历史记录只读访问告知\n\n' + + '使用本插件前,请确认您了解以下隐私与安全边界:\n\n' + + '- **读取范围**:仅在您主动打开或搜索时,只读查询本机已安装浏览器(Chrome、Edge、Brave、Arc、Firefox、macOS Safari)的历史访问记录数据库。\n' + + '- **数据安全**:查询过程仅复制只读临时副本并立即销毁,**不会修改**任何浏览器数据文件。\n' + + '- **本地运行**:全部检索与筛选均在本地完成,**不会上传**您的浏览历史至任何远程服务器。\n' + + '- **随时撤销**:您可随时在动作面板中撤销本地同意状态。', + consentAccept: '我已知晓并开启只读检索', + consentMetaScopeLabel: '读取方式', + consentMetaScopeValue: '仅本机只读临时副本', + consentMetaUploadLabel: '数据上传', + consentMetaUploadValue: '不上传、不持久化同步', + consentMetaBrowsersLabel: '支持浏览器', + consentMetaBrowsersValue: 'Chrome / Edge / Brave / Arc / Firefox / Safari', + revokeConsent: '撤销隐私授权提示', + consentRevokedToast: '已重置隐私告知状态', + searchPlaceholder: '搜索标题、网址或输入 domain:example.com 限定域名…', + browserFilterTooltip: '按浏览器筛选', + allBrowsers: '全部浏览器', + timeRangeLabel: '时间范围', + range24h: '24 小时', + range7d: '7 天', + range30d: '30 天', + rangeAll: '全部', + refreshAction: '刷新', + detailsAction: '告警详情', + detailsNavTitle: '浏览器历史读取告警详情', + summaryLoading: '正在只读检索本机浏览器历史…', + summaryFailed: '读取失败', + summaryPartial: '部分来源受限 · ', + summaryResult: '{prefix}共 {total} 条匹配,显示 {visible} 条', + openInBrowser: '打开网页', + copyUrlWithCredentials: '复制链接(含登录凭据,禁止直接打开)', + copyUrl: '复制链接', + copyMarkdownLink: '复制 Markdown 链接', + copyTitle: '复制标题', + copySafariGuide: '复制 Safari 完全磁盘访问指引', + safariGuideText: + '打开“系统设置 > 隐私与安全性 > 完全磁盘访问权限”,为 ZTools 开启权限后重启 ZTools 再刷新历史记录。', + safariWarningPrefix: 'Safari 权限提示:', + visitCountSuffix: '次访问', + timeUnknown: '时间未知', + emptyLoadingTitle: '正在检索历史记录…', + emptyFailedTitle: '无法读取浏览器历史记录', + emptySafariTitle: 'Safari 历史记录需要“完全磁盘访问权限”', + emptySafariSubtitle: '请在系统设置中为 ZTools 开启完全磁盘访问权限后重新打开客户端并刷新', + emptyNoMatchTitle: '没有匹配的历史记录', + emptyNoMatchSubtitle: '尝试更换关键词、放宽时间范围或切换为全部浏览器', + emptyNoDataTitle: '未发现可读的浏览器历史记录', + emptyNoDataSubtitle: '仅展示本机已安装浏览器中的 HTTP / HTTPS 网页访问记录', + readFailedTitle: '历史记录读取失败', + readFailedFallback: '读取本机浏览器历史记录失败', + upgradeClientRequired: '当前客户端版本暂不支持浏览器历史记录接口,请升级 ZTools 客户端后重试', + invalidHostResult: '客户端返回的历史记录数据格式无效', + unsafeUrlBlocked: '已拦截非 HTTP/HTTPS 协议或非法链接', + copiedTitle: '已复制到剪贴板' + }, + 'en-US': { + navTitle: 'Browser History', + consentNavTitle: 'Privacy Notice & Read-Only Access', + consentMarkdown: + '# Local Browser History Read-Only Notice\n\n' + + 'Before using this extension, please review the privacy and security boundaries:\n\n' + + '- **Scope**: Reads browsing history databases only when you open or search locally installed browsers (Chrome, Edge, Brave, Arc, Firefox, and Safari on macOS).\n' + + '- **Read-Only Isolation**: Queries run against temporary read-only snapshots that are removed immediately; browser files are **never modified**.\n' + + '- **Local Only**: All searching and filtering run locally on your device; **nothing is uploaded**.\n' + + '- **Revocable**: You can reset this notice at any time from the action panel.', + consentAccept: 'Acknowledge & Enable Read-Only Search', + consentMetaScopeLabel: 'Access Mode', + consentMetaScopeValue: 'Local read-only temporary snapshot', + consentMetaUploadLabel: 'Cloud Upload', + consentMetaUploadValue: 'None (100% local)', + consentMetaBrowsersLabel: 'Supported Browsers', + consentMetaBrowsersValue: 'Chrome / Edge / Brave / Arc / Firefox / Safari', + revokeConsent: 'Reset Privacy Notice', + consentRevokedToast: 'Privacy notice has been reset', + searchPlaceholder: 'Search title, URL, or use domain:example.com…', + browserFilterTooltip: 'Filter by browser', + allBrowsers: 'All Browsers', + timeRangeLabel: 'Time Range', + range24h: '24h', + range7d: '7d', + range30d: '30d', + rangeAll: 'All', + refreshAction: 'Refresh', + detailsAction: 'Warnings', + detailsNavTitle: 'History Read Warnings', + summaryLoading: 'Querying local browser history…', + summaryFailed: 'Query failed', + summaryPartial: 'Some sources restricted · ', + summaryResult: '{prefix}{total} matched, showing {visible}', + openInBrowser: 'Open in Browser', + copyUrlWithCredentials: 'Copy URL (contains credentials, cannot open directly)', + copyUrl: 'Copy URL', + copyMarkdownLink: 'Copy Markdown Link', + copyTitle: 'Copy Title', + copySafariGuide: 'Copy Safari Full Disk Access Guide', + safariGuideText: + 'Open System Settings > Privacy & Security > Full Disk Access, enable ZTools, reopen ZTools, and refresh.', + safariWarningPrefix: 'Safari Permission: ', + visitCountSuffix: 'visits', + timeUnknown: 'Unknown time', + emptyLoadingTitle: 'Searching browser history…', + emptyFailedTitle: 'Failed to Read Browser History', + emptySafariTitle: 'Safari History Requires Full Disk Access', + emptySafariSubtitle: 'Grant Full Disk Access to ZTools in System Settings, reopen ZTools, and refresh', + emptyNoMatchTitle: 'No Matching History Entries', + emptyNoMatchSubtitle: 'Try another keyword, widen the time range, or switch to All Browsers', + emptyNoDataTitle: 'No Readable Browser History Found', + emptyNoDataSubtitle: 'Only displays local HTTP / HTTPS history entries from detected browsers', + readFailedTitle: 'History Query Failed', + readFailedFallback: 'Failed to read local browser history', + upgradeClientRequired: 'Your ZTools client does not support browser history queries yet. Please update ZTools.', + invalidHostResult: 'Invalid browser history payload returned by host', + unsafeUrlBlocked: 'Blocked non-HTTP/HTTPS or invalid URL', + copiedTitle: 'Copied to Clipboard' + } +} as const + +export const DEFAULT_MESSAGES = MESSAGES['zh-CN'] +export const t = createTranslator(MESSAGES, { defaultLocale: 'en-US' }) diff --git a/extensions/browser-history/src/index.tsx b/extensions/browser-history/src/index.tsx new file mode 100644 index 00000000..4be539f8 --- /dev/null +++ b/extensions/browser-history/src/index.tsx @@ -0,0 +1,386 @@ +import React, { + Action, + ActionPanel, + Detail, + Icon, + List, + Toast, + showToast, + useEffect, + useLocale, + useNavigation, + useRef, + useState +} from '@ztools/declarative-ui' +import { resolveErrorMessage } from './error-i18n.js' +import { + browserFilterOptions, + detectPlatform, + formatHistoryMarkdown, + formatVisitedAt, + hasSafariPermissionWarning, + hasUrlCredentials, + isSafeHttpUrl, + queryBrowserHistory, + readPrivacyConsent, + savePrivacyConsent +} from './history-client.js' +import { t } from './i18n.js' +import type { + HistoryBrowserFilter, + HistoryItem, + HistoryPermissionWarning, + HistoryTimeRange, + HostPlatform +} from './types.js' + +export * from './types.js' +export * from './history-client.js' + +function escapeMarkdown(text: string): string { + return text.replace(/[\\`*_{}[\]()<>#!|]/g, (ch) => `\\${ch}`) +} + +export interface BrowserHistoryProps { + readonly initialTimeRange?: HistoryTimeRange + readonly initialBrowser?: HistoryBrowserFilter + readonly platform?: HostPlatform +} + +export default function BrowserHistoryCommand({ + initialTimeRange = '7d', + initialBrowser = 'all', + platform = detectPlatform() +}: BrowserHistoryProps = {}) { + useLocale() + const { push } = useNavigation() + + const [consentChecked, setConsentChecked] = useState(false) + const [consentAccepted, setConsentAccepted] = useState(false) + + const [query, setQuery] = useState('') + const [browser, setBrowser] = useState(initialBrowser) + const [timeRange, setTimeRange] = useState(initialTimeRange) + + const [items, setItems] = useState([]) + const [totalMatched, setTotalMatched] = useState(0) + const [warnings, setWarnings] = useState([]) + const [permissionWarnings, setPermissionWarnings] = useState([]) + const [loading, setLoading] = useState(false) + const [error, setError] = useState('') + + const mountedRef = useRef(true) + const abortRef = useRef(null) + const seqRef = useRef(0) + + // 启动时读取本地隐私告知确认态 + useEffect(() => { + mountedRef.current = true + void (async () => { + try { + const accepted = await readPrivacyConsent() + if (mountedRef.current) { + setConsentAccepted(accepted) + } + } catch { + if (mountedRef.current) { + setConsentAccepted(false) + } + } finally { + if (mountedRef.current) { + setConsentChecked(true) + } + } + })() + return () => { + mountedRef.current = false + abortRef.current?.abort() + } + }, []) + + const runQuery = async (nextQuery: string, nextBrowser: HistoryBrowserFilter, nextRange: HistoryTimeRange) => { + abortRef.current?.abort() + const controller = new AbortController() + abortRef.current = controller + const ticket = ++seqRef.current + + setLoading(true) + setError('') + + try { + const result = await queryBrowserHistory( + { + query: nextQuery, + browser: nextBrowser, + timeRange: nextRange, + limit: 200 + }, + controller.signal + ) + if (!mountedRef.current || ticket !== seqRef.current || controller.signal.aborted) return + setItems(result.items) + setTotalMatched(result.totalMatched) + setWarnings(result.warnings) + setPermissionWarnings(result.permissionWarnings) + } catch (failure) { + if (!mountedRef.current || ticket !== seqRef.current || controller.signal.aborted) return + const msg = resolveErrorMessage(failure, t('readFailedFallback')) + setError(msg) + await showToast({ style: Toast.Style.Failure, title: t('readFailedTitle'), message: msg }) + } finally { + if (mountedRef.current && ticket === seqRef.current) { + abortRef.current = null + setLoading(false) + } + } + } + + // 已同意隐私告知后,随检索参数变化触发防抖查询 + useEffect(() => { + if (!consentChecked || !consentAccepted) return + const timer = setTimeout(() => { + void runQuery(query, browser, timeRange) + }, query ? 120 : 0) + return () => clearTimeout(timer) + }, [consentChecked, consentAccepted, query, browser, timeRange]) + + const handleAcceptConsent = async () => { + try { + await savePrivacyConsent(true) + if (mountedRef.current) { + setConsentAccepted(true) + } + } catch (err) { + await showToast({ + style: Toast.Style.Failure, + title: t('readFailedTitle'), + message: resolveErrorMessage(err, t('readFailedFallback')) + }) + } + } + + const handleRevokeConsent = async () => { + abortRef.current?.abort() + await savePrivacyConsent(false) + if (!mountedRef.current) return + setConsentAccepted(false) + setItems([]) + setTotalMatched(0) + setWarnings([]) + setPermissionWarnings([]) + setError('') + await showToast({ style: Toast.Style.Success, title: t('consentRevokedToast') }) + } + + // 等待读取本地同意状态期间展示加载态 + if (!consentChecked) { + return ( + + + + ) + } + + // 首次使用:显式展示只读隐私告知,确认后持久化到 LocalStorage + if (!consentAccepted) { + return ( + + + + + + } + actions={ + + + + } + /> + ) + } + + const safariBlocked = hasSafariPermissionWarning(permissionWarnings) + const warningLines = [ + ...(error ? [error] : []), + ...permissionWarnings.map((w) => + w.guidance ? `${w.browserLabel} / ${w.profile}: ${w.message} (${w.guidance})` : `${w.browserLabel} / ${w.profile}: ${w.message}` + ), + ...warnings.filter((w) => !permissionWarnings.some((pw) => w.includes(pw.message))) + ] + + const openWarningsDetail = () => { + const safariBlock = safariBlocked ? `\n\n> ${t('safariWarningPrefix')}${escapeMarkdown(t('safariGuideText'))}` : '' + push( + `- ${escapeMarkdown(line)}`).join('\n') + safariBlock} + actions={ + + {safariBlocked && ( + + )} + void runQuery(query, browser, timeRange)} + /> + + } + /> + ) + } + + const summaryPrefix = warningLines.length > 0 ? t('summaryPartial') : '' + const summaryText = loading + ? t('summaryLoading') + : error && items.length === 0 + ? t('summaryFailed') + : t('summaryResult', { prefix: summaryPrefix, total: totalMatched, visible: items.length }) + + const showEmpty = !loading && items.length === 0 + const emptyTitle = error + ? t('emptyFailedTitle') + : safariBlocked && (browser === 'safari' || browser === 'all') + ? t('emptySafariTitle') + : query.trim() + ? t('emptyNoMatchTitle') + : t('emptyNoDataTitle') + const emptySubtitle = error + ? error + : safariBlocked && (browser === 'safari' || browser === 'all') + ? t('emptySafariSubtitle') + : query.trim() + ? t('emptyNoMatchSubtitle') + : t('emptyNoDataSubtitle') + + return ( + ({ value, label })) + ], + onChange: (value) => setBrowser(value as HistoryBrowserFilter) + }, + { + id: 'timeRange', + label: t('timeRangeLabel'), + value: timeRange, + options: [ + { value: '24h', label: t('range24h') }, + { value: '7d', label: t('range7d') }, + { value: '30d', label: t('range30d') }, + { value: 'all', label: t('rangeAll') } + ], + onChange: (value) => setTimeRange(value as HistoryTimeRange) + } + ], + actions: showEmpty + ? [] + : [ + { + id: 'refresh', + title: t('refreshAction'), + icon: Icon.ArrowClockwise, + onAction: () => void runQuery(query, browser, timeRange) + }, + ...(warningLines.length > 0 + ? [ + { + id: 'warnings', + title: t('detailsAction'), + icon: Icon.Info, + onAction: openWarningsDetail + } + ] + : []) + ] + }} + > + {items.map((item) => { + const allowOpen = isSafeHttpUrl(item.url) && !hasUrlCredentials(item.url) + return ( + + {allowOpen ? ( + + ) : ( + + )} + {allowOpen && ( + + )} + + + {safariBlocked && ( + + )} + + + } + /> + ) + })} + + {showEmpty && ( + + {safariBlocked && ( + + )} + void runQuery(query, browser, timeRange)} + /> + {warningLines.length > 0 && ( + + )} + + + } + /> + )} + + ) +} + +export const commands = { + 'history-all': () => , + 'history-today': () => +} diff --git a/extensions/browser-history/src/types.ts b/extensions/browser-history/src/types.ts new file mode 100644 index 00000000..05be8bf3 --- /dev/null +++ b/extensions/browser-history/src/types.ts @@ -0,0 +1,48 @@ +export type HistoryBrowser = 'chrome' | 'edge' | 'brave' | 'arc' | 'firefox' | 'safari' +export type HistoryBrowserFilter = 'all' | HistoryBrowser +export type HistoryTimeRange = '24h' | '7d' | '30d' | 'all' +export type HostPlatform = 'windows' | 'mac' | 'unknown' + +export interface HistoryItem { + readonly id: string + readonly title: string + readonly url: string + readonly hostname: string + readonly browser: HistoryBrowser + readonly browserLabel: string + readonly profile: string + readonly visitedAt: number + readonly visitCount: number +} + +export type HistoryWarningCode = + | 'FULL_DISK_ACCESS_REQUIRED' + | 'PERMISSION_DENIED' + | 'DATABASE_CORRUPT' + | 'DATABASE_BUSY' + | 'READ_ERROR' + +export interface HistoryPermissionWarning { + readonly browser: HistoryBrowser + readonly browserLabel: string + readonly profile: string + readonly code: HistoryWarningCode + readonly message: string + readonly guidance?: string +} + +export interface HistoryQueryResponse { + readonly items: readonly HistoryItem[] + readonly totalMatched: number + readonly sourcesRead: number + readonly browsersDetected: readonly HistoryBrowser[] + readonly warnings: readonly string[] + readonly permissionWarnings: readonly HistoryPermissionWarning[] +} + +export interface HistoryQueryParams { + readonly query: string + readonly browser: HistoryBrowserFilter + readonly timeRange: HistoryTimeRange + readonly limit?: number +} diff --git a/extensions/browser-history/tests/index.test.mjs b/extensions/browser-history/tests/index.test.mjs new file mode 100644 index 00000000..e01ff0bb --- /dev/null +++ b/extensions/browser-history/tests/index.test.mjs @@ -0,0 +1,166 @@ +import test from 'node:test' +import assert from 'node:assert/strict' +import { createHost, mount, tick } from '../../shared/test-harness.mjs' +import BrowserHistoryCommand, { + PRIVACY_CONSENT_STORAGE_KEY, + commands, + formatHistoryMarkdown, + isSafeHttpUrl, + validateHistoryResponse +} from '../dist/index.js' + +const host = createHost() +const views = [] + +const sampleItem = (overrides = {}) => ({ + id: 'chrome:abc:1', + title: 'ZTools 文档中心', + url: 'https://docs.ztools.dev/guide', + hostname: 'docs.ztools.dev', + browser: 'chrome', + browserLabel: 'Chrome', + profile: 'Default', + visitedAt: Date.UTC(2026, 4, 20, 9, 30, 0), + visitCount: 6, + ...overrides +}) + +const sampleReply = (items = [sampleItem()], extra = {}) => ({ + success: true, + items, + totalMatched: items.length, + sourcesRead: 1, + browsersDetected: ['chrome'], + warnings: [], + permissionWarnings: [], + ...extra +}) + +test.beforeEach(() => { + host.reset() + host.ipc.browser_history_query = async () => sampleReply() + host.ipc.browser_history_cancel = async () => ({ success: true, cancelRequested: true }) +}) + +test.afterEach(() => { + views.splice(0).forEach((v) => v.unmount()) +}) + +async function open(factory = commands['history-all']) { + const view = await mount(factory) + views.push(view) + await tick(30) + return view +} + +test('首次使用必须显式展示隐私告知,确认后持久化 LocalStorage 并开始只读检索', async () => { + const view = await open() + // 未同意前展示 Detail 隐私告知,严禁提前发起 browser_history_query + assert.equal(view.tree().type, 'Detail') + assert.equal(host.ipcCalls.filter(([m]) => m === 'browser_history_query').length, 0) + + const acceptAction = view.actions(view.tree())[0] + assert.match(acceptAction.props.title, /只读检索/) + await acceptAction.props.onAction() + await tick(40) + + assert.equal(host.storage.get(PRIVACY_CONSENT_STORAGE_KEY), JSON.stringify('accepted')) + assert.equal(view.tree().type, 'List') + assert.equal(view.tree().props.isShowingDetail, false) + assert.equal(view.items().length, 1) + assert.equal(view.items()[0].props.title, 'ZTools 文档中心') +}) + +test('已授权后支持关键词搜索、浏览器筛选、时间范围切换、打开与复制动作', async () => { + host.storage.set(PRIVACY_CONSENT_STORAGE_KEY, JSON.stringify('accepted')) + const queries = [] + host.ipc.browser_history_query = async (params) => { + queries.push(params) + return sampleReply([ + sampleItem(), + sampleItem({ + id: 'chrome:abc:2', + title: '带凭据内网页', + url: 'https://user:secret@intra.example.com/admin', + hostname: 'intra.example.com' + }) + ]) + } + + const view = await open() + assert.equal(view.items().length, 2) + + // 普通链接主动作是 Action.OpenInBrowser,次动作是复制链接 + const normalActions = view.actions(view.item('chrome:abc:1')) + assert.equal(normalActions[0].type, 'Action.OpenInBrowser') + assert.equal(normalActions[1].props.title, '复制链接') + await view.run(view.item('chrome:abc:1'), '复制链接') + assert.equal(host.clipboard.text, 'https://docs.ztools.dev/guide') + + // 含凭据链接禁止直接 OpenInBrowser,只提供复制 + const credActions = view.actions(view.item('chrome:abc:2')) + assert.ok(credActions.every((a) => a.type !== 'Action.OpenInBrowser')) + assert.match(credActions[0].props.title, /含登录凭据/) + + // 切换时间范围为 30d 并搜索关键词 + const rangeGroup = view.tree().props.filterBar.groups.find((g) => g.id === 'timeRange') + rangeGroup.onChange('30d') + await view.search('ztools') + await tick(180) + assert.ok(queries.some((q) => q.timeRange === '30d' && q.query === 'ztools')) +}) + +test('协议白名单过滤非法 URL,Safari 权限告警展示完全磁盘访问引导且无假数据', async () => { + assert.equal(isSafeHttpUrl('https://example.com'), true) + assert.equal(isSafeHttpUrl('javascript:alert(1)'), false) + assert.equal(isSafeHttpUrl('file:///etc/passwd'), false) + assert.equal( + formatHistoryMarkdown({ title: 'A [B]', url: 'https://example.com/x>y' }), + '[A \\[B\\]]()' + ) + + const validated = validateHistoryResponse( + sampleReply([ + sampleItem(), + sampleItem({ id: 'bad-proto', url: 'javascript:alert(1)' }) + ]) + ) + assert.equal(validated.items.length, 1) + + host.storage.set(PRIVACY_CONSENT_STORAGE_KEY, JSON.stringify('accepted')) + host.ipc.browser_history_query = async () => + sampleReply([], { + sourcesRead: 0, + browsersDetected: [], + warnings: ['Safari / Default: Safari history requires Full Disk Access permission on macOS.'], + permissionWarnings: [ + { + browser: 'safari', + browserLabel: 'Safari', + profile: 'Default', + code: 'FULL_DISK_ACCESS_REQUIRED', + message: 'Safari history requires Full Disk Access permission on macOS.', + guidance: 'System Settings > Privacy & Security > Full Disk Access' + } + ] + }) + + const view = await open(() => BrowserHistoryCommand({ platform: 'mac', initialBrowser: 'safari' })) + assert.equal(view.items().length, 1) + assert.equal(view.items()[0].props.id, 'empty') + assert.match(view.items()[0].props.title, /完全磁盘访问权限/) + const actions = view.actions(view.item('empty')) + assert.ok(actions.some((a) => a.props.title.includes('Safari'))) +}) + +test('宿主失败时如实报错且绝不生成示例假数据', async () => { + host.storage.set(PRIVACY_CONSENT_STORAGE_KEY, JSON.stringify('accepted')) + host.ipc.browser_history_query = async () => { + throw new Error('历史库读取超时') + } + const view = await open() + assert.equal(view.items().length, 1) + assert.equal(view.items()[0].props.id, 'empty') + assert.match(view.items()[0].props.title, /无法读取浏览器历史记录/) + assert.match(view.items()[0].props.subtitle, /历史库读取超时/) +}) diff --git a/extensions/browser-history/tsconfig.json b/extensions/browser-history/tsconfig.json new file mode 100644 index 00000000..b0bc7c48 --- /dev/null +++ b/extensions/browser-history/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ES2022", + "moduleResolution": "bundler", + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true, + "rootDir": "./src", + "outDir": "./dist", + "jsx": "react", + "jsxFactory": "React.createElement", + "jsxFragmentFactory": "React.Fragment" + }, + "include": ["src/**/*"] +} diff --git a/extensions/caffeine/README.en.md b/extensions/caffeine/README.en.md new file mode 100644 index 00000000..079a0af4 --- /dev/null +++ b/extensions/caffeine/README.en.md @@ -0,0 +1,20 @@ +# Keep Awake (Caffeine) + +Prevent your system from sleeping automatically for a set duration, with an option to keep the display awake as well. + +## Usage + +- Commands: Type `caffeine`, `keep awake`, or `prevent sleep` in the launcher to open the duration list; type `caffeine toggle` or `toggle awake` to open the plugin and immediately toggle keep-awake on or off (turning it on uses Indefinite duration and "Keep display on + prevent system sleep" mode). Keywords such as `enable awake` and `disable awake` also perform a toggle rather than forcing on or off. +- Available durations: Indefinite (until manually stopped), 15 minutes, 30 minutes, 1 hour, 2 hours, and 4 hours. Select an option and press `Enter` to activate. +- Select the mode from the top dropdown: "Keep display on + prevent system sleep" or "Allow display sleep, keep system awake". Changing the mode does not affect an active session and takes effect the next time you enable it. +- Once active, the status bar shows the remaining time. Pressing `Enter` ("Stop Keep Awake") on the active duration ends it early; if the active row is filtered out by search, "Stop Keep Awake" appears in the status bar. When status cannot be read, the reason and a "Retry Query" action are shown. +- Keep-awake requests are released upon expiration, manual stop, closing the plugin window, disabling or uninstalling the plugin, or quitting the client, restoring your normal system power settings. It does not block manual screen locking or lid-close sleep. + +## Platforms & Requirements + +- Supported: Windows, macOS +- Requires client version 1.1.8.5 or later. + +## Network & Data + +- Works offline; stores no data. diff --git a/extensions/caffeine/plugin.json b/extensions/caffeine/plugin.json index 58bfab70..4bce3115 100644 --- a/extensions/caffeine/plugin.json +++ b/extensions/caffeine/plugin.json @@ -1,7 +1,8 @@ { "id": "caffeine", "name": "防休眠常亮", - "version": "1.0.8", + "version": "1.0.9", + "minAppVersion": "1.1.8.0", "description": "阻止系统自动休眠与息屏,支持定时倒计时自动恢复与一键常亮切换", "author": "ZTools Team", "entry": "dist/index.js", @@ -64,7 +65,11 @@ "keep awake", "prevent sleep", "screen on", - "awake" + "awake", + "stay awake", + "no sleep", + "no lock", + "insomnia" ], "features": { "caffeine-panel": { @@ -100,5 +105,17 @@ { "path": "screenshots/02-action-panel.png" } + ], + "keywords": [ + "防休眠", + "常亮", + "不锁屏", + "屏幕常亮", + "防锁屏", + "防熄屏", + "保持唤醒", + "咖啡因", + "别休眠", + "不黑屏" ] } diff --git a/extensions/caffeine/src/native-ipc.ts b/extensions/caffeine/src/native-ipc.ts index 51576b99..13643277 100644 --- a/extensions/caffeine/src/native-ipc.ts +++ b/extensions/caffeine/src/native-ipc.ts @@ -174,11 +174,13 @@ function normalizeMethodResult(method: string, payload: DynamicBridge): DynamicB if (method === 'system_get_battery_status') { // 宿主约定 percent 超出 0-100(如 255)表示无电池或电量未知,不能改写成 100% + // 若宿主明确给出 hasBattery 布尔值,必须原样保留,仅在缺失时按合法电量推算 const rawPct = payload.percent - const hasBattery = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const validPct = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const hasBattery = typeof payload.hasBattery === 'boolean' ? payload.hasBattery : validPct return { ...payload, - percent: hasBattery ? rawPct : null, + percent: validPct ? rawPct : null, hasBattery } } @@ -489,6 +491,8 @@ export interface RealDirectoryScanResult extends Iterable approximate?: boolean /** 宿主实际遍历的条目数 */ visitedEntries?: number + /** 目录本身不存在(ENOENT) */ + missing?: boolean /** 读取失败的真实原因;已有文件仍可使用,但不能当作完整结果。 */ error?: string } @@ -497,6 +501,7 @@ interface ScanResultMeta { truncated?: boolean approximate?: boolean visitedEntries?: number + missing?: boolean } export interface ScanDirectoryTreeOptions { @@ -504,6 +509,10 @@ export interface ScanDirectoryTreeOptions { maxFiles?: number collectTopN?: number filterExt?: RegExp + /** 为 true 时,目录本身不存在(ENOENT)按空目录处理,不返回 error(权限拒绝/读取失败仍照常报错) */ + ignoreMissing?: boolean + /** Top-N 保留与排序方式:默认按体积降序,下载/录屏等时效场景可传 mtime-desc */ + sortBy?: 'size-desc' | 'mtime-desc' hostOverride?: DynamicBridge } @@ -519,8 +528,9 @@ function normalizeIndexedFileEntry(f: DynamicBridge): RealIndexedFileEntry { const sz = Number(f?.size ?? f?.sizeBytes ?? 0) const isDir = Boolean(f?.is_dir || f?.isDir || f?.isDirectory) const rawMtime = Number(f?.mtime ?? f?.mtimeMs ?? 0) - const mtimeMs = rawMtime > 1e11 ? rawMtime : rawMtime > 0 ? rawMtime * 1000 : Date.now() - const mtimeSec = rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime + const validMtime = Number.isFinite(rawMtime) && rawMtime > 0 + const mtimeMs = validMtime ? (rawMtime > 1e11 ? rawMtime : rawMtime * 1000) : 0 + const mtimeSec = validMtime ? (rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime) : 0 if (p && sz >= 0) realFileSizeCache.set(p, sz) return { name, @@ -551,6 +561,7 @@ function makeScanResult( subdirs, ...(meta.truncated ? { truncated: true } : {}), ...(meta.approximate ? { approximate: true } : {}), + ...(meta.missing ? { missing: true } : {}), ...(typeof meta.visitedEntries === 'number' ? { visitedEntries: meta.visitedEntries } : {}), [Symbol.iterator]() { return files[Symbol.iterator]() @@ -609,13 +620,40 @@ export async function scanRealDirectoryTree( return result.error ? { ...result.scan, error: result.error } : result.scan } +/** 仅当正则明确声明了扩展名(含 `\.`)时提取后缀列表,避免把 `thumbcache|iconcache` 等文件名关键词误拆成假扩展名 */ +function extractExtensionTokensFromFilter(filterExt: RegExp): string[] { + const src = filterExt.source + if (!src.includes('\\.')) return [] + const afterDot = src.slice(src.indexOf('\\.') + 2) + const rawTokens = afterDot.match(/[a-z0-9]{1,8}/gi) || [] + const seen = new Set() + const out: string[] = [] + for (const token of rawTokens) { + const lower = token.toLowerCase() + if (!lower || seen.has(lower)) continue + seen.add(lower) + out.push(lower) + } + return out +} + +function isMissingDirectoryError(res: { error?: string; errorCode?: string; errorDetails?: Record }): boolean { + if (res.errorDetails?.reason === 'ENOENT' || res.errorCode === 'ENOENT') return true + const msg = String(res.error || '') + return /Directory does not exist|ENOENT/i.test(msg) +} + /** 一次界面扫描的错误汇总;多个目录并行扫描时保留可读目录的结果。 */ export function createDirectoryScanner(hostOverride?: DynamicBridge) { const failures = new Map() return { async scan(dir: string, options: number | ScanDirectoryTreeOptions = 160) { const result = await scanRealDirectoryTree(dir, options, hostOverride) - const error = result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') + const ignoreMissing = typeof options === 'object' && options !== null && options.ignoreMissing === true + const error = + result.missing && ignoreMissing + ? '' + : result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') if (error) failures.set(dir, error) else failures.delete(dir) return result @@ -648,26 +686,38 @@ async function scanDirectoryTreeWithError( const safeLimit = Math.min(200, Math.max(1, Math.floor(rawLimit || 160))) const hostOverride = opts.hostOverride const filterExt = opts.filterExt + const ignoreMissing = opts.ignoreMissing === true const dirQuery = `dir:${targetDir}` try { let rawPayload: DynamicBridge = null + const searchParams: Record = { + query: dirQuery, + limit: safeLimit, + ...(opts.sortBy ? { sortBy: opts.sortBy } : {}) + } const res = await callHostTransport( 'system_search_files', - { query: dirQuery, limit: safeLimit }, + searchParams, hostOverride ) - if (res.ok && res.data) { + if (res.ok && res.data && res.data.degraded !== true) { rawPayload = res.data + } else if (!res.ok && ignoreMissing && isMissingDirectoryError(res)) { + const missingScan = makeScanResult([], 0, 0, [], { missing: true }) + return { scan: missingScan } } - if (!rawPayload && !hostOverride && typeof window !== 'undefined') { + if (!rawPayload && !hostOverride && res.errorCode === 'METHOD_NOT_AVAILABLE' && typeof window !== 'undefined') { const w = window as DynamicBridge if (typeof w.__ztoolsLauncher?.searchFiles === 'function') { const rawOuter = await w.__ztoolsLauncher.searchFiles(dirQuery, safeLimit) - rawPayload = + const candidate = rawOuter && typeof rawOuter === 'object' && 'data' in rawOuter && rawOuter.data ? rawOuter.data : rawOuter + if (candidate && candidate.degraded !== true && candidate.success !== false) { + rawPayload = candidate + } } } @@ -678,29 +728,32 @@ async function scanDirectoryTreeWithError( let files: RealIndexedFileEntry[] = rawPayload.files.map(normalizeIndexedFileEntry) if (filterExt instanceof RegExp) { files = files.filter(f => !f.isDir && (filterExt.test(f.name) || filterExt.test(f.ext))) - // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索目标扩展名 + // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索明确声明的目标扩展名 if (files.length === 0 && !hostOverride) { - const extTokens = (filterExt.source.match(/[a-z0-9]{2,5}/gi) || []) - .filter(t => !['thumbcache', 'iconcache'].includes(t.toLowerCase())) - .slice(0, 4) - // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 - const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() - const extraLists = await Promise.all( - extTokens.map(ext => searchRealIndexedFiles(`.${ext.toLowerCase()}`, 30, hostOverride)) - ) - const seen = new Set() - for (const list of extraLists) { - for (const item of list) { - if (!item.isDir && item.size > 0 && !seen.has(item.path)) { - if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { - seen.add(item.path) - files.push(item) + const extTokens = extractExtensionTokensFromFilter(filterExt) + if (extTokens.length > 0) { + // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 + const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() + const extraLists = await Promise.all( + extTokens.map(ext => searchRealIndexedFiles(`.${ext}`, 30, hostOverride)) + ) + const seen = new Set() + for (const list of extraLists) { + for (const item of list) { + if (!item.isDir && item.size > 0 && !seen.has(item.path)) { + if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { + seen.add(item.path) + files.push(item) + } } } } } } } + // 先基于过滤后的完整命中集合计算总文件数与总字节数,再按 collectTopN 裁剪样本列表 + const matchedCount = files.length + const matchedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) if (typeof opts.collectTopN === 'number' && opts.collectTopN > 0 && files.length > opts.collectTopN) { files = files.slice(0, opts.collectTopN) } @@ -714,11 +767,10 @@ async function scanDirectoryTreeWithError( ...(s.approximate === true ? { approximate: true } : {}) })) : [] - const computedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) const totalFilesCount = - filterExt instanceof RegExp ? files.length : Number(rawPayload.total_matches ?? files.length) + filterExt instanceof RegExp ? matchedCount : Number(rawPayload.total_matches ?? matchedCount) const totalBytesCount = - filterExt instanceof RegExp ? computedBytes : Number(rawPayload.total_bytes ?? computedBytes) + filterExt instanceof RegExp ? matchedBytes : Number(rawPayload.total_bytes ?? matchedBytes) const visited = Number(rawPayload.visited_entries) return { scan: makeScanResult(files, totalFilesCount, totalBytesCount, subdirs, { @@ -1817,8 +1869,6 @@ export async function writeRealClipboardText(text: string, hostOverride?: Dynami const payload = { text: String(text || '') } const res = await callHostTransport('clipboard_copy_text', payload, hostOverride) if (res.ok) return true - const fallbackRes = await callHostTransport('clipboard_write_text', payload, hostOverride) - if (fallbackRes.ok) return true try { if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) { await navigator.clipboard.writeText(String(text || '')) diff --git a/extensions/calculator/README.en.md b/extensions/calculator/README.en.md new file mode 100644 index 00000000..0ff423f6 --- /dev/null +++ b/extensions/calculator/README.en.md @@ -0,0 +1,48 @@ +# Calculator + +Evaluate expressions as you type with built-in scientific functions, unit conversion across 9 categories (length, mass, area, volume, speed, angle, data storage, energy, temperature, including traditional Chinese units) and base conversion, live exchange rates (supporting 15 major fiat currencies plus gold and Bitcoin), date math, color value inspection, and two-way Chinese RMB uppercase / Chinese numeral conversion. + +## Usage + +- Commands: Main Calculator, Unit Converter (`unit convert`, `area convert`), Currency Converter (`exchange rate`, `currency`), and RMB Uppercase & Chinese Numerals (`rmb uppercase`, `chinese numerals`). Search for `calc`, `calculator`, `unit convert`, `exchange rate`, or `rmb uppercase` in the launcher to open. +- Expression and inline conversion examples: + - Math: `128 * 4 + 16`, `2 ^ 16`, `sqrt(65536)`, `sin(pi / 2)` (trigonometric functions use radians). + - Unit & base conversion: `10km to miles`, `1 acre to m2`, `100 km/h to mph`, `180 deg to rad`, `1 kwh to kj`, `1e3 m to km`, `32px to rem`, `255 to hex`, `now + 2 weeks`. Converting between different unit types (such as `5 kg to m`) reports a clear error. + - Storage units: `kb`, `mb`, `gb`, `tb` use the Windows-style 1024 base (same as `kib`, `mib`); spell out decimal units, e.g. `1 gigabyte to megabytes`. + - Inline live exchange rates: Type `100 usd to cny`, `5000 jpy to rmb`, `1 xau to usd`, or `0.5 btc to usd` directly in the main calculator for instant conversion. + - Color inspection: Enter `#3B82F6` or `rgb(59, 130, 246)` to list HEX, RGB, HSL, and CMYK representations along with contrast ratios. +- Unit converter board (**Unit Converter Board...** in the calculator action panel, or pick a category in the `unit convert` command; press `⌘/Ctrl+R` on a conversion result to open it with the current value and unit): + - Switch among 9 categories from the dropdown to list the value in every unit of that category, labeled by measurement system (metric, US/imperial, Chinese, etc.). + - Enter a number, scientific notation, or an expression (`3*12`); typing `5 kg` switches the category and base unit directly. + - Copy each row with or without the unit, copy the conversion equation, set it as the base unit (`⌘/Ctrl+B`), and adjust 0–10 decimal places from the action panel. +- RMB uppercase & Chinese numerals (`rmb uppercase` command or **RMB Uppercase...** in the calculator action panel; press `⌘/Ctrl+U` on a plain numeric result to bring it in): + - Arabic numbers produce invoice-grade RMB uppercase, Chinese financial uppercase, and everyday Chinese numerals at once. + - Chinese numerals convert back to digits, including uppercase, lowercase, invoice amounts, negatives, decimals, digit-by-digit writing, and colloquial shorthand (the standard reading is shown for verification). + - Invoice rules can be toggled from the action panel or the rules section: the Renminbi prefix, yuan character variant, whole-amount suffix variant, whether amounts below one yuan start with zero yuan, and cent handling (exact to the cent by default with an error beyond two decimals; switch to round half up or truncate). The integer part supports up to 16 digits. +- Main calculator shortcuts: `Enter` copies the result and saves it to history; `⌘/Ctrl+Enter` pastes into the active window; `⌘/Ctrl+E` fills the result back into the input box for further calculation; `⌘/Ctrl+K` opens the action panel. +- Multi-currency board (`exchange rate` command, or select **Currency Converter...** in the calculator action panel): + - Choose the default source currency from the dropdown on the right side of the search box (defaults to CNY), then enter an amount (such as `100`, `100 USD`, or `100 USD to CNY`) to view converted amounts and inverse rates across target currencies at once. Type a currency code or name (such as `JPY`, `gold`, or `bitcoin`) to filter. + - Select a currency and press `Enter` to copy the converted amount, `⌘/Ctrl+Enter` to copy the conversion equation, or `⌘/Ctrl+D` to pin favorite currencies to the top. You can also choose "Use as Source Currency" to fill the converted value back in for chained calculations. +- Main calculator shortcuts: `Enter` copies the result and saves it to history; `⌘/Ctrl+Enter` pastes into the active window; `⌘/Ctrl+E` fills the result back into the input box for further calculation; `⌘/Ctrl+K` opens the action panel. +- Date math: When a target month lacks the day (such as `2026-01-31 + 1 month`), the last day of that month (`2026-02-28`) is used. Hours and minutes are calculated by elapsed time; local timestamps skipped by Daylight Saving Time report that the time does not exist. +- Does not use `eval`; syntax errors, division by zero, and overflows display clear error messages instead of fabricated results. +- Calculation history keeps up to the most recent 100 entries (pinned items are not counted toward the limit), and the list displays the most recent 15. + +## Platforms & Requirements + +- Supported: Windows, macOS +- Built into the client; no separate installation required. + +## Network & Data + +Only when currency conversion is triggered does the client send two read-only GET requests (standard arithmetic, unit conversion, date math, and color inspection are completely offline). Amounts and currencies are converted locally and never sent to any external service: + +| Domain | Request URL | Purpose | +| --- | --- | --- | +| `open.er-api.com` | `https://open.er-api.com/v6/latest/USD` | Fetch USD-based fiat exchange rate table (ExchangeRate-API, updated daily) | +| `api.coingecko.com` | `https://api.coingecko.com/api/v3/simple/price?ids=bitcoin,tether-gold&vs_currencies=usd` | Fetch USD prices for Bitcoin and gold (Tether Gold, 1 troy ounce) | + +- Exchange rates are cached locally; reusing them within 30 minutes reads from the cache with a timestamp label, and refreshes online automatically after 30 minutes. +- If fetching fiat exchange rates fails, the error is shown as-is and estimated or sample data is never substituted. If real cached data from within the last 7 days exists locally, it falls back to that cache and clearly marks "Refresh Failed" along with the cache timestamp in the status bar/subtitle. +- If gold or Bitcoin prices fail to load, those items show "Quote unavailable" while other fiat rates remain usable. +- Calculation history, default source currency, and pinned currencies are stored only in local plugin storage; if reading fails, existing data will not be overwritten. diff --git a/extensions/calculator/README.md b/extensions/calculator/README.md index 614cb1d8..aca2751a 100644 --- a/extensions/calculator/README.md +++ b/extensions/calculator/README.md @@ -1,20 +1,29 @@ # 计算器 -输入算式即时出结果,内置科学函数、单位与进制换算、实时汇率换算(支持 15 种主流法币及黄金、比特币)、日期推算、颜色值检测以及人民币大写金额转换。 +输入算式即时出结果,内置科学函数、9 大类单位换算(长度、质量、面积、体积、速度、角度、数据存储、功与能量、温度,含斤、两、亩等市制单位)与进制换算、实时汇率换算(支持 15 种主流法币及黄金、比特币)、日期推算、颜色值检测,以及人民币大写与中文数字双向转换。 ## 使用 -- 命令:主计算器、单位换算(`calc-unit`)、汇率换算(`calc-currency`)、人民币大写金额转换(`calc-rmb`);可输入 `计算器`、`单位换算`、`汇率`、`exchange rate`、`大写金额` 等关键词打开。 +- 命令:主计算器、单位换算(`calc-unit`)、汇率换算(`calc-currency`)、人民币大写与中文数字(`calc-rmb`);可输入 `计算器`、`单位换算`、`面积换算`、`汇率`、`exchange rate`、`大写金额`、`中文数字` 等关键词打开。 - 算式与内联换算示例: - 数学计算:`128 * 4 + 16`、`2 ^ 16`、`sqrt(65536)`、`sin(pi / 2)`(三角函数按弧度计算)。 - - 单位与进制换算:`10km to miles`、`32px to rem`、`255 to hex`、`now + 2 weeks`。 + - 单位与进制换算:`10km to miles`、`1 acre to m2`、`100 km/h to mph`、`3斤 to kg`、`1亩等于多少平方米`、`1公斤转换成斤`、`1e3 m to km`、`32px to rem`、`255 to hex`、`now + 2 weeks`。连接词支持 `to`、`in`、`=`、`转`、`换成`、`等于多少` 等;单位类型不一致(如 `5 kg to m`)会明确报错。 + - 存储单位:`kb`、`mb`、`gb`、`tb` 按 Windows 习惯以 1024 进制换算(与 `kib`、`mib` 相同);十进制单位写全称,如 `1 gigabyte to megabytes`。 - 内联实时汇率:直接在主计算器输入 `100 usd to cny`、`5000 jpy to rmb`、`100 美元 转 人民币`、`1 xau to usd`、`0.5 btc to usd` 即时换算。 - 色彩检测:输入 `#3B82F6` 或 `rgb(59, 130, 246)` 列出 HEX、RGB、HSL、CMYK 写法及对比度。 +- 单位换算看板(计算器动作面板「单位换算看板…」,或在 `单位换算` 命令里选择分类;换算结果上按 `⌘/Ctrl+R` 带入当前数值与单位): + - 下拉切换 9 大分类,一次列出该分类全部单位的换算结果,并标注公制、英美制、市制等计量体系。 + - 输入数值、科学计数法或算式(`3*12`);输入 `5 kg`、`1 平方公里` 可直接切换分类与基准单位。 + - 每行可复制带单位结果、纯数值或换算等式,设为基准单位(`⌘/Ctrl+B`),并在动作面板中调整保留 0~10 位小数。 +- 人民币大写与中文数字(`大写金额` 命令,或计算器动作面板「人民币大写…」;普通数字结果上按 `⌘/Ctrl+U` 直接带入): + - 输入阿拉伯数字:同时给出票据人民币大写、中文大写(壹万贰仟…)与中文小写(一万二千…)。 + - 输入中文数字:转回阿拉伯数字,支持大写、小写、票据金额(含元角分整)、负数、小数、逐位写法与“三百五”“一万五”这类口语省略写法(会提示按口语理解的规范读法)。 + - 票据规则可在动作面板或规则区切换:“人民币”前缀、元/圆、整/正、不足一元是否写“零元”,以及分位处理(默认精确到分,超过两位小数时报错;可改为四舍五入或直接截断)。整数部分最多 16 位(到兆级)。 +- 主计算器快捷键:`Enter` 复制结果并记入计算历史,`⌘/Ctrl+Enter` 粘贴到前台应用,`⌘/Ctrl+E` 将结果数值填回输入框继续计算,`⌘/Ctrl+K` 打开动作面板。 - 多币种汇率看板(`汇率换算` 命令,或在计算器动作面板中选择「汇率换算…」): - 搜索框右侧下拉选择默认源币种(默认人民币),输入金额(如 `100`、`100 USD`、`100 USD to CNY`)一次列出各目标币种换算结果与反向汇率;输入币种代码或中文名(如 `日元`、`gold`、`比特币`)可筛选币种。 - 选中币种按 `Enter` 复制换算结果,`⌘/Ctrl+Enter` 复制换算等式,`⌘/Ctrl+D` 收藏置顶常用币种;也可执行「以该币种为源币种」将换算结果回填继续换算。 - 主计算器快捷键:`Enter` 复制结果并记入计算历史,`⌘/Ctrl+Enter` 粘贴到前台应用,`⌘/Ctrl+E` 将结果数值填回输入框继续计算,`⌘/Ctrl+K` 打开动作面板。 -- 人民币大写最多两位小数、不做四舍五入,最大 999999999999.99 元。 - 日期推算:`2026-01-31 + 1 month` 这类目标月没有该日的,取当月最后一天(2026-02-28);小时、分钟按实际经过时间计算,夏令时跳过的本地时刻会提示不存在。 - 不使用 `eval`;语法错误、除零与溢出会显示明确错误,不给出伪造结果。 - 计算历史保存最近 100 条(置顶的不计入),列表中显示最近 15 条。 diff --git a/extensions/calculator/plugin.json b/extensions/calculator/plugin.json index 06aead6d..6dfd320e 100644 --- a/extensions/calculator/plugin.json +++ b/extensions/calculator/plugin.json @@ -1,8 +1,8 @@ { "id": "calculator", "name": "计算器", - "version": "2.2.1", - "description": "输入算式即时计算,内置科学函数、单位换算、多币种实时汇率(含黄金/比特币)、人民币大写金额转换与日期推算", + "version": "2.3.0", + "description": "输入算式即时计算,内置科学函数、9 大类单位换算(长度/质量/面积/体积/速度/角度/存储/能量/温度,含市制)、多币种实时汇率(含黄金/比特币)、人民币大写与中文数字双向转换和日期推算", "author": "ZTools Team", "entry": "dist/index.js", "icon": "icon.svg", @@ -45,19 +45,49 @@ "比特币", "bitcoin", "BTC", - "大写金额" + "大写金额", + "算账", + "算数", + "单位换算", + "汇率换算", + "人民币大写", + "财务大写", + "日期计算", + "科学计算", + "面积换算", + "体积换算", + "速度换算", + "角度换算", + "能量换算", + "温度换算", + "度量衡", + "市制", + "斤", + "亩", + "中文数字", + "数字转中文", + "中文转数字", + "大写数字", + "金额大写", + "发票大写" ], "features": [ { "code": "calc-unit", - "explain": "长度/重量/存储/温度单位换算", + "explain": "长度/质量/面积/体积/速度/角度/存储/能量/温度单位换算与全单位对照", "mode": "view", "cmds": [ "单位换算", "长度换算", "重量换算", "存储换算", - "温度换算" + "温度换算", + "面积换算", + "体积换算", + "速度换算", + "角度换算", + "能量换算", + "度量衡" ] }, { @@ -78,13 +108,18 @@ }, { "code": "calc-rmb", - "explain": "财务人民币大写金额转换", + "explain": "人民币大写金额与中文数字双向转换", "mode": "view", "cmds": [ "大写金额", "人民币大写", "财务大写", - "数字转大写" + "数字转大写", + "中文数字", + "数字转中文", + "中文转数字", + "大写数字", + "金额大写" ] } ], @@ -97,7 +132,7 @@ "i18n": { "en-US": { "name": "Calculator", - "description": "Instant expression calculator with scientific functions, unit conversions, live multi-currency exchange rates (including gold and Bitcoin), Chinese RMB uppercase formatting, and date math.", + "description": "Instant expression calculator with scientific functions, unit conversion across 9 categories (length, mass, area, volume, speed, angle, data, energy, temperature, including Chinese units), live multi-currency exchange rates (including gold and Bitcoin), two-way Chinese RMB uppercase and Chinese numeral conversion, and date math.", "keywords": [ "calc", "calculator", @@ -106,16 +141,33 @@ "currency", "exchange rate", "gold", - "bitcoin" + "bitcoin", + "unit converter", + "date math", + "convert", + "money", + "rmb", + "area", + "volume", + "speed", + "angle", + "energy", + "chinese numerals", + "number to chinese" ], "features": { "calc-unit": { - "explain": "Convert length, weight, storage, and temperature units", + "explain": "Convert length, mass, area, volume, speed, angle, data, energy, and temperature units with a full comparison board", "cmds": [ "unit convert", "length convert", "weight convert", - "temperature convert" + "temperature convert", + "area convert", + "volume convert", + "speed convert", + "angle convert", + "energy convert" ] }, "calc-currency": { @@ -129,11 +181,13 @@ ] }, "calc-rmb": { - "explain": "Convert numbers to Chinese financial uppercase RMB format", + "explain": "Convert numbers to Chinese RMB uppercase and Chinese numerals, and back to digits", "cmds": [ "rmb uppercase", "chinese currency", - "financial uppercase" + "financial uppercase", + "chinese numerals", + "chinese to number" ] } }, diff --git a/extensions/calculator/src/calculator-engine.ts b/extensions/calculator/src/calculator-engine.ts index a8ccba3d..17466eb3 100644 --- a/extensions/calculator/src/calculator-engine.ts +++ b/extensions/calculator/src/calculator-engine.ts @@ -34,10 +34,18 @@ export interface UnitConversionResult { formattedAnswer: string; fromUnit: string; toUnit: string; - category: "css" | "length" | "mass" | "temp" | "digital" | "radix"; + category: "css" | "radix" | UnitCategoryId; + /** 度量衡换算的来源单位与数值:用于在单位看板中展开同类全部单位 */ + unitSource?: UnitSource; error?: string; } +export interface UnitSource { + readonly categoryId: UnitCategoryId; + readonly unitId: string; + readonly value: number; +} + export interface CurrencyConversionResult { isCurrency: boolean; expression: string; @@ -68,6 +76,8 @@ export interface CalculatorQueryResult { fillText?: string; details?: string; colorResult?: CalculatorColorResult; + /** 度量衡换算结果的来源单位:界面据此提供「在单位看板中查看全部单位」 */ + unitSource?: UnitSource; error?: string; } @@ -103,6 +113,7 @@ const ENGINE_MESSAGES = { overflowOrNonReal: "计算结果溢出或无实数解", belowAbsoluteZero: "温度不能低于绝对零度(0 K / -273.15 °C / -459.67 °F)", unitOverflow: "换算结果超出数值范围", + unitCategoryMismatch: '单位类型不一致,无法换算:"{from}" 属于 {fromCategory},"{to}" 属于 {toCategory}', unitDetails: "单位换算 ({category}): {from} -> {to}", dateOutOfRange: "日期超出可表示范围", dateNotExist: '日期不存在: "{expr}"', @@ -135,6 +146,7 @@ const ENGINE_MESSAGES = { overflowOrNonReal: "Result overflowed or is not a real number", belowAbsoluteZero: "Temperature cannot be below absolute zero (0 K / -273.15 °C / -459.67 °F)", unitOverflow: "Conversion result exceeds numeric range", + unitCategoryMismatch: 'Cannot convert between different unit types: "{from}" is {fromCategory}, "{to}" is {toCategory}', unitDetails: "Unit conversion ({category}): {from} -> {to}", dateOutOfRange: "Date is out of representable range", dateNotExist: 'Date does not exist: "{expr}"', @@ -511,49 +523,294 @@ export function evaluateMathExpression(input: string, options: { locale?: string } // ========================================================================= -// 2. Unit Conversions (px<->rem, distance, mass, temperature, storage, radix) +// 2. Unit Conversions(px↔rem、进制,以及 9 大类度量衡单位注册表) // ========================================================================= -const LENGTH_RATIOS: Record = { - m: 1, - km: 1000, - cm: 0.01, - mm: 0.001, - mi: 1609.344, - miles: 1609.344, - mile: 1609.344, - ft: 0.3048, - feet: 0.3048, - foot: 0.3048, - in: 0.0254, - inch: 0.0254, - inches: 0.0254, - yd: 0.9144, - yard: 0.9144, - yards: 0.9144 -}; +/** 度量衡单位分类(temp / digital 沿用历史命名,结果详情中显示为 TEMP / DIGITAL) */ +export type UnitCategoryId = "length" | "mass" | "area" | "volume" | "speed" | "angle" | "digital" | "energy" | "temp"; + +/** 计量体系:公制、美制、英制、英美通用、市制、其他 */ +export type UnitSystemId = "metric" | "us" | "imperial" | "us-imperial" | "chinese" | "other"; + +/** 单位文字:与语言无关时直接写字符串,否则按语言给出 */ +export type UnitText = string | Readonly>; + +export interface UnitDefinition { + readonly id: string; + /** 显示符号 */ + readonly symbol: UnitText; + readonly names: Readonly>; + readonly system?: UnitSystemId; + /** 线性单位:1 个本单位等于多少个基准单位 */ + readonly factor?: number; + /** 非线性单位(温度):换算到基准单位(摄氏度)与从基准单位换算回来 */ + readonly toBase?: (value: number) => number; + readonly fromBase?: (value: number) => number; + /** 内联输入可识别的别名(统一小写);按语言分组只用于整理,解析时两组同时生效 */ + readonly aliases: Readonly>; +} -const MASS_RATIOS: Record = { - g: 1, - kg: 1000, - mg: 0.001, - lb: 453.59237, - lbs: 453.59237, - pound: 453.59237, - pounds: 453.59237, - oz: 28.349523125, - ounce: 28.349523125, - ounces: 28.349523125 -}; +export interface UnitCategoryDefinition { + readonly id: UnitCategoryId; + readonly defaultFrom: string; + readonly units: readonly UnitDefinition[]; +} -const DIGITAL_RATIOS: Record = { - b: 1, - kb: 1024, - mb: 1024 * 1024, - gb: 1024 * 1024 * 1024, - tb: 1024 * 1024 * 1024 * 1024, - pb: 1024 * 1024 * 1024 * 1024 * 1024 -}; +/** 绝对零度(摄氏度) */ +const ABSOLUTE_ZERO_CELSIUS = -273.15; + +export const UNIT_CATEGORIES: readonly UnitCategoryDefinition[] = [ + { + id: "length", + defaultFrom: "meter", + units: [ + { id: "millimeter", symbol: "mm", system: "metric", factor: 0.001, names: { "zh-CN": "毫米", "en-US": "Millimeter" }, aliases: { "zh-CN": ["毫米"], "en-US": ["mm", "millimeter", "millimeters", "millimetre", "millimetres"] } }, + { id: "centimeter", symbol: "cm", system: "metric", factor: 0.01, names: { "zh-CN": "厘米", "en-US": "Centimeter" }, aliases: { "zh-CN": ["厘米"], "en-US": ["cm", "centimeter", "centimeters", "centimetre", "centimetres"] } }, + { id: "meter", symbol: "m", system: "metric", factor: 1, names: { "zh-CN": "米", "en-US": "Meter" }, aliases: { "zh-CN": ["米", "公尺"], "en-US": ["m", "meter", "meters", "metre", "metres"] } }, + { id: "kilometer", symbol: "km", system: "metric", factor: 1000, names: { "zh-CN": "千米", "en-US": "Kilometer" }, aliases: { "zh-CN": ["千米", "公里"], "en-US": ["km", "kilometer", "kilometers", "kilometre", "kilometres"] } }, + { id: "inch", symbol: "in", system: "us-imperial", factor: 0.0254, names: { "zh-CN": "英寸", "en-US": "Inch" }, aliases: { "zh-CN": ["英寸", "吋"], "en-US": ["in", "inch", "inches"] } }, + { id: "foot", symbol: "ft", system: "us-imperial", factor: 0.3048, names: { "zh-CN": "英尺", "en-US": "Foot" }, aliases: { "zh-CN": ["英尺", "呎"], "en-US": ["ft", "foot", "feet"] } }, + { id: "yard", symbol: "yd", system: "us-imperial", factor: 0.9144, names: { "zh-CN": "码", "en-US": "Yard" }, aliases: { "zh-CN": ["码"], "en-US": ["yd", "yard", "yards"] } }, + { id: "mile", symbol: "mi", system: "us-imperial", factor: 1609.344, names: { "zh-CN": "英里", "en-US": "Mile" }, aliases: { "zh-CN": ["英里"], "en-US": ["mi", "mile", "miles"] } }, + { id: "nautical-mile", symbol: "nmi", system: "other", factor: 1852, names: { "zh-CN": "海里", "en-US": "Nautical mile" }, aliases: { "zh-CN": ["海里"], "en-US": ["nmi", "nauticalmile", "nauticalmiles"] } } + ] + }, + { + id: "mass", + defaultFrom: "kilogram", + units: [ + { id: "milligram", symbol: "mg", system: "metric", factor: 0.000001, names: { "zh-CN": "毫克", "en-US": "Milligram" }, aliases: { "zh-CN": ["毫克"], "en-US": ["mg", "milligram", "milligrams"] } }, + { id: "gram", symbol: "g", system: "metric", factor: 0.001, names: { "zh-CN": "克", "en-US": "Gram" }, aliases: { "zh-CN": ["克"], "en-US": ["g", "gram", "grams"] } }, + { id: "kilogram", symbol: "kg", system: "metric", factor: 1, names: { "zh-CN": "千克", "en-US": "Kilogram" }, aliases: { "zh-CN": ["千克", "公斤"], "en-US": ["kg", "kilogram", "kilograms", "kilo", "kilos"] } }, + { id: "tonne", symbol: "t", system: "metric", factor: 1000, names: { "zh-CN": "吨", "en-US": "Tonne" }, aliases: { "zh-CN": ["吨", "公吨"], "en-US": ["t", "tonne", "tonnes"] } }, + { id: "ounce", symbol: "oz", system: "us-imperial", factor: 0.028349523125, names: { "zh-CN": "盎司", "en-US": "Ounce" }, aliases: { "zh-CN": ["盎司"], "en-US": ["oz", "ounce", "ounces"] } }, + { id: "pound", symbol: "lb", system: "us-imperial", factor: 0.45359237, names: { "zh-CN": "磅", "en-US": "Pound" }, aliases: { "zh-CN": ["磅"], "en-US": ["lb", "lbs", "pound", "pounds"] } }, + { id: "jin", symbol: { "zh-CN": "斤", "en-US": "jin" }, system: "chinese", factor: 0.5, names: { "zh-CN": "斤", "en-US": "Jin (catty)" }, aliases: { "zh-CN": ["斤", "市斤"], "en-US": ["jin", "catty"] } }, + { id: "liang", symbol: { "zh-CN": "两", "en-US": "liang" }, system: "chinese", factor: 0.05, names: { "zh-CN": "两", "en-US": "Liang (tael)" }, aliases: { "zh-CN": ["两"], "en-US": ["liang", "tael"] } } + ] + }, + { + id: "area", + defaultFrom: "square-meter", + units: [ + { id: "square-millimeter", symbol: "mm²", system: "metric", factor: 0.000001, names: { "zh-CN": "平方毫米", "en-US": "Square millimeter" }, aliases: { "zh-CN": ["平方毫米"], "en-US": ["mm2", "mm²", "sqmm"] } }, + { id: "square-centimeter", symbol: "cm²", system: "metric", factor: 0.0001, names: { "zh-CN": "平方厘米", "en-US": "Square centimeter" }, aliases: { "zh-CN": ["平方厘米"], "en-US": ["cm2", "cm²", "sqcm"] } }, + { id: "square-meter", symbol: "m²", system: "metric", factor: 1, names: { "zh-CN": "平方米", "en-US": "Square meter" }, aliases: { "zh-CN": ["平方米", "平米"], "en-US": ["m2", "m²", "sqm"] } }, + { id: "square-kilometer", symbol: "km²", system: "metric", factor: 1000000, names: { "zh-CN": "平方千米", "en-US": "Square kilometer" }, aliases: { "zh-CN": ["平方千米", "平方公里"], "en-US": ["km2", "km²", "sqkm"] } }, + { id: "hectare", symbol: "ha", system: "metric", factor: 10000, names: { "zh-CN": "公顷", "en-US": "Hectare" }, aliases: { "zh-CN": ["公顷"], "en-US": ["ha", "hectare", "hectares"] } }, + { id: "mu", symbol: { "zh-CN": "亩", "en-US": "mu" }, system: "chinese", factor: 10000 / 15, names: { "zh-CN": "亩", "en-US": "Mu" }, aliases: { "zh-CN": ["亩", "市亩"], "en-US": ["mu"] } }, + { id: "square-inch", symbol: "in²", system: "us-imperial", factor: 0.00064516, names: { "zh-CN": "平方英寸", "en-US": "Square inch" }, aliases: { "zh-CN": ["平方英寸"], "en-US": ["in2", "in²", "sqin"] } }, + { id: "square-foot", symbol: "ft²", system: "us-imperial", factor: 0.09290304, names: { "zh-CN": "平方英尺", "en-US": "Square foot" }, aliases: { "zh-CN": ["平方英尺"], "en-US": ["ft2", "ft²", "sqft"] } }, + { id: "square-yard", symbol: "yd²", system: "us-imperial", factor: 0.83612736, names: { "zh-CN": "平方码", "en-US": "Square yard" }, aliases: { "zh-CN": ["平方码"], "en-US": ["yd2", "yd²", "sqyd"] } }, + { id: "square-mile", symbol: "mi²", system: "us-imperial", factor: 2589988.110336, names: { "zh-CN": "平方英里", "en-US": "Square mile" }, aliases: { "zh-CN": ["平方英里"], "en-US": ["mi2", "mi²", "sqmi"] } }, + { id: "acre", symbol: "ac", system: "us-imperial", factor: 4046.8564224, names: { "zh-CN": "英亩", "en-US": "Acre" }, aliases: { "zh-CN": ["英亩"], "en-US": ["ac", "acre", "acres"] } } + ] + }, + { + id: "volume", + defaultFrom: "liter", + units: [ + { id: "milliliter", symbol: "mL", system: "metric", factor: 0.001, names: { "zh-CN": "毫升", "en-US": "Milliliter" }, aliases: { "zh-CN": ["毫升"], "en-US": ["ml", "milliliter", "milliliters", "millilitre", "millilitres"] } }, + { id: "liter", symbol: "L", system: "metric", factor: 1, names: { "zh-CN": "升", "en-US": "Liter" }, aliases: { "zh-CN": ["升", "公升"], "en-US": ["l", "liter", "liters", "litre", "litres"] } }, + { id: "cubic-centimeter", symbol: "cm³", system: "metric", factor: 0.001, names: { "zh-CN": "立方厘米", "en-US": "Cubic centimeter" }, aliases: { "zh-CN": ["立方厘米"], "en-US": ["cm3", "cm³", "cc"] } }, + { id: "cubic-meter", symbol: "m³", system: "metric", factor: 1000, names: { "zh-CN": "立方米", "en-US": "Cubic meter" }, aliases: { "zh-CN": ["立方米", "方"], "en-US": ["m3", "m³"] } }, + { id: "teaspoon", symbol: "tsp", system: "us", factor: 0.00492892159375, names: { "zh-CN": "茶匙 (美制)", "en-US": "Teaspoon (US)" }, aliases: { "zh-CN": ["茶匙"], "en-US": ["tsp", "teaspoon", "teaspoons"] } }, + { id: "tablespoon", symbol: "tbsp", system: "us", factor: 0.01478676478125, names: { "zh-CN": "汤匙 (美制)", "en-US": "Tablespoon (US)" }, aliases: { "zh-CN": ["汤匙"], "en-US": ["tbsp", "tablespoon", "tablespoons"] } }, + { id: "fluid-ounce", symbol: "fl oz", system: "us", factor: 0.0295735295625, names: { "zh-CN": "液体盎司 (美制)", "en-US": "Fluid ounce (US)" }, aliases: { "zh-CN": ["液体盎司"], "en-US": ["floz", "fluidounce", "fluidounces"] } }, + { id: "cup", symbol: "cup", system: "us", factor: 0.2365882365, names: { "zh-CN": "杯 (美制)", "en-US": "Cup (US)" }, aliases: { "zh-CN": ["杯"], "en-US": ["cup", "cups"] } }, + { id: "us-pint", symbol: "pt", system: "us", factor: 0.473176473, names: { "zh-CN": "品脱 (美制)", "en-US": "Pint (US)" }, aliases: { "zh-CN": ["品脱"], "en-US": ["pt", "pint", "pints"] } }, + { id: "us-quart", symbol: "qt", system: "us", factor: 0.946352946, names: { "zh-CN": "夸脱 (美制)", "en-US": "Quart (US)" }, aliases: { "zh-CN": ["夸脱"], "en-US": ["qt", "quart", "quarts"] } }, + { id: "gallon", symbol: "gal", system: "us", factor: 3.785411784, names: { "zh-CN": "加仑 (美制)", "en-US": "Gallon (US)" }, aliases: { "zh-CN": ["加仑", "美制加仑"], "en-US": ["gal", "gallon", "gallons"] } }, + { id: "imperial-gallon", symbol: { "zh-CN": "gal (英)", "en-US": "gal (UK)" }, system: "imperial", factor: 4.54609, names: { "zh-CN": "加仑 (英制)", "en-US": "Gallon (imperial)" }, aliases: { "zh-CN": ["英制加仑"], "en-US": ["impgal", "ukgal"] } } + ] + }, + { + id: "speed", + defaultFrom: "kilometer-per-hour", + units: [ + { id: "meter-per-second", symbol: "m/s", factor: 1, names: { "zh-CN": "米/秒", "en-US": "Meter per second" }, aliases: { "zh-CN": ["米每秒", "米/秒"], "en-US": ["m/s", "mps"] } }, + { id: "kilometer-per-hour", symbol: "km/h", factor: 1 / 3.6, names: { "zh-CN": "千米/时", "en-US": "Kilometer per hour" }, aliases: { "zh-CN": ["千米每小时", "公里每小时", "千米/时", "公里/时", "公里/小时"], "en-US": ["km/h", "kmh", "kph"] } }, + { id: "mile-per-hour", symbol: "mph", factor: 0.44704, names: { "zh-CN": "英里/时", "en-US": "Mile per hour" }, aliases: { "zh-CN": ["英里每小时", "英里/时"], "en-US": ["mph", "mi/h"] } }, + { id: "foot-per-second", symbol: "ft/s", factor: 0.3048, names: { "zh-CN": "英尺/秒", "en-US": "Foot per second" }, aliases: { "zh-CN": ["英尺每秒", "英尺/秒"], "en-US": ["ft/s", "fps"] } }, + { id: "knot", symbol: "kn", factor: 1852 / 3600, names: { "zh-CN": "节 (海里/时)", "en-US": "Knot (nmi/h)" }, aliases: { "zh-CN": ["节"], "en-US": ["kn", "kt", "knot", "knots"] } }, + { id: "mach", symbol: "Mach", factor: 340.29, names: { "zh-CN": "马赫 (标准大气)", "en-US": "Mach (standard atmosphere)" }, aliases: { "zh-CN": ["马赫"], "en-US": ["mach"] } } + ] + }, + { + id: "angle", + defaultFrom: "degree", + units: [ + { id: "degree", symbol: "°", factor: Math.PI / 180, names: { "zh-CN": "度", "en-US": "Degree" }, aliases: { "zh-CN": ["度"], "en-US": ["°", "deg", "degree", "degrees"] } }, + { id: "circle", symbol: { "zh-CN": "圈", "en-US": "turn" }, factor: Math.PI * 2, names: { "zh-CN": "整圆", "en-US": "Full turn" }, aliases: { "zh-CN": ["圈", "周", "整圆"], "en-US": ["turn", "turns", "circle", "rev"] } }, + { id: "right-angle", symbol: { "zh-CN": "直角", "en-US": "∟" }, factor: Math.PI / 2, names: { "zh-CN": "直角", "en-US": "Right angle" }, aliases: { "zh-CN": ["直角"], "en-US": ["rightangle"] } }, + { id: "gradian", symbol: "gon", factor: Math.PI / 200, names: { "zh-CN": "百分度", "en-US": "Gradian" }, aliases: { "zh-CN": ["百分度"], "en-US": ["gon", "grad", "gradian", "gradians"] } }, + { id: "arcminute", symbol: "′", factor: Math.PI / 10800, names: { "zh-CN": "角分", "en-US": "Arcminute" }, aliases: { "zh-CN": ["角分"], "en-US": ["′", "arcmin", "arcminute", "arcminutes"] } }, + { id: "arcsecond", symbol: "″", factor: Math.PI / 648000, names: { "zh-CN": "角秒", "en-US": "Arcsecond" }, aliases: { "zh-CN": ["角秒"], "en-US": ["″", "arcsec", "arcsecond", "arcseconds"] } }, + { id: "radian", symbol: "rad", factor: 1, names: { "zh-CN": "弧度", "en-US": "Radian" }, aliases: { "zh-CN": ["弧度"], "en-US": ["rad", "radian", "radians"] } }, + { id: "milliradian", symbol: "mrad", factor: 0.001, names: { "zh-CN": "毫弧度", "en-US": "Milliradian" }, aliases: { "zh-CN": ["毫弧度"], "en-US": ["mrad", "milliradian", "milliradians"] } } + ] + }, + { + // 内联输入的 kb/mb/gb/tb/pb 沿用 Windows 习惯按 1024 进制换算;十进制单位用全称(kilobyte 等) + id: "digital", + defaultFrom: "mebibyte", + units: [ + { id: "bit", symbol: "bit", factor: 0.125, names: { "zh-CN": "比特", "en-US": "Bit" }, aliases: { "zh-CN": ["比特"], "en-US": ["bit", "bits"] } }, + { id: "byte", symbol: "B", factor: 1, names: { "zh-CN": "字节", "en-US": "Byte" }, aliases: { "zh-CN": ["字节"], "en-US": ["b", "byte", "bytes"] } }, + { id: "kilobyte", symbol: "KB", factor: 1e3, names: { "zh-CN": "千字节 (十进制 1000)", "en-US": "Kilobyte (decimal, 1000)" }, aliases: { "zh-CN": [], "en-US": ["kilobyte", "kilobytes"] } }, + { id: "megabyte", symbol: "MB", factor: 1e6, names: { "zh-CN": "兆字节 (十进制 1000)", "en-US": "Megabyte (decimal, 1000)" }, aliases: { "zh-CN": [], "en-US": ["megabyte", "megabytes"] } }, + { id: "gigabyte", symbol: "GB", factor: 1e9, names: { "zh-CN": "吉字节 (十进制 1000)", "en-US": "Gigabyte (decimal, 1000)" }, aliases: { "zh-CN": [], "en-US": ["gigabyte", "gigabytes"] } }, + { id: "terabyte", symbol: "TB", factor: 1e12, names: { "zh-CN": "太字节 (十进制 1000)", "en-US": "Terabyte (decimal, 1000)" }, aliases: { "zh-CN": [], "en-US": ["terabyte", "terabytes"] } }, + { id: "petabyte", symbol: "PB", factor: 1e15, names: { "zh-CN": "拍字节 (十进制 1000)", "en-US": "Petabyte (decimal, 1000)" }, aliases: { "zh-CN": [], "en-US": ["petabyte", "petabytes"] } }, + { id: "kibibyte", symbol: "KiB", factor: 1024, names: { "zh-CN": "千字节 (二进制 1024,即 Windows 的 KB)", "en-US": "Kibibyte (binary 1024, Windows \"KB\")" }, aliases: { "zh-CN": [], "en-US": ["kb", "kib", "kibibyte", "kibibytes"] } }, + { id: "mebibyte", symbol: "MiB", factor: 1024 ** 2, names: { "zh-CN": "兆字节 (二进制 1024,即 Windows 的 MB)", "en-US": "Mebibyte (binary 1024, Windows \"MB\")" }, aliases: { "zh-CN": [], "en-US": ["mb", "mib", "mebibyte", "mebibytes"] } }, + { id: "gibibyte", symbol: "GiB", factor: 1024 ** 3, names: { "zh-CN": "吉字节 (二进制 1024,即 Windows 的 GB)", "en-US": "Gibibyte (binary 1024, Windows \"GB\")" }, aliases: { "zh-CN": [], "en-US": ["gb", "gib", "gibibyte", "gibibytes"] } }, + { id: "tebibyte", symbol: "TiB", factor: 1024 ** 4, names: { "zh-CN": "太字节 (二进制 1024,即 Windows 的 TB)", "en-US": "Tebibyte (binary 1024, Windows \"TB\")" }, aliases: { "zh-CN": [], "en-US": ["tb", "tib", "tebibyte", "tebibytes"] } }, + { id: "pebibyte", symbol: "PiB", factor: 1024 ** 5, names: { "zh-CN": "拍字节 (二进制 1024,即 Windows 的 PB)", "en-US": "Pebibyte (binary 1024, Windows \"PB\")" }, aliases: { "zh-CN": [], "en-US": ["pb", "pib", "pebibyte", "pebibytes"] } } + ] + }, + { + id: "energy", + defaultFrom: "joule", + units: [ + { id: "joule", symbol: "J", factor: 1, names: { "zh-CN": "焦耳", "en-US": "Joule" }, aliases: { "zh-CN": ["焦耳", "焦"], "en-US": ["j", "joule", "joules"] } }, + { id: "kilojoule", symbol: "kJ", factor: 1000, names: { "zh-CN": "千焦", "en-US": "Kilojoule" }, aliases: { "zh-CN": ["千焦", "千焦耳"], "en-US": ["kj", "kilojoule", "kilojoules"] } }, + { id: "megajoule", symbol: "MJ", factor: 1000000, names: { "zh-CN": "兆焦", "en-US": "Megajoule" }, aliases: { "zh-CN": ["兆焦", "兆焦耳"], "en-US": ["mj", "megajoule", "megajoules"] } }, + { id: "watt-hour", symbol: "W·h", factor: 3600, names: { "zh-CN": "瓦时", "en-US": "Watt-hour" }, aliases: { "zh-CN": ["瓦时"], "en-US": ["wh", "w·h", "watthour", "watthours"] } }, + { id: "kilowatt-hour", symbol: "kW·h", factor: 3600000, names: { "zh-CN": "千瓦时 (度)", "en-US": "Kilowatt-hour" }, aliases: { "zh-CN": ["千瓦时", "度电"], "en-US": ["kwh", "kw·h", "kilowatthour", "kilowatthours"] } }, + { id: "calorie", symbol: "cal", factor: 4.1868, names: { "zh-CN": "卡路里", "en-US": "Calorie" }, aliases: { "zh-CN": ["卡路里", "卡"], "en-US": ["cal", "calorie", "calories"] } }, + { id: "kilocalorie", symbol: "kcal", factor: 4186.8, names: { "zh-CN": "千卡 (大卡)", "en-US": "Kilocalorie" }, aliases: { "zh-CN": ["千卡", "大卡"], "en-US": ["kcal", "kilocalorie", "kilocalories"] } }, + { id: "british-thermal-unit", symbol: "BTU", factor: 1055.05585262, names: { "zh-CN": "英热单位", "en-US": "British thermal unit" }, aliases: { "zh-CN": ["英热单位"], "en-US": ["btu"] } }, + { id: "foot-pound-force", symbol: "ft·lbf", factor: 1.3558179483314, names: { "zh-CN": "英尺磅", "en-US": "Foot-pound force" }, aliases: { "zh-CN": ["英尺磅"], "en-US": ["ft·lbf", "ftlbf", "ftlb"] } } + ] + }, + { + id: "temp", + defaultFrom: "celsius", + units: [ + { id: "celsius", symbol: "°C", toBase: (v) => v, fromBase: (v) => v, names: { "zh-CN": "摄氏度", "en-US": "Celsius" }, aliases: { "zh-CN": ["摄氏度"], "en-US": ["c", "°c", "celsius"] } }, + { id: "fahrenheit", symbol: "°F", toBase: (v) => (v - 32) * (5 / 9), fromBase: (v) => v * (9 / 5) + 32, names: { "zh-CN": "华氏度", "en-US": "Fahrenheit" }, aliases: { "zh-CN": ["华氏度"], "en-US": ["f", "°f", "fahrenheit"] } }, + { id: "kelvin", symbol: "K", toBase: (v) => v + ABSOLUTE_ZERO_CELSIUS, fromBase: (v) => v - ABSOLUTE_ZERO_CELSIUS, names: { "zh-CN": "开尔文", "en-US": "Kelvin" }, aliases: { "zh-CN": ["开尔文", "开"], "en-US": ["k", "kelvin"] } }, + { id: "rankine", symbol: "°R", toBase: (v) => (v - 491.67) * (5 / 9), fromBase: (v) => (v - ABSOLUTE_ZERO_CELSIUS) * (9 / 5), names: { "zh-CN": "兰氏度", "en-US": "Rankine" }, aliases: { "zh-CN": ["兰氏度"], "en-US": ["r", "°r", "rankine"] } } + ] + } +]; + +export interface UnitRef { + readonly category: UnitCategoryDefinition; + readonly unit: UnitDefinition; +} + +/** 别名 → 单位索引;同一别名只登记第一次出现的单位(测试保证别名不重复) */ +const UNIT_ALIAS_INDEX: ReadonlyMap = (() => { + const index = new Map(); + for (const category of UNIT_CATEGORIES) { + for (const unit of category.units) { + for (const alias of [...unit.aliases["zh-CN"], ...unit.aliases["en-US"]]) { + if (!index.has(alias)) index.set(alias, { category, unit }); + } + } + } + return index; +})(); + +export function findUnitCategory(categoryId: string): UnitCategoryDefinition | undefined { + return UNIT_CATEGORIES.find((category) => category.id === categoryId); +} + +/** 按别名查找单位(不区分大小写);不认识时返回 null */ +export function resolveUnitAlias(token: string): UnitRef | null { + if (typeof token !== "string") return null; + return UNIT_ALIAS_INDEX.get(token.trim().toLowerCase()) ?? null; +} + +function pickUnitText(text: UnitText, explicitLocale?: string): string { + return typeof text === "string" ? text : text[resolveEngineLocale(explicitLocale)]; +} + +export function getUnitName(unit: UnitDefinition, explicitLocale?: string): string { + return pickUnitText(unit.names, explicitLocale); +} + +export function getUnitSymbol(unit: UnitDefinition, explicitLocale?: string): string { + return pickUnitText(unit.symbol, explicitLocale); +} + +export type UnitValueResult = + | { readonly ok: true; readonly value: number } + | { readonly ok: false; readonly reason: "invalid" | "overflow" | "belowAbsoluteZero" }; + +/** + * 同一分类内的单位换算: + * - 线性单位按倍数换算,结果溢出或非零输入被舍成 0(下溢)都视为超出范围; + * - 温度经摄氏度中转,低于绝对零度(留 1e-9 容差避免浮点误报)时拒绝换算。 + */ +export function convertUnitValue( + value: number, + categoryId: UnitCategoryId, + fromUnitId: string, + toUnitId: string +): UnitValueResult { + if (!Number.isFinite(value)) return { ok: false, reason: "invalid" }; + const category = findUnitCategory(categoryId); + const fromUnit = category?.units.find((unit) => unit.id === fromUnitId); + const toUnit = category?.units.find((unit) => unit.id === toUnitId); + if (!fromUnit || !toUnit) return { ok: false, reason: "invalid" }; + + if (fromUnit.toBase || toUnit.fromBase) { + const baseValue = fromUnit.toBase ? fromUnit.toBase(value) : value * (fromUnit.factor ?? Number.NaN); + if (!Number.isFinite(baseValue)) return { ok: false, reason: "overflow" }; + if (categoryId === "temp" && baseValue < ABSOLUTE_ZERO_CELSIUS - 1e-9) { + return { ok: false, reason: "belowAbsoluteZero" }; + } + const result = toUnit.fromBase ? toUnit.fromBase(baseValue) : baseValue / (toUnit.factor ?? Number.NaN); + return Number.isFinite(result) ? { ok: true, value: result } : { ok: false, reason: "overflow" }; + } + + const fromFactor = fromUnit.factor ?? Number.NaN; + const toFactor = toUnit.factor ?? Number.NaN; + if (!(fromFactor > 0) || !(toFactor > 0)) return { ok: false, reason: "invalid" }; + const result = fromUnitId === toUnitId ? value : value * (fromFactor / toFactor); + if (!Number.isFinite(result) || (value !== 0 && result === 0)) return { ok: false, reason: "overflow" }; + return { ok: true, value: result }; +} + +/** 小数位数限定在 0~12 位,非法值回落到 4 位 */ +export function normalizeUnitPrecision(precision: number): number { + if (!Number.isFinite(precision)) return 4; + return Math.min(12, Math.max(0, Math.round(precision))); +} + +/** 单位看板的数值格式:按小数位四舍五入;极小值会被舍成 0 时改用科学计数法,不显示误导性的 0 */ +export function formatUnitValue(value: number, precision = 4): string { + if (!Number.isFinite(value)) return ""; + const digits = normalizeUnitPrecision(precision); + const rounded = Number(value.toFixed(digits)); + if (rounded === 0 && value !== 0 && digits > 0) return String(Number(value.toExponential(digits))); + return Object.is(rounded, -0) ? "0" : String(rounded); +} + +/** 换算结果:保留 4 位小数,极小值改为 6 位有效数字(避免 1 mm to km 显示为 0) */ +function roundUnitResult(value: number): number { + const rounded = roundTo(value, 4); + if (rounded === 0 && value !== 0) return Number(value.toPrecision(6)); + return rounded; +} + +/** 结果后缀:温度用规范符号;存储单位缩写转成大写(kib → KiB);其余沿用用户输入的单位写法 */ +function unitResultLabel(categoryId: UnitCategoryId, token: string, unit: UnitDefinition, locale?: string): string { + if (categoryId === "temp") return getUnitSymbol(unit, locale); + if (categoryId === "digital") { + return /^[kmgtp]?i?b$/.test(token) ? token.toUpperCase().replace("IB", "iB") : getUnitSymbol(unit, locale); + } + return token; +} + +/** 内联换算:数字可带科学计数法;单位允许中文、°、²、³、/、·;连接词支持 to / in / = / 转 / 换成 / 等于多少等(长的写在前面) */ +const GENERAL_UNIT_RE = + /^([+-]?[\d.]+(?:e[+-]?\d+)?)\s*([a-z\u4e00-\u9fa5°′″][a-z0-9\u4e00-\u9fa5°′″²³/·]*?)\s*(?:to|in|as|=|->|→|转换成|转换为|转成|转为|换算成|换算为|换成|等于多少|合多少|是多少|转)\s*([a-z\u4e00-\u9fa5°′″][a-z0-9\u4e00-\u9fa5°′″²³/·]*)$/; +/** 度量衡换算里的数字:可带正负号、最多一个小数点与科学计数法 */ +const GENERAL_UNIT_NUMBER_RE = /^[+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?$/; export function convertUnits( input: string, @@ -644,26 +901,38 @@ export function convertUnits( }; } - // 3. General units with pattern: " to/in " - const unitMatch = s.match(/^([+-]?[\d.]+)\s*([a-z]+)\s*(?:to|in|=)\s*([a-z]+)$/); + // 3. 度量衡单位:「<数字> <单位> to/in/=/转 <单位>」,单位与别名来自统一注册表 + const unitMatch = s.match(GENERAL_UNIT_RE); if (unitMatch) { const from = unitMatch[2]; const to = unitMatch[3]; - const category = getUnitCategory(from, to); - // 不认识的单位组合不当作换算,交给后面的日期 / 算式判断 - if (!category) return null; - const val = parseUnitNumber(unitMatch[1]); - if (val === null) return unitError(input, unitMatch[1], from, to, category, locale); - - // Temperature: c, f, k, celsius, fahrenheit, kelvin - if (category === "temp") { - const fromNorm = from.startsWith("c") ? "c" : from.startsWith("f") ? "f" : "k"; - const toNorm = to.startsWith("c") ? "c" : to.startsWith("f") ? "f" : "k"; - let cVal = val; - if (fromNorm === "f") cVal = (val - 32) * (5 / 9); - if (fromNorm === "k") cVal = val - 273.15; - // 低于绝对零度(0 K = -273.15 °C)的温度不存在;留 1e-9 容差避免浮点误差误报 - if (cVal < -273.15 - 1e-9) { + const fromRef = resolveUnitAlias(from); + const toRef = resolveUnitAlias(to); + // 不认识的单位(如货币代码)不当作换算,交给后面的日期 / 汇率 / 算式判断 + if (!fromRef || !toRef) return null; + const categoryId = fromRef.category.id; + if (categoryId !== toRef.category.id) { + return { + isConversion: true, + expression: input.trim(), + value: NaN, + formattedAnswer: "", + fromUnit: from, + toUnit: to, + category: categoryId, + error: engineT( + "unitCategoryMismatch", + { from, to, fromCategory: categoryId.toUpperCase(), toCategory: toRef.category.id.toUpperCase() }, + locale + ) + }; + } + const val = parseGeneralUnitNumber(unitMatch[1]); + if (val === null) return unitError(input, unitMatch[1], from, to, categoryId, locale); + + const converted = convertUnitValue(val, categoryId, fromRef.unit.id, toRef.unit.id); + if (!converted.ok) { + if (converted.reason === "belowAbsoluteZero") { return { isConversion: true, expression: input.trim(), @@ -671,93 +940,30 @@ export function convertUnits( formattedAnswer: "", fromUnit: from, toUnit: to, - category, + category: categoryId, error: engineT("belowAbsoluteZero", undefined, locale) }; } - - let targetVal = cVal; - if (toNorm === "f") targetVal = cVal * (9 / 5) + 32; - if (toNorm === "k") targetVal = cVal + 273.15; - - const rounded = roundTo(targetVal, 2); - if (!Number.isFinite(rounded)) return unitOverflow(input, from, to, "temp", locale); - return { - isConversion: true, - expression: input.trim(), - value: rounded, - formattedAnswer: `${rounded} °${toNorm.toUpperCase()}`, - fromUnit: from, - toUnit: to, - category: "temp" - }; - } - - // Length - if (LENGTH_RATIOS[from] && LENGTH_RATIOS[to]) { - const inMeters = val * LENGTH_RATIOS[from]; - const targetVal = inMeters / LENGTH_RATIOS[to]; - const rounded = roundTo(targetVal, 4); - if (!Number.isFinite(rounded)) return unitOverflow(input, from, to, category, locale); - return { - isConversion: true, - expression: input.trim(), - value: rounded, - formattedAnswer: `${rounded} ${to}`, - fromUnit: from, - toUnit: to, - category: "length" - }; - } - - // Mass - if (MASS_RATIOS[from] && MASS_RATIOS[to]) { - const inGrams = val * MASS_RATIOS[from]; - const targetVal = inGrams / MASS_RATIOS[to]; - const rounded = roundTo(targetVal, 4); - if (!Number.isFinite(rounded)) return unitOverflow(input, from, to, category, locale); - return { - isConversion: true, - expression: input.trim(), - value: rounded, - formattedAnswer: `${rounded} ${to}`, - fromUnit: from, - toUnit: to, - category: "mass" - }; - } - - // Digital - if (DIGITAL_RATIOS[from] && DIGITAL_RATIOS[to]) { - const inBytes = val * DIGITAL_RATIOS[from]; - const targetVal = inBytes / DIGITAL_RATIOS[to]; - const rounded = roundTo(targetVal, 4); - if (!Number.isFinite(rounded)) return unitOverflow(input, from, to, category, locale); - return { - isConversion: true, - expression: input.trim(), - value: rounded, - formattedAnswer: `${rounded} ${to.toUpperCase()}`, - fromUnit: from, - toUnit: to, - category: "digital" - }; + return unitOverflow(input, from, to, categoryId, locale); } + // 温度保留 2 位小数(舍入后的 -0 规范成 0);其余保留 4 位,极小值保留 6 位有效数字 + const rounded = categoryId === "temp" ? roundTo(converted.value, 2) : roundUnitResult(converted.value); + if (!Number.isFinite(rounded)) return unitOverflow(input, from, to, categoryId, locale); + return { + isConversion: true, + expression: input.trim(), + value: rounded, + formattedAnswer: `${rounded} ${unitResultLabel(categoryId, to, toRef.unit, locale)}`, + fromUnit: from, + toUnit: to, + category: categoryId, + unitSource: { categoryId, unitId: fromRef.unit.id, value: val } + }; } return null; } -const TEMP_UNITS = new Set(["c", "f", "k", "celsius", "fahrenheit", "kelvin"]); - -function getUnitCategory(from: string, to: string): UnitConversionResult["category"] | null { - if (TEMP_UNITS.has(from) && TEMP_UNITS.has(to)) return "temp"; - if (LENGTH_RATIOS[from] && LENGTH_RATIOS[to]) return "length"; - if (MASS_RATIOS[from] && MASS_RATIOS[to]) return "mass"; - if (DIGITAL_RATIOS[from] && DIGITAL_RATIOS[to]) return "digital"; - return null; -} - /** 严格解析换算数字:格式不对(1.5.5、.、1..2)或不是有限数时返回 null */ function parseUnitNumber(raw: string): number | null { if (!UNIT_NUMBER_RE.test(raw)) return null; @@ -765,6 +971,13 @@ function parseUnitNumber(raw: string): number | null { return Number.isFinite(val) ? val : null; } +/** 度量衡换算的数字:在 parseUnitNumber 基础上允许科学计数法(1e4 m to km) */ +function parseGeneralUnitNumber(raw: string): number | null { + if (!GENERAL_UNIT_NUMBER_RE.test(raw)) return null; + const val = Number(raw); + return Number.isFinite(val) ? val : null; +} + /** 换算结果超出双精度范围(如 1e308 km to mm):报错,不能显示 Infinity */ function unitOverflow( input: string, @@ -1138,7 +1351,8 @@ export function evaluateCalculatorQuery( // 进制结果原样填回(0xFF、0b1010 单独出现时按转十进制计算;十进制整数按 BigInt 精确显示), // 其余换算填回不带单位的数值(与显示一致的舍入值),都能再次计算出同一数值 fillText: unit.category === "radix" ? unit.formattedAnswer : String(unit.value), - details: engineT("unitDetails", { category: unit.category.toUpperCase(), from: unit.fromUnit, to: unit.toUnit }, options.locale) + details: engineT("unitDetails", { category: unit.category.toUpperCase(), from: unit.fromUnit, to: unit.toUnit }, options.locale), + ...(unit.unitSource ? { unitSource: unit.unitSource } : {}) }; } diff --git a/extensions/calculator/src/chinese-number.ts b/extensions/calculator/src/chinese-number.ts new file mode 100644 index 00000000..cfcf79ea --- /dev/null +++ b/extensions/calculator/src/chinese-number.ts @@ -0,0 +1,438 @@ +/** + * 中文数字与人民币大写转换核心算法(纯函数,不经浮点运算): + * 1. 数字 → 中文小写(一万二千三百四十五点六七)/ 中文大写(壹万贰仟叁佰肆拾伍点陆柒); + * 2. 数字 → 票据人民币大写(壹万贰仟叁佰肆拾伍元陆角柒分),支持前缀、元/圆、整/正、舍入方式与零元规则; + * 3. 中文数字 → 阿拉伯数字(小写、大写、票据金额、负数、小数与“三百五”这类口语省略写法)。 + * 整数部分最多 16 位(到兆级),小数部分最多 16 位。 + */ +import { t } from "./i18n.js"; +import { + LOWER_DIGITS, + UPPER_DIGITS, + LOWER_SMALL_UNITS, + UPPER_SMALL_UNITS, + GROUP_UNITS, + CN_ZERO, + CN_POINT, + CN_NEGATIVE, + CN_RMB_PREFIX, + CN_YUAN, + CN_YUAN_FORMAL, + CN_JIAO, + CN_FEN, + CN_WHOLE, + CN_WHOLE_ALT, + CN_LEADING_ONE_TEN, + PARSE_DIGITS, + SMALL_UNIT_VALUES, + LARGE_UNIT_VALUES, + NORMALIZE_MAP, + CN_INTEGER_RE, + CN_HAS_UNIT_RE, + CN_DIGITS_ONLY_RE, + CN_TICKET_MARK_RE, + CN_TICKET_RE +} from "./chinese-number.zh-data.js"; + +export type ChineseDigitStyle = "lower" | "upper"; +/** exact:精确到分,超过两位的非零小数直接报错;half-up:四舍五入到分;truncate:直接截断到分 */ +export type TicketRoundingMode = "exact" | "half-up" | "truncate"; + +export interface TicketRules { + /** 前置“人民币” */ + readonly currencyPrefix: boolean; + /** 用“圆”代替“元” */ + readonly formalYuan: boolean; + /** 用“正”代替“整” */ + readonly wholeAlt: boolean; + readonly roundingMode: TicketRoundingMode; + /** 不足一元时是否写出“零元”(关闭时 0.05 写作“伍分”) */ + readonly showZeroYuan: boolean; +} + +export const DEFAULT_TICKET_RULES: TicketRules = Object.freeze({ + currencyPrefix: false, + formalYuan: false, + wholeAlt: false, + roundingMode: "exact", + showZeroYuan: true +}); + +export const TICKET_ROUNDING_MODES: readonly TicketRoundingMode[] = Object.freeze(["exact", "half-up", "truncate"]); + +const MAX_INTEGER_DIGITS = 16; +const MAX_FRACTION_DIGITS = 16; +const MAX_INPUT_LENGTH = 256; +/** 输入里出现中文字符(含〇)时按中文数字解析 */ +const CHINESE_CHAR_RE = /[\u3007\u4e00-\u9fa5]/; + +export class ConversionError extends Error { + constructor(message: string) { + super(message); + this.name = "ConversionError"; + } +} + +interface ParsedDecimal { + readonly negative: boolean; + readonly integer: string; + readonly fraction: string; +} + +/** 全角数字与符号转半角 */ +export function normalizeFullWidth(text: string): string { + return text.replace(/[0-9.,+-]/g, (char) => { + if (char >= "0" && char <= "9") return String.fromCharCode(char.charCodeAt(0) - 0xfee0); + return ({ ".": ".", ",": ",", "+": "+", "-": "-" } as Record)[char] ?? char; + }); +} + +/** 按十进制原文解析数字(支持千位分隔符、正负号与全角字符),不经浮点 */ +export function parseArabicDecimal(input: string): ParsedDecimal { + const text = normalizeFullWidth(input).trim(); + if (!text) throw new ConversionError(t("cnErrEmptyNumber")); + if (text.length > MAX_INPUT_LENGTH) throw new ConversionError(t("cnErrTooLong")); + + const signless = text.replace(/^[+-]/, ""); + const integerWithSeparators = signless.split(".")[0] ?? ""; + if (integerWithSeparators.includes(",") && !/^\d{1,3}(?:,\d{3})+$/.test(integerWithSeparators)) { + throw new ConversionError(t("cnErrSeparator")); + } + + const match = text.replace(/,/g, "").match(/^([+-]?)(?:(\d+)(?:\.(\d*))?|\.(\d+))$/); + if (!match) throw new ConversionError(t("cnErrInvalidDecimal")); + + const integer = (match[2] ?? "0").replace(/^0+(?=\d)/, "") || "0"; + const fraction = match[3] ?? match[4] ?? ""; + if (integer.length > MAX_INTEGER_DIGITS) throw new ConversionError(t("cnErrIntegerTooLong")); + if (fraction.length > MAX_FRACTION_DIGITS) throw new ConversionError(t("cnErrFractionTooLong")); + + const isZero = integer === "0" && !/[1-9]/.test(fraction); + return { negative: match[1] === "-" && !isZero, integer, fraction }; +} + +function convertGroup(groupText: string, style: ChineseDigitStyle): string { + const digits = style === "upper" ? UPPER_DIGITS : LOWER_DIGITS; + const units = style === "upper" ? UPPER_SMALL_UNITS : LOWER_SMALL_UNITS; + const padded = groupText.padStart(4, "0"); + let output = ""; + let zeroPending = false; + for (let index = 0; index < padded.length; index += 1) { + const digit = Number(padded[index]); + if (digit === 0) { + if (output) zeroPending = true; + continue; + } + if (zeroPending) { + output += CN_ZERO; + zeroPending = false; + } + output += `${digits[digit]}${units[padded.length - 1 - index] ?? ""}`; + } + return output; +} + +function integerToChinese(integer: string, style: ChineseDigitStyle): string { + if (integer === "0") return CN_ZERO; + const groups: string[] = []; + for (let end = integer.length; end > 0; end -= 4) { + groups.unshift(integer.slice(Math.max(0, end - 4), end)); + } + if (groups.length > GROUP_UNITS.length) throw new ConversionError(t("cnErrIntegerTooLong")); + + let output = ""; + let zeroBetweenGroups = false; + groups.forEach((group, index) => { + const value = Number(group); + if (value === 0) { + if (output) zeroBetweenGroups = true; + return; + } + if (output && (zeroBetweenGroups || value < 1000) && !output.endsWith(CN_ZERO)) output += CN_ZERO; + output += `${convertGroup(group, style)}${GROUP_UNITS[groups.length - 1 - index] ?? ""}`; + zeroBetweenGroups = false; + }); + + if (style === "lower" && output.startsWith(CN_LEADING_ONE_TEN)) return output.slice(1); + return output; +} + +/** 数字转中文读法(lower:中文小写,upper:中文大写) */ +export function numberToChinese(input: string, style: ChineseDigitStyle = "lower"): string { + const parsed = parseArabicDecimal(input); + const digits = style === "upper" ? UPPER_DIGITS : LOWER_DIGITS; + const integerText = integerToChinese(parsed.integer, style); + const fractionText = parsed.fraction + ? `${CN_POINT}${[...parsed.fraction].map((digit) => digits[Number(digit)]).join("")}` + : ""; + return `${parsed.negative ? CN_NEGATIVE : ""}${integerText}${fractionText}`; +} + +function normalizeChineseInput(input: string): string { + const compact = normalizeFullWidth(input).trim().replace(/[\s,,]/g, ""); + if (!compact) throw new ConversionError(t("cnErrEmptyChinese")); + if (compact.length > MAX_INPUT_LENGTH) throw new ConversionError(t("cnErrTooLong")); + return [...compact].map((char) => NORMALIZE_MAP[char] ?? char).join(""); +} + +interface ParsedChineseInteger { + readonly value: bigint; + /** 是否按口语省略写法(如“三百五”“一万五”)解析了末位数字 */ + readonly colloquial: boolean; +} + +function parseChineseInteger(input: string): ParsedChineseInteger { + if (!input) return { value: 0n, colloquial: false }; + if (!CN_INTEGER_RE.test(input)) throw new ConversionError(t("cnErrInvalidChars")); + + if (!CN_HAS_UNIT_RE.test(input)) { + // 逐位写法:一二三 = 123 + const normalized = [...input].map((char) => PARSE_DIGITS[char]).join("").replace(/^0+(?=\d)/, "") || "0"; + if (normalized.length > MAX_INTEGER_DIGITS) throw new ConversionError(t("cnErrIntegerTooLong")); + return { value: BigInt(normalized), colloquial: false }; + } + + const NO_SMALL_UNIT = 10000n; + const NO_LARGE_UNIT = 10000000000000n; + let total = 0n; + let section = 0n; + let pendingDigit: number | null = null; + let pendingAfterZero = false; + let lastSmallUnit = NO_SMALL_UNIT; + let lastLargeUnit = NO_LARGE_UNIT; + let lastWasZero = false; + let colloquial = false; + + /** + * 没有单位跟随的数字的位权:前面有“零”时是个位(三百零五 = 305); + * 紧跟在百、千后面且中间没有“零”时,按口语省略写法表示下一级单位(三百五 = 350,一千二百三 = 1230); + * allowLargeUnit 为真(数字位于末尾)且本节没有十百千时,紧跟在万、亿、兆后面的数字同理(一万五 = 15000)。 + */ + const pendingWeight = (allowLargeUnit: boolean): bigint => { + if (pendingAfterZero) return 1n; + if (lastSmallUnit !== NO_SMALL_UNIT) return lastSmallUnit / 10n; + if (allowLargeUnit && section === 0n && lastLargeUnit !== NO_LARGE_UNIT) return lastLargeUnit / 10n; + return 1n; + }; + const flushPending = (allowLargeUnit: boolean) => { + if (pendingDigit === null) return; + const weight = pendingWeight(allowLargeUnit); + if (weight > 1n) colloquial = true; + section += BigInt(pendingDigit) * weight; + pendingDigit = null; + }; + + for (const char of input) { + const digit = PARSE_DIGITS[char]; + if (digit !== undefined) { + if (digit === 0) { + if (pendingDigit !== null) throw new ConversionError(t("cnErrDigitOrder")); + lastWasZero = true; + continue; + } + if (pendingDigit !== null) throw new ConversionError(t("cnErrConsecutiveDigits")); + pendingDigit = digit; + pendingAfterZero = lastWasZero; + lastWasZero = false; + continue; + } + + const smallUnit = SMALL_UNIT_VALUES[char]; + if (smallUnit) { + if (smallUnit >= lastSmallUnit || lastWasZero) throw new ConversionError(t("cnErrSmallUnitOrder")); + section += BigInt(pendingDigit ?? 1) * smallUnit; + pendingDigit = null; + lastSmallUnit = smallUnit; + lastWasZero = false; + continue; + } + + const largeUnit = LARGE_UNIT_VALUES[char]; + if (largeUnit) { + // 数字紧挨在万、亿、兆前面时是该单位的系数,只按本节的十百千判断是否口语省略(一千二万 = 1200 万) + flushPending(false); + if (section === 0n || largeUnit >= lastLargeUnit) throw new ConversionError(t("cnErrLargeUnitOrder")); + total += section * largeUnit; + section = 0n; + lastSmallUnit = NO_SMALL_UNIT; + lastLargeUnit = largeUnit; + lastWasZero = false; + continue; + } + + throw new ConversionError(t("cnErrUnknownChar", { char })); + } + + if (lastWasZero) throw new ConversionError(t("cnErrTrailingZero")); + flushPending(true); + const result = total + section; + if (result.toString().length > MAX_INTEGER_DIGITS) throw new ConversionError(t("cnErrIntegerTooLong")); + return { value: result, colloquial }; +} + +function normalizeNumberOutput(integer: bigint, fraction: string, negative: boolean): string { + const trimmedFraction = fraction.replace(/0+$/, ""); + const zero = integer === 0n && !trimmedFraction; + return `${negative && !zero ? "-" : ""}${integer.toString()}${trimmedFraction ? `.${trimmedFraction}` : ""}`; +} + +export interface ChineseNumberParseResult { + /** 阿拉伯数字结果 */ + readonly value: string; + /** 是否按口语省略写法解析(三百五 = 350、一万五 = 15000),界面据此提示用户核对 */ + readonly colloquial: boolean; +} + +function parseTicketChinese(input: string, negative: boolean): ChineseNumberParseResult { + const match = input.match(CN_TICKET_RE); + if (!match) throw new ConversionError(t("cnErrTicketFormat")); + + const integerText = match[1] ?? ""; + const hasYuan = Boolean(match[2]); + const jiaoText = match[3]; + const fenText = match[4]; + const hasWhole = Boolean(match[5]); + if (!hasYuan && integerText) throw new ConversionError(t("cnErrMissingYuan")); + if (!hasYuan && !jiaoText && !fenText) throw new ConversionError(t("cnErrMissingTicketUnit")); + if (hasYuan && !integerText) throw new ConversionError(t("cnErrMissingAmountBeforeYuan")); + if (hasWhole && (!hasYuan || jiaoText || fenText)) throw new ConversionError(t("cnErrWholeMisuse")); + + const integer = parseChineseInteger(integerText || CN_ZERO); + const jiao = jiaoText ? PARSE_DIGITS[jiaoText] ?? 0 : 0; + const fen = fenText ? PARSE_DIGITS[fenText] ?? 0 : 0; + return { value: normalizeNumberOutput(integer.value, `${jiao}${fen}`, negative), colloquial: integer.colloquial }; +} + +/** 中文数字转阿拉伯数字,并返回是否使用了口语省略写法 */ +export function parseChineseNumber(input: string): ChineseNumberParseResult { + let normalized = normalizeChineseInput(input); + let negative = false; + if (normalized.startsWith(CN_NEGATIVE)) { + negative = true; + normalized = normalized.slice(CN_NEGATIVE.length); + } + if (normalized.startsWith(CN_RMB_PREFIX)) normalized = normalized.slice(CN_RMB_PREFIX.length); + if (!normalized || normalized.includes(CN_NEGATIVE)) throw new ConversionError(t("cnErrNegativePosition")); + + if (CN_TICKET_MARK_RE.test(normalized)) return parseTicketChinese(normalized, negative); + + const parts = normalized.split(CN_POINT); + if (parts.length > 2) throw new ConversionError(t("cnErrMultiplePoints")); + const integerText = parts[0] || CN_ZERO; + const fractionText = parts[1] ?? ""; + if (parts.length === 2 && !fractionText) throw new ConversionError(t("cnErrMissingFraction")); + if (fractionText && !CN_DIGITS_ONLY_RE.test(fractionText)) throw new ConversionError(t("cnErrFractionDigits")); + if (fractionText.length > MAX_FRACTION_DIGITS) throw new ConversionError(t("cnErrFractionTooLong")); + + const integer = parseChineseInteger(integerText); + const fraction = [...fractionText].map((char) => PARSE_DIGITS[char]).join(""); + return { value: normalizeNumberOutput(integer.value, fraction, negative), colloquial: integer.colloquial }; +} + +/** 中文数字转阿拉伯数字(支持小写、大写、票据金额与小数) */ +export function chineseToNumber(input: string): string { + return parseChineseNumber(input).value; +} + +/** 金额换算到分:exact 模式下分以后还有非零数字直接报错,不静默舍入 */ +function decimalToFen(parsed: ParsedDecimal, roundingMode: TicketRoundingMode): bigint { + const rest = parsed.fraction.slice(2); + if (roundingMode === "exact" && /[1-9]/.test(rest)) throw new ConversionError(t("cnErrExactDecimals")); + const cents = parsed.fraction.padEnd(2, "0").slice(0, 2); + const shouldRound = roundingMode === "half-up" && Number(rest[0] ?? "0") >= 5; + let value = BigInt(parsed.integer) * 100n + BigInt(cents) + (shouldRound ? 1n : 0n); + if ((value / 100n).toString().length > MAX_INTEGER_DIGITS) throw new ConversionError(t("cnErrRoundOverflow")); + if (parsed.negative) value = -value; + return value; +} + +/** 数字转票据人民币大写金额 */ +export function numberToTicketUppercase(input: string, rules: TicketRules = DEFAULT_TICKET_RULES): string { + const amountFen = decimalToFen(parseArabicDecimal(input), rules.roundingMode); + const negative = amountFen < 0n; + const absoluteFen = negative ? -amountFen : amountFen; + const yuan = absoluteFen / 100n; + const jiao = Number((absoluteFen / 10n) % 10n); + const fen = Number(absoluteFen % 10n); + const showYuan = rules.showZeroYuan || yuan > 0n || (jiao === 0 && fen === 0); + + let body = ""; + if (showYuan) body += `${integerToChinese(yuan.toString(), "upper")}${rules.formalYuan ? CN_YUAN_FORMAL : CN_YUAN}`; + if (jiao === 0 && fen === 0) { + body += rules.wholeAlt ? CN_WHOLE_ALT : CN_WHOLE; + } else { + if (jiao > 0) body += `${UPPER_DIGITS[jiao]}${CN_JIAO}`; + if (fen > 0) { + // 元与分之间缺角时补“零”(壹元零伍分);不足一元时不补(零元伍分) + if (jiao === 0 && yuan > 0n) body += CN_ZERO; + body += `${UPPER_DIGITS[fen]}${CN_FEN}`; + } + } + // 归零后的负数(-0.001 截断)不带负号 + const signed = negative && absoluteFen > 0n; + return `${signed ? CN_NEGATIVE : ""}${rules.currencyPrefix ? CN_RMB_PREFIX : ""}${body}`; +} + +/** 默认票据规则下的人民币大写(精确到分,不四舍五入) */ +export function toChineseAmount(input: string): string { + return numberToTicketUppercase(input, DEFAULT_TICKET_RULES); +} + +export type ChineseNumberRowKind = "arabic" | "ticket" | "upper" | "lower"; + +export interface ChineseNumberRow { + readonly kind: ChineseNumberRowKind; + /** 成功时的结果 */ + readonly value?: string; + /** 该行单独失败(如精确到分规则下小数超过两位)时的原因;其余行照常显示 */ + readonly error?: string; + /** 阿拉伯数字行:是否按口语省略写法理解 */ + readonly colloquial?: boolean; +} + +export interface ChineseNumberConversion { + readonly source: "arabic" | "chinese"; + /** 规范化后的阿拉伯数字 */ + readonly arabic: string; + readonly rows: readonly ChineseNumberRow[]; +} + +function ticketRow(arabic: string, rules: TicketRules): ChineseNumberRow { + try { + return { kind: "ticket", value: numberToTicketUppercase(arabic, rules) }; + } catch (error: unknown) { + if (error instanceof ConversionError) return { kind: "ticket", error: error.message }; + throw error; + } +} + +/** + * 大写金额视图的双向转换:输入含中文时按中文数字解析,否则按阿拉伯数字解析。 + * 输入本身无法解析时抛出 ConversionError。 + */ +export function convertChineseNumberInput(input: string, rules: TicketRules = DEFAULT_TICKET_RULES): ChineseNumberConversion { + if (CHINESE_CHAR_RE.test(input)) { + const parsed = parseChineseNumber(input); + return { + source: "chinese", + arabic: parsed.value, + rows: [ + { kind: "arabic", value: parsed.value, colloquial: parsed.colloquial }, + ticketRow(parsed.value, rules), + { kind: "upper", value: numberToChinese(parsed.value, "upper") }, + { kind: "lower", value: numberToChinese(parsed.value, "lower") } + ] + }; + } + const parsed = parseArabicDecimal(input); + const arabic = normalizeNumberOutput(BigInt(parsed.integer), parsed.fraction, parsed.negative); + return { + source: "arabic", + arabic, + rows: [ + ticketRow(input, rules), + { kind: "upper", value: numberToChinese(input, "upper") }, + { kind: "lower", value: numberToChinese(input, "lower") } + ] + }; +} diff --git a/extensions/calculator/src/chinese-number.zh-data.ts b/extensions/calculator/src/chinese-number.zh-data.ts new file mode 100644 index 00000000..1c9921fa --- /dev/null +++ b/extensions/calculator/src/chinese-number.zh-data.ts @@ -0,0 +1,61 @@ +/** + * 中文数字与人民币大写的静态汉字表与解析规则(纯数据,不含界面与报错文案) + */ +export const LOWER_DIGITS: readonly string[] = Object.freeze(["零", "一", "二", "三", "四", "五", "六", "七", "八", "九"]); +export const UPPER_DIGITS: readonly string[] = Object.freeze(["零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"]); +export const LOWER_SMALL_UNITS: readonly string[] = Object.freeze(["", "十", "百", "千"]); +export const UPPER_SMALL_UNITS: readonly string[] = Object.freeze(["", "拾", "佰", "仟"]); +export const GROUP_UNITS: readonly string[] = Object.freeze(["", "万", "亿", "兆"]); + +export const CN_ZERO = "零"; +export const CN_POINT = "点"; +export const CN_NEGATIVE = "负"; +export const CN_RMB_PREFIX = "人民币"; +export const CN_YUAN = "元"; +export const CN_YUAN_FORMAL = "圆"; +export const CN_JIAO = "角"; +export const CN_FEN = "分"; +export const CN_WHOLE = "整"; +export const CN_WHOLE_ALT = "正"; +/** 小写读法里开头的“一十”读作“十” */ +export const CN_LEADING_ONE_TEN = "一十"; + +/** 解析用:归一化后的小写数字 → 数值 */ +export const PARSE_DIGITS: Readonly> = Object.freeze({ + 零: 0, 一: 1, 二: 2, 三: 3, 四: 4, 五: 5, 六: 6, 七: 7, 八: 8, 九: 9 +}); + +export const SMALL_UNIT_VALUES: Readonly> = Object.freeze({ + 十: 10n, 百: 100n, 千: 1000n +}); + +export const LARGE_UNIT_VALUES: Readonly> = Object.freeze({ + 万: 10000n, 亿: 100000000n, 兆: 1000000000000n +}); + +/** 大写、繁体、异体字统一归一化为小写简体 */ +export const NORMALIZE_MAP: Readonly> = Object.freeze({ + 〇: "零", 壹: "一", 贰: "二", 貳: "二", 貮: "二", 两: "二", 兩: "二", 叁: "三", 參: "三", + 肆: "四", 伍: "五", 陆: "六", 陸: "六", 柒: "七", 捌: "八", 玖: "九", + 拾: "十", 佰: "百", 仟: "千", 萬: "万", 億: "亿", 點: "点", + 圆: "元", 圓: "元", 負: "负", 正: "整" +}); + +/** 归一化后的整数部分只能包含这些字 */ +export const CN_INTEGER_RE = /^[零一二三四五六七八九十百千万亿兆]+$/; +/** 是否带十百千万亿兆单位 */ +export const CN_HAS_UNIT_RE = /[十百千万亿兆]/; +/** 只由数字组成(小数部分、逐位写法) */ +export const CN_DIGITS_ONLY_RE = /^[零一二三四五六七八九]+$/; +/** 是否为票据金额写法(含元角分整) */ +export const CN_TICKET_MARK_RE = /[元角分整]/; +/** 票据金额:[整数][元][N角][零N分][整] */ +export const CN_TICKET_RE = + /^([零一二三四五六七八九十百千万亿兆]+)?(元)?(?:([零一二三四五六七八九])角)?(?:零?([零一二三四五六七八九])分)?(整)?$/; + +/** 大写金额视图里的中文输入示例(中文界面才显示) */ +export const CHINESE_INPUT_EXAMPLES: readonly string[] = Object.freeze([ + "壹万贰仟叁佰肆拾伍元陆角柒分", + "三千五百二十点五", + "三百五" +]); diff --git a/extensions/calculator/src/i18n.ts b/extensions/calculator/src/i18n.ts index cfc875a3..a5260e39 100644 --- a/extensions/calculator/src/i18n.ts +++ b/extensions/calculator/src/i18n.ts @@ -51,7 +51,7 @@ export const t = createTranslator( clearedHistoryToast: "已清空所有历史计算记录", actionOpenRmb: "人民币大写…", actionOpenCurrency: "汇率换算…", - placeholderUnitOnly: "输入换算,如 10km to miles、5kg to lbs、100c to f、1024mb to gb", + placeholderUnitOnly: "输入换算,如 10km to miles、5kg to lbs、100c to f、3斤 to kg、1亩等于多少平方米", placeholderDefault: "输入算式,如 128*1024、32px to rem、0xFF to dec、now + 2 weeks", // 色彩区 @@ -194,15 +194,136 @@ export const t = createTranslator( currXAU: "黄金(盎司)", currBTC: "比特币", - // 人民币大写 + // 人民币大写与中文数字 rmbNavTitle: "人民币大写", - rmbSearchPlaceholder: "输入金额,如 12345.67,精确到分", - rmbIdleTitle: "输入金额转换为人民币大写", - rmbIdleSubtitle: "最多两位小数,不进行四舍五入", - rmbResultSubtitle: "{amount} 元", + rmbSearchPlaceholder: "输入金额(如 12345.67)或中文数字(如 壹万贰仟元、三百五)双向转换", + rmbIdleTitle: "输入金额或中文数字开始转换", + rmbIdleSubtitle: "数字转票据大写、中文大写与中文小写;中文数字转阿拉伯数字", rmbActionCopy: "复制大写金额", - rmbErrInvalidFormat: "请输入金额,最多两位小数(不进行四舍五入)", - rmbErrTooLarge: "最大支持 999999999999.99 元" + rmbActionCopyUpper: "复制中文大写", + rmbActionCopyLower: "复制中文小写", + rmbActionCopyArabic: "复制阿拉伯数字", + rmbActionCopyPair: "复制完整对照(输入 = 结果)", + rmbActionClearInput: "清空输入", + rmbTagTicket: "大写金额", + rmbTagUpper: "中文大写", + rmbTagLower: "中文小写", + rmbTagArabic: "阿拉伯数字", + rmbRowTicketSubtitle: "票据人民币大写 · {rounding}", + rmbRowTicketFailedSubtitle: "无法生成大写金额,可在动作面板的票据大写规则中切换分位处理", + rmbRowUpperSubtitle: "中文大写数字(财务正体)", + rmbRowLowerSubtitle: "中文小写数字(日常读法)", + rmbRowArabicSubtitle: "阿拉伯数字", + rmbRowArabicColloquialSubtitle: "阿拉伯数字(按口语省略写法理解:{reading})", + rmbErrorSubtitle: "请输入阿拉伯数字(如 12345.67)或中文数字(如 壹万贰仟元、三百五)", + rmbSectionResults: "转换结果", + rmbSectionExamples: "常用示例(回车填入)", + rmbActionFillExample: "带入示例", + rmbExampleInvoice: "发票常规金额", + rmbExampleFen: "零头分币金额", + rmbExampleLarge: "大额跨级金额", + rmbExampleTicketReverse: "大写金额反查", + rmbExampleLowerReverse: "中文小写数字", + rmbExampleColloquial: "口语省略写法", + rmbSectionRules: "票据大写规则", + rmbRulesSubmenu: "票据大写规则", + rmbActionToggleRule: "切换此规则", + rmbRuleChangedToast: "已切换:{rule}", + rmbRulePrefix: "币种前缀:{value}", + rmbRulePrefixOn: "人民币", + rmbRulePrefixOff: "无", + rmbRulePrefixHint: "开启后在大写金额前加“人民币”", + rmbRuleYuan: "金额单位:{value}", + rmbRuleYuanStandard: "元", + rmbRuleYuanFormal: "圆", + rmbRuleYuanHint: "票据填写规定允许使用“元”或“圆”", + rmbRuleWhole: "整额后缀:{value}", + rmbRuleWholeStandard: "整", + rmbRuleWholeAlt: "正", + rmbRuleWholeHint: "金额到元为止时在末尾写“整”或“正”", + rmbRuleRounding: "分位处理:{value}", + rmbRoundingExact: "精确到分(超过两位小数时报错)", + rmbRoundingHalfUp: "四舍五入到分", + rmbRoundingTruncate: "直接截断到分", + rmbRuleRoundingHint: "金额小数超过两位时的处理方式", + rmbRuleZeroYuan: "不足一元:{value}", + rmbRuleZeroYuanShow: "写出“零元”(零元伍分)", + rmbRuleZeroYuanHide: "省略“零元”(伍分)", + rmbRuleZeroYuanHint: "金额小于一元时是否写出“零元”", + + // 中文数字解析与转换错误 + cnErrEmptyNumber: "请输入有效数字", + cnErrTooLong: "输入长度不能超过 256 个字符", + cnErrSeparator: "千位分隔符位置不正确", + cnErrInvalidDecimal: "不是有效的十进制数字格式", + cnErrIntegerTooLong: "整数部分最多支持 16 位数字", + cnErrFractionTooLong: "小数部分最多支持 16 位数字", + cnErrEmptyChinese: "请输入中文数字", + cnErrInvalidChars: "包含无法识别的中文数字字符", + cnErrDigitOrder: "中文数字位序不正确", + cnErrConsecutiveDigits: "带单位写法中不能连续出现多个数字", + cnErrSmallUnitOrder: "十、百、千的顺序不正确", + cnErrLargeUnitOrder: "万、亿、兆的顺序不正确", + cnErrUnknownChar: "无法识别字符“{char}”", + cnErrTrailingZero: "中文数字不能以无意义的零结尾", + cnErrTicketFormat: "票据金额格式或单位顺序不正确", + cnErrMissingYuan: "整数金额后缺少元或圆", + cnErrMissingTicketUnit: "票据金额缺少元、角或分", + cnErrMissingAmountBeforeYuan: "元或圆前缺少金额", + cnErrWholeMisuse: "整或正只能用于无角分的金额", + cnErrNegativePosition: "负号位置不正确", + cnErrMultiplePoints: "只能包含一个小数点", + cnErrMissingFraction: "小数点后缺少数字", + cnErrFractionDigits: "小数部分只能逐位书写中文数字", + cnErrExactDecimals: "金额最多两位小数(当前精确到分,可在票据大写规则中改为四舍五入或截断)", + cnErrRoundOverflow: "舍入后的整数金额超过 16 位", + + // 主计算器:单位看板与大写金额入口 + actionOpenUnitBoard: "单位换算看板…", + actionViewAllUnits: "在单位看板中查看全部单位…", + actionToRmb: "转为人民币大写…", + sectionUnitCategories: "单位分类(回车打开换算看板)", + unitCategoryItemSubtitle: "{count} 个单位,如 {examples}", + actionOpenCategoryBoard: "打开{category}换算看板", + + // 单位分类与计量体系 + unitCatLength: "长度", + unitCatMass: "质量", + unitCatArea: "面积", + unitCatVolume: "体积", + unitCatSpeed: "速度", + unitCatAngle: "角度", + unitCatDigital: "数据存储", + unitCatEnergy: "功与能量", + unitCatTemp: "温度", + unitSystemMetric: "公制", + unitSystemUs: "美制", + unitSystemImperial: "英制", + unitSystemUsImperial: "英美制", + unitSystemChinese: "市制", + unitSystemOther: "其他", + unitSystemGeneral: "通用", + + // 单位换算看板 + unitBoardNavTitle: "单位换算", + unitBoardPlaceholder: "输入数值或算式换算(当前基准:{unit}),输入“5 kg”可直接切换基准单位", + unitBoardCategoryTooltip: "选择单位分类", + unitBoardCategoryOption: "{name}({count} 个单位)", + unitBoardSection: "{category}换算(基准 {value} {unit} · 保留 {precision} 位小数)", + unitBoardInvalidInput: "请输入有效的数值或算式,例如 100、2.5、1e4、3*12", + unitBoardInvalidAccessory: "数值格式异常", + unitBoardResetInput: "重置为 1", + unitBoardBelowAbsoluteZero: "温度不能低于绝对零度(0 K / -273.15 °C / -459.67 °F)", + unitBoardBaseAccessory: "基准单位", + unitBoardOverflow: "超出数值范围", + unitBoardRowSubtitle: "{name} · {system}", + unitBoardActionCopyWithUnit: "复制结果({text})", + unitBoardActionCopyNumber: "复制纯数值", + unitBoardActionCopyEquation: "复制换算等式", + unitBoardActionSetBase: "设为基准单位({name})", + unitBoardPrecisionSubmenu: "调整保留小数位数", + unitBoardPrecisionOption: "保留 {digits} 位小数", + unitBoardBaseChangedToast: "已将基准单位设为:{unit}" }, "en-US": { // Main calculator categories @@ -253,7 +374,7 @@ export const t = createTranslator( clearedHistoryToast: "Cleared all calculation history", actionOpenRmb: "RMB Uppercase…", actionOpenCurrency: "Currency Converter…", - placeholderUnitOnly: "Enter conversion, e.g. 10km to miles, 5kg to lbs, 100c to f, 1024mb to gb", + placeholderUnitOnly: "Enter conversion, e.g. 10km to miles, 5kg to lbs, 100c to f, 1 acre to m2, 100 km/h to mph", placeholderDefault: "Enter expression, e.g. 128*1024, 32px to rem, 0xFF to dec, now + 2 weeks", // Color section @@ -396,15 +517,136 @@ export const t = createTranslator( currXAU: "Gold (oz)", currBTC: "Bitcoin", - // RMB Uppercase + // RMB Uppercase & Chinese numerals rmbNavTitle: "Chinese RMB Uppercase", - rmbSearchPlaceholder: "Enter amount, e.g. 12345.67 (up to 2 decimals)", - rmbIdleTitle: "Enter an amount to convert to RMB uppercase", - rmbIdleSubtitle: "Up to 2 decimal places, exact without rounding", - rmbResultSubtitle: "¥ {amount} CNY", + rmbSearchPlaceholder: "Enter an amount (e.g. 12345.67) or Chinese numerals to convert both ways", + rmbIdleTitle: "Enter an amount or Chinese numerals to convert", + rmbIdleSubtitle: "Numbers to RMB uppercase and Chinese numerals; Chinese numerals back to digits", rmbActionCopy: "Copy Uppercase Amount", - rmbErrInvalidFormat: "Enter a valid amount with at most 2 decimal places (no rounding)", - rmbErrTooLarge: "Maximum supported amount is 999,999,999,999.99" + rmbActionCopyUpper: "Copy Chinese Uppercase", + rmbActionCopyLower: "Copy Chinese Lowercase", + rmbActionCopyArabic: "Copy Arabic Number", + rmbActionCopyPair: "Copy Input = Result", + rmbActionClearInput: "Clear Input", + rmbTagTicket: "RMB uppercase", + rmbTagUpper: "Uppercase", + rmbTagLower: "Lowercase", + rmbTagArabic: "Arabic", + rmbRowTicketSubtitle: "Invoice RMB uppercase · {rounding}", + rmbRowTicketFailedSubtitle: "Cannot format as RMB uppercase; change cent handling in the invoice rules", + rmbRowUpperSubtitle: "Chinese financial uppercase numerals", + rmbRowLowerSubtitle: "Chinese everyday numerals", + rmbRowArabicSubtitle: "Arabic number", + rmbRowArabicColloquialSubtitle: "Arabic number (read as colloquial shorthand: {reading})", + rmbErrorSubtitle: "Enter an Arabic number (e.g. 12345.67) or Chinese numerals", + rmbSectionResults: "Conversion Results", + rmbSectionExamples: "Examples (Enter to fill)", + rmbActionFillExample: "Fill Example", + rmbExampleInvoice: "Typical invoice amount", + rmbExampleFen: "Cents only", + rmbExampleLarge: "Large amount across units", + rmbExampleTicketReverse: "Reverse lookup of RMB uppercase", + rmbExampleLowerReverse: "Chinese lowercase numerals", + rmbExampleColloquial: "Colloquial shorthand", + rmbSectionRules: "Invoice Uppercase Rules", + rmbRulesSubmenu: "Invoice Uppercase Rules", + rmbActionToggleRule: "Toggle Rule", + rmbRuleChangedToast: "Updated: {rule}", + rmbRulePrefix: "Currency prefix: {value}", + rmbRulePrefixOn: "Renminbi", + rmbRulePrefixOff: "None", + rmbRulePrefixHint: "Adds the Renminbi prefix before the uppercase amount", + rmbRuleYuan: "Yuan character: {value}", + rmbRuleYuanStandard: "Standard form", + rmbRuleYuanFormal: "Formal variant", + rmbRuleYuanHint: "Bank instrument rules allow either yuan character", + rmbRuleWhole: "Whole-amount suffix: {value}", + rmbRuleWholeStandard: "Standard form", + rmbRuleWholeAlt: "Variant form", + rmbRuleWholeHint: "Suffix written when the amount has no jiao or fen", + rmbRuleRounding: "Cent handling: {value}", + rmbRoundingExact: "Exact to the cent (error beyond 2 decimals)", + rmbRoundingHalfUp: "Round half up to the cent", + rmbRoundingTruncate: "Truncate to the cent", + rmbRuleRoundingHint: "How amounts with more than 2 decimals are handled", + rmbRuleZeroYuan: "Below one yuan: {value}", + rmbRuleZeroYuanShow: "Write zero yuan", + rmbRuleZeroYuanHide: "Omit zero yuan", + rmbRuleZeroYuanHint: "Whether amounts under one yuan start with zero yuan", + + // Chinese numeral parsing & conversion errors + cnErrEmptyNumber: "Please enter a valid number", + cnErrTooLong: "Input cannot exceed 256 characters", + cnErrSeparator: "Thousands separators are misplaced", + cnErrInvalidDecimal: "Not a valid decimal number", + cnErrIntegerTooLong: "The integer part supports at most 16 digits", + cnErrFractionTooLong: "The fractional part supports at most 16 digits", + cnErrEmptyChinese: "Please enter Chinese numerals", + cnErrInvalidChars: "Contains characters that are not Chinese numerals", + cnErrDigitOrder: "Chinese numeral digits are out of order", + cnErrConsecutiveDigits: "Digits cannot appear consecutively when units are used", + cnErrSmallUnitOrder: "Ten / hundred / thousand units are out of order", + cnErrLargeUnitOrder: "Ten-thousand / hundred-million / trillion units are out of order", + cnErrUnknownChar: "Unrecognized character \"{char}\"", + cnErrTrailingZero: "Chinese numerals cannot end with a meaningless zero", + cnErrTicketFormat: "Invalid RMB uppercase format or unit order", + cnErrMissingYuan: "The integer amount is missing the yuan unit", + cnErrMissingTicketUnit: "The amount is missing yuan, jiao or fen", + cnErrMissingAmountBeforeYuan: "Missing amount before the yuan unit", + cnErrWholeMisuse: "The whole-amount suffix can only follow an amount without jiao or fen", + cnErrNegativePosition: "The negative sign is misplaced", + cnErrMultiplePoints: "Only one decimal point is allowed", + cnErrMissingFraction: "Missing digits after the decimal point", + cnErrFractionDigits: "The fractional part must be written digit by digit", + cnErrExactDecimals: "At most 2 decimal places (exact to the cent; switch to rounding or truncation in the invoice rules)", + cnErrRoundOverflow: "The rounded integer amount exceeds 16 digits", + + // Main calculator: unit board & RMB entry points + actionOpenUnitBoard: "Unit Converter Board…", + actionViewAllUnits: "View All Units in Board…", + actionToRmb: "Convert to RMB Uppercase…", + sectionUnitCategories: "Unit Categories (Enter to open board)", + unitCategoryItemSubtitle: "{count} units, e.g. {examples}", + actionOpenCategoryBoard: "Open {category} Board", + + // Unit categories & measurement systems + unitCatLength: "Length", + unitCatMass: "Mass", + unitCatArea: "Area", + unitCatVolume: "Volume", + unitCatSpeed: "Speed", + unitCatAngle: "Angle", + unitCatDigital: "Data Storage", + unitCatEnergy: "Energy", + unitCatTemp: "Temperature", + unitSystemMetric: "Metric", + unitSystemUs: "US", + unitSystemImperial: "Imperial", + unitSystemUsImperial: "US & Imperial", + unitSystemChinese: "Chinese", + unitSystemOther: "Other", + unitSystemGeneral: "General", + + // Unit converter board + unitBoardNavTitle: "Unit Converter", + unitBoardPlaceholder: "Enter a value or expression (base: {unit}); type \"5 kg\" to switch the base unit", + unitBoardCategoryTooltip: "Unit category", + unitBoardCategoryOption: "{name} ({count} units)", + unitBoardSection: "{category} (base {value} {unit} · {precision} decimals)", + unitBoardInvalidInput: "Enter a valid number or expression, e.g. 100, 2.5, 1e4, 3*12", + unitBoardInvalidAccessory: "Invalid value", + unitBoardResetInput: "Reset to 1", + unitBoardBelowAbsoluteZero: "Temperature cannot be below absolute zero (0 K / -273.15 °C / -459.67 °F)", + unitBoardBaseAccessory: "Base unit", + unitBoardOverflow: "Out of range", + unitBoardRowSubtitle: "{name} · {system}", + unitBoardActionCopyWithUnit: "Copy Result ({text})", + unitBoardActionCopyNumber: "Copy Number Only", + unitBoardActionCopyEquation: "Copy Conversion Equation", + unitBoardActionSetBase: "Set as Base Unit ({name})", + unitBoardPrecisionSubmenu: "Decimal Places", + unitBoardPrecisionOption: "{digits} decimal places", + unitBoardBaseChangedToast: "Base unit set to {unit}" } }, { defaultLocale: "en-US" } @@ -439,3 +681,44 @@ export function getCurrencyName(code: string, fallback?: string): string { const key = CURRENCY_NAME_KEYS[code]; return key ? t(key) : (fallback ?? code); } + +type UnitCategoryNameKey = + | "unitCatLength" | "unitCatMass" | "unitCatArea" | "unitCatVolume" | "unitCatSpeed" + | "unitCatAngle" | "unitCatDigital" | "unitCatEnergy" | "unitCatTemp"; + +const UNIT_CATEGORY_NAME_KEYS: Readonly> = Object.freeze({ + length: "unitCatLength", + mass: "unitCatMass", + area: "unitCatArea", + volume: "unitCatVolume", + speed: "unitCatSpeed", + angle: "unitCatAngle", + digital: "unitCatDigital", + energy: "unitCatEnergy", + temp: "unitCatTemp" +}); + +/** 单位分类的本地化名称;未知分类原样返回 id */ +export function getUnitCategoryName(categoryId: string): string { + const key = UNIT_CATEGORY_NAME_KEYS[categoryId]; + return key ? t(key) : categoryId; +} + +type UnitSystemKey = + | "unitSystemMetric" | "unitSystemUs" | "unitSystemImperial" | "unitSystemUsImperial" + | "unitSystemChinese" | "unitSystemOther"; + +const UNIT_SYSTEM_KEYS: Readonly> = Object.freeze({ + metric: "unitSystemMetric", + us: "unitSystemUs", + imperial: "unitSystemImperial", + "us-imperial": "unitSystemUsImperial", + chinese: "unitSystemChinese", + other: "unitSystemOther" +}); + +/** 计量体系标签;未标注体系的单位(速度、角度等)显示“通用” */ +export function getUnitSystemLabel(system?: string): string { + const key = system ? UNIT_SYSTEM_KEYS[system] : undefined; + return key ? t(key) : t("unitSystemGeneral"); +} diff --git a/extensions/calculator/src/index.tsx b/extensions/calculator/src/index.tsx index 8b032c23..0177e8d0 100644 --- a/extensions/calculator/src/index.tsx +++ b/extensions/calculator/src/index.tsx @@ -10,8 +10,9 @@ import { Clipboard } from "@ztools/declarative-ui"; import { useState, useEffect, useMemo, useNavigation, useLocale } from "@ztools/declarative-ui"; -import { t } from "./i18n.js"; +import { t, getUnitCategoryName } from "./i18n.js"; import RmbCommand from "./rmb.js"; +import UnitBoardCommand, { type UnitBoardProps } from "./unit-board.js"; import CurrencyCommand, { useRates } from "./currency.js"; export { default as calcRmb } from "./rmb.js"; export { default as calcCurrency } from "./currency.js"; @@ -32,6 +33,8 @@ import { togglePinCalculatorHistory, deleteCalculatorHistory, clearCalculatorHistory, + getUnitName, + UNIT_CATEGORIES, CalculatorQueryResult, CalculatorHistoryItem, CalculatorColorResult, @@ -53,25 +56,32 @@ const DEFAULT_CALC_EXAMPLES: ReadonlyArray<{ categoryKey: ExampleCategoryKey; isUnit?: boolean; }> = [ + { expr: "100 usd to cny", descKey: "eg16Desc", categoryKey: "catCurrency" }, { expr: "1024 * 768", descKey: "eg0Desc", categoryKey: "catMath" }, + { expr: "now + 2 weeks", descKey: "eg13Desc", categoryKey: "catDate" }, + { expr: "5kg to lbs", descKey: "eg7Desc", categoryKey: "catUnit", isUnit: true }, + { expr: "10km to miles", descKey: "eg6Desc", categoryKey: "catUnit", isUnit: true }, + { expr: "100c to f", descKey: "eg8Desc", categoryKey: "catUnit", isUnit: true }, + { expr: "1024mb to gb", descKey: "eg9Desc", categoryKey: "catUnit", isUnit: true }, { expr: "sqrt(65536)", descKey: "eg1Desc", categoryKey: "catMath" }, { expr: "2 ^ 16", descKey: "eg2Desc", categoryKey: "catMath" }, { expr: "sin(pi / 2)", descKey: "eg3Desc", categoryKey: "catMath" }, { expr: "32px to rem", descKey: "eg4Desc", categoryKey: "catUnit", isUnit: true }, { expr: "2.5rem to px", descKey: "eg5Desc", categoryKey: "catUnit", isUnit: true }, - { expr: "10km to miles", descKey: "eg6Desc", categoryKey: "catUnit", isUnit: true }, - { expr: "5kg to lbs", descKey: "eg7Desc", categoryKey: "catUnit", isUnit: true }, - { expr: "100c to f", descKey: "eg8Desc", categoryKey: "catUnit", isUnit: true }, - { expr: "1024mb to gb", descKey: "eg9Desc", categoryKey: "catUnit", isUnit: true }, - { expr: "0xFF to dec", descKey: "eg10Desc", categoryKey: "catRadix" }, - { expr: "255 to hex", descKey: "eg11Desc", categoryKey: "catRadix" }, - { expr: "255 to bin", descKey: "eg12Desc", categoryKey: "catRadix" }, - { expr: "now + 2 weeks", descKey: "eg13Desc", categoryKey: "catDate" }, { expr: "#3B82F6", descKey: "eg14Desc", categoryKey: "catColor" }, { expr: "rgb(59, 130, 246)", descKey: "eg15Desc", categoryKey: "catColor" }, - { expr: "100 usd to cny", descKey: "eg16Desc", categoryKey: "catCurrency" } + { expr: "0xFF to dec", descKey: "eg10Desc", categoryKey: "catRadix" }, + { expr: "255 to hex", descKey: "eg11Desc", categoryKey: "catRadix" }, + { expr: "255 to bin", descKey: "eg12Desc", categoryKey: "catRadix" } ]; +function exampleIconForCategory(categoryKey: ExampleCategoryKey) { + if (categoryKey === "catCurrency") return Icon.Globe; + if (categoryKey === "catDate") return Icon.Clock; + if (categoryKey === "catUnit") return Icon.ArrowRight; + return Icon.Pencil; +} + type HistoryTypeKey = "historyTypeMath" | "historyTypeUnit" | "historyTypeCurrency" | "historyTypeDate" | "historyTypeColor"; const HISTORY_TYPE_KEYS: Record = { @@ -320,14 +330,84 @@ export default function CalculatorCommand(props?: CalculatorProps) { push(() => CurrencyCommand(initialQuery ? { initialQuery } : undefined)); }; + const openUnitBoard = (boardProps?: UnitBoardProps) => { + push(() => UnitBoardCommand(boardProps)); + }; + + const openRmb = (initialQuery?: string) => { + push(() => RmbCommand(initialQuery ? { initialQuery } : undefined)); + }; + + // 数学结果是普通十进制数(不是科学计数法)时,可直接带入人民币大写 + const rmbCandidate = + queryResult.type === "math" && !queryResult.error && queryResult.fillText && /^-?\d+(?:\.\d+)?$/.test(queryResult.fillText) + ? queryResult.fillText + : undefined; + const pinnedItems = history.filter((item) => item.pinned); const recentItems = history.filter((item) => !item.pinned); + const hasActiveResult = queryResult.type !== "none" && !queryResult.error && !queryResult.loadingCurrency; + + const renderHistoryItem = (item: CalculatorHistoryItem, isPinned: boolean) => ( + + handleCopy(item.answer, isPinned ? t("labelPinnedResult") : t("labelHistoryResult"), false)} + /> + handlePaste(item.answer, false)} + /> + handleTogglePin(item.id)} + /> + fillSearch(item.expression, item.id)} + /> + handleDeleteHistory(item.id)} + /> + {!isPinned && ( + + )} + + } + /> + ); return ( push(RmbCommand) }), + Action({ title: t("actionOpenRmb"), icon: Icon.Text, onAction: () => openRmb() }), + Action({ title: t("actionOpenUnitBoard"), icon: Icon.ArrowRight, onAction: () => openUnitBoard() }), Action({ title: t("actionOpenCurrency"), icon: Icon.Globe, onAction: () => openCurrencyBoard() }) ])} searchBarPlaceholder={ @@ -377,6 +457,7 @@ export default function CalculatorCommand(props?: CalculatorProps) { handlePaste(queryResult.colorResult!.hex)} /> @@ -395,6 +476,12 @@ export default function CalculatorCommand(props?: CalculatorProps) { icon={Icon.CopyClipboard} onAction={() => handleCopy(queryResult.colorResult!.rgb, "RGB")} /> + handlePaste(queryResult.colorResult!.rgb)} + /> } /> @@ -411,6 +498,12 @@ export default function CalculatorCommand(props?: CalculatorProps) { icon={Icon.CopyClipboard} onAction={() => handleCopy(queryResult.colorResult!.hsl, "HSL")} /> + handlePaste(queryResult.colorResult!.hsl)} + /> } /> @@ -427,6 +520,12 @@ export default function CalculatorCommand(props?: CalculatorProps) { icon={Icon.CopyClipboard} onAction={() => handleCopy(queryResult.colorResult!.cmyk, "CMYK")} /> + handlePaste(queryResult.colorResult!.cmyk)} + /> } /> @@ -475,7 +574,7 @@ export default function CalculatorCommand(props?: CalculatorProps) { ? `${queryResult.expression} (${queryResult.details})` : queryResult.expression } - icon={queryResult.type === "currency" ? Icon.Globe : Icon.Terminal} + icon={queryResult.type === "currency" ? Icon.Globe : queryResult.type === "date" ? Icon.Clock : Icon.Checkmark} accessories={[{ text: t("accessoryEnterCopy") }]} actions={ @@ -535,6 +634,28 @@ export default function CalculatorCommand(props?: CalculatorProps) { } /> )} + {queryResult.unitSource !== undefined && ( + + openUnitBoard({ + categoryId: queryResult.unitSource!.categoryId, + unitId: queryResult.unitSource!.unitId, + initialValue: String(queryResult.unitSource!.value) + }) + } + /> + )} + {rmbCandidate !== undefined && ( + openRmb(rmbCandidate)} + /> + )} } /> @@ -545,92 +666,40 @@ export default function CalculatorCommand(props?: CalculatorProps) { {/* 3. 已置顶算式 */} {pinnedItems.length > 0 && ( - {pinnedItems.map((item) => ( - - handleCopy(item.answer, t("labelPinnedResult"), false)} - /> - handlePaste(item.answer, false)} - /> - handleTogglePin(item.id)} - /> - fillSearch(item.expression, item.id)} - /> - handleDeleteHistory(item.id)} - /> - - } - /> - ))} + {pinnedItems.map((item) => renderHistoryItem(item, true))} )} {/* 4. 最近计算历史 */} {recentItems.length > 0 && ( - {recentItems.slice(0, 15).map((item) => ( + {recentItems.slice(0, 15).map((item) => renderHistoryItem(item, false))} + + )} + + {/* 5. 快速计算、换算与语法示例(用户输入有效算式产出结果时自动收起减少视觉干扰) */} + {!hasActiveResult && ( + + {examples.map(({ idx, ...eg }) => ( - handleCopy(item.answer, t("labelHistoryResult"), false)} - /> + handlePaste(item.answer, false)} - /> - handleTogglePin(item.id)} - /> - fillSearch(item.expression, item.id)} + onAction={() => fillSearch(eg.expr, `eg-${idx}`)} /> handleDeleteHistory(item.id)} - /> - handleCopy(eg.expr, t("labelExpr"), false)} /> } @@ -639,34 +708,35 @@ export default function CalculatorCommand(props?: CalculatorProps) { )} - {/* 5. 快速计算、换算与语法示例 */} - - {examples.map(({ idx, ...eg }) => ( - - fillSearch(eg.expr, `eg-${idx}`)} - /> - handleCopy(eg.expr, t("labelExpr"), false)} - /> - - } - /> - ))} - + {/* 6. 单位换算入口:按分类打开全部单位对照看板 */} + {unitOnly && !hasActiveResult && ( + + {UNIT_CATEGORIES.map((category) => { + const name = getUnitCategoryName(category.id); + return ( + getUnitName(unit, locale)).join(" / ") + })} + icon={Icon.ArrowRight} + actions={ + + openUnitBoard({ categoryId: category.id })} + /> + + } + /> + ); + })} + + )} ); } diff --git a/extensions/calculator/src/rmb.ts b/extensions/calculator/src/rmb.ts index 7732e956..d92bed8b 100644 --- a/extensions/calculator/src/rmb.ts +++ b/extensions/calculator/src/rmb.ts @@ -1,66 +1,283 @@ -import { List, ActionPanel, Action, Icon, useState, useLocale } from "@ztools/declarative-ui"; +/** + * 人民币大写与中文数字视图(calc-rmb): + * - 输入阿拉伯数字:票据人民币大写、中文大写、中文小写; + * - 输入中文数字:阿拉伯数字(含口语省略提示)、票据大写、中文大写、中文小写; + * - 票据规则(人民币前缀、元/圆、整/正、分位处理、零元)在动作面板与规则区切换。 + */ +import { List, ActionPanel, Action, Icon, Clipboard, showToast, Toast, useState, useLocale } from "@ztools/declarative-ui"; import { t } from "./i18n.js"; +import { CHINESE_INPUT_EXAMPLES } from "./chinese-number.zh-data.js"; import { - RMB_DIGITS, - RMB_UNITS, - RMB_SECTION_UNITS, - RMB_ZERO, - RMB_NEGATIVE, - RMB_YUAN, - RMB_ZHENG, - RMB_JIAO, - RMB_FEN -} from "./rmb.zh-data.js"; - -function groupText(group: string): string { - let text = ""; - let zero = false; - for (let i = 0; i < group.length; i++) { - const digit = Number(group[i]); - if (digit === 0) { if (text) zero = true; continue; } - if (zero) text += RMB_ZERO; - text += RMB_DIGITS[digit] + RMB_UNITS[group.length - i - 1]; - zero = false; - } - return text; + ConversionError, + DEFAULT_TICKET_RULES, + TICKET_ROUNDING_MODES, + convertChineseNumberInput, + numberToChinese, + type ChineseNumberConversion, + type ChineseNumberRow, + type ChineseNumberRowKind, + type TicketRoundingMode, + type TicketRules +} from "./chinese-number.js"; + +export { + toChineseAmount, + numberToChinese, + numberToTicketUppercase, + parseChineseNumber, + chineseToNumber, + convertChineseNumberInput, + DEFAULT_TICKET_RULES +} from "./chinese-number.js"; + +export interface RmbCommandProps { + /** 打开时预填的输入(主计算器「转为人民币大写」带入计算结果) */ + readonly initialQuery?: string; +} + +type ListChild = ReturnType | ReturnType; +type ActionChild = ReturnType | ReturnType; + +type RowTagKey = "rmbTagTicket" | "rmbTagUpper" | "rmbTagLower" | "rmbTagArabic"; +type RowCopyKey = "rmbActionCopy" | "rmbActionCopyUpper" | "rmbActionCopyLower" | "rmbActionCopyArabic"; + +/** 结果行的固定 id 与文案;票据大写行沿用 rmb-result,旧快捷入口与测试都依赖它 */ +const ROW_META: Readonly> = { + arabic: { id: "rmb-arabic", tagKey: "rmbTagArabic", copyKey: "rmbActionCopyArabic" }, + ticket: { id: "rmb-result", tagKey: "rmbTagTicket", copyKey: "rmbActionCopy" }, + upper: { id: "rmb-upper", tagKey: "rmbTagUpper", copyKey: "rmbActionCopyUpper" }, + lower: { id: "rmb-lower", tagKey: "rmbTagLower", copyKey: "rmbActionCopyLower" } +}; + +type ArabicExampleKey = "rmbExampleInvoice" | "rmbExampleFen" | "rmbExampleLarge"; +type ChineseExampleKey = "rmbExampleTicketReverse" | "rmbExampleLowerReverse" | "rmbExampleColloquial"; + +const ARABIC_EXAMPLES: ReadonlyArray<{ value: string; labelKey: ArabicExampleKey }> = [ + { value: "12345.67", labelKey: "rmbExampleInvoice" }, + { value: "0.05", labelKey: "rmbExampleFen" }, + { value: "100200300.50", labelKey: "rmbExampleLarge" } +]; +const CHINESE_EXAMPLE_LABEL_KEYS: readonly ChineseExampleKey[] = ["rmbExampleTicketReverse", "rmbExampleLowerReverse", "rmbExampleColloquial"]; + +function roundingLabel(mode: TicketRoundingMode): string { + if (mode === "half-up") return t("rmbRoundingHalfUp"); + if (mode === "truncate") return t("rmbRoundingTruncate"); + return t("rmbRoundingExact"); +} + +function nextRounding(mode: TicketRoundingMode): TicketRoundingMode { + const index = TICKET_ROUNDING_MODES.indexOf(mode); + return TICKET_ROUNDING_MODES[(index + 1) % TICKET_ROUNDING_MODES.length] ?? "exact"; +} + +interface RuleDefinition { + readonly id: string; + readonly label: (rules: TicketRules) => string; + readonly hint: () => string; + readonly active: (rules: TicketRules) => boolean; + readonly next: (rules: TicketRules) => TicketRules; } -/** 按十进制原文转换到分,不经浮点运算或静默四舍五入。 */ -export function toChineseAmount(input: string): string { - const text = input.trim(); - if (!/^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d{1,2})?$/.test(text)) throw new Error(t("rmbErrInvalidFormat")); - const [rawInteger, rawFraction = ""] = text.replace(/^-/, "").replace(/,/g, "").split("."); - const integer = rawInteger.replace(/^0+(?=\d)/, ""); - if (integer.length > 12) throw new Error(t("rmbErrTooLarge")); - const groups: string[] = []; - for (let end = integer.length; end > 0; end -= 4) groups.unshift(integer.slice(Math.max(0, end - 4), end)); - let result = ""; - let gap = false; - for (let i = 0; i < groups.length; i++) { - const group = groups[i]; - if (Number(group) === 0) { if (result) gap = true; continue; } - if (result && (gap || Number(group) < 1000)) result += RMB_ZERO; - result += groupText(group) + RMB_SECTION_UNITS[groups.length - i - 1]; - gap = false; +const RULES: readonly RuleDefinition[] = [ + { + id: "prefix", + label: (r) => t("rmbRulePrefix", { value: r.currencyPrefix ? t("rmbRulePrefixOn") : t("rmbRulePrefixOff") }), + hint: () => t("rmbRulePrefixHint"), + active: (r) => r.currencyPrefix, + next: (r) => ({ ...r, currencyPrefix: !r.currencyPrefix }) + }, + { + id: "yuan", + label: (r) => t("rmbRuleYuan", { value: r.formalYuan ? t("rmbRuleYuanFormal") : t("rmbRuleYuanStandard") }), + hint: () => t("rmbRuleYuanHint"), + active: (r) => r.formalYuan, + next: (r) => ({ ...r, formalYuan: !r.formalYuan }) + }, + { + id: "whole", + label: (r) => t("rmbRuleWhole", { value: r.wholeAlt ? t("rmbRuleWholeAlt") : t("rmbRuleWholeStandard") }), + hint: () => t("rmbRuleWholeHint"), + active: (r) => r.wholeAlt, + next: (r) => ({ ...r, wholeAlt: !r.wholeAlt }) + }, + { + id: "rounding", + label: (r) => t("rmbRuleRounding", { value: roundingLabel(r.roundingMode) }), + hint: () => t("rmbRuleRoundingHint"), + active: (r) => r.roundingMode !== "exact", + next: (r) => ({ ...r, roundingMode: nextRounding(r.roundingMode) }) + }, + { + id: "zero-yuan", + label: (r) => t("rmbRuleZeroYuan", { value: r.showZeroYuan ? t("rmbRuleZeroYuanShow") : t("rmbRuleZeroYuanHide") }), + hint: () => t("rmbRuleZeroYuanHint"), + active: (r) => r.showZeroYuan, + next: (r) => ({ ...r, showZeroYuan: !r.showZeroYuan }) } - const [jiao, fen] = rawFraction.padEnd(2, "0").split("").map(Number); - const negative = text.startsWith("-") && (integer !== "0" || jiao !== 0 || fen !== 0); - result = (negative ? RMB_NEGATIVE : "") + (result || RMB_ZERO) + RMB_YUAN; - if (!jiao && !fen) return result + RMB_ZHENG; - if (jiao) result += RMB_DIGITS[jiao] + RMB_JIAO; - else if (integer !== "0") result += RMB_ZERO; - if (fen) result += RMB_DIGITS[fen] + RMB_FEN; - return result; +]; + +function errorMessage(error: unknown): string { + return error instanceof Error ? error.message : String(error); } -export default function RmbCommand() { - useLocale(); - const [text, setText] = useState(""); - let result = ""; let error = ""; - if (text.trim()) { - try { result = toChineseAmount(text); } - catch (err: unknown) { error = err instanceof Error ? err.message : String(err); } +export default function RmbCommand(props?: RmbCommandProps) { + const locale = useLocale(); + const initialQuery = typeof props?.initialQuery === "string" ? props.initialQuery : ""; + const [text, setText] = useState(initialQuery); + const [rules, setRules] = useState(DEFAULT_TICKET_RULES); + const trimmed = text.trim(); + const isChineseLocale = /^zh(?:[-_]|$)/i.test(String(locale ?? "")); + + let conversion: ChineseNumberConversion | null = null; + let inputError = ""; + if (trimmed) { + try { + conversion = convertChineseNumberInput(trimmed, rules); + } catch (error: unknown) { + inputError = error instanceof ConversionError ? error.message : errorMessage(error); + } + } + + const copy = async (value: string, label: string) => { + await Clipboard.copy(value); + await showToast(Toast.Style.Success, t("copiedToastTitle", { label }), value); + }; + + const paste = async (value: string) => { + await Clipboard.paste(value); + await showToast(Toast.Style.Success, t("pastedToastTitle"), value); + }; + + const toggleRule = async (rule: RuleDefinition) => { + const updated = rule.next(rules); + setRules(updated); + await showToast(Toast.Style.Success, t("rmbRuleChangedToast", { rule: rule.label(updated) })); + }; + + const rulesSubmenu = (): ActionChild => + ActionPanel.Submenu( + { title: t("rmbRulesSubmenu"), icon: Icon.Gear }, + RULES.map((rule) => + Action({ + key: `rule-${rule.id}`, + title: rule.label(rules), + icon: rule.active(rules) ? Icon.Check : Icon.Circle, + onAction: () => toggleRule(rule) + }) + ) + ); + + const rowSubtitle = (row: ChineseNumberRow): string => { + if (row.kind === "ticket") return t("rmbRowTicketSubtitle", { rounding: roundingLabel(rules.roundingMode) }); + if (row.kind === "upper") return t("rmbRowUpperSubtitle"); + if (row.kind === "lower") return t("rmbRowLowerSubtitle"); + // 口语省略写法(三百五、一万五)与规范写法(三百零五)结果不同,附上规范读法便于核对 + return row.colloquial && row.value + ? t("rmbRowArabicColloquialSubtitle", { reading: numberToChinese(row.value, "lower") }) + : t("rmbRowArabicSubtitle"); + }; + + const resultItem = (row: ChineseNumberRow) => { + const meta = ROW_META[row.kind]; + const tag = t(meta.tagKey); + const value = row.value; + if (row.error || value === undefined) { + return List.Item({ + id: meta.id, + title: row.error ?? "", + subtitle: t("rmbRowTicketFailedSubtitle"), + icon: Icon.ExclamationMark, + accessories: [{ text: tag }], + actions: ActionPanel({ title: tag }, [rulesSubmenu()]) + }); + } + return List.Item({ + id: meta.id, + title: value, + subtitle: rowSubtitle(row), + icon: row.kind === "ticket" ? Icon.Document : Icon.Text, + accessories: [{ text: tag }, { text: t("accessoryEnterCopy"), icon: Icon.CopyClipboard }], + actions: ActionPanel({ title: tag }, [ + Action({ title: t(meta.copyKey), icon: Icon.CopyClipboard, onAction: () => copy(value, tag) }), + Action({ + title: t("actionPasteToApp"), + icon: Icon.Checkmark, + shortcut: { modifiers: ["ctrl", "shift"], key: "v" }, + onAction: () => paste(value) + }), + Action({ + title: t("rmbActionCopyPair"), + icon: Icon.Document, + shortcut: { modifiers: ["ctrl", "alt"], key: "c" }, + onAction: () => copy(`${trimmed} = ${value}`, t("labelFullExpr")) + }), + rulesSubmenu() + ]) + }); + }; + + const exampleItem = (value: string, label: string, index: number) => + List.Item({ + id: `rmb-eg-${index}`, + title: value, + subtitle: label, + icon: Icon.Star, + actions: ActionPanel({ title: t("panelExamples") }, [ + Action({ title: t("rmbActionFillExample"), icon: Icon.Pencil, onAction: () => setText(value) }), + Action({ title: t("actionCopyExpr"), icon: Icon.CopyClipboard, onAction: () => copy(value, label) }) + ]) + }); + + const children: ListChild[] = []; + if (inputError) { + children.push( + List.Section({ title: t("rmbSectionResults") }, [ + List.Item({ + id: "rmb-error", + title: inputError, + subtitle: t("rmbErrorSubtitle"), + icon: Icon.ExclamationMark, + actions: ActionPanel({}, [ + Action({ title: t("rmbActionClearInput"), icon: Icon.Trash, onAction: () => setText("") }) + ]) + }) + ]) + ); + } else if (conversion) { + children.push(List.Section({ title: t("rmbSectionResults") }, conversion.rows.map(resultItem))); + } else { + children.push( + List.Item({ id: "rmb-input", title: t("rmbIdleTitle"), subtitle: t("rmbIdleSubtitle"), icon: Icon.Text }) + ); + // 中文输入示例本身是中文,只在中文界面展示 + const examples = [ + ...ARABIC_EXAMPLES.map((eg) => ({ value: eg.value, label: t(eg.labelKey) })), + ...(isChineseLocale + ? CHINESE_INPUT_EXAMPLES.map((value, index) => ({ value, label: t(CHINESE_EXAMPLE_LABEL_KEYS[index] ?? "rmbExampleLowerReverse") })) + : []) + ]; + children.push( + List.Section({ title: t("rmbSectionExamples") }, examples.map((eg, index) => exampleItem(eg.value, eg.label, index))) + ); } + + children.push( + List.Section( + { title: t("rmbSectionRules") }, + RULES.map((rule) => + List.Item({ + id: `rmb-rule-${rule.id}`, + title: rule.label(rules), + subtitle: rule.hint(), + icon: rule.active(rules) ? Icon.Check : Icon.Circle, + actions: ActionPanel({ title: t("rmbRulesSubmenu") }, [ + Action({ title: t("rmbActionToggleRule"), icon: Icon.Repeat, onAction: () => toggleRule(rule) }) + ]) + }) + ) + ) + ); + return List( { navigationTitle: t("rmbNavTitle"), @@ -68,14 +285,6 @@ export default function RmbCommand() { onSearchTextChange: setText, searchBarPlaceholder: t("rmbSearchPlaceholder") }, - [ - List.Item({ - id: result ? "rmb-result" : "rmb-input", - title: result || error || t("rmbIdleTitle"), - subtitle: result ? t("rmbResultSubtitle", { amount: text.trim() }) : t("rmbIdleSubtitle"), - icon: error ? Icon.ExclamationMark : Icon.Text, - actions: result ? ActionPanel({}, [Action.CopyToClipboard({ title: t("rmbActionCopy"), content: result })]) : undefined - }) - ] + children ); } diff --git a/extensions/calculator/src/rmb.zh-data.ts b/extensions/calculator/src/rmb.zh-data.ts deleted file mode 100644 index 5c10bf12..00000000 --- a/extensions/calculator/src/rmb.zh-data.ts +++ /dev/null @@ -1,10 +0,0 @@ -/** 人民币中文大写转换所需的静态汉字表 */ -export const RMB_DIGITS = "零壹贰叁肆伍陆柒捌玖"; -export const RMB_UNITS: readonly string[] = Object.freeze(["", "拾", "佰", "仟"]); -export const RMB_SECTION_UNITS: readonly string[] = Object.freeze(["", "万", "亿"]); -export const RMB_ZERO = "零"; -export const RMB_NEGATIVE = "负"; -export const RMB_YUAN = "元"; -export const RMB_ZHENG = "整"; -export const RMB_JIAO = "角"; -export const RMB_FEN = "分"; diff --git a/extensions/calculator/src/unit-board.ts b/extensions/calculator/src/unit-board.ts new file mode 100644 index 00000000..866b2c75 --- /dev/null +++ b/extensions/calculator/src/unit-board.ts @@ -0,0 +1,236 @@ +/** + * 单位换算看板:选定分类后,把输入数值一次换算成该分类下的全部单位。 + * - 分类下拉切换 9 大分类(长度、质量、面积、体积、速度、角度、数据存储、功与能量、温度); + * - 输入框支持数值、科学计数法与算式(3*12),也可输入“5 kg”直接切换分类与基准单位; + * - 每行可复制带单位结果、纯数值、换算等式,设为基准单位,调整保留小数位数。 + */ +import { List, ActionPanel, Action, Icon, Clipboard, showToast, Toast, useState, useLocale } from "@ztools/declarative-ui"; +import { t, getUnitCategoryName, getUnitSystemLabel } from "./i18n.js"; +import { + UNIT_CATEGORIES, + convertUnitValue, + evaluateMathExpression, + findUnitCategory, + formatUnitValue, + getUnitName, + getUnitSymbol, + resolveUnitAlias, + type UnitCategoryDefinition, + type UnitCategoryId, + type UnitDefinition +} from "./calculator-engine.js"; + +export interface UnitBoardProps { + readonly categoryId?: UnitCategoryId; + readonly unitId?: string; + readonly initialValue?: string; +} + +type ListChild = ReturnType | ReturnType; + +const PRECISION_OPTIONS: readonly number[] = [0, 2, 4, 6, 8, 10]; +const DEFAULT_PRECISION = 4; +const PLAIN_NUMBER_RE = /^[+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?$/i; +/** “5 kg”“3斤”“100 km/h”:数值 + 单位,单位写法与内联换算一致 */ +const VALUE_WITH_UNIT_RE = /^([+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?)\s*([a-z\u4e00-\u9fa5°′″][a-z0-9\u4e00-\u9fa5°′″²³/·]*)$/i; + +type ParsedBoardInput = + | { readonly kind: "value"; readonly value: number; readonly unitOverride?: { category: UnitCategoryDefinition; unit: UnitDefinition } } + | { readonly kind: "error" }; + +/** 解析看板输入:空输入按 1 处理;数值;数值 + 已知单位;其余交给安全算式求值 */ +function parseBoardInput(raw: string, locale: string | undefined): ParsedBoardInput { + const text = raw.trim(); + if (!text) return { kind: "value", value: 1 }; + if (PLAIN_NUMBER_RE.test(text)) { + const value = Number(text); + return Number.isFinite(value) ? { kind: "value", value } : { kind: "error" }; + } + const withUnit = text.match(VALUE_WITH_UNIT_RE); + if (withUnit) { + const ref = resolveUnitAlias(withUnit[2] ?? ""); + const value = Number(withUnit[1]); + if (ref && Number.isFinite(value)) return { kind: "value", value, unitOverride: ref }; + } + const math = evaluateMathExpression(text, { locale }); + if (math.isCalculation && !math.error && math.answer !== null && Number.isFinite(math.answer)) { + return { kind: "value", value: math.answer }; + } + return { kind: "error" }; +} + +export default function UnitBoardCommand(props?: UnitBoardProps) { + const locale = useLocale(); + const initialCategory = (props?.categoryId && findUnitCategory(props.categoryId)) || UNIT_CATEGORIES[0]!; + const initialUnit = + initialCategory.units.find((unit) => unit.id === props?.unitId)?.id ?? initialCategory.defaultFrom; + const [categoryId, setCategoryId] = useState(initialCategory.id); + const [fromUnitId, setFromUnitId] = useState(initialUnit); + const [searchText, setSearchText] = useState(typeof props?.initialValue === "string" ? props.initialValue : ""); + const [precision, setPrecision] = useState(DEFAULT_PRECISION); + + const parsed = parseBoardInput(searchText, locale); + // 输入里带了单位(5 kg)时以输入为准,不改动保存的分类,清掉单位后恢复原来的选择 + const selectedCategory = findUnitCategory(categoryId) ?? UNIT_CATEGORIES[0]!; + const category = parsed.kind === "value" && parsed.unitOverride ? parsed.unitOverride.category : selectedCategory; + const fromUnit = + parsed.kind === "value" && parsed.unitOverride + ? parsed.unitOverride.unit + : category.units.find((unit) => unit.id === fromUnitId) ?? category.units[0]!; + const categoryName = getUnitCategoryName(category.id); + const fromSymbol = getUnitSymbol(fromUnit, locale); + const fromLabel = `${getUnitName(fromUnit, locale)} [${fromSymbol}]`; + const value = parsed.kind === "value" ? parsed.value : 1; + const valueText = formatUnitValue(value, 12); + + const copy = async (text: string, label: string) => { + await Clipboard.copy(text); + await showToast(Toast.Style.Success, t("copiedToastTitle", { label }), text); + }; + + const changeCategory = (nextId: string) => { + const next = findUnitCategory(nextId); + if (!next) return; + // 输入里带单位(5 kg)时切换分类要去掉单位,否则显示仍由输入里的单位决定 + if (parsed.kind === "value" && parsed.unitOverride) setSearchText(valueText); + setCategoryId(next.id); + setFromUnitId(next.defaultFrom); + }; + + const setBaseUnit = async (unit: UnitDefinition) => { + // 输入里带单位时先去掉单位,只保留数值,避免设好的基准被输入里的单位覆盖 + if (parsed.kind === "value" && parsed.unitOverride) setSearchText(valueText); + setCategoryId(category.id); + setFromUnitId(unit.id); + await showToast(Toast.Style.Success, t("unitBoardBaseChangedToast", { unit: `${getUnitName(unit, locale)} (${getUnitSymbol(unit, locale)})` })); + }; + + const precisionSubmenu = () => + ActionPanel.Submenu( + { title: t("unitBoardPrecisionSubmenu"), icon: Icon.Gear }, + PRECISION_OPTIONS.map((digits) => + Action({ + key: `precision-${digits}`, + title: t("unitBoardPrecisionOption", { digits }), + icon: digits === precision ? Icon.Check : Icon.Circle, + onAction: () => setPrecision(digits) + }) + ) + ); + + const unitItem = (unit: UnitDefinition) => { + const isBase = unit.id === fromUnit.id; + const symbol = getUnitSymbol(unit, locale); + const name = getUnitName(unit, locale); + const subtitle = t("unitBoardRowSubtitle", { name, system: getUnitSystemLabel(unit.system) }); + const converted = convertUnitValue(value, category.id, fromUnit.id, unit.id); + if (!converted.ok) { + return List.Item({ + id: `unit-${unit.id}`, + title: t("unitBoardOverflow"), + subtitle, + icon: Icon.ExclamationMark, + accessories: [{ text: symbol }], + actions: ActionPanel({ title: name }, [ + Action({ title: t("unitBoardActionSetBase", { name }), icon: Icon.ArrowRight, onAction: () => setBaseUnit(unit) }), + precisionSubmenu() + ]) + }); + } + const formatted = formatUnitValue(converted.value, precision); + const withUnit = `${formatted} ${symbol}`; + return List.Item({ + id: `unit-${unit.id}`, + title: withUnit, + subtitle, + icon: isBase ? Icon.Check : Icon.Circle, + keywords: [name, symbol, unit.id], + accessories: isBase + ? [{ text: t("unitBoardBaseAccessory") }] + : [{ text: t("accessoryEnterCopy"), icon: Icon.CopyClipboard }], + actions: ActionPanel({ title: name }, [ + Action({ title: t("unitBoardActionCopyWithUnit", { text: withUnit }), icon: Icon.CopyClipboard, onAction: () => copy(withUnit, name) }), + Action({ + title: t("unitBoardActionCopyNumber"), + icon: Icon.CopyClipboard, + shortcut: { modifiers: ["ctrl", "shift"], key: "c" }, + onAction: () => copy(formatted, name) + }), + Action({ + title: t("actionPasteToApp"), + icon: Icon.Checkmark, + shortcut: { modifiers: ["ctrl", "shift"], key: "v" }, + onAction: async () => { + await Clipboard.paste(withUnit); + await showToast(Toast.Style.Success, t("pastedToastTitle"), withUnit); + } + }), + Action({ + title: t("unitBoardActionCopyEquation"), + icon: Icon.Document, + shortcut: { modifiers: ["ctrl", "alt"], key: "c" }, + onAction: () => copy(`${valueText} ${fromSymbol} = ${withUnit}`, t("labelFullExpr")) + }), + Action({ + title: t("unitBoardActionSetBase", { name }), + icon: Icon.ArrowRight, + shortcut: { modifiers: ["ctrl"], key: "b" }, + onAction: () => setBaseUnit(unit) + }), + precisionSubmenu() + ]) + }); + }; + + const resetAction = Action({ title: t("unitBoardResetInput"), icon: Icon.Repeat, onAction: () => setSearchText("1") }); + const children: ListChild[] = []; + if (parsed.kind === "error") { + children.push( + List.Item({ + id: "unit-input-error", + title: t("unitBoardInvalidInput"), + subtitle: searchText.trim(), + icon: Icon.ExclamationMark, + accessories: [{ text: t("unitBoardInvalidAccessory") }], + actions: ActionPanel({}, [resetAction]) + }) + ); + } else if (category.id === "temp" && !convertUnitValue(value, "temp", fromUnit.id, "celsius").ok) { + children.push( + List.Item({ + id: "unit-input-error", + title: t("unitBoardBelowAbsoluteZero"), + subtitle: `${valueText} ${fromSymbol}`, + icon: Icon.ExclamationMark, + actions: ActionPanel({}, [resetAction]) + }) + ); + } else { + children.push( + List.Section( + { title: t("unitBoardSection", { category: categoryName, value: valueText, unit: fromLabel, precision }) }, + category.units.map(unitItem) + ) + ); + } + + return List( + { + navigationTitle: t("unitBoardNavTitle"), + searchBarPlaceholder: t("unitBoardPlaceholder", { unit: fromLabel }), + searchText, + onSearchTextChange: setSearchText, + searchBarAccessory: List.Dropdown( + { tooltip: t("unitBoardCategoryTooltip"), value: category.id, onChange: changeCategory }, + UNIT_CATEGORIES.map((item) => + List.Dropdown.Item({ + key: item.id, + title: t("unitBoardCategoryOption", { name: getUnitCategoryName(item.id), count: item.units.length }), + value: item.id + }) + ) + ) + }, + children + ); +} diff --git a/extensions/calculator/tests/chinese-number-merge.test.mjs b/extensions/calculator/tests/chinese-number-merge.test.mjs new file mode 100644 index 00000000..f5e063e9 --- /dev/null +++ b/extensions/calculator/tests/chinese-number-merge.test.mjs @@ -0,0 +1,233 @@ +// 人民币大写与中文数字(原 chinese-number-converter 插件已合并进计算器):算法与 calc-rmb 视图 +import test from 'node:test' +import assert from 'node:assert/strict' +import { setRuntimeLocale } from '@ztools/declarative-ui' +import { createHost, mount, mountPushed } from '../../shared/test-harness.mjs' +import CalculatorCommand, { calcRmb } from '../dist/index.js' +import { + DEFAULT_TICKET_RULES, + chineseToNumber, + convertChineseNumberInput, + numberToChinese, + numberToTicketUppercase, + parseArabicDecimal, + parseChineseNumber +} from '../dist/chinese-number.js' + +const host = createHost() +test.beforeEach(() => { + host.reset() + setRuntimeLocale('zh-CN') +}) + +const rules = (patch) => ({ ...DEFAULT_TICKET_RULES, ...patch }) + +test('数字转中文小写 / 中文大写:零与跨级(亿、万、千)、负数与小数', () => { + assert.equal(numberToChinese('12345.67', 'lower'), '一万二千三百四十五点六七') + assert.equal(numberToChinese('12345.67', 'upper'), '壹万贰仟叁佰肆拾伍点陆柒') + assert.equal(numberToChinese('100200300.5', 'lower'), '一亿零二十万零三百点五') + assert.equal(numberToChinese('100200300.5', 'upper'), '壹亿零贰拾万零叁佰点伍') + assert.equal(numberToChinese('10', 'lower'), '十') + assert.equal(numberToChinese('10', 'upper'), '壹拾') + assert.equal(numberToChinese('-0.00'), '零点零零') + assert.equal(numberToChinese('-3.5'), '负三点五') + assert.equal(numberToChinese('1,234'), '一千二百三十四') + assert.equal(numberToChinese('9999999999999999', 'upper'), '玖仟玖佰玖拾玖兆玖仟玖佰玖拾玖亿玖仟玖佰玖拾玖万玖仟玖佰玖拾玖') +}) + +test('票据大写:默认规则、人民币前缀、圆、正、零元与三种分位处理', () => { + assert.equal(numberToTicketUppercase('12345.67'), '壹万贰仟叁佰肆拾伍元陆角柒分') + assert.equal(numberToTicketUppercase('500'), '伍佰元整') + assert.equal(numberToTicketUppercase('10.05'), '壹拾元零伍分') + assert.equal(numberToTicketUppercase('0.05'), '零元伍分') + assert.equal(numberToTicketUppercase('0.05', rules({ showZeroYuan: false })), '伍分') + assert.equal(numberToTicketUppercase('0', rules({ showZeroYuan: false })), '零元整') + assert.equal(numberToTicketUppercase('500', rules({ currencyPrefix: true, formalYuan: true, wholeAlt: true })), '人民币伍佰圆正') + assert.equal(numberToTicketUppercase('-1.2', rules({ currencyPrefix: true })), '负人民币壹元贰角') + assert.equal(numberToTicketUppercase('10.555', rules({ roundingMode: 'half-up' })), '壹拾元伍角陆分') + assert.equal(numberToTicketUppercase('10.555', rules({ roundingMode: 'truncate' })), '壹拾元伍角伍分') + assert.equal(numberToTicketUppercase('0.995', rules({ roundingMode: 'half-up' })), '壹元整') + assert.equal(numberToTicketUppercase('-0.001', rules({ roundingMode: 'truncate' })), '零元整') + assert.throws(() => numberToTicketUppercase('10.555'), /精确到分/) + assert.throws(() => numberToTicketUppercase('9999999999999999.995', rules({ roundingMode: 'half-up' })), /超过 16 位/) +}) + +test('中文数字转阿拉伯数字:小写、大写、票据金额、负数、逐位写法与人民币前缀', () => { + assert.equal(chineseToNumber('壹万贰仟叁佰肆拾伍点陆柒'), '12345.67') + assert.equal(chineseToNumber('一万二千三百四十五点六七'), '12345.67') + assert.equal(chineseToNumber('壹万贰仟叁佰肆拾伍元陆角柒分'), '12345.67') + assert.equal(chineseToNumber('伍佰元整'), '500') + assert.equal(chineseToNumber('人民币伍佰圆正'), '500') + assert.equal(chineseToNumber('负五万零三'), '-50003') + assert.equal(chineseToNumber('一二三'), '123') + assert.equal(chineseToNumber('零元伍分'), '0.05') + assert.equal(chineseToNumber('伍分'), '0.05') +}) + +test('口语省略写法:单位后直接跟一位数字且中间没有“零”时按下一级单位计权', () => { + const colloquial = { + 三百五: '350', 一千二: '1200', 一万五: '15000', 一百一: '110', 叁佰伍: '350', 两千五: '2500', + 一万二千五: '12500', 一千二百三: '1230', 一亿五: '150000000', 十万五: '105000', 一千二万: '12000000', + 负一万五: '-15000', 三百五元: '350' + } + for (const [input, expected] of Object.entries(colloquial)) { + const parsed = parseChineseNumber(input) + assert.equal(parsed.value, expected, input) + assert.equal(parsed.colloquial, true, `${input} 应标记为口语省略写法`) + } + const standard = { + 三百零五: '305', 一千零二: '1002', 一万零五: '10005', 一亿零五: '100000005', 一万二千零五: '12005', + 二十五: '25', 十五: '15', 一万五千: '15000', 一亿五万: '100050000', 两千五百万: '25000000', 叁佰伍拾元: '350' + } + for (const [input, expected] of Object.entries(standard)) { + const parsed = parseChineseNumber(input) + assert.equal(parsed.value, expected, input) + assert.equal(parsed.colloquial, false, `${input} 不应标记为口语省略写法`) + } +}) + +test('[异常] 非法输入、位序错误、分隔符与 16 位上限给出明确错误', () => { + assert.throws(() => parseArabicDecimal(''), /请输入有效数字/) + assert.throws(() => chineseToNumber(''), /请输入中文数字/) + assert.throws(() => parseArabicDecimal('abc123'), /不是有效的十进制数字格式/) + assert.throws(() => chineseToNumber('一百块钱'), /包含无法识别的中文数字字符/) + assert.throws(() => parseArabicDecimal('1,23,456'), /千位分隔符位置不正确/) + assert.throws(() => parseArabicDecimal('12345678901234567'), /整数部分最多支持 16 位数字/) + assert.throws(() => chineseToNumber('三百五五'), /不能连续出现多个数字/) + assert.throws(() => chineseToNumber('三五百'), /不能连续出现多个数字/) + assert.throws(() => chineseToNumber('三百零'), /无意义的零结尾/) + assert.throws(() => chineseToNumber('一万五万'), /万、亿、兆的顺序不正确/) + assert.throws(() => chineseToNumber('五负'), /负号位置不正确/) + assert.throws(() => chineseToNumber('一点二点三'), /只能包含一个小数点/) + assert.throws(() => chineseToNumber('伍佰元整伍分'), /票据金额格式|整或正/) + assert.equal(chineseToNumber('九千九百九十九兆九千九百九十九亿九千九百九十九万九千九百九'), '9999999999999990') + assert.throws(() => chineseToNumber('九万兆五'), /万、亿、兆的顺序不正确|16 位/) + setRuntimeLocale('en-US') + assert.throws(() => chineseToNumber('三百五五'), /Digits cannot appear consecutively/) +}) + +test('双向转换:票据大写单独失败(精确到分)时其余结果照常给出', () => { + const fromArabic = convertChineseNumberInput('3.14159') + assert.equal(fromArabic.source, 'arabic') + assert.match(fromArabic.rows[0].error, /精确到分/) + assert.equal(fromArabic.rows[1].value, '叁点壹肆壹伍玖') + const fromChinese = convertChineseNumberInput('三百五') + assert.equal(fromChinese.source, 'chinese') + assert.deepEqual(fromChinese.rows.map((r) => r.value), ['350', '叁佰伍拾元整', '叁佰伍拾', '三百五十']) + assert.equal(fromChinese.rows[0].colloquial, true) +}) + +test('calc-rmb 视图:数字输入给出票据大写、中文大写、中文小写,可复制、粘贴与复制对照', async () => { + const view = await mount(calcRmb) + try { + await view.search('12345.67') + assert.equal(view.item('rmb-result').props.title, '壹万贰仟叁佰肆拾伍元陆角柒分') + assert.equal(view.item('rmb-upper').props.title, '壹万贰仟叁佰肆拾伍点陆柒') + assert.equal(view.item('rmb-lower').props.title, '一万二千三百四十五点六七') + await view.run(view.item('rmb-upper'), '复制中文大写') + assert.equal(host.clipboard.text, '壹万贰仟叁佰肆拾伍点陆柒') + await view.run(view.item('rmb-result'), '复制完整对照(输入 = 结果)') + assert.equal(host.clipboard.text, '12345.67 = 壹万贰仟叁佰肆拾伍元陆角柒分') + await view.run(view.item('rmb-lower'), '粘贴到前台应用') + assert.deepEqual(host.clipboard.pasted.at(-1), '一万二千三百四十五点六七') + } finally { + view.unmount() + } +}) + +test('calc-rmb 视图:中文输入首行为阿拉伯数字并提示口语省略,规范写法不提示', async () => { + const view = await mount(calcRmb) + try { + await view.search('三百五') + const arabic = view.item('rmb-arabic') + assert.equal(arabic.props.title, '350') + assert.match(arabic.props.subtitle, /口语省略写法.*三百五十/) + assert.equal(view.item('rmb-result').props.title, '叁佰伍拾元整') + await view.run(arabic, '复制阿拉伯数字') + assert.equal(host.clipboard.text, '350') + await view.search('一千零二') + assert.equal(view.item('rmb-arabic').props.subtitle, '阿拉伯数字') + } finally { + view.unmount() + } +}) + +test('calc-rmb 视图:票据规则在动作面板与规则区切换并立即生效', async () => { + const view = await mount(calcRmb) + try { + await view.search('500') + await view.run(view.item('rmb-result'), '币种前缀:无') + assert.equal(view.item('rmb-result').props.title, '人民币伍佰元整') + await view.run(view.item('rmb-rule-yuan'), '切换此规则') + await view.run(view.item('rmb-rule-whole'), '切换此规则') + assert.equal(view.item('rmb-result').props.title, '人民币伍佰圆正') + assert.match(String(host.lastToast().title), /已切换:整额后缀:正/) + + await view.search('0.05') + await view.run(view.item('rmb-rule-zero-yuan'), '切换此规则') + assert.equal(view.item('rmb-result').props.title, '人民币伍分') + + // 精确到分:小数超过两位时票据大写行报错且不可复制,中文大写照常;切到四舍五入后恢复 + await view.search('10.555') + const failed = view.item('rmb-result') + assert.match(failed.props.title, /精确到分/) + assert.ok(!view.actions(failed).some((a) => a.props.title === '复制大写金额')) + assert.equal(view.item('rmb-upper').props.title, '壹拾点伍伍伍') + await view.run(failed, '分位处理:精确到分(超过两位小数时报错)') + assert.equal(view.item('rmb-result').props.title, '人民币壹拾圆伍角陆分') + await view.run(view.item('rmb-rule-rounding'), '切换此规则') + assert.equal(view.item('rmb-result').props.title, '人民币壹拾圆伍角伍分') + } finally { + view.unmount() + } +}) + +test('[异常] calc-rmb 视图:无法解析的输入显示错误行且不出现结果行,清空后回到示例', async () => { + const view = await mount(calcRmb) + try { + await view.search('三百五五') + const err = view.item('rmb-error') + assert.match(err.props.title, /不能连续出现多个数字/) + assert.ok(!view.items().some((i) => i.props.id === 'rmb-result')) + await view.search('1,23') + assert.match(view.item('rmb-error').props.title, /千位分隔符/) + await view.run(view.item('rmb-error'), '清空输入') + assert.ok(view.item('rmb-input')) + const examples = view.items().filter((i) => String(i.props.id).startsWith('rmb-eg-')).map((i) => i.props.title) + assert.ok(examples.includes('12345.67')) + assert.ok(examples.includes('三百五')) + await view.run(view.item('rmb-eg-0'), '带入示例') + assert.equal(view.item('rmb-result').props.title, '壹万贰仟叁佰肆拾伍元陆角柒分') + } finally { + view.unmount() + } +}) + +test('i18n: 英文模式下大写金额视图的空闲态、示例与规则区无中文残留', async () => { + setRuntimeLocale('en-US') + const view = await mount(calcRmb) + try { + assert.ok(!/[\u4e00-\u9fa5]/.test(view.text()), `en-US rmb idle view should not contain CJK: ${view.text()}`) + assert.ok(view.item('rmb-rule-rounding')) + await view.search('abc') + assert.equal(view.item('rmb-error').props.title, 'Not a valid decimal number') + } finally { + view.unmount() + } +}) + +test('主计算器联动:普通数字结果可一键转为人民币大写,科学计数法结果不提供', async () => { + const main = await mount(CalculatorCommand) + try { + await main.search('1200*3.5') + await main.run(main.item('calc-success'), '转为人民币大写…') + const rmb = await mountPushed(host) + assert.equal(rmb.tree().props.searchText, '4200') + assert.equal(rmb.item('rmb-result').props.title, '肆仟贰佰元整') + rmb.unmount() + await main.search('2^100') + assert.ok(!main.actions(main.item('calc-success')).some((a) => a.props.title === '转为人民币大写…')) + } finally { + main.unmount() + } +}) diff --git a/extensions/calculator/tests/date-and-history-scope.test.mjs b/extensions/calculator/tests/date-and-history-scope.test.mjs index 9867d21d..8b2983df 100644 --- a/extensions/calculator/tests/date-and-history-scope.test.mjs +++ b/extensions/calculator/tests/date-and-history-scope.test.mjs @@ -69,11 +69,16 @@ test('复制历史结果、置顶结果与示例时,不把输入框里的当 assert.equal(host.clipboard.text, '42') await view.run(view.item('h-old'), '粘贴到前台') assert.deepEqual(host.clipboard.pasted, ['2']) - await view.run(view.item('eg-0'), '复制表达式') + // 输入有效算式时静态示例自动收起,清空输入后示例恢复展示 + assert.equal(view.items().some((it) => String(it.props.id).startsWith('eg-')), false) + await view.search('') + const mathExample = view.item((it) => String(it.props.id).startsWith('eg-') && it.props.title === '1024 * 768') + await view.run(mathExample, '复制表达式') assert.equal(host.clipboard.text, '1024 * 768') assert.deepEqual(stored().map((it) => it.expression), ['7*6', '1+1'], '历史里不能出现未被复制过的 9*9') // 复制当前结果本身仍然记入历史 + await view.search('9*9') await view.run(view.item('calc-success'), '复制计算结果') assert.equal(stored()[0].expression, '9*9') view.unmount() diff --git a/extensions/calculator/tests/fixes.test.mjs b/extensions/calculator/tests/fixes.test.mjs index c6063cd2..b72c2420 100644 --- a/extensions/calculator/tests/fixes.test.mjs +++ b/extensions/calculator/tests/fixes.test.mjs @@ -24,7 +24,8 @@ const seedHistory = (items) => host.storage.set(HISTORY_KEY, JSON.stringify(item test('列表是受控输入框:填入示例后输入框显示示例、结果行被选中,Enter 复制的是新结果', async () => { const view = await mount(CalculatorCommand) assert.equal(view.tree().props.searchText, '') - await view.run(view.item('eg-1'), '填入搜索框并计算') + const sqrtExample = view.item((it) => String(it.props.id).startsWith('eg-') && it.props.title === 'sqrt(65536)') + await view.run(sqrtExample, '填入搜索框并计算') assert.equal(view.tree().props.searchText, 'sqrt(65536)', '输入框应显示被填入的示例') assert.equal(view.tree().props.selectedItemId, 'calc-success', '应选中新算出的结果行') const result = view.item('calc-success') @@ -152,7 +153,8 @@ test('单位换算支持负数', () => { assert.equal(evaluateCalculatorQuery('-16px to rem').formattedAnswer, '-1 rem') assert.equal(evaluateCalculatorQuery('-2.5rem to px').formattedAnswer, '-40 px') assert.equal(evaluateCalculatorQuery('+5 km to m').formattedAnswer, '5000 m') - assert.equal(evaluateCalculatorQuery('-273.15 c to k').formattedAnswer, '0 °K') + // 开尔文是绝对温标,符号不带度号(K 而不是 °K) + assert.equal(evaluateCalculatorQuery('-273.15 c to k').formattedAnswer, '0 K') assert.equal(evaluateCalculatorQuery('-0.001 c to c').formattedAnswer, '0 °C', '舍入后的 -0 应显示为 0') }) diff --git a/extensions/calculator/tests/review-regressions.test.mjs b/extensions/calculator/tests/review-regressions.test.mjs index a1868a07..d8992ea3 100644 --- a/extensions/calculator/tests/review-regressions.test.mjs +++ b/extensions/calculator/tests/review-regressions.test.mjs @@ -53,9 +53,12 @@ test('人民币大写不经过浮点计算,零值/分/万亿边界与非法金 ]) { assert.equal(toChineseAmount(input), output) } - for (const invalid of ['', '1.005', '1e3', '1,23', '1000000000000', 'NaN']) { + // 整数部分支持到 16 位(兆级),17 位超限;默认“精确到分”规则下超过两位的非零小数报错 + for (const invalid of ['', '1.005', '1e3', '1,23', '12345678901234567', 'NaN']) { assert.throws(() => toChineseAmount(invalid)) } + assert.equal(toChineseAmount('1000000000000'), '壹兆元整') + assert.equal(toChineseAmount('1.100'), '壹元壹角') }) test('人民币大写子命令与计算器动作都可达,并可复制', async () => { diff --git a/extensions/calculator/tests/unit-conversion-merge.test.mjs b/extensions/calculator/tests/unit-conversion-merge.test.mjs new file mode 100644 index 00000000..c2b92979 --- /dev/null +++ b/extensions/calculator/tests/unit-conversion-merge.test.mjs @@ -0,0 +1,301 @@ +// 单位换算(原 unit-converter 插件已合并进计算器):注册表、内联换算、单位看板与主计算器联动 +import test from 'node:test' +import assert from 'node:assert/strict' +import { setRuntimeLocale } from '@ztools/declarative-ui' +import { createHost, mount, mountPushed } from '../../shared/test-harness.mjs' +import CalculatorCommand, { calcUnit } from '../dist/index.js' +import UnitBoardCommand from '../dist/unit-board.js' +import { + UNIT_CATEGORIES, + convertUnitValue, + evaluateCalculatorQuery, + formatUnitValue, + resolveUnitAlias +} from '../dist/calculator-engine.js' +import { CURRENCIES } from '../dist/currency-rates.js' + +const host = createHost() +test.beforeEach(() => { + host.reset() + setRuntimeLocale('zh-CN') +}) + +const convert = (value, category, from, to) => { + const r = convertUnitValue(value, category, from, to) + assert.equal(r.ok, true, `${value} ${from} -> ${to}`) + return r.value +} + +test('注册表:覆盖原单位换算插件的 9 大分类与全部单位,别名全小写且不重复', () => { + const expected = { + length: ['millimeter', 'centimeter', 'meter', 'kilometer', 'inch', 'foot', 'yard', 'mile', 'nautical-mile'], + mass: ['milligram', 'gram', 'kilogram', 'tonne', 'ounce', 'pound', 'jin', 'liang'], + area: ['square-millimeter', 'square-centimeter', 'square-meter', 'square-kilometer', 'hectare', 'mu', 'square-inch', 'square-foot', 'square-yard', 'square-mile', 'acre'], + volume: ['milliliter', 'liter', 'cubic-centimeter', 'cubic-meter', 'teaspoon', 'tablespoon', 'fluid-ounce', 'cup', 'us-pint', 'us-quart', 'gallon', 'imperial-gallon'], + speed: ['meter-per-second', 'kilometer-per-hour', 'mile-per-hour', 'foot-per-second', 'knot', 'mach'], + angle: ['degree', 'circle', 'right-angle', 'gradian', 'arcminute', 'arcsecond', 'radian', 'milliradian'], + digital: ['bit', 'byte', 'kilobyte', 'megabyte', 'gigabyte', 'terabyte', 'kibibyte', 'mebibyte', 'gibibyte', 'tebibyte'], + energy: ['joule', 'kilojoule', 'megajoule', 'watt-hour', 'kilowatt-hour', 'calorie', 'kilocalorie', 'british-thermal-unit', 'foot-pound-force'], + temp: ['celsius', 'fahrenheit', 'kelvin', 'rankine'] + } + for (const [categoryId, ids] of Object.entries(expected)) { + const category = UNIT_CATEGORIES.find((c) => c.id === categoryId) + assert.ok(category, categoryId) + const present = new Set(category.units.map((u) => u.id)) + for (const id of ids) assert.ok(present.has(id), `${categoryId} 缺少 ${id}`) + assert.ok(present.has(category.defaultFrom), `${categoryId} 默认单位不存在`) + } + const seen = new Map() + for (const category of UNIT_CATEGORIES) { + for (const unit of category.units) { + assert.ok(unit.names['zh-CN'] && unit.names['en-US'], `${unit.id} 缺少双语名称`) + assert.ok(!/[\u4e00-\u9fa5]/.test(unit.names['en-US']), `${unit.id} 英文名称不能含中文`) + for (const alias of [...unit.aliases['zh-CN'], ...unit.aliases['en-US']]) { + assert.equal(alias, alias.toLowerCase(), `${alias} 必须是小写`) + assert.ok(!seen.has(alias), `别名 ${alias} 同时属于 ${seen.get(alias)} 与 ${unit.id}`) + seen.set(alias, unit.id) + } + } + } +}) + +test('注册表:货币代码不会被当成单位,汇率换算不受影响(pound 为旧版既有的质量单位别名)', () => { + for (const currency of CURRENCIES) { + assert.equal(resolveUnitAlias(currency.code), null, currency.code) + } + assert.equal(evaluateCalculatorQuery('100 usd to cny').type, 'none') + assert.equal(evaluateCalculatorQuery('100 pound to usd').type, 'none') + assert.equal(evaluateCalculatorQuery('1 pound to oz').type, 'unit') +}) + +test('换算精度与原单位换算插件一致(长度、质量、数据、温度、面积、体积、速度、角度、能量)', () => { + assert.equal(convert(1, 'length', 'meter', 'millimeter'), 1000) + assert.equal(convert(1, 'length', 'meter', 'kilometer'), 0.001) + assert.equal(convert(1, 'length', 'inch', 'meter'), 0.0254) + assert.equal(convert(1, 'length', 'nautical-mile', 'meter'), 1852) + assert.equal(convert(1, 'mass', 'kilogram', 'gram'), 1000) + assert.equal(convert(1, 'mass', 'kilogram', 'jin'), 2) + assert.equal(convert(1, 'mass', 'jin', 'liang'), 10) + assert.equal(convert(1, 'digital', 'mebibyte', 'kibibyte'), 1024) + assert.equal(convert(1, 'digital', 'megabyte', 'kilobyte'), 1000) + assert.equal(convert(1, 'digital', 'byte', 'bit'), 8) + assert.equal(convert(100, 'temp', 'celsius', 'fahrenheit'), 212) + assert.equal(convert(0, 'temp', 'celsius', 'kelvin'), 273.15) + assert.ok(Math.abs(convert(491.67, 'temp', 'rankine', 'celsius')) < 1e-9) + assert.equal(formatUnitValue(convert(1, 'area', 'mu', 'square-meter'), 4), '666.6667') + assert.equal(convert(1, 'area', 'hectare', 'mu'), 15) + assert.equal(formatUnitValue(convert(1, 'volume', 'gallon', 'liter'), 4), '3.7854') + assert.equal(formatUnitValue(convert(100, 'speed', 'kilometer-per-hour', 'meter-per-second'), 4), '27.7778') + assert.equal(convert(1, 'speed', 'knot', 'kilometer-per-hour'), 1.852) + assert.ok(Math.abs(convert(180, 'angle', 'degree', 'radian') - Math.PI) < 1e-12) + assert.equal(convert(1, 'angle', 'circle', 'degree'), 360) + assert.equal(convert(1, 'energy', 'kilowatt-hour', 'joule'), 3600000) + assert.equal(formatUnitValue(convert(1, 'energy', 'kilocalorie', 'calorie'), 6), '1000') +}) + +test('[异常] 看板换算:未知分类或单位、非有限数、低于绝对零度、上溢与下溢都不返回数值', () => { + assert.deepEqual(convertUnitValue(1, 'length', 'meter', 'gram'), { ok: false, reason: 'invalid' }) + assert.deepEqual(convertUnitValue(1, 'nope', 'meter', 'meter'), { ok: false, reason: 'invalid' }) + assert.deepEqual(convertUnitValue(Number.NaN, 'length', 'meter', 'meter'), { ok: false, reason: 'invalid' }) + assert.deepEqual(convertUnitValue(Infinity, 'length', 'meter', 'meter'), { ok: false, reason: 'invalid' }) + assert.deepEqual(convertUnitValue(-1, 'temp', 'kelvin', 'celsius'), { ok: false, reason: 'belowAbsoluteZero' }) + assert.deepEqual(convertUnitValue(-500, 'temp', 'fahrenheit', 'kelvin'), { ok: false, reason: 'belowAbsoluteZero' }) + assert.deepEqual(convertUnitValue(1e308, 'length', 'kilometer', 'millimeter'), { ok: false, reason: 'overflow' }) + assert.deepEqual(convertUnitValue(1e-320, 'length', 'millimeter', 'kilometer'), { ok: false, reason: 'overflow' }) + // 0 可以换算(不能用 !value 判空) + assert.deepEqual(convertUnitValue(0, 'length', 'meter', 'kilometer'), { ok: true, value: 0 }) +}) + +test('formatUnitValue:按小数位舍入,极小值改用科学计数法,-0 显示为 0', () => { + assert.equal(formatUnitValue(1 / 3, 2), '0.33') + assert.equal(formatUnitValue(1 / 3, 6), '0.333333') + assert.equal(formatUnitValue(0.000001, 4), '0.000001') + assert.equal(formatUnitValue(-0.00001, 2), '-0.00001') + assert.equal(formatUnitValue(-0.0000001, 0), '0') + assert.equal(formatUnitValue(12, 99), '12') + assert.equal(formatUnitValue(Number.NaN, 4), '') +}) + +test('内联换算:新增分类、中文单位、中文连接词、科学计数法与旧写法保持兼容', () => { + const cases = { + '1 acre to m2': '4046.8564 m2', + '100 km/h to mph': '62.1371 mph', + '3斤 to kg': '1.5 kg', + '1亩等于多少平方米': '666.6667 平方米', + '1公斤转换成斤': '2 斤', + '180 deg to rad': '3.1416 rad', + '1 kwh to kj': '3600 kj', + '1 gallon to l': '3.7854 l', + '1 mm to km': '0.000001 km', + '1e3 m to km': '1 km', + '1 nmi to km': '1.852 km', + '491.67 r to c': '0 °C', + '0 c to k': '273.15 K', + '1 gib to mib': '1024 MiB', + '1 gigabyte to megabytes': '1000 MB', + '1 in in cm': '2.54 cm', + '2 ha to 亩': '30 亩', + // 旧写法:结果格式不变 + '10km to miles': '6.2137 miles', + '5kg to lbs': '11.0231 lbs', + '1024mb to gb': '1 GB', + '-40c to f': '-40 °F' + } + for (const [query, answer] of Object.entries(cases)) { + const r = evaluateCalculatorQuery(query, { locale: 'zh-CN' }) + assert.equal(r.type, 'unit', query) + assert.equal(r.error, undefined, `${query}: ${r.error}`) + assert.equal(r.formattedAnswer, answer, query) + } + const r = evaluateCalculatorQuery('3斤 to kg') + assert.deepEqual(r.unitSource, { categoryId: 'mass', unitId: 'jin', value: 3 }) + assert.match(r.details, /MASS/) + // px/rem 与进制不属于度量衡,不提供单位看板来源 + assert.equal(evaluateCalculatorQuery('32px to rem').unitSource, undefined) + assert.equal(evaluateCalculatorQuery('255 to hex').unitSource, undefined) +}) + +test('[异常] 内联换算:单位类型不一致、低于绝对零度、畸形数字给出明确错误,不认识的单位不当作换算', () => { + const mismatch = evaluateCalculatorQuery('5 kg to m', { locale: 'zh-CN' }) + assert.equal(mismatch.type, 'unit') + assert.match(mismatch.error, /单位类型不一致.*MASS.*LENGTH/) + assert.match(evaluateCalculatorQuery('5 kg to m', { locale: 'en-US' }).error, /Cannot convert between different unit types/) + assert.match(evaluateCalculatorQuery('-500 c to k').error, /绝对零度/) + assert.match(evaluateCalculatorQuery('-1 k to c').error, /绝对零度/) + assert.match(evaluateCalculatorQuery('1.2.3 斤 to kg').error, /数字格式不正确/) + assert.notEqual(evaluateCalculatorQuery('3 days to hours').type, 'unit') + assert.notEqual(evaluateCalculatorQuery('1 foo to bar').type, 'unit') +}) + +test('单位看板:默认长度分类以米为基准列出全部单位,复制带单位结果、纯数值与换算等式', async () => { + const view = await mount(UnitBoardCommand) + try { + assert.equal(view.tree().props.navigationTitle, '单位换算') + assert.equal(view.tree().props.searchBarAccessory.props.value, 'length') + assert.equal(view.item('unit-kilometer').props.title, '0.001 km') + assert.equal(view.item('unit-meter').props.accessories[0].text, '基准单位') + await view.search('1500') + assert.equal(view.item('unit-kilometer').props.title, '1.5 km') + await view.run(view.item('unit-kilometer'), '复制结果(1.5 km)') + assert.equal(host.clipboard.text, '1.5 km') + await view.run(view.item('unit-kilometer'), '复制纯数值') + assert.equal(host.clipboard.text, '1.5') + await view.run(view.item('unit-kilometer'), '复制换算等式') + assert.equal(host.clipboard.text, '1500 m = 1.5 km') + } finally { + view.unmount() + } +}) + +test('单位看板:切换分类、设为基准单位、调整小数位数、算式输入与“数值 + 单位”直接切换基准', async () => { + const view = await mount(UnitBoardCommand) + try { + await view.dropdown('mass') + assert.equal(view.item('unit-gram').props.title, '1000 g') + assert.equal(view.item('unit-jin').props.title, '2 斤') + await view.run(view.item('unit-jin'), '设为基准单位(斤)') + assert.equal(view.item('unit-kilogram').props.title, '0.5 kg') + assert.equal(view.item('unit-liang').props.title, '10 两') + + await view.dropdown('length') + await view.search('1') + await view.run(view.item('unit-inch'), '保留 2 位小数') + assert.equal(view.item('unit-inch').props.title, '39.37 in') + await view.run(view.item('unit-inch'), '保留 6 位小数') + assert.equal(view.item('unit-inch').props.title, '39.370079 in') + + await view.search('3*4') + assert.equal(view.item('unit-centimeter').props.title, '1200 cm') + + // 输入“5 kg”:直接以千克为基准换算质量单位,下拉同步显示质量 + await view.search('5 kg') + assert.equal(view.tree().props.searchBarAccessory.props.value, 'mass') + assert.equal(view.item('unit-pound').props.title, '11.023113 lb') + await view.search('1 平方公里') + assert.equal(view.item('unit-mu').props.title, '1500 亩') + } finally { + view.unmount() + } +}) + +test('[异常] 单位看板:非法输入与低于绝对零度显示错误行且不可复制,重置后恢复', async () => { + const view = await mount(UnitBoardCommand) + try { + await view.search('abc') + const err = view.item('unit-input-error') + assert.match(err.props.title, /请输入有效的数值或算式/) + assert.ok(!view.items().some((i) => String(i.props.id).startsWith('unit-meter'))) + await view.run(err, '重置为 1') + assert.equal(view.item('unit-meter').props.title, '1 m') + + await view.dropdown('temp') + await view.search('-300') + assert.match(view.item('unit-input-error').props.title, /绝对零度/) + assert.ok(!view.actions(view.item('unit-input-error')).some((a) => /复制/.test(a.props.title))) + await view.search('100') + assert.equal(view.item('unit-fahrenheit').props.title, '212 °F') + assert.equal(view.item('unit-kelvin').props.title, '373.15 K') + + // 超出范围的单位行不提供复制 + await view.dropdown('length') + await view.search('1e308') + const overflow = view.item('unit-millimeter') + assert.equal(overflow.props.title, '超出数值范围') + assert.ok(!view.actions(overflow).some((a) => /复制/.test(a.props.title))) + } finally { + view.unmount() + } +}) + +test('i18n: 英文模式下单位看板无中文残留(含市制单位)', async () => { + setRuntimeLocale('en-US') + const view = await mount(() => UnitBoardCommand({ categoryId: 'mass' })) + try { + assert.equal(view.tree().props.navigationTitle, 'Unit Converter') + assert.equal(view.item('unit-jin').props.title, '2 jin') + assert.ok(!/[\u4e00-\u9fa5]/.test(view.text()), `en-US unit board should not contain CJK: ${view.text()}`) + } finally { + view.unmount() + } +}) + +test('主计算器联动:换算结果可在单位看板查看全部单位,根动作可打开看板,calc-unit 列出单位分类入口', async () => { + const main = await mount(CalculatorCommand) + try { + await main.search('3斤 to kg') + const result = main.item('calc-success') + assert.equal(result.props.title, '= 1.5 kg') + await main.run(result, '在单位看板中查看全部单位…') + const board = await mountPushed(host) + assert.equal(board.tree().props.searchBarAccessory.props.value, 'mass') + assert.equal(board.item('unit-gram').props.title, '1500 g') + assert.equal(board.item('unit-jin').props.accessories[0].text, '基准单位') + board.unmount() + + await main.search('32px to rem') + assert.ok(!main.actions(main.item('calc-success')).some((a) => a.props.title === '在单位看板中查看全部单位…')) + + await main.run(null, '单位换算看板…') + const blank = await mountPushed(host) + assert.equal(blank.tree().props.navigationTitle, '单位换算') + blank.unmount() + } finally { + main.unmount() + } + + const unit = await mount(calcUnit) + try { + const cats = unit.items().filter((i) => String(i.props.id).startsWith('unit-cat-')) + assert.equal(cats.length, UNIT_CATEGORIES.length) + await unit.run(unit.item('unit-cat-area'), '打开面积换算看板') + const board = await mountPushed(host) + assert.equal(board.tree().props.searchBarAccessory.props.value, 'area') + assert.equal(board.item('unit-mu').props.title, '0.0015 亩') + board.unmount() + // 输入换算得到结果后分类入口收起,减少干扰 + await unit.search('1km to m') + assert.ok(!unit.items().some((i) => String(i.props.id).startsWith('unit-cat-'))) + } finally { + unit.unmount() + } +}) diff --git a/extensions/calendar/README.en.md b/extensions/calendar/README.en.md new file mode 100644 index 00000000..06f31995 --- /dev/null +++ b/extensions/calendar/README.en.md @@ -0,0 +1,21 @@ +# Local Calendar + +Record and view events inside ZTools, open video meeting links from events in your browser, and export schedules as ICS calendar files. + +## Usage + +- Command: Search for "Local Calendar" in the launcher to open. +- Top dropdown filters: All Events (from today onward), Upcoming (within 24 hours), With Video Meeting Link, and Past Events. The search box matches title, location, notes, and calendar name; titles also support pinyin search (pinyin search is not supported under the "Upcoming" filter). +- `Enter`: Opens the meeting link in your browser if present, otherwise copies the event summary; `⌘/Ctrl+Enter`: Copies the meeting link if present, otherwise exports the event as an ICS file; `⌘/Ctrl+K`: Opens the action panel. +- `⌘/Ctrl+N` creates a new event; `⌘/Ctrl+E` exports the current list as an ICS file; reload is available in the action panel (`⌘/Ctrl+R` is intentionally unbound because it maps to the client's Reload menu shortcut on macOS); `⌘/Ctrl+C` copies the event summary; `⌘/Ctrl+Shift+Backspace` deletes an event (requires confirmation and cannot be undone). You can also copy the list as ICS text from the action panel. +- Creating an event requires a title, date (`YYYY-MM-DD`), and start/end times (`HH:MM`); for multi-day events, write the end time as `YYYY-MM-DD HH:MM`. Meeting links accept only `http` or `https` URLs, automatically prepending `https://` if no scheme is given. +- Events are stored in the client's local database and neither read from nor write to system calendars (such as Apple Calendar or Outlook). Up to 500 events are loaded at a time; if exceeded, the status bar notifies you. +- If loading fails, the reason is shown while keeping the previous list; choose "Reload Events" in the action panel to retry (or press `Enter` directly when the list is empty). + +## Platforms & Requirements + +- Supported: Windows, macOS + +## Network & Data + +- The plugin itself works offline and stores events locally only; "Join Video Meeting" opens the event's meeting URL in your system browser. diff --git a/extensions/calendar/plugin.json b/extensions/calendar/plugin.json index 876fa9f6..98e2c506 100644 --- a/extensions/calendar/plugin.json +++ b/extensions/calendar/plugin.json @@ -1,7 +1,8 @@ { "id": "calendar", "name": "日程日历", - "version": "2.0.12", + "version": "2.0.13", + "minAppVersion": "1.1.8.0", "description": "在本机记录和查看日程,用浏览器打开日程里的视频会议链接,可新建、删除日程并导出 ICS 日历文件", "author": "ZTools Team", "category": [ @@ -43,7 +44,12 @@ "events", "ics", "meeting", - "agenda" + "agenda", + "date", + "planner", + "reminder", + "month", + "day" ], "screenshots": [ { @@ -59,5 +65,18 @@ { "path": "screenshots/02-action-panel.png" } + ], + "keywords": [ + "日历", + "日程", + "待办日历", + "万年历", + "看日期", + "星期几", + "安排", + "日程表", + "节假日", + "calendar", + "schedule" ] } diff --git a/extensions/calendar/src/i18n.ts b/extensions/calendar/src/i18n.ts index 44ca3fc2..ba1d35fb 100644 --- a/extensions/calendar/src/i18n.ts +++ b/extensions/calendar/src/i18n.ts @@ -130,6 +130,7 @@ const rawT = createTranslator( metaMeetingStatus: "会议状态", metaCanJoin: "可一键入会", searchPlaceholder: "搜索日程标题、地点、日历或备注...", + btnNewEvent: "新建日程", btnExportIcs: "导出当前列表 (.ics)", dropdownTooltip: "筛选日程范围", scopeAll: "全部日程 · 今天起", @@ -272,6 +273,7 @@ const rawT = createTranslator( metaMeetingStatus: "Meeting", metaCanJoin: "Ready to Join", searchPlaceholder: "Search event title, location, calendar, or notes...", + btnNewEvent: "New Event", btnExportIcs: "Export ICS", dropdownTooltip: "Filter Events", scopeAll: "All Events · From Today", diff --git a/extensions/calendar/src/index.tsx b/extensions/calendar/src/index.tsx index 36de5538..42dfce70 100644 --- a/extensions/calendar/src/index.tsx +++ b/extensions/calendar/src/index.tsx @@ -865,6 +865,7 @@ export function CreateCalendarEventForm({ placeholder={t("fieldTitlePlaceholder")} value={title} error={errors.title} + autoFocus={true} onChange={(v: string) => { setTitle(v); clearErrors("title"); @@ -977,6 +978,7 @@ export function groupEventsByDay(events: readonly CalendarEventItem[], now = Dat export function CalendarCommand() { const locale = useLocale(); + const { push } = useNavigation(); const realHost = isRealElectronHost(); const [events, setEvents] = useState([]); const [total, setTotal] = useState(0); @@ -1207,6 +1209,7 @@ export function CalendarCommand() { key="edit" title={t("actionEditOne")} icon={Icon.Pencil} + shortcut={{ modifiers: ["ctrl", "shift"], key: "e" }} target={} />, push(createForm) + }, { id: "export-all-ics", label: t("btnExportIcs"), title: t("btnExportIcs"), + icon: Icon.Download, style: "secondary", onAction: () => handleExportFile(displayedEvents) }, diff --git a/extensions/calendar/src/native-ipc.ts b/extensions/calendar/src/native-ipc.ts index 51576b99..13643277 100644 --- a/extensions/calendar/src/native-ipc.ts +++ b/extensions/calendar/src/native-ipc.ts @@ -174,11 +174,13 @@ function normalizeMethodResult(method: string, payload: DynamicBridge): DynamicB if (method === 'system_get_battery_status') { // 宿主约定 percent 超出 0-100(如 255)表示无电池或电量未知,不能改写成 100% + // 若宿主明确给出 hasBattery 布尔值,必须原样保留,仅在缺失时按合法电量推算 const rawPct = payload.percent - const hasBattery = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const validPct = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const hasBattery = typeof payload.hasBattery === 'boolean' ? payload.hasBattery : validPct return { ...payload, - percent: hasBattery ? rawPct : null, + percent: validPct ? rawPct : null, hasBattery } } @@ -489,6 +491,8 @@ export interface RealDirectoryScanResult extends Iterable approximate?: boolean /** 宿主实际遍历的条目数 */ visitedEntries?: number + /** 目录本身不存在(ENOENT) */ + missing?: boolean /** 读取失败的真实原因;已有文件仍可使用,但不能当作完整结果。 */ error?: string } @@ -497,6 +501,7 @@ interface ScanResultMeta { truncated?: boolean approximate?: boolean visitedEntries?: number + missing?: boolean } export interface ScanDirectoryTreeOptions { @@ -504,6 +509,10 @@ export interface ScanDirectoryTreeOptions { maxFiles?: number collectTopN?: number filterExt?: RegExp + /** 为 true 时,目录本身不存在(ENOENT)按空目录处理,不返回 error(权限拒绝/读取失败仍照常报错) */ + ignoreMissing?: boolean + /** Top-N 保留与排序方式:默认按体积降序,下载/录屏等时效场景可传 mtime-desc */ + sortBy?: 'size-desc' | 'mtime-desc' hostOverride?: DynamicBridge } @@ -519,8 +528,9 @@ function normalizeIndexedFileEntry(f: DynamicBridge): RealIndexedFileEntry { const sz = Number(f?.size ?? f?.sizeBytes ?? 0) const isDir = Boolean(f?.is_dir || f?.isDir || f?.isDirectory) const rawMtime = Number(f?.mtime ?? f?.mtimeMs ?? 0) - const mtimeMs = rawMtime > 1e11 ? rawMtime : rawMtime > 0 ? rawMtime * 1000 : Date.now() - const mtimeSec = rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime + const validMtime = Number.isFinite(rawMtime) && rawMtime > 0 + const mtimeMs = validMtime ? (rawMtime > 1e11 ? rawMtime : rawMtime * 1000) : 0 + const mtimeSec = validMtime ? (rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime) : 0 if (p && sz >= 0) realFileSizeCache.set(p, sz) return { name, @@ -551,6 +561,7 @@ function makeScanResult( subdirs, ...(meta.truncated ? { truncated: true } : {}), ...(meta.approximate ? { approximate: true } : {}), + ...(meta.missing ? { missing: true } : {}), ...(typeof meta.visitedEntries === 'number' ? { visitedEntries: meta.visitedEntries } : {}), [Symbol.iterator]() { return files[Symbol.iterator]() @@ -609,13 +620,40 @@ export async function scanRealDirectoryTree( return result.error ? { ...result.scan, error: result.error } : result.scan } +/** 仅当正则明确声明了扩展名(含 `\.`)时提取后缀列表,避免把 `thumbcache|iconcache` 等文件名关键词误拆成假扩展名 */ +function extractExtensionTokensFromFilter(filterExt: RegExp): string[] { + const src = filterExt.source + if (!src.includes('\\.')) return [] + const afterDot = src.slice(src.indexOf('\\.') + 2) + const rawTokens = afterDot.match(/[a-z0-9]{1,8}/gi) || [] + const seen = new Set() + const out: string[] = [] + for (const token of rawTokens) { + const lower = token.toLowerCase() + if (!lower || seen.has(lower)) continue + seen.add(lower) + out.push(lower) + } + return out +} + +function isMissingDirectoryError(res: { error?: string; errorCode?: string; errorDetails?: Record }): boolean { + if (res.errorDetails?.reason === 'ENOENT' || res.errorCode === 'ENOENT') return true + const msg = String(res.error || '') + return /Directory does not exist|ENOENT/i.test(msg) +} + /** 一次界面扫描的错误汇总;多个目录并行扫描时保留可读目录的结果。 */ export function createDirectoryScanner(hostOverride?: DynamicBridge) { const failures = new Map() return { async scan(dir: string, options: number | ScanDirectoryTreeOptions = 160) { const result = await scanRealDirectoryTree(dir, options, hostOverride) - const error = result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') + const ignoreMissing = typeof options === 'object' && options !== null && options.ignoreMissing === true + const error = + result.missing && ignoreMissing + ? '' + : result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') if (error) failures.set(dir, error) else failures.delete(dir) return result @@ -648,26 +686,38 @@ async function scanDirectoryTreeWithError( const safeLimit = Math.min(200, Math.max(1, Math.floor(rawLimit || 160))) const hostOverride = opts.hostOverride const filterExt = opts.filterExt + const ignoreMissing = opts.ignoreMissing === true const dirQuery = `dir:${targetDir}` try { let rawPayload: DynamicBridge = null + const searchParams: Record = { + query: dirQuery, + limit: safeLimit, + ...(opts.sortBy ? { sortBy: opts.sortBy } : {}) + } const res = await callHostTransport( 'system_search_files', - { query: dirQuery, limit: safeLimit }, + searchParams, hostOverride ) - if (res.ok && res.data) { + if (res.ok && res.data && res.data.degraded !== true) { rawPayload = res.data + } else if (!res.ok && ignoreMissing && isMissingDirectoryError(res)) { + const missingScan = makeScanResult([], 0, 0, [], { missing: true }) + return { scan: missingScan } } - if (!rawPayload && !hostOverride && typeof window !== 'undefined') { + if (!rawPayload && !hostOverride && res.errorCode === 'METHOD_NOT_AVAILABLE' && typeof window !== 'undefined') { const w = window as DynamicBridge if (typeof w.__ztoolsLauncher?.searchFiles === 'function') { const rawOuter = await w.__ztoolsLauncher.searchFiles(dirQuery, safeLimit) - rawPayload = + const candidate = rawOuter && typeof rawOuter === 'object' && 'data' in rawOuter && rawOuter.data ? rawOuter.data : rawOuter + if (candidate && candidate.degraded !== true && candidate.success !== false) { + rawPayload = candidate + } } } @@ -678,29 +728,32 @@ async function scanDirectoryTreeWithError( let files: RealIndexedFileEntry[] = rawPayload.files.map(normalizeIndexedFileEntry) if (filterExt instanceof RegExp) { files = files.filter(f => !f.isDir && (filterExt.test(f.name) || filterExt.test(f.ext))) - // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索目标扩展名 + // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索明确声明的目标扩展名 if (files.length === 0 && !hostOverride) { - const extTokens = (filterExt.source.match(/[a-z0-9]{2,5}/gi) || []) - .filter(t => !['thumbcache', 'iconcache'].includes(t.toLowerCase())) - .slice(0, 4) - // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 - const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() - const extraLists = await Promise.all( - extTokens.map(ext => searchRealIndexedFiles(`.${ext.toLowerCase()}`, 30, hostOverride)) - ) - const seen = new Set() - for (const list of extraLists) { - for (const item of list) { - if (!item.isDir && item.size > 0 && !seen.has(item.path)) { - if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { - seen.add(item.path) - files.push(item) + const extTokens = extractExtensionTokensFromFilter(filterExt) + if (extTokens.length > 0) { + // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 + const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() + const extraLists = await Promise.all( + extTokens.map(ext => searchRealIndexedFiles(`.${ext}`, 30, hostOverride)) + ) + const seen = new Set() + for (const list of extraLists) { + for (const item of list) { + if (!item.isDir && item.size > 0 && !seen.has(item.path)) { + if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { + seen.add(item.path) + files.push(item) + } } } } } } } + // 先基于过滤后的完整命中集合计算总文件数与总字节数,再按 collectTopN 裁剪样本列表 + const matchedCount = files.length + const matchedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) if (typeof opts.collectTopN === 'number' && opts.collectTopN > 0 && files.length > opts.collectTopN) { files = files.slice(0, opts.collectTopN) } @@ -714,11 +767,10 @@ async function scanDirectoryTreeWithError( ...(s.approximate === true ? { approximate: true } : {}) })) : [] - const computedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) const totalFilesCount = - filterExt instanceof RegExp ? files.length : Number(rawPayload.total_matches ?? files.length) + filterExt instanceof RegExp ? matchedCount : Number(rawPayload.total_matches ?? matchedCount) const totalBytesCount = - filterExt instanceof RegExp ? computedBytes : Number(rawPayload.total_bytes ?? computedBytes) + filterExt instanceof RegExp ? matchedBytes : Number(rawPayload.total_bytes ?? matchedBytes) const visited = Number(rawPayload.visited_entries) return { scan: makeScanResult(files, totalFilesCount, totalBytesCount, subdirs, { @@ -1817,8 +1869,6 @@ export async function writeRealClipboardText(text: string, hostOverride?: Dynami const payload = { text: String(text || '') } const res = await callHostTransport('clipboard_copy_text', payload, hostOverride) if (res.ok) return true - const fallbackRes = await callHostTransport('clipboard_write_text', payload, hostOverride) - if (fallbackRes.ok) return true try { if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) { await navigator.clipboard.writeText(String(text || '')) diff --git a/extensions/calendar/tests/calendar.fixes.test.mjs b/extensions/calendar/tests/calendar.fixes.test.mjs index 92e64083..db7822fa 100644 --- a/extensions/calendar/tests/calendar.fixes.test.mjs +++ b/extensions/calendar/tests/calendar.fixes.test.mjs @@ -484,8 +484,8 @@ test('删除不再占用 ⌘X,改为 ⌘⇧⌫,且必须确认;取消确 assert.ok(!view.items().some((i) => i.props.id === 'a')) assert.equal(host.lastToast().title, '已删除日程: 周会') - // 全局栏仅导出,删除只属于列表行,空选择也不留下无效删除按钮。 - assert.deepEqual(view.tree().props.filterBar.actions.map(a => a.id), ['export-all-ics'], '新建不在顶部重复出现') + // 顶栏提供新建与导出,删除只属于列表行,空选择也不留下无效删除按钮。 + assert.deepEqual(view.tree().props.filterBar.actions.map(a => a.id), ['new-event', 'export-all-ics'], '顶栏应展示新建与导出') assert.equal(view.tree().props.filterBar.groups, undefined) assert.ok(view.actions(view.items()[0]).some(a => a.props.title === '删除此日程...')) view.unmount() diff --git a/extensions/chmod-cidr-calc/README.en.md b/extensions/chmod-cidr-calc/README.en.md new file mode 100644 index 00000000..c5edc093 --- /dev/null +++ b/extensions/chmod-cidr-calc/README.en.md @@ -0,0 +1,21 @@ +# CIDR & Chmod Calculator + +Calculate IPv4 CIDR subnet masks, usable host ranges, and 32-bit binary masks, and convert between Linux `chmod` octal and symbolic permissions—completely offline. + +## Usage + +- Command: Calculate IPv4 CIDR subnet ranges or convert Linux `chmod` permissions (keywords such as `cidr`, `chmod`, `subnet`, `ipcalc`, `netmask`, `permissions`). +- Type directly into the search box and the mode switches automatically based on input: inputs like `755`, `rwxr-xr-x`, or `chmod 755` switch to permission calculation, while inputs containing `.` or `/` switch to CIDR calculation. You can also switch modes on the right side of the search box. +- CIDR result rows: `Enter` copies the usable IP range, `⌘/Ctrl+Enter` copies the subnet mask, and `⌘/Ctrl+K` lets you copy the network address/CIDR. Permission result rows: `Enter` copies the `chmod` command, `⌘/Ctrl+Enter` copies the octal value, and `⌘/Ctrl+K` lets you copy the symbolic string. Press `Enter` on the common subnets or common permissions listed below to load them into the calculator. +- CIDR supports `/0` through `/32` and defaults to `/24` when the prefix is omitted. You can also enter a subnet mask such as `192.168.1.5 255.255.255.0`, `192.168.1.5/255.255.255.0`, or the hexadecimal mask format from macOS `ifconfig` (`192.168.1.5/0xffffff00`); masks must be contiguous. IPv4 addresses must be four decimal octets without leading zeros. `/31` is counted as 2 addresses for point-to-point links and `/32` represents a single host, neither having a separate broadcast address. Usable host counts are mathematical values and do not exclude special-purpose addresses within the range. +- Displays the address classification (private, loopback, link-local, documentation, multicast, reserved, etc., based on the IANA IPv4 Special-Purpose Address Registry); classification applies only to the entered IP and does not probe reachability. +- Permissions support 3–4 digit octal values (e.g., `755`, `4755`, `1777`), 9-character symbolic strings (e.g., `rwxr-xr-x`, `rwsr-xr-x`, `rwxrwxrwt`), and `ls`-style strings with a leading file type character (e.g., `drwxr-xr-x`, optionally ending with macOS `@` / `+` or Linux `.` markers), distinguishing `s`/`S` and `t`/`T`. You can also enter `chmod 755` or `chmod -R 755`, but trailing filenames are not accepted and will report a format error. Replace `` in the copied command template yourself; the plugin never executes commands. +- Warns when world-writable permissions are set. Does not evaluate ACLs, file flags, user identity, or other runtime access controls. + +## Platforms & Requirements + +- Supported: Windows, macOS + +## Network & Data + +- Works offline; all calculations run locally. diff --git a/extensions/chmod-cidr-calc/plugin.json b/extensions/chmod-cidr-calc/plugin.json index 770aabfe..c37543cb 100644 --- a/extensions/chmod-cidr-calc/plugin.json +++ b/extensions/chmod-cidr-calc/plugin.json @@ -1,7 +1,8 @@ { "id": "chmod-cidr-calc", "name": "网段与权限计算", - "version": "1.0.6", + "version": "1.0.7", + "minAppVersion": "1.1.8.0", "description": "IPv4 CIDR 子网掩码/可用地址池/32 位二进制掩码计算与 Linux chmod 八进制/符号权限位双向推演工具", "author": "ZTools Team", "category": [ @@ -55,7 +56,11 @@ "ipcalc", "netmask", "permissions", - "ipv4" + "ipv4", + "ip calculator", + "linux permissions", + "network mask", + "umask" ], "features": { "chmod-cidr-calc": { @@ -81,5 +86,18 @@ { "path": "screenshots/01.png" } + ], + "keywords": [ + "权限计算", + "网段计算", + "子网掩码", + "ip计算", + "chmod", + "cidr", + "子网划分", + "linux权限", + "755", + "644", + "掩码" ] } diff --git a/extensions/clean-keyboard/README.en.md b/extensions/clean-keyboard/README.en.md new file mode 100644 index 00000000..1de697f3 --- /dev/null +++ b/extensions/clean-keyboard/README.en.md @@ -0,0 +1,22 @@ +# Keyboard Cleaning Lock + +Temporarily intercept keyboard input (and optionally mouse input) while wiping your keyboard; automatically restores input when the countdown ends, on emergency unlock, or if communication with the client is lost. + +## Usage + +- Command: Lock keyboard input for cleaning with automatic unlock after countdown (keywords such as `clean keyboard`, `lock keyboard`, `keyboard lock`, `disable keyboard`). +- Choose 15 seconds, 30 seconds, 1 minute, 2 minutes, or 5 minutes and press `Enter` to start, or press `⌘+Enter` to set a custom duration between 5 and 300 seconds. "Locked" is displayed only after the system confirms that input interception is active. +- Locks the keyboard only by default; switch to "Keyboard & Mouse" on the right side of the search box to also intercept mouse movement, clicks, and scrolling. +- Press `⌘+U` (or `Control+U`) at any time for emergency unlock; when only the keyboard is locked, you can also click **Unlock Now** with the mouse. Input also unlocks automatically when the timer expires, when leaving the plugin, when the client quits, or if communication is interrupted. +- Requires permission for ZTools under **System Settings → Privacy & Security → Accessibility**. When permission is missing or macOS Secure Input is active, locking fails explicitly rather than falsely reporting locked status. +- The power button, Touch ID, system-reserved keys, media keys, and certain trackpad gestures are outside the interception scope. Anyone can unlock using the emergency shortcut, so this is not a security screen lock and cannot prevent others from using your Mac. +- Only counts blocked events during the current lock session; never logs keystrokes or saves usage history. + +## Platforms & Requirements + +- Supported: macOS only +- Requires client version 1.1.8.5 or later. + +## Network & Data + +- Works offline; data stays on your local device. diff --git a/extensions/clean-keyboard/plugin.json b/extensions/clean-keyboard/plugin.json index 19f10a66..d2dd17eb 100644 --- a/extensions/clean-keyboard/plugin.json +++ b/extensions/clean-keyboard/plugin.json @@ -1,8 +1,9 @@ { "id": "clean-keyboard", "name": "键盘清洁锁", - "version": "1.0.5", - "description": "Mac 系统键盘清洁锁,可同时拦截鼠标,支持 5~300 秒倒计时、紧急解锁与失联自动解除", + "version": "1.0.6", + "minAppVersion": "1.1.8.0", + "description": "系统键盘清洁锁,可同时拦截鼠标,支持 5~300 秒倒计时、紧急解锁与失联自动解除", "author": "ZTools Team", "entry": "dist/index.js", "icon": "icon.svg", @@ -35,19 +36,30 @@ "platform": "macos", "runtime": "electron", "arch": "any" + }, + { + "id": "windows-electron-any", + "platform": "windows", + "runtime": "electron", + "arch": "any" } ], "defaultLocale": "zh-CN", "i18n": { "en-US": { "name": "Keyboard Cleaning Lock", - "description": "Lock your Mac keyboard (and optionally mouse) for safe cleaning with a 5 to 300 second countdown, emergency unlock, and automatic failsafe release.", + "description": "Lock your keyboard (and optionally mouse) for safe cleaning with a 5 to 300 second countdown, emergency unlock, and automatic failsafe release.", "keywords": [ "keyboard lock", "clean keyboard", "disable keyboard", "macos", - "lock input" + "windows", + "lock input", + "lock keyboard", + "wipe keyboard", + "cat lock", + "cleaning mode" ], "features": { "clean-keyboard": { @@ -71,5 +83,16 @@ { "path": "screenshots/01.png" } + ], + "keywords": [ + "键盘清洁", + "锁键盘", + "擦键盘", + "防误触", + "清洁键盘", + "锁定键盘", + "猫踩键盘", + "键盘锁", + "clean keyboard" ] } diff --git a/extensions/clean-keyboard/src/i18n.ts b/extensions/clean-keyboard/src/i18n.ts index c2ef1f58..7c833a3b 100644 --- a/extensions/clean-keyboard/src/i18n.ts +++ b/extensions/clean-keyboard/src/i18n.ts @@ -13,16 +13,19 @@ export const t = createTranslator( lockFailedTitle: "输入锁操作失败", navTitle: "键盘清洁锁", searchPlaceholder: "选择清洁时长,⌘+U 或 Control+U 紧急解除", + searchPlaceholderWin: "选择清洁时长,Ctrl+Alt+Shift+U 紧急解除", modeKeyboardOnly: "仅键盘", modeKeyboardAndPointer: "键盘与鼠标", summaryUnconfirmed: "状态未确认:{error}", summaryLocked: "系统输入锁已启用 · 剩余 {seconds} 秒", summaryExitedFallback: "输入锁已退出", summaryDefault: "最长 5 分钟;电源键、Touch ID、系统保留按键与部分手势不在保护范围", + summaryDefaultWin: "最长 5 分钟;Ctrl+Alt+Del 系统安全阀与电源键始终可用,不在拦截范围", activeUnconfirmedTitle: "锁定状态未确认,请勿开始清洁", activeBothLockedTitle: "键盘与鼠标已锁定", activeKeyboardLockedTitle: "键盘已锁定", activeSubtitle: "⌘+U 或 Control+U 立即解除;到时或离开插件自动解除", + activeSubtitleWin: "按 Ctrl+Alt+Shift+U 立即解除;Ctrl+Alt+Del 安全阀随时可用,到时或离开插件自动解除", blockedEventsAcc: "{count} 次拦截", unlockNowAction: "立即解除", cleanPresetTitle: "清洁 {duration}", @@ -58,17 +61,20 @@ export const t = createTranslator( lockNotConfirmed: "System did not confirm lock; do not start cleaning", lockFailedTitle: "Input lock failed", navTitle: "Clean Keyboard", - searchPlaceholder: "Choose clean duration; press ⌘+U or Ctrl+U to unlock urgently", + searchPlaceholder: "Choose clean duration; press ⌘+U or Control+U to unlock urgently", + searchPlaceholderWin: "Choose clean duration; press Ctrl+Alt+Shift+U to unlock urgently", modeKeyboardOnly: "Keyboard Only", modeKeyboardAndPointer: "Keyboard & Mouse", summaryUnconfirmed: "Status unconfirmed: {error}", summaryLocked: "Input lock active · {seconds}s remaining", summaryExitedFallback: "Input lock exited", summaryDefault: "Up to 5 min; power button, Touch ID, system-reserved keys and some gestures are not blocked", + summaryDefaultWin: "Up to 5 min; the Ctrl+Alt+Del system failsafe and power button always remain available", activeUnconfirmedTitle: "Lock unconfirmed — do not start cleaning", activeBothLockedTitle: "Keyboard & Mouse Locked", activeKeyboardLockedTitle: "Keyboard Locked", - activeSubtitle: "Press ⌘+U or Ctrl+U to unlock immediately; auto-unlocks on timeout or exit", + activeSubtitle: "Press ⌘+U or Control+U to unlock immediately; auto-unlocks on timeout or exit", + activeSubtitleWin: "Press Ctrl+Alt+Shift+U to unlock immediately; Ctrl+Alt+Del failsafe remains available, auto-unlocks on timeout or exit", blockedEventsAcc: "{count} blocked", unlockNowAction: "Unlock Now", cleanPresetTitle: "Clean for {duration}", diff --git a/extensions/clean-keyboard/src/index.tsx b/extensions/clean-keyboard/src/index.tsx index 357cf793..fdddb8df 100644 --- a/extensions/clean-keyboard/src/index.tsx +++ b/extensions/clean-keyboard/src/index.tsx @@ -1,5 +1,5 @@ import React, { Action, ActionPanel, Form, Icon, List, Toast, showToast, useEffect, useLocale, useNavigation, useRef, useState } from '@ztools/declarative-ui' -import { CLEAN_DURATION_PRESETS, createLockOperationId, formatCleanDuration, keyboardLock, unlockReasons } from './keyboard-lock-service.js' +import { CLEAN_DURATION_PRESETS, createLockOperationId, detectLockPlatform, formatCleanDuration, keyboardLock, unlockReasons, type LockClientPlatform } from './keyboard-lock-service.js' import type { KeyboardLockState } from './types.js' import { t } from './i18n.js' export * from './keyboard-lock-service.js' @@ -11,13 +11,15 @@ function CustomDurationForm({ start }: { start: (seconds: number) => Promise { if (await start(Number(values.seconds))) pop() }} />}> - + } -export function CleanKeyboardCommand() { +export function CleanKeyboardCommand(props?: { platform?: LockClientPlatform }) { useLocale() + const isWindows = detectLockPlatform(props?.platform) === 'windows' const [state, setState] = useState(null), [error, setError] = useState('') const [busy, setBusy] = useState(false), [pointer, setPointer] = useState(false) + const { push } = useNavigation() const id = useRef(createLockOperationId()), alive = useRef(true), changing = useRef(false) const revision = useRef(0), refreshing = useRef(null) const refresh = async () => { @@ -63,18 +65,28 @@ export function CleanKeyboardCommand() { } const locked = state?.status === 'locked' return setPointer(value === 'all')}> : undefined} - filterBar={{ summaryText: error ? t('summaryUnconfirmed', { error }) : locked ? t('summaryLocked', { seconds: state.remainingSeconds }) : state?.reason ? unlockReasons[state.reason] || t('summaryExitedFallback') : t('summaryDefault') }}> + filterBar={{ + summaryText: error ? t('summaryUnconfirmed', { error }) : locked ? t('summaryLocked', { seconds: state.remainingSeconds }) : state?.reason ? unlockReasons[state.reason] || t('summaryExitedFallback') : t(isWindows ? 'summaryDefaultWin' : 'summaryDefault'), + actions: locked + ? [{ id: 'unlock-now', title: t('unlockNowAction'), style: 'primary', onAction: () => void change() }] + : state + ? [ + { id: 'start-clean', title: t('startCleanAction'), style: 'primary', onAction: () => void change(CLEAN_DURATION_PRESETS[0]) }, + { id: 'custom-duration', title: t('customDurationAction'), onAction: () => push() } + ] + : [{ id: 'recheck', title: t('recheckAction'), onAction: () => void refresh() }] + }}> {locked ? { await change() }} />} /> : state ? <>{CLEAN_DURATION_PRESETS.map(seconds => { await change(seconds) }} /> - } shortcut={{ modifiers: ['cmd'], key: 'enter' }} /> + } shortcut={{ modifiers: ['ctrl'], key: 'enter' }} /> } />)} : } />} diff --git a/extensions/clean-keyboard/src/keyboard-lock-service.ts b/extensions/clean-keyboard/src/keyboard-lock-service.ts index d2a41548..3c7356fa 100644 --- a/extensions/clean-keyboard/src/keyboard-lock-service.ts +++ b/extensions/clean-keyboard/src/keyboard-lock-service.ts @@ -5,6 +5,18 @@ interface BridgeReply { success?: boolean; data?: unknown; error?: { message?: s interface Bridge { transport?: { methods?: { keyboard_lock?: (request: unknown) => Promise } } } let sequence = 0 export const CLEAN_DURATION_PRESETS = [15, 30, 60, 120, 300] as const +export type LockClientPlatform = 'windows' | 'macos' +/** 同步识别当前客户端操作系统,不触发额外 IPC 调用 */ +export function detectLockPlatform(override?: LockClientPlatform): LockClientPlatform { + if (override === 'windows' || override === 'macos') return override + const nav = (globalThis as { navigator?: { userAgent?: string; platform?: string } }).navigator + const hint = `${nav?.platform ?? ''} ${nav?.userAgent ?? ''}` + if (/win/i.test(hint)) return 'windows' + if (/mac/i.test(hint)) return 'macos' + const proc = (globalThis as { process?: { platform?: string } }).process + if (proc?.platform === 'win32') return 'windows' + return 'macos' +} export function createLockOperationId() { return `keyboard_${Date.now()}_${++sequence}` } export function validateLockState(value: unknown, id: string): KeyboardLockState { const state = value as KeyboardLockState | null diff --git a/extensions/clean-keyboard/tests/index.test.mjs b/extensions/clean-keyboard/tests/index.test.mjs index 205ae62b..51fa9edd 100644 --- a/extensions/clean-keyboard/tests/index.test.mjs +++ b/extensions/clean-keyboard/tests/index.test.mjs @@ -74,10 +74,22 @@ test('自定义时长只接受5至300整数,验证失败不会调用系统锁 await submit({ seconds: '45' }) assert.equal(host.ipcCalls.find(([, p]) => p.action === 'start')[1].durationSeconds, 45) }) -test('仅 macOS 插件的紧急解除提示使用 Mac 按键名称', async () => { - const view = await open() - assert.match(view.tree().props.searchBarPlaceholder, /⌘\+U 或 Control\+U/) - await view.run(view.item('duration-15'), '开始清洁') - assert.match(view.item('active').props.subtitle, /Control\+U/) - assert.doesNotMatch(view.text() + view.tree().props.searchBarPlaceholder, /Ctrl/) +test('macOS 与 Windows 各自展示平台对应的紧急解除快捷键与安全阀文案', async () => { + const macView = await mount(() => commands['clean-keyboard']({ platform: 'macos' })) + views.push(macView) + assert.match(macView.tree().props.searchBarPlaceholder, /⌘\+U 或 Control\+U/) + await macView.run(macView.item('duration-15'), '开始清洁') + assert.match(macView.item('active').props.subtitle, /Control\+U/) + assert.doesNotMatch(macView.text() + macView.tree().props.searchBarPlaceholder, /Ctrl/) + macView.unmount() + views.splice(views.indexOf(macView), 1) + await tick() + + const winView = await mount(() => commands['clean-keyboard']({ platform: 'windows' })) + views.push(winView) + assert.match(winView.tree().props.searchBarPlaceholder, /Ctrl\+Alt\+Shift\+U/) + assert.match(winView.tree().props.filterBar.summaryText, /Ctrl\+Alt\+Del/) + await winView.run(winView.item('duration-15'), '开始清洁') + assert.match(winView.item('active').props.subtitle, /Ctrl\+Alt\+Shift\+U/) + assert.match(winView.item('active').props.subtitle, /Ctrl\+Alt\+Del/) }) diff --git a/extensions/cleaner/README.en.md b/extensions/cleaner/README.en.md new file mode 100644 index 00000000..e8bda65b --- /dev/null +++ b/extensions/cleaner/README.en.md @@ -0,0 +1,21 @@ +# System Cleaner + +Scan temporary folders, browser caches, developer caches, and crash dumps, then move checked files to the Recycle Bin or empty the Recycle Bin. + +## Usage + +- Command: Search for "System Cleaner" in the launcher to open. +- Scan locations: User temp folder (`%TEMP%`; `C:\Windows\Temp` is a system directory that the client does not allow plugins to clean, so it is not scanned); File Explorer thumbnail and icon caches; Edge and Chrome web, script, and GPU caches (excluding cookies and saved passwords); npm and pip caches; VS Code caches and logs; application crash dumps and Windows Error Reporting; D3DSCache and SquirrelTemp; WPS Office backup folder; and installers/archives in the Downloads folder (`exe`, `msi`, `msix`, `zip`, `7z`, `rar`, `iso`). +- Non-empty "Safe Cache" categories are checked by default; the WPS Office backup folder (which may contain document backups), npm/pip caches, and installers in Downloads are unchecked by default. Use the top dropdown to filter by safety level, or filter by category on the left or switch to "Sample File Details" to check individual files. +- `Enter`: Clean checked files within the current filter after confirming the summary dialog showing file counts and sizes per category; `Ctrl+Enter`: Reveal in File Explorer; `Ctrl+K`: Open the action panel to empty the Recycle Bin or copy paths. +- Only the 25 largest files found per category are collected as samples, and the list indicates the cleanable sample count and size. Cleaning moves only the checked sample files to the Recycle Bin rather than deleting entire folders, so actual reclaimed disk space is typically smaller than the total folder usage shown. Files remain on disk while in the Recycle Bin until you empty it. +- Emptying the Recycle Bin requires confirmation and permanently deletes everything inside (including files deleted earlier elsewhere) without undo; if emptying fails, the reason is shown. +- Files currently in use or lacking permissions fail to move; whenever any files fail, the summary reports the failure count and reasons. If the user home directory cannot be read, a scan failure is reported. + +## Platforms & Requirements + +- Supported: Windows only + +## Network & Data + +- Works offline; data stays on your local device. diff --git a/extensions/cleaner/plugin.json b/extensions/cleaner/plugin.json index 9b1b36b7..759dacf6 100644 --- a/extensions/cleaner/plugin.json +++ b/extensions/cleaner/plugin.json @@ -2,7 +2,7 @@ "id": "cleaner", "name": "垃圾清理", "description": "扫描临时文件、浏览器缓存、开发工具缓存与崩溃转储等位置,把勾选的文件移入回收站,也可以清空回收站", - "version": "2.0.12", + "version": "2.0.13", "author": "ZTools Team", "entry": "dist/index.js", "icon": "icon.svg", @@ -38,7 +38,13 @@ "cache", "temp files", "recycle bin", - "disk cleanup" + "disk cleanup", + "junk cleaner", + "clean cache", + "free space", + "system cleaner", + "trash", + "purge" ], "screenshots": [ { @@ -51,5 +57,17 @@ { "path": "screenshots/02-action-panel.png" } + ], + "keywords": [ + "垃圾清理", + "清理垃圾", + "清垃圾", + "清缓存", + "释放空间", + "c盘清理", + "电脑清理", + "临时文件", + "回收站", + "系统清理" ] } diff --git a/extensions/cleaner/src/i18n.ts b/extensions/cleaner/src/i18n.ts index 0a6d02a8..d574ec2c 100644 --- a/extensions/cleaner/src/i18n.ts +++ b/extensions/cleaner/src/i18n.ts @@ -87,6 +87,11 @@ const rawT = createTranslator( actionUncheckGroup: "取消勾选此项", actionCheckGroup: "勾选此项", actionViewSampleFiles: "查看样本文件明细", + actionBackToRules: "返回清理规则列表", + toastCleaningTitle: "正在移入回收站...", + toastCleaningMsg: "正在处理 {count} 个文件,请稍候", + toastEmptyingBinTitle: "正在清空回收站...", + rightTitleGroupFiles: "{name} · 样本文件(按体积降序)", actionEmptySysBin: "清空系统回收站", actionCopyScanPath: "复制扫描路径", rightTitleFiles: "样本文件明细(按体积降序)", @@ -200,6 +205,11 @@ const rawT = createTranslator( actionUncheckGroup: "Uncheck Group", actionCheckGroup: "Check Group", actionViewSampleFiles: "View Sample Files", + actionBackToRules: "Back to Cleanup Rules", + toastCleaningTitle: "Moving files to Recycle Bin...", + toastCleaningMsg: "Processing {count} [[count:file|files]], please wait", + toastEmptyingBinTitle: "Emptying Recycle Bin...", + rightTitleGroupFiles: "{name} · Sample Files (Sorted by Size)", actionEmptySysBin: "Empty Recycle Bin", actionCopyScanPath: "Copy Scan Path", rightTitleFiles: "Sample Files (Sorted by Size)", diff --git a/extensions/cleaner/src/index.ts b/extensions/cleaner/src/index.ts index ccc8bbd4..bbda6a76 100644 --- a/extensions/cleaner/src/index.ts +++ b/extensions/cleaner/src/index.ts @@ -5,6 +5,7 @@ import { Icon, useState, useEffect, + useRef, showToast, Toast, confirmAlert, @@ -41,12 +42,15 @@ export default function CleanerCommand() { const inRealHost = isRealElectronHost() const [searchText, setSearchText] = useState('') const [viewMode, setViewMode] = useState<'groups' | 'files'>('groups') + const [drillGroupId, setDrillGroupId] = useState(null) const [classIdFilter, setClassIdFilter] = useState(0) const [riskFilter, setRiskFilter] = useState('all') const [groups, setGroups] = useState([]) const [checkedFilePaths, setCheckedFilePaths] = useState([]) const [summary, setSummary] = useState(() => computeCleanSummary([])) const [isLoading, setIsLoading] = useState(inRealHost) + const [isCleaning, setIsCleaning] = useState(false) + const cleaningRef = useRef(false) const [scanError, setScanError] = useState('') /** @@ -103,6 +107,11 @@ export default function CleanerCommand() { ) .sort((a, b) => b.sizeBytes - a.sizeBytes) + const drillGroup = drillGroupId ? filtered.find(g => g.id === drillGroupId) ?? null : null + const displayedSampleFiles: SampleRow[] = drillGroup + ? allSampleFiles.filter(f => f.groupId === drillGroup.id) + : allSampleFiles + // 清理范围:当前筛选(分类、安全等级、搜索)下显示的规则里,用户勾选的样本文件 const targetFiles = allSampleFiles.filter(f => checkedFileSet.has(f.path)) const targetBytes = targetFiles.reduce((s, f) => s + f.sizeBytes, 0) @@ -131,6 +140,7 @@ export default function CleanerCommand() { } async function handleCleanSelected() { + if (cleaningRef.current) return if (targetFiles.length === 0) { showToast({ style: Toast.Style.Failure, @@ -140,69 +150,104 @@ export default function CleanerCommand() { return } - const breakdownLines = filtered - .map(g => { - const inGroup = targetFiles.filter(f => f.groupId === g.id) - if (inGroup.length === 0) return '' - const bytes = inGroup.reduce((s, f) => s + f.sizeBytes, 0) - return t('confirmCleanBreakdown', { name: g.name, count: inGroup.length, size: formatBytes(bytes) }) + cleaningRef.current = true + setIsCleaning(true) + try { + const breakdownLines = filtered + .map(g => { + const inGroup = targetFiles.filter(f => f.groupId === g.id) + if (inGroup.length === 0) return '' + const bytes = inGroup.reduce((s, f) => s + f.sizeBytes, 0) + return t('confirmCleanBreakdown', { name: g.name, count: inGroup.length, size: formatBytes(bytes) }) + }) + .filter(Boolean) + .join('\n') + const hasCaution = filtered.some( + g => g.riskLevel === 'caution' && targetFiles.some(f => f.groupId === g.id) + ) + + const confirmed = await confirmAlert({ + title: t('confirmCleanTitle', { count: targetFiles.length }), + message: t('confirmCleanMsg', { + size: formatBytes(targetBytes), + breakdown: breakdownLines, + caution: hasCaution ? t('confirmCleanCaution') : '' + }), + primaryAction: { title: t('actionMoveToTrash'), style: 'destructive' } }) - .filter(Boolean) - .join('\n') - const hasCaution = filtered.some( - g => g.riskLevel === 'caution' && targetFiles.some(f => f.groupId === g.id) - ) + if (!confirmed) return - const confirmed = await confirmAlert({ - title: t('confirmCleanTitle', { count: targetFiles.length }), - message: t('confirmCleanMsg', { - size: formatBytes(targetBytes), - breakdown: breakdownLines, - caution: hasCaution ? t('confirmCleanCaution') : '' - }), - primaryAction: { title: t('actionMoveToTrash'), style: 'destructive' } - }) - if (!confirmed) return + showToast({ + style: Toast.Style.Animated, + title: t('toastCleaningTitle'), + message: t('toastCleaningMsg', { count: targetFiles.length }) + }) - const res = await executeCleanFiles( - targetFiles.map(f => f.path), - targetFiles - ) - const toast = summarizeCleanResult(res) - showToast({ - style: toast.success ? Toast.Style.Success : Toast.Style.Failure, - title: toast.title, - message: toast.message - }) - if (res.deletedCount > 0) { - await refreshData({ keepSelection: true }) + const res = await executeCleanFiles( + targetFiles.map(f => f.path), + targetFiles + ) + const toast = summarizeCleanResult(res) + showToast({ + style: toast.success ? Toast.Style.Success : Toast.Style.Failure, + title: toast.title, + message: toast.message + }) + if (res.deletedCount > 0) { + await refreshData({ keepSelection: true }) + } + } finally { + cleaningRef.current = false + setIsCleaning(false) } } async function handleEmptyRecycleBin() { - const confirmed = await confirmAlert({ - title: t('confirmEmptyBinTitle'), - message: t('confirmEmptyBinMsg'), - primaryAction: { title: t('actionEmptyBin'), style: 'destructive' } - }) - if (!confirmed) return + if (cleaningRef.current) return + cleaningRef.current = true + setIsCleaning(true) + try { + const confirmed = await confirmAlert({ + title: t('confirmEmptyBinTitle'), + message: t('confirmEmptyBinMsg'), + primaryAction: { title: t('actionEmptyBin'), style: 'destructive' } + }) + if (!confirmed) return - const res = await emptyRecycleBin() - if (!res.ok) { - showToast({ style: Toast.Style.Failure, title: t('emptyBinFailedDefault'), message: res.error }) - return + showToast({ + style: Toast.Style.Animated, + title: t('toastEmptyingBinTitle') + }) + + const res = await emptyRecycleBin() + if (!res.ok) { + showToast({ style: Toast.Style.Failure, title: t('emptyBinFailedDefault'), message: res.error }) + return + } + showToast({ + style: Toast.Style.Success, + title: t('emptyBinOkTitle'), + message: res.message || (typeof res.removedCount === 'number' ? t('emptyBinOkCount', { count: res.removedCount }) : undefined) + }) + await refreshData({ keepSelection: true }) + } finally { + cleaningRef.current = false + setIsCleaning(false) } - showToast({ - style: Toast.Style.Success, - title: t('emptyBinOkTitle'), - message: res.message || (typeof res.removedCount === 'number' ? t('emptyBinOkCount', { count: res.removedCount }) : undefined) - }) - await refreshData({ keepSelection: true }) } async function locate(path: string) { - const ok = await showRealItemInFolder(path) - if (!ok) showToast({ style: Toast.Style.Failure, title: t('revealFailedTitle'), message: path }) + if (!path) { + showToast({ style: Toast.Style.Failure, title: t('revealFailedTitle'), message: t('dirNotFound') }) + return + } + try { + const ok = await showRealItemInFolder(path) + if (!ok) showToast({ style: Toast.Style.Failure, title: t('revealFailedTitle'), message: path }) + } catch (err) { + const message = err instanceof Error ? err.message : String(err) + showToast({ style: Toast.Style.Failure, title: t('revealFailedTitle'), message: message || path }) + } } if (!inRealHost) { @@ -221,11 +266,11 @@ export default function CleanerCommand() { const cleanActionTitle = t('actionCleanSelected', { count: targetFiles.length, size: formatBytes(targetBytes) }) const maxGroupBytes = Math.max(1, filtered[0]?.totalSizeBytes || 1) - const maxSampleFileBytes = Math.max(1, allSampleFiles[0]?.sizeBytes || 1) + const maxSampleFileBytes = Math.max(1, displayedSampleFiles[0]?.sizeBytes || 1) const rightSubListItems = viewMode === 'files' - ? allSampleFiles.map(file => { + ? displayedSampleFiles.map(file => { const fileName = file.path.split(/[\\/]/).pop() || file.path const volRatio = Math.max(8, Math.min(100, Math.round((file.sizeBytes / maxSampleFileBytes) * 100))) const isChecked = checkedFileSet.has(file.path) @@ -256,6 +301,18 @@ export default function CleanerCommand() { icon: Icon.Checkmark, onAction: () => setPathsChecked([file.path], !isChecked) }), + ...(drillGroup + ? [ + Action({ + title: t('actionBackToRules'), + icon: Icon.ArrowLeft, + onAction: () => { + setDrillGroupId(null) + setViewMode('groups') + } + }) + ] + : []), Action({ title: cleanActionTitle, icon: Icon.Trash, @@ -298,6 +355,14 @@ export default function CleanerCommand() { actions: ActionPanel({ title: item.name, children: [ + Action({ + title: t('actionViewSampleFiles'), + icon: Icon.Document, + onAction: () => { + setDrillGroupId(item.id) + setViewMode('files') + } + }), ...(item.sampleFiles.length > 0 ? [ Action({ @@ -307,11 +372,6 @@ export default function CleanerCommand() { }) ] : []), - Action({ - title: t('actionViewSampleFiles'), - icon: Icon.Document, - onAction: () => setViewMode('files') - }), ...(locatePath ? [ Action({ @@ -331,6 +391,7 @@ export default function CleanerCommand() { Action({ title: t('actionEmptySysBin'), icon: Icon.Trash, + style: Action.Style.Destructive, onAction: () => handleEmptyRecycleBin() }), Action.CopyToClipboard({ @@ -345,15 +406,19 @@ export default function CleanerCommand() { const activeClassMeta = cleanClasses.find(c => c.classId === classIdFilter) const rightTitle = viewMode === 'files' - ? t('rightTitleFiles') + ? drillGroup + ? t('rightTitleGroupFiles', { name: drillGroup.name }) + : t('rightTitleFiles') : activeClassMeta ? t('rightTitleClass', { name: activeClassMeta.name }) : t('rightTitleAll') const checkableGroups = filtered.filter(g => g.sampleFiles.length > 0) - const scopePaths = allSampleFiles.map(f => f.path) - const allScopeChecked = scopePaths.length > 0 && targetFiles.length === scopePaths.length - const someScopeChecked = targetFiles.length > 0 && !allScopeChecked + const scopeFiles = viewMode === 'files' ? displayedSampleFiles : allSampleFiles + const scopePaths = scopeFiles.map(f => f.path) + const scopeCheckedCount = scopeFiles.filter(f => checkedFileSet.has(f.path)).length + const allScopeChecked = scopePaths.length > 0 && scopeCheckedCount === scopePaths.length + const someScopeChecked = scopeCheckedCount > 0 && !allScopeChecked const diskText = summary.diskTotalSizeBytes > 0 ? t('diskFreeText', { size: formatBytes(summary.diskFreeSizeBytes) }) : '' return List({ @@ -396,7 +461,7 @@ export default function CleanerCommand() { label: cleanActionTitle, title: cleanActionTitle, style: 'primary', - disabled: targetFiles.length === 0, + disabled: targetFiles.length === 0 || isCleaning, onAction: () => handleCleanSelected() }, { @@ -404,6 +469,7 @@ export default function CleanerCommand() { label: t('btnRescan'), title: t('btnRescan'), style: 'secondary', + disabled: isCleaning, onAction: () => refreshData({ showIndicator: true }) } ] @@ -412,9 +478,9 @@ export default function CleanerCommand() { title: rightTitle, subtitle: viewMode === 'files' - ? t('subListSubFiles', { total: allSampleFiles.length, checked: targetFiles.length, size: formatBytes(targetBytes) }) + ? t('subListSubFiles', { total: displayedSampleFiles.length, checked: targetFiles.length, size: formatBytes(targetBytes) }) : t('subListSubGroups', { total: filtered.length, checked: targetFiles.length, size: formatBytes(targetBytes) }), - checkable: viewMode === 'files' ? allSampleFiles.length > 0 : checkableGroups.length > 0, + checkable: viewMode === 'files' ? displayedSampleFiles.length > 0 : checkableGroups.length > 0, checked: allScopeChecked ? true : someScopeChecked ? 'indeterminate' : false, onCheckChange: () => setPathsChecked(scopePaths, !allScopeChecked), emptyText: isLoading @@ -436,6 +502,7 @@ export default function CleanerCommand() { accessories: [{ text: formatBytes(summary.totalSizeBytes) }], onSelect: () => { setClassIdFilter(0) + setDrillGroupId(null) setViewMode('groups') } }), @@ -445,7 +512,10 @@ export default function CleanerCommand() { subtitle: t('navFilesSub', { count: allSampleFiles.length }), icon: { source: Icon.Document }, accessories: [{ text: t('itemCountText', { count: allSampleFiles.length }) }], - onSelect: () => setViewMode('files') + onSelect: () => { + setDrillGroupId(null) + setViewMode('files') + } }) ] }), @@ -462,6 +532,7 @@ export default function CleanerCommand() { accessories: [{ text: formatBytes(clsBytes) }], onSelect: () => { setClassIdFilter(cls.classId) + setDrillGroupId(null) setViewMode('groups') } }) diff --git a/extensions/cleaner/src/logic.ts b/extensions/cleaner/src/logic.ts index cb1d8abe..8cb197a9 100644 --- a/extensions/cleaner/src/logic.ts +++ b/extensions/cleaner/src/logic.ts @@ -193,6 +193,7 @@ async function scanRealCleanRuleTree( maxFiles: 200, collectTopN: 20, filterExt, + ignoreMissing: true, hostOverride }) fileCount += res.fileCount diff --git a/extensions/cleaner/src/native-ipc.ts b/extensions/cleaner/src/native-ipc.ts index 51576b99..13643277 100644 --- a/extensions/cleaner/src/native-ipc.ts +++ b/extensions/cleaner/src/native-ipc.ts @@ -174,11 +174,13 @@ function normalizeMethodResult(method: string, payload: DynamicBridge): DynamicB if (method === 'system_get_battery_status') { // 宿主约定 percent 超出 0-100(如 255)表示无电池或电量未知,不能改写成 100% + // 若宿主明确给出 hasBattery 布尔值,必须原样保留,仅在缺失时按合法电量推算 const rawPct = payload.percent - const hasBattery = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const validPct = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const hasBattery = typeof payload.hasBattery === 'boolean' ? payload.hasBattery : validPct return { ...payload, - percent: hasBattery ? rawPct : null, + percent: validPct ? rawPct : null, hasBattery } } @@ -489,6 +491,8 @@ export interface RealDirectoryScanResult extends Iterable approximate?: boolean /** 宿主实际遍历的条目数 */ visitedEntries?: number + /** 目录本身不存在(ENOENT) */ + missing?: boolean /** 读取失败的真实原因;已有文件仍可使用,但不能当作完整结果。 */ error?: string } @@ -497,6 +501,7 @@ interface ScanResultMeta { truncated?: boolean approximate?: boolean visitedEntries?: number + missing?: boolean } export interface ScanDirectoryTreeOptions { @@ -504,6 +509,10 @@ export interface ScanDirectoryTreeOptions { maxFiles?: number collectTopN?: number filterExt?: RegExp + /** 为 true 时,目录本身不存在(ENOENT)按空目录处理,不返回 error(权限拒绝/读取失败仍照常报错) */ + ignoreMissing?: boolean + /** Top-N 保留与排序方式:默认按体积降序,下载/录屏等时效场景可传 mtime-desc */ + sortBy?: 'size-desc' | 'mtime-desc' hostOverride?: DynamicBridge } @@ -519,8 +528,9 @@ function normalizeIndexedFileEntry(f: DynamicBridge): RealIndexedFileEntry { const sz = Number(f?.size ?? f?.sizeBytes ?? 0) const isDir = Boolean(f?.is_dir || f?.isDir || f?.isDirectory) const rawMtime = Number(f?.mtime ?? f?.mtimeMs ?? 0) - const mtimeMs = rawMtime > 1e11 ? rawMtime : rawMtime > 0 ? rawMtime * 1000 : Date.now() - const mtimeSec = rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime + const validMtime = Number.isFinite(rawMtime) && rawMtime > 0 + const mtimeMs = validMtime ? (rawMtime > 1e11 ? rawMtime : rawMtime * 1000) : 0 + const mtimeSec = validMtime ? (rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime) : 0 if (p && sz >= 0) realFileSizeCache.set(p, sz) return { name, @@ -551,6 +561,7 @@ function makeScanResult( subdirs, ...(meta.truncated ? { truncated: true } : {}), ...(meta.approximate ? { approximate: true } : {}), + ...(meta.missing ? { missing: true } : {}), ...(typeof meta.visitedEntries === 'number' ? { visitedEntries: meta.visitedEntries } : {}), [Symbol.iterator]() { return files[Symbol.iterator]() @@ -609,13 +620,40 @@ export async function scanRealDirectoryTree( return result.error ? { ...result.scan, error: result.error } : result.scan } +/** 仅当正则明确声明了扩展名(含 `\.`)时提取后缀列表,避免把 `thumbcache|iconcache` 等文件名关键词误拆成假扩展名 */ +function extractExtensionTokensFromFilter(filterExt: RegExp): string[] { + const src = filterExt.source + if (!src.includes('\\.')) return [] + const afterDot = src.slice(src.indexOf('\\.') + 2) + const rawTokens = afterDot.match(/[a-z0-9]{1,8}/gi) || [] + const seen = new Set() + const out: string[] = [] + for (const token of rawTokens) { + const lower = token.toLowerCase() + if (!lower || seen.has(lower)) continue + seen.add(lower) + out.push(lower) + } + return out +} + +function isMissingDirectoryError(res: { error?: string; errorCode?: string; errorDetails?: Record }): boolean { + if (res.errorDetails?.reason === 'ENOENT' || res.errorCode === 'ENOENT') return true + const msg = String(res.error || '') + return /Directory does not exist|ENOENT/i.test(msg) +} + /** 一次界面扫描的错误汇总;多个目录并行扫描时保留可读目录的结果。 */ export function createDirectoryScanner(hostOverride?: DynamicBridge) { const failures = new Map() return { async scan(dir: string, options: number | ScanDirectoryTreeOptions = 160) { const result = await scanRealDirectoryTree(dir, options, hostOverride) - const error = result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') + const ignoreMissing = typeof options === 'object' && options !== null && options.ignoreMissing === true + const error = + result.missing && ignoreMissing + ? '' + : result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') if (error) failures.set(dir, error) else failures.delete(dir) return result @@ -648,26 +686,38 @@ async function scanDirectoryTreeWithError( const safeLimit = Math.min(200, Math.max(1, Math.floor(rawLimit || 160))) const hostOverride = opts.hostOverride const filterExt = opts.filterExt + const ignoreMissing = opts.ignoreMissing === true const dirQuery = `dir:${targetDir}` try { let rawPayload: DynamicBridge = null + const searchParams: Record = { + query: dirQuery, + limit: safeLimit, + ...(opts.sortBy ? { sortBy: opts.sortBy } : {}) + } const res = await callHostTransport( 'system_search_files', - { query: dirQuery, limit: safeLimit }, + searchParams, hostOverride ) - if (res.ok && res.data) { + if (res.ok && res.data && res.data.degraded !== true) { rawPayload = res.data + } else if (!res.ok && ignoreMissing && isMissingDirectoryError(res)) { + const missingScan = makeScanResult([], 0, 0, [], { missing: true }) + return { scan: missingScan } } - if (!rawPayload && !hostOverride && typeof window !== 'undefined') { + if (!rawPayload && !hostOverride && res.errorCode === 'METHOD_NOT_AVAILABLE' && typeof window !== 'undefined') { const w = window as DynamicBridge if (typeof w.__ztoolsLauncher?.searchFiles === 'function') { const rawOuter = await w.__ztoolsLauncher.searchFiles(dirQuery, safeLimit) - rawPayload = + const candidate = rawOuter && typeof rawOuter === 'object' && 'data' in rawOuter && rawOuter.data ? rawOuter.data : rawOuter + if (candidate && candidate.degraded !== true && candidate.success !== false) { + rawPayload = candidate + } } } @@ -678,29 +728,32 @@ async function scanDirectoryTreeWithError( let files: RealIndexedFileEntry[] = rawPayload.files.map(normalizeIndexedFileEntry) if (filterExt instanceof RegExp) { files = files.filter(f => !f.isDir && (filterExt.test(f.name) || filterExt.test(f.ext))) - // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索目标扩展名 + // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索明确声明的目标扩展名 if (files.length === 0 && !hostOverride) { - const extTokens = (filterExt.source.match(/[a-z0-9]{2,5}/gi) || []) - .filter(t => !['thumbcache', 'iconcache'].includes(t.toLowerCase())) - .slice(0, 4) - // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 - const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() - const extraLists = await Promise.all( - extTokens.map(ext => searchRealIndexedFiles(`.${ext.toLowerCase()}`, 30, hostOverride)) - ) - const seen = new Set() - for (const list of extraLists) { - for (const item of list) { - if (!item.isDir && item.size > 0 && !seen.has(item.path)) { - if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { - seen.add(item.path) - files.push(item) + const extTokens = extractExtensionTokensFromFilter(filterExt) + if (extTokens.length > 0) { + // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 + const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() + const extraLists = await Promise.all( + extTokens.map(ext => searchRealIndexedFiles(`.${ext}`, 30, hostOverride)) + ) + const seen = new Set() + for (const list of extraLists) { + for (const item of list) { + if (!item.isDir && item.size > 0 && !seen.has(item.path)) { + if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { + seen.add(item.path) + files.push(item) + } } } } } } } + // 先基于过滤后的完整命中集合计算总文件数与总字节数,再按 collectTopN 裁剪样本列表 + const matchedCount = files.length + const matchedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) if (typeof opts.collectTopN === 'number' && opts.collectTopN > 0 && files.length > opts.collectTopN) { files = files.slice(0, opts.collectTopN) } @@ -714,11 +767,10 @@ async function scanDirectoryTreeWithError( ...(s.approximate === true ? { approximate: true } : {}) })) : [] - const computedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) const totalFilesCount = - filterExt instanceof RegExp ? files.length : Number(rawPayload.total_matches ?? files.length) + filterExt instanceof RegExp ? matchedCount : Number(rawPayload.total_matches ?? matchedCount) const totalBytesCount = - filterExt instanceof RegExp ? computedBytes : Number(rawPayload.total_bytes ?? computedBytes) + filterExt instanceof RegExp ? matchedBytes : Number(rawPayload.total_bytes ?? matchedBytes) const visited = Number(rawPayload.visited_entries) return { scan: makeScanResult(files, totalFilesCount, totalBytesCount, subdirs, { @@ -1817,8 +1869,6 @@ export async function writeRealClipboardText(text: string, hostOverride?: Dynami const payload = { text: String(text || '') } const res = await callHostTransport('clipboard_copy_text', payload, hostOverride) if (res.ok) return true - const fallbackRes = await callHostTransport('clipboard_write_text', payload, hostOverride) - if (fallbackRes.ok) return true try { if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) { await navigator.clipboard.writeText(String(text || '')) diff --git a/extensions/cleaner/tests/cleaner.ui.test.mjs b/extensions/cleaner/tests/cleaner.ui.test.mjs index 45d31182..6a2bb775 100644 --- a/extensions/cleaner/tests/cleaner.ui.test.mjs +++ b/extensions/cleaner/tests/cleaner.ui.test.mjs @@ -77,7 +77,7 @@ test('默认勾选安全缓存,WPS 备份与“下载”里的文件默认不 assert.match(host.confirms[0].title, /把 2 个文件移入回收站/) assert.deepEqual(trashed.sort(), [`${TEMP}\\a.tmp`, `${TEMP}\\b.tmp`]) assert.equal(host.dllCalls.length, 0, '清理不能走整类清理接口') - const done = host.toasts.find(t => /回收站/.test(t.title)) + const done = host.toasts.filter(t => /回收站/.test(t.title)).at(-1) assert.equal(done.style, Toast.Style.Success) assert.equal(done.title, '已移入回收站 2 个文件') }) @@ -218,11 +218,11 @@ test('安全红线:分组行与文件行 Enter 主动作不触发全局清理 const view = await mount(CleanerCommand) await waitFor(view, loaded) - // 1. 分组行主动作应切换勾选(或查看样本),而非全局清理 + // 1. 分组行主动作应钻取当前规则的样本文件明细,而非全局清理 const temp = subItems(view).find(it => it.props.id === 'group-sys-temp') const groupActions = view.actions(temp) assert.ok(!groupActions[0].props.title.startsWith('清理已勾选'), '分组行 Enter 主动作不能触发全局清理') - assert.match(groupActions[0].props.title, /勾选此项/) + assert.match(groupActions[0].props.title, /查看样本文件明细/) const groupCleanAct = cleanAction(view, temp) assert.ok(groupCleanAct && groupCleanAct.props.shortcut, '清理动作应作为次动作并带快捷键') @@ -243,3 +243,83 @@ test('安全红线:分组行与文件行 Enter 主动作不触发全局清理 const fileCleanAct = cleanAction(view, fileRow) assert.ok(fileCleanAct && fileCleanAct.props.shortcut) }) + +test('回归:ENOENT 缺失目录不记入扫描 error,PERMISSION_DENIED 仍报错', async () => { + const host = createHost() + installCleanerHost(host) + host.ipc.system_search_files = async ({ query }) => { + const dir = String(query).slice(4) + if (dir === TEMP) { + const files = [entry(`${TEMP}\\a.tmp`, 1024)] + return { files, subdirs: [], total_matches: 1, total_bytes: 1024 } + } + throw Object.assign(new Error('Directory does not exist'), { code: 'ENOENT' }) + } + const okScan = await logic.fetchCleanRulesAndScan() + assert.equal(okScan.error, undefined, '可选目录 ENOENT 不应触发扫描不完整红错') + assert.equal(okScan.groups.find(g => g.id === 'group-sys-temp').fileCount, 1) + + host.ipc.system_search_files = async ({ query }) => { + const dir = String(query).slice(4) + if (dir === TEMP) { + const files = [entry(`${TEMP}\\a.tmp`, 1024)] + return { files, subdirs: [], total_matches: 1, total_bytes: 1024 } + } + if (dir.includes('Chrome')) { + throw Object.assign(new Error('PERMISSION_DENIED: chrome cache'), { code: 'PERMISSION_DENIED' }) + } + throw Object.assign(new Error('Directory does not exist'), { code: 'ENOENT' }) + } + host.ipc.filesystem_get_directory_contents = async () => { + throw Object.assign(new Error('PERMISSION_DENIED: chrome cache'), { code: 'PERMISSION_DENIED' }) + } + const permScan = await logic.fetchCleanRulesAndScan() + assert.match(permScan.error || '', /PERMISSION_DENIED/, '权限拒绝必须照常报错') +}) + +test('回归:filterExt 命中超过 20 个文件时 fileCount 与 totalSizeBytes 不被 collectTopN 截断', async () => { + const host = createHost() + installCleanerHost(host) + const exeFiles = Array.from({ length: 30 }, (_, i) => entry(`${DOWNLOADS}\\pkg_${i}.exe`, 1000 + i)) + const noiseFiles = Array.from({ length: 5 }, (_, i) => entry(`${DOWNLOADS}\\note_${i}.txt`, 500)) + const expectedTotalBytes = exeFiles.reduce((sum, f) => sum + f.size, 0) + host.ipc.system_search_files = async ({ query }) => { + const dir = String(query).slice(4) + if (dir === DOWNLOADS) { + const all = [...exeFiles, ...noiseFiles] + return { + files: all, + subdirs: [], + total_matches: all.length, + total_bytes: all.reduce((sum, f) => sum + f.size, 0) + } + } + if (dir === TEMP) { + return { files: [entry(`${TEMP}\\a.tmp`, 100)], subdirs: [], total_matches: 1, total_bytes: 100 } + } + throw Object.assign(new Error('Directory does not exist'), { code: 'ENOENT' }) + } + const res = await logic.fetchCleanRulesAndScan() + assert.equal(res.error, undefined) + const dl = res.groups.find(g => g.id === 'group-downloads-installers') + assert.ok(dl) + assert.equal(dl.fileCount, 30, 'fileCount 应保留全部 30 个命中文件,不能被 collectTopN=20 截断') + assert.equal(dl.totalSizeBytes, expectedTotalBytes, 'totalSizeBytes 应统计全部 30 个命中文件总大小') + assert.equal(dl.sampleFiles.length, 20, 'sampleFiles 仍按 collectTopN=20 裁剪') +}) + +test('回归:无样本文件的规则点击定位失败时弹出明确失败 Toast,不静默失败', async () => { + const host = createHost() + installCleanerHost(host) + host.ipc.shell_show_item_in_folder = async () => ({ success: false, error: '路径不存在' }) + const view = await mount(CleanerCommand) + await waitFor(view, loaded) + + const edge = subItems(view).find(it => it.props.id === 'group-browser-edge') + assert.ok(edge, '应存在无样本文件的 Edge 规则项') + await view.run(edge, '在资源管理器定位') + const toast = host.lastToast() + assert.equal(toast.style, Toast.Style.Failure) + assert.equal(toast.title, '无法在资源管理器中定位') + assert.match(toast.message, /Microsoft\\Edge\\User Data\\Default\\Cache/) +}) diff --git a/extensions/clipboard-manager/README.en.md b/extensions/clipboard-manager/README.en.md new file mode 100644 index 00000000..8b347cce --- /dev/null +++ b/extensions/clipboard-manager/README.en.md @@ -0,0 +1,22 @@ +# Clipboard History + +Browse local clipboard history (text, images, files) recorded by the client; search, pin, edit, and paste items back into your active application. + +## Usage + +- Command: Search for "Clipboard History" in the launcher to open. +- Lists the most recent 100 items. The search box supports content and pinyin initials, and the top dropdown filters by type (Pinned, Color, JSON, Code, Link, File, Image, Plain Text). +- `Enter`: Paste into the active foreground application; `⌘/Ctrl+Enter`: Copy to clipboard only; `⌘/Ctrl+K`: Open the action panel. +- Common shortcuts: `⌘/Ctrl+P` pin or unpin; `⌘/Ctrl+E` edit; `⌘/Ctrl+N` create new item; `⌘/Ctrl+D` view full details; `⌘/Ctrl+B` show or hide the right detail pane; `⌘/Ctrl+O` open link or reveal file; `⌘/Ctrl+Shift+V` paste next item in sequence; `⌘/Ctrl+X` delete (requires confirmation); `⌘/Ctrl+Shift+X` clear all unpinned items. +- Clearing unpinned items (including **Clear Unpinned** in the status bar) prompts for confirmation while keeping pinned items intact. +- Suspected sensitive values (such as API keys, GitHub tokens, AWS credentials, private keys, and JWTs) are masked in the list and preview, while copying and pasting still use the original text. +- Pasting into the active application requires simulated keystrokes, so on macOS you must grant Accessibility permission to ZTools in **System Settings → Privacy & Security → Accessibility**. Without permission, items are only copied to the clipboard without auto-pasting, and a prompt guides you to System Settings. + +## Platforms & Requirements + +- Supported: Windows, macOS +- Requires client version 1.1.8.3 or later. + +## Network & Data + +- Works offline; clipboard history stays on your local device. diff --git a/extensions/clipboard-manager/plugin.json b/extensions/clipboard-manager/plugin.json index 98b18066..1d749547 100644 --- a/extensions/clipboard-manager/plugin.json +++ b/extensions/clipboard-manager/plugin.json @@ -2,7 +2,8 @@ "id": "clipboard-manager", "name": "剪贴板历史", "description": "查看客户端记录的剪贴板历史(文本、图片、文件),支持搜索、置顶、编辑,并粘贴回前台应用", - "version": "2.0.14", + "version": "2.0.15", + "minAppVersion": "1.1.8.0", "author": "ZTools Team", "entry": "dist/index.js", "icon": "icon.svg", @@ -41,7 +42,14 @@ "paste", "copy", "snippets", - "pin" + "pin", + "clipboard history", + "paste history", + "copy history", + "copied text", + "pasteboard", + "clip", + "recent copies" ], "screenshots": [ { @@ -54,5 +62,17 @@ { "path": "screenshots/01.png" } + ], + "keywords": [ + "剪贴板", + "剪切板", + "复制历史", + "粘贴历史", + "剪贴板历史", + "刚才复制的", + "复制记录", + "粘贴记录", + "clipboard", + "history" ] } diff --git a/extensions/clipboard-manager/src/i18n.ts b/extensions/clipboard-manager/src/i18n.ts index 4bcc6b7a..4e2ea067 100644 --- a/extensions/clipboard-manager/src/i18n.ts +++ b/extensions/clipboard-manager/src/i18n.ts @@ -163,7 +163,12 @@ const rawT = createTranslator( actionHideDetail: "关闭右侧详情分栏", actionShowDetail: "展开右侧详情分栏", actionEditRecord: "编辑该剪贴板内容...", - actionClearUnpinnedAll: "清空所有未置顶记录" + actionClearUnpinnedAll: "清空所有未置顶记录", + emptyHistoryTitle: "暂无剪贴板历史", + emptyHistorySub: "复制文本、图片或文件后自动记录,按 Enter 立即同步当前剪贴板", + emptyNoMatchTitle: "没有匹配的剪贴板记录", + emptyNoMatchSub: "当前搜索词或筛选类型下无结果,按 Enter 清除筛选", + actionResetFilter: "清除搜索与类型筛选" }, "en-US": { notInClient: "Requires the ZTools client", @@ -326,7 +331,12 @@ const rawT = createTranslator( actionHideDetail: "Hide Detail Pane", actionShowDetail: "Show Detail Pane", actionEditRecord: "Edit Content...", - actionClearUnpinnedAll: "Clear All Unpinned" + actionClearUnpinnedAll: "Clear All Unpinned", + emptyHistoryTitle: "No Clipboard History", + emptyHistorySub: "Copied text, images, or files appear here; press Enter to sync now", + emptyNoMatchTitle: "No Matching Clipboard Items", + emptyNoMatchSub: "No results for current query or filter; press Enter to reset", + actionResetFilter: "Reset Search & Filter" } } ) diff --git a/extensions/clipboard-manager/src/index.tsx b/extensions/clipboard-manager/src/index.tsx index 2a5d6011..d9c60078 100644 --- a/extensions/clipboard-manager/src/index.tsx +++ b/extensions/clipboard-manager/src/index.tsx @@ -84,7 +84,7 @@ export function getDisplayTitle(item: ClipboardItem): string { } export function getClipboardMarkdown(item: ClipboardItem): string { - let markdown = t("detailTitle"); + let markdown = ""; const sensitivity = maskSensitiveContent(item.content); if (sensitivity.isSensitive) { @@ -357,6 +357,7 @@ export function ClipboardDetailView({ { if (!(await confirmDeleteItem(item))) return; @@ -596,6 +597,7 @@ export default function ClipboardHistoryCommand() { setSelectedId(id || "")} @@ -612,7 +614,7 @@ export default function ClipboardHistoryCommand() { id: "clear", label: t("btnClearUnpinned"), title: t("btnClearUnpinned"), - style: "secondary", + style: "destructive", onAction: () => { void handleClearUnpinned(); } @@ -668,6 +670,49 @@ export default function ClipboardHistoryCommand() { subtitle={!inClient ? t("loadErrorClientSub") : loadError} icon={Icon.ExclamationMark} /> + ) : inClient && !loadError && !isLoading && filteredItems.length === 0 ? ( + items.length === 0 ? ( + + + } + /> + + } + /> + ) : ( + + { + setFilterType("all"); + setSearchText(""); + }} + /> + + } + /> + ) ) : null} {filteredItems.map(item => { @@ -781,24 +826,20 @@ export default function ClipboardHistoryCommand() { - } - /> + {item.type !== "image" && item.type !== "files" ? ( + } + /> + ) : null} } /> - { if (!(await confirmDeleteItem(item))) return; await handleDelete(item.id); }} /> - - } /> diff --git a/extensions/clipboard-manager/src/native-ipc.ts b/extensions/clipboard-manager/src/native-ipc.ts index 51576b99..13643277 100644 --- a/extensions/clipboard-manager/src/native-ipc.ts +++ b/extensions/clipboard-manager/src/native-ipc.ts @@ -174,11 +174,13 @@ function normalizeMethodResult(method: string, payload: DynamicBridge): DynamicB if (method === 'system_get_battery_status') { // 宿主约定 percent 超出 0-100(如 255)表示无电池或电量未知,不能改写成 100% + // 若宿主明确给出 hasBattery 布尔值,必须原样保留,仅在缺失时按合法电量推算 const rawPct = payload.percent - const hasBattery = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const validPct = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const hasBattery = typeof payload.hasBattery === 'boolean' ? payload.hasBattery : validPct return { ...payload, - percent: hasBattery ? rawPct : null, + percent: validPct ? rawPct : null, hasBattery } } @@ -489,6 +491,8 @@ export interface RealDirectoryScanResult extends Iterable approximate?: boolean /** 宿主实际遍历的条目数 */ visitedEntries?: number + /** 目录本身不存在(ENOENT) */ + missing?: boolean /** 读取失败的真实原因;已有文件仍可使用,但不能当作完整结果。 */ error?: string } @@ -497,6 +501,7 @@ interface ScanResultMeta { truncated?: boolean approximate?: boolean visitedEntries?: number + missing?: boolean } export interface ScanDirectoryTreeOptions { @@ -504,6 +509,10 @@ export interface ScanDirectoryTreeOptions { maxFiles?: number collectTopN?: number filterExt?: RegExp + /** 为 true 时,目录本身不存在(ENOENT)按空目录处理,不返回 error(权限拒绝/读取失败仍照常报错) */ + ignoreMissing?: boolean + /** Top-N 保留与排序方式:默认按体积降序,下载/录屏等时效场景可传 mtime-desc */ + sortBy?: 'size-desc' | 'mtime-desc' hostOverride?: DynamicBridge } @@ -519,8 +528,9 @@ function normalizeIndexedFileEntry(f: DynamicBridge): RealIndexedFileEntry { const sz = Number(f?.size ?? f?.sizeBytes ?? 0) const isDir = Boolean(f?.is_dir || f?.isDir || f?.isDirectory) const rawMtime = Number(f?.mtime ?? f?.mtimeMs ?? 0) - const mtimeMs = rawMtime > 1e11 ? rawMtime : rawMtime > 0 ? rawMtime * 1000 : Date.now() - const mtimeSec = rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime + const validMtime = Number.isFinite(rawMtime) && rawMtime > 0 + const mtimeMs = validMtime ? (rawMtime > 1e11 ? rawMtime : rawMtime * 1000) : 0 + const mtimeSec = validMtime ? (rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime) : 0 if (p && sz >= 0) realFileSizeCache.set(p, sz) return { name, @@ -551,6 +561,7 @@ function makeScanResult( subdirs, ...(meta.truncated ? { truncated: true } : {}), ...(meta.approximate ? { approximate: true } : {}), + ...(meta.missing ? { missing: true } : {}), ...(typeof meta.visitedEntries === 'number' ? { visitedEntries: meta.visitedEntries } : {}), [Symbol.iterator]() { return files[Symbol.iterator]() @@ -609,13 +620,40 @@ export async function scanRealDirectoryTree( return result.error ? { ...result.scan, error: result.error } : result.scan } +/** 仅当正则明确声明了扩展名(含 `\.`)时提取后缀列表,避免把 `thumbcache|iconcache` 等文件名关键词误拆成假扩展名 */ +function extractExtensionTokensFromFilter(filterExt: RegExp): string[] { + const src = filterExt.source + if (!src.includes('\\.')) return [] + const afterDot = src.slice(src.indexOf('\\.') + 2) + const rawTokens = afterDot.match(/[a-z0-9]{1,8}/gi) || [] + const seen = new Set() + const out: string[] = [] + for (const token of rawTokens) { + const lower = token.toLowerCase() + if (!lower || seen.has(lower)) continue + seen.add(lower) + out.push(lower) + } + return out +} + +function isMissingDirectoryError(res: { error?: string; errorCode?: string; errorDetails?: Record }): boolean { + if (res.errorDetails?.reason === 'ENOENT' || res.errorCode === 'ENOENT') return true + const msg = String(res.error || '') + return /Directory does not exist|ENOENT/i.test(msg) +} + /** 一次界面扫描的错误汇总;多个目录并行扫描时保留可读目录的结果。 */ export function createDirectoryScanner(hostOverride?: DynamicBridge) { const failures = new Map() return { async scan(dir: string, options: number | ScanDirectoryTreeOptions = 160) { const result = await scanRealDirectoryTree(dir, options, hostOverride) - const error = result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') + const ignoreMissing = typeof options === 'object' && options !== null && options.ignoreMissing === true + const error = + result.missing && ignoreMissing + ? '' + : result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') if (error) failures.set(dir, error) else failures.delete(dir) return result @@ -648,26 +686,38 @@ async function scanDirectoryTreeWithError( const safeLimit = Math.min(200, Math.max(1, Math.floor(rawLimit || 160))) const hostOverride = opts.hostOverride const filterExt = opts.filterExt + const ignoreMissing = opts.ignoreMissing === true const dirQuery = `dir:${targetDir}` try { let rawPayload: DynamicBridge = null + const searchParams: Record = { + query: dirQuery, + limit: safeLimit, + ...(opts.sortBy ? { sortBy: opts.sortBy } : {}) + } const res = await callHostTransport( 'system_search_files', - { query: dirQuery, limit: safeLimit }, + searchParams, hostOverride ) - if (res.ok && res.data) { + if (res.ok && res.data && res.data.degraded !== true) { rawPayload = res.data + } else if (!res.ok && ignoreMissing && isMissingDirectoryError(res)) { + const missingScan = makeScanResult([], 0, 0, [], { missing: true }) + return { scan: missingScan } } - if (!rawPayload && !hostOverride && typeof window !== 'undefined') { + if (!rawPayload && !hostOverride && res.errorCode === 'METHOD_NOT_AVAILABLE' && typeof window !== 'undefined') { const w = window as DynamicBridge if (typeof w.__ztoolsLauncher?.searchFiles === 'function') { const rawOuter = await w.__ztoolsLauncher.searchFiles(dirQuery, safeLimit) - rawPayload = + const candidate = rawOuter && typeof rawOuter === 'object' && 'data' in rawOuter && rawOuter.data ? rawOuter.data : rawOuter + if (candidate && candidate.degraded !== true && candidate.success !== false) { + rawPayload = candidate + } } } @@ -678,29 +728,32 @@ async function scanDirectoryTreeWithError( let files: RealIndexedFileEntry[] = rawPayload.files.map(normalizeIndexedFileEntry) if (filterExt instanceof RegExp) { files = files.filter(f => !f.isDir && (filterExt.test(f.name) || filterExt.test(f.ext))) - // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索目标扩展名 + // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索明确声明的目标扩展名 if (files.length === 0 && !hostOverride) { - const extTokens = (filterExt.source.match(/[a-z0-9]{2,5}/gi) || []) - .filter(t => !['thumbcache', 'iconcache'].includes(t.toLowerCase())) - .slice(0, 4) - // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 - const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() - const extraLists = await Promise.all( - extTokens.map(ext => searchRealIndexedFiles(`.${ext.toLowerCase()}`, 30, hostOverride)) - ) - const seen = new Set() - for (const list of extraLists) { - for (const item of list) { - if (!item.isDir && item.size > 0 && !seen.has(item.path)) { - if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { - seen.add(item.path) - files.push(item) + const extTokens = extractExtensionTokensFromFilter(filterExt) + if (extTokens.length > 0) { + // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 + const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() + const extraLists = await Promise.all( + extTokens.map(ext => searchRealIndexedFiles(`.${ext}`, 30, hostOverride)) + ) + const seen = new Set() + for (const list of extraLists) { + for (const item of list) { + if (!item.isDir && item.size > 0 && !seen.has(item.path)) { + if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { + seen.add(item.path) + files.push(item) + } } } } } } } + // 先基于过滤后的完整命中集合计算总文件数与总字节数,再按 collectTopN 裁剪样本列表 + const matchedCount = files.length + const matchedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) if (typeof opts.collectTopN === 'number' && opts.collectTopN > 0 && files.length > opts.collectTopN) { files = files.slice(0, opts.collectTopN) } @@ -714,11 +767,10 @@ async function scanDirectoryTreeWithError( ...(s.approximate === true ? { approximate: true } : {}) })) : [] - const computedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) const totalFilesCount = - filterExt instanceof RegExp ? files.length : Number(rawPayload.total_matches ?? files.length) + filterExt instanceof RegExp ? matchedCount : Number(rawPayload.total_matches ?? matchedCount) const totalBytesCount = - filterExt instanceof RegExp ? computedBytes : Number(rawPayload.total_bytes ?? computedBytes) + filterExt instanceof RegExp ? matchedBytes : Number(rawPayload.total_bytes ?? matchedBytes) const visited = Number(rawPayload.visited_entries) return { scan: makeScanResult(files, totalFilesCount, totalBytesCount, subdirs, { @@ -1817,8 +1869,6 @@ export async function writeRealClipboardText(text: string, hostOverride?: Dynami const payload = { text: String(text || '') } const res = await callHostTransport('clipboard_copy_text', payload, hostOverride) if (res.ok) return true - const fallbackRes = await callHostTransport('clipboard_write_text', payload, hostOverride) - if (fallbackRes.ok) return true try { if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) { await navigator.clipboard.writeText(String(text || '')) diff --git a/extensions/clipboard-manager/tests/clipboard-manager.fixes.test.mjs b/extensions/clipboard-manager/tests/clipboard-manager.fixes.test.mjs index 38fada9d..d3bd4c7f 100644 --- a/extensions/clipboard-manager/tests/clipboard-manager.fixes.test.mjs +++ b/extensions/clipboard-manager/tests/clipboard-manager.fixes.test.mjs @@ -269,7 +269,7 @@ test('清空非置顶:宿主库和插件存储都清,置顶的保留', async writeStored([localRec('clip-1790000000001', 'L1'), localRec('clip-1790000000002', 'L2', { pinned: true })]) const view = await mount(ClipboardHistoryCommand) await tick(20) - await view.run(view.item('h-a'), '清空所有未置顶记录') + await view.tree().props.filterBar.actions.find((a) => a.id === 'clear').onAction() await tick(20) assert.deepEqual(db.rows.map((r) => r.content), ['B']) assert.deepEqual(readStored().map((i) => i.content), ['L2']) @@ -524,17 +524,12 @@ test('清空非置顶前必须确认:取消时宿主库和插件存储都不 const view = await mount(ClipboardHistoryCommand) await tick(20) host.setConfirm(false) - await view.run(view.item('h-a'), '清空所有未置顶记录') + await view.tree().props.filterBar.actions.find((a) => a.id === 'clear').onAction() await tick(20) assert.equal(host.confirms.length, 1) assert.match(host.confirms[0].message, /置顶的记录会保留/) assert.deepEqual(db.rows.map((r) => r.content).sort(), ['A', 'B']) assert.deepEqual(readStored().map((i) => i.content), ['L1']) - // 状态栏的「清空非置顶」走同一个确认 - await view.tree().props.filterBar.actions.find((a) => a.id === 'clear').onAction() - await tick(20) - assert.equal(host.confirms.length, 2) - assert.deepEqual(db.rows.map((r) => r.content).sort(), ['A', 'B']) }) test('删除单条记录前必须确认(列表与详情页):取消时不调用宿主删除', async () => { diff --git a/extensions/color-picker/README.en.md b/extensions/color-picker/README.en.md new file mode 100644 index 00000000..a5ef8d62 --- /dev/null +++ b/extensions/color-picker/README.en.md @@ -0,0 +1,20 @@ +# Color Picker + +Convert between color formats, check WCAG accessibility contrast ratios, and save favorite colors to a local palette. + +## Usage + +- Commands: Color format conversion (keywords such as `color convert`, `hex to rgb`, `rgb to hex`, `oklch`, `cmyk`, `hsl`) and WCAG accessibility contrast check (`contrast`, `wcag`, `contrast check`, `color accessibility`). For contrast checking, enter foreground and background colors (e.g., `#333333 #FFFFFF`) to view the contrast ratio and AA/AAA pass status for normal and large text; if only one color is entered, it checks against both white and black backgrounds. +- Enter `#RGB`, `#RRGGBB`, `#RRGGBBAA`, `rgb()`, `hsl()`, `hsv()`, `oklch()`, `cmyk()`, or a CSS color name to list HEX, RGB, HSL, OKLCH, HSV, CMYK, HEX with alpha, Tailwind arbitrary value, and CSS variable formats. Out-of-gamut sRGB colors are clamped to the nearest sRGB color with a notice. +- The right pane displays the color swatch, contrast ratios against white and black text, WCAG grade (`AAA`, `AA`, `AA Large`, or `Fail`), recommended text color, as well as complementary, analogous, triadic, and monochromatic gradient palettes. +- Press `Enter` on any format row to copy it, `⌘/Ctrl+Enter` to save to your palette, or `⌘/Ctrl+K` to open the action panel (such as pasting into the active application). In the palette view, press `Enter` to copy HEX or `⌘/Ctrl+Enter` to inspect all formats; removing an item or clearing the palette is available in the action panel. The palette holds up to 100 colors, and removing a single color or clearing the palette requires confirmation. +- Screen color picking (eyedropper) is not provided. + +## Platforms & Requirements + +- Supported: Windows, macOS +- Built into the client; no separate installation required. + +## Network & Data + +- Works offline; data stays on your local device. diff --git a/extensions/color-picker/plugin.json b/extensions/color-picker/plugin.json index 6e4f5a84..fdffb5b8 100644 --- a/extensions/color-picker/plugin.json +++ b/extensions/color-picker/plugin.json @@ -1,7 +1,7 @@ { "id": "color-picker", "name": "取色与配色", - "version": "2.1.7", + "version": "2.1.8", "description": "支持 HEX / RGB / HSL / CMYK 色值实时互转、WCAG 无障碍对比度检测与常用色板收藏", "author": "ZTools Team", "entry": "dist/index.js", @@ -32,7 +32,14 @@ "rgb", "hsl", "oklch", - "调色板" + "调色板", + "取色", + "配色", + "颜色转换", + "色值", + "颜色代码", + "对比度", + "十六进制颜色" ], "features": [ { @@ -79,7 +86,11 @@ "cmyk", "wcag", "contrast", - "palette" + "palette", + "color picker", + "color converter", + "swatch", + "colour" ], "features": { "convert-color": { diff --git a/extensions/color-picker/src/index.ts b/extensions/color-picker/src/index.ts index e55ab5a8..ccab4e12 100644 --- a/extensions/color-picker/src/index.ts +++ b/extensions/color-picker/src/index.ts @@ -252,6 +252,15 @@ export function ColorPickerCommand() { ); } + const barActions = [ + ...(color && valid + ? [{ id: "save-palette", title: t("saveToPaletteAction"), style: "primary" as const, onAction: () => void save(color) }] + : []), + ...(palette.length > 0 + ? [{ id: "clear-palette", title: t("clearPaletteAction"), style: "secondary" as const, onAction: () => void clearAll() }] + : []) + ]; + return List( { navigationTitle: t("navTitle"), @@ -259,7 +268,18 @@ export function ColorPickerCommand() { isShowingDetail: valid || paletteMatches.length > 0, searchBarPlaceholder: t("searchPlaceholder"), searchText: input, - onSearchTextChange: (val: string) => setInput(val) + onSearchTextChange: (val: string) => setInput(val), + ...(barActions.length > 0 + ? { + filterBar: { + summaryText: + color && valid + ? `${displayHex(color)} · ${color.hasAlpha ? color.cssRgba : color.cssRgb} · WCAG ${color.wcag.whiteRating}/${color.wcag.blackRating}` + : t("sectionPaletteCount", { count: palette.length }), + actions: barActions + } + } + : {}) }, sections ); @@ -382,7 +402,22 @@ export function ContrastCheckCommand() { isShowingDetail: showDetail, searchBarPlaceholder: t("contrastSearchPlaceholder"), searchText: input, - onSearchTextChange: (val: string) => setInput(val) + onSearchTextChange: (val: string) => setInput(val), + ...(colors.length === 2 && !invalidPart && parts.length <= 2 + ? { + filterBar: { + summaryText: t("pairTitle", { fg: displayHex(colors[0]), bg: displayHex(colors[1]) }), + actions: [ + { + id: "swap-colors", + title: t("swapColorsAction"), + style: "secondary" as const, + onAction: () => setInput(`${displayHex(colors[1])} ${displayHex(colors[0])}`) + } + ] + } + } + : {}) }, sections ); diff --git a/extensions/context-menu/README.en.md b/extensions/context-menu/README.en.md new file mode 100644 index 00000000..79fbb0c8 --- /dev/null +++ b/extensions/context-menu/README.en.md @@ -0,0 +1,23 @@ +# Context Menu Manager + +List command entries in the Windows Explorer right-click menu for files, folders, and folder backgrounds (Registry `shell` subkeys), enable or disable them individually, and switch to the Windows 11 classic context menu. + +## Usage + +- Command: Context Menu Manager (main plugin command). +- Scans `*\shell` and `Directory\shell` under both Current User (`HKCU`) and Local Machine (`HKLM`), as well as `Directory\Background\shell` under Current User (`HKCU`). Lists up to 40 items per location (the status bar warns if the cap is reached). Shell extensions (`shellex`) are excluded. +- Filter by location on the right side of the search bar: All Files, Folders, Folder Background, or Disabled. +- `Enter` enables or disables the selected entry (by writing or deleting the `LegacyDisable` Registry value and reading it back to verify); `Ctrl+Enter` copies the Registry path; `Ctrl+Shift+C` copies the execution command (when present); `Ctrl+K` opens the action panel. +- Entries with an unrecognized status cannot be enabled or disabled; `Enter` copies the Registry path instead. +- Modifying system-wide (`HKLM`) entries requires running ZTools as Administrator; otherwise an error is reported. +- The "Windows 11 Context Menu Mode" entry toggles between the classic full menu and the Windows 11 default. It applies to Windows 11 only and requires restarting Explorer or signing out and back in to take effect; before toggling, its current mode is shown as "Unrecognized". +- When reading fails, the failure reason is displayed rather than showing an empty list. + +## Platforms & Requirements + +- Supported: Windows only +- Windows implementation is pending verification on physical hardware. + +## Network & Data + +- Works offline; data stays on your local device. diff --git a/extensions/context-menu/plugin.json b/extensions/context-menu/plugin.json index 1da65629..ee87c53c 100644 --- a/extensions/context-menu/plugin.json +++ b/extensions/context-menu/plugin.json @@ -1,8 +1,9 @@ { "id": "context-menu", "name": "右键菜单管理", - "description": "列出文件、文件夹和文件夹空白处右键菜单里的命令项(注册表 shell 子键),可逐项启用或禁用,并可切换 Windows 11 经典右键菜单;暂不包含外壳扩展(shellex)", - "version": "2.0.10", + "description": "统一管理 Windows 文件、文件夹与空白处右键菜单:覆盖静态 shell 动词、shellex 外壳扩展(还原真实 DLL 与厂商)及 Win11 打包应用菜单,支持无损可逆启停与经典菜单切换", + "version": "2.0.11", + "minAppVersion": "1.3.0.2", "author": "ZTools Team", "entry": "dist/index.js", "icon": "icon.svg", @@ -28,14 +29,18 @@ "i18n": { "en-US": { "name": "Context Menu Manager", - "description": "Inspect and toggle Windows Explorer context menu shell entries for files, folders, and directory backgrounds, plus switch to the Windows 11 classic menu (shell extensions excluded).", + "description": "Manage Windows Explorer context menus across static shell verbs, shellex handlers (with real DLL path and vendor info), and Win11 packaged app menus with lossless toggle and Win11 classic switch.", "keywords": [ "context menu", "right click", "windows 11", "explorer", "registry", - "shell" + "shell", + "shell menu", + "explorer menu", + "right-click menu", + "menu manager" ], "screenshots": [ { @@ -48,5 +53,15 @@ { "path": "screenshots/01.png" } + ], + "keywords": [ + "右键菜单", + "管理右键", + "清理右键", + "右键精简", + "鼠标右键", + "右键选项", + "context menu", + "shell menu" ] } diff --git a/extensions/context-menu/src/i18n.ts b/extensions/context-menu/src/i18n.ts index 6702fec9..8a0528b6 100644 --- a/extensions/context-menu/src/i18n.ts +++ b/extensions/context-menu/src/i18n.ts @@ -3,11 +3,14 @@ import { createTranslator } from '@ztools/declarative-ui' const rawT = createTranslator({ 'zh-CN': { 'forbidden.reason': '禁止删除或篡改系统根级 HKCR / SAM 安全注册表分支', - 'error.noHost': 'NO_HOST: 当前环境无法访问系统注册表,请在 Windows 版 ZTools 中使用', + 'error.noHost': 'NO_HOST: 当前环境无法访问右键菜单宿主服务,请在 Windows 版 ZTools 中使用', 'scope.file': '所有文件', 'scope.directory': '文件夹', 'scope.background': '文件夹空白处', 'scope.unknown': '位置未识别', + 'source.shell': '静态命令', + 'source.shellex': '外壳扩展', + 'source.packaged': 'Win11 打包', 'error.invalidMethod': 'INVALID_METHOD: 调用方法名不能为空', 'error.invalidParams': 'INVALID_PARAMS: 参数必须为非空对象', 'error.securityIntercepted': 'SECURITY_INTERCEPTED ({key}): {reason}', @@ -25,6 +28,8 @@ const rawT = createTranslator({ 'error.emptyEntryId': '右键菜单项 ID 不能为空', 'error.toggleEntryFailed': '修改右键菜单项 [{key}] 失败', 'error.stateMismatch': 'STATE_MISMATCH: 宿主返回的启用状态与请求不一致,请重新扫描后再试', + 'error.restartExplorerFailed': '重启资源管理器失败', + 'msg.explorerRestarted': '已请求重启资源管理器', 'msg.entryEnabled': '已启用右键菜单项:{name}', 'msg.entryDisabled': '已禁用右键菜单项:{name}', 'win11.unknown': '未识别', @@ -36,48 +41,60 @@ const rawT = createTranslator({ 'summary.counts': '共 {total} 项 · 已启用 {enabled} 项 · 已禁用 {disabled} 项', 'summary.unknownCount': ' · 状态未识别 {count} 项', 'summary.truncated': ' · {count} 个位置达到扫描上限,可能未列全', + 'summary.needElevation': ' · 修改系统项/外壳扩展需管理员或提权服务', 'section.scanError': '读取异常', 'item.rescanFailed': '重新扫描失败', 'item.scanFailed': '读取右键菜单失败', 'action.rescan': '重新扫描', 'action.switchToClassic': '切换为经典完整右键菜单', 'action.restoreWin11': '恢复 Windows 11 默认右键菜单', + 'action.restartExplorer': '重启资源管理器使更改生效', 'section.systemSettings': '系统设置', 'win11.title': 'Windows 11 右键菜单模式', 'win11.subtitle': '仅 Windows 11 有效;切换后需重启资源管理器或重新登录', 'status.unknown': '状态未识别', 'status.enabled': '已启用', 'status.disabled': '已禁用', + 'tag.admin': '需提权', 'action.disableEntry': '禁用该菜单项', 'action.enableEntry': '启用该菜单项', 'action.copyRegPath': '复制注册表路径', 'toast.copiedRegPath': '已复制注册表路径', - 'action.copyCommand': '复制执行命令', - 'toast.copiedCommand': '已复制执行命令', + 'action.copyCommand': '复制执行命令 / 模块路径', + 'toast.copiedCommand': '已复制执行命令 / 模块路径', + 'action.copyClsid': '复制 CLSID', + 'toast.copiedClsid': '已复制 CLSID', 'toast.rescanSuccess': '已重新扫描右键菜单', 'toast.rescanSummary': '已启用 {enabled} 项 · 已禁用 {disabled} 项', 'toast.toggleFailed': '修改右键菜单项失败', 'toast.switchWin11Failed': '切换 Windows 11 右键菜单模式失败', + 'toast.restartExplorerFailed': '重启资源管理器失败', 'toast.copyFailed': '复制失败', 'nav.title': '右键菜单管理', - 'search.placeholder': '搜索菜单名称、注册表路径或命令', - 'filter.tooltip': '按菜单位置筛选', - 'filter.all': '全部位置', - 'filter.file': '所有文件 (*\\shell)', - 'filter.directory': '文件夹 (Directory\\shell)', - 'filter.background': '文件夹空白处 (Directory\\Background\\shell)', + 'search.placeholder': '搜索菜单名称、厂商、DLL 路径、CLSID 或注册表路径', + 'filter.tooltip': '按来源或位置筛选', + 'filter.all': '全部条目', + 'filter.shell': '静态动词 (shell)', + 'filter.shellex': '外壳扩展 (shellex)', + 'filter.packaged': 'Win11 打包应用 (AppX)', + 'filter.file': '所有文件', + 'filter.directory': '文件夹', + 'filter.background': '文件夹空白处', 'filter.disabled': '已禁用', 'filterBar.scanning': '正在扫描...', - 'section.entries': '右键菜单命令项 ({count})', - 'section.entriesSubtitle': '只包含注册表 shell 下的命令项,不包含外壳扩展 (shellex)' + 'section.entries': '右键菜单条目 ({count})', + 'section.entriesSubtitle': '覆盖静态 shell 动词、shellex 外壳扩展与 Win11 打包菜单;通过 LegacyDisable 与 Shell Extensions\\Blocked 无损启停' }, 'en-US': { 'forbidden.reason': 'Deleting or modifying root HKCR / SAM security registry hives is forbidden', - 'error.noHost': 'NO_HOST: Cannot access system registry in this environment. Please use ZTools for Windows', + 'error.noHost': 'NO_HOST: Context menu host service is unavailable. Please use ZTools for Windows', 'scope.file': 'All Files', 'scope.directory': 'Folders', 'scope.background': 'Folder Background', 'scope.unknown': 'Unknown Location', + 'source.shell': 'Static Verb', + 'source.shellex': 'Shell Extension', + 'source.packaged': 'Win11 Packaged', 'error.invalidMethod': 'INVALID_METHOD: Method name cannot be empty', 'error.invalidParams': 'INVALID_PARAMS: Parameters must be a non-empty object', 'error.securityIntercepted': 'SECURITY_INTERCEPTED ({key}): {reason}', @@ -95,6 +112,8 @@ const rawT = createTranslator({ 'error.emptyEntryId': 'Context menu entry ID cannot be empty', 'error.toggleEntryFailed': 'Failed to update context menu entry [{key}]', 'error.stateMismatch': 'STATE_MISMATCH: Host returned a different state than requested. Please rescan and try again', + 'error.restartExplorerFailed': 'Failed to restart Windows Explorer', + 'msg.explorerRestarted': 'Windows Explorer restart requested', 'msg.entryEnabled': 'Enabled context menu entry: {name}', 'msg.entryDisabled': 'Disabled context menu entry: {name}', 'win11.unknown': 'Unknown', @@ -106,40 +125,49 @@ const rawT = createTranslator({ 'summary.counts': '{total} total · {enabled} enabled · {disabled} disabled', 'summary.unknownCount': ' · {count} unknown status', 'summary.truncated': ' · {count} [[count:location|locations]] hit scan limit, may be incomplete', + 'summary.needElevation': ' · System items/extensions require Admin or privileged service', 'section.scanError': 'Scan Error', 'item.rescanFailed': 'Rescan Failed', 'item.scanFailed': 'Failed to Read Context Menu', 'action.rescan': 'Rescan', 'action.switchToClassic': 'Switch to Classic Full Context Menu', 'action.restoreWin11': 'Restore Windows 11 Default Context Menu', + 'action.restartExplorer': 'Restart Explorer to Apply Changes', 'section.systemSettings': 'System Settings', 'win11.title': 'Windows 11 Context Menu Mode', 'win11.subtitle': 'Windows 11 only; restart Explorer or sign out after switching', 'status.unknown': 'Unknown Status', 'status.enabled': 'Enabled', 'status.disabled': 'Disabled', + 'tag.admin': 'Elevated', 'action.disableEntry': 'Disable Entry', 'action.enableEntry': 'Enable Entry', 'action.copyRegPath': 'Copy Registry Path', 'toast.copiedRegPath': 'Registry path copied', - 'action.copyCommand': 'Copy Command', - 'toast.copiedCommand': 'Command copied', + 'action.copyCommand': 'Copy Command / Module Path', + 'toast.copiedCommand': 'Command / module path copied', + 'action.copyClsid': 'Copy CLSID', + 'toast.copiedClsid': 'CLSID copied', 'toast.rescanSuccess': 'Context menu rescanned', 'toast.rescanSummary': '{enabled} enabled · {disabled} disabled', 'toast.toggleFailed': 'Failed to update context menu entry', 'toast.switchWin11Failed': 'Failed to switch Windows 11 context menu mode', + 'toast.restartExplorerFailed': 'Failed to restart Explorer', 'toast.copyFailed': 'Copy failed', 'nav.title': 'Context Menu Manager', - 'search.placeholder': 'Search menu name, registry path, or command', - 'filter.tooltip': 'Filter by menu location', - 'filter.all': 'All Locations', - 'filter.file': 'All Files (*\\shell)', - 'filter.directory': 'Folders (Directory\\shell)', - 'filter.background': 'Folder Background (Directory\\Background\\shell)', + 'search.placeholder': 'Search menu name, vendor, DLL path, CLSID, or registry path', + 'filter.tooltip': 'Filter by source or scope', + 'filter.all': 'All Entries', + 'filter.shell': 'Static Verbs (shell)', + 'filter.shellex': 'Shell Extensions (shellex)', + 'filter.packaged': 'Win11 Packaged Apps (AppX)', + 'filter.file': 'All Files', + 'filter.directory': 'Folders', + 'filter.background': 'Folder Background', 'filter.disabled': 'Disabled', 'filterBar.scanning': 'Scanning...', - 'section.entries': 'Context Menu Commands ({count})', - 'section.entriesSubtitle': 'Includes only registry shell command items, excluding shell extensions (shellex)' + 'section.entries': 'Context Menu Entries ({count})', + 'section.entriesSubtitle': 'Covers static shell verbs, shellex handlers, and Win11 packaged menus via lossless LegacyDisable & Shell Extensions\\Blocked' } }) export const t: typeof rawT = (key, params) => { diff --git a/extensions/context-menu/src/index.ts b/extensions/context-menu/src/index.ts index 47685fd5..eb51c55c 100644 --- a/extensions/context-menu/src/index.ts +++ b/extensions/context-menu/src/index.ts @@ -18,6 +18,7 @@ import { fetchContextMenuEntries, toggleContextMenuEntry, switchWin11ClassicMenu, + restartWindowsExplorer, filterContextMenuEntries, buildSummaryText, win11ModeLabel @@ -50,15 +51,19 @@ function scanErrorSection(scanError: string, hasEntries: boolean, onRescan: () = }) } -/** Win11 菜单模式行:状态未识别时两个方向都提供,已知时只提供切换到另一种 */ -function win11Section(mode: boolean | null, onSwitch: (useClassic: boolean) => Promise) { +function win11Section( + mode: boolean | null, + onSwitch: (useClassic: boolean) => Promise, + onRestartExplorer: () => Promise +) { const actions = [ mode !== true ? Action({ title: t('action.switchToClassic'), icon: Icon.List, onAction: () => onSwitch(true) }) : null, mode !== false ? Action({ title: t('action.restoreWin11'), icon: Icon.ArrowClockwise, onAction: () => onSwitch(false) }) - : null + : null, + Action({ title: t('action.restartExplorer'), icon: Icon.ArrowClockwise, onAction: onRestartExplorer }) ].filter(Boolean) return List.Section({ title: t('section.systemSettings'), @@ -75,19 +80,32 @@ function win11Section(mode: boolean | null, onSwitch: (useClassic: boolean) => P }) } +function buildEntrySubtitle(item: ContextMenuEntry): string { + const parts: string[] = [] + if (item.publisher) parts.push(item.publisher) + if (item.dllPath) parts.push(item.dllPath) + else if (item.command) parts.push(item.command) + if (parts.length === 0) return item.registryKey + if (item.sourceKind === 'shell') return `${item.registryKey} · ${parts.join(' · ')}` + return parts.join(' · ') +} + function entryItem( item: ContextMenuEntry, onToggle: (item: ContextMenuEntry) => Promise, onCopy: (text: string, successTitle: string) => Promise ) { - const canToggle = item.enabled !== null && Boolean(item.registryKey) + const canToggle = item.canToggle && item.enabled !== null + const moduleOrCommand = item.dllPath || item.command return List.Item({ id: item.id, title: item.title, - subtitle: item.command ? `${item.registryKey} · ${item.command}` : item.registryKey, + subtitle: buildEntrySubtitle(item), icon: item.enabled === null ? Icon.QuestionMark : item.enabled ? Icon.Checkmark : Icon.XMarkCircle, accessories: [ + { tag: { value: item.sourceLabel } }, { tag: { value: item.scopeLabel } }, + ...(item.requiresAdmin ? [{ tag: { value: t('tag.admin') } }] : []), { text: item.enabled === null ? t('status.unknown') : item.enabled ? t('status.enabled') : t('status.disabled') } ], actions: ActionPanel({ @@ -107,12 +125,19 @@ function entryItem( onAction: () => onCopy(item.registryKey, t('toast.copiedRegPath')) }) : null, - item.command + moduleOrCommand ? Action({ title: t('action.copyCommand'), icon: Icon.Code, shortcut: { modifiers: ['cmd', 'shift'], key: 'c' }, - onAction: () => onCopy(item.command, t('toast.copiedCommand')) + onAction: () => onCopy(moduleOrCommand, t('toast.copiedCommand')) + }) + : null, + item.clsid + ? Action({ + title: t('action.copyClsid'), + icon: Icon.Clipboard, + onAction: () => onCopy(item.clsid!, t('toast.copiedClsid')) }) : null ].filter(Boolean) @@ -127,8 +152,9 @@ export function ContextMenuCommand() { const [entries, setEntries] = useState([]) const [scanError, setScanError] = useState('') const [truncatedLocations, setTruncatedLocations] = useState([]) - // 宿主扫描不返回 Win11 经典菜单状态:未成功切换过之前一律显示未识别,不假设任何一种模式 const [win11Classic, setWin11Classic] = useState(null) + const [isAdmin, setIsAdmin] = useState(false) + const [privilegedServiceReady, setPrivilegedServiceReady] = useState(false) const [isLoading, setIsLoading] = useState(true) const generation = useRef(0) const pendingIds = useRef(new Set()) @@ -140,7 +166,6 @@ export function ContextMenuCommand() { const snap = await fetchContextMenuEntries() if (request !== generation.current) return if (!snap.ok) { - // 扫描失败不能当成没有菜单项:保留上次结果并显示错误 setScanError(resolveErrorMessage(snap, t('item.scanFailed'))) showToast({ style: Toast.Style.Failure, title: t('item.scanFailed'), message: snap.error }) return @@ -148,6 +173,8 @@ export function ContextMenuCommand() { setScanError('') setEntries(snap.entries) setTruncatedLocations(snap.truncatedLocations) + setIsAdmin(snap.isAdmin) + setPrivilegedServiceReady(snap.privilegedServiceReady) if (snap.win11ClassicEnabled !== null) setWin11Classic(snap.win11ClassicEnabled) if (showNotice) { showToast({ @@ -170,7 +197,7 @@ export function ContextMenuCommand() { }, []) async function handleToggleEntry(item: ContextMenuEntry) { - if (item.enabled === null || !item.registryKey || pendingIds.current.has(item.id)) return + if (!item.canToggle || item.enabled === null || pendingIds.current.has(item.id)) return pendingIds.current.add(item.id) try { const res = await toggleContextMenuEntry(item.id, !item.enabled, undefined, item.registryKey, item.title) @@ -201,6 +228,19 @@ export function ContextMenuCommand() { } } + async function handleRestartExplorer() { + try { + const res = await restartWindowsExplorer() + if (res.ok) { + showToast({ style: Toast.Style.Success, title: res.message }) + } else { + showToast({ style: Toast.Style.Failure, title: t('toast.restartExplorerFailed'), message: res.message }) + } + } catch (err) { + showToast({ style: Toast.Style.Failure, title: t('toast.restartExplorerFailed'), message: errorText(err) }) + } + } + async function copyText(text: string, successTitle: string) { try { await Clipboard.copy(text) @@ -226,6 +266,9 @@ export function ContextMenuCommand() { onChange: (val: string) => setFilterMode(val as ContextMenuFilterMode), children: [ List.Dropdown.Item({ title: t('filter.all'), value: 'all' }), + List.Dropdown.Item({ title: t('filter.shell'), value: 'shell' }), + List.Dropdown.Item({ title: t('filter.shellex'), value: 'shellex' }), + List.Dropdown.Item({ title: t('filter.packaged'), value: 'packaged' }), List.Dropdown.Item({ title: t('filter.file'), value: 'file' }), List.Dropdown.Item({ title: t('filter.directory'), value: 'directory' }), List.Dropdown.Item({ title: t('filter.background'), value: 'background' }), @@ -233,7 +276,14 @@ export function ContextMenuCommand() { ] }), filterBar: { - summaryText: buildSummaryText({ entries, scanError, isLoading, truncatedLocations }), + summaryText: buildSummaryText({ + entries, + scanError, + isLoading, + truncatedLocations, + isAdmin, + privilegedServiceReady + }), actions: [ { id: 'rescan-reg', @@ -247,7 +297,7 @@ export function ContextMenuCommand() { }, children: [ scanError ? scanErrorSection(scanError, entries.length > 0, () => refreshEntries(true)) : null, - showWin11Row ? win11Section(win11Classic, handleSwitchWin11) : null, + showWin11Row ? win11Section(win11Classic, handleSwitchWin11, handleRestartExplorer) : null, List.Section({ title: t('section.entries', { count: filtered.length }), subtitle: t('section.entriesSubtitle'), diff --git a/extensions/context-menu/src/logic.ts b/extensions/context-menu/src/logic.ts index 3a3d6247..fe5b4b4e 100644 --- a/extensions/context-menu/src/logic.ts +++ b/extensions/context-menu/src/logic.ts @@ -1,43 +1,43 @@ /** - * 右键菜单管理逻辑:读取宿主扫描到的右键菜单命令项(注册表 shell 子键),启用 / 禁用单项,切换 Windows 11 经典右键菜单。 - * - * 约定: - * - 读取、写入都只经宿主完成;宿主不可用、调用失败或返回格式无法识别时如实返回失败,不用示例数据或默认状态顶替。 - * - 宿主没有返回的信息(启用状态、位置)标为未识别,不填默认值。 - * - 宿主目前只扫描 shell 子键,不扫描外壳扩展(shellex\ContextMenuHandlers),界面需如实说明。 + * 右键菜单管理逻辑:通过专用宿主 IPC `context_menu` 统一枚举与管理三类菜单来源 + * (静态 shell 动词、shellex 外壳扩展与 Win11 打包应用菜单),彻底剥离旧 DLL 调用。 */ -import { - invokePluginService, - isRealElectronHost, - invokeDllPluginCapability, - type NativeInvocationResult as HostCallResult -} from './native-ipc.js' +import { callHostTransport, isRealElectronHost } from './native-ipc.js' import { t } from './i18n.js' import { resolveErrorMessage } from './error-i18n.js' -export interface NativeInvocationResult { - ok: boolean - pluginName: string - method: string - data?: unknown - error?: string - fromFallback?: boolean -} - export type ContextMenuScope = 'file' | 'directory' | 'background' -export type ContextMenuFilterMode = 'all' | 'file' | 'directory' | 'background' | 'disabled' +export type ContextMenuSourceKind = 'shell' | 'shellex' | 'packaged' +export type ContextMenuFilterMode = + | 'all' + | 'shell' + | 'shellex' + | 'packaged' + | 'file' + | 'directory' + | 'background' + | 'disabled' export interface ContextMenuEntry { id: string title: string + sourceKind: ContextMenuSourceKind + sourceLabel: string /** null:宿主没有给出、也无法从注册表路径判断菜单所在位置 */ scope: ContextMenuScope | null scopeLabel: string registryKey: string command: string + clsid: string | null + dllPath: string | null + publisher: string | null + description: string | null + packageFamilyName: string | null + requiresAdmin: boolean /** null:宿主没有返回启用状态,不能切换 */ enabled: boolean | null + canToggle: boolean } export interface ContextMenuSnapshot { @@ -50,19 +50,19 @@ export interface ContextMenuSnapshot { enabledCount: number disabledCount: number unknownCount: number - /** 扫描条数达到宿主单个位置上限的注册表位置,这些位置可能没有列全 */ truncatedLocations: string[] + isAdmin: boolean + privilegedServiceReady: boolean } -export const DLL_PLUGIN_NAME = 'ContextMenuPlugin' +export const CONTEXT_MENU_IPC_METHOD = 'context_menu' export const FORBIDDEN_TARGET_PATTERN = new RegExp('^(?:HKLM\\\\SAM|HKLM\\\\SECURITY|DELETE_ROOT_CLASSES)$', 'i') +export const HOST_SCAN_LIMIT_PER_LOCATION = 40 + export function getForbiddenReason(): string { return t('forbidden.reason') } -/** 宿主扫描时每个注册表位置最多返回的条数;达到该数量说明这个位置可能还有未列出的项 */ -export const HOST_SCAN_LIMIT_PER_LOCATION = 40 - export function getNoHostError(): string { return t('error.noHost') } @@ -90,6 +90,12 @@ export function getScopeLabel(scope: ContextMenuScope | null): string { return t('scope.unknown') } +export function getSourceLabel(sourceKind: ContextMenuSourceKind): string { + if (sourceKind === 'shellex') return t('source.shellex') + if (sourceKind === 'packaged') return t('source.packaged') + return t('source.shell') +} + function hasHost(hostOverride?: unknown): boolean { return Boolean(hostOverride) || isRealElectronHost(hostOverride) } @@ -102,49 +108,33 @@ function nonEmptyString(value: unknown): string { return typeof value === 'string' ? value.trim() : '' } -/** 宿主在结果里显式标明失败时取出失败原因,否则返回空串 */ -function explicitFailure(data: unknown, fallback: string): string { - const rec = asRecord(data) - if (!rec) return '' - if (rec.ok === false || rec.success === false) { - return resolveErrorMessage(rec, fallback) - } - return '' +function nullableString(value: unknown): string | null { + const s = nonEmptyString(value) + return s ? s : null } -export function validateInvocationPayload(method: string, params: unknown): { valid: boolean; error?: string } { - if (typeof method !== 'string' || !method.trim()) { - return { valid: false, error: t('error.invalidMethod') } - } - if (params === null || params === undefined || typeof params !== 'object' || Array.isArray(params)) { - return { valid: false, error: t('error.invalidParams') } - } - for (const [k, v] of Object.entries(params as Record)) { - if (typeof v === 'string' && FORBIDDEN_TARGET_PATTERN.test(v.trim())) { - return { valid: false, error: t('error.securityIntercepted', { key: k, reason: t('forbidden.reason') }) } - } +function contextMenuErrorCodeMap(): Record { + return { + PRIVILEGED_WRITE_UNAVAILABLE: t('summary.needElevation').replace(/^ · /, ''), + ADMIN_PRIVILEGE_REQUIRED: t('summary.needElevation').replace(/^ · /, ''), + ADMIN_REQUIRED: t('summary.needElevation').replace(/^ · /, '') } - return { valid: true } } -export async function invokeNativeCapability( - method: string, - params: Record, - hostBridge?: unknown -): Promise { - const check = validateInvocationPayload(method, params) - if (!check.valid) { - throw new Error(resolveErrorMessage(check, t('error.paramValidationFailed'))) +function explicitFailure(data: unknown, fallback: string): string { + const rec = asRecord(data) + if (!rec) return '' + if (rec.ok === false || rec.success === false) { + return resolveErrorMessage(rec, fallback, contextMenuErrorCodeMap()) } - return invokeDllPluginCapability(DLL_PLUGIN_NAME, method.trim(), params, hostBridge) + return '' } -/** 按注册表路径判断菜单位置:Software\Classes 下 *\shell、Directory\shell、Directory\Background\shell */ export function scopeFromRegistryKey(registryKey: string): ContextMenuScope | null { const key = registryKey.toLowerCase() - if (key.includes('\\directory\\background\\shell\\')) return 'background' - if (key.includes('\\directory\\shell\\')) return 'directory' - if (key.includes('\\*\\shell\\')) return 'file' + if (key.includes('\\directory\\background\\')) return 'background' + if (key.includes('\\directory\\')) return 'directory' + if (key.includes('\\*\\')) return 'file' return null } @@ -154,6 +144,15 @@ function resolveScope(raw: Record, registryKey: string): Contex return scopeFromRegistryKey(registryKey) } +function resolveSourceKind(raw: Record, registryKey: string): ContextMenuSourceKind { + const declared = nonEmptyString(raw.sourceKind).toLowerCase() + if (declared === 'shellex' || declared === 'packaged' || declared === 'shell') return declared + const lowerKey = registryKey.toLowerCase() + if (lowerKey.includes('\\shellex\\')) return 'shellex' + if (lowerKey.startsWith('appxpackage\\')) return 'packaged' + return 'shell' +} + function lastKeySegment(registryKey: string): string { const parts = registryKey.split('\\').filter(Boolean) return parts.length > 0 ? parts[parts.length - 1]! : '' @@ -162,6 +161,7 @@ function lastKeySegment(registryKey: string): string { export function mapRawContextMenuEntry(raw: unknown, i: number): ContextMenuEntry { const rec = asRecord(raw) ?? {} const registryKey = nonEmptyString(rec.registryKey) || nonEmptyString(rec.regPath) || nonEmptyString(rec.keyPath) + const sourceKind = resolveSourceKind(rec, registryKey) const scope = resolveScope(rec, registryKey) const title = nonEmptyString(rec.title) || @@ -169,21 +169,36 @@ export function mapRawContextMenuEntry(raw: unknown, i: number): ContextMenuEntr nonEmptyString(rec.keyName) || lastKeySegment(registryKey) || t('entry.unknownName') + const enabled = typeof rec.enabled === 'boolean' ? rec.enabled : null + const clsid = nullableString(rec.clsid) + const canToggle = + typeof rec.canToggle === 'boolean' + ? rec.canToggle && enabled !== null + : enabled !== null && (sourceKind === 'shell' ? Boolean(registryKey) : Boolean(clsid)) return { id: nonEmptyString(rec.id) || registryKey || `ctx-entry-${i}`, title, + sourceKind, + sourceLabel: getSourceLabel(sourceKind), scope, scopeLabel: getScopeLabel(scope), registryKey, command: nonEmptyString(rec.command), - enabled: typeof rec.enabled === 'boolean' ? rec.enabled : null + clsid, + dllPath: nullableString(rec.dllPath), + publisher: nullableString(rec.publisher), + description: nullableString(rec.description), + packageFamilyName: nullableString(rec.packageFamilyName), + requiresAdmin: typeof rec.requiresAdmin === 'boolean' ? rec.requiresAdmin : sourceKind !== 'shell' || registryKey.toUpperCase().startsWith('HKEY_LOCAL_MACHINE\\'), + enabled, + canToggle } } -/** 找出条数达到宿主扫描上限的注册表位置(菜单项的上级键,如 HKEY_CURRENT_USER\Software\Classes\*\shell) */ export function findTruncatedLocations(entries: ContextMenuEntry[], limit = HOST_SCAN_LIMIT_PER_LOCATION): string[] { const counts = new Map() for (const e of entries) { + if (e.sourceKind !== 'shell') continue const idx = e.registryKey.lastIndexOf('\\') if (idx <= 0) continue const parent = e.registryKey.slice(0, idx) @@ -204,20 +219,18 @@ function failedSnapshot(error: string): ContextMenuSnapshot { enabledCount: 0, disabledCount: 0, unknownCount: 0, - truncatedLocations: [] + truncatedLocations: [], + isAdmin: false, + privilegedServiceReady: false } } -/** - * 读取右键菜单项。宿主扫描失败(如 SCAN_FAILED / SCAN_TIMEOUT)、不可用或返回格式无法识别时返回 ok: false 与原因, - * 不能当成“没有右键菜单项”。 - */ export async function fetchContextMenuEntries(hostOverride?: unknown): Promise { if (!hasHost(hostOverride)) return failedSnapshot(t('error.noHost')) - let res: HostCallResult + let res: { ok: boolean; data?: unknown; error?: string; errorCode?: string; errorDetails?: Record } try { - res = await invokePluginService(DLL_PLUGIN_NAME, 'scanEntries', {}, hostOverride) + res = await callHostTransport(CONTEXT_MENU_IPC_METHOD, { action: 'scan' }, hostOverride) } catch (err) { return failedSnapshot(`SCAN_FAILED: ${err instanceof Error ? err.message : String(err)}`) } @@ -233,10 +246,10 @@ export async function fetchContextMenuEntries(hostOverride?: unknown): Promise + let svcRes: { ok: boolean; data?: unknown; error?: string; errorCode?: string; errorDetails?: Record } try { - svcRes = await invokePluginService( - DLL_PLUGIN_NAME, - 'switchWin11Classic', - { classic: useClassic, enabled: useClassic }, + svcRes = await callHostTransport( + CONTEXT_MENU_IPC_METHOD, + { action: 'switch-win11-classic', classic: useClassic }, hostOverride ) } catch (err) { @@ -288,11 +298,7 @@ export async function switchWin11ClassicMenu( const returnedMode = asRecord(svcRes.data)?.classic if (typeof returnedMode === 'boolean' && returnedMode !== useClassic) { - return { - ok: false, - classicMode: null, - message: t('error.modeMismatch') - } + return { ok: false, classicMode: null, message: t('error.modeMismatch') } } return { @@ -302,10 +308,29 @@ export async function switchWin11ClassicMenu( } } -/** - * 启用或禁用一个右键菜单项(宿主通过 LegacyDisable 值实现并读回确认)。 - * 宿主拒绝(如 ADMIN_REQUIRED、ITEM_NOT_FOUND、VERIFY_FAILED)或不可用时如实返回失败,enabled 保持原状态。 - */ +export async function restartWindowsExplorer( + hostOverride?: unknown +): Promise<{ ok: boolean; message: string }> { + if (!hasHost(hostOverride)) { + return { ok: false, message: t('error.noHost') } + } + try { + const res = await callHostTransport( + CONTEXT_MENU_IPC_METHOD, + { action: 'restart-explorer' }, + hostOverride + ) + if (!res.ok) { + return { ok: false, message: resolveErrorMessage(res, t('error.restartExplorerFailed')) } + } + const failure = explicitFailure(res.data, t('error.restartExplorerFailed')) + if (failure) return { ok: false, message: failure } + return { ok: true, message: t('msg.explorerRestarted') } + } catch (err) { + return { ok: false, message: err instanceof Error ? err.message : String(err) } + } +} + export async function toggleContextMenuEntry( id: string, enabled: boolean, @@ -330,19 +355,18 @@ export async function toggleContextMenuEntry( } const fallbackError = t('error.toggleEntryFailed', { key: resolvedRegKey }) - let svcRes: HostCallResult + let svcRes: { ok: boolean; data?: unknown; error?: string; errorCode?: string; errorDetails?: Record } try { - svcRes = await invokePluginService( - DLL_PLUGIN_NAME, - 'toggleEntry', - { id: normalizedId, regPath: resolvedRegKey, registryKey: resolvedRegKey, enabled }, + svcRes = await callHostTransport( + CONTEXT_MENU_IPC_METHOD, + { action: 'toggle', id: normalizedId, enabled }, hostOverride ) } catch (err) { return { ok: false, enabled: previous, message: err instanceof Error ? err.message : String(err) } } if (!svcRes.ok) { - return { ok: false, enabled: previous, message: resolveErrorMessage(svcRes, fallbackError) } + return { ok: false, enabled: previous, message: resolveErrorMessage(svcRes, fallbackError, contextMenuErrorCodeMap()) } } const failure = explicitFailure(svcRes.data, fallbackError) if (failure) return { ok: false, enabled: previous, message: failure } @@ -364,24 +388,29 @@ export function win11ModeLabel(mode: boolean | null): string { return mode === null ? t('win11.unknown') : mode ? t('win11.classic') : t('win11.default') } -/** 状态条文字:读取失败时说明不能判断,重新扫描失败时说明显示的是旧结果,不把失败写成“共 0 项” */ export function buildSummaryText(input: { entries: ContextMenuEntry[] scanError: string isLoading: boolean truncatedLocations: string[] + isAdmin?: boolean + privilegedServiceReady?: boolean }): string { - const { entries, scanError, isLoading, truncatedLocations } = input + const { entries, scanError, isLoading, truncatedLocations, isAdmin, privilegedServiceReady } = input if (scanError && entries.length === 0) return t('summary.initialScanFailed', { error: scanError }) if (scanError) return t('summary.rescanFailed', { error: scanError }) if (isLoading && entries.length === 0) return t('summary.scanning') const enabledCount = entries.filter((e) => e.enabled === true).length const disabledCount = entries.filter((e) => e.enabled === false).length const unknownCount = entries.length - enabledCount - disabledCount + const elevationHint = isAdmin === false && privilegedServiceReady === false && entries.some((e) => e.requiresAdmin) + ? t('summary.needElevation') + : '' return ( t('summary.counts', { total: entries.length, enabled: enabledCount, disabled: disabledCount }) + (unknownCount > 0 ? t('summary.unknownCount', { count: unknownCount }) : '') + - (truncatedLocations.length > 0 ? t('summary.truncated', { count: truncatedLocations.length }) : '') + (truncatedLocations.length > 0 ? t('summary.truncated', { count: truncatedLocations.length }) : '') + + elevationHint ) } @@ -392,7 +421,9 @@ export function filterContextMenuEntries( ): ContextMenuEntry[] { if (!Array.isArray(entries)) return [] let list = entries - if (filterMode === 'file' || filterMode === 'directory' || filterMode === 'background') { + if (filterMode === 'shell' || filterMode === 'shellex' || filterMode === 'packaged') { + list = list.filter((e) => e.sourceKind === filterMode) + } else if (filterMode === 'file' || filterMode === 'directory' || filterMode === 'background') { list = list.filter((e) => e.scope === filterMode) } else if (filterMode === 'disabled') { list = list.filter((e) => e.enabled === false) @@ -405,6 +436,10 @@ export function filterContextMenuEntries( e.title.toLowerCase().includes(q) || e.registryKey.toLowerCase().includes(q) || e.command.toLowerCase().includes(q) || - e.scopeLabel.toLowerCase().includes(q) + e.scopeLabel.toLowerCase().includes(q) || + e.sourceLabel.toLowerCase().includes(q) || + (e.publisher?.toLowerCase().includes(q) ?? false) || + (e.dllPath?.toLowerCase().includes(q) ?? false) || + (e.clsid?.toLowerCase().includes(q) ?? false) ) } diff --git a/extensions/context-menu/src/native-ipc.ts b/extensions/context-menu/src/native-ipc.ts index 51576b99..13643277 100644 --- a/extensions/context-menu/src/native-ipc.ts +++ b/extensions/context-menu/src/native-ipc.ts @@ -174,11 +174,13 @@ function normalizeMethodResult(method: string, payload: DynamicBridge): DynamicB if (method === 'system_get_battery_status') { // 宿主约定 percent 超出 0-100(如 255)表示无电池或电量未知,不能改写成 100% + // 若宿主明确给出 hasBattery 布尔值,必须原样保留,仅在缺失时按合法电量推算 const rawPct = payload.percent - const hasBattery = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const validPct = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const hasBattery = typeof payload.hasBattery === 'boolean' ? payload.hasBattery : validPct return { ...payload, - percent: hasBattery ? rawPct : null, + percent: validPct ? rawPct : null, hasBattery } } @@ -489,6 +491,8 @@ export interface RealDirectoryScanResult extends Iterable approximate?: boolean /** 宿主实际遍历的条目数 */ visitedEntries?: number + /** 目录本身不存在(ENOENT) */ + missing?: boolean /** 读取失败的真实原因;已有文件仍可使用,但不能当作完整结果。 */ error?: string } @@ -497,6 +501,7 @@ interface ScanResultMeta { truncated?: boolean approximate?: boolean visitedEntries?: number + missing?: boolean } export interface ScanDirectoryTreeOptions { @@ -504,6 +509,10 @@ export interface ScanDirectoryTreeOptions { maxFiles?: number collectTopN?: number filterExt?: RegExp + /** 为 true 时,目录本身不存在(ENOENT)按空目录处理,不返回 error(权限拒绝/读取失败仍照常报错) */ + ignoreMissing?: boolean + /** Top-N 保留与排序方式:默认按体积降序,下载/录屏等时效场景可传 mtime-desc */ + sortBy?: 'size-desc' | 'mtime-desc' hostOverride?: DynamicBridge } @@ -519,8 +528,9 @@ function normalizeIndexedFileEntry(f: DynamicBridge): RealIndexedFileEntry { const sz = Number(f?.size ?? f?.sizeBytes ?? 0) const isDir = Boolean(f?.is_dir || f?.isDir || f?.isDirectory) const rawMtime = Number(f?.mtime ?? f?.mtimeMs ?? 0) - const mtimeMs = rawMtime > 1e11 ? rawMtime : rawMtime > 0 ? rawMtime * 1000 : Date.now() - const mtimeSec = rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime + const validMtime = Number.isFinite(rawMtime) && rawMtime > 0 + const mtimeMs = validMtime ? (rawMtime > 1e11 ? rawMtime : rawMtime * 1000) : 0 + const mtimeSec = validMtime ? (rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime) : 0 if (p && sz >= 0) realFileSizeCache.set(p, sz) return { name, @@ -551,6 +561,7 @@ function makeScanResult( subdirs, ...(meta.truncated ? { truncated: true } : {}), ...(meta.approximate ? { approximate: true } : {}), + ...(meta.missing ? { missing: true } : {}), ...(typeof meta.visitedEntries === 'number' ? { visitedEntries: meta.visitedEntries } : {}), [Symbol.iterator]() { return files[Symbol.iterator]() @@ -609,13 +620,40 @@ export async function scanRealDirectoryTree( return result.error ? { ...result.scan, error: result.error } : result.scan } +/** 仅当正则明确声明了扩展名(含 `\.`)时提取后缀列表,避免把 `thumbcache|iconcache` 等文件名关键词误拆成假扩展名 */ +function extractExtensionTokensFromFilter(filterExt: RegExp): string[] { + const src = filterExt.source + if (!src.includes('\\.')) return [] + const afterDot = src.slice(src.indexOf('\\.') + 2) + const rawTokens = afterDot.match(/[a-z0-9]{1,8}/gi) || [] + const seen = new Set() + const out: string[] = [] + for (const token of rawTokens) { + const lower = token.toLowerCase() + if (!lower || seen.has(lower)) continue + seen.add(lower) + out.push(lower) + } + return out +} + +function isMissingDirectoryError(res: { error?: string; errorCode?: string; errorDetails?: Record }): boolean { + if (res.errorDetails?.reason === 'ENOENT' || res.errorCode === 'ENOENT') return true + const msg = String(res.error || '') + return /Directory does not exist|ENOENT/i.test(msg) +} + /** 一次界面扫描的错误汇总;多个目录并行扫描时保留可读目录的结果。 */ export function createDirectoryScanner(hostOverride?: DynamicBridge) { const failures = new Map() return { async scan(dir: string, options: number | ScanDirectoryTreeOptions = 160) { const result = await scanRealDirectoryTree(dir, options, hostOverride) - const error = result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') + const ignoreMissing = typeof options === 'object' && options !== null && options.ignoreMissing === true + const error = + result.missing && ignoreMissing + ? '' + : result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') if (error) failures.set(dir, error) else failures.delete(dir) return result @@ -648,26 +686,38 @@ async function scanDirectoryTreeWithError( const safeLimit = Math.min(200, Math.max(1, Math.floor(rawLimit || 160))) const hostOverride = opts.hostOverride const filterExt = opts.filterExt + const ignoreMissing = opts.ignoreMissing === true const dirQuery = `dir:${targetDir}` try { let rawPayload: DynamicBridge = null + const searchParams: Record = { + query: dirQuery, + limit: safeLimit, + ...(opts.sortBy ? { sortBy: opts.sortBy } : {}) + } const res = await callHostTransport( 'system_search_files', - { query: dirQuery, limit: safeLimit }, + searchParams, hostOverride ) - if (res.ok && res.data) { + if (res.ok && res.data && res.data.degraded !== true) { rawPayload = res.data + } else if (!res.ok && ignoreMissing && isMissingDirectoryError(res)) { + const missingScan = makeScanResult([], 0, 0, [], { missing: true }) + return { scan: missingScan } } - if (!rawPayload && !hostOverride && typeof window !== 'undefined') { + if (!rawPayload && !hostOverride && res.errorCode === 'METHOD_NOT_AVAILABLE' && typeof window !== 'undefined') { const w = window as DynamicBridge if (typeof w.__ztoolsLauncher?.searchFiles === 'function') { const rawOuter = await w.__ztoolsLauncher.searchFiles(dirQuery, safeLimit) - rawPayload = + const candidate = rawOuter && typeof rawOuter === 'object' && 'data' in rawOuter && rawOuter.data ? rawOuter.data : rawOuter + if (candidate && candidate.degraded !== true && candidate.success !== false) { + rawPayload = candidate + } } } @@ -678,29 +728,32 @@ async function scanDirectoryTreeWithError( let files: RealIndexedFileEntry[] = rawPayload.files.map(normalizeIndexedFileEntry) if (filterExt instanceof RegExp) { files = files.filter(f => !f.isDir && (filterExt.test(f.name) || filterExt.test(f.ext))) - // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索目标扩展名 + // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索明确声明的目标扩展名 if (files.length === 0 && !hostOverride) { - const extTokens = (filterExt.source.match(/[a-z0-9]{2,5}/gi) || []) - .filter(t => !['thumbcache', 'iconcache'].includes(t.toLowerCase())) - .slice(0, 4) - // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 - const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() - const extraLists = await Promise.all( - extTokens.map(ext => searchRealIndexedFiles(`.${ext.toLowerCase()}`, 30, hostOverride)) - ) - const seen = new Set() - for (const list of extraLists) { - for (const item of list) { - if (!item.isDir && item.size > 0 && !seen.has(item.path)) { - if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { - seen.add(item.path) - files.push(item) + const extTokens = extractExtensionTokensFromFilter(filterExt) + if (extTokens.length > 0) { + // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 + const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() + const extraLists = await Promise.all( + extTokens.map(ext => searchRealIndexedFiles(`.${ext}`, 30, hostOverride)) + ) + const seen = new Set() + for (const list of extraLists) { + for (const item of list) { + if (!item.isDir && item.size > 0 && !seen.has(item.path)) { + if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { + seen.add(item.path) + files.push(item) + } } } } } } } + // 先基于过滤后的完整命中集合计算总文件数与总字节数,再按 collectTopN 裁剪样本列表 + const matchedCount = files.length + const matchedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) if (typeof opts.collectTopN === 'number' && opts.collectTopN > 0 && files.length > opts.collectTopN) { files = files.slice(0, opts.collectTopN) } @@ -714,11 +767,10 @@ async function scanDirectoryTreeWithError( ...(s.approximate === true ? { approximate: true } : {}) })) : [] - const computedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) const totalFilesCount = - filterExt instanceof RegExp ? files.length : Number(rawPayload.total_matches ?? files.length) + filterExt instanceof RegExp ? matchedCount : Number(rawPayload.total_matches ?? matchedCount) const totalBytesCount = - filterExt instanceof RegExp ? computedBytes : Number(rawPayload.total_bytes ?? computedBytes) + filterExt instanceof RegExp ? matchedBytes : Number(rawPayload.total_bytes ?? matchedBytes) const visited = Number(rawPayload.visited_entries) return { scan: makeScanResult(files, totalFilesCount, totalBytesCount, subdirs, { @@ -1817,8 +1869,6 @@ export async function writeRealClipboardText(text: string, hostOverride?: Dynami const payload = { text: String(text || '') } const res = await callHostTransport('clipboard_copy_text', payload, hostOverride) if (res.ok) return true - const fallbackRes = await callHostTransport('clipboard_write_text', payload, hostOverride) - if (fallbackRes.ok) return true try { if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) { await navigator.clipboard.writeText(String(text || '')) diff --git a/extensions/context-menu/tests/context-menu.host.test.mjs b/extensions/context-menu/tests/context-menu.host.test.mjs index e89175db..28cbadd1 100644 --- a/extensions/context-menu/tests/context-menu.host.test.mjs +++ b/extensions/context-menu/tests/context-menu.host.test.mjs @@ -1,9 +1,9 @@ -// 本插件的宿主集成测试(导入本插件的 dist/) -// 宿主替身按真实链路返回:内置处理器结果 → dllplugin_call 路由(无 data 时补一层 data)→ IPC 外层 { success, data } +// context-menu 宿主逻辑单元测试(基于新专用 context_menu IPC,零 DLL) import test from 'node:test' import assert from 'node:assert/strict' import { setRuntimeLocale } from '@ztools/declarative-ui' setRuntimeLocale('zh-CN') + const { fetchContextMenuEntries, toggleContextMenuEntry, @@ -15,313 +15,193 @@ const { HOST_SCAN_LIMIT_PER_LOCATION, SCOPE_LABELS, getScopeLabel, + getSourceLabel, getForbiddenReason, getNoHostError, getUnknownScopeLabel } = await import('../dist/logic.js') const HKCU_FILE = 'HKEY_CURRENT_USER\\Software\\Classes\\*\\shell' -const HKLM_DIR = 'HKEY_LOCAL_MACHINE\\Software\\Classes\\Directory\\shell' +const HKLM_DIR = 'HKEY_LOCAL_MACHINE\\SOFTWARE\\Classes\\Directory\\shell' const HKCU_BG = 'HKEY_CURRENT_USER\\Software\\Classes\\Directory\\Background\\shell' -/** 与 dllplugin_call 路由一致:处理器结果没有 data 字段时补 data: { ...结果 },再包一层 IPC 成功响应 */ -function routerResponse(hostResult) { - const isRecord = hostResult && typeof hostResult === 'object' && !Array.isArray(hostResult) - const data = isRecord && hostResult.data === undefined ? { ...hostResult, data: { ...hostResult } } : hostResult - return { messageId: 'm1', success: true, data } -} - -/** 与宿主扫描脚本输出一致的菜单项(没有 publisher 字段) */ -function hostEntry(parent, keyName, { name = keyName, command = '', enabled = true, scope } = {}) { - const keyPath = `${parent}\\${keyName}` - const inferred = parent.includes('Background') ? 'background' : parent.includes('Directory') ? 'directory' : 'file' - return { id: keyPath, name, keyName, scope: scope ?? inferred, scopeLabel: '', regPath: keyPath, keyPath, command, icon: '', enabled } -} - function createHost(handlers) { const calls = [] return { calls, - async dllplugin_call({ plugin, func, params }) { - calls.push({ plugin, func, params }) - const handler = handlers[func] - if (!handler) return routerResponse({ ok: false, success: false, error: `Unsupported ContextMenuPlugin function: ${func}` }) + async context_menu(params) { + calls.push(params) + const handler = handlers[params.action] + if (!handler) return { success: false, error: { code: 'INVALID_REQUEST', message: `Unsupported action: ${params.action}` } } return handler(params) } } } -test('扫描成功:按宿主真实字段映射,不编造发布者,Win11 经典菜单状态未返回时为未识别', async () => { +test('扫描成功:覆盖静态 shell、shellex(含真实 DLL 与厂商)及 Win11 打包菜单,且不调用 dllplugin_call', async () => { const host = createHost({ - scanEntries: () => { - const items = [ - hostEntry(HKCU_FILE, 'VSCode', { name: 'Open with Code', command: '"Code.exe" "%1"' }), - hostEntry(HKLM_DIR, 'git_shell', { name: 'Open Git Bash here', enabled: false }), - hostEntry(HKCU_BG, 'wt', { name: '在终端中打开' }) - ] - return routerResponse({ ok: true, success: true, items, entries: items }) - } + scan: () => ({ + success: true, + data: { + success: true, + isAdmin: false, + privilegedServiceReady: true, + win11ClassicEnabled: false, + entries: [ + { + id: 'id-shell', + sourceKind: 'shell', + title: 'Open with Code', + scope: 'file', + registryKey: `${HKCU_FILE}\\VSCode`, + command: '"Code.exe" "%1"', + clsid: null, + dllPath: null, + publisher: null, + requiresAdmin: false, + enabled: true, + canToggle: true + }, + { + id: 'id-shellex', + sourceKind: 'shellex', + title: '7-Zip Shell Extension', + scope: 'file', + registryKey: 'HKEY_LOCAL_MACHINE\\SOFTWARE\\Classes\\*\\shellex\\ContextMenuHandlers\\7-Zip', + command: 'C:\\Program Files\\7-Zip\\7-zip.dll', + clsid: '{23170F69-40C1-278A-1000-000100020000}', + dllPath: 'C:\\Program Files\\7-Zip\\7-zip.dll', + publisher: 'Igor Pavlov', + requiresAdmin: true, + enabled: false, + canToggle: true + }, + { + id: 'id-packaged', + sourceKind: 'packaged', + title: 'Windows Terminal (OpenTerminalHere)', + scope: 'directory', + registryKey: 'AppxPackage\\Microsoft.WindowsTerminal\\{9F156763-7844-4DC4-B2B1-901F640F5155}', + command: 'C:\\Program Files\\WindowsApps\\WT', + clsid: '{9F156763-7844-4DC4-B2B1-901F640F5155}', + dllPath: 'C:\\Program Files\\WindowsApps\\WT', + publisher: 'Microsoft Corporation', + requiresAdmin: true, + enabled: true, + canToggle: true + } + ] + } + }) }) const snap = await fetchContextMenuEntries(host) assert.equal(snap.ok, true) - assert.deepEqual(snap.entries.map((e) => [e.title, e.scope, e.scopeLabel, e.enabled]), [ - ['Open with Code', 'file', '所有文件', true], - ['Open Git Bash here', 'directory', '文件夹', false], - ['在终端中打开', 'background', '文件夹空白处', true] + assert.equal(snap.entries.length, 3) + assert.deepEqual(snap.entries.map((e) => [e.sourceKind, e.sourceLabel, e.publisher]), [ + ['shell', '静态命令', null], + ['shellex', '外壳扩展', 'Igor Pavlov'], + ['packaged', 'Win11 打包', 'Microsoft Corporation'] ]) - assert.equal(snap.entries[0].registryKey, `${HKCU_FILE}\\VSCode`) - assert.equal(snap.entries[0].command, '"Code.exe" "%1"') - assert.equal('publisher' in snap.entries[0], false) + assert.equal(snap.win11ClassicEnabled, false) assert.equal(snap.enabledCount, 2) assert.equal(snap.disabledCount, 1) - assert.equal(snap.unknownCount, 0) - assert.equal(snap.win11ClassicEnabled, null) - assert.deepEqual(snap.truncatedLocations, []) - assert.deepEqual(host.calls.map((c) => [c.plugin, c.func]), [['ContextMenuPlugin', 'scanEntries']]) + assert.equal(filterContextMenuEntries(snap.entries, '', 'shellex').length, 1) + assert.equal(filterContextMenuEntries(snap.entries, '', 'packaged').length, 1) + assert.equal(filterContextMenuEntries(snap.entries, 'igor', 'all').length, 1) + assert.deepEqual(host.calls, [{ action: 'scan' }]) }) -test('扫描失败:宿主返回 SCAN_FAILED / SCAN_TIMEOUT 时如实返回失败,不当成没有菜单项', async () => { - for (const code of ['SCAN_FAILED', 'SCAN_TIMEOUT']) { - const host = createHost({ - scanEntries: () => - routerResponse({ ok: false, success: false, errorCode: code, error: `${code}: 读取右键菜单失败:PowerShell 退出码 1` }) - }) - const snap = await fetchContextMenuEntries(host) - assert.equal(snap.ok, false, code) - assert.match(snap.error, new RegExp(code)) - assert.deepEqual(snap.entries, []) - assert.equal(snap.win11ClassicEnabled, null) - } -}) - -test('扫描失败:IPC 层失败、结果格式无法识别、调用抛错都返回失败', async () => { - const platformDenied = await fetchContextMenuEntries({ - async dllplugin_call() { - return { messageId: 'm1', success: false, error: { code: 'PLATFORM_NOT_SUPPORTED', message: '当前操作系统 (darwin) 不支持方法: dllplugin_call' } } - } - }) - assert.equal(platformDenied.ok, false) - assert.match(platformDenied.error, /不支持方法/) +test('扫描失败:宿主返回 SCAN_FAILED、平台不支持、畸形格式、调用抛错都如实返回失败', async () => { + const failed = await fetchContextMenuEntries(createHost({ + scan: () => ({ success: false, error: { code: 'SCAN_FAILED', message: 'SCAN_FAILED: PowerShell 退出码 1' } }) + })) + assert.equal(failed.ok, false) + assert.match(failed.error, /SCAN_FAILED/) - const malformed = await fetchContextMenuEntries(createHost({ scanEntries: () => routerResponse({ ok: true, success: true }) })) + const malformed = await fetchContextMenuEntries(createHost({ scan: () => ({ success: true, data: { success: true } }) })) assert.equal(malformed.ok, false) assert.match(malformed.error, /格式无法识别/) - const thrown = await fetchContextMenuEntries({ - async dllplugin_call() { - throw new Error('IPC 通道已关闭') - } - }) + const thrown = await fetchContextMenuEntries({ async context_menu() { throw new Error('IPC 通道已关闭') } }) assert.equal(thrown.ok, false) assert.match(thrown.error, /IPC 通道已关闭/) }) -test('宿主缺字段:启用状态标为未识别,位置按注册表路径判断,判断不了标未识别', async () => { - const host = createHost({ - scanEntries: () => { - const items = [ - { regPath: `${HKCU_FILE}\\NoState` }, - { regPath: 'HKEY_CURRENT_USER\\Software\\Classes\\Drive\\shell\\Odd', name: 'Drive 菜单', enabled: true }, - { name: '无路径项', enabled: false } - ] - return routerResponse({ ok: true, success: true, items, entries: items }) - } - }) - const snap = await fetchContextMenuEntries(host) - assert.equal(snap.ok, true) - const [noState, drive, noPath] = snap.entries - assert.equal(noState.title, 'NoState') - assert.equal(noState.enabled, null) - assert.equal(noState.scope, 'file') - assert.equal(drive.scope, null) - assert.equal(drive.scopeLabel, '位置未识别') - assert.equal(noPath.registryKey, '') - assert.equal(snap.unknownCount, 1) - assert.equal(snap.enabledCount, 1) - assert.equal(snap.disabledCount, 1) - // “已禁用”筛选不包含状态未识别的项 - assert.deepEqual(filterContextMenuEntries(snap.entries, '', 'disabled').map((e) => e.title), ['无路径项']) -}) - -test('扫描上限:某个位置达到宿主每个位置的条数上限时标为可能未列全', async () => { - const full = Array.from({ length: HOST_SCAN_LIMIT_PER_LOCATION }, (_, i) => hostEntry(HKCU_FILE, `item${i}`)) - const partial = Array.from({ length: HOST_SCAN_LIMIT_PER_LOCATION - 1 }, (_, i) => hostEntry(HKLM_DIR, `dir${i}`)) - const host = createHost({ - scanEntries: () => { - const items = [...full, ...partial] - return routerResponse({ ok: true, success: true, items, entries: items }) - } - }) - const snap = await fetchContextMenuEntries(host) - assert.deepEqual(snap.truncatedLocations, [HKCU_FILE]) - assert.deepEqual(findTruncatedLocations([]), []) -}) - -test('没有宿主:读取、启用禁用、切换 Win11 菜单都返回失败,不返回示例数据或假成功', async () => { +test('没有宿主:读取、启停、切换 Win11 均返回 NO_HOST,不造假', async () => { assert.equal(globalThis.window, undefined) const snap = await fetchContextMenuEntries() assert.equal(snap.ok, false) assert.match(snap.error, /NO_HOST/) - assert.deepEqual(snap.entries, []) - const toggle = await toggleContextMenuEntry(`${HKCU_FILE}\\VSCode`, false, undefined, `${HKCU_FILE}\\VSCode`) + const toggle = await toggleContextMenuEntry('id-1', false) assert.equal(toggle.ok, false) assert.equal(toggle.enabled, true) assert.match(toggle.message, /NO_HOST/) const classic = await switchWin11ClassicMenu(true) assert.equal(classic.ok, false) - assert.equal(classic.classicMode, null) assert.match(classic.message, /NO_HOST/) }) -test('启用 / 禁用:成功时按宿主确认返回;ADMIN_REQUIRED、ITEM_NOT_FOUND、VERIFY_FAILED 如实返回失败并保持原状态', async () => { - const failures = { - [`${HKLM_DIR}\\git_shell`]: { errorCode: 'ADMIN_REQUIRED', error: 'ADMIN_REQUIRED: 修改该右键菜单项需要管理员权限,请以管理员身份运行 ZTools 后重试' }, - [`${HKCU_FILE}\\Gone`]: { errorCode: 'ITEM_NOT_FOUND', error: 'ITEM_NOT_FOUND: 右键菜单项不存在,可能已被删除' }, - [`${HKCU_FILE}\\Sticky`]: { errorCode: 'VERIFY_FAILED', error: 'VERIFY_FAILED: 已执行修改,但读回的启用状态与预期不符' } - } +test('启停条目:走 context_menu toggle,ADMIN_PRIVILEGE_REQUIRED / VERIFY_FAILED 如实失败', async () => { const host = createHost({ - toggleEntry: (params) => { - const base = { regPath: params.regPath, keyPath: params.regPath, enabled: params.enabled } - const failure = failures[params.regPath] - if (failure) return routerResponse({ ok: false, success: false, ...base, ...failure }) - return routerResponse({ ok: true, success: true, ...base }) + toggle: ({ id, enabled }) => { + if (id === 'id-admin') { + return { success: false, error: { code: 'PERMISSION_DENIED', details: { hostCode: 'ADMIN_PRIVILEGE_REQUIRED' }, message: 'ADMIN_PRIVILEGE_REQUIRED' } } + } + return { success: true, data: { success: true, id, enabled } } } }) - const ok = await toggleContextMenuEntry(`${HKCU_FILE}\\VSCode`, false, host, `${HKCU_FILE}\\VSCode`, 'Open with Code') + const ok = await toggleContextMenuEntry('id-hkcu', false, host, `${HKCU_FILE}\\VSCode`, 'Open with Code') assert.equal(ok.ok, true) assert.equal(ok.enabled, false) assert.match(ok.message, /已禁用.*Open with Code/) - assert.deepEqual(host.calls[0].params, { - id: `${HKCU_FILE}\\VSCode`, - regPath: `${HKCU_FILE}\\VSCode`, - registryKey: `${HKCU_FILE}\\VSCode`, - enabled: false - }) - - for (const [regPath, failure] of Object.entries(failures)) { - const res = await toggleContextMenuEntry(regPath, false, host, regPath) - assert.equal(res.ok, false, regPath) - assert.equal(res.enabled, true, '失败时保持原来的启用状态') - assert.match(res.message, new RegExp(failure.errorCode)) - } - // 每次只调用一次宿主,没有再去调用不存在的旧方法 - assert.equal(host.calls.length, 4) - assert.ok(host.calls.every((c) => c.func === 'toggleEntry')) -}) - -test('启用 / 禁用:IPC 失败、宿主返回状态与请求不符、参数缺失、敏感注册表路径都不报成功', async () => { - const regPath = `${HKCU_FILE}\\VSCode` - const ipcFail = await toggleContextMenuEntry(regPath, true, { - async dllplugin_call() { - return { messageId: 'm1', success: false, error: { code: 'PERMISSION_DENIED', message: '第三方插件无权调用特权方法' } } - } - }, regPath) - assert.equal(ipcFail.ok, false) - assert.equal(ipcFail.enabled, false) - assert.match(ipcFail.message, /无权调用/) + assert.deepEqual(host.calls[0], { action: 'toggle', id: 'id-hkcu', enabled: false }) - const mismatch = await toggleContextMenuEntry(regPath, false, createHost({ - toggleEntry: (params) => routerResponse({ ok: true, success: true, regPath: params.regPath, enabled: true }) - }), regPath) - assert.equal(mismatch.ok, false) - assert.match(mismatch.message, /STATE_MISMATCH/) + const denied = await toggleContextMenuEntry('id-admin', false, host, `${HKLM_DIR}\\git`) + assert.equal(denied.ok, false) + assert.equal(denied.enabled, true) + assert.match(denied.message, /管理员权限|提权服务/) - const host = createHost({ toggleEntry: () => routerResponse({ ok: true, success: true }) }) - const noState = await toggleContextMenuEntry(regPath, undefined, host, regPath) - assert.equal(noState.ok, false) - assert.match(noState.message, /INVALID_PARAMS/) - const noId = await toggleContextMenuEntry(' ', false, host) - assert.equal(noId.ok, false) const sam = await toggleContextMenuEntry('HKLM\\SAM', false, host, 'HKLM\\SAM') assert.equal(sam.ok, false) assert.match(sam.message, /禁止/) - assert.equal(host.calls.length, 0, '参数无效或被拦截时不调用宿主') }) -test('Win11 经典菜单:显式传目标模式,成功提示需要重启资源管理器;宿主执行的模式不符或写入失败时报失败', async () => { - // 按宿主真实逻辑:有 classic / enabled 参数时按参数执行,否则按当前注册表状态反转 - let classicKeyExists = true +test('Win11 经典菜单切换:显式传 classic 并核验返回模式', async () => { const host = createHost({ - switchWin11Classic: (params) => { - const enableClassic = typeof params.classic === 'boolean' ? params.classic : typeof params.enabled === 'boolean' ? params.enabled : !classicKeyExists - classicKeyExists = enableClassic - return routerResponse({ ok: true, success: true, classic: enableClassic, output: '操作成功完成。' }) - } + 'switch-win11-classic': ({ classic }) => ({ success: true, data: { success: true, classic } }) }) - const res = await switchWin11ClassicMenu(true, host) - assert.equal(res.ok, true) - assert.equal(res.classicMode, true) - assert.match(res.message, /重启资源管理器/) - assert.equal(host.calls[0].params.classic, true) - assert.equal(classicKeyExists, true, '已是经典模式时再次请求经典模式不能被反转成默认模式') - - const restore = await switchWin11ClassicMenu(false, host) - assert.equal(restore.ok, true) - assert.equal(restore.classicMode, false) - assert.equal(classicKeyExists, false) - - // 宿主忽略参数并反转了模式:不能报告为请求的模式 - const ignoring = createHost({ switchWin11Classic: () => routerResponse({ ok: true, success: true, classic: false }) }) - const mismatch = await switchWin11ClassicMenu(true, ignoring) + const enable = await switchWin11ClassicMenu(true, host) + assert.equal(enable.ok, true) + assert.equal(enable.classicMode, true) + assert.match(enable.message, /重启资源管理器/) + + const mismatch = await switchWin11ClassicMenu(true, createHost({ + 'switch-win11-classic': () => ({ success: true, data: { success: true, classic: false } }) + })) assert.equal(mismatch.ok, false) - assert.equal(mismatch.classicMode, null) assert.match(mismatch.message, /STATE_MISMATCH/) - - const regFail = createHost({ - switchWin11Classic: () => routerResponse({ ok: false, success: false, classic: true, output: '', error: '错误: 拒绝访问。' }) - }) - const failed = await switchWin11ClassicMenu(true, regFail) - assert.equal(failed.ok, false) - assert.match(failed.message, /拒绝访问/) - - const invalid = await switchWin11ClassicMenu(undefined, host) - assert.equal(invalid.ok, false) - assert.match(invalid.message, /INVALID_PARAMS/) }) -test('状态条文字:读取失败、重新扫描失败、扫描中、成功各自如实描述,Win11 模式未知时为未识别', () => { - const entry = { id: 'a', title: 'A', scope: 'file', scopeLabel: '所有文件', registryKey: `${HKCU_FILE}\\A`, command: '', enabled: true } - assert.match(buildSummaryText({ entries: [], scanError: 'SCAN_FAILED: x', isLoading: false, truncatedLocations: [] }), /^读取失败,不能判断/) - assert.match(buildSummaryText({ entries: [entry], scanError: 'SCAN_TIMEOUT: x', isLoading: false, truncatedLocations: [] }), /^重新扫描失败,下方是上次的结果:SCAN_TIMEOUT/) - assert.equal(buildSummaryText({ entries: [], scanError: '', isLoading: true, truncatedLocations: [] }), '正在扫描右键菜单...') - assert.equal(buildSummaryText({ entries: [], scanError: '', isLoading: false, truncatedLocations: [] }), '共 0 项 · 已启用 0 项 · 已禁用 0 项') - assert.equal( - buildSummaryText({ entries: [entry, { ...entry, id: 'b', enabled: null }], scanError: '', isLoading: false, truncatedLocations: [HKCU_FILE] }), - '共 2 项 · 已启用 1 项 · 已禁用 0 项 · 状态未识别 1 项 · 1 个位置达到扫描上限,可能未列全' - ) +test('截断检测、状态条摘要与 i18n 热切换', () => { + const full = Array.from({ length: HOST_SCAN_LIMIT_PER_LOCATION }, (_, i) => ({ + id: `i-${i}`, title: `T${i}`, sourceKind: 'shell', sourceLabel: '静态命令', + scope: 'file', scopeLabel: '所有文件', registryKey: `${HKCU_FILE}\\item${i}`, + command: '', clsid: null, dllPath: null, publisher: null, description: null, + packageFamilyName: null, requiresAdmin: false, enabled: true, canToggle: true + })) + assert.deepEqual(findTruncatedLocations(full), [HKCU_FILE]) assert.deepEqual([null, true, false].map(win11ModeLabel), ['未识别', '经典完整', '默认折叠']) -}) + assert.match(buildSummaryText({ entries: [], scanError: '', isLoading: false, truncatedLocations: [] }), /共 0 项/) -test('i18n 热切换:运行时在 zh-CN 与 en-US 之间切换时,getter 与动态函数文案实时更新不冻结', () => { try { - setRuntimeLocale('zh-CN') - const zhFile = SCOPE_LABELS.file - const zhDir = SCOPE_LABELS.directory - const zhBg = SCOPE_LABELS.background - const zhForbidden = getForbiddenReason() - const zhNoHost = getNoHostError() - const zhUnknown = getUnknownScopeLabel() - assert.equal(getScopeLabel('file'), zhFile) - assert.match(zhFile, /[\u4e00-\u9fa5]/) - setRuntimeLocale('en-US') - const enFile = SCOPE_LABELS.file - const enDir = SCOPE_LABELS.directory - const enBg = SCOPE_LABELS.background - const enForbidden = getForbiddenReason() - const enNoHost = getNoHostError() - const enUnknown = getUnknownScopeLabel() - assert.equal(getScopeLabel('file'), enFile) - assert.notEqual(enFile, zhFile) - assert.notEqual(enDir, zhDir) - assert.notEqual(enBg, zhBg) - assert.notEqual(enForbidden, zhForbidden) - assert.notEqual(enNoHost, zhNoHost) - assert.notEqual(enUnknown, zhUnknown) - assert.doesNotMatch(`${enFile} ${enDir} ${enBg} ${enForbidden} ${enNoHost} ${enUnknown}`, /[\u4e00-\u9fa5]/) + assert.equal(getScopeLabel('file'), 'All Files') + assert.equal(getSourceLabel('shellex'), 'Shell Extension') + assert.equal(SCOPE_LABELS.background, 'Folder Background') + assert.doesNotMatch(`${getForbiddenReason()} ${getNoHostError()} ${getUnknownScopeLabel()}`, /[\u4e00-\u9fa5]/) } finally { setRuntimeLocale('zh-CN') } diff --git a/extensions/context-menu/tests/context-menu.ui.test.mjs b/extensions/context-menu/tests/context-menu.ui.test.mjs index ec8abf19..4ddab412 100644 --- a/extensions/context-menu/tests/context-menu.ui.test.mjs +++ b/extensions/context-menu/tests/context-menu.ui.test.mjs @@ -1,5 +1,4 @@ -// context-menu 界面集成测试:真实声明式运行时 + 按宿主 dllplugin_call 返回结构模拟的 Windows 宿主 -// 覆盖:扫描失败显示错误而不是空列表、重新扫描失败保留旧结果、写入失败如实提示、状态未识别不可切换、Win11 菜单模式未识别与显式切换 +// context-menu 界面集成测试:验证专用 context_menu IPC 与三类来源展示、无损启停与权限提示 import test from 'node:test' import assert from 'node:assert/strict' import { createHost, mount, tick } from '../../shared/test-harness.mjs' @@ -8,182 +7,152 @@ import ContextMenuCommand from '../dist/index.js' const host = createHost() const HKCU_FILE = 'HKEY_CURRENT_USER\\Software\\Classes\\*\\shell' -const HKLM_DIR = 'HKEY_LOCAL_MACHINE\\Software\\Classes\\Directory\\shell' - -/** 与 dllplugin_call 路由一致:处理器结果没有 data 字段时补 data: { ...结果 }(测试工具再包一层 IPC 成功响应) */ -function routed(hostResult) { - return hostResult.data === undefined ? { ...hostResult, data: { ...hostResult } } : hostResult -} - -function hostEntry(parent, keyName, extra = {}) { - const keyPath = `${parent}\\${keyName}` - return { id: keyPath, name: keyName, keyName, scope: parent.includes('Directory') ? 'directory' : 'file', regPath: keyPath, keyPath, command: '', enabled: true, ...extra } -} +const HKLM_DIR = 'HKEY_LOCAL_MACHINE\\SOFTWARE\\Classes\\Directory\\shell' const ENTRIES = [ - hostEntry(HKCU_FILE, 'VSCode', { name: 'Open with Code', command: '"Code.exe" "%1"' }), - hostEntry(HKLM_DIR, 'git_shell', { name: 'Open Git Bash here' }), - hostEntry(HKCU_FILE, 'Legacy', { name: '旧菜单', enabled: false }), - hostEntry(HKCU_FILE, 'NoState', { name: '状态缺失', enabled: undefined }) + { + id: 'entry-vscode', + sourceKind: 'shell', + title: 'Open with Code', + scope: 'file', + registryKey: `${HKCU_FILE}\\VSCode`, + command: '"Code.exe" "%1"', + clsid: null, + dllPath: null, + publisher: null, + description: null, + packageFamilyName: null, + requiresAdmin: false, + enabled: true, + canToggle: true + }, + { + id: 'entry-7zip', + sourceKind: 'shellex', + title: '7-Zip Shell Extension', + scope: 'file', + registryKey: 'HKEY_LOCAL_MACHINE\\SOFTWARE\\Classes\\*\\shellex\\ContextMenuHandlers\\7-Zip', + command: 'C:\\Program Files\\7-Zip\\7-zip.dll', + clsid: '{23170F69-40C1-278A-1000-000100020000}', + dllPath: 'C:\\Program Files\\7-Zip\\7-zip.dll', + publisher: 'Igor Pavlov', + description: '7-Zip Shell Extension', + packageFamilyName: null, + requiresAdmin: true, + enabled: true, + canToggle: true + }, + { + id: 'entry-wt', + sourceKind: 'packaged', + title: 'Windows Terminal', + scope: 'directory', + registryKey: 'AppxPackage\\Microsoft.WindowsTerminal\\{9F156763-7844-4DC4-B2B1-901F640F5155}', + command: 'C:\\Program Files\\WindowsApps\\WT', + clsid: '{9F156763-7844-4DC4-B2B1-901F640F5155}', + dllPath: 'C:\\Program Files\\WindowsApps\\WT', + publisher: 'Microsoft Corporation', + description: 'Windows Terminal', + packageFamilyName: 'Microsoft.WindowsTerminal', + requiresAdmin: true, + enabled: false, + canToggle: true + } ] -/** - * 安装宿主:scan 为扫描结果(函数或固定值),toggle / classic 记录调用并按真实处理器返回 - */ function installHost({ scan, toggleFailures = {}, classicFailure = null } = {}) { host.reset() const calls = { scan: 0, toggle: [], classic: [] } - host.ipc.dllplugin_call = async ({ plugin, func, params }) => { - assert.equal(plugin, 'ContextMenuPlugin') - if (func === 'scanEntries') { + host.ipc.context_menu = async (params) => { + if (params.action === 'scan') { calls.scan++ - const res = typeof scan === 'function' ? scan(calls.scan) : scan - return routed(res) + return typeof scan === 'function' ? scan(calls.scan) : scan } - if (func === 'toggleEntry') { + if (params.action === 'toggle') { calls.toggle.push(params) - const base = { regPath: params.regPath, keyPath: params.regPath, enabled: params.enabled } - const failure = toggleFailures[params.regPath] - return routed(failure ? { ok: false, success: false, ...base, ...failure } : { ok: true, success: true, ...base }) + const fail = toggleFailures[params.id] + if (fail) return fail + return { success: true, id: params.id, enabled: params.enabled } } - if (func === 'switchWin11Classic') { + if (params.action === 'switch-win11-classic') { calls.classic.push(params) - if (classicFailure) return routed({ ok: false, success: false, classic: params.classic, output: '', error: classicFailure }) - return routed({ ok: true, success: true, classic: params.classic, output: '操作成功完成。' }) + if (classicFailure) return { success: false, error: classicFailure } + return { success: true, classic: params.classic } + } + if (params.action === 'restart-explorer') { + return { success: true, restarted: true } } - return routed({ ok: false, success: false, error: `Unsupported ContextMenuPlugin function: ${func}` }) + throw new Error(`Unexpected context_menu action: ${params.action}`) } return calls } -const okScan = (entries = ENTRIES) => ({ ok: true, success: true, items: entries, entries }) -const failedScan = { ok: false, success: false, errorCode: 'SCAN_FAILED', error: 'SCAN_FAILED: 读取右键菜单失败:PowerShell 退出码 1' } - -function summary(view) { - return view.tree().props.filterBar.summaryText -} +const okScan = (entries = ENTRIES, extra = {}) => ({ + success: true, + entries, + win11ClassicEnabled: null, + warnings: [], + isAdmin: false, + privilegedServiceReady: false, + ...extra +}) function accessoryText(item) { return item.props.accessories.map((a) => a.text ?? a.tag?.value).join('|') } -test('首次扫描返回 SCAN_FAILED:显示错误行与失败提示,不显示成空列表', async () => { - installHost({ scan: failedScan }) - const view = await mount(ContextMenuCommand) - const errorRow = view.item('ctx-scan-error') - assert.equal(errorRow.props.title, '读取右键菜单失败') - assert.match(errorRow.props.subtitle, /SCAN_FAILED/) - assert.match(summary(view), /读取失败,不能判断有哪些右键菜单项/) - assert.doesNotMatch(summary(view), /共 0 项/) - assert.equal(host.lastToast().style, Toast.Style.Failure) - assert.match(host.lastToast().message, /SCAN_FAILED/) - // 只有错误行与 Win11 设置行,没有菜单项 - assert.deepEqual(view.items().map((i) => i.props.id), ['ctx-scan-error', 'ctx-win11-classic']) - assert.equal(view.tree().props.isLoading, false) - view.unmount() -}) - -test('错误行的重新扫描成功后清除错误并显示真实结果', async () => { - const calls = installHost({ scan: (n) => (n === 1 ? failedScan : okScan()) }) - const view = await mount(ContextMenuCommand) - await view.run(view.item('ctx-scan-error'), '重新扫描') - assert.equal(calls.scan, 2) - assert.equal(view.items().some((i) => i.props.id === 'ctx-scan-error'), false) - assert.match(summary(view), /共 4 项 · 已启用 2 项 · 已禁用 1 项 · 状态未识别 1 项/) - assert.equal(host.lastToast().style, Toast.Style.Success) - view.unmount() -}) - -test('重新扫描失败:保留上次结果并标明是旧结果', async () => { - const calls = installHost({ scan: (n) => (n === 1 ? okScan() : failedScan) }) +test('展示三类菜单来源标签、真实 DLL/厂商与权限提示,且绝不调用 dllplugin_call', async () => { + installHost({ scan: okScan() }) const view = await mount(ContextMenuCommand) - assert.equal(view.items().length, 5) - await view.tree().props.filterBar.actions[0].onAction() - await tick() - assert.equal(calls.scan, 2) - assert.equal(view.item('ctx-scan-error').props.title, '重新扫描失败') - assert.match(summary(view), /重新扫描失败,下方是上次的结果/) - assert.ok(view.item(`${HKCU_FILE}\\VSCode`)) + assert.ok(!host.ipcCalls.some(([m]) => m === 'dllplugin_call')) + assert.match(accessoryText(view.item('entry-vscode')), /静态命令/) + assert.match(accessoryText(view.item('entry-7zip')), /外壳扩展.*需提权/) + assert.match(view.item('entry-7zip').props.subtitle, /Igor Pavlov.*7-zip\.dll/) + assert.match(accessoryText(view.item('entry-wt')), /Win11 打包.*已禁用/) + assert.match(view.tree().props.filterBar.summaryText, /需管理员或提权服务/) + + await view.dropdown('shellex') + assert.deepEqual(view.items().map((i) => i.props.id), ['entry-7zip']) + await view.dropdown('packaged') + assert.deepEqual(view.items().map((i) => i.props.id), ['entry-wt']) view.unmount() }) -test('禁用菜单项:需要管理员权限时如实提示失败并保持已启用;HKCU 项禁用成功后状态更新', async () => { +test('禁用 shellex 权限不足如实提示失败并保持启用;禁用 HKCU shell 成功后立即更新', async () => { const calls = installHost({ scan: okScan(), toggleFailures: { - [`${HKLM_DIR}\\git_shell`]: { - errorCode: 'ADMIN_REQUIRED', - error: 'ADMIN_REQUIRED: 修改该右键菜单项需要管理员权限,请以管理员身份运行 ZTools 后重试' + 'entry-7zip': { + success: false, + errorCode: 'ADMIN_PRIVILEGE_REQUIRED', + error: 'ADMIN_PRIVILEGE_REQUIRED: 修改外壳扩展需要管理员权限或 ZTools 提权服务' } } }) const view = await mount(ContextMenuCommand) - - await view.run(view.item(`${HKLM_DIR}\\git_shell`), '禁用该菜单项') + await view.run(view.item('entry-7zip'), '禁用该菜单项') assert.equal(host.lastToast().style, Toast.Style.Failure) - assert.equal(host.lastToast().title, '修改右键菜单项失败') - assert.match(host.lastToast().message, /ADMIN_REQUIRED/) - assert.match(accessoryText(view.item(`${HKLM_DIR}\\git_shell`)), /已启用/) + assert.match(host.lastToast().message, /管理员权限|提权服务/) + assert.match(accessoryText(view.item('entry-7zip')), /已启用/) - await view.run(view.item(`${HKCU_FILE}\\VSCode`), '禁用该菜单项') + await view.run(view.item('entry-vscode'), '禁用该菜单项') assert.equal(host.lastToast().style, Toast.Style.Success) - assert.match(accessoryText(view.item(`${HKCU_FILE}\\VSCode`)), /已禁用/) - assert.deepEqual(calls.toggle.map((p) => [p.regPath, p.enabled]), [ - [`${HKLM_DIR}\\git_shell`, false], - [`${HKCU_FILE}\\VSCode`, false] + assert.match(accessoryText(view.item('entry-vscode')), /已禁用/) + assert.deepEqual(calls.toggle.map((c) => [c.id, c.enabled]), [ + ['entry-7zip', false], + ['entry-vscode', false] ]) view.unmount() }) -test('状态未识别的项不提供启用 / 禁用;没有命令的项不提供复制命令', async () => { - installHost({ scan: okScan() }) - const view = await mount(ContextMenuCommand) - const noState = view.item(`${HKCU_FILE}\\NoState`) - assert.match(accessoryText(noState), /状态未识别/) - assert.deepEqual(view.actions(noState).map((a) => a.props.title), ['复制注册表路径']) - const withCommand = view.item(`${HKCU_FILE}\\VSCode`) - assert.deepEqual(view.actions(withCommand).map((a) => a.props.title), ['禁用该菜单项', '复制注册表路径', '复制执行命令']) - await view.run(withCommand, '复制执行命令') - assert.equal(host.clipboard.text, '"Code.exe" "%1"') - view.unmount() -}) - -test('“已禁用”筛选只列出宿主确认已禁用的项,并隐藏 Win11 设置行', async () => { - installHost({ scan: okScan() }) - const view = await mount(ContextMenuCommand) - await view.dropdown('disabled') - assert.deepEqual(view.items().map((i) => i.props.title), ['旧菜单']) - view.unmount() -}) - -test('Win11 菜单模式:初始为未识别并提供两个方向;显式切换成功后更新,写入失败如实提示', async () => { - const calls = installHost({ scan: okScan() }) - const view = await mount(ContextMenuCommand) - const row = () => view.item('ctx-win11-classic') - assert.equal(accessoryText(row()), '未识别') - assert.deepEqual(view.actions(row()).map((a) => a.props.title), ['切换为经典完整右键菜单', '恢复 Windows 11 默认右键菜单']) - - await view.run(row(), '切换为经典完整右键菜单') - assert.deepEqual(calls.classic.map((p) => p.classic), [true]) - assert.equal(accessoryText(row()), '经典完整') - assert.match(host.lastToast().title, /重启资源管理器/) - assert.deepEqual(view.actions(row()).map((a) => a.props.title), ['恢复 Windows 11 默认右键菜单']) - view.unmount() - - const failCalls = installHost({ scan: okScan(), classicFailure: '错误: 拒绝访问。' }) - const view2 = await mount(ContextMenuCommand) - await view2.run(view2.item('ctx-win11-classic'), '恢复 Windows 11 默认右键菜单') - assert.deepEqual(failCalls.classic.map((p) => p.classic), [false]) - assert.equal(host.lastToast().style, Toast.Style.Failure) - assert.match(host.lastToast().message, /拒绝访问/) - assert.equal(accessoryText(view2.item('ctx-win11-classic')), '未识别') - view2.unmount() -}) - -test('某个位置达到宿主扫描上限时在状态条提示可能未列全', async () => { - const many = Array.from({ length: 40 }, (_, i) => hostEntry(HKCU_FILE, `item${i}`)) - installHost({ scan: okScan(many) }) +test('首次扫描失败显示错误行而非空列表,重扫成功后清除错误', async () => { + const calls = installHost({ + scan: (n) => (n === 1 ? { success: false, errorCode: 'SCAN_FAILED', error: 'SCAN_FAILED: 枚举失败' } : okScan()) + }) const view = await mount(ContextMenuCommand) - assert.match(summary(view), /1 个位置达到扫描上限,可能未列全/) + assert.equal(view.item('ctx-scan-error').props.title, '读取右键菜单失败') + await view.run(view.item('ctx-scan-error'), '重新扫描') + assert.equal(calls.scan, 2) + assert.equal(view.items().some((i) => i.props.id === 'ctx-scan-error'), false) view.unmount() }) diff --git a/extensions/crypto-tool/README.en.md b/extensions/crypto-tool/README.en.md new file mode 100644 index 00000000..85383a05 --- /dev/null +++ b/extensions/crypto-tool/README.en.md @@ -0,0 +1,21 @@ +# Codec + +Compute text hashes, encode/decode Base64, URL, Unicode, and Hex strings, encrypt/decrypt with AES, compute HMAC signatures, and batch generate UUIDs. + +## Usage + +- Commands: Base64 Encode/Decode (`base64`), URL Encode/Decode (`urlencode`, `urldecode`), MD5 / SHA Hash (`md5`, `sha256`, `hash`), AES Encrypt/Decrypt (`aes`), HMAC Sign (`hmac`), Unicode Encode/Decode (`unicode`), Hex Encode/Decode (`hex`), and Batch Generate UUID (`uuid`, `guid`). +- In Hash mode, typing text updates MD5 (32-char uppercase/lowercase, 16-char), SHA-1, SHA-256, SHA-512, Base64, and URL-encoded results in real time. Use the dropdown next to the search box to switch to Base64, URL, Unicode, or Hex encode/decode modes. +- `Enter` copies the selected result; `⌘/Ctrl+K` opens the action panel to enter AES encryption/decryption, HMAC calculation (`SHA-256`, `SHA-512`, `SHA-1`, `MD5`), and batch UUID generation. Inside forms, press `⌘/Ctrl+Enter` to run encrypt/decrypt or copy the HMAC result. +- AES uses AES-256-CBC: the key is the SHA-256 digest of the passphrase; the IV uses the MD5 digest of the IV input if provided, or the first 16 bytes of the key if left blank (so the same passphrase and plaintext produce identical ciphertext each time); ciphertext is Base64-encoded. CBC mode does not verify ciphertext integrity; external tools must handle the passphrase and IV identically to interoperate. +- Base64 mode shows both encoded and decoded results; decoding supports standard and URL-safe Base64 and requires valid UTF-8 text output. Hex encodes/decodes as UTF-8. Invalid inputs display the error reason. +- Generates 1 to 1,000 UUIDs at a time using the system cryptographically secure random number generator. + +## Platforms & Requirements + +- Supported: Windows, macOS +- Built into the client; no separate installation required. + +## Network & Data + +- Works offline; data stays on your local device. diff --git a/extensions/crypto-tool/plugin.json b/extensions/crypto-tool/plugin.json index 6ddbfe5b..badc2756 100644 --- a/extensions/crypto-tool/plugin.json +++ b/extensions/crypto-tool/plugin.json @@ -1,7 +1,8 @@ { "id": "crypto-tool", "name": "编码与加密", - "version": "1.1.5", + "version": "1.1.6", + "minAppVersion": "1.1.8.0", "description": "支持 Base64 / URL / Unicode / Hex 编码互转、MD5 / SHA 哈希计算、AES 加解密、HMAC 计算与 UUID 批量生成", "author": "ZTools Team", "entry": "dist/index.js", @@ -41,7 +42,10 @@ "编码转换", "unicode", "uuid", - "guid" + "guid", + "编码", + "解码", + "散列" ], "features": [ { @@ -153,7 +157,14 @@ "hash", "aes", "hmac", - "uuid" + "uuid", + "encode", + "decode", + "encrypt", + "decrypt", + "url encode", + "crypto", + "codec" ], "features": { "codec-base64": { diff --git a/extensions/crypto-tool/src/i18n.ts b/extensions/crypto-tool/src/i18n.ts index b5a0d0a3..0fd3e2ad 100644 --- a/extensions/crypto-tool/src/i18n.ts +++ b/extensions/crypto-tool/src/i18n.ts @@ -42,6 +42,8 @@ const rawT = createTranslator( readClipboardFailed: "读取剪贴板失败", actionsTitle: "操作", pasteFromClipboard: "从剪贴板粘贴", + readClipboardBtn: "从剪贴板读取", + pasteToActive: "直接粘贴到当前应用", clearInput: "清空输入", copy: "复制", codecEmptyTitle: "输入文字或编码内容", @@ -166,6 +168,8 @@ const rawT = createTranslator( readClipboardFailed: "Failed to read clipboard", actionsTitle: "Actions", pasteFromClipboard: "Paste from Clipboard", + readClipboardBtn: "Read Clipboard", + pasteToActive: "Paste to Frontmost App", clearInput: "Clear Input", copy: "Copy", codecEmptyTitle: "Enter text or encoded content", diff --git a/extensions/crypto-tool/src/index.ts b/extensions/crypto-tool/src/index.ts index aa86b433..c9fd6df2 100644 --- a/extensions/crypto-tool/src/index.ts +++ b/extensions/crypto-tool/src/index.ts @@ -151,6 +151,7 @@ export function AesForm({ draft = DEFAULT_AES_DRAFT, onDraftChange }: DraftProps placeholder: direction === "encrypt" ? t("plaintextPlaceholder") : t("ciphertextPlaceholder"), value: text, error, + autoFocus: true, onChange: (v: string) => { setText(v); resetResult(); } }), Form.PasswordField({ id: "key", title: t("passphraseTitle"), placeholder: t("passphrasePlaceholder"), value: key, onChange: (v: string) => { setKey(v); resetResult(); } }), @@ -191,7 +192,7 @@ export function HmacForm({ draft = DEFAULT_HMAC_DRAFT, onDraftChange }: DraftPro Form.Dropdown.Item({ title: "HMAC-MD5", value: "md5" }) ] ), - Form.TextArea({ id: "text", title: t("messageField"), placeholder: t("messagePlaceholder"), value: text, onChange: (v: string) => setText(v) }), + Form.TextArea({ id: "text", title: t("messageField"), placeholder: t("messagePlaceholder"), value: text, autoFocus: true, onChange: (v: string) => setText(v) }), Form.PasswordField({ id: "key", title: t("secretField"), placeholder: t("secretPlaceholder"), value: key, onChange: (v: string) => setKey(v) }), Form.Description({ title: t("hmacResultTitle"), text: hasInput ? value : t("hmacResultHint") }) ] @@ -282,21 +283,35 @@ export default function CryptoToolCommand() { const commonItemActions = (value: string, label: string) => ActionPanel({ title: label }, [ Action.CopyToClipboard({ title: t("copy"), content: value, icon: Icon.CopyClipboard }), - Action({ title: t("clearInput"), icon: Icon.Trash, onAction: clearAllInput }), + Action.Paste({ title: t("pasteToActive"), content: value, icon: Icon.ArrowRight, shortcut: { modifiers: ["ctrl"], key: "return" } }), + Action({ title: t("clearInput"), icon: Icon.Trash, shortcut: { modifiers: ["ctrl"], key: "backspace" }, onAction: clearAllInput }), // AES / HMAC / UUID 是另开表单的全局工具,排在后面收进动作面板,不占回车与次动作位 ...globalActions ]); let items: ReturnType[]; if (mode === "url" || mode === "unicode" || mode === "hex") { - items = !inputText ? [List.Item({ id: "empty", title: t("codecEmptyTitle"), subtitle: t("codecEmptySub"), icon: Icon.Text, actions: emptyActions })] : (["encode", "decode"] as const).map(direction => { + if (!inputText) { + items = [List.Item({ id: "empty", title: t("codecEmptyTitle"), subtitle: t("codecEmptySub"), icon: Icon.Text, actions: emptyActions })]; + } else { + let encodeItem: ReturnType; try { - const value = direction === "encode" ? encodeText(inputText, mode) : decodeText(inputText, mode); - return List.Item({ id: direction, title: value || t("emptyTextLabel"), subtitle: `${CODEC_LABEL[mode]} ${direction === "encode" ? t("encodeWord") : t("decodeWord")}`, icon: Icon.Text, detail: List.Item.Detail({ markdown: valueMarkdown(value) }), actions: commonItemActions(value, direction === "encode" ? t("encodeResult") : t("decodeResult")) }); + const value = encodeText(inputText, mode); + encodeItem = List.Item({ id: "encode", title: value || t("emptyTextLabel"), subtitle: `${CODEC_LABEL[mode]} ${t("encodeWord")}`, icon: Icon.Text, detail: List.Item.Detail({ markdown: valueMarkdown(value) }), actions: commonItemActions(value, t("encodeResult")) }); } catch (err: unknown) { - return List.Item({ id: `${direction}-error`, title: direction === "encode" ? t("cannotEncode") : t("cannotDecode"), subtitle: err instanceof Error ? err.message : String(err), icon: Icon.ExclamationMark, actions: errorActions }); + encodeItem = List.Item({ id: "encode-error", title: t("cannotEncode"), subtitle: err instanceof Error ? err.message : String(err), icon: Icon.ExclamationMark, actions: errorActions }); } - }); + let decodeItem: ReturnType; + let effectiveDecode = false; + try { + const value = decodeText(inputText, mode); + effectiveDecode = value !== inputText; + decodeItem = List.Item({ id: "decode", title: value || t("emptyTextLabel"), subtitle: `${CODEC_LABEL[mode]} ${t("decodeWord")}`, icon: Icon.Text, detail: List.Item.Detail({ markdown: valueMarkdown(value) }), actions: commonItemActions(value, t("decodeResult")) }); + } catch (err: unknown) { + decodeItem = List.Item({ id: "decode-error", title: t("cannotDecode"), subtitle: err instanceof Error ? err.message : String(err), icon: Icon.ExclamationMark, actions: errorActions }); + } + items = effectiveDecode ? [decodeItem, encodeItem] : [encodeItem, decodeItem]; + } } else if (mode === "base64-decode") { const decoded = decodeBase64(inputText); const encoded = inputText.trim() @@ -408,6 +423,20 @@ export default function CryptoToolCommand() { searchBarPlaceholder: mode === "hash" ? t("placeholderHash") : mode === "base64-decode" ? t("placeholderBase64") : t("placeholderCodec"), searchText: inputText, onSearchTextChange: (text: string) => { setFileHash(null); setInputText(text); }, + filterBar: { + actions: [ + { + id: "read-clipboard", + label: t("readClipboardBtn"), + title: t("pasteFromClipboard"), + icon: Icon.Clipboard, + style: "primary", + onAction: () => { + void pasteFromClipboard(); + } + } + ] + }, searchBarAccessory: List.Dropdown( { tooltip: t("modeTooltip"), value: mode, onChange: (v: string) => setMode(isMode(v) ? v : "hash") }, [ diff --git a/extensions/crypto-tool/tests/mac-review.test.mjs b/extensions/crypto-tool/tests/mac-review.test.mjs index 0a1fea15..dd57fbda 100644 --- a/extensions/crypto-tool/tests/mac-review.test.mjs +++ b/extensions/crypto-tool/tests/mac-review.test.mjs @@ -32,12 +32,12 @@ test('从剪贴板粘贴:有文字填入搜索框;剪贴板为空时提示 } finally { view.unmount() } }) -test('结果行:回车复制、⌘/Ctrl+Enter 是清空输入,AES 排在后面', async () => { +test('结果行:回车复制、⌘/Ctrl+Enter 是直接粘贴到当前应用,清空输入与 AES 排在后面', async () => { const view = await mount(CryptoToolCommand) try { await view.search('abc') const t = titles(view, view.item('sha256')) - assert.deepEqual(t.slice(0, 2), ['复制', '清空输入']) + assert.deepEqual(t.slice(0, 3), ['复制', '直接粘贴到当前应用', '清空输入']) } finally { view.unmount() } }) diff --git a/extensions/curl-http/README.en.md b/extensions/curl-http/README.en.md new file mode 100644 index 00000000..724a1010 --- /dev/null +++ b/extensions/curl-http/README.en.md @@ -0,0 +1,19 @@ +# Lightweight HTTP Client + +Parse cURL commands copied from browser developer tools, send HTTP requests to inspect responses, or convert requests into Fetch, Axios, Python Requests, or Go code snippets. + +## Usage + +- Command: Type `curl`, `http`, `api`, `fetch`, or `rest client` in the launcher to open. +- Paste a cURL command or an `http` / `https` URL into the search box, or load it from the clipboard via the action panel. Recognizes `-X`, `-H`, `-d` / `--data*`, `--json`, `-b`, `-u`, `-A`, `-e`, `-G`, `-I`, and `--url` flags, as well as multiline line continuations using bash `\`, cmd `^`, or PowerShell backticks. Works with both "Copy as cURL (bash)" and "Copy as cURL (cmd)" from browser developer tools (including bash `$'...'` and cmd `^"` escapes). Unsupported flags such as proxies, timeouts, or certificate-skip options do not take effect and are listed in the UI; flags that read local files (`-d @file`, `-F` form uploads, `-T`) are not supported. +- Select the code generation language from the top dropdown: JavaScript Fetch, TypeScript Axios, Python Requests, or Go `net/http`. +- `Enter`: Send the request and view the status code, duration, and response body on the right (JSON is automatically formatted); `⌘/Ctrl+Enter`: Copy the generated code snippet; `⌘/Ctrl+K`: Open the action panel to copy the response body. +- Supports `GET`, `HEAD`, `POST`, `PUT`, and `DELETE` requests only. `DELETE` and `PUT` require confirmation before sending, and `DELETE` requests cannot include a request body; for other methods, copy the generated code and run it externally. Request timeout is 10 seconds, and maximum request body size is 768 KB. Connection-level headers such as `Connection` and `Content-Length` are handled automatically by the client and stripped before sending, and `Host` cannot be customized. Only the response body is shown (response headers are not displayed); bodies larger than 5 MB are truncated. + +## Platforms & Requirements + +- Supported: Windows, macOS + +## Network & Data + +- Sends requests only to the URL you enter, executed through the client. The plugin does not save requests or responses. diff --git a/extensions/curl-http/plugin.json b/extensions/curl-http/plugin.json index b920872a..3de9e29c 100644 --- a/extensions/curl-http/plugin.json +++ b/extensions/curl-http/plugin.json @@ -1,7 +1,8 @@ { "id": "curl-http", "name": "轻量接口调试", - "version": "1.0.9", + "version": "1.0.10", + "minAppVersion": "1.1.8.0", "description": "解析 cURL 命令(bash / cmd 写法)或网址,由客户端发起 HTTP 请求查看响应,并生成 Fetch、Axios、Python、Go 请求代码", "author": "ZTools Team", "category": [ @@ -57,7 +58,11 @@ "fetch", "axios", "request", - "debug" + "debug", + "postman", + "endpoint", + "debug api", + "http client" ], "features": { "curl-http": { @@ -86,5 +91,17 @@ { "path": "screenshots/02-action-panel.png" } + ], + "keywords": [ + "接口调试", + "发请求", + "测接口", + "http请求", + "curl", + "postman", + "api调试", + "接口测试", + "get请求", + "post请求" ] } diff --git a/extensions/curl-http/src/index.tsx b/extensions/curl-http/src/index.tsx index c6e8230a..f52e0974 100644 --- a/extensions/curl-http/src/index.tsx +++ b/extensions/curl-http/src/index.tsx @@ -179,6 +179,38 @@ export function CurlHttpCommand() { } + filterBar={{ + summaryText: parsedState.ok + ? `${parsedState.parsed.method} · ${t('overview.subtitle', { count: Object.keys(parsedState.parsed.headers).length, lang: targetLang.toUpperCase() })}` + : rawCurl.trim() + ? t('error.parseTitle') + : isMacPlatform() + ? t('empty.subtitleMac') + : t('empty.subtitle'), + actions: parsedState.ok + ? [ + { + id: 'send-request', + title: t('action.sendRequest'), + style: 'primary', + onAction: () => void handleSendRequest(), + }, + { + id: 'load-clipboard', + title: t('action.loadClipboard'), + style: 'secondary', + onAction: () => void handleLoadClipboard(), + }, + ] + : [ + { + id: 'load-clipboard', + title: t('action.pasteFromClipboard'), + style: 'primary', + onAction: () => void handleLoadClipboard(), + }, + ], + }} > {!parsedState.ok && !rawCurl.trim() && ( = 0 && rawPct <= 100 + const validPct = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const hasBattery = typeof payload.hasBattery === 'boolean' ? payload.hasBattery : validPct return { ...payload, - percent: hasBattery ? rawPct : null, + percent: validPct ? rawPct : null, hasBattery } } @@ -489,6 +491,8 @@ export interface RealDirectoryScanResult extends Iterable approximate?: boolean /** 宿主实际遍历的条目数 */ visitedEntries?: number + /** 目录本身不存在(ENOENT) */ + missing?: boolean /** 读取失败的真实原因;已有文件仍可使用,但不能当作完整结果。 */ error?: string } @@ -497,6 +501,7 @@ interface ScanResultMeta { truncated?: boolean approximate?: boolean visitedEntries?: number + missing?: boolean } export interface ScanDirectoryTreeOptions { @@ -504,6 +509,10 @@ export interface ScanDirectoryTreeOptions { maxFiles?: number collectTopN?: number filterExt?: RegExp + /** 为 true 时,目录本身不存在(ENOENT)按空目录处理,不返回 error(权限拒绝/读取失败仍照常报错) */ + ignoreMissing?: boolean + /** Top-N 保留与排序方式:默认按体积降序,下载/录屏等时效场景可传 mtime-desc */ + sortBy?: 'size-desc' | 'mtime-desc' hostOverride?: DynamicBridge } @@ -519,8 +528,9 @@ function normalizeIndexedFileEntry(f: DynamicBridge): RealIndexedFileEntry { const sz = Number(f?.size ?? f?.sizeBytes ?? 0) const isDir = Boolean(f?.is_dir || f?.isDir || f?.isDirectory) const rawMtime = Number(f?.mtime ?? f?.mtimeMs ?? 0) - const mtimeMs = rawMtime > 1e11 ? rawMtime : rawMtime > 0 ? rawMtime * 1000 : Date.now() - const mtimeSec = rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime + const validMtime = Number.isFinite(rawMtime) && rawMtime > 0 + const mtimeMs = validMtime ? (rawMtime > 1e11 ? rawMtime : rawMtime * 1000) : 0 + const mtimeSec = validMtime ? (rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime) : 0 if (p && sz >= 0) realFileSizeCache.set(p, sz) return { name, @@ -551,6 +561,7 @@ function makeScanResult( subdirs, ...(meta.truncated ? { truncated: true } : {}), ...(meta.approximate ? { approximate: true } : {}), + ...(meta.missing ? { missing: true } : {}), ...(typeof meta.visitedEntries === 'number' ? { visitedEntries: meta.visitedEntries } : {}), [Symbol.iterator]() { return files[Symbol.iterator]() @@ -609,13 +620,40 @@ export async function scanRealDirectoryTree( return result.error ? { ...result.scan, error: result.error } : result.scan } +/** 仅当正则明确声明了扩展名(含 `\.`)时提取后缀列表,避免把 `thumbcache|iconcache` 等文件名关键词误拆成假扩展名 */ +function extractExtensionTokensFromFilter(filterExt: RegExp): string[] { + const src = filterExt.source + if (!src.includes('\\.')) return [] + const afterDot = src.slice(src.indexOf('\\.') + 2) + const rawTokens = afterDot.match(/[a-z0-9]{1,8}/gi) || [] + const seen = new Set() + const out: string[] = [] + for (const token of rawTokens) { + const lower = token.toLowerCase() + if (!lower || seen.has(lower)) continue + seen.add(lower) + out.push(lower) + } + return out +} + +function isMissingDirectoryError(res: { error?: string; errorCode?: string; errorDetails?: Record }): boolean { + if (res.errorDetails?.reason === 'ENOENT' || res.errorCode === 'ENOENT') return true + const msg = String(res.error || '') + return /Directory does not exist|ENOENT/i.test(msg) +} + /** 一次界面扫描的错误汇总;多个目录并行扫描时保留可读目录的结果。 */ export function createDirectoryScanner(hostOverride?: DynamicBridge) { const failures = new Map() return { async scan(dir: string, options: number | ScanDirectoryTreeOptions = 160) { const result = await scanRealDirectoryTree(dir, options, hostOverride) - const error = result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') + const ignoreMissing = typeof options === 'object' && options !== null && options.ignoreMissing === true + const error = + result.missing && ignoreMissing + ? '' + : result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') if (error) failures.set(dir, error) else failures.delete(dir) return result @@ -648,26 +686,38 @@ async function scanDirectoryTreeWithError( const safeLimit = Math.min(200, Math.max(1, Math.floor(rawLimit || 160))) const hostOverride = opts.hostOverride const filterExt = opts.filterExt + const ignoreMissing = opts.ignoreMissing === true const dirQuery = `dir:${targetDir}` try { let rawPayload: DynamicBridge = null + const searchParams: Record = { + query: dirQuery, + limit: safeLimit, + ...(opts.sortBy ? { sortBy: opts.sortBy } : {}) + } const res = await callHostTransport( 'system_search_files', - { query: dirQuery, limit: safeLimit }, + searchParams, hostOverride ) - if (res.ok && res.data) { + if (res.ok && res.data && res.data.degraded !== true) { rawPayload = res.data + } else if (!res.ok && ignoreMissing && isMissingDirectoryError(res)) { + const missingScan = makeScanResult([], 0, 0, [], { missing: true }) + return { scan: missingScan } } - if (!rawPayload && !hostOverride && typeof window !== 'undefined') { + if (!rawPayload && !hostOverride && res.errorCode === 'METHOD_NOT_AVAILABLE' && typeof window !== 'undefined') { const w = window as DynamicBridge if (typeof w.__ztoolsLauncher?.searchFiles === 'function') { const rawOuter = await w.__ztoolsLauncher.searchFiles(dirQuery, safeLimit) - rawPayload = + const candidate = rawOuter && typeof rawOuter === 'object' && 'data' in rawOuter && rawOuter.data ? rawOuter.data : rawOuter + if (candidate && candidate.degraded !== true && candidate.success !== false) { + rawPayload = candidate + } } } @@ -678,29 +728,32 @@ async function scanDirectoryTreeWithError( let files: RealIndexedFileEntry[] = rawPayload.files.map(normalizeIndexedFileEntry) if (filterExt instanceof RegExp) { files = files.filter(f => !f.isDir && (filterExt.test(f.name) || filterExt.test(f.ext))) - // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索目标扩展名 + // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索明确声明的目标扩展名 if (files.length === 0 && !hostOverride) { - const extTokens = (filterExt.source.match(/[a-z0-9]{2,5}/gi) || []) - .filter(t => !['thumbcache', 'iconcache'].includes(t.toLowerCase())) - .slice(0, 4) - // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 - const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() - const extraLists = await Promise.all( - extTokens.map(ext => searchRealIndexedFiles(`.${ext.toLowerCase()}`, 30, hostOverride)) - ) - const seen = new Set() - for (const list of extraLists) { - for (const item of list) { - if (!item.isDir && item.size > 0 && !seen.has(item.path)) { - if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { - seen.add(item.path) - files.push(item) + const extTokens = extractExtensionTokensFromFilter(filterExt) + if (extTokens.length > 0) { + // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 + const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() + const extraLists = await Promise.all( + extTokens.map(ext => searchRealIndexedFiles(`.${ext}`, 30, hostOverride)) + ) + const seen = new Set() + for (const list of extraLists) { + for (const item of list) { + if (!item.isDir && item.size > 0 && !seen.has(item.path)) { + if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { + seen.add(item.path) + files.push(item) + } } } } } } } + // 先基于过滤后的完整命中集合计算总文件数与总字节数,再按 collectTopN 裁剪样本列表 + const matchedCount = files.length + const matchedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) if (typeof opts.collectTopN === 'number' && opts.collectTopN > 0 && files.length > opts.collectTopN) { files = files.slice(0, opts.collectTopN) } @@ -714,11 +767,10 @@ async function scanDirectoryTreeWithError( ...(s.approximate === true ? { approximate: true } : {}) })) : [] - const computedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) const totalFilesCount = - filterExt instanceof RegExp ? files.length : Number(rawPayload.total_matches ?? files.length) + filterExt instanceof RegExp ? matchedCount : Number(rawPayload.total_matches ?? matchedCount) const totalBytesCount = - filterExt instanceof RegExp ? computedBytes : Number(rawPayload.total_bytes ?? computedBytes) + filterExt instanceof RegExp ? matchedBytes : Number(rawPayload.total_bytes ?? matchedBytes) const visited = Number(rawPayload.visited_entries) return { scan: makeScanResult(files, totalFilesCount, totalBytesCount, subdirs, { @@ -1817,8 +1869,6 @@ export async function writeRealClipboardText(text: string, hostOverride?: Dynami const payload = { text: String(text || '') } const res = await callHostTransport('clipboard_copy_text', payload, hostOverride) if (res.ok) return true - const fallbackRes = await callHostTransport('clipboard_write_text', payload, hostOverride) - if (fallbackRes.ok) return true try { if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) { await navigator.clipboard.writeText(String(text || '')) diff --git a/extensions/data-recovery/THIRD_PARTY_NOTICES.txt b/extensions/data-recovery/THIRD_PARTY_NOTICES.txt new file mode 100644 index 00000000..5ba79b09 --- /dev/null +++ b/extensions/data-recovery/THIRD_PARTY_NOTICES.txt @@ -0,0 +1,38 @@ +THIRD-PARTY SOFTWARE NOTICES AND INFORMATION +============================================ + +Component: ZTools Data Recovery Plugin (`data-recovery` / `lib/DataRecoveryPlugin.dll`) +Audit Date: 2026-11-27 + +This plugin bundles and invokes `lib/DataRecoveryPlugin.dll`, which statically links the following +third-party open-source components. A complete file-by-file license audit confirmed that NO GPL, +AGPL, or LGPL copyleft components are linked. + +1. The Sleuth Kit (libtsk) + - Copyright (c) 2002-2024 Brian Carrier, Basis Technology, Sleuth Kit Labs, LLC, @stake Inc., + and IBM Corporation. + - Licenses: Common Public License 1.0 (CPL-1.0) and IBM Public License 1.0 (IPL-1.0). + - Upstream source: https://github.com/sleuthkit/sleuthkit + +2. CrossGuid (`guid.h` / `guid.cpp`, bundled in libtsk) + - Copyright (c) 2014 Graeme Hill. + - License: MIT License. + +3. Apple LZVN Decompressor (`lzvn.c`, bundled in libtsk) + - Copyright (c) 2015-2016 Apple Inc. + - License: 3-Clause BSD License. + +4. Unicode UTF Conversion (`tsk_unicode.c`, bundled in libtsk) + - Copyright (c) 2001-2004 Unicode, Inc. + - License: Unicode, Inc. Permissive Redistribution License. + +5. RSA Data Security MD5 (`md5c.c`, bundled in libtsk) + - Copyright (c) 1991-1992 RSA Data Security, Inc. + - License: RSA Data Security MD5 License (permissive attribution license). + +6. SQLite (`sqlite3.c`) and Public Domain Utilities (`crc.c`, `sha1c.c`, `XGetopt.c`, `decmpfs.c`) + - License: Public Domain. + +7. JsonCpp + - Copyright (c) 2007-2010 Baptiste Lepilleur and The JsonCpp Authors. + - License: MIT License / Public Domain. diff --git a/extensions/data-recovery/plugin.json b/extensions/data-recovery/plugin.json index 709d0bca..2a4fe4c6 100644 --- a/extensions/data-recovery/plugin.json +++ b/extensions/data-recovery/plugin.json @@ -1,10 +1,8 @@ { "id": "data-recovery", "name": "数据恢复", - "description": "列出 Windows 回收站里的文件,把勾选的文件复制到桌面的恢复文件夹", - "version": "2.0.10", - "draft": true, - "draftReason": "客户端目前只能列出 C、D、E 盘回收站里的文件,且只给出回收站内部的 $R 文件名,没有原始文件名、原路径和删除时间,用户难以辨认要找回的文件;也不能扫描已清空回收站、格式化或被覆盖的数据。等客户端能读出回收站文件的原始名称与路径、提供磁盘级的已删除文件扫描能力,并在 Windows 上实测通过后再发布", + "description": "提供快速回收站恢复(解析 $Recycle.Bin $I 元数据还原原始文件名、原路径与删除时间)与管理员级磁盘深度恢复(对接 DataRecoveryPlugin 扫描物理磁盘与分区)", + "version": "2.1.0", "author": "ZTools Team", "entry": "dist/index.js", "icon": "icon.svg", @@ -21,26 +19,40 @@ "system", "shell" ], - "requireAdmin": false, - "nativeComponents": [], + "requireAdmin": true, + "dllloader": "lib/DataRecoveryPlugin.dll", + "minAppVersion": "1.3.0.0", + "nativeComponents": [ + { + "id": "data-recovery-dll", + "kind": "dll", + "targetId": "windows-electron-any", + "arch": "ia32", + "abi": "ztools-native-host/v1", + "protocolVersion": 1, + "entry": "lib/DataRecoveryPlugin.dll" + } + ], "targets": [ { "id": "windows-electron-any", "platform": "windows", "runtime": "electron", - "arch": "any" + "arch": "x64" } ], "defaultLocale": "zh-CN", "i18n": { "en-US": { - "name": "Recycle Bin Recovery", - "description": "List files in the Windows Recycle Bin and copy selected items safely to a recovery folder on your Desktop.", + "name": "Data Recovery", + "description": "Two-tier Windows data recovery: fast Recycle Bin recovery ($I v1/v2 metadata parser restoring original names, paths, and deletion times) and elevated deep disk recovery via DataRecoveryPlugin.", "keywords": [ "recovery", + "data recovery", "recycle bin", "restore", "undelete", + "disk scan", "files", "windows" ] diff --git a/extensions/data-recovery/src/i18n.ts b/extensions/data-recovery/src/i18n.ts index 87ff1374..f6abca67 100644 --- a/extensions/data-recovery/src/i18n.ts +++ b/extensions/data-recovery/src/i18n.ts @@ -4,6 +4,7 @@ const rawT = createTranslator( { "zh-CN": { forbiddenReason: "不能向系统目录写入恢复文件,路径中也不能包含 ..", + sameDriveTargetReason: "恢复输出目录不能位于源待恢复分区({drive}:\\),请改选其他磁盘分区以免覆盖待恢复扇区数据", notInClientMessage: "需要在 ZTools 客户端中使用", catDocumentsName: "文档", catDocumentsSubtitle: "Word / Excel / PPT / PDF / 文本", @@ -17,14 +18,24 @@ const rawT = createTranslator( catOtherSubtitle: "不属于以上类型的文件", hostNoResult: "客户端没有返回结果", scanFailed: "读取回收站失败:{error}", + deepScanFailed: "磁盘深度扫描失败:{error}", + deviceListFailed: "读取物理磁盘列表失败:{error}", + partitionsFailed: "读取磁盘分区失败:{error}", + enumFilesFailed: "查询扫描文件列表失败:{error}", + recoverFailed: "恢复文件失败:{error}", + metadataFailed: "读取文件元数据失败:{error}", + previewFailed: "生成文件预览失败:{error}", + scanHistoryFailed: "读取扫描历史失败:{error}", + scanStatusFailed: "查询扫描状态失败:{error}", + stopScanFailed: "停止扫描失败:{error}", desktopUnavailable: "无法获取桌面路径,不能恢复文件", selectFilesFirst: "请先勾选要恢复的文件", unknownFile: "(未知文件)", invalidFilePath: "文件路径无效", copyFailed: "复制失败", - restoreSuccessMsg: "已将 {count} 个文件 ({size}) 复制到 {dir}", - restoreAllFailedMsg: "恢复失败,{count} 个文件均未复制。{detail}", - restorePartialMsg: "已复制 {okCount} 个文件到 {dir},{failCount} 个失败。{detail}", + restoreSuccessMsg: "已将 {count} 个文件 ({size}) 恢复到 {dir}", + restoreAllFailedMsg: "恢复失败,{count} 个文件均未恢复。{detail}", + restorePartialMsg: "已恢复 {okCount} 个文件到 {dir},{failCount} 个失败。{detail}", restoreSuccessTitle: "恢复完成", restorePartialTitle: "部分文件恢复失败", restoreFailedTitle: "恢复失败", @@ -34,27 +45,47 @@ const rawT = createTranslator( locateFailedTitle: "无法在资源管理器中定位此文件", unknownTarget: "(未知)", selectionSummary: "已勾选 {count} 项 ({size}) · 恢复到 {dir}", - recycleSummary: "回收站文件 {count} 项 ({size}) · {selection}", - copyCheckedAction: "复制已勾选文件到恢复文件夹 ({count} 项)", + recycleSummary: "快速回收站 {count} 项 ({size}) · {selection}", + deepSummary: "磁盘深度恢复 · 设备 {devices} 个 · 已发现 {count} 项 · {selection}", + crossUserPermissionWarning: "已跳过 {count} 个无权访问的其他用户回收站目录(跨用户目录需管理员权限)", + copyCheckedAction: "恢复已勾选文件 ({count} 项)", allRecycleFiles: "全部回收站文件", itemCount: "{count} 项", openRecoveryFolder: "打开恢复文件夹", filterCategoryAction: "筛选「{name}」", + deletedAtSubtitle: "原路径:{path} · 删除于 {time}", modifiedSubtitle: "{path} · 修改于 {time}", locateInExplorer: "在资源管理器中定位此文件", uncheckFile: "取消勾选此文件", checkFile: "勾选此文件", - searchPlaceholder: "搜索文件名、扩展名(如 .docx)...", + searchPlaceholder: "搜索原始文件名、原路径或扩展名(如 .docx)...", rescanAction: "重新扫描", - subListTitle: "回收站文件 ({count} 项 · 已选 {size})", - subListSubtitle: "列表显示回收站内部文件名,恢复出的文件也使用这个名字", - loadingText: "正在读取回收站...", - emptyText: "当前分类下没有回收站文件", - sectionTitle: "文件类型", - sectionSubtitle: "按扩展名分类" + switchToDeepMode: "切换到磁盘深度恢复", + switchToRecycleMode: "切换到快速回收站", + subListTitle: "可恢复文件 ({count} 项 · 已选 {size})", + subListSubtitleRecycle: "已解析 Windows $Recycle.Bin $I 元数据,显示原始文件名与原路径;输出目录须避开源分区", + subListSubtitleDeep: "来自 DataRecoveryPlugin 物理磁盘扫描结果;恢复目标盘符必须与源待恢复分区不同", + loadingText: "正在扫描可恢复文件...", + emptyText: "当前视图下没有可恢复文件", + sectionTitle: "快速回收站(按类型)", + sectionSubtitle: "解析 $Recycle.Bin $I 原始元数据", + deepSectionTitle: "磁盘深度恢复(管理员)", + deepSectionSubtitle: "对接 DataRecoveryPlugin 扫描物理磁盘与分区", + deepDeviceSubtitle: "{type} · {size} · 卷 {volumes}", + deepStartScanAction: "深度扫描此磁盘", + deepStopScanAction: "停止当前扫描", + deepLoadHistoryAction: "查看历史扫描记录", + deepScanStartedTitle: "深度扫描已启动", + deepScanStartedMsg: "扫描任务 {scanId} 正在运行,稍后可刷新文件列表", + deepScanStoppedTitle: "已请求停止扫描", + deepNoDevicesText: "未检测到可访问的物理磁盘(请确认以管理员权限运行)", + deepVolumesUnknown: "无盘符", + deepRecoverStartedTitle: "已提交深度恢复任务", + deepRecoverStartedMsg: "正在将 {count} 个文件恢复到 {dir}" }, "en-US": { forbiddenReason: "Cannot write recovered files to system directories or paths containing ..", + sameDriveTargetReason: "Recovery target directory must not be on source drive ({drive}:\\). Choose another drive to avoid overwriting recoverable sectors.", notInClientMessage: "Requires ZTools client environment", catDocumentsName: "Documents", catDocumentsSubtitle: "Word / Excel / PPT / PDF / Text", @@ -68,14 +99,24 @@ const rawT = createTranslator( catOtherSubtitle: "Files outside above types", hostNoResult: "No result returned from client", scanFailed: "Failed to read Recycle Bin: {error}", + deepScanFailed: "Deep disk scan failed: {error}", + deviceListFailed: "Failed to list physical disks: {error}", + partitionsFailed: "Failed to read disk partitions: {error}", + enumFilesFailed: "Failed to query scanned files: {error}", + recoverFailed: "File recovery failed: {error}", + metadataFailed: "Failed to read file metadata: {error}", + previewFailed: "Failed to preview file: {error}", + scanHistoryFailed: "Failed to load scan history: {error}", + scanStatusFailed: "Failed to query scan status: {error}", + stopScanFailed: "Failed to stop scan: {error}", desktopUnavailable: "Desktop path unavailable; cannot recover files", selectFilesFirst: "Please select files to recover first", unknownFile: "(Unknown file)", invalidFilePath: "Invalid file path", copyFailed: "Copy failed", - restoreSuccessMsg: "Copied {count} file(s) ({size}) to {dir}", - restoreAllFailedMsg: "Recovery failed; {count} file(s) not copied. {detail}", - restorePartialMsg: "Copied {okCount} file(s) to {dir}, {failCount} failed. {detail}", + restoreSuccessMsg: "Recovered {count} file(s) ({size}) to {dir}", + restoreAllFailedMsg: "Recovery failed; {count} file(s) not recovered. {detail}", + restorePartialMsg: "Recovered {okCount} file(s) to {dir}, {failCount} failed. {detail}", restoreSuccessTitle: "Recovery Complete", restorePartialTitle: "Some Files Failed", restoreFailedTitle: "Recovery Failed", @@ -86,32 +127,52 @@ const rawT = createTranslator( unknownTarget: "(Unknown)", selectionSummary: "Checked {count} ({size}) · Target: {dir}", recycleSummary: "Recycle Bin: {count} ({size}) · {selection}", - copyCheckedAction: "Copy Checked Files ({count})", + deepSummary: "Deep Disk Recovery · {devices} disk(s) · {count} file(s) · {selection}", + crossUserPermissionWarning: "Skipped {count} inaccessible other-user Recycle Bin folder(s) (administrator privileges required)", + copyCheckedAction: "Recover Checked Files ({count})", allRecycleFiles: "All Recycle Bin Files", itemCount: "{count} [[count:item|items]]", openRecoveryFolder: "Open Recovery Folder", filterCategoryAction: "Filter \"{name}\"", + deletedAtSubtitle: "Original: {path} · Deleted {time}", modifiedSubtitle: "{path} · Modified {time}", locateInExplorer: "Reveal in Folder", uncheckFile: "Uncheck File", checkFile: "Check File", - searchPlaceholder: "Search filename or extension (e.g. .docx)...", + searchPlaceholder: "Search original filename, path, or extension (e.g. .docx)...", rescanAction: "Rescan", - subListTitle: "Recycle Bin ({count} · Selected {size})", - subListSubtitle: "Shows internal Recycle Bin filenames; recovered files keep these names", - loadingText: "Reading Recycle Bin...", - emptyText: "No Recycle Bin files in this category", - sectionTitle: "File Types", - sectionSubtitle: "Grouped by extension" + switchToDeepMode: "Switch to Deep Disk Recovery", + switchToRecycleMode: "Switch to Fast Recycle Bin", + subListTitle: "Recoverable Files ({count} · Selected {size})", + subListSubtitleRecycle: "Parsed Windows $Recycle.Bin $I metadata with original names and paths; target must differ from source drive", + subListSubtitleDeep: "Results from DataRecoveryPlugin physical disk scan; target drive must differ from source partition", + loadingText: "Scanning recoverable files...", + emptyText: "No recoverable files in this view", + sectionTitle: "Fast Recycle Bin (By Type)", + sectionSubtitle: "Parses $Recycle.Bin $I original metadata", + deepSectionTitle: "Deep Disk Recovery (Admin)", + deepSectionSubtitle: "Physical disks & partitions via DataRecoveryPlugin", + deepDeviceSubtitle: "{type} · {size} · Volumes {volumes}", + deepStartScanAction: "Deep Scan This Disk", + deepStopScanAction: "Stop Current Scan", + deepLoadHistoryAction: "Load Scan History", + deepScanStartedTitle: "Deep Scan Started", + deepScanStartedMsg: "Scan task {scanId} is running; refresh to inspect found files", + deepScanStoppedTitle: "Scan Stop Requested", + deepNoDevicesText: "No accessible physical disks detected (ensure administrator privileges)", + deepVolumesUnknown: "None", + deepRecoverStartedTitle: "Deep Recovery Started", + deepRecoverStartedMsg: "Recovering {count} file(s) to {dir}" } } -) +); + export const t: typeof rawT = (key, params) => { - const out = rawT(key, params) - if (!out.includes('[[')) return out + const out = rawT(key, params); + if (!out.includes("[[")) return out; return out.replace(/\[\[([A-Za-z0-9_.-]+):([^|\]]+)\|([^\]]+)\]\]/g, (_m, k: string, one: string, other: string) => { - const v = params?.[k] - const n = typeof v === 'number' ? v : Number(String(v ?? '').replace(/,/g, '')) - return n === 1 ? one : other - }) -} + const v = params?.[k]; + const n = typeof v === "number" ? v : Number(String(v ?? "").replace(/,/g, "")); + return n === 1 ? one : other; + }); +}; diff --git a/extensions/data-recovery/src/index.ts b/extensions/data-recovery/src/index.ts index 967c1a04..021b5e14 100644 --- a/extensions/data-recovery/src/index.ts +++ b/extensions/data-recovery/src/index.ts @@ -1,9 +1,11 @@ /** - * 回收站文件取回(布局二:左侧文件类型 + 右侧可勾选文件列表) + * 数据恢复插件(布局二:左侧模式/分类/物理磁盘导航 + 右侧可勾选文件列表) * - * - 列出客户端读取到的回收站文件,按扩展名分类;打开时不勾选任何文件 - * - 只复制已勾选的文件到桌面恢复文件夹下新建的子文件夹,不覆盖已有文件,回收站里的文件保持不动 - * - 读取或复制失败时在状态条与提示里如实显示原因 + * 两级恢复模式: + * 1. 快速回收站恢复:解析 Windows $Recycle.Bin\\$I* 二进制元数据(v1/v2), + * 还原原始文件名、原始完整路径、大小与删除时间;跨用户目录权限受限时如实提示。 + * 2. 磁盘深度恢复(管理员):对接 DataRecoveryPlugin 真实 12 个导出接口, + * 扫描物理磁盘与分区,并硬校验恢复目标盘符严禁与源待恢复分区相同。 */ import { @@ -18,22 +20,36 @@ import { useState } from "@ztools/declarative-ui"; import { t } from "./i18n.js"; +import { resolveErrorMessage } from "./error-i18n.js"; import { isRealElectronHost } from "./native-ipc.js"; import { - getNotInClientMessage, - getRecoveryCategories, createEmptyRecoverySnapshot, + enumScanFiles, fetchRecoverableFiles, formatBytes, + getDeviceList, + getNotInClientMessage, + getRecoveryCategories, + getScanHistory, openRecoveryFolder, + recoverDeepFiles, + restoreRunFolderName, restoreSelectedFiles, showRecoveryItem, + startDiskScan, + stopDiskScan, type DataRecoverySnapshot, - type RecoveryCategory + type DeepScannedFileItem, + type PhysicalDiskDevice, + type RecoveryCategory, + type RecoveryMode } from "./logic.js"; +export * from "./logic.js"; + export function DataRecoveryCommand() { useLocale(); + const [mode, setMode] = useState("recycle-bin"); const [snapshot, setSnapshot] = useState(() => isRealElectronHost() ? createEmptyRecoverySnapshot() : createEmptyRecoverySnapshot(getNotInClientMessage()) ); @@ -44,6 +60,14 @@ export function DataRecoveryCommand() { const [lastOutputDir, setLastOutputDir] = useState(""); const [isLoading, setIsLoading] = useState(isRealElectronHost()); + // 磁盘深度恢复状态 + const [devices, setDevices] = useState([]); + const [selectedDeviceId, setSelectedDeviceId] = useState(""); + const [activeScanTaskId, setActiveScanTaskId] = useState(""); + const [activeScanId, setActiveScanId] = useState(""); + const [deepFiles, setDeepFiles] = useState([]); + const [deepError, setDeepError] = useState(""); + const reloadRecoveryList = async () => { setIsLoading(true); try { @@ -51,7 +75,26 @@ export function DataRecoveryCommand() { setSnapshot(data); const existing = new Set(data.items.map((i) => i.id)); setCheckedIds((prev) => prev.filter((id) => existing.has(id))); - setStatusBanner(""); + setStatusBanner(data.permissionWarning || ""); + } finally { + setIsLoading(false); + } + }; + + const reloadDeepDevices = async () => { + setIsLoading(true); + try { + const res = await getDeviceList(); + if (!res.ok) { + setDeepError(resolveErrorMessage(res, t("deepNoDevicesText"))); + setDevices([]); + } else { + setDeepError(""); + setDevices(res.data || []); + if ((res.data || []).length > 0 && !selectedDeviceId) { + setSelectedDeviceId(res.data![0].deviceId); + } + } } finally { setIsLoading(false); } @@ -61,50 +104,169 @@ export function DataRecoveryCommand() { void reloadRecoveryList(); }, []); + const switchMode = async (nextMode: RecoveryMode) => { + setMode(nextMode); + setCheckedIds([]); + setStatusBanner(""); + if (nextMode === "deep-disk") { + await reloadDeepDevices(); + } else { + await reloadRecoveryList(); + } + }; + + const handleStartDeepScan = async (device: PhysicalDiskDevice) => { + setSelectedDeviceId(device.deviceId); + setIsLoading(true); + try { + const taskId = `scan_${Date.now()}`; + const res = await startDiskScan({ + taskId, + deviceId: device.deviceId, + partitionNum: -1, + scanType: "quick", + scanScenario: "deleted" + }); + if (!res.ok || !res.data) { + const errMsg = resolveErrorMessage(res, t("deepScanFailed", { error: t("hostNoResult") })); + setDeepError(errMsg); + showToast({ style: Toast.Style.Failure, title: t("restoreFailedTitle"), message: errMsg }); + return; + } + setDeepError(""); + setActiveScanTaskId(taskId); + setActiveScanId(res.data.scanId); + showToast({ + style: Toast.Style.Success, + title: t("deepScanStartedTitle"), + message: t("deepScanStartedMsg", { scanId: res.data.scanId || taskId }) + }); + if (res.data.scanId) { + const enumRes = await enumScanFiles({ scanId: res.data.scanId, pageIndex: 0, pageSize: 100 }); + if (enumRes.ok && enumRes.data) { + setDeepFiles(enumRes.data.files); + } + } + } finally { + setIsLoading(false); + } + }; + + const handleStopDeepScan = async () => { + if (!activeScanTaskId) return; + const res = await stopDiskScan(activeScanTaskId); + if (res.ok) { + setActiveScanTaskId(""); + showToast({ style: Toast.Style.Success, title: t("deepScanStoppedTitle") }); + } else { + showToast({ style: Toast.Style.Failure, title: t("restoreFailedTitle"), message: res.error }); + } + }; + + const handleLoadScanHistory = async () => { + setIsLoading(true); + try { + const histRes = await getScanHistory(20); + if (!histRes.ok || !histRes.data || histRes.data.length === 0) { + setDeepError(histRes.ok ? t("emptyText") : resolveErrorMessage(histRes, t("emptyText"))); + return; + } + const latest = histRes.data[0]; + setActiveScanId(latest.scanId); + const enumRes = await enumScanFiles({ scanId: latest.scanId, pageIndex: 0, pageSize: 100 }); + if (enumRes.ok && enumRes.data) { + setDeepFiles(enumRes.data.files); + setDeepError(""); + } else { + setDeepError(enumRes.error || ""); + } + } finally { + setIsLoading(false); + } + }; + const keyword = searchText.trim().toLowerCase(); - const visibleItems = snapshot.items.filter((item) => { + + const visibleRecycleItems = snapshot.items.filter((item) => { if (selectedCategory !== "all" && item.category !== selectedCategory) return false; if (keyword) { - const hay = `${item.name} ${item.cachePath} ${item.categoryName}`.toLowerCase(); + const hay = `${item.name} ${item.originalPath || ""} ${item.cachePath} ${item.categoryName}`.toLowerCase(); if (!hay.includes(keyword)) return false; } return true; }); + const visibleDeepItems = deepFiles.filter((item) => { + if (!keyword) return true; + const hay = `${item.name} ${item.path} ${item.type}`.toLowerCase(); + return hay.includes(keyword); + }); + const checkedSet = new Set(checkedIds); - const selectedItems = snapshot.items.filter((item) => checkedSet.has(item.id)); - const selectedBytes = selectedItems.reduce((acc, item) => acc + item.sizeBytes, 0); + + const selectedRecycleItems = snapshot.items.filter((item) => checkedSet.has(item.id)); + const selectedDeepItems = deepFiles.filter((item) => checkedSet.has(item.fileId)); + const selectedCount = mode === "recycle-bin" ? selectedRecycleItems.length : selectedDeepItems.length; + const selectedBytes = + mode === "recycle-bin" + ? selectedRecycleItems.reduce((acc, item) => acc + item.sizeBytes, 0) + : selectedDeepItems.reduce((acc, item) => acc + item.size, 0); const toggleItemCheck = (id: string) => { setCheckedIds((prev) => (prev.includes(id) ? prev.filter((i) => i !== id) : [...prev, id])); }; + const currentVisibleIds = + mode === "recycle-bin" ? visibleRecycleItems.map((i) => i.id) : visibleDeepItems.map((i) => i.fileId); + const toggleAllVisible = () => { - const visibleIds = visibleItems.map((i) => i.id); - const allChecked = visibleIds.length > 0 && visibleIds.every((id) => checkedSet.has(id)); + const allChecked = currentVisibleIds.length > 0 && currentVisibleIds.every((id) => checkedSet.has(id)); if (allChecked) { - const removeSet = new Set(visibleIds); + const removeSet = new Set(currentVisibleIds); setCheckedIds((prev) => prev.filter((id) => !removeSet.has(id))); } else { - setCheckedIds((prev) => Array.from(new Set([...prev, ...visibleIds]))); + setCheckedIds((prev) => Array.from(new Set([...prev, ...currentVisibleIds]))); } }; const handleBatchRestore = async () => { - if (selectedItems.length === 0) { + if (selectedCount === 0) { showToast({ style: Toast.Style.Failure, title: t("selectFilesFirst") }); return; } setIsLoading(true); try { - const res = await restoreSelectedFiles(selectedItems, snapshot.restoreTargetDir); - if (res.outputDir) setLastOutputDir(res.outputDir); - setStatusBanner(res.message); - showToast({ - style: res.ok ? Toast.Style.Success : Toast.Style.Failure, - title: res.ok ? t("restoreSuccessTitle") : res.restoredCount > 0 ? t("restorePartialTitle") : t("restoreFailedTitle"), - message: res.message - }); + if (mode === "recycle-bin") { + const res = await restoreSelectedFiles(selectedRecycleItems, snapshot.restoreTargetDir); + if (res.outputDir) setLastOutputDir(res.outputDir); + setStatusBanner(res.message); + showToast({ + style: res.ok ? Toast.Style.Success : Toast.Style.Failure, + title: res.ok ? t("restoreSuccessTitle") : res.restoredCount > 0 ? t("restorePartialTitle") : t("restoreFailedTitle"), + message: res.message + }); + } else { + const currentDevice = devices.find((d) => d.deviceId === selectedDeviceId); + const sourceDrives = currentDevice ? currentDevice.volumes : []; + const baseDir = snapshot.restoreTargetDir; + const targetPath = baseDir ? `${baseDir}\\${restoreRunFolderName()}` : ""; + const res = await recoverDeepFiles({ + taskId: `recover_${Date.now()}`, + scanId: activeScanId, + fileIds: selectedDeepItems.map((i) => i.fileId), + targetPath, + sourceDrives + }); + if (!res.ok) { + setStatusBanner(res.error || ""); + showToast({ style: Toast.Style.Failure, title: t("restoreFailedTitle"), message: res.error }); + } else { + setLastOutputDir(targetPath); + const msg = t("deepRecoverStartedMsg", { count: selectedDeepItems.length, dir: targetPath }); + setStatusBanner(msg); + showToast({ style: Toast.Style.Success, title: t("deepRecoverStartedTitle"), message: msg }); + } + } } finally { setIsLoading(false); } @@ -130,36 +292,51 @@ export function DataRecoveryCommand() { }; const selectionText = t("selectionSummary", { - count: selectedItems.length, + count: selectedCount, size: formatBytes(selectedBytes), dir: snapshot.restoreTargetDir || t("unknownTarget") }); - const summaryText = snapshot.error - ? snapshot.error - : statusBanner - ? `${statusBanner} · ${selectionText}` - : t("recycleSummary", { - count: snapshot.items.length, - size: formatBytes(snapshot.totalSizeBytes), - selection: selectionText - }); + + const summaryText = + mode === "recycle-bin" + ? snapshot.error + ? snapshot.error + : statusBanner + ? `${statusBanner} · ${selectionText}` + : t("recycleSummary", { + count: snapshot.items.length, + size: formatBytes(snapshot.totalSizeBytes), + selection: selectionText + }) + : deepError + ? deepError + : statusBanner + ? `${statusBanner} · ${selectionText}` + : t("deepSummary", { + devices: devices.length, + count: deepFiles.length, + selection: selectionText + }); const restoreAction = () => Action({ - title: t("copyCheckedAction", { count: selectedItems.length }), + title: t("copyCheckedAction", { count: selectedCount }), icon: Icon.CheckCircle, onAction: handleBatchRestore }); const categories = getRecoveryCategories(); - const leftNavNodes = [ + const recycleNavNodes = [ List.Item({ id: "nav-rec-all", title: t("allRecycleFiles"), subtitle: t("itemCount", { count: snapshot.items.length }), icon: Icon.HardDrive, - onSelect: () => setSelectedCategory("all"), + onSelect: () => { + setMode("recycle-bin"); + setSelectedCategory("all"); + }, accessories: [ { tag: { value: t("itemCount", { count: snapshot.items.length }) } }, { text: formatBytes(snapshot.totalSizeBytes) } @@ -185,7 +362,10 @@ export function DataRecoveryCommand() { title: cat.name, subtitle: cat.subtitle, icon: Icon.Document, - onSelect: () => setSelectedCategory(cat.id), + onSelect: () => { + setMode("recycle-bin"); + setSelectedCategory(cat.id); + }, accessories: [ { progress: ratio }, { tag: { value: t("itemCount", { count: catItems.length }) } }, @@ -196,7 +376,10 @@ export function DataRecoveryCommand() { Action({ title: t("filterCategoryAction", { name: cat.name }), icon: Icon.Filter, - onAction: () => setSelectedCategory(cat.id) + onAction: () => { + setMode("recycle-bin"); + setSelectedCategory(cat.id); + } }), restoreAction() ] @@ -205,44 +388,148 @@ export function DataRecoveryCommand() { }) ]; - const subListItems = visibleItems.map((item) => { - const isChecked = checkedSet.has(item.id); - - return List.Item({ - id: `rec-item-${item.id}`, - title: item.name, - subtitle: item.modifiedText ? t("modifiedSubtitle", { path: item.cachePath, time: item.modifiedText }) : item.cachePath, - icon: Icon.Document, - checkable: true, - checked: isChecked, - onCheckChange: () => toggleItemCheck(item.id), - onToggleCheck: () => toggleItemCheck(item.id), - accessories: [{ tag: { value: item.categoryName } }, { text: formatBytes(item.sizeBytes) }], - actions: ActionPanel({ - children: [ - restoreAction(), - Action({ - title: t("locateInExplorer"), - icon: Icon.Folder, - onAction: () => locateItem(item.cachePath) - }), - Action({ - title: isChecked ? t("uncheckFile") : t("checkFile"), - icon: Icon.CheckCircle, - onAction: () => toggleItemCheck(item.id) - }), - Action({ - title: t("openRecoveryFolder"), - icon: Icon.Folder, - onAction: openOutputFolder + const deepNavNodes = + devices.length > 0 + ? devices.map((device) => + List.Item({ + id: `nav-disk-${device.deviceId}`, + title: device.name, + subtitle: t("deepDeviceSubtitle", { + type: device.type, + size: formatBytes(device.size), + volumes: device.volumes.length > 0 ? device.volumes.map((v) => `${v}:`).join(", ") : t("deepVolumesUnknown") + }), + icon: Icon.HardDrive, + onSelect: () => { + setMode("deep-disk"); + setSelectedDeviceId(device.deviceId); + }, + actions: ActionPanel({ + children: [ + Action({ + title: t("deepStartScanAction"), + icon: Icon.MagnifyingGlass, + onAction: () => handleStartDeepScan(device) + }), + ...(activeScanTaskId + ? [ + Action({ + title: t("deepStopScanAction"), + icon: Icon.Stop, + onAction: handleStopDeepScan + }) + ] + : []), + Action({ + title: t("deepLoadHistoryAction"), + icon: Icon.Clock, + onAction: handleLoadScanHistory + }) + ] + }) }) - ] - }) - }); - }); + ) + : [ + List.Item({ + id: "nav-disk-empty", + title: t("deepSectionTitle"), + subtitle: deepError || t("deepNoDevicesText"), + icon: Icon.HardDrive, + onSelect: () => void switchMode("deep-disk"), + actions: ActionPanel({ + children: [ + Action({ + title: t("rescanAction"), + icon: Icon.ArrowClockwise, + onAction: () => void reloadDeepDevices() + }), + Action({ + title: t("deepLoadHistoryAction"), + icon: Icon.Clock, + onAction: handleLoadScanHistory + }) + ] + }) + }) + ]; - const allChecked = visibleItems.length > 0 && visibleItems.every((i) => checkedSet.has(i.id)); - const someChecked = visibleItems.some((i) => checkedSet.has(i.id)); + const subListItems = + mode === "recycle-bin" + ? visibleRecycleItems.map((item) => { + const isChecked = checkedSet.has(item.id); + const subtitle = + item.originalPath && item.deletedAtText + ? t("deletedAtSubtitle", { path: item.originalPath, time: item.deletedAtText }) + : item.originalPath + ? item.originalPath + : item.modifiedText + ? t("modifiedSubtitle", { path: item.cachePath, time: item.modifiedText }) + : item.cachePath; + + return List.Item({ + id: `rec-item-${item.id}`, + title: item.name, + subtitle, + icon: Icon.Document, + checkable: true, + checked: isChecked, + onCheckChange: () => toggleItemCheck(item.id), + onToggleCheck: () => toggleItemCheck(item.id), + accessories: [{ tag: { value: item.categoryName } }, { text: formatBytes(item.sizeBytes) }], + actions: ActionPanel({ + children: [ + restoreAction(), + Action({ + title: t("locateInExplorer"), + icon: Icon.Folder, + onAction: () => locateItem(item.cachePath) + }), + Action({ + title: isChecked ? t("uncheckFile") : t("checkFile"), + icon: Icon.CheckCircle, + onAction: () => toggleItemCheck(item.id) + }), + Action({ + title: t("openRecoveryFolder"), + icon: Icon.Folder, + onAction: openOutputFolder + }) + ] + }) + }); + }) + : visibleDeepItems.map((item) => { + const isChecked = checkedSet.has(item.fileId); + return List.Item({ + id: `deep-item-${item.fileId}`, + title: item.name, + subtitle: item.path, + icon: Icon.Document, + checkable: true, + checked: isChecked, + onCheckChange: () => toggleItemCheck(item.fileId), + onToggleCheck: () => toggleItemCheck(item.fileId), + accessories: [{ tag: { value: item.type } }, { text: formatBytes(item.size) }], + actions: ActionPanel({ + children: [ + restoreAction(), + Action({ + title: isChecked ? t("uncheckFile") : t("checkFile"), + icon: Icon.CheckCircle, + onAction: () => toggleItemCheck(item.fileId) + }), + Action({ + title: t("openRecoveryFolder"), + icon: Icon.Folder, + onAction: openOutputFolder + }) + ] + }) + }); + }); + + const allChecked = currentVisibleIds.length > 0 && currentVisibleIds.every((id) => checkedSet.has(id)); + const someChecked = currentVisibleIds.some((id) => checkedSet.has(id)); return List({ isLoading, @@ -252,21 +539,34 @@ export function DataRecoveryCommand() { filterBar: { summaryText, actions: [ + { + id: "toggle-mode", + title: mode === "recycle-bin" ? t("switchToDeepMode") : t("switchToRecycleMode"), + style: "secondary", + onAction: () => { + void switchMode(mode === "recycle-bin" ? "deep-disk" : "recycle-bin"); + } + }, { id: "rescan", title: t("rescanAction"), style: "secondary", onAction: () => { - void reloadRecoveryList(); + if (mode === "recycle-bin") { + void reloadRecoveryList(); + } else { + void reloadDeepDevices(); + } } } ] }, subList: { - title: t("subListTitle", { count: visibleItems.length, size: formatBytes(selectedBytes) }), - subtitle: t("subListSubtitle"), - emptyText: snapshot.error || (isLoading ? t("loadingText") : t("emptyText")), - checkable: visibleItems.length > 0, + title: t("subListTitle", { count: currentVisibleIds.length, size: formatBytes(selectedBytes) }), + subtitle: mode === "recycle-bin" ? t("subListSubtitleRecycle") : t("subListSubtitleDeep"), + emptyText: + (mode === "recycle-bin" ? snapshot.error : deepError) || (isLoading ? t("loadingText") : t("emptyText")), + checkable: currentVisibleIds.length > 0, checked: allChecked ? true : someChecked ? "indeterminate" : false, onCheckChange: () => toggleAllVisible(), items: subListItems @@ -275,7 +575,12 @@ export function DataRecoveryCommand() { List.Section({ title: t("sectionTitle"), subtitle: t("sectionSubtitle"), - children: leftNavNodes + children: recycleNavNodes + }), + List.Section({ + title: t("deepSectionTitle"), + subtitle: t("deepSectionSubtitle"), + children: deepNavNodes }) ] }); diff --git a/extensions/data-recovery/src/logic.ts b/extensions/data-recovery/src/logic.ts index 621838f5..1b675447 100644 --- a/extensions/data-recovery/src/logic.ts +++ b/extensions/data-recovery/src/logic.ts @@ -1,31 +1,62 @@ -import { getLocale } from '@ztools/declarative-ui' -type DynamicBridge = ReturnType; -/** - * 回收站文件取回:由客户端列出 Windows 回收站(C、D、E 盘)里的文件,把勾选的文件复制到桌面的恢复文件夹。 - * - * - 列表里是回收站内部的文件名(以 $R 开头),客户端不提供原始文件名、原路径和删除时间,界面也不编造 - * - 不能恢复已清空回收站、格式化或被覆盖的数据 - * - 每次恢复复制到一个新的、以时间命名的子文件夹,不覆盖已有文件;回收站里的文件保持不动 - * - 任何一个文件失败都如实列出原因,不改用其他方式顶替 - */ - +import { getLocale } from "@ztools/declarative-ui"; import { t } from "./i18n.js"; import { + callHostTransport, formatBytes, getRealSystemPath, - invokeHostCapability, + invokePluginService, isRealElectronHost, openRealPath, + probeRealDiskDrives, showRealItemInFolder, type NativeInvocationResult } from "./native-ipc.js"; -import { resolveErrorMessage } from './error-i18n.js' +import { resolveErrorMessage } from "./error-i18n.js"; +import { + FORBIDDEN_TARGET_PATTERN, + decodeBase64ToBytes, + extractDriveLetter, + filetimeToUnixMs, + parseRecycleBinInfoFile, + validateRecoveryOutputTarget, + type ParsedRecycleBinInfo, + type RecoveryTargetValidationResult +} from "./recycle-bin.js"; + +type DynamicBridge = ReturnType; + +export { + FORBIDDEN_TARGET_PATTERN, + decodeBase64ToBytes, + extractDriveLetter, + filetimeToUnixMs, + formatBytes, + parseRecycleBinInfoFile, + validateRecoveryOutputTarget +}; +export type { NativeInvocationResult, ParsedRecycleBinInfo, RecoveryTargetValidationResult }; + +export const DATA_RECOVERY_DLL_PLUGIN = "DataRecoveryPlugin"; + +/** DataRecoveryPlugin.dll 真实导出的全部 12 个业务函数白名单 */ +export const DATA_RECOVERY_DLL_FUNCTIONS = [ + "GetDeviceList", + "GetDeviceListAsync", + "GetPartitions", + "StartScan", + "StopScan", + "EnumFiles", + "EnumFilesAsync", + "RecoverFile", + "GetFileMetadata", + "PreviewFile", + "GetScanStatus", + "GetScanHistory" +] as const; -export { formatBytes }; -export type { NativeInvocationResult }; +export type DataRecoveryDllFunctionName = (typeof DATA_RECOVERY_DLL_FUNCTIONS)[number]; +export type RecoveryMode = "recycle-bin" | "deep-disk"; -export const FORBIDDEN_TARGET_PATTERN = - /(^|[\\/])(Windows|System32|SysWOW64|Program Files|Program Files \(x86\)|\.\.)($|[\\/])/i; export function getNotInClientMessage(): string { return t("notInClientMessage"); } @@ -46,7 +77,12 @@ export interface RecoveryCategoryMeta { const CATEGORY_DEFS: Array<{ id: Exclude; nameKey: "catDocumentsName" | "catImagesName" | "catMediaName" | "catArchivesCodeName" | "catOtherName"; - subtitleKey: "catDocumentsSubtitle" | "catImagesSubtitle" | "catMediaSubtitle" | "catArchivesCodeSubtitle" | "catOtherSubtitle"; + subtitleKey: + | "catDocumentsSubtitle" + | "catImagesSubtitle" + | "catMediaSubtitle" + | "catArchivesCodeSubtitle" + | "catOtherSubtitle"; exts: string[]; }> = [ { @@ -92,29 +128,44 @@ export function getRecoveryCategories(): RecoveryCategoryMeta[] { export interface RecoverableFileItem { id: string; - /** 回收站内部文件名(以 $R 开头,保留扩展名) */ + /** 优先为 $I 元数据还原后的原始文件名,无法读取 $I 时回退回收站内部 $R 文件名 */ name: string; - /** 文件在回收站中的位置 */ + /** 文件在回收站中的真实实体路径($R*) */ cachePath: string; + /** 对应的 $I 元数据文件路径(存在时提供) */ + infoFilePath?: string; + /** 从 $I 解析出的原始完整路径 */ + originalPath?: string; + /** 源所在盘符(大写,如 "C") */ + sourceDrive?: string; category: Exclude; categoryName: string; sizeBytes: number; - /** 文件的修改时间(不是删除时间);客户端没有提供时为空 */ + /** 删除时间(源自 $I FILETIME,无则为空) */ + deletedAtMs?: number; + deletedAtText?: string; + /** 文件修改时间或删除时间展示文本 */ modifiedText: string; + /** 元数据解析状态:parsed=成功解析 $I,raw=未配对或 $I 损坏 */ + metadataStatus: "parsed" | "raw"; } export interface DataRecoverySnapshot { - /** 恢复文件夹(每次恢复在其中新建以时间命名的子文件夹);拿不到桌面路径时为空 */ + /** 推荐恢复目录(自动优先避开与源回收站相同的系统盘);桌面不可用时为空 */ restoreTargetDir: string; items: RecoverableFileItem[]; totalSizeBytes: number; updatedAt: string; + /** 跨用户 SID 目录因普通权限被拒绝时如实记录 */ + inaccessibleSids: string[]; + permissionWarning?: string; error?: string; } export interface RestoreFailure { name: string; error: string; + errorCode?: string; } export interface RestoreResult { @@ -127,12 +178,73 @@ export interface RestoreResult { message: string; } +// ============================================================================ +// 磁盘深度恢复(DataRecoveryPlugin 12 个真实导出函数)类型定义 +// ============================================================================ + +export interface PhysicalDiskDevice { + deviceId: string; + name: string; + size: number; + type: string; + status: string; + fileSystem: string; + volumes: string[]; +} + +export interface DiskPartitionInfo { + partitionNum: number; + start: number; + length: number; + description: string; + type: string; + fileSystem: string; + allocated: boolean; + driveLetter: string; +} + +export interface DeepScannedFileItem { + fileId: string; + id: number; + name: string; + path: string; + size: number; + type: string; + recoverable: boolean; + integrity: string; + isDeleted: boolean; +} + +export interface DeepScanHistoryItem { + scanId: string; + deviceId: string; + deviceName: string; + partitionNum: number; + scanType: string; + scanScenario: string; + startTime: number; + endTime: number | null; + totalFiles: number; + totalSize: number; + status: string; + description: string; + cacheAvailable: boolean; +} + +export interface DeepCallResult { + ok: boolean; + data?: T; + error?: string; + errorCode?: string; +} + export function createEmptyRecoverySnapshot(error?: string): DataRecoverySnapshot { return { restoreTargetDir: "", items: [], totalSizeBytes: 0, updatedAt: "", + inaccessibleSids: [], ...(error ? { error } : {}) }; } @@ -154,6 +266,20 @@ function errorText(err: unknown): string { return err instanceof Error ? err.message : String(err); } +function isAccessDeniedError(error?: string, errorCode?: string): boolean { + const code = String(errorCode || "").toUpperCase(); + if (code === "PERMISSION_DENIED" || code === "EACCES" || code === "EPERM" || code === "ACCESS_DENIED") { + return true; + } + const msg = String(error || ""); + return /EACCES|EPERM|access\s*denied|permission\s*denied/i.test(msg); +} + +function formatTimestampMs(ms: number): string { + if (!Number.isFinite(ms) || ms <= 0) return ""; + return new Date(ms).toLocaleString(getLocale()); +} + function formatModified(raw: DynamicBridge): string { const iso = typeof raw?.modifiedAt === "string" ? Date.parse(raw.modifiedAt) : NaN; const ms = Number.isFinite(iso) ? iso : Number(raw?.deletedAtMs); @@ -161,61 +287,224 @@ function formatModified(raw: DynamicBridge): string { return new Date(ms).toLocaleString(getLocale()); } -export async function fetchRecoverableFiles(hostBridge?: DynamicBridge): Promise { +interface RawDirEntry { + name: string; + path: string; + isDirectory: boolean; + sizeBytes: number; + modifiedAtMs: number; +} + +function normalizeDirEntries(parentDir: string, payload: DynamicBridge): RawDirEntry[] { + const rawList: DynamicBridge[] = Array.isArray(payload) + ? payload + : Array.isArray(payload?.entries) + ? payload.entries + : Array.isArray(payload?.items) + ? payload.items + : Array.isArray(payload?.files) + ? payload.files + : []; + const base = parentDir.replace(/[\\/]+$/, ""); + const entries: RawDirEntry[] = []; + for (const item of rawList) { + if (!item || typeof item !== "object") continue; + const rawName = String(item.name || item.fileName || "").trim(); + const rawPath = String(item.path || item.fullPath || (rawName ? `${base}\\${rawName}` : "")).trim(); + const name = rawName || rawPath.split(/[\\/]/).pop() || ""; + if (!name || !rawPath) continue; + const isDirectory = Boolean(item.isDirectory ?? item.isDir ?? item.is_dir ?? item.type === "directory"); + const sizeNum = Number(item.sizeBytes ?? item.size ?? 0); + const iso = typeof item.modifiedAt === "string" ? Date.parse(item.modifiedAt) : NaN; + const rawMtime = Number(item.mtimeMs ?? item.mtime ?? 0); + const modifiedAtMs = Number.isFinite(iso) ? iso : Number.isFinite(rawMtime) && rawMtime > 0 ? rawMtime : 0; + entries.push({ + name, + path: rawPath, + isDirectory, + sizeBytes: Number.isFinite(sizeNum) && sizeNum >= 0 ? sizeNum : 0, + modifiedAtMs + }); + } + return entries; +} + +function extractBase64Content(payload: DynamicBridge): string { + if (typeof payload === "string") return payload; + if (payload && typeof payload === "object") { + if (typeof payload.content === "string") return payload.content; + if (typeof payload.data === "string") return payload.data; + if (typeof payload.base64 === "string") return payload.base64; + } + return ""; +} + +/** + * 模式 ①:快速回收站恢复扫描。 + * 遍历各盘符 `$Recycle.Bin\`,配对读取 `$I*` 二进制头(v1/v2)还原原始文件名、原完整路径、 + * 原始大小与 FILETIME 删除时间;跨用户 SID 目录遇权限拒绝时如实记录并提示需管理员权限,绝不造假。 + */ +export async function scanRecycleBinFast( + hostBridge?: DynamicBridge, + driveLetters?: string[] +): Promise { if (!hasClientHost(hostBridge)) { return createEmptyRecoverySnapshot(getNotInClientMessage()); } + try { - const [desktop, hostScanRes] = await Promise.all([ - getRealSystemPath("desktop", hostBridge), - invokeHostCapability("recovery.scanDeletedFiles", {}, hostBridge) - ]); + const desktop = await getRealSystemPath("desktop", hostBridge); const restoreTargetDir = desktop ? `${desktop.replace(/[\\/]+$/, "")}\\${RESTORE_FOLDER_NAME}` : ""; - if (!hostScanRes.ok || !hostScanRes.data) { - return { - ...createEmptyRecoverySnapshot( - t("scanFailed", { error: resolveErrorMessage(hostScanRes, t("hostNoResult")) }) - ), - restoreTargetDir - }; + let candidateDrives: string[] = []; + if (Array.isArray(driveLetters) && driveLetters.length > 0) { + candidateDrives = driveLetters + .map((d) => extractDriveLetter(d)) + .filter((d): d is string => Boolean(d)); + } else { + const probed = await probeRealDiskDrives(["C", "D", "E", "F", "G"], hostBridge); + candidateDrives = probed + .map((d) => extractDriveLetter(d.drive)) + .filter((d): d is string => Boolean(d)); + if (candidateDrives.length === 0) { + candidateDrives = ["C", "D", "E"]; + } } - const data = hostScanRes.data; - const rawItems: DynamicBridge[] = Array.isArray(data) - ? data - : Array.isArray(data.items) - ? data.items - : Array.isArray(data.files) - ? data.files - : []; + candidateDrives = Array.from(new Set(candidateDrives)); const items: RecoverableFileItem[] = []; const seen = new Set(); - for (const raw of rawItems) { - const cachePath = String(raw?.cachePath || raw?.path || raw?.sourcePath || "").trim(); - if (!cachePath) continue; - const key = cachePath.toLowerCase(); - if (seen.has(key)) continue; - seen.add(key); - const name = String(raw?.name || cachePath.split(/[\\/]/).pop() || ""); - const extMatch = name.match(/\.[^.\\/]+$/); - const cat = classifyRecoveryExt(extMatch ? extMatch[0] : ""); - items.push({ - id: String(raw?.id || `rec_${items.length}`), - name, - cachePath, - category: cat.id, - categoryName: cat.name, - sizeBytes: Math.max(0, Number(raw?.sizeBytes ?? raw?.size ?? 0) || 0), - modifiedText: formatModified(raw) - }); + const inaccessibleSids: string[] = []; + let readSuccessDrives = 0; + let firstFatalError = ""; + + for (const drive of candidateDrives) { + const recycleRoot = `${drive}:\\$Recycle.Bin`; + const rootRes = await callHostTransport( + "filesystem_get_directory_contents", + { path: recycleRoot }, + hostBridge + ); + + if (!rootRes.ok) { + if (isAccessDeniedError(rootRes.error, rootRes.errorCode)) { + inaccessibleSids.push(recycleRoot); + } else if (!firstFatalError && rootRes.errorCode !== "FILE_NOT_FOUND" && !/ENOENT|not\s*found/i.test(String(rootRes.error || ""))) { + firstFatalError = resolveErrorMessage(rootRes, t("hostNoResult")); + } + continue; + } + + readSuccessDrives += 1; + const sidDirs = normalizeDirEntries(recycleRoot, rootRes.data).filter( + (entry) => entry.isDirectory && /^S-1-/i.test(entry.name) + ); + + for (const sidDir of sidDirs) { + const sidRes = await callHostTransport( + "filesystem_get_directory_contents", + { path: sidDir.path }, + hostBridge + ); + if (!sidRes.ok) { + if (isAccessDeniedError(sidRes.error, sidRes.errorCode)) { + inaccessibleSids.push(sidDir.path); + } + continue; + } + + const dirEntries = normalizeDirEntries(sidDir.path, sidRes.data); + const infoBySuffix = new Map(); + const dataEntries: RawDirEntry[] = []; + + for (const entry of dirEntries) { + if (entry.name.startsWith("$I") && !entry.isDirectory) { + infoBySuffix.set(entry.name.slice(2).toLowerCase(), entry); + } else if (entry.name.startsWith("$R")) { + dataEntries.push(entry); + } + } + + for (const dataEntry of dataEntries) { + const dedupKey = dataEntry.path.toLowerCase(); + if (seen.has(dedupKey)) continue; + seen.add(dedupKey); + + const suffixKey = dataEntry.name.slice(2).toLowerCase(); + const infoEntry = infoBySuffix.get(suffixKey); + + let displayName = dataEntry.name; + let originalPath: string | undefined; + let sizeBytes = dataEntry.sizeBytes; + let deletedAtMs = 0; + let metadataStatus: "parsed" | "raw" = "raw"; + + if (infoEntry) { + const readInfoRes = await callHostTransport( + "filesystem_read_file", + { path: infoEntry.path, encoding: "base64" }, + hostBridge + ); + if (readInfoRes.ok) { + const b64 = extractBase64Content(readInfoRes.data); + const rawBytes = decodeBase64ToBytes(b64); + if (rawBytes) { + const parsed = parseRecycleBinInfoFile(rawBytes); + if (parsed.ok) { + displayName = parsed.originalName; + originalPath = parsed.originalPath; + if (parsed.originalSizeBytes >= 0) { + sizeBytes = parsed.originalSizeBytes; + } + deletedAtMs = parsed.deletedAtMs; + metadataStatus = "parsed"; + } + } + } + } + + const extMatch = displayName.match(/\.[^.\\/]+$/); + const cat = classifyRecoveryExt(extMatch ? extMatch[0] : ""); + const deletedAtText = deletedAtMs > 0 ? formatTimestampMs(deletedAtMs) : ""; + const modifiedText = deletedAtText || (dataEntry.modifiedAtMs > 0 ? formatTimestampMs(dataEntry.modifiedAtMs) : ""); + + items.push({ + id: `rb_${drive}_${items.length}`, + name: displayName, + cachePath: dataEntry.path, + ...(infoEntry ? { infoFilePath: infoEntry.path } : {}), + ...(originalPath ? { originalPath } : {}), + sourceDrive: drive, + category: cat.id, + categoryName: cat.name, + sizeBytes: Math.max(0, sizeBytes), + ...(deletedAtMs > 0 ? { deletedAtMs, deletedAtText } : {}), + modifiedText, + metadataStatus + }); + } + } + } + + const permissionWarning = + inaccessibleSids.length > 0 + ? t("crossUserPermissionWarning", { count: inaccessibleSids.length }) + : undefined; + + if (readSuccessDrives === 0 && inaccessibleSids.length === 0 && firstFatalError) { + return { + ...createEmptyRecoverySnapshot(t("scanFailed", { error: firstFatalError })), + restoreTargetDir + }; } return { restoreTargetDir, items, - totalSizeBytes: items.reduce((s, i) => s + i.sizeBytes, 0), + totalSizeBytes: items.reduce((sum, item) => sum + item.sizeBytes, 0), updatedAt: new Date().toLocaleTimeString(getLocale()), + inaccessibleSids, + ...(permissionWarning ? { permissionWarning } : {}), ...(restoreTargetDir ? {} : { error: t("desktopUnavailable") }) }; } catch (err) { @@ -223,7 +512,8 @@ export async function fetchRecoverableFiles(hostBridge?: DynamicBridge): Promise } } -export const scanRecoverableFiles = fetchRecoverableFiles; +export const fetchRecoverableFiles = scanRecycleBinFast; +export const scanRecoverableFiles = scanRecycleBinFast; function pad(n: number, width = 2): string { return String(n).padStart(width, "0"); @@ -255,6 +545,11 @@ function uniqueName(name: string, used: Set): string { } } +/** + * 恢复选中的回收站文件: + * - 硬校验输出目录严禁位于系统目录或源待恢复文件所在分区; + * - 逐个通过宿主 `filesystem_copy_file` 复制到带时间戳的新建子文件夹,不删除回收站原文件。 + */ export async function restoreSelectedFiles( items: RecoverableFileItem[], restoreDir: string, @@ -271,11 +566,21 @@ export async function restoreSelectedFiles( outputDir: "", message }); - if (!baseDir) return empty(t("desktopUnavailable")); - if (FORBIDDEN_TARGET_PATTERN.test(baseDir)) return empty(getForbiddenReason()); + if (!items || items.length === 0) return empty(t("selectFilesFirst")); + const sourceDrives = items + .map((item) => item.sourceDrive || extractDriveLetter(item.cachePath) || "") + .filter(Boolean); + + const targetCheck = validateRecoveryOutputTarget(sourceDrives, baseDir); + if (!targetCheck.ok) { + return empty(targetCheck.error || getForbiddenReason()); + } + const outputDir = `${baseDir}\\${restoreRunFolderName(now)}`; + await callHostTransport("filesystem_create_directory", { path: outputDir }, hostOverride); + const used = new Set(); const restoredPaths: string[] = []; const failed: RestoreFailure[] = []; @@ -292,17 +597,28 @@ export async function restoreSelectedFiles( failed.push({ name, error: getForbiddenReason() }); continue; } + + const perItemDriveCheck = validateRecoveryOutputTarget(src, outputDir); + if (!perItemDriveCheck.ok) { + failed.push({ + name, + error: perItemDriveCheck.error || getForbiddenReason(), + ...(perItemDriveCheck.errorCode ? { errorCode: perItemDriveCheck.errorCode } : {}) + }); + continue; + } + const dest = `${outputDir}\\${uniqueName(name, used)}`; - const res = await invokeHostCapability( - "recovery.restoreFile", - { sourcePath: src, targetPath: dest }, + const copyRes = await callHostTransport( + "filesystem_copy_file", + { sourcePath: src, destPath: dest }, hostOverride ); - if (res.ok) { - restoredPaths.push(String(res.data?.targetPath || dest)); + if (copyRes.ok) { + restoredPaths.push(dest); restoredBytes += item.sizeBytes; } else { - failed.push({ name, error: resolveErrorMessage(res, t("copyFailed")) }); + failed.push({ name, error: resolveErrorMessage(copyRes, t("copyFailed")) }); } } @@ -336,6 +652,400 @@ export async function restoreSelectedFiles( }; } +// ============================================================================ +// 模式 ②:磁盘深度恢复 —— 对接 DataRecoveryPlugin 全部 12 个真实导出函数 +// ============================================================================ + +async function callDataRecoveryDll( + func: DataRecoveryDllFunctionName, + params: Record, + fallbackErrorKey: + | "deviceListFailed" + | "partitionsFailed" + | "deepScanFailed" + | "stopScanFailed" + | "enumFilesFailed" + | "recoverFailed" + | "metadataFailed" + | "previewFailed" + | "scanStatusFailed" + | "scanHistoryFailed", + hostOverride?: DynamicBridge, + useCallbackChannel = false +): Promise> { + if (!hasClientHost(hostOverride)) { + return { ok: false, error: getNotInClientMessage(), errorCode: "NO_HOST" }; + } + + if (useCallbackChannel) { + const cbRes = await callHostTransport( + "dllplugin_call_with_callback", + { plugin: DATA_RECOVERY_DLL_PLUGIN, func, params }, + hostOverride + ); + if (!cbRes.ok) { + const msg = resolveErrorMessage(cbRes, t("hostNoResult")); + return { + ok: false, + error: t(fallbackErrorKey, { error: msg }), + ...(cbRes.errorCode ? { errorCode: cbRes.errorCode } : {}) + }; + } + const inner = cbRes.data; + if (inner && typeof inner === "object" && (inner.success === false || inner.ok === false)) { + const msg = resolveErrorMessage(inner, t("hostNoResult")); + return { + ok: false, + error: t(fallbackErrorKey, { error: msg }), + ...(typeof inner.errorCode === "string" ? { errorCode: inner.errorCode } : {}) + }; + } + return { ok: true, data: inner as T }; + } + + const res = await invokePluginService(DATA_RECOVERY_DLL_PLUGIN, func, params, hostOverride); + if (!res.ok || (res.data && typeof res.data === "object" && (res.data.success === false || res.data.ok === false))) { + const errSource = res.data && typeof res.data === "object" && res.data.error ? res.data : res; + const msg = resolveErrorMessage(errSource, t("hostNoResult")); + const code = + typeof res.data?.errorCode === "string" + ? res.data.errorCode + : res.errorCode; + return { + ok: false, + error: t(fallbackErrorKey, { error: msg }), + ...(code ? { errorCode: code } : {}) + }; + } + return { ok: true, data: res.data as T }; +} + +/** 1/12: GetDeviceList(同步获取物理磁盘与卷列表) */ +export async function getDeviceList(hostOverride?: DynamicBridge): Promise> { + const res = await callDataRecoveryDll("GetDeviceList", {}, "deviceListFailed", hostOverride, false); + if (!res.ok) return { ok: false, error: res.error, errorCode: res.errorCode }; + const rawDevices: DynamicBridge[] = Array.isArray(res.data?.devices) ? res.data.devices : []; + const devices: PhysicalDiskDevice[] = rawDevices + .filter((d) => d && typeof d === "object" && typeof d.deviceId === "string" && d.deviceId.trim().length > 0) + .map((d) => ({ + deviceId: String(d.deviceId), + name: String(d.name || d.deviceId), + size: Math.max(0, Number(d.size ?? 0) || 0), + type: String(d.type || "other"), + status: String(d.status || "normal"), + fileSystem: String(d.fileSystem || ""), + volumes: Array.isArray(d.volumes) + ? d.volumes + .map((v: DynamicBridge) => (typeof v === "string" ? v : String(v?.letter || ""))) + .map((v: string) => extractDriveLetter(v) || "") + .filter(Boolean) + : [] + })); + return { ok: true, data: devices }; +} + +/** 2/12: GetDeviceListAsync(带回调异步获取物理磁盘列表) */ +export async function getDeviceListAsync( + taskId: string, + hostOverride?: DynamicBridge +): Promise> { + return callDataRecoveryDll( + "GetDeviceListAsync", + { taskId }, + "deviceListFailed", + hostOverride, + true + ); +} + +/** 3/12: GetPartitions(读取指定物理磁盘的分区列表) */ +export async function getPartitions( + deviceId: string, + hostOverride?: DynamicBridge +): Promise> { + const res = await callDataRecoveryDll( + "GetPartitions", + { deviceId }, + "partitionsFailed", + hostOverride, + false + ); + if (!res.ok) return { ok: false, error: res.error, errorCode: res.errorCode }; + const rawList: DynamicBridge[] = Array.isArray(res.data?.partitions) ? res.data.partitions : []; + const partitions: DiskPartitionInfo[] = rawList + .filter((p) => p && typeof p === "object") + .map((p) => ({ + partitionNum: typeof p.partitionNum === "number" && Number.isFinite(p.partitionNum) ? p.partitionNum : -1, + start: Math.max(0, Number(p.start ?? 0) || 0), + length: Math.max(0, Number(p.length ?? 0) || 0), + description: String(p.description || ""), + type: String(p.type || ""), + fileSystem: String(p.fileSystem || ""), + allocated: Boolean(p.allocated), + driveLetter: extractDriveLetter(String(p.driveLetter || "")) || "" + })); + return { ok: true, data: partitions }; +} + +/** 4/12: StartScan(启动物理磁盘或指定分区的深度扫描任务) */ +export async function startDiskScan( + params: { + taskId: string; + deviceId: string; + partitionNum?: number; + scanType?: "quick" | "deep" | "raw"; + scanScenario?: string; + }, + hostOverride?: DynamicBridge +): Promise> { + const partitionNum = + typeof params.partitionNum === "number" && Number.isFinite(params.partitionNum) ? params.partitionNum : -1; + const payload = { + taskId: params.taskId, + deviceId: params.deviceId, + partitionNum, + scanType: params.scanType || "quick", + scanScenario: params.scanScenario || "deleted" + }; + const res = await callDataRecoveryDll("StartScan", payload, "deepScanFailed", hostOverride, true); + if (!res.ok) return { ok: false, error: res.error, errorCode: res.errorCode }; + return { + ok: true, + data: { + scanId: String(res.data?.scanId || ""), + taskId: params.taskId + } + }; +} + +/** 5/12: StopScan(停止指定扫描任务) */ +export async function stopDiskScan( + taskId: string, + hostOverride?: DynamicBridge +): Promise> { + const res = await callDataRecoveryDll("StopScan", { taskId }, "stopScanFailed", hostOverride, false); + if (!res.ok) return { ok: false, error: res.error, errorCode: res.errorCode }; + return { ok: true, data: { message: String(res.data?.message || "Scan stopped") } }; +} + +function parseDeepFileRows(data: DynamicBridge): { files: DeepScannedFileItem[]; totalCount: number } { + const rawFiles: DynamicBridge[] = Array.isArray(data?.files) ? data.files : []; + const files: DeepScannedFileItem[] = rawFiles + .filter((f) => f && typeof f === "object") + .map((f) => ({ + fileId: String(f.fileId ?? f.id ?? ""), + id: Number(f.id ?? f.fileId ?? 0) || 0, + name: String(f.name || ""), + path: String(f.path || "/"), + size: Math.max(0, Number(f.size ?? 0) || 0), + type: String(f.type || "other"), + recoverable: f.recoverable !== false, + integrity: String(f.integrity || "good"), + isDeleted: Boolean(f.isDeleted) + })); + const totalCount = + typeof data?.totalCount === "number" && Number.isFinite(data.totalCount) ? data.totalCount : files.length; + return { files, totalCount }; +} + +/** 6/12: EnumFiles(同步分页查询扫描数据库中的文件) */ +export async function enumScanFiles( + params: { + scanId: string; + pageIndex?: number; + pageSize?: number; + fileType?: string; + searchKeyword?: string; + }, + hostOverride?: DynamicBridge +): Promise> { + const payload = { + scanId: params.scanId, + pageIndex: typeof params.pageIndex === "number" && Number.isFinite(params.pageIndex) ? params.pageIndex : 0, + pageSize: typeof params.pageSize === "number" && Number.isFinite(params.pageSize) ? params.pageSize : 100, + fileType: params.fileType || "all", + searchKeyword: params.searchKeyword || "" + }; + const res = await callDataRecoveryDll("EnumFiles", payload, "enumFilesFailed", hostOverride, false); + if (!res.ok) return { ok: false, error: res.error, errorCode: res.errorCode }; + return { ok: true, data: parseDeepFileRows(res.data) }; +} + +/** 7/12: EnumFilesAsync(异步回调查询扫描数据库中的文件) */ +export async function enumScanFilesAsync( + params: { + taskId: string; + scanId: string; + pageIndex?: number; + pageSize?: number; + fileType?: string; + searchKeyword?: string; + }, + hostOverride?: DynamicBridge +): Promise> { + const payload = { + taskId: params.taskId, + scanId: params.scanId, + pageIndex: typeof params.pageIndex === "number" && Number.isFinite(params.pageIndex) ? params.pageIndex : 0, + pageSize: typeof params.pageSize === "number" && Number.isFinite(params.pageSize) ? params.pageSize : 100, + fileType: params.fileType || "all", + searchKeyword: params.searchKeyword || "" + }; + return callDataRecoveryDll("EnumFilesAsync", payload, "enumFilesFailed", hostOverride, true); +} + +/** + * 8/12: RecoverFile(将扫描结果中的指定文件恢复到目标目录) + * 硬约束:调用 DLL 前必须通过 `validateRecoveryOutputTarget` 校验目标目录盘符严禁落在源待恢复分区! + */ +export async function recoverDeepFiles( + params: { + taskId: string; + scanId: string; + fileIds: string[]; + targetPath: string; + sourceDrives: string | string[]; + options?: { skipExisting?: boolean; overwriteExisting?: boolean }; + }, + hostOverride?: DynamicBridge +): Promise> { + const validation = validateRecoveryOutputTarget(params.sourceDrives, params.targetPath); + if (!validation.ok) { + return { + ok: false, + error: validation.error || getForbiddenReason(), + errorCode: validation.errorCode + }; + } + if (!Array.isArray(params.fileIds) || params.fileIds.length === 0) { + return { ok: false, error: t("selectFilesFirst"), errorCode: "EMPTY_SELECTION" }; + } + + const payload = { + taskId: params.taskId, + scanId: params.scanId, + fileIds: params.fileIds, + targetPath: params.targetPath, + options: params.options || { skipExisting: false, overwriteExisting: false } + }; + const res = await callDataRecoveryDll("RecoverFile", payload, "recoverFailed", hostOverride, true); + if (!res.ok) return { ok: false, error: res.error, errorCode: res.errorCode }; + return { + ok: true, + data: { + message: String(res.data?.message || "Recovery started"), + targetPath: params.targetPath + } + }; +} + +/** 9/12: GetFileMetadata(获取指定扫描文件的元数据详情) */ +export async function getDeepFileMetadata( + scanId: string, + fileId: string, + hostOverride?: DynamicBridge +): Promise> { + const res = await callDataRecoveryDll( + "GetFileMetadata", + { scanId, fileId }, + "metadataFailed", + hostOverride, + false + ); + if (!res.ok) return { ok: false, error: res.error, errorCode: res.errorCode }; + const d = res.data || {}; + return { + ok: true, + data: { + fileId, + id: Number(fileId) || 0, + name: String(d.name || ""), + path: String(d.path || "/"), + size: Math.max(0, Number(d.size ?? 0) || 0), + type: String(d.type || "other"), + recoverable: d.recoverable !== false, + integrity: String(d.integrity || "good"), + isDeleted: Boolean(d.isDeleted) + } + }; +} + +/** 10/12: PreviewFile(提取图片类扫描文件的临时预览路径) */ +export async function previewDeepFile( + scanId: string, + fileId: string, + hostOverride?: DynamicBridge +): Promise> { + const res = await callDataRecoveryDll( + "PreviewFile", + { scanId, fileId }, + "previewFailed", + hostOverride, + false + ); + if (!res.ok) return { ok: false, error: res.error, errorCode: res.errorCode }; + return { + ok: true, + data: { + previewPath: String(res.data?.previewPath || ""), + fileType: String(res.data?.fileType || "") + } + }; +} + +/** 11/12: GetScanStatus(查询指定扫描任务运行状态) */ +export async function getScanStatus( + taskId: string, + hostOverride?: DynamicBridge +): Promise> { + const res = await callDataRecoveryDll("GetScanStatus", { taskId }, "scanStatusFailed", hostOverride, false); + if (!res.ok) return { ok: false, error: res.error, errorCode: res.errorCode }; + const d = res.data || {}; + return { + ok: true, + data: { + scanning: Boolean(d.scanning), + ...(typeof d.scanId === "string" ? { scanId: d.scanId } : {}), + ...(typeof d.deviceId === "string" ? { deviceId: d.deviceId } : {}), + ...(typeof d.scanType === "string" ? { scanType: d.scanType } : {}) + } + }; +} + +/** 12/12: GetScanHistory(读取历史深度扫描记录) */ +export async function getScanHistory( + limit = 100, + hostOverride?: DynamicBridge +): Promise> { + const res = await callDataRecoveryDll( + "GetScanHistory", + { limit }, + "scanHistoryFailed", + hostOverride, + false + ); + if (!res.ok) return { ok: false, error: res.error, errorCode: res.errorCode }; + const rawList: DynamicBridge[] = Array.isArray(res.data?.history) ? res.data.history : []; + const history: DeepScanHistoryItem[] = rawList + .filter((h) => h && typeof h === "object") + .map((h) => ({ + scanId: String(h.scanId || ""), + deviceId: String(h.deviceId || ""), + deviceName: String(h.deviceName || h.deviceId || ""), + partitionNum: typeof h.partitionNum === "number" && Number.isFinite(h.partitionNum) ? h.partitionNum : -1, + scanType: String(h.scanType || "quick"), + scanScenario: String(h.scanScenario || "deleted"), + startTime: Number(h.startTime ?? 0) || 0, + endTime: typeof h.endTime === "number" && Number.isFinite(h.endTime) ? h.endTime : null, + totalFiles: Math.max(0, Number(h.totalFiles ?? 0) || 0), + totalSize: Math.max(0, Number(h.totalSize ?? 0) || 0), + status: String(h.status || ""), + description: String(h.description || ""), + cacheAvailable: Boolean(h.cacheAvailable) + })); + return { ok: true, data: history }; +} + export async function showRecoveryItem(targetPath: string, hostBridge?: DynamicBridge): Promise { if (!targetPath) return false; return showRealItemInFolder(targetPath, hostBridge); @@ -345,3 +1055,5 @@ export async function openRecoveryFolder(dirPath: string, hostBridge?: DynamicBr if (!dirPath) return false; return openRealPath(dirPath, hostBridge); } + +export { formatModified }; diff --git a/extensions/data-recovery/src/native-ipc.ts b/extensions/data-recovery/src/native-ipc.ts index 51576b99..13643277 100644 --- a/extensions/data-recovery/src/native-ipc.ts +++ b/extensions/data-recovery/src/native-ipc.ts @@ -174,11 +174,13 @@ function normalizeMethodResult(method: string, payload: DynamicBridge): DynamicB if (method === 'system_get_battery_status') { // 宿主约定 percent 超出 0-100(如 255)表示无电池或电量未知,不能改写成 100% + // 若宿主明确给出 hasBattery 布尔值,必须原样保留,仅在缺失时按合法电量推算 const rawPct = payload.percent - const hasBattery = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const validPct = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const hasBattery = typeof payload.hasBattery === 'boolean' ? payload.hasBattery : validPct return { ...payload, - percent: hasBattery ? rawPct : null, + percent: validPct ? rawPct : null, hasBattery } } @@ -489,6 +491,8 @@ export interface RealDirectoryScanResult extends Iterable approximate?: boolean /** 宿主实际遍历的条目数 */ visitedEntries?: number + /** 目录本身不存在(ENOENT) */ + missing?: boolean /** 读取失败的真实原因;已有文件仍可使用,但不能当作完整结果。 */ error?: string } @@ -497,6 +501,7 @@ interface ScanResultMeta { truncated?: boolean approximate?: boolean visitedEntries?: number + missing?: boolean } export interface ScanDirectoryTreeOptions { @@ -504,6 +509,10 @@ export interface ScanDirectoryTreeOptions { maxFiles?: number collectTopN?: number filterExt?: RegExp + /** 为 true 时,目录本身不存在(ENOENT)按空目录处理,不返回 error(权限拒绝/读取失败仍照常报错) */ + ignoreMissing?: boolean + /** Top-N 保留与排序方式:默认按体积降序,下载/录屏等时效场景可传 mtime-desc */ + sortBy?: 'size-desc' | 'mtime-desc' hostOverride?: DynamicBridge } @@ -519,8 +528,9 @@ function normalizeIndexedFileEntry(f: DynamicBridge): RealIndexedFileEntry { const sz = Number(f?.size ?? f?.sizeBytes ?? 0) const isDir = Boolean(f?.is_dir || f?.isDir || f?.isDirectory) const rawMtime = Number(f?.mtime ?? f?.mtimeMs ?? 0) - const mtimeMs = rawMtime > 1e11 ? rawMtime : rawMtime > 0 ? rawMtime * 1000 : Date.now() - const mtimeSec = rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime + const validMtime = Number.isFinite(rawMtime) && rawMtime > 0 + const mtimeMs = validMtime ? (rawMtime > 1e11 ? rawMtime : rawMtime * 1000) : 0 + const mtimeSec = validMtime ? (rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime) : 0 if (p && sz >= 0) realFileSizeCache.set(p, sz) return { name, @@ -551,6 +561,7 @@ function makeScanResult( subdirs, ...(meta.truncated ? { truncated: true } : {}), ...(meta.approximate ? { approximate: true } : {}), + ...(meta.missing ? { missing: true } : {}), ...(typeof meta.visitedEntries === 'number' ? { visitedEntries: meta.visitedEntries } : {}), [Symbol.iterator]() { return files[Symbol.iterator]() @@ -609,13 +620,40 @@ export async function scanRealDirectoryTree( return result.error ? { ...result.scan, error: result.error } : result.scan } +/** 仅当正则明确声明了扩展名(含 `\.`)时提取后缀列表,避免把 `thumbcache|iconcache` 等文件名关键词误拆成假扩展名 */ +function extractExtensionTokensFromFilter(filterExt: RegExp): string[] { + const src = filterExt.source + if (!src.includes('\\.')) return [] + const afterDot = src.slice(src.indexOf('\\.') + 2) + const rawTokens = afterDot.match(/[a-z0-9]{1,8}/gi) || [] + const seen = new Set() + const out: string[] = [] + for (const token of rawTokens) { + const lower = token.toLowerCase() + if (!lower || seen.has(lower)) continue + seen.add(lower) + out.push(lower) + } + return out +} + +function isMissingDirectoryError(res: { error?: string; errorCode?: string; errorDetails?: Record }): boolean { + if (res.errorDetails?.reason === 'ENOENT' || res.errorCode === 'ENOENT') return true + const msg = String(res.error || '') + return /Directory does not exist|ENOENT/i.test(msg) +} + /** 一次界面扫描的错误汇总;多个目录并行扫描时保留可读目录的结果。 */ export function createDirectoryScanner(hostOverride?: DynamicBridge) { const failures = new Map() return { async scan(dir: string, options: number | ScanDirectoryTreeOptions = 160) { const result = await scanRealDirectoryTree(dir, options, hostOverride) - const error = result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') + const ignoreMissing = typeof options === 'object' && options !== null && options.ignoreMissing === true + const error = + result.missing && ignoreMissing + ? '' + : result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') if (error) failures.set(dir, error) else failures.delete(dir) return result @@ -648,26 +686,38 @@ async function scanDirectoryTreeWithError( const safeLimit = Math.min(200, Math.max(1, Math.floor(rawLimit || 160))) const hostOverride = opts.hostOverride const filterExt = opts.filterExt + const ignoreMissing = opts.ignoreMissing === true const dirQuery = `dir:${targetDir}` try { let rawPayload: DynamicBridge = null + const searchParams: Record = { + query: dirQuery, + limit: safeLimit, + ...(opts.sortBy ? { sortBy: opts.sortBy } : {}) + } const res = await callHostTransport( 'system_search_files', - { query: dirQuery, limit: safeLimit }, + searchParams, hostOverride ) - if (res.ok && res.data) { + if (res.ok && res.data && res.data.degraded !== true) { rawPayload = res.data + } else if (!res.ok && ignoreMissing && isMissingDirectoryError(res)) { + const missingScan = makeScanResult([], 0, 0, [], { missing: true }) + return { scan: missingScan } } - if (!rawPayload && !hostOverride && typeof window !== 'undefined') { + if (!rawPayload && !hostOverride && res.errorCode === 'METHOD_NOT_AVAILABLE' && typeof window !== 'undefined') { const w = window as DynamicBridge if (typeof w.__ztoolsLauncher?.searchFiles === 'function') { const rawOuter = await w.__ztoolsLauncher.searchFiles(dirQuery, safeLimit) - rawPayload = + const candidate = rawOuter && typeof rawOuter === 'object' && 'data' in rawOuter && rawOuter.data ? rawOuter.data : rawOuter + if (candidate && candidate.degraded !== true && candidate.success !== false) { + rawPayload = candidate + } } } @@ -678,29 +728,32 @@ async function scanDirectoryTreeWithError( let files: RealIndexedFileEntry[] = rawPayload.files.map(normalizeIndexedFileEntry) if (filterExt instanceof RegExp) { files = files.filter(f => !f.isDir && (filterExt.test(f.name) || filterExt.test(f.ext))) - // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索目标扩展名 + // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索明确声明的目标扩展名 if (files.length === 0 && !hostOverride) { - const extTokens = (filterExt.source.match(/[a-z0-9]{2,5}/gi) || []) - .filter(t => !['thumbcache', 'iconcache'].includes(t.toLowerCase())) - .slice(0, 4) - // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 - const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() - const extraLists = await Promise.all( - extTokens.map(ext => searchRealIndexedFiles(`.${ext.toLowerCase()}`, 30, hostOverride)) - ) - const seen = new Set() - for (const list of extraLists) { - for (const item of list) { - if (!item.isDir && item.size > 0 && !seen.has(item.path)) { - if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { - seen.add(item.path) - files.push(item) + const extTokens = extractExtensionTokensFromFilter(filterExt) + if (extTokens.length > 0) { + // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 + const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() + const extraLists = await Promise.all( + extTokens.map(ext => searchRealIndexedFiles(`.${ext}`, 30, hostOverride)) + ) + const seen = new Set() + for (const list of extraLists) { + for (const item of list) { + if (!item.isDir && item.size > 0 && !seen.has(item.path)) { + if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { + seen.add(item.path) + files.push(item) + } } } } } } } + // 先基于过滤后的完整命中集合计算总文件数与总字节数,再按 collectTopN 裁剪样本列表 + const matchedCount = files.length + const matchedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) if (typeof opts.collectTopN === 'number' && opts.collectTopN > 0 && files.length > opts.collectTopN) { files = files.slice(0, opts.collectTopN) } @@ -714,11 +767,10 @@ async function scanDirectoryTreeWithError( ...(s.approximate === true ? { approximate: true } : {}) })) : [] - const computedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) const totalFilesCount = - filterExt instanceof RegExp ? files.length : Number(rawPayload.total_matches ?? files.length) + filterExt instanceof RegExp ? matchedCount : Number(rawPayload.total_matches ?? matchedCount) const totalBytesCount = - filterExt instanceof RegExp ? computedBytes : Number(rawPayload.total_bytes ?? computedBytes) + filterExt instanceof RegExp ? matchedBytes : Number(rawPayload.total_bytes ?? matchedBytes) const visited = Number(rawPayload.visited_entries) return { scan: makeScanResult(files, totalFilesCount, totalBytesCount, subdirs, { @@ -1817,8 +1869,6 @@ export async function writeRealClipboardText(text: string, hostOverride?: Dynami const payload = { text: String(text || '') } const res = await callHostTransport('clipboard_copy_text', payload, hostOverride) if (res.ok) return true - const fallbackRes = await callHostTransport('clipboard_write_text', payload, hostOverride) - if (fallbackRes.ok) return true try { if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) { await navigator.clipboard.writeText(String(text || '')) diff --git a/extensions/data-recovery/src/recycle-bin.ts b/extensions/data-recovery/src/recycle-bin.ts new file mode 100644 index 00000000..8e3e1e26 --- /dev/null +++ b/extensions/data-recovery/src/recycle-bin.ts @@ -0,0 +1,301 @@ +/** + * Windows $Recycle.Bin\\$I* 二进制元数据头解析器与恢复目标安全校验器 + * + * 格式规范(Windows Vista / 7 / 8 / 10 / 11): + * - Header v1 (Vista / Win7 / Win8): + * [0..7] uint64le version = 1 + * [8..15] uint64le original file size in bytes + * [16..23] uint64le deletion timestamp (Windows FILETIME: 100ns intervals since 1601-01-01 UTC) + * [24..543] 520 bytes fixed UTF-16LE NUL-terminated original path (260 WCHARs) + * - Header v2 (Windows 10 / 11): + * [0..7] uint64le version = 2 + * [8..15] uint64le original file size in bytes + * [16..23] uint64le deletion timestamp (Windows FILETIME) + * [24..27] uint32le path length in UTF-16 code units (including trailing NUL) + * [28..] pathLen * 2 bytes variable-length UTF-16LE original path + */ + +import { t } from "./i18n.js"; + +/** Windows FILETIME 纪元(1601-01-01)到 Unix 纪元(1970-01-01)的 100 纳秒差值 */ +const FILETIME_EPOCH_DIFF_100NS = 116444736000000000n; +const TICKS_PER_MS = 10000n; +/** 合理时间上限(2200-01-01 UTC) */ +const MAX_REASONABLE_UNIX_MS = Date.UTC(2200, 0, 1); + +/** v1 路径区固定最大 UTF-16 code unit 数量(MAX_PATH = 260) */ +const V1_MAX_PATH_CHARS = 260; +/** v2 变长路径最大允许 UTF-16 code unit 数量(NTFS 扩展路径上限 32768) */ +const V2_MAX_PATH_CHARS = 32768; + +export const FORBIDDEN_TARGET_PATTERN = + /(^|[\\/])(Windows|System32|SysWOW64|Program Files|Program Files \(x86\)|\.\.)($|[\\/])/i; + +export interface ParsedRecycleBinInfoSuccess { + ok: true; + headerVersion: 1 | 2; + originalSizeBytes: number; + deletedAtMs: number; + originalPath: string; + originalName: string; +} + +export interface ParsedRecycleBinInfoFailure { + ok: false; + errorCode: + | "INVALID_INPUT" + | "TRUNCATED_HEADER" + | "UNSUPPORTED_VERSION" + | "INVALID_PATH_LENGTH" + | "CORRUPT_PATH"; + error: string; +} + +export type ParsedRecycleBinInfo = ParsedRecycleBinInfoSuccess | ParsedRecycleBinInfoFailure; + +export interface RecoveryTargetValidationResult { + ok: boolean; + errorCode?: "EMPTY_TARGET" | "FORBIDDEN_TARGET" | "SAME_SOURCE_DRIVE"; + sourceDrive?: string; + targetDrive?: string; + error?: string; +} + +/** + * 将 Windows FILETIME(1601-01-01 起百纳秒整数)转换为 Unix 毫秒时间戳。 + * 输入为 0 或超出合理时间范围时返回 0(不编造伪时间)。 + */ +export function filetimeToUnixMs(filetime: bigint): number { + if (filetime <= FILETIME_EPOCH_DIFF_100NS) { + return 0; + } + const unixMsBig = (filetime - FILETIME_EPOCH_DIFF_100NS) / TICKS_PER_MS; + if (unixMsBig <= 0n || unixMsBig > BigInt(MAX_REASONABLE_UNIX_MS)) { + return 0; + } + return Number(unixMsBig); +} + +/** + * 将标准 Base64 字符串解码为 Uint8Array(纯 JS 实现,兼容浏览器渲染层与 Node 测试环境)。 + */ +export function decodeBase64ToBytes(base64: string): Uint8Array | null { + if (typeof base64 !== "string") return null; + const cleaned = base64.replace(/\s+/g, ""); + if (cleaned.length === 0) return new Uint8Array(0); + if (cleaned.length % 4 !== 0 || !/^[A-Za-z0-9+/]*={0,2}$/.test(cleaned)) { + return null; + } + const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + let padding = 0; + if (cleaned.endsWith("==")) padding = 2; + else if (cleaned.endsWith("=")) padding = 1; + + const outLen = (cleaned.length / 4) * 3 - padding; + const out = new Uint8Array(outLen); + let outIdx = 0; + + for (let i = 0; i < cleaned.length; i += 4) { + const c0 = alphabet.indexOf(cleaned[i]); + const c1 = alphabet.indexOf(cleaned[i + 1]); + const c2 = cleaned[i + 2] === "=" ? 0 : alphabet.indexOf(cleaned[i + 2]); + const c3 = cleaned[i + 3] === "=" ? 0 : alphabet.indexOf(cleaned[i + 3]); + if (c0 < 0 || c1 < 0 || c2 < 0 || c3 < 0) return null; + + const triple = (c0 << 18) | (c1 << 12) | (c2 << 6) | c3; + if (outIdx < outLen) out[outIdx++] = (triple >> 16) & 0xff; + if (outIdx < outLen) out[outIdx++] = (triple >> 8) & 0xff; + if (outIdx < outLen) out[outIdx++] = triple & 0xff; + } + return out; +} + +/** + * 从小端 UTF-16LE 字节片段解码字符串,遇到第一个 0x0000 终止符停止。 + */ +function decodeUtf16LeUntilNul(view: DataView, byteOffset: number, charCount: number): string { + const units: number[] = []; + for (let i = 0; i < charCount; i += 1) { + const codeUnit = view.getUint16(byteOffset + i * 2, true); + if (codeUnit === 0) break; + units.push(codeUnit); + } + // 分块 String.fromCharCode,避免超长路径(> 8192 字符)触发调用栈溢出 + let result = ""; + const chunkSize = 4096; + for (let i = 0; i < units.length; i += chunkSize) { + result += String.fromCharCode(...units.slice(i, i + chunkSize)); + } + return result; +} + +/** + * 解析 Windows `$Recycle.Bin\\$I*` 二进制元数据文件。 + * 严格支持 v1(Vista/Win7/Win8 24 字节头 + 520 字节固定路径)与 v2(Win10/Win11 28 字节头 + 变长 UTF-16LE 路径), + * 对截断头、非法版本、越界长度与损坏路径一律显式拒绝。 + */ +export function parseRecycleBinInfoFile(bytes: Uint8Array): ParsedRecycleBinInfo { + if (!(bytes instanceof Uint8Array)) { + return { ok: false, errorCode: "INVALID_INPUT", error: "Expected Uint8Array for $I metadata" }; + } + if (bytes.byteLength < 26) { + return { + ok: false, + errorCode: "TRUNCATED_HEADER", + error: `Recycle Bin $I header too short (${bytes.byteLength} bytes)` + }; + } + + const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + const version = view.getBigUint64(0, true); + const rawSize = view.getBigUint64(8, true); + const rawFiletime = view.getBigUint64(16, true); + + if (rawSize > BigInt(Number.MAX_SAFE_INTEGER)) { + return { + ok: false, + errorCode: "CORRUPT_PATH", + error: "Original file size in $I header exceeds safe integer range" + }; + } + + const originalSizeBytes = Number(rawSize); + const deletedAtMs = filetimeToUnixMs(rawFiletime); + + let headerVersion: 1 | 2; + let originalPath = ""; + + if (version === 1n) { + headerVersion = 1; + // v1 规范总长为 544 字节(24 字节头 + 520 字节固定 UTF-16LE 路径区);至少需含 24 字节头 + 1 个 UTF-16 字符 + const availableChars = Math.floor((bytes.byteLength - 24) / 2); + if (availableChars < 1) { + return { + ok: false, + errorCode: "TRUNCATED_HEADER", + error: "v1 $I file missing UTF-16LE path payload" + }; + } + const charsToRead = Math.min(V1_MAX_PATH_CHARS, availableChars); + originalPath = decodeUtf16LeUntilNul(view, 24, charsToRead); + } else if (version === 2n) { + headerVersion = 2; + if (bytes.byteLength < 30) { + return { + ok: false, + errorCode: "TRUNCATED_HEADER", + error: `v2 $I header truncated (${bytes.byteLength} bytes)` + }; + } + const pathCharLen = view.getUint32(24, true); + if (pathCharLen < 1 || pathCharLen > V2_MAX_PATH_CHARS) { + return { + ok: false, + errorCode: "INVALID_PATH_LENGTH", + error: `v2 $I path length out of range: ${pathCharLen}` + }; + } + const requiredBytes = 28 + pathCharLen * 2; + if (requiredBytes > bytes.byteLength) { + return { + ok: false, + errorCode: "TRUNCATED_HEADER", + error: `v2 $I payload truncated: expected ${requiredBytes} bytes, got ${bytes.byteLength}` + }; + } + originalPath = decodeUtf16LeUntilNul(view, 28, pathCharLen); + } else { + return { + ok: false, + errorCode: "UNSUPPORTED_VERSION", + error: `Unsupported $I header version: ${version.toString()}` + }; + } + + const normalizedPath = originalPath.trim(); + if (!normalizedPath || /[\u0000-\u001f]/.test(normalizedPath)) { + return { + ok: false, + errorCode: "CORRUPT_PATH", + error: "Decoded original path in $I metadata is empty or contains control characters" + }; + } + + const segments = normalizedPath.split(/[\\/]+/).filter(Boolean); + const originalName = segments.length > 0 ? segments[segments.length - 1] : normalizedPath; + + return { + ok: true, + headerVersion, + originalSizeBytes, + deletedAtMs, + originalPath: normalizedPath, + originalName + }; +} + +/** + * 从路径或卷标识中提取规范大写 Windows 盘符(如 "C")。 + * 支持格式:"C:\\path"、"c:/path"、"\\\\.\\C:"、"\\\\?\\D:\\dir"、"E:"、"F"。 + */ +export function extractDriveLetter(pathOrVolume: string): string | null { + const raw = String(pathOrVolume || "").trim(); + if (!raw) return null; + const extendedMatch = raw.match(/^\\\\[.?]\\([A-Za-z]):(?:[\\/]|$)/); + if (extendedMatch) return extendedMatch[1].toUpperCase(); + const driveMatch = raw.match(/^([A-Za-z]):(?:[\\/]|$)/); + if (driveMatch) return driveMatch[1].toUpperCase(); + const singleLetterMatch = raw.match(/^([A-Za-z])$/); + if (singleLetterMatch) return singleLetterMatch[1].toUpperCase(); + return null; +} + +/** + * 恢复输出目录硬校验: + * 1. 严禁为空; + * 2. 严禁落在系统目录或包含 `..` 路径穿越; + * 3. **严禁落在任何源待恢复分区所在盘符**(防止恢复写入覆盖尚未读取的待恢复扇区)。 + */ +export function validateRecoveryOutputTarget( + sourcePathsOrDrives: string | string[], + targetDir: string +): RecoveryTargetValidationResult { + const normalizedTarget = String(targetDir || "").trim().replace(/[\\/]+$/, ""); + if (!normalizedTarget) { + return { + ok: false, + errorCode: "EMPTY_TARGET", + error: t("desktopUnavailable") + }; + } + + if (FORBIDDEN_TARGET_PATTERN.test(normalizedTarget)) { + return { + ok: false, + errorCode: "FORBIDDEN_TARGET", + error: t("forbiddenReason") + }; + } + + const targetDrive = extractDriveLetter(normalizedTarget); + const sourceList = Array.isArray(sourcePathsOrDrives) ? sourcePathsOrDrives : [sourcePathsOrDrives]; + if (targetDrive) { + for (const src of sourceList) { + const srcDrive = extractDriveLetter(src); + if (srcDrive && srcDrive === targetDrive) { + return { + ok: false, + errorCode: "SAME_SOURCE_DRIVE", + sourceDrive: srcDrive, + targetDrive, + error: t("sameDriveTargetReason", { drive: targetDrive }) + }; + } + } + } + + return { + ok: true, + ...(targetDrive ? { targetDrive } : {}) + }; +} diff --git a/extensions/data-recovery/tests/data-recovery.host.test.mjs b/extensions/data-recovery/tests/data-recovery.host.test.mjs index 57fb2fee..6941995c 100644 --- a/extensions/data-recovery/tests/data-recovery.host.test.mjs +++ b/extensions/data-recovery/tests/data-recovery.host.test.mjs @@ -1,15 +1,49 @@ -// 本插件现行代码的宿主集成测试(从 packages/declarative-ui/tests/real-layout2-plugins.test.mjs 按插件拆出,导入改为本插件的 dist/) import test from 'node:test' import assert from 'node:assert/strict' -import fs from 'node:fs' -import path from 'node:path' -import { fileURLToPath } from 'node:url' import { setRuntimeLocale } from '@ztools/declarative-ui' setRuntimeLocale('zh-CN') const dataRecovery = await import('../dist/logic.js') -const __dirname = path.dirname(fileURLToPath(import.meta.url)) +const FILETIME_EPOCH_DIFF_100NS = 116444736000000000n + +function unixMsToFiletime(ms) { + return BigInt(ms) * 10000n + FILETIME_EPOCH_DIFF_100NS +} + +/** 构造规范的 Windows $Recycle.Bin $I v1 (544 bytes: 24 字节头 + 520 字节固定 UTF-16LE 路径) */ +function buildRecycleInfoV1({ originalSize, deletedAtMs, originalPath }) { + const buf = new Uint8Array(544) + const view = new DataView(buf.buffer) + view.setBigUint64(0, 1n, true) + view.setBigUint64(8, BigInt(originalSize), true) + view.setBigUint64(16, unixMsToFiletime(deletedAtMs), true) + for (let i = 0; i < originalPath.length && i < 259; i += 1) { + view.setUint16(24 + i * 2, originalPath.charCodeAt(i), true) + } + return buf +} + +/** 构造规范的 Windows $Recycle.Bin $I v2 (28 字节头 + 变长 UTF-16LE 路径 + 尾 NUL) */ +function buildRecycleInfoV2({ originalSize, deletedAtMs, originalPath }) { + const pathCharLen = originalPath.length + 1 + const buf = new Uint8Array(28 + pathCharLen * 2) + const view = new DataView(buf.buffer) + view.setBigUint64(0, 2n, true) + view.setBigUint64(8, BigInt(originalSize), true) + view.setBigUint64(16, unixMsToFiletime(deletedAtMs), true) + view.setUint32(24, pathCharLen, true) + for (let i = 0; i < originalPath.length; i += 1) { + view.setUint16(28 + i * 2, originalPath.charCodeAt(i), true) + } + view.setUint16(28 + originalPath.length * 2, 0, true) + return buf +} + +function toBase64(bytes) { + return Buffer.from(bytes).toString('base64') +} + function createRealHostStub(handlers = {}) { const calls = [] const dispatch = async (method, params) => { @@ -26,9 +60,7 @@ function createRealHostStub(handlers = {}) { const stub = { __isRealHost: true, calls, - transport: { - call: dispatch - } + transport: { call: dispatch } } for (const key of Object.keys(handlers)) { @@ -38,130 +70,405 @@ function createRealHostStub(handlers = {}) { return stub } -const DESKTOP = 'C:\\Users\\RealUser\\Desktop' -const BIN = 'C:\\$Recycle.Bin\\S-1-5-21-1000' +test('data-recovery $I 二进制解析: 支持 Vista/Win7 v1 (24B 头 + 中文路径 + FILETIME)', () => { + const deletedAtMs = Date.UTC(2026, 4, 15, 8, 30, 45) + const originalPath = 'D:\\工作文档\\2026财务报表\\季度总结.xlsx' + const raw = buildRecycleInfoV1({ originalSize: 123456, deletedAtMs, originalPath }) -const SCAN_RESULT = { - ok: true, - success: true, - items: [ - { - id: 'a1', - name: '$RABC123.docx', - path: `${BIN}\\$RABC123.docx`, - cachePath: `${BIN}\\$RABC123.docx`, - originalPath: `${BIN}\\$RABC123.docx`, - sizeBytes: 20480, - deletedAtMs: Date.UTC(2026, 0, 2, 3, 4, 5), - modifiedAt: new Date(Date.UTC(2026, 0, 2, 3, 4, 5)).toISOString(), - integrity: '回收站/备份可恢复' - }, - { - id: 'b2', - name: '$RXYZ999.bin', - path: `${BIN}\\$RXYZ999.bin`, - cachePath: `${BIN}\\$RXYZ999.bin`, - sizeBytes: 100 - } - ] -} + const parsed = dataRecovery.parseRecycleBinInfoFile(raw) + assert.equal(parsed.ok, true) + assert.equal(parsed.headerVersion, 1) + assert.equal(parsed.originalSizeBytes, 123456) + assert.equal(parsed.deletedAtMs, deletedAtMs) + assert.equal(parsed.originalPath, originalPath) + assert.equal(parsed.originalName, '季度总结.xlsx') +}) -function pathHandler({ name }) { - return name === 'desktop' ? DESKTOP : '' -} +test('data-recovery $I 二进制解析: 支持 Win10/11 v2 (变长 UTF-16LE 中文路径与超长路径 >300 字符)', () => { + const deletedAtMs = Date.UTC(2026, 10, 27, 10, 20, 30) + const longDir = '归档目录_'.repeat(65) + const originalPath = `E:\\项目资料\\${longDir}\\核心设计方案_最终版.docx` + assert.ok(originalPath.length > 320, '路径应超过传统 MAX_PATH=260 限制') -test('data-recovery: 不在客户端里运行时不显示示例文件', async () => { - const snap = await dataRecovery.fetchRecoverableFiles() - assert.equal(snap.items.length, 0) - assert.equal(snap.error, dataRecovery.getNotInClientMessage()) - assert.equal(typeof dataRecovery.createInitialRecoverySnapshot, 'undefined') - assert.equal(typeof dataRecovery.SCAN_DEPTH_MODES, 'undefined', '不再提供客户端做不到的扫描模式') + const raw = buildRecycleInfoV2({ originalSize: 987654321, deletedAtMs, originalPath }) + const parsed = dataRecovery.parseRecycleBinInfoFile(raw) + assert.equal(parsed.ok, true) + assert.equal(parsed.headerVersion, 2) + assert.equal(parsed.originalSizeBytes, 987654321) + assert.equal(parsed.deletedAtMs, deletedAtMs) + assert.equal(parsed.originalPath, originalPath) + assert.equal(parsed.originalName, '核心设计方案_最终版.docx') }) -test('data-recovery: 读取回收站失败时如实报错,不改列临时文件冒充可恢复文件', async () => { - const host = createRealHostStub({ - system_get_path: pathHandler, - dllplugin_call: () => ({ ok: false, success: false, error: '拒绝访问' }), - system_search_files: () => ({ - files: [{ name: '~WRL0001.tmp', path: 'C:\\Users\\RealUser\\AppData\\Local\\Temp\\~WRL0001.tmp', is_dir: false, size: 51200, mtime: 1 }], - total_matches: 1 - }) - }) - const snap = await dataRecovery.fetchRecoverableFiles(host) - assert.equal(snap.items.length, 0) - assert.match(snap.error, /读取回收站失败:拒绝访问/) - assert.equal(host.calls.some((c) => c.channel === 'system_search_files'), false) +test('data-recovery $I 二进制解析: 严格拒绝截断头、未知版本、越界长度与空路径损坏头', () => { + // 1. 截断过短 + const tooShort = new Uint8Array(16) + const resShort = dataRecovery.parseRecycleBinInfoFile(tooShort) + assert.equal(resShort.ok, false) + assert.equal(resShort.errorCode, 'TRUNCATED_HEADER') + + // 2. 未知版本 (version = 99) + const badVer = new Uint8Array(64) + new DataView(badVer.buffer).setBigUint64(0, 99n, true) + const resVer = dataRecovery.parseRecycleBinInfoFile(badVer) + assert.equal(resVer.ok, false) + assert.equal(resVer.errorCode, 'UNSUPPORTED_VERSION') + + // 3. v2 声称路径长度超出实际字节缓冲区(截断损坏) + const truncatedV2 = new Uint8Array(40) + const viewTrunc = new DataView(truncatedV2.buffer) + viewTrunc.setBigUint64(0, 2n, true) + viewTrunc.setBigUint64(8, 1024n, true) + viewTrunc.setBigUint64(16, unixMsToFiletime(Date.UTC(2026, 0, 1)), true) + viewTrunc.setUint32(24, 50, true) // 需要 28 + 100 = 128 bytes,但只有 40 bytes + const resTruncV2 = dataRecovery.parseRecycleBinInfoFile(truncatedV2) + assert.equal(resTruncV2.ok, false) + assert.equal(resTruncV2.errorCode, 'TRUNCATED_HEADER') + + // 4. v2 路径长度为 0 + const zeroLenV2 = new Uint8Array(32) + const viewZero = new DataView(zeroLenV2.buffer) + viewZero.setBigUint64(0, 2n, true) + viewZero.setUint32(24, 0, true) + const resZero = dataRecovery.parseRecycleBinInfoFile(zeroLenV2) + assert.equal(resZero.ok, false) + assert.equal(resZero.errorCode, 'INVALID_PATH_LENGTH') + + // 5. v1 空路径 + const emptyPathV1 = new Uint8Array(544) + new DataView(emptyPathV1.buffer).setBigUint64(0, 1n, true) + const resEmptyPath = dataRecovery.parseRecycleBinInfoFile(emptyPathV1) + assert.equal(resEmptyPath.ok, false) + assert.equal(resEmptyPath.errorCode, 'CORRUPT_PATH') }) -test('data-recovery: 列表只用客户端返回的字段,不编造原路径、完整度与删除时间', async () => { +test('data-recovery 快速回收站: 精确还原 $I 元数据,跨用户 SID 权限拒绝如实提示且不造假', async () => { + const deletedMs = Date.UTC(2026, 8, 1, 12, 0, 0) + const infoBytes = buildRecycleInfoV2({ + originalSize: 20480, + deletedAtMs: deletedMs, + originalPath: 'D:\\重要合同\\年度合作协议.pdf' + }) + const host = createRealHostStub({ - system_get_path: pathHandler, - dllplugin_call: (payload) => { - assert.equal(payload.plugin, 'DataRecoveryPlugin') - assert.equal(payload.func, 'scanDeletedFiles') - return SCAN_RESULT + system_get_path: ({ name }) => (name === 'desktop' ? 'E:\\Users\\Tester\\Desktop' : ''), + system_get_disk_usage: ({ drive }) => { + if (drive === 'D:\\') return { total: 1000, used: 500, available: 500 } + throw new Error('DRIVE_NOT_READY') + }, + filesystem_get_directory_contents: ({ path }) => { + if (path === 'D:\\$Recycle.Bin') { + return { + entries: [ + { name: 'S-1-5-21-1000', path: 'D:\\$Recycle.Bin\\S-1-5-21-1000', isDirectory: true }, + { name: 'S-1-5-21-1001', path: 'D:\\$Recycle.Bin\\S-1-5-21-1001', isDirectory: true } + ] + } + } + if (path === 'D:\\$Recycle.Bin\\S-1-5-21-1000') { + return { + entries: [ + { name: '$IABC123.pdf', path: 'D:\\$Recycle.Bin\\S-1-5-21-1000\\$IABC123.pdf', isDirectory: false, size: infoBytes.byteLength }, + { name: '$RABC123.pdf', path: 'D:\\$Recycle.Bin\\S-1-5-21-1000\\$RABC123.pdf', isDirectory: false, size: 20480 } + ] + } + } + if (path === 'D:\\$Recycle.Bin\\S-1-5-21-1001') { + return { success: false, errorCode: 'PERMISSION_DENIED', error: 'EACCES: 拒绝访问其他用户回收站目录' } + } + return { success: false, errorCode: 'FILE_NOT_FOUND', error: 'ENOENT' } + }, + filesystem_read_file: ({ path, encoding }) => { + assert.equal(encoding, 'base64') + assert.equal(path, 'D:\\$Recycle.Bin\\S-1-5-21-1000\\$IABC123.pdf') + return { content: toBase64(infoBytes) } } }) - const snap = await dataRecovery.fetchRecoverableFiles(host) + + const snap = await dataRecovery.scanRecycleBinFast(host, ['D']) assert.equal(snap.error, undefined) - assert.equal(snap.restoreTargetDir, `${DESKTOP}\\ZToolsRecovered`) - assert.deepEqual(snap.items.map((i) => [i.name, i.category]), [['$RABC123.docx', 'documents'], ['$RXYZ999.bin', 'other']]) - assert.ok(snap.items[0].modifiedText.length > 0) - assert.equal(snap.items[1].modifiedText, '') - const text = JSON.stringify(snap) - assert.doesNotMatch(text, /完整度|integrity|originalPath|Documents/) + assert.equal(snap.items.length, 1) + assert.equal(snap.items[0].name, '年度合作协议.pdf') + assert.equal(snap.items[0].originalPath, 'D:\\重要合同\\年度合作协议.pdf') + assert.equal(snap.items[0].sizeBytes, 20480) + assert.equal(snap.items[0].deletedAtMs, deletedMs) + assert.equal(snap.items[0].metadataStatus, 'parsed') + assert.deepEqual(snap.inaccessibleSids, ['D:\\$Recycle.Bin\\S-1-5-21-1001']) + assert.match(snap.permissionWarning, /管理员权限/) }) -test('data-recovery: 拿不到桌面路径时不使用猜测的目录,恢复直接拒绝', async () => { +test('data-recovery 安全硬拦截: 恢复目标盘符与源待恢复分区盘符相同时严格拒绝', async () => { + // 1. 直接校验函数测试 + const sameDriveCheck = dataRecovery.validateRecoveryOutputTarget('D:\\$Recycle.Bin\\S-1\\$R1.docx', 'd:\\Recovered') + assert.equal(sameDriveCheck.ok, false) + assert.equal(sameDriveCheck.errorCode, 'SAME_SOURCE_DRIVE') + assert.equal(sameDriveCheck.sourceDrive, 'D') + assert.equal(sameDriveCheck.targetDrive, 'D') + + const diffDriveCheck = dataRecovery.validateRecoveryOutputTarget('D:\\$Recycle.Bin\\S-1\\$R1.docx', 'E:\\Recovered') + assert.equal(diffDriveCheck.ok, true) + + // 2. 快速回收站恢复同盘拦截(严禁发起复制 IPC) const host = createRealHostStub({ - system_get_path: () => { - throw new Error('PATH_UNAVAILABLE') - }, - dllplugin_call: () => SCAN_RESULT + filesystem_create_directory: () => ({ ok: true }), + filesystem_copy_file: () => { + throw new Error('同盘恢复必须在前置硬拦截,严禁写入源分区') + } + }) + const itemsOnC = [ + { + id: '1', + name: 'report.docx', + cachePath: 'C:\\$Recycle.Bin\\S-1-5-21-1000\\$R1.docx', + sourceDrive: 'C', + category: 'documents', + categoryName: '文档', + sizeBytes: 1024, + modifiedText: '', + metadataStatus: 'parsed' + } + ] + const sameDriveRes = await dataRecovery.restoreSelectedFiles(itemsOnC, 'C:\\Users\\Tester\\Desktop\\ZToolsRecovered', host) + assert.equal(sameDriveRes.ok, false) + assert.equal(sameDriveRes.restoredCount, 0) + assert.match(sameDriveRes.message, /源待恢复分区(C:\\)/) + assert.equal(host.calls.some((c) => c.channel === 'filesystem_copy_file'), false) + + // 3. 磁盘深度恢复同盘拦截(严禁发起 RecoverFile DLL 调用) + const deepHost = createRealHostStub({ + dllplugin_call_with_callback: () => { + throw new Error('同盘深度恢复必须在前置硬拦截') + } }) - const snap = await dataRecovery.fetchRecoverableFiles(host) - assert.equal(snap.restoreTargetDir, '') - assert.match(snap.error, /无法获取桌面路径/) - const res = await dataRecovery.restoreSelectedFiles(snap.items, snap.restoreTargetDir, host) - assert.equal(res.ok, false) - assert.equal(host.calls.filter((c) => c.channel === 'dllplugin_call').length, 1) + const deepBlocked = await dataRecovery.recoverDeepFiles( + { + taskId: 't_recover_1', + scanId: 'scan_001', + fileIds: ['101'], + targetPath: 'D:\\OutputFolder', + sourceDrives: ['C', 'D'] + }, + deepHost + ) + assert.equal(deepBlocked.ok, false) + assert.equal(deepBlocked.errorCode, 'SAME_SOURCE_DRIVE') + assert.equal(deepHost.calls.length, 0) }) -test('data-recovery: 恢复到新建的时间子文件夹,重名自动编号,部分失败如实列出', async () => { - const restoreCalls = [] +test('data-recovery 磁盘深度恢复: 完整验证 DataRecoveryPlugin 全部 12 个真实导出函数契约', async () => { + const invoked = [] const host = createRealHostStub({ - dllplugin_call: (payload) => { - assert.equal(payload.func, 'restoreFile') - restoreCalls.push(payload.params) - if (payload.params.sourcePath.endsWith('bad.txt')) return { ok: false, success: false, error: '待恢复的源文件不存在' } - return { ok: true, success: true, recoveredCount: 1, targetPath: payload.params.targetPath } + dllplugin_call: ({ plugin, func, params }) => { + assert.equal(plugin, 'DataRecoveryPlugin') + invoked.push({ channel: 'dllplugin_call', func, params }) + switch (func) { + case 'GetDeviceList': + return { + success: true, + devices: [ + { + deviceId: '\\\\.\\PhysicalDrive0', + name: 'NVMe SSD 1TB', + size: 1000204886016, + type: 'SSD', + status: 'normal', + fileSystem: 'NTFS', + volumes: [{ letter: 'C' }, { letter: 'D' }] + } + ] + } + case 'GetPartitions': + return { + success: true, + partitions: [ + { + partitionNum: 0, + start: 2048, + length: 209715200, + description: 'NTFS Primary', + type: 'gpt', + fileSystem: 'ntfs', + allocated: true, + driveLetter: 'D' + } + ] + } + case 'StopScan': + return { success: true, message: 'Scan stopped' } + case 'EnumFiles': + return { + success: true, + totalCount: 1, + files: [ + { + fileId: '42', + id: 42, + name: 'photo.jpg', + path: '/Photos', + size: 409600, + type: 'image', + recoverable: true, + integrity: 'good', + isDeleted: true + } + ] + } + case 'GetFileMetadata': + return { + success: true, + name: 'photo.jpg', + path: '/Photos', + size: 409600, + type: 'image', + recoverable: true, + integrity: 'good', + isDeleted: true + } + case 'PreviewFile': + return { + success: true, + previewPath: 'C:\\ZTools\\Cache\\DataRecoveryPlugin\\preview_scan_001_42.jpg', + fileType: 'image' + } + case 'GetScanStatus': + return { + success: true, + scanning: true, + scanId: 'scan_001', + deviceId: '\\\\.\\PhysicalDrive0', + scanType: 'deep' + } + case 'GetScanHistory': + return { + success: true, + total: 1, + history: [ + { + scanId: 'scan_001', + deviceId: '\\\\.\\PhysicalDrive0', + deviceName: 'NVMe SSD 1TB', + partitionNum: 0, + scanType: 'deep', + scanScenario: 'deleted', + startTime: 1700000000, + endTime: 1700000120, + totalFiles: 128, + totalSize: 52428800, + status: 'completed', + description: '', + cacheAvailable: true + } + ] + } + default: + throw new Error(`unexpected sync func: ${func}`) + } }, - filesystem_copy_file: () => { - throw new Error('不能改用其他复制方式') + dllplugin_call_with_callback: ({ plugin, func, params }) => { + assert.equal(plugin, 'DataRecoveryPlugin') + invoked.push({ channel: 'dllplugin_call_with_callback', func, params }) + if (func === 'GetDeviceListAsync') return { success: true, devices: [] } + if (func === 'StartScan') return { success: true, scanId: 'scan_001' } + if (func === 'EnumFilesAsync') return { success: true, files: [], totalCount: 0 } + if (func === 'RecoverFile') return { success: true, message: 'Recovery started' } + throw new Error(`unexpected callback func: ${func}`) } }) - const items = [ - { id: '1', name: 'same.docx', cachePath: 'C:\\$Recycle.Bin\\S-1\\same.docx', category: 'documents', categoryName: '文档', sizeBytes: 10, modifiedText: '' }, - { id: '2', name: 'same.docx', cachePath: 'D:\\$Recycle.Bin\\S-1\\same.docx', category: 'documents', categoryName: '文档', sizeBytes: 20, modifiedText: '' }, - { id: '3', name: 'bad.txt', cachePath: 'C:\\$Recycle.Bin\\S-1\\bad.txt', category: 'documents', categoryName: '文档', sizeBytes: 5, modifiedText: '' } - ] - const now = new Date(2026, 9, 28, 15, 30, 12, 45) - const res = await dataRecovery.restoreSelectedFiles(items, `${DESKTOP}\\ZToolsRecovered`, host, now) - const outDir = `${DESKTOP}\\ZToolsRecovered\\20261028-153012-045` - assert.deepEqual(restoreCalls.map((c) => c.targetPath), [`${outDir}\\same.docx`, `${outDir}\\same (2).docx`, `${outDir}\\bad.txt`]) - assert.ok(restoreCalls.every((c) => !('targetDir' in c))) - assert.equal(res.ok, false) - assert.equal(res.restoredCount, 2) - assert.equal(res.restoredBytes, 30) - assert.equal(res.outputDir, outDir) - assert.deepEqual(res.failed, [{ name: 'bad.txt', error: '待恢复的源文件不存在' }]) - assert.match(res.message, /1 个失败/) - assert.match(res.message, /待恢复的源文件不存在/) - assert.equal(host.calls.some((c) => c.channel === 'filesystem_copy_file'), false) - const none = await dataRecovery.restoreSelectedFiles([], `${DESKTOP}\\ZToolsRecovered`, host) - assert.equal(none.ok, false) - assert.equal(none.message, '请先勾选要恢复的文件') - const sys = await dataRecovery.restoreSelectedFiles(items, 'C:\\Windows\\Temp', host) - assert.equal(sys.ok, false) + // 1. GetDeviceList + const devRes = await dataRecovery.getDeviceList(host) + assert.equal(devRes.ok, true) + assert.equal(devRes.data.length, 1) + assert.deepEqual(devRes.data[0].volumes, ['C', 'D']) + + // 2. GetDeviceListAsync + const devAsyncRes = await dataRecovery.getDeviceListAsync('task_dev_1', host) + assert.equal(devAsyncRes.ok, true) + + // 3. GetPartitions (允许 partitionNum === 0) + const partRes = await dataRecovery.getPartitions('\\\\.\\PhysicalDrive0', host) + assert.equal(partRes.ok, true) + assert.equal(partRes.data[0].partitionNum, 0) + assert.equal(partRes.data[0].driveLetter, 'D') + + // 4. StartScan (允许 partitionNum === 0) + const scanRes = await dataRecovery.startDiskScan( + { taskId: 'task_scan_1', deviceId: '\\\\.\\PhysicalDrive0', partitionNum: 0, scanType: 'deep' }, + host + ) + assert.equal(scanRes.ok, true) + assert.equal(scanRes.data.scanId, 'scan_001') + + // 5. GetScanStatus + const statusRes = await dataRecovery.getScanStatus('task_scan_1', host) + assert.equal(statusRes.ok, true) + assert.equal(statusRes.data.scanning, true) + + // 6. StopScan + const stopRes = await dataRecovery.stopDiskScan('task_scan_1', host) + assert.equal(stopRes.ok, true) + + // 7. EnumFiles + const enumRes = await dataRecovery.enumScanFiles({ scanId: 'scan_001', pageIndex: 0, pageSize: 50 }, host) + assert.equal(enumRes.ok, true) + assert.equal(enumRes.data.totalCount, 1) + assert.equal(enumRes.data.files[0].fileId, '42') + + // 8. EnumFilesAsync + const enumAsyncRes = await dataRecovery.enumScanFilesAsync({ taskId: 'task_enum_1', scanId: 'scan_001' }, host) + assert.equal(enumAsyncRes.ok, true) + + // 9. GetFileMetadata + const metaRes = await dataRecovery.getDeepFileMetadata('scan_001', '42', host) + assert.equal(metaRes.ok, true) + assert.equal(metaRes.data.name, 'photo.jpg') + + // 10. PreviewFile + const prevRes = await dataRecovery.previewDeepFile('scan_001', '42', host) + assert.equal(prevRes.ok, true) + assert.match(prevRes.data.previewPath, /preview_scan_001_42\.jpg$/) + + // 11. RecoverFile(跨盘 D -> E,允许通过) + const recRes = await dataRecovery.recoverDeepFiles( + { + taskId: 'task_rec_1', + scanId: 'scan_001', + fileIds: ['42'], + targetPath: 'E:\\ZToolsRecovered\\20261127', + sourceDrives: ['D'] + }, + host + ) + assert.equal(recRes.ok, true) + + // 12. GetScanHistory + const histRes = await dataRecovery.getScanHistory(10, host) + assert.equal(histRes.ok, true) + assert.equal(histRes.data[0].partitionNum, 0) + + // 确认全部 12 个真实方法都被完整覆盖调用 + const calledFuncs = new Set(invoked.map((x) => x.func)) + for (const fn of dataRecovery.DATA_RECOVERY_DLL_FUNCTIONS) { + assert.ok(calledFuncs.has(fn), `缺少对真实导出函数 ${fn} 的调用校验`) + } + assert.equal(calledFuncs.size, 12) +}) + +test('data-recovery: 不在客户端环境中运行不返回假数据,且双语热切换正常', async () => { + try { + setRuntimeLocale('zh-CN') + const snapZh = await dataRecovery.fetchRecoverableFiles() + assert.equal(snapZh.items.length, 0) + assert.match(snapZh.error, /客户端/) + + setRuntimeLocale('en-US') + const snapEn = await dataRecovery.fetchRecoverableFiles() + assert.equal(snapEn.items.length, 0) + assert.doesNotMatch(snapEn.error, /[\u4e00-\u9fa5]/) + const sameEn = dataRecovery.validateRecoveryOutputTarget('D:\\$Recycle.Bin\\S-1\\$R1', 'D:\\Recovered') + assert.equal(sameEn.ok, false) + assert.doesNotMatch(sameEn.error, /[\u4e00-\u9fa5]/) + } finally { + setRuntimeLocale('zh-CN') + } }) diff --git a/extensions/data-recovery/tests/data-recovery.ui.test.mjs b/extensions/data-recovery/tests/data-recovery.ui.test.mjs index 3e03f2d3..93bd0b0e 100644 --- a/extensions/data-recovery/tests/data-recovery.ui.test.mjs +++ b/extensions/data-recovery/tests/data-recovery.ui.test.mjs @@ -3,76 +3,126 @@ import assert from 'node:assert/strict' import { createHost, mount } from '../../shared/test-harness.mjs' import DataRecoveryCommand from '../dist/index.js' -const DESKTOP = 'C:\\Users\\Tester\\Desktop' -const BIN = 'C:\\$Recycle.Bin\\S-1-5-21-1000' +const FILETIME_EPOCH_DIFF_100NS = 116444736000000000n -function installHost(host) { - const restoreCalls = [] - host.ipc.system_get_path = async ({ name }) => (name === 'desktop' ? DESKTOP : '') - host.ipc.dllplugin_call = async ({ plugin, func, params }) => { +function buildRecycleInfoV2(originalPath, originalSize, deletedAtMs) { + const pathCharLen = originalPath.length + 1 + const buf = new Uint8Array(28 + pathCharLen * 2) + const view = new DataView(buf.buffer) + view.setBigUint64(0, 2n, true) + view.setBigUint64(8, BigInt(originalSize), true) + view.setBigUint64(16, BigInt(deletedAtMs) * 10000n + FILETIME_EPOCH_DIFF_100NS, true) + view.setUint32(24, pathCharLen, true) + for (let i = 0; i < originalPath.length; i += 1) { + view.setUint16(28 + i * 2, originalPath.charCodeAt(i), true) + } + return Buffer.from(buf).toString('base64') +} + +const DESKTOP_E = 'E:\\Users\\Tester\\Desktop' +const BIN_D = 'D:\\$Recycle.Bin\\S-1-5-21-1000' + +function installHost(host, desktopDir = DESKTOP_E) { + const copyCalls = [] + const infoA = buildRecycleInfoV2('D:\\Docs\\合同草案.docx', 2048, Date.UTC(2026, 4, 1, 9, 0, 0)) + const infoB = buildRecycleInfoV2('D:\\Pics\\封面图.png', 4096, Date.UTC(2026, 4, 2, 10, 0, 0)) + + host.ipc.system_get_path = async ({ name }) => (name === 'desktop' ? desktopDir : '') + host.ipc.system_get_disk_usage = async ({ drive }) => { + if (drive === 'D:\\') return { total: 1000, used: 400, available: 600 } + throw new Error('ENOENT') + } + host.ipc.filesystem_get_directory_contents = async ({ path }) => { + if (path === 'D:\\$Recycle.Bin') { + return { entries: [{ name: 'S-1-5-21-1000', path: BIN_D, isDirectory: true }] } + } + if (path === BIN_D) { + return { + entries: [ + { name: '$IAAA111.docx', path: `${BIN_D}\\$IAAA111.docx`, isDirectory: false, size: 128 }, + { name: '$RAAA111.docx', path: `${BIN_D}\\$RAAA111.docx`, isDirectory: false, size: 2048 }, + { name: '$IBBB222.png', path: `${BIN_D}\\$IBBB222.png`, isDirectory: false, size: 128 }, + { name: '$RBBB222.png', path: `${BIN_D}\\$RBBB222.png`, isDirectory: false, size: 4096 } + ] + } + } + return { success: false, errorCode: 'FILE_NOT_FOUND', error: 'ENOENT' } + } + host.ipc.filesystem_read_file = async ({ path }) => { + if (path.endsWith('$IAAA111.docx')) return { content: infoA } + if (path.endsWith('$IBBB222.png')) return { content: infoB } + return { success: false, error: 'FILE_NOT_FOUND' } + } + host.ipc.filesystem_create_directory = async () => ({ ok: true }) + host.ipc.filesystem_copy_file = async (params) => { + copyCalls.push(params) + return { ok: true } + } + host.ipc.dllplugin_call = async ({ plugin, func }) => { assert.equal(plugin, 'DataRecoveryPlugin') - if (func === 'scanDeletedFiles') { + if (func === 'GetDeviceList') { return { - ok: true, success: true, - items: [ - { id: 'a', name: '$RAAA111.docx', cachePath: `${BIN}\\$RAAA111.docx`, sizeBytes: 2048 }, - { id: 'b', name: '$RBBB222.png', cachePath: `${BIN}\\$RBBB222.png`, sizeBytes: 4096 } + devices: [ + { + deviceId: '\\\\.\\PhysicalDrive0', + name: 'SSD 512GB', + size: 512000000000, + type: 'SSD', + status: 'normal', + volumes: [{ letter: 'D' }] + } ] } } - if (func === 'restoreFile') { - restoreCalls.push(params) - return { ok: true, success: true, targetPath: params.targetPath } - } - throw new Error(`unexpected ${func}`) + return { success: true } } - return restoreCalls + return copyCalls } function fileRows(view) { return view.items().filter((it) => String(it.props.id).startsWith('rec-item-')) } -test('data-recovery UI: 不默认勾选,没有勾选时不恢复任何文件,也没有客户端做不到的扫描模式', async () => { +test('data-recovery UI: 显示 $I 解析后的原始中文文件名与原路径,且默认不勾选', async () => { const host = createHost() - const restoreCalls = installHost(host) + const copyCalls = installHost(host) const view = await mount(DataRecoveryCommand, host) const rows = fileRows(view) assert.equal(rows.length, 2) assert.ok(rows.every((r) => r.props.checked === false)) - assert.equal(view.tree().props.searchBarAccessory, undefined) - assert.doesNotMatch(view.text(), /完整度|深度扇区|MFT/) + assert.equal(rows[0].props.title, '合同草案.docx') + assert.match(rows[0].props.subtitle, /D:\\Docs\\合同草案\.docx/) + assert.equal(rows[1].props.title, '封面图.png') - await view.run(rows[0], '复制已勾选文件到恢复文件夹 (0 项)') - assert.equal(restoreCalls.length, 0) + await view.run(rows[0], '恢复已勾选文件 (0 项)') + assert.equal(copyCalls.length, 0) assert.equal(host.lastToast().title, '请先勾选要恢复的文件') view.unmount() }) -test('data-recovery UI: 只复制已勾选的文件到新的子文件夹,并提示结果', async () => { +test('data-recovery UI: 跨盘(D -> E)恢复成功使用原始文件名,同盘(D -> D)恢复被硬拦截', async () => { const host = createHost() - const restoreCalls = installHost(host) + const copyCalls = installHost(host, DESKTOP_E) const view = await mount(DataRecoveryCommand, host) await view.run(fileRows(view)[1], '勾选此文件') - await view.run(fileRows(view)[0], '复制已勾选文件到恢复文件夹 (1 项)') - assert.equal(restoreCalls.length, 1) - assert.equal(restoreCalls[0].sourcePath, `${BIN}\\$RBBB222.png`) - assert.match(restoreCalls[0].targetPath, /^C:\\Users\\Tester\\Desktop\\ZToolsRecovered\\\d{8}-\d{6}-\d{3}\\\$RBBB222\.png$/) + await view.run(fileRows(view)[0], '恢复已勾选文件 (1 项)') + assert.equal(copyCalls.length, 1) + assert.equal(copyCalls[0].sourcePath, `${BIN_D}\\$RBBB222.png`) + assert.match(copyCalls[0].destPath, /^E:\\Users\\Tester\\Desktop\\ZToolsRecovered\\\d{8}-\d{6}-\d{3}\\封面图\.png$/) assert.equal(host.lastToast().style, 'SUCCESS') - assert.match(host.lastToast().message, /已将 1 个文件/) view.unmount() -}) -test('data-recovery UI: 读取回收站失败时显示原因,不显示任何文件', async () => { - const host = createHost() - installHost(host) - host.ipc.dllplugin_call = async () => ({ ok: false, success: false, error: '拒绝访问' }) - const view = await mount(DataRecoveryCommand, host) - assert.equal(fileRows(view).length, 0) - assert.match(view.tree().props.filterBar.summaryText, /读取回收站失败:拒绝访问/) - assert.match(view.tree().props.subList.emptyText, /拒绝访问/) - view.unmount() + // 同盘 D -> D 硬拦截测试 + const hostSame = createHost() + const copyCallsSame = installHost(hostSame, 'D:\\Users\\Tester\\Desktop') + const viewSame = await mount(DataRecoveryCommand, hostSame) + await viewSame.run(fileRows(viewSame)[0], '勾选此文件') + await viewSame.run(fileRows(viewSame)[0], '恢复已勾选文件 (1 项)') + assert.equal(copyCallsSame.length, 0) + assert.equal(hostSame.lastToast().style, 'FAILURE') + assert.match(hostSame.lastToast().message, /源待恢复分区(D:\\)/) + viewSame.unmount() }) diff --git a/extensions/disk-analyzer/README.en.md b/extensions/disk-analyzer/README.en.md new file mode 100644 index 00000000..7c5b9f33 --- /dev/null +++ b/extensions/disk-analyzer/README.en.md @@ -0,0 +1,21 @@ +# Disk Space Analyzer + +Display capacity and used space for each disk partition, locate large files across common folders and partitions, browse by file type, extension, or directory, and move files to the Recycle Bin / Trash. + +## Usage + +- Command: Search for "Disk Space Analyzer" in the launcher to open. +- Scans the root of each partition as well as Downloads, Documents, Desktop, Videos (Movies on macOS), and the system temp folder (plus `~/Library/Caches` on macOS; scanning the temp folder requires the client's common-directories API and is skipped on older clients), collecting up to the 100 largest files per location. When a scan hits the entry cap, the large files list is marked "Sampled" and does not represent all files on disk. If an individual location fails to read (for example, denied access to Documents/Desktop/Downloads on macOS or an unreadable external volume), remaining locations still display and failed locations with reasons are listed under "Unscanned Directories" on the left; only when all locations fail is the scan marked failed with the reason in the status bar. +- Filter by partition, 10 file categories, and hotspot folders on the left; the large files list on the right is sorted by size descending and supports checkboxes. +- `Enter`: Move the selected file to the Recycle Bin / Trash (requires confirmation); `⌘/Ctrl+Enter`: Reveal in File Explorer (Finder on macOS); `⌘/Ctrl+K`: Open the action panel to open with the default app, filter to the same extension, batch clean checked files, or copy the path. +- Files inside system directories and protected packages (such as Applications, Photos / iMovie / Final Cut libraries, and virtual machines) cannot be checked or removed; pressing `Enter` reveals them instead. +- Files are only moved to the Recycle Bin / Trash and can be restored; files in use or lacking permissions report a removal failure. + +## Platforms & Requirements + +- Supported: Windows, macOS +- Requires client version 1.1.8.3 or later. "Open this partition in Explorer / Finder" requires a client newer than 1.1.8.6; older clients prompt to upgrade while all other features continue working. + +## Network & Data + +- Works offline; data stays on your local device. diff --git a/extensions/disk-analyzer/plugin.json b/extensions/disk-analyzer/plugin.json index 4e57f4e1..50d9bef4 100644 --- a/extensions/disk-analyzer/plugin.json +++ b/extensions/disk-analyzer/plugin.json @@ -2,7 +2,8 @@ "id": "disk-analyzer", "name": "磁盘空间分析", "description": "快速分析各磁盘分区空间占用,按文件夹大小与大文件排行直观找出占满硬盘的文件", - "version": "2.0.15", + "version": "2.0.16", + "minAppVersion": "1.1.8.0", "author": "ZTools Team", "entry": "dist/index.js", "icon": "icon.svg", @@ -16,7 +17,8 @@ ], "permissions": [ "fs", - "system" + "system", + "shell" ], "requireAdmin": false, "nativeComponents": [], @@ -45,7 +47,14 @@ "space", "analyzer", "large files", - "folders" + "folders", + "disk analyzer", + "disk space", + "big files", + "disk usage", + "drive full", + "space analyzer", + "cleanup" ], "screenshots": [ { @@ -58,5 +67,17 @@ { "path": "screenshots/01.png" } + ], + "keywords": [ + "磁盘分析", + "空间分析", + "找大文件", + "大文件清理", + "c盘满了", + "硬盘满了", + "磁盘空间", + "占空间", + "空间扫描", + "大文件" ] } diff --git a/extensions/disk-analyzer/src/directory-scan.ts b/extensions/disk-analyzer/src/directory-scan.ts index a82337e9..1f84ab1f 100644 --- a/extensions/disk-analyzer/src/directory-scan.ts +++ b/extensions/disk-analyzer/src/directory-scan.ts @@ -8,6 +8,7 @@ export async function scanRealDirectoryTree(directory: string, limit: number, ho const data = result.data if (!result.ok || !data || !Array.isArray(data.files)) throw new Error(`${directory}: ${resolveErrorMessage(result, t('dirScanInvalidResult'))}`) if (data.degraded || data.partial) throw new Error(`${directory}: ${t('dirScanIncomplete')}`) + const scanError = typeof data.scan_error === 'string' && data.scan_error.trim() ? data.scan_error.trim() : undefined return { files: data.files.map((value: unknown) => { if (!value || typeof value !== 'object') throw new Error(`${directory}: ${t('dirScanInvalidFileRecord')}`) @@ -28,6 +29,8 @@ export async function scanRealDirectoryTree(directory: string, limit: number, ho } }), truncated: data.truncated === true, - visitedEntries: typeof data.visited_entries === 'number' && Number.isFinite(data.visited_entries) ? data.visited_entries : undefined + approximate: Boolean(data.approximate), + visitedEntries: typeof data.visited_entries === 'number' && Number.isFinite(data.visited_entries) ? data.visited_entries : undefined, + ...(scanError ? { error: scanError } : {}) } } diff --git a/extensions/disk-analyzer/src/i18n.ts b/extensions/disk-analyzer/src/i18n.ts index 1cf6aebe..874129e3 100644 --- a/extensions/disk-analyzer/src/i18n.ts +++ b/extensions/disk-analyzer/src/i18n.ts @@ -174,10 +174,12 @@ const rawT = createTranslator( summaryScanningPrefix: "正在扫描大文件 · ", summaryMain: "已挂载卷容量 {cap} / 已用 {used} ({pct}%) / 剩余 {avail}", summarySampled: " · 抽样结果(已扫描 {count} 项)", + summaryPartialVolumes: " · 部分卷读取失败({detail})", summaryFailedDirs: " · {count} 个目录未能扫描(见左侧列表)", summarySelected: " · 已勾选 {count} 项 ({size})", btnScanning: "正在扫描...", btnRescan: "重新扫描", + btnBatchTrash: "移入{trash} ({count})", subListScanning: "扫描中", subListSubtitle: "{count} 项 · {size}", subListEmptyScanning: "正在扫描大文件,目录较多时需要几十秒…", @@ -375,10 +377,12 @@ const rawT = createTranslator( summaryScanningPrefix: "Scanning large files · ", summaryMain: "Mounted {cap} / Used {used} ({pct}%) / Free {avail}", summarySampled: " · Sampled ({count} scanned)", + summaryPartialVolumes: " · Some volumes unreadable ({detail})", summaryFailedDirs: " · {count} unreadable folder(s)", summarySelected: " · Checked {count} ({size})", btnScanning: "Scanning...", btnRescan: "Rescan", + btnBatchTrash: "Move to {trash} ({count})", subListScanning: "Scanning", subListSubtitle: "{count} [[count:item|items]] · {size}", subListEmptyScanning: "Scanning large files, this may take a moment for large directories...", diff --git a/extensions/disk-analyzer/src/index.ts b/extensions/disk-analyzer/src/index.ts index 87a737d6..72f7ed8f 100644 --- a/extensions/disk-analyzer/src/index.ts +++ b/extensions/disk-analyzer/src/index.ts @@ -100,6 +100,24 @@ function dirDisplayName(dirPath: string): string { return name || dirPath } +/** 路径是否位于指定目录之下(带路径分隔符边界,防止 C:\Data 误匹配 C:\DataBackup) */ +function isPathWithinDirectory(targetPath: string, dirPath: string): boolean { + const rawDir = String(dirPath || '').trim() + const rawTarget = String(targetPath || '').trim() + if (!rawDir || !rawTarget) return false + const isPosix = rawDir.startsWith('/') + const sep = isPosix ? '/' : '\\' + const normDir = isPosix + ? (rawDir.replace(/\/+$/, '') || '/').toLowerCase() + : rawDir.replace(/\//g, '\\').replace(/\\+$/, '').toLowerCase() + const normTarget = isPosix + ? (rawTarget.replace(/\/+$/, '') || '/').toLowerCase() + : rawTarget.replace(/\//g, '\\').replace(/\\+$/, '').toLowerCase() + if (normTarget === normDir) return true + const prefix = normDir.endsWith(sep) ? normDir : `${normDir}${sep}` + return normTarget.startsWith(prefix) +} + export default function DiskAnalyzerCommand() { useLocale() const [searchText, setSearchText] = useState('') @@ -120,6 +138,8 @@ export default function DiskAnalyzerCommand() { const [sampledScan, setSampledScan] = useState<{ sampled: boolean; scannedEntries: number }>({ sampled: false, scannedEntries: 0 }) // 未能扫描的目录(用户拒绝访问、外接卷不可读等):其余目录照常展示,这些目录在左侧单独列出原因 const [failedScans, setFailedScans] = useState([]) + // 部分磁盘卷读取失败告警(如 BitLocker 锁定分区、断开的网络卷) + const [volumeWarnings, setVolumeWarnings] = useState([]) const [totalCapacity, setTotalCapacity] = useState(0) const [totalUsed, setTotalUsed] = useState(0) const [totalAvailable, setTotalAvailable] = useState(0) @@ -147,6 +167,7 @@ export default function DiskAnalyzerCommand() { // 分区容量先到先显示;大文件和目录要等扫描完成 const snap = await fetchDiskAnalysisSnapshot(undefined, summary => { setDrives(summary.drives) + setVolumeWarnings(Array.isArray(summary.volumeWarnings) ? summary.volumeWarnings : []) setTotalCapacity(summary.totalCapacityBytes) setTotalUsed(summary.totalUsedBytes) setTotalAvailable(summary.totalAvailableBytes) @@ -158,6 +179,7 @@ export default function DiskAnalyzerCommand() { setSampledScan({ sampled: snap.sampled === true, scannedEntries: Number(snap.scannedEntries) || 0 }) const failed = Array.isArray(snap.failedScans) ? snap.failedScans : [] setFailedScans(failed) + setVolumeWarnings(Array.isArray(snap.volumeWarnings) ? snap.volumeWarnings : []) setTotalCapacity(snap.totalCapacityBytes) setTotalUsed(snap.totalUsedBytes) setTotalAvailable(snap.totalAvailableBytes) @@ -228,10 +250,9 @@ export default function DiskAnalyzerCommand() { const finalFilteredFiles = groupScopedFiles .filter(f => { if (selectedDirPath !== 'ALL') { - const normDir = selectedDirPath.toLowerCase() if ( - !f.path.toLowerCase().startsWith(normDir) && - !f.parentDir.toLowerCase().startsWith(normDir) + !isPathWithinDirectory(f.path, selectedDirPath) && + !isPathWithinDirectory(f.parentDir, selectedDirPath) ) { return false } @@ -651,6 +672,7 @@ export default function DiskAnalyzerCommand() { avail: formatBytes(metricAvail) }) + (sampledScan.sampled ? t('summarySampled', { count: sampledScan.scannedEntries }) : '') + + (volumeWarnings.length > 0 ? t('summaryPartialVolumes', { detail: volumeWarnings.join(t('pairSep')) }) : '') + (failedScans.length > 0 ? t('summaryFailedDirs', { count: failedScans.length }) : '') + (selectedEntries.length > 0 ? t('summarySelected', { count: selectedEntries.length, size: formatBytes(selectedBytes) }) : '') @@ -693,7 +715,20 @@ export default function DiskAnalyzerCommand() { style: 'secondary', disabled: isScanning, onAction: () => refreshAnalysis(true) - } + }, + ...(selectedEntries.length > 0 + ? [ + { + id: 'act-batch-trash', + label: t('btnBatchTrash', { trash: defaultTrash, count: selectedEntries.length }), + title: t('btnBatchTrash', { trash: defaultTrash, count: selectedEntries.length }), + style: 'primary', + onAction: () => { + void handleBatchTrashSelected() + } + } + ] + : []) ] }, subList: { @@ -705,7 +740,7 @@ export default function DiskAnalyzerCommand() { ? false : allFilteredChecked ? true - : selectedEntries.length > 0 + : selectableInFilter.some(f => selectedSet.has(f.path)) ? 'indeterminate' : false, onCheckChange: () => toggleSelectAllFiltered(), @@ -747,7 +782,7 @@ export default function DiskAnalyzerCommand() { { tag: { value: `${d.usagePercent}%`, - ...(isDanger ? { color: 'red' } : {}) + ...(isDanger ? { color: Color.Red } : {}) } } ], diff --git a/extensions/disk-analyzer/src/logic.ts b/extensions/disk-analyzer/src/logic.ts index f197742c..4c9859fa 100644 --- a/extensions/disk-analyzer/src/logic.ts +++ b/extensions/disk-analyzer/src/logic.ts @@ -1,10 +1,9 @@ import { scanRealDirectoryTree } from './directory-scan.js' -import { probeRealDiskDrives, uniqueCapacityDrives, type RealDiskDriveInfo } from './volume-ipc.js' -import { hostUpgradeError, isHostMethodMissing } from './host-compat.js' +import { probeRealDiskDrivesWithStatus, uniqueCapacityDrives, type RealDiskDriveInfo } from './volume-ipc.js' import { t } from './i18n.js' /** * 磁盘空间分析业务逻辑 - * 读取磁盘分区容量 (system_get_disk_usage)、扫描分区与用户目录, + * 读取磁盘分区容量 (system_list_volumes)、扫描分区与用户目录, * 按 10 类文件类型分组统计体积,并可下钻到二级扩展名 */ @@ -12,11 +11,8 @@ import { formatBytes as formatBinaryBytes, getRealFileSize, getRealSystemPath, - invokeDllPluginCapability, isRealElectronHost, listRealDirectoryContents, - - searchRealIndexedFiles, callHostTransport, showRealItemInFolder, @@ -50,24 +46,6 @@ export function formatBytes(bytes: number, decimals = 1, mac: boolean = isMacPla /** 测试注入的宿主替身(与 callHostTransport 的 hostOverride 相同) */ type HostOverride = Parameters[2] -export interface CapabilityActionItem { - id: string - title: string - subtitle: string - tag: string - method: string - params: Record -} - -export interface NativeInvocationResult { - ok: boolean - pluginName: string - method: string - data?: unknown - error?: string - fromFallback?: boolean -} - export interface DiskDriveItem { drive: string label: string @@ -249,12 +227,15 @@ export interface DiskAnalysisSnapshot { scannedEntries?: number /** 未能扫描的目录与原因(这些目录的内容不在结果里);为空表示全部扫描成功 */ failedScans: DiskScanFailure[] + /** 部分挂载卷读取失败(如 BitLocker 锁定分区) */ + partialVolumes?: boolean + /** 部分挂载卷读取失败告警明细 */ + volumeWarnings?: string[] totalCapacityBytes: number totalUsedBytes: number totalAvailableBytes: number } -export const DLL_PLUGIN_NAME = 'AnalyzerPlugin' /** Windows:系统目录、卷影副本区与程序安装目录 */ const WINDOWS_PROTECTED_PATTERN = /^(?:C:\\Windows(?:\\.*)?|C:\\System Volume Information(?:\\.*)?|C:\\Program Files(?:\\.*)?|C:\\Program Files \(x86\)(?:\\.*)?)$/i @@ -276,58 +257,6 @@ export function getForbiddenReason(): string { return t('forbiddenReason') } -export function getCapabilityItems(): CapabilityActionItem[] { - return [ - { - id: 'disk-c-overview', - title: t('presetCOverviewTitle'), - subtitle: t('presetCOverviewSub'), - tag: t('presetCOverviewTag'), - method: 'StartScanAsync', - params: { drive: 'C:\\' } - }, - { - id: 'disk-large-files', - title: t('presetLargeTitle'), - subtitle: t('presetLargeSub'), - tag: t('presetLargeTag'), - method: 'GetGroupFiles', - params: { minSizeMb: 500 } - }, - { - id: 'disk-ext-stats', - title: t('presetExtTitle'), - subtitle: t('presetExtSub'), - tag: t('presetExtTag'), - method: 'GetExtensionStats', - params: { topN: 20 } - }, - { - id: 'disk-drives-list', - title: t('presetDrivesTitle'), - subtitle: t('presetDrivesSub'), - tag: t('presetDrivesTag'), - method: 'GetAvailableDrives', - params: {} - } - ] -} - -export function filterCapabilityItems(items: CapabilityActionItem[], query: string): CapabilityActionItem[] { - if (!Array.isArray(items)) return [] - const q = typeof query === 'string' ? query.trim().toLowerCase() : '' - if (!q) return items - return items.filter(item => { - if (!item || typeof item.title !== 'string') return false - return ( - item.title.toLowerCase().includes(q) || - item.subtitle.toLowerCase().includes(q) || - item.tag.toLowerCase().includes(q) || - item.method.toLowerCase().includes(q) - ) - }) -} - export function formatDateTime(mtimeSeconds: number): string { if (!mtimeSeconds || !Number.isFinite(mtimeSeconds) || mtimeSeconds <= 0) return t('unknownTime') const ms = mtimeSeconds > 1e12 ? mtimeSeconds : mtimeSeconds * 1000 @@ -339,56 +268,6 @@ export function formatDateTime(mtimeSeconds: number): string { return `${yyyy}-${mm}-${dd}` } -export function validateInvocationPayload(method: string, params: unknown): { valid: boolean; error?: string } { - if (typeof method !== 'string' || method.trim().length === 0) { - return { valid: false, error: t('invalidMethodEmpty') } - } - if (method.length > 128 || !/^[A-Za-z0-9_]+$/.test(method.trim())) { - return { valid: false, error: t('invalidMethodFormat') } - } - if (params === null || params === undefined || typeof params !== 'object' || Array.isArray(params)) { - return { valid: false, error: t('invalidParamsObject') } - } - - const record = params as Record - for (const [key, val] of Object.entries(record)) { - if (typeof val === 'string') { - if (val.length > 4096) { - return { valid: false, error: t('paramTooLong', { key }) } - } - if (FORBIDDEN_TARGET_PATTERN.test(val)) { - return { valid: false, error: t('securityIntercepted', { reason: getForbiddenReason() }) } - } - } else if (typeof val === 'number') { - if (!Number.isFinite(val) || val < -1000 || val > 100_000_000) { - return { valid: false, error: t('paramOutOfRange', { key }) } - } - } - } - - return { valid: true } -} - -export async function invokeNativeCapability( - method: string, - params: Record, - hostBridge?: { dllplugin?: { call?: (plugin: string, fn: string, payload: unknown) => Promise }; __isRealHost?: boolean } -): Promise { - const check = validateInvocationPayload(method, params) - if (!check.valid) { - throw new Error(resolveErrorMessage(check, t('paramValidateFailed'))) - } - const res = await invokeDllPluginCapability(DLL_PLUGIN_NAME, method, params, hostBridge) - return { - ok: res.ok, - pluginName: DLL_PLUGIN_NAME, - method: method.trim(), - data: res.data ?? undefined, - error: res.error, - fromFallback: res.fromFallback - } -} - export function getGroupMetaById(groupId: OfficialFileTypeGroupId): OfficialFileTypeGroupMeta { const groups = getOfficialFileTypeGroups() return groups.find(g => g.groupId === groupId) || groups[groups.length - 1] @@ -544,21 +423,26 @@ function extractDrivePrefix(filePath: string): string { /** * 读取挂载卷;个别卷读不到容量(BitLocker 锁定卷、断开的网络卷、损坏的磁盘映像等)时, - * 其余卷照常返回,读不到的卷连同原因放在 errors 里由界面如实列出,不让整次分析失败。 - * 公共的 probeRealDiskDrives 遇到不完整列表直接报错,这里先去掉不完整标记再交给它校验每一卷的数据。 + * 通过 probeRealDiskDrivesWithStatus 保留全部有效卷并透传告警,仅在无有效卷时抛错。 */ -export async function probeDiskVolumesTolerant(hostOverride?: HostOverride): Promise<{ drives: RealDiskDriveInfo[]; errors: string[] }> { - const res = await callHostTransport>('system_list_volumes', {}, hostOverride) - if (!res.ok && isHostMethodMissing(res.error)) throw hostUpgradeError(t('volumeListFeature')) - if (!res.ok || !res.data || !Array.isArray(res.data.volumes)) throw new Error(resolveErrorMessage(res, t('volumeListUnavailable'))) - const errors = res.data.partial - ? (Array.isArray(res.data.errors) && res.data.errors.length ? res.data.errors.map(String) : [t('someVolumeFailed')]) - : [] - if (!res.data.volumes.length && errors.length) throw new Error(t('noMountedVolumes', { detail: errors.join(t('pairSep')) })) - // 同一份宿主快照交给公共解析(校验每一卷的数据),不重复请求宿主 - const snapshot = { ...res.data, partial: false, errors: [] } - const drives = await probeRealDiskDrives([], { system_list_volumes: () => snapshot } as unknown as HostOverride) - return { drives, errors } +export async function probeDiskVolumesTolerant( + hostOverride?: HostOverride +): Promise<{ drives: RealDiskDriveInfo[]; partial: boolean; warnings: string[]; errors: string[] }> { + try { + const result = await probeRealDiskDrivesWithStatus([], hostOverride) + return { + drives: result.drives, + partial: result.partial, + warnings: result.warnings, + errors: result.warnings + } + } catch (err) { + const typed = err as { code?: unknown; warnings?: unknown } | null + if (typed && typed.code === 'VOLUME_PARTIAL_EMPTY' && Array.isArray(typed.warnings) && typed.warnings.length > 0) { + throw new Error(t('noMountedVolumes', { detail: typed.warnings.map(String).join(t('pairSep')) })) + } + throw err + } } /** @@ -578,6 +462,8 @@ export async function getSystemTempDir(hostOverride?: HostOverride): Promise void ): Promise { // 1. 探测真实磁盘分区 (C:/ ~ G:/) - const { drives: rawDrives, errors: volumeErrors } = await probeDiskVolumesTolerant(hostOverride) + const { drives: rawDrives, partial: volumePartial, warnings: volumeWarnings } = await probeDiskVolumesTolerant(hostOverride) + const volumeErrors = volumeWarnings const drives: DiskDriveItem[] = rawDrives.map(d => ({ drive: d.drive, label: d.label || d.drive, @@ -608,7 +495,14 @@ export async function fetchDiskAnalysisSnapshot( const totalUsedBytes = capacityDrives.reduce((s, d) => s + d.usedBytes, 0) const totalAvailableBytes = capacityDrives.reduce((s, d) => s + d.availableBytes, 0) try { - onVolumes?.({ drives, totalCapacityBytes, totalUsedBytes, totalAvailableBytes }) + onVolumes?.({ + drives, + ...(volumePartial ? { partialVolumes: true } : {}), + ...(volumeWarnings.length > 0 ? { volumeWarnings } : {}), + totalCapacityBytes, + totalUsedBytes, + totalAvailableBytes + }) } catch { // 界面回调出错不影响后续扫描 } @@ -708,11 +602,15 @@ export async function fetchDiskAnalysisSnapshot( } for (const [scanIndex, outcome] of settled.entries()) { if (outcome.status !== 'fulfilled') continue + const targetDir = realTargetDirs[scanIndex]! const res = outcome.value - if (res.truncated) sampled = true + if (res.truncated || res.approximate) sampled = true + if (res.error) { + failedScans.push({ path: targetDir, reason: describeScanFailure(targetDir, res.error) }) + } scannedEntries += Number(res.visitedEntries) || 0 - // 分区根目录扫描被截断时,文件只是最先遍历到的系统文件(如 /usr/bin),不代表大文件,只取其子目录体积 - const isTruncatedDriveRoot = Boolean(res.truncated) && driveRoots.includes(realTargetDirs[scanIndex]!) + // 分区根目录扫描被截断时,保留非受保护的有效大文件并标记抽样;仅跳过受保护系统目录文件(如 /usr/bin、C:\Windows),避免系统碎片污染同时不丢弃数据盘(D:\、E:\ 等)大文件 + const isTruncatedDriveRoot = Boolean(res.truncated) && driveRoots.includes(targetDir) if (Array.isArray(res.subdirs)) { for (const sub of res.subdirs) { if (!sub.path || sub.totalBytes <= 0) continue @@ -730,9 +628,9 @@ export async function fetchDiskAnalysisSnapshot( }) } } - if (isTruncatedDriveRoot) continue for (const f of res.files) { if (!f.isDir && f.size > 0) { + if (isTruncatedDriveRoot && FORBIDDEN_TARGET_PATTERN.test(toNativePath(f.path))) continue addFileEntry(f.path, f.size, f.mtime) } } @@ -763,6 +661,8 @@ export async function fetchDiskAnalysisSnapshot( topDirectories, ...(sampled ? { sampled: true, scannedEntries } : {}), failedScans, + ...(volumePartial ? { partialVolumes: true } : {}), + ...(volumeWarnings.length > 0 ? { volumeWarnings } : {}), totalCapacityBytes, totalUsedBytes, totalAvailableBytes diff --git a/extensions/disk-analyzer/src/native-ipc.ts b/extensions/disk-analyzer/src/native-ipc.ts index 51576b99..13643277 100644 --- a/extensions/disk-analyzer/src/native-ipc.ts +++ b/extensions/disk-analyzer/src/native-ipc.ts @@ -174,11 +174,13 @@ function normalizeMethodResult(method: string, payload: DynamicBridge): DynamicB if (method === 'system_get_battery_status') { // 宿主约定 percent 超出 0-100(如 255)表示无电池或电量未知,不能改写成 100% + // 若宿主明确给出 hasBattery 布尔值,必须原样保留,仅在缺失时按合法电量推算 const rawPct = payload.percent - const hasBattery = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const validPct = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const hasBattery = typeof payload.hasBattery === 'boolean' ? payload.hasBattery : validPct return { ...payload, - percent: hasBattery ? rawPct : null, + percent: validPct ? rawPct : null, hasBattery } } @@ -489,6 +491,8 @@ export interface RealDirectoryScanResult extends Iterable approximate?: boolean /** 宿主实际遍历的条目数 */ visitedEntries?: number + /** 目录本身不存在(ENOENT) */ + missing?: boolean /** 读取失败的真实原因;已有文件仍可使用,但不能当作完整结果。 */ error?: string } @@ -497,6 +501,7 @@ interface ScanResultMeta { truncated?: boolean approximate?: boolean visitedEntries?: number + missing?: boolean } export interface ScanDirectoryTreeOptions { @@ -504,6 +509,10 @@ export interface ScanDirectoryTreeOptions { maxFiles?: number collectTopN?: number filterExt?: RegExp + /** 为 true 时,目录本身不存在(ENOENT)按空目录处理,不返回 error(权限拒绝/读取失败仍照常报错) */ + ignoreMissing?: boolean + /** Top-N 保留与排序方式:默认按体积降序,下载/录屏等时效场景可传 mtime-desc */ + sortBy?: 'size-desc' | 'mtime-desc' hostOverride?: DynamicBridge } @@ -519,8 +528,9 @@ function normalizeIndexedFileEntry(f: DynamicBridge): RealIndexedFileEntry { const sz = Number(f?.size ?? f?.sizeBytes ?? 0) const isDir = Boolean(f?.is_dir || f?.isDir || f?.isDirectory) const rawMtime = Number(f?.mtime ?? f?.mtimeMs ?? 0) - const mtimeMs = rawMtime > 1e11 ? rawMtime : rawMtime > 0 ? rawMtime * 1000 : Date.now() - const mtimeSec = rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime + const validMtime = Number.isFinite(rawMtime) && rawMtime > 0 + const mtimeMs = validMtime ? (rawMtime > 1e11 ? rawMtime : rawMtime * 1000) : 0 + const mtimeSec = validMtime ? (rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime) : 0 if (p && sz >= 0) realFileSizeCache.set(p, sz) return { name, @@ -551,6 +561,7 @@ function makeScanResult( subdirs, ...(meta.truncated ? { truncated: true } : {}), ...(meta.approximate ? { approximate: true } : {}), + ...(meta.missing ? { missing: true } : {}), ...(typeof meta.visitedEntries === 'number' ? { visitedEntries: meta.visitedEntries } : {}), [Symbol.iterator]() { return files[Symbol.iterator]() @@ -609,13 +620,40 @@ export async function scanRealDirectoryTree( return result.error ? { ...result.scan, error: result.error } : result.scan } +/** 仅当正则明确声明了扩展名(含 `\.`)时提取后缀列表,避免把 `thumbcache|iconcache` 等文件名关键词误拆成假扩展名 */ +function extractExtensionTokensFromFilter(filterExt: RegExp): string[] { + const src = filterExt.source + if (!src.includes('\\.')) return [] + const afterDot = src.slice(src.indexOf('\\.') + 2) + const rawTokens = afterDot.match(/[a-z0-9]{1,8}/gi) || [] + const seen = new Set() + const out: string[] = [] + for (const token of rawTokens) { + const lower = token.toLowerCase() + if (!lower || seen.has(lower)) continue + seen.add(lower) + out.push(lower) + } + return out +} + +function isMissingDirectoryError(res: { error?: string; errorCode?: string; errorDetails?: Record }): boolean { + if (res.errorDetails?.reason === 'ENOENT' || res.errorCode === 'ENOENT') return true + const msg = String(res.error || '') + return /Directory does not exist|ENOENT/i.test(msg) +} + /** 一次界面扫描的错误汇总;多个目录并行扫描时保留可读目录的结果。 */ export function createDirectoryScanner(hostOverride?: DynamicBridge) { const failures = new Map() return { async scan(dir: string, options: number | ScanDirectoryTreeOptions = 160) { const result = await scanRealDirectoryTree(dir, options, hostOverride) - const error = result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') + const ignoreMissing = typeof options === 'object' && options !== null && options.ignoreMissing === true + const error = + result.missing && ignoreMissing + ? '' + : result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') if (error) failures.set(dir, error) else failures.delete(dir) return result @@ -648,26 +686,38 @@ async function scanDirectoryTreeWithError( const safeLimit = Math.min(200, Math.max(1, Math.floor(rawLimit || 160))) const hostOverride = opts.hostOverride const filterExt = opts.filterExt + const ignoreMissing = opts.ignoreMissing === true const dirQuery = `dir:${targetDir}` try { let rawPayload: DynamicBridge = null + const searchParams: Record = { + query: dirQuery, + limit: safeLimit, + ...(opts.sortBy ? { sortBy: opts.sortBy } : {}) + } const res = await callHostTransport( 'system_search_files', - { query: dirQuery, limit: safeLimit }, + searchParams, hostOverride ) - if (res.ok && res.data) { + if (res.ok && res.data && res.data.degraded !== true) { rawPayload = res.data + } else if (!res.ok && ignoreMissing && isMissingDirectoryError(res)) { + const missingScan = makeScanResult([], 0, 0, [], { missing: true }) + return { scan: missingScan } } - if (!rawPayload && !hostOverride && typeof window !== 'undefined') { + if (!rawPayload && !hostOverride && res.errorCode === 'METHOD_NOT_AVAILABLE' && typeof window !== 'undefined') { const w = window as DynamicBridge if (typeof w.__ztoolsLauncher?.searchFiles === 'function') { const rawOuter = await w.__ztoolsLauncher.searchFiles(dirQuery, safeLimit) - rawPayload = + const candidate = rawOuter && typeof rawOuter === 'object' && 'data' in rawOuter && rawOuter.data ? rawOuter.data : rawOuter + if (candidate && candidate.degraded !== true && candidate.success !== false) { + rawPayload = candidate + } } } @@ -678,29 +728,32 @@ async function scanDirectoryTreeWithError( let files: RealIndexedFileEntry[] = rawPayload.files.map(normalizeIndexedFileEntry) if (filterExt instanceof RegExp) { files = files.filter(f => !f.isDir && (filterExt.test(f.name) || filterExt.test(f.ext))) - // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索目标扩展名 + // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索明确声明的目标扩展名 if (files.length === 0 && !hostOverride) { - const extTokens = (filterExt.source.match(/[a-z0-9]{2,5}/gi) || []) - .filter(t => !['thumbcache', 'iconcache'].includes(t.toLowerCase())) - .slice(0, 4) - // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 - const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() - const extraLists = await Promise.all( - extTokens.map(ext => searchRealIndexedFiles(`.${ext.toLowerCase()}`, 30, hostOverride)) - ) - const seen = new Set() - for (const list of extraLists) { - for (const item of list) { - if (!item.isDir && item.size > 0 && !seen.has(item.path)) { - if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { - seen.add(item.path) - files.push(item) + const extTokens = extractExtensionTokensFromFilter(filterExt) + if (extTokens.length > 0) { + // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 + const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() + const extraLists = await Promise.all( + extTokens.map(ext => searchRealIndexedFiles(`.${ext}`, 30, hostOverride)) + ) + const seen = new Set() + for (const list of extraLists) { + for (const item of list) { + if (!item.isDir && item.size > 0 && !seen.has(item.path)) { + if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { + seen.add(item.path) + files.push(item) + } } } } } } } + // 先基于过滤后的完整命中集合计算总文件数与总字节数,再按 collectTopN 裁剪样本列表 + const matchedCount = files.length + const matchedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) if (typeof opts.collectTopN === 'number' && opts.collectTopN > 0 && files.length > opts.collectTopN) { files = files.slice(0, opts.collectTopN) } @@ -714,11 +767,10 @@ async function scanDirectoryTreeWithError( ...(s.approximate === true ? { approximate: true } : {}) })) : [] - const computedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) const totalFilesCount = - filterExt instanceof RegExp ? files.length : Number(rawPayload.total_matches ?? files.length) + filterExt instanceof RegExp ? matchedCount : Number(rawPayload.total_matches ?? matchedCount) const totalBytesCount = - filterExt instanceof RegExp ? computedBytes : Number(rawPayload.total_bytes ?? computedBytes) + filterExt instanceof RegExp ? matchedBytes : Number(rawPayload.total_bytes ?? matchedBytes) const visited = Number(rawPayload.visited_entries) return { scan: makeScanResult(files, totalFilesCount, totalBytesCount, subdirs, { @@ -1817,8 +1869,6 @@ export async function writeRealClipboardText(text: string, hostOverride?: Dynami const payload = { text: String(text || '') } const res = await callHostTransport('clipboard_copy_text', payload, hostOverride) if (res.ok) return true - const fallbackRes = await callHostTransport('clipboard_write_text', payload, hostOverride) - if (fallbackRes.ok) return true try { if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) { await navigator.clipboard.writeText(String(text || '')) diff --git a/extensions/disk-analyzer/src/volume-ipc.ts b/extensions/disk-analyzer/src/volume-ipc.ts index 4be65bd7..0059623b 100644 --- a/extensions/disk-analyzer/src/volume-ipc.ts +++ b/extensions/disk-analyzer/src/volume-ipc.ts @@ -50,23 +50,97 @@ export interface RealDiskDriveInfo { usagePercent: number } +export interface RealDiskDrivesProbeResult { + drives: RealDiskDriveInfo[] + partial: boolean + warnings: string[] +} + /** - * 读取宿主枚举的已挂载卷,不猜测盘符或挂载点。 + * 读取宿主枚举的已挂载卷,并返回部分失败状态与告警; + * 当 partial 为 true 且存在有效卷时保留有效卷并透传 warnings,仅在无任何有效卷时抛错。 */ -export async function probeRealDiskDrives(_letters: string[] = [], hostOverride?: unknown): Promise { +export async function probeRealDiskDrivesWithStatus( + _letters: string[] = [], + hostOverride?: unknown +): Promise { const s = volumeIpcStrings() const res = await callHostTransport>('system_list_volumes', {}, hostOverride) if (!res.ok && isHostMethodMissing(res.error)) throw hostUpgradeError(s.listVolumesFeature) if (!res.ok || !Array.isArray(res.data?.volumes)) throw new Error(res.error || s.unableToReadVolumes) - if (res.data.partial) throw new Error(s.incompleteVolumeList(Array.isArray(res.data.errors) ? res.data.errors.join(s.errorSep) : s.capacityReadFailed)) - const drives = res.data.volumes.map((value: unknown) => { - if (!value || typeof value !== 'object') throw new Error(s.invalidVolumeData) + + const hostPartial = res.data.partial === true + const warnings: string[] = Array.isArray(res.data.errors) + ? res.data.errors.map(err => String(err ?? '').trim()).filter(Boolean) + : [] + if (hostPartial && warnings.length === 0) { + warnings.push(s.capacityReadFailed) + } + + const drives: RealDiskDriveInfo[] = [] + let invalidCount = 0 + for (const value of res.data.volumes as unknown[]) { + if (!value || typeof value !== 'object') { + invalidCount += 1 + warnings.push(s.invalidVolumeData) + continue + } const v = value as Record - const total = Number(v.totalBytes), used = Number(v.usedBytes), available = Number(v.availableBytes) - if (typeof v.path !== 'string' || !v.path || !Number.isFinite(total) || total <= 0 || !Number.isFinite(used) || used < 0 || !Number.isFinite(available) || available < 0) throw new Error(s.invalidVolumeData) - return { drive: v.path.replace(/^([A-Za-z]:)[\\/]$/, '$1'), label: String(v.label || v.path), fileSystem: String(v.fileSystem || s.unknownFs), capacityGroup: String(v.capacityGroup || v.path), totalBytes: total, usedBytes: used, availableBytes: available, usagePercent: Math.round(used / total * 100) } - }) - if (!drives.length) throw new Error(s.noMountedVolumes) + const total = Number(v.totalBytes) + const used = Number(v.usedBytes) + const available = Number(v.availableBytes) + const valid = + typeof v.path === 'string' && + v.path.length > 0 && + typeof v.totalBytes === 'number' && + typeof v.usedBytes === 'number' && + typeof v.availableBytes === 'number' && + Number.isFinite(total) && + total > 0 && + Number.isFinite(used) && + used >= 0 && + Number.isFinite(available) && + available >= 0 + if (!valid) { + invalidCount += 1 + warnings.push(typeof v.path === 'string' && v.path ? `${v.path}: ${s.invalidVolumeData}` : s.invalidVolumeData) + continue + } + const volumePath = v.path as string + drives.push({ + drive: volumePath.replace(/^([A-Za-z]:)[\\/]$/, '$1'), + label: String(v.label || volumePath), + fileSystem: String(v.fileSystem || s.unknownFs), + capacityGroup: String(v.capacityGroup || volumePath), + totalBytes: total, + usedBytes: used, + availableBytes: available, + usagePercent: Math.round((used / total) * 100) + }) + } + + const partial = hostPartial || invalidCount > 0 + if (!drives.length) { + if (hostPartial) { + throw Object.assign(new Error(s.incompleteVolumeList(warnings.join(s.errorSep))), { + code: 'VOLUME_PARTIAL_EMPTY', + warnings + }) + } + if (invalidCount > 0) { + throw new Error(s.invalidVolumeData) + } + throw new Error(s.noMountedVolumes) + } + + return { drives, partial, warnings } +} + +/** + * 读取宿主枚举的已挂载卷,不猜测盘符或挂载点(仅在无有效卷时抛错)。 + */ +export async function probeRealDiskDrives(_letters: string[] = [], hostOverride?: unknown): Promise { + const { drives } = await probeRealDiskDrivesWithStatus(_letters, hostOverride) return drives } diff --git a/extensions/disk-analyzer/tests/disk-analyzer.host.test.mjs b/extensions/disk-analyzer/tests/disk-analyzer.host.test.mjs index c7845746..74c9e785 100644 --- a/extensions/disk-analyzer/tests/disk-analyzer.host.test.mjs +++ b/extensions/disk-analyzer/tests/disk-analyzer.host.test.mjs @@ -36,25 +36,20 @@ function createRealHostStub(handlers = {}) { return stub } -test("disk-analyzer: 真实传输层与异常边界验证", async () => { - const failHost = createRealHostStub({}) - const dllKillHost = createRealHostStub({ - dllplugin_call: (payload) => { - assert.equal(payload.plugin, 'ProcessMonitorPlugin') - assert.equal(payload.func, 'TerminateProcessByPID') - return { success: true } +test("disk-analyzer: 插件不再保留旧 AnalyzerPlugin DLL 调用入口", async () => { + assert.equal(diskAnalyzer.DLL_PLUGIN_NAME, undefined) + assert.equal(diskAnalyzer.invokeNativeCapability, undefined) + assert.equal(diskAnalyzer.getCapabilityItems, undefined) + assert.equal(diskAnalyzer.validateInvocationPayload, undefined) + const dllHost = createRealHostStub({ + system_get_path: () => '/Users/tester/Downloads', + system_search_files: () => ({ files: [], subdirs: [], total_matches: 0 }), + dllplugin_call: () => { + throw new Error('不应调用旧 DLL 接口') } }) - const diskCapFail = await diskAnalyzer.invokeNativeCapability('StartScan', { rootPath: 'C:\\' }, failHost) - assert.equal(diskCapFail.ok, false) - assert.equal(diskCapFail.data?.simulated, undefined) - const dllOkHost = createRealHostStub({ - dllplugin_call: (payload) => ({ - executed: true, - plugin: payload.plugin, - func: payload.func - }) - }) + await diskAnalyzer.fetchDiskAnalysisSnapshot(dllHost) + assert.equal(dllHost.calls.some((c) => c.channel === 'dllplugin_call'), false) }) // ---- 宿主 dir: 扫描截断:如实标注抽样,不把抽样当全盘结果;macOS 额外扫描 ~/Library/Caches ---- @@ -117,3 +112,68 @@ test('disk-analyzer: 宿主完整扫描(未截断)时不标抽样;畸形 const garbageSnap = await diskAnalyzer.fetchDiskAnalysisSnapshot(garbage) assert.equal(garbageSnap.sampled, undefined) }) + +test('disk-analyzer: scanRealDirectoryTree 透传 scan_error 与顶层 approximate,非系统盘截断保留有效大文件,清单含 shell 权限', async () => { + const { scanRealDirectoryTree } = await import('../dist/directory-scan.js') + const host = createRealHostStub({ + system_search_files: () => ({ + success: true, + data: { + files: [{ name: 'big.iso', path: 'D:\\Videos\\big.iso', is_dir: false, size: 512 * 1024 * 1024, mtime: 1700000000 }], + subdirs: [], + truncated: true, + approximate: true, + visited_entries: 2000, + scan_error: '部分子目录无权限' + } + }) + }) + const tree = await scanRealDirectoryTree('D:\\', 100, host) + assert.equal(tree.approximate, true) + assert.equal(tree.error, '部分子目录无权限') + + const manifest = JSON.parse(fs.readFileSync(path.resolve(__dirname, '../plugin.json'), 'utf8')) + assert.ok(manifest.permissions.includes('shell'), 'plugin.json 必须声明 shell 权限') + + // 验证真实宿主(无 hostOverride)下 Windows D:\ 截断仍保留非受保护大文件并标 sampled,且过滤受保护系统文件 + const { createHost } = await import('../../shared/test-harness.mjs') + const realHost = createHost() + try { + realHost.ipc.system_list_volumes = async () => ({ + volumes: [ + { path: 'C:\\', label: 'OS', fileSystem: 'NTFS', totalBytes: 256e9, usedBytes: 120e9, availableBytes: 136e9 }, + { path: 'D:\\', label: 'Data', fileSystem: 'NTFS', totalBytes: 512e9, usedBytes: 200e9, availableBytes: 312e9 } + ], + partial: false, + errors: [] + }) + realHost.ipc.system_get_path = async ({ name }) => ({ success: true, path: `C:\\Users\\Tester\\${name}` }) + realHost.ipc.system_list_common_folders = async () => ({ folders: [] }) + realHost.ipc.system_search_files = async ({ query }) => { + if (query === 'dir:D:\\') { + return { + files: [{ name: 'movie.mkv', path: 'D:\\Media\\movie.mkv', is_dir: false, size: 900 * 1024 * 1024, mtime: 1700000000 }], + subdirs: [], + truncated: true, + approximate: true, + visited_entries: 2000 + } + } + if (query === 'dir:C:\\') { + return { + files: [{ name: 'kernel32.dll', path: 'C:\\Windows\\System32\\kernel32.dll', is_dir: false, size: 10 * 1024 * 1024, mtime: 1700000000 }], + subdirs: [], + truncated: true, + visited_entries: 2000 + } + } + return { files: [], subdirs: [], truncated: false, visited_entries: 0 } + } + const snap = await diskAnalyzer.fetchDiskAnalysisSnapshot() + assert.equal(snap.sampled, true) + assert.ok(snap.files.some((f) => f.path === 'D:\\Media\\movie.mkv'), 'D:\\ 截断时应保留非受保护大文件') + assert.equal(snap.files.some((f) => f.path === 'C:\\Windows\\System32\\kernel32.dll'), false, '截断系统盘根的受保护系统文件应跳过') + } finally { + realHost.reset() + } +}) diff --git a/extensions/disk-analyzer/tests/disk-analyzer.old-host.test.mjs b/extensions/disk-analyzer/tests/disk-analyzer.old-host.test.mjs index 7c8b6a04..54991124 100644 --- a/extensions/disk-analyzer/tests/disk-analyzer.old-host.test.mjs +++ b/extensions/disk-analyzer/tests/disk-analyzer.old-host.test.mjs @@ -3,7 +3,7 @@ import test from 'node:test' import assert from 'node:assert/strict' import { setRuntimeLocale } from '@ztools/declarative-ui' import { createHost } from '../../shared/test-harness.mjs' -import { probeRealDiskDrives } from '../dist/volume-ipc.js' +import { probeRealDiskDrives, probeRealDiskDrivesWithStatus } from '../dist/volume-ipc.js' test('旧客户端读卷列表时提示升级', async () => { const host = createHost() @@ -14,6 +14,35 @@ test('旧客户端读卷列表时提示升级', async () => { await assert.rejects(probeRealDiskDrives(), /磁盘忙/) }) +test('partial: true 且存在有效卷时不抛错,透传 warnings;无有效卷时才抛错', async () => { + const host = createHost() + host.reset() + setRuntimeLocale('zh-CN') + host.ipc.system_list_volumes = async () => ({ + volumes: [ + { path: 'C:\\', label: '系统', fileSystem: 'NTFS', totalBytes: 500_000, usedBytes: 200_000, availableBytes: 300_000 } + ], + partial: true, + errors: ['D:\\: BitLocker 锁定分区无法读取'] + }) + const status = await probeRealDiskDrivesWithStatus() + assert.equal(status.partial, true) + assert.deepEqual(status.drives.map(d => d.drive), ['C:']) + assert.deepEqual(status.warnings, ['D:\\: BitLocker 锁定分区无法读取']) + // 兼容旧签名 probeRealDiskDrives:存在有效卷时不抛错 + const drives = await probeRealDiskDrives() + assert.deepEqual(drives.map(d => d.drive), ['C:']) + + // 全部卷均失败(无有效卷)时仍抛错 + host.ipc.system_list_volumes = async () => ({ + volumes: [], + partial: true, + errors: ['D:\\: BitLocker 锁定分区无法读取'] + }) + await assert.rejects(probeRealDiskDrivesWithStatus(), /挂载卷列表不完整:D:\\: BitLocker 锁定分区无法读取/) + await assert.rejects(probeRealDiskDrives(), /挂载卷列表不完整:D:\\: BitLocker 锁定分区无法读取/) +}) + test('i18n en-US: volume-ipc 全部错误提示与未知文件系统实时切换为英文且无中文残留', async () => { const host = createHost() host.reset() diff --git a/extensions/disk-analyzer/tests/disk-analyzer.scan-failures.test.mjs b/extensions/disk-analyzer/tests/disk-analyzer.scan-failures.test.mjs index cb5ab0eb..3b545412 100644 --- a/extensions/disk-analyzer/tests/disk-analyzer.scan-failures.test.mjs +++ b/extensions/disk-analyzer/tests/disk-analyzer.scan-failures.test.mjs @@ -140,6 +140,25 @@ test('界面:部分失败时列表照常展示,左侧列出未能扫描的 assert.equal(rejections.length, 0) }) +test('界面:部分磁盘卷读取失败(如 BitLocker 锁定分区)时正常列出有效卷并在顶部状态条提示告警', async () => { + installHost() + host.ipc.system_list_volumes = async () => ({ + volumes: [ + { path: '/', label: 'Macintosh HD', fileSystem: 'APFS', totalBytes: 500 * 1024 ** 3, usedBytes: 100 * 1024 ** 3, availableBytes: 400 * 1024 ** 3, capacityGroup: 'disk3' } + ], + partial: true, + errors: ['E:\\: BitLocker 锁定分区'] + }) + const view = await mountLoaded() + assert.ok(view.item('drive-/'), '已读到的磁盘卷应正常列出') + const summary = view.tree().props.filterBar.summaryText + assert.match(summary, /部分卷读取失败(E:\\: BitLocker 锁定分区)/) + assert.doesNotMatch(summary, /扫描失败/) + assert.deepEqual(fileTitles(view), ['movie.mp4']) + view.unmount() + assert.equal(rejections.length, 0) +}) + test('界面:全部目录失败时报扫描失败,不显示空的「完成」结果', async () => { installHost(Object.fromEntries([DOWNLOADS, DOCUMENTS, DESKTOP, `${HOME}/Movies`, '/private/var/folders/ab/T', `${HOME}/Library/Caches`, '/', EXT].map((d) => [d, 'denied']))) const view = await mountLoaded() diff --git a/extensions/dns-benchmark/README.en.md b/extensions/dns-benchmark/README.en.md new file mode 100644 index 00000000..638c6fea --- /dev/null +++ b/extensions/dns-benchmark/README.en.md @@ -0,0 +1,29 @@ +# DNS Benchmark + +On macOS, measures the latency of real DNS `A`-record queries for `example.com` across public DNS servers. Results reflect a single lookup and do not represent all websites or long-term network performance; failures are never replaced with fixed placeholder latencies. + +## Usage + +**macOS:** + +- Choose an active network service in the top-right corner, wait for the benchmark to finish, select a server, and press `Enter` to apply it. Applies one selected server address at a time; `⌘+Enter` copies the address. +- Changing DNS triggers a macOS administrator authorization prompt. Your previous configuration is backed up before writing; if the configuration was modified by another program in the meantime, the plugin stops and asks you to re-benchmark and reload the configuration first. +- Below the list, **Restore Automatic DNS** clears manual DNS addresses, while **Restore Latest Backup** restores the addresses saved before the last operation on that network service. Backups are stored per network service and retained even if an operation fails. +- **Flush DNS Cache** requests administrator authorization separately. Canceling authorization or a command failure reports failure rather than falsely reporting success. +- You can click **Cancel** while waiting for benchmarks or system authorization. If the system has already entered the commit phase, the apply or restore finishes before returning the actual result; requesting cancellation does not roll back an already succeeded change. +- If "Write status unconfirmed" is shown, reload the system configuration before deciding whether to restore the backup so you do not overwrite settings from other software. + +**Windows:** + +- Ranks servers by TCP port 53 connection latency (not DNS resolution latency) and switches DNS using `netsh`, which requires running as Administrator. + +## Platforms & Requirements + +- Supported: Windows, macOS +- Requires client version 1.1.8.5 or later. +- macOS requires the client's bundled DNS configuration component. Running from source without Xcode Command Line Tools may lack this component; official macOS release packages include it. +- Windows implementation is pending verification on physical hardware. + +## Network & Data + +- Benchmarking only connects to the 15 built-in public DNS servers (Alibaba Cloud, Tencent DNSPod, 114DNS, Cloudflare, Google, etc.): macOS sends an `A`-record query for `example.com` to each server, while Windows opens a TCP port 53 connection to each server. diff --git a/extensions/dns-benchmark/plugin.json b/extensions/dns-benchmark/plugin.json index a5e4749e..8eb59813 100644 --- a/extensions/dns-benchmark/plugin.json +++ b/extensions/dns-benchmark/plugin.json @@ -1,7 +1,8 @@ { "id": "dns-benchmark", "name": "DNS测速", - "version": "1.0.9", + "version": "1.0.10", + "minAppVersion": "1.1.8.0", "description": "测试公共 DNS 地址的响应情况,切换当前网络 DNS;Mac 支持真实域名解析、配置备份与恢复", "author": "ZTools Team", "entry": "dist/index.js", @@ -78,7 +79,12 @@ "latency", "flush dns", "network", - "resolver" + "resolver", + "dns benchmark", + "dns speed", + "fastest dns", + "nameserver", + "ping dns" ], "features": { "dns-benchmark-run": { @@ -122,5 +128,15 @@ { "path": "screenshots/02-action-panel.png" } + ], + "keywords": [ + "dns测速", + "测dns", + "最快dns", + "域名解析测速", + "网络卡", + "换dns", + "dns", + "benchmark" ] } diff --git a/extensions/dns-benchmark/src/dns-service.ts b/extensions/dns-benchmark/src/dns-service.ts index ab75ef39..5ee743d4 100644 --- a/extensions/dns-benchmark/src/dns-service.ts +++ b/extensions/dns-benchmark/src/dns-service.ts @@ -67,33 +67,45 @@ export function isSafeAdapterName(name: string): boolean { return !/[;&|`$<>\\"\r\n\0]/.test(trimmed) } +let dnsOpSeq = 0 +function nextDnsOperationId(): string { + dnsOpSeq = (dnsOpSeq + 1) % 1_000_000 + return `dns_${Date.now()}_${dnsOpSeq}` +} + +/** 缓存最近一次 list 返回的网卡静态 DNS,用于乐观并发校验(expectedServers) */ +const cachedServiceServers = new Map() + export async function getActiveNetworkAdapters( hostOverride?: unknown ): Promise { const res = await callHostTransport>( - 'dllplugin_call', + 'dns_benchmark', { - plugin: 'DnsBenchmarkPlugin', - func: 'getActiveAdapters', - params: {} + action: 'list', + operationId: nextDnsOperationId() }, hostOverride ) - if (!res.ok || !res.data || res.data.ok === false || !Array.isArray(res.data.adapters)) { + if (!res.ok || !res.data || res.data.success === false || !Array.isArray(res.data.services)) { throw new Error(resolveErrorMessage(res.data?.error ? res.data : res, t('errAdapterQuery'))) } - return (res.data.adapters as Array>) - .map((a) => { - const currentDns = Array.isArray(a.currentDns) ? a.currentDns.map(String) : [] + cachedServiceServers.clear() + return (res.data.services as Array>) + .map((s) => { + const name = String(s.name ?? '').trim() + const servers = Array.isArray(s.servers) ? s.servers.map(String).filter(Boolean) : [] + const addresses = Array.isArray(s.addresses) ? s.addresses.map(String).filter(Boolean) : [] + if (name) cachedServiceServers.set(name, [...servers]) return { - name: String(a.name ?? ''), - description: String(a.description ?? a.name ?? ''), - ipv4: String(a.ipv4 ?? ''), - isDhcp: Boolean(a.isDhcp ?? currentDns.length === 0), - currentDns + name, + description: String(s.device ?? name), + ipv4: addresses[0] ?? '', + isDhcp: servers.length === 0, + currentDns: servers } }) - .filter((a) => a.name) + .filter((a) => Boolean(a.name)) } export function sortAndMarkDnsItems( @@ -121,7 +133,7 @@ export function sortAndMarkDnsItems( const noResult = matched === undefined const timeout = matched?.timeout === true const rawAvg = Number(matched?.avgMs) - const avgMs = Number.isFinite(rawAvg) && rawAvg > 0 ? Math.round(rawAvg) : 0 + const avgMs = Number.isFinite(rawAvg) && rawAvg >= 0 ? Math.round(rawAvg) : 0 const isCurrentActive = activeSet.has(preset.primary) || (Boolean(preset.secondary) && activeSet.has(preset.secondary)) @@ -151,36 +163,65 @@ export async function runDnsBenchmark( hostOverride?: unknown, presets: readonly DnsProviderPreset[] = getPublicDnsPresets() ): Promise<{ items: DnsBenchmarkItem[]; fastestDns: DnsBenchmarkItem | null; allTimeout: boolean }> { + const uniqueServers: string[] = [] + const seen = new Set() + for (const p of presets) { + for (const addr of [p.primary, p.secondary]) { + const ip = String(addr ?? '').trim() + if (ip && isValidIpv4Address(ip) && !seen.has(ip)) { + seen.add(ip) + uniqueServers.push(ip) + } + } + } + const res = await callHostTransport>( - 'dllplugin_call', + 'dns_benchmark', { - plugin: 'DnsBenchmarkPlugin', - func: 'benchmarkDns', - params: { - servers: presets.map((p) => ({ - id: p.id, - primary: p.primary, - secondary: p.secondary - })) - } + action: 'benchmark', + operationId: nextDnsOperationId(), + servers: uniqueServers.slice(0, 40) }, hostOverride ) // 测速接口失败要如实报错,不能显示成“所有节点超时” - if (!res.ok || !res.data || res.data.ok === false || !Array.isArray(res.data.results)) { + if (!res.ok || !res.data || res.data.success === false || !Array.isArray(res.data.results)) { throw new Error(resolveErrorMessage(res.data?.error ? res.data : res, t('errBenchmarkFailed'))) } - const rawResults = res.data.results as Array<{ - id?: string - primary?: string - avgMs?: number - primaryMs?: number | null - secondaryMs?: number | null - timeout?: boolean - }> - const sorted = sortAndMarkDnsItems(presets, rawResults, activeDnsList) + const probeByServer = new Map() + for (const entry of res.data.results as Array>) { + const server = typeof entry?.server === 'string' ? entry.server.trim() : '' + if (!server) continue + const ms = entry.milliseconds + probeByServer.set(server, typeof ms === 'number' && Number.isFinite(ms) && ms >= 0 ? Math.round(ms) : null) + } + + const aggregated = presets + .map((p) => { + const hasPrimary = probeByServer.has(p.primary) + const hasSecondary = Boolean(p.secondary) && probeByServer.has(p.secondary) + if (!hasPrimary && !hasSecondary) return null + const primaryMs = hasPrimary ? (probeByServer.get(p.primary) ?? null) : null + const secondaryMs = hasSecondary ? (probeByServer.get(p.secondary) ?? null) : null + const anyOk = primaryMs !== null || secondaryMs !== null + const avgMs = + primaryMs !== null && secondaryMs !== null + ? Math.round((primaryMs + secondaryMs) / 2) + : (primaryMs ?? secondaryMs ?? 0) + return { + id: p.id, + primary: p.primary, + avgMs, + primaryMs, + secondaryMs, + timeout: !anyOk + } + }) + .filter((item): item is NonNullable => item !== null) + + const sorted = sortAndMarkDnsItems(presets, aggregated, activeDnsList) const fastestDns = sorted.find((item) => !item.timeout && !item.noResult) ?? null const allTimeout = sorted.length > 0 && sorted.every((item) => item.timeout) return { @@ -194,7 +235,8 @@ export async function applyAdapterDns( adapterName: string, primary: string, secondary = '', - hostOverride?: unknown + hostOverride?: unknown, + expectedServers?: readonly string[] ): Promise { if (!isSafeAdapterName(adapterName)) { return { @@ -203,7 +245,9 @@ export async function applyAdapterDns( error: t('errInvalidAdapter') } } - if (!isValidIpv4Address(primary) || (secondary && !isValidIpv4Address(secondary))) { + const cleanPrimary = primary.trim() + const cleanSecondary = secondary.trim() + if (!isValidIpv4Address(cleanPrimary) || (cleanSecondary && !isValidIpv4Address(cleanSecondary))) { return { ok: false, errorCode: 'INVALID_DNS_IP', @@ -211,47 +255,51 @@ export async function applyAdapterDns( } } + const serviceName = adapterName.trim() + const targetServers = cleanSecondary && cleanSecondary !== cleanPrimary ? [cleanPrimary, cleanSecondary] : [cleanPrimary] + const expected = expectedServers ? [...expectedServers] : [...(cachedServiceServers.get(serviceName) ?? [])] + const res = await callHostTransport>( - 'dllplugin_call', + 'dns_benchmark', { - plugin: 'DnsBenchmarkPlugin', - func: 'applyDns', - params: { - adapterName: adapterName.trim(), - primary: primary.trim(), - secondary: secondary.trim(), - executeSystemModify: hostOverride === undefined - } + action: 'apply', + operationId: nextDnsOperationId(), + service: serviceName, + expectedServers: expected, + servers: targetServers }, hostOverride ) - if (!res.ok || (res.data && res.data.ok === false)) { + if (!res.ok || !res.data || res.data.success === false) { const rawErrText = String(res.data?.error ?? res.error ?? '') - const codeMatch = rawErrText.match(/^([A-Z0-9_]+):/) + const codeMatch = rawErrText.match(/\b(SECONDARY_DNS_FAILED|ADMIN_PRIVILEGE_REQUIRED|TIMEOUT|NETSH_FAILED|INVALID_ADAPTER_NAME|INVALID_DNS_IP)\b|^([A-Z0-9_]+):/) return { ok: false, - errorCode: String(res.data?.errorCode ?? codeMatch?.[1] ?? 'APPLY_DNS_FAILED'), + errorCode: String(res.data?.errorCode ?? codeMatch?.[1] ?? codeMatch?.[2] ?? res.errorCode ?? 'APPLY_DNS_FAILED'), error: resolveErrorMessage(res.data?.error ? res.data : res, t('errApplyDns')) } } - // 以宿主重新读出的系统实际 DNS 为准;读不到时不假定已生效 - const currentDns = Array.isArray(res.data?.currentDns) ? (res.data.currentDns as unknown[]).map(String) : undefined - const flushError = typeof res.data?.flushError === 'string' ? res.data.flushError : undefined + const svc = res.data.service && typeof res.data.service === 'object' ? (res.data.service as Record) : null + const currentDns = Array.isArray(svc?.servers) ? (svc.servers as unknown[]).map(String) : undefined + if (currentDns) cachedServiceServers.set(serviceName, [...currentDns]) + + const flushRes = await flushSystemDnsCache(hostOverride) return { ok: true, - adapterName: adapterName.trim(), + adapterName: serviceName, ...(currentDns ? { currentDns } : {}), - isDhcp: res.data?.isDhcp === true, - flushed: res.data?.flushed === true, - ...(flushError ? { flushError } : {}) + isDhcp: currentDns ? currentDns.length === 0 : false, + flushed: flushRes.ok, + ...(!flushRes.ok && flushRes.error ? { flushError: flushRes.error } : {}) } } export async function resetAdapterToDhcp( adapterName: string, - hostOverride?: unknown + hostOverride?: unknown, + expectedServers?: readonly string[] ): Promise { if (!isSafeAdapterName(adapterName)) { return { @@ -261,55 +309,58 @@ export async function resetAdapterToDhcp( } } + const serviceName = adapterName.trim() + const expected = expectedServers ? [...expectedServers] : [...(cachedServiceServers.get(serviceName) ?? [])] + const res = await callHostTransport>( - 'dllplugin_call', + 'dns_benchmark', { - plugin: 'DnsBenchmarkPlugin', - func: 'resetDhcp', - params: { - adapterName: adapterName.trim(), - executeSystemModify: hostOverride === undefined - } + action: 'reset', + operationId: nextDnsOperationId(), + service: serviceName, + expectedServers: expected }, hostOverride ) - if (!res.ok || (res.data && res.data.ok === false)) { + if (!res.ok || !res.data || res.data.success === false) { const rawErrText = String(res.data?.error ?? res.error ?? '') - const codeMatch = rawErrText.match(/^([A-Z0-9_]+):/) + const codeMatch = rawErrText.match(/\b(ADMIN_PRIVILEGE_REQUIRED|TIMEOUT|NETSH_FAILED|INVALID_ADAPTER_NAME)\b|^([A-Z0-9_]+):/) return { ok: false, - errorCode: String(res.data?.errorCode ?? codeMatch?.[1] ?? 'RESET_DHCP_FAILED'), + errorCode: String(res.data?.errorCode ?? codeMatch?.[1] ?? codeMatch?.[2] ?? res.errorCode ?? 'RESET_DHCP_FAILED'), error: resolveErrorMessage(res.data?.error ? res.data : res, t('errResetDhcp')) } } - const currentDns = Array.isArray(res.data?.currentDns) ? (res.data.currentDns as unknown[]).map(String) : undefined - const flushError = typeof res.data?.flushError === 'string' ? res.data.flushError : undefined + const svc = res.data.service && typeof res.data.service === 'object' ? (res.data.service as Record) : null + const currentDns = Array.isArray(svc?.servers) ? (svc.servers as unknown[]).map(String) : [] + cachedServiceServers.set(serviceName, [...currentDns]) + + const flushRes = await flushSystemDnsCache(hostOverride) return { ok: true, - adapterName: adapterName.trim(), - ...(currentDns ? { currentDns } : {}), - isDhcp: res.data?.isDhcp !== false, - flushed: res.data?.flushed === true, - ...(flushError ? { flushError } : {}) + adapterName: serviceName, + currentDns, + isDhcp: currentDns.length === 0, + flushed: flushRes.ok, + ...(!flushRes.ok && flushRes.error ? { flushError: flushRes.error } : {}) } } export async function flushSystemDnsCache(hostOverride?: unknown): Promise { const res = await callHostTransport>( - 'dllplugin_call', + 'dns_benchmark', { - plugin: 'DnsBenchmarkPlugin', - func: 'flushCache', - params: {} + action: 'flush', + operationId: nextDnsOperationId() }, hostOverride ) - if (!res.ok || (res.data && res.data.ok === false)) { + if (!res.ok || !res.data || res.data.success === false) { return { ok: false, - errorCode: 'FLUSH_DNS_FAILED', + errorCode: String(res.data?.errorCode ?? res.errorCode ?? 'FLUSH_DNS_FAILED'), error: resolveErrorMessage(res.data?.error ? res.data : res, t('errFlushCache')) } } diff --git a/extensions/dns-benchmark/src/index.tsx b/extensions/dns-benchmark/src/index.tsx index e9d4a039..067cdd39 100644 --- a/extensions/dns-benchmark/src/index.tsx +++ b/extensions/dns-benchmark/src/index.tsx @@ -151,7 +151,7 @@ function WindowsDnsBenchmarkCommand(props: DnsBenchmarkCommandProps = {}) { dismissAction: { title: t('cancelBtn') } }) if (confirmed && !cancelled) { - const rRes = await resetAdapterToDhcp(activeAdapter.name, props.hostOverride) + const rRes = await resetAdapterToDhcp(activeAdapter.name, props.hostOverride, activeAdapter.currentDns) if (!cancelled) { if (!rRes.ok) { await showToast({ @@ -225,7 +225,7 @@ function WindowsDnsBenchmarkCommand(props: DnsBenchmarkCommandProps = {}) { await showToast({ style: Toast.Style.Failure, title: t('toastNoAdapter') }) return } - const res = await applyAdapterDns(targetNic, dns.primary, dns.secondary, props.hostOverride) + const res = await applyAdapterDns(targetNic, dns.primary, dns.secondary, props.hostOverride, currentDnsList) if (!res.ok) { const title = resolveErrorMessage(res, t('errApplyDns')) await showToast({ @@ -276,7 +276,7 @@ function WindowsDnsBenchmarkCommand(props: DnsBenchmarkCommandProps = {}) { await showToast({ style: Toast.Style.Failure, title: t('toastNoAdapter') }) return } - const res = await resetAdapterToDhcp(targetNic, props.hostOverride) + const res = await resetAdapterToDhcp(targetNic, props.hostOverride, currentDnsList) if (!res.ok) { const title = resolveErrorMessage(res, t('errResetDhcp')) await showToast({ diff --git a/extensions/dns-benchmark/src/native-ipc.ts b/extensions/dns-benchmark/src/native-ipc.ts index 51576b99..13643277 100644 --- a/extensions/dns-benchmark/src/native-ipc.ts +++ b/extensions/dns-benchmark/src/native-ipc.ts @@ -174,11 +174,13 @@ function normalizeMethodResult(method: string, payload: DynamicBridge): DynamicB if (method === 'system_get_battery_status') { // 宿主约定 percent 超出 0-100(如 255)表示无电池或电量未知,不能改写成 100% + // 若宿主明确给出 hasBattery 布尔值,必须原样保留,仅在缺失时按合法电量推算 const rawPct = payload.percent - const hasBattery = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const validPct = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const hasBattery = typeof payload.hasBattery === 'boolean' ? payload.hasBattery : validPct return { ...payload, - percent: hasBattery ? rawPct : null, + percent: validPct ? rawPct : null, hasBattery } } @@ -489,6 +491,8 @@ export interface RealDirectoryScanResult extends Iterable approximate?: boolean /** 宿主实际遍历的条目数 */ visitedEntries?: number + /** 目录本身不存在(ENOENT) */ + missing?: boolean /** 读取失败的真实原因;已有文件仍可使用,但不能当作完整结果。 */ error?: string } @@ -497,6 +501,7 @@ interface ScanResultMeta { truncated?: boolean approximate?: boolean visitedEntries?: number + missing?: boolean } export interface ScanDirectoryTreeOptions { @@ -504,6 +509,10 @@ export interface ScanDirectoryTreeOptions { maxFiles?: number collectTopN?: number filterExt?: RegExp + /** 为 true 时,目录本身不存在(ENOENT)按空目录处理,不返回 error(权限拒绝/读取失败仍照常报错) */ + ignoreMissing?: boolean + /** Top-N 保留与排序方式:默认按体积降序,下载/录屏等时效场景可传 mtime-desc */ + sortBy?: 'size-desc' | 'mtime-desc' hostOverride?: DynamicBridge } @@ -519,8 +528,9 @@ function normalizeIndexedFileEntry(f: DynamicBridge): RealIndexedFileEntry { const sz = Number(f?.size ?? f?.sizeBytes ?? 0) const isDir = Boolean(f?.is_dir || f?.isDir || f?.isDirectory) const rawMtime = Number(f?.mtime ?? f?.mtimeMs ?? 0) - const mtimeMs = rawMtime > 1e11 ? rawMtime : rawMtime > 0 ? rawMtime * 1000 : Date.now() - const mtimeSec = rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime + const validMtime = Number.isFinite(rawMtime) && rawMtime > 0 + const mtimeMs = validMtime ? (rawMtime > 1e11 ? rawMtime : rawMtime * 1000) : 0 + const mtimeSec = validMtime ? (rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime) : 0 if (p && sz >= 0) realFileSizeCache.set(p, sz) return { name, @@ -551,6 +561,7 @@ function makeScanResult( subdirs, ...(meta.truncated ? { truncated: true } : {}), ...(meta.approximate ? { approximate: true } : {}), + ...(meta.missing ? { missing: true } : {}), ...(typeof meta.visitedEntries === 'number' ? { visitedEntries: meta.visitedEntries } : {}), [Symbol.iterator]() { return files[Symbol.iterator]() @@ -609,13 +620,40 @@ export async function scanRealDirectoryTree( return result.error ? { ...result.scan, error: result.error } : result.scan } +/** 仅当正则明确声明了扩展名(含 `\.`)时提取后缀列表,避免把 `thumbcache|iconcache` 等文件名关键词误拆成假扩展名 */ +function extractExtensionTokensFromFilter(filterExt: RegExp): string[] { + const src = filterExt.source + if (!src.includes('\\.')) return [] + const afterDot = src.slice(src.indexOf('\\.') + 2) + const rawTokens = afterDot.match(/[a-z0-9]{1,8}/gi) || [] + const seen = new Set() + const out: string[] = [] + for (const token of rawTokens) { + const lower = token.toLowerCase() + if (!lower || seen.has(lower)) continue + seen.add(lower) + out.push(lower) + } + return out +} + +function isMissingDirectoryError(res: { error?: string; errorCode?: string; errorDetails?: Record }): boolean { + if (res.errorDetails?.reason === 'ENOENT' || res.errorCode === 'ENOENT') return true + const msg = String(res.error || '') + return /Directory does not exist|ENOENT/i.test(msg) +} + /** 一次界面扫描的错误汇总;多个目录并行扫描时保留可读目录的结果。 */ export function createDirectoryScanner(hostOverride?: DynamicBridge) { const failures = new Map() return { async scan(dir: string, options: number | ScanDirectoryTreeOptions = 160) { const result = await scanRealDirectoryTree(dir, options, hostOverride) - const error = result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') + const ignoreMissing = typeof options === 'object' && options !== null && options.ignoreMissing === true + const error = + result.missing && ignoreMissing + ? '' + : result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') if (error) failures.set(dir, error) else failures.delete(dir) return result @@ -648,26 +686,38 @@ async function scanDirectoryTreeWithError( const safeLimit = Math.min(200, Math.max(1, Math.floor(rawLimit || 160))) const hostOverride = opts.hostOverride const filterExt = opts.filterExt + const ignoreMissing = opts.ignoreMissing === true const dirQuery = `dir:${targetDir}` try { let rawPayload: DynamicBridge = null + const searchParams: Record = { + query: dirQuery, + limit: safeLimit, + ...(opts.sortBy ? { sortBy: opts.sortBy } : {}) + } const res = await callHostTransport( 'system_search_files', - { query: dirQuery, limit: safeLimit }, + searchParams, hostOverride ) - if (res.ok && res.data) { + if (res.ok && res.data && res.data.degraded !== true) { rawPayload = res.data + } else if (!res.ok && ignoreMissing && isMissingDirectoryError(res)) { + const missingScan = makeScanResult([], 0, 0, [], { missing: true }) + return { scan: missingScan } } - if (!rawPayload && !hostOverride && typeof window !== 'undefined') { + if (!rawPayload && !hostOverride && res.errorCode === 'METHOD_NOT_AVAILABLE' && typeof window !== 'undefined') { const w = window as DynamicBridge if (typeof w.__ztoolsLauncher?.searchFiles === 'function') { const rawOuter = await w.__ztoolsLauncher.searchFiles(dirQuery, safeLimit) - rawPayload = + const candidate = rawOuter && typeof rawOuter === 'object' && 'data' in rawOuter && rawOuter.data ? rawOuter.data : rawOuter + if (candidate && candidate.degraded !== true && candidate.success !== false) { + rawPayload = candidate + } } } @@ -678,29 +728,32 @@ async function scanDirectoryTreeWithError( let files: RealIndexedFileEntry[] = rawPayload.files.map(normalizeIndexedFileEntry) if (filterExt instanceof RegExp) { files = files.filter(f => !f.isDir && (filterExt.test(f.name) || filterExt.test(f.ext))) - // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索目标扩展名 + // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索明确声明的目标扩展名 if (files.length === 0 && !hostOverride) { - const extTokens = (filterExt.source.match(/[a-z0-9]{2,5}/gi) || []) - .filter(t => !['thumbcache', 'iconcache'].includes(t.toLowerCase())) - .slice(0, 4) - // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 - const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() - const extraLists = await Promise.all( - extTokens.map(ext => searchRealIndexedFiles(`.${ext.toLowerCase()}`, 30, hostOverride)) - ) - const seen = new Set() - for (const list of extraLists) { - for (const item of list) { - if (!item.isDir && item.size > 0 && !seen.has(item.path)) { - if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { - seen.add(item.path) - files.push(item) + const extTokens = extractExtensionTokensFromFilter(filterExt) + if (extTokens.length > 0) { + // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 + const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() + const extraLists = await Promise.all( + extTokens.map(ext => searchRealIndexedFiles(`.${ext}`, 30, hostOverride)) + ) + const seen = new Set() + for (const list of extraLists) { + for (const item of list) { + if (!item.isDir && item.size > 0 && !seen.has(item.path)) { + if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { + seen.add(item.path) + files.push(item) + } } } } } } } + // 先基于过滤后的完整命中集合计算总文件数与总字节数,再按 collectTopN 裁剪样本列表 + const matchedCount = files.length + const matchedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) if (typeof opts.collectTopN === 'number' && opts.collectTopN > 0 && files.length > opts.collectTopN) { files = files.slice(0, opts.collectTopN) } @@ -714,11 +767,10 @@ async function scanDirectoryTreeWithError( ...(s.approximate === true ? { approximate: true } : {}) })) : [] - const computedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) const totalFilesCount = - filterExt instanceof RegExp ? files.length : Number(rawPayload.total_matches ?? files.length) + filterExt instanceof RegExp ? matchedCount : Number(rawPayload.total_matches ?? matchedCount) const totalBytesCount = - filterExt instanceof RegExp ? computedBytes : Number(rawPayload.total_bytes ?? computedBytes) + filterExt instanceof RegExp ? matchedBytes : Number(rawPayload.total_bytes ?? matchedBytes) const visited = Number(rawPayload.visited_entries) return { scan: makeScanResult(files, totalFilesCount, totalBytesCount, subdirs, { @@ -1817,8 +1869,6 @@ export async function writeRealClipboardText(text: string, hostOverride?: Dynami const payload = { text: String(text || '') } const res = await callHostTransport('clipboard_copy_text', payload, hostOverride) if (res.ok) return true - const fallbackRes = await callHostTransport('clipboard_write_text', payload, hostOverride) - if (fallbackRes.ok) return true try { if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) { await navigator.clipboard.writeText(String(text || '')) diff --git a/extensions/dns-benchmark/tests/windows-dns-refresh.test.mjs b/extensions/dns-benchmark/tests/windows-dns-refresh.test.mjs index cc573237..a39419f2 100644 --- a/extensions/dns-benchmark/tests/windows-dns-refresh.test.mjs +++ b/extensions/dns-benchmark/tests/windows-dns-refresh.test.mjs @@ -5,42 +5,57 @@ import { createHost, mount, tick } from '../../shared/test-harness.mjs' const host = createHost(), views = [] async function settled() { for (let i = 0; i < 6; i++) await tick() } -const calls = func => host.ipcCalls.filter(([m, p]) => m === 'dllplugin_call' && p.func === func) +const calls = action => host.ipcCalls.filter(([m, p]) => m === 'dns_benchmark' && p.action === action) const isActive = item => item.props.accessories.some(a => a.tag === '当前生效') -/** Windows 旧接口替身:adapterDns 为网卡当前真实 DNS,applyDns / resetDhcp 的结果可按用例替换 */ +/** Windows 专用 dns_benchmark 接口替身:adapterDns 为网卡当前真实 DNS,apply / reset 的结果可按用例替换 */ let adapterDns, applyDns, resetDhcp, adapterFault test.beforeEach(() => { host.reset() adapterDns = ['223.5.5.5', '223.6.6.6']; adapterFault = null - applyDns = async () => ({ ok: true, success: true, currentDns: adapterDns }) - resetDhcp = async () => ({ ok: true, success: true, currentDns: [], isDhcp: true }) + applyDns = async (params) => { + adapterDns = [...params.servers] + return { success: true, service: { name: '以太网', device: 'Intel', addresses: ['192.0.2.10'], servers: [...adapterDns], backup: null } } + } + resetDhcp = async () => { + adapterDns = [] + return { success: true, service: { name: '以太网', device: 'Intel', addresses: ['192.0.2.10'], servers: [], backup: null } } + } host.ipc.system_get_platform = async () => ({ success: true, platform: 'windows' }) - host.ipc.dllplugin_call = async ({ func, params }) => { - if (func === 'getActiveAdapters') { - if (adapterFault) return { ok: false, success: false, error: adapterFault } - return { ok: true, adapters: [{ name: '以太网', description: 'Intel', ipv4: '192.0.2.10', isDhcp: false, currentDns: [...adapterDns] }] } + host.ipc.dns_benchmark = async (params) => { + if (params.action === 'list') { + if (adapterFault) throw new Error(adapterFault) + return { success: true, services: [{ name: '以太网', device: 'Intel', addresses: ['192.0.2.10'], servers: [...adapterDns], backup: null }] } + } + if (params.action === 'benchmark') { + return { + success: true, + domain: 'example.com', + results: params.servers.map((server, i) => ({ server, milliseconds: 10 + i, answers: ['192.0.2.9'], error: null })) + } } - if (func === 'benchmarkDns') return { ok: true, results: params.servers.map((s, i) => ({ id: s.id, primary: s.primary, avgMs: 10 + i, timeout: false })) } - if (func === 'applyDns') return applyDns(params) - if (func === 'resetDhcp') return resetDhcp(params) - throw new Error(`未预期的调用 ${func}`) + if (params.action === 'apply') return applyDns(params) + if (params.action === 'reset') return resetDhcp(params) + if (params.action === 'flush') return { success: true } + if (params.action === 'cancel') return { success: true, cancelled: true } + throw new Error(`未预期的调用 ${params.action}`) } }) test.afterEach(() => views.splice(0).forEach(v => v.unmount())) async function open() { const v = await mount(() => DnsCommand({})); views.push(v); await settled(); return v } -test('备用 DNS 设置失败(主 DNS 已改):提示失败后重新读取网卡,按真实 DNS 标记“当前生效”,不重新测速', async () => { +test('备用 DNS 设置失败(主 DNS 已改):提示失败后重新读取网卡,按真实 DNS 标记“当前生效”,不重新测速且不走 dllplugin_call', async () => { const v = await open() - assert.equal(calls('getActiveAdapters').length, 1); assert.equal(calls('benchmarkDns').length, 1) + assert.equal(calls('list').length, 1); assert.equal(calls('benchmark').length, 1) + assert.ok(!host.ipcCalls.some(([m]) => m === 'dllplugin_call'), 'Windows 端绝不可调用 dllplugin_call') assert.ok(isActive(v.item('alidns'))) // 宿主:主 DNS 已写入,备用 DNS 失败 - applyDns = async () => { adapterDns = ['114.114.114.114']; return { ok: false, success: false, errorCode: 'SECONDARY_DNS_FAILED', error: 'SECONDARY_DNS_FAILED: 主 DNS 已修改,备用 DNS 设置失败' } } + applyDns = async () => { adapterDns = ['114.114.114.114']; throw new Error('SECONDARY_DNS_FAILED: 主 DNS 已修改,备用 DNS 设置失败') } await v.run(v.item('114dns'), v.actions(v.item('114dns'))[0].props.title) await settled() - assert.equal(calls('applyDns').length, 1) - assert.equal(calls('getActiveAdapters').length, 2, '失败后必须重新读取网卡') - assert.equal(calls('benchmarkDns').length, 1, '只重新读取 DNS,不重新测速') + assert.equal(calls('apply').length, 1) + assert.equal(calls('list').length, 2, '失败后必须重新读取网卡') + assert.equal(calls('benchmark').length, 1, '只重新读取 DNS,不重新测速') const failure = host.toasts.find(t => /SECONDARY_DNS_FAILED/.test(t.title)) assert.ok(failure); assert.equal(failure.style, 'FAILURE'); assert.match(failure.message, /重新读取/) assert.ok(!host.toasts.some(t => String(t.style).toUpperCase() === 'SUCCESS')) @@ -53,10 +68,10 @@ test('备用 DNS 设置失败(主 DNS 已改):提示失败后重新读取 test('其他失败同样重新读取;重新读取也失败时不再标记任何“当前生效”,并如实提示状态未知', async () => { const v = await open() - applyDns = async () => { adapterFault = 'DNS_ADAPTER_QUERY_FAILED: 无法枚举系统活动网卡'; return { ok: false, success: false, errorCode: 'APPLY_DNS_FAILED', error: 'APPLY_DNS_FAILED: 拒绝访问' } } + applyDns = async () => { adapterFault = 'DNS_ADAPTER_QUERY_FAILED: 无法枚举系统活动网卡'; throw new Error('APPLY_DNS_FAILED: 拒绝访问') } await v.run(v.item('114dns'), v.actions(v.item('114dns'))[0].props.title) await settled() - assert.equal(calls('getActiveAdapters').length, 2) + assert.equal(calls('list').length, 2) assert.ok(v.items().every(item => !isActive(item))) const last = host.lastToast() assert.equal(last.style, 'FAILURE') @@ -65,7 +80,7 @@ test('其他失败同样重新读取;重新读取也失败时不再标记任 assert.match(v.text(), /DNS 状态未知/) // 之后重新读取成功会清除“状态未知” adapterFault = null; adapterDns = ['223.5.5.5'] - applyDns = async () => ({ ok: false, success: false, error: 'SECONDARY_DNS_FAILED: 备用失败' }) + applyDns = async () => { throw new Error('SECONDARY_DNS_FAILED: 备用失败') } await v.run(v.item('114dns'), v.actions(v.item('114dns'))[0].props.title) await settled() assert.doesNotMatch(v.text(), /DNS 状态未知/) @@ -75,11 +90,11 @@ test('其他失败同样重新读取;重新读取也失败时不再标记任 test('恢复 DHCP 失败后同样重新读取网卡 DNS', async () => { const v = await open() const resetTitle = '恢复网卡为 DHCP 自动获取 DNS' - const before = calls('getActiveAdapters').length - resetDhcp = async () => { adapterDns = []; return { ok: false, success: false, error: 'RESET_DHCP_FAILED: 部分完成' } } + const before = calls('list').length + resetDhcp = async () => { adapterDns = []; throw new Error('RESET_DHCP_FAILED: 部分完成') } await v.run(v.item('alidns'), resetTitle) await settled() - assert.equal(calls('getActiveAdapters').length, before + 1) + assert.equal(calls('list').length, before + 1) assert.ok(v.items().every(item => !isActive(item))) assert.ok(host.toasts.some(t => /RESET_DHCP_FAILED/.test(t.title) && t.style === 'FAILURE')) }) @@ -91,25 +106,32 @@ test('回归:Windows 端 dns-reset-dhcp 入口弹窗确认防误触,取消 await settled() assert.equal(host.confirms.length, 1) assert.match(host.confirms[0].title, /以太网/) - assert.equal(calls('resetDhcp').length, 0, '取消确认后绝不能调用 resetDhcp') + assert.equal(calls('reset').length, 0, '取消确认后绝不能调用 reset') host.reset() adapterDns = ['223.5.5.5', '223.6.6.6'] host.ipc.system_get_platform = async () => ({ success: true, platform: 'windows' }) - host.ipc.dllplugin_call = async ({ func, params }) => { - if (func === 'getActiveAdapters') { - return { ok: true, adapters: [{ name: '以太网', description: 'Intel', ipv4: '192.0.2.10', isDhcp: adapterDns.length === 0, currentDns: [...adapterDns] }] } + host.ipc.dns_benchmark = async (params) => { + if (params.action === 'list') { + return { success: true, services: [{ name: '以太网', device: 'Intel', addresses: ['192.0.2.10'], servers: [...adapterDns], backup: null }] } + } + if (params.action === 'benchmark') { + return { success: true, domain: 'example.com', results: params.servers.map((server, i) => ({ server, milliseconds: 10 + i, answers: ['192.0.2.9'], error: null })) } + } + if (params.action === 'reset') { + adapterDns = [] + return { success: true, service: { name: '以太网', device: 'Intel', addresses: ['192.0.2.10'], servers: [], backup: null } } } - if (func === 'benchmarkDns') return { ok: true, results: params.servers.map((s, i) => ({ id: s.id, primary: s.primary, avgMs: 10 + i, timeout: false })) } - if (func === 'resetDhcp') { adapterDns = []; return { ok: true, success: true, currentDns: [], isDhcp: true } } - throw new Error(`未预期的调用 ${func}`) + if (params.action === 'flush') return { success: true } + throw new Error(`未预期的调用 ${params.action}`) } host.setConfirm(true) const vConfirm = await mount(() => DnsCommand({ featureCode: 'dns-reset-dhcp' })) views.push(vConfirm) await settled() assert.equal(host.confirms.length, 1) - assert.equal(calls('resetDhcp').length, 1, '确认后应调用 resetDhcp') + assert.equal(calls('reset').length, 1, '确认后应调用 reset') + assert.ok(!host.ipcCalls.some(([m]) => m === 'dllplugin_call')) assert.ok(host.toasts.some(t => t.style === 'SUCCESS' && /DHCP/.test(t.title))) }) diff --git a/extensions/docker-manager/README.en.md b/extensions/docker-manager/README.en.md new file mode 100644 index 00000000..58311f10 --- /dev/null +++ b/extensions/docker-manager/README.en.md @@ -0,0 +1,22 @@ +# Docker Container Manager + +Inspect local Docker container status, port mappings, and CPU/memory snapshots; start, stop, and restart containers; read the last 100 log lines; and remove stopped containers after confirming a checklist. + +## Usage + +- Commands: View all local Docker containers, port mappings, and recent logs (keywords such as `docker`, `containers`, `docker ps`), plus "Filter running containers and inspect CPU and memory usage" (`running containers`, `docker stats`) and "List and remove stopped containers after confirmation while keeping volumes" (`clean containers`, `prune docker`), which pre-filter for running or stopped containers upon opening. +- Selecting a container: If it is running and maps a common web port (`80`, `443`, `3000`, `8080`, etc.), `Enter` opens the corresponding local address in your browser; otherwise `Enter` opens logs. `⌘/Ctrl+Enter` starts or stops the container; `⌘/Ctrl+K` provides View Logs, Restart Container, and Copy Full Container ID. +- Resource metrics are single-point snapshots taken on refresh; read failures display the error reason rather than substituting zero values. Logs display stdout and stderr separately. +- **Clean Stopped Containers** displays a checklist first and, after confirmation, removes stopped containers one by one (up to 100 per batch) without removing images, mounted volumes, or host directories. Writable container layers are permanently deleted, so back up any data you need beforehand. +- You can click **Cancel** while an operation is running. After a failure, cancellation, or timeout, the container list refreshes to show the actual state; unconfirmed operations never report success. +- Requires Docker Desktop to be installed and running (on macOS, Colima or OrbStack with the Docker CLI and a local socket also works). The plugin uses your current Docker context without modifying Docker configuration; remote TCP/SSH contexts must be switched back to a local context in Docker first. + +## Platforms & Requirements + +- Supported: Windows, macOS +- Requires client version 1.1.8.5 or later. + +## Network & Data + +- Does not access the internet: communicates with the local Docker engine via the local Docker CLI (Unix socket or Windows named pipe). +- "Open Service Webpage" simply opens the container's locally mapped URL in your browser, such as `http://localhost:8080`. diff --git a/extensions/docker-manager/plugin.json b/extensions/docker-manager/plugin.json index 9bd49d62..b79418fd 100644 --- a/extensions/docker-manager/plugin.json +++ b/extensions/docker-manager/plugin.json @@ -1,7 +1,8 @@ { "id": "docker-manager", "name": "容器管控", - "version": "1.0.8", + "version": "1.0.9", + "minAppVersion": "1.1.8.0", "description": "查看本机 Docker 容器、端口和资源采样,支持启停、日志与确认后清理停止容器;需已安装并启动 Docker 环境", "author": "ZTools Team", "category": [ @@ -70,7 +71,12 @@ "logs", "ports", "devops", - "prune" + "prune", + "container", + "image", + "images", + "compose", + "restart container" ], "features": { "docker-all": { @@ -113,5 +119,15 @@ { "path": "screenshots/02-action-panel.png" } + ], + "keywords": [ + "容器", + "docker", + "镜像", + "容器管理", + "启停容器", + "看容器日志", + "码头", + "container" ] } diff --git a/extensions/docker-manager/src/docker-service.ts b/extensions/docker-manager/src/docker-service.ts index 2f6c6a8c..7346a923 100644 --- a/extensions/docker-manager/src/docker-service.ts +++ b/extensions/docker-manager/src/docker-service.ts @@ -1,7 +1,44 @@ import { t } from './i18n.js' -import type { ContainerSummary, DockerLogs, DockerSnapshot } from './types.js' -import { resolveErrorMessage } from './error-i18n.js' -interface Reply { success?: boolean; data?: unknown; error?: { message?: string } } +import type { ContainerSummary, DockerFailure, DockerFailureCode, DockerLogs, DockerPlatform, DockerSnapshot } from './types.js' +import { extractErrorCode, extractHostCode, extractRawErrorText, isDisplayableInCurrentLocale, resolveErrorMessage } from './error-i18n.js' + +export const DOCKER_DOWNLOAD_URLS = { + win32: 'https://docs.docker.com/desktop/setup/install/windows-install/', + darwin: 'https://docs.docker.com/desktop/setup/install/mac-install/', + default: 'https://www.docker.com/products/docker-desktop/' +} as const + +/** 检测当前运行平台(优先读取浏览器 navigator,Node 测试环境下回退 process.platform) */ +export function detectDockerPlatform(overridePlatform?: string): DockerPlatform { + const probe = ( + overridePlatform ?? + (() => { + const nav = (globalThis as { navigator?: { platform?: string; userAgent?: string } }).navigator + const navText = `${nav?.platform || ''} ${nav?.userAgent || ''}`.trim() + if (navText) return navText + const proc = (globalThis as { process?: { platform?: string } }).process + return proc?.platform || '' + })() + ).trim() + if (/darwin|mac/i.test(probe)) return 'darwin' + if (/win/i.test(probe)) return 'win32' + return 'other' +} + +/** 按当前操作系统返回对应的 Docker 官方下载安装页地址 */ +export function dockerDownloadUrl(platform: DockerPlatform = detectDockerPlatform()): string { + if (platform === 'win32') return DOCKER_DOWNLOAD_URLS.win32 + if (platform === 'darwin') return DOCKER_DOWNLOAD_URLS.darwin + return DOCKER_DOWNLOAD_URLS.default +} +interface ReplyError { + code?: string + errorCode?: string + message?: string + details?: Record + errorDetails?: Record +} +interface Reply { success?: boolean; data?: unknown; error?: ReplyError | string } interface Bridge { transport?: { methods?: Record Promise> } } let sequence = 0 function record(value: unknown): value is Record { return value !== null && typeof value === 'object' && !Array.isArray(value) } @@ -9,11 +46,263 @@ function validContainer(raw: unknown): raw is ContainerSummary { return record(raw) && typeof raw.id === 'string' && /^[0-9a-f]{64}$/.test(raw.id) && ['name', 'image', 'state', 'status', 'ports', 'createdAt'].every(k => typeof raw[k] === 'string') && ['created', 'running', 'paused', 'restarting', 'removing', 'exited', 'dead'].includes(String(raw.state)) && (raw.cpu === null || typeof raw.cpu === 'string') && (raw.memory === null || typeof raw.memory === 'string') } + +const KNOWN_HOST_CODES: ReadonlySet = new Set([ + 'DOCKER_CLI_NOT_FOUND', + 'DOCKER_DAEMON_OFFLINE', + 'DOCKER_PERMISSION_DENIED', + 'DOCKER_REMOTE_CONTEXT', + 'DOCKER_INVALID_CONTEXT', + 'DOCKER_CONTEXT_ENDPOINT_UNAVAILABLE', + 'DOCKER_REQUEST_TIMEOUT', + 'DOCKER_REQUEST_CANCELLED', + 'DOCKER_OUTPUT_TOO_LARGE', + 'DOCKER_SERVICE_STOPPED', + 'DOCKER_OPERATION_IN_PROGRESS', + 'DOCKER_DAEMON_INVALID_IDENTITY', + 'DOCKER_TOO_MANY_SESSIONS', + 'DOCKER_SESSION_EXPIRED', + 'DOCKER_CONTEXT_CHANGED', + 'DOCKER_CONTAINER_NOT_IN_LIST', + 'DOCKER_CONTAINER_STATE_UNVERIFIABLE', + 'DOCKER_CONTAINER_STATE_CHANGED', + 'DOCKER_CONTAINER_STATE_UNSUPPORTED', + 'DOCKER_CONTAINER_STATE_UNCONFIRMED', + 'DOCKER_INVALID_CONTAINER_LIST', + 'DOCKER_REMOVE_NOT_STOPPED', + 'DOCKER_CLIENT_UPGRADE_REQUIRED' +]) + +function readPublicMeta(source: unknown): { context?: string; state?: string } { + if (!record(source)) return {} + const details = record(source.errorDetails) ? source.errorDetails : record(source.details) ? source.details : undefined + if (!details) return {} + const context = typeof details.context === 'string' && details.context.trim() ? details.context.trim() : undefined + const state = typeof details.state === 'string' && details.state.trim() ? details.state.trim() : undefined + return { ...(context ? { context } : {}), ...(state ? { state } : {}) } +} + +/** 根据标准宿主码或兼容旧宿主的原文模式识别结构化 Docker 错误类别 */ +function detectFailureCodeFromText(rawText: string): { code: DockerFailureCode; context?: string; state?: string } { + if (!rawText) return { code: 'DOCKER_UNKNOWN' } + if ( + /DOCKER_CLI_NOT_FOUND|Docker CLI not found|not recognized as an internal or external command|command not found/i.test(rawText) || + // i18n-allow: legacy host fallback + /未找到 Docker 命令行|当前设备未安装 Docker|未安装 Docker/.test(rawText) + ) { + return { code: 'DOCKER_CLI_NOT_FOUND' } + } + if ( + /DOCKER_DAEMON_OFFLINE|cannot connect to the docker daemon|unable to connect to local docker daemon|failed to connect to the docker API|is the docker daemon running|open \/\/\.\/pipe\/(?:docker_engine|dockerDesktopLinuxEngine)|dial unix .*docker\.sock.*(?:no such file or directory|connection refused)|error during connect[\s\S]*(?:cannot find the file specified|no such file or directory|connection refused|pipe\/docker|docker\.sock|dockerDesktopLinuxEngine|docker_engine)/i.test(rawText) || + // i18n-allow: legacy host fallback + /无法连接本机 Docker 引擎|Docker 服务未启动|Docker 引擎未运行/.test(rawText) + ) { + return { code: 'DOCKER_DAEMON_OFFLINE' } + } + if ( + /DOCKER_PERMISSION_DENIED|(?:got\s+)?permission denied while trying to connect|permission denied (?:while connecting to|when accessing) (?:the )?local docker (?:daemon|engine)|access is denied.*(?:pipe|docker)|permission denied.*(?:docker\.sock|docker_engine|dockerDesktopLinuxEngine)|permission denied when executing docker cli/i.test(rawText) || + // i18n-allow: legacy host fallback + /无权访问本机 Docker 引擎|权限不足,无法访问本机 Docker 引擎/.test(rawText) + ) { + return { code: 'DOCKER_PERMISSION_DENIED' } + } + if ( + /DOCKER_REMOTE_CONTEXT|not a local connection/i.test(rawText) || + // i18n-allow: legacy host fallback + /不是本机连接/.test(rawText) + ) { + const match = rawText.match(/context\s+([a-zA-Z0-9][a-zA-Z0-9_.-]{0,199})\s+is not a local connection/i) + return { code: 'DOCKER_REMOTE_CONTEXT', ...(match?.[1] ? { context: match[1] } : {}) } + } + if (/DOCKER_INVALID_CONTEXT|Current Docker context is invalid/i.test(rawText)) { + return { code: 'DOCKER_INVALID_CONTEXT' } + } + if (/DOCKER_CONTEXT_ENDPOINT_UNAVAILABLE|Unable to read Docker context endpoint/i.test(rawText)) { + return { code: 'DOCKER_CONTEXT_ENDPOINT_UNAVAILABLE' } + } + if ( + /DOCKER_REQUEST_TIMEOUT|Docker request timed out/i.test(rawText) || + // i18n-allow: legacy host fallback + /操作 Docker 超时|Docker 响应超时/.test(rawText) + ) { + return { code: 'DOCKER_REQUEST_TIMEOUT' } + } + if ( + /DOCKER_REQUEST_CANCELLED|Docker request was cancelled/i.test(rawText) || + // i18n-allow: legacy host fallback + /已取消本次 Docker 操作/.test(rawText) + ) { + return { code: 'DOCKER_REQUEST_CANCELLED' } + } + if (/DOCKER_OUTPUT_TOO_LARGE|Docker output exceeded 4 MiB/i.test(rawText)) { + return { code: 'DOCKER_OUTPUT_TOO_LARGE' } + } + if (/DOCKER_SERVICE_STOPPED|Docker service has stopped/i.test(rawText)) { + return { code: 'DOCKER_SERVICE_STOPPED' } + } + if (/DOCKER_OPERATION_IN_PROGRESS|Docker operation is already in progress/i.test(rawText)) { + return { code: 'DOCKER_OPERATION_IN_PROGRESS' } + } + if (/DOCKER_DAEMON_INVALID_IDENTITY|Docker engine did not return a valid identity/i.test(rawText)) { + return { code: 'DOCKER_DAEMON_INVALID_IDENTITY' } + } + if (/DOCKER_TOO_MANY_SESSIONS|Too many Docker sessions/i.test(rawText)) { + return { code: 'DOCKER_TOO_MANY_SESSIONS' } + } + if (/DOCKER_SESSION_EXPIRED|Container list has expired/i.test(rawText)) { + return { code: 'DOCKER_SESSION_EXPIRED' } + } + if (/DOCKER_CONTEXT_CHANGED|Docker context or engine has changed/i.test(rawText)) { + return { code: 'DOCKER_CONTEXT_CHANGED' } + } + if (/DOCKER_CONTAINER_NOT_IN_LIST|This container is not in the loaded list/i.test(rawText)) { + return { code: 'DOCKER_CONTAINER_NOT_IN_LIST' } + } + if (/DOCKER_CONTAINER_STATE_UNVERIFIABLE|did not return a verifiable container state/i.test(rawText)) { + return { code: 'DOCKER_CONTAINER_STATE_UNVERIFIABLE' } + } + if (/DOCKER_CONTAINER_STATE_CHANGED|Container state has changed/i.test(rawText)) { + return { code: 'DOCKER_CONTAINER_STATE_CHANGED' } + } + if (/DOCKER_CONTAINER_STATE_UNSUPPORTED|Current container state does not support this operation/i.test(rawText)) { + return { code: 'DOCKER_CONTAINER_STATE_UNSUPPORTED' } + } + if (/DOCKER_CONTAINER_STATE_UNCONFIRMED|Command returned, but container state is/i.test(rawText)) { + const match = rawText.match(/state is ([a-zA-Z0-9_.-]+)/i) + return { code: 'DOCKER_CONTAINER_STATE_UNCONFIRMED', ...(match?.[1] ? { state: match[1] } : {}) } + } + if (/DOCKER_INVALID_CONTAINER_LIST|Invalid container record returned by Docker|contains duplicate IDs/i.test(rawText)) { + return { code: 'DOCKER_INVALID_CONTAINER_LIST' } + } + if (/DOCKER_REMOVE_NOT_STOPPED|not confirmed stopped/i.test(rawText)) { + return { code: 'DOCKER_REMOVE_NOT_STOPPED' } + } + return { code: 'DOCKER_UNKNOWN' } +} + +/** 按当前运行语言与操作系统格式化结构化 Docker 失败信息(支持语言热切换实时重算) */ +export function formatDockerFailure(failure: DockerFailure, platform: DockerPlatform = detectDockerPlatform()): string { + if (failure.customMessage) return failure.customMessage + switch (failure.code) { + case 'DOCKER_CLI_NOT_FOUND': + return platform === 'win32' ? t('errCliNotFoundWin') : platform === 'darwin' ? t('errCliNotFoundMac') : t('errCliNotFound') + case 'DOCKER_DAEMON_OFFLINE': + return platform === 'win32' ? t('errDaemonOfflineWin') : platform === 'darwin' ? t('errDaemonOfflineMac') : t('errDaemonOffline') + case 'DOCKER_PERMISSION_DENIED': + return platform === 'win32' ? t('errPermissionDeniedWin') : t('errPermissionDenied') + case 'DOCKER_REMOTE_CONTEXT': + return failure.context ? t('errRemoteContextNamed', { context: failure.context }) : t('errRemoteContext') + case 'DOCKER_INVALID_CONTEXT': return t('errInvalidContext') + case 'DOCKER_CONTEXT_ENDPOINT_UNAVAILABLE': return t('errContextEndpointUnavailable') + case 'DOCKER_REQUEST_TIMEOUT': return t('errTimeout') + case 'DOCKER_REQUEST_CANCELLED': return t('errCancelled') + case 'DOCKER_OUTPUT_TOO_LARGE': return t('errOutputTooLarge') + case 'DOCKER_SERVICE_STOPPED': return t('errServiceStopped') + case 'DOCKER_OPERATION_IN_PROGRESS': return t('errOperationInProgress') + case 'DOCKER_DAEMON_INVALID_IDENTITY': return t('errDaemonInvalidIdentity') + case 'DOCKER_TOO_MANY_SESSIONS': return t('errTooManySessions') + case 'DOCKER_SESSION_EXPIRED': return t('errSessionExpired') + case 'DOCKER_CONTEXT_CHANGED': return t('errContextChanged') + case 'DOCKER_CONTAINER_NOT_IN_LIST': return t('errContainerNotInList') + case 'DOCKER_CONTAINER_STATE_UNVERIFIABLE': return t('errContainerStateUnverifiable') + case 'DOCKER_CONTAINER_STATE_CHANGED': return t('errContainerStateChanged') + case 'DOCKER_CONTAINER_STATE_UNSUPPORTED': return t('errContainerStateUnsupported') + case 'DOCKER_CONTAINER_STATE_UNCONFIRMED': + return failure.state ? t('errContainerStateUnconfirmedWithState', { state: failure.state }) : t('errContainerStateUnconfirmed') + case 'DOCKER_INVALID_CONTAINER_LIST': return t('errInvalidContainerList') + case 'DOCKER_REMOVE_NOT_STOPPED': return t('errRemoveNotStopped') + case 'DOCKER_CLIENT_UPGRADE_REQUIRED': return t('upgradeClient') + case 'DOCKER_UNKNOWN': + default: + return failure.fallbackMessage || t('dockerRequestFailed') + } +} + +export class DockerServiceError extends Error { + readonly failure: DockerFailure + constructor(failure: DockerFailure) { + super(formatDockerFailure(failure)) + this.name = 'DockerServiceError' + this.failure = failure + } +} + +/** 将宿主 IPC 错误信封或异常统一解析为结构化 DockerFailure(兼容新旧宿主) */ +export function classifyDockerFailure(source: unknown): DockerFailure { + if (source instanceof DockerServiceError) return source.failure + + const hostCode = extractHostCode(source) + const code = extractErrorCode(source) + const rawText = extractRawErrorText(source) + const meta = readPublicMeta(source) + + // 1. 新宿主显式返回的结构化 DOCKER_* hostCode:完全按当前语言实时翻译 + if (hostCode && KNOWN_HOST_CODES.has(hostCode as DockerFailureCode)) { + return { + code: hostCode as DockerFailureCode, + ...(meta.context ? { context: meta.context } : {}), + ...(meta.state ? { state: meta.state } : {}) + } + } + + // 2. 宿主标准错误码映射(如客户端版本过低、权限不足、超时、取消、正忙、输出过大) + if (code === 'METHOD_NOT_FOUND' || code === 'METHOD_NOT_AVAILABLE') { + return { code: 'DOCKER_CLIENT_UPGRADE_REQUIRED' } + } + if (code === 'PERMISSION_DENIED') { + return { code: 'DOCKER_PERMISSION_DENIED' } + } + if (code === 'REQUEST_TIMEOUT') { + return { code: 'DOCKER_REQUEST_TIMEOUT' } + } + if (code === 'CANCELLED' || code === 'OPERATION_CANCELLED') { + return { code: 'DOCKER_REQUEST_CANCELLED' } + } + if (code === 'PLUGIN_BUSY') { + return { code: 'DOCKER_OPERATION_IN_PROGRESS' } + } + if (code === 'RESPONSE_TOO_LARGE') { + return { code: 'DOCKER_OUTPUT_TOO_LARGE' } + } + + // 3. 兼容旧宿主或未带 hostCode 的错误文本:先特征分类,防止被 NATIVE_HOST_ERROR 吞成「原生宿主执行失败」 + const detected = detectFailureCodeFromText(rawText) + if (detected.code !== 'DOCKER_UNKNOWN') { + // 若原文已属于当前语种(例如明确的手写中文/英文引导文案),保留原文并附带精确分类; + // 若原文语种不匹配(如旧宿主在中文模式下发来英文 "Docker CLI not found..."),交由插件本地 t(...) 翻译 + const keepCustom = Boolean(rawText && isDisplayableInCurrentLocale(rawText)) + return { + code: detected.code, + ...(keepCustom ? { customMessage: rawText } : {}), + ...(meta.context || detected.context ? { context: meta.context || detected.context } : {}), + ...(meta.state || detected.state ? { state: meta.state || detected.state } : {}) + } + } + + // 4. 其他未知或通用命令错误:若为 DOCKER_COMMAND_FAILED 且原文语种不匹配,回落为通用 Docker 请求失败,而非晦涩的“原生宿主执行失败” + if (hostCode === 'DOCKER_COMMAND_FAILED') { + return { + code: 'DOCKER_UNKNOWN', + fallbackMessage: rawText && isDisplayableInCurrentLocale(rawText) ? rawText : t('dockerRequestFailed') + } + } + const resolved = resolveErrorMessage(source, t('dockerRequestFailed')) + return { + code: 'DOCKER_UNKNOWN', + fallbackMessage: resolved + } +} + async function invoke(params: Record) { const call = (globalThis as unknown as { __ztoolsElectron?: Bridge }).__ztoolsElectron?.transport?.methods?.docker_manager - if (!call) throw new Error(t('upgradeClient')) - const result = await call({ messageId: `docker_${Date.now()}_${++sequence}`, params, timeoutMs: 240000 }) - if (result?.success !== true) throw new Error(resolveErrorMessage(result?.error, t('dockerRequestFailed'))) + if (!call) throw new DockerServiceError({ code: 'DOCKER_CLIENT_UPGRADE_REQUIRED' }) + let result: Reply + try { + result = await call({ messageId: `docker_${Date.now()}_${++sequence}`, params, timeoutMs: 240000 }) + } catch (err) { + throw new DockerServiceError(classifyDockerFailure(err)) + } + if (result?.success !== true) throw new DockerServiceError(classifyDockerFailure(result?.error)) if (!record(result.data) || result.data.success !== true) throw new Error(t('dockerUnconfirmed')) return result.data } diff --git a/extensions/docker-manager/src/i18n.ts b/extensions/docker-manager/src/i18n.ts index efa31f01..704d53c1 100644 --- a/extensions/docker-manager/src/i18n.ts +++ b/extensions/docker-manager/src/i18n.ts @@ -24,6 +24,47 @@ export const t = createTranslator( emptyNoMatchTitle: "没有符合条件的容器", emptyNotConnectedTitle: "未连接 Docker", toastOpFailed: "Docker 操作未完成", + toastCliNotFound: "未安装 Docker", + toastDaemonOffline: "Docker 服务未启动", + toastPermissionDenied: "无权访问 Docker", + toastRemoteContext: "不支持远程 Docker 上下文", + toastContextInvalid: "Docker 上下文配置异常", + toastTimeout: "Docker 响应超时", + toastCancelled: "Docker 操作已取消", + toastBusy: "Docker 正忙", + toastRefreshRequired: "容器列表需要刷新", + toastUpgradeRequired: "需要升级 ZTools 客户端", + toastOutputTooLarge: "Docker 输出超出限制", + toastServiceUnavailable: "Docker 服务暂不可用", + errCliNotFound: "当前设备未安装 Docker。请先安装并启动本机 Docker 环境,完成后按回车刷新", + errCliNotFoundWin: "当前设备未安装 Docker。请先安装并启动 Docker Desktop(或配置 Rancher Desktop / WSL 2 Docker 环境),完成后按回车刷新", + errCliNotFoundMac: "当前设备未安装 Docker。请先安装并启动 Docker Desktop,或配置已有的 Colima / OrbStack / Rancher Desktop 后按回车刷新", + errDaemonOffline: "Docker 服务未启动。请先启动本机 Docker 引擎,待就绪后按回车刷新", + errDaemonOfflineWin: "Docker 服务未启动。请先启动 Docker Desktop(或确认 WSL 2 / Rancher Desktop 引擎已运行),待引擎就绪后按回车刷新", + errDaemonOfflineMac: "Docker 服务未启动。请先启动 Docker Desktop、Colima 或 OrbStack,待引擎就绪后按回车刷新", + errPermissionDenied: "权限不足,无法访问本机 Docker 引擎。请检查本机 Docker Socket 访问权限或当前用户的 docker 组权限,处理后按回车刷新", + errPermissionDeniedWin: "权限不足,无法访问本机 Docker 引擎。请确认当前账号已加入 docker-users 用户组并重新登录,处理后按回车刷新", + errRemoteContext: "当前 Docker 上下文不是本机连接。为保障安全,容器管控仅支持本机连接,请切换到本机上下文后刷新", + errRemoteContextNamed: "当前 Docker 上下文({context})不是本机连接。为保障安全,容器管控仅支持本机连接,请切换到本机上下文后刷新", + errInvalidContext: "当前 Docker 上下文配置无效。请检查本机 Docker 上下文设置后按回车刷新", + errContextEndpointUnavailable: "无法读取当前 Docker 上下文的连接地址。请检查本机 Docker 配置后按回车刷新", + errTimeout: "连接或操作 Docker 超时。Docker 引擎可能正在启动或负载较高,请稍候并刷新确认最新状态", + errCancelled: "已取消本次 Docker 操作。请刷新确认实际容器状态", + errOutputTooLarge: "Docker 输出超过 4 MiB 限制。请缩小查询或操作范围后重试", + errServiceStopped: "Docker 管理服务已停止。请重新打开容器管控后重试", + errOperationInProgress: "另一项 Docker 操作正在执行中。请等待当前操作完成后重试", + errDaemonInvalidIdentity: "Docker 引擎未返回有效标识。请确认本机 Docker 服务运行正常后按回车刷新", + errTooManySessions: "当前打开的 Docker 会话过多。请关闭其他容器管控窗口后重试", + errSessionExpired: "容器列表已过期。请先刷新容器列表后再执行操作", + errContextChanged: "Docker 上下文或运行引擎已发生变化。请刷新容器列表后重试", + errContainerNotInList: "目标容器不在当前已加载的列表中。请刷新容器列表后重试", + errContainerStateUnverifiable: "Docker 未返回可校验的容器状态。请刷新容器列表后重试", + errContainerStateChanged: "容器状态已发生变化。请刷新容器列表后再执行操作", + errContainerStateUnsupported: "当前容器状态不支持此操作。请刷新容器列表后重试", + errContainerStateUnconfirmed: "命令已返回,但容器状态未按预期变更。请查看容器日志并刷新确认", + errContainerStateUnconfirmedWithState: "命令已返回,但容器当前状态为 {state}。请查看容器日志并刷新确认", + errInvalidContainerList: "Docker 返回的容器列表数据无效或包含重复条目。请按回车刷新重试", + errRemoveNotStopped: "待清理列表中包含未确认停止的容器。请刷新容器列表后重试", cancelUnconfirmed: "取消未确认:{error}", refreshListFirst: "请刷新容器列表", refreshFailedPrefix: "刷新失败:{error}", @@ -77,6 +118,47 @@ export const t = createTranslator( emptyNoMatchTitle: "No Matching Containers", emptyNotConnectedTitle: "Docker Not Connected", toastOpFailed: "Docker operation failed", + toastCliNotFound: "Docker Not Installed", + toastDaemonOffline: "Docker Engine Not Running", + toastPermissionDenied: "Docker Access Denied", + toastRemoteContext: "Remote Context Unsupported", + toastContextInvalid: "Invalid Docker Context", + toastTimeout: "Docker Timed Out", + toastCancelled: "Operation Cancelled", + toastBusy: "Docker Is Busy", + toastRefreshRequired: "Refresh Required", + toastUpgradeRequired: "ZTools Update Required", + toastOutputTooLarge: "Output Too Large", + toastServiceUnavailable: "Docker Service Unavailable", + errCliNotFound: "Docker is not installed on this device. Install and start a local Docker environment, then press Enter to refresh.", + errCliNotFoundWin: "Docker is not installed on this device. Install and start Docker Desktop (or configure Rancher Desktop / WSL 2 Docker), then press Enter to refresh.", + errCliNotFoundMac: "Docker is not installed on this device. Install and start Docker Desktop, or configure Colima, OrbStack, or Rancher Desktop, then press Enter to refresh.", + errDaemonOffline: "Docker engine is not running. Start your local Docker daemon, wait until it is ready, and press Enter to refresh.", + errDaemonOfflineWin: "Docker engine is not running. Start Docker Desktop (or verify your WSL 2 / Rancher Desktop engine is running), wait until it is ready, and press Enter to refresh.", + errDaemonOfflineMac: "Docker engine is not running. Start Docker Desktop, Colima, or OrbStack, wait until it is ready, and press Enter to refresh.", + errPermissionDenied: "Permission denied when accessing the local Docker engine. Check your local Docker socket or docker group permissions, then press Enter to refresh.", + errPermissionDeniedWin: "Permission denied when accessing the local Docker engine. Ensure your account is in the docker-users group and sign in again, then press Enter to refresh.", + errRemoteContext: "The current Docker context is not a local connection. For safety, Docker Manager only supports local connections; switch to a local context and refresh.", + errRemoteContextNamed: "Current Docker context ({context}) is not a local connection. For safety, Docker Manager only supports local connections; switch to a local context and refresh.", + errInvalidContext: "Current Docker context configuration is invalid. Check your local Docker context settings and press Enter to refresh.", + errContextEndpointUnavailable: "Unable to read the endpoint for the current Docker context. Check your local Docker configuration and press Enter to refresh.", + errTimeout: "Docker request timed out. The Docker engine may still be starting or under heavy load; wait a moment and refresh to verify the latest state.", + errCancelled: "Docker operation was cancelled. Refresh to verify the actual container state.", + errOutputTooLarge: "Docker output exceeded the 4 MiB limit. Narrow the scope and try again.", + errServiceStopped: "Docker manager service has stopped. Reopen Docker Manager and try again.", + errOperationInProgress: "Another Docker operation is already in progress. Please wait for it to finish.", + errDaemonInvalidIdentity: "Docker engine did not return a valid identity. Verify that your local Docker daemon is healthy and press Enter to refresh.", + errTooManySessions: "Too many Docker sessions are open. Close other Docker Manager windows and retry.", + errSessionExpired: "The container list has expired. Refresh the list before trying again.", + errContextChanged: "The Docker context or engine has changed. Refresh the container list and retry.", + errContainerNotInList: "This container is not in the currently loaded list. Refresh and try again.", + errContainerStateUnverifiable: "Docker did not return a verifiable container state. Refresh and try again.", + errContainerStateChanged: "Container state has changed. Refresh the container list before retrying.", + errContainerStateUnsupported: "The current container state does not support this action. Refresh the container list and try again.", + errContainerStateUnconfirmed: "The command returned, but the container state did not change as expected. Check the container logs and refresh.", + errContainerStateUnconfirmedWithState: "The command returned, but the container is still {state}. Check the container logs and refresh.", + errInvalidContainerList: "Docker returned invalid or duplicate container records. Press Enter to refresh and retry.", + errRemoveNotStopped: "The prune list includes containers that are not confirmed stopped. Refresh and try again.", cancelUnconfirmed: "Cancellation unconfirmed: {error}", refreshListFirst: "Please refresh the container list", refreshFailedPrefix: "Refresh failed: {error}", diff --git a/extensions/docker-manager/src/index.tsx b/extensions/docker-manager/src/index.tsx index d94255fb..6dc62c61 100644 --- a/extensions/docker-manager/src/index.tsx +++ b/extensions/docker-manager/src/index.tsx @@ -1,10 +1,63 @@ import React, { Action, ActionPanel, Icon, List, Toast, confirmAlert, showToast, useEffect, useLocale, useRef, useState } from '@ztools/declarative-ui' import { t } from './i18n.js' -import { cancelDocker, containerWebUrl, controlContainer, getContainerTailLogs, logMarkdown, listContainers, removeContainers } from './docker-service.js' -import { isStopped, type ContainerStatusFilter, type ContainerSummary, type DockerLogs, type DockerSnapshot } from './types.js' +import { DOCKER_DOWNLOAD_URLS, DockerServiceError, cancelDocker, classifyDockerFailure, containerWebUrl, controlContainer, dockerDownloadUrl, formatDockerFailure, getContainerTailLogs, logMarkdown, listContainers, removeContainers } from './docker-service.js' +import { isStopped, type ContainerStatusFilter, type ContainerSummary, type DockerFailure, type DockerFailureCode, type DockerLogs, type DockerSnapshot } from './types.js' export * from './types.js' export * from './docker-service.js' const failureMessage = (e: unknown) => e instanceof Error ? e.message : String(e) + +/** 按错误场景选择专属 Toast 标题;仅未知错误时才用“Docker 操作未完成”作为兜底。 */ +export function toastTitleForFailure(code: DockerFailureCode): string { + switch (code) { + case 'DOCKER_CLI_NOT_FOUND': return t('toastCliNotFound') + case 'DOCKER_DAEMON_OFFLINE': return t('toastDaemonOffline') + case 'DOCKER_PERMISSION_DENIED': return t('toastPermissionDenied') + case 'DOCKER_REMOTE_CONTEXT': return t('toastRemoteContext') + case 'DOCKER_INVALID_CONTEXT': + case 'DOCKER_CONTEXT_ENDPOINT_UNAVAILABLE': return t('toastContextInvalid') + case 'DOCKER_REQUEST_TIMEOUT': return t('toastTimeout') + case 'DOCKER_REQUEST_CANCELLED': return t('toastCancelled') + case 'DOCKER_OPERATION_IN_PROGRESS': return t('toastBusy') + case 'DOCKER_SESSION_EXPIRED': + case 'DOCKER_CONTEXT_CHANGED': + case 'DOCKER_CONTAINER_NOT_IN_LIST': + case 'DOCKER_CONTAINER_STATE_UNVERIFIABLE': + case 'DOCKER_CONTAINER_STATE_CHANGED': + case 'DOCKER_CONTAINER_STATE_UNSUPPORTED': + case 'DOCKER_INVALID_CONTAINER_LIST': + case 'DOCKER_REMOVE_NOT_STOPPED': return t('toastRefreshRequired') + case 'DOCKER_CLIENT_UPGRADE_REQUIRED': return t('toastUpgradeRequired') + case 'DOCKER_OUTPUT_TOO_LARGE': return t('toastOutputTooLarge') + case 'DOCKER_SERVICE_STOPPED': + case 'DOCKER_TOO_MANY_SESSIONS': + case 'DOCKER_DAEMON_INVALID_IDENTITY': return t('toastServiceUnavailable') + case 'DOCKER_CONTAINER_STATE_UNCONFIRMED': + case 'DOCKER_UNKNOWN': + default: + return t('toastOpFailed') + } +} + +/** 将结构化失败转为界面展示所需文案(Toast 标题、首句主标题、引导副标题及是否缺少 Docker CLI)。 */ +export function presentDockerFailure(failure: DockerFailure) { + const message = formatDockerFailure(failure) + const at = message.search(/。|\.(?:\s|$)/) + const title = at > 0 ? message.slice(0, at) : message + const rest = at > 0 ? message.slice(at + 1).trim() : '' + const toastTitle = toastTitleForFailure(failure.code) + // 当 Toast 标题已点明错误类型且存在后续引导说明时,Toast 正文展示具体引导,避免机械重复标题 + const toastMessage = rest && failure.code !== 'DOCKER_UNKNOWN' ? rest : message + return { + code: failure.code, + message, + title, + subtitle: rest || t('emptyRefreshSubtitle'), + toastTitle, + toastMessage, + missingCli: failure.code === 'DOCKER_CLI_NOT_FOUND' + } +} + /** 空列表提示按实际原因区分:已连上 Docker 但没有匹配项时,不能再提示“请启动 Docker 引擎”。 */ export function emptyHint(error: string, busy: boolean, snapshot: DockerSnapshot | null, total: number): string { if (error) return error @@ -12,33 +65,44 @@ export function emptyHint(error: string, busy: boolean, snapshot: DockerSnapshot if (!snapshot) return t('hintStartDaemon') return total ? t('hintNoMatch') : t('hintNoContainers') } -export const DOCKER_DOWNLOAD_URL = 'https://www.docker.com/products/docker-desktop/' +export const DOCKER_DOWNLOAD_URL = DOCKER_DOWNLOAD_URLS.default /** 空列表条目:错误原文只在条目里出现一次(首句作标题、其余作说明),摘要栏只写“Docker 未就绪”。 */ -export function emptyState(error: string, busy: boolean, snapshot: DockerSnapshot | null, total: number) { +export function emptyState(error: string | DockerFailure | null, busy: boolean, snapshot: DockerSnapshot | null, total: number) { if (error) { + if (typeof error !== 'string') { + const presented = presentDockerFailure(error) + return { title: presented.title, subtitle: presented.subtitle, icon: Icon.ExclamationMark, missingCli: presented.missingCli } + } const at = error.search(/。|\.(?:\s|$)/) const title = at > 0 ? error.slice(0, at) : error, rest = at > 0 ? error.slice(at + 1).trim() : '' const isMissingCli = - /DOCKER_CLI_NOT_FOUND|Docker CLI not found/i.test(error) || + /DOCKER_CLI_NOT_FOUND|Docker CLI not found|Docker is not installed/i.test(error) || // i18n-allow: legacy host fallback - /未找到 Docker 命令行/.test(error) + /未找到 Docker 命令行|未安装 Docker/.test(error) return { title, subtitle: rest || t('emptyRefreshSubtitle'), icon: Icon.ExclamationMark, missingCli: isMissingCli } } - if (busy) return { title: t('emptyLoadingTitle'), subtitle: emptyHint(error, busy, snapshot, total), icon: Icon.CircleProgress, missingCli: false } - return { title: snapshot ? t('emptyNoMatchTitle') : t('emptyNotConnectedTitle'), subtitle: emptyHint(error, busy, snapshot, total), icon: Icon.Info, missingCli: false } + if (busy) return { title: t('emptyLoadingTitle'), subtitle: emptyHint('', busy, snapshot, total), icon: Icon.CircleProgress, missingCli: false } + return { title: snapshot ? t('emptyNoMatchTitle') : t('emptyNotConnectedTitle'), subtitle: emptyHint('', busy, snapshot, total), icon: Icon.Info, missingCli: false } } export interface DockerManagerCommandProps { featureCode?: string } export function DockerManagerCommand({ featureCode = 'docker-all' }: DockerManagerCommandProps = {}) { useLocale() - const [snapshot, setSnapshot] = useState(null), [error, setError] = useState(''), [busy, setBusy] = useState(false) + const [snapshot, setSnapshot] = useState(null), [failure, setFailure] = useState(null), [busy, setBusy] = useState(false) const [status, setStatus] = useState(featureCode === 'docker-running' ? 'running' : featureCode === 'docker-clean-stopped' ? 'exited' : 'all') const [query, setQuery] = useState(''), [selected, setSelected] = useState(null), [logs, setLogs] = useState>({}) const active = useRef(false), alive = useRef(true) const work = async (run: () => Promise) => { if (active.current) return - active.current = true; setBusy(true); setError('') + active.current = true; setBusy(true); setFailure(null) try { await run() } - catch (e) { if (alive.current) { setError(failureMessage(e)); await showToast(Toast.Style.Failure, t('toastOpFailed'), failureMessage(e)) } } + catch (e) { + if (alive.current) { + const nextFailure = classifyDockerFailure(e) + const presented = presentDockerFailure(nextFailure) + setFailure(nextFailure) + await showToast(Toast.Style.Failure, presented.toastTitle, presented.toastMessage) + } + } finally { active.current = false; if (alive.current) setBusy(false) } } const reload = async () => { @@ -48,15 +112,30 @@ export function DockerManagerCommand({ featureCode = 'docker-all' }: DockerManag if (alive.current) { setSnapshot(next); setSelected(id => next.containers.some(c => c.id === id) ? id : next.containers[0]?.id || null) } } const refresh = () => work(reload) - const cancel = async () => { try { await cancelDocker() } catch (e) { if (alive.current) setError(t('cancelUnconfirmed', { error: failureMessage(e) })) } } + const cancel = async () => { + try { await cancelDocker() } + catch (e) { + if (alive.current) { + setFailure({ code: 'DOCKER_UNKNOWN', fallbackMessage: t('cancelUnconfirmed', { error: failureMessage(e) }) }) + } + } + } useEffect(() => { alive.current = true; void refresh(); return () => { alive.current = false; if (active.current) void cancelDocker().catch(e => console.warn('Docker cancellation unconfirmed', e)) } }, []) const toggle = (c: ContainerSummary, restart = false) => work(async () => { if (!snapshot) throw new Error(t('refreshListFirst')) + let operationFailure: DockerFailure | null = null let operationError = '' try { await controlContainer(snapshot.sessionId, c.id, restart ? 'restart' : c.state === 'running' ? 'stop' : 'start') } - catch (e) { operationError = failureMessage(e) } + catch (e) { operationFailure = classifyDockerFailure(e); operationError = formatDockerFailure(operationFailure) } if (!alive.current) return - try { await reload() } catch (e) { operationError += `${operationError ? '; ' : ''}${t('refreshFailedPrefix', { error: failureMessage(e) })}` } + try { await reload() } catch (e) { + const refreshErr = failureMessage(e) + operationError += `${operationError ? '; ' : ''}${t('refreshFailedPrefix', { error: refreshErr })}` + operationFailure = null + } + if (operationFailure) { + throw new DockerServiceError(operationFailure) + } if (operationError) throw new Error(operationError) if (alive.current) await showToast(Toast.Style.Success, t('containerUpdatedToast')) }) @@ -88,8 +167,9 @@ export function DockerManagerCommand({ featureCode = 'docker-all' }: DockerManag const containers = snapshot?.containers || [], q = query.toLowerCase().trim() const visible = containers.filter(c => (status === 'all' || (status === 'running' ? c.state === 'running' : isStopped(c))) && (!q || `${c.name} ${c.image} ${c.id} ${c.ports}`.toLowerCase().includes(q))) const stoppedCount = containers.filter(isStopped).length + const errorText = failure ? formatDockerFailure(failure) : '' // 没拿到列表时错误原文放在空状态条目里,摘要只写“Docker 未就绪”;有列表时操作失败仍在摘要显示原文。 - const loadError = snapshot ? '' : error + const loadFailure = snapshot ? null : failure // 未连上 Docker 时空状态行带“刷新”动作(与客户端提示“再点击刷新”一致),顶部不再重复同一按钮 const emptyOffersRetry = !visible.length && !busy && !snapshot return setStatus(value as ContainerStatusFilter)} tooltip={t('statusTooltip')}> } - filterBar={{ summaryText: loadError ? t('summaryNotReady') : error || (busy ? t('summaryBusy') : snapshot ? t('summaryReady', { context: snapshot.context, count: containers.length, statsError: snapshot.statsError ? ' · ' + snapshot.statsError : '' }) : t('summaryDisconnected')), + filterBar={{ summaryText: loadFailure ? t('summaryNotReady') : errorText || (busy ? t('summaryBusy') : snapshot ? t('summaryReady', { context: snapshot.context, count: containers.length, statsError: snapshot.statsError ? ' · ' + snapshot.statsError : '' }) : t('summaryDisconnected')), actions: busy ? [{ id: 'cancel', title: t('cancelAction'), onAction: cancel }] : [...(emptyOffersRetry ? [] : [{ id: 'refresh', title: t('refreshAction'), onAction: refresh }]), ...(stoppedCount ? [{ id: 'prune', title: t('pruneAction'), onAction: prune }] : [])] }}> - {!visible.length && (() => { const empty = emptyState(loadError, busy, snapshot, containers.length) + {!visible.length && (() => { const empty = emptyState(loadFailure, busy, snapshot, containers.length) return - {empty.missingCli && } + {empty.missingCli && } } /> })()} diff --git a/extensions/docker-manager/src/native-ipc.ts b/extensions/docker-manager/src/native-ipc.ts index 51576b99..13643277 100644 --- a/extensions/docker-manager/src/native-ipc.ts +++ b/extensions/docker-manager/src/native-ipc.ts @@ -174,11 +174,13 @@ function normalizeMethodResult(method: string, payload: DynamicBridge): DynamicB if (method === 'system_get_battery_status') { // 宿主约定 percent 超出 0-100(如 255)表示无电池或电量未知,不能改写成 100% + // 若宿主明确给出 hasBattery 布尔值,必须原样保留,仅在缺失时按合法电量推算 const rawPct = payload.percent - const hasBattery = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const validPct = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const hasBattery = typeof payload.hasBattery === 'boolean' ? payload.hasBattery : validPct return { ...payload, - percent: hasBattery ? rawPct : null, + percent: validPct ? rawPct : null, hasBattery } } @@ -489,6 +491,8 @@ export interface RealDirectoryScanResult extends Iterable approximate?: boolean /** 宿主实际遍历的条目数 */ visitedEntries?: number + /** 目录本身不存在(ENOENT) */ + missing?: boolean /** 读取失败的真实原因;已有文件仍可使用,但不能当作完整结果。 */ error?: string } @@ -497,6 +501,7 @@ interface ScanResultMeta { truncated?: boolean approximate?: boolean visitedEntries?: number + missing?: boolean } export interface ScanDirectoryTreeOptions { @@ -504,6 +509,10 @@ export interface ScanDirectoryTreeOptions { maxFiles?: number collectTopN?: number filterExt?: RegExp + /** 为 true 时,目录本身不存在(ENOENT)按空目录处理,不返回 error(权限拒绝/读取失败仍照常报错) */ + ignoreMissing?: boolean + /** Top-N 保留与排序方式:默认按体积降序,下载/录屏等时效场景可传 mtime-desc */ + sortBy?: 'size-desc' | 'mtime-desc' hostOverride?: DynamicBridge } @@ -519,8 +528,9 @@ function normalizeIndexedFileEntry(f: DynamicBridge): RealIndexedFileEntry { const sz = Number(f?.size ?? f?.sizeBytes ?? 0) const isDir = Boolean(f?.is_dir || f?.isDir || f?.isDirectory) const rawMtime = Number(f?.mtime ?? f?.mtimeMs ?? 0) - const mtimeMs = rawMtime > 1e11 ? rawMtime : rawMtime > 0 ? rawMtime * 1000 : Date.now() - const mtimeSec = rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime + const validMtime = Number.isFinite(rawMtime) && rawMtime > 0 + const mtimeMs = validMtime ? (rawMtime > 1e11 ? rawMtime : rawMtime * 1000) : 0 + const mtimeSec = validMtime ? (rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime) : 0 if (p && sz >= 0) realFileSizeCache.set(p, sz) return { name, @@ -551,6 +561,7 @@ function makeScanResult( subdirs, ...(meta.truncated ? { truncated: true } : {}), ...(meta.approximate ? { approximate: true } : {}), + ...(meta.missing ? { missing: true } : {}), ...(typeof meta.visitedEntries === 'number' ? { visitedEntries: meta.visitedEntries } : {}), [Symbol.iterator]() { return files[Symbol.iterator]() @@ -609,13 +620,40 @@ export async function scanRealDirectoryTree( return result.error ? { ...result.scan, error: result.error } : result.scan } +/** 仅当正则明确声明了扩展名(含 `\.`)时提取后缀列表,避免把 `thumbcache|iconcache` 等文件名关键词误拆成假扩展名 */ +function extractExtensionTokensFromFilter(filterExt: RegExp): string[] { + const src = filterExt.source + if (!src.includes('\\.')) return [] + const afterDot = src.slice(src.indexOf('\\.') + 2) + const rawTokens = afterDot.match(/[a-z0-9]{1,8}/gi) || [] + const seen = new Set() + const out: string[] = [] + for (const token of rawTokens) { + const lower = token.toLowerCase() + if (!lower || seen.has(lower)) continue + seen.add(lower) + out.push(lower) + } + return out +} + +function isMissingDirectoryError(res: { error?: string; errorCode?: string; errorDetails?: Record }): boolean { + if (res.errorDetails?.reason === 'ENOENT' || res.errorCode === 'ENOENT') return true + const msg = String(res.error || '') + return /Directory does not exist|ENOENT/i.test(msg) +} + /** 一次界面扫描的错误汇总;多个目录并行扫描时保留可读目录的结果。 */ export function createDirectoryScanner(hostOverride?: DynamicBridge) { const failures = new Map() return { async scan(dir: string, options: number | ScanDirectoryTreeOptions = 160) { const result = await scanRealDirectoryTree(dir, options, hostOverride) - const error = result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') + const ignoreMissing = typeof options === 'object' && options !== null && options.ignoreMissing === true + const error = + result.missing && ignoreMissing + ? '' + : result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') if (error) failures.set(dir, error) else failures.delete(dir) return result @@ -648,26 +686,38 @@ async function scanDirectoryTreeWithError( const safeLimit = Math.min(200, Math.max(1, Math.floor(rawLimit || 160))) const hostOverride = opts.hostOverride const filterExt = opts.filterExt + const ignoreMissing = opts.ignoreMissing === true const dirQuery = `dir:${targetDir}` try { let rawPayload: DynamicBridge = null + const searchParams: Record = { + query: dirQuery, + limit: safeLimit, + ...(opts.sortBy ? { sortBy: opts.sortBy } : {}) + } const res = await callHostTransport( 'system_search_files', - { query: dirQuery, limit: safeLimit }, + searchParams, hostOverride ) - if (res.ok && res.data) { + if (res.ok && res.data && res.data.degraded !== true) { rawPayload = res.data + } else if (!res.ok && ignoreMissing && isMissingDirectoryError(res)) { + const missingScan = makeScanResult([], 0, 0, [], { missing: true }) + return { scan: missingScan } } - if (!rawPayload && !hostOverride && typeof window !== 'undefined') { + if (!rawPayload && !hostOverride && res.errorCode === 'METHOD_NOT_AVAILABLE' && typeof window !== 'undefined') { const w = window as DynamicBridge if (typeof w.__ztoolsLauncher?.searchFiles === 'function') { const rawOuter = await w.__ztoolsLauncher.searchFiles(dirQuery, safeLimit) - rawPayload = + const candidate = rawOuter && typeof rawOuter === 'object' && 'data' in rawOuter && rawOuter.data ? rawOuter.data : rawOuter + if (candidate && candidate.degraded !== true && candidate.success !== false) { + rawPayload = candidate + } } } @@ -678,29 +728,32 @@ async function scanDirectoryTreeWithError( let files: RealIndexedFileEntry[] = rawPayload.files.map(normalizeIndexedFileEntry) if (filterExt instanceof RegExp) { files = files.filter(f => !f.isDir && (filterExt.test(f.name) || filterExt.test(f.ext))) - // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索目标扩展名 + // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索明确声明的目标扩展名 if (files.length === 0 && !hostOverride) { - const extTokens = (filterExt.source.match(/[a-z0-9]{2,5}/gi) || []) - .filter(t => !['thumbcache', 'iconcache'].includes(t.toLowerCase())) - .slice(0, 4) - // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 - const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() - const extraLists = await Promise.all( - extTokens.map(ext => searchRealIndexedFiles(`.${ext.toLowerCase()}`, 30, hostOverride)) - ) - const seen = new Set() - for (const list of extraLists) { - for (const item of list) { - if (!item.isDir && item.size > 0 && !seen.has(item.path)) { - if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { - seen.add(item.path) - files.push(item) + const extTokens = extractExtensionTokensFromFilter(filterExt) + if (extTokens.length > 0) { + // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 + const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() + const extraLists = await Promise.all( + extTokens.map(ext => searchRealIndexedFiles(`.${ext}`, 30, hostOverride)) + ) + const seen = new Set() + for (const list of extraLists) { + for (const item of list) { + if (!item.isDir && item.size > 0 && !seen.has(item.path)) { + if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { + seen.add(item.path) + files.push(item) + } } } } } } } + // 先基于过滤后的完整命中集合计算总文件数与总字节数,再按 collectTopN 裁剪样本列表 + const matchedCount = files.length + const matchedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) if (typeof opts.collectTopN === 'number' && opts.collectTopN > 0 && files.length > opts.collectTopN) { files = files.slice(0, opts.collectTopN) } @@ -714,11 +767,10 @@ async function scanDirectoryTreeWithError( ...(s.approximate === true ? { approximate: true } : {}) })) : [] - const computedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) const totalFilesCount = - filterExt instanceof RegExp ? files.length : Number(rawPayload.total_matches ?? files.length) + filterExt instanceof RegExp ? matchedCount : Number(rawPayload.total_matches ?? matchedCount) const totalBytesCount = - filterExt instanceof RegExp ? computedBytes : Number(rawPayload.total_bytes ?? computedBytes) + filterExt instanceof RegExp ? matchedBytes : Number(rawPayload.total_bytes ?? matchedBytes) const visited = Number(rawPayload.visited_entries) return { scan: makeScanResult(files, totalFilesCount, totalBytesCount, subdirs, { @@ -1817,8 +1869,6 @@ export async function writeRealClipboardText(text: string, hostOverride?: Dynami const payload = { text: String(text || '') } const res = await callHostTransport('clipboard_copy_text', payload, hostOverride) if (res.ok) return true - const fallbackRes = await callHostTransport('clipboard_write_text', payload, hostOverride) - if (fallbackRes.ok) return true try { if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) { await navigator.clipboard.writeText(String(text || '')) diff --git a/extensions/docker-manager/src/types.ts b/extensions/docker-manager/src/types.ts index 8fd1408a..2179bb9b 100644 --- a/extensions/docker-manager/src/types.ts +++ b/extensions/docker-manager/src/types.ts @@ -1,4 +1,41 @@ export type ContainerStatusFilter = 'all' | 'running' | 'exited' +export type DockerPlatform = 'win32' | 'darwin' | 'other' +export type DockerFailureCode = + | 'DOCKER_CLI_NOT_FOUND' + | 'DOCKER_DAEMON_OFFLINE' + | 'DOCKER_PERMISSION_DENIED' + | 'DOCKER_REMOTE_CONTEXT' + | 'DOCKER_INVALID_CONTEXT' + | 'DOCKER_CONTEXT_ENDPOINT_UNAVAILABLE' + | 'DOCKER_REQUEST_TIMEOUT' + | 'DOCKER_REQUEST_CANCELLED' + | 'DOCKER_OUTPUT_TOO_LARGE' + | 'DOCKER_SERVICE_STOPPED' + | 'DOCKER_OPERATION_IN_PROGRESS' + | 'DOCKER_DAEMON_INVALID_IDENTITY' + | 'DOCKER_TOO_MANY_SESSIONS' + | 'DOCKER_SESSION_EXPIRED' + | 'DOCKER_CONTEXT_CHANGED' + | 'DOCKER_CONTAINER_NOT_IN_LIST' + | 'DOCKER_CONTAINER_STATE_UNVERIFIABLE' + | 'DOCKER_CONTAINER_STATE_CHANGED' + | 'DOCKER_CONTAINER_STATE_UNSUPPORTED' + | 'DOCKER_CONTAINER_STATE_UNCONFIRMED' + | 'DOCKER_INVALID_CONTAINER_LIST' + | 'DOCKER_REMOVE_NOT_STOPPED' + | 'DOCKER_CLIENT_UPGRADE_REQUIRED' + | 'DOCKER_UNKNOWN' +export interface DockerFailure { + code: DockerFailureCode + /** 若存在与当前语言匹配且来自外部/旧宿主的精准文案(无 hostCode),优先保留展示;已知 hostCode 则按当前语言实时翻译 */ + customMessage?: string + /** 仅用于 DOCKER_UNKNOWN 或附加详情的兜底文案 */ + fallbackMessage?: string + /** 远程上下文名(用于 DOCKER_REMOTE_CONTEXT) */ + context?: string + /** 容器当前状态(用于 DOCKER_CONTAINER_STATE_UNCONFIRMED) */ + state?: string +} export interface ContainerSummary { id: string; name: string; image: string; state: string; status: string; ports: string; createdAt: string cpu: string | null; memory: string | null diff --git a/extensions/docker-manager/tests/docker.test.mjs b/extensions/docker-manager/tests/docker.test.mjs index 2c671131..cb109a1d 100644 --- a/extensions/docker-manager/tests/docker.test.mjs +++ b/extensions/docker-manager/tests/docker.test.mjs @@ -2,7 +2,7 @@ import test, { beforeEach, afterEach } from 'node:test' import assert from 'node:assert/strict' import { Toast, setRuntimeLocale } from '@ztools/declarative-ui' import { createHost, mount, tick } from '../../shared/test-harness.mjs' -import { DockerManagerCommand, commands, containerWebUrl, listContainers, removeContainers, getContainerTailLogs, logMarkdown } from '../dist/index.js' +import { DockerManagerCommand, commands, containerWebUrl, detectDockerPlatform, dockerDownloadUrl, formatDockerFailure, listContainers, removeContainers, getContainerTailLogs, logMarkdown } from '../dist/index.js' const a = 'a'.repeat(64), b = 'b'.repeat(64), sessionId = '12345678-1234-1234-1234-123456789012' const container = (id, state = 'exited') => ({ id, name: id === a ? 'alpha' : 'beta', image: 'fixture:latest', state, status: state, ports: '', createdAt: '2026-01-01', cpu: null, memory: null }) let host, views, rows @@ -132,7 +132,7 @@ test('未找到 Docker 命令行:错误只在条目出现一次,主动作打 const titles = v.actions(row).map(a => a.props.title) assert.deepEqual(titles, ['打开 Docker 官网下载页', '刷新']) assert.equal(v.tree().props.filterBar.actions.some(a => a.id === 'refresh'), false) - assert.equal(v.actions(row)[0].props.url, 'https://www.docker.com/products/docker-desktop/') + assert.equal(v.actions(row)[0].props.url, dockerDownloadUrl()) fail = false; await v.run(row, '刷新'); await tick() assert.equal(v.items().length, 2); assert.equal(v.tree().props.filterBar.summaryText.includes('未就绪'), false) // 连上后列表有容器,刷新回到顶部状态条 @@ -144,3 +144,189 @@ test('清单只声明实际用到的 shell 权限,不声明未使用的网络 const manifest = JSON.parse(await readFile(new URL('../plugin.json', import.meta.url), 'utf8')) assert.deepEqual(manifest.permissions, ['shell']) }) + +test('未安装 Docker(含旧宿主 NATIVE_HOST_ERROR 英文原文与新宿主 hostCode):展示专属中文/英文提示而非“原生宿主执行失败”或兜底 Toast', async () => { + // 1. 复现旧宿主返回 NATIVE_HOST_ERROR + 英文 "Docker CLI not found..." 的场景 + globalThis.__ztoolsElectron.transport.methods = { + docker_manager: async () => ({ + messageId: 'legacy_cli_missing', + success: false, + error: { + code: 'NATIVE_HOST_ERROR', + message: 'Docker CLI not found. Please install and start Docker Desktop, or configure an existing Colima / OrbStack Docker environment and retry' + } + }) + } + const vLegacy = await open() + const rowLegacy = vLegacy.items()[0] + assert.equal(rowLegacy.props.title, '当前设备未安装 Docker') + assert.match( + rowLegacy.props.subtitle, + detectDockerPlatform() === 'other' ? /安装并启动本机 Docker 环境/ : /Docker Desktop/ + ) + assert.doesNotMatch(vLegacy.text(), /原生宿主执行失败/) + assert.equal(host.lastToast().title, '未安装 Docker') + assert.notEqual(host.lastToast().title, 'Docker 操作未完成') + assert.deepEqual(vLegacy.actions(rowLegacy).map(a => a.props.title), ['打开 Docker 官网下载页', '刷新']) + + // 2. 新宿主返回结构化 details.hostCode,并验证运行期语言热切换(zh-CN -> en-US -> zh-CN) + globalThis.__ztoolsElectron.transport.methods = { + docker_manager: async () => ({ + messageId: 'structured_cli_missing', + success: false, + error: { + code: 'NATIVE_HOST_UNAVAILABLE', + message: '当前设备未安装 Docker。请先安装并启动 Docker Desktop', + details: { hostCode: 'DOCKER_CLI_NOT_FOUND' } + } + }) + } + const vStructured = await open() + assert.equal(vStructured.items()[0].props.title, '当前设备未安装 Docker') + assert.equal(host.lastToast().title, '未安装 Docker') + try { + setRuntimeLocale('en-US') + await tick() + assert.equal(vStructured.items()[0].props.title, 'Docker is not installed on this device') + assert.deepEqual(vStructured.actions(vStructured.items()[0]).map(a => a.props.title), ['Open Docker Download Page', 'Refresh']) + const vEn = await open() + assert.equal(host.lastToast().title, 'Docker Not Installed') + assert.notEqual(host.lastToast().title, 'Docker operation failed') + } finally { + setRuntimeLocale('zh-CN') + } +}) + +test('各已知 Docker 异常展示专属场景化 Toast 与详细提示,仅未知错误回退到“Docker 操作未完成”兜底', async () => { + const cases = [ + { + error: { code: 'NATIVE_HOST_ERROR', message: 'error during connect: open //./pipe/dockerDesktopLinuxEngine: The system cannot find the file specified.', details: { hostCode: 'DOCKER_DAEMON_OFFLINE' } }, + zhToast: 'Docker 服务未启动', + enToast: 'Docker Engine Not Running', + zhTitle: 'Docker 服务未启动', + enTitle: 'Docker engine is not running', + hasDownload: false + }, + { + error: { code: 'PERMISSION_DENIED', message: 'Permission denied', details: { hostCode: 'DOCKER_PERMISSION_DENIED' } }, + zhToast: '无权访问 Docker', + enToast: 'Docker Access Denied', + zhTitle: '权限不足,无法访问本机 Docker 引擎', + enTitle: 'Permission denied when accessing the local Docker engine', + hasDownload: false + }, + { + error: { code: 'NOT_SUPPORTED', message: 'Current Docker context prod-ssh is not a local connection', details: { hostCode: 'DOCKER_REMOTE_CONTEXT', context: 'prod-ssh' } }, + zhToast: '不支持远程 Docker 上下文', + enToast: 'Remote Context Unsupported', + zhTitle: '当前 Docker 上下文(prod-ssh)不是本机连接', + enTitle: 'Current Docker context (prod-ssh) is not a local connection', + hasDownload: false + }, + { + error: { code: 'REQUEST_TIMEOUT', message: 'Docker request timed out', details: { hostCode: 'DOCKER_REQUEST_TIMEOUT' } }, + zhToast: 'Docker 响应超时', + enToast: 'Docker Timed Out', + zhTitle: '连接或操作 Docker 超时', + enTitle: 'Docker request timed out', + hasDownload: false + }, + { + error: { code: 'PLUGIN_BUSY', message: 'A Docker operation is already in progress', details: { hostCode: 'DOCKER_OPERATION_IN_PROGRESS' } }, + zhToast: 'Docker 正忙', + enToast: 'Docker Is Busy', + zhTitle: '另一项 Docker 操作正在执行中', + enTitle: 'Another Docker operation is already in progress', + hasDownload: false + } + ] + + for (const item of cases) { + globalThis.__ztoolsElectron.transport.methods = { + docker_manager: async () => ({ messageId: 'case', success: false, error: item.error }) + } + setRuntimeLocale('zh-CN') + const vZh = await open() + assert.equal(host.lastToast().title, item.zhToast) + assert.equal(vZh.items()[0].props.title, item.zhTitle) + assert.equal(vZh.actions(vZh.items()[0]).some(a => /下载页/.test(a.props.title)), item.hasDownload) + + try { + setRuntimeLocale('en-US') + const vEn = await open() + assert.equal(host.lastToast().title, item.enToast) + assert.equal(vEn.items()[0].props.title, item.enTitle) + } finally { + setRuntimeLocale('zh-CN') + } + } + + // 未知错误才使用兜底 Toast 标题“Docker 操作未完成” / “Docker operation failed” + globalThis.__ztoolsElectron.transport.methods = { + docker_manager: async () => ({ + messageId: 'unknown', + success: false, + error: { code: 'UNKNOWN_DOCKER_ERROR', message: '容器存储卷驱动返回未知异常' } + }) + } + const vUnknownZh = await open() + assert.equal(host.lastToast().title, 'Docker 操作未完成') + assert.match(vUnknownZh.items()[0].props.title, /容器存储卷驱动返回未知异常/) + + try { + setRuntimeLocale('en-US') + globalThis.__ztoolsElectron.transport.methods = { + docker_manager: async () => ({ + messageId: 'unknown_en', + success: false, + error: { code: 'UNKNOWN_DOCKER_ERROR', message: 'unexpected storage driver failure' } + }) + } + const vUnknownEn = await open() + assert.equal(host.lastToast().title, 'Docker operation failed') + assert.match(vUnknownEn.items()[0].props.title, /unexpected storage driver failure/) + } finally { + setRuntimeLocale('zh-CN') + } +}) + +test('下载页快捷入口与引导文案按 Windows / macOS 精准分流且兼容双语', () => { + // 1. 平台识别与下载页 URL 映射 + assert.equal(detectDockerPlatform('Win32'), 'win32') + assert.equal(detectDockerPlatform('MacIntel'), 'darwin') + assert.equal(detectDockerPlatform('Linux x86_64'), 'other') + assert.equal(dockerDownloadUrl('win32'), 'https://docs.docker.com/desktop/setup/install/windows-install/') + assert.equal(dockerDownloadUrl('darwin'), 'https://docs.docker.com/desktop/setup/install/mac-install/') + assert.equal(dockerDownloadUrl('other'), 'https://www.docker.com/products/docker-desktop/') + + // 2. Windows 文案贴合 WSL 2 / Rancher Desktop / docker-users,不出现 macOS 专属工具 Colima / OrbStack + setRuntimeLocale('zh-CN') + const winCliZh = formatDockerFailure({ code: 'DOCKER_CLI_NOT_FOUND' }, 'win32') + const winDaemonZh = formatDockerFailure({ code: 'DOCKER_DAEMON_OFFLINE' }, 'win32') + const winPermZh = formatDockerFailure({ code: 'DOCKER_PERMISSION_DENIED' }, 'win32') + assert.match(winCliZh, /WSL 2/) + assert.doesNotMatch(winCliZh, /Colima|OrbStack/) + assert.match(winDaemonZh, /WSL 2/) + assert.doesNotMatch(winDaemonZh, /Colima|OrbStack/) + assert.match(winPermZh, /docker-users/) + + // 3. macOS 文案包含 Docker Desktop / Colima / OrbStack + const macCliZh = formatDockerFailure({ code: 'DOCKER_CLI_NOT_FOUND' }, 'darwin') + const macDaemonZh = formatDockerFailure({ code: 'DOCKER_DAEMON_OFFLINE' }, 'darwin') + const macPermZh = formatDockerFailure({ code: 'DOCKER_PERMISSION_DENIED' }, 'darwin') + assert.match(macCliZh, /Colima.*OrbStack/) + assert.match(macDaemonZh, /Colima.*OrbStack/) + assert.match(macPermZh, /Docker Socket/) + + // 4. 英文模式同样精准区分平台 + try { + setRuntimeLocale('en-US') + const winCliEn = formatDockerFailure({ code: 'DOCKER_CLI_NOT_FOUND' }, 'win32') + const macCliEn = formatDockerFailure({ code: 'DOCKER_CLI_NOT_FOUND' }, 'darwin') + assert.match(winCliEn, /WSL 2/) + assert.doesNotMatch(winCliEn, /Colima|OrbStack/) + assert.match(macCliEn, /Colima, OrbStack/) + } finally { + setRuntimeLocale('zh-CN') + } +}) diff --git a/extensions/downloads-manager/README.en.md b/extensions/downloads-manager/README.en.md new file mode 100644 index 00000000..27d6d29f --- /dev/null +++ b/extensions/downloads-manager/README.en.md @@ -0,0 +1,30 @@ +# Downloads Manager + +Aggregate files from your system download folder, automatically detected cloud drive, downloader, and chat app received folders, as well as custom folders you add. Supports filtering, opening, revealing in your file manager, copying, and moving items to the Recycle Bin (Trash on macOS). + +## Usage + +- **Commands**: Downloads Manager (keywords such as `downloads`, `dl`, `downloads manager`), cloud downloads (`netdisk`, `cloud downloads`), chat received files (`chat files`, `wechat files`, `received files`), and clean installers (`clean installers`, `installers`). Opening the last three pre-filters for cloud drives & downloaders, chat received folders, and installer packages respectively. +- **Grouping & Filtering**: Items are grouped into Today, Last 7 Days, and Earlier (or sorted by size descending when filtering installers). Use the dropdown next to the search box to filter by source (Chat Apps, Cloud Drives & Downloaders, Browser & System Downloads, Custom Folders) or file type. +- **Shortcuts**: + - `Enter`: Open the file (in the "Clean Installers" command, `Enter` moves the item to Recycle Bin / Trash after confirmation to prevent accidental execution). + - `⌘/Ctrl+Enter`: Reveal in file manager. + - `⌘/Ctrl+Shift+C`: Copy the file itself. + - `⌘/Ctrl+P`: Pin / protect the item from cleanup. + - `⌘/Ctrl+Backspace`: Move to Recycle Bin / Trash (confirmation required). + - `⌘/Ctrl+R`: Refresh the list. + - `⌘/Ctrl+K`: Open the action panel. +- **Custom Folders**: Folders that are not automatically detected can be added via the system folder picker under "Manage Download Folders" in the action panel. Removing a folder entry does not delete any files. +- **Scanning & Limits**: Folders are scanned once when the plugin opens; refresh after folder contents change. Each folder (including subfolders) lists up to the 100 most recently modified files. When this limit is exceeded or scanning is incomplete, the summary notes that only partial results are shown. Hidden files and files inside macOS app bundles or incomplete `.download` packages are excluded. Folders that fail to read are listed separately; in that case, the list should not be treated as complete. +- **Batch Cleanup (Action Panel)**: Clean installer packages in the current list, or files older than 30 days and at least 100 MB. Only unprotected items in the current filtered results are processed, and all target paths are listed for confirmation before execution. Files with unknown modification times are excluded from age-based cleanup. Closing the plugin stops any pending recycle requests. +- **Recycling Behavior**: Moving files to the system Recycle Bin (Trash on macOS) does not immediately free disk space. Only items confirmed to have been moved are removed from the list; failed items stay in the list with an error notice. + +## Platforms & Requirements + +- Supported: Windows, macOS +- Automatic discovery of WeChat, QQ, WeCom, DingTalk, Lark received folders and IDM subfolders is supported on Windows only. On macOS, these apps store files in sandboxed containers that require extra system permissions and vary by app version, so they are not auto-detected; check the file save path in your chat app settings and add it as a custom folder. +- Built into the client; no separate installation required. + +## Network & Data + +- Offline only; all data stays on your device. Pinned protections and custom folder settings are saved in plugin storage, and any save failure is reported rather than shown as succeeded. diff --git a/extensions/downloads-manager/plugin.json b/extensions/downloads-manager/plugin.json index 8f486b26..e01fba8a 100644 --- a/extensions/downloads-manager/plugin.json +++ b/extensions/downloads-manager/plugin.json @@ -2,7 +2,8 @@ "id": "downloads-manager", "name": "下载管理", "description": "聚合已识别的系统下载、网盘与接收目录,支持自定义目录、筛选、打开和安全回收;扫描不完整时明确提示", - "version": "2.1.11", + "version": "2.1.12", + "minAppVersion": "1.1.8.0", "author": "ZTools Team", "entry": "dist/index.js", "icon": "icon.svg", @@ -87,7 +88,10 @@ "files", "installers", "folders", - "cleanup" + "cleanup", + "downloaded files", + "recent downloads", + "download folder" ], "features": { "downloads-all": { @@ -138,5 +142,14 @@ { "path": "screenshots/02-action-panel.png" } + ], + "keywords": [ + "下载管理", + "下载文件", + "刚下载的", + "下载文件夹", + "安装包", + "找下载的文件", + "downloads" ] } diff --git a/extensions/downloads-manager/src/downloads-service.ts b/extensions/downloads-manager/src/downloads-service.ts index 4996a0cc..f2565708 100644 --- a/extensions/downloads-manager/src/downloads-service.ts +++ b/extensions/downloads-manager/src/downloads-service.ts @@ -151,6 +151,36 @@ export function validateCustomDownloadDirPath(rawPath: string): { ok: boolean; n return { ok: true, normalizedPath: normalized } } +/** 校验拖放/粘贴路径是否为有效目录,拦截普通文件直接传入 dir: 扫描 */ +export async function checkDroppedDirectoryPath( + rawPath: string, + hostOverride?: unknown +): Promise<{ ok: boolean; normalizedPath?: string; error?: string }> { + const check = validateCustomDownloadDirPath(rawPath) + if (!check.ok || !check.normalizedPath) return check + const target = check.normalizedPath + const dirCheck = await callHostTransport<{ exists?: boolean }>( + 'filesystem_directory_exists', + { path: target }, + hostOverride + ) + if (dirCheck.ok && typeof dirCheck.data?.exists === 'boolean') { + return dirCheck.data.exists + ? { ok: true, normalizedPath: target } + : { ok: false, error: t('errDropNotDirectory') } + } + const errRaw = String(dirCheck.error || '') + if (/\b(?:ENOTDIR|NOT_A_DIRECTORY)\b|not a directory|不是目录/i.test(errRaw)) { + return { ok: false, error: t('errDropNotDirectory') } + } + // 宿主未提供目录存在性检查时,拦截明显带有常见文件扩展名或临时后缀的路径,避免把普通文件塞给 dir: + const baseName = target.split(/[\\/]/).pop() || '' + if (baseName && (classifyDownloadFile(baseName) !== 'other' || isDownloadTemporaryOrHiddenFile(baseName))) { + return { ok: false, error: t('errDropNotDirectory') } + } + return { ok: true, normalizedPath: target } +} + /** * 读取客户端平台。办公 IM(微信 / QQ / 企业微信 / 钉钉 / 飞书)接收目录的自动发现只按 Windows 目录布局实现; * macOS 上这些应用把文件存在各自的沙盒容器里,读取需系统额外授权且布局随版本变化,因此不宣称支持。 @@ -275,7 +305,7 @@ function buildDownloadEntry( const HOST_SCAN_LIMIT = 200 interface SearchFile { name?: string; path?: string; size?: number; sizeBytes?: number; mtime?: number; mtimeMs?: number; is_dir?: boolean; isDir?: boolean; isDirectory?: boolean } -interface SearchResult { files?: SearchFile[]; total_matches?: number; truncated?: boolean; approximate?: boolean; success?: boolean } +interface SearchResult { files?: SearchFile[]; total_matches?: number; truncated?: boolean; approximate?: boolean; degraded?: boolean; scan_error?: string; success?: boolean } export async function scanDownloadsDirectory(customDirOrOptions?: string | { customDirs?: string[]; maxFilesPerSource?: number; shouldContinue?: () => boolean }, hostOverride?: unknown): Promise { const preferences = await readDownloadPreferences(), pinned = new Set(preferences.pins) @@ -289,13 +319,15 @@ export async function scanDownloadsDirectory(customDirOrOptions?: string | { cus let partial = false for (const source of sources) { if (typeof customDirOrOptions === 'object' && customDirOrOptions.shouldContinue?.() === false) throw new Error('SCAN_CANCELLED') - // 宿主 dir: 扫描会递归子目录并按体积从大到小返回;向宿主多要一些结果,再按修改时间取最近的 requested 个, - // 让“今天 / 近 7 天”的小文件不被大文件挤掉。结果仍不完整时如实标注“仅部分结果”。 - const response = await callHostTransport('system_search_files', { query: `dir:${source.path}`, limit: HOST_SCAN_LIMIT }, hostOverride) + // 宿主 dir: 扫描传 sortBy: 'mtime-desc' 按最新修改时间保留 Top-N,避免“今天 / 近 7 天”的小文件被大文件挤掉 + const response = await callHostTransport('system_search_files', { query: `dir:${source.path}`, limit: HOST_SCAN_LIMIT, sortBy: 'mtime-desc' }, hostOverride) if (!response.ok || response.data?.success === false || !Array.isArray(response.data?.files)) { scanIssues.push({ path: source.path, message: resolveErrorMessage(response, t('errScanInvalidData')) }); continue } const data = response.data + if (data.degraded === true) { + scanIssues.push({ path: source.path, message: t('errScanDegraded') }); continue + } if (data.truncated || data.approximate || (data.total_matches ?? 0) > data.files!.length || (data.files!.length >= HOST_SCAN_LIMIT && data.total_matches === undefined)) partial = true const sourceEntries: DownloadEntry[] = [] for (const file of data.files!) { diff --git a/extensions/downloads-manager/src/i18n.ts b/extensions/downloads-manager/src/i18n.ts index 7b01b2a5..5b6b665c 100644 --- a/extensions/downloads-manager/src/i18n.ts +++ b/extensions/downloads-manager/src/i18n.ts @@ -43,6 +43,9 @@ const rawT = createTranslator( systemDownloadsApp: "系统下载", errMaxFilesRange: "每个来源的显示上限必须为 1~{max}", errScanInvalidData: "目录扫描返回无效数据", + errScanDegraded: "目录扫描已降级,当前结果不可用,请检查目录权限后重试", + errDropNotDirectory: "仅支持拖入或粘贴文件夹,不支持直接扫描单个文件", + toastDropDirOnlyTitle: "请拖入文件夹", errIgnoredOutsideFile: "已忽略不属于该目录的无效结果", errPinTargetNotFound: "未找到要保护的下载项", errTrashUnconfirmed: "未收到明确的回收成功回执,请刷新核对;没有自动重试。", @@ -116,6 +119,9 @@ const rawT = createTranslator( actionCleanOldLarge: "清理当前列表中 30 天前的大文件 (≥ 100 MB)", actionManageDirs: "管理下载目录", actionRefreshAll: "刷新全渠道扫描", + btnOpenDownloadDir: "打开下载目录", + btnRefresh: "刷新", + toastNoDownloadDir: "暂无可打开的下载目录", navTitle: "下载管理", searchPlaceholderWin: "检索文件名、后缀(.exe/.pdf/.zip)或来源(微信/百度网盘/夸克/QQ)...", searchPlaceholderOther: "检索文件名、后缀(.dmg/.pdf/.zip)或来源(系统下载/百度网盘/夸克)...", @@ -188,6 +194,9 @@ const rawT = createTranslator( systemDownloadsApp: "System Downloads", errMaxFilesRange: "Files per source limit must be between 1 and {max}", errScanInvalidData: "Directory scan returned invalid data", + errScanDegraded: "Directory scan degraded; results unavailable, check permissions and retry", + errDropNotDirectory: "Only folders are supported; cannot scan a single file", + toastDropDirOnlyTitle: "Please Drop a Folder", errIgnoredOutsideFile: "Ignored invalid item outside target directory", errPinTargetNotFound: "Download item to pin not found", errTrashUnconfirmed: "Trash action unconfirmed; refresh to verify (no auto-retry).", @@ -261,6 +270,9 @@ const rawT = createTranslator( actionCleanOldLarge: "Clean Old Large Files (≥ 30d, ≥ 100 MB)", actionManageDirs: "Manage Download Folders", actionRefreshAll: "Refresh All Sources", + btnOpenDownloadDir: "Open Downloads Folder", + btnRefresh: "Refresh", + toastNoDownloadDir: "No download folder available to open", navTitle: "Downloads Manager", searchPlaceholderWin: "Search filename, extension (.exe/.pdf/.zip), or source...", searchPlaceholderOther: "Search filename, extension (.dmg/.pdf/.zip), or source...", diff --git a/extensions/downloads-manager/src/index.tsx b/extensions/downloads-manager/src/index.tsx index 201f8c25..f8ea228b 100644 --- a/extensions/downloads-manager/src/index.tsx +++ b/extensions/downloads-manager/src/index.tsx @@ -22,6 +22,7 @@ import { } from './host-compat.js' import { addCustomDownloadDirectory, + checkDroppedDirectoryPath, cleanExpiredDownloads, cleanRedundantInstallers, computeDashboardSummary, @@ -248,10 +249,20 @@ export default function DownloadsManagerCommand(props?: { if (busy.current) return const target = (rawDir || '').trim() if (!target) return + const checked = await checkDroppedDirectoryPath(target) + if (!alive.current) return + if (!checked.ok || !checked.normalizedPath) { + await showToast({ + style: Toast.Style.Failure, + title: t('toastDropDirOnlyTitle'), + message: resolveErrorMessage(checked, t('errDropNotDirectory')) + }) + return + } const request = ++generation.current setIsLoading(true); setLoadError('') try { - const result = await scanDownloadsDirectory(target) + const result = await scanDownloadsDirectory(checked.normalizedPath) if (!alive.current || request !== generation.current) return setCustomDirs(prev => prev.includes(result.downloadDir) ? prev : [result.downloadDir, ...prev]) setSummary(result) @@ -395,7 +406,7 @@ export default function DownloadsManagerCommand(props?: { key="reveal" title={t('actionRevealFolder')} icon={Icon.Folder} - shortcut={{ modifiers: ['ctrl'], key: 'enter' }} + shortcut={{ modifiers: ['ctrl'], key: 'return' }} onAction={async () => { const ok = await revealDownloadItem(item.path) await showToast({ @@ -527,7 +538,38 @@ export default function DownloadsManagerCommand(props?: { searchText={searchQuery} onSearchTextChange={(q: string) => setSearchQuery(q)} filterBar={{ - summaryText: loadError ? t('summaryLoadError') : filteredSummaryText(filteredEntries.length, summary.totalCount, summary.sources.length, summary.partial, summary.scanIssues.length) + summaryText: loadError ? t('summaryLoadError') : filteredSummaryText(filteredEntries.length, summary.totalCount, summary.sources.length, summary.partial, summary.scanIssues.length), + actions: [ + { + id: 'open-download-dir', + label: t('btnOpenDownloadDir'), + title: t('btnOpenDownloadDir'), + icon: Icon.Folder, + style: 'primary', + onAction: () => { + const targetDir = summary.downloadDir || summary.sources[0]?.path || '' + if (!targetDir) { + void showToast({ style: Toast.Style.Failure, title: t('toastNoDownloadDir') }) + return + } + void openDownloadItem(targetDir).then((ok) => { + if (!ok) { + void showToast({ style: Toast.Style.Failure, title: t('toastOpenFailed'), message: targetDir }) + } + }) + } + }, + { + id: 'refresh-downloads', + label: t('btnRefresh'), + title: t('actionRefreshAll'), + icon: Icon.ArrowClockwise, + style: 'secondary', + onAction: () => { + void reloadDownloads(customDirs) + } + } + ] }} searchBarAccessory={ = 0 && rawPct <= 100 + const validPct = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const hasBattery = typeof payload.hasBattery === 'boolean' ? payload.hasBattery : validPct return { ...payload, - percent: hasBattery ? rawPct : null, + percent: validPct ? rawPct : null, hasBattery } } @@ -489,6 +491,8 @@ export interface RealDirectoryScanResult extends Iterable approximate?: boolean /** 宿主实际遍历的条目数 */ visitedEntries?: number + /** 目录本身不存在(ENOENT) */ + missing?: boolean /** 读取失败的真实原因;已有文件仍可使用,但不能当作完整结果。 */ error?: string } @@ -497,6 +501,7 @@ interface ScanResultMeta { truncated?: boolean approximate?: boolean visitedEntries?: number + missing?: boolean } export interface ScanDirectoryTreeOptions { @@ -504,6 +509,10 @@ export interface ScanDirectoryTreeOptions { maxFiles?: number collectTopN?: number filterExt?: RegExp + /** 为 true 时,目录本身不存在(ENOENT)按空目录处理,不返回 error(权限拒绝/读取失败仍照常报错) */ + ignoreMissing?: boolean + /** Top-N 保留与排序方式:默认按体积降序,下载/录屏等时效场景可传 mtime-desc */ + sortBy?: 'size-desc' | 'mtime-desc' hostOverride?: DynamicBridge } @@ -519,8 +528,9 @@ function normalizeIndexedFileEntry(f: DynamicBridge): RealIndexedFileEntry { const sz = Number(f?.size ?? f?.sizeBytes ?? 0) const isDir = Boolean(f?.is_dir || f?.isDir || f?.isDirectory) const rawMtime = Number(f?.mtime ?? f?.mtimeMs ?? 0) - const mtimeMs = rawMtime > 1e11 ? rawMtime : rawMtime > 0 ? rawMtime * 1000 : Date.now() - const mtimeSec = rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime + const validMtime = Number.isFinite(rawMtime) && rawMtime > 0 + const mtimeMs = validMtime ? (rawMtime > 1e11 ? rawMtime : rawMtime * 1000) : 0 + const mtimeSec = validMtime ? (rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime) : 0 if (p && sz >= 0) realFileSizeCache.set(p, sz) return { name, @@ -551,6 +561,7 @@ function makeScanResult( subdirs, ...(meta.truncated ? { truncated: true } : {}), ...(meta.approximate ? { approximate: true } : {}), + ...(meta.missing ? { missing: true } : {}), ...(typeof meta.visitedEntries === 'number' ? { visitedEntries: meta.visitedEntries } : {}), [Symbol.iterator]() { return files[Symbol.iterator]() @@ -609,13 +620,40 @@ export async function scanRealDirectoryTree( return result.error ? { ...result.scan, error: result.error } : result.scan } +/** 仅当正则明确声明了扩展名(含 `\.`)时提取后缀列表,避免把 `thumbcache|iconcache` 等文件名关键词误拆成假扩展名 */ +function extractExtensionTokensFromFilter(filterExt: RegExp): string[] { + const src = filterExt.source + if (!src.includes('\\.')) return [] + const afterDot = src.slice(src.indexOf('\\.') + 2) + const rawTokens = afterDot.match(/[a-z0-9]{1,8}/gi) || [] + const seen = new Set() + const out: string[] = [] + for (const token of rawTokens) { + const lower = token.toLowerCase() + if (!lower || seen.has(lower)) continue + seen.add(lower) + out.push(lower) + } + return out +} + +function isMissingDirectoryError(res: { error?: string; errorCode?: string; errorDetails?: Record }): boolean { + if (res.errorDetails?.reason === 'ENOENT' || res.errorCode === 'ENOENT') return true + const msg = String(res.error || '') + return /Directory does not exist|ENOENT/i.test(msg) +} + /** 一次界面扫描的错误汇总;多个目录并行扫描时保留可读目录的结果。 */ export function createDirectoryScanner(hostOverride?: DynamicBridge) { const failures = new Map() return { async scan(dir: string, options: number | ScanDirectoryTreeOptions = 160) { const result = await scanRealDirectoryTree(dir, options, hostOverride) - const error = result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') + const ignoreMissing = typeof options === 'object' && options !== null && options.ignoreMissing === true + const error = + result.missing && ignoreMissing + ? '' + : result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') if (error) failures.set(dir, error) else failures.delete(dir) return result @@ -648,26 +686,38 @@ async function scanDirectoryTreeWithError( const safeLimit = Math.min(200, Math.max(1, Math.floor(rawLimit || 160))) const hostOverride = opts.hostOverride const filterExt = opts.filterExt + const ignoreMissing = opts.ignoreMissing === true const dirQuery = `dir:${targetDir}` try { let rawPayload: DynamicBridge = null + const searchParams: Record = { + query: dirQuery, + limit: safeLimit, + ...(opts.sortBy ? { sortBy: opts.sortBy } : {}) + } const res = await callHostTransport( 'system_search_files', - { query: dirQuery, limit: safeLimit }, + searchParams, hostOverride ) - if (res.ok && res.data) { + if (res.ok && res.data && res.data.degraded !== true) { rawPayload = res.data + } else if (!res.ok && ignoreMissing && isMissingDirectoryError(res)) { + const missingScan = makeScanResult([], 0, 0, [], { missing: true }) + return { scan: missingScan } } - if (!rawPayload && !hostOverride && typeof window !== 'undefined') { + if (!rawPayload && !hostOverride && res.errorCode === 'METHOD_NOT_AVAILABLE' && typeof window !== 'undefined') { const w = window as DynamicBridge if (typeof w.__ztoolsLauncher?.searchFiles === 'function') { const rawOuter = await w.__ztoolsLauncher.searchFiles(dirQuery, safeLimit) - rawPayload = + const candidate = rawOuter && typeof rawOuter === 'object' && 'data' in rawOuter && rawOuter.data ? rawOuter.data : rawOuter + if (candidate && candidate.degraded !== true && candidate.success !== false) { + rawPayload = candidate + } } } @@ -678,29 +728,32 @@ async function scanDirectoryTreeWithError( let files: RealIndexedFileEntry[] = rawPayload.files.map(normalizeIndexedFileEntry) if (filterExt instanceof RegExp) { files = files.filter(f => !f.isDir && (filterExt.test(f.name) || filterExt.test(f.ext))) - // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索目标扩展名 + // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索明确声明的目标扩展名 if (files.length === 0 && !hostOverride) { - const extTokens = (filterExt.source.match(/[a-z0-9]{2,5}/gi) || []) - .filter(t => !['thumbcache', 'iconcache'].includes(t.toLowerCase())) - .slice(0, 4) - // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 - const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() - const extraLists = await Promise.all( - extTokens.map(ext => searchRealIndexedFiles(`.${ext.toLowerCase()}`, 30, hostOverride)) - ) - const seen = new Set() - for (const list of extraLists) { - for (const item of list) { - if (!item.isDir && item.size > 0 && !seen.has(item.path)) { - if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { - seen.add(item.path) - files.push(item) + const extTokens = extractExtensionTokensFromFilter(filterExt) + if (extTokens.length > 0) { + // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 + const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() + const extraLists = await Promise.all( + extTokens.map(ext => searchRealIndexedFiles(`.${ext}`, 30, hostOverride)) + ) + const seen = new Set() + for (const list of extraLists) { + for (const item of list) { + if (!item.isDir && item.size > 0 && !seen.has(item.path)) { + if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { + seen.add(item.path) + files.push(item) + } } } } } } } + // 先基于过滤后的完整命中集合计算总文件数与总字节数,再按 collectTopN 裁剪样本列表 + const matchedCount = files.length + const matchedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) if (typeof opts.collectTopN === 'number' && opts.collectTopN > 0 && files.length > opts.collectTopN) { files = files.slice(0, opts.collectTopN) } @@ -714,11 +767,10 @@ async function scanDirectoryTreeWithError( ...(s.approximate === true ? { approximate: true } : {}) })) : [] - const computedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) const totalFilesCount = - filterExt instanceof RegExp ? files.length : Number(rawPayload.total_matches ?? files.length) + filterExt instanceof RegExp ? matchedCount : Number(rawPayload.total_matches ?? matchedCount) const totalBytesCount = - filterExt instanceof RegExp ? computedBytes : Number(rawPayload.total_bytes ?? computedBytes) + filterExt instanceof RegExp ? matchedBytes : Number(rawPayload.total_bytes ?? matchedBytes) const visited = Number(rawPayload.visited_entries) return { scan: makeScanResult(files, totalFilesCount, totalBytesCount, subdirs, { @@ -1817,8 +1869,6 @@ export async function writeRealClipboardText(text: string, hostOverride?: Dynami const payload = { text: String(text || '') } const res = await callHostTransport('clipboard_copy_text', payload, hostOverride) if (res.ok) return true - const fallbackRes = await callHostTransport('clipboard_write_text', payload, hostOverride) - if (fallbackRes.ok) return true try { if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) { await navigator.clipboard.writeText(String(text || '')) diff --git a/extensions/downloads-manager/tests/integrity.test.mjs b/extensions/downloads-manager/tests/integrity.test.mjs index b5a364ab..02512324 100644 --- a/extensions/downloads-manager/tests/integrity.test.mjs +++ b/extensions/downloads-manager/tests/integrity.test.mjs @@ -130,3 +130,33 @@ test('同时保存保护项与自定义目录不会互相覆盖',async()=>{ await Promise.all([togglePinEntry([installer],installer.id),addCustomDownloadDirectory(source,{downloads_manager:async()=>({ok:true,path:source})})]) assert.deepEqual(await readDownloadPreferences(),{pins:[installer.id],directories:[source]}) }) + +test('目录扫描传 sortBy:mtime-desc,degraded 降级响应记录单条错误不刷屏越界告警,拖放校验拦截普通文件',async()=>{ + const {checkDroppedDirectoryPath}=await import('../dist/downloads-service.js') + createHost() + const calls=[] + const degradedHost={transport:{call:async(method,params)=>{ + calls.push([method,params]) + if(method==='system_search_files'){ + return{success:true,degraded:true,files:[ + {name:'out1.pdf',path:'/other/dir/out1.pdf',size:100,mtime:1700000000000,is_dir:false}, + {name:'out2.pdf',path:'/other/dir/out2.pdf',size:200,mtime:1700000000000,is_dir:false} + ],total_matches:2} + } + throw new Error('不支持'+method) + }}} + const res=await scanDownloadsDirectory(source,degradedHost) + assert.equal(calls[0][1].sortBy,'mtime-desc') + assert.equal(res.entries.length,0) + assert.equal(res.partial,true) + assert.equal(res.scanIssues.length,1) + assert.match(res.scanIssues[0].message,/降级/) + + // 拖放普通文件拦截(宿主返回 exists:false 以及未提供检测时的扩展名兜底) + const fileHost={filesystem_directory_exists:async()=>({exists:false})} + const dirHost={filesystem_directory_exists:async()=>({exists:true})} + assert.equal((await checkDroppedDirectoryPath('/tmp/setup.exe',fileHost)).ok,false) + assert.equal((await checkDroppedDirectoryPath('/tmp/my-folder',dirHost)).ok,true) + assert.equal((await checkDroppedDirectoryPath('/tmp/report.pdf',{})).ok,false) + assert.equal((await checkDroppedDirectoryPath('/tmp/plain-folder',{})).ok,true) +}) diff --git a/extensions/env-manager/README.en.md b/extensions/env-manager/README.en.md new file mode 100644 index 00000000..f9943fa8 --- /dev/null +++ b/extensions/env-manager/README.en.md @@ -0,0 +1,29 @@ +# Environment Variables + +Inspect a snapshot of the current process's environment variables, manage Windows user/system variables or macOS shell variables, preview cleanup of nonexistent PATH directories, and keep restorable backups before making changes. + +## Usage + +- **Commands**: Environment Variables (keywords such as `env`, `path`, `environment variables`, `env manager`), plus dedicated commands to preview and clean nonexistent PATH directories from persistent configuration (`clean path`, `fix path`) and to view/restore pre-edit backups or copy the current variable snapshot (`backup env`, `export env`, `restore env`). +- **Views**: Switch views on the right side of the search bar: All Variables, User Config (Shell Config on macOS), System Config (Windows only), Current Process (read-only), PATH Entries, PATH with Invalid Entries, and Edit Backups. +- **Shortcuts**: + - Persistent config variables: `Enter` to edit, `⌘/Ctrl+Enter` to copy value, `⌘/Ctrl+K` to remove a variable or preview PATH cleanup. + - Current process variables: `Enter` to copy value, `⌘/Ctrl+Enter` to write to persistent config. + - Edit backups: `Enter` to preview and restore the previous configuration. +- **Safe Modification Flow**: Creating, editing, removing, cleaning, or restoring variables first displays a summary of changes and target locations (listing directories to remove during cleanup). After confirmation, the plugin saves and verifies a backup of the original configuration, writes the changes, reads back to verify, and only then reports success. +- **macOS**: Supports zsh and Bash. For zsh, writes to `$ZDOTDIR/.zshrc` (or `~/.zshrc` if unset); for Bash, writes to `~/.bash_profile`. Only the ZTools-managed block in the file is modified, leaving all other content untouched. Variable values are stored literally—`$HOME`, backticks, and command expressions are not evaluated. Changes take effect in newly opened terminals that source the file, though other startup scripts may still affect final values. The variable list and PATH cleanup only cover this managed block; variables set elsewhere in scripts are not listed. Saving `PATH` in shell config replaces the `PATH` for new terminals (entries set earlier by `.zprofile`, Homebrew, etc. will no longer apply), so `PATH` must be a complete list of directories starting with `/`, must retain `/usr/bin` and `/bin`, and is rejected if it contains `$`, backticks, or `~`. Because the current process `PATH` is the minimal GUI app environment, "Write to Persistent Config" is disabled for `PATH` on macOS. For Bash, if `~/.bash_profile` does not exist while `~/.bash_login` or `~/.profile` exists, the plugin stops instead of creating a file that would shadow them. Original files are backed up to a `.ztools-env-recovery-*` folder in the same directory, and the path is shown upon success. +- **Windows**: Reads raw values from the current user and system registry keys. Modifying system variables requires appropriate privileges. Applications launched after signing out and back in will inherit the updated environment. +- **Read-Only Process Snapshot**: The current process snapshot is read-only; modifying persistent configuration does not alter already running applications. +- **PATH Cleanup Rules**: Only removes local absolute directories confirmed not to exist. Empty entries, relative paths, unverifiable paths, external volumes, and entries containing variable references are preserved in their original order. Cleanup aborts if the resulting `PATH` would be empty. +- **Backup Restore Guard**: Restoring a backup aborts if the configuration has been modified since that backup was created so newer edits are not overwritten; the backup remains intact. +- **Security Note**: "Copy Variable Snapshot" copies the actual values currently read, which may contain secrets or tokens—store the copied output securely. + +## Platforms & Requirements + +- Supported: Windows, macOS +- Requires client version 1.1.8.5 or later. +- Windows implementation is pending physical-device verification. + +## Network & Data + +- Offline only; backups and modifications stay on your device. diff --git a/extensions/env-manager/plugin.json b/extensions/env-manager/plugin.json index bb928825..1d778edb 100644 --- a/extensions/env-manager/plugin.json +++ b/extensions/env-manager/plugin.json @@ -1,7 +1,7 @@ { "id": "env-manager", "name": "环境变量", - "version": "1.0.9", + "version": "1.0.10", "description": "管理 Windows 注册表环境与 macOS 终端变量,查看只读进程快照,预览 PATH 清理,修改前保留可恢复备份", "author": "ZTools Team", "category": [ @@ -73,7 +73,11 @@ "path", "variables", "shell", - "registry" + "registry", + "environment variables", + "system env", + "user env", + "config" ], "features": { "env-all": { @@ -114,5 +118,14 @@ { "path": "screenshots/01.png" } + ], + "keywords": [ + "环境变量", + "path", + "系统变量", + "用户变量", + "配置path", + "改环境变量", + "env" ] } diff --git a/extensions/env-manager/src/index.tsx b/extensions/env-manager/src/index.tsx index 5ff7038d..569e042a 100644 --- a/extensions/env-manager/src/index.tsx +++ b/extensions/env-manager/src/index.tsx @@ -56,8 +56,8 @@ export function EnvVarForm({ item, snapshot, onSave }: { item?: EnvItem; snapsho } return
}> - {item ? : } - + {item ? : } + setSource(v as EnvScope)}> {snapshot.sources.map(s => )} @@ -136,10 +136,10 @@ export function EnvManagerCommand({ featureCode = 'env-all' }: { featureCode?: s const hidden = (item: EnvItem) => Boolean(item.value) && isSensitiveKey(item.key) && !revealed.includes(rowId(item)) const toggleReveal = (item: EnvItem) => setRevealed(list => list.includes(rowId(item)) ? list.filter(id => id !== rowId(item)) : [...list, rowId(item)]) const rowActions = (item: EnvItem) => - {item.scope === 'process' ? : category === 'invalid' ? runChange({ kind: 'clean', source: item.scope as EnvScope })} /> : edit(item)} />} + {item.scope === 'process' ? : category === 'invalid' ? runChange({ kind: 'clean', source: item.scope as EnvScope })} /> : edit(item)} />} {/* macOS 的当前进程变量来自启动 ZTools 的环境,写进终端配置不会改变它,也容易把临时值固化下来:只提供复制 */} - {item.scope !== 'process' ? : platform !== 'darwin' && edit(item)} />} - {item.scope !== 'process' && runChange({ kind: 'delete', source: item.scope as EnvScope, key: item.key })} />} + {item.scope !== 'process' ? : platform !== 'darwin' && edit(item)} />} + {item.scope !== 'process' && runChange({ kind: 'delete', source: item.scope as EnvScope, key: item.key })} />} {item.scope !== 'process' && category !== 'invalid' && isPath(item) && invalid(item.scope) > 0 && runChange({ kind: 'clean', source: item.scope as EnvScope })} />} {Boolean(item.value) && isSensitiveKey(item.key) && toggleReveal(item)} />} @@ -150,7 +150,7 @@ export function EnvManagerCommand({ featureCode = 'env-all' }: { featureCode?: s } - filterBar={{ summaryText: error || (busy ? t('summaryBusy') : snapshot ? t('summaryReady', { count, hint: platform === 'darwin' ? t('summaryHintDarwin') : t('summaryHintWin') }) : t('summaryNotLoaded')), actions: busy ? [{ id: 'cancel', title: t('cancelBtn'), onAction: cancel }] : [{ id: 'refresh', title: t('actionRefresh'), onAction: refresh }, ...(snapshot ? [{ id: category === 'backups' ? 'export' : 'new', title: category === 'backups' ? t('actionCopySnapshot') : t('actionNewVar'), onAction: category === 'backups' ? exportBackup : () => edit() }] : [])] }}> + filterBar={{ summaryText: error || (busy ? t('summaryBusy') : snapshot ? t('summaryReady', { count, hint: platform === 'darwin' ? t('summaryHintDarwin') : t('summaryHintWin') }) : t('summaryNotLoaded')), actions: busy ? [{ id: 'cancel', title: t('cancelBtn'), style: 'secondary', onAction: cancel }] : [...(snapshot ? [{ id: category === 'backups' ? 'export' : 'new', label: category === 'backups' ? t('actionCopySnapshot') : t('actionNewVar'), title: category === 'backups' ? t('actionCopySnapshot') : t('actionNewVar'), icon: category === 'backups' ? Icon.CopyClipboard : Icon.Plus, style: 'primary', onAction: category === 'backups' ? exportBackup : () => edit() }] : []), { id: 'refresh', label: t('actionRefresh'), title: t('actionRefresh'), icon: Icon.ArrowClockwise, style: 'secondary', onAction: refresh }] }}> {!count && } {groupVariables(items, platform).map(group => {group.items.map(item => = 0 && rawPct <= 100 + const validPct = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const hasBattery = typeof payload.hasBattery === 'boolean' ? payload.hasBattery : validPct return { ...payload, - percent: hasBattery ? rawPct : null, + percent: validPct ? rawPct : null, hasBattery } } @@ -489,6 +491,8 @@ export interface RealDirectoryScanResult extends Iterable approximate?: boolean /** 宿主实际遍历的条目数 */ visitedEntries?: number + /** 目录本身不存在(ENOENT) */ + missing?: boolean /** 读取失败的真实原因;已有文件仍可使用,但不能当作完整结果。 */ error?: string } @@ -497,6 +501,7 @@ interface ScanResultMeta { truncated?: boolean approximate?: boolean visitedEntries?: number + missing?: boolean } export interface ScanDirectoryTreeOptions { @@ -504,6 +509,10 @@ export interface ScanDirectoryTreeOptions { maxFiles?: number collectTopN?: number filterExt?: RegExp + /** 为 true 时,目录本身不存在(ENOENT)按空目录处理,不返回 error(权限拒绝/读取失败仍照常报错) */ + ignoreMissing?: boolean + /** Top-N 保留与排序方式:默认按体积降序,下载/录屏等时效场景可传 mtime-desc */ + sortBy?: 'size-desc' | 'mtime-desc' hostOverride?: DynamicBridge } @@ -519,8 +528,9 @@ function normalizeIndexedFileEntry(f: DynamicBridge): RealIndexedFileEntry { const sz = Number(f?.size ?? f?.sizeBytes ?? 0) const isDir = Boolean(f?.is_dir || f?.isDir || f?.isDirectory) const rawMtime = Number(f?.mtime ?? f?.mtimeMs ?? 0) - const mtimeMs = rawMtime > 1e11 ? rawMtime : rawMtime > 0 ? rawMtime * 1000 : Date.now() - const mtimeSec = rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime + const validMtime = Number.isFinite(rawMtime) && rawMtime > 0 + const mtimeMs = validMtime ? (rawMtime > 1e11 ? rawMtime : rawMtime * 1000) : 0 + const mtimeSec = validMtime ? (rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime) : 0 if (p && sz >= 0) realFileSizeCache.set(p, sz) return { name, @@ -551,6 +561,7 @@ function makeScanResult( subdirs, ...(meta.truncated ? { truncated: true } : {}), ...(meta.approximate ? { approximate: true } : {}), + ...(meta.missing ? { missing: true } : {}), ...(typeof meta.visitedEntries === 'number' ? { visitedEntries: meta.visitedEntries } : {}), [Symbol.iterator]() { return files[Symbol.iterator]() @@ -609,13 +620,40 @@ export async function scanRealDirectoryTree( return result.error ? { ...result.scan, error: result.error } : result.scan } +/** 仅当正则明确声明了扩展名(含 `\.`)时提取后缀列表,避免把 `thumbcache|iconcache` 等文件名关键词误拆成假扩展名 */ +function extractExtensionTokensFromFilter(filterExt: RegExp): string[] { + const src = filterExt.source + if (!src.includes('\\.')) return [] + const afterDot = src.slice(src.indexOf('\\.') + 2) + const rawTokens = afterDot.match(/[a-z0-9]{1,8}/gi) || [] + const seen = new Set() + const out: string[] = [] + for (const token of rawTokens) { + const lower = token.toLowerCase() + if (!lower || seen.has(lower)) continue + seen.add(lower) + out.push(lower) + } + return out +} + +function isMissingDirectoryError(res: { error?: string; errorCode?: string; errorDetails?: Record }): boolean { + if (res.errorDetails?.reason === 'ENOENT' || res.errorCode === 'ENOENT') return true + const msg = String(res.error || '') + return /Directory does not exist|ENOENT/i.test(msg) +} + /** 一次界面扫描的错误汇总;多个目录并行扫描时保留可读目录的结果。 */ export function createDirectoryScanner(hostOverride?: DynamicBridge) { const failures = new Map() return { async scan(dir: string, options: number | ScanDirectoryTreeOptions = 160) { const result = await scanRealDirectoryTree(dir, options, hostOverride) - const error = result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') + const ignoreMissing = typeof options === 'object' && options !== null && options.ignoreMissing === true + const error = + result.missing && ignoreMissing + ? '' + : result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') if (error) failures.set(dir, error) else failures.delete(dir) return result @@ -648,26 +686,38 @@ async function scanDirectoryTreeWithError( const safeLimit = Math.min(200, Math.max(1, Math.floor(rawLimit || 160))) const hostOverride = opts.hostOverride const filterExt = opts.filterExt + const ignoreMissing = opts.ignoreMissing === true const dirQuery = `dir:${targetDir}` try { let rawPayload: DynamicBridge = null + const searchParams: Record = { + query: dirQuery, + limit: safeLimit, + ...(opts.sortBy ? { sortBy: opts.sortBy } : {}) + } const res = await callHostTransport( 'system_search_files', - { query: dirQuery, limit: safeLimit }, + searchParams, hostOverride ) - if (res.ok && res.data) { + if (res.ok && res.data && res.data.degraded !== true) { rawPayload = res.data + } else if (!res.ok && ignoreMissing && isMissingDirectoryError(res)) { + const missingScan = makeScanResult([], 0, 0, [], { missing: true }) + return { scan: missingScan } } - if (!rawPayload && !hostOverride && typeof window !== 'undefined') { + if (!rawPayload && !hostOverride && res.errorCode === 'METHOD_NOT_AVAILABLE' && typeof window !== 'undefined') { const w = window as DynamicBridge if (typeof w.__ztoolsLauncher?.searchFiles === 'function') { const rawOuter = await w.__ztoolsLauncher.searchFiles(dirQuery, safeLimit) - rawPayload = + const candidate = rawOuter && typeof rawOuter === 'object' && 'data' in rawOuter && rawOuter.data ? rawOuter.data : rawOuter + if (candidate && candidate.degraded !== true && candidate.success !== false) { + rawPayload = candidate + } } } @@ -678,29 +728,32 @@ async function scanDirectoryTreeWithError( let files: RealIndexedFileEntry[] = rawPayload.files.map(normalizeIndexedFileEntry) if (filterExt instanceof RegExp) { files = files.filter(f => !f.isDir && (filterExt.test(f.name) || filterExt.test(f.ext))) - // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索目标扩展名 + // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索明确声明的目标扩展名 if (files.length === 0 && !hostOverride) { - const extTokens = (filterExt.source.match(/[a-z0-9]{2,5}/gi) || []) - .filter(t => !['thumbcache', 'iconcache'].includes(t.toLowerCase())) - .slice(0, 4) - // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 - const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() - const extraLists = await Promise.all( - extTokens.map(ext => searchRealIndexedFiles(`.${ext.toLowerCase()}`, 30, hostOverride)) - ) - const seen = new Set() - for (const list of extraLists) { - for (const item of list) { - if (!item.isDir && item.size > 0 && !seen.has(item.path)) { - if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { - seen.add(item.path) - files.push(item) + const extTokens = extractExtensionTokensFromFilter(filterExt) + if (extTokens.length > 0) { + // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 + const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() + const extraLists = await Promise.all( + extTokens.map(ext => searchRealIndexedFiles(`.${ext}`, 30, hostOverride)) + ) + const seen = new Set() + for (const list of extraLists) { + for (const item of list) { + if (!item.isDir && item.size > 0 && !seen.has(item.path)) { + if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { + seen.add(item.path) + files.push(item) + } } } } } } } + // 先基于过滤后的完整命中集合计算总文件数与总字节数,再按 collectTopN 裁剪样本列表 + const matchedCount = files.length + const matchedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) if (typeof opts.collectTopN === 'number' && opts.collectTopN > 0 && files.length > opts.collectTopN) { files = files.slice(0, opts.collectTopN) } @@ -714,11 +767,10 @@ async function scanDirectoryTreeWithError( ...(s.approximate === true ? { approximate: true } : {}) })) : [] - const computedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) const totalFilesCount = - filterExt instanceof RegExp ? files.length : Number(rawPayload.total_matches ?? files.length) + filterExt instanceof RegExp ? matchedCount : Number(rawPayload.total_matches ?? matchedCount) const totalBytesCount = - filterExt instanceof RegExp ? computedBytes : Number(rawPayload.total_bytes ?? computedBytes) + filterExt instanceof RegExp ? matchedBytes : Number(rawPayload.total_bytes ?? matchedBytes) const visited = Number(rawPayload.visited_entries) return { scan: makeScanResult(files, totalFilesCount, totalBytesCount, subdirs, { @@ -1817,8 +1869,6 @@ export async function writeRealClipboardText(text: string, hostOverride?: Dynami const payload = { text: String(text || '') } const res = await callHostTransport('clipboard_copy_text', payload, hostOverride) if (res.ok) return true - const fallbackRes = await callHostTransport('clipboard_write_text', payload, hostOverride) - if (fallbackRes.ok) return true try { if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) { await navigator.clipboard.writeText(String(text || '')) diff --git a/extensions/env-manager/tests/environment.test.mjs b/extensions/env-manager/tests/environment.test.mjs index 8a333156..015e8e6f 100644 --- a/extensions/env-manager/tests/environment.test.mjs +++ b/extensions/env-manager/tests/environment.test.mjs @@ -31,7 +31,7 @@ test('真实读取后按来源筛选,入口不自动清理;主界面只用 await v.dropdown('process'); assert.deepEqual(v.items().map(i => i.props.id), ['process:PROCESS_ONLY']) assert.equal(v.actions(v.item('process:PROCESS_ONLY'))[0].props.title, '复制变量值') const clean = await open(commands['env-path-clean']); assert.deepEqual(clean.items().map(i => i.props.id), ['user:PATH']); assert.equal(calls('apply').length, 0) - assert.deepEqual(clean.tree().props.filterBar.actions.map(a => a.id), ['refresh', 'new']) + assert.deepEqual(clean.tree().props.filterBar.actions.map(a => a.id), ['new', 'refresh']) }) test('读取失败明确保留原因,不显示空配置成功;旧客户端与嵌套失败拒绝', async () => { host.ipc.environment_manager = async () => { throw new Error('权限不足,无法读取') } diff --git a/extensions/everything-file-search/README.en.md b/extensions/everything-file-search/README.en.md new file mode 100644 index 00000000..27cbc3c7 --- /dev/null +++ b/extensions/everything-file-search/README.en.md @@ -0,0 +1,28 @@ +# Instant File Search + +Search local files and folders by name or extension, and directly open, reveal in folder, preview, or copy them. + +## Usage + +- **Command**: Search for `Instant File Search` (or keywords like `file search`, `everything`) in the launcher to open. +- **Search & Filtering**: Type keywords to start searching (up to 50 results shown). When the query is empty, recently modified items in the top level of your Downloads, Desktop, and Documents folders are listed. Use the top dropdown to filter by type (Documents, Images, Videos, Audio, Archives, Code, Folders) or change sorting (Name, Size, Date Modified). +- **Shortcuts**: + - `Enter`: Open file or folder. + - `⌘/Ctrl+Enter`: Reveal in Finder (macOS) or File Explorer (Windows). + - `⌘/Ctrl+K`: Open the action panel. + - `⌘/Ctrl+Shift+P`: Preview text, code, image contents, or folder children inside the plugin (`⌘Y` also opens macOS Quick Look; not available on Windows). + - `⌘/Ctrl+Shift+C`: Copy full path. + - `⌘/Ctrl+Shift+N`: Copy file name. + - `⌘/Ctrl+Shift+V`: Copy the file itself. + - `⌘/Ctrl+Shift+H`: Compute and copy SHA-256 hash. + - `⌘/Ctrl+Shift+Backspace`: Move to Recycle Bin (Trash on macOS; confirmation required; files only, folders are not supported). +- **Indexing Backend**: Uses macOS Spotlight index on macOS. On Windows, uses the client's built-in file indexer; if the indexer is not running, empty, or fails, search falls back to the top level of Downloads, Desktop, and Documents. +- No third-party Everything installation is required. + +## Platforms & Requirements + +- Supported: Windows, macOS + +## Network & Data + +- Offline only; all data stays on your device. diff --git a/extensions/everything-file-search/plugin.json b/extensions/everything-file-search/plugin.json index b78bf9ca..ba423cd4 100644 --- a/extensions/everything-file-search/plugin.json +++ b/extensions/everything-file-search/plugin.json @@ -1,7 +1,8 @@ { "id": "everything-file-search", "name": "文件秒搜", - "version": "2.0.18", + "version": "2.0.19", + "minAppVersion": "1.1.8.0", "description": "按文件名或扩展名搜索本机文件和文件夹,可打开、定位、预览、复制路径或移入回收站", "author": "ZTools Team", "category": [ @@ -17,7 +18,12 @@ "everything", "mft", "usn", - "全盘搜索" + "全盘搜索", + "搜文件", + "搜索文件", + "本地搜索", + "文件查找", + "快速找文件" ], "permissions": [ "clipboard", @@ -50,7 +56,13 @@ "find files", "mft", "usn", - "search" + "search", + "find file", + "instant search", + "local search", + "locate file", + "spotlight", + "search files" ], "screenshots": [ { diff --git a/extensions/everything-file-search/src/i18n.ts b/extensions/everything-file-search/src/i18n.ts index 02f803a0..2c41d45a 100644 --- a/extensions/everything-file-search/src/i18n.ts +++ b/extensions/everything-file-search/src/i18n.ts @@ -49,7 +49,19 @@ const rawT = createTranslator( msgQuickLookOpened: "已调起系统快速预览", msgQuickLookFailed: "快速预览失败: {reason}", - // index.tsx + // 时间与数量格式化 + timeToday: "今天 {hm}", + timeYesterday: "昨天 {hm}", + indexedCountWan: "{val} 万", + indexedCountBrief: "已索引 {count} 项", + indexedWarming: "索引构建中…", + indexSyncSuccess: "索引已同步,共 {count} 项", + indexSyncChanged: "已同步卷变化(+{added}/-{removed}),共 {count} 项", + indexRebuildSuccess: "全盘索引已重建,共 {count} 项(耗时 {ms} ms)", + indexRefreshFailed: "刷新索引失败:{reason}", + indexRefreshUnsupported: "当前客户端暂不支持手动刷新索引", + + // 预览与详情页 sha256LargeFileNote: "文件较大,可在列表动作里按需计算", sha256CalcFailedNote: "未能计算:{error}", qlReading: "正在读取文件内容…", @@ -80,49 +92,149 @@ const rawT = createTranslator( metaLinesTruncated: " (已截取前200行)", metaCategory: "分类", metaDirTag: "目录", - actionPanelOps: "文件操作", - actionOpenFolder: "打开文件夹", - actionOpenFile: "打开文件", - actionRevealInFm: "在{fm}中定位", - actionQuickLookSys: "Quick Look 快速预览", - actionCopyAbsPath: "复制文件绝对路径", - actionCopyName: "复制文件名", - actionCopySha256: "复制 SHA-256 哈希值", - confirmTrashTitle: "将「{name}」移入{trash}?", - actionMoveToTrash: "移入{trash}", - actionCancel: "取消", - toastCopiedSha256: "已复制 SHA-256: {prefix}...", - toastCalcSha256Failed: "计算 SHA-256 失败: {error}", - searchPlaceholder: "搜索文件名或扩展名...", + + // 顶栏与状态栏 + searchPlaceholder: "搜文件名、多词空格、*.pdf、!排除、ext:png、size:>10m、dm:7d、拼音...", summarySearchFailed: "搜索失败:{error}", summaryMatched: "{scope}当前匹配 {count} 个文件/目录 · 总大小 {size}{queryPart}", + summaryMatchedWithTotal: "{scope}已显示 {count} / 共命中 {total} 项 · {size}{elapsed}{queryPart}", + summaryElapsed: " · {ms} ms", summaryQueryPart: " · 检索词 \"{query}\"", - dropdownTooltip: "类型筛选与排序", - secTypeFilter: "类型筛选", + scopeDirPrefix: "目录 {dir}", + sortDropdownTooltip: "选择排序方式", + secSortOption: "排序方式", + sortRelevance: "相关性优先", + sortMtimeDesc: "修改时间(最新优先)", + sortMtimeAsc: "修改时间(最早优先)", + sortSizeDesc: "文件大小(从大到小)", + sortSizeAsc: "文件大小(从小到大)", + sortNameAsc: "名称(A → Z)", + sortNameDesc: "名称(Z → A)", + btnEnablePreview: "开启预览", + btnDisablePreview: "退出预览", + btnRefreshIndex: "刷新索引", + btnRefreshingIndex: "刷新中…", + + // 左栏导航分组与项 + navSecPresets: "快捷视图与位置", + navAllFiles: "全部文件", + navAllFilesSub: "全盘索引检索", + navPresetToday: "今日修改", + navPresetTodaySub: "今天更新的文件", + navPresetWeek: "近 7 天修改", + navPresetWeekSub: "本周活跃文件", + navPresetLarge: "大文件 (>50 MB)", + navPresetLargeSub: "按体积降序定位", + navFolderDesktop: "桌面", + navFolderDownloads: "下载", + navFolderDocuments: "文档", + navActiveDir: "当前目录", + navDriveTitle: "{label} ({drive})", + navDriveDefaultLabel: "磁盘", + navDriveAvail: "可用 {avail}", + navSecTypes: "文件类型", typeAll: "全部文件与文件夹", + typeFolder: "文件夹目录", typeDocument: "文档与表格", typeImage: "图片与照片", typeVideo: "视频与影片", typeAudio: "音频与音乐", typeArchive: "压缩文件", typeCode: "源代码与配置", - typeFolder: "文件夹目录", - secSortOption: "排序方式", - sortNameAsc: "按名称升序 (A-Z)", - sortNameDesc: "按名称降序 (Z-A)", - sortSizeDesc: "按文件大小 (从大到小)", - sortSizeAsc: "按文件大小 (从小到大)", - sortMtimeDesc: "按修改时间 (最新优先)", - sortMtimeAsc: "按修改时间 (最早优先)", + typeApp: "应用程序", + navSecFilters: "精细筛选", + filterKindTitle: "对象类型", + filterKindAll: "全部", + filterKindFile: "仅文件", + filterKindDir: "仅文件夹", + filterHiddenTitle: "隐藏文件", + filterHiddenShow: "显示", + filterHiddenHide: "已隐藏", + filterTimeTitle: "修改时间", + filterTimeAny: "不限", + filterTimeToday: "今天", + filterTime7d: "近 7 天", + filterTime30d: "近 30 天", + filterSizeTitle: "文件大小", + filterSizeAny: "不限", + filterSizeGt10mb: "> 10 MB", + filterSizeGt100mb: "> 100 MB", + filterSizeEmpty: "空文件 (0 B)", + navSecBookmarks: "搜索书签", + navSecHistory: "最近搜索", + navActiveTag: "当前", + + // 右栏表头、分页与空状态 + subListSubtitleCount: "共 {count} 项 · {size}", + subListSubtitleChecked: "已勾选 {checked} 项({checkedSize}) · 共 {count} 项", + loadMoreTitle: "加载更多结果(+{count})", + loadMoreSubtitle: "还有 {remaining} 项匹配结果,按 Enter 或点击继续加载", + emptyNoMatch: "未找到匹配的文件或文件夹", + emptyFilteredHint: "当前已启用范围或筛选条件,可按 Ctrl+Shift+R 重置筛选,或尝试 *.pdf、!排除、ext:png、size:>10mb、dm:7d 语法", + emptySyntaxHint: "支持多词空格、*.pdf、!排除、ext:png;jpg、size:>10mb、dm:7d、拼音首字母检索", notInClientSub: "在 ZTools 中打开「文件秒搜」后再搜索", searchErrTitle: "读取文件索引失败", actionRetrySearch: "重新搜索", + + // 动作面板 + actionPanelOps: "文件操作", + secBatchActions: "批量操作(已勾选 {count} 项)", + actionBatchCopyPaths: "批量复制文件路径 ({count} 项)", + actionBatchTrash: "批量移入{trash} ({count} 个文件)", + actionClearChecked: "取消全部勾选", + confirmBatchTrashTitle: "将已勾选的 {count} 个文件移入{trash}?", + confirmBatchTrashMsg: "首项:{first}{more}{skipNote}", + confirmBatchTrashMore: " 等 {count} 个文件", + confirmBatchTrashSkipDirs: "(将自动跳过 {dirs} 个文件夹)", + toastBatchCopiedPaths: "已复制 {count} 条文件路径", + toastBatchTrashDone: "已将 {count} 个文件移入{trash}", + toastBatchTrashPartial: "已移入 {ok} 个,{fail} 个失败:{reason}", + toastBatchTrashNoFiles: "勾选项目中没有可移入{trash}的普通文件", + secCoreActions: "核心动作", + actionOpenFolder: "打开文件夹", + actionOpenFile: "打开文件", + actionRevealInFm: "在{fm}中定位", + actionTogglePreview: "切换实时侧边预览", + actionQuickLookSys: "Quick Look 快速预览", actionInstantPreview: "即时预览", + secSortMenu: "排序方式", + actionReverseSort: "反转排序方向", + secDirectoryNav: "目录与范围", + actionSearchInDir: "在此目录内搜索", + actionSearchInParentDir: "在所在目录内搜索", + actionParentDirScope: "返回上级目录", + actionExitDirScope: "返回全盘搜索", + actionResetFilters: "重置全部筛选与范围", + actionSaveBookmark: "保存当前搜索为书签", + actionDeleteBookmark: "删除此书签", + actionDeleteHistory: "删除此历史记录", + actionClearHistory: "清空搜索历史", + actionSyncIndex: "增量同步磁盘索引", + actionRebuildIndex: "重建全盘文件索引", + actionViewIndexStats: "查看索引状态", secQuickCopy: "快捷复制", + actionCopyAbsPath: "复制文件绝对路径", + actionCopyParentPath: "复制所在目录路径", + actionCopyName: "复制文件名", actionCopyFileObj: "复制文件本身到剪贴板", actionCalcCopySha256: "计算并复制 SHA-256", - secFileManage: "文件治理" + actionCopySha256: "复制 SHA-256 哈希值", + secFileManage: "文件治理", + confirmTrashTitle: "将「{name}」移入{trash}?", + actionMoveToTrash: "移入{trash}", + actionCancel: "取消", + toastCopiedSha256: "已复制 SHA-256: {prefix}...", + toastCalcSha256Failed: "计算 SHA-256 失败: {error}", + toastBookmarkSaved: "已保存搜索书签:{title}", + toastBookmarkEmpty: "请先输入搜索词或启用筛选条件后再保存书签", + toastBookmarkRemoved: "已删除书签", + toastHistoryCleared: "已清空搜索历史", + toastFiltersReset: "已重置全部筛选与范围", + toastIndexStatsTitle: "文件索引状态", + toastIndexStatsMsg: "已索引 {count} 项 · 覆盖 {drives}", + toastIndexStatsNoDrives: "已索引 {count} 项({type})", + toastIndexStatsUnavailable: "当前无法获取索引统计信息" }, "en-US": { notInClientMessage: "Requires ZTools client environment", @@ -171,7 +283,19 @@ const rawT = createTranslator( msgQuickLookOpened: "System Quick Look opened", msgQuickLookFailed: "Quick Look failed: {reason}", - // index.tsx + // Time & counts + timeToday: "Today {hm}", + timeYesterday: "Yesterday {hm}", + indexedCountWan: "{val}K", + indexedCountBrief: "{count} indexed", + indexedWarming: "Indexing...", + indexSyncSuccess: "Index synced ({count} entries)", + indexSyncChanged: "Synced drives (+{added}/-{removed}), {count} entries", + indexRebuildSuccess: "Index rebuilt ({count} entries in {ms} ms)", + indexRefreshFailed: "Index refresh failed: {reason}", + indexRefreshUnsupported: "Manual index refresh is not supported by this client version", + + // Preview & Detail sha256LargeFileNote: "Large file; calculate on demand via Actions", sha256CalcFailedNote: "Failed: {error}", qlReading: "Reading file content...", @@ -202,58 +326,158 @@ const rawT = createTranslator( metaLinesTruncated: " (first 200)", metaCategory: "Type", metaDirTag: "Folder", - actionPanelOps: "File Actions", - actionOpenFolder: "Open Folder", - actionOpenFile: "Open File", - actionRevealInFm: "Reveal in {fm}", - actionQuickLookSys: "System Quick Look", - actionCopyAbsPath: "Copy Full Path", - actionCopyName: "Copy Filename", - actionCopySha256: "Copy SHA-256", - confirmTrashTitle: "Move \"{name}\" to {trash}?", - actionMoveToTrash: "Move to {trash}", - actionCancel: "Cancel", - toastCopiedSha256: "Copied SHA-256: {prefix}...", - toastCalcSha256Failed: "SHA-256 failed: {error}", - searchPlaceholder: "Search filename or extension...", + + // Header & status bar + searchPlaceholder: "Search name, multi-word, *.pdf, !exclude, ext:png, size:>10m, dm:7d...", summarySearchFailed: "Search failed: {error}", - summaryMatched: "{scope}{count} item(s) · Total {size}{queryPart}", + summaryMatched: "{scope}{count} [[count:item|items]] · Total {size}{queryPart}", + summaryMatchedWithTotal: "{scope}Showing {count} of {total} · {size}{elapsed}{queryPart}", + summaryElapsed: " · {ms} ms", summaryQueryPart: " · Query \"{query}\"", - dropdownTooltip: "Filter & Sort", - secTypeFilter: "File Type", + scopeDirPrefix: "In {dir}", + sortDropdownTooltip: "Sort results", + secSortOption: "Sort By", + sortRelevance: "Relevance", + sortMtimeDesc: "Modified (Newest)", + sortMtimeAsc: "Modified (Oldest)", + sortSizeDesc: "Size (Largest)", + sortSizeAsc: "Size (Smallest)", + sortNameAsc: "Name (A to Z)", + sortNameDesc: "Name (Z to A)", + btnEnablePreview: "Live Preview", + btnDisablePreview: "Exit Preview", + btnRefreshIndex: "Refresh Index", + btnRefreshingIndex: "Refreshing...", + + // Left nav + navSecPresets: "Views & Locations", + navAllFiles: "All Files", + navAllFilesSub: "Full disk search", + navPresetToday: "Modified Today", + navPresetTodaySub: "Updated today", + navPresetWeek: "Past 7 Days", + navPresetWeekSub: "Recently modified", + navPresetLarge: "Large Files (>50 MB)", + navPresetLargeSub: "Sorted by size", + navFolderDesktop: "Desktop", + navFolderDownloads: "Downloads", + navFolderDocuments: "Documents", + navActiveDir: "Scoped Folder", + navDriveTitle: "{label} ({drive})", + navDriveDefaultLabel: "Drive", + navDriveAvail: "{avail} free", + navSecTypes: "File Types", typeAll: "All Files & Folders", + typeFolder: "Folders", typeDocument: "Documents & Sheets", typeImage: "Images & Photos", typeVideo: "Videos", typeAudio: "Audio & Music", typeArchive: "Archives", typeCode: "Code & Config", - typeFolder: "Folders", - secSortOption: "Sort By", - sortNameAsc: "Name (A-Z)", - sortNameDesc: "Name (Z-A)", - sortSizeDesc: "Size (Largest First)", - sortSizeAsc: "Size (Smallest First)", - sortMtimeDesc: "Modified (Newest First)", - sortMtimeAsc: "Modified (Oldest First)", + typeApp: "Applications", + navSecFilters: "Quick Filters", + filterKindTitle: "Object Kind", + filterKindAll: "All", + filterKindFile: "Files Only", + filterKindDir: "Folders Only", + filterHiddenTitle: "Hidden Files", + filterHiddenShow: "Shown", + filterHiddenHide: "Hidden", + filterTimeTitle: "Modified Time", + filterTimeAny: "Any Time", + filterTimeToday: "Today", + filterTime7d: "Past 7 Days", + filterTime30d: "Past 30 Days", + filterSizeTitle: "File Size", + filterSizeAny: "Any Size", + filterSizeGt10mb: "> 10 MB", + filterSizeGt100mb: "> 100 MB", + filterSizeEmpty: "Empty (0 B)", + navSecBookmarks: "Bookmarks", + navSecHistory: "Recent Searches", + navActiveTag: "Active", + + // Right subList + subListSubtitleCount: "{count} [[count:item|items]] · {size}", + subListSubtitleChecked: "{checked} selected ({checkedSize}) · {count} total", + loadMoreTitle: "Load More Results (+{count})", + loadMoreSubtitle: "{remaining} more matches available; press Enter or click to load", + emptyNoMatch: "No matching files or folders", + emptyFilteredHint: "Active scope or filters may hide results. Press Ctrl+Shift+R to reset, or try *.pdf, !exclude, ext:png, size:>10mb, dm:7d", + emptySyntaxHint: "Supports multi-word, *.pdf, !exclude, ext:png;jpg, size:>10mb, dm:7d", notInClientSub: "Open File Search inside ZTools to search", searchErrTitle: "Failed to read file index", actionRetrySearch: "Retry Search", + + // Actions + actionPanelOps: "File Actions", + secBatchActions: "Batch Actions ({count} selected)", + actionBatchCopyPaths: "Copy Selected Paths ({count})", + actionBatchTrash: "Move Selected to {trash} ({count})", + actionClearChecked: "Clear Selection", + confirmBatchTrashTitle: "Move {count} selected [[count:file|files]] to {trash}?", + confirmBatchTrashMsg: "First: {first}{more}{skipNote}", + confirmBatchTrashMore: " and {count} more", + confirmBatchTrashSkipDirs: " ({dirs} [[dirs:folder|folders]] will be skipped)", + toastBatchCopiedPaths: "Copied {count} file [[count:path|paths]]", + toastBatchTrashDone: "Moved {count} [[count:file|files]] to {trash}", + toastBatchTrashPartial: "Moved {ok}, {fail} failed: {reason}", + toastBatchTrashNoFiles: "No regular files selected to move to {trash}", + secCoreActions: "Actions", + actionOpenFolder: "Open Folder", + actionOpenFile: "Open File", + actionRevealInFm: "Reveal in {fm}", + actionTogglePreview: "Toggle Live Preview", + actionQuickLookSys: "System Quick Look", actionInstantPreview: "Instant Preview", + secSortMenu: "Sort By", + actionReverseSort: "Reverse Sort Direction", + secDirectoryNav: "Scope & Filters", + actionSearchInDir: "Search Inside Folder", + actionSearchInParentDir: "Search Inside Parent Folder", + actionParentDirScope: "Go to Parent Folder", + actionExitDirScope: "Back to Global Search", + actionResetFilters: "Reset All Filters & Scope", + actionSaveBookmark: "Save Search as Bookmark", + actionDeleteBookmark: "Delete Bookmark", + actionDeleteHistory: "Remove History Entry", + actionClearHistory: "Clear Search History", + actionSyncIndex: "Sync Disk Index", + actionRebuildIndex: "Rebuild Full Disk Index", + actionViewIndexStats: "View Index Status", secQuickCopy: "Copy", + actionCopyAbsPath: "Copy Full Path", + actionCopyParentPath: "Copy Parent Folder Path", + actionCopyName: "Copy Filename", actionCopyFileObj: "Copy File to Clipboard", actionCalcCopySha256: "Calculate & Copy SHA-256", - secFileManage: "Manage" + actionCopySha256: "Copy SHA-256", + secFileManage: "Manage", + confirmTrashTitle: "Move \"{name}\" to {trash}?", + actionMoveToTrash: "Move to {trash}", + actionCancel: "Cancel", + toastCopiedSha256: "Copied SHA-256: {prefix}...", + toastCalcSha256Failed: "SHA-256 failed: {error}", + toastBookmarkSaved: "Saved bookmark: {title}", + toastBookmarkEmpty: "Enter a query or enable a filter before saving a bookmark", + toastBookmarkRemoved: "Bookmark removed", + toastHistoryCleared: "Search history cleared", + toastFiltersReset: "All filters and scope reset", + toastIndexStatsTitle: "File Index Status", + toastIndexStatsMsg: "{count} indexed · Drives: {drives}", + toastIndexStatsNoDrives: "{count} indexed ({type})", + toastIndexStatsUnavailable: "Index statistics are currently unavailable" } } -) +); export const t: typeof rawT = (key, params) => { - const out = rawT(key, params) - if (!out.includes('[[')) return out + const out = rawT(key, params); + if (!out.includes("[[")) return out; return out.replace(/\[\[([A-Za-z0-9_.-]+):([^|\]]+)\|([^\]]+)\]\]/g, (_m, k: string, one: string, other: string) => { - const v = params?.[k] - const n = typeof v === 'number' ? v : Number(String(v ?? '').replace(/,/g, '')) - return n === 1 ? one : other - }) -} + const v = params?.[k]; + const n = typeof v === "number" ? v : Number(String(v ?? "").replace(/,/g, "")); + return n === 1 ? one : other; + }); +}; diff --git a/extensions/everything-file-search/src/index.tsx b/extensions/everything-file-search/src/index.tsx index 81469ef6..2683728b 100644 --- a/extensions/everything-file-search/src/index.tsx +++ b/extensions/everything-file-search/src/index.tsx @@ -8,11 +8,26 @@ import { showToast, Toast, Clipboard, + LocalStorage, confirmAlert } from "@ztools/declarative-ui"; import { useState, useEffect, useRef, useLocale, getLocale } from "@ztools/declarative-ui"; import { t } from "./i18n.js"; -import { FileRecord, SortOption, TypeFilter, FileQuickLookResult, FileActionResult } from "./types.js"; +import { + FileRecord, + SortOption, + TypeFilter, + KindFilter, + TimeFilter, + SizeFilter, + SearchPreferences, + SearchBookmark, + VolumeScope, + CommonFolderScope, + IndexerStats, + FileQuickLookResult, + FileActionResult +} from "./types.js"; import { formatBytes, truncatePath, @@ -20,17 +35,26 @@ import { getNotInClientMessage, supportsSystemQuickLook, sortAndFilterFiles, + reverseSortOption, + composeEffectiveQuery, + formatRelativeMtime, + formatIndexedCount, searchLocalFilesDetailed, getFileQuickLook, calculateFileSha256, openFile, revealFile, moveToTrash, + batchMoveToTrash, copyFileToClipboard, - quickLookFile + quickLookFile, + getIndexerStats, + refreshFileIndex, + loadCommonFolders, + loadMountedVolumes } from "./search-service.js"; import { isRealElectronHost } from "./native-ipc.js"; -import { resolveErrorMessage } from './error-i18n.js' +import { resolveErrorMessage } from "./error-i18n.js"; /** 文件管理器与回收站的系统叫法:macOS 为「访达」「废纸篓」,Windows 为「资源管理器」「回收站」 */ const platformNames = () => supportsSystemQuickLook() @@ -41,12 +65,146 @@ const platformNames = () => supportsSystemQuickLook() const AUTO_SHA256_MAX_BYTES = 64 * 1024 * 1024; /** 输入停顿多久后才发起检索;同时用递增序号只采用最新一次检索的结果 */ -export const SEARCH_DEBOUNCE_MS = 150; +export const SEARCH_DEBOUNCE_MS = 120; + +/** 每页从底层引擎拉取的最大条数(支持分页续拉) */ +export const PAGE_SIZE = 100; + +const STORAGE_KEYS = { + preferences: "efs:preferences:v1", + bookmarks: "efs:bookmarks:v1", + history: "efs:history:v1" +} as const; + +const MAX_HISTORY_ITEMS = 8; +const MAX_BOOKMARKS = 12; + +const SORT_OPTIONS: readonly SortOption[] = [ + "relevance", + "mtime-desc", + "mtime-asc", + "size-desc", + "size-asc", + "name-asc", + "name-desc" +]; + +const DEFAULT_PREFERENCES: SearchPreferences = { + sortOption: "relevance", + includeHidden: false, + livePreview: false +}; + +function sortOptionLabel(opt: SortOption): string { + switch (opt) { + case "relevance": return t("sortRelevance"); + case "name-asc": return t("sortNameAsc"); + case "name-desc": return t("sortNameDesc"); + case "size-desc": return t("sortSizeDesc"); + case "size-asc": return t("sortSizeAsc"); + case "mtime-desc": return t("sortMtimeDesc"); + case "mtime-asc": return t("sortMtimeAsc"); + } +} + +function parentDirectoryOf(dirPath: string): string { + const trimmed = dirPath.trim().replace(/[\\/]+$/, ""); + if (!trimmed) return ""; + if (/^[a-zA-Z]:$/.test(trimmed)) return ""; + const sep = trimmed.includes("\\") ? "\\" : "/"; + const idx = trimmed.lastIndexOf(sep); + if (idx <= 0) return sep === "/" && trimmed.length > 1 ? "/" : ""; + const parent = trimmed.slice(0, idx); + if (/^[a-zA-Z]:$/.test(parent)) return `${parent}\\`; + return parent; +} + +function fileIconFor(file: FileRecord): Icon { + if (file.isDir) return Icon.Folder; + const category = getFileCategory(file.name, false); + if (category === "image") return Icon.Image; + if (category === "video") return Icon.Video; + if (category === "audio") return Icon.Play; + if (category === "code") return Icon.Code; + if (category === "archive") return Icon.HardDrive; + if (category === "app") return Icon.Terminal; + return Icon.Document; +} + +function buildQuickLookMarkdown(file: FileRecord, ql: FileQuickLookResult | null): string { + const ext = (file.name.split(".").pop() || "").toLowerCase(); + let markdown = `# ${file.name}\n\n`; + + if (!ql) { + markdown += t("qlReading"); + } else if (ql.previewType === "error") { + markdown += t("qlReadErrTitle", { + error: resolveErrorMessage(ql, t("qlReadErrDefault")), + hint: supportsSystemQuickLook() ? t("qlReadErrHintMac") : t("qlReadErrHintOther") + }); + } else if (ql.previewType === "empty") { + markdown += t("qlEmptyFileMd"); + } else if (ql.previewType === "directory") { + markdown += t("qlDirHeading", { count: ql.totalLines ?? 0, plus: ql.partial ? "+" : "" }); + if (ql.dirEntries && ql.dirEntries.length > 0) { + markdown += ql.dirEntries + .map((e) => `- \`${e.name}${e.isDir ? "/" : ""}\`${e.isDir ? t("qlDirSuffix") : ""}`) + .join("\n"); + if (ql.truncated) markdown += t("qlDirTruncated"); + if (ql.partial) markdown += t("qlDirPartial"); + } else { + markdown += ql.partial ? t("qlDirEmptyPartial") : t("qlDirEmpty"); + } + } else if (ql.previewType === "image") { + markdown += `![${t("qlImageAlt")}](${ql.content})`; + } else if (ql.previewType === "markdown") { + markdown += `${ql.content}\n\n`; + if (ql.truncated) markdown += t("qlTextTruncated"); + } else if (ql.previewType === "code") { + markdown += `\`\`\`${ql.codeLanguage || ext}\n${ql.content}\n\`\`\`\n\n`; + if (ql.truncated) markdown += t("qlCodeTruncated"); + } else { + markdown += `> ${ql.content || t("qlBinaryFallback")}`; + } + return markdown; +} async function toastResult(res: FileActionResult) { await showToast(res.success ? Toast.Style.Success : Toast.Style.Failure, res.message); } +/** 详情页与主列表复用的文件核心打开/定位/QuickLook 动作 */ +function renderCoreFileActions(file: FileRecord) { + const isDir = file.isDir; + return ( + <> + toastResult(await openFile(file.path))} + /> + toastResult(await revealFile(file.path))} + /> + {supportsSystemQuickLook() ? ( + toastResult(await quickLookFile(file.path))} + /> + ) : null} + + ); +} + +function isValidSortOption(value: unknown): value is SortOption { + return typeof value === "string" && (SORT_OPTIONS as readonly string[]).includes(value); +} + export * from "./types.js"; export * from "./search-service.js"; @@ -64,7 +222,6 @@ export function FileQuickLookDetailView({ useLocale(); const [quickLook, setQuickLook] = useState(initialQuickLook || null); const [sha256, setSha256] = useState(""); - const [sha256Note, setSha256Note] = useState(""); React.useEffect(() => { @@ -72,7 +229,6 @@ export function FileQuickLookDetailView({ if (!initialQuickLook) { void getFileQuickLook(file).then((value) => { if (alive) setQuickLook(value); }); } - // 文件夹没有哈希;大文件不在打开预览时自动读完整个文件 if (file.isDir) { setSha256Note(""); } else if (file.size > AUTO_SHA256_MAX_BYTES) { @@ -88,49 +244,7 @@ export function FileQuickLookDetailView({ const ext = (file.name.split(".").pop() || "").toLowerCase(); const ql = quickLook; - - // 路径与大小等信息已在右侧元数据中,正文只放文件的真实内容 - let markdown = `# ${file.name}\n\n`; - - if (!ql) { - markdown += t("qlReading"); - } else if (ql.previewType === "error") { - markdown += t("qlReadErrTitle", { - error: resolveErrorMessage(ql, t("qlReadErrDefault")), - hint: supportsSystemQuickLook() ? t("qlReadErrHintMac") : t("qlReadErrHintOther") - }); - } else if (ql.previewType === "empty") { - markdown += t("qlEmptyFileMd"); - } else if (ql.previewType === "directory") { - markdown += t("qlDirHeading", { count: ql.totalLines ?? 0, plus: ql.partial ? "+" : "" }); - if (ql.dirEntries && ql.dirEntries.length > 0) { - markdown += ql.dirEntries - .map((e) => `- \`${e.name}${e.isDir ? "/" : ""}\`${e.isDir ? t("qlDirSuffix") : ""}`) - .join("\n"); - if (ql.truncated) { - markdown += t("qlDirTruncated"); - } - if (ql.partial) { - markdown += t("qlDirPartial"); - } - } else { - markdown += ql.partial ? t("qlDirEmptyPartial") : t("qlDirEmpty"); - } - } else if (ql.previewType === "image") { - markdown += `![${t("qlImageAlt")}](${ql.content})`; - } else if (ql.previewType === "markdown") { - markdown += `${ql.content}\n\n`; - if (ql.truncated) { - markdown += t("qlTextTruncated"); - } - } else if (ql.previewType === "code") { - markdown += `\`\`\`${ql.codeLanguage || ext}\n${ql.content}\n\`\`\`\n\n`; - if (ql.truncated) { - markdown += t("qlCodeTruncated"); - } - } else { - markdown += `> ${ql.content || t("qlBinaryFallback")}`; - } + const markdown = buildQuickLookMarkdown(file, ql); return ( - toastResult(await openFile(file.path))} - /> - toastResult(await revealFile(file.path))} - /> - {supportsSystemQuickLook() ? ( - toastResult(await quickLookFile(file.path))} - /> - ) : null} + {renderCoreFileActions(file)} ("name-asc"); + const [sortOption, setSortOption] = useState(DEFAULT_PREFERENCES.sortOption); const [typeFilter, setTypeFilter] = useState("all"); - // 不在客户端里运行时直接显示提示,不显示任何示例文件 + const [kindFilter, setKindFilter] = useState("all"); + const [timeFilter, setTimeFilter] = useState("any"); + const [sizeFilter, setSizeFilter] = useState("any"); + const [includeHidden, setIncludeHidden] = useState(DEFAULT_PREFERENCES.includeHidden); + const [livePreview, setLivePreview] = useState(DEFAULT_PREFERENCES.livePreview); + const [pathPrefix, setPathPrefix] = useState(""); + const [activeNavId, setActiveNavId] = useState("preset:all"); + const [allFiles, setAllFiles] = useState([]); - const inClient = isRealElectronHost(); + const [totalMatches, setTotalMatches] = useState(0); + const [hasMore, setHasMore] = useState(false); + const [elapsedMs, setElapsedMs] = useState(undefined); const [isLoading, setIsLoading] = useState(() => inClient); const [searchError, setSearchError] = useState(""); - // 宿主报告搜索范围受限(全盘索引不可用 / Spotlight 失败)时的真实说明 const [scopeNotice, setScopeNotice] = useState(""); - // 每次检索递增;慢的旧请求晚返回时序号已过期,结果直接丢弃,不能覆盖新关键词的结果 + + const [checkedPaths, setCheckedPaths] = useState([]); + const [selectedFilePath, setSelectedFilePath] = useState(""); + const [previewCache, setPreviewCache] = useState>({}); + const [commonFolders, setCommonFolders] = useState([]); + const [volumes, setVolumes] = useState([]); + const [indexerStats, setIndexerStats] = useState(null); + const [isRefreshingIndex, setIsRefreshingIndex] = useState(false); + + const [bookmarks, setBookmarks] = useState([]); + const [history, setHistory] = useState([]); + const searchSeqRef = useRef(0); const debounceTimerRef = useRef | null>(null); + const aliveRef = useRef(true); + const prefsRef = useRef(DEFAULT_PREFERENCES); + prefsRef.current = { sortOption, includeHidden, livePreview }; + + const persistPreferences = (next: SearchPreferences) => { + void LocalStorage.setItem(STORAGE_KEYS.preferences, next).catch((err) => { + console.warn("[everything-file-search] persistPreferences failed:", err); + }); + }; + + const recordSearchHistory = (text: string) => { + const clean = text.trim(); + if (clean.length < 2) return; + setHistory((prev) => { + const updated = [clean, ...prev.filter((item) => item !== clean)].slice(0, MAX_HISTORY_ITEMS); + void LocalStorage.setItem(STORAGE_KEYS.history, updated).catch((err) => { + console.warn("[everything-file-search] recordSearchHistory failed:", err); + }); + return updated; + }); + }; + + const runSearch = ( + text: string, + delayMs: number, + overrides?: { + typeFilter?: TypeFilter; + kindFilter?: KindFilter; + timeFilter?: TimeFilter; + sizeFilter?: SizeFilter; + includeHidden?: boolean; + sortBy?: SortOption; + pathPrefix?: string; + offset?: number; + append?: boolean; + recordHistory?: boolean; + } + ) => { + const activeType = overrides?.typeFilter ?? typeFilter; + const activeKind = overrides?.kindFilter ?? kindFilter; + const activeTime = overrides?.timeFilter ?? timeFilter; + const activeSize = overrides?.sizeFilter ?? sizeFilter; + const activeHidden = overrides?.includeHidden ?? includeHidden; + const activeSort = overrides?.sortBy ?? sortOption; + const activePrefix = overrides?.pathPrefix ?? pathPrefix; + const offset = overrides?.offset ?? 0; + const append = overrides?.append === true; + + const effectiveQuery = composeEffectiveQuery(text, activeTime, activeSize); - const runSearch = (text: string, delayMs: number) => { const seq = ++searchSeqRef.current; if (debounceTimerRef.current) clearTimeout(debounceTimerRef.current); setIsLoading(true); @@ -245,42 +410,420 @@ export default function EverythingFileSearchCommand() { let results: FileRecord[] = []; let notice = ""; let failure = ""; + let matchedTotal = 0; + let more = false; + let costMs: number | undefined; try { - const outcome = await searchLocalFilesDetailed(text, 50); + const outcome = await searchLocalFilesDetailed(effectiveQuery, PAGE_SIZE, undefined, { + offset, + typeFilter: activeType, + kind: activeKind, + sortBy: activeSort, + includeHidden: activeHidden, + pathPrefix: activePrefix + }); results = outcome.files; notice = outcome.scopeNotice; + matchedTotal = outcome.totalMatches; + more = outcome.hasMore; + costMs = outcome.elapsedMs; } catch (err) { failure = err instanceof Error ? err.message : String(err); } - if (seq !== searchSeqRef.current) return; + if (!aliveRef.current || seq !== searchSeqRef.current) return; setSearchError(failure); setScopeNotice(notice); - setAllFiles(results); + setTotalMatches(matchedTotal); + setHasMore(more); + setElapsedMs(costMs); + if (append) { + setAllFiles((prev) => { + const seen = new Set(prev.map((item) => item.path)); + return [...prev, ...results.filter((item) => !seen.has(item.path))]; + }); + } else { + setAllFiles(results); + setCheckedPaths([]); + } + if (!failure && overrides?.recordHistory) { + recordSearchHistory(text); + } setIsLoading(false); }, delayMs); }; - const handleSearchTextChange = (text: string) => { - setQuery(text); - runSearch(text, SEARCH_DEBOUNCE_MS); - }; - useEffect(() => { - if (isRealElectronHost()) { - runSearch("", 0); - } + aliveRef.current = true; + let initialPrefs = DEFAULT_PREFERENCES; + + const bootstrap = async () => { + try { + const [savedPrefs, savedBookmarks, savedHistory] = await Promise.all([ + LocalStorage.getItem>(STORAGE_KEYS.preferences).catch(() => undefined), + LocalStorage.getItem(STORAGE_KEYS.bookmarks).catch(() => undefined), + LocalStorage.getItem(STORAGE_KEYS.history).catch(() => undefined) + ]); + if (!aliveRef.current) return; + + if (savedPrefs && typeof savedPrefs === "object") { + const restoredSort = isValidSortOption(savedPrefs.sortOption) + ? savedPrefs.sortOption + : DEFAULT_PREFERENCES.sortOption; + const restoredHidden = typeof savedPrefs.includeHidden === "boolean" + ? savedPrefs.includeHidden + : DEFAULT_PREFERENCES.includeHidden; + const restoredPreview = typeof savedPrefs.livePreview === "boolean" + ? savedPrefs.livePreview + : DEFAULT_PREFERENCES.livePreview; + initialPrefs = { + sortOption: restoredSort, + includeHidden: restoredHidden, + livePreview: restoredPreview + }; + setSortOption(restoredSort); + setIncludeHidden(restoredHidden); + setLivePreview(restoredPreview); + } + if (Array.isArray(savedBookmarks)) { + setBookmarks(savedBookmarks.filter((b) => b && typeof b.id === "string")); + } + if (Array.isArray(savedHistory)) { + setHistory(savedHistory.filter((h) => typeof h === "string" && h.trim().length > 0).slice(0, MAX_HISTORY_ITEMS)); + } + } catch { + // 忽略存储读取异常,使用默认配置 + } + + if (!aliveRef.current) return; + if (isRealElectronHost()) { + runSearch("", 0, { + sortBy: initialPrefs.sortOption, + includeHidden: initialPrefs.includeHidden + }); + void Promise.allSettled([ + loadCommonFolders(), + loadMountedVolumes(), + getIndexerStats() + ]).then(([foldersRes, drivesRes, statsRes]) => { + if (!aliveRef.current) return; + if (foldersRes.status === "fulfilled" && foldersRes.value.length > 0) setCommonFolders(foldersRes.value); + if (drivesRes.status === "fulfilled" && drivesRes.value.length > 0) setVolumes(drivesRes.value); + if (statsRes.status === "fulfilled" && statsRes.value) setIndexerStats(statsRes.value); + }); + } + }; + + void bootstrap(); + return () => { - // 视图卸载:作废所有在途检索,清掉防抖定时器 + aliveRef.current = false; searchSeqRef.current++; if (debounceTimerRef.current) clearTimeout(debounceTimerRef.current); debounceTimerRef.current = null; }; }, []); - // 排序与筛选后的展示列表 - const displayedFiles = sortAndFilterFiles(allFiles, sortOption, typeFilter); + const displayedFiles = sortAndFilterFiles(allFiles, sortOption, typeFilter, kindFilter); const totalSizeBytes = displayedFiles.reduce((acc, f) => acc + (f.isDir ? 0 : f.size || 0), 0); + // 实时侧边预览:选中项变化且开启 livePreview 时,懒加载该文件的 QuickLook 内容 + const activePreviewFile = displayedFiles.find((f) => f.path === selectedFilePath) || displayedFiles[0]; + useEffect(() => { + if (!livePreview || !inClient || !activePreviewFile) return; + if (previewCache[activePreviewFile.path]) return; + let alive = true; + void getFileQuickLook(activePreviewFile).then((ql) => { + if (!alive || !aliveRef.current) return; + setPreviewCache((prev) => ({ ...prev, [activePreviewFile.path]: ql })); + }); + return () => { alive = false; }; + }, [livePreview, activePreviewFile?.path]); + + const handleSearchTextChange = (text: string) => { + setQuery(text); + runSearch(text, SEARCH_DEBOUNCE_MS, { recordHistory: true }); + }; + + const handleSortChange = (nextSort: SortOption) => { + setSortOption(nextSort); + persistPreferences({ ...prefsRef.current, sortOption: nextSort }); + if (inClient) { + runSearch(query, 0, { sortBy: nextSort, offset: 0, append: false }); + } + }; + + const handleReverseSort = () => { + handleSortChange(reverseSortOption(sortOption)); + }; + + const handleTypeFilterChange = (nextType: TypeFilter, navId?: string) => { + setTypeFilter(nextType); + if (navId) setActiveNavId(navId); + if (inClient) { + runSearch(query, 0, { typeFilter: nextType, offset: 0, append: false }); + } + }; + + const handleKindFilterChange = (nextKind: KindFilter) => { + setKindFilter(nextKind); + if (inClient) { + runSearch(query, 0, { kindFilter: nextKind, offset: 0, append: false }); + } + }; + + const handleTimeFilterChange = (nextTime: TimeFilter) => { + setTimeFilter(nextTime); + if (inClient) { + runSearch(query, 0, { timeFilter: nextTime, offset: 0, append: false }); + } + }; + + const handleSizeFilterChange = (nextSize: SizeFilter) => { + setSizeFilter(nextSize); + if (inClient) { + runSearch(query, 0, { sizeFilter: nextSize, offset: 0, append: false }); + } + }; + + const handleToggleIncludeHidden = () => { + const next = !includeHidden; + setIncludeHidden(next); + persistPreferences({ ...prefsRef.current, includeHidden: next }); + if (inClient) { + runSearch(query, 0, { includeHidden: next, offset: 0, append: false }); + } + }; + + const handleToggleLivePreview = () => { + const next = !livePreview; + setLivePreview(next); + persistPreferences({ ...prefsRef.current, livePreview: next }); + }; + + const handleScopeDirectory = (nextDir: string, navId?: string) => { + setPathPrefix(nextDir); + if (navId) setActiveNavId(navId); + else setActiveNavId(nextDir ? "scope:custom" : "preset:all"); + if (inClient) { + runSearch(query, 0, { pathPrefix: nextDir, offset: 0, append: false }); + } + }; + + const handleApplyPreset = (preset: "all" | "today" | "week" | "large") => { + setActiveNavId(`preset:${preset}`); + if (preset === "all") { + setPathPrefix(""); + setTypeFilter("all"); + setKindFilter("all"); + setTimeFilter("any"); + setSizeFilter("any"); + if (inClient) { + runSearch(query, 0, { + pathPrefix: "", + typeFilter: "all", + kindFilter: "all", + timeFilter: "any", + sizeFilter: "any", + offset: 0, + append: false + }); + } + return; + } + if (preset === "today") { + setTimeFilter("today"); + setSortOption("mtime-desc"); + persistPreferences({ ...prefsRef.current, sortOption: "mtime-desc" }); + if (inClient) { + runSearch(query, 0, { timeFilter: "today", sortBy: "mtime-desc", offset: 0, append: false }); + } + return; + } + if (preset === "week") { + setTimeFilter("7d"); + setSortOption("mtime-desc"); + persistPreferences({ ...prefsRef.current, sortOption: "mtime-desc" }); + if (inClient) { + runSearch(query, 0, { timeFilter: "7d", sortBy: "mtime-desc", offset: 0, append: false }); + } + return; + } + setSizeFilter("gt10mb"); + setKindFilter("file"); + setSortOption("size-desc"); + persistPreferences({ ...prefsRef.current, sortOption: "size-desc" }); + if (inClient) { + runSearch(query, 0, { sizeFilter: "gt10mb", kindFilter: "file", sortBy: "size-desc", offset: 0, append: false }); + } + }; + + const handleResetFilters = async () => { + setQuery(""); + setTypeFilter("all"); + setKindFilter("all"); + setTimeFilter("any"); + setSizeFilter("any"); + setPathPrefix(""); + setActiveNavId("preset:all"); + if (inClient) { + runSearch("", 0, { + typeFilter: "all", + kindFilter: "all", + timeFilter: "any", + sizeFilter: "any", + pathPrefix: "", + offset: 0, + append: false + }); + } + await showToast(Toast.Style.Success, t("toastFiltersReset")); + }; + + const handleSaveBookmark = async () => { + const hasFilter = Boolean( + query.trim() || + typeFilter !== "all" || + kindFilter !== "all" || + timeFilter !== "any" || + sizeFilter !== "any" || + pathPrefix + ); + if (!hasFilter) { + await showToast(Toast.Style.Failure, t("toastBookmarkEmpty")); + return; + } + const titleParts: string[] = []; + if (query.trim()) titleParts.push(query.trim()); + if (pathPrefix) titleParts.push(truncatePath(pathPrefix, 20)); + if (typeFilter !== "all") titleParts.push(typeFilter); + if (timeFilter !== "any") titleParts.push(timeFilter); + if (sizeFilter !== "any") titleParts.push(sizeFilter); + const title = titleParts.join(" · ") || t("navAllFiles"); + const bookmark: SearchBookmark = { + id: `bm_${Date.now()}`, + title, + query, + typeFilter, + kindFilter, + timeFilter, + sizeFilter, + pathPrefix, + sortOption, + includeHidden, + createdAt: Date.now() + }; + const next = [bookmark, ...bookmarks].slice(0, MAX_BOOKMARKS); + try { + await LocalStorage.setItem(STORAGE_KEYS.bookmarks, next); + if (!aliveRef.current) return; + setBookmarks(next); + await showToast(Toast.Style.Success, t("toastBookmarkSaved", { title })); + } catch (err) { + if (aliveRef.current) { + await showToast(Toast.Style.Failure, err instanceof Error ? err.message : String(err)); + } + } + }; + + const handleApplyBookmark = (bm: SearchBookmark) => { + setQuery(bm.query); + setTypeFilter(bm.typeFilter); + setKindFilter(bm.kindFilter); + setTimeFilter(bm.timeFilter); + setSizeFilter(bm.sizeFilter); + setPathPrefix(bm.pathPrefix); + setSortOption(bm.sortOption); + setIncludeHidden(bm.includeHidden); + setActiveNavId(`bm:${bm.id}`); + persistPreferences({ ...prefsRef.current, sortOption: bm.sortOption, includeHidden: bm.includeHidden }); + if (inClient) { + runSearch(bm.query, 0, { + typeFilter: bm.typeFilter, + kindFilter: bm.kindFilter, + timeFilter: bm.timeFilter, + sizeFilter: bm.sizeFilter, + pathPrefix: bm.pathPrefix, + sortBy: bm.sortOption, + includeHidden: bm.includeHidden, + offset: 0, + append: false + }); + } + }; + + const handleDeleteBookmark = async (id: string) => { + const next = bookmarks.filter((b) => b.id !== id); + try { + await LocalStorage.setItem(STORAGE_KEYS.bookmarks, next); + if (!aliveRef.current) return; + setBookmarks(next); + await showToast(Toast.Style.Success, t("toastBookmarkRemoved")); + } catch (err) { + if (aliveRef.current) { + await showToast(Toast.Style.Failure, err instanceof Error ? err.message : String(err)); + } + } + }; + + const handleDeleteHistory = (term: string) => { + const next = history.filter((h) => h !== term); + setHistory(next); + void LocalStorage.setItem(STORAGE_KEYS.history, next).catch((err) => { + console.warn("[everything-file-search] handleDeleteHistory failed:", err); + }); + }; + + const handleClearHistory = async () => { + try { + await LocalStorage.removeItem(STORAGE_KEYS.history); + if (!aliveRef.current) return; + setHistory([]); + await showToast(Toast.Style.Success, t("toastHistoryCleared")); + } catch (err) { + if (aliveRef.current) { + await showToast(Toast.Style.Failure, err instanceof Error ? err.message : String(err)); + } + } + }; + + const handleRefreshIndex = async (mode: "sync" | "rebuild" = "sync") => { + if (!inClient || isRefreshingIndex) return; + setIsRefreshingIndex(true); + try { + const result = await refreshFileIndex(mode); + if (!aliveRef.current) return; + await showToast(result.ok ? Toast.Style.Success : Toast.Style.Failure, result.message); + if (result.ok) { + const stats = await getIndexerStats(); + if (!aliveRef.current) return; + if (stats) setIndexerStats(stats); + runSearch(query, 0, { offset: 0, append: false }); + } + } finally { + if (aliveRef.current) setIsRefreshingIndex(false); + } + }; + + const handleViewIndexStats = async () => { + const stats = indexerStats ?? await getIndexerStats(); + if (!aliveRef.current) return; + if (!stats) { + await showToast(Toast.Style.Failure, t("toastIndexStatsUnavailable")); + return; + } + setIndexerStats(stats); + const count = formatIndexedCount(stats.totalIndexed); + const msg = stats.indexedDrives.length > 0 + ? t("toastIndexStatsMsg", { count, drives: stats.indexedDrives.join(", ") }) + : t("toastIndexStatsNoDrives", { count, type: stats.indexType || "local" }); + await showToast(Toast.Style.Success, t("toastIndexStatsTitle"), msg); + }; + + const handleLoadMore = () => { + if (!inClient || isLoading || !hasMore) return; + runSearch(query, 0, { offset: allFiles.length, append: true }); + }; + const handleMoveToTrash = async (file: FileRecord) => { const confirmed = await confirmAlert({ title: t("confirmTrashTitle", { name: file.name, trash: platformNames().trash }), @@ -288,14 +831,84 @@ export default function EverythingFileSearchCommand() { primaryAction: { title: t("actionMoveToTrash", { trash: platformNames().trash }), style: "destructive" }, dismissAction: { title: t("actionCancel") } }); - if (!confirmed) return; + if (!confirmed || !aliveRef.current) return; const res = await moveToTrash(file.path, undefined, file.isDir); + if (!aliveRef.current) return; if (res.success) { setAllFiles((prev) => prev.filter((f) => f.path !== file.path)); + setCheckedPaths((prev) => prev.filter((p) => p !== file.path)); } await toastResult(res); }; + const checkedSet = new Set(checkedPaths); + const checkedFiles = displayedFiles.filter((f) => checkedSet.has(f.path)); + const checkedSizeBytes = checkedFiles.reduce((acc, f) => acc + (f.isDir ? 0 : f.size || 0), 0); + const checkedRegularFiles = checkedFiles.filter((f) => !f.isDir); + + const handleToggleCheckPath = (filePath: string, nextChecked: boolean) => { + setCheckedPaths((prev) => { + if (nextChecked) { + return prev.includes(filePath) ? prev : [...prev, filePath]; + } + return prev.filter((p) => p !== filePath); + }); + }; + + const handleToggleCheckAll = (nextChecked: boolean) => { + if (nextChecked) { + setCheckedPaths(displayedFiles.map((f) => f.path)); + } else { + setCheckedPaths([]); + } + }; + + const handleBatchCopyPaths = async () => { + if (checkedFiles.length === 0) return; + await Clipboard.copy(checkedFiles.map((f) => f.path).join("\n")); + await showToast(Toast.Style.Success, t("toastBatchCopiedPaths", { count: checkedFiles.length })); + }; + + const handleBatchTrash = async () => { + if (checkedRegularFiles.length === 0) { + await showToast(Toast.Style.Failure, t("toastBatchTrashNoFiles", { trash: platformNames().trash })); + return; + } + const trash = platformNames().trash; + const skippedCount = checkedFiles.length - checkedRegularFiles.length; + const confirmed = await confirmAlert({ + title: t("confirmBatchTrashTitle", { count: checkedRegularFiles.length, trash }), + message: t("confirmBatchTrashMsg", { + first: checkedRegularFiles[0].name, + more: checkedRegularFiles.length > 1 ? t("confirmBatchTrashMore", { count: checkedRegularFiles.length - 1 }) : "", + skipNote: skippedCount > 0 ? t("confirmBatchTrashSkipDirs", { dirs: skippedCount }) : "" + }), + primaryAction: { title: t("actionMoveToTrash", { trash }), style: "destructive" }, + dismissAction: { title: t("actionCancel") } + }); + if (!confirmed || !aliveRef.current) return; + + const summary = await batchMoveToTrash(checkedFiles); + if (!aliveRef.current) return; + if (summary.trashedPaths.length > 0) { + const removedSet = new Set(summary.trashedPaths); + setAllFiles((prev) => prev.filter((f) => !removedSet.has(f.path))); + setCheckedPaths((prev) => prev.filter((p) => !removedSet.has(p))); + } + if (summary.failures.length === 0) { + await showToast(Toast.Style.Success, t("toastBatchTrashDone", { count: summary.trashedPaths.length, trash })); + } else { + await showToast( + Toast.Style.Failure, + t("toastBatchTrashPartial", { + ok: summary.trashedPaths.length, + fail: summary.failures.length, + reason: summary.failures[0]?.reason || "" + }) + ); + } + }; + const handleCopyFile = async (file: FileRecord) => toastResult(await copyFileToClipboard(file.path)); const handleCalculateSha256 = async (file: FileRecord) => { @@ -310,11 +923,356 @@ export default function EverythingFileSearchCommand() { }; const notInClientMsg = getNotInClientMessage(); + const scopeParts: string[] = []; + if (pathPrefix) scopeParts.push(t("scopeDirPrefix", { dir: truncatePath(pathPrefix, 32) })); + if (scopeNotice) scopeParts.push(scopeNotice); + const scopeLead = scopeParts.length > 0 ? `${scopeParts.join(" · ")} · ` : ""; + const elapsedText = elapsedMs !== undefined && elapsedMs >= 0 + ? t("summaryElapsed", { ms: elapsedMs < 10 ? elapsedMs.toFixed(1) : Math.round(elapsedMs) }) + : ""; + const indexedPart = indexerStats + ? indexerStats.indexing + ? ` · ${t("indexedWarming")}` + : indexerStats.totalIndexed > 0 + ? ` · ${t("indexedCountBrief", { count: formatIndexedCount(indexerStats.totalIndexed) })}` + : "" + : ""; + const remainingCount = Math.max(0, totalMatches - displayedFiles.length); + const hasAnyFilter = Boolean( + query.trim() || + typeFilter !== "all" || + kindFilter !== "all" || + timeFilter !== "any" || + sizeFilter !== "any" || + pathPrefix + ); + + const filterBarActions = [ + { + id: "toggle-live-preview", + title: livePreview ? t("btnDisablePreview") : t("btnEnablePreview"), + onAction: handleToggleLivePreview + }, + { + id: "refresh-index", + title: isRefreshingIndex ? t("btnRefreshingIndex") : t("btnRefreshIndex"), + disabled: isRefreshingIndex, + onAction: () => { void handleRefreshIndex("sync"); } + } + ]; + + const folderLabelMap: Record = { + desktop: t("navFolderDesktop"), + downloads: t("navFolderDownloads"), + documents: t("navFolderDocuments") + }; + + const buildFileActions = (file: FileRecord) => { + const isDir = file.isDir; + const parentDir = parentDirectoryOf(file.path); + return ( + + + {renderCoreFileActions(file)} + } + /> + + + + {checkedFiles.length > 0 ? ( + + + {checkedRegularFiles.length > 0 ? ( + + ) : null} + setCheckedPaths([])} + /> + + ) : null} + + + + {SORT_OPTIONS.map((opt) => ( + handleSortChange(opt)} + /> + ))} + + + + {isDir ? ( + handleScopeDirectory(file.path)} + /> + ) : parentDir ? ( + handleScopeDirectory(parentDir)} + /> + ) : null} + {pathPrefix ? ( + handleScopeDirectory(parentDirectoryOf(pathPrefix))} + /> + ) : null} + {pathPrefix ? ( + handleScopeDirectory("")} + /> + ) : null} + + {hasAnyFilter ? ( + + ) : null} + handleRefreshIndex("sync")} + /> + handleRefreshIndex("rebuild")} + /> + + + + + + {parentDir ? ( + + ) : null} + + handleCopyFile(file)} + /> + handleCalculateSha256(file)} + /> + + + {/* 宿主不允许回收文件夹(误删整个目录后果太大),文件夹结果不提供该动作 */} + {isDir ? null : ( + + handleMoveToTrash(file)} + /> + + )} + + ); + }; + + // 构建右侧列表项(布局二:subList.items;非客户端或失败时展示错误节点) + const subListItems = (() => { + if (!inClient) { + return [ + + ]; + } + if (searchError) { + return [ + + runSearch(query, 0)} /> + + } + /> + ]; + } + const items = displayedFiles.map((file) => { + const mtimeLabel = formatRelativeMtime(file.mtime); + const sizeLabel = file.isDir ? t("folderLabel") : formatBytes(file.size); + const accessories = mtimeLabel + ? [{ text: mtimeLabel }, { text: sizeLabel }] + : [{ text: sizeLabel }]; + const cachedQl = livePreview ? previewCache[file.path] : undefined; + return ( + handleToggleCheckPath(file.path, checked)} + onSelect={() => setSelectedFilePath(file.path)} + accessories={accessories} + detail={livePreview ? : undefined} + actions={buildFileActions(file)} + /> + ); + }); + if (hasMore && remainingCount > 0) { + const nextCount = Math.min(PAGE_SIZE, remainingCount); + items.push( + + + + } + /> + ); + } + return items; + })(); + + const allCheckedState: boolean | "indeterminate" = + displayedFiles.length === 0 || checkedFiles.length === 0 + ? false + : checkedFiles.length === displayedFiles.length + ? true + : "indeterminate"; + + const subListTitle = pathPrefix + ? t("scopeDirPrefix", { dir: truncatePath(pathPrefix, 36) }) + : t("navAllFiles"); + const subListSubtitle = checkedFiles.length > 0 + ? t("subListSubtitleChecked", { + checked: checkedFiles.length, + checkedSize: formatBytes(checkedSizeBytes), + count: displayedFiles.length + }) + : t("subListSubtitleCount", { + count: displayedFiles.length, + size: formatBytes(totalSizeBytes) + }); + + const typeMenuItems: Array<{ id: TypeFilter; title: string; icon: Icon }> = [ + { id: "all", title: t("typeAll"), icon: Icon.List }, + { id: "folder", title: t("typeFolder"), icon: Icon.Folder }, + { id: "document", title: t("typeDocument"), icon: Icon.Document }, + { id: "image", title: t("typeImage"), icon: Icon.Image }, + { id: "video", title: t("typeVideo"), icon: Icon.Video }, + { id: "audio", title: t("typeAudio"), icon: Icon.Play }, + { id: "archive", title: t("typeArchive"), icon: Icon.HardDrive }, + { id: "code", title: t("typeCode"), icon: Icon.Code }, + { id: "app", title: t("typeApp"), icon: Icon.Terminal } + ]; + + const kindLabel = kindFilter === "file" + ? t("filterKindFile") + : kindFilter === "directory" + ? t("filterKindDir") + : t("filterKindAll"); + const timeLabel = timeFilter === "today" + ? t("filterTimeToday") + : timeFilter === "7d" + ? t("filterTime7d") + : timeFilter === "30d" + ? t("filterTime30d") + : t("filterTimeAny"); + const sizeLabel = sizeFilter === "gt10mb" + ? t("filterSizeGt10mb") + : sizeFilter === "gt100mb" + ? t("filterSizeGt100mb") + : sizeFilter === "empty" + ? t("filterSizeEmpty") + : t("filterSizeAny"); return ( displayedFiles.length + ? t("summaryMatchedWithTotal", { + scope: scopeLead, + count: displayedFiles.length, + total: totalMatches, + size: formatBytes(totalSizeBytes), + elapsed: `${elapsedText}${indexedPart}`, + queryPart: query ? t("summaryQueryPart", { query }) : "" + }) + : t("summaryMatched", { + scope: scopeLead, + count: displayedFiles.length, + size: formatBytes(totalSizeBytes), + queryPart: `${elapsedText}${indexedPart}${query ? t("summaryQueryPart", { query }) : ""}` + }), + actions: inClient ? filterBarActions : [] }} searchBarAccessory={ { if (val.startsWith("sort:")) { - setSortOption(val.replace("sort:", "") as SortOption); - } else if (val.startsWith("type:")) { - setTypeFilter(val.replace("type:", "") as TypeFilter); + const next = val.slice(5); + if (isValidSortOption(next)) handleSortChange(next); } }} > - - - - - - - - - - - - - - - - + {SORT_OPTIONS.map((opt) => ( + + ))} } + subList={{ + title: subListTitle, + subtitle: subListSubtitle, + emptyText: hasAnyFilter ? t("emptyFilteredHint") : t("emptyNoMatch"), + checkable: displayedFiles.length > 0 && !searchError && inClient, + checked: allCheckedState, + onCheckChange: handleToggleCheckAll, + items: subListItems + }} > - {!inClient ? ( - - ) : searchError ? ( - runSearch(query, 0)} />} /> - ) : null} - {displayedFiles.map((file) => { - const isDir = file.isDir; - const category = getFileCategory(file.name, isDir); - - let fileIcon = Icon.Document; - if (isDir) fileIcon = Icon.Folder; - else if (category === "image") fileIcon = Icon.Image; - else if (category === "video") fileIcon = Icon.Video; - else if (category === "audio") fileIcon = Icon.Play; - else if (category === "code") fileIcon = Icon.Code; - else if (category === "archive") fileIcon = Icon.HardDrive; - else if (category === "app") fileIcon = Icon.Terminal; - - return ( + + handleApplyPreset("all")} + /> + handleApplyPreset("today")} + /> + handleApplyPreset("week")} + /> + 10MB" }]} + onSelect={() => handleApplyPreset("large")} + /> + {commonFolders.map((folder) => { + const navId = `folder:${folder.id}`; + const isCurrent = activeNavId === navId || pathPrefix === folder.path; + return ( + handleScopeDirectory(folder.path, navId)} + /> + ); + })} + {volumes.map((vol) => { + const navId = `vol:${vol.path}`; + const isCurrent = activeNavId === navId || pathPrefix === vol.path; + const cleanDrive = vol.path.replace(/[\\]+$/, ""); + return ( + handleScopeDirectory(vol.path, navId)} + /> + ); + })} + {pathPrefix && activeNavId === "scope:custom" ? ( - - toastResult(await openFile(file.path))} - /> - toastResult(await revealFile(file.path))} - /> - {/* 系统快速预览只在 macOS 上有;Windows 上不提供,避免把「在资源管理器中定位」当成预览成功 */} - {supportsSystemQuickLook() ? ( - toastResult(await quickLookFile(file.path))} - /> - ) : null} - } - /> - - - - - - handleCopyFile(file)} - /> - handleCalculateSha256(file)} - /> - - - {/* 宿主不允许回收文件夹(误删整个目录后果太大),文件夹结果不提供该动作 */} - {isDir ? null : ( - - handleMoveToTrash(file)} - /> - - )} + + handleScopeDirectory("")} /> + handleScopeDirectory(parentDirectoryOf(pathPrefix))} /> } /> - ); - })} + ) : null} + + + + {typeMenuItems.map((item) => { + const navId = `type:${item.id}`; + return ( + handleTypeFilterChange(item.id, navId)} + /> + ); + })} + + + + { + const order: readonly KindFilter[] = ["all", "file", "directory"]; + handleKindFilterChange(order[(order.indexOf(kindFilter) + 1) % order.length]); + }} + actions={ + + handleKindFilterChange("all")} /> + handleKindFilterChange("file")} /> + handleKindFilterChange("directory")} /> + + } + /> + { + const order: readonly TimeFilter[] = ["any", "today", "7d", "30d"]; + handleTimeFilterChange(order[(order.indexOf(timeFilter) + 1) % order.length]); + }} + actions={ + + handleTimeFilterChange("any")} /> + handleTimeFilterChange("today")} /> + handleTimeFilterChange("7d")} /> + handleTimeFilterChange("30d")} /> + + } + /> + { + const order: readonly SizeFilter[] = ["any", "gt10mb", "gt100mb", "empty"]; + handleSizeFilterChange(order[(order.indexOf(sizeFilter) + 1) % order.length]); + }} + actions={ + + handleSizeFilterChange("any")} /> + handleSizeFilterChange("gt10mb")} /> + handleSizeFilterChange("gt100mb")} /> + handleSizeFilterChange("empty")} /> + + } + /> + + + + {bookmarks.length > 0 ? ( + + {bookmarks.map((bm) => ( + handleApplyBookmark(bm)} + actions={ + + handleApplyBookmark(bm)} /> + handleDeleteBookmark(bm.id)} /> + + } + /> + ))} + + ) : null} + + {history.length > 0 ? ( + + {history.map((term) => ( + { + setQuery(term); + if (inClient) runSearch(term, 0, { offset: 0, append: false }); + }} + actions={ + + { + setQuery(term); + if (inClient) runSearch(term, 0, { offset: 0, append: false }); + }} + /> + handleDeleteHistory(term)} /> + + + } + /> + ))} + + ) : null} ); } diff --git a/extensions/everything-file-search/src/native-ipc.ts b/extensions/everything-file-search/src/native-ipc.ts index 51576b99..13643277 100644 --- a/extensions/everything-file-search/src/native-ipc.ts +++ b/extensions/everything-file-search/src/native-ipc.ts @@ -174,11 +174,13 @@ function normalizeMethodResult(method: string, payload: DynamicBridge): DynamicB if (method === 'system_get_battery_status') { // 宿主约定 percent 超出 0-100(如 255)表示无电池或电量未知,不能改写成 100% + // 若宿主明确给出 hasBattery 布尔值,必须原样保留,仅在缺失时按合法电量推算 const rawPct = payload.percent - const hasBattery = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const validPct = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const hasBattery = typeof payload.hasBattery === 'boolean' ? payload.hasBattery : validPct return { ...payload, - percent: hasBattery ? rawPct : null, + percent: validPct ? rawPct : null, hasBattery } } @@ -489,6 +491,8 @@ export interface RealDirectoryScanResult extends Iterable approximate?: boolean /** 宿主实际遍历的条目数 */ visitedEntries?: number + /** 目录本身不存在(ENOENT) */ + missing?: boolean /** 读取失败的真实原因;已有文件仍可使用,但不能当作完整结果。 */ error?: string } @@ -497,6 +501,7 @@ interface ScanResultMeta { truncated?: boolean approximate?: boolean visitedEntries?: number + missing?: boolean } export interface ScanDirectoryTreeOptions { @@ -504,6 +509,10 @@ export interface ScanDirectoryTreeOptions { maxFiles?: number collectTopN?: number filterExt?: RegExp + /** 为 true 时,目录本身不存在(ENOENT)按空目录处理,不返回 error(权限拒绝/读取失败仍照常报错) */ + ignoreMissing?: boolean + /** Top-N 保留与排序方式:默认按体积降序,下载/录屏等时效场景可传 mtime-desc */ + sortBy?: 'size-desc' | 'mtime-desc' hostOverride?: DynamicBridge } @@ -519,8 +528,9 @@ function normalizeIndexedFileEntry(f: DynamicBridge): RealIndexedFileEntry { const sz = Number(f?.size ?? f?.sizeBytes ?? 0) const isDir = Boolean(f?.is_dir || f?.isDir || f?.isDirectory) const rawMtime = Number(f?.mtime ?? f?.mtimeMs ?? 0) - const mtimeMs = rawMtime > 1e11 ? rawMtime : rawMtime > 0 ? rawMtime * 1000 : Date.now() - const mtimeSec = rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime + const validMtime = Number.isFinite(rawMtime) && rawMtime > 0 + const mtimeMs = validMtime ? (rawMtime > 1e11 ? rawMtime : rawMtime * 1000) : 0 + const mtimeSec = validMtime ? (rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime) : 0 if (p && sz >= 0) realFileSizeCache.set(p, sz) return { name, @@ -551,6 +561,7 @@ function makeScanResult( subdirs, ...(meta.truncated ? { truncated: true } : {}), ...(meta.approximate ? { approximate: true } : {}), + ...(meta.missing ? { missing: true } : {}), ...(typeof meta.visitedEntries === 'number' ? { visitedEntries: meta.visitedEntries } : {}), [Symbol.iterator]() { return files[Symbol.iterator]() @@ -609,13 +620,40 @@ export async function scanRealDirectoryTree( return result.error ? { ...result.scan, error: result.error } : result.scan } +/** 仅当正则明确声明了扩展名(含 `\.`)时提取后缀列表,避免把 `thumbcache|iconcache` 等文件名关键词误拆成假扩展名 */ +function extractExtensionTokensFromFilter(filterExt: RegExp): string[] { + const src = filterExt.source + if (!src.includes('\\.')) return [] + const afterDot = src.slice(src.indexOf('\\.') + 2) + const rawTokens = afterDot.match(/[a-z0-9]{1,8}/gi) || [] + const seen = new Set() + const out: string[] = [] + for (const token of rawTokens) { + const lower = token.toLowerCase() + if (!lower || seen.has(lower)) continue + seen.add(lower) + out.push(lower) + } + return out +} + +function isMissingDirectoryError(res: { error?: string; errorCode?: string; errorDetails?: Record }): boolean { + if (res.errorDetails?.reason === 'ENOENT' || res.errorCode === 'ENOENT') return true + const msg = String(res.error || '') + return /Directory does not exist|ENOENT/i.test(msg) +} + /** 一次界面扫描的错误汇总;多个目录并行扫描时保留可读目录的结果。 */ export function createDirectoryScanner(hostOverride?: DynamicBridge) { const failures = new Map() return { async scan(dir: string, options: number | ScanDirectoryTreeOptions = 160) { const result = await scanRealDirectoryTree(dir, options, hostOverride) - const error = result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') + const ignoreMissing = typeof options === 'object' && options !== null && options.ignoreMissing === true + const error = + result.missing && ignoreMissing + ? '' + : result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') if (error) failures.set(dir, error) else failures.delete(dir) return result @@ -648,26 +686,38 @@ async function scanDirectoryTreeWithError( const safeLimit = Math.min(200, Math.max(1, Math.floor(rawLimit || 160))) const hostOverride = opts.hostOverride const filterExt = opts.filterExt + const ignoreMissing = opts.ignoreMissing === true const dirQuery = `dir:${targetDir}` try { let rawPayload: DynamicBridge = null + const searchParams: Record = { + query: dirQuery, + limit: safeLimit, + ...(opts.sortBy ? { sortBy: opts.sortBy } : {}) + } const res = await callHostTransport( 'system_search_files', - { query: dirQuery, limit: safeLimit }, + searchParams, hostOverride ) - if (res.ok && res.data) { + if (res.ok && res.data && res.data.degraded !== true) { rawPayload = res.data + } else if (!res.ok && ignoreMissing && isMissingDirectoryError(res)) { + const missingScan = makeScanResult([], 0, 0, [], { missing: true }) + return { scan: missingScan } } - if (!rawPayload && !hostOverride && typeof window !== 'undefined') { + if (!rawPayload && !hostOverride && res.errorCode === 'METHOD_NOT_AVAILABLE' && typeof window !== 'undefined') { const w = window as DynamicBridge if (typeof w.__ztoolsLauncher?.searchFiles === 'function') { const rawOuter = await w.__ztoolsLauncher.searchFiles(dirQuery, safeLimit) - rawPayload = + const candidate = rawOuter && typeof rawOuter === 'object' && 'data' in rawOuter && rawOuter.data ? rawOuter.data : rawOuter + if (candidate && candidate.degraded !== true && candidate.success !== false) { + rawPayload = candidate + } } } @@ -678,29 +728,32 @@ async function scanDirectoryTreeWithError( let files: RealIndexedFileEntry[] = rawPayload.files.map(normalizeIndexedFileEntry) if (filterExt instanceof RegExp) { files = files.filter(f => !f.isDir && (filterExt.test(f.name) || filterExt.test(f.ext))) - // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索目标扩展名 + // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索明确声明的目标扩展名 if (files.length === 0 && !hostOverride) { - const extTokens = (filterExt.source.match(/[a-z0-9]{2,5}/gi) || []) - .filter(t => !['thumbcache', 'iconcache'].includes(t.toLowerCase())) - .slice(0, 4) - // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 - const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() - const extraLists = await Promise.all( - extTokens.map(ext => searchRealIndexedFiles(`.${ext.toLowerCase()}`, 30, hostOverride)) - ) - const seen = new Set() - for (const list of extraLists) { - for (const item of list) { - if (!item.isDir && item.size > 0 && !seen.has(item.path)) { - if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { - seen.add(item.path) - files.push(item) + const extTokens = extractExtensionTokensFromFilter(filterExt) + if (extTokens.length > 0) { + // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 + const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() + const extraLists = await Promise.all( + extTokens.map(ext => searchRealIndexedFiles(`.${ext}`, 30, hostOverride)) + ) + const seen = new Set() + for (const list of extraLists) { + for (const item of list) { + if (!item.isDir && item.size > 0 && !seen.has(item.path)) { + if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { + seen.add(item.path) + files.push(item) + } } } } } } } + // 先基于过滤后的完整命中集合计算总文件数与总字节数,再按 collectTopN 裁剪样本列表 + const matchedCount = files.length + const matchedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) if (typeof opts.collectTopN === 'number' && opts.collectTopN > 0 && files.length > opts.collectTopN) { files = files.slice(0, opts.collectTopN) } @@ -714,11 +767,10 @@ async function scanDirectoryTreeWithError( ...(s.approximate === true ? { approximate: true } : {}) })) : [] - const computedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) const totalFilesCount = - filterExt instanceof RegExp ? files.length : Number(rawPayload.total_matches ?? files.length) + filterExt instanceof RegExp ? matchedCount : Number(rawPayload.total_matches ?? matchedCount) const totalBytesCount = - filterExt instanceof RegExp ? computedBytes : Number(rawPayload.total_bytes ?? computedBytes) + filterExt instanceof RegExp ? matchedBytes : Number(rawPayload.total_bytes ?? matchedBytes) const visited = Number(rawPayload.visited_entries) return { scan: makeScanResult(files, totalFilesCount, totalBytesCount, subdirs, { @@ -1817,8 +1869,6 @@ export async function writeRealClipboardText(text: string, hostOverride?: Dynami const payload = { text: String(text || '') } const res = await callHostTransport('clipboard_copy_text', payload, hostOverride) if (res.ok) return true - const fallbackRes = await callHostTransport('clipboard_write_text', payload, hostOverride) - if (fallbackRes.ok) return true try { if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) { await navigator.clipboard.writeText(String(text || '')) diff --git a/extensions/everything-file-search/src/search-service.js b/extensions/everything-file-search/src/search-service.js deleted file mode 100644 index 101d2172..00000000 --- a/extensions/everything-file-search/src/search-service.js +++ /dev/null @@ -1,184 +0,0 @@ -import { getLocale } from "@ztools/declarative-ui"; - -export function formatBytes(bytes) { - if (bytes <= 0 || !Number.isFinite(bytes)) - return "0 B"; - const units = ["B", "KB", "MB", "GB", "TB"]; - const i = Math.floor(Math.log(bytes) / Math.log(1024)); - const val = bytes / Math.pow(1024, i); - return `${val.toFixed(i === 0 ? 0 : 1)} ${units[i]}`; -} -export function truncatePath(fullPath, maxLength = 46) { - if (!fullPath) - return ""; - if (fullPath.length <= maxLength) - return fullPath; - const parts = fullPath.split(/[\\/]/); - if (parts.length <= 3) - return fullPath; - return `${parts[0]}\\...\\${parts.slice(-2).join("\\")}`; -} -export function getFileCategory(fileName, isDir) { - if (isDir) - return "folder"; - const ext = (fileName.split(".").pop() || "").toLowerCase(); - if (["doc", "docx", "pdf", "txt", "md", "xls", "xlsx", "ppt", "pptx", "csv"].includes(ext)) { - return "document"; - } - if (["png", "jpg", "jpeg", "gif", "webp", "svg", "bmp", "ico"].includes(ext)) { - return "image"; - } - if (["mp4", "mkv", "avi", "mov", "mp3", "wav", "flac", "aac", "ogg"].includes(ext)) { - return "media"; - } - if (["js", "ts", "vue", "html", "css", "json", "py", "cpp", "c", "h", "rs", "go", "java", "sql"].includes(ext)) { - return "code"; - } - if (["zip", "rar", "7z", "tar", "gz"].includes(ext)) { - return "archive"; - } - if (["exe", "bat", "cmd", "msi", "ps1"].includes(ext)) { - return "app"; - } - return "document"; -} -export const SAMPLE_FILES = [ - { - name: "ZTools-Architecture-Design.docx", - path: "C:\\Users\\User\\Documents\\ZTools\\ZTools-Architecture-Design.docx", - isDir: false, - size: 4520192, - mtime: Date.now() - 3600000 * 2, - acronym: "zad", - pinyin: "ztools architecture" - }, - { - name: "launcher-design-notes.md", - path: "D:\\Workspace\\Projects\\ZTools\\docs\\launcher-design-notes.md", - isDir: false, - size: 25451, - mtime: Date.now() - 3600000 * 5, - acronym: "ldn", - pinyin: "launcher design notes" - }, - { - name: "Development-Plan-2026.pdf", - path: "C:\\Users\\User\\Downloads\\Development-Plan-2026.pdf", - isDir: false, - size: 1845120, - mtime: Date.now() - 3600000 * 12, - acronym: "dp2", - pinyin: "development plan" - }, - { - name: "ztools-indexer.exe", - path: "D:\\Workspace\\Projects\\ZTools\\electron-client\\out\\native\\win32-x64\\bin\\ztools-indexer.exe", - isDir: false, - size: 891240, - mtime: Date.now() - 3600000 * 18, - acronym: "zi", - pinyin: "ztools indexer" - }, - { - name: "Projects", - path: "D:\\Workspace\\Projects", - isDir: true, - size: 0, - mtime: Date.now() - 86400000 * 3, - acronym: "p", - pinyin: "projects" - }, - { - name: "wechat-backup-2026.zip", - path: "D:\\Backup\\wechat-backup-2026.zip", - isDir: false, - size: 852910240, - mtime: Date.now() - 86400000 * 6, - acronym: "wb", - pinyin: "wechat backup" - }, - { - name: "indexer.rs", - path: "D:\\Workspace\\Projects\\ZTools\\electron-client\\native\\indexer\\src\\main.rs", - isDir: false, - size: 14208, - mtime: Date.now() - 3600000 * 3, - acronym: "ir", - pinyin: "indexer rs" - }, - { - name: "architecture-diagram.png", - path: "D:\\Workspace\\Projects\\ZTools\\docs\\images\\architecture-diagram.png", - isDir: false, - size: 382910, - mtime: Date.now() - 3600000 * 8, - acronym: "adp", - pinyin: "architecture diagram" - } -]; -export function sortAndFilterFiles(files, sortOption, typeFilter) { - let result = files; - if (typeFilter !== "all") { - result = result.filter((f) => getFileCategory(f.name, f.isDir) === typeFilter); - } - const sorted = [...result]; - const locale = getLocale(); - switch (sortOption) { - case "name-asc": - sorted.sort((a, b) => a.name.localeCompare(b.name, locale)); - break; - case "name-desc": - sorted.sort((a, b) => b.name.localeCompare(a.name, locale)); - break; - case "size-desc": - sorted.sort((a, b) => b.size - a.size); - break; - case "size-asc": - sorted.sort((a, b) => a.size - b.size); - break; - case "mtime-desc": - sorted.sort((a, b) => b.mtime - a.mtime); - break; - case "mtime-asc": - sorted.sort((a, b) => a.mtime - b.mtime); - break; - } - return sorted; -} -export async function searchLocalFiles(query, limit = 50) { - const trimmed = (query || "").trim().toLowerCase(); - // 1. 若在真实宿主浏览器/Renderer环境中,调用自有底层引擎 - try { - const launcher = globalThis.__ztoolsLauncher; - const system = globalThis.ztools?.system; - let res = null; - if (launcher?.searchFiles) { - res = await launcher.searchFiles(trimmed, limit); - } - else if (system?.searchFiles) { - res = await system.searchFiles(trimmed, limit); - } - if (res && Array.isArray(res.files)) { - return res.files.map((f) => ({ - name: f.name, - path: f.path, - isDir: Boolean(f.is_dir), - size: Number(f.size) || 0, - mtime: Number(f.mtime) || Date.now(), - acronym: f.acronym, - pinyin: f.pinyin - })); - } - } - catch (err) { - console.warn("[EverythingFileSearch] 调用宿主引擎异常,转入回退引擎:", err); - } - // 2. 离线/测试/降级兜底引擎 - if (!trimmed) { - return SAMPLE_FILES; - } - return SAMPLE_FILES.filter((f) => f.name.toLowerCase().includes(trimmed) || - f.path.toLowerCase().includes(trimmed) || - (f.acronym && f.acronym.includes(trimmed)) || - (f.pinyin && f.pinyin.includes(trimmed))); -} diff --git a/extensions/everything-file-search/src/search-service.ts b/extensions/everything-file-search/src/search-service.ts index 2ed40d00..37ea817e 100644 --- a/extensions/everything-file-search/src/search-service.ts +++ b/extensions/everything-file-search/src/search-service.ts @@ -1,11 +1,25 @@ import { getLocale } from "@ztools/declarative-ui"; import { t } from "./i18n.js"; -import { FileRecord, SortOption, TypeFilter, FileQuickLookResult, FileActionResult } from "./types.js"; +import { + FileRecord, + SortOption, + TypeFilter, + KindFilter, + TimeFilter, + SizeFilter, + VolumeScope, + CommonFolderScope, + IndexerStats, + IndexRefreshResult, + BatchTrashSummary, + FileQuickLookResult, + FileActionResult +} from "./types.js"; import { callHostTransport, isRealElectronHost, getRealSystemPath, - readRealDirectory, + probeRealDiskDrives, listDirectChildren, DIRECTORY_EMPTY_OR_UNREADABLE, trashRealItem, @@ -129,10 +143,17 @@ export function supportsSystemQuickLook(platform?: string): boolean { export function sortAndFilterFiles( files: FileRecord[], sortOption: SortOption, - typeFilter: TypeFilter + typeFilter: TypeFilter, + kindFilter: KindFilter = "all" ): FileRecord[] { let result = files; + if (kindFilter === "file") { + result = result.filter((f) => !f.isDir); + } else if (kindFilter === "directory") { + result = result.filter((f) => f.isDir); + } + if (typeFilter === "video") { result = result.filter((f) => getFileCategory(f.name, f.isDir, true) === "video"); } else if (typeFilter === "audio") { @@ -146,6 +167,9 @@ export function sortAndFilterFiles( const sorted = [...result]; switch (sortOption) { + case "relevance": + // 保留底层引擎相关性打分顺序 + break; case "name-asc": sorted.sort((a, b) => a.name.localeCompare(b.name, getLocale())); break; @@ -168,6 +192,95 @@ export function sortAndFilterFiles( return sorted; } +/** + * 反转当前排序方向;相关性优先时默认切为修改时间最新优先 + */ +export function reverseSortOption(opt: SortOption): SortOption { + switch (opt) { + case "relevance": return "mtime-desc"; + case "mtime-desc": return "mtime-asc"; + case "mtime-asc": return "mtime-desc"; + case "size-desc": return "size-asc"; + case "size-asc": return "size-desc"; + case "name-asc": return "name-desc"; + case "name-desc": return "name-asc"; + } +} + +/** + * 将搜索框词条与左侧精细筛选(修改时间 / 文件大小)组合为引擎查询语句。 + * 若用户已在搜索框手写对应语法(dm:/modified: 或 size:),不再重复追加避免冲突。 + */ +export function composeEffectiveQuery( + baseQuery: string, + timeFilter: TimeFilter = "any", + sizeFilter: SizeFilter = "any", + extraToken = "" +): string { + const parts: string[] = []; + const trimmed = (baseQuery || "").trim(); + if (trimmed) parts.push(trimmed); + + const extra = (extraToken || "").trim(); + if (extra) parts.push(extra); + + const combined = parts.join(" "); + const hasTimeToken = /(?:^|\s)(?:dm|modified):/i.test(combined); + const hasSizeToken = /(?:^|\s)size:/i.test(combined); + + if (!hasTimeToken && timeFilter !== "any") { + if (timeFilter === "today") parts.push("dm:today"); + else if (timeFilter === "7d") parts.push("dm:7d"); + else if (timeFilter === "30d") parts.push("dm:30d"); + } + + if (!hasSizeToken && sizeFilter !== "any") { + if (sizeFilter === "gt10mb") parts.push("size:>10mb"); + else if (sizeFilter === "gt100mb") parts.push("size:>100mb"); + else if (sizeFilter === "empty") parts.push("size:0"); + } + + return parts.join(" ").trim(); +} + +/** + * 格式化列表行展示用的相对修改时间(今天 / 昨天 / MM-DD / YYYY-MM-DD);无效时间返回空串 + */ +export function formatRelativeMtime(mtimeMs: number, nowMs = Date.now()): string { + if (!Number.isFinite(mtimeMs) || mtimeMs <= 0) return ""; + const date = new Date(mtimeMs); + if (Number.isNaN(date.getTime())) return ""; + const now = new Date(nowMs); + const startToday = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime(); + const startYesterday = startToday - 24 * 3600 * 1000; + const pad = (n: number) => String(n).padStart(2, "0"); + const hm = `${pad(date.getHours())}:${pad(date.getMinutes())}`; + if (mtimeMs >= startToday) return t("timeToday", { hm }); + if (mtimeMs >= startYesterday) return t("timeYesterday", { hm }); + if (date.getFullYear() === now.getFullYear()) { + return `${pad(date.getMonth() + 1)}-${pad(date.getDate())}`; + } + return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`; +} + +/** + * 紧凑格式化已索引条目数量(中文万级 / 英文 K 级) + */ +export function formatIndexedCount(total: number): string { + if (!Number.isFinite(total) || total <= 0) return "0"; + const locale = getLocale(); + if (locale === "zh-CN") { + if (total >= 10000) { + return t("indexedCountWan", { val: (total / 10000).toFixed(1) }); + } + return total.toLocaleString("zh-CN"); + } + if (total >= 1000) { + return t("indexedCountWan", { val: (total / 1000).toFixed(1) }); + } + return total.toLocaleString("en-US"); +} + function mapRawFileToRecord(raw: unknown): FileRecord { const f = raw as RawFileEntry | null | undefined; const isDir = Boolean(f?.is_dir || f?.isDir || f?.isDirectory); @@ -210,37 +323,92 @@ export function describeSearchScope(raw: unknown, query: string): string { return t("scopeDegradedGeneric"); } +export interface FileSearchRequestOptions { + readonly offset?: number; + readonly typeFilter?: TypeFilter; + readonly kind?: KindFilter; + readonly sortBy?: SortOption; + readonly includeHidden?: boolean; + readonly pathPrefix?: string; +} + export interface FileSearchOutcome { readonly files: FileRecord[]; /** 搜索范围受限时的真实说明(来自宿主 degraded / source);完整搜索时为空字符串 */ readonly scopeNotice: string; + /** 引擎命中的总条数(用于区分当前页数量与全盘命中总数) */ + readonly totalMatches: number; + /** 当前分页偏移量 */ + readonly offset: number; + /** 是否还有更多分页结果 */ + readonly hasMore: boolean; + /** 引擎检索耗时(毫秒) */ + readonly elapsedMs?: number; } /** - * 检索文件:交给客户端的文件搜索接口(Windows 上由原生索引组件 ztools-indexer 提供,macOS 上用 Spotlight)。 - * 同时透传宿主的降级标记,界面据此提示搜索范围。拿不到任何宿主通道时抛出 NOT_IN_CLIENT_MESSAGE,不返回示例数据。 + * 检索文件:交给客户端的文件搜索接口(Win/Mac 优先走同源 C++20 原生索引组件 ztools-indexer,未就绪时自动降级)。 + * 支持将类型筛选、对象类型、隐藏文件、排序、分页偏移量与目录范围下推至引擎层执行,同时透传宿主降级标记。 */ export async function searchLocalFilesDetailed( query: string, - limit = 50, - hostOverride?: unknown + limit = 100, + hostOverride?: unknown, + options?: FileSearchRequestOptions ): Promise { const trimmed = (query || "").trim(); const realHost = isRealElectronHost(hostOverride); + const safeOffset = Math.max(0, Math.trunc(Number(options?.offset ?? 0) || 0)); + const typeFilter = options?.typeFilter && options.typeFilter !== "all" ? options.typeFilter : undefined; + const kind = options?.kind && options.kind !== "all" ? options.kind : undefined; + const sortBy = options?.sortBy; + const includeHidden = typeof options?.includeHidden === "boolean" ? options.includeHidden : undefined; + const pathPrefix = options?.pathPrefix?.trim() || undefined; - // 1. 在真实宿主环境或注入了 hostOverride 时,调用客户端的 filesearch_query(Windows 上由 C++ 原生索引组件 ztools-indexer 提供结果)。 - // 必须走插件自己的通道(callHostTransport,带本插件会话):宿主只把这样拿到的普通文件结果授权给本插件移入回收站; - // __ztoolsLauncher.searchFiles 不带插件身份,结果只能打开 / 定位 / 预览,所以只在没有宿主通道时才用。 + const extractMeta = (raw: unknown, mappedCount: number): { totalMatches: number; offset: number; hasMore: boolean; elapsedMs?: number } => { + const rec = raw && typeof raw === "object" && !Array.isArray(raw) ? raw as Record : undefined; + const rawTotal = Number(rec?.total_matches); + const totalMatches = Number.isFinite(rawTotal) && rawTotal >= mappedCount ? rawTotal : mappedCount; + const rawOffset = Number(rec?.offset); + const offset = Number.isFinite(rawOffset) && rawOffset >= 0 ? rawOffset : safeOffset; + const hasMore = typeof rec?.has_more === "boolean" ? rec.has_more : offset + mappedCount < totalMatches; + const rawElapsed = Number(rec?.elapsed_ms); + const elapsedMs = Number.isFinite(rawElapsed) && rawElapsed >= 0 ? rawElapsed : undefined; + return { totalMatches, offset, hasMore, elapsedMs }; + }; + + // 1. 在真实宿主环境或注入了 hostOverride 时,调用客户端的 filesearch_query。 if (hostOverride || realHost) { + const safeLimit = Number.isFinite(Number(limit)) ? Math.max(1, Math.trunc(Number(limit))) : 100; const errors: string[] = []; - for (const method of ["filesearch_query", "system_search_files"]) { - // 空关键词原样发送:宿主把空查询当作「最近文件」(Spotlight 最近修改 / 用户目录最近文件); - // 改成 "." 会被当成普通关键词去匹配文件名里的点号,首屏就成了无关文件 - const result = await callHostTransport(method, { query: trimmed, limit }, hostOverride); + // 携带目录范围过滤(pathPrefix)时不静默回退到不支持前缀过滤的 system_search_files 全盘搜索 + const methods = pathPrefix ? ["filesearch_query"] : ["filesearch_query", "system_search_files"]; + for (const method of methods) { + const params: Record = method === "filesearch_query" + ? { + query: trimmed, + limit: safeLimit, + ...(safeOffset > 0 ? { offset: safeOffset } : {}), + ...(typeFilter ? { typeFilter } : {}), + ...(kind ? { kind } : {}), + ...(sortBy ? { sortBy } : {}), + ...(includeHidden !== undefined ? { includeHidden } : {}), + ...(pathPrefix ? { pathPrefix } : {}) + } + : { query: trimmed, limit: Math.min(200, Math.max(1, safeLimit)) }; + const result = await callHostTransport(method, params, hostOverride); const data = result.data; const record = data && typeof data === "object" ? data as Record : undefined; const files = Array.isArray(data) ? data : Array.isArray(record?.files) ? record.files : Array.isArray(record?.items) ? record.items : null; - if (result.ok && files) return { files: files.map(mapRawFileToRecord), scopeNotice: describeSearchScope(data, trimmed) }; + if (result.ok && files) { + const mapped = files.map(mapRawFileToRecord); + const meta = extractMeta(data, mapped.length); + return { + files: mapped, + scopeNotice: describeSearchScope(data, trimmed), + ...meta + }; + } errors.push(resolveErrorMessage(result, t("errMethodInvalidResult", { method }))); } throw new Error(t("errSearchUnavailable", { detail: errors.join("; ") })); @@ -259,9 +427,14 @@ export async function searchLocalFilesDetailed( } const listed = res && typeof res === "object" ? (res as { files?: unknown }).files : undefined; const rawFiles = Array.isArray(res) ? res : Array.isArray(listed) ? listed : null; - // 返回结构不对时如实报错,不能当成「没有匹配的文件」 if (!rawFiles) throw new Error(t("errSearchInvalidResult")); - return { files: rawFiles.map(mapRawFileToRecord), scopeNotice: describeSearchScope(res, trimmed) }; + const mapped = rawFiles.map(mapRawFileToRecord); + const meta = extractMeta(res, mapped.length); + return { + files: mapped, + scopeNotice: describeSearchScope(res, trimmed), + ...meta + }; } } @@ -712,3 +885,145 @@ export async function quickLookFile(filePath: string, hostOverride?: unknown): P }; } +/** + * 查询底层文件索引统计状态(filesearch_stats) + */ +export async function getIndexerStats(hostOverride?: unknown): Promise { + if (!hostOverride && !isRealElectronHost()) return null; + const res = await callHostTransport>("filesearch_stats", {}, hostOverride); + if (!res.ok || !res.data || typeof res.data !== "object") return null; + const raw = res.data; + const totalIndexed = Number(raw.total_indexed ?? raw.totalIndexed ?? 0); + const drivesRaw = raw.indexed_drives ?? raw.indexedDrives; + const indexedDrives = Array.isArray(drivesRaw) + ? drivesRaw.map((d) => String(d)).filter(Boolean) + : []; + return { + totalIndexed: Number.isFinite(totalIndexed) && totalIndexed >= 0 ? totalIndexed : 0, + indexType: String(raw.index_type ?? raw.indexType ?? ""), + indexing: Boolean(raw.indexing), + indexedDrives, + sidecarState: typeof raw.sidecar_state === "string" + ? raw.sidecar_state + : typeof raw.sidecarState === "string" + ? raw.sidecarState + : undefined + }; +} + +/** + * 手动刷新磁盘索引:增量同步(sync)或全盘重建(rebuild) + */ +export async function refreshFileIndex( + mode: "sync" | "rebuild" = "sync", + hostOverride?: unknown +): Promise { + if (!hostOverride && !isRealElectronHost()) { + return { + ok: false, + mode, + totalIndexed: 0, + message: getNotInClientMessage() + }; + } + const res = await callHostTransport>("filesearch_refresh", { mode }, hostOverride); + if (!res.ok) { + if (res.errorCode === "METHOD_NOT_AVAILABLE" || res.errorCode === "NOT_SUPPORTED") { + return { ok: false, mode, totalIndexed: 0, message: t("indexRefreshUnsupported") }; + } + return { + ok: false, + mode, + totalIndexed: 0, + message: t("indexRefreshFailed", { reason: resolveErrorMessage(res, res.error || "UNKNOWN") }) + }; + } + const raw = (res.data && typeof res.data === "object" ? res.data : {}) as Record; + const totalIndexed = Number(raw.total_indexed ?? raw.totalIndexed ?? 0) || 0; + const addedCount = Number(raw.added_count ?? raw.addedCount ?? 0) || 0; + const removedCount = Number(raw.removed_count ?? raw.removedCount ?? 0) || 0; + const elapsedRaw = Number(raw.elapsed_ms ?? raw.elapsedMs); + const elapsedMs = Number.isFinite(elapsedRaw) && elapsedRaw >= 0 ? Math.round(elapsedRaw) : undefined; + const changed = raw.changed === true || addedCount > 0 || removedCount > 0; + const countStr = formatIndexedCount(totalIndexed); + + let message: string; + if (mode === "rebuild") { + message = t("indexRebuildSuccess", { count: countStr, ms: elapsedMs ?? 0 }); + } else if (changed) { + message = t("indexSyncChanged", { added: addedCount, removed: removedCount, count: countStr }); + } else { + message = t("indexSyncSuccess", { count: countStr }); + } + return { + ok: true, + mode, + totalIndexed, + changed, + addedCount, + removedCount, + elapsedMs, + message + }; +} + +/** + * 加载系统常用目录(桌面、下载、文档)用于左侧快捷范围导航 + */ +export async function loadCommonFolders(hostOverride?: unknown): Promise { + if (!hostOverride && !isRealElectronHost()) return []; + const ids: Array = ["desktop", "downloads", "documents"]; + const paths = await Promise.all(ids.map((id) => getRealSystemPath(id, hostOverride))); + const scopes: CommonFolderScope[] = []; + for (let i = 0; i < ids.length; i++) { + const p = paths[i]?.trim(); + if (p) scopes.push({ id: ids[i], path: p }); + } + return scopes; +} + +/** + * 探测本机真实挂载磁盘分区用于左侧盘符范围导航 + */ +export async function loadMountedVolumes(hostOverride?: unknown): Promise { + if (!hostOverride && !isRealElectronHost()) return []; + const drives = await probeRealDiskDrives(["C", "D", "E", "F", "G", "H", "I", "J"], hostOverride); + return drives.map((d) => { + const isPosix = d.drive.startsWith("/"); + return { + path: isPosix ? d.drive : `${d.drive}\\`, + label: t("navDriveDefaultLabel"), + fileSystem: "", + totalBytes: d.totalBytes, + availableBytes: d.availableBytes + }; + }); +} + +/** + * 批量移入回收站:仅处理普通文件,自动跳过文件夹并汇总成功/失败明细 + */ +export async function batchMoveToTrash( + files: FileRecord[], + hostOverride?: unknown +): Promise { + const trashedPaths: string[] = []; + const skippedDirs: string[] = []; + const failures: Array<{ path: string; name: string; reason: string }> = []; + + for (const file of files) { + if (file.isDir) { + skippedDirs.push(file.path); + continue; + } + const res = await moveToTrash(file.path, hostOverride, false); + if (res.success) { + trashedPaths.push(file.path); + } else { + failures.push({ path: file.path, name: file.name, reason: res.message }); + } + } + + return { trashedPaths, skippedDirs, failures }; +} + diff --git a/extensions/everything-file-search/src/types.js b/extensions/everything-file-search/src/types.js deleted file mode 100644 index cb0ff5c3..00000000 --- a/extensions/everything-file-search/src/types.js +++ /dev/null @@ -1 +0,0 @@ -export {}; diff --git a/extensions/everything-file-search/src/types.ts b/extensions/everything-file-search/src/types.ts index 92b93f9d..f4022e88 100644 --- a/extensions/everything-file-search/src/types.ts +++ b/extensions/everything-file-search/src/types.ts @@ -1,4 +1,5 @@ export type SortOption = + | "relevance" | "name-asc" | "name-desc" | "size-desc" @@ -19,6 +20,70 @@ export type TypeFilter = | "app" | "other"; // 不属于以上任何一类(以前误归为文档) +export type KindFilter = "all" | "file" | "directory"; + +export type TimeFilter = "any" | "today" | "7d" | "30d"; + +export type SizeFilter = "any" | "gt10mb" | "gt100mb" | "empty"; + +export interface SearchPreferences { + sortOption: SortOption; + includeHidden: boolean; + livePreview: boolean; +} + +export interface SearchBookmark { + id: string; + title: string; + query: string; + typeFilter: TypeFilter; + kindFilter: KindFilter; + timeFilter: TimeFilter; + sizeFilter: SizeFilter; + pathPrefix: string; + sortOption: SortOption; + includeHidden: boolean; + createdAt: number; +} + +export interface VolumeScope { + path: string; + label: string; + fileSystem: string; + totalBytes: number; + availableBytes: number; +} + +export interface CommonFolderScope { + id: "desktop" | "downloads" | "documents"; + path: string; +} + +export interface IndexerStats { + totalIndexed: number; + indexType: string; + indexing: boolean; + indexedDrives: string[]; + sidecarState?: string; +} + +export interface IndexRefreshResult { + ok: boolean; + mode: "sync" | "rebuild"; + totalIndexed: number; + changed?: boolean; + addedCount?: number; + removedCount?: number; + elapsedMs?: number; + message: string; +} + +export interface BatchTrashSummary { + trashedPaths: string[]; + skippedDirs: string[]; + failures: Array<{ path: string; name: string; reason: string }>; +} + export interface FileRecord { name: string; path: string; diff --git a/extensions/everything-file-search/tests/everything-file-search.advanced-query.test.mjs b/extensions/everything-file-search/tests/everything-file-search.advanced-query.test.mjs new file mode 100644 index 00000000..f3913539 --- /dev/null +++ b/extensions/everything-file-search/tests/everything-file-search.advanced-query.test.mjs @@ -0,0 +1,97 @@ +import test from 'node:test' +import assert from 'node:assert/strict' +import { createHost } from '../../shared/test-harness.mjs' +import * as mod from '../dist/index.js' + +const host = createHost() + +test.beforeEach(() => host.reset()) + +test('searchLocalFilesDetailed 透传引擎级筛选/排序/分页/目录参数并回传元数据', async () => { + const received = [] + host.ipc.filesearch_query = async (params) => { + received.push(params) + return { + files: [ + { name: 'file-search-service.ts', path: 'E:\\work\\src\\file-search-service.ts', is_dir: false, size: 4200, mtime: 1700000000000 }, + { name: 'query-engine.ts', path: 'E:\\work\\src\\query-engine.ts', is_dir: false, size: 1200, mtime: 1700000005000 } + ], + total_matches: 180, + offset: 100, + has_more: true, + elapsed_ms: 4.25 + } + } + + const outcome = await mod.searchLocalFilesDetailed('fsearch !test', 100, undefined, { + offset: 100, + typeFilter: 'code', + sortBy: 'relevance', + pathPrefix: 'E:\\work\\src' + }) + + assert.equal(received.length, 1) + assert.deepEqual(received[0], { + query: 'fsearch !test', + limit: 100, + offset: 100, + typeFilter: 'code', + sortBy: 'relevance', + pathPrefix: 'E:\\work\\src' + }) + assert.equal(outcome.files.length, 2) + assert.equal(outcome.totalMatches, 180) + assert.equal(outcome.offset, 100) + assert.equal(outcome.hasMore, true) + assert.equal(outcome.elapsedMs, 4.25) +}) + +test('sortAndFilterFiles 在 relevance 排序下完整保留底层引擎相关性顺序', () => { + const engineOrdered = [ + { name: 'z_exact.ts', path: 'C:\\z_exact.ts', isDir: false, size: 100, mtime: 1, category: 'code' }, + { name: 'a_fuzzy.ts', path: 'C:\\a_fuzzy.ts', isDir: false, size: 9000, mtime: 9, category: 'code' } + ] + const kept = mod.sortAndFilterFiles(engineOrdered, 'relevance', 'all') + assert.deepEqual(kept.map((f) => f.name), ['z_exact.ts', 'a_fuzzy.ts']) +}) + +test('searchLocalFilesDetailed 边界:offset 为 0 不传多余字段,typeFilter 为 all 不下发多余筛选', async () => { + const received = [] + host.ipc.filesearch_query = async (params) => { + received.push(params) + return { files: [], total_matches: 0, offset: 0, has_more: false, elapsed_ms: 0 } + } + const outcome = await mod.searchLocalFilesDetailed('*.pdf', 100, undefined, { + offset: 0, + typeFilter: 'all', + sortBy: 'mtime-desc' + }) + assert.deepEqual(received[0], { query: '*.pdf', limit: 100, sortBy: 'mtime-desc' }) + assert.equal(outcome.totalMatches, 0) + assert.equal(outcome.offset, 0) + assert.equal(outcome.hasMore, false) + assert.equal(outcome.elapsedMs, 0) +}) + +test('filesearch_query 失败回退 system_search_files 时钳制 limit <= 200,携带 pathPrefix 时不静默退化全盘搜索', async () => { + const fallbackCalls = [] + host.ipc.filesearch_query = async () => { + throw new Error('INDEXER_BUSY') + } + host.ipc.system_search_files = async (params) => { + fallbackCalls.push(params) + return { files: [{ name: 'a.txt', path: 'C:\\a.txt', is_dir: false, size: 10, mtime: 1700000000000 }], total_matches: 1 } + } + + const res = await mod.searchLocalFilesDetailed('report', 500) + assert.equal(fallbackCalls.length, 1) + assert.equal(fallbackCalls[0].limit, 200) + assert.equal(res.files.length, 1) + + fallbackCalls.length = 0 + await assert.rejects( + () => mod.searchLocalFilesDetailed('report', 500, undefined, { pathPrefix: 'E:\\work\\src' }), + /文件搜索不可用|filesearch_query/ + ) + assert.equal(fallbackCalls.length, 0, '携带 pathPrefix 时不得静默回退到无前缀的 system_search_files') +}) diff --git a/extensions/everything-file-search/tests/everything-file-search.degraded-scope.test.mjs b/extensions/everything-file-search/tests/everything-file-search.degraded-scope.test.mjs index 74fde378..b83bea3d 100644 --- a/extensions/everything-file-search/tests/everything-file-search.degraded-scope.test.mjs +++ b/extensions/everything-file-search/tests/everything-file-search.degraded-scope.test.mjs @@ -15,6 +15,7 @@ const waitSearch = async (ms = mod.SEARCH_DEBOUNCE_MS + 30) => { await tick(10) } const summary = (view) => view.tree().props.filterBar.summaryText +const resultItems = (view) => view.items().filter((i) => !String(i.props.id || '').startsWith('nav:')) test.beforeEach(() => host.reset()) @@ -122,7 +123,7 @@ test('界面:慢的旧请求带着降级标记晚返回时,不能覆盖新 await tick(10) assert.match(summary(view), /^当前匹配 1 个文件\/目录/) assert.ok(!summary(view).includes('全盘索引')) - assert.deepEqual(view.items().map((i) => i.props.title), ['new.txt']) + assert.deepEqual(resultItems(view).map((i) => i.props.title), ['new.txt']) view.unmount() }) diff --git a/extensions/everything-file-search/tests/everything-file-search.fixes.test.mjs b/extensions/everything-file-search/tests/everything-file-search.fixes.test.mjs index 9800a8c6..2d6c0aa6 100644 --- a/extensions/everything-file-search/tests/everything-file-search.fixes.test.mjs +++ b/extensions/everything-file-search/tests/everything-file-search.fixes.test.mjs @@ -75,6 +75,8 @@ async function mountList(host) { return view } +const resultItems = (view) => view.items().filter((i) => !String(i.props.id || '').startsWith('nav:')) + // ---------------- -1 打开 / 定位 ---------------- test('-1 打开文件:宿主 filesearch_open 返回 success:false 时提示失败并带上真实原因,不再调 shell_open_path', async () => { @@ -388,7 +390,7 @@ test('-13 慢的旧请求晚返回时不覆盖新关键词的结果', async () = await waitSearch() // 防抖结束,d 的请求已发出(400ms 才返回) await view.search('dtv') await waitSearch(600) // d 与 dtv 都已返回,d 最后返回 - assert.deepEqual(view.items().map((i) => i.props.title), ['hit-dtv.txt']) + assert.deepEqual(resultItems(view).map((i) => i.props.title), ['hit-dtv.txt']) assert.equal(view.tree().props.isLoading, false) assert.ok(queriesSent(host).includes('d') && queriesSent(host).includes('dtv')) view.unmount() @@ -407,7 +409,7 @@ test('-13 连续快速输入只在停顿后检索最后一个关键词;最新 assert.equal(view.tree().props.isLoading, true) await waitSearch(250) assert.deepEqual(queriesSent(host), ['auth.j']) - assert.deepEqual(view.items().map((i) => i.props.title), ['hit-auth.j.txt']) + assert.deepEqual(resultItems(view).map((i) => i.props.title), ['hit-auth.j.txt']) host.ipc.filesearch_query = async () => { throw new Error('indexer crashed') @@ -490,13 +492,13 @@ test('不在客户端里运行:列表为空并提示「需要在 ZTools 客户 try { const view = await mount(Command, host) await waitSearch(20) - const items = view.items() + const items = resultItems(view) assert.deepEqual(items.map((i) => i.props.id), ['search-error']) assert.equal(items[0].props.title, '需要在 ZTools 客户端中使用') assert.match(view.tree().props.filterBar.summaryText, /需要在 ZTools 客户端中使用/) await view.search('md') await waitSearch() - assert.deepEqual(view.items().map((i) => i.props.id), ['search-error']) + assert.deepEqual(resultItems(view).map((i) => i.props.id), ['search-error']) view.unmount() } finally { globalThis.__ztoolsElectron = saved @@ -531,7 +533,7 @@ test('下拉筛选与动作分组标题不带英文括注', async () => { } walk(view.tree().props.searchBarAccessory) walk(view.item(notesTxt).props.actions) - assert.ok(titles.includes('全部文件与文件夹'), titles.join('|')) + assert.ok(titles.includes('相关性优先'), titles.join('|')) assert.ok(titles.includes('快捷复制'), titles.join('|')) for (const title of titles) assert.doesNotMatch(title, /[((](All|Documents|Images|Videos|Audio|Archives|Code|Folders|Clipboard|Operations)[))]/, title) } finally { view.unmount() } diff --git a/extensions/everything-file-search/tests/everything-file-search.path-grants.test.mjs b/extensions/everything-file-search/tests/everything-file-search.path-grants.test.mjs index d632841f..2bb867a2 100644 --- a/extensions/everything-file-search/tests/everything-file-search.path-grants.test.mjs +++ b/extensions/everything-file-search/tests/everything-file-search.path-grants.test.mjs @@ -106,7 +106,8 @@ test.afterEach(() => { test('检索走插件自己的 filesearch_query(带插件身份),有宿主通道时不调用 __ztoolsLauncher.searchFiles', async () => { const { calls } = installGrantHost() const view = await mountList() - assert.deepEqual(view.items().map((i) => i.props.id).sort(), [folder, photoPng, reportTxt].sort()) + const resultIds = view.items().filter((i) => !String(i.props.id || '').startsWith('nav:')).map((i) => i.props.id).sort() + assert.deepEqual(resultIds, [folder, photoPng, reportTxt].sort()) assert.equal(calls.launcher, 0, '不能走不带插件身份的悬浮条检索') assert.ok(host.ipcCalls.some(([m]) => m === 'filesearch_query')) await view.search('report') diff --git a/extensions/everything-file-search/tests/everything-file-search.v2-features.test.mjs b/extensions/everything-file-search/tests/everything-file-search.v2-features.test.mjs new file mode 100644 index 00000000..c85e580d --- /dev/null +++ b/extensions/everything-file-search/tests/everything-file-search.v2-features.test.mjs @@ -0,0 +1,195 @@ +import test from 'node:test' +import assert from 'node:assert/strict' +import { createHost, mount, tick } from '../../shared/test-harness.mjs' +import * as mod from '../dist/index.js' + +const Command = mod.default +const host = createHost() + +const waitSearch = async (ms = mod.SEARCH_DEBOUNCE_MS + 30) => { + await new Promise((r) => setTimeout(r, ms)) + await tick(10) +} + +const resultItems = (view) => view.items().filter((i) => !String(i.props.id || '').startsWith('nav:')) + +test.beforeEach(() => host.reset()) + +test('顶栏排序下拉切换排序方式并持久化到 LocalStorage,下次打开自动恢复', async () => { + const received = [] + host.ipc.filesearch_query = async (params) => { + received.push(params) + return { + files: [ + { name: 'small.txt', path: 'C:\\docs\\small.txt', is_dir: false, size: 100, mtime: 1700000000 }, + { name: 'big.txt', path: 'C:\\docs\\big.txt', is_dir: false, size: 5000, mtime: 1700000500 } + ], + total_matches: 2, + elapsed_ms: 1.5 + } + } + + const view = await mount(Command, host) + await waitSearch(20) + assert.equal(view.tree().props.searchBarAccessory.props.value, 'sort:relevance') + + await view.dropdown('sort:size-desc') + await waitSearch(20) + assert.equal(received[received.length - 1].sortBy, 'size-desc') + assert.deepEqual(resultItems(view).map((i) => i.props.title), ['big.txt', 'small.txt']) + view.unmount() + + // 重新挂载,验证排序偏好从 LocalStorage 恢复 + received.length = 0 + const view2 = await mount(Command, host) + await waitSearch(20) + assert.equal(view2.tree().props.searchBarAccessory.props.value, 'sort:size-desc') + assert.equal(received[0].sortBy, 'size-desc') + view2.unmount() +}) + +test('动作面板支持反转排序方向,列表行展示修改时间与大小', async () => { + const now = Date.now() + host.ipc.filesearch_query = async () => ({ + files: [ + { name: 'alpha.ts', path: 'C:\\code\\alpha.ts', is_dir: false, size: 2048, mtime: now }, + { name: 'beta.ts', path: 'C:\\code\\beta.ts', is_dir: false, size: 512, mtime: now - 86400_000 } + ] + }) + const view = await mount(Command, host) + await waitSearch(20) + + const row = view.item('C:\\code\\alpha.ts') + assert.equal(row.props.accessories.length, 2) + assert.match(row.props.accessories[0].text, /^今天 /) + assert.equal(row.props.accessories[1].text, '2.0 KB') + + await view.run(row, '反转排序方向') + await waitSearch(20) + assert.equal(view.tree().props.searchBarAccessory.props.value, 'sort:mtime-desc') + await view.run(view.item('C:\\code\\alpha.ts'), '反转排序方向') + await waitSearch(20) + assert.equal(view.tree().props.searchBarAccessory.props.value, 'sort:mtime-asc') + view.unmount() +}) + +test('左侧精细筛选与快捷视图组合生效(kind / time / size / includeHidden / 盘符)', async () => { + const received = [] + host.ipc.filesearch_query = async (params) => { + received.push(params) + return { files: [{ name: 'huge.zip', path: 'D:\\huge.zip', is_dir: false, size: 200 * 1024 * 1024, mtime: Date.now() }] } + } + host.ipc.system_get_disk_usage = async ({ drive }) => { + if (drive === 'D:\\') return { total: 500e9, used: 100e9, available: 400e9, percent: 20 } + return { success: false, error: 'not found' } + } + host.ipc.system_get_path = async ({ name }) => (name === 'desktop' ? 'C:\\Users\\demo\\Desktop' : '') + + const view = await mount(Command, host) + await waitSearch(20) + + // 点击左侧「大文件 (>50 MB)」快捷视图 + await view.item('nav:preset:large').props.onSelect() + await waitSearch(20) + const last1 = received[received.length - 1] + assert.equal(last1.kind, 'file') + assert.equal(last1.sortBy, 'size-desc') + assert.match(last1.query, /size:>10mb/) + + // 切换隐藏文件开关 + await view.item('nav:filter:hidden').props.onSelect() + await waitSearch(20) + assert.equal(received[received.length - 1].includeHidden, true) + + // 点击盘符 D: + await view.item('nav:vol:D:\\').props.onSelect() + await waitSearch(20) + assert.equal(received[received.length - 1].pathPrefix, 'D:\\') + view.unmount() +}) + +test('多选勾选与批量复制路径、批量移入回收站(自动跳过文件夹)', async () => { + const trashed = [] + host.ipc.filesearch_query = async () => ({ + files: [ + { name: 'a.txt', path: 'C:\\tmp\\a.txt', is_dir: false, size: 100, mtime: 1700000000 }, + { name: 'b.txt', path: 'C:\\tmp\\b.txt', is_dir: false, size: 200, mtime: 1700000000 }, + { name: 'dir', path: 'C:\\tmp\\dir', is_dir: true, size: 0, mtime: 1700000000 } + ] + }) + host.ipc.shell_trash_item = async ({ fullPath }) => { + trashed.push(fullPath) + return { success: true } + } + + const view = await mount(Command, host) + await waitSearch(20) + + // 勾选两个文件和一个目录 + view.item('C:\\tmp\\a.txt').props.onCheckChange(true) + view.item('C:\\tmp\\b.txt').props.onCheckChange(true) + view.item('C:\\tmp\\dir').props.onCheckChange(true) + await tick(5) + + assert.match(view.tree().props.subList.subtitle, /已勾选 3 项/) + + await view.run(view.item('C:\\tmp\\a.txt'), '批量复制文件路径 (3 项)') + assert.equal(host.clipboard.text, 'C:\\tmp\\a.txt\nC:\\tmp\\b.txt\nC:\\tmp\\dir') + + host.setConfirm(true) + await view.run(view.item('C:\\tmp\\a.txt'), '批量移入回收站 (2 个文件)') + assert.deepEqual(trashed, ['C:\\tmp\\a.txt', 'C:\\tmp\\b.txt']) + assert.deepEqual(resultItems(view).map((i) => i.props.id), ['C:\\tmp\\dir']) + view.unmount() +}) + +test('搜索书签保存与回放、实时侧边预览开关与索引刷新', async () => { + host.ipc.filesearch_query = async ({ query }) => ({ + files: [{ name: `${query || 'all'}.md`, path: `C:\\notes\\${query || 'all'}.md`, is_dir: false, size: 64, mtime: Date.now() }] + }) + host.ipc.filesearch_stats = async () => ({ + total_indexed: 125000, + index_type: 'ntfs_mft', + indexing: false, + indexed_drives: ['C:', 'D:'] + }) + host.ipc.filesearch_refresh = async ({ mode }) => ({ + ok: true, + mode, + total_indexed: 125100, + changed: true, + added_count: 100, + removed_count: 0, + elapsed_ms: 42 + }) + host.ipc.filesystem_read_file_chunk = async () => ({ + success: true, + content: Buffer.from('# Hello\n').toString('base64'), + totalSize: 8 + }) + + const view = await mount(Command, host) + await waitSearch(20) + assert.match(view.tree().props.filterBar.summaryText, /已索引 12\.5 万 项/) + + // 搜索并保存书签 + await view.search('todo') + await waitSearch() + await view.run(view.item('C:\\notes\\todo.md'), '保存当前搜索为书签') + assert.ok(view.items().some((i) => String(i.props.id).startsWith('nav:bm:'))) + + // 开启实时侧边预览 + const previewBtn = view.tree().props.filterBar.actions.find((a) => a.id === 'toggle-live-preview') + assert.ok(previewBtn) + previewBtn.onAction() + await tick(20) + assert.equal(view.tree().props.isShowingDetail, true) + + // 刷新索引 + const refreshBtn = view.tree().props.filterBar.actions.find((a) => a.id === 'refresh-index') + assert.ok(refreshBtn) + await refreshBtn.onAction() + await waitSearch(20) + assert.match(host.lastToast().title, /已同步卷变化(\+100\/-0)/) + view.unmount() +}) diff --git a/extensions/exchange-rate/plugin.json b/extensions/exchange-rate/plugin.json index 3f22fa3a..3ef327cc 100644 --- a/extensions/exchange-rate/plugin.json +++ b/extensions/exchange-rate/plugin.json @@ -2,6 +2,7 @@ "id": "exchange-rate", "name": "汇率计算", "version": "2.0.0", + "minAppVersion": "1.1.8.0", "revoked": true, "revokedReason": "已合并至内置「计算器」插件(支持多币种汇率看板与算式内联换算),请改用计算器", "description": "实时汇率查询与多币种换算,支持 15 种主流法币以及黄金(盎司)、比特币,汇率本地缓存 30 分钟并显示更新时间", diff --git a/extensions/file-compare/README.en.md b/extensions/file-compare/README.en.md new file mode 100644 index 00000000..5b582f98 --- /dev/null +++ b/extensions/file-compare/README.en.md @@ -0,0 +1,23 @@ +# Text Diff + +Compare two blocks of text, code snippets, or configuration files line by line, list every change, and copy a unified diff report. + +## Usage + +- **Command**: Text Diff (keywords such as `diff`, `compare`, `text diff`). +- **Input**: Paste into the left (Original) and right (Modified) editors, or load each side from the clipboard or a file (UTF-8 text, up to 4 MB per file). If only one side is loaded, the plugin prompts you to provide the other side. +- **Diff View**: Once both sides have content, differences are listed item by item with added/deleted lines shown in the right preview pane and counts of deletions, additions, and hunks in the title. +- **Shortcuts**: + - On start: select the first row and press `Enter` to open the editor; press `⌘/Ctrl+Enter` inside the editor to run the comparison. + - When differences exist: `Enter` copies the full diff report, `⌘/Ctrl+Enter` copies only the selected hunk, and `⌘/Ctrl+K` opens the action panel (swap sides, ignore whitespace differences, load from clipboard or file, clear, etc.). +- **Ignore Whitespace**: Collapses consecutive whitespace into a single space and trims leading/trailing whitespace before comparing. +- **Limits**: Supports up to 20,000 lines per side. When changes are too extensive, an approximate diff is shown and noted in the title. + +## Platforms & Requirements + +- Supported: Windows, macOS +- Built into the client; no separate installation required. + +## Network & Data + +- Offline only; all data stays on your device. diff --git a/extensions/file-compare/plugin.json b/extensions/file-compare/plugin.json index 687f12ce..107c4804 100644 --- a/extensions/file-compare/plugin.json +++ b/extensions/file-compare/plugin.json @@ -1,7 +1,8 @@ { "id": "file-compare", "name": "文本对比", - "version": "2.0.13", + "version": "2.0.14", + "minAppVersion": "1.1.8.0", "description": "逐行对比两段文本、代码或配置文件,逐处列出增删的行,支持忽略空白与复制 unified diff 差异报告", "author": "ZTools Team", "entry": "dist/index.js", @@ -31,7 +32,14 @@ "对比", "比较", "compare", - "差异" + "差异", + "文本对比", + "文件对比", + "找不同", + "比对文本", + "对比差异", + "代码对比", + "文档对比" ], "category": [ "开发工具" @@ -47,7 +55,12 @@ "compare", "text diff", "patch", - "unified diff" + "unified diff", + "file compare", + "compare text", + "differences", + "compare files", + "merge" ], "screenshots": [ { diff --git a/extensions/file-compare/src/i18n.ts b/extensions/file-compare/src/i18n.ts index 9770cd31..ee3d9621 100644 --- a/extensions/file-compare/src/i18n.ts +++ b/extensions/file-compare/src/i18n.ts @@ -31,7 +31,7 @@ const MESSAGES = { readClipboardFailed: '读取剪贴板失败', pickLeftFileTitle: '选择左侧(原文)文件', pickRightFileTitle: '选择右侧(新文)文件', - actionEditTexts: '编辑两段文本…', + actionEditTexts: '编辑对比文本', actionPasteLeft: '剪贴板内容设为左侧', actionPasteRight: '剪贴板内容设为右侧', actionPickLeft: '选择文件作为左侧…', @@ -69,9 +69,16 @@ const MESSAGES = { actionCopyHunk: '复制这一处差异', copiedHunkToast: '已复制这一处差异', navTitle: '文本对比', - searchPlaceholderResult: '按回车复制差异报告,{key} 查看更多操作', - searchPlaceholderIdle: '按回车开始,{key} 查看更多操作', - panelGlobalActions: '全局操作' + searchPlaceholderResult: '按回车复制差异报告,或点击行尾 ⋯ 查看更多操作', + searchPlaceholderIdle: '选择下方对比方式,或点击右上角按钮开始…', + panelGlobalActions: '全局操作', + barEditTexts: '编辑对比文本', + barPickFile: '选择文件', + barPickRight: '选择右侧文件', + barSummaryIdle: '支持粘贴文本、拖入文件或点击右侧按钮开始对比', + barSummaryOneSide: '已载入{side}:{name},请补上另一侧', + barSummaryIdentical: '{left} ↔ {right} · 内容一致', + barSummaryDiff: '{left} ↔ {right} · 删除 {removed} 行,新增 {added} 行 · {hunks} 处差异' }, 'en-US': { sideLeft: 'Left', @@ -141,9 +148,16 @@ const MESSAGES = { actionCopyHunk: 'Copy This Hunk', copiedHunkToast: 'Copied hunk', navTitle: 'Text Diff', - searchPlaceholderResult: 'Press Enter to copy diff report, {key} for more actions', - searchPlaceholderIdle: 'Press Enter to start, {key} for more actions', - panelGlobalActions: 'Global Actions' + searchPlaceholderResult: 'Press Enter to copy diff report, or click ⋯ for more actions', + searchPlaceholderIdle: 'Pick an option below or use the top bar to start comparing...', + panelGlobalActions: 'Global Actions', + barEditTexts: 'Edit Texts', + barPickFile: 'Select File', + barPickRight: 'Select Right File', + barSummaryIdle: 'Paste text, drop files, or use the buttons to start comparing', + barSummaryOneSide: 'Loaded {side}: {name}. Fill the other side to compare', + barSummaryIdentical: '{left} ↔ {right} · Identical', + barSummaryDiff: '{left} ↔ {right} · -{removed} / +{added} lines · {hunks} [[hunks:hunk|hunks]]' } } as const diff --git a/extensions/file-compare/src/index.ts b/extensions/file-compare/src/index.ts index 44760e2c..9ddcdbfc 100644 --- a/extensions/file-compare/src/index.ts +++ b/extensions/file-compare/src/index.ts @@ -80,7 +80,7 @@ export function EditTextsForm({ left, right, onSave }: { left: Side; right: Side ]) }, [ - Form.TextArea({ id: 'left', title: t('sideLeftFull'), placeholder: t('leftPlaceholder'), value: a, onChange: (v: string) => setA(v) }), + Form.TextArea({ id: 'left', title: t('sideLeftFull'), placeholder: t('leftPlaceholder'), value: a, autoFocus: true, onChange: (v: string) => setA(v) }), Form.TextArea({ id: 'right', title: t('sideRightFull'), placeholder: t('rightPlaceholder'), value: b, onChange: (v: string) => setB(v) }) ] ) @@ -337,6 +337,18 @@ export function FileCompareCommand() { sections = [] } + const barSummaryText = error + ? error + : hasLeft !== hasRight + ? t('barSummaryOneSide', { side: hasLeft ? t('sideLeft') : t('sideRight'), name: hasLeft ? leftName : rightName }) + : result?.identical + ? t('barSummaryIdentical', { left: leftName, right: rightName }) + : result + ? t('barSummaryDiff', { left: leftName, right: rightName, removed: result.removed, added: result.added, hunks: result.hunks.length }) + : t('barSummaryIdle') + + const pickSideForBar: 'left' | 'right' = hasLeft && !hasRight ? 'right' : 'left' + return List( { ...fileInputProps, @@ -345,6 +357,23 @@ export function FileCompareCommand() { searchBarPlaceholder: result && result.hunks.length > 0 ? t('searchPlaceholderResult', { key: actionPanelKey() }) : t('searchPlaceholderIdle', { key: actionPanelKey() }), + filterBar: { + summaryText: barSummaryText, + actions: [ + { + id: 'edit-texts', + title: t('barEditTexts'), + style: ready ? 'secondary' : 'primary', + onAction: openEditor + }, + { + id: 'pick-file', + title: pickSideForBar === 'right' ? t('barPickRight') : t('barPickFile'), + style: 'secondary', + onAction: () => void pickFile(pickSideForBar) + } + ] + }, actions: ActionPanel({ title: t('panelGlobalActions') }, [...reportActions, ...sourceActions]) }, sections diff --git a/extensions/file-compare/tests/fixes.test.mjs b/extensions/file-compare/tests/fixes.test.mjs index e4397511..25ec76f8 100644 --- a/extensions/file-compare/tests/fixes.test.mjs +++ b/extensions/file-compare/tests/fixes.test.mjs @@ -1,7 +1,7 @@ import test from 'node:test' import assert from 'node:assert/strict' import { createHost, mount, mountPushed, tick } from '../../shared/test-harness.mjs' -import FileCompareCommand from '../dist/index.js' +import FileCompareCommand, { actionPanelKey } from '../dist/index.js' import { diffText, MAX_DIFF_LINES } from '../dist/logic.js' const host = createHost() @@ -190,7 +190,7 @@ test('[边界] 交换后变成只缺左侧;表单空侧视为已提交;单 await view.run(view.item('need-other'), '清空') assert.equal(view.items()[0].props.id, 'start-edit') - await view.run(view.item('start-edit'), '编辑两段文本…') + await view.run(view.item('start-edit'), '编辑对比文本') const form = await mountPushed(host) await form.fill('left', 'only left') await form.run(null, '开始对比') @@ -212,7 +212,7 @@ test('编辑表单只有「开始对比」一个动作(宿主把它映射到 const view = await mount(FileCompareCommand) fs.pickNext('/left.txt') await view.run(view.item('start-file'), '选择文件作为左侧…') - await view.run(view.item('need-other'), '编辑两段文本…') + await view.run(view.item('need-other'), '编辑对比文本') const form = await mountPushed(host) assert.deepEqual(form.actions().map((a) => a.props.title), ['开始对比']) assert.equal(form.field('left').props.value, 'a\nb\n') @@ -222,28 +222,45 @@ test('编辑表单只有「开始对比」一个动作(宿主把它映射到 assert.equal(host.pushed.length, 0, '提交后返回列表') // 左侧未改动:保留文件名;右侧来自表单 assert.match(view.text(), /left\.txt ↔ 右侧 · 删除 1 行,新增 1 行/) - await view.run(view.item('hunk-0'), '编辑两段文本…') + await view.run(view.item('hunk-0'), '编辑对比文本') const again = await mountPushed(host) assert.equal(again.field('left').props.value, 'a\nb\n') assert.equal(again.field('right').props.value, 'a\nc\n') }) -test('搜索框占位里的动作面板快捷键按平台只写一种:macOS 为 ⌘K,Windows 为 Ctrl+K', async () => { +test('搜索框占位在首屏与结果态展示新版引导文案;actionPanelKey 按平台返回单种快捷键并在 navigator 不可用时兜底', async () => { const original = Object.getOwnPropertyDescriptor(globalThis, 'navigator') try { - for (const [platform, expected, absent] of [['MacIntel', '⌘K', /Ctrl/], ['Win32', 'Ctrl+K', /⌘/]]) { + for (const [platform, expectedKey, absentKey] of [['MacIntel', '⌘K', /Ctrl/], ['Win32', 'Ctrl+K', /⌘/]]) { Object.defineProperty(globalThis, 'navigator', { value: { platform, userAgent: '' }, configurable: true }) + const key = actionPanelKey() + assert.equal(key, expectedKey) + assert.doesNotMatch(key, absentKey) const view = await mount(FileCompareCommand) try { - const placeholder = view.tree().props.searchBarPlaceholder - assert.ok(placeholder.includes(expected), placeholder) - assert.doesNotMatch(placeholder, absent) + const idlePlaceholder = view.tree().props.searchBarPlaceholder + assert.equal(idlePlaceholder, '选择下方对比方式,或点击右上角按钮开始…') + assert.doesNotMatch(idlePlaceholder, /⌘K|Ctrl\+K/) } finally { view.unmount() } } - // navigator 不可用时按 Windows 写法兜底,不抛错 + // navigator 不可用时按 Windows 写法兜底,挂载与结果态占位均不抛错 Object.defineProperty(globalThis, 'navigator', { value: undefined, configurable: true }) + assert.equal(actionPanelKey(), 'Ctrl+K') const view = await mount(FileCompareCommand) - try { assert.match(view.tree().props.searchBarPlaceholder, /Ctrl\+K/) } finally { view.unmount() } + try { + assert.equal(view.tree().props.searchBarPlaceholder, '选择下方对比方式,或点击右上角按钮开始…') + await view.run(view.item('start-edit'), '编辑对比文本') + const form = await mountPushed(host) + try { + await form.fill('left', 'a\nb') + await form.fill('right', 'a\nc') + await form.run(null, '开始对比') + } finally { form.unmount() } + await tick() + const resultPlaceholder = view.tree().props.searchBarPlaceholder + assert.equal(resultPlaceholder, '按回车复制差异报告,或点击行尾 ⋯ 查看更多操作') + assert.doesNotMatch(resultPlaceholder, /⌘K|Ctrl\+K/) + } finally { view.unmount() } } finally { if (original) Object.defineProperty(globalThis, 'navigator', original) } diff --git a/extensions/file-compare/tests/index.test.mjs b/extensions/file-compare/tests/index.test.mjs index 5c4938f3..ef0180f9 100644 --- a/extensions/file-compare/tests/index.test.mjs +++ b/extensions/file-compare/tests/index.test.mjs @@ -70,7 +70,7 @@ test('[边界] 换行符差异、忽略空白、空文本、超大文本', () => test('界面:空状态无示例数据;填写两段文本后列出差异并可复制报告', async () => { const view = await mount(FileCompareCommand) assert.equal(view.items()[0].props.id, 'start-edit') - await view.run(view.item('start-edit'), '编辑两段文本…') + await view.run(view.item('start-edit'), '编辑对比文本') const form = await mountPushed(host) await form.fill('left', 'a\nb\nc') await form.fill('right', 'a\nB\nc') diff --git a/extensions/file-compare/tests/patch-roundtrip.test.mjs b/extensions/file-compare/tests/patch-roundtrip.test.mjs index fa722c52..35695f32 100644 --- a/extensions/file-compare/tests/patch-roundtrip.test.mjs +++ b/extensions/file-compare/tests/patch-roundtrip.test.mjs @@ -33,7 +33,7 @@ test('报告原样交给 git apply:空文件、末尾换行增删、无换行 test('真实复制动作保留结尾换行与 EOF 标记,不由测试补写报告内容', async () => { const host = createHost(), view = await mount(Command) try { - await view.run(null, '编辑两段文本…') + await view.run(null, '编辑对比文本') const form = await mountPushed(host) try { await form.fill('left', 'same'); await form.fill('right', 'same\n') diff --git a/extensions/file-compare/tests/popout.test.mjs b/extensions/file-compare/tests/popout.test.mjs index 45147754..d60b8071 100644 --- a/extensions/file-compare/tests/popout.test.mjs +++ b/extensions/file-compare/tests/popout.test.mjs @@ -52,7 +52,7 @@ const sectionTitle = (win) => win.all('List.Section')[0].props.title test('弹出闭环:两侧文本与忽略空白带到新窗口,差异与报告和旧窗口一致', async () => { const old = await openWindow(FileCompareCommand) - await old.act('编辑两段文本…') + await old.act('编辑对比文本') const form = await mountPushed(host) await form.fill('left', 'a\nb c\nd') await form.fill('right', 'a\nb c\nD') diff --git a/extensions/file-compare/tests/review-regressions.test.mjs b/extensions/file-compare/tests/review-regressions.test.mjs index 09204dbe..671d9adc 100644 --- a/extensions/file-compare/tests/review-regressions.test.mjs +++ b/extensions/file-compare/tests/review-regressions.test.mjs @@ -9,7 +9,7 @@ test('提交空文本仍代表已载入:整篇新增、删除和两侧为空', for (const [left, right, expected] of [['原文', '', '-原文'], ['', '新文', '+新文'], ['', '', null]]) { const view = await mount(Command) try { - await view.run(null, '编辑两段文本…') + await view.run(null, '编辑对比文本') const form = await mountPushed(host) try { await form.fill('left', left); await form.fill('right', right); await form.run(null, '开始对比') } finally { form.unmount() } @@ -74,11 +74,11 @@ test('[异常] 读取剪贴板或复制失败时提示失败,不显示成功 finally { Object.defineProperty(host.clipboard, 'text', { configurable: true, writable: true, enumerable: true, value: '' }) } assert.equal(host.lastToast().style, 'FAILURE'); assert.match(host.lastToast().title, /读取剪贴板失败/) assert.ok(view.item('start-edit'), '失败后仍停留在开始页') - await view.run(view.item('start-edit'), '编辑两段文本…') + await view.run(view.item('start-edit'), '编辑对比文本') const form = await mountPushed(host); await form.fill('left', 'a\r\nb\r\n'); await form.fill('right', 'a\nb\n'); await form.run(null, '开始对比'); form.unmount(); await tick() assert.ok(view.item('hunk-0')); assert.doesNotMatch(view.text(), /完全相同/) // 复制失败(宿主拒绝空内容)时不提示「已复制」 - await view.run(view.item('hunk-0'), '编辑两段文本…') + await view.run(view.item('hunk-0'), '编辑对比文本') const again = await mountPushed(host); await again.fill('left', 'x'); await again.fill('right', 'y'); await again.run(null, '开始对比'); again.unmount(); await tick() const count = host.toasts.length await view.run(view.item('hunk-0'), '复制差异报告'); assert.equal(host.lastToast().style, 'SUCCESS'); assert.equal(host.clipboard.text.split('\n')[0], '--- 左侧') diff --git a/extensions/file-inspector/README.en.md b/extensions/file-inspector/README.en.md new file mode 100644 index 00000000..42854b55 --- /dev/null +++ b/extensions/file-inspector/README.en.md @@ -0,0 +1,21 @@ +# File Inspector & Transcoder + +Detect the real format of files from their magic bytes and inspect text encoding and line endings. Save text files as UTF-8 with BOM (fixing garbled CSVs in Excel) or correct mismatched file extensions. + +## Usage + +- **Commands**: File Inspector (`file inspector`, `check file`, `file encoding`), Fix CSV (`fix csv`, `csv bom`, `utf8 bom`), and Fix Extension (`fix extension`, `magic bytes`, `detect format`). All three open the same workbench; start by clicking "Select Local File". +- **Magic Byte Detection**: Identifies PNG, JPEG, WebP, AVIF, GIF, PDF, ZIP (`.docx`, `.xlsx`, `.pptx`, `.odt`, `.epub`, `.jar`, `.apk`, and macOS `.pages`, `.numbers`, `.key` ZIP-based formats are treated as matching; Illustrator `.ai` is treated as matching PDF), and HTML-tagged text (flagged as mismatched only when the extension implies a binary format such as image, PDF, or archive—not for `.php`, `.htm`, etc.). Displays the first 16 bytes in hex and the real MIME type, and warns when the extension does not match. +- **Text Encoding & Line Endings**: Detects UTF-8 / UTF-16 when a BOM is present. Without a BOM, valid UTF-8 is detected as UTF-8 and all other text is treated as GBK / GB18030, with the status bar indicating the detection basis. UTF-16 without a BOM is treated as binary. You can also manually select UTF-8, GBK / GB18030, Big5, or UTF-16LE. Detects CRLF, LF, CR, or mixed line endings. The list shows the first 100 decoded lines (searchable); binary files show a single row with header hex bytes. +- **Shortcuts**: On a preview row, `Enter` runs the primary action ("Save as UTF-8 with BOM" for text files, or "Fix Extension" for mismatched binary files), `⌘/Ctrl+Enter` runs the secondary action, and `⌘/Ctrl+K` opens the action panel (Fix Extension, Copy Line). +- **Save as UTF-8 with BOM**: Normalizes line endings to the selected target (CRLF or LF) and saves a new file via the save dialog, up to 16 MiB. Saving is blocked if decoding under the source encoding fails. Binary files cannot be transcoded. +- **Fix Extension**: Requires selecting the file's parent folder in the prompt to authorize renaming; refuses to overwrite if the target filename already exists. + +## Platforms & Requirements + +- Supported: Windows, macOS +- Requires client version 1.1.8.3 or later. + +## Network & Data + +- Offline only; all data stays on your device. diff --git a/extensions/file-inspector/plugin.json b/extensions/file-inspector/plugin.json index 12e09eea..83eabf54 100644 --- a/extensions/file-inspector/plugin.json +++ b/extensions/file-inspector/plugin.json @@ -1,7 +1,8 @@ { "id": "file-inspector", "name": "文件透视与转码", - "version": "1.0.10", + "version": "1.0.11", + "minAppVersion": "1.1.8.0", "description": "按文件头识别真实格式并修正错误的扩展名;检查文本文件的编码与换行符,可另存为 UTF-8-BOM,解决 Excel 打开 CSV 乱码", "author": "ZTools Team", "category": [ @@ -75,7 +76,12 @@ "bom", "csv", "extension", - "magic bytes" + "magic bytes", + "gbk", + "fix garbled", + "file type", + "mime", + "transcode" ], "features": { "file-inspector-workbench": { @@ -120,5 +126,17 @@ { "path": "screenshots/02-action-panel.png" } + ], + "keywords": [ + "文件透视", + "文件转码", + "编码转换", + "乱码修复", + "gbk转utf8", + "utf8", + "真实格式", + "改后缀", + "bom", + "文件乱码" ] } diff --git a/extensions/file-inspector/src/index.tsx b/extensions/file-inspector/src/index.tsx index cf99d4dc..a4213bd7 100644 --- a/extensions/file-inspector/src/index.tsx +++ b/extensions/file-inspector/src/index.tsx @@ -219,10 +219,48 @@ export function FileInspectorCommand(props: FileInspectorCommandProps = {}) { { id: 'pick-file', title: t('btnSelectFile'), + style: 'secondary', onAction: () => { void handlePickFile() } - } + }, + ...(fileInfo + ? mode === 'file-fix-extension' + ? fileInfo.extensionMismatch + ? [{ + id: 'fix-ext', + title: t('actionFixExt', { ext: fileInfo.realExtension }), + style: 'primary', + disabled: isLoading, + onAction: () => { void handleFixExtension() } + }] + : fileInfo.isText + ? [{ + id: 'save-utf8-bom', + title: t('actionSaveUtf8Bom'), + style: 'primary', + disabled: isLoading, + onAction: () => { void handleConvertToUtf8Bom() } + }] + : [] + : fileInfo.isText + ? [{ + id: 'save-utf8-bom', + title: t('actionSaveUtf8Bom'), + style: 'primary', + disabled: isLoading, + onAction: () => { void handleConvertToUtf8Bom() } + }] + : fileInfo.extensionMismatch + ? [{ + id: 'fix-ext', + title: t('actionFixExt', { ext: fileInfo.realExtension }), + style: 'primary', + disabled: isLoading, + onAction: () => { void handleFixExtension() } + }] + : [] + : []) ] }} workbenchPanel={{ diff --git a/extensions/file-inspector/src/native-ipc.ts b/extensions/file-inspector/src/native-ipc.ts index 51576b99..13643277 100644 --- a/extensions/file-inspector/src/native-ipc.ts +++ b/extensions/file-inspector/src/native-ipc.ts @@ -174,11 +174,13 @@ function normalizeMethodResult(method: string, payload: DynamicBridge): DynamicB if (method === 'system_get_battery_status') { // 宿主约定 percent 超出 0-100(如 255)表示无电池或电量未知,不能改写成 100% + // 若宿主明确给出 hasBattery 布尔值,必须原样保留,仅在缺失时按合法电量推算 const rawPct = payload.percent - const hasBattery = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const validPct = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const hasBattery = typeof payload.hasBattery === 'boolean' ? payload.hasBattery : validPct return { ...payload, - percent: hasBattery ? rawPct : null, + percent: validPct ? rawPct : null, hasBattery } } @@ -489,6 +491,8 @@ export interface RealDirectoryScanResult extends Iterable approximate?: boolean /** 宿主实际遍历的条目数 */ visitedEntries?: number + /** 目录本身不存在(ENOENT) */ + missing?: boolean /** 读取失败的真实原因;已有文件仍可使用,但不能当作完整结果。 */ error?: string } @@ -497,6 +501,7 @@ interface ScanResultMeta { truncated?: boolean approximate?: boolean visitedEntries?: number + missing?: boolean } export interface ScanDirectoryTreeOptions { @@ -504,6 +509,10 @@ export interface ScanDirectoryTreeOptions { maxFiles?: number collectTopN?: number filterExt?: RegExp + /** 为 true 时,目录本身不存在(ENOENT)按空目录处理,不返回 error(权限拒绝/读取失败仍照常报错) */ + ignoreMissing?: boolean + /** Top-N 保留与排序方式:默认按体积降序,下载/录屏等时效场景可传 mtime-desc */ + sortBy?: 'size-desc' | 'mtime-desc' hostOverride?: DynamicBridge } @@ -519,8 +528,9 @@ function normalizeIndexedFileEntry(f: DynamicBridge): RealIndexedFileEntry { const sz = Number(f?.size ?? f?.sizeBytes ?? 0) const isDir = Boolean(f?.is_dir || f?.isDir || f?.isDirectory) const rawMtime = Number(f?.mtime ?? f?.mtimeMs ?? 0) - const mtimeMs = rawMtime > 1e11 ? rawMtime : rawMtime > 0 ? rawMtime * 1000 : Date.now() - const mtimeSec = rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime + const validMtime = Number.isFinite(rawMtime) && rawMtime > 0 + const mtimeMs = validMtime ? (rawMtime > 1e11 ? rawMtime : rawMtime * 1000) : 0 + const mtimeSec = validMtime ? (rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime) : 0 if (p && sz >= 0) realFileSizeCache.set(p, sz) return { name, @@ -551,6 +561,7 @@ function makeScanResult( subdirs, ...(meta.truncated ? { truncated: true } : {}), ...(meta.approximate ? { approximate: true } : {}), + ...(meta.missing ? { missing: true } : {}), ...(typeof meta.visitedEntries === 'number' ? { visitedEntries: meta.visitedEntries } : {}), [Symbol.iterator]() { return files[Symbol.iterator]() @@ -609,13 +620,40 @@ export async function scanRealDirectoryTree( return result.error ? { ...result.scan, error: result.error } : result.scan } +/** 仅当正则明确声明了扩展名(含 `\.`)时提取后缀列表,避免把 `thumbcache|iconcache` 等文件名关键词误拆成假扩展名 */ +function extractExtensionTokensFromFilter(filterExt: RegExp): string[] { + const src = filterExt.source + if (!src.includes('\\.')) return [] + const afterDot = src.slice(src.indexOf('\\.') + 2) + const rawTokens = afterDot.match(/[a-z0-9]{1,8}/gi) || [] + const seen = new Set() + const out: string[] = [] + for (const token of rawTokens) { + const lower = token.toLowerCase() + if (!lower || seen.has(lower)) continue + seen.add(lower) + out.push(lower) + } + return out +} + +function isMissingDirectoryError(res: { error?: string; errorCode?: string; errorDetails?: Record }): boolean { + if (res.errorDetails?.reason === 'ENOENT' || res.errorCode === 'ENOENT') return true + const msg = String(res.error || '') + return /Directory does not exist|ENOENT/i.test(msg) +} + /** 一次界面扫描的错误汇总;多个目录并行扫描时保留可读目录的结果。 */ export function createDirectoryScanner(hostOverride?: DynamicBridge) { const failures = new Map() return { async scan(dir: string, options: number | ScanDirectoryTreeOptions = 160) { const result = await scanRealDirectoryTree(dir, options, hostOverride) - const error = result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') + const ignoreMissing = typeof options === 'object' && options !== null && options.ignoreMissing === true + const error = + result.missing && ignoreMissing + ? '' + : result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') if (error) failures.set(dir, error) else failures.delete(dir) return result @@ -648,26 +686,38 @@ async function scanDirectoryTreeWithError( const safeLimit = Math.min(200, Math.max(1, Math.floor(rawLimit || 160))) const hostOverride = opts.hostOverride const filterExt = opts.filterExt + const ignoreMissing = opts.ignoreMissing === true const dirQuery = `dir:${targetDir}` try { let rawPayload: DynamicBridge = null + const searchParams: Record = { + query: dirQuery, + limit: safeLimit, + ...(opts.sortBy ? { sortBy: opts.sortBy } : {}) + } const res = await callHostTransport( 'system_search_files', - { query: dirQuery, limit: safeLimit }, + searchParams, hostOverride ) - if (res.ok && res.data) { + if (res.ok && res.data && res.data.degraded !== true) { rawPayload = res.data + } else if (!res.ok && ignoreMissing && isMissingDirectoryError(res)) { + const missingScan = makeScanResult([], 0, 0, [], { missing: true }) + return { scan: missingScan } } - if (!rawPayload && !hostOverride && typeof window !== 'undefined') { + if (!rawPayload && !hostOverride && res.errorCode === 'METHOD_NOT_AVAILABLE' && typeof window !== 'undefined') { const w = window as DynamicBridge if (typeof w.__ztoolsLauncher?.searchFiles === 'function') { const rawOuter = await w.__ztoolsLauncher.searchFiles(dirQuery, safeLimit) - rawPayload = + const candidate = rawOuter && typeof rawOuter === 'object' && 'data' in rawOuter && rawOuter.data ? rawOuter.data : rawOuter + if (candidate && candidate.degraded !== true && candidate.success !== false) { + rawPayload = candidate + } } } @@ -678,29 +728,32 @@ async function scanDirectoryTreeWithError( let files: RealIndexedFileEntry[] = rawPayload.files.map(normalizeIndexedFileEntry) if (filterExt instanceof RegExp) { files = files.filter(f => !f.isDir && (filterExt.test(f.name) || filterExt.test(f.ext))) - // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索目标扩展名 + // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索明确声明的目标扩展名 if (files.length === 0 && !hostOverride) { - const extTokens = (filterExt.source.match(/[a-z0-9]{2,5}/gi) || []) - .filter(t => !['thumbcache', 'iconcache'].includes(t.toLowerCase())) - .slice(0, 4) - // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 - const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() - const extraLists = await Promise.all( - extTokens.map(ext => searchRealIndexedFiles(`.${ext.toLowerCase()}`, 30, hostOverride)) - ) - const seen = new Set() - for (const list of extraLists) { - for (const item of list) { - if (!item.isDir && item.size > 0 && !seen.has(item.path)) { - if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { - seen.add(item.path) - files.push(item) + const extTokens = extractExtensionTokensFromFilter(filterExt) + if (extTokens.length > 0) { + // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 + const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() + const extraLists = await Promise.all( + extTokens.map(ext => searchRealIndexedFiles(`.${ext}`, 30, hostOverride)) + ) + const seen = new Set() + for (const list of extraLists) { + for (const item of list) { + if (!item.isDir && item.size > 0 && !seen.has(item.path)) { + if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { + seen.add(item.path) + files.push(item) + } } } } } } } + // 先基于过滤后的完整命中集合计算总文件数与总字节数,再按 collectTopN 裁剪样本列表 + const matchedCount = files.length + const matchedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) if (typeof opts.collectTopN === 'number' && opts.collectTopN > 0 && files.length > opts.collectTopN) { files = files.slice(0, opts.collectTopN) } @@ -714,11 +767,10 @@ async function scanDirectoryTreeWithError( ...(s.approximate === true ? { approximate: true } : {}) })) : [] - const computedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) const totalFilesCount = - filterExt instanceof RegExp ? files.length : Number(rawPayload.total_matches ?? files.length) + filterExt instanceof RegExp ? matchedCount : Number(rawPayload.total_matches ?? matchedCount) const totalBytesCount = - filterExt instanceof RegExp ? computedBytes : Number(rawPayload.total_bytes ?? computedBytes) + filterExt instanceof RegExp ? matchedBytes : Number(rawPayload.total_bytes ?? matchedBytes) const visited = Number(rawPayload.visited_entries) return { scan: makeScanResult(files, totalFilesCount, totalBytesCount, subdirs, { @@ -1817,8 +1869,6 @@ export async function writeRealClipboardText(text: string, hostOverride?: Dynami const payload = { text: String(text || '') } const res = await callHostTransport('clipboard_copy_text', payload, hostOverride) if (res.ok) return true - const fallbackRes = await callHostTransport('clipboard_write_text', payload, hostOverride) - if (fallbackRes.ok) return true try { if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) { await navigator.clipboard.writeText(String(text || '')) diff --git a/extensions/file-inspector/tests/file-inspector.view.test.mjs b/extensions/file-inspector/tests/file-inspector.view.test.mjs index 606072ac..69651164 100644 --- a/extensions/file-inspector/tests/file-inspector.view.test.mjs +++ b/extensions/file-inspector/tests/file-inspector.view.test.mjs @@ -42,10 +42,11 @@ test('二进制文件不能转码,后缀修正成功更新当前路径并移 const view = await mount(FileInspectorCommand) try { await pick(view) - assert.deepEqual(view.tree().props.filterBar.actions.map(a => a.id), ['pick-file']) + assert.deepEqual(view.tree().props.filterBar.actions.map(a => a.id), ['pick-file', 'fix-ext']) assert.ok(!view.actions(view.item('line-1')).some(a => a.props.title.includes('UTF-8'))) await view.run(view.item('line-1'), '修正扩展名为 .png') assert.match(view.text(), /sample.png/) + assert.deepEqual(view.tree().props.filterBar.actions.map(a => a.id), ['pick-file']) assert.ok(!view.actions(view.item('line-1')).some(a => a.props.title.includes('修正'))) } finally { view.unmount() } }) diff --git a/extensions/file-unlock/README.en.md b/extensions/file-unlock/README.en.md new file mode 100644 index 00000000..b12e2c60 --- /dev/null +++ b/extensions/file-unlock/README.en.md @@ -0,0 +1,24 @@ +# File Unlocker + +Neither macOS nor Windows reads the clipboard or scans directories/disks automatically on startup. Only after you actively select a target does the plugin inspect actual locking processes and ask for confirmation before acting. + +## Usage + +- **Windows**: + - The top bar and action panel provide "Select File to Check", "Select Folder to Check", and a manual "Check Path in Clipboard" action. You can also drag and drop a file/folder or paste a full path into the search box to check automatically. + - The `usb unlock` entry lists only removable drives and USB/SD/MMC external partitions for selection without automatically scanning handles on the drive. + - From the action panel on a target or process row, you can run "Terminate Locking Process (Unlock)", "Unlock All", "Unlock and Move to Recycle Bin", or "Clear Current Target" (`Ctrl+Shift+Backspace`). +- **macOS**: + - Select a file or folder, or paste a full path (quotes allowed) and press `Enter` to see which processes are holding locks. On a target or process item, "Clear Current Target" is bound to `Cmd+Shift+Backspace`. + - The external drive entry lists mounted external drives recognized by the system, or lets you manually pick a mount directory. + - Selecting a process: `Enter` sends a normal termination signal, while force kill is in the action panel; a timed-out normal termination does not automatically escalate to force kill. Terminating a process may cause loss of unsaved data, so processes are listed for confirmation beforehand. The client re-verifies process identity and lock state before sending signals and re-scans afterward. + - On a target row, you can re-scan, copy the path, unlock and move to Trash, or open the rename form. Renaming stays within the same folder and aborts if a target with the same name already exists. Trash supports files and non-empty folders, which can be restored from Finder's Trash. Operations stop if locks remain, scanning fails, the target is replaced, a symlink/hardlink is encountered, or the target is a system-critical directory, disk root, or client data directory. + +Detection results only reflect processes visible under your current permissions. Folder scans do not follow symbolic links or cross nested mount points, and a failed scan is never reported as "not locked". "No locks found" is not a guarantee that a drive can be safely ejected—always use Safe Eject or Finder to eject disks. + +## Platforms & Requirements + +- Supported: Windows, macOS +- Requires client version 1.1.8.5 or later. +- macOS requires a client build with file unlocking capability and native file access components. +- Windows implementation is pending physical-device verification. diff --git a/extensions/file-unlock/plugin.json b/extensions/file-unlock/plugin.json index b0f2b240..1bae06de 100644 --- a/extensions/file-unlock/plugin.json +++ b/extensions/file-unlock/plugin.json @@ -2,7 +2,7 @@ "id": "file-unlock", "name": "文件解锁", "description": "检测文件、文件夹和外接磁盘的真实进程占用,确认后结束进程,支持不覆盖改名,或移入回收站 / 废纸篓以便恢复", - "version": "1.0.13", + "version": "1.0.14", "author": "ZTools Team", "entry": "dist/index.js", "icon": "icon.svg", @@ -76,7 +76,14 @@ "handle", "eject", "usb", - "delete" + "delete", + "file unlock", + "unlocker", + "file in use", + "locked file", + "cannot delete", + "eject usb", + "release lock" ], "features": { "file-unlock": { @@ -113,5 +120,15 @@ { "path": "screenshots/02-action-panel.png" } + ], + "keywords": [ + "文件解锁", + "解除占用", + "删不掉文件", + "文件被占用", + "强力删除", + "谁占用了文件", + "u盘退不出", + "解锁文件" ] } diff --git a/extensions/file-unlock/src/i18n.ts b/extensions/file-unlock/src/i18n.ts index 5832ac07..ed6ce44e 100644 --- a/extensions/file-unlock/src/i18n.ts +++ b/extensions/file-unlock/src/i18n.ts @@ -97,6 +97,7 @@ const rawT = createTranslator( cancelAction: "取消", chooseFileBtn: "选择文件", chooseFolderBtn: "选择文件夹", + btnRefresh: "刷新", inspectPathTitle: "检测此路径", tagInspectedTarget: "检测目标", tagPendingReinspect: "待重新检测", @@ -307,6 +308,7 @@ const rawT = createTranslator( cancelAction: "Cancel", chooseFileBtn: "Choose File", chooseFolderBtn: "Choose Folder", + btnRefresh: "Refresh", inspectPathTitle: "Inspect This Path", tagInspectedTarget: "Target", tagPendingReinspect: "Needs Rescan", diff --git a/extensions/file-unlock/src/mac-command.tsx b/extensions/file-unlock/src/mac-command.tsx index 06bc95ee..61d050b6 100644 --- a/extensions/file-unlock/src/mac-command.tsx +++ b/extensions/file-unlock/src/mac-command.tsx @@ -26,7 +26,7 @@ export function RenameTargetForm({ snapshot, save }: { snapshot: LockSnapshot; s finally { active.current = false; if (alive.current) setBusy(false) } } return }> - + {error && } @@ -182,7 +182,7 @@ export default function MacFileUnlockCommand({ initialPath = '', featureCode = ' return { void clearTarget() }} /> : undefined} searchBarAccessory={} - filterBar={{ summaryText, actions: busy ? [{ id: 'cancel', title: t('cancelAction'), onAction: cancel }] : chooseInRow ? [] : [{ id: 'file', title: t('chooseFileBtn'), onAction: () => choose(false) }, { id: 'folder', title: t('chooseFolderBtn'), onAction: () => choose(true) }] }}> + filterBar={{ summaryText, actions: busy ? [{ id: 'cancel', label: t('cancelAction'), title: t('cancelAction'), style: 'secondary', onAction: cancel }] : chooseInRow ? [] : [{ id: 'file', label: t('chooseFileBtn'), title: t('chooseFileBtn'), icon: Icon.Document, style: 'primary', onAction: () => choose(false) }, { id: 'folder', label: t('chooseFolderBtn'), title: t('chooseFolderBtn'), icon: Icon.Folder, style: 'secondary', onAction: () => choose(true) }] }}> {pathInput && work(() => inspect(pathInput))} />} />} {target && diff --git a/extensions/file-unlock/src/native-ipc.ts b/extensions/file-unlock/src/native-ipc.ts index 51576b99..13643277 100644 --- a/extensions/file-unlock/src/native-ipc.ts +++ b/extensions/file-unlock/src/native-ipc.ts @@ -174,11 +174,13 @@ function normalizeMethodResult(method: string, payload: DynamicBridge): DynamicB if (method === 'system_get_battery_status') { // 宿主约定 percent 超出 0-100(如 255)表示无电池或电量未知,不能改写成 100% + // 若宿主明确给出 hasBattery 布尔值,必须原样保留,仅在缺失时按合法电量推算 const rawPct = payload.percent - const hasBattery = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const validPct = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const hasBattery = typeof payload.hasBattery === 'boolean' ? payload.hasBattery : validPct return { ...payload, - percent: hasBattery ? rawPct : null, + percent: validPct ? rawPct : null, hasBattery } } @@ -489,6 +491,8 @@ export interface RealDirectoryScanResult extends Iterable approximate?: boolean /** 宿主实际遍历的条目数 */ visitedEntries?: number + /** 目录本身不存在(ENOENT) */ + missing?: boolean /** 读取失败的真实原因;已有文件仍可使用,但不能当作完整结果。 */ error?: string } @@ -497,6 +501,7 @@ interface ScanResultMeta { truncated?: boolean approximate?: boolean visitedEntries?: number + missing?: boolean } export interface ScanDirectoryTreeOptions { @@ -504,6 +509,10 @@ export interface ScanDirectoryTreeOptions { maxFiles?: number collectTopN?: number filterExt?: RegExp + /** 为 true 时,目录本身不存在(ENOENT)按空目录处理,不返回 error(权限拒绝/读取失败仍照常报错) */ + ignoreMissing?: boolean + /** Top-N 保留与排序方式:默认按体积降序,下载/录屏等时效场景可传 mtime-desc */ + sortBy?: 'size-desc' | 'mtime-desc' hostOverride?: DynamicBridge } @@ -519,8 +528,9 @@ function normalizeIndexedFileEntry(f: DynamicBridge): RealIndexedFileEntry { const sz = Number(f?.size ?? f?.sizeBytes ?? 0) const isDir = Boolean(f?.is_dir || f?.isDir || f?.isDirectory) const rawMtime = Number(f?.mtime ?? f?.mtimeMs ?? 0) - const mtimeMs = rawMtime > 1e11 ? rawMtime : rawMtime > 0 ? rawMtime * 1000 : Date.now() - const mtimeSec = rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime + const validMtime = Number.isFinite(rawMtime) && rawMtime > 0 + const mtimeMs = validMtime ? (rawMtime > 1e11 ? rawMtime : rawMtime * 1000) : 0 + const mtimeSec = validMtime ? (rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime) : 0 if (p && sz >= 0) realFileSizeCache.set(p, sz) return { name, @@ -551,6 +561,7 @@ function makeScanResult( subdirs, ...(meta.truncated ? { truncated: true } : {}), ...(meta.approximate ? { approximate: true } : {}), + ...(meta.missing ? { missing: true } : {}), ...(typeof meta.visitedEntries === 'number' ? { visitedEntries: meta.visitedEntries } : {}), [Symbol.iterator]() { return files[Symbol.iterator]() @@ -609,13 +620,40 @@ export async function scanRealDirectoryTree( return result.error ? { ...result.scan, error: result.error } : result.scan } +/** 仅当正则明确声明了扩展名(含 `\.`)时提取后缀列表,避免把 `thumbcache|iconcache` 等文件名关键词误拆成假扩展名 */ +function extractExtensionTokensFromFilter(filterExt: RegExp): string[] { + const src = filterExt.source + if (!src.includes('\\.')) return [] + const afterDot = src.slice(src.indexOf('\\.') + 2) + const rawTokens = afterDot.match(/[a-z0-9]{1,8}/gi) || [] + const seen = new Set() + const out: string[] = [] + for (const token of rawTokens) { + const lower = token.toLowerCase() + if (!lower || seen.has(lower)) continue + seen.add(lower) + out.push(lower) + } + return out +} + +function isMissingDirectoryError(res: { error?: string; errorCode?: string; errorDetails?: Record }): boolean { + if (res.errorDetails?.reason === 'ENOENT' || res.errorCode === 'ENOENT') return true + const msg = String(res.error || '') + return /Directory does not exist|ENOENT/i.test(msg) +} + /** 一次界面扫描的错误汇总;多个目录并行扫描时保留可读目录的结果。 */ export function createDirectoryScanner(hostOverride?: DynamicBridge) { const failures = new Map() return { async scan(dir: string, options: number | ScanDirectoryTreeOptions = 160) { const result = await scanRealDirectoryTree(dir, options, hostOverride) - const error = result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') + const ignoreMissing = typeof options === 'object' && options !== null && options.ignoreMissing === true + const error = + result.missing && ignoreMissing + ? '' + : result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') if (error) failures.set(dir, error) else failures.delete(dir) return result @@ -648,26 +686,38 @@ async function scanDirectoryTreeWithError( const safeLimit = Math.min(200, Math.max(1, Math.floor(rawLimit || 160))) const hostOverride = opts.hostOverride const filterExt = opts.filterExt + const ignoreMissing = opts.ignoreMissing === true const dirQuery = `dir:${targetDir}` try { let rawPayload: DynamicBridge = null + const searchParams: Record = { + query: dirQuery, + limit: safeLimit, + ...(opts.sortBy ? { sortBy: opts.sortBy } : {}) + } const res = await callHostTransport( 'system_search_files', - { query: dirQuery, limit: safeLimit }, + searchParams, hostOverride ) - if (res.ok && res.data) { + if (res.ok && res.data && res.data.degraded !== true) { rawPayload = res.data + } else if (!res.ok && ignoreMissing && isMissingDirectoryError(res)) { + const missingScan = makeScanResult([], 0, 0, [], { missing: true }) + return { scan: missingScan } } - if (!rawPayload && !hostOverride && typeof window !== 'undefined') { + if (!rawPayload && !hostOverride && res.errorCode === 'METHOD_NOT_AVAILABLE' && typeof window !== 'undefined') { const w = window as DynamicBridge if (typeof w.__ztoolsLauncher?.searchFiles === 'function') { const rawOuter = await w.__ztoolsLauncher.searchFiles(dirQuery, safeLimit) - rawPayload = + const candidate = rawOuter && typeof rawOuter === 'object' && 'data' in rawOuter && rawOuter.data ? rawOuter.data : rawOuter + if (candidate && candidate.degraded !== true && candidate.success !== false) { + rawPayload = candidate + } } } @@ -678,29 +728,32 @@ async function scanDirectoryTreeWithError( let files: RealIndexedFileEntry[] = rawPayload.files.map(normalizeIndexedFileEntry) if (filterExt instanceof RegExp) { files = files.filter(f => !f.isDir && (filterExt.test(f.name) || filterExt.test(f.ext))) - // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索目标扩展名 + // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索明确声明的目标扩展名 if (files.length === 0 && !hostOverride) { - const extTokens = (filterExt.source.match(/[a-z0-9]{2,5}/gi) || []) - .filter(t => !['thumbcache', 'iconcache'].includes(t.toLowerCase())) - .slice(0, 4) - // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 - const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() - const extraLists = await Promise.all( - extTokens.map(ext => searchRealIndexedFiles(`.${ext.toLowerCase()}`, 30, hostOverride)) - ) - const seen = new Set() - for (const list of extraLists) { - for (const item of list) { - if (!item.isDir && item.size > 0 && !seen.has(item.path)) { - if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { - seen.add(item.path) - files.push(item) + const extTokens = extractExtensionTokensFromFilter(filterExt) + if (extTokens.length > 0) { + // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 + const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() + const extraLists = await Promise.all( + extTokens.map(ext => searchRealIndexedFiles(`.${ext}`, 30, hostOverride)) + ) + const seen = new Set() + for (const list of extraLists) { + for (const item of list) { + if (!item.isDir && item.size > 0 && !seen.has(item.path)) { + if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { + seen.add(item.path) + files.push(item) + } } } } } } } + // 先基于过滤后的完整命中集合计算总文件数与总字节数,再按 collectTopN 裁剪样本列表 + const matchedCount = files.length + const matchedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) if (typeof opts.collectTopN === 'number' && opts.collectTopN > 0 && files.length > opts.collectTopN) { files = files.slice(0, opts.collectTopN) } @@ -714,11 +767,10 @@ async function scanDirectoryTreeWithError( ...(s.approximate === true ? { approximate: true } : {}) })) : [] - const computedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) const totalFilesCount = - filterExt instanceof RegExp ? files.length : Number(rawPayload.total_matches ?? files.length) + filterExt instanceof RegExp ? matchedCount : Number(rawPayload.total_matches ?? matchedCount) const totalBytesCount = - filterExt instanceof RegExp ? computedBytes : Number(rawPayload.total_bytes ?? computedBytes) + filterExt instanceof RegExp ? matchedBytes : Number(rawPayload.total_bytes ?? matchedBytes) const visited = Number(rawPayload.visited_entries) return { scan: makeScanResult(files, totalFilesCount, totalBytesCount, subdirs, { @@ -1817,8 +1869,6 @@ export async function writeRealClipboardText(text: string, hostOverride?: Dynami const payload = { text: String(text || '') } const res = await callHostTransport('clipboard_copy_text', payload, hostOverride) if (res.ok) return true - const fallbackRes = await callHostTransport('clipboard_write_text', payload, hostOverride) - if (fallbackRes.ok) return true try { if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) { await navigator.clipboard.writeText(String(text || '')) diff --git a/extensions/file-unlock/src/unlock-service.ts b/extensions/file-unlock/src/unlock-service.ts index 26614f6f..bd3b505f 100644 --- a/extensions/file-unlock/src/unlock-service.ts +++ b/extensions/file-unlock/src/unlock-service.ts @@ -2,11 +2,9 @@ import { t } from './i18n.js' import { HOST_SERVICE_LABEL_ZH } from './unlock-labels.zh-data.js' import { callHostTransport, - invokePluginService, openRealPath, readRealClipboardText, showRealItemInFolder, - trashRealItem, writeRealClipboardText } from './native-ipc.js' import type { @@ -20,7 +18,19 @@ import type { } from './types.js' import { resolveErrorMessage } from './error-i18n.js' -export const FILE_UNLOCK_PLUGIN_NAME = 'FileUnlockPlugin' +/** 缓存最近一次 file_unlock inspect 返回的会话 ID(按归一化目标路径索引) */ +const activeSessionByPath = new Map() + +function sessionPathKey(targetPath: string): string { + return sanitizeInputPath(targetPath).replace(/[\\/]+$/, '').toLowerCase() +} + +function formatDriveBytes(bytes: number): string { + if (!Number.isFinite(bytes) || bytes <= 0) return '0 B' + const units = ['B', 'KB', 'MB', 'GB', 'TB'] + const idx = Math.min(Math.floor(Math.log(bytes) / Math.log(1024)), units.length - 1) + return `${(bytes / Math.pow(1024, idx)).toFixed(idx === 0 ? 0 : 1)} ${units[idx] ?? 'B'}` +} export const CRITICAL_KERNEL_PROCESS_NAMES = new Set([ 'system', @@ -154,13 +164,16 @@ export function normalizeLockingProcess( const pid = Number(raw.pid ?? 0) const name = String(raw.name ?? `PID-${pid}`).trim() const executablePath = String(raw.executablePath ?? name).trim() - const lockedPath = String(raw.lockedPath ?? fallbackTargetPath).trim() - const isProtected = Boolean(raw.isProtected) || isKernelProtectedProcess(pid, name) - const serviceTypeLabel = resolveServiceTypeLabel( - pid, - name, - typeof raw.serviceTypeLabel === 'string' ? raw.serviceTypeLabel : undefined - ) + const rawPaths = Array.isArray(raw.paths) ? raw.paths.filter((p): p is string => typeof p === 'string' && Boolean(p.trim())) : [] + const lockedPath = String(raw.lockedPath ?? rawPaths[0] ?? fallbackTargetPath).trim() + const isProtected = Boolean(raw.isProtected ?? raw.protected) || isKernelProtectedProcess(pid, name) + const rawServiceType = + typeof raw.serviceTypeLabel === 'string' + ? raw.serviceTypeLabel + : typeof raw.serviceType === 'string' + ? raw.serviceType + : undefined + const serviceTypeLabel = resolveServiceTypeLabel(pid, name, rawServiceType) const rawHandle = String(raw.handleType ?? 'file').toLowerCase() const handleType: HandleKind = rawHandle === 'directory' || rawHandle === 'dll' || rawHandle === 'unknown' @@ -194,15 +207,14 @@ export async function listRemovableDrives(hostOverride?: unknown): Promise { - const res = await invokePluginService<{ ok?: boolean; drives?: Array>; error?: string; warning?: string }>( - FILE_UNLOCK_PLUGIN_NAME, - 'listRemovableDrives', - {}, + const res = await callHostTransport<{ success?: boolean; drives?: Array>; error?: string; warning?: string }>( + 'file_unlock', + { action: 'drives' }, hostOverride ) - if (!res.ok || !res.data || res.data.ok === false || !Array.isArray(res.data.drives)) { + if (!res.ok || !res.data || res.data.success === false || !Array.isArray(res.data.drives)) { return { drives: [], error: resolveErrorMessage(res.data?.error ? res.data : res, t('errLoadDrivesFailed')) } } const warning = typeof res.data.warning === 'string' && res.data.warning ? res.data.warning : undefined @@ -211,14 +223,19 @@ export async function loadRemovableDrives(hostOverride?: unknown): Promise<{ dri function normalizeDrives(list: Array>): RemovableDriveItem[] { return list - .map((d) => ({ - mount: String(d.mount ?? ''), - label: String(d.label ?? t('removableDriveDefaultLabel')), - totalBytes: Number(d.totalBytes ?? 0), - freeBytes: Number(d.freeBytes ?? 0), - totalText: String(d.totalText ?? '0 B'), - freeText: String(d.freeText ?? '0 B') - })) + .map((d) => { + const mount = String(d.mount ?? d.path ?? '') + const totalBytes = Number(d.totalBytes ?? 0) + const freeBytes = Number(d.freeBytes ?? 0) + return { + mount, + label: String(d.label || '') || t('removableDriveDefaultLabel'), + totalBytes, + freeBytes, + totalText: typeof d.totalText === 'string' && d.totalText ? d.totalText : formatDriveBytes(totalBytes), + freeText: typeof d.freeText === 'string' && d.freeText ? d.freeText : formatDriveBytes(freeBytes) + } + }) .filter((d) => Boolean(d.mount)) } @@ -233,8 +250,7 @@ function extractErrorCode(errorMsg?: string, rawCode?: unknown): string { export async function inspectTargetLocks( rawTargetPath: string, - hostOverride?: unknown, - extraParams: Record = {} + hostOverride?: unknown ): Promise { const validation = validateTargetPath(rawTargetPath) if (!validation.valid) { @@ -249,19 +265,15 @@ export async function inspectTargetLocks( } } - const res = await invokePluginService>( - FILE_UNLOCK_PLUGIN_NAME, - 'inspectLocks', - { - targetPath: validation.normalizedPath, - ...extraParams - }, + const res = await callHostTransport>( + 'file_unlock', + { action: 'inspect', targetPath: validation.normalizedPath }, hostOverride ) - if (!res.ok || !res.data || res.data.ok === false) { - const rawErrText = String(res.data?.error ?? res.error ?? res.message ?? '') - const errCode = extractErrorCode(rawErrText, res.data?.errorCode) + if (!res.ok || !res.data || res.data.success === false) { + const rawErrText = String(res.data?.error ?? res.error ?? '') + const errCode = extractErrorCode(rawErrText, res.data?.errorCode ?? res.errorCode) return { ok: false, targetPath: validation.normalizedPath, @@ -273,13 +285,13 @@ export async function inspectTargetLocks( } } - const rawList = Array.isArray(res.data.processes) - ? res.data.processes - : Array.isArray(res.data.lockingProcesses) - ? res.data.lockingProcesses - : [] - + const rawList = Array.isArray(res.data.processes) ? res.data.processes : [] const resolvedTarget = String(res.data.targetPath ?? validation.normalizedPath) + if (typeof res.data.sessionId === 'string' && res.data.sessionId) { + activeSessionByPath.set(sessionPathKey(validation.normalizedPath), res.data.sessionId) + activeSessionByPath.set(sessionPathKey(resolvedTarget), res.data.sessionId) + } + const processes = rawList .filter((item): item is Record => Boolean(item && typeof item === 'object')) .map((item) => normalizeLockingProcess(item, resolvedTarget)) @@ -295,13 +307,70 @@ export async function inspectTargetLocks( } } +async function ensureSessionId(targetPath: string, hostOverride?: unknown): Promise { + const existing = activeSessionByPath.get(sessionPathKey(targetPath)) + if (existing) return existing + const inspected = await inspectTargetLocks(targetPath, hostOverride) + if (!inspected.ok) return null + return activeSessionByPath.get(sessionPathKey(inspected.targetPath)) ?? activeSessionByPath.get(sessionPathKey(targetPath)) ?? null +} + +async function performPostUnlockMutation( + sessionId: string, + targetPath: string, + options: { trashAfterUnlock?: boolean; renameTo?: string }, + hostOverride?: unknown +): Promise<{ ok: true; trashed: boolean; renamedPath?: string } | { ok: false; errorCode: string; error: string }> { + if (options.trashAfterUnlock) { + const trashRes = await callHostTransport>( + 'file_unlock', + { action: 'trash', sessionId }, + hostOverride + ) + activeSessionByPath.delete(sessionPathKey(targetPath)) + if (!trashRes.ok || !trashRes.data || trashRes.data.success === false || trashRes.data.status !== 'trashed') { + const rawErrText = String(trashRes.data?.error ?? trashRes.error ?? '') + return { + ok: false, + errorCode: extractErrorCode(rawErrText, trashRes.data?.errorCode ?? trashRes.errorCode ?? 'TRASH_FAILED'), + error: resolveErrorMessage(trashRes.data?.error ? trashRes.data : trashRes, t('errTrashFailed')) + } + } + return { ok: true, trashed: true } + } + + if (options.renameTo) { + const renameRes = await callHostTransport>( + 'file_unlock', + { action: 'rename', sessionId, name: options.renameTo }, + hostOverride + ) + activeSessionByPath.delete(sessionPathKey(targetPath)) + if (!renameRes.ok || !renameRes.data || renameRes.data.success === false || renameRes.data.status !== 'renamed') { + const rawErrText = String(renameRes.data?.error ?? renameRes.error ?? '') + return { + ok: false, + errorCode: extractErrorCode(rawErrText, renameRes.data?.errorCode ?? renameRes.errorCode ?? 'RENAME_FAILED'), + error: resolveErrorMessage(renameRes.data?.error ? renameRes.data : renameRes, t('errUnlockPathFailed')) + } + } + return { + ok: true, + trashed: false, + ...(typeof renameRes.data.targetPath === 'string' ? { renamedPath: renameRes.data.targetPath } : {}) + } + } + + return { ok: true, trashed: false } +} + export async function unlockSingleProcess( proc: LockingProcessItem, targetPath: string, options: { trashAfterUnlock?: boolean renameTo?: string - extraParams?: Record + mode?: 'graceful' | 'force' } = {}, hostOverride?: unknown ): Promise { @@ -327,23 +396,36 @@ export async function unlockSingleProcess( } } - const res = await invokePluginService>( - FILE_UNLOCK_PLUGIN_NAME, - 'unlockPath', - { + const normalizedTarget = sanitizeInputPath(targetPath || proc.lockedPath) + const sessionId = await ensureSessionId(normalizedTarget, hostOverride) + if (!sessionId) { + return { + ok: false, pid: proc.pid, expectedName: proc.name, - targetPath: sanitizeInputPath(targetPath || proc.lockedPath), - trashAfterUnlock: Boolean(options.trashAfterUnlock), - ...(options.renameTo ? { renameTo: options.renameTo } : {}), - ...(options.extraParams ?? {}) + unlockedCount: 0, + skippedProtectedCount: 0, + errorCode: 'LOCK_RECHECK_FAILED', + error: t('errInspectLocksFailed') + } + } + + const res = await callHostTransport>( + 'file_unlock', + { + action: 'terminate', + sessionId, + pids: [proc.pid], + mode: options.mode ?? 'force' }, hostOverride ) - if (!res.ok || !res.data || res.data.ok === false) { - const rawErrText = String(res.data?.error ?? res.error ?? res.message ?? '') - const errCode = extractErrorCode(rawErrText, res.data?.errorCode) + if (!res.ok || !res.data || res.data.success === false) { + const failures = Array.isArray(res.data?.failures) ? (res.data.failures as Array>) : [] + const firstFailureMsg = typeof failures[0]?.message === 'string' ? failures[0].message : '' + const rawErrText = firstFailureMsg || String(res.data?.refreshError ?? res.data?.error ?? res.error ?? '') + const errCode = extractErrorCode(rawErrText, res.data?.errorCode ?? res.errorCode) return { ok: false, pid: proc.pid, @@ -351,7 +433,22 @@ export async function unlockSingleProcess( unlockedCount: 0, skippedProtectedCount: errCode === 'PROCESS_PROTECTED' ? 1 : 0, errorCode: errCode, - error: resolveErrorMessage(res.data?.error ? res.data : res, t('errUnlockPathFailed')) + error: resolveErrorMessage(rawErrText ? { error: rawErrText, errorCode: errCode } : res, t('errUnlockPathFailed')) + } + } + + const explorerRestarted = Boolean(res.data.explorerRestarted) + const post = await performPostUnlockMutation(sessionId, normalizedTarget, options, hostOverride) + if (!post.ok) { + return { + ok: false, + pid: proc.pid, + expectedName: proc.name, + unlockedCount: 1, + skippedProtectedCount: 0, + explorerRestarted, + errorCode: post.errorCode, + error: post.error } } @@ -361,9 +458,9 @@ export async function unlockSingleProcess( expectedName: proc.name, unlockedCount: 1, skippedProtectedCount: 0, - explorerRestarted: Boolean(res.data.explorerRestarted), - trashed: Boolean(res.data.trashed), - ...(typeof res.data.renamedPath === 'string' ? { renamedPath: res.data.renamedPath } : {}) + explorerRestarted, + trashed: post.trashed, + ...(post.renamedPath ? { renamedPath: post.renamedPath } : {}) } } @@ -373,7 +470,7 @@ export async function unlockAllProcesses( options: { trashAfterUnlock?: boolean renameTo?: string - extraParams?: Record + mode?: 'graceful' | 'force' } = {}, hostOverride?: unknown ): Promise { @@ -401,54 +498,66 @@ export async function unlockAllProcesses( } } - if (killable.length === 0 && options.trashAfterUnlock) { - const trashRes = await trashRealItem(validation.normalizedPath, hostOverride) - if (!trashRes.ok) { - return { - ok: false, - unlockedCount: 0, - skippedProtectedCount: 0, - errorCode: 'TRASH_FAILED', - error: resolveErrorMessage(trashRes, t('errTrashFailed')) - } - } + const sessionId = await ensureSessionId(validation.normalizedPath, hostOverride) + if (!sessionId) { return { - ok: true, + ok: false, unlockedCount: 0, - skippedProtectedCount: 0, - trashed: true + skippedProtectedCount: protectedCount, + errorCode: 'LOCK_RECHECK_FAILED', + error: t('errInspectLocksFailed') } } let unlockedCount = 0 let explorerRestarted = false - let trashed = false - let renamedPath: string | undefined - for (let i = 0; i < killable.length; i++) { - const proc = killable[i]! - const isLast = i === killable.length - 1 - const singleRes = await unlockSingleProcess( - proc, - validation.normalizedPath, + if (killable.length > 0) { + const res = await callHostTransport>( + 'file_unlock', { - trashAfterUnlock: Boolean(isLast && options.trashAfterUnlock && protectedCount === 0), - renameTo: isLast && protectedCount === 0 ? options.renameTo : undefined, - extraParams: options.extraParams + action: 'terminate', + sessionId, + pids: killable.map((p) => p.pid), + mode: options.mode ?? 'force' }, hostOverride ) - if (!singleRes.ok) { + const terminated = Array.isArray(res.data?.terminated) ? res.data.terminated.length : 0 + unlockedCount = terminated + explorerRestarted = Boolean(res.data?.explorerRestarted) + if (!res.ok || !res.data || res.data.success === false) { + const failures = Array.isArray(res.data?.failures) ? (res.data.failures as Array>) : [] + const firstFailureMsg = typeof failures[0]?.message === 'string' ? failures[0].message : '' + const rawErrText = firstFailureMsg || String(res.data?.refreshError ?? res.data?.error ?? res.error ?? '') + const errCode = extractErrorCode(rawErrText, res.data?.errorCode ?? res.errorCode) return { - ...singleRes, + ok: false, unlockedCount, - skippedProtectedCount: protectedCount + singleRes.skippedProtectedCount + skippedProtectedCount: protectedCount, + explorerRestarted, + errorCode: errCode, + error: resolveErrorMessage(rawErrText ? { error: rawErrText, errorCode: errCode } : res, t('errUnlockPathFailed')) } } - unlockedCount += 1 - if (singleRes.explorerRestarted) explorerRestarted = true - if (singleRes.trashed) trashed = true - if (singleRes.renamedPath) renamedPath = singleRes.renamedPath + } + + let trashed = false + let renamedPath: string | undefined + if (protectedCount === 0 && (options.trashAfterUnlock || options.renameTo)) { + const post = await performPostUnlockMutation(sessionId, validation.normalizedPath, options, hostOverride) + if (!post.ok) { + return { + ok: false, + unlockedCount, + skippedProtectedCount: protectedCount, + explorerRestarted, + errorCode: post.errorCode, + error: post.error + } + } + trashed = post.trashed + renamedPath = post.renamedPath } return { @@ -464,18 +573,42 @@ export async function unlockAllProcesses( export async function unlockAndTrashTarget( processes: LockingProcessItem[], targetPath: string, - hostOverride?: unknown, - extraParams: Record = {} + hostOverride?: unknown ): Promise { return unlockAllProcesses( processes, targetPath, - { - trashAfterUnlock: true, - extraParams - }, + { trashAfterUnlock: true }, + hostOverride + ) +} + +export async function ejectRemovableDrive( + drive: string, + hostOverride?: unknown +): Promise<{ ok: boolean; drive: string; ejected: boolean; error?: string }> { + const res = await callHostTransport>( + 'file_unlock', + { action: 'eject', drive: sanitizeInputPath(drive) }, hostOverride ) + if (!res.ok || !res.data || res.data.success === false || res.data.ejected !== true) { + return { + ok: false, + drive, + ejected: false, + error: resolveErrorMessage(res.data?.error ? res.data : res, t('errUnlockPathFailed')) + } + } + return { ok: true, drive: String(res.data.drive ?? drive), ejected: true } +} + +export async function finishWindowsUnlockSession( + action: 'cancel' | 'close', + hostOverride?: unknown +): Promise { + if (action === 'close') activeSessionByPath.clear() + await callHostTransport('file_unlock', { action }, hostOverride) } export function filterLockingProcesses( diff --git a/extensions/file-unlock/src/windows-command.tsx b/extensions/file-unlock/src/windows-command.tsx index 39a857f1..dc1c9100 100644 --- a/extensions/file-unlock/src/windows-command.tsx +++ b/extensions/file-unlock/src/windows-command.tsx @@ -19,6 +19,7 @@ import { detectClipboardCandidatePath, extractDroppedUnlockPath, filterLockingProcesses, + finishWindowsUnlockSession, inspectTargetLocks, loadRemovableDrives, looksLikeFilePath, @@ -130,6 +131,7 @@ export default function FileUnlockCommand(props?: { alive.current = false ++inspectSeq.current ++targetEpoch.current + void finishWindowsUnlockSession('close', props?.hostOverride).catch((e) => console.warn('Windows 文件解锁关闭未确认', e)) } }, [props?.initialPath, props?.featureCode, props?.hostOverride]) @@ -452,20 +454,46 @@ export default function FileUnlockCommand(props?: { actions: [ { id: 'pick-file', + label: t('actionPickFileInspect'), title: t('actionPickFileInspect'), - style: 'secondary', + icon: Icon.Document, + style: 'primary', onAction: () => { void handlePickTarget(false) } }, - { - id: 'pick-folder', - title: t('actionPickFolderInspect'), - style: 'secondary', - onAction: () => { - void handlePickTarget(true) - } - } + targetPath + ? { + id: 'rescan', + label: t('btnRefresh'), + title: t('actionRescanLocks'), + icon: Icon.ArrowClockwise, + style: 'secondary', + onAction: () => { + void runInspection(targetPath) + } + } + : isUsbEntry + ? { + id: 'refresh-drives', + label: t('btnRefresh'), + title: t('actionRefreshDrives'), + icon: Icon.ArrowClockwise, + style: 'secondary', + onAction: () => { + void refreshRemovableDrives() + } + } + : { + id: 'pick-folder', + label: t('actionPickFolderInspect'), + title: t('actionPickFolderInspect'), + icon: Icon.Folder, + style: 'secondary', + onAction: () => { + void handlePickTarget(true) + } + } ] }} > @@ -629,6 +657,7 @@ export default function FileUnlockCommand(props?: { title={t('actionKillAndDelete')} icon={Icon.Trash} style={Action.Style.Destructive} + shortcut={{ modifiers: ['ctrl'], key: 'return' }} onAction={() => { void handleUnlockSingle(proc, true) }} diff --git a/extensions/file-unlock/tests/file-unlock.test.mjs b/extensions/file-unlock/tests/file-unlock.test.mjs index 08fdd8c1..8b59bc7e 100644 --- a/extensions/file-unlock/tests/file-unlock.test.mjs +++ b/extensions/file-unlock/tests/file-unlock.test.mjs @@ -201,7 +201,7 @@ test('Ctrl+V 粘贴文件或文件夹与 Windows 手动选择文件/文件夹检 assert.equal(calls('inspect')[0][1].targetPath, '/fixture/文档.txt') assert.ok(view.item('process:55')) - // Windows 平台下支持粘贴文件检测,且提供手动「选择文件检测」「选择文件夹检测」Action + // Windows 平台下支持粘贴文件检测,且提供手动「选择文件检测」「选择文件夹检测」Action,统一走 file_unlock 专用 IPC host.reset() host.ipc.system_get_platform = async () => ({ success: true, platform: 'windows' }) host.ipc.window_show_open_dialog = async (params) => ({ @@ -209,18 +209,22 @@ test('Ctrl+V 粘贴文件或文件夹与 Windows 手动选择文件/文件夹检 filePath: params.properties?.includes('openDirectory') ? 'D:\\Locked\\FolderA' : 'D:\\Locked\\report.docx' }) const winInspectCalls = [] - host.ipc.dllplugin_call = async ({ func, params }) => { - if (func === 'listRemovableDrives') return { ok: true, drives: [] } - if (func === 'inspectLocks') { - winInspectCalls.push(params.targetPath) + host.ipc.file_unlock = async (p) => { + if (p.action === 'drives') return { success: true, drives: [] } + if (p.action === 'close' || p.action === 'cancel') return { success: true, cancelRequested: true } + if (p.action === 'inspect') { + winInspectCalls.push(p.targetPath) return { - ok: true, - targetPath: params.targetPath, - isDirectory: params.targetPath.endsWith('FolderA'), - processes: [{ id: 'win-p1', pid: 4321, name: 'WINWORD.EXE', executablePath: 'C:\\Program Files\\WINWORD.EXE', lockedPath: params.targetPath }] + success: true, + sessionId, + targetPath: p.targetPath, + isDirectory: p.targetPath.endsWith('FolderA'), + notice: 'Windows Restart Manager', + mutationBlockedReason: '', + processes: [{ id: 'win-p1', pid: 4321, name: 'WINWORD.EXE', executablePath: 'C:\\Program Files\\WINWORD.EXE', userId: 0, paths: [p.targetPath], protected: false, reason: '' }] } } - return { ok: true } + return { success: true } } const winView = await open(commands['file-unlock']) @@ -238,10 +242,11 @@ test('Ctrl+V 粘贴文件或文件夹与 Windows 手动选择文件/文件夹检 await winView.pasteFiles(['D:\\Locked\\pasted_table.xlsx']) await tick(10) assert.equal(winInspectCalls.at(-1), 'D:\\Locked\\pasted_table.xlsx') + assert.ok(!host.ipcCalls.some(([m]) => m === 'dllplugin_call'), 'Windows 端绝不可调用 dllplugin_call') }) test('Windows 挂载零扫盘且不读剪贴板;usb-unlock 只列磁盘不扫描占用;手动检测剪贴板与清空当前目标(双端)', async () => { - // 1. Windows file-unlock 挂载:不调 clipboard_read_text、inspectLocks、listRemovableDrives,顶栏恰 2 个按钮 + // 1. Windows file-unlock 挂载:不调 clipboard_read_text、inspect、drives,顶栏恰 2 个按钮 host.reset() host.ipc.system_get_platform = async () => ({ success: true, platform: 'windows' }) host.clipboard.text = 'D:\\Secret\\from-clipboard.docx' @@ -252,33 +257,40 @@ test('Windows 挂载零扫盘且不读剪贴板;usb-unlock 只列磁盘不扫 } let releasePendingInspect let pendingInspectMode = false - host.ipc.dllplugin_call = async ({ func, params }) => { - winCalls.push(`${func}:${params.targetPath || ''}`) - if (func === 'listRemovableDrives') { + host.ipc.file_unlock = async (p) => { + if (p.action === 'close' || p.action === 'cancel') return { success: true, cancelRequested: true } + winCalls.push(`${p.action}:${p.targetPath || ''}`) + if (p.action === 'drives') { return { - ok: true, - drives: [{ mount: 'E:\\', label: 'MyUSB', totalBytes: 1024, freeBytes: 512, totalText: '1.0 KB', freeText: '512 B' }] + success: true, + drives: [{ path: 'E:\\', mount: 'E:\\', label: 'MyUSB', totalBytes: 1024, freeBytes: 512, totalText: '1.0 KB', freeText: '512 B' }] } } - if (func === 'inspectLocks') { + if (p.action === 'inspect') { if (pendingInspectMode) { return await new Promise((resolve) => { releasePendingInspect = () => resolve({ - ok: true, - targetPath: params.targetPath, + success: true, + sessionId, + targetPath: p.targetPath, isDirectory: false, - processes: [{ id: 'late-1', pid: 7777, name: 'notepad.exe', executablePath: 'C:\\Windows\\notepad.exe', lockedPath: params.targetPath }] + notice: 'Windows Restart Manager', + mutationBlockedReason: '', + processes: [{ id: 'late-1', pid: 7777, name: 'notepad.exe', executablePath: 'C:\\Windows\\notepad.exe', userId: 0, paths: [p.targetPath], protected: false, reason: '' }] }) }) } return { - ok: true, - targetPath: params.targetPath, + success: true, + sessionId, + targetPath: p.targetPath, isDirectory: false, - processes: [{ id: 'clip-p1', pid: 5566, name: 'WINWORD.EXE', executablePath: 'C:\\Program Files\\WINWORD.EXE', lockedPath: params.targetPath }] + notice: 'Windows Restart Manager', + mutationBlockedReason: '', + processes: [{ id: 'clip-p1', pid: 5566, name: 'WINWORD.EXE', executablePath: 'C:\\Program Files\\WINWORD.EXE', userId: 0, paths: [p.targetPath], protected: false, reason: '' }] } } - return { ok: true } + return { success: true } } const winView = await open(commands['file-unlock']) @@ -297,7 +309,7 @@ test('Windows 挂载零扫盘且不读剪贴板;usb-unlock 只列磁盘不扫 await winView.run(winView.item('empty-status'), '检测剪贴板中的路径') await tick(10) assert.equal(winCalls[0], 'clipboard_read_text') - assert.equal(winCalls[1], 'inspectLocks:D:\\Secret\\from-clipboard.docx') + assert.equal(winCalls[1], 'inspect:D:\\Secret\\from-clipboard.docx') const procItem = winView.item('clip-p1') const procActionTitles = winView.actions(procItem).map((a) => a.props.title) assert.ok(procActionTitles.includes('一键全部解锁')) @@ -312,7 +324,7 @@ test('Windows 挂载零扫盘且不读剪贴板;usb-unlock 只列磁盘不扫 assert.ok(winView.item('empty-status')) assert.match(winView.tree().props.filterBar.summaryText, /尚未选择目标/) - // 剪贴板无有效路径时给出提示,不触发 inspectLocks + // 剪贴板无有效路径时给出提示,不触发 inspect host.ipc.clipboard_read_text = async () => ({ success: true, data: 'plain text not a path' }) const countBeforeBadClip = winCalls.length await winView.run(winView.item('empty-status'), '检测剪贴板中的路径') @@ -338,17 +350,18 @@ test('Windows 挂载零扫盘且不读剪贴板;usb-unlock 只列磁盘不扫 await tick(10) assert.ok(winView.item('late-1')) - // 3. Windows usb-unlock 挂载:只调用 listRemovableDrives 列出盘符,不自动检测磁盘占用也不读剪贴板 + // 3. Windows usb-unlock 挂载:只调用 drives 列出盘符,不自动检测磁盘占用也不读剪贴板 winCalls.length = 0 pendingInspectMode = false const usbView = await open(commands['usb-unlock']) await tick(10) - assert.deepEqual(winCalls, ['listRemovableDrives:']) + assert.deepEqual(winCalls, ['drives:']) assert.ok(usbView.item('drive-E:\\')) assert.ok(usbView.item('empty-status')) await usbView.run(usbView.item('drive-E:\\'), '检测此移动磁盘的占用进程') await tick(10) - assert.equal(winCalls.at(-1), 'inspectLocks:E:\\') + assert.equal(winCalls.at(-1), 'inspect:E:\\') + assert.ok(!host.ipcCalls.some(([m]) => m === 'dllplugin_call'), 'Windows usb-unlock 绝不可调用 dllplugin_call') // 4. macOS 端支持「清空当前目标」(Cmd+Shift+Backspace)且操作进行中不可用 host.reset() diff --git a/extensions/flow-guard/README.en.md b/extensions/flow-guard/README.en.md new file mode 100644 index 00000000..e008be4d --- /dev/null +++ b/extensions/flow-guard/README.en.md @@ -0,0 +1,21 @@ +# Network Traffic Monitor + +Inspect active TCP/UDP connections and listening ports for local processes, categorized into public, LAN, and loopback addresses, with the ability to force-terminate processes that are accessing the network. + +## Usage + +- **Command**: Network Traffic Monitor (`flow-guard`). +- **List & Filtering**: Displays process name, PID, local/remote address and port, and connection state. Filter in the search box by process name, PID, executable path, port, or IP, and use the adjacent dropdown to switch between All Connections, Public Only, LAN, Listening Ports, TCP Only, UDP Only, or Group by Process. Up to the first 120 connection entries are displayed. +- **Scope & Refresh**: Displays connection state only—it does not measure network speed or traffic volume, and cannot throttle bandwidth. The list is read once on open and must be refreshed manually; if reading fails, the reason is shown in the top status bar. +- **Shortcuts**: + - Connection details view: `Enter` force-terminates the process, `Ctrl+Enter` (or `Ctrl+C`) copies the connection info, `Ctrl+O` reveals the executable in File Explorer (omitted if path is unavailable), `Ctrl+R` refreshes, and `Ctrl+K` opens the action panel (such as filtering to connections for that process only). + - Grouped by process view: `Enter` views all connections for that process, and `Ctrl+Enter` force-terminates the process. +- **Process Termination**: "Force Terminate" kills the entire process rather than closing a single socket, so unsaved data in that app will be lost; confirmation is required first. The plugin does not block the app from reconnecting later—once reopened or auto-restarted, it can access the network again. System processes such as `System`, `svchost.exe`, `lsass.exe`, `dns.exe`, `csrss.exe`, and `services.exe` cannot be terminated. Failures (such as insufficient permissions) display the reason. + +## Platforms & Requirements + +- Supported: Windows only + +## Network & Data + +- Offline only; only reads local connection and port tables. diff --git a/extensions/flow-guard/plugin.json b/extensions/flow-guard/plugin.json index e34a5888..4d16a7ad 100644 --- a/extensions/flow-guard/plugin.json +++ b/extensions/flow-guard/plugin.json @@ -2,7 +2,8 @@ "id": "flow-guard", "name": "流量监控", "description": "查看本机各进程的 TCP / UDP 连接和监听端口,按公网、局域网、本机回环分类,可强制结束正在联网的进程", - "version": "2.0.11", + "version": "2.0.12", + "minAppVersion": "1.1.8.0", "author": "ZTools Team", "entry": "dist/index.js", "icon": "icon.svg", @@ -42,7 +43,15 @@ "udp", "ports", "connections", - "monitor" + "monitor", + "network traffic", + "bandwidth", + "net speed", + "traffic monitor", + "upload", + "download", + "who uses network", + "flow" ], "screenshots": [ { @@ -58,5 +67,15 @@ { "path": "screenshots/02-action-panel.png" } + ], + "keywords": [ + "流量监控", + "网速监控", + "谁在占网速", + "看网速", + "上传下载", + "网络流量", + "带宽监控", + "占带宽" ] } diff --git a/extensions/flow-guard/src/i18n.ts b/extensions/flow-guard/src/i18n.ts index ef07dacc..9b0c227a 100644 --- a/extensions/flow-guard/src/i18n.ts +++ b/extensions/flow-guard/src/i18n.ts @@ -57,7 +57,8 @@ const rawT = createTranslator( secEndpointDetails: "活动套接字连接明细 ({count})", actionCopyTuple: "复制五元组连接信息", toastCopiedTuple: "已复制五元组信息", - actionFilterByProc: "仅筛选该进程连接" + actionFilterByProc: "仅筛选该进程连接", + kernelTimeWaitHint: "已关闭待内核回收连接" }, "en-US": { notInClientMessage: "Requires ZTools client environment", @@ -114,7 +115,8 @@ const rawT = createTranslator( secEndpointDetails: "Active Socket Endpoints ({count})", actionCopyTuple: "Copy 5-Tuple Info", toastCopiedTuple: "5-Tuple info copied", - actionFilterByProc: "Filter by This Process" + actionFilterByProc: "Filter by This Process", + kernelTimeWaitHint: "Closed socket awaiting kernel cleanup" } } ) diff --git a/extensions/flow-guard/src/index.ts b/extensions/flow-guard/src/index.ts index 9588f2d0..967be38a 100644 --- a/extensions/flow-guard/src/index.ts +++ b/extensions/flow-guard/src/index.ts @@ -32,8 +32,9 @@ export default function FlowGuardCommand() { useLocale() const [searchText, setSearchText] = useState('') const [dropdownFilter, setDropdownFilter] = useState('all') - const [focusPid, setFocusPid] = useState(0) + const [focusPid, setFocusPid] = useState(null) const [groups, setGroups] = useState([]) + const [activeProcessCount, setActiveProcessCount] = useState(0) const [totalEndpoints, setTotalEndpoints] = useState(0) const [totalEstablished, setTotalEstablished] = useState(0) const [totalListening, setTotalListening] = useState(0) @@ -53,6 +54,7 @@ export default function FlowGuardCommand() { if (snap.error) { // 读取失败时清空列表,避免把旧数据当成当前连接 setGroups([]) + setActiveProcessCount(0) setTotalEndpoints(0) setTotalEstablished(0) setTotalListening(0) @@ -66,6 +68,7 @@ export default function FlowGuardCommand() { return } setGroups(snap.groups) + setActiveProcessCount(snap.activeProcessCount) setTotalEndpoints(snap.totalEndpoints) setTotalEstablished(snap.totalEstablished) setTotalListening(snap.totalListening) @@ -78,7 +81,7 @@ export default function FlowGuardCommand() { style: Toast.Style.Success, title: t('toastRefreshedTitle'), message: t('toastRefreshedMsg', { - procs: snap.groups.length, + procs: snap.activeProcessCount, publicCount: snap.totalPublic, endpoints: snap.totalEndpoints }) @@ -144,7 +147,7 @@ export default function FlowGuardCommand() { : 'all' const filteredGroups = groups.filter((g) => { - if (focusPid > 0 && g.pid !== focusPid) return false + if (focusPid !== null && g.pid !== focusPid) return false if (protoFilter === 'TCP' && g.tcpCount === 0) return false if (protoFilter === 'UDP' && g.udpCount === 0) return false if (scopeFilter === 'public' && g.publicCount === 0) return false @@ -218,10 +221,10 @@ export default function FlowGuardCommand() { listening: totalListening, lan: totalLan, loopback: totalLoopback, - procs: groups.length + procs: activeProcessCount }), actions: [ - ...(focusPid > 0 + ...(focusPid !== null ? [ { id: 'clear-focus-pid', @@ -229,7 +232,7 @@ export default function FlowGuardCommand() { title: t('btnExitFocusPid', { pid: focusPid }), style: 'secondary' as const, onAction: () => { - setFocusPid(0) + setFocusPid(null) } } ] @@ -256,23 +259,31 @@ export default function FlowGuardCommand() { const ratio = Math.min(100, Math.max(5, Math.round((g.endpoints.length / maxGroupEndpoints) * 100))) const scopeTag = g.publicCount > 0 ? t('scopePublic') : g.listeningCount > 0 ? t('scopeListening') : t('scopeLan') + const procSub = g.pid === 0 + ? `${t('kernelTimeWaitHint')} · ${t('procSubtitle', { + summary: epSummary, + pub: g.publicCount, + lan: g.lanCount, + listen: g.listeningCount + })}` + : t('procSubtitle', { + summary: epSummary, + pub: g.publicCount, + lan: g.lanCount, + listen: g.listeningCount + }) return List.Item({ id: `net-proc-${g.pid}`, title: `${g.processName} (PID: ${g.pid})`, - subtitle: t('procSubtitle', { - summary: epSummary, - pub: g.publicCount, - lan: g.lanCount, - listen: g.listeningCount - }), + subtitle: procSub, icon: g.isProtected ? Icon.Shield : Icon.Globe, accessories: [ { progress: { value: ratio } }, { tag: { value: scopeTag, - ...(g.publicCount > 25 ? { color: Color.Red } : {}) + ...(g.pid > 0 && g.activePublicCount > 25 ? { color: Color.Red } : {}) } }, { text: `ESTABLISHED ${g.establishedCount} / LISTEN ${g.listeningCount}` } @@ -288,13 +299,17 @@ export default function FlowGuardCommand() { setDropdownFilter('all') } }), - Action({ - title: t('actionKillProcess'), - icon: Icon.XMarkCircle, - style: 'destructive', - shortcut: { modifiers: ['ctrl'], key: 'return' }, - onAction: () => handleKillProcess(g) - }), + ...(g.pid > 0 + ? [ + Action({ + title: t('actionKillProcess'), + icon: Icon.XMarkCircle, + style: 'destructive', + shortcut: { modifiers: ['ctrl'], key: 'return' }, + onAction: () => handleKillProcess(g) + }) + ] + : []), ...(g.processPath ? [ Action({ @@ -339,7 +354,7 @@ export default function FlowGuardCommand() { : [ List.Section({ title: t('secEndpointDetails', { count: allEndpoints.length }), - children: allEndpoints.slice(0, 120).map((ep, idx) => { + children: allEndpoints.slice(0, 200).map((ep, idx) => { const scopeLabel = ep.remoteScope === 'public' ? t('scopePublic') @@ -349,11 +364,26 @@ export default function FlowGuardCommand() { ? t('scopeLoopback') : t('scopeListening') const ratio = Math.min(100, Math.max(6, Math.round((ep.groupCount / maxGroupEndpoints) * 100))) + const epSubtitle = ep.pid === 0 + ? `${ep.protocol} ${ep.localAddress}:${ep.localPort} -> ${ep.remoteAddress}:${ep.remotePort} (${scopeLabel} · ${t('kernelTimeWaitHint')})` + : `${ep.protocol} ${ep.localAddress}:${ep.localPort} -> ${ep.remoteAddress}:${ep.remotePort} (${scopeLabel})` + + const copyTupleAction = Action({ + title: t('actionCopyTuple'), + icon: Icon.Clipboard, + shortcut: { modifiers: ['ctrl'], key: 'c' }, + onAction: async () => { + await Clipboard.copy( + `${ep.processName} (PID:${ep.pid}) ${ep.protocol} ${ep.localAddress}:${ep.localPort} -> ${ep.remoteAddress}:${ep.remotePort} [${ep.state}]` + ) + showToast({ style: Toast.Style.Success, title: t('toastCopiedTuple') }) + } + }) return List.Item({ id: `ep-${idx}-${ep.pid}-${ep.localPort}-${ep.remotePort}`, title: `${ep.processName} (PID: ${ep.pid})`, - subtitle: `${ep.protocol} ${ep.localAddress}:${ep.localPort} -> ${ep.remoteAddress}:${ep.remotePort} (${scopeLabel})`, + subtitle: epSubtitle, icon: ep.isProtected ? Icon.Shield : Icon.Globe, accessories: [ { progress: { value: ratio } }, @@ -363,23 +393,17 @@ export default function FlowGuardCommand() { actions: ActionPanel({ title: `${ep.processName} (${ep.localPort})`, children: [ - Action({ - title: t('actionKillProcess'), - icon: Icon.XMarkCircle, - style: 'destructive', - onAction: () => handleKillProcess(ep.groupRef) - }), - Action({ - title: t('actionCopyTuple'), - icon: Icon.Clipboard, - shortcut: { modifiers: ['ctrl'], key: 'c' }, - onAction: async () => { - await Clipboard.copy( - `${ep.processName} (PID:${ep.pid}) ${ep.protocol} ${ep.localAddress}:${ep.localPort} -> ${ep.remoteAddress}:${ep.remotePort} [${ep.state}]` - ) - showToast({ style: Toast.Style.Success, title: t('toastCopiedTuple') }) - } - }), + ...(ep.pid > 0 + ? [ + Action({ + title: t('actionKillProcess'), + icon: Icon.XMarkCircle, + style: 'destructive', + onAction: () => handleKillProcess(ep.groupRef) + }), + copyTupleAction + ] + : [copyTupleAction]), Action({ title: t('actionFilterByProc'), icon: Icon.MagnifyingGlass, diff --git a/extensions/flow-guard/src/logic.ts b/extensions/flow-guard/src/logic.ts index 695077a9..98cdccf5 100644 --- a/extensions/flow-guard/src/logic.ts +++ b/extensions/flow-guard/src/logic.ts @@ -43,6 +43,8 @@ export interface ProcessNetworkGroup { establishedCount: number listeningCount: number publicCount: number + activePublicCount: number + timeWaitCount: number lanCount: number loopbackCount: number endpoints: PortEndpointItem[] @@ -51,6 +53,7 @@ export interface ProcessNetworkGroup { export interface FlowGuardSnapshot { groups: ProcessNetworkGroup[] + activeProcessCount: number totalEndpoints: number totalEstablished: number totalListening: number @@ -62,6 +65,70 @@ export interface FlowGuardSnapshot { error?: string } +const CLOSED_OR_WAIT_STATES = new Set(['TIME_WAIT', 'CLOSED', 'DELETE_TCB']) +const ACTIVE_CLOSING_STATES = new Set(['CLOSE_WAIT', 'FIN_WAIT_1', 'FIN_WAIT_2', 'CLOSING', 'LAST_ACK']) +const KERNEL_IDLE_RAW_NAMES = new Set(['[system process]', 'system idle process', 'idle']) + +function isClosedOrWaitState(state: string): boolean { + return CLOSED_OR_WAIT_STATES.has(state.toUpperCase()) +} + +function getEndpointStateRank(state: string): number { + const st = state.toUpperCase() + if (st === 'ESTABLISHED') return 0 + if (st === 'SYN_SENT' || st === 'SYN_RECV') return 1 + if (ACTIVE_CLOSING_STATES.has(st)) return 2 + if (st === 'LISTENING' || st === 'LISTEN') return 3 + if (st === 'BOUND') return 4 + if (CLOSED_OR_WAIT_STATES.has(st)) return 6 + return 5 +} + +function getScopeRank(scope?: RemoteIpScope): number { + if (scope === 'public') return 0 + if (scope === 'lan') return 1 + if (scope === 'loopback') return 2 + return 3 +} + +function extractPathBasename(filePath: string): string { + const trimmed = String(filePath || '').trim() + if (!trimmed) return '' + const parts = trimmed.split(/[\\/]/) + return parts[parts.length - 1]?.trim() || '' +} + +/** + * 规范化进程显示名: + * - PID 0(Windows 内核接管的 TIME_WAIT 待回收连接)统一显示为 System Idle Process + * - PID 4 兜底显示为 System + * - 真实进程名直接保留宿主/系统返回的准确名称,不再错误追加 .exe(避免污染 System/Registry 等内核进程名) + */ +export function resolveProcessName( + pid: number, + endpointName?: string, + procInfo?: { name: string; path: string } +): string { + const epName = String(endpointName || '').trim() + const snapName = String(procInfo?.name || '').trim() + const pathName = extractPathBasename(procInfo?.path || '') + const candidate = epName || snapName || pathName + + if (pid === 0) { + if (!candidate || KERNEL_IDLE_RAW_NAMES.has(candidate.toLowerCase())) { + return 'System Idle Process' + } + return candidate + } + if (pid === 4) { + return candidate || 'System' + } + if (candidate) { + return candidate + } + return `PID-${pid}` +} + export const FORBIDDEN_TARGET_PATTERN = new RegExp('^(?:System|svchost\\.exe|lsass\\.exe|dns\\.exe|csrss\\.exe|services\\.exe)$', 'i') export function getForbiddenReason(): string { return t('forbiddenReason') @@ -114,6 +181,7 @@ export function classifyRemoteIpScope(remoteAddress: string, state: string, prot function emptySnapshot(error: string): FlowGuardSnapshot { return { groups: [], + activeProcessCount: 0, totalEndpoints: 0, totalEstablished: 0, totalListening: 0, @@ -133,31 +201,59 @@ function extractRows(payload: unknown): DynamicBridge[] { return [] } +function mergeProcessRows( + map: Map, + rows: DynamicBridge[] +): void { + for (const p of rows) { + const rawPid = p?.pid ?? p?.processId + const pid = Number(rawPid) + if (!Number.isInteger(pid) || pid < 0) continue + const rawName = typeof p?.name === 'string' + ? p.name.trim() + : typeof p?.processName === 'string' + ? p.processName.trim() + : '' + const rawPath = p?.fieldAvailability?.path === false + ? '' + : typeof p?.path === 'string' + ? p.path.trim() + : typeof p?.executablePath === 'string' + ? p.executablePath.trim() + : '' + const existing = map.get(pid) + if (!existing) { + map.set(pid, { name: rawName, path: rawPath }) + } else { + if (!existing.name && rawName) existing.name = rawName + if (!existing.path && rawPath) existing.path = rawPath + } + } +} + /** * 读取进程名与程序路径:先读带路径的完整快照,读不到再用基础列表。 * 进程信息只用于补充名称和路径,读取失败不影响连接列表。 */ -async function loadProcessInfo(hostOverride?: DynamicBridge): Promise> { +async function loadProcessInfo( + hostOverride?: DynamicBridge +): Promise<{ map: Map; usedBasicList: boolean }> { const map = new Map() const snapshot = await callHostTransport( 'dllplugin_call', { plugin: 'ProcessMonitorPlugin', func: 'GetProcessList', params: {} }, hostOverride ) - let rows = snapshot.ok && !snapshot.data?.error ? extractRows(snapshot.data) : [] - if (rows.length === 0) { + const snapshotRows = snapshot.ok && !snapshot.data?.error ? extractRows(snapshot.data) : [] + mergeProcessRows(map, snapshotRows) + + if (snapshotRows.length === 0) { const basic = await callHostTransport('process_list', {}, hostOverride) - rows = basic.ok ? extractRows(basic.data) : [] + const basicRows = basic.ok ? extractRows(basic.data) : [] + mergeProcessRows(map, basicRows) + return { map, usedBasicList: true } } - for (const p of rows) { - const pid = Number(p?.pid) - if (!Number.isInteger(pid)) continue - map.set(pid, { - name: typeof p?.name === 'string' ? p.name : '', - path: p?.fieldAvailability?.path === false || typeof p?.path !== 'string' ? '' : p.path - }) - } - return map + return { map, usedBasicList: false } } /** @@ -168,7 +264,7 @@ export async function fetchFlowGuardSnapshot(hostOverride?: DynamicBridge): Prom return emptySnapshot(getNotInClientMessage()) } - const [portsRes, procMap] = await Promise.all([ + const [portsRes, procLoaded] = await Promise.all([ callHostTransport('process_list_ports', {}, hostOverride), loadProcessInfo(hostOverride) ]) @@ -178,6 +274,25 @@ export async function fetchFlowGuardSnapshot(hostOverride?: DynamicBridge): Prom } const rawPorts = portsRes.data + const procMap = procLoaded.map + + // 若完整快照漏掉了某些活跃 PID 的进程名,自动补充一次基础进程列表(tasklist / ps),确保尽量显示对应进程名 + if (!procLoaded.usedBasicList) { + const hasUnresolvedActivePid = rawPorts.some((ep) => { + const pid = Number(ep.pid ?? 0) + if (!Number.isInteger(pid) || pid <= 0 || pid === 4) return false + if (typeof ep.processName === 'string' && ep.processName.trim()) return false + const info = procMap.get(pid) + return !(info && (info.name || extractPathBasename(info.path))) + }) + if (hasUnresolvedActivePid) { + const basic = await callHostTransport('process_list', {}, hostOverride) + if (basic.ok) { + mergeProcessRows(procMap, extractRows(basic.data)) + } + } + } + const groupMap = new Map() let totalEstablished = 0 @@ -188,15 +303,15 @@ export async function fetchFlowGuardSnapshot(hostOverride?: DynamicBridge): Prom let totalLoopback = 0 for (const ep of rawPorts) { - const pid = Number(ep.pid || 0) + const rawPid = Number(ep.pid ?? 0) + const pid = Number.isInteger(rawPid) && rawPid >= 0 ? rawPid : 0 const procInfo = procMap.get(pid) - const rawName = String(ep.processName || procInfo?.name || (pid === 4 ? 'System' : `PID-${pid}`)) - const processName = - rawName.toLowerCase().endsWith('.exe') || rawName === 'System' || rawName.startsWith('PID-') ? rawName : `${rawName}.exe` + const processName = resolveProcessName(pid, ep.processName, procInfo) const proto = String(ep.protocol || 'TCP').toUpperCase() const state = String(ep.state || '').toUpperCase() const remoteAddress = String(ep.remoteAddress || '*') const remoteScope = classifyRemoteIpScope(remoteAddress, state, proto) + const closedOrWait = isClosedOrWaitState(state) if (proto === 'UDP') totalUdp += 1 if (state === 'ESTABLISHED') totalEstablished += 1 @@ -216,10 +331,12 @@ export async function fetchFlowGuardSnapshot(hostOverride?: DynamicBridge): Prom establishedCount: 0, listeningCount: 0, publicCount: 0, + activePublicCount: 0, + timeWaitCount: 0, lanCount: 0, loopbackCount: 0, endpoints: [], - isProtected: pid <= 4 || FORBIDDEN_TARGET_PATTERN.test(processName) || FORBIDDEN_TARGET_PATTERN.test(rawName) + isProtected: pid <= 4 || FORBIDDEN_TARGET_PATTERN.test(processName) } groupMap.set(pid, group) } @@ -231,9 +348,15 @@ export async function fetchFlowGuardSnapshot(hostOverride?: DynamicBridge): Prom } if (state === 'ESTABLISHED') group.establishedCount += 1 if (state === 'LISTENING' || state === 'LISTEN') group.listeningCount += 1 - if (remoteScope === 'public') group.publicCount += 1 - else if (remoteScope === 'lan') group.lanCount += 1 - else if (remoteScope === 'loopback') group.loopbackCount += 1 + if (closedOrWait) group.timeWaitCount += 1 + if (remoteScope === 'public') { + group.publicCount += 1 + if (!closedOrWait) group.activePublicCount += 1 + } else if (remoteScope === 'lan') { + group.lanCount += 1 + } else if (remoteScope === 'loopback') { + group.loopbackCount += 1 + } group.endpoints.push({ protocol: proto, @@ -248,14 +371,34 @@ export async function fetchFlowGuardSnapshot(hostOverride?: DynamicBridge): Prom }) } + for (const group of groupMap.values()) { + group.endpoints.sort((a, b) => { + const stateDiff = getEndpointStateRank(a.state) - getEndpointStateRank(b.state) + if (stateDiff !== 0) return stateDiff + const scopeDiff = getScopeRank(a.remoteScope) - getScopeRank(b.remoteScope) + if (scopeDiff !== 0) return scopeDiff + return a.localPort - b.localPort + }) + } + const groups = Array.from(groupMap.values()).sort((a, b) => { - if (b.publicCount !== a.publicCount) return b.publicCount - a.publicCount + // PID 0(Windows 内核托管的 TIME_WAIT 待回收连接)始终沉底,避免挤占真实联网进程的首屏展示 + const aIsKernelZero = a.pid === 0 ? 1 : 0 + const bIsKernelZero = b.pid === 0 ? 1 : 0 + if (aIsKernelZero !== bIsKernelZero) return aIsKernelZero - bIsKernelZero + if (b.activePublicCount !== a.activePublicCount) return b.activePublicCount - a.activePublicCount if (b.establishedCount !== a.establishedCount) return b.establishedCount - a.establishedCount - return b.endpoints.length - a.endpoints.length + if (b.publicCount !== a.publicCount) return b.publicCount - a.publicCount + if (b.listeningCount !== a.listeningCount) return b.listeningCount - a.listeningCount + if (b.endpoints.length !== a.endpoints.length) return b.endpoints.length - a.endpoints.length + return a.pid - b.pid }) + const activeProcessCount = groups.filter((g) => g.pid > 0).length + return { groups, + activeProcessCount, totalEndpoints: rawPorts.length, totalEstablished, totalListening, diff --git a/extensions/flow-guard/src/native-ipc.ts b/extensions/flow-guard/src/native-ipc.ts index 51576b99..13643277 100644 --- a/extensions/flow-guard/src/native-ipc.ts +++ b/extensions/flow-guard/src/native-ipc.ts @@ -174,11 +174,13 @@ function normalizeMethodResult(method: string, payload: DynamicBridge): DynamicB if (method === 'system_get_battery_status') { // 宿主约定 percent 超出 0-100(如 255)表示无电池或电量未知,不能改写成 100% + // 若宿主明确给出 hasBattery 布尔值,必须原样保留,仅在缺失时按合法电量推算 const rawPct = payload.percent - const hasBattery = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const validPct = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const hasBattery = typeof payload.hasBattery === 'boolean' ? payload.hasBattery : validPct return { ...payload, - percent: hasBattery ? rawPct : null, + percent: validPct ? rawPct : null, hasBattery } } @@ -489,6 +491,8 @@ export interface RealDirectoryScanResult extends Iterable approximate?: boolean /** 宿主实际遍历的条目数 */ visitedEntries?: number + /** 目录本身不存在(ENOENT) */ + missing?: boolean /** 读取失败的真实原因;已有文件仍可使用,但不能当作完整结果。 */ error?: string } @@ -497,6 +501,7 @@ interface ScanResultMeta { truncated?: boolean approximate?: boolean visitedEntries?: number + missing?: boolean } export interface ScanDirectoryTreeOptions { @@ -504,6 +509,10 @@ export interface ScanDirectoryTreeOptions { maxFiles?: number collectTopN?: number filterExt?: RegExp + /** 为 true 时,目录本身不存在(ENOENT)按空目录处理,不返回 error(权限拒绝/读取失败仍照常报错) */ + ignoreMissing?: boolean + /** Top-N 保留与排序方式:默认按体积降序,下载/录屏等时效场景可传 mtime-desc */ + sortBy?: 'size-desc' | 'mtime-desc' hostOverride?: DynamicBridge } @@ -519,8 +528,9 @@ function normalizeIndexedFileEntry(f: DynamicBridge): RealIndexedFileEntry { const sz = Number(f?.size ?? f?.sizeBytes ?? 0) const isDir = Boolean(f?.is_dir || f?.isDir || f?.isDirectory) const rawMtime = Number(f?.mtime ?? f?.mtimeMs ?? 0) - const mtimeMs = rawMtime > 1e11 ? rawMtime : rawMtime > 0 ? rawMtime * 1000 : Date.now() - const mtimeSec = rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime + const validMtime = Number.isFinite(rawMtime) && rawMtime > 0 + const mtimeMs = validMtime ? (rawMtime > 1e11 ? rawMtime : rawMtime * 1000) : 0 + const mtimeSec = validMtime ? (rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime) : 0 if (p && sz >= 0) realFileSizeCache.set(p, sz) return { name, @@ -551,6 +561,7 @@ function makeScanResult( subdirs, ...(meta.truncated ? { truncated: true } : {}), ...(meta.approximate ? { approximate: true } : {}), + ...(meta.missing ? { missing: true } : {}), ...(typeof meta.visitedEntries === 'number' ? { visitedEntries: meta.visitedEntries } : {}), [Symbol.iterator]() { return files[Symbol.iterator]() @@ -609,13 +620,40 @@ export async function scanRealDirectoryTree( return result.error ? { ...result.scan, error: result.error } : result.scan } +/** 仅当正则明确声明了扩展名(含 `\.`)时提取后缀列表,避免把 `thumbcache|iconcache` 等文件名关键词误拆成假扩展名 */ +function extractExtensionTokensFromFilter(filterExt: RegExp): string[] { + const src = filterExt.source + if (!src.includes('\\.')) return [] + const afterDot = src.slice(src.indexOf('\\.') + 2) + const rawTokens = afterDot.match(/[a-z0-9]{1,8}/gi) || [] + const seen = new Set() + const out: string[] = [] + for (const token of rawTokens) { + const lower = token.toLowerCase() + if (!lower || seen.has(lower)) continue + seen.add(lower) + out.push(lower) + } + return out +} + +function isMissingDirectoryError(res: { error?: string; errorCode?: string; errorDetails?: Record }): boolean { + if (res.errorDetails?.reason === 'ENOENT' || res.errorCode === 'ENOENT') return true + const msg = String(res.error || '') + return /Directory does not exist|ENOENT/i.test(msg) +} + /** 一次界面扫描的错误汇总;多个目录并行扫描时保留可读目录的结果。 */ export function createDirectoryScanner(hostOverride?: DynamicBridge) { const failures = new Map() return { async scan(dir: string, options: number | ScanDirectoryTreeOptions = 160) { const result = await scanRealDirectoryTree(dir, options, hostOverride) - const error = result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') + const ignoreMissing = typeof options === 'object' && options !== null && options.ignoreMissing === true + const error = + result.missing && ignoreMissing + ? '' + : result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') if (error) failures.set(dir, error) else failures.delete(dir) return result @@ -648,26 +686,38 @@ async function scanDirectoryTreeWithError( const safeLimit = Math.min(200, Math.max(1, Math.floor(rawLimit || 160))) const hostOverride = opts.hostOverride const filterExt = opts.filterExt + const ignoreMissing = opts.ignoreMissing === true const dirQuery = `dir:${targetDir}` try { let rawPayload: DynamicBridge = null + const searchParams: Record = { + query: dirQuery, + limit: safeLimit, + ...(opts.sortBy ? { sortBy: opts.sortBy } : {}) + } const res = await callHostTransport( 'system_search_files', - { query: dirQuery, limit: safeLimit }, + searchParams, hostOverride ) - if (res.ok && res.data) { + if (res.ok && res.data && res.data.degraded !== true) { rawPayload = res.data + } else if (!res.ok && ignoreMissing && isMissingDirectoryError(res)) { + const missingScan = makeScanResult([], 0, 0, [], { missing: true }) + return { scan: missingScan } } - if (!rawPayload && !hostOverride && typeof window !== 'undefined') { + if (!rawPayload && !hostOverride && res.errorCode === 'METHOD_NOT_AVAILABLE' && typeof window !== 'undefined') { const w = window as DynamicBridge if (typeof w.__ztoolsLauncher?.searchFiles === 'function') { const rawOuter = await w.__ztoolsLauncher.searchFiles(dirQuery, safeLimit) - rawPayload = + const candidate = rawOuter && typeof rawOuter === 'object' && 'data' in rawOuter && rawOuter.data ? rawOuter.data : rawOuter + if (candidate && candidate.degraded !== true && candidate.success !== false) { + rawPayload = candidate + } } } @@ -678,29 +728,32 @@ async function scanDirectoryTreeWithError( let files: RealIndexedFileEntry[] = rawPayload.files.map(normalizeIndexedFileEntry) if (filterExt instanceof RegExp) { files = files.filter(f => !f.isDir && (filterExt.test(f.name) || filterExt.test(f.ext))) - // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索目标扩展名 + // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索明确声明的目标扩展名 if (files.length === 0 && !hostOverride) { - const extTokens = (filterExt.source.match(/[a-z0-9]{2,5}/gi) || []) - .filter(t => !['thumbcache', 'iconcache'].includes(t.toLowerCase())) - .slice(0, 4) - // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 - const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() - const extraLists = await Promise.all( - extTokens.map(ext => searchRealIndexedFiles(`.${ext.toLowerCase()}`, 30, hostOverride)) - ) - const seen = new Set() - for (const list of extraLists) { - for (const item of list) { - if (!item.isDir && item.size > 0 && !seen.has(item.path)) { - if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { - seen.add(item.path) - files.push(item) + const extTokens = extractExtensionTokensFromFilter(filterExt) + if (extTokens.length > 0) { + // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 + const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() + const extraLists = await Promise.all( + extTokens.map(ext => searchRealIndexedFiles(`.${ext}`, 30, hostOverride)) + ) + const seen = new Set() + for (const list of extraLists) { + for (const item of list) { + if (!item.isDir && item.size > 0 && !seen.has(item.path)) { + if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { + seen.add(item.path) + files.push(item) + } } } } } } } + // 先基于过滤后的完整命中集合计算总文件数与总字节数,再按 collectTopN 裁剪样本列表 + const matchedCount = files.length + const matchedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) if (typeof opts.collectTopN === 'number' && opts.collectTopN > 0 && files.length > opts.collectTopN) { files = files.slice(0, opts.collectTopN) } @@ -714,11 +767,10 @@ async function scanDirectoryTreeWithError( ...(s.approximate === true ? { approximate: true } : {}) })) : [] - const computedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) const totalFilesCount = - filterExt instanceof RegExp ? files.length : Number(rawPayload.total_matches ?? files.length) + filterExt instanceof RegExp ? matchedCount : Number(rawPayload.total_matches ?? matchedCount) const totalBytesCount = - filterExt instanceof RegExp ? computedBytes : Number(rawPayload.total_bytes ?? computedBytes) + filterExt instanceof RegExp ? matchedBytes : Number(rawPayload.total_bytes ?? matchedBytes) const visited = Number(rawPayload.visited_entries) return { scan: makeScanResult(files, totalFilesCount, totalBytesCount, subdirs, { @@ -1817,8 +1869,6 @@ export async function writeRealClipboardText(text: string, hostOverride?: Dynami const payload = { text: String(text || '') } const res = await callHostTransport('clipboard_copy_text', payload, hostOverride) if (res.ok) return true - const fallbackRes = await callHostTransport('clipboard_write_text', payload, hostOverride) - if (fallbackRes.ok) return true try { if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) { await navigator.clipboard.writeText(String(text || '')) diff --git a/extensions/flow-guard/tests/flow-guard.host.test.mjs b/extensions/flow-guard/tests/flow-guard.host.test.mjs index 1b2babda..07417ef7 100644 --- a/extensions/flow-guard/tests/flow-guard.host.test.mjs +++ b/extensions/flow-guard/tests/flow-guard.host.test.mjs @@ -8,6 +8,7 @@ const { default: FlowGuardCommand, getNotInClientMessage, fetchFlowGuardSnapshot, + resolveProcessName, terminateNetworkProcess, openNetworkProcessLocation } = await import('../dist/index.js') @@ -148,3 +149,112 @@ test('flow-guard: 定位程序失败或不在客户端里时返回 false', async } assert.equal(await openNetworkProcessLocation('C:\\Tools\\curl.exe', failing), false) }) + +test('flow-guard: 大量 PID 0 (TIME_WAIT) 沉底且规范命名,真实活跃联网进程排在最前并显示进程名', async () => { + const timeWaitPorts = Array.from({ length: 15 }, (_, idx) => ({ + protocol: 'TCP', + localAddress: '198.18.0.1', + localPort: 50000 + idx, + remoteAddress: `106.52.160.${10 + idx}`, + remotePort: 443, + state: 'TIME_WAIT', + pid: 0, + processName: '' + })) + const chromeEstablished = { + protocol: 'TCP', + localAddress: '192.168.1.10', + localPort: 51001, + remoteAddress: '142.250.72.14', + remotePort: 443, + state: 'ESTABLISHED', + pid: 2048, + processName: '' + } + const chromeTimeWait = { + protocol: 'TCP', + localAddress: '192.168.1.10', + localPort: 51002, + remoteAddress: '142.250.72.15', + remotePort: 443, + state: 'TIME_WAIT', + pid: 2048, + processName: '' + } + const systemListen = { + protocol: 'TCP', + localAddress: '0.0.0.0', + localPort: 445, + remoteAddress: '0.0.0.0', + remotePort: 0, + state: 'LISTENING', + pid: 4, + processName: '' + } + + const snap = await fetchFlowGuardSnapshot({ + process_list_ports: async () => ({ + success: true, + data: [...timeWaitPorts, chromeTimeWait, systemListen, chromeEstablished], + source: 'windows-netstat' + }), + dllplugin_call: async () => ({ + success: true, + data: { + processes: [ + { pid: 0, name: '[System Process]', path: '' }, + { pid: 4, name: 'System', path: '' }, + { pid: 2048, name: 'chrome.exe', path: 'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe' } + ] + } + }) + }) + + assert.equal(snap.error, undefined) + assert.equal(snap.activeProcessCount, 2) + assert.equal(snap.groups.length, 3) + // 真实公网已建立进程排第一,System 监听排第二,PID 0(尽管公网 TIME_WAIT 数量最多)必须沉底 + assert.deepEqual(snap.groups.map((g) => g.pid), [2048, 4, 0]) + assert.equal(snap.groups[0].processName, 'chrome.exe') + assert.equal(snap.groups[0].endpoints[0].state, 'ESTABLISHED') + assert.equal(snap.groups[0].endpoints[1].state, 'TIME_WAIT') + assert.equal(snap.groups[1].processName, 'System') + assert.equal(snap.groups[2].processName, 'System Idle Process') + assert.equal(snap.groups[2].timeWaitCount, 15) + assert.equal(snap.groups[2].activePublicCount, 0) +}) + +test('flow-guard: 完整快照缺漏部分活跃 PID 时自动用 process_list 补齐进程名,且不给系统进程误加 .exe', async () => { + let basicCalls = 0 + const snap = await fetchFlowGuardSnapshot({ + process_list_ports: async () => [ + { protocol: 'TCP', localAddress: '127.0.0.1', localPort: 7890, remoteAddress: '1.1.1.1', remotePort: 443, state: 'ESTABLISHED', pid: 3301, processName: '' }, + { protocol: 'TCP', localAddress: '127.0.0.1', localPort: 8080, remoteAddress: '0.0.0.0', remotePort: 0, state: 'LISTENING', pid: 3302, processName: '' }, + { protocol: 'TCP', localAddress: '127.0.0.1', localPort: 9090, remoteAddress: '0.0.0.0', remotePort: 0, state: 'LISTENING', pid: 3303, processName: '' } + ], + dllplugin_call: async () => ({ + success: true, + data: { + processes: [ + { pid: 3301, name: '', path: 'D:\\Apps\\mihomo.exe' } + ] + } + }), + process_list: async () => { + basicCalls += 1 + return [ + { pid: 3302, name: 'node.exe', path: '' }, + { pid: 3303, name: 'Registry', path: '' } + ] + } + }) + + assert.equal(basicCalls, 1) + const byPid = new Map(snap.groups.map((g) => [g.pid, g.processName])) + assert.equal(byPid.get(3301), 'mihomo.exe') + assert.equal(byPid.get(3302), 'node.exe') + assert.equal(byPid.get(3303), 'Registry') + assert.equal(resolveProcessName(0, '', undefined), 'System Idle Process') + assert.equal(resolveProcessName(4, '', undefined), 'System') + assert.equal(resolveProcessName(99999, '', undefined), 'PID-99999') +}) diff --git a/extensions/folder-sync/README.en.md b/extensions/folder-sync/README.en.md new file mode 100644 index 00000000..7089b124 --- /dev/null +++ b/extensions/folder-sync/README.en.md @@ -0,0 +1,27 @@ +# Folder Sync + +Compare regular file contents between two folders and copy differences to the other side; before overwriting or moving files to Trash (macOS mirror mode only), save and verify backups of the original files. + +## Usage + +- **Commands**: `folder sync`, `directory sync`, `incremental backup`, `compare folders`. +- **Workflow**: Click "Select Folders" at the top to pick the source and target folders in turn (they cannot be identical or nested inside one another), choose a sync mode on the left, and click "Re-compare". The right pane lists files to add, overwrite, move to Trash (mirror mode), and conflicts. +- **Sync Modes**: + - **One-way Incremental**: Copies new and changed files from source to target. + - **Two-way Merge**: Copies files unique to each side to the other; when a file exists on both sides with different contents, direction is chosen by modification time (if timestamps differ by 2 seconds or less, it is marked as a conflict). + - **Mirror (macOS only)**: Also moves files unique to the target folder to Trash (not shown on Windows). +- **Shortcuts**: `Space` checks/unchecks a file, `Enter` executes checked items, and `⌘/Ctrl+Enter` reveals the file in the file manager. Files to be moved to Trash must be checked manually. Conflicting files cannot be executed and must be resolved manually before re-comparing. +- **Default Ignores**: `.git`, `node_modules`, `.DS_Store`, and `Thumbs.db` are ignored by default and can be toggled off on the left. +- **Safety Checks**: Both sides are re-scanned before execution. Any file changes since comparison, symlinks, read errors, or backup failures stop the run and report both completed and remaining counts; completed writes are not automatically rolled back, and original files can be restored from backups. +- **Backups**: Backups are saved under `.ztools-sync-backups//` in the root of the modified folder: `backup/` holds copies of original files from comparison time, `original/` holds original files moved out during execution, and `incoming/` holds content not yet written. After execution, you can open the backup folder from the action panel and follow the recovery instructions file (`恢复说明.txt`) to copy files back to the same relative paths. Backups are not cleaned up automatically, and `.ztools-sync-backups` at the root is excluded from sync. +- **Limits**: Syncs regular files only and does not replicate empty folders. Maximum single file size is 2 GiB, and each side scans at most 5,000 items and 48 directory levels. + +## Platforms & Requirements + +- Supported: Windows, macOS (Mirror mode is macOS only) +- Requires client version 1.1.8.5 or later. +- Requires the client's safe file access component; if missing, an unavailable-component notice is shown. + +## Network & Data + +- Offline only; all data stays on your device. diff --git a/extensions/folder-sync/plugin.json b/extensions/folder-sync/plugin.json index 3fc411cd..3f8368b0 100644 --- a/extensions/folder-sync/plugin.json +++ b/extensions/folder-sync/plugin.json @@ -1,7 +1,7 @@ { "id": "folder-sync", "name": "目录同步", - "version": "1.0.10", + "version": "1.0.11", "description": "比对普通文件内容后增量或双向同步,覆盖前保留校验备份;macOS 另支持镜像模式,把目标独有文件移入废纸篓(单文件最大 2 GiB)", "author": "ZTools Team", "entry": "dist/index.js", @@ -63,7 +63,12 @@ "directory sync", "backup", "incremental", - "compare folders" + "compare folders", + "backup folder", + "mirror", + "sync files", + "rsync", + "two-way sync" ], "features": { "folder-sync-workbench": { @@ -98,5 +103,14 @@ { "path": "screenshots/02-action-panel.png" } + ], + "keywords": [ + "目录同步", + "文件夹同步", + "备份文件夹", + "双向同步", + "增量同步", + "镜像备份", + "同步目录" ] } diff --git a/extensions/folder-sync/src/native-ipc.ts b/extensions/folder-sync/src/native-ipc.ts index 51576b99..13643277 100644 --- a/extensions/folder-sync/src/native-ipc.ts +++ b/extensions/folder-sync/src/native-ipc.ts @@ -174,11 +174,13 @@ function normalizeMethodResult(method: string, payload: DynamicBridge): DynamicB if (method === 'system_get_battery_status') { // 宿主约定 percent 超出 0-100(如 255)表示无电池或电量未知,不能改写成 100% + // 若宿主明确给出 hasBattery 布尔值,必须原样保留,仅在缺失时按合法电量推算 const rawPct = payload.percent - const hasBattery = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const validPct = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const hasBattery = typeof payload.hasBattery === 'boolean' ? payload.hasBattery : validPct return { ...payload, - percent: hasBattery ? rawPct : null, + percent: validPct ? rawPct : null, hasBattery } } @@ -489,6 +491,8 @@ export interface RealDirectoryScanResult extends Iterable approximate?: boolean /** 宿主实际遍历的条目数 */ visitedEntries?: number + /** 目录本身不存在(ENOENT) */ + missing?: boolean /** 读取失败的真实原因;已有文件仍可使用,但不能当作完整结果。 */ error?: string } @@ -497,6 +501,7 @@ interface ScanResultMeta { truncated?: boolean approximate?: boolean visitedEntries?: number + missing?: boolean } export interface ScanDirectoryTreeOptions { @@ -504,6 +509,10 @@ export interface ScanDirectoryTreeOptions { maxFiles?: number collectTopN?: number filterExt?: RegExp + /** 为 true 时,目录本身不存在(ENOENT)按空目录处理,不返回 error(权限拒绝/读取失败仍照常报错) */ + ignoreMissing?: boolean + /** Top-N 保留与排序方式:默认按体积降序,下载/录屏等时效场景可传 mtime-desc */ + sortBy?: 'size-desc' | 'mtime-desc' hostOverride?: DynamicBridge } @@ -519,8 +528,9 @@ function normalizeIndexedFileEntry(f: DynamicBridge): RealIndexedFileEntry { const sz = Number(f?.size ?? f?.sizeBytes ?? 0) const isDir = Boolean(f?.is_dir || f?.isDir || f?.isDirectory) const rawMtime = Number(f?.mtime ?? f?.mtimeMs ?? 0) - const mtimeMs = rawMtime > 1e11 ? rawMtime : rawMtime > 0 ? rawMtime * 1000 : Date.now() - const mtimeSec = rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime + const validMtime = Number.isFinite(rawMtime) && rawMtime > 0 + const mtimeMs = validMtime ? (rawMtime > 1e11 ? rawMtime : rawMtime * 1000) : 0 + const mtimeSec = validMtime ? (rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime) : 0 if (p && sz >= 0) realFileSizeCache.set(p, sz) return { name, @@ -551,6 +561,7 @@ function makeScanResult( subdirs, ...(meta.truncated ? { truncated: true } : {}), ...(meta.approximate ? { approximate: true } : {}), + ...(meta.missing ? { missing: true } : {}), ...(typeof meta.visitedEntries === 'number' ? { visitedEntries: meta.visitedEntries } : {}), [Symbol.iterator]() { return files[Symbol.iterator]() @@ -609,13 +620,40 @@ export async function scanRealDirectoryTree( return result.error ? { ...result.scan, error: result.error } : result.scan } +/** 仅当正则明确声明了扩展名(含 `\.`)时提取后缀列表,避免把 `thumbcache|iconcache` 等文件名关键词误拆成假扩展名 */ +function extractExtensionTokensFromFilter(filterExt: RegExp): string[] { + const src = filterExt.source + if (!src.includes('\\.')) return [] + const afterDot = src.slice(src.indexOf('\\.') + 2) + const rawTokens = afterDot.match(/[a-z0-9]{1,8}/gi) || [] + const seen = new Set() + const out: string[] = [] + for (const token of rawTokens) { + const lower = token.toLowerCase() + if (!lower || seen.has(lower)) continue + seen.add(lower) + out.push(lower) + } + return out +} + +function isMissingDirectoryError(res: { error?: string; errorCode?: string; errorDetails?: Record }): boolean { + if (res.errorDetails?.reason === 'ENOENT' || res.errorCode === 'ENOENT') return true + const msg = String(res.error || '') + return /Directory does not exist|ENOENT/i.test(msg) +} + /** 一次界面扫描的错误汇总;多个目录并行扫描时保留可读目录的结果。 */ export function createDirectoryScanner(hostOverride?: DynamicBridge) { const failures = new Map() return { async scan(dir: string, options: number | ScanDirectoryTreeOptions = 160) { const result = await scanRealDirectoryTree(dir, options, hostOverride) - const error = result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') + const ignoreMissing = typeof options === 'object' && options !== null && options.ignoreMissing === true + const error = + result.missing && ignoreMissing + ? '' + : result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') if (error) failures.set(dir, error) else failures.delete(dir) return result @@ -648,26 +686,38 @@ async function scanDirectoryTreeWithError( const safeLimit = Math.min(200, Math.max(1, Math.floor(rawLimit || 160))) const hostOverride = opts.hostOverride const filterExt = opts.filterExt + const ignoreMissing = opts.ignoreMissing === true const dirQuery = `dir:${targetDir}` try { let rawPayload: DynamicBridge = null + const searchParams: Record = { + query: dirQuery, + limit: safeLimit, + ...(opts.sortBy ? { sortBy: opts.sortBy } : {}) + } const res = await callHostTransport( 'system_search_files', - { query: dirQuery, limit: safeLimit }, + searchParams, hostOverride ) - if (res.ok && res.data) { + if (res.ok && res.data && res.data.degraded !== true) { rawPayload = res.data + } else if (!res.ok && ignoreMissing && isMissingDirectoryError(res)) { + const missingScan = makeScanResult([], 0, 0, [], { missing: true }) + return { scan: missingScan } } - if (!rawPayload && !hostOverride && typeof window !== 'undefined') { + if (!rawPayload && !hostOverride && res.errorCode === 'METHOD_NOT_AVAILABLE' && typeof window !== 'undefined') { const w = window as DynamicBridge if (typeof w.__ztoolsLauncher?.searchFiles === 'function') { const rawOuter = await w.__ztoolsLauncher.searchFiles(dirQuery, safeLimit) - rawPayload = + const candidate = rawOuter && typeof rawOuter === 'object' && 'data' in rawOuter && rawOuter.data ? rawOuter.data : rawOuter + if (candidate && candidate.degraded !== true && candidate.success !== false) { + rawPayload = candidate + } } } @@ -678,29 +728,32 @@ async function scanDirectoryTreeWithError( let files: RealIndexedFileEntry[] = rawPayload.files.map(normalizeIndexedFileEntry) if (filterExt instanceof RegExp) { files = files.filter(f => !f.isDir && (filterExt.test(f.name) || filterExt.test(f.ext))) - // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索目标扩展名 + // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索明确声明的目标扩展名 if (files.length === 0 && !hostOverride) { - const extTokens = (filterExt.source.match(/[a-z0-9]{2,5}/gi) || []) - .filter(t => !['thumbcache', 'iconcache'].includes(t.toLowerCase())) - .slice(0, 4) - // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 - const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() - const extraLists = await Promise.all( - extTokens.map(ext => searchRealIndexedFiles(`.${ext.toLowerCase()}`, 30, hostOverride)) - ) - const seen = new Set() - for (const list of extraLists) { - for (const item of list) { - if (!item.isDir && item.size > 0 && !seen.has(item.path)) { - if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { - seen.add(item.path) - files.push(item) + const extTokens = extractExtensionTokensFromFilter(filterExt) + if (extTokens.length > 0) { + // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 + const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() + const extraLists = await Promise.all( + extTokens.map(ext => searchRealIndexedFiles(`.${ext}`, 30, hostOverride)) + ) + const seen = new Set() + for (const list of extraLists) { + for (const item of list) { + if (!item.isDir && item.size > 0 && !seen.has(item.path)) { + if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { + seen.add(item.path) + files.push(item) + } } } } } } } + // 先基于过滤后的完整命中集合计算总文件数与总字节数,再按 collectTopN 裁剪样本列表 + const matchedCount = files.length + const matchedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) if (typeof opts.collectTopN === 'number' && opts.collectTopN > 0 && files.length > opts.collectTopN) { files = files.slice(0, opts.collectTopN) } @@ -714,11 +767,10 @@ async function scanDirectoryTreeWithError( ...(s.approximate === true ? { approximate: true } : {}) })) : [] - const computedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) const totalFilesCount = - filterExt instanceof RegExp ? files.length : Number(rawPayload.total_matches ?? files.length) + filterExt instanceof RegExp ? matchedCount : Number(rawPayload.total_matches ?? matchedCount) const totalBytesCount = - filterExt instanceof RegExp ? computedBytes : Number(rawPayload.total_bytes ?? computedBytes) + filterExt instanceof RegExp ? matchedBytes : Number(rawPayload.total_bytes ?? matchedBytes) const visited = Number(rawPayload.visited_entries) return { scan: makeScanResult(files, totalFilesCount, totalBytesCount, subdirs, { @@ -1817,8 +1869,6 @@ export async function writeRealClipboardText(text: string, hostOverride?: Dynami const payload = { text: String(text || '') } const res = await callHostTransport('clipboard_copy_text', payload, hostOverride) if (res.ok) return true - const fallbackRes = await callHostTransport('clipboard_write_text', payload, hostOverride) - if (fallbackRes.ok) return true try { if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) { await navigator.clipboard.writeText(String(text || '')) diff --git a/extensions/font-manager/README.en.md b/extensions/font-manager/README.en.md new file mode 100644 index 00000000..ac9da34c --- /dev/null +++ b/extensions/font-manager/README.en.md @@ -0,0 +1,21 @@ +# Font Manager + +Search locally installed fonts, preview real glyphs with custom text, and inspect embedded license and copyright metadata in font files. + +## Usage + +- **Commands**: Font Manager (keywords such as `fonts`, `font manager`, `font preview`), Font License (`font license`, `embedded license metadata`), and Fonts Without License Metadata (`no license metadata`, `font copyright`). The latter two pre-filter for fonts with or without embedded license metadata respectively. +- **Filtering**: Filter by font name or style in the search box, and use the adjacent dropdown to switch between All Fonts, With License Info, Without License Info, and System Fonts. +- **Preview**: The right pane renders a preview image using the selected font. If the font lacks glyphs for part of your text, a notice is shown (on macOS, system fallback fonts used are listed; characters missing from all local fonts render as placeholder boxes with a note). Click "Set Preview Text" at the top to customize the sample text (up to 160 characters). +- **Shortcuts**: `Enter` copies the font name, `⌘/Ctrl+Enter` copies a CSS `font-family` declaration, and `⌘/Ctrl+K` opens the action panel (reveal font file, view license info). +- **License Info**: Displays the raw license text, copyright notice, and manufacturer metadata embedded in the font file; this metadata alone cannot determine whether free commercial use is permitted. +- Does not install or uninstall fonts. + +## Platforms & Requirements + +- Supported: Windows, macOS +- Requires client version 1.1.8.5 or later. + +## Network & Data + +- Offline only; all data stays on your device. Clicking "Open Font License URL" on the license details page opens the URL embedded in the font file in your default browser. diff --git a/extensions/font-manager/plugin.json b/extensions/font-manager/plugin.json index 54a7c917..67812060 100644 --- a/extensions/font-manager/plugin.json +++ b/extensions/font-manager/plugin.json @@ -1,7 +1,7 @@ { "id": "font-manager", "name": "字体管理", - "version": "1.0.8", + "version": "1.0.9", "description": "检索本机已安装字体,输入文字查看真实字形,查看字体文件附带的许可与版权说明。", "author": "ZTools Team", "category": [ @@ -71,7 +71,12 @@ "typography", "font preview", "system fonts", - "license" + "license", + "font", + "font manager", + "typeface", + "preview font", + "installed fonts" ], "features": { "font-manager-all": { @@ -117,5 +122,15 @@ { "path": "screenshots/03-interactive.png" } + ], + "keywords": [ + "字体管理", + "看字体", + "预览字体", + "已装字体", + "找字体", + "字体预览", + "系统字体", + "fonts" ] } diff --git a/extensions/font-manager/src/index.tsx b/extensions/font-manager/src/index.tsx index 304d4394..565ddb5d 100644 --- a/extensions/font-manager/src/index.tsx +++ b/extensions/font-manager/src/index.tsx @@ -26,7 +26,7 @@ export function PreviewTextForm({ initial, save }: { initial: string; save: (tex catch (error) { await showToast(Toast.Style.Failure, errorText(error)) } } return
}> - + } diff --git a/extensions/font-manager/src/native-ipc.ts b/extensions/font-manager/src/native-ipc.ts index 51576b99..13643277 100644 --- a/extensions/font-manager/src/native-ipc.ts +++ b/extensions/font-manager/src/native-ipc.ts @@ -174,11 +174,13 @@ function normalizeMethodResult(method: string, payload: DynamicBridge): DynamicB if (method === 'system_get_battery_status') { // 宿主约定 percent 超出 0-100(如 255)表示无电池或电量未知,不能改写成 100% + // 若宿主明确给出 hasBattery 布尔值,必须原样保留,仅在缺失时按合法电量推算 const rawPct = payload.percent - const hasBattery = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const validPct = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const hasBattery = typeof payload.hasBattery === 'boolean' ? payload.hasBattery : validPct return { ...payload, - percent: hasBattery ? rawPct : null, + percent: validPct ? rawPct : null, hasBattery } } @@ -489,6 +491,8 @@ export interface RealDirectoryScanResult extends Iterable approximate?: boolean /** 宿主实际遍历的条目数 */ visitedEntries?: number + /** 目录本身不存在(ENOENT) */ + missing?: boolean /** 读取失败的真实原因;已有文件仍可使用,但不能当作完整结果。 */ error?: string } @@ -497,6 +501,7 @@ interface ScanResultMeta { truncated?: boolean approximate?: boolean visitedEntries?: number + missing?: boolean } export interface ScanDirectoryTreeOptions { @@ -504,6 +509,10 @@ export interface ScanDirectoryTreeOptions { maxFiles?: number collectTopN?: number filterExt?: RegExp + /** 为 true 时,目录本身不存在(ENOENT)按空目录处理,不返回 error(权限拒绝/读取失败仍照常报错) */ + ignoreMissing?: boolean + /** Top-N 保留与排序方式:默认按体积降序,下载/录屏等时效场景可传 mtime-desc */ + sortBy?: 'size-desc' | 'mtime-desc' hostOverride?: DynamicBridge } @@ -519,8 +528,9 @@ function normalizeIndexedFileEntry(f: DynamicBridge): RealIndexedFileEntry { const sz = Number(f?.size ?? f?.sizeBytes ?? 0) const isDir = Boolean(f?.is_dir || f?.isDir || f?.isDirectory) const rawMtime = Number(f?.mtime ?? f?.mtimeMs ?? 0) - const mtimeMs = rawMtime > 1e11 ? rawMtime : rawMtime > 0 ? rawMtime * 1000 : Date.now() - const mtimeSec = rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime + const validMtime = Number.isFinite(rawMtime) && rawMtime > 0 + const mtimeMs = validMtime ? (rawMtime > 1e11 ? rawMtime : rawMtime * 1000) : 0 + const mtimeSec = validMtime ? (rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime) : 0 if (p && sz >= 0) realFileSizeCache.set(p, sz) return { name, @@ -551,6 +561,7 @@ function makeScanResult( subdirs, ...(meta.truncated ? { truncated: true } : {}), ...(meta.approximate ? { approximate: true } : {}), + ...(meta.missing ? { missing: true } : {}), ...(typeof meta.visitedEntries === 'number' ? { visitedEntries: meta.visitedEntries } : {}), [Symbol.iterator]() { return files[Symbol.iterator]() @@ -609,13 +620,40 @@ export async function scanRealDirectoryTree( return result.error ? { ...result.scan, error: result.error } : result.scan } +/** 仅当正则明确声明了扩展名(含 `\.`)时提取后缀列表,避免把 `thumbcache|iconcache` 等文件名关键词误拆成假扩展名 */ +function extractExtensionTokensFromFilter(filterExt: RegExp): string[] { + const src = filterExt.source + if (!src.includes('\\.')) return [] + const afterDot = src.slice(src.indexOf('\\.') + 2) + const rawTokens = afterDot.match(/[a-z0-9]{1,8}/gi) || [] + const seen = new Set() + const out: string[] = [] + for (const token of rawTokens) { + const lower = token.toLowerCase() + if (!lower || seen.has(lower)) continue + seen.add(lower) + out.push(lower) + } + return out +} + +function isMissingDirectoryError(res: { error?: string; errorCode?: string; errorDetails?: Record }): boolean { + if (res.errorDetails?.reason === 'ENOENT' || res.errorCode === 'ENOENT') return true + const msg = String(res.error || '') + return /Directory does not exist|ENOENT/i.test(msg) +} + /** 一次界面扫描的错误汇总;多个目录并行扫描时保留可读目录的结果。 */ export function createDirectoryScanner(hostOverride?: DynamicBridge) { const failures = new Map() return { async scan(dir: string, options: number | ScanDirectoryTreeOptions = 160) { const result = await scanRealDirectoryTree(dir, options, hostOverride) - const error = result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') + const ignoreMissing = typeof options === 'object' && options !== null && options.ignoreMissing === true + const error = + result.missing && ignoreMissing + ? '' + : result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') if (error) failures.set(dir, error) else failures.delete(dir) return result @@ -648,26 +686,38 @@ async function scanDirectoryTreeWithError( const safeLimit = Math.min(200, Math.max(1, Math.floor(rawLimit || 160))) const hostOverride = opts.hostOverride const filterExt = opts.filterExt + const ignoreMissing = opts.ignoreMissing === true const dirQuery = `dir:${targetDir}` try { let rawPayload: DynamicBridge = null + const searchParams: Record = { + query: dirQuery, + limit: safeLimit, + ...(opts.sortBy ? { sortBy: opts.sortBy } : {}) + } const res = await callHostTransport( 'system_search_files', - { query: dirQuery, limit: safeLimit }, + searchParams, hostOverride ) - if (res.ok && res.data) { + if (res.ok && res.data && res.data.degraded !== true) { rawPayload = res.data + } else if (!res.ok && ignoreMissing && isMissingDirectoryError(res)) { + const missingScan = makeScanResult([], 0, 0, [], { missing: true }) + return { scan: missingScan } } - if (!rawPayload && !hostOverride && typeof window !== 'undefined') { + if (!rawPayload && !hostOverride && res.errorCode === 'METHOD_NOT_AVAILABLE' && typeof window !== 'undefined') { const w = window as DynamicBridge if (typeof w.__ztoolsLauncher?.searchFiles === 'function') { const rawOuter = await w.__ztoolsLauncher.searchFiles(dirQuery, safeLimit) - rawPayload = + const candidate = rawOuter && typeof rawOuter === 'object' && 'data' in rawOuter && rawOuter.data ? rawOuter.data : rawOuter + if (candidate && candidate.degraded !== true && candidate.success !== false) { + rawPayload = candidate + } } } @@ -678,29 +728,32 @@ async function scanDirectoryTreeWithError( let files: RealIndexedFileEntry[] = rawPayload.files.map(normalizeIndexedFileEntry) if (filterExt instanceof RegExp) { files = files.filter(f => !f.isDir && (filterExt.test(f.name) || filterExt.test(f.ext))) - // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索目标扩展名 + // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索明确声明的目标扩展名 if (files.length === 0 && !hostOverride) { - const extTokens = (filterExt.source.match(/[a-z0-9]{2,5}/gi) || []) - .filter(t => !['thumbcache', 'iconcache'].includes(t.toLowerCase())) - .slice(0, 4) - // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 - const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() - const extraLists = await Promise.all( - extTokens.map(ext => searchRealIndexedFiles(`.${ext.toLowerCase()}`, 30, hostOverride)) - ) - const seen = new Set() - for (const list of extraLists) { - for (const item of list) { - if (!item.isDir && item.size > 0 && !seen.has(item.path)) { - if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { - seen.add(item.path) - files.push(item) + const extTokens = extractExtensionTokensFromFilter(filterExt) + if (extTokens.length > 0) { + // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 + const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() + const extraLists = await Promise.all( + extTokens.map(ext => searchRealIndexedFiles(`.${ext}`, 30, hostOverride)) + ) + const seen = new Set() + for (const list of extraLists) { + for (const item of list) { + if (!item.isDir && item.size > 0 && !seen.has(item.path)) { + if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { + seen.add(item.path) + files.push(item) + } } } } } } } + // 先基于过滤后的完整命中集合计算总文件数与总字节数,再按 collectTopN 裁剪样本列表 + const matchedCount = files.length + const matchedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) if (typeof opts.collectTopN === 'number' && opts.collectTopN > 0 && files.length > opts.collectTopN) { files = files.slice(0, opts.collectTopN) } @@ -714,11 +767,10 @@ async function scanDirectoryTreeWithError( ...(s.approximate === true ? { approximate: true } : {}) })) : [] - const computedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) const totalFilesCount = - filterExt instanceof RegExp ? files.length : Number(rawPayload.total_matches ?? files.length) + filterExt instanceof RegExp ? matchedCount : Number(rawPayload.total_matches ?? matchedCount) const totalBytesCount = - filterExt instanceof RegExp ? computedBytes : Number(rawPayload.total_bytes ?? computedBytes) + filterExt instanceof RegExp ? matchedBytes : Number(rawPayload.total_bytes ?? matchedBytes) const visited = Number(rawPayload.visited_entries) return { scan: makeScanResult(files, totalFilesCount, totalBytesCount, subdirs, { @@ -1817,8 +1869,6 @@ export async function writeRealClipboardText(text: string, hostOverride?: Dynami const payload = { text: String(text || '') } const res = await callHostTransport('clipboard_copy_text', payload, hostOverride) if (res.ok) return true - const fallbackRes = await callHostTransport('clipboard_write_text', payload, hostOverride) - if (fallbackRes.ok) return true try { if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) { await navigator.clipboard.writeText(String(text || '')) diff --git a/extensions/formula-ocr/README.en.md b/extensions/formula-ocr/README.en.md new file mode 100644 index 00000000..f1eec7e4 --- /dev/null +++ b/extensions/formula-ocr/README.en.md @@ -0,0 +1,37 @@ +# Math Formula OCR + +Recognize mathematical formulas from screen captures, the clipboard, or image files into LaTeX locally on your device without uploading images. Supports both printed formulas (textbooks, papers, slides) and handwritten formulas. Can also be opened directly by typing `latex` in the launcher. + +## First-Time Setup + +The recognition model is not bundled with the client installer. The first time you open Math Formula OCR, press `Enter` to download it (around 114 MB, one-time download). Downloads run inside the client and continue even if you close the plugin, showing progress when reopened. Failed downloads can be retried while preserving intact downloaded files. Once downloaded, recognition runs completely offline. + +## Usage + +- **Region Capture (`formula capture`, `screenshot latex`)**: Hides the ZTools window so you can drag-select a formula on screen and press `Enter` (`Esc` to cancel). The recognized LaTeX is copied to the clipboard in your selected format with a system notification. +- **Clipboard Recognition (`clipboard formula`, `clipboard latex`)**: Recognizes a formula image from the clipboard and copies the resulting LaTeX back to the clipboard. +- **Formula Workbench (`formula ocr`, `latex ocr`)**: + - Use "Capture Region" (`⌘/Ctrl+N`) or "Add Images" (`⌘/Ctrl+O`, supports multi-select, processed sequentially) in the top bar. The action panel also offers "Select Folder..." (`⌘/Ctrl+Shift+O`, recursively collects up to 5 levels and 100 images per batch) and "Recognize Clipboard Image" (`⌘/Ctrl+Shift+V`), or you can drag and drop or paste images and folders directly. Screen capture and clipboard results are copied automatically. + - The right pane displays the original image preview, rendered math preview, and raw LaTeX source for verification. Previews preserve original aspect ratio and colors; older entries may retain only source text. + - On completed items, press `Enter` to copy in the active format, or `⌘/Ctrl+Enter` / `⌘/Ctrl+E` to edit (with live preview; `⌘/Ctrl+Enter` saves, `Esc` discards). `⌘/Ctrl+K` lists all copy formats. On failed items, press `Enter` to retry. +- **Copy Format**: Choose on the right of the workbench search bar: Inline Math `$…$` (default, ideal for Markdown, Typora, Obsidian, Notion), Display Math `$$…$$`, or Raw LaTeX. The preference is saved and also applies to region capture and clipboard commands. +- **Selection Tips**: Capture one formula at a time—leaving a bit of margin is fine since extra whitespace is trimmed automatically. Dark-background screenshots are also supported. + +## Scope & Limitations + +- Recognizes one formula per capture (multi-line formulas such as systems of equations, matrices, and piecewise functions are supported). For mixed text-and-formula pages, select the formula region separately. +- Non-math text mixed inside a formula (such as prose words) is poorly recognized; select only the mathematical expression. +- Output is LaTeX source code and individual symbols may occasionally be misread; verify against the rendered preview on the right for important work. +- Bold styling, vector markers, grouping braces, and text spacing are preserved without automatic stripping. A successful render or high model score does not guarantee accuracy—always verify against the original image; the "Please verify" badge is only an extra reminder when model confidence is low. + +## Platforms & Requirements + +- Supported: macOS (requires client version 1.1.8.11 or later). Windows support will open after physical-device verification. +- macOS: Region capture requires enabling Screen Recording permission for ZTools under System Settings > Privacy & Security. + +## Network & Data + +- Network access is used only for the initial model download (tries the official ZTools CDN, Hugging Face, and its mirror in order; upstream and mirror pin the exact same commit, and every file is verified against the same SHA-256 checksum). Recognition runs offline and images never leave your device. +- Temporary screenshots from region capture and clipboard recognition are deleted immediately after recognition. +- Recognition results and image previews are kept in memory only and cleared when the client exits. Up to 50 finished results and 4 MiB of preview images are retained; deleting results or clearing the list removes their previews. Headless commands do not keep image previews. +- Recognition model: [Pix2Text-MFR 1.5](https://huggingface.co/breezedeus/pix2text-mfr-1.5) (MIT License). diff --git a/extensions/formula-ocr/plugin.json b/extensions/formula-ocr/plugin.json index e1ce05d6..7a99d11e 100644 --- a/extensions/formula-ocr/plugin.json +++ b/extensions/formula-ocr/plugin.json @@ -2,7 +2,7 @@ "id": "formula-ocr", "name": "公式识别", "description": "框选屏幕、剪贴板或图片里的数学公式,在本机识别成 LaTeX,支持印刷体与手写,结果直接复制", - "version": "1.1.3", + "version": "1.1.4", "author": "ZTools Team", "entry": "dist/index.js", "icon": "icon.svg", @@ -74,7 +74,12 @@ "ocr", "math", "equation", - "screenshot" + "screenshot", + "formula ocr", + "math ocr", + "mathpix", + "screenshot math", + "formula recognition" ], "features": { "formula-region": { @@ -114,5 +119,15 @@ { "path": "screenshots/01.png" } + ], + "keywords": [ + "公式识别", + "数学公式", + "图片转latex", + "截公式", + "latex识别", + "公式ocr", + "手写公式", + "论文公式" ] } diff --git a/extensions/git-helper/README.en.md b/extensions/git-helper/README.en.md new file mode 100644 index 00000000..66ccf2b5 --- /dev/null +++ b/extensions/git-helper/README.en.md @@ -0,0 +1,23 @@ +# Git Rescue & Helper + +Search Git undo and recovery commands in plain language, generate Conventional Commits messages, and compose `.gitignore` files by tech stack. The plugin only generates text to copy—it never executes Git commands. + +## Usage + +- **Commands**: Three commands open each mode directly, or you can switch modes from the right side of the search bar: + - Plain-language lookup for Git recovery commands (`git rescue`, `undo commit`, `git reset`, `git revert`); + - Interactive Conventional Commits message builder (`conventional commit`, `commit builder`, `cz`); + - `.gitignore` generator combining tech stacks and operating systems (`gitignore`, `generate gitignore`). +- **Git Rescue**: Covers undoing the latest commit while keeping changes, amending missed files or commit messages, recovering a deleted branch or code lost before `reset --hard`, fixing commits made to the wrong/main branch, undoing a messy `pull` / `merge`, and reverting commits already pushed to a shared branch. `Enter` copies the primary command, and `⌘/Ctrl+Enter` copies the full guide (every line starts with `#` so pasting into a terminal will not execute automatically). Choose the option that fits your situation—do not run all alternatives sequentially. +- **Undo Safety**: When undoing an unpushed latest commit, the primary command creates a `backup/before-undo` branch before soft resetting; if that branch already exists, the command stops so you can pick a new name. The backup branch only preserves committed changes—back up uncommitted files separately. +- **Commit Builder**: Enter your change summary in the search box (`scope:summary` is supported using an ASCII colon; if the text before the colon contains spaces or is a URL, the whole input is treated as the summary, and prefixes like `fix:summary` have the prefix stripped). Select a commit type and press `Enter` to copy the full `git commit -m` command, or `⌘/Ctrl+Enter` to copy just the commit message text. If no summary is entered, `Enter` copies only the type prefix (such as `feat: `). Generated commands target Bash, zsh, and Git Bash on Windows; PowerShell and CMD users should copy the message text and commit via their terminal or Git GUI. +- **`.gitignore` Generator**: Press `⌘/Ctrl+Enter` to toggle stacks (Node, React / Vue, Python, Java, Go, Rust, macOS, Windows, IDE). By default, only your current OS (macOS or Windows) and IDE are selected. The right pane previews the deduplicated result; press `Enter` to copy all. The Rust template keeps `Cargo.lock` (per Cargo's recommendation for binaries), the Java template keeps Gradle/Maven wrapper JARs, and the Go template does not ignore `vendor/`; append rules manually if needed. +- **Notes**: Use revert commits for history already pushed to shared branches. Aborting an in-progress merge conflict and undoing a completed merge are different operations—consult the official Git documentation for exact behavior. + +## Platforms & Requirements + +- Supported: Windows, macOS + +## Network & Data + +- Offline only; all content is generated locally. diff --git a/extensions/git-helper/plugin.json b/extensions/git-helper/plugin.json index 7491b7c7..77174dda 100644 --- a/extensions/git-helper/plugin.json +++ b/extensions/git-helper/plugin.json @@ -1,7 +1,8 @@ { "id": "git-helper", "name": "Git救命锦囊", - "version": "1.0.5", + "version": "1.0.6", + "minAppVersion": "1.1.8.0", "description": "大白话场景检索Git回滚自救命令、交互式规范提交(Conventional Commits)生成器与多语言.gitignore模板合成", "author": "ZTools Team", "category": [ @@ -77,7 +78,13 @@ "gitignore", "conventional commits", "reset", - "revert" + "revert", + "git helper", + "git undo", + "rebase", + "cheatsheet", + "git rescue", + "git commands" ], "features": { "git-emergency": { @@ -122,5 +129,16 @@ { "path": "screenshots/02-action-panel.png" } + ], + "keywords": [ + "git", + "git救命", + "撤销提交", + "回滚", + "git命令", + "git速查", + "冲突解决", + "提交撤销", + "代码回退" ] } diff --git a/extensions/google-auth/README.en.md b/extensions/google-auth/README.en.md new file mode 100644 index 00000000..fe33421d --- /dev/null +++ b/extensions/google-auth/README.en.md @@ -0,0 +1,20 @@ +# 2FA Authenticator + +Generate two-factor authentication one-time passwords (TOTP) per RFC 6238 with automatic countdown refresh and quick copy. + +## Usage + +- **Command**: 2FA Authenticator (keywords such as `2fa`, `totp`, `otp`, `authenticator`). +- **Adding Accounts**: Select "Add 2FA Account" in the action panel (or press `Enter` when no accounts exist yet), enter a name and Base32 secret, or paste an `otpauth://totp/...` URI to auto-fill all fields. Supports 6/8 digits, 30/60s periods, and SHA1/SHA256/SHA512; URIs specifying 7 digits or custom periods (1–300 seconds) are also accepted, while unsupported digits, periods, or algorithms report an error instead of silently falling back to defaults. HOTP (counter-based) URIs and QR code image scanning are not supported. +- **Codes & Actions**: The list shows each account's current code and remaining seconds. Press `Enter` to copy the code (recalculated at the exact moment of copy), or `⌘/Ctrl+K` to open the action panel (copy Base32 secret, add account, delete account, etc.). Copying a secret requires confirmation because it places the plaintext secret on the clipboard where clipboard history tools may record it. TOTP relies on your system clock—if clock skew exceeds one period, codes will be rejected; enable automatic time sync in your system settings. +- **Deletion**: Deleting an account requires confirmation and cannot be undone. Accounts cannot be edited in place; delete and re-add to make changes. + +## Platforms & Requirements + +- Supported: Windows, macOS +- Built into the client; no separate installation required. + +## Network & Data + +- Offline only; all data stays on your device. +- Accounts and secrets are stored in the client's system encrypted storage. If encrypted storage is unavailable, legacy plaintext accounts are shown read-only while adding and deleting are disabled. Legacy plaintext accounts are automatically migrated to encrypted storage on open, and plaintext records are removed once migration succeeds. diff --git a/extensions/google-auth/plugin.json b/extensions/google-auth/plugin.json index d409c4d7..aaa99720 100644 --- a/extensions/google-auth/plugin.json +++ b/extensions/google-auth/plugin.json @@ -1,7 +1,8 @@ { "id": "google-auth", "name": "2FA 验证码", - "version": "1.0.9", + "version": "1.0.10", + "minAppVersion": "1.1.8.0", "description": "桌面端两步验证动态口令(TOTP)管理工具,支持秒级复制 6 位验证码,密钥加密保存在本机", "author": "ZTools Team", "entry": "dist/index.js", @@ -31,7 +32,12 @@ "otp", "验证码", "动态口令", - "authenticator" + "authenticator", + "两步验证", + "谷歌验证器", + "令牌", + "安全码", + "身份验证器" ], "category": [ "安全隐私" @@ -48,7 +54,12 @@ "otp", "authenticator", "security", - "codes" + "codes", + "google authenticator", + "two factor", + "mfa", + "verification code", + "token" ], "screenshots": [ { diff --git a/extensions/google-auth/src/i18n.ts b/extensions/google-auth/src/i18n.ts index 7cd37603..18a8220c 100644 --- a/extensions/google-auth/src/i18n.ts +++ b/extensions/google-auth/src/i18n.ts @@ -102,7 +102,9 @@ const rawT = createTranslator( toastParseClipboardFailed: '无法解析剪贴板里的链接', toastAccountAddedSimple: '已添加账号 {name}', addAccountAction: '添加 2FA 账号', + addAccountBtn: '添加密钥', importClipboardAction: '从剪贴板导入 otpauth 链接', + importClipboardBtn: '剪贴板导入', confirmDeleteTitle: '删除账号「{name}」?', confirmDeleteMsg: '删除后密钥无法找回。请先确认该账号已在其他验证器中备份,或已关闭两步验证。', confirmDeleteAction: '删除', @@ -241,7 +243,9 @@ const rawT = createTranslator( toastParseClipboardFailed: 'Failed to Parse Clipboard Link', toastAccountAddedSimple: 'Added account {name}', addAccountAction: 'Add 2FA Account', + addAccountBtn: 'Add Account', importClipboardAction: 'Import otpauth Link from Clipboard', + importClipboardBtn: 'Import Clipboard', confirmDeleteTitle: 'Delete account "{name}"?', confirmDeleteMsg: 'Secrets cannot be recovered after deletion. Make sure this account is backed up elsewhere or 2FA is disabled.', confirmDeleteAction: 'Delete', diff --git a/extensions/google-auth/src/index.ts b/extensions/google-auth/src/index.ts index f1feb4c1..e1627e38 100644 --- a/extensions/google-auth/src/index.ts +++ b/extensions/google-auth/src/index.ts @@ -124,11 +124,6 @@ export function CreateAccountForm({ onCreated }: { onCreated: (account: AuthAcco title: t("saveAccountAction"), icon: Icon.Check, onSubmit: handleSubmit - }), - Action({ - title: t("backToListAction"), - icon: Icon.ArrowLeft, - onAction: () => pop() }) ]) }, @@ -139,6 +134,7 @@ export function CreateAccountForm({ onCreated }: { onCreated: (account: AuthAcco placeholder: t("fieldNamePlaceholder"), value: name, error, + autoFocus: true, onChange: (val) => { setName(val); if (error) setError(undefined); @@ -601,12 +597,14 @@ export default function GoogleAuthCommand() { Action({ title: t("addAccountAction"), icon: Icon.Plus, + shortcut: { modifiers: ["ctrl"], key: "n" }, onAction: handleOpenAddForm }); const importAction = () => Action({ title: t("importClipboardAction"), icon: Icon.CopyClipboard, + shortcut: { modifiers: ["ctrl", "shift"], key: "v" }, onAction: handleImportFromClipboard }); @@ -734,6 +732,30 @@ export default function GoogleAuthCommand() { searchBarPlaceholder: t("searchPlaceholder"), searchText: searchQuery, onSearchTextChange: (val) => setSearchQuery(val), + filterBar: { + actions: [ + { + id: "add-account", + label: t("addAccountBtn"), + title: t("addAccountAction"), + icon: Icon.Plus, + style: "primary", + onAction: () => { + void handleOpenAddForm(); + } + }, + { + id: "import-clipboard", + label: t("importClipboardBtn"), + title: t("importClipboardAction"), + icon: Icon.CopyClipboard, + style: "secondary", + onAction: () => { + void handleImportFromClipboard(); + } + } + ] + }, actions: ActionPanel({ title: t("globalActionsTitle") }, [ addAction(), importAction(), @@ -792,19 +814,17 @@ export default function GoogleAuthCommand() { onAction: () => handleCopyCode(account) }) ]), - Action({ - title: t("addNewAccountAction"), - icon: Icon.Plus, - onAction: handleOpenAddForm - }), Action({ title: t("copySecretAction"), icon: Icon.Key, + shortcut: { modifiers: ["ctrl", "shift"], key: "c" }, onAction: () => handleCopySecret(account) }), Action({ title: t("deleteAccountAction"), icon: Icon.Trash, + style: Action.Style.Destructive, + shortcut: { modifiers: ["ctrl"], key: "backspace" }, onAction: () => handleDeleteAccount(account.id, account.name) }) ]) diff --git a/extensions/google-auth/tests/secure-migration.test.mjs b/extensions/google-auth/tests/secure-migration.test.mjs index 3e914253..ed18b23c 100644 --- a/extensions/google-auth/tests/secure-migration.test.mjs +++ b/extensions/google-auth/tests/secure-migration.test.mjs @@ -80,7 +80,7 @@ test('[故障注入] 写入加密存储失败:明文保留不删,进入可 // 故障消除后重新读取:完成迁移 ss.faults.set = null - await view.run(view.items()[0], '添加新账号') // 仍被拦截(状态未刷新) + await view.run(view.tree(), '添加 2FA 账号') // 仍被拦截(状态未刷新) assert.deepEqual(plain(), JSON.parse(JSON.stringify(old))) view.unmount() const again = await open() diff --git a/extensions/hardware-info/README.en.md b/extensions/hardware-info/README.en.md new file mode 100644 index 00000000..c68c7cf6 --- /dev/null +++ b/extensions/hardware-info/README.en.md @@ -0,0 +1,25 @@ +# Hardware Info + +Inspect your computer's CPU model and load, physical memory, OS version, disk capacity, displays, and power status, view rule-based estimates for 4 common usage scenarios, and copy a hardware configuration report in Markdown, JSON, or TXT format. + +- **Architecture**: Built with `@ztools/declarative-ui` view descriptors using Layout 1 (single-column list + right detail pane). +- **Data Sources**: Uses generic host system APIs (`system_get_hardware_summary`, `get_system_info`, `system_get_cpu_usage`, `system_get_memory_usage`, `system_get_battery_status`, `screen_get_all_displays`, `system_list_volumes`) without native DLL dependencies. +- **Read Failures**: If any API fails, the affected field displays a read-failure state with an error prompt instead of substituting default values; load headroom and scenario estimates are calculated only when all required data is available. +- **Power Status**: Displays "No battery" only when the system explicitly reports no battery; unknown charge level (system reports `255`) displays "Unknown charge" or "Battery status unknown"; read failures display a power status error with the reason. +- **Disk Capacity**: When some volumes fail to read, readable volumes are still shown while the status bar and report note partial volume read failure along with the reasons. +- **Capacity Units**: Memory uses binary units (1024-based). Disk capacity uses decimal units (1000-based) on macOS (matching Finder and About This Mac) and binary units (1024-based) on Windows (matching File Explorer). Volumes sharing an APFS container are counted only once in the total. +- **CPU Load**: Sampled twice ~0.4 seconds apart to show load over that interval; the host reports only the average since the previous read, so a single read may reflect a long-term average. +- **Actions**: Top bar actions "Refresh" and "Copy Markdown Report" apply to the whole machine; individual selected items can copy a summary or detailed specs; the "Export Hardware Report" dropdown copies Markdown, JSON, or TXT. +- **Load Headroom**: Defined as the smaller unused percentage of CPU and memory, i.e., `100 - max(CPU usage, memory usage)`, and does not indicate hardware lifespan or fault status. Exported as `loadHeadroomPercent` in JSON (`null` if either usage metric is missing). +- **Scenario Estimates**: Rule-based estimates using only thread count and memory capacity, with disk free space used solely as a storage warning. No benchmarks are run, and software compatibility, game frame rates, or model inference speeds are not guaranteed. JSON reports mark `assessment.performanceMeasured: false` to distinguish estimates from measurements. +- **Not Provided**: Temperature/fan sensors, GPU, motherboard, memory SPD, and disk SMART data (no cross-platform host APIs are available yet). + +## Platforms & Requirements + +- Supported: Windows, macOS +- Requires client version 1.1.8.3 or later. +- Windows implementation is pending physical-device verification. + +## Network & Data + +- Offline only; all data stays on your device. diff --git a/extensions/hardware-info/plugin.json b/extensions/hardware-info/plugin.json index 8dc7b1f7..4d9d5e79 100644 --- a/extensions/hardware-info/plugin.json +++ b/extensions/hardware-info/plugin.json @@ -2,7 +2,8 @@ "id": "hardware-info", "name": "硬件信息", "description": "查看电脑 CPU、内存、磁盘容量、显示器与电源状态,支持导出硬件配置报告", - "version": "2.0.13", + "version": "2.0.14", + "minAppVersion": "1.1.8.0", "author": "ZTools Team", "entry": "dist/index.js", "icon": "icon.svg", @@ -41,7 +42,10 @@ "ram", "disk", "system info", - "specs" + "specs", + "gpu", + "motherboard", + "pc specs" ], "screenshots": [ { @@ -54,5 +58,17 @@ { "path": "screenshots/01.png" } + ], + "keywords": [ + "硬件信息", + "看配置", + "电脑配置", + "显卡", + "cpu", + "内存型号", + "硬盘信息", + "主板", + "系统配置", + "鲁大师" ] } diff --git a/extensions/hardware-info/src/logic.ts b/extensions/hardware-info/src/logic.ts index 0ad9c0db..336c68d7 100644 --- a/extensions/hardware-info/src/logic.ts +++ b/extensions/hardware-info/src/logic.ts @@ -176,7 +176,9 @@ export function interpretBatteryStatus(res: { ok: boolean; data?: unknown; error const hostState = data.batteryState === 'present' || data.batteryState === 'absent' || data.batteryState === 'unknown' ? data.batteryState : null const hostSource = data.powerSource === 'ac' || data.powerSource === 'battery' || data.powerSource === 'unknown' ? data.powerSource : null const isCharging = data.isCharging === true - const batteryState: BatteryState = hostState ?? (exactPercent === null ? 'unknown' : 'present') + // 若宿主明确上报 hasBattery: true 且电量未知(如 255 -> percent: null),按有电池但电量未知处理,不误归为无电池或电池状态未知 + const hasExplicitBatteryWithUnknownPct = data.hasBattery === true && percent === null + const batteryState: BatteryState = hostState ?? (exactPercent !== null || hasExplicitBatteryWithUnknownPct ? 'present' : 'unknown') const powerSource: PowerSource = hostSource ?? (typeof data.isCharging === 'boolean' ? (isCharging ? 'ac' : 'battery') : 'unknown') return { batteryPercent: batteryState === 'present' ? exactPercent : null, isCharging, batteryState, powerSource, readError: null } } diff --git a/extensions/hardware-info/src/native-ipc.ts b/extensions/hardware-info/src/native-ipc.ts index 51576b99..13643277 100644 --- a/extensions/hardware-info/src/native-ipc.ts +++ b/extensions/hardware-info/src/native-ipc.ts @@ -174,11 +174,13 @@ function normalizeMethodResult(method: string, payload: DynamicBridge): DynamicB if (method === 'system_get_battery_status') { // 宿主约定 percent 超出 0-100(如 255)表示无电池或电量未知,不能改写成 100% + // 若宿主明确给出 hasBattery 布尔值,必须原样保留,仅在缺失时按合法电量推算 const rawPct = payload.percent - const hasBattery = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const validPct = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const hasBattery = typeof payload.hasBattery === 'boolean' ? payload.hasBattery : validPct return { ...payload, - percent: hasBattery ? rawPct : null, + percent: validPct ? rawPct : null, hasBattery } } @@ -489,6 +491,8 @@ export interface RealDirectoryScanResult extends Iterable approximate?: boolean /** 宿主实际遍历的条目数 */ visitedEntries?: number + /** 目录本身不存在(ENOENT) */ + missing?: boolean /** 读取失败的真实原因;已有文件仍可使用,但不能当作完整结果。 */ error?: string } @@ -497,6 +501,7 @@ interface ScanResultMeta { truncated?: boolean approximate?: boolean visitedEntries?: number + missing?: boolean } export interface ScanDirectoryTreeOptions { @@ -504,6 +509,10 @@ export interface ScanDirectoryTreeOptions { maxFiles?: number collectTopN?: number filterExt?: RegExp + /** 为 true 时,目录本身不存在(ENOENT)按空目录处理,不返回 error(权限拒绝/读取失败仍照常报错) */ + ignoreMissing?: boolean + /** Top-N 保留与排序方式:默认按体积降序,下载/录屏等时效场景可传 mtime-desc */ + sortBy?: 'size-desc' | 'mtime-desc' hostOverride?: DynamicBridge } @@ -519,8 +528,9 @@ function normalizeIndexedFileEntry(f: DynamicBridge): RealIndexedFileEntry { const sz = Number(f?.size ?? f?.sizeBytes ?? 0) const isDir = Boolean(f?.is_dir || f?.isDir || f?.isDirectory) const rawMtime = Number(f?.mtime ?? f?.mtimeMs ?? 0) - const mtimeMs = rawMtime > 1e11 ? rawMtime : rawMtime > 0 ? rawMtime * 1000 : Date.now() - const mtimeSec = rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime + const validMtime = Number.isFinite(rawMtime) && rawMtime > 0 + const mtimeMs = validMtime ? (rawMtime > 1e11 ? rawMtime : rawMtime * 1000) : 0 + const mtimeSec = validMtime ? (rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime) : 0 if (p && sz >= 0) realFileSizeCache.set(p, sz) return { name, @@ -551,6 +561,7 @@ function makeScanResult( subdirs, ...(meta.truncated ? { truncated: true } : {}), ...(meta.approximate ? { approximate: true } : {}), + ...(meta.missing ? { missing: true } : {}), ...(typeof meta.visitedEntries === 'number' ? { visitedEntries: meta.visitedEntries } : {}), [Symbol.iterator]() { return files[Symbol.iterator]() @@ -609,13 +620,40 @@ export async function scanRealDirectoryTree( return result.error ? { ...result.scan, error: result.error } : result.scan } +/** 仅当正则明确声明了扩展名(含 `\.`)时提取后缀列表,避免把 `thumbcache|iconcache` 等文件名关键词误拆成假扩展名 */ +function extractExtensionTokensFromFilter(filterExt: RegExp): string[] { + const src = filterExt.source + if (!src.includes('\\.')) return [] + const afterDot = src.slice(src.indexOf('\\.') + 2) + const rawTokens = afterDot.match(/[a-z0-9]{1,8}/gi) || [] + const seen = new Set() + const out: string[] = [] + for (const token of rawTokens) { + const lower = token.toLowerCase() + if (!lower || seen.has(lower)) continue + seen.add(lower) + out.push(lower) + } + return out +} + +function isMissingDirectoryError(res: { error?: string; errorCode?: string; errorDetails?: Record }): boolean { + if (res.errorDetails?.reason === 'ENOENT' || res.errorCode === 'ENOENT') return true + const msg = String(res.error || '') + return /Directory does not exist|ENOENT/i.test(msg) +} + /** 一次界面扫描的错误汇总;多个目录并行扫描时保留可读目录的结果。 */ export function createDirectoryScanner(hostOverride?: DynamicBridge) { const failures = new Map() return { async scan(dir: string, options: number | ScanDirectoryTreeOptions = 160) { const result = await scanRealDirectoryTree(dir, options, hostOverride) - const error = result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') + const ignoreMissing = typeof options === 'object' && options !== null && options.ignoreMissing === true + const error = + result.missing && ignoreMissing + ? '' + : result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') if (error) failures.set(dir, error) else failures.delete(dir) return result @@ -648,26 +686,38 @@ async function scanDirectoryTreeWithError( const safeLimit = Math.min(200, Math.max(1, Math.floor(rawLimit || 160))) const hostOverride = opts.hostOverride const filterExt = opts.filterExt + const ignoreMissing = opts.ignoreMissing === true const dirQuery = `dir:${targetDir}` try { let rawPayload: DynamicBridge = null + const searchParams: Record = { + query: dirQuery, + limit: safeLimit, + ...(opts.sortBy ? { sortBy: opts.sortBy } : {}) + } const res = await callHostTransport( 'system_search_files', - { query: dirQuery, limit: safeLimit }, + searchParams, hostOverride ) - if (res.ok && res.data) { + if (res.ok && res.data && res.data.degraded !== true) { rawPayload = res.data + } else if (!res.ok && ignoreMissing && isMissingDirectoryError(res)) { + const missingScan = makeScanResult([], 0, 0, [], { missing: true }) + return { scan: missingScan } } - if (!rawPayload && !hostOverride && typeof window !== 'undefined') { + if (!rawPayload && !hostOverride && res.errorCode === 'METHOD_NOT_AVAILABLE' && typeof window !== 'undefined') { const w = window as DynamicBridge if (typeof w.__ztoolsLauncher?.searchFiles === 'function') { const rawOuter = await w.__ztoolsLauncher.searchFiles(dirQuery, safeLimit) - rawPayload = + const candidate = rawOuter && typeof rawOuter === 'object' && 'data' in rawOuter && rawOuter.data ? rawOuter.data : rawOuter + if (candidate && candidate.degraded !== true && candidate.success !== false) { + rawPayload = candidate + } } } @@ -678,29 +728,32 @@ async function scanDirectoryTreeWithError( let files: RealIndexedFileEntry[] = rawPayload.files.map(normalizeIndexedFileEntry) if (filterExt instanceof RegExp) { files = files.filter(f => !f.isDir && (filterExt.test(f.name) || filterExt.test(f.ext))) - // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索目标扩展名 + // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索明确声明的目标扩展名 if (files.length === 0 && !hostOverride) { - const extTokens = (filterExt.source.match(/[a-z0-9]{2,5}/gi) || []) - .filter(t => !['thumbcache', 'iconcache'].includes(t.toLowerCase())) - .slice(0, 4) - // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 - const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() - const extraLists = await Promise.all( - extTokens.map(ext => searchRealIndexedFiles(`.${ext.toLowerCase()}`, 30, hostOverride)) - ) - const seen = new Set() - for (const list of extraLists) { - for (const item of list) { - if (!item.isDir && item.size > 0 && !seen.has(item.path)) { - if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { - seen.add(item.path) - files.push(item) + const extTokens = extractExtensionTokensFromFilter(filterExt) + if (extTokens.length > 0) { + // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 + const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() + const extraLists = await Promise.all( + extTokens.map(ext => searchRealIndexedFiles(`.${ext}`, 30, hostOverride)) + ) + const seen = new Set() + for (const list of extraLists) { + for (const item of list) { + if (!item.isDir && item.size > 0 && !seen.has(item.path)) { + if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { + seen.add(item.path) + files.push(item) + } } } } } } } + // 先基于过滤后的完整命中集合计算总文件数与总字节数,再按 collectTopN 裁剪样本列表 + const matchedCount = files.length + const matchedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) if (typeof opts.collectTopN === 'number' && opts.collectTopN > 0 && files.length > opts.collectTopN) { files = files.slice(0, opts.collectTopN) } @@ -714,11 +767,10 @@ async function scanDirectoryTreeWithError( ...(s.approximate === true ? { approximate: true } : {}) })) : [] - const computedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) const totalFilesCount = - filterExt instanceof RegExp ? files.length : Number(rawPayload.total_matches ?? files.length) + filterExt instanceof RegExp ? matchedCount : Number(rawPayload.total_matches ?? matchedCount) const totalBytesCount = - filterExt instanceof RegExp ? computedBytes : Number(rawPayload.total_bytes ?? computedBytes) + filterExt instanceof RegExp ? matchedBytes : Number(rawPayload.total_bytes ?? matchedBytes) const visited = Number(rawPayload.visited_entries) return { scan: makeScanResult(files, totalFilesCount, totalBytesCount, subdirs, { @@ -1817,8 +1869,6 @@ export async function writeRealClipboardText(text: string, hostOverride?: Dynami const payload = { text: String(text || '') } const res = await callHostTransport('clipboard_copy_text', payload, hostOverride) if (res.ok) return true - const fallbackRes = await callHostTransport('clipboard_write_text', payload, hostOverride) - if (fallbackRes.ok) return true try { if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) { await navigator.clipboard.writeText(String(text || '')) diff --git a/extensions/hardware-info/src/volume-ipc.ts b/extensions/hardware-info/src/volume-ipc.ts index 4be65bd7..0059623b 100644 --- a/extensions/hardware-info/src/volume-ipc.ts +++ b/extensions/hardware-info/src/volume-ipc.ts @@ -50,23 +50,97 @@ export interface RealDiskDriveInfo { usagePercent: number } +export interface RealDiskDrivesProbeResult { + drives: RealDiskDriveInfo[] + partial: boolean + warnings: string[] +} + /** - * 读取宿主枚举的已挂载卷,不猜测盘符或挂载点。 + * 读取宿主枚举的已挂载卷,并返回部分失败状态与告警; + * 当 partial 为 true 且存在有效卷时保留有效卷并透传 warnings,仅在无任何有效卷时抛错。 */ -export async function probeRealDiskDrives(_letters: string[] = [], hostOverride?: unknown): Promise { +export async function probeRealDiskDrivesWithStatus( + _letters: string[] = [], + hostOverride?: unknown +): Promise { const s = volumeIpcStrings() const res = await callHostTransport>('system_list_volumes', {}, hostOverride) if (!res.ok && isHostMethodMissing(res.error)) throw hostUpgradeError(s.listVolumesFeature) if (!res.ok || !Array.isArray(res.data?.volumes)) throw new Error(res.error || s.unableToReadVolumes) - if (res.data.partial) throw new Error(s.incompleteVolumeList(Array.isArray(res.data.errors) ? res.data.errors.join(s.errorSep) : s.capacityReadFailed)) - const drives = res.data.volumes.map((value: unknown) => { - if (!value || typeof value !== 'object') throw new Error(s.invalidVolumeData) + + const hostPartial = res.data.partial === true + const warnings: string[] = Array.isArray(res.data.errors) + ? res.data.errors.map(err => String(err ?? '').trim()).filter(Boolean) + : [] + if (hostPartial && warnings.length === 0) { + warnings.push(s.capacityReadFailed) + } + + const drives: RealDiskDriveInfo[] = [] + let invalidCount = 0 + for (const value of res.data.volumes as unknown[]) { + if (!value || typeof value !== 'object') { + invalidCount += 1 + warnings.push(s.invalidVolumeData) + continue + } const v = value as Record - const total = Number(v.totalBytes), used = Number(v.usedBytes), available = Number(v.availableBytes) - if (typeof v.path !== 'string' || !v.path || !Number.isFinite(total) || total <= 0 || !Number.isFinite(used) || used < 0 || !Number.isFinite(available) || available < 0) throw new Error(s.invalidVolumeData) - return { drive: v.path.replace(/^([A-Za-z]:)[\\/]$/, '$1'), label: String(v.label || v.path), fileSystem: String(v.fileSystem || s.unknownFs), capacityGroup: String(v.capacityGroup || v.path), totalBytes: total, usedBytes: used, availableBytes: available, usagePercent: Math.round(used / total * 100) } - }) - if (!drives.length) throw new Error(s.noMountedVolumes) + const total = Number(v.totalBytes) + const used = Number(v.usedBytes) + const available = Number(v.availableBytes) + const valid = + typeof v.path === 'string' && + v.path.length > 0 && + typeof v.totalBytes === 'number' && + typeof v.usedBytes === 'number' && + typeof v.availableBytes === 'number' && + Number.isFinite(total) && + total > 0 && + Number.isFinite(used) && + used >= 0 && + Number.isFinite(available) && + available >= 0 + if (!valid) { + invalidCount += 1 + warnings.push(typeof v.path === 'string' && v.path ? `${v.path}: ${s.invalidVolumeData}` : s.invalidVolumeData) + continue + } + const volumePath = v.path as string + drives.push({ + drive: volumePath.replace(/^([A-Za-z]:)[\\/]$/, '$1'), + label: String(v.label || volumePath), + fileSystem: String(v.fileSystem || s.unknownFs), + capacityGroup: String(v.capacityGroup || volumePath), + totalBytes: total, + usedBytes: used, + availableBytes: available, + usagePercent: Math.round((used / total) * 100) + }) + } + + const partial = hostPartial || invalidCount > 0 + if (!drives.length) { + if (hostPartial) { + throw Object.assign(new Error(s.incompleteVolumeList(warnings.join(s.errorSep))), { + code: 'VOLUME_PARTIAL_EMPTY', + warnings + }) + } + if (invalidCount > 0) { + throw new Error(s.invalidVolumeData) + } + throw new Error(s.noMountedVolumes) + } + + return { drives, partial, warnings } +} + +/** + * 读取宿主枚举的已挂载卷,不猜测盘符或挂载点(仅在无有效卷时抛错)。 + */ +export async function probeRealDiskDrives(_letters: string[] = [], hostOverride?: unknown): Promise { + const { drives } = await probeRealDiskDrivesWithStatus(_letters, hostOverride) return drives } diff --git a/extensions/hardware-info/tests/hardware-info.host.test.mjs b/extensions/hardware-info/tests/hardware-info.host.test.mjs index e86912d0..f5df5189 100644 --- a/extensions/hardware-info/tests/hardware-info.host.test.mjs +++ b/extensions/hardware-info/tests/hardware-info.host.test.mjs @@ -139,6 +139,39 @@ test('hardware-info: 新版宿主有电池但电量未知(255)显示「电 assert.match(systemRowMarkdown(unknown), /电池状态未知/) }) +test('hardware-info: 宿主显式返回 hasBattery: true 且 percent 为 255 时保留 hasBattery 且展示「电量未知」而非「无电池」', async () => { + const { callHostTransport } = await import('../dist/native-ipc.js') + const normalized = await callHostTransport('system_get_battery_status', {}, { + system_get_battery_status: async () => ({ percent: 255, hasBattery: true, isCharging: false }) + }) + assert.equal(normalized.ok, true) + assert.equal(normalized.data.hasBattery, true) + assert.equal(normalized.data.percent, null) + + // 宿主显式返回 hasBattery: false 且缺失 batteryState 时同样原样保留 hasBattery: false + const explicitFalse = await callHostTransport('system_get_battery_status', {}, { + system_get_battery_status: async () => ({ percent: 255, hasBattery: false, isCharging: true }) + }) + assert.equal(explicitFalse.ok, true) + assert.equal(explicitFalse.data.hasBattery, false) + assert.equal(explicitFalse.data.percent, null) + + // 宿主缺失 hasBattery 时按合法百分比推算 + const inferred = await callHostTransport('system_get_battery_status', {}, { + system_get_battery_status: async () => ({ percent: 65, isCharging: true }) + }) + assert.equal(inferred.ok, true) + assert.equal(inferred.data.hasBattery, true) + assert.equal(inferred.data.percent, 65) + + // 通过逻辑快照渲染:hasBattery: true + percent: 255 展示为「电量未知」而非「无电池」 + const snap = await fetchHardwareTelemetrySnapshot(makeHardwareHost(async () => ({ percent: 255, hasBattery: true, isCharging: false }))) + assert.equal(snap.batteryState, 'present') + assert.equal(snap.batteryPercent, null) + assert.match(systemRowMarkdown(snap), /电量未知 \(电池放电中\)/) + assert.doesNotMatch(systemRowMarkdown(snap), /无电池/) +}) + test('hardware-info: 宿主报告电源读取失败(readError)时标「电源状态读取失败」并给出原因', async () => { const snap = await fetchHardwareTelemetrySnapshot(makeHardwareHost(async () => ({ success: true, percent: 255, isCharging: false, timeRemaining: -1, batteryState: 'unknown', powerSource: 'unknown', readError: '电源状态读取超时' diff --git a/extensions/hosts-switcher/README.en.md b/extensions/hosts-switcher/README.en.md new file mode 100644 index 00000000..5610edb3 --- /dev/null +++ b/extensions/hosts-switcher/README.en.md @@ -0,0 +1,18 @@ +# Hosts Switcher + +Save multiple Hosts profiles, preview changes, and apply them to the system. The features and safeguards below apply to macOS only: macOS uses system authorization so you do not need to launch the client as administrator. + +- Creating or editing a profile saves only locally; press `Enter` on a profile row to preview, then confirm to apply. +- Current system contents are read directly from the system hosts file. Active status is read from the system managed block; editing a profile without re-applying marks it as "System using previous content". +- Existing system entries outside the managed block are preserved intact. If the same hostname within the same address family maps to different IPs, merging stops to avoid silently overwriting existing rules. IPv4 and IPv6 entries may coexist. +- Before writing, a backup is saved and verified, and writing aborts if the original file changed during confirmation. Atomic swap preserves the replaced file object; backups can be viewed, previewed, and restored from the action panel on "Current System Hosts". +- Writing the hosts file and flushing DNS report results separately. Canceling DNS authorization does not roll back an already written hosts file; you can flush DNS again or restore from backup. +- Broken fallback profiles are never loaded and corrupted local profiles are never overwritten. Merging stops if an external program corrupts the managed block structure—inspect the system hosts file first. + +Configuration files are limited to 1 MiB and 256 local profiles. System authorization prompts, file permissions, read-only disks, or security software may block changes; the UI displays actual errors and never claims success falsely. + +## Platforms & Requirements + +- Supported: macOS only +- Requires client version 1.1.8.5 or later. +- The Windows version is currently being reworked and is temporarily unavailable on the plugin marketplace for Windows. diff --git a/extensions/hosts-switcher/plugin.json b/extensions/hosts-switcher/plugin.json index d4e78d04..6aeb6cf3 100644 --- a/extensions/hosts-switcher/plugin.json +++ b/extensions/hosts-switcher/plugin.json @@ -1,8 +1,8 @@ { "id": "hosts-switcher", "name": "域名映射", - "version": "1.0.11", - "description": "保存并切换多套 Hosts 方案;Mac 写入前预览、校验和备份,通过系统授权应用并支持恢复", + "version": "1.0.12", + "description": "保存并切换多套 Hosts 方案;写入前预览、校验与备份,经受控提权写应用并支持读回核验与恢复", "author": "ZTools Team", "category": [ "网络工具" @@ -12,6 +12,12 @@ "icon": "icon.svg", "nativeComponents": [], "targets": [ + { + "id": "windows-electron-any", + "platform": "windows", + "runtime": "electron", + "arch": "any" + }, { "id": "macos-electron-any", "platform": "macos", @@ -59,13 +65,18 @@ "i18n": { "en-US": { "name": "Hosts Switcher", - "description": "Manage and switch between multiple Hosts profiles. On macOS, previews, validates, and backs up before applying via system authorization with restore support.", + "description": "Manage and switch between multiple Hosts profiles across Windows and macOS with preview, validation, backup, readback verification, and restore support.", "keywords": [ "hosts", "dns", "switchhosts", "domain mapping", - "network" + "network", + "hosts switcher", + "local dns", + "etc hosts", + "flush dns", + "switch hosts" ], "features": { "hosts-all": { @@ -108,5 +119,15 @@ { "path": "screenshots/02-action-panel.png" } + ], + "keywords": [ + "hosts", + "域名映射", + "改hosts", + "切换hosts", + "本地域名", + "屏蔽域名", + "刷新dns", + "hosts管理" ] } diff --git a/extensions/hosts-switcher/src/hosts-service.ts b/extensions/hosts-switcher/src/hosts-service.ts index 18f88b83..b20f9c64 100644 --- a/extensions/hosts-switcher/src/hosts-service.ts +++ b/extensions/hosts-switcher/src/hosts-service.ts @@ -1,266 +1,5 @@ -import { callHostTransport } from './native-ipc.js' -import { t } from './i18n.js' -import type { HostRule, HostsProfile } from './types.js' -import { resolveErrorMessage } from './error-i18n.js' - -export function isValidIpAddress(ip: string): boolean { - const trimmed = String(ip ?? '').trim() - // IPv4 - const ipv4Match = trimmed.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/) - if (ipv4Match) { - for (let i = 1; i <= 4; i++) { - const n = Number(ipv4Match[i]) - if (!Number.isInteger(n) || n < 0 || n > 255) return false - } - return true - } - // IPv6 basic check (e.g. ::1, fe80::1, 2001:db8::1) - if (trimmed.includes(':') && /^[0-9a-fA-F:]+$/.test(trimmed)) { - return true - } - return false -} - -export function isValidDomainName(domain: string): boolean { - const trimmed = String(domain ?? '').trim() - if (!trimmed || trimmed.length > 253) return false - if (trimmed === 'localhost') return true - return /^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+$/.test( - trimmed - ) -} - -export function parseHostsContent(rawContent: string): HostRule[] { - const lines = String(rawContent ?? '').replace(/\r\n/g, '\n').split('\n') - const rules: HostRule[] = [] - - for (const rawLine of lines) { - const trimmed = rawLine.trim() - if (!trimmed || trimmed.startsWith('#')) continue - - const hashIdx = trimmed.indexOf('#') - const mainPart = (hashIdx >= 0 ? trimmed.slice(0, hashIdx) : trimmed).trim() - const comment = hashIdx >= 0 ? trimmed.slice(hashIdx + 1).trim() : undefined - - const tokens = mainPart.split(/\s+/).filter(Boolean) - if (tokens.length < 2) { - rules.push({ - ip: tokens[0] || '', - domain: '', - comment, - isValid: false, - rawLine - }) - continue - } - - const ip = tokens[0]! - const ipOk = isValidIpAddress(ip) - for (let i = 1; i < tokens.length; i++) { - const domain = tokens[i]! - const domainOk = isValidDomainName(domain) - rules.push({ - ip, - domain, - comment, - isValid: ipOk && domainOk, - rawLine - }) - } - } - - return rules -} - /** - * 合并多个已启用的 Hosts 方案(跳过语法错误行,同一域名后面的启用方案覆盖或去重) + * Hosts 管理服务统一出口:双端均走 `hosts_manager` 专用宿主 IPC,彻底移除旧 HostsSwitcherPlugin DLL 调用。 */ -export function buildCombinedHostsContent(profiles: HostsProfile[]): { - combinedContent: string - activeRulesCount: number - skippedInvalidCount: number -} { - const enabledProfiles = profiles.filter((p) => p.isEnabled) - const domainMap = new Map() - let skippedInvalidCount = 0 - - for (const profile of enabledProfiles) { - const parsed = parseHostsContent(profile.rawContent) - for (const rule of parsed) { - if (!rule.isValid) { - skippedInvalidCount++ - continue - } - const key = `${rule.domain.toLowerCase()}` - domainMap.set(key, { - ip: rule.ip, - domain: rule.domain, - profileName: profile.name, - comment: rule.comment - }) - } - } - - const lines: string[] = [ - '# ============================================================', - '# Generated by ZTools Hosts Switcher (Atomic Managed)', - '# ============================================================' - ] - - for (const item of domainMap.values()) { - const commentSuffix = item.comment ? ` # ${item.comment} [${item.profileName}]` : ` # [${item.profileName}]` - lines.push(`${item.ip.padEnd(16, ' ')} ${item.domain}${commentSuffix}`) - } - - return { - combinedContent: lines.join('\n') + '\n', - activeRulesCount: domainMap.size, - skippedInvalidCount - } -} - -/** 根据当前运行时语言动态生成首次初始化默认 Hosts 方案,避免模块顶层静态冻结 */ -export function getDefaultHostsProfiles(): HostsProfile[] { - return [ - { - id: 'hosts-system', - name: t('defaultSystemName'), - isEnabled: true, - isSystem: true, - rawContent: '127.0.0.1 localhost\n::1 localhost', - rulesCount: 2, - invalidCount: 0, - updatedAt: 1700000000000, - updatedAtFormatted: '2026-10-25 10:00' - }, - { - id: 'hosts-local-dev', - name: t('defaultLocalDevName'), - isEnabled: false, - isSystem: false, - rawContent: [ - t('defaultLocalDevComment'), - '127.0.0.1 dev.ztools.local', - '127.0.0.1 api-dev.ztools.local', - '127.0.0.1 auth-dev.ztools.local' - ].join('\n'), - rulesCount: 3, - invalidCount: 0, - updatedAt: 1700000000000, - updatedAtFormatted: '2026-10-25 11:20' - }, - { - id: 'hosts-staging', - name: t('defaultStagingName'), - isEnabled: false, - isSystem: false, - rawContent: [ - t('defaultStagingComment'), - '192.168.10.50 staging.example.com', - '192.168.10.51 mysql.staging.example.com', - '192.168.10.52 redis.staging.example.com' - ].join('\n'), - rulesCount: 3, - invalidCount: 0, - updatedAt: 1700000000000, - updatedAtFormatted: '2026-10-25 09:15' - }, - { - id: 'hosts-github', - name: t('defaultGithubName'), - isEnabled: false, - isSystem: false, - rawContent: [ - '140.82.113.4 github.com', - '185.199.108.133 raw.githubusercontent.com' - ].join('\n'), - rulesCount: 2, - invalidCount: 0, - updatedAt: 1700000000000, - updatedAtFormatted: '2026-10-24 18:00' - } - ] -} - -// 宿主只读写系统 hosts,调用方不能指定其他路径,所以这里不提供路径选项 -export async function readSystemHosts( - options?: Record, - hostOverride?: unknown -): Promise<{ ok: boolean; content: string; path?: string }> { - const res = await callHostTransport<{ content?: string; hostsPath?: string; path?: string }>( - 'dllplugin_call', - { - plugin: 'HostsSwitcherPlugin', - func: 'readSystemHosts', - params: options || {} - }, - hostOverride - ) - if (res.ok && typeof res.data?.content === 'string') { - return { ok: true, content: res.data.content, path: res.data.hostsPath ?? res.data.path } - } - return { ok: false, content: '' } -} - -/** 从 "CODE: 说明" 形式的宿主错误里取错误码;宿主失败回执经传输层解包后只剩错误文本 */ -function errorCodeFromMessage(message: string | undefined): string | undefined { - return String(message ?? '').match(/^([A-Z][A-Z0-9_]+):/)?.[1] -} - -export async function applyCombinedHosts( - content: string, - options?: { skipFlushDns?: boolean }, - hostOverride?: unknown -): Promise<{ success: boolean; errorCode?: string; error?: string; warnings?: string[] }> { - const res = await callHostTransport<{ errorCode?: string; error?: string; warnings?: unknown }>( - 'dllplugin_call', - { - plugin: 'HostsSwitcherPlugin', - func: 'applyCombinedHosts', - params: { - content, - ...options - } - }, - hostOverride - ) - if (!res.ok) { - const error = resolveErrorMessage(res.error ? res : res.data, t('errWriteSystemHostsFailed')) - return { - success: false, - errorCode: res.data?.errorCode || errorCodeFromMessage(error) || 'WRITE_FAILED', - error - } - } - // 宿主已写入但部分步骤失败(如刷新 DNS 缓存失败)时会带回警告,必须原样交给界面,不能只报成功 - const warnings = Array.isArray(res.data?.warnings) - ? res.data.warnings.filter((w): w is string => typeof w === 'string' && w.trim().length > 0) - : [] - return warnings.length ? { success: true, warnings } : { success: true } -} - -export async function flushDnsCache( - options?: { dryRun?: boolean }, - hostOverride?: unknown -): Promise<{ success: boolean; output: string; error?: string }> { - const res = await callHostTransport<{ output?: string; error?: string }>( - 'dllplugin_call', - { - plugin: 'HostsSwitcherPlugin', - func: 'flushDns', - params: options || {} - }, - hostOverride - ) - if (!res.ok) { - return { - success: false, - output: '', - error: resolveErrorMessage(res.error ? res : res.data, t('errFlushDnsFailed')) - } - } - return { - success: true, - output: res.data?.output || t('toastFlushDnsSuccess') - } -} +export * from './mac-service.js' +export * from './mac-model.js' diff --git a/extensions/hosts-switcher/src/index.tsx b/extensions/hosts-switcher/src/index.tsx index f4b76ed8..1fbad271 100644 --- a/extensions/hosts-switcher/src/index.tsx +++ b/extensions/hosts-switcher/src/index.tsx @@ -1,10 +1,12 @@ import React, { Action, ActionPanel, List, useEffect, useLocale, useState } from '@ztools/declarative-ui' -import WindowsCommand, { type HostsSwitcherCommandProps } from './windows-command.js' import MacHostsCommand from './mac-command.js' import { hostsInvoke } from './mac-service.js' import { t } from './i18n.js' export * from './mac-model.js' export * from './mac-service.js' +export interface HostsSwitcherCommandProps { + featureCode?: string +} export default function HostsCommand(props: HostsSwitcherCommandProps = {}) { useLocale() const [platform, setPlatform] = useState(''), [error, setError] = useState(''), [attempt, setAttempt] = useState(0) @@ -16,8 +18,7 @@ export default function HostsCommand(props: HostsSwitcherCommandProps = {}) { }).catch(e => { if (alive) setError(e instanceof Error ? e.message : String(e)) }) return () => { alive = false } }, [attempt]) - if (platform === 'macos') return MacHostsCommand({ featureCode: props.featureCode }) - if (platform === 'windows') return WindowsCommand(props) + if (platform === 'macos' || platform === 'windows') return MacHostsCommand({ featureCode: props.featureCode }) return setAttempt(attempt + 1)} />} /> } export const commands = { diff --git a/extensions/hosts-switcher/src/mac-command.tsx b/extensions/hosts-switcher/src/mac-command.tsx index 40193ab0..dcbf74a2 100644 --- a/extensions/hosts-switcher/src/mac-command.tsx +++ b/extensions/hosts-switcher/src/mac-command.tsx @@ -24,7 +24,7 @@ export function ProfileForm({ initial, saved }: { initial?: Profile; saved: () = finally { active.current = false; if (alive.current) setBusy(false) } } return
}> - + {error && } diff --git a/extensions/hosts-switcher/src/native-ipc.ts b/extensions/hosts-switcher/src/native-ipc.ts index 51576b99..13643277 100644 --- a/extensions/hosts-switcher/src/native-ipc.ts +++ b/extensions/hosts-switcher/src/native-ipc.ts @@ -174,11 +174,13 @@ function normalizeMethodResult(method: string, payload: DynamicBridge): DynamicB if (method === 'system_get_battery_status') { // 宿主约定 percent 超出 0-100(如 255)表示无电池或电量未知,不能改写成 100% + // 若宿主明确给出 hasBattery 布尔值,必须原样保留,仅在缺失时按合法电量推算 const rawPct = payload.percent - const hasBattery = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const validPct = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const hasBattery = typeof payload.hasBattery === 'boolean' ? payload.hasBattery : validPct return { ...payload, - percent: hasBattery ? rawPct : null, + percent: validPct ? rawPct : null, hasBattery } } @@ -489,6 +491,8 @@ export interface RealDirectoryScanResult extends Iterable approximate?: boolean /** 宿主实际遍历的条目数 */ visitedEntries?: number + /** 目录本身不存在(ENOENT) */ + missing?: boolean /** 读取失败的真实原因;已有文件仍可使用,但不能当作完整结果。 */ error?: string } @@ -497,6 +501,7 @@ interface ScanResultMeta { truncated?: boolean approximate?: boolean visitedEntries?: number + missing?: boolean } export interface ScanDirectoryTreeOptions { @@ -504,6 +509,10 @@ export interface ScanDirectoryTreeOptions { maxFiles?: number collectTopN?: number filterExt?: RegExp + /** 为 true 时,目录本身不存在(ENOENT)按空目录处理,不返回 error(权限拒绝/读取失败仍照常报错) */ + ignoreMissing?: boolean + /** Top-N 保留与排序方式:默认按体积降序,下载/录屏等时效场景可传 mtime-desc */ + sortBy?: 'size-desc' | 'mtime-desc' hostOverride?: DynamicBridge } @@ -519,8 +528,9 @@ function normalizeIndexedFileEntry(f: DynamicBridge): RealIndexedFileEntry { const sz = Number(f?.size ?? f?.sizeBytes ?? 0) const isDir = Boolean(f?.is_dir || f?.isDir || f?.isDirectory) const rawMtime = Number(f?.mtime ?? f?.mtimeMs ?? 0) - const mtimeMs = rawMtime > 1e11 ? rawMtime : rawMtime > 0 ? rawMtime * 1000 : Date.now() - const mtimeSec = rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime + const validMtime = Number.isFinite(rawMtime) && rawMtime > 0 + const mtimeMs = validMtime ? (rawMtime > 1e11 ? rawMtime : rawMtime * 1000) : 0 + const mtimeSec = validMtime ? (rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime) : 0 if (p && sz >= 0) realFileSizeCache.set(p, sz) return { name, @@ -551,6 +561,7 @@ function makeScanResult( subdirs, ...(meta.truncated ? { truncated: true } : {}), ...(meta.approximate ? { approximate: true } : {}), + ...(meta.missing ? { missing: true } : {}), ...(typeof meta.visitedEntries === 'number' ? { visitedEntries: meta.visitedEntries } : {}), [Symbol.iterator]() { return files[Symbol.iterator]() @@ -609,13 +620,40 @@ export async function scanRealDirectoryTree( return result.error ? { ...result.scan, error: result.error } : result.scan } +/** 仅当正则明确声明了扩展名(含 `\.`)时提取后缀列表,避免把 `thumbcache|iconcache` 等文件名关键词误拆成假扩展名 */ +function extractExtensionTokensFromFilter(filterExt: RegExp): string[] { + const src = filterExt.source + if (!src.includes('\\.')) return [] + const afterDot = src.slice(src.indexOf('\\.') + 2) + const rawTokens = afterDot.match(/[a-z0-9]{1,8}/gi) || [] + const seen = new Set() + const out: string[] = [] + for (const token of rawTokens) { + const lower = token.toLowerCase() + if (!lower || seen.has(lower)) continue + seen.add(lower) + out.push(lower) + } + return out +} + +function isMissingDirectoryError(res: { error?: string; errorCode?: string; errorDetails?: Record }): boolean { + if (res.errorDetails?.reason === 'ENOENT' || res.errorCode === 'ENOENT') return true + const msg = String(res.error || '') + return /Directory does not exist|ENOENT/i.test(msg) +} + /** 一次界面扫描的错误汇总;多个目录并行扫描时保留可读目录的结果。 */ export function createDirectoryScanner(hostOverride?: DynamicBridge) { const failures = new Map() return { async scan(dir: string, options: number | ScanDirectoryTreeOptions = 160) { const result = await scanRealDirectoryTree(dir, options, hostOverride) - const error = result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') + const ignoreMissing = typeof options === 'object' && options !== null && options.ignoreMissing === true + const error = + result.missing && ignoreMissing + ? '' + : result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') if (error) failures.set(dir, error) else failures.delete(dir) return result @@ -648,26 +686,38 @@ async function scanDirectoryTreeWithError( const safeLimit = Math.min(200, Math.max(1, Math.floor(rawLimit || 160))) const hostOverride = opts.hostOverride const filterExt = opts.filterExt + const ignoreMissing = opts.ignoreMissing === true const dirQuery = `dir:${targetDir}` try { let rawPayload: DynamicBridge = null + const searchParams: Record = { + query: dirQuery, + limit: safeLimit, + ...(opts.sortBy ? { sortBy: opts.sortBy } : {}) + } const res = await callHostTransport( 'system_search_files', - { query: dirQuery, limit: safeLimit }, + searchParams, hostOverride ) - if (res.ok && res.data) { + if (res.ok && res.data && res.data.degraded !== true) { rawPayload = res.data + } else if (!res.ok && ignoreMissing && isMissingDirectoryError(res)) { + const missingScan = makeScanResult([], 0, 0, [], { missing: true }) + return { scan: missingScan } } - if (!rawPayload && !hostOverride && typeof window !== 'undefined') { + if (!rawPayload && !hostOverride && res.errorCode === 'METHOD_NOT_AVAILABLE' && typeof window !== 'undefined') { const w = window as DynamicBridge if (typeof w.__ztoolsLauncher?.searchFiles === 'function') { const rawOuter = await w.__ztoolsLauncher.searchFiles(dirQuery, safeLimit) - rawPayload = + const candidate = rawOuter && typeof rawOuter === 'object' && 'data' in rawOuter && rawOuter.data ? rawOuter.data : rawOuter + if (candidate && candidate.degraded !== true && candidate.success !== false) { + rawPayload = candidate + } } } @@ -678,29 +728,32 @@ async function scanDirectoryTreeWithError( let files: RealIndexedFileEntry[] = rawPayload.files.map(normalizeIndexedFileEntry) if (filterExt instanceof RegExp) { files = files.filter(f => !f.isDir && (filterExt.test(f.name) || filterExt.test(f.ext))) - // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索目标扩展名 + // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索明确声明的目标扩展名 if (files.length === 0 && !hostOverride) { - const extTokens = (filterExt.source.match(/[a-z0-9]{2,5}/gi) || []) - .filter(t => !['thumbcache', 'iconcache'].includes(t.toLowerCase())) - .slice(0, 4) - // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 - const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() - const extraLists = await Promise.all( - extTokens.map(ext => searchRealIndexedFiles(`.${ext.toLowerCase()}`, 30, hostOverride)) - ) - const seen = new Set() - for (const list of extraLists) { - for (const item of list) { - if (!item.isDir && item.size > 0 && !seen.has(item.path)) { - if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { - seen.add(item.path) - files.push(item) + const extTokens = extractExtensionTokensFromFilter(filterExt) + if (extTokens.length > 0) { + // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 + const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() + const extraLists = await Promise.all( + extTokens.map(ext => searchRealIndexedFiles(`.${ext}`, 30, hostOverride)) + ) + const seen = new Set() + for (const list of extraLists) { + for (const item of list) { + if (!item.isDir && item.size > 0 && !seen.has(item.path)) { + if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { + seen.add(item.path) + files.push(item) + } } } } } } } + // 先基于过滤后的完整命中集合计算总文件数与总字节数,再按 collectTopN 裁剪样本列表 + const matchedCount = files.length + const matchedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) if (typeof opts.collectTopN === 'number' && opts.collectTopN > 0 && files.length > opts.collectTopN) { files = files.slice(0, opts.collectTopN) } @@ -714,11 +767,10 @@ async function scanDirectoryTreeWithError( ...(s.approximate === true ? { approximate: true } : {}) })) : [] - const computedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) const totalFilesCount = - filterExt instanceof RegExp ? files.length : Number(rawPayload.total_matches ?? files.length) + filterExt instanceof RegExp ? matchedCount : Number(rawPayload.total_matches ?? matchedCount) const totalBytesCount = - filterExt instanceof RegExp ? computedBytes : Number(rawPayload.total_bytes ?? computedBytes) + filterExt instanceof RegExp ? matchedBytes : Number(rawPayload.total_bytes ?? matchedBytes) const visited = Number(rawPayload.visited_entries) return { scan: makeScanResult(files, totalFilesCount, totalBytesCount, subdirs, { @@ -1817,8 +1869,6 @@ export async function writeRealClipboardText(text: string, hostOverride?: Dynami const payload = { text: String(text || '') } const res = await callHostTransport('clipboard_copy_text', payload, hostOverride) if (res.ok) return true - const fallbackRes = await callHostTransport('clipboard_write_text', payload, hostOverride) - if (fallbackRes.ok) return true try { if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) { await navigator.clipboard.writeText(String(text || '')) diff --git a/extensions/hosts-switcher/src/windows-command.tsx b/extensions/hosts-switcher/src/windows-command.tsx index 3bba1d29..1d176014 100644 --- a/extensions/hosts-switcher/src/windows-command.tsx +++ b/extensions/hosts-switcher/src/windows-command.tsx @@ -1,365 +1,10 @@ -import React, { - Action, - ActionPanel, - Form, - Icon, - List, - Toast, - showToast, - useLocale, - useMemo, - useRef, - useState, - useNavigation -} from '@ztools/declarative-ui' -import { - applyCombinedHosts, - buildCombinedHostsContent, - flushDnsCache, - getDefaultHostsProfiles, - parseHostsContent, - readSystemHosts -} from './hosts-service.js' -import { t } from './i18n.js' -import type { HostsProfile } from './types.js' - -export * from './types.js' -export * from './hosts-service.js' - -export function HostsProfileForm({ - initialProfile, - onSave -}: { - initialProfile?: HostsProfile - onSave: (profile: HostsProfile) => void -}) { - useLocale() - const { pop } = useNavigation() - const [name, setName] = useState(initialProfile?.name ?? '') - const [rawContent, setRawContent] = useState( - initialProfile?.rawContent ?? '127.0.0.1 example.local' - ) - - const handleSubmit = async () => { - if (!name.trim()) { - await showToast({ style: Toast.Style.Failure, title: t('errProfileNameEmpty') }) - return - } - const rules = parseHostsContent(rawContent) - const validCount = rules.filter((r) => r.isValid).length - const invalidCount = rules.filter((r) => !r.isValid).length - - onSave({ - id: initialProfile?.id || `hosts-${Date.now()}`, - name: name.trim(), - isEnabled: initialProfile?.isEnabled ?? true, - isSystem: initialProfile?.isSystem ?? false, - rawContent, - rulesCount: validCount, - invalidCount, - updatedAt: Date.now(), - updatedAtFormatted: t('justUpdated') - }) - await showToast({ style: Toast.Style.Success, title: t('toastProfileSaved', { name: name.trim() }) }) - pop() - } - - return ( -
- - - } - > - - - - ) -} +import MacHostsCommand from './mac-command.js' export interface HostsSwitcherCommandProps { featureCode?: string - initialProfiles?: HostsProfile[] - hostOverride?: unknown } -export function HostsSwitcherCommand(props: HostsSwitcherCommandProps = {}) { - const locale = useLocale() - const { push } = useNavigation() - const lastDefaultsRef = useRef(null) - const [profiles, setProfiles] = useState(() => { - if (props.initialProfiles) return props.initialProfiles - const defaults = getDefaultHostsProfiles() - lastDefaultsRef.current = defaults - return defaults - }) - const [filterStatus, setFilterStatus] = useState<'all' | 'enabled' | 'disabled'>('all') - const [searchText, setSearchText] = useState('') - const [isLoading, setIsLoading] = useState(false) - - // 运行时切换语言时,仅同步尚未被用户改写或系统读回覆盖的默认预置方案名称与注释 - React.useEffect(() => { - if (!props.initialProfiles) { - const prevDefaults = lastDefaultsRef.current ?? [] - const nextDefaults = getDefaultHostsProfiles() - lastDefaultsRef.current = nextDefaults - setProfiles((prev) => - prev.map((p) => { - const prevDef = prevDefaults.find((d) => d.id === p.id) - const nextDef = nextDefaults.find((d) => d.id === p.id) - if (!prevDef || !nextDef) return p - return { - ...p, - name: p.name === prevDef.name ? nextDef.name : p.name, - rawContent: p.rawContent === prevDef.rawContent ? nextDef.rawContent : p.rawContent - } - }) - ) - } - }, [locale, props.initialProfiles]) - - React.useEffect(() => { - if (!props.initialProfiles) { - void (async () => { - const sysRes = await readSystemHosts(undefined, props.hostOverride) - if (sysRes.ok && sysRes.content.trim()) { - const rules = parseHostsContent(sysRes.content) - const validCount = rules.filter((r) => r.isValid).length - const invalidCount = rules.filter((r) => !r.isValid).length - setProfiles((prev) => - prev.map((p) => - p.id === 'hosts-system' - ? { - ...p, - rawContent: sysRes.content, - rulesCount: validCount, - invalidCount - } - : p - ) - ) - } - })() - } - }, []) - - const filteredProfiles = useMemo(() => { - const byStatus = profiles.filter((p) => { - if (filterStatus === 'enabled') return p.isEnabled - if (filterStatus === 'disabled') return !p.isEnabled - return true - }) - const q = searchText.trim().toLowerCase() - if (!q) return byStatus - return byStatus.filter( - (p) => p.name.toLowerCase().includes(q) || p.rawContent.toLowerCase().includes(q) - ) - }, [profiles, filterStatus, searchText]) - - const activeCount = useMemo( - () => profiles.filter((p) => p.isEnabled).length, - [profiles] - ) - - const handleToggleProfile = async (profileId: string) => { - const previous = profiles - const next = profiles.map((p) => - p.id === profileId ? { ...p, isEnabled: !p.isEnabled } : p - ) - setProfiles(next) - setIsLoading(true) - try { - const merged = buildCombinedHostsContent(next) - const res = await applyCombinedHosts(merged.combinedContent, undefined, props.hostOverride) - if (!res.success) { - // 系统 hosts 没有写入:启用状态退回原样,不能显示成已切换 - setProfiles(previous) - await showToast({ - style: Toast.Style.Failure, - title: t('toastWriteBlocked'), - message: res.error - }) - return - } - if (res.warnings?.length) { - // 已写入但刷新 DNS 等后续步骤失败:如实说明,不能提示“已刷新” - const detail = res.warnings.map((w) => w.replace(/^hosts 已写入,但/, '')).join(';') - await showToast({ - style: Toast.Style.Success, - title: t('toastWrittenWithWarnings', { count: merged.activeRulesCount, detail }) - }) - return - } - await showToast({ - style: Toast.Style.Success, - title: t('toastAppliedAndFlushed', { count: merged.activeRulesCount }) - }) - } finally { - setIsLoading(false) - } - } - - const handleFlushDns = async () => { - setIsLoading(true) - try { - const res = await flushDnsCache(undefined, props.hostOverride) - if (!res.success) { - await showToast({ - style: Toast.Style.Failure, - title: t('errFlushDnsFailed'), - message: res.error - }) - return - } - await showToast({ - style: Toast.Style.Success, - title: t('toastFlushDnsSuccess') - }) - } finally { - setIsLoading(false) - } - } - - const handleOpenCreateForm = () => { - push( - { - setProfiles((prev) => [...prev, created]) - }} - /> - ) - } - - const handleEditProfile = (profile: HostsProfile) => { - push( - { - setProfiles((prev) => prev.map((p) => (p.id === updated.id ? updated : p))) - }} - /> - ) - } - - const handleDeleteProfile = async (id: string) => { - setProfiles((prev) => prev.filter((p) => p.id !== id)) - await showToast({ style: Toast.Style.Success, title: t('toastProfileDeleted') }) - } - - return ( - setFilterStatus(v as 'all' | 'enabled' | 'disabled')} - tooltip={t('winFilterTooltip')} - > - - - -
- } - filterBar={{ - summaryText: t('winSummaryText', { total: profiles.length, active: activeCount }), - actions: [ - { id: 'new-profile', title: t('winBarNewProfile'), onAction: handleOpenCreateForm }, - { id: 'flush-dns', title: t('winBarFlushDns'), onAction: handleFlushDns } - ] - }} - > - {filteredProfiles.map((profile) => ( - - - - - - - - } - /> - } - actions={ - - handleToggleProfile(profile.id)} - /> - handleEditProfile(profile)} - /> - - - {!profile.isSystem ? ( - handleDeleteProfile(profile.id)} - /> - ) : null} - - } - /> - ))} -
- ) +/** Windows 已并入统一 hosts_manager 宿主 IPC,彻底移除旧 HostsSwitcherPlugin DLL 分支 */ +export default function WindowsHostsCommand(props: HostsSwitcherCommandProps = {}) { + return MacHostsCommand({ featureCode: props.featureCode }) } - -export default HostsSwitcherCommand diff --git a/extensions/hosts-switcher/tests/hosts-switcher.test.mjs b/extensions/hosts-switcher/tests/hosts-switcher.test.mjs index ca423fc8..16161694 100644 --- a/extensions/hosts-switcher/tests/hosts-switcher.test.mjs +++ b/extensions/hosts-switcher/tests/hosts-switcher.test.mjs @@ -116,53 +116,40 @@ test('编辑启用方案产生冲突后仍可停用旧系统内容,保留已 assert.equal(state.content,base);assert.equal((await loadProfiles())[0].content,'127.0.0.3 localhost');assert.match(view.text(),/未启用/) }) -// ==================== Windows 旧入口:宿主回执如实透传 ==================== -const winHosts = '127.0.0.1 localhost\r\n' -function windowsHost(applyReply) { +// ==================== Windows 双端统一走 hosts_manager IPC(零 DLL) ==================== +test('Windows:走统一 hosts_manager IPC 读取与预览应用,保留 CRLF,不调用 dllplugin_call', async () => { host.ipc.system_get_platform = async () => ({ success: true, platform: 'windows' }) - host.ipc.dllplugin_call = async p => { - if (p.func === 'readSystemHosts') return { ok: true, success: true, content: winHosts, hostsPath: 'C:\\Windows\\System32\\drivers\\etc\\hosts' } - if (p.func === 'applyCombinedHosts') return applyReply(p) - if (p.func === 'flushDns') return { ok: true, success: true, output: '已成功刷新 DNS 解析缓存。' } - throw new Error('unexpected request') - } -} -const applyCalls = () => host.ipcCalls.filter(([m, p]) => m === 'dllplugin_call' && p.func === 'applyCombinedHosts') -test('Windows:写入成功但刷新 DNS 失败时,成功提示如实写明“已写入,但刷新 DNS 缓存失败”,不再宣称已刷新', async () => { - windowsHost(() => ({ ok: true, success: true, hostsPath: 'C:\\hosts', warnings: ['hosts 已写入,但刷新 DNS 缓存失败:拒绝访问。'] })) + state.path = 'C:\\Windows\\System32\\drivers\\etc\\hosts' + seed() const view = await open() - assert.doesNotMatch(view.text(), /DNS 缓存已处于最新/) - await view.run(view.item('hosts-local-dev'), '启用此方案') - const toast = host.lastToast() - assert.equal(toast.style, Toast.Style.Success) - assert.match(toast.title, /^已写入 \(\d+ 条映射\),但刷新 DNS 缓存失败:拒绝访问/) - assert.doesNotMatch(toast.title, /并刷新 DNS/) - assert.equal(applyCalls().length, 1) - assert.equal('customHostsPath' in applyCalls()[0][1].params, false, '不再发送宿主忽略的 customHostsPath') - assert.equal(view.item('hosts-local-dev').props.accessories.at(-1).text, '已启用') - // 宿主没有警告才显示已刷新 - windowsHost(() => ({ ok: true, success: true, hostsPath: 'C:\\hosts' })) - await view.run(view.item('hosts-staging'), '启用此方案') - assert.match(host.lastToast().title, /已生效 \(\d+ 条映射\) 并刷新 DNS/) -}) -test('Windows:备份失败宿主停止写入,界面报失败并保留错误码,方案启用状态退回', async () => { - windowsHost(() => ({ ok: false, success: false, errorCode: 'BACKUP_FAILED', error: 'BACKUP_FAILED: 备份系统 hosts 到 C:\\hosts.ztools.bak 失败(权限不足),已停止写入,系统 hosts 未改动' })) + assert.equal(calls('read').length, 1) + assert.ok(!host.ipcCalls.some(([m]) => m === 'dllplugin_call')) + await view.run(view.item(profile.id), '预览并启用方案') + const preview = await pushed() + assert.match(preview.text(), /drivers.+etc.+hosts/) + await preview.run(undefined, '确认应用到系统') + assert.equal(calls('apply').length, 1) + assert.equal(splitHosts(state.content).base, base) + assert.ok(!host.ipcCalls.some(([m]) => m === 'dllplugin_call')) +}) +test('Windows:Defender 拦截或权限不足时原样报失败,不谎报成功', async () => { + host.ipc.system_get_platform = async () => ({ success: true, platform: 'windows' }) + state.path = 'C:\\Windows\\System32\\drivers\\etc\\hosts' + seed() const view = await open() - await view.run(view.item('hosts-local-dev'), '启用此方案') - const toast = host.lastToast() - assert.equal(toast.style, Toast.Style.Failure) - assert.match(toast.message, /BACKUP_FAILED.*已停止写入/) - assert.equal(view.item('hosts-local-dev').props.accessories.at(-1).text, '未激活', '写入失败不能显示成已启用') - const { applyCombinedHosts } = await import('../dist/hosts-service.js') - const backup = await applyCombinedHosts('x', undefined) - assert.equal(backup.success, false); assert.equal(backup.errorCode, 'BACKUP_FAILED') - // 传输层故障与无错误码文本:不再一律报成 EACCES - host.ipc.dllplugin_call = async () => { throw new Error('通道断开') } - const broken = await applyCombinedHosts('x', undefined) - assert.equal(broken.success, false); assert.equal(broken.errorCode, 'WRITE_FAILED'); assert.match(broken.error, /通道断开/) - // 畸形警告(非字符串、空白)被丢弃,不会冒充成功提示内容 - host.ipc.dllplugin_call = async () => ({ ok: true, success: true, warnings: [42, ' ', null] }) - assert.deepEqual(await applyCombinedHosts('x', undefined), { success: true }) + const real = host.ipc.hosts_manager + host.ipc.hosts_manager = async p => { + if (p.action === 'apply') { + throw new Error('HOSTS_VERIFY_MISMATCH: 写入后读回校验不一致(可能被 Microsoft Defender HostsFileHijack 拦截还原)') + } + return real(p) + } + await view.run(view.item(profile.id), '预览并启用方案') + const preview = await pushed() + await preview.run(undefined, '确认应用到系统') + assert.match(preview.text(), /HOSTS_VERIFY_MISMATCH/) + assert.ok(!host.toasts.some(t => t.style === Toast.Style.Success)) + assert.equal(state.content, base) }) test('Mac:写入成功后重新读取失败,仍报告已写入而不是“结果未确认”', async () => { diff --git a/extensions/hosts-switcher/tests/i18n.test.mjs b/extensions/hosts-switcher/tests/i18n.test.mjs index 4583c4e9..9aa5c5d8 100644 --- a/extensions/hosts-switcher/tests/i18n.test.mjs +++ b/extensions/hosts-switcher/tests/i18n.test.mjs @@ -3,9 +3,8 @@ import assert from 'node:assert/strict' import fs from 'node:fs' import { setRuntimeLocale } from '@ztools/declarative-ui' import { validatePluginManifest } from '../../../packages/ztools-plugins-spec/src/validator.js' -import { createHost, mount, mountPushed, tick } from '../../shared/test-harness.mjs' +import { createHost, mount, tick } from '../../shared/test-harness.mjs' import HostsCommand from '../dist/index.js' -import { getDefaultHostsProfiles } from '../dist/hosts-service.js' import { t } from '../dist/i18n.js' let host @@ -15,12 +14,14 @@ test.beforeEach(() => { setRuntimeLocale('zh-CN') }) -test('plugin.json: 具备 defaultLocale、categoryId 与完整的 en-US 元数据及 features 映射', () => { +test('plugin.json: 具备 defaultLocale、categoryId、双端 targets 与完整的 en-US 元数据及 features 映射', () => { const manifest = JSON.parse(fs.readFileSync(new URL('../plugin.json', import.meta.url), 'utf8')) const validation = validatePluginManifest(manifest) assert.equal(validation.valid, true, `清单校验失败: ${validation.errors.join('; ')}`) assert.equal(manifest.defaultLocale, 'zh-CN') assert.equal(manifest.categoryId, 'network') + assert.ok(manifest.targets.some((t) => t.id === 'windows-electron-any')) + assert.ok(manifest.targets.some((t) => t.id === 'macos-electron-any')) const en = manifest.i18n?.['en-US'] assert.ok(en && typeof en === 'object') @@ -41,113 +42,50 @@ test('plugin.json: 具备 defaultLocale、categoryId 与完整的 en-US 元数 test('i18n 词典: zh-CN 与 en-US 翻译及插值输出正确,无空串与键名回退', () => { setRuntimeLocale('zh-CN') assert.equal(t('macNavTitle'), '域名映射') - assert.equal(t('winSummaryText', { total: 4, active: 1 }), '共 4 个方案(已激活 1 个)') assert.equal(t('errRuleInvalidLine', { line: 2 }), '第 2 行规则无效,请使用 IP 域名格式') setRuntimeLocale('en-US') assert.equal(t('macNavTitle'), 'Hosts Switcher') - assert.equal(t('winSummaryText', { total: 4, active: 1 }), '4 profiles (1 active)') assert.equal(t('errRuleInvalidLine', { line: 2 }), 'Invalid rule on line 2; use "IP domain" format') assert.doesNotMatch(t('macSummaryText', { localCount: 2, activeCount: 1 }), /[\u4e00-\u9fa5]|\{localCount\}|\{activeCount\}/) }) -test('默认预置 Hosts 方案按当前语言动态生成,英文态首次默认名称与注释均为纯英文', () => { - setRuntimeLocale('en-US') - const enProfiles = getDefaultHostsProfiles() - assert.equal(enProfiles.length, 4) - for (const profile of enProfiles) { - assert.ok(profile.name.trim().length > 0 && !/[\u4e00-\u9fa5]/.test(profile.name), `英文预设方案名含中文: ${profile.name}`) - assert.ok(!/[\u4e00-\u9fa5]/.test(profile.rawContent), `英文预设方案注释含中文: ${profile.rawContent}`) - } - assert.match(enProfiles.find((p) => p.id === 'hosts-local-dev').rawContent, /^# Local frontend & gateway mappings/) - assert.match(enProfiles.find((p) => p.id === 'hosts-staging').rawContent, /^# Example: map staging domains/) - - // 切回中文态应动态输出中文默认方案,而非静态冻结 - setRuntimeLocale('zh-CN') - const zhProfiles = getDefaultHostsProfiles() - assert.equal(zhProfiles.find((p) => p.id === 'hosts-system')?.name, '系统基础默认 Hosts') - assert.match(zhProfiles.find((p) => p.id === 'hosts-local-dev').rawContent, /^# 本地前端与网关调试映射/) -}) - -test('i18n 运行时热切换 (Windows 视图): zh-CN -> en-US -> zh-CN 同步默认方案名称与注释,不覆盖用户修改', async () => { - host.ipc.system_get_platform = async () => ({ success: true, platform: 'windows' }) - host.ipc.dllplugin_call = async (p) => { - if (p.func === 'readSystemHosts') return { ok: true, success: true, content: '127.0.0.1 localhost\n' } - return { ok: true, success: true } - } - - const view = await mount(HostsCommand, host) - try { - await tick(3) - assert.equal(view.item('hosts-system').props.title, '系统基础默认 Hosts') - assert.match(String(view.tree().props.filterBar?.summaryText), /共 4 个方案/) - - // 热切换至 en-US - setRuntimeLocale('en-US') - await tick(3) - assert.equal(view.item('hosts-system').props.title, 'System Default Hosts') - assert.equal(view.item('hosts-local-dev').props.title, 'Local Microservices Dev (Local Dev)') - assert.match(String(view.item('hosts-local-dev').props.detail?.props?.markdown), /# Local frontend & gateway mappings/) - assert.ok(!/[\u4e00-\u9fa5]/.test(view.text()), `en-US Windows 视图不应包含中文: ${view.text()}`) +for (const platform of ['windows', 'macos']) { + test(`i18n 运行时热切换 (${platform} 统一视图): zh-CN -> en-US -> zh-CN 实时更新且英文态无中文残留`, async () => { + host.ipc.system_get_platform = async () => ({ success: true, platform }) + host.ipc.hosts_manager = async (p) => { + if (p.action === 'read') { + return { + success: true, + sessionId: '11111111-1111-4111-8111-111111111111', + content: '127.0.0.1 localhost\r\n::1 localhost\r\n', + path: platform === 'windows' ? 'C:\\Windows\\System32\\drivers\\etc\\hosts' : '/private/etc/hosts', + backups: [] + } + } + if (p.action === 'cancel') return { success: true } + throw new Error(`unexpected action: ${p.action}`) + } - // 用户编辑其中一个方案后,切换语言不应覆盖用户修改的自定义名称与内容 - await view.run(view.item('hosts-staging'), 'Edit Profile') - const form = await mountPushed(host) + const view = await mount(HostsCommand, host) try { - await form.fill('name', 'My Custom Staging') - await form.fill('rawContent', '# Custom note\n10.0.0.8 custom.local') - await form.run(null, 'Save Profile') + await tick(3) + assert.equal(view.tree().props.navigationTitle, '域名映射') + assert.equal(view.item('system').props.title, '当前系统 Hosts') + + setRuntimeLocale('en-US') + await tick(3) + assert.equal(view.tree().props.navigationTitle, 'Hosts Switcher') + assert.equal(view.item('system').props.title, 'Current System Hosts') + assert.ok(!/[\u4e00-\u9fa5]/.test(view.text()), `en-US ${platform} 视图不应包含中文: ${view.text()}`) + + setRuntimeLocale('zh-CN') + await tick(3) + assert.equal(view.tree().props.navigationTitle, '域名映射') + assert.equal(view.item('system').props.title, '当前系统 Hosts') } finally { - form.unmount() + view.unmount() + await tick() } - await tick(2) - - // 热切换回 zh-CN - setRuntimeLocale('zh-CN') - await tick(3) - assert.equal(view.item('hosts-system').props.title, '系统基础默认 Hosts') - assert.equal(view.item('hosts-staging').props.title, 'My Custom Staging') - assert.match(String(view.item('hosts-staging').props.detail?.props?.markdown), /# Custom note/) - } finally { - view.unmount() - await tick() - } -}) - -test('i18n 运行时热切换 (macOS 视图): zh-CN -> en-US -> zh-CN 实时更新且英文态无中文残留', async () => { - host.ipc.system_get_platform = async () => ({ success: true, platform: 'macos' }) - host.ipc.hosts_manager = async (p) => { - if (p.action === 'read') { - return { - success: true, - sessionId: '11111111-1111-4111-8111-111111111111', - content: '127.0.0.1 localhost\n::1 localhost', - path: '/private/etc/hosts', - backups: [] - } - } - if (p.action === 'cancel') return { success: true } - throw new Error(`unexpected action: ${p.action}`) - } - - const view = await mount(HostsCommand, host) - try { - await tick(3) - assert.equal(view.tree().props.navigationTitle, '域名映射') - assert.equal(view.item('system').props.title, '当前系统 Hosts') - - setRuntimeLocale('en-US') - await tick(3) - assert.equal(view.tree().props.navigationTitle, 'Hosts Switcher') - assert.equal(view.item('system').props.title, 'Current System Hosts') - assert.ok(!/[\u4e00-\u9fa5]/.test(view.text()), `en-US macOS 视图不应包含中文: ${view.text()}`) - - setRuntimeLocale('zh-CN') - await tick(3) - assert.equal(view.tree().props.navigationTitle, '域名映射') - assert.equal(view.item('system').props.title, '当前系统 Hosts') - } finally { - view.unmount() - await tick() - } -}) + }) +} diff --git a/extensions/hosts/plugin.json b/extensions/hosts/plugin.json index 118e4d52..9a59bc12 100644 --- a/extensions/hosts/plugin.json +++ b/extensions/hosts/plugin.json @@ -3,6 +3,7 @@ "name": "Hosts 管理器", "description": "系统 Hosts 规则查看与切换", "version": "1.0.0", + "minAppVersion": "1.1.8.0", "revoked": true, "revokedReason": "功能未完成(只有示例数据)", "author": "ZTools Team", @@ -18,5 +19,14 @@ "arch": "any" } ], - "nativeComponents": [] + "nativeComponents": [], + "categoryId": "system", + "defaultLocale": "zh-CN", + "i18n": { + "en-US": { + "name": "Hosts Manager", + "description": "View and switch system Hosts rules.", + "revokedReason": "Feature incomplete (contains sample data only)." + } + } } diff --git a/extensions/hotkey-radar/README.en.md b/extensions/hotkey-radar/README.en.md new file mode 100644 index 00000000..87b11ee4 --- /dev/null +++ b/extensions/hotkey-radar/README.en.md @@ -0,0 +1,29 @@ +# Hotkey Radar & Cheatsheet + +Detect global shortcut registrations and browse offline keyboard shortcut cheatsheets. + +**macOS**: Enter `⇧⌘P` or `Shift+Cmd+P` on the detector view and press `Enter` to check, or `⌘Enter` to copy the selected combination. Switch cheatsheet apps on the right of the search bar; pressing `Enter` in the cheatsheet copies the Mac default shortcut. Both detector results and cheatsheets consistently use `⌃⌥⇧⌘` symbols; `⌘` and `⌃` are handled separately, `⌥` is Option (Alt), and the plus key is written as `Plus`. + +**macOS Result Meanings**: + +- **System Assigned**: This key combination is present in currently enabled macOS system keyboard shortcuts. +- **Exclusive Conflict**: macOS rejected another exclusive registration, though it does not expose the owning process name. +- **Registered by ZTools**: The current ZTools client holds this binding; checking does not unregister it. +- **Available for Exclusive Registration**: A temporary registration succeeded and was immediately released. **This does not guarantee there are no conflicts**: shared registrations in other apps, event taps, key remappers, and in-app shortcuts cannot be exhaustively enumerated. + +The macOS detector reads your current keyboard layout without modifying system keybindings or terminating processes. Results reflect the state at the moment of check only. When a request fails, a required component is missing, or the layout cannot be mapped, an error is shown rather than a false "available" result. Troubleshooting steps are available in the detector's action panel. + +**Windows**: A shortcut is reported as occupied only when Windows `RegisterHotKey` rejects it (system-reserved combinations such as `Win+L` and `Alt+Tab` are directly labeled as system-reserved), and currently running apps are shown only as possible sources; failed checks display "Hotkey check incomplete". Combinations containing unsupported keys display "Cannot detect". Press `Enter` on a result row to copy the combination, or type a `+`-separated combo in the search box to check it individually. In the Windows cheatsheet, `Enter` copies the Windows shortcut. + +Cheatsheets list default keybindings; custom bindings depend on each application's settings. References: [Apple Mac keyboard shortcuts](https://support.apple.com/zh-cn/102650), [VS Code macOS default shortcuts](https://code.visualstudio.com/shortcuts/keyboard-shortcuts-macos.pdf), [Excel keyboard shortcuts](https://support.microsoft.com/en-us/accessibility/excel/keyboard-shortcuts-in-excel), [Photoshop merge and stamp layers](https://helpx.adobe.com/photoshop/desktop/create-manage-layers/get-started-layers/merge-and-stamp-layers.html), [Chrome keyboard shortcuts](https://support.google.com/chrome/answer/157179), and [Edge keyboard shortcuts](https://support.microsoft.com/en-us/edge/keyboard-shortcuts-in-microsoft-edge). + +## Platforms & Requirements + +- Supported: Windows, macOS +- Requires client version 1.1.8.5 or later. +- macOS requires the client's Mac hotkey component; when running from source, build that component first. +- Windows implementation is pending physical-device verification. + +## Network & Data + +- Offline only; all data stays on your device. diff --git a/extensions/hotkey-radar/plugin.json b/extensions/hotkey-radar/plugin.json index 7c306878..e6abb722 100644 --- a/extensions/hotkey-radar/plugin.json +++ b/extensions/hotkey-radar/plugin.json @@ -1,7 +1,7 @@ { "id": "hotkey-radar", "name": "热键侦测", - "version": "1.0.9", + "version": "1.0.10", "description": "检测全局快捷键注册情况,离线查询系统与常用软件快捷键;Mac 区分 ⌘ 与 ⌃,不推测占用进程", "author": "ZTools Team", "entry": "dist/index.js", @@ -65,7 +65,11 @@ "shortcut", "conflict", "cheatsheet", - "keybindings" + "keybindings", + "shortcut conflict", + "hotkey radar", + "shortcuts", + "detect hotkey" ], "features": { "hotkey-conflict-radar": { @@ -101,5 +105,14 @@ { "path": "screenshots/02-action-panel.png" } + ], + "keywords": [ + "热键侦测", + "快捷键冲突", + "热键冲突", + "谁占了快捷键", + "查看快捷键", + "热键占用", + "快捷键速查" ] } diff --git a/extensions/hotkey-radar/src/hotkey-service.ts b/extensions/hotkey-radar/src/hotkey-service.ts index d157ac00..12e02c4c 100644 --- a/extensions/hotkey-radar/src/hotkey-service.ts +++ b/extensions/hotkey-radar/src/hotkey-service.ts @@ -1,5 +1,6 @@ import { callHostTransport } from './native-ipc.js' import { getCheatsheetShortcuts, getHighConflictPresets } from './cheatsheet-data.js' +import { hotkeyFingerprint } from './mac-service.js' import { t } from './i18n.js' import type { CheatsheetShortcutItem, @@ -10,6 +11,40 @@ import type { } from './types.js' import { resolveErrorMessage } from './error-i18n.js' +/** 把 Windows 侧组合键(如 Win+L、Ctrl+Alt+Del)转换为跨端 hotkey_probe IPC 规范格式 */ +export function toHostHotkeyProbeCombo(combo: string): string { + const parts = String(combo ?? '') + .split('+') + .map((part) => part.trim()) + .filter(Boolean) + const mapped = parts.map((part) => { + const lower = part.toLowerCase() + if (lower === 'ctrl' || lower === 'control' || lower === 'ctl') return 'Control' + if (lower === 'alt' || lower === 'option' || lower === 'opt') return 'Alt' + if (lower === 'shift' || lower === 'shft') return 'Shift' + if (lower === 'win' || lower === 'meta' || lower === 'super' || lower === 'cmd' || lower === 'command') return 'Command' + if (lower === 'del' || lower === 'delete') return 'Delete' + if (lower === 'esc' || lower === 'escape') return 'Escape' + if (lower === 'enter' || lower === 'return') return 'Return' + if (lower === 'space') return 'Space' + if (lower === 'tab') return 'Tab' + if (lower === 'backspace') return 'Backspace' + if (lower === 'home') return 'Home' + if (lower === 'end') return 'End' + if (lower === 'pageup') return 'PageUp' + if (lower === 'pagedown') return 'PageDown' + if (lower === 'up') return 'Up' + if (lower === 'down') return 'Down' + if (lower === 'left') return 'Left' + if (lower === 'right') return 'Right' + if (lower === 'plus') return 'Plus' + if (lower === 'minus') return '-' + if (/^[a-z0-9]$/i.test(part) || /^f(?:[1-9]|1\d|20)$/i.test(part)) return part.toUpperCase() + return part + }) + return mapped.join('+') +} + const MODIFIER_ORDER = ['Ctrl', 'Alt', 'Shift', 'Win'] as const const MODIFIER_MAP: Record = { ctrl: 'Ctrl', @@ -153,50 +188,53 @@ export async function probeGlobalHotkeys( } } - const res = await callHostTransport>( - 'dllplugin_call', - { - plugin: 'HotkeyRadarPlugin', - func: 'probeHotkeys', - params: { - combos: effectivePresets.map((p) => p.keyCombo) - } - }, - hostOverride - ) + const hostCombos = effectivePresets.map((p) => toHostHotkeyProbeCombo(p.keyCombo)) + const uniqueHostCombos = [...new Set(hostCombos)] + const hostMap = new Map() - // 探测失败不能把所有组合显示成“空闲” - if (!res.ok || !res.data || res.data.ok === false || !Array.isArray(res.data.results)) { - throw new Error(resolveErrorMessage(res.data?.error ? res.data : res, t('errWinProbeIncomplete'))) - } - const hostMap = new Map>() - for (const r of res.data.results as Array>) { - const key = String(r.keyCombo ?? '').toUpperCase().replace(/\s+/g, '') - if (key) hostMap.set(key, r) + // hotkey_probe 单次请求上限 32 组,超出时按批次顺序探测 + for (let offset = 0; offset < uniqueHostCombos.length; offset += 32) { + const batch = uniqueHostCombos.slice(offset, offset + 32) + const res = await callHostTransport>( + 'hotkey_probe', + { combos: batch }, + hostOverride + ) + // 探测失败不能把所有组合显示成“空闲” + if (!res.ok || !res.data || res.data.success === false || !Array.isArray(res.data.results)) { + throw new Error(resolveErrorMessage(res.data?.error ? res.data : res, t('errWinProbeIncomplete'))) + } + for (const r of res.data.results as Array>) { + const combo = typeof r?.combo === 'string' ? r.combo : '' + const status = typeof r?.status === 'string' ? r.status : '' + if (combo && (status === 'registered' || status === 'occupied' || status === 'system' || status === 'owned')) { + hostMap.set(hotkeyFingerprint(combo), status) + } + } } - const items: HotkeyProbeResultItem[] = effectivePresets.map((preset) => { + const items: HotkeyProbeResultItem[] = effectivePresets.map((preset, idx) => { + const hostCombo = hostCombos[idx]! const upper = preset.keyCombo.toUpperCase().replace(/\s+/g, '') - const hostEntry = hostMap.get(upper) - const isSystemReserved = Boolean( - hostEntry?.isSystemReserved ?? (upper === 'WIN+L' || upper === 'CTRL+ALT+DEL') - ) - const rawStatus = String(hostEntry?.probeStatus ?? '') + const hostStatus = hostMap.get(hotkeyFingerprint(hostCombo)) + const isSystemReserved = hostStatus === 'system' || upper === 'WIN+L' || upper === 'CTRL+ALT+DEL' const probeStatus: 'reserved' | 'occupied' | 'free' | 'unsupported' = - isSystemReserved ? 'reserved' : rawStatus === 'occupied' || rawStatus === 'free' ? rawStatus : 'unsupported' + isSystemReserved + ? 'reserved' + : hostStatus === 'occupied' || hostStatus === 'owned' + ? 'occupied' + : hostStatus === 'registered' + ? 'free' + : 'unsupported' const isOccupied = probeStatus === 'reserved' || probeStatus === 'occupied' const suspectApp = isOccupied - ? String(hostEntry?.suspectApp || (isSystemReserved ? t('winSuspectReserved') : t('winSuspectUnknown'))) + ? (isSystemReserved + ? t('winSuspectReserved') + : hostStatus === 'owned' + ? 'ZTools' + : t('winSuspectUnknown')) : null - const suspectProcess = - isOccupied && typeof hostEntry?.suspectProcess === 'string' - ? hostEntry.suspectProcess - : null - const suspectPid = - isOccupied && !isSystemReserved && typeof hostEntry?.suspectPid === 'number' && hostEntry.suspectPid > 4 - ? hostEntry.suspectPid - : null - const modifyGuide = String(hostEntry?.modifyGuide || preset.modifyGuide) + const modifyGuide = preset.modifyGuide return { id: preset.id, @@ -213,8 +251,8 @@ export async function probeGlobalHotkeys( isOccupied, isSystemReserved, suspectApp, - suspectProcess, - suspectPid, + suspectProcess: null, + suspectPid: null, modifyGuide } }) diff --git a/extensions/hotkey-radar/src/native-ipc.ts b/extensions/hotkey-radar/src/native-ipc.ts index 51576b99..13643277 100644 --- a/extensions/hotkey-radar/src/native-ipc.ts +++ b/extensions/hotkey-radar/src/native-ipc.ts @@ -174,11 +174,13 @@ function normalizeMethodResult(method: string, payload: DynamicBridge): DynamicB if (method === 'system_get_battery_status') { // 宿主约定 percent 超出 0-100(如 255)表示无电池或电量未知,不能改写成 100% + // 若宿主明确给出 hasBattery 布尔值,必须原样保留,仅在缺失时按合法电量推算 const rawPct = payload.percent - const hasBattery = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const validPct = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const hasBattery = typeof payload.hasBattery === 'boolean' ? payload.hasBattery : validPct return { ...payload, - percent: hasBattery ? rawPct : null, + percent: validPct ? rawPct : null, hasBattery } } @@ -489,6 +491,8 @@ export interface RealDirectoryScanResult extends Iterable approximate?: boolean /** 宿主实际遍历的条目数 */ visitedEntries?: number + /** 目录本身不存在(ENOENT) */ + missing?: boolean /** 读取失败的真实原因;已有文件仍可使用,但不能当作完整结果。 */ error?: string } @@ -497,6 +501,7 @@ interface ScanResultMeta { truncated?: boolean approximate?: boolean visitedEntries?: number + missing?: boolean } export interface ScanDirectoryTreeOptions { @@ -504,6 +509,10 @@ export interface ScanDirectoryTreeOptions { maxFiles?: number collectTopN?: number filterExt?: RegExp + /** 为 true 时,目录本身不存在(ENOENT)按空目录处理,不返回 error(权限拒绝/读取失败仍照常报错) */ + ignoreMissing?: boolean + /** Top-N 保留与排序方式:默认按体积降序,下载/录屏等时效场景可传 mtime-desc */ + sortBy?: 'size-desc' | 'mtime-desc' hostOverride?: DynamicBridge } @@ -519,8 +528,9 @@ function normalizeIndexedFileEntry(f: DynamicBridge): RealIndexedFileEntry { const sz = Number(f?.size ?? f?.sizeBytes ?? 0) const isDir = Boolean(f?.is_dir || f?.isDir || f?.isDirectory) const rawMtime = Number(f?.mtime ?? f?.mtimeMs ?? 0) - const mtimeMs = rawMtime > 1e11 ? rawMtime : rawMtime > 0 ? rawMtime * 1000 : Date.now() - const mtimeSec = rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime + const validMtime = Number.isFinite(rawMtime) && rawMtime > 0 + const mtimeMs = validMtime ? (rawMtime > 1e11 ? rawMtime : rawMtime * 1000) : 0 + const mtimeSec = validMtime ? (rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime) : 0 if (p && sz >= 0) realFileSizeCache.set(p, sz) return { name, @@ -551,6 +561,7 @@ function makeScanResult( subdirs, ...(meta.truncated ? { truncated: true } : {}), ...(meta.approximate ? { approximate: true } : {}), + ...(meta.missing ? { missing: true } : {}), ...(typeof meta.visitedEntries === 'number' ? { visitedEntries: meta.visitedEntries } : {}), [Symbol.iterator]() { return files[Symbol.iterator]() @@ -609,13 +620,40 @@ export async function scanRealDirectoryTree( return result.error ? { ...result.scan, error: result.error } : result.scan } +/** 仅当正则明确声明了扩展名(含 `\.`)时提取后缀列表,避免把 `thumbcache|iconcache` 等文件名关键词误拆成假扩展名 */ +function extractExtensionTokensFromFilter(filterExt: RegExp): string[] { + const src = filterExt.source + if (!src.includes('\\.')) return [] + const afterDot = src.slice(src.indexOf('\\.') + 2) + const rawTokens = afterDot.match(/[a-z0-9]{1,8}/gi) || [] + const seen = new Set() + const out: string[] = [] + for (const token of rawTokens) { + const lower = token.toLowerCase() + if (!lower || seen.has(lower)) continue + seen.add(lower) + out.push(lower) + } + return out +} + +function isMissingDirectoryError(res: { error?: string; errorCode?: string; errorDetails?: Record }): boolean { + if (res.errorDetails?.reason === 'ENOENT' || res.errorCode === 'ENOENT') return true + const msg = String(res.error || '') + return /Directory does not exist|ENOENT/i.test(msg) +} + /** 一次界面扫描的错误汇总;多个目录并行扫描时保留可读目录的结果。 */ export function createDirectoryScanner(hostOverride?: DynamicBridge) { const failures = new Map() return { async scan(dir: string, options: number | ScanDirectoryTreeOptions = 160) { const result = await scanRealDirectoryTree(dir, options, hostOverride) - const error = result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') + const ignoreMissing = typeof options === 'object' && options !== null && options.ignoreMissing === true + const error = + result.missing && ignoreMissing + ? '' + : result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') if (error) failures.set(dir, error) else failures.delete(dir) return result @@ -648,26 +686,38 @@ async function scanDirectoryTreeWithError( const safeLimit = Math.min(200, Math.max(1, Math.floor(rawLimit || 160))) const hostOverride = opts.hostOverride const filterExt = opts.filterExt + const ignoreMissing = opts.ignoreMissing === true const dirQuery = `dir:${targetDir}` try { let rawPayload: DynamicBridge = null + const searchParams: Record = { + query: dirQuery, + limit: safeLimit, + ...(opts.sortBy ? { sortBy: opts.sortBy } : {}) + } const res = await callHostTransport( 'system_search_files', - { query: dirQuery, limit: safeLimit }, + searchParams, hostOverride ) - if (res.ok && res.data) { + if (res.ok && res.data && res.data.degraded !== true) { rawPayload = res.data + } else if (!res.ok && ignoreMissing && isMissingDirectoryError(res)) { + const missingScan = makeScanResult([], 0, 0, [], { missing: true }) + return { scan: missingScan } } - if (!rawPayload && !hostOverride && typeof window !== 'undefined') { + if (!rawPayload && !hostOverride && res.errorCode === 'METHOD_NOT_AVAILABLE' && typeof window !== 'undefined') { const w = window as DynamicBridge if (typeof w.__ztoolsLauncher?.searchFiles === 'function') { const rawOuter = await w.__ztoolsLauncher.searchFiles(dirQuery, safeLimit) - rawPayload = + const candidate = rawOuter && typeof rawOuter === 'object' && 'data' in rawOuter && rawOuter.data ? rawOuter.data : rawOuter + if (candidate && candidate.degraded !== true && candidate.success !== false) { + rawPayload = candidate + } } } @@ -678,29 +728,32 @@ async function scanDirectoryTreeWithError( let files: RealIndexedFileEntry[] = rawPayload.files.map(normalizeIndexedFileEntry) if (filterExt instanceof RegExp) { files = files.filter(f => !f.isDir && (filterExt.test(f.name) || filterExt.test(f.ext))) - // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索目标扩展名 + // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索明确声明的目标扩展名 if (files.length === 0 && !hostOverride) { - const extTokens = (filterExt.source.match(/[a-z0-9]{2,5}/gi) || []) - .filter(t => !['thumbcache', 'iconcache'].includes(t.toLowerCase())) - .slice(0, 4) - // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 - const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() - const extraLists = await Promise.all( - extTokens.map(ext => searchRealIndexedFiles(`.${ext.toLowerCase()}`, 30, hostOverride)) - ) - const seen = new Set() - for (const list of extraLists) { - for (const item of list) { - if (!item.isDir && item.size > 0 && !seen.has(item.path)) { - if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { - seen.add(item.path) - files.push(item) + const extTokens = extractExtensionTokensFromFilter(filterExt) + if (extTokens.length > 0) { + // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 + const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() + const extraLists = await Promise.all( + extTokens.map(ext => searchRealIndexedFiles(`.${ext}`, 30, hostOverride)) + ) + const seen = new Set() + for (const list of extraLists) { + for (const item of list) { + if (!item.isDir && item.size > 0 && !seen.has(item.path)) { + if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { + seen.add(item.path) + files.push(item) + } } } } } } } + // 先基于过滤后的完整命中集合计算总文件数与总字节数,再按 collectTopN 裁剪样本列表 + const matchedCount = files.length + const matchedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) if (typeof opts.collectTopN === 'number' && opts.collectTopN > 0 && files.length > opts.collectTopN) { files = files.slice(0, opts.collectTopN) } @@ -714,11 +767,10 @@ async function scanDirectoryTreeWithError( ...(s.approximate === true ? { approximate: true } : {}) })) : [] - const computedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) const totalFilesCount = - filterExt instanceof RegExp ? files.length : Number(rawPayload.total_matches ?? files.length) + filterExt instanceof RegExp ? matchedCount : Number(rawPayload.total_matches ?? matchedCount) const totalBytesCount = - filterExt instanceof RegExp ? computedBytes : Number(rawPayload.total_bytes ?? computedBytes) + filterExt instanceof RegExp ? matchedBytes : Number(rawPayload.total_bytes ?? matchedBytes) const visited = Number(rawPayload.visited_entries) return { scan: makeScanResult(files, totalFilesCount, totalBytesCount, subdirs, { @@ -1817,8 +1869,6 @@ export async function writeRealClipboardText(text: string, hostOverride?: Dynami const payload = { text: String(text || '') } const res = await callHostTransport('clipboard_copy_text', payload, hostOverride) if (res.ok) return true - const fallbackRes = await callHostTransport('clipboard_write_text', payload, hostOverride) - if (fallbackRes.ok) return true try { if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) { await navigator.clipboard.writeText(String(text || '')) diff --git a/extensions/hotkey-radar/tests/mac-hotkey.test.mjs b/extensions/hotkey-radar/tests/mac-hotkey.test.mjs index b095254e..3f34a1b2 100644 --- a/extensions/hotkey-radar/tests/mac-hotkey.test.mjs +++ b/extensions/hotkey-radar/tests/mac-hotkey.test.mjs @@ -50,11 +50,23 @@ test('Mac 结果把宿主的 Alt 显示和复制为 Option,按 Option 搜索 await v.search('option');assert.ok(v.item('probe-Alt+Command+Escape')) await v.dropdown('probe:unavailable');assert.ok(v.item('probe-Alt+Command+Escape')) }) -test('Windows 宿主未给出占用程序时不拿常见软件冒充占用来源',async()=>{ +test('Windows 端统一走 hotkey_probe,不调用 dllplugin_call,也不拿常见软件冒充占用来源',async()=>{ const {probeGlobalHotkeys}=await import('../dist/hotkey-service.js') - const hostOverride={dllplugin_call:async()=>({ok:true,results:[{keyCombo:'Ctrl+Alt+A',probeStatus:'occupied'}]})} - const [item]=await probeGlobalHotkeys([{id:'shot',keyCombo:'Ctrl+Alt+A',commonVictim:'截图',typicalCulprit:'微信 / QQ / 钉钉全局截图',modifyGuide:'检查设置'}],undefined,hostOverride) - assert.equal(item.isOccupied,true);assert.equal(item.suspectApp,'系统未提供占用程序');assert.doesNotMatch(item.subtitle,/占用来源: 微信/) + const calls=[] + const hostOverride={ + hotkey_probe:async(p)=>{calls.push(p.combos);return {success:true,checkedAt:new Date().toISOString(),results:[{combo:'Control+Alt+A',status:'occupied'},{combo:'Command+L',status:'system'},{combo:'Control+Shift+K',status:'registered'}]}}, + dllplugin_call:async()=>{throw new Error('不应调用 dllplugin_call')} + } + const items=await probeGlobalHotkeys([ + {id:'shot',keyCombo:'Ctrl+Alt+A',commonVictim:'截图',typicalCulprit:'微信 / QQ / 钉钉全局截图',modifyGuide:'检查设置'}, + {id:'lock',keyCombo:'Win+L',commonVictim:'锁屏',typicalCulprit:'Windows 系统',modifyGuide:'不可覆盖'}, + {id:'free',keyCombo:'Ctrl+Shift+K',commonVictim:'空闲测试',typicalCulprit:'无',modifyGuide:'可绑定'} + ],undefined,hostOverride) + assert.deepEqual(calls,[['Control+Alt+A','Command+L','Control+Shift+K']]) + const shot=items.find(i=>i.id==='shot'),lock=items.find(i=>i.id==='lock'),free=items.find(i=>i.id==='free') + assert.equal(shot.isOccupied,true);assert.equal(shot.suspectApp,'系统未提供占用程序');assert.doesNotMatch(shot.subtitle,/占用来源: 微信/) + assert.equal(lock.isSystemReserved,true);assert.equal(lock.probeStatus,'reserved') + assert.equal(free.isOccupied,false);assert.equal(free.probeStatus,'free') }) test('Mac 速查与检测统一用 ⌃⌥⇧⌘ 符号;输入符号写法也能检测;说明按实际只写 Mac',async()=>{ const {macSymbols,macPlusForm}=await import('../dist/index.js') diff --git a/extensions/id-watermark/README.en.md b/extensions/id-watermark/README.en.md new file mode 100644 index 00000000..2886f41a --- /dev/null +++ b/extensions/id-watermark/README.en.md @@ -0,0 +1,20 @@ +# ID Watermark + +Select a JPG, PNG, or static WebP image, press `⌘/Ctrl+K`, choose "Edit Watermark Purpose" in the action panel to enter the intended use, save it, and pick a text template. Press `Enter` to save a new PNG copy or `⌘/Ctrl+Enter` to copy the watermarked image. All processing happens locally and the original image stays untouched: saving over the original file is rejected, and another existing file is overwritten only if you explicitly confirm replacement in the system save dialog. + +The **Quick Watermark** (`quick watermark`, `clipboard watermark`) command reads an image from the clipboard first, lets you confirm the watermark text, and copies the result when you press `Enter`. You can also click "Read Clipboard" in the main workbench (`watermark`, `id watermark`, `add watermark`). Watermark templates populate the purpose you entered and today's date. + +Input and output images are limited to 16 MiB, max 8,192 pixels per side, and max 8 × 1024 × 1024 total pixels. Output preserves the decoded original pixel dimensions (including JPEG EXIF orientation) and is always encoded as PNG. Decode, render, or write failures report an explicit error instead of producing a blank placeholder image. Watermarks only mark intended usage and cannot guarantee an image cannot be altered or misused. + +## Platforms & Requirements + +- Supported: Windows, macOS +- Requires client version 1.1.8.4 or later. + +## Network & Data + +- Offline only; all data stays on your device. + +## Development & Verification + +Run `node --test extensions/id-watermark/tests/*.test.mjs` in the extensions repository root to check real declarative runtime entry points and failure boundaries. `extensions/id-watermark/tests/browser-watermark.mjs` exports browser regression tests that require an isolated test page with `OffscreenCanvas` to verify real encoding/decoding, original pixel preservation, file services, and action flows. Browser test file adapters must use test directories only, and clipboard operations use test receipts. diff --git a/extensions/id-watermark/plugin.json b/extensions/id-watermark/plugin.json index 45bb8afd..25a7c399 100644 --- a/extensions/id-watermark/plugin.json +++ b/extensions/id-watermark/plugin.json @@ -1,7 +1,7 @@ { "id": "id-watermark", "name": "防盗水印", - "version": "1.0.11", + "version": "1.0.12", "description": "本地为 JPG、PNG、WebP 图片添加斜向文字水印,保留原图,另存 PNG 新副本或复制图片", "author": "ZTools Team", "category": [ @@ -68,7 +68,12 @@ "privacy", "image", "protect", - "stamp" + "stamp", + "id watermark", + "add watermark", + "photo watermark", + "privacy watermark", + "protect id" ], "features": { "id-watermark-workbench": { @@ -102,5 +107,15 @@ { "path": "screenshots/02-action-panel.png" } + ], + "keywords": [ + "防盗水印", + "证件水印", + "身份证水印", + "加水印", + "图片水印", + "仅供办理", + "合同水印", + "打水印" ] } diff --git a/extensions/id-watermark/src/i18n.ts b/extensions/id-watermark/src/i18n.ts index 2ae17249..b2c31da6 100644 --- a/extensions/id-watermark/src/i18n.ts +++ b/extensions/id-watermark/src/i18n.ts @@ -65,6 +65,8 @@ export const t = createTranslator( actionPickImage: '选择原图…', barPickImage: '选择原图', barReadClipboard: '读取剪贴板', + barSaveWatermark: '生成并另存', + barCopyWatermark: '生成并复制', panelTitle: '水印参数', fieldTemplate: '文字模板', fieldBusiness: '用途(在动作面板修改)', @@ -143,6 +145,8 @@ export const t = createTranslator( actionPickImage: 'Select Image…', barPickImage: 'Select Image', barReadClipboard: 'From Clipboard', + barSaveWatermark: 'Save Watermarked', + barCopyWatermark: 'Copy Watermarked', panelTitle: 'Watermark Settings', fieldTemplate: 'Text Template', fieldBusiness: 'Purpose (Edit in Actions)', diff --git a/extensions/id-watermark/src/index.tsx b/extensions/id-watermark/src/index.tsx index b4e471e4..90ecb64e 100644 --- a/extensions/id-watermark/src/index.tsx +++ b/extensions/id-watermark/src/index.tsx @@ -111,9 +111,12 @@ export function IdWatermarkCommand({ clipboardFirst = false }: { clipboardFirst? {clipboardFirst ? load(true)} /> : load(false)} />} {clipboardFirst ? load(false)} /> : load(true)} />} } - filterBar={{ summaryText: status, actions: [ - { id: 'pick', title: t('barPickImage'), onAction: () => load(false) }, - { id: 'clipboard', title: t('barReadClipboard'), onAction: () => load(true) } + filterBar={{ summaryText: status, actions: image ? [ + { id: 'pick', title: t('barPickImage'), style: 'secondary', onAction: () => load(false) }, + { id: 'generate', title: clipboardFirst ? t('barCopyWatermark') : t('barSaveWatermark'), style: 'primary', disabled: loading, onAction: () => output(clipboardFirst) } + ] : [ + { id: 'pick', title: t('barPickImage'), style: 'secondary', onAction: () => load(false) }, + { id: 'clipboard', title: t('barReadClipboard'), style: 'secondary', onAction: () => load(true) } ] }} workbenchPanel={{ title: t('panelTitle'), fields: [ { id: 'template', label: t('fieldTemplate'), type: 'select', value: templateId, options: presets.map(p => ({ label: p.scenarioTag, value: p.id })), onChange: (value: unknown) => { if (!pending.current && presets.some(p => p.id === value)) setTemplateId(String(value)) } }, diff --git a/extensions/id-watermark/src/native-ipc.ts b/extensions/id-watermark/src/native-ipc.ts index 51576b99..13643277 100644 --- a/extensions/id-watermark/src/native-ipc.ts +++ b/extensions/id-watermark/src/native-ipc.ts @@ -174,11 +174,13 @@ function normalizeMethodResult(method: string, payload: DynamicBridge): DynamicB if (method === 'system_get_battery_status') { // 宿主约定 percent 超出 0-100(如 255)表示无电池或电量未知,不能改写成 100% + // 若宿主明确给出 hasBattery 布尔值,必须原样保留,仅在缺失时按合法电量推算 const rawPct = payload.percent - const hasBattery = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const validPct = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const hasBattery = typeof payload.hasBattery === 'boolean' ? payload.hasBattery : validPct return { ...payload, - percent: hasBattery ? rawPct : null, + percent: validPct ? rawPct : null, hasBattery } } @@ -489,6 +491,8 @@ export interface RealDirectoryScanResult extends Iterable approximate?: boolean /** 宿主实际遍历的条目数 */ visitedEntries?: number + /** 目录本身不存在(ENOENT) */ + missing?: boolean /** 读取失败的真实原因;已有文件仍可使用,但不能当作完整结果。 */ error?: string } @@ -497,6 +501,7 @@ interface ScanResultMeta { truncated?: boolean approximate?: boolean visitedEntries?: number + missing?: boolean } export interface ScanDirectoryTreeOptions { @@ -504,6 +509,10 @@ export interface ScanDirectoryTreeOptions { maxFiles?: number collectTopN?: number filterExt?: RegExp + /** 为 true 时,目录本身不存在(ENOENT)按空目录处理,不返回 error(权限拒绝/读取失败仍照常报错) */ + ignoreMissing?: boolean + /** Top-N 保留与排序方式:默认按体积降序,下载/录屏等时效场景可传 mtime-desc */ + sortBy?: 'size-desc' | 'mtime-desc' hostOverride?: DynamicBridge } @@ -519,8 +528,9 @@ function normalizeIndexedFileEntry(f: DynamicBridge): RealIndexedFileEntry { const sz = Number(f?.size ?? f?.sizeBytes ?? 0) const isDir = Boolean(f?.is_dir || f?.isDir || f?.isDirectory) const rawMtime = Number(f?.mtime ?? f?.mtimeMs ?? 0) - const mtimeMs = rawMtime > 1e11 ? rawMtime : rawMtime > 0 ? rawMtime * 1000 : Date.now() - const mtimeSec = rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime + const validMtime = Number.isFinite(rawMtime) && rawMtime > 0 + const mtimeMs = validMtime ? (rawMtime > 1e11 ? rawMtime : rawMtime * 1000) : 0 + const mtimeSec = validMtime ? (rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime) : 0 if (p && sz >= 0) realFileSizeCache.set(p, sz) return { name, @@ -551,6 +561,7 @@ function makeScanResult( subdirs, ...(meta.truncated ? { truncated: true } : {}), ...(meta.approximate ? { approximate: true } : {}), + ...(meta.missing ? { missing: true } : {}), ...(typeof meta.visitedEntries === 'number' ? { visitedEntries: meta.visitedEntries } : {}), [Symbol.iterator]() { return files[Symbol.iterator]() @@ -609,13 +620,40 @@ export async function scanRealDirectoryTree( return result.error ? { ...result.scan, error: result.error } : result.scan } +/** 仅当正则明确声明了扩展名(含 `\.`)时提取后缀列表,避免把 `thumbcache|iconcache` 等文件名关键词误拆成假扩展名 */ +function extractExtensionTokensFromFilter(filterExt: RegExp): string[] { + const src = filterExt.source + if (!src.includes('\\.')) return [] + const afterDot = src.slice(src.indexOf('\\.') + 2) + const rawTokens = afterDot.match(/[a-z0-9]{1,8}/gi) || [] + const seen = new Set() + const out: string[] = [] + for (const token of rawTokens) { + const lower = token.toLowerCase() + if (!lower || seen.has(lower)) continue + seen.add(lower) + out.push(lower) + } + return out +} + +function isMissingDirectoryError(res: { error?: string; errorCode?: string; errorDetails?: Record }): boolean { + if (res.errorDetails?.reason === 'ENOENT' || res.errorCode === 'ENOENT') return true + const msg = String(res.error || '') + return /Directory does not exist|ENOENT/i.test(msg) +} + /** 一次界面扫描的错误汇总;多个目录并行扫描时保留可读目录的结果。 */ export function createDirectoryScanner(hostOverride?: DynamicBridge) { const failures = new Map() return { async scan(dir: string, options: number | ScanDirectoryTreeOptions = 160) { const result = await scanRealDirectoryTree(dir, options, hostOverride) - const error = result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') + const ignoreMissing = typeof options === 'object' && options !== null && options.ignoreMissing === true + const error = + result.missing && ignoreMissing + ? '' + : result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') if (error) failures.set(dir, error) else failures.delete(dir) return result @@ -648,26 +686,38 @@ async function scanDirectoryTreeWithError( const safeLimit = Math.min(200, Math.max(1, Math.floor(rawLimit || 160))) const hostOverride = opts.hostOverride const filterExt = opts.filterExt + const ignoreMissing = opts.ignoreMissing === true const dirQuery = `dir:${targetDir}` try { let rawPayload: DynamicBridge = null + const searchParams: Record = { + query: dirQuery, + limit: safeLimit, + ...(opts.sortBy ? { sortBy: opts.sortBy } : {}) + } const res = await callHostTransport( 'system_search_files', - { query: dirQuery, limit: safeLimit }, + searchParams, hostOverride ) - if (res.ok && res.data) { + if (res.ok && res.data && res.data.degraded !== true) { rawPayload = res.data + } else if (!res.ok && ignoreMissing && isMissingDirectoryError(res)) { + const missingScan = makeScanResult([], 0, 0, [], { missing: true }) + return { scan: missingScan } } - if (!rawPayload && !hostOverride && typeof window !== 'undefined') { + if (!rawPayload && !hostOverride && res.errorCode === 'METHOD_NOT_AVAILABLE' && typeof window !== 'undefined') { const w = window as DynamicBridge if (typeof w.__ztoolsLauncher?.searchFiles === 'function') { const rawOuter = await w.__ztoolsLauncher.searchFiles(dirQuery, safeLimit) - rawPayload = + const candidate = rawOuter && typeof rawOuter === 'object' && 'data' in rawOuter && rawOuter.data ? rawOuter.data : rawOuter + if (candidate && candidate.degraded !== true && candidate.success !== false) { + rawPayload = candidate + } } } @@ -678,29 +728,32 @@ async function scanDirectoryTreeWithError( let files: RealIndexedFileEntry[] = rawPayload.files.map(normalizeIndexedFileEntry) if (filterExt instanceof RegExp) { files = files.filter(f => !f.isDir && (filterExt.test(f.name) || filterExt.test(f.ext))) - // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索目标扩展名 + // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索明确声明的目标扩展名 if (files.length === 0 && !hostOverride) { - const extTokens = (filterExt.source.match(/[a-z0-9]{2,5}/gi) || []) - .filter(t => !['thumbcache', 'iconcache'].includes(t.toLowerCase())) - .slice(0, 4) - // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 - const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() - const extraLists = await Promise.all( - extTokens.map(ext => searchRealIndexedFiles(`.${ext.toLowerCase()}`, 30, hostOverride)) - ) - const seen = new Set() - for (const list of extraLists) { - for (const item of list) { - if (!item.isDir && item.size > 0 && !seen.has(item.path)) { - if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { - seen.add(item.path) - files.push(item) + const extTokens = extractExtensionTokensFromFilter(filterExt) + if (extTokens.length > 0) { + // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 + const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() + const extraLists = await Promise.all( + extTokens.map(ext => searchRealIndexedFiles(`.${ext}`, 30, hostOverride)) + ) + const seen = new Set() + for (const list of extraLists) { + for (const item of list) { + if (!item.isDir && item.size > 0 && !seen.has(item.path)) { + if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { + seen.add(item.path) + files.push(item) + } } } } } } } + // 先基于过滤后的完整命中集合计算总文件数与总字节数,再按 collectTopN 裁剪样本列表 + const matchedCount = files.length + const matchedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) if (typeof opts.collectTopN === 'number' && opts.collectTopN > 0 && files.length > opts.collectTopN) { files = files.slice(0, opts.collectTopN) } @@ -714,11 +767,10 @@ async function scanDirectoryTreeWithError( ...(s.approximate === true ? { approximate: true } : {}) })) : [] - const computedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) const totalFilesCount = - filterExt instanceof RegExp ? files.length : Number(rawPayload.total_matches ?? files.length) + filterExt instanceof RegExp ? matchedCount : Number(rawPayload.total_matches ?? matchedCount) const totalBytesCount = - filterExt instanceof RegExp ? computedBytes : Number(rawPayload.total_bytes ?? computedBytes) + filterExt instanceof RegExp ? matchedBytes : Number(rawPayload.total_bytes ?? matchedBytes) const visited = Number(rawPayload.visited_entries) return { scan: makeScanResult(files, totalFilesCount, totalBytesCount, subdirs, { @@ -1817,8 +1869,6 @@ export async function writeRealClipboardText(text: string, hostOverride?: Dynami const payload = { text: String(text || '') } const res = await callHostTransport('clipboard_copy_text', payload, hostOverride) if (res.ok) return true - const fallbackRes = await callHostTransport('clipboard_write_text', payload, hostOverride) - if (fallbackRes.ok) return true try { if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) { await navigator.clipboard.writeText(String(text || '')) diff --git a/extensions/image-editor/README.en.md b/extensions/image-editor/README.en.md new file mode 100644 index 00000000..f363286b --- /dev/null +++ b/extensions/image-editor/README.en.md @@ -0,0 +1,14 @@ +# Image Editor & Beautify Workbench + +Parametric image editing workbench powered by host `image.inspect` and `image.process` primitives (Phase 1: Windows only). + +## Highlights + +- **Flexible Import**: Drop images, pick files via system dialog, or paste from clipboard; automatically inspects real dimensions, format, and size via `tool_image_inspect`. +- **Parametric Workbench**: + - Resize (original, 1920px, 1280px, 800px, or custom width) + - Crop (1:1, 16:9, 4:3 aspect ratios, or free pixel rect `x,y,w,h`) + - Rotate (90 / 180 / 270 deg) and flip (horizontal / vertical / both) + - Text watermark (text, 5 positions, opacity) + - Rounded corners and beautify frame (radius, padding, semantic theme tokens) +- **Live Summary & Batch Queue**: Synchronized parameter summary and output queue supporting single save-as, batch folder export, and clipboard copy. diff --git a/extensions/image-editor/README.md b/extensions/image-editor/README.md index 4e1cfa23..010cd7fe 100644 --- a/extensions/image-editor/README.md +++ b/extensions/image-editor/README.md @@ -1,3 +1,14 @@ -# 图片轻量编辑与批注 +# 图片轻量编辑与美化工作台 -已下架:功能未完成(只有示例数据)。 +基于宿主 `image.inspect` 与 `image.process` 原语构建的参数化轻量修图工作台(一期仅支持 Windows)。 + +## 核心能力 + +- **多途径导入**:支持拖入图片、文件弹窗多选以及直接读取剪贴板图片,导入后自动调用 `tool_image_inspect` 读取真实分辨率、格式与文件体积。 +- **参数化配置面板**: + - 尺寸缩放(原尺寸 / 1920px / 1280px / 800px / 自定义宽度) + - 比例与自由裁剪(1:1 / 16:9 / 4:3 / 自由像素 `x,y,w,h`) + - 旋转(90° / 180° / 270°)与翻转(水平 / 垂直 / 双向) + - 文字水印(自定义文案、五方位布局、透明度调节) + - 圆角与美化背景框(圆角半径、内边距与预设语义主题背景) +- **实时联动预览与批处理队列**:左栏实时联动输出尺寸与处理管线摘要,右栏队列支持单张另存、批量导出与结果路径复制。 diff --git a/extensions/image-editor/icon.svg b/extensions/image-editor/icon.svg new file mode 100644 index 00000000..6ea77b4c --- /dev/null +++ b/extensions/image-editor/icon.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/extensions/image-editor/plugin.json b/extensions/image-editor/plugin.json index 4efa61e5..bd0a7b7f 100644 --- a/extensions/image-editor/plugin.json +++ b/extensions/image-editor/plugin.json @@ -1,27 +1,90 @@ { "id": "image-editor", - "name": "图片轻量编辑与批注", - "description": "图片缩放、旋转翻转与文字水印", - "version": "1.0.0", - "revoked": true, - "revokedReason": "功能未完成(只有示例数据)", + "name": "图片轻量编辑与美化工作台", + "description": "面向 Windows 的参数化轻量修图工作台:支持拖入、选择或粘贴剪贴板图片,实时读取尺寸与格式,配置尺寸缩放、常用比例/自由像素裁剪、旋转翻转、文字水印、圆角与美化背景框,并一键导出或批量处理", + "version": "1.1.0", + "minAppVersion": "1.3.0.4", "author": "ZTools Team", "entry": "dist/index.js", "icon": "icon.svg", - "permissions": [], + "category": [ + "图像媒体" + ], + "categoryId": "media", + "keywords": [ + "图片编辑", + "修图", + "裁剪", + "旋转", + "翻转", + "文字水印", + "圆角", + "美化背景", + "image editor", + "watermark", + "crop" + ], + "requiredCapabilities": [ + "image.inspect", + "image.process" + ], + "permissions": [ + "media.read", + "media.process", + "dialog", + "fs", + "clipboard" + ], + "requireAdmin": false, + "nativeComponents": [], + "features": [ + { + "code": "image-editor-workbench", + "explain": "参数化轻量图片编辑、裁剪、旋转翻转、水印与美化背景框工作台", + "cmds": [ + "图片编辑", + "轻量修图", + "图片水印", + "图片美化", + "image editor" + ] + } + ], "targets": [ { "id": "windows-electron-any", "platform": "windows", "runtime": "electron", "arch": "any" - }, - { - "id": "macos-electron-any", - "platform": "macos", - "runtime": "electron", - "arch": "any" } ], - "nativeComponents": [] + "defaultLocale": "zh-CN", + "i18n": { + "en-US": { + "name": "Image Editor & Beautify Workbench", + "description": "Parametric image editing workbench for Windows: drop, pick, or paste images to inspect real dimensions and apply resize, aspect/free crop, rotate/flip, text watermark, rounded corners, and themed background frames in single or batch mode.", + "keywords": [ + "image editor", + "resize", + "crop", + "rotate", + "flip", + "watermark", + "rounded corners", + "frame", + "batch" + ], + "features": { + "image-editor-workbench": { + "explain": "Parametric image editing workbench for crop, rotate, flip, watermark, and beautify frame", + "cmds": [ + "image editor", + "edit image", + "image watermark", + "beautify image" + ] + } + } + } + } } diff --git a/extensions/image-editor/src/error-i18n.ts b/extensions/image-editor/src/error-i18n.ts new file mode 100644 index 00000000..d97366d1 --- /dev/null +++ b/extensions/image-editor/src/error-i18n.ts @@ -0,0 +1,213 @@ +/** + * 声明式插件通用错误本地化解析器(R7 双轨平滑迁移共享底座)。 + * + * 规则: + * 1. 优先按结构化错误码(errorDetails.hostCode / details.hostCode / errorCode / code)查表: + * 先查插件传入的 codeMap,再查标准宿主错误码双语表; + * 2. 对称展示规则:中文模式(zh-CN)原文含 CJK 才直接展示,英文模式(en-US)原文不含 CJK 才直接展示, + * 既保留宿主精确本地化消息,又拦截英文技术原文裸露到中文界面、拦截中文原文裸露到英文界面; + * 3. 原文语言不匹配时优先使用标准宿主错误码译文,否则回退到插件本地 t(...) 兜底文案。 + */ + +import { getLocale } from '@ztools/declarative-ui' + +const CJK_REGEX = /[\u4e00-\u9fa5]/ + +const HOST_ERROR_CODE_MESSAGES: Record>> = { + 'zh-CN': { + INVALID_REQUEST: '请求参数无效', + METHOD_NOT_FOUND: '当前 ZTools 版本过低或不支持此接口,请升级客户端后重试', + METHOD_NOT_AVAILABLE: '当前 ZTools 版本过低或不支持此接口,请升级客户端后重试', + PERMISSION_DENIED: '权限不足,无法执行该操作', + REQUEST_TIMEOUT: '请求执行超时,请稍后重试', + CALLER_DESTROYED: '调用窗口已关闭,操作已中止', + APP_STOPPING: '应用正在退出,操作已取消', + CANCELLED: '操作已取消', + OPERATION_CANCELLED: '操作已取消', + NOT_SUPPORTED: '当前环境不支持此操作', + PLATFORM_NOT_SUPPORTED: '当前操作系统不支持此功能', + NETWORK_ERROR: '网络请求失败,请检查网络连接', + RESPONSE_TOO_LARGE: '响应数据超出大小限制', + FILE_ERROR: '文件操作失败', + FILE_NOT_FOUND: '目标文件或目录不存在', + FILE_TOO_LARGE: '文件大小超出限制', + FILE_ALREADY_EXISTS: '目标文件已存在', + DISK_FULL: '磁盘空间不足', + SHELL_ERROR: '系统命令或外部应用启动失败', + PROCESS_ERROR: '进程操作失败', + PROCESS_PROTECTED: '目标进程受系统保护,无法操作', + PROCESS_NOT_FOUND: '未找到目标进程', + PROCESS_ACCESS_DENIED: '无权访问或操作目标进程', + SCREEN_ERROR: '屏幕或窗口操作失败', + CLIPBOARD_ERROR: '剪贴板读写失败', + DATABASE_LOCKED: '本地数据库正被占用,请稍后重试', + DATABASE_KEY_NOT_FOUND: '未找到指定的数据项', + DATA_CORRUPT: '本地数据格式损坏或校验失败', + STORAGE_ERROR: '本地存储读写失败', + PLUGIN_BUSY: '插件正忙,请稍后重试', + PLUGIN_PERMISSION_REQUIRED: '插件缺少所需权限声明', + DLL_ERROR: '原生组件执行失败', + NATIVE_HOST_UNAVAILABLE: '原生宿主组件不可用', + NATIVE_HOST_ERROR: '原生宿主执行失败', + SERVICE_UNAVAILABLE: '系统提权服务不可用', + INTERNAL_ERROR: '宿主内部错误' + }, + 'en-US': { + INVALID_REQUEST: 'Invalid request parameters', + METHOD_NOT_FOUND: 'Your ZTools version is too old or does not support this API. Please upgrade and try again.', + METHOD_NOT_AVAILABLE: 'Your ZTools version is too old or does not support this API. Please upgrade and try again.', + PERMISSION_DENIED: 'Permission denied', + REQUEST_TIMEOUT: 'Request timed out. Please try again later.', + CALLER_DESTROYED: 'The caller window was closed and the operation was aborted', + APP_STOPPING: 'Application is exiting; operation cancelled', + CANCELLED: 'Operation cancelled', + OPERATION_CANCELLED: 'Operation cancelled', + NOT_SUPPORTED: 'This operation is not supported in the current environment', + PLATFORM_NOT_SUPPORTED: 'This feature is not supported on the current operating system', + NETWORK_ERROR: 'Network request failed. Please check your connection.', + RESPONSE_TOO_LARGE: 'Response payload exceeds size limit', + FILE_ERROR: 'File operation failed', + FILE_NOT_FOUND: 'Target file or directory not found', + FILE_TOO_LARGE: 'File size exceeds limit', + FILE_ALREADY_EXISTS: 'Target file already exists', + DISK_FULL: 'Insufficient disk space', + SHELL_ERROR: 'Failed to launch system command or external application', + PROCESS_ERROR: 'Process operation failed', + PROCESS_PROTECTED: 'Target process is protected by the system', + PROCESS_NOT_FOUND: 'Target process not found', + PROCESS_ACCESS_DENIED: 'Access denied for target process', + SCREEN_ERROR: 'Screen or window operation failed', + CLIPBOARD_ERROR: 'Failed to read or write clipboard', + DATABASE_LOCKED: 'Local database is locked. Please try again later.', + DATABASE_KEY_NOT_FOUND: 'Requested item was not found', + DATA_CORRUPT: 'Local data is corrupted or failed validation', + STORAGE_ERROR: 'Local storage operation failed', + PLUGIN_BUSY: 'Plugin is busy. Please try again later.', + PLUGIN_PERMISSION_REQUIRED: 'Plugin is missing required permission declaration', + DLL_ERROR: 'Native component execution failed', + NATIVE_HOST_UNAVAILABLE: 'Native host component is unavailable', + NATIVE_HOST_ERROR: 'Native host execution failed', + SERVICE_UNAVAILABLE: 'Elevated system service is unavailable', + INTERNAL_ERROR: 'Internal host error' + } +} + +function asObj(value: unknown): Record | null { + return value && typeof value === 'object' && !Array.isArray(value) + ? (value as Record) + : null +} + +function pickNonEmptyString(value: unknown): string { + return typeof value === 'string' && value.trim().length > 0 ? value.trim() : '' +} + +/** 从错误对象或宿主响应信封中提取结构化错误码(优先 errorCode,再 code) */ +export function extractErrorCode(source: unknown): string { + const rec = asObj(source) + if (!rec) return '' + const direct = pickNonEmptyString(rec.errorCode) || pickNonEmptyString(rec.code) + if (direct) return direct + const nestedErr = asObj(rec.error) + if (nestedErr) { + return pickNonEmptyString(nestedErr.errorCode) || pickNonEmptyString(nestedErr.code) + } + const nestedData = asObj(rec.data) + if (nestedData) { + return pickNonEmptyString(nestedData.errorCode) || pickNonEmptyString(nestedData.code) + } + return '' +} + +/** 从错误对象或宿主响应信封中提取 details.hostCode */ +export function extractHostCode(source: unknown): string { + const rec = asObj(source) + if (!rec) return '' + const directDetails = asObj(rec.errorDetails) || asObj(rec.details) + const fromDirect = directDetails ? pickNonEmptyString(directDetails.hostCode) : '' + if (fromDirect) return fromDirect + const nestedErr = asObj(rec.error) + if (nestedErr) { + const nestedDetails = asObj(nestedErr.errorDetails) || asObj(nestedErr.details) + const fromNested = nestedDetails ? pickNonEmptyString(nestedDetails.hostCode) : '' + if (fromNested) return fromNested + } + return '' +} + +/** 从错误对象、宿主响应或字符串中提取原始错误文案 */ +export function extractRawErrorText(source: unknown): string { + if (typeof source === 'string') return source.trim() + if (source instanceof Error) return source.message.trim() + const rec = asObj(source) + if (!rec) return '' + if ('error' in rec) { + if (typeof rec.error === 'string') return rec.error.trim() + const nestedErr = asObj(rec.error) + if (nestedErr) { + return pickNonEmptyString(nestedErr.message) || pickNonEmptyString(nestedErr.error) + } + return '' + } + return pickNonEmptyString(rec.message) +} + +/** 判断某段文本在当前 locale 下是否可直接展示给用户(对称规则:zh-CN 需含 CJK,en-US 需不含 CJK) */ +export function isDisplayableInCurrentLocale(text: string): boolean { + if (!text) return false + const locale = getLocale() + if (locale === 'zh-CN') return CJK_REGEX.test(text) + return !CJK_REGEX.test(text) +} + +/** + * 将宿主响应、异常对象或原始错误字符串安全解析为当前语言的提示文案: + * 1. 若对象属于成功响应且无 error,直接返回 fallback(避免误读成功态 message/code); + * 2. 优先按 hostCode / errorCode / code 查插件自定义 codeMap; + * 3. 若存在标准宿主错误码且无原文或原文语言不匹配,按当前语言查标准词典; + * 4. 若原始文案非空且符合当前语种(中文模式含 CJK,英文模式不含 CJK),保留原始文案; + * 5. 其余情况一律回退到插件本地传入的 fallback(即 t('...'))。 + */ +export function resolveErrorMessage( + source: unknown, + fallback: string, + codeMap?: Readonly> +): string { + if (source === null || source === undefined || source === '') { + return fallback + } + const rec = asObj(source) + if (rec && 'error' in rec && rec.ok === true && !rec.error) { + return fallback + } + + const hostCode = extractHostCode(source) + const code = extractErrorCode(source) + const rawText = extractRawErrorText(source) + + // 非失败响应容器若既无 error 文案也无 errorCode,直接返回 fallback(如 snapshot.error || t('empty')) + if (rec && 'error' in rec && !rawText && !rec.errorCode && rec.ok !== false && rec.success !== false) { + return fallback + } + + const locale = getLocale() + const dict = HOST_ERROR_CODE_MESSAGES[locale] ?? HOST_ERROR_CODE_MESSAGES['en-US'] + + if (codeMap) { + if (hostCode && codeMap[hostCode]) return codeMap[hostCode] + if (code && codeMap[code]) return codeMap[code] + } + + if (hostCode && dict[hostCode]) { + if (!rawText || !isDisplayableInCurrentLocale(rawText)) return dict[hostCode] + } + if (code && dict[code]) { + if (!rawText || !isDisplayableInCurrentLocale(rawText)) return dict[code] + } + + if (rawText && isDisplayableInCurrentLocale(rawText)) { + return rawText + } + + return fallback +} diff --git a/extensions/image-editor/src/host-compat.ts b/extensions/image-editor/src/host-compat.ts new file mode 100644 index 00000000..d7bd47df --- /dev/null +++ b/extensions/image-editor/src/host-compat.ts @@ -0,0 +1,201 @@ +/** + * 旧版客户端兼容:插件运行在比自己更旧的 ZTools 里时,给出明确的升级提示或安全的退路。 + * + * - 插件里的 `@ztools/declarative-ui` 由客户端在运行时提供,SDK 里新增的方法在旧客户端上并不存在; + * - 宿主接口在旧客户端上不存在时返回「未知方法」,这里统一换成用户看得懂的升级提示。 + */ + +import { getLocale } from '@ztools/declarative-ui' + +const HOST_COMPAT_MESSAGES: Record string +}> = { + 'zh-CN': { + upgradeHint: '当前 ZTools 版本过低,请升级到最新版本后再试', + featureUpgradeError: (feature, hint) => `${feature}需要新版 ZTools,${hint}` + }, + 'en-US': { + upgradeHint: 'Your ZTools version is too old. Please upgrade to the latest version and try again.', + featureUpgradeError: (feature, hint) => `${feature} requires a newer version of ZTools. ${hint}` + } +} + +function hostCompatStrings() { + const locale = getLocale() + return HOST_COMPAT_MESSAGES[locale] ?? HOST_COMPAT_MESSAGES['en-US'] +} + +/** 动态获取旧版客户端升级提示(请始终调用本函数以支持语言热切换,禁止在模块顶层缓存为静态常量) */ +export function getHostUpgradeHint(): string { + return hostCompatStrings().upgradeHint +} + +/** 提取结构化错误码(优先 code / errorCode / details.hostCode) */ +function extractCompatErrorCodes(error: unknown): { code: string; hostCode: string } { + if (!error || typeof error !== 'object') return { code: '', hostCode: '' } + const rec = error as Record + const directCode = + typeof rec.errorCode === 'string' && rec.errorCode.trim() + ? rec.errorCode.trim() + : typeof rec.code === 'string' && rec.code.trim() + ? rec.code.trim() + : '' + const nestedErr = rec.error && typeof rec.error === 'object' ? (rec.error as Record) : null + const code = + directCode || + (nestedErr && typeof nestedErr.errorCode === 'string' && nestedErr.errorCode.trim() + ? nestedErr.errorCode.trim() + : nestedErr && typeof nestedErr.code === 'string' && nestedErr.code.trim() + ? nestedErr.code.trim() + : '') + const details = + (rec.errorDetails && typeof rec.errorDetails === 'object' ? (rec.errorDetails as Record) : null) || + (rec.details && typeof rec.details === 'object' ? (rec.details as Record) : null) || + (nestedErr?.details && typeof nestedErr.details === 'object' ? (nestedErr.details as Record) : null) + const hostCode = + details && typeof details.hostCode === 'string' && details.hostCode.trim() ? details.hostCode.trim() : '' + return { code, hostCode } +} + +/** 宿主是否因为不认识这个接口而失败(旧客户端):优先按结构化错误码判定,无码时兼容老宿主中文文案 */ +export function isHostMethodMissing(error: unknown): boolean { + const { code, hostCode } = extractCompatErrorCodes(error) + if ( + code === 'METHOD_NOT_FOUND' || + code === 'METHOD_NOT_AVAILABLE' || + hostCode === 'METHOD_NOT_FOUND' || + hostCode === 'METHOD_NOT_AVAILABLE' + ) { + return true + } + const text = + error instanceof Error + ? error.message + : error && typeof error === 'object' && typeof (error as { error?: unknown }).error === 'string' + ? String((error as { error: string }).error) + : error && typeof error === 'object' && typeof (error as { message?: unknown }).message === 'string' + ? String((error as { message: string }).message) + : String(error ?? '') + if (/METHOD_NOT_FOUND|METHOD_NOT_AVAILABLE|is not a function/.test(text)) { + return true + } + if (!code && !hostCode) { + // i18n-allow: legacy host fallback + return /未知方法/.test(text) + } + return false +} + +/** 生成「某功能需要新版客户端」的报错 */ +export function hostUpgradeError(feature: string): Error { + const s = hostCompatStrings() + return new Error(s.featureUpgradeError(feature, s.upgradeHint)) +} + +export interface UpdatableStorage { + getItem(key: string): Promise + setItem(key: string, value: unknown): Promise + updateItem?: (key: string, update: (current: unknown) => T) => Promise +} + +/** + * 读出最新值、修改后写回。 + * 客户端提供 updateItem 时用它保证多窗口不互相覆盖;旧客户端没有时退回读后写(与旧版插件行为一致)。 + */ +export async function updateStorageItem( + storage: UpdatableStorage, + key: string, + update: (current: unknown) => T +): Promise { + if (typeof storage.updateItem === 'function') return storage.updateItem(key, update) + const current = await storage.getItem(key) + const next = update(current) + if (JSON.stringify(next) !== JSON.stringify(current)) await storage.setItem(key, next) + return next +} + +export interface CompatFileInputConfig { + /** 允许的扩展名列表(如 ['.png', '.jpg']),不填表示允许任意扩展名 */ + extensions?: string[] + /** 是否允许接收文件夹(默认 false) */ + allowDirectories?: boolean + /** 是否允许将剪贴板纯位图(截图)落盘为临时 PNG 接收(默认 false) */ + allowClipboardImage?: boolean + /** 拖放遮罩提示文案 */ + dropTitle?: string + dropSubtitle?: string + /** 双模粘贴(文件优先,纯文本回退):当焦点位于空搜索框或非输入区域且剪贴板仅含文本时触发 */ + onTextPaste?: (text: string) => boolean | void | Promise +} + +export interface CompatFileInputPayload { + files: string[] + source: 'drop' | 'paste' | 'launch' + targetFieldId?: string + rejectedCount?: number +} + +/** + * 从宿主事件信封、FileInputPayload 或裸路径数组中安全提取规范化非空文件路径列表 + */ +export function extractCompatInputFiles(payload: unknown): string[] { + if (Array.isArray(payload)) { + return payload + .map((item) => { + if (typeof item === 'string') return item.trim() + if (item && typeof item === 'object' && typeof (item as { path?: unknown }).path === 'string') { + return String((item as { path: string }).path).trim() + } + return '' + }) + .filter(Boolean) + } + if (!payload || typeof payload !== 'object') return [] + const record = payload as Record + const inner = record.payload && typeof record.payload === 'object' ? (record.payload as Record) : record + if (Array.isArray(inner.files)) return extractCompatInputFiles(inner.files) + if (Array.isArray(inner.paths)) return extractCompatInputFiles(inner.paths) + return [] +} + +/** + * 判断当前宿主渲染器是否已原生支持栈顶 单点消费路由。 + * - 新版宿主会注入 window.__ztoolsDeclarativeFeatures.fileInput === true; + * - 旧版宿主未注入该标记时,插件可保留原有的 plugin_files_dropped 事件订阅作为回退,避免新旧宿主双重触发。 + */ +export function isDeclarativeFileInputSupported(): boolean { + if (typeof window === 'undefined') return true + const w = window as unknown as { __ztoolsDeclarativeFeatures?: { fileInput?: boolean } } + return w.__ztoolsDeclarativeFeatures?.fileInput === true +} + +/** + * 生成可直接展开到 /
/ 的属性对象。 + * 旧版客户端会静默忽略未知的 descriptor.props.fileInput / onFileInput 属性而不报错; + * 新版客户端由 DeclarativeView 栈顶单点消费拖放与 Ctrl+V / ⌘V 粘贴输入。 + */ +export function createCompatFileInputProps( + onFiles: (files: string[], payload: CompatFileInputPayload) => void | Promise, + config?: CompatFileInputConfig +): { + fileInput: CompatFileInputConfig + onFileInput: (payload: CompatFileInputPayload | string[]) => void +} { + return { + fileInput: config ? { ...config } : {}, + onFileInput: (raw: CompatFileInputPayload | string[]) => { + const files = extractCompatInputFiles(raw) + if (files.length === 0) return + const normalizedPayload: CompatFileInputPayload = Array.isArray(raw) + ? { files, source: 'drop' } + : { + files, + source: raw?.source || 'drop', + ...(typeof raw?.targetFieldId === 'string' && raw.targetFieldId ? { targetFieldId: raw.targetFieldId } : {}), + ...(typeof raw?.rejectedCount === 'number' ? { rejectedCount: raw.rejectedCount } : {}) + } + void onFiles(files, normalizedPayload) + } + } +} diff --git a/extensions/image-editor/src/i18n.ts b/extensions/image-editor/src/i18n.ts new file mode 100644 index 00000000..c221370b --- /dev/null +++ b/extensions/image-editor/src/i18n.ts @@ -0,0 +1,201 @@ +import { createTranslator } from '@ztools/declarative-ui' + +const MESSAGES = { + 'zh-CN': { + navTitle: '图片轻量编辑与美化工作台', + searchPlaceholder: '筛选队列中的图片文件名或路径…', + workbenchTitle: '修图参数配置', + workbenchSubtitle: '参数实时联动右侧预览摘要与批量导出队列', + queueTitle: '待处理图片队列', + queueSubtitle: '已勾选 {checked} / 共 {total} 张', + queueEmptyText: '拖入图片、点击「选择图片」或「粘贴剪贴板图片」开始编辑', + fieldFormat: '输出格式', + fieldScaleMode: '尺寸缩放', + fieldCustomWidth: '自定义宽度 (px)', + fieldCropPreset: '裁剪比例', + fieldFreeCrop: '自由裁剪 (x,y,w,h)', + fieldRotate: '顺时针旋转', + fieldFlip: '图像翻转', + fieldWatermarkText: '文字水印', + fieldWatermarkPos: '水印位置', + fieldWatermarkOpacity: '水印透明度', + fieldCornerRadius: '圆角半径 (px)', + fieldFramePadding: '美化背景内边距 (px)', + fieldFrameTheme: '美化背景主题', + scaleSource: '保持原尺寸', + scale1920: '宽度 1920px', + scale1280: '宽度 1280px', + scale800: '宽度 800px', + scaleCustom: '自定义宽度', + cropNone: '不裁剪', + cropFree: '自由像素', + rotate0: '不旋转 (0°)', + rotate90: '90°', + rotate180: '180°', + rotate270: '270°', + flipNone: '不翻转', + flipHorizontal: '水平翻转', + flipVertical: '垂直翻转', + flipBoth: '双向翻转', + posBottomRight: '右下角', + posBottomLeft: '左下角', + posTopRight: '右上角', + posTopLeft: '左上角', + posCenter: '居中', + themeNone: '无背景框', + themeSurface: '极简纸白', + themeOcean: '海湾蓝调', + themeSlate: '冷峻石板', + themeForest: '松林青灰', + themeSunset: '暖阳柔沙', + previewEmptyTitle: '等待导入图片', + previewEmptySubtitle: '导入后将通过 image.inspect 读取真实分辨率并计算目标参数', + previewTargetMetric: '预计输出尺寸', + previewPipelineMetric: '已启用步骤', + previewFormatMetric: '输出格式', + previewNoSteps: '无变换(仅重编码)', + actionAddImages: '选择图片', + actionPasteClipboard: '读取剪贴板图片', + actionBatchExport: '批量导出勾选图片', + actionSaveSingle: '另存为导出', + actionCopyOutputPath: '复制输出路径', + actionEnsureEngine: '准备图像引擎', + actionRemoveItem: '从队列移除', + actionClearQueue: '清空队列', + summaryReady: '图像引擎已就绪 · 队列 {count} 张', + summaryNeedsProvision: '图像引擎需按需准备 · 点击「准备图像引擎」后即可处理', + summaryUnsupported: '当前客户端暂不支持 image.inspect / image.process 能力', + statusPending: '待处理', + statusProcessing: '处理中…', + statusDone: '已完成', + statusFailed: '失败', + inspectingText: '读取尺寸中…', + inspectFailedText: '尺寸读取失败', + pickImagesTitle: '选择需要编辑的图片', + pickImagesFilterName: '图片文件', + pickOutputDirTitle: '选择批量导出目录', + saveImageTitle: '导出编辑后的图片', + dropTitle: '拖放图片到修图工作台', + dropSubtitle: '支持 PNG / JPG / WebP / BMP / GIF / TIFF', + toastEngineReady: '图像引擎已准备就绪', + toastEngineFailed: '准备图像引擎失败', + toastClipboardEmpty: '剪贴板中没有可用图片或图片文件路径', + toastClipboardLoaded: '已从剪贴板导入图片', + toastSingleExported: '导出成功:{name}', + toastBatchDone: '批量处理完成:成功 {succeeded} 张,失败 {failed} 张', + toastCopiedPath: '已复制输出路径', + toastInvalidFreeCrop: '自由裁剪格式应为 x,y,width,height(非负整数,宽高大于 0)', + toastNoCheckedItems: '请先在队列中勾选至少一张图片', + toastUnsupportedEngine: '当前宿主不支持图像原语能力,请升级客户端', + errUpgradeClient: '当前客户端版本暂不支持图像原语接口,请升级 ZTools 客户端后重试', + errInvalidHostResult: '客户端返回的图像处理结果无效', + errProcessFailed: '图像处理失败', + stepResize: '缩放', + stepCrop: '裁剪', + stepRotate: '旋转', + stepFlip: '翻转', + stepWatermark: '水印', + stepRadius: '圆角', + stepFrame: '背景框' + }, + 'en-US': { + navTitle: 'Image Editor & Beautify Workbench', + searchPlaceholder: 'Filter queued images by name or path…', + workbenchTitle: 'Edit Parameters', + workbenchSubtitle: 'Parameters sync live with the preview summary and export queue', + queueTitle: 'Image Queue', + queueSubtitle: '{checked} selected / {total} total', + queueEmptyText: 'Drop images, click Select Images, or paste a clipboard image to begin', + fieldFormat: 'Output Format', + fieldScaleMode: 'Resize', + fieldCustomWidth: 'Custom Width (px)', + fieldCropPreset: 'Crop Ratio', + fieldFreeCrop: 'Free Crop (x,y,w,h)', + fieldRotate: 'Rotate Clockwise', + fieldFlip: 'Flip', + fieldWatermarkText: 'Text Watermark', + fieldWatermarkPos: 'Watermark Position', + fieldWatermarkOpacity: 'Watermark Opacity', + fieldCornerRadius: 'Corner Radius (px)', + fieldFramePadding: 'Frame Padding (px)', + fieldFrameTheme: 'Frame Theme Token', + scaleSource: 'Original Size', + scale1920: 'Width 1920px', + scale1280: 'Width 1280px', + scale800: 'Width 800px', + scaleCustom: 'Custom Width', + cropNone: 'No Crop', + cropFree: 'Free Pixels', + rotate0: 'None (0°)', + rotate90: '90°', + rotate180: '180°', + rotate270: '270°', + flipNone: 'None', + flipHorizontal: 'Horizontal', + flipVertical: 'Vertical', + flipBoth: 'Both', + posBottomRight: 'Bottom Right', + posBottomLeft: 'Bottom Left', + posTopRight: 'Top Right', + posTopLeft: 'Top Left', + posCenter: 'Center', + themeNone: 'No Frame', + themeSurface: 'Clean Surface', + themeOcean: 'Ocean Breeze', + themeSlate: 'Cool Slate', + themeForest: 'Forest Mist', + themeSunset: 'Warm Sand', + previewEmptyTitle: 'No Image Loaded', + previewEmptySubtitle: 'Import images to inspect real dimensions via image.inspect', + previewTargetMetric: 'Estimated Output', + previewPipelineMetric: 'Active Steps', + previewFormatMetric: 'Format', + previewNoSteps: 'Re-encode only', + actionAddImages: 'Select Images', + actionPasteClipboard: 'Paste Clipboard Image', + actionBatchExport: 'Batch Export Selected', + actionSaveSingle: 'Export As…', + actionCopyOutputPath: 'Copy Output Path', + actionEnsureEngine: 'Prepare Image Engine', + actionRemoveItem: 'Remove from Queue', + actionClearQueue: 'Clear Queue', + summaryReady: 'Image engine ready · {count} in queue', + summaryNeedsProvision: 'Image engine requires provisioning · Click Prepare Image Engine', + summaryUnsupported: 'Host does not support image.inspect / image.process capabilities', + statusPending: 'Pending', + statusProcessing: 'Processing…', + statusDone: 'Done', + statusFailed: 'Failed', + inspectingText: 'Inspecting…', + inspectFailedText: 'Inspect failed', + pickImagesTitle: 'Select Images to Edit', + pickImagesFilterName: 'Images', + pickOutputDirTitle: 'Select Batch Output Folder', + saveImageTitle: 'Export Edited Image', + dropTitle: 'Drop Images Here', + dropSubtitle: 'Supports PNG / JPG / WebP / BMP / GIF / TIFF', + toastEngineReady: 'Image engine is ready', + toastEngineFailed: 'Failed to prepare image engine', + toastClipboardEmpty: 'No image or image file path found in clipboard', + toastClipboardLoaded: 'Imported image from clipboard', + toastSingleExported: 'Exported: {name}', + toastBatchDone: 'Batch finished: {succeeded} succeeded, {failed} failed', + toastCopiedPath: 'Output path copied', + toastInvalidFreeCrop: 'Free crop must be x,y,width,height (non-negative integers, width/height > 0)', + toastNoCheckedItems: 'Select at least one image in the queue first', + toastUnsupportedEngine: 'Image capabilities are unavailable in this client; please update ZTools', + errUpgradeClient: 'Your ZTools client does not support image primitives yet. Please update ZTools.', + errInvalidHostResult: 'Invalid image processing result returned by host', + errProcessFailed: 'Image processing failed', + stepResize: 'Resize', + stepCrop: 'Crop', + stepRotate: 'Rotate', + stepFlip: 'Flip', + stepWatermark: 'Watermark', + stepRadius: 'Radius', + stepFrame: 'Frame' + } +} as const + +export const DEFAULT_MESSAGES = MESSAGES['zh-CN'] +export const t = createTranslator(MESSAGES, { defaultLocale: 'en-US' }) diff --git a/extensions/image-editor/src/index.tsx b/extensions/image-editor/src/index.tsx new file mode 100644 index 00000000..06ce3a07 --- /dev/null +++ b/extensions/image-editor/src/index.tsx @@ -0,0 +1,727 @@ +import React, { + Action, + ActionPanel, + Clipboard, + Color, + Icon, + List, + Toast, + showToast, + useEffect, + useLocale, + useMemo, + useRef, + useState, + type WorkbenchFieldItem, + type WorkbenchPreviewCard +} from '@ztools/declarative-ui' +import { isDeclarativeFileInputSupported } from './host-compat.js' +import { t } from './i18n.js' +import { + DEFAULT_EDITOR_SETTINGS, + IMAGE_EXTENSIONS, + buildEditedFileName, + ensureImageCapabilities, + estimateOutputDimensions, + fileNameOf, + formatBytes, + inspectImageFile, + isSupportedImagePath, + joinOutputPath, + parseFreeCropExpression, + pickExportDirectory, + pickImageFiles, + pickSaveImagePath, + probeImageCapabilities, + processImageFile, + readClipboardImagePaths, + summarizeActiveSteps +} from './logic.js' +import type { + FrameThemeToken, + ImageCapabilityState, + ImageCropPreset, + ImageEditorSettings, + ImageFlipMode, + ImageOutputFormat, + ImageQueueItem, + ImageRotateAngle, + ImageScaleMode, + WatermarkPosition +} from './types.js' + +export * from './types.js' +export * from './logic.js' + +function statusLabel(status: ImageQueueItem['status']): string { + if (status === 'processing') return t('statusProcessing') + if (status === 'done') return t('statusDone') + if (status === 'failed') return t('statusFailed') + return t('statusPending') +} + +export default function ImageEditorCommand() { + useLocale() + + const [capability, setCapability] = useState({ + inspectStatus: 'ready', + processStatus: 'ready', + overallStatus: 'ready' + }) + const [settings, setSettings] = useState(DEFAULT_EDITOR_SETTINGS) + const [queue, setQueue] = useState([]) + const [checkedIds, setCheckedIds] = useState([]) + const [selectedId, setSelectedId] = useState(null) + const [searchText, setSearchText] = useState('') + const [busy, setBusy] = useState(false) + + const mountedRef = useRef(true) + const queueRef = useRef(queue) + queueRef.current = queue + + const refreshCapabilities = async () => { + const state = await probeImageCapabilities() + if (mountedRef.current) setCapability(state) + } + + useEffect(() => { + mountedRef.current = true + void refreshCapabilities() + return () => { + mountedRef.current = false + } + }, []) + + const inspectPaths = async (paths: readonly string[]) => { + for (const filePath of paths) { + const inspected = await inspectImageFile(filePath) + if (!mountedRef.current) return + setQueue((prev) => + prev.map((item) => + item.path === filePath + ? { + ...item, + meta: inspected.ok ? (inspected.meta ?? null) : null, + ...(inspected.ok ? { inspectError: undefined } : { inspectError: inspected.error }) + } + : item + ) + ) + } + } + + const enqueueImages = async (rawPaths: readonly string[]) => { + const existing = new Set(queueRef.current.map((item) => item.path.toLowerCase())) + const addedPaths: string[] = [] + const addedItems: ImageQueueItem[] = [] + + for (const raw of rawPaths) { + const p = raw.trim() + if (!p || !isSupportedImagePath(p)) continue + const key = p.toLowerCase() + if (existing.has(key)) continue + existing.add(key) + addedPaths.push(p) + addedItems.push({ + id: p, + path: p, + name: fileNameOf(p), + meta: null, + status: 'pending' + }) + } + + if (addedItems.length === 0) return + setQueue((prev) => [...prev, ...addedItems]) + setCheckedIds((prev) => Array.from(new Set([...prev, ...addedItems.map((item) => item.id)]))) + setSelectedId((prev) => prev ?? addedItems[0]!.id) + await inspectPaths(addedPaths) + } + + const handleSelectImages = async () => { + const files = await pickImageFiles() + if (files.length > 0) { + await enqueueImages(files) + } + } + + const handlePasteClipboard = async () => { + const files = await readClipboardImagePaths() + if (files.length === 0) { + await showToast({ style: Toast.Style.Failure, title: t('toastClipboardEmpty') }) + return + } + await enqueueImages(files) + await showToast({ style: Toast.Style.Success, title: t('toastClipboardLoaded') }) + } + + const handleEnsureEngine = async () => { + setBusy(true) + try { + const res = await ensureImageCapabilities() + if (!mountedRef.current) return + if (res.ok) { + await refreshCapabilities() + await showToast({ style: Toast.Style.Success, title: t('toastEngineReady') }) + } else { + await showToast({ + style: Toast.Style.Failure, + title: t('toastEngineFailed'), + message: res.error + }) + } + } finally { + if (mountedRef.current) setBusy(false) + } + } + + const validateBeforeProcess = (): boolean => { + if (capability.overallStatus === 'unsupported') { + void showToast({ style: Toast.Style.Failure, title: t('toastUnsupportedEngine') }) + return false + } + if (settings.cropPreset === 'free' && !parseFreeCropExpression(settings.freeCropText)) { + void showToast({ style: Toast.Style.Failure, title: t('toastInvalidFreeCrop') }) + return false + } + return true + } + + const handleSaveSingle = async (item: ImageQueueItem) => { + if (!validateBeforeProcess()) return + const outputPath = await pickSaveImagePath(item.path, settings.format) + if (!outputPath) return + + setBusy(true) + setQueue((prev) => prev.map((it) => (it.id === item.id ? { ...it, status: 'processing', error: undefined } : it))) + try { + const res = await processImageFile(item, outputPath, settings) + if (!mountedRef.current) return + if (res.ok && res.result) { + setQueue((prev) => + prev.map((it) => + it.id === item.id + ? { + ...it, + status: 'done', + outputPath: res.result!.outputPath ?? outputPath, + outputBytes: res.result!.outputBytes, + outputWidth: res.result!.width, + outputHeight: res.result!.height, + previewImageUrl: res.result!.previewDataUrl, + durationMs: res.result!.durationMs, + error: undefined + } + : it + ) + ) + await showToast({ + style: Toast.Style.Success, + title: t('toastSingleExported', { name: fileNameOf(res.result.outputPath ?? outputPath) }) + }) + } else { + setQueue((prev) => + prev.map((it) => (it.id === item.id ? { ...it, status: 'failed', error: res.error } : it)) + ) + await showToast({ style: Toast.Style.Failure, title: t('errProcessFailed'), message: res.error }) + } + } finally { + if (mountedRef.current) setBusy(false) + } + } + + const handleBatchExport = async () => { + if (!validateBeforeProcess()) return + const targets = queue.filter((item) => checkedIds.includes(item.id)) + if (targets.length === 0) { + await showToast({ style: Toast.Style.Failure, title: t('toastNoCheckedItems') }) + return + } + const outputDir = await pickExportDirectory() + if (!outputDir) return + + setBusy(true) + let succeeded = 0 + let failed = 0 + try { + for (const item of targets) { + if (!mountedRef.current) break + const outPath = joinOutputPath(outputDir, buildEditedFileName(item.path, settings.format)) + setQueue((prev) => + prev.map((it) => (it.id === item.id ? { ...it, status: 'processing', error: undefined } : it)) + ) + const res = await processImageFile(item, outPath, settings) + if (!mountedRef.current) break + if (res.ok && res.result) { + succeeded += 1 + setQueue((prev) => + prev.map((it) => + it.id === item.id + ? { + ...it, + status: 'done', + outputPath: res.result!.outputPath ?? outPath, + outputBytes: res.result!.outputBytes, + outputWidth: res.result!.width, + outputHeight: res.result!.height, + previewImageUrl: res.result!.previewDataUrl, + durationMs: res.result!.durationMs, + error: undefined + } + : it + ) + ) + } else { + failed += 1 + setQueue((prev) => + prev.map((it) => (it.id === item.id ? { ...it, status: 'failed', error: res.error } : it)) + ) + } + } + if (mountedRef.current) { + await showToast({ + style: failed === 0 ? Toast.Style.Success : Toast.Style.Failure, + title: t('toastBatchDone', { succeeded, failed }) + }) + } + } finally { + if (mountedRef.current) setBusy(false) + } + } + + const handleRemoveItem = (id: string) => { + setQueue((prev) => prev.filter((item) => item.id !== id)) + setCheckedIds((prev) => prev.filter((itemId) => itemId !== id)) + if (selectedId === id) setSelectedId(null) + } + + const activeItem = useMemo( + () => queue.find((item) => item.id === selectedId) ?? queue[0] ?? null, + [queue, selectedId] + ) + + const filteredQueue = useMemo(() => { + const q = searchText.trim().toLowerCase() + if (!q) return queue + return queue.filter((item) => `${item.name} ${item.path}`.toLowerCase().includes(q)) + }, [queue, searchText]) + + const updateSetting = (key: K, value: ImageEditorSettings[K]) => { + setSettings((prev) => ({ ...prev, [key]: value })) + } + + const workbenchFields: WorkbenchFieldItem[] = [ + { + id: 'format', + label: t('fieldFormat'), + type: 'select', + value: settings.format, + options: [ + { label: 'PNG', value: 'png' }, + { label: 'JPEG', value: 'jpeg' }, + { label: 'WebP', value: 'webp' } + ], + onChange: (val) => updateSetting('format', val as ImageOutputFormat) + }, + { + id: 'scaleMode', + label: t('fieldScaleMode'), + type: 'select', + value: settings.scaleMode, + options: [ + { label: t('scaleSource'), value: 'source' }, + { label: t('scale1920'), value: '1920' }, + { label: t('scale1280'), value: '1280' }, + { label: t('scale800'), value: '800' }, + { label: t('scaleCustom'), value: 'custom' } + ], + onChange: (val) => updateSetting('scaleMode', val as ImageScaleMode) + }, + ...(settings.scaleMode === 'custom' + ? [ + { + id: 'customWidth', + label: t('fieldCustomWidth'), + type: 'text' as const, + value: settings.customWidth, + onChange: (val: string) => updateSetting('customWidth', String(val ?? '')) + } + ] + : []), + { + id: 'cropPreset', + label: t('fieldCropPreset'), + type: 'select', + value: settings.cropPreset, + options: [ + { label: t('cropNone'), value: 'none' }, + { label: '1:1', value: '1:1' }, + { label: '16:9', value: '16:9' }, + { label: '4:3', value: '4:3' }, + { label: t('cropFree'), value: 'free' } + ], + onChange: (val) => updateSetting('cropPreset', val as ImageCropPreset) + }, + ...(settings.cropPreset === 'free' + ? [ + { + id: 'freeCropText', + label: t('fieldFreeCrop'), + type: 'text' as const, + value: settings.freeCropText, + onChange: (val: string) => updateSetting('freeCropText', String(val ?? '')) + } + ] + : []), + { + id: 'rotate', + label: t('fieldRotate'), + type: 'select', + value: String(settings.rotate), + options: [ + { label: t('rotate0'), value: '0' }, + { label: t('rotate90'), value: '90' }, + { label: t('rotate180'), value: '180' }, + { label: t('rotate270'), value: '270' } + ], + onChange: (val) => updateSetting('rotate', Number(val) as ImageRotateAngle) + }, + { + id: 'flip', + label: t('fieldFlip'), + type: 'select', + value: settings.flip, + options: [ + { label: t('flipNone'), value: 'none' }, + { label: t('flipHorizontal'), value: 'horizontal' }, + { label: t('flipVertical'), value: 'vertical' }, + { label: t('flipBoth'), value: 'both' } + ], + onChange: (val) => updateSetting('flip', val as ImageFlipMode) + }, + { + id: 'watermarkText', + label: t('fieldWatermarkText'), + type: 'text', + value: settings.watermarkText, + onChange: (val) => updateSetting('watermarkText', String(val ?? '')) + }, + ...(settings.watermarkText.trim() + ? [ + { + id: 'watermarkPosition', + label: t('fieldWatermarkPos'), + type: 'select' as const, + value: settings.watermarkPosition, + options: [ + { label: t('posBottomRight'), value: 'bottom-right' }, + { label: t('posBottomLeft'), value: 'bottom-left' }, + { label: t('posTopRight'), value: 'top-right' }, + { label: t('posTopLeft'), value: 'top-left' }, + { label: t('posCenter'), value: 'center' } + ], + onChange: (val: string) => updateSetting('watermarkPosition', val as WatermarkPosition) + }, + { + id: 'watermarkOpacity', + label: t('fieldWatermarkOpacity'), + type: 'select' as const, + value: settings.watermarkOpacity, + options: [ + { label: '20%', value: '0.2' }, + { label: '40%', value: '0.4' }, + { label: '60%', value: '0.6' }, + { label: '80%', value: '0.8' } + ], + onChange: (val: string) => updateSetting('watermarkOpacity', val) + } + ] + : []), + { + id: 'cornerRadius', + label: t('fieldCornerRadius'), + type: 'select', + value: settings.cornerRadius, + options: [ + { label: '0px', value: '0' }, + { label: '12px', value: '12' }, + { label: '24px', value: '24' }, + { label: '36px', value: '36' } + ], + onChange: (val) => updateSetting('cornerRadius', val) + }, + { + id: 'frameTheme', + label: t('fieldFrameTheme'), + type: 'select', + value: settings.frameTheme, + options: [ + { label: t('themeNone'), value: 'none' }, + { label: t('themeSurface'), value: 'surface' }, + { label: t('themeOcean'), value: 'ocean' }, + { label: t('themeSlate'), value: 'slate' }, + { label: t('themeForest'), value: 'forest' }, + { label: t('themeSunset'), value: 'sunset' } + ], + onChange: (val) => updateSetting('frameTheme', val as FrameThemeToken) + }, + ...(settings.frameTheme !== 'none' + ? [ + { + id: 'framePadding', + label: t('fieldFramePadding'), + type: 'select' as const, + value: settings.framePadding, + options: [ + { label: '0px', value: '0' }, + { label: '24px', value: '24' }, + { label: '48px', value: '48' }, + { label: '72px', value: '72' } + ], + onChange: (val: string) => updateSetting('framePadding', val) + } + ] + : []) + ] + + const activeSteps = summarizeActiveSteps(settings) + const estimatedDim = estimateOutputDimensions(activeItem?.meta ?? null, settings) + + const previewCard: WorkbenchPreviewCard = activeItem + ? { + title: activeItem.name, + subtitle: activeItem.meta + ? `${activeItem.meta.width} × ${activeItem.meta.height} · ${activeItem.meta.format.toUpperCase()} · ${formatBytes(activeItem.meta.sizeBytes)}` + : activeItem.inspectError || t('inspectingText'), + badge: statusLabel(activeItem.status), + ...(activeItem.previewImageUrl ? { imageUrl: activeItem.previewImageUrl } : {}), + metrics: [ + { + label: t('previewTargetMetric'), + value: estimatedDim ? `${estimatedDim.width} × ${estimatedDim.height}` : '-' + }, + { + label: t('previewPipelineMetric'), + value: activeSteps.length > 0 ? activeSteps.join(' · ') : t('previewNoSteps') + }, + { + label: t('previewFormatMetric'), + value: settings.format.toUpperCase() + } + ] + } + : { + title: t('previewEmptyTitle'), + subtitle: t('previewEmptySubtitle'), + metrics: [ + { + label: t('previewPipelineMetric'), + value: activeSteps.length > 0 ? activeSteps.join(' · ') : t('previewNoSteps') + } + ] + } + + const summaryText = + capability.overallStatus === 'unsupported' + ? t('summaryUnsupported') + : capability.overallStatus === 'needs_provisioning' + ? t('summaryNeedsProvision') + : t('summaryReady', { count: queue.length }) + + const allChecked = queue.length > 0 && checkedIds.length === queue.length + const checkedState: boolean | 'indeterminate' = + allChecked ? true : checkedIds.length > 0 ? 'indeterminate' : false + + const subListItems = filteredQueue.map((item) => { + const dimText = item.meta + ? `${item.meta.width} × ${item.meta.height} · ${item.meta.format.toUpperCase()}` + : item.inspectError || t('inspectingText') + const outSummary = + item.status === 'done' && item.outputBytes !== undefined + ? `${formatBytes(item.outputBytes)}${item.outputWidth && item.outputHeight ? ` · ${item.outputWidth}×${item.outputHeight}` : ''}` + : item.error || '' + + return ( + { + setCheckedIds((prev) => + checked ? Array.from(new Set([...prev, item.id])) : prev.filter((id) => id !== item.id) + ) + }} + onSelect={() => setSelectedId(item.id)} + accessories={[ + { + tag: + item.status === 'failed' + ? { value: statusLabel(item.status), color: Color.Red } + : statusLabel(item.status) + } + ]} + actions={ + + void handleSaveSingle(item)} + /> + void handleBatchExport()} + /> + {item.outputPath && ( + { + void Clipboard.copy(item.outputPath!).then(() => + showToast({ style: Toast.Style.Success, title: t('toastCopiedPath') }) + ) + }} + /> + )} + void handlePasteClipboard()} + /> + handleRemoveItem(item.id)} + /> + + } + /> + ) + }) + + const supportsFileInput = isDeclarativeFileInputSupported() + + const topActions = + capability.overallStatus === 'needs_provisioning' + ? [ + { + id: 'ensure-engine', + title: t('actionEnsureEngine'), + icon: Icon.Download, + style: 'primary', + onAction: () => void handleEnsureEngine() + }, + { + id: 'add-images', + title: t('actionAddImages'), + icon: Icon.Image, + onAction: () => void handleSelectImages() + } + ] + : [ + { + id: 'add-images', + title: t('actionAddImages'), + icon: Icon.Image, + onAction: () => void handleSelectImages() + }, + ...(queue.length > 0 + ? [ + { + id: 'batch-export', + title: t('actionBatchExport'), + icon: Icon.Download, + style: 'primary', + onAction: () => void handleBatchExport() + } + ] + : [ + { + id: 'paste-clipboard', + title: t('actionPasteClipboard'), + icon: Icon.Clipboard, + onAction: () => void handlePasteClipboard() + } + ]) + ] + + return ( + { + setCheckedIds(checked ? queue.map((item) => item.id) : []) + }, + items: subListItems + }} + actions={ + + void handleSelectImages()} /> + void handlePasteClipboard()} + /> + {queue.length > 0 && ( + { + setQueue([]) + setCheckedIds([]) + setSelectedId(null) + }} + /> + )} + + } + {...(supportsFileInput + ? { + fileInput: { + extensions: [...IMAGE_EXTENSIONS], + allowDirectories: false, + allowClipboardImage: true, + dropTitle: t('dropTitle'), + dropSubtitle: t('dropSubtitle') + }, + onFileInput: (payload: { files: string[] }) => { + if (Array.isArray(payload.files) && payload.files.length > 0) { + void enqueueImages(payload.files) + } + } + } + : {})} + /> + ) +} + +export const commands = { + 'image-editor-workbench': () => +} diff --git a/extensions/image-editor/src/logic.ts b/extensions/image-editor/src/logic.ts new file mode 100644 index 00000000..0df0b314 --- /dev/null +++ b/extensions/image-editor/src/logic.ts @@ -0,0 +1,455 @@ +import { resolveErrorMessage } from './error-i18n.js' +import { t } from './i18n.js' +import type { + ImageCapabilityState, + ImageCropRect, + ImageEditorSettings, + ImageInspectMeta, + ImageOutputFormat, + ImageProcessResponse, + ImageQueueItem, + ToolCapabilityStatus +} from './types.js' + +export const IMAGE_EXTENSIONS = ['.png', '.jpg', '.jpeg', '.webp', '.bmp', '.gif', '.tiff', '.tif'] as const +export const IMAGE_SUPPORTED_TEXT = 'PNG / JPG / WebP / BMP / GIF / TIFF' + +export const DEFAULT_EDITOR_SETTINGS: ImageEditorSettings = { + format: 'png', + scaleMode: 'source', + customWidth: '', + cropPreset: 'none', + freeCropText: '', + rotate: 0, + flip: 'none', + watermarkText: '', + watermarkPosition: 'bottom-right', + watermarkOpacity: '0.6', + cornerRadius: '0', + framePadding: '0', + frameTheme: 'none' +} + +interface HostBridge { + transport?: { + methods?: Record< + string, + (req: { + messageId: string + params: Record + timeoutMs?: number + }) => Promise<{ success?: boolean; data?: unknown; error?: { code?: string; message?: string } }> + > + } +} + +let reqSeq = 0 +function nextId(prefix = 'imged'): string { + reqSeq = (reqSeq + 1) % 1_000_000 + return `${prefix}_${Date.now()}_${reqSeq}` +} + +function isObject(value: unknown): value is Record { + return Boolean(value && typeof value === 'object' && !Array.isArray(value)) +} + +export function fileNameOf(filePath: string): string { + const normalized = filePath.replace(/\\/g, '/') + const idx = normalized.lastIndexOf('/') + return idx >= 0 ? normalized.slice(idx + 1) : normalized +} + +export function stripExtension(fileName: string): string { + const idx = fileName.lastIndexOf('.') + return idx > 0 ? fileName.slice(0, idx) : fileName +} + +export function formatBytes(bytes: number): string { + if (!Number.isFinite(bytes) || bytes < 0) return '0 B' + if (bytes < 1024) return `${Math.round(bytes)} B` + const units = ['KB', 'MB', 'GB'] + let val = bytes / 1024 + let i = 0 + while (val >= 1024 && i < units.length - 1) { + val /= 1024 + i += 1 + } + return `${val >= 100 ? val.toFixed(0) : val >= 10 ? val.toFixed(1) : val.toFixed(2)} ${units[i]}` +} + +export function extensionForFormat(format: ImageOutputFormat): string { + return format === 'jpeg' ? 'jpg' : format +} + +export function buildEditedFileName(sourcePath: string, format: ImageOutputFormat): string { + const stem = stripExtension(fileNameOf(sourcePath)) + return `${stem}_edited.${extensionForFormat(format)}` +} + +export function joinOutputPath(dirPath: string, fileName: string): string { + const sep = dirPath.includes('\\') || /^[A-Za-z]:/.test(dirPath) ? '\\' : '/' + return `${dirPath.replace(/[\\/]+$/, '')}${sep}${fileName}` +} + +/** 解析自由像素裁剪表达式 `x,y,width,height`(允许 x=0, y=0,严禁用 !val 误判 0) */ +export function parseFreeCropExpression(raw: string): ImageCropRect | null { + const trimmed = raw.trim() + if (!trimmed) return null + const parts = trimmed.split(/[\s,xX×]+/).filter(Boolean) + if (parts.length !== 4) return null + const nums = parts.map((p) => Number(p)) + if (nums.some((n) => !Number.isSafeInteger(n))) return null + const [x, y, width, height] = nums as [number, number, number, number] + if (x < 0 || y < 0 || width <= 0 || height <= 0) return null + return { x, y, width, height } +} + +/** 根据原图尺寸与裁剪预设计算居中比例裁剪框或自由裁剪框 */ +export function resolveCropRect( + meta: Pick | null, + settings: Pick +): ImageCropRect | null { + if (settings.cropPreset === 'none') return null + if (settings.cropPreset === 'free') { + const rect = parseFreeCropExpression(settings.freeCropText) + if (!rect) return null + if (!meta) return rect + const clampedX = Math.min(rect.x, Math.max(0, meta.width - 1)) + const clampedY = Math.min(rect.y, Math.max(0, meta.height - 1)) + const clampedW = Math.min(rect.width, Math.max(1, meta.width - clampedX)) + const clampedH = Math.min(rect.height, Math.max(1, meta.height - clampedY)) + return { x: clampedX, y: clampedY, width: clampedW, height: clampedH } + } + if (!meta || meta.width <= 0 || meta.height <= 0) return null + const ratioMap: Record<'1:1' | '16:9' | '4:3', number> = { + '1:1': 1, + '16:9': 16 / 9, + '4:3': 4 / 3 + } + const targetRatio = ratioMap[settings.cropPreset] + const currentRatio = meta.width / meta.height + if (currentRatio > targetRatio) { + const width = Math.max(1, Math.round(meta.height * targetRatio)) + const x = Math.max(0, Math.floor((meta.width - width) / 2)) + return { x, y: 0, width, height: meta.height } + } + const height = Math.max(1, Math.round(meta.width / targetRatio)) + const y = Math.max(0, Math.floor((meta.height - height) / 2)) + return { x: 0, y, width: meta.width, height } +} + +/** 解析目标缩放宽度(像素);不缩放时返回 undefined */ +export function resolveTargetWidth(settings: Pick): number | undefined { + if (settings.scaleMode === 'source') return undefined + if (settings.scaleMode === 'custom') { + const n = Number(settings.customWidth.trim()) + return Number.isSafeInteger(n) && n >= 16 && n <= 16384 ? n : undefined + } + return Number(settings.scaleMode) +} + +/** 根据原图真实尺寸与当前参数推算预计输出分辨率 */ +export function estimateOutputDimensions( + meta: ImageInspectMeta | null, + settings: ImageEditorSettings +): { width: number; height: number } | null { + if (!meta || meta.width <= 0 || meta.height <= 0) return null + const crop = resolveCropRect(meta, settings) + let width = crop ? crop.width : meta.width + let height = crop ? crop.height : meta.height + + const targetWidth = resolveTargetWidth(settings) + if (targetWidth !== undefined && targetWidth !== width) { + height = Math.max(1, Math.round((height * targetWidth) / width)) + width = targetWidth + } + + if (settings.rotate === 90 || settings.rotate === 270) { + const swapped = width + width = height + height = swapped + } + + const padding = Number(settings.framePadding) + if (settings.frameTheme !== 'none' && Number.isFinite(padding) && padding > 0) { + width += Math.floor(padding) * 2 + height += Math.floor(padding) * 2 + } + return { width, height } +} + +/** 生成当前启用的编辑步骤摘要 */ +export function summarizeActiveSteps(settings: ImageEditorSettings): string[] { + const steps: string[] = [] + if (resolveTargetWidth(settings) !== undefined) steps.push(t('stepResize')) + if (settings.cropPreset !== 'none') steps.push(t('stepCrop')) + if (settings.rotate !== 0) steps.push(`${t('stepRotate')} ${settings.rotate}°`) + if (settings.flip !== 'none') steps.push(t('stepFlip')) + if (settings.watermarkText.trim()) steps.push(t('stepWatermark')) + const radius = Number(settings.cornerRadius) + if (Number.isFinite(radius) && radius > 0) steps.push(`${t('stepRadius')} ${Math.floor(radius)}px`) + const padding = Number(settings.framePadding) + if (settings.frameTheme !== 'none' && Number.isFinite(padding) && padding > 0) { + steps.push(`${t('stepFrame')} +${Math.floor(padding)}px`) + } + return steps +} + +/** 构造发往宿主 `tool_image_process` 的结构化请求载荷(与 `ToolPathSlot` 规范一致) */ +export function buildImageProcessPayload( + item: Pick, + outputPath: string, + settings: ImageEditorSettings +): Record { + const crop = resolveCropRect(item.meta, settings) + const targetWidth = resolveTargetWidth(settings) + const radius = Number(settings.cornerRadius) + const padding = Number(settings.framePadding) + const opacity = Number(settings.watermarkOpacity) + + const payload: Record = { + taskId: nextId('imgjob'), + input: { path: item.path }, + output: { path: outputPath }, + overwrite: true, + format: settings.format + } + + if (targetWidth !== undefined) { + payload.width = targetWidth + payload.keepAspectRatio = true + } + if (crop) { + payload.crop = crop + } + if (settings.rotate !== 0) { + payload.rotate = settings.rotate + } + if (settings.flip !== 'none') { + payload.flip = settings.flip + } + if (settings.watermarkText.trim()) { + payload.watermarkText = settings.watermarkText.trim().slice(0, 120) + payload.watermarkOpacity = Number.isFinite(opacity) && opacity > 0 && opacity <= 1 ? opacity : 0.6 + } + if (Number.isFinite(radius) && radius > 0) { + payload.borderRadiusPx = Math.floor(radius) + } + if (settings.frameTheme !== 'none' && Number.isFinite(padding) && padding > 0) { + payload.paddingPx = Math.floor(padding) + payload.backgroundColor = settings.frameTheme + } + + return payload +} + +async function callHost( + method: string, + params: Record, + timeoutMs = 60_000 +): Promise<{ ok: boolean; data?: unknown; error?: string; errorCode?: string }> { + const fn = (globalThis as unknown as { __ztoolsElectron?: HostBridge }).__ztoolsElectron?.transport?.methods?.[method] + if (typeof fn !== 'function') { + return { ok: false, error: t('errUpgradeClient'), errorCode: 'METHOD_NOT_AVAILABLE' } + } + const isDialog = method === 'window_show_open_dialog' || method === 'window_show_save_dialog' + try { + const raw = await fn({ + messageId: nextId(method.slice(0, 16)), + params, + ...(!isDialog ? { timeoutMs } : {}) + }) + if (!isObject(raw) || raw.success !== true) { + return { + ok: false, + error: resolveErrorMessage(raw?.error ?? raw, t('errProcessFailed')), + ...(isObject(raw?.error) && typeof raw.error.code === 'string' ? { errorCode: raw.error.code } : {}) + } + } + return { ok: true, data: raw.data } + } catch (err) { + return { + ok: false, + error: resolveErrorMessage(err, t('errProcessFailed')) + } + } +} + +/** 查询宿主 `image.inspect` 与 `image.process` 能力就绪状态 */ +export async function probeImageCapabilities(): Promise { + const res = await callHost('tool_runtime_capabilities', {}, 10_000) + if (!res.ok || !isObject(res.data) || !Array.isArray(res.data.capabilities)) { + return { inspectStatus: 'unsupported', processStatus: 'unsupported', overallStatus: 'unsupported' } + } + const findStatus = (primitiveId: string): ToolCapabilityStatus => { + const cap = (res.data as { capabilities: unknown[] }).capabilities.find( + (item) => isObject(item) && item.primitiveId === primitiveId + ) + if (!isObject(cap)) return 'unsupported' + return cap.status === 'ready' || cap.status === 'needs_provisioning' ? cap.status : 'unsupported' + } + const inspectStatus = findStatus('image.inspect') + const processStatus = findStatus('image.process') + const overallStatus: ToolCapabilityStatus = + inspectStatus === 'unsupported' || processStatus === 'unsupported' + ? 'unsupported' + : inspectStatus === 'ready' && processStatus === 'ready' + ? 'ready' + : 'needs_provisioning' + return { inspectStatus, processStatus, overallStatus } +} + +/** 按需准备图像能力引擎 */ +export async function ensureImageCapabilities(): Promise<{ ok: boolean; error?: string }> { + for (const primitiveId of ['image.inspect', 'image.process'] as const) { + const res = await callHost('tool_runtime_ensure', { primitiveId }, 120_000) + if (!res.ok) { + return { ok: false, error: resolveErrorMessage(res, t('toastEngineFailed')) } + } + } + return { ok: true } +} + +/** 调用宿主 `tool_image_inspect` 读取图片真实尺寸与格式 */ +export async function inspectImageFile(filePath: string): Promise<{ ok: boolean; meta?: ImageInspectMeta; error?: string }> { + const res = await callHost('tool_image_inspect', { inputs: [{ path: filePath }] }, 20_000) + if (!res.ok || !isObject(res.data)) { + return { ok: false, error: resolveErrorMessage(res, t('inspectFailedText')) } + } + const items = Array.isArray(res.data.items) ? res.data.items : null + const first = items && items.length > 0 && isObject(items[0]) ? items[0] : res.data + const width = Number(first.width) + const height = Number(first.height) + const sizeBytes = Number(first.sizeBytes ?? first.size ?? 0) + const format = typeof first.format === 'string' && first.format.trim() ? first.format.trim().toLowerCase() : '' + if (!Number.isFinite(width) || width <= 0 || !Number.isFinite(height) || height <= 0 || !format) { + return { ok: false, error: t('errInvalidHostResult') } + } + return { + ok: true, + meta: { + width: Math.floor(width), + height: Math.floor(height), + format, + sizeBytes: Number.isFinite(sizeBytes) && sizeBytes >= 0 ? Math.floor(sizeBytes) : 0, + ...(typeof first.hasAlpha === 'boolean' ? { hasAlpha: first.hasAlpha } : {}) + } + } +} + +/** 调用宿主 `tool_image_process` 执行真实图像处理并落盘 */ +export async function processImageFile( + item: Pick, + outputPath: string, + settings: ImageEditorSettings +): Promise<{ ok: boolean; result?: ImageProcessResponse; error?: string }> { + const payload = buildImageProcessPayload(item, outputPath, settings) + const res = await callHost('tool_image_process', payload, 120_000) + if (!res.ok || !isObject(res.data)) { + return { ok: false, error: resolveErrorMessage(res, t('errProcessFailed')) } + } + const d = res.data + const outputBytes = Number(d.outputBytes ?? d.sizeBytes ?? d.size ?? 0) + if (!Number.isFinite(outputBytes) || outputBytes < 0) { + return { ok: false, error: t('errInvalidHostResult') } + } + const width = typeof d.width === 'number' && Number.isFinite(d.width) ? Math.floor(d.width) : undefined + const height = typeof d.height === 'number' && Number.isFinite(d.height) ? Math.floor(d.height) : undefined + const durationMs = + typeof d.durationMs === 'number' && Number.isFinite(d.durationMs) && d.durationMs >= 0 + ? Math.floor(d.durationMs) + : undefined + return { + ok: true, + result: { + outputPath: typeof d.outputPath === 'string' && d.outputPath ? d.outputPath : outputPath, + outputBytes: Math.floor(outputBytes), + ...(width !== undefined ? { width } : {}), + ...(height !== undefined ? { height } : {}), + ...(typeof d.format === 'string' && d.format ? { format: d.format } : {}), + ...(durationMs !== undefined ? { durationMs } : {}), + ...(typeof d.previewDataUrl === 'string' && d.previewDataUrl.startsWith('data:image/') + ? { previewDataUrl: d.previewDataUrl } + : {}) + } + } +} + +function extractDialogPaths(data: unknown): string[] { + if (!isObject(data)) return [] + const out: string[] = [] + if (typeof data.filePath === 'string' && data.filePath.trim()) out.push(data.filePath.trim()) + if (typeof data.folderPath === 'string' && data.folderPath.trim()) out.push(data.folderPath.trim()) + if (Array.isArray(data.filePaths)) { + for (const item of data.filePaths) { + if (typeof item === 'string' && item.trim()) out.push(item.trim()) + else if (isObject(item) && typeof item.path === 'string' && item.path.trim()) out.push(item.path.trim()) + } + } + return Array.from(new Set(out)) +} + +export function isSupportedImagePath(filePath: string): boolean { + const lower = filePath.toLowerCase() + return IMAGE_EXTENSIONS.some((ext) => lower.endsWith(ext)) +} + +/** 通过系统弹窗多选图片文件 */ +export async function pickImageFiles(): Promise { + const res = await callHost('window_show_open_dialog', { + title: t('pickImagesTitle'), + filters: [{ name: t('pickImagesFilterName'), extensions: ['png', 'jpg', 'jpeg', 'webp', 'bmp', 'gif', 'tiff'] }], + properties: ['openFile', 'multiSelections'] + }) + if (!res.ok || !isObject(res.data) || res.data.canceled === true) return [] + return extractDialogPaths(res.data).filter(isSupportedImagePath) +} + +/** 选择批量导出目录 */ +export async function pickExportDirectory(): Promise { + const res = await callHost('window_show_open_dialog', { + title: t('pickOutputDirTitle'), + properties: ['openDirectory', 'createDirectory'] + }) + if (!res.ok || !isObject(res.data) || res.data.canceled === true) return null + return extractDialogPaths(res.data)[0] ?? null +} + +/** 单张另存为弹窗 */ +export async function pickSaveImagePath(sourcePath: string, format: ImageOutputFormat): Promise { + const ext = extensionForFormat(format) + const res = await callHost('window_show_save_dialog', { + title: t('saveImageTitle'), + defaultName: buildEditedFileName(sourcePath, format), + filters: [{ name: format.toUpperCase(), extensions: [ext] }] + }) + if (!res.ok || !isObject(res.data) || res.data.canceled === true) return null + return extractDialogPaths(res.data)[0] ?? null +} + +/** + * 读取剪贴板中的图片文件路径或临时落盘图片路径(不造假数据:剪贴板无有效图片路径时返回空数组)。 + */ +export async function readClipboardImagePaths(): Promise { + // 1. 优先尝试读取剪贴板复制的图片文件列表 + const filesRes = await callHost('clipboard_read_files', {}, 5000) + if (filesRes.ok) { + const rawFiles = Array.isArray(filesRes.data) + ? filesRes.data + : isObject(filesRes.data) && Array.isArray(filesRes.data.files) + ? filesRes.data.files + : [] + const matched = rawFiles + .filter((item): item is string => typeof item === 'string' && item.trim().length > 0) + .map((p) => p.trim()) + .filter(isSupportedImagePath) + if (matched.length > 0) return matched + } + + // 2. 尝试读取剪贴板纯位图(宿主若支持返回临时文件路径 path 则直接导入) + const imgRes = await callHost('clipboard_read_image', {}, 5000) + if (imgRes.ok && isObject(imgRes.data) && typeof imgRes.data.path === 'string' && imgRes.data.path.trim()) { + return [imgRes.data.path.trim()] + } + return [] +} diff --git a/extensions/image-editor/src/types.ts b/extensions/image-editor/src/types.ts new file mode 100644 index 00000000..35480cd8 --- /dev/null +++ b/extensions/image-editor/src/types.ts @@ -0,0 +1,73 @@ +export type ToolCapabilityStatus = 'ready' | 'needs_provisioning' | 'unsupported' + +export type ImageOutputFormat = 'png' | 'jpeg' | 'webp' +export type ImageScaleMode = 'source' | '1920' | '1280' | '800' | 'custom' +export type ImageCropPreset = 'none' | '1:1' | '16:9' | '4:3' | 'free' +export type ImageRotateAngle = 0 | 90 | 180 | 270 +export type ImageFlipMode = 'none' | 'horizontal' | 'vertical' | 'both' +export type WatermarkPosition = 'bottom-right' | 'bottom-left' | 'top-right' | 'top-left' | 'center' +/** 预设语义背景色 Token(严禁硬编码 #hex,由宿主按主题 Token 渲染) */ +export type FrameThemeToken = 'none' | 'surface' | 'ocean' | 'slate' | 'forest' | 'sunset' + +export interface ImageCropRect { + readonly x: number + readonly y: number + readonly width: number + readonly height: number +} + +export interface ImageInspectMeta { + readonly width: number + readonly height: number + readonly format: string + readonly sizeBytes: number + readonly hasAlpha?: boolean +} + +export interface ImageEditorSettings { + readonly format: ImageOutputFormat + readonly scaleMode: ImageScaleMode + readonly customWidth: string + readonly cropPreset: ImageCropPreset + readonly freeCropText: string + readonly rotate: ImageRotateAngle + readonly flip: ImageFlipMode + readonly watermarkText: string + readonly watermarkPosition: WatermarkPosition + readonly watermarkOpacity: string + readonly cornerRadius: string + readonly framePadding: string + readonly frameTheme: FrameThemeToken +} + +export interface ImageQueueItem { + readonly id: string + readonly path: string + readonly name: string + readonly meta: ImageInspectMeta | null + readonly inspectError?: string + readonly status: 'pending' | 'processing' | 'done' | 'failed' + readonly outputPath?: string + readonly outputBytes?: number + readonly outputWidth?: number + readonly outputHeight?: number + readonly previewImageUrl?: string + readonly durationMs?: number + readonly error?: string +} + +export interface ImageProcessResponse { + readonly outputPath?: string + readonly outputBytes: number + readonly width?: number + readonly height?: number + readonly format?: string + readonly durationMs?: number + readonly previewDataUrl?: string +} + +export interface ImageCapabilityState { + readonly inspectStatus: ToolCapabilityStatus + readonly processStatus: ToolCapabilityStatus + readonly overallStatus: ToolCapabilityStatus +} diff --git a/extensions/image-editor/tests/index.test.mjs b/extensions/image-editor/tests/index.test.mjs new file mode 100644 index 00000000..bc61e94b --- /dev/null +++ b/extensions/image-editor/tests/index.test.mjs @@ -0,0 +1,190 @@ +import test from 'node:test' +import assert from 'node:assert/strict' +import { createHost, mount, tick } from '../../shared/test-harness.mjs' +import { + DEFAULT_EDITOR_SETTINGS, + buildImageProcessPayload, + commands, + estimateOutputDimensions, + parseFreeCropExpression, + resolveCropRect +} from '../dist/index.js' + +const host = createHost() +const views = [] + +const readyCapabilities = () => ({ + contractVersion: 1, + platform: 'windows', + domains: ['image'], + capabilities: [ + { + primitiveId: 'image.inspect', + domain: 'image', + summary: 'Inspect image metadata', + ipcMethods: ['tool_image_inspect'], + requiredPermissions: ['media.read'], + status: 'ready', + optionalExtensions: [] + }, + { + primitiveId: 'image.process', + domain: 'image', + summary: 'Process image transforms', + ipcMethods: ['tool_image_process'], + requiredPermissions: ['media.process'], + status: 'ready', + optionalExtensions: [] + } + ] +}) + +test.beforeEach(() => { + host.reset() + host.ipc.tool_runtime_capabilities = async () => readyCapabilities() + host.ipc.tool_runtime_ensure = async ({ primitiveId }) => ({ + primitiveId, + status: 'ready', + provisioned: true + }) + host.ipc.tool_image_inspect = async () => ({ + items: [ + { + displayName: 'sample.png', + width: 2400, + height: 1600, + format: 'png', + sizeBytes: 512000, + hasAlpha: true, + hasExif: false + } + ] + }) + host.ipc.tool_image_process = async ({ taskId }) => ({ + taskId: taskId || 'imgjob_1', + outputBytes: 184320, + width: 1280, + height: 720, + format: 'webp', + exifStripped: false + }) +}) + +test.afterEach(() => { + views.splice(0).forEach((v) => v.unmount()) +}) + +async function open() { + const view = await mount(commands['image-editor-workbench']) + views.push(view) + await tick(30) + return view +} + +test('裁剪解析允许坐标 0,比例裁剪与旋转/美化背景框目标尺寸联动计算准确', () => { + assert.deepEqual(parseFreeCropExpression('0,0,640,480'), { x: 0, y: 0, width: 640, height: 480 }) + assert.equal(parseFreeCropExpression('0,0,0,480'), null) + assert.equal(parseFreeCropExpression('-1,0,100,100'), null) + + const crop169 = resolveCropRect({ width: 2400, height: 1600 }, { cropPreset: '16:9', freeCropText: '' }) + assert.deepEqual(crop169, { x: 0, y: 125, width: 2400, height: 1350 }) + + const settings = { + ...DEFAULT_EDITOR_SETTINGS, + format: 'webp', + scaleMode: '1280', + cropPreset: '16:9', + rotate: 90, + flip: 'horizontal', + watermarkText: 'ZTools', + watermarkPosition: 'bottom-right', + watermarkOpacity: '0.6', + cornerRadius: '24', + frameTheme: 'ocean', + framePadding: '48' + } + const est = estimateOutputDimensions({ width: 2400, height: 1600, format: 'png', sizeBytes: 1000 }, settings) + // 16:9 -> 2400x1350 -> scale width 1280 => 1280x720 -> rotate 90 => 720x1280 -> padding 48*2 => 816x1376 + assert.deepEqual(est, { width: 816, height: 1376 }) + + const payload = buildImageProcessPayload( + { path: 'E:\\photos\\demo.png', meta: { width: 2400, height: 1600, format: 'png', sizeBytes: 1000 } }, + 'E:\\out\\demo_edited.webp', + settings + ) + assert.deepEqual(payload.input, { path: 'E:\\photos\\demo.png' }) + assert.deepEqual(payload.output, { path: 'E:\\out\\demo_edited.webp' }) + assert.equal(payload.width, 1280) + assert.equal(payload.keepAspectRatio, true) + assert.deepEqual(payload.crop, { x: 0, y: 125, width: 2400, height: 1350 }) + assert.equal(payload.rotate, 90) + assert.equal(payload.flip, 'horizontal') + assert.equal(payload.watermarkText, 'ZTools') + assert.equal(payload.watermarkOpacity, 0.6) + assert.equal(payload.borderRadiusPx, 24) + assert.equal(payload.paddingPx, 48) + assert.equal(payload.backgroundColor, 'ocean') +}) + +test('布局三工作台:导入图片自动调用 tool_image_inspect,调整参数并一键批量调用 tool_image_process', async () => { + host.ipc.window_show_open_dialog = async (params) => { + if (params.properties?.includes('openDirectory')) { + return { canceled: false, filePaths: ['E:\\exports'] } + } + return { canceled: false, filePaths: ['E:\\photos\\sample.png'] } + } + + const view = await open() + assert.equal(view.tree().props.isShowingDetail, false) + assert.ok(view.tree().props.workbenchPanel, '必须使用布局三 workbenchPanel') + assert.ok(view.tree().props.subList, '必须使用布局三 subList') + assert.equal(view.tree().props.subList.items.length, 0, '未导入图片时队列必须为空,严禁假数据') + + // 点击选择图片 + await view.tree().props.filterBar.actions.find((a) => a.id === 'add-images').onAction() + await tick(30) + + assert.equal(host.ipcCalls.filter(([m]) => m === 'tool_image_inspect').length, 1) + assert.equal(view.tree().props.subList.items.length, 1) + assert.match(view.tree().props.workbenchPanel.previewCard.subtitle, /2400 × 1600/) + + // 左栏调整参数:1:1 裁剪 + 水印 + 圆角 + const fields = view.tree().props.workbenchPanel.fields + fields.find((f) => f.id === 'cropPreset').onChange('1:1') + fields.find((f) => f.id === 'watermarkText').onChange('CONFIDENTIAL') + fields.find((f) => f.id === 'cornerRadius').onChange('12') + await tick(20) + + assert.match(view.tree().props.workbenchPanel.previewCard.metrics[0].value, /1600 × 1600/) + + // 批量导出 + await view.tree().props.filterBar.actions.find((a) => a.id === 'batch-export').onAction() + await tick(30) + + const processCall = host.ipcCalls.find(([m]) => m === 'tool_image_process') + assert.ok(processCall, '必须调用真实 tool_image_process') + assert.deepEqual(processCall[1].crop, { x: 400, y: 0, width: 1600, height: 1600 }) + assert.equal(processCall[1].watermarkText, 'CONFIDENTIAL') + assert.equal(processCall[1].borderRadiusPx, 12) + assert.equal(view.tree().props.subList.items[0].props.accessories[0].tag, '已完成') +}) + +test('支持读取剪贴板图片导入;处理失败时如实标记失败态不造假成功', async () => { + host.ipc.clipboard_read_files = async () => ({ files: ['E:\\clip\\shot.png'] }) + host.ipc.window_show_save_dialog = async () => ({ canceled: false, filePath: 'E:\\clip\\shot_edited.png' }) + host.ipc.tool_image_process = async () => { + throw new Error('图像编码失败') + } + + const view = await open() + await view.tree().props.filterBar.actions.find((a) => a.id === 'paste-clipboard').onAction() + await tick(30) + assert.equal(view.tree().props.subList.items.length, 1) + + const queueItem = view.tree().props.subList.items[0] + await view.run(queueItem, '另存为导出') + await tick(20) + + const tag = view.tree().props.subList.items[0].props.accessories[0].tag + assert.equal(tag.value, '失败') +}) diff --git a/extensions/image-editor/tsconfig.json b/extensions/image-editor/tsconfig.json new file mode 100644 index 00000000..b0bc7c48 --- /dev/null +++ b/extensions/image-editor/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ES2022", + "moduleResolution": "bundler", + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true, + "rootDir": "./src", + "outDir": "./dist", + "jsx": "react", + "jsxFactory": "React.createElement", + "jsxFragmentFactory": "React.Fragment" + }, + "include": ["src/**/*"] +} diff --git a/extensions/image-tool/README.md b/extensions/image-tool/README.md index 1c96a8dc..6efc9066 100644 --- a/extensions/image-tool/README.md +++ b/extensions/image-tool/README.md @@ -1,3 +1,3 @@ # 图像转换与元数据 -已下架:功能未完成(只有示例数据)。 +已下架:功能已合并至图片压缩与工具(`batch-image`)。 diff --git a/extensions/image-tool/plugin.json b/extensions/image-tool/plugin.json index 1a59271a..78615d58 100644 --- a/extensions/image-tool/plugin.json +++ b/extensions/image-tool/plugin.json @@ -3,8 +3,9 @@ "name": "图像转换与元数据", "description": "图片格式转换与分辨率、体积等元数据查看", "version": "1.0.0", + "minAppVersion": "1.1.8.0", "revoked": true, - "revokedReason": "功能未完成(只有示例数据)", + "revokedReason": "功能已合并至图片压缩与工具(batch-image)", "author": "ZTools Team", "entry": "dist/index.js", "icon": "icon.svg", @@ -23,5 +24,14 @@ "arch": "any" } ], - "nativeComponents": [] + "nativeComponents": [], + "categoryId": "media", + "defaultLocale": "zh-CN", + "i18n": { + "en-US": { + "name": "Image Converter & Metadata", + "description": "Convert image formats and inspect metadata such as resolution and file size.", + "revokedReason": "Merged into Batch Image & Inspector (batch-image)." + } + } } diff --git a/extensions/invoice-assistant/README.en.md b/extensions/invoice-assistant/README.en.md new file mode 100644 index 00000000..44fcebea --- /dev/null +++ b/extensions/invoice-assistant/README.en.md @@ -0,0 +1,35 @@ +# Invoice Assistant + +Import PDF, OFD, XML, JPG, or PNG electronic invoices via "Select Files", "Select Folder", or drag-and-drop / paste (folders scan recursively up to 5 levels and 500 files per run, automatically skipping previous `ZTools_Reimbursement_Export` folders). Extracts invoice number, issue date, seller, buyer, total amount, and tax amount, checks for duplicate invoice numbers and buyer header anomalies, and exports reimbursement summaries. + +## Usage + +- **Commands**: Summarize e-invoices and export reimbursement spreadsheets (`invoice`, `reimbursement`, `expense report`, `invoice summary`), copy e-invoices with standardized template filenames (`rename invoice`, `invoice archive`), and filter travel, transport, and hotel invoices (`travel invoice`, `hotel invoice`, `transport receipt`). +- **Import**: Use "Select Files" (`Ctrl+O`), "Select Folder" (`Ctrl+Shift+O`), or drag-and-drop / paste invoice files and folders directly in the top bar or empty state; files are parsed in batches of up to 50. +- **Verification & Completeness**: Unrecognized fields are marked "Unrecognized", and invoices whose issue date matches today are marked "Needs Review". Such invoices cannot be checked for export until you press `Ctrl+I` to complete or verify their details in the form. +- **Duplicate & Header Checks**: An invoice whose number matches an earlier invoice in the list is marked as a duplicate and cannot be checked. If the buyer name contains "个人", "先生", "女士", or contains no Chinese characters, it is flagged as a header anomaly and unchecked by default. +- **Naming Templates**: Select one of 4 filename templates on the right of the search bar (combining category, date, seller, amount, and invoice number). +- **Shortcuts**: + - `Enter`: Generate reimbursement archive—copies template-renamed invoice files and exports a reimbursement summary CSV (if fields are incomplete, `Enter` opens the completion form first). + - `Ctrl+Enter`: Copy reimbursement details of checked invoices (tab-separated for pasting into spreadsheets). + - `Ctrl+E`: Export only the reimbursement summary CSV. + - `Ctrl+T`: Cycle expense category. + - `Ctrl+Shift+C`: Copy current invoice details. + - `Ctrl+L`: Reveal original invoice in File Explorer. + - `Ctrl+Backspace`: Remove from list (does not delete the original file). + - `Ctrl+Shift+Backspace`: Clear list. + - `Ctrl+A`: Select / deselect all. + - `Delete`: Move original invoice file to Recycle Bin (requires confirmation). + - `Ctrl+K`: Open the action panel. +- **Export Output**: Each export creates `ZTools_Reimbursement_Export\报销归档_` inside the first invoice's parent directory and writes both renamed copies and the CSV there. Original invoices are never modified; duplicate filenames in the same batch get `_2`, `_3`, etc. appended. +- **Error Reporting**: When some files fail to read or parse, the failure count is shown and "Failed Files" on the left lets you copy the failed file paths and error reasons. + +## Platforms & Requirements + +- Supported: Windows only +- Built into the client; no separate installation required. +- Windows implementation is pending physical-device verification. + +## Network & Data + +- Offline only; all data stays on your device. diff --git a/extensions/invoice-assistant/plugin.json b/extensions/invoice-assistant/plugin.json index 673714cd..a7f25a64 100644 --- a/extensions/invoice-assistant/plugin.json +++ b/extensions/invoice-assistant/plugin.json @@ -1,8 +1,9 @@ { "id": "invoice-assistant", "name": "发票助手", - "description": "通过选择文件、选择文件夹或拖入导入 PDF/OFD/XML/图片电子发票,识别发票号码、开票日期、销售方、购买方与金额(识别不到的字段需手动补全后才能导出),支持发票号查重、个人抬头提示、按模板复制规范命名的发票副本、导出报销明细 CSV 与复制表格文本", - "version": "1.1.11", + "description": "通过宿主文档、归档薄原语与本地 OCR 编排四类电子发票输入:XML/OFD 结构化解析、PDF 文本提取、图片扫描件 OCR 与合并报销单 PDF;未识别字段一律返回 null 并标示未识别支持人工补录,支持发票号查重、金额 0 合法校验与导出报销明细 CSV", + "version": "2.0.0", + "minAppVersion": "1.3.0.4", "author": "ZTools Team", "entry": "dist/index.js", "icon": "icon.svg", @@ -16,17 +17,26 @@ "fapiao", "reimbursement", "pdf", + "ofd", + "xml", + "ocr", "csv", - "excel", "发票", "报销", "电子发票", - "数电票" + "数电票", + "发票助手", + "发票整理", + "发票合并", + "pdf发票", + "发票汇总", + "打印发票", + "算报销" ], "features": [ { "code": "invoice-reimburse", - "explain": "电子发票汇总与导出报销明细", + "explain": "电子发票汇总、合并报销单 PDF 与导出报销明细", "mode": "view", "cmds": [ "发票报销", @@ -60,6 +70,12 @@ ] } ], + "requiredCapabilities": [ + "document.pdf.inspect", + "document.pdf.transform", + "archive.list", + "archive.extract" + ], "permissions": [ "fs", "dialog", @@ -76,24 +92,30 @@ "arch": "any" } ], - "minAppVersion": "1.1.8.9", "defaultLocale": "zh-CN", "i18n": { "en-US": { "name": "Invoice Assistant", - "description": "Import PDF, OFD, XML, or image e-invoices to extract invoice numbers, dates, sellers, buyers, and amounts, detect duplicates, copy renamed archives, and export expense CSVs.", + "description": "Import XML, OFD, PDF, and scanned image e-invoices via host document/archive primitives and local OCR. Keeps unrecognized fields strictly null for manual review, detects duplicates, merges reimbursement PDFs, and exports CSV summaries.", "keywords": [ "invoice", "fapiao", "reimbursement", "expense", "pdf", + "ofd", + "xml", + "ocr", "csv", - "receipt" + "receipt", + "merge invoice", + "pdf invoice", + "tax", + "billing" ], "features": { "invoice-reimburse": { - "explain": "Summarize e-invoices and export reimbursement CSV spreadsheets", + "explain": "Summarize e-invoices, merge reimbursement PDFs, and export CSV spreadsheets", "cmds": [ "invoice", "reimbursement", diff --git a/extensions/invoice-assistant/src/i18n.ts b/extensions/invoice-assistant/src/i18n.ts index d778d0f7..7695ffbc 100644 --- a/extensions/invoice-assistant/src/i18n.ts +++ b/extensions/invoice-assistant/src/i18n.ts @@ -1,443 +1,286 @@ import { createTranslator } from '@ztools/declarative-ui' -const rawT = createTranslator( - { - 'zh-CN': { - fieldInvoiceNo: '发票号码', - fieldIssueDate: '开票日期', - fieldSellerName: '销售方', - fieldBuyerName: '购买方', - fieldTotalAmount: '价税合计', - fieldTaxAmount: '税额', - unrecognized: '未识别', - forbiddenReason: '发票归档输出目录不可指向系统受保护路径或包含路径穿越', - tpl1Title: '模板 1: [分类]_[日期]_[销方]_[金额]元_[尾号]', - tpl2Title: '模板 2: [日期]_[分类]_[金额]元_[销方]', - tpl3Title: '模板 3: [分类]_[金额]元_[销方]_[尾号]', - tpl4Title: '模板 4: [发票全号]_[日期]_[销方]_[金额]元', - tpl1Desc: '[餐饮招待]_2026-10-18_星巴克咖啡_68.00元_8921.pdf', - tpl2Desc: '2026-10-18_[餐饮招待]_68.00元_星巴克咖啡.pdf', - tpl3Desc: '[餐饮招待]_68.00元_星巴克咖啡_8921.pdf', - tpl4Desc: '24312000000048298921_2026-10-18_星巴克咖啡_68.00元.pdf', - grpAll: '全部电子发票', - grpTravel: '差旅 (交通出行 + 住宿)', - grpTransit: '交通出行 (滴滴/高铁/打车)', - grpLodging: '差旅住宿 (酒店/机票)', - grpDining: '餐饮招待 (餐饮/咖啡)', - grpOffice: '办公采购与云服务', - grpOther: '其他费用', - catDining: '餐饮招待', - catTransit: '交通出行', - catLodging: '差旅住宿', - catOffice: '办公采购', - catOther: '其他费用', - issueMissingPrefix: '未识别:{fields}', - issueNeedsReviewSuffix: '{fields}待核对', - listSep: '、', - semiSep: ';', - formatAmount: '{amount}元', - needsReviewTag: '{date}(待核对)', - tsvColIndex: '序号', - tsvColInvoiceNo: '发票号码', - tsvColIssueDate: '开票日期', - tsvColCategory: '费用分类', - tsvColSeller: '销方名称', - tsvColBuyer: '购方抬头', - tsvColTotal: '价税合计(元)', - tsvColTax: '税额(元)', - tsvColNet: '不含税金额(元)', - tsvColFileName: '归档文件名', - summaryLineNo: '发票号码: {val}', - summaryLineDate: '开票日期: {val}', - summaryLineSeller: '销方名称: {val}', - summaryLineBuyer: '购方名称: {val}', - summaryLineAmount: '价税合计: {total}元 (税额: {tax}元)', - errEditInvoiceNo: '发票号码应为 8 位(传统发票)或 20 位(数电发票)数字', - errEditIssueDate: '请按 YYYY-MM-DD 填写真实的开票日期,且不能晚于今天', - errEditSellerEmpty: '请填写销售方名称', - errEditSellerLong: '销售方名称不能超过 100 个字符', - errEditBuyerEmpty: '请填写购买方名称(发票抬头)', - errEditBuyerLong: '购买方名称不能超过 100 个字符', - errEditTotalInvalid: '价税合计应为大于 0 的金额,最多两位小数', - errEditTotalRange: '价税合计超出范围', - errEditTaxInvalid: '税额应为不小于 0 的金额,最多两位小数(免税填 0)', - errEditTaxExceeds: '税额不能大于价税合计', - errMethodEmpty: 'INVALID_METHOD: 调用方法名不能为空', - errMethodFormat: 'INVALID_METHOD_FORMAT: 方法名包含非法字符或超长', - errParamsObject: 'INVALID_PARAMS: 参数必须为非空对象', - errParamTooLong: 'PARAM_TOO_LONG: 参数 {key} 超过最大长度限制', - errSecurityIntercepted: 'SECURITY_INTERCEPTED: {reason}', - errParamValidation: '参数校验失败', - errHostNoInvoiceResult: '宿主没有返回发票识别结果', - nthResultFallback: '第 {n} 条结果', - errResultMissingPath: '识别结果缺少文件路径', - errParseInvoicesFailed: '识别电子发票失败', - errUnknown: '未知错误', - errCannotResolveDir: '无法确定发票所在目录: {path}', - emptyPathLabel: '(空路径)', - exportDirPrefix: '报销归档', - errExportEmpty: '请先勾选至少 1 张需要报销的电子发票', - errExportIncomplete: '{count} 张发票有未识别或待核对的字段(如 {file}),请先补全', - errExportDuplicate: '{count} 张发票与其他发票号码重复(如 {file}),不能重复报销', - errCopyBundleFailed: '复制规范命名副本失败:{error}({dir} 中可能已有部分副本)', - errHostNoReason: '宿主未说明原因', - errHostNoCopiedFiles: '宿主没有返回已复制的文件列表,无法确认副本已生成', - errPartialCopied: '只复制了 {copied}/{total} 份副本,未生成报销明细 CSV', - copiedNotePrefix: '已复制 {count} 份副本,但', - errExportCsvFailed: '{note}生成报销明细 CSV 失败:{error}', - errHostNoCsvPath: '{note}宿主没有返回 CSV 文件路径,无法确认报销明细已生成', - errTrashFailed: '移入回收站失败', - // index.ts - toastFixRedFields: '请先修正标红的字段', - toastSaveNotInList: '保存失败:这张发票已不在列表中', - toastSavedInvoice: '已保存发票信息', - formSaveAction: '保存发票信息', - formNavTitle: '核对发票信息:{file}', - formOriginalFile: '原发票文件', - formOriginalFileDesc: '{file}\n{issues},请对照发票原件填写。', - phInvoiceNo: '8 位或 20 位数字', - infoIssueDateReview: '识别结果与今天相同,可能是未识别到日期时的默认值,请对照发票核对', - phSellerName: '发票上的销售方名称', - phBuyerName: '发票抬头(购买方名称)', - phTotalAmount: '例如 128.50', - phTaxAmount: '免税或不含税额时填 0', - noteAlreadyInList: '{count} 个已在列表中', - noteIgnoredUnsupported: '忽略 {count} 个不支持的文件', - noteTruncated: '文件较多,只导入了一部分', - noteFailedDirs: '{count} 个子文件夹无法读取', - toastPartialImportTitle: '已添加 {added} 张,{errors} 个文件读取或识别失败', - toastAllImportFailedTitle: '{errors} 个文件读取或识别失败', - noteCheckedCount: '当前已勾选 {count} 张可报销发票', - toastImportFailed: '导入电子发票失败', - pickFilesTitle: '选择电子发票文件', - pickFilesFilter: '电子发票', - pickFolderTitle: '选择包含电子发票的文件夹', - errNoFolderSelected: '没有选择文件夹', - confirmRootTitle: '导入整个磁盘 {path} 中的电子发票?', - confirmRootMsg: '将读取该磁盘下 5 层以内的文件夹,最多导入 500 个文件,可能需要一些时间。', - confirmRootAction: '继续导入', - toastWaitProcessingRemove: '正在处理,完成后再移除', - toastWaitProcessingClear: '正在处理,完成后再清空', - dropTitle: '拖入电子发票或文件夹', - dropSubtitle: '支持 PDF / OFD / XML / JPG / PNG,文件夹内 5 层以内一并导入', - toastExportingBundle: '正在为 {count} 张发票生成规范命名副本与报销明细...', - toastExportingCsv: '正在导出 {count} 张发票的报销明细 CSV...', - toastTotalSum: '合计 {amount}', - toastExportBundleFailed: '生成报销归档失败', - toastExportCsvFailed: '导出报销明细 CSV 失败', - toastExportBundleOk: '已复制 {count} 份规范命名副本并生成报销明细 CSV ({amount})', - toastExportCsvOk: '已导出 {count} 张发票的报销明细 CSV ({amount})', - toastOutputDirMsg: '输出目录: {dir}', - toastExportException: '导出报销材料异常', - toastPickToCopyTsv: '请先勾选需要复制的发票', - toastCopyTsvFailed: '复制报销明细失败', - toastCopyTsvOk: '已复制 {count} 条报销明细 (Excel TSV)', - toastCopyTsvHint: '可直接在 Excel / WPS / 飞书表格中粘贴成表', - toastIncompleteCannotCheck: '这张发票有未识别的字段,补全后才能勾选', - toastDuplicateCannotCheck: '发票号码与其他发票重复,不能重复报销', - toastDuplicateHint: '如果识别有误,请先修改发票号码', - toastCopyFailed: '复制失败', - toastCopiedParseErrors: '已复制 {count} 条读取失败记录', - toastNoSelectable: '当前列表中没有可勾选的合规发票', - actionPickFiles: '选择文件…', - actionPickFolder: '选择文件夹…', - actionClearList: '清空列表', - exportBundleBtnTitle: '生成报销归档:规范命名副本 + 明细 CSV ({count}张 · {amount})', - actionEditComplete: '核对 / 修改发票信息', - actionEditIncomplete: '补全未识别的发票信息', - actionCopyTsv: '复制已选发票的报销明细 (Excel TSV)', - actionExportCsv: '仅导出已选发票的报销明细 (.csv)', - actionCycleCategory: '切换费用分类 (当前: {category})', - actionCopySummary: '复制当前发票信息文本', - toastCopiedSummary: '已复制发票信息', - actionLocateFile: '在资源管理器定位原发票', - toastLocateFailed: '无法在资源管理器中定位该发票', - actionTrashFile: '将当前发票原件移入系统回收站', - toastWaitProcessingTrash: '正在处理,完成后再移入回收站', - confirmTrashTitle: '确认将该发票移入回收站?', - confirmTrashMsg: '文件名: {file}\n发票号: {no}\n金额: {amount}', - confirmTrashBtn: '移入回收站', - toastTrashed: '已移入系统回收站', - toastTrashFailed: '移除失败', - toastFileInUse: '文件可能被占用', - sectionList: '列表', - actionRemoveFromList: '从列表移除(不删原件)', - actionDeselectAll: '取消全选', - actionSelectAll: '全选', - tagIncomplete: '信息不全', - tagDuplicate: '重复发票号', - tagAbnormalHeader: '抬头异常', - amountUnrecognized: '金额未识别', - itemSubtitleComplete: '发票号: {no} · 购方: {buyer} · 税额: {tax}', - summarySelected: '已选 {selected}/{total} 张发票 · 报销总额 {amount} (含税额 {tax})', - summaryDuplicates: '重复票 {count} 张', - summaryIncomplete: '信息不全 {count} 张', - summaryParseErrors: '读取失败 {count} 个文件', - summaryClearHint: '清空列表 Ctrl+Shift+Backspace', - summaryParsing: '正在导入:已找到 {total} 个文件,正在识别({done}/{total})...', - summaryReading: '正在导入:已读取 {dirs} 个文件夹,找到 {files} 个文件', - emptyClientNeeded: '需要在 ZTools 客户端中使用', - emptyNoInvoices: '尚未添加电子发票 · 可选择文件、文件夹,或直接拖入', - emptyNoMatch: '当前分类下没有匹配的电子发票', - auditDupTitle: '重复发票号防重拦截', - auditDupSubFound: '检测到 {count} 张发票号码与其他发票相同,已取消勾选防止重复报销', - auditDupSubNone: '已识别的发票号码没有重复', - auditDupTagFound: '{count} 张重复', - auditDupTagNone: '无重复', - auditDupPanel: '重复发票号筛查', - auditDupAction: '仅筛选查看重复发票', - auditHeaderTitle: '购方抬头检查', - auditHeaderSubFound: '发现 {count} 张个人或非企业抬头发票,默认不勾选', - auditHeaderSubNone: '已识别的购方抬头中没有个人抬头', - auditHeaderTagFound: '{count} 张异常', - auditHeaderTagNone: '无异常', - auditHeaderPanel: '抬头异常筛查', - auditHeaderAction: '仅筛选查看抬头异常发票', - auditIncTitle: '未识别字段', - auditIncSubFound: '{count} 张发票有未识别或待核对的字段,补全后才能勾选导出', - auditIncSubNone: '全部发票的报销字段均已识别', - auditIncTagFound: '{count} 张待补全', - auditIncTagNone: '已完整', - auditIncPanel: '未识别字段筛查', - auditIncAction: '仅筛选查看信息不全的发票', - auditErrTitle: '读取失败的文件', - auditErrSub: '{count} 个文件无法读取或识别,未列入右侧', - auditErrTag: '{count} 个失败', - auditErrAction: '复制失败文件与原因', - searchPlaceholder: '搜索开票商户、发票号码、开票日期、金额或费用分类...', - dropdownTooltip: '选择归档文件命名模板', - barPickFiles: '选择文件', - barPickFolder: '选择文件夹', - subListTitle: '发票识别与归档命名预览 (勾选后按 ↵ 生成规范命名副本 + 报销明细 CSV)', - subListSubtitle: '{count} 张发票 · 已选报销合计 {amount}', - catSectionTitle: '费用科目与报销分类导航', - catSubWithUnknown: '{amount}(另有 {count} 张金额未识别)', - catCountText: '{count} 张', - catFilterAction: '筛选查看「{name}」', - auditSectionTitle: '报销合规预检' - }, - 'en-US': { - fieldInvoiceNo: 'Invoice No.', - fieldIssueDate: 'Issue Date', - fieldSellerName: 'Seller', - fieldBuyerName: 'Buyer', - fieldTotalAmount: 'Total Amount', - fieldTaxAmount: 'Tax Amount', - unrecognized: 'Unrecognized', - forbiddenReason: 'Export directory cannot point to protected system paths or contain path traversal', - tpl1Title: 'Template 1: [Category]_[Date]_[Seller]_[Amount]_[Last4]', - tpl2Title: 'Template 2: [Date]_[Category]_[Amount]_[Seller]', - tpl3Title: 'Template 3: [Category]_[Amount]_[Seller]_[Last4]', - tpl4Title: 'Template 4: [InvoiceNo]_[Date]_[Seller]_[Amount]', - tpl1Desc: '[Dining]_2026-10-18_Starbucks_CNY68.00_8921.pdf', - tpl2Desc: '2026-10-18_[Dining]_CNY68.00_Starbucks.pdf', - tpl3Desc: '[Dining]_CNY68.00_Starbucks_8921.pdf', - tpl4Desc: '24312000000048298921_2026-10-18_Starbucks_CNY68.00.pdf', - grpAll: 'All E-Invoices', - grpTravel: 'Travel (Transit + Lodging)', - grpTransit: 'Transit (Ride-hailing / Rail)', - grpLodging: 'Lodging (Hotel / Flight)', - grpDining: 'Dining & Meals', - grpOffice: 'Office & Cloud Services', - grpOther: 'Other Expenses', - catDining: 'Dining', - catTransit: 'Transit', - catLodging: 'Lodging', - catOffice: 'Office', - catOther: 'Other', - issueMissingPrefix: 'Missing: {fields}', - issueNeedsReviewSuffix: '{fields} needs review', - listSep: ', ', - semiSep: '; ', - formatAmount: 'CNY{amount}', - needsReviewTag: '{date} (Needs Review)', - tsvColIndex: 'No.', - tsvColInvoiceNo: 'Invoice No.', - tsvColIssueDate: 'Issue Date', - tsvColCategory: 'Category', - tsvColSeller: 'Seller', - tsvColBuyer: 'Buyer', - tsvColTotal: 'Total', - tsvColTax: 'Tax', - tsvColNet: 'Net Amount', - tsvColFileName: 'Archived File Name', - summaryLineNo: 'Invoice No.: {val}', - summaryLineDate: 'Issue Date: {val}', - summaryLineSeller: 'Seller: {val}', - summaryLineBuyer: 'Buyer: {val}', - summaryLineAmount: 'Total: {total} (Tax: {tax})', - errEditInvoiceNo: 'Invoice number must be 8 digits (legacy) or 20 digits (e-invoice)', - errEditIssueDate: 'Enter a valid issue date in YYYY-MM-DD (not in the future)', - errEditSellerEmpty: 'Enter the seller name', - errEditSellerLong: 'Seller name cannot exceed 100 characters', - errEditBuyerEmpty: 'Enter the buyer name (invoice title)', - errEditBuyerLong: 'Buyer name cannot exceed 100 characters', - errEditTotalInvalid: 'Total amount must be greater than 0 (up to 2 decimal places)', - errEditTotalRange: 'Total amount out of range', - errEditTaxInvalid: 'Tax amount must be 0 or greater (up to 2 decimal places)', - errEditTaxExceeds: 'Tax amount cannot exceed total amount', - errMethodEmpty: 'INVALID_METHOD: Method name cannot be empty', - errMethodFormat: 'INVALID_METHOD_FORMAT: Method name contains illegal characters or is too long', - errParamsObject: 'INVALID_PARAMS: Parameters must be a non-null object', - errParamTooLong: 'PARAM_TOO_LONG: Parameter {key} exceeds maximum length', - errSecurityIntercepted: 'SECURITY_INTERCEPTED: {reason}', - errParamValidation: 'Parameter validation failed', - errHostNoInvoiceResult: 'Host returned no invoice recognition results', - nthResultFallback: 'Result #{n}', - errResultMissingPath: 'Recognition result is missing file path', - errParseInvoicesFailed: 'Failed to parse e-invoices', - errUnknown: 'Unknown error', - errCannotResolveDir: 'Unable to determine invoice directory: {path}', - emptyPathLabel: '(empty path)', - exportDirPrefix: 'Reimbursement_Export', - errExportEmpty: 'Select at least 1 invoice to export', - errExportIncomplete: '{count} invoice(s) have missing or unverified fields (e.g. {file}); complete them first', - errExportDuplicate: '{count} invoice(s) have duplicate invoice numbers (e.g. {file}) and cannot be exported', - errCopyBundleFailed: 'Failed to copy renamed invoices: {error} (partial copies may exist in {dir})', - errHostNoReason: 'Host provided no reason', - errHostNoCopiedFiles: 'Host did not return copied file list; unable to confirm archive generation', - errPartialCopied: 'Only copied {copied}/{total} [[total:file|files]]; reimbursement CSV was not generated', - copiedNotePrefix: 'Copied {count} [[count:file|files]], but ', - errExportCsvFailed: '{note}failed to export reimbursement CSV: {error}', - errHostNoCsvPath: '{note}host did not return CSV path; unable to confirm CSV generation', - errTrashFailed: 'Failed to move file to Trash', - toastFixRedFields: 'Fix highlighted fields first', - toastSaveNotInList: 'Save failed: invoice is no longer in the list', - toastSavedInvoice: 'Saved Invoice Details', - formSaveAction: 'Save Invoice', - formNavTitle: 'Review Invoice: {file}', - formOriginalFile: 'Source File', - formOriginalFileDesc: '{file}\n{issues}. Verify against the original invoice.', - phInvoiceNo: '8 or 20 digits', - infoIssueDateReview: 'Matches today’s date; may be a fallback value. Verify against the invoice.', - phSellerName: 'Seller name on the invoice', - phBuyerName: 'Buyer / entity title on the invoice', - phTotalAmount: 'e.g. 128.50', - phTaxAmount: 'Enter 0 if tax-exempt', - noteAlreadyInList: '{count} already in list', - noteIgnoredUnsupported: 'ignored {count} unsupported file(s)', - noteTruncated: 'too many files, partially imported', - noteFailedDirs: '{count} subfolder(s) unreadable', - toastPartialImportTitle: 'Added {added}; {errors} file(s) failed to read or parse', - toastAllImportFailedTitle: '{errors} file(s) failed to read or parse', - noteCheckedCount: '{count} valid invoice(s) selected', - toastImportFailed: 'Failed to Import Invoices', - pickFilesTitle: 'Select E-Invoice Files', - pickFilesFilter: 'E-Invoices', - pickFolderTitle: 'Select Folder Containing E-Invoices', - errNoFolderSelected: 'No folder selected', - confirmRootTitle: 'Import e-invoices from entire drive {path}?', - confirmRootMsg: 'Scans up to 5 folder levels (max 500 files), which may take a while.', - confirmRootAction: 'Continue Import', - toastWaitProcessingRemove: 'Processing in progress; wait before removing', - toastWaitProcessingClear: 'Processing in progress; wait before clearing', - dropTitle: 'Drop E-Invoices or Folders', - dropSubtitle: 'Supports PDF / OFD / XML / JPG / PNG (scans up to 5 folder levels)', - toastExportingBundle: 'Generating renamed copies and CSV for {count} invoice(s)...', - toastExportingCsv: 'Exporting reimbursement CSV for {count} invoice(s)...', - toastTotalSum: 'Total {amount}', - toastExportBundleFailed: 'Archive Export Failed', - toastExportCsvFailed: 'CSV Export Failed', - toastExportBundleOk: 'Copied {count} renamed [[count:file|files]] & exported CSV ({amount})', - toastExportCsvOk: 'Exported CSV for {count} invoice(s) ({amount})', - toastOutputDirMsg: 'Output folder: {dir}', - toastExportException: 'Export Error', - toastPickToCopyTsv: 'Select at least one invoice to copy', - toastCopyTsvFailed: 'Failed to Copy Details', - toastCopyTsvOk: 'Copied {count} [[count:row|rows]] (Excel TSV)', - toastCopyTsvHint: 'Paste directly into Excel, WPS, or Feishu Sheets', - toastIncompleteCannotCheck: 'Complete missing fields before selecting this invoice', - toastDuplicateCannotCheck: 'Duplicate invoice number cannot be selected', - toastDuplicateHint: 'Edit the invoice number if recognition was incorrect', - toastCopyFailed: 'Copy Failed', - toastCopiedParseErrors: 'Copied {count} failed file error(s)', - toastNoSelectable: 'No complete non-duplicate invoices in current view', - actionPickFiles: 'Select Files…', - actionPickFolder: 'Select Folder…', - actionClearList: 'Clear List', - exportBundleBtnTitle: 'Export Bundle: Renamed Copies + CSV ({count} · {amount})', - actionEditComplete: 'Review / Edit Invoice', - actionEditIncomplete: 'Complete Missing Fields', - actionCopyTsv: 'Copy Selected Rows (Excel TSV)', - actionExportCsv: 'Export Selected to CSV Only (.csv)', - actionCycleCategory: 'Switch Category (Current: {category})', - actionCopySummary: 'Copy Invoice Summary', - toastCopiedSummary: 'Copied Invoice Summary', - actionLocateFile: 'Reveal Original File', - toastLocateFailed: 'Unable to reveal file in folder', - actionTrashFile: 'Move Original File to Trash', - toastWaitProcessingTrash: 'Processing in progress; wait before trashing', - confirmTrashTitle: 'Move this invoice file to Trash?', - confirmTrashMsg: 'File: {file}\nInvoice No.: {no}\nAmount: {amount}', - confirmTrashBtn: 'Move to Trash', - toastTrashed: 'Moved to Trash', - toastTrashFailed: 'Move to Trash Failed', - toastFileInUse: 'File may be in use', - sectionList: 'List', - actionRemoveFromList: 'Remove from List (Keep File)', - actionDeselectAll: 'Deselect All', - actionSelectAll: 'Select All', - tagIncomplete: 'Incomplete', - tagDuplicate: 'Duplicate No.', - tagAbnormalHeader: 'Buyer Mismatch', - amountUnrecognized: 'Amount Missing', - itemSubtitleComplete: 'No.: {no} · Buyer: {buyer} · Tax: {tax}', - summarySelected: 'Selected {selected}/{total} · Total {amount} (Tax {tax})', - summaryDuplicates: '{count} duplicate(s)', - summaryIncomplete: '{count} incomplete', - summaryParseErrors: '{count} failed', - summaryClearHint: 'Clear Ctrl+Shift+Backspace', - summaryParsing: 'Importing: found {total} [[total:file|files]], parsing ({done}/{total})...', - summaryReading: 'Importing: scanned {dirs} [[dirs:folder|folders]], found {files} [[files:file|files]]', - emptyClientNeeded: 'Requires ZTools desktop client', - emptyNoInvoices: 'No e-invoices yet · Select files, folder, or drop here', - emptyNoMatch: 'No matching e-invoices in this category', - auditDupTitle: 'Duplicate Invoice Check', - auditDupSubFound: '{count} invoice(s) share an invoice number and were deselected', - auditDupSubNone: 'No duplicate invoice numbers found', - auditDupTagFound: '{count} [[count:Duplicate|Duplicates]]', - auditDupTagNone: 'No Duplicates', - auditDupPanel: 'Duplicate Filter', - auditDupAction: 'Filter Duplicate Invoices', - auditHeaderTitle: 'Buyer Header Check', - auditHeaderSubFound: '{count} invoice(s) have personal or non-company buyer titles', - auditHeaderSubNone: 'No personal buyer titles detected', - auditHeaderTagFound: '{count} Flagged', - auditHeaderTagNone: 'OK', - auditHeaderPanel: 'Header Filter', - auditHeaderAction: 'Filter Flagged Headers', - auditIncTitle: 'Missing Fields', - auditIncSubFound: '{count} invoice(s) have missing or unverified fields', - auditIncSubNone: 'All invoice fields are recognized', - auditIncTagFound: '{count} Incomplete', - auditIncTagNone: 'Complete', - auditIncPanel: 'Incomplete Filter', - auditIncAction: 'Filter Incomplete Invoices', - auditErrTitle: 'Failed Files', - auditErrSub: '{count} file(s) could not be read or parsed', - auditErrTag: '{count} Failed', - auditErrAction: 'Copy Failed Files & Reasons', - searchPlaceholder: 'Search seller, invoice number, date, amount, or category...', - dropdownTooltip: 'Select rename template', - barPickFiles: 'Select Files', - barPickFolder: 'Select Folder', - subListTitle: 'Parsed Invoices & Filename Preview (Check items and press ↵ to export)', - subListSubtitle: '{count} [[count:invoice|invoices]] · Selected Total {amount}', - catSectionTitle: 'Expense Categories', - catSubWithUnknown: '{amount} ({count} missing amount)', - catCountText: '{count}', - catFilterAction: 'Filter "{name}"', - auditSectionTitle: 'Compliance Checks' - } +const MESSAGES = { + 'zh-CN': { + unrecognized: '未识别', + forbiddenReason: '严禁向系统受保护目录或路径穿越目标写入文件', + catDining: '餐饮招待', + catTransit: '交通出行', + catLodging: '差旅住宿', + catOffice: '办公采购', + catOther: '其他费用', + fieldInvoiceNo: '发票号码', + fieldIssueDate: '开票日期', + fieldSellerName: '销售方', + fieldBuyerName: '购买方', + fieldTotalAmount: '价税合计', + fieldTaxAmount: '税额', + tpl1Title: '模板 1: [分类]_[日期]_[销方]_[金额]元_[尾号]', + tpl1Desc: '[餐饮招待]_2026-10-18_星巴克咖啡_68.00元_8921.pdf', + tpl2Title: '模板 2: [日期]_[分类]_[金额]元_[销方]', + tpl2Desc: '2026-10-18_[餐饮招待]_68.00元_星巴克咖啡.pdf', + tpl3Title: '模板 3: [分类]_[金额]元_[销方]_[尾号]', + tpl3Desc: '[餐饮招待]_68.00元_星巴克咖啡_8921.pdf', + tpl4Title: '模板 4: [发票全号]_[日期]_[销方]_[金额]元', + tpl4Desc: '24312000000048298921_2026-10-18_星巴克咖啡_68.00元.pdf', + grpAll: '全部发票', + grpTravel: '差旅 (交通 + 住宿)', + grpTransit: '交通出行', + grpLodging: '差旅住宿', + grpDining: '餐饮招待', + grpOffice: '办公采购', + grpOther: '其他费用', + grpIncomplete: '含未识别字段', + grpDuplicate: '重复发票号', + formatAmount: '{amount}元', + issueMissingPrefix: '未识别:{fields}', + listSep: '、', + tsvColIndex: '序号', + tsvColInvoiceNo: '发票号码', + tsvColIssueDate: '开票日期', + tsvColCategory: '费用分类', + tsvColSeller: '销售方', + tsvColBuyer: '购买方', + tsvColTotal: '价税合计', + tsvColTax: '税额', + tsvColNet: '不含税金额', + tsvColFileName: '归档文件名', + summaryLineNo: '发票号码:{val}', + summaryLineDate: '开票日期:{val}', + summaryLineSeller: '销售方:{val}', + summaryLineBuyer: '购买方:{val}', + summaryLineAmount: '价税合计:{total} | 税额:{tax}', + errEditInvoiceNo: '请输入 8 位或 20 位数字发票号码', + errEditIssueDate: '请输入有效日期(YYYY-MM-DD)', + errEditSellerEmpty: '销售方不能为空', + errEditSellerLong: '销售方名称不能超过 100 字', + errEditBuyerEmpty: '购买方不能为空', + errEditBuyerLong: '购买方名称不能超过 100 字', + errEditTotalInvalid: '请输入有效的非负金额(允许 0,最多两位小数)', + errEditTotalRange: '金额超出合理范围', + errEditTaxInvalid: '请输入有效的非负税额(允许 0,最多两位小数)', + errEditTaxExceeds: '税额不能大于价税合计', + errUnsupportedInvoiceFormat: '暂不支持的发票文件格式', + errXmlReadFailed: '读取 XML 发票内容失败', + errOfdListFailed: '读取 OFD 归档结构失败', + errOfdNoXml: 'OFD 中未找到可解析的发票 XML 节点', + errOfdExtractFailed: '提取 OFD 内部发票 XML 失败', + errPdfInspectFailed: '提取 PDF 发票文本失败', + errOcrFailed: '扫描件/图片发票 OCR 识别失败', + errMergePdfEmpty: '请选择至少 1 张 PDF 或图片发票以合并报销单', + errMergePdfFailed: '合并报销单 PDF 失败', + errExportEmpty: '请先勾选至少 1 张字段完整的发票', + errExportIncomplete: '存在 {count} 张含未识别字段的发票(如 {file}),请先人工补录', + errExportDuplicate: '存在 {count} 张重复发票号(如 {file}),请先核对去重', + errCsvWriteFailed: '导出报销明细 CSV 失败', + errTrashFailed: '移入回收站失败', + formNavTitle: '补录 / 编辑发票:{file}', + formSaveAction: '保存发票信息', + formOriginalFile: '原始文件', + formOriginalFileDesc: '{file}({issues})', + phInvoiceNo: '8 位传统票或 20 位全电发票号', + phSellerName: '销售方企业全称', + phBuyerName: '购买方抬头', + phTotalAmount: '价税合计(支持 0,如 128.50)', + phTaxAmount: '税额(支持 0,如 7.27)', + toastFixRedFields: '请先修正标红字段', + toastSaveNotInList: '该发票已不在当前列表', + toastSavedInvoice: '已保存发票信息', + toastImportOk: '已解析 {count} 张发票', + toastImportPartial: '已解析 {ok} 张,失败 {fail} 张', + toastImportFail: '发票导入解析失败', + toastMergePdfOk: '合并报销单 PDF 完成', + toastMergePdfMsg: '共 {pages} 页({size}):{path}', + toastMergePdfFail: '合并报销单 PDF 失败', + toastExportCsvOk: '报销明细 CSV 已导出', + toastExportCsvFail: '导出 CSV 失败', + toastCopyTsvOk: '已复制报销表格 TSV(可直接粘贴到 Excel)', + toastCopySummaryOk: '已复制发票摘要', + toastRevealFail: '无法打开文件位置', + pickFilesTitle: '选择电子发票文件', + pickFilesFilter: '电子发票 (PDF/OFD/XML/图片)', + pickFolderTitle: '选择电子发票文件夹', + errNoFolderPicked: '未选择文件夹', + confirmRootTitle: '确定扫描磁盘根目录 {path} 吗?', + confirmRootMsg: '扫描根目录可能耗时较长,建议选择具体发票文件夹。', + confirmRootAction: '继续扫描', + dropTitle: '拖入 PDF / OFD / XML / 扫描图片电子发票', + dropSubtitle: '未识别字段保持未识别状态供人工补录,绝不编造默认值', + searchPlaceholder: '搜索发票号、销售方、购买方或文件名...', + actionPickFiles: '导入发票...', + actionPickFolder: '导入文件夹...', + actionMergePdf: '合并报销单 PDF ({count})', + actionExportCsv: '导出报销明细 CSV ({count})', + actionCopyTsv: '复制表格文本 (TSV)', + actionEditInvoice: '补录 / 编辑字段', + actionCopySummary: '复制单票摘要', + actionRevealFile: '在文件夹中显示', + actionToggleAll: '全选 / 取消全选', + actionRemoveItem: '移出列表', + actionTrashItem: '移入回收站', + actionClearList: '清空列表', + wbTitle: '发票助手工作台', + wbSubtitle: 'XML / OFD / PDF / OCR · 零假默认值', + wbFilterLabel: '视图筛选', + wbTemplateLabel: '归档命名模板', + wbCardTitle: '报销汇总', + metricTotalCount: '发票总数', + metricSelectedSum: '已选金额合计', + metricIncomplete: '待补录', + metricDuplicate: '重复票', + cardNote: '未识别字段一律标记为「未识别」并支持人工补录;金额 0 合法,支持合并 PDF 与导出 CSV。', + subListTitle: '电子发票列表 ({count})', + subListSubtitle: '已勾选 {selected} 张 · 合计 {sum}', + emptyList: '请点击「导入发票」或拖入 PDF / OFD / XML / 图片发票', + emptyNoMatch: '没有匹配的发票记录', + tagIncomplete: '待补录', + tagDuplicate: '重复', + tagHeaderAbnormal: '个人抬头', + tagComplete: '可导出', + panelTitle: '发票助手', + sectionTitle: '发票列表 ({count})', + exportDirPrefix: '报销归档' }, - { defaultLocale: 'en-US' } -) -export const t: typeof rawT = (key, params) => { - const out = rawT(key, params) - if (!out.includes('[[')) return out - return out.replace(/\[\[([A-Za-z0-9_.-]+):([^|\]]+)\|([^\]]+)\]\]/g, (_m, k: string, one: string, other: string) => { - const v = params?.[k] - const n = typeof v === 'number' ? v : Number(String(v ?? '').replace(/,/g, '')) - return n === 1 ? one : other - }) + 'en-US': { + unrecognized: 'Unrecognized', + forbiddenReason: 'Protected system directories or traversal paths are blocked', + catDining: 'Dining', + catTransit: 'Transit', + catLodging: 'Lodging', + catOffice: 'Office', + catOther: 'Other', + fieldInvoiceNo: 'Invoice No.', + fieldIssueDate: 'Issue Date', + fieldSellerName: 'Seller', + fieldBuyerName: 'Buyer', + fieldTotalAmount: 'Total Amount', + fieldTaxAmount: 'Tax Amount', + tpl1Title: 'Template 1: [Category]_[Date]_[Seller]_[Amount]_[Tail]', + tpl1Desc: '[Dining]_2026-10-18_Starbucks_68.00_8921.pdf', + tpl2Title: 'Template 2: [Date]_[Category]_[Amount]_[Seller]', + tpl2Desc: '2026-10-18_[Dining]_68.00_Starbucks.pdf', + tpl3Title: 'Template 3: [Category]_[Amount]_[Seller]_[Tail]', + tpl3Desc: '[Dining]_68.00_Starbucks_8921.pdf', + tpl4Title: 'Template 4: [FullNo]_[Date]_[Seller]_[Amount]', + tpl4Desc: '24312000000048298921_2026-10-18_Starbucks_68.00.pdf', + grpAll: 'All Invoices', + grpTravel: 'Travel (Transit + Lodging)', + grpTransit: 'Transit', + grpLodging: 'Lodging', + grpDining: 'Dining', + grpOffice: 'Office', + grpOther: 'Other', + grpIncomplete: 'Has Unrecognized Fields', + grpDuplicate: 'Duplicate Numbers', + formatAmount: '{amount}', + issueMissingPrefix: 'Unrecognized: {fields}', + listSep: ', ', + tsvColIndex: 'No.', + tsvColInvoiceNo: 'Invoice No.', + tsvColIssueDate: 'Issue Date', + tsvColCategory: 'Category', + tsvColSeller: 'Seller', + tsvColBuyer: 'Buyer', + tsvColTotal: 'Total', + tsvColTax: 'Tax', + tsvColNet: 'Net', + tsvColFileName: 'Archive Filename', + summaryLineNo: 'Invoice No.: {val}', + summaryLineDate: 'Issue Date: {val}', + summaryLineSeller: 'Seller: {val}', + summaryLineBuyer: 'Buyer: {val}', + summaryLineAmount: 'Total: {total} | Tax: {tax}', + errEditInvoiceNo: 'Enter an 8-digit or 20-digit invoice number', + errEditIssueDate: 'Enter a valid date (YYYY-MM-DD)', + errEditSellerEmpty: 'Seller cannot be empty', + errEditSellerLong: 'Seller name cannot exceed 100 chars', + errEditBuyerEmpty: 'Buyer cannot be empty', + errEditBuyerLong: 'Buyer name cannot exceed 100 chars', + errEditTotalInvalid: 'Enter a valid non-negative amount (0 allowed, up to 2 decimals)', + errEditTotalRange: 'Amount out of valid range', + errEditTaxInvalid: 'Enter a valid non-negative tax amount (0 allowed, up to 2 decimals)', + errEditTaxExceeds: 'Tax amount cannot exceed total amount', + errUnsupportedInvoiceFormat: 'Unsupported invoice file format', + errXmlReadFailed: 'Failed to read XML invoice content', + errOfdListFailed: 'Failed to list OFD archive entries', + errOfdNoXml: 'No parseable invoice XML found inside OFD', + errOfdExtractFailed: 'Failed to extract XML from OFD archive', + errPdfInspectFailed: 'Failed to extract text from PDF invoice', + errOcrFailed: 'Failed to run OCR on image invoice', + errMergePdfEmpty: 'Select at least 1 PDF or image invoice to merge', + errMergePdfFailed: 'Failed to merge reimbursement PDF', + errExportEmpty: 'Select at least 1 complete invoice first', + errExportIncomplete: '{count} invoice(s) still have unrecognized fields (e.g. {file}); please edit first', + errExportDuplicate: '{count} duplicate invoice number(s) found (e.g. {file})', + errCsvWriteFailed: 'Failed to export CSV summary', + errTrashFailed: 'Failed to move file to trash', + formNavTitle: 'Edit Invoice: {file}', + formSaveAction: 'Save Invoice', + formOriginalFile: 'Source File', + formOriginalFileDesc: '{file} ({issues})', + phInvoiceNo: '8-digit or 20-digit invoice number', + phSellerName: 'Seller entity name', + phBuyerName: 'Buyer entity name', + phTotalAmount: 'Total amount (0 allowed, e.g. 128.50)', + phTaxAmount: 'Tax amount (0 allowed, e.g. 7.27)', + toastFixRedFields: 'Please fix highlighted fields', + toastSaveNotInList: 'Invoice is no longer in list', + toastSavedInvoice: 'Invoice saved', + toastImportOk: 'Parsed {count} invoice(s)', + toastImportPartial: 'Parsed {ok}, failed {fail}', + toastImportFail: 'Failed to parse invoices', + toastMergePdfOk: 'Reimbursement PDF merged', + toastMergePdfMsg: '{pages} page(s) ({size}): {path}', + toastMergePdfFail: 'Failed to merge PDF', + toastExportCsvOk: 'Reimbursement CSV exported', + toastExportCsvFail: 'Failed to export CSV', + toastCopyTsvOk: 'Copied TSV table to clipboard', + toastCopySummaryOk: 'Copied invoice summary', + toastRevealFail: 'Failed to reveal file', + pickFilesTitle: 'Select E-Invoice Files', + pickFilesFilter: 'E-Invoices (PDF/OFD/XML/Images)', + pickFolderTitle: 'Select Invoice Folder', + errNoFolderPicked: 'No folder selected', + confirmRootTitle: 'Scan drive root {path}?', + confirmRootMsg: 'Scanning a drive root may take a long time.', + confirmRootAction: 'Continue', + dropTitle: 'Drop PDF / OFD / XML / image invoices', + dropSubtitle: 'Unrecognized fields remain null for manual editing; zero fabricated defaults', + searchPlaceholder: 'Search invoice no, seller, buyer, or filename...', + actionPickFiles: 'Import Invoices...', + actionPickFolder: 'Import Folder...', + actionMergePdf: 'Merge Reimbursement PDF ({count})', + actionExportCsv: 'Export Summary CSV ({count})', + actionCopyTsv: 'Copy Table Text (TSV)', + actionEditInvoice: 'Edit / Complete Fields', + actionCopySummary: 'Copy Invoice Summary', + actionRevealFile: 'Reveal in Folder', + actionToggleAll: 'Toggle Select All', + actionRemoveItem: 'Remove from List', + actionTrashItem: 'Move to Trash', + actionClearList: 'Clear List', + wbTitle: 'Invoice Workbench', + wbSubtitle: 'XML / OFD / PDF / OCR · Zero Fake Defaults', + wbFilterLabel: 'Filter View', + wbTemplateLabel: 'Archive Template', + wbCardTitle: 'Reimbursement Summary', + metricTotalCount: 'Total Invoices', + metricSelectedSum: 'Selected Total', + metricIncomplete: 'Incomplete', + metricDuplicate: 'Duplicates', + cardNote: 'Unrecognized fields stay null and display as Unrecognized for manual entry. Zero amounts are valid.', + subListTitle: 'Invoices ({count})', + subListSubtitle: 'Selected {selected} · Sum {sum}', + emptyList: 'Import or drop PDF / OFD / XML / image invoices to begin', + emptyNoMatch: 'No matching invoices', + tagIncomplete: 'Incomplete', + tagDuplicate: 'Duplicate', + tagHeaderAbnormal: 'Personal Header', + tagComplete: 'Ready', + panelTitle: 'Invoice Assistant', + sectionTitle: 'Invoices ({count})', + exportDirPrefix: 'Reimbursement' + } } + +export const t = createTranslator(MESSAGES, { defaultLocale: 'en-US' }) diff --git a/extensions/invoice-assistant/src/index.ts b/extensions/invoice-assistant/src/index.ts index dfc61f91..de8af22b 100644 --- a/extensions/invoice-assistant/src/index.ts +++ b/extensions/invoice-assistant/src/index.ts @@ -1,58 +1,55 @@ +/** + * 发票助手(布局三:左侧筛选/汇总工作台 + 右侧电子发票队列,含人工补录表单) + * + * - 编排四类电子发票输入:XML / OFD(archive) / PDF(document.pdf.inspect) / 图片扫描件(image_ocr) + * - 未识别字段严格保持 null 并在界面显式标示「未识别」,支持人工编辑补录;金额 0 合法 + * - 支持合并报销单 PDF(document.pdf.transform)、导出 UTF-8 BOM CSV 与复制 TSV + */ import { List, Form, ActionPanel, Action, Icon, - Color, Clipboard, useState, - useEffect, useLocale, useRef, useNavigation, showToast, Toast, confirmAlert, - FilterBar, - KeyboardShortcut + FilterBar } from '@ztools/declarative-ui' import { - InvoiceRecordItem, - InvoiceEditValues, - InvoiceFieldKey, - InvoiceParseError, - InvoiceExportMode, - INVOICE_RENAME_TEMPLATES, - EXPENSE_CATEGORY_CYCLE, INVOICE_IMPORT_RULES, - INVOICE_IMPORT_SUPPORTED_TEXT, - createInvoiceImportTransport, - formatCurrency, - buildTargetInvoiceFileName, - buildInvoiceTsvTable, + INVOICE_RENAME_TEMPLATES, + applyInvoiceEdits, buildInvoiceSummaryText, - exportInvoices, - openInvoiceLocation, - trashInvoiceFile, + buildInvoiceTsvTable, + createInvoiceImportTransport, + defaultCheckedInvoiceIds, + describeInvoiceIssues, detectInvoiceAnomalies, - applyInvoiceEdits, - validateInvoiceEdits, - getInvoiceFieldIssues, + exportInvoicesCsv, + formatCurrency, + getInvoiceCategoryGroups, getInvoiceFieldLabel, getInvoiceRenameTemplates, - getInvoiceCategoryGroups, - translateCategory, - describeInvoiceIssues, isInvoiceComplete, isInvoiceSelectable, - defaultCheckedInvoiceIds, matchesInvoiceFilter, - parseInvoiceFiles + mergeInvoicesToPdf, + openInvoiceLocation, + parseInvoiceFiles, + translateCategory, + trashInvoiceFile, + validateInvoiceEdits, + type InvoiceEditValues, + type InvoiceFieldKey, + type InvoiceRecordItem } from './logic.js' import { t } from './i18n.js' -import { isRealElectronHost } from './native-ipc.js' -import { isDeclarativeFileInputSupported } from './host-compat.js' import { FileImportResult, NormalizedFileInput, @@ -62,105 +59,41 @@ import { friendlyFileError, isVolumeRoot, mergeByPath, - normalizeFileInput, - pathKey, pickFiles, - pickFolder, - summarizeImport + pickFolder } from './file-import.js' import { resolveErrorMessage } from './error-i18n.js' export * from './logic.js' -/** 用户在本次会话里手动补全的字段与分类,后续追加导入按文件路径保留 */ -type InvoiceOverride = Partial & { category?: InvoiceRecordItem['category'] } - -interface ImportProgress { - visitedDirs: number - matchedFiles: number -} - -interface ParseProgress { - done: number - total: number -} - -type ImportTask = ( - signal: AbortSignal, - onProgress: (progress: ImportProgress) => void -) => Promise - -const SHORTCUT_PICK_FILES: KeyboardShortcut = { modifiers: ['ctrl'], key: 'o' } -const SHORTCUT_PICK_FOLDER: KeyboardShortcut = { modifiers: ['ctrl', 'shift'], key: 'o' } -const SHORTCUT_REMOVE: KeyboardShortcut = { modifiers: ['ctrl'], key: 'backspace' } -const SHORTCUT_CLEAR: KeyboardShortcut = { modifiers: ['ctrl', 'shift'], key: 'backspace' } -const SHORTCUT_TOGGLE_ALL: KeyboardShortcut = { modifiers: ['ctrl'], key: 'a' } -const SHORTCUT_LOCATE_FILE: KeyboardShortcut = { modifiers: ['ctrl'], key: 'l' } - -function overrideKey(filePath: string): string { - return pathKey(filePath) -} - -function applyOverrides(items: InvoiceRecordItem[], overrides: Map): InvoiceRecordItem[] { - if (overrides.size === 0) return items - return detectInvoiceAnomalies( - items.map((item) => { - const ov = overrides.get(overrideKey(item.path)) - if (!ov) return item - const next: InvoiceRecordItem = { ...item, ...ov } - if (ov.issueDate) next.issueDateNeedsReview = false - return next - }) - ) -} - function amountInputText(value: number | null): string { return value === null || !Number.isFinite(value) ? '' : value.toFixed(2) } export function InvoiceEditForm(props: { invoice: InvoiceRecordItem - /** 返回 false 表示发票已不在列表中(例如已移入回收站),未保存 */ onSave: (values: InvoiceEditValues) => boolean }) { useLocale() const inv = props.invoice const { pop } = useNavigation() - const issues = getInvoiceFieldIssues(inv) - const [invoiceNo, setInvoiceNo] = useState(inv.invoiceNo) - const [issueDate, setIssueDate] = useState(inv.issueDate) - const [sellerName, setSellerName] = useState(inv.sellerName) - const [buyerName, setBuyerName] = useState(inv.buyerName) + const [invoiceNo, setInvoiceNo] = useState(inv.invoiceNo ?? '') + const [issueDate, setIssueDate] = useState(inv.issueDate ?? '') + const [sellerName, setSellerName] = useState(inv.sellerName ?? '') + const [buyerName, setBuyerName] = useState(inv.buyerName ?? '') const [totalAmount, setTotalAmount] = useState(amountInputText(inv.totalAmount)) const [taxAmount, setTaxAmount] = useState(amountInputText(inv.taxAmount)) const [errors, setErrors] = useState>>({}) - const clearError = (field: InvoiceFieldKey) => { - setErrors((prev) => { - if (!prev[field]) return prev - const next = { ...prev } - delete next[field] - return next - }) - } - async function handleSave() { const result = validateInvoiceEdits({ invoiceNo, issueDate, sellerName, buyerName, totalAmount, taxAmount }) if (!result.ok) { setErrors(result.errors) - await showToast({ - style: Toast.Style.Failure, - title: t('toastFixRedFields'), - message: Object.values(result.errors)[0] - }) + await showToast({ style: Toast.Style.Failure, title: t('toastFixRedFields'), message: Object.values(result.errors)[0] }) return } if (!props.onSave(result.values)) { - await showToast({ - style: Toast.Style.Failure, - title: t('toastSaveNotInList'), - message: inv.fileName - }) + await showToast({ style: Toast.Style.Failure, title: t('toastSaveNotInList'), message: inv.fileName }) return } await showToast({ style: Toast.Style.Success, title: t('toastSavedInvoice'), message: inv.fileName }) @@ -168,26 +101,6 @@ export function InvoiceEditForm(props: { } const issueText = describeInvoiceIssues(inv) - const field = ( - id: InvoiceFieldKey, - value: string, - setter: (v: string) => void, - placeholder: string, - info?: string - ) => - Form.TextField({ - id, - title: getInvoiceFieldLabel(id), - placeholder, - value, - error: errors[id], - info, - onChange: (v: string) => { - setter(v) - clearError(id) - } - }) - return Form({ navigationTitle: t('formNavTitle', { file: inv.fileName }), actions: ActionPanel({ @@ -198,202 +111,59 @@ export function InvoiceEditForm(props: { title: t('formOriginalFile'), text: issueText ? t('formOriginalFileDesc', { file: inv.fileName, issues: issueText }) : inv.fileName }), - field('invoiceNo', invoiceNo, setInvoiceNo, t('phInvoiceNo')), - field( - 'issueDate', - issueDate, - setIssueDate, - 'YYYY-MM-DD', - issues.needsReview.includes('issueDate') - ? t('infoIssueDateReview') - : undefined - ), - field('sellerName', sellerName, setSellerName, t('phSellerName')), - field('buyerName', buyerName, setBuyerName, t('phBuyerName')), - field('totalAmount', totalAmount, setTotalAmount, t('phTotalAmount')), - field('taxAmount', taxAmount, setTaxAmount, t('phTaxAmount')) + Form.TextField({ id: 'invoiceNo', title: getInvoiceFieldLabel('invoiceNo'), placeholder: t('phInvoiceNo'), value: invoiceNo, error: errors.invoiceNo, onChange: setInvoiceNo }), + Form.TextField({ id: 'issueDate', title: getInvoiceFieldLabel('issueDate'), placeholder: 'YYYY-MM-DD', value: issueDate, error: errors.issueDate, onChange: setIssueDate }), + Form.TextField({ id: 'sellerName', title: getInvoiceFieldLabel('sellerName'), placeholder: t('phSellerName'), value: sellerName, error: errors.sellerName, onChange: setSellerName }), + Form.TextField({ id: 'buyerName', title: getInvoiceFieldLabel('buyerName'), placeholder: t('phBuyerName'), value: buyerName, error: errors.buyerName, onChange: setBuyerName }), + Form.TextField({ id: 'totalAmount', title: getInvoiceFieldLabel('totalAmount'), placeholder: t('phTotalAmount'), value: totalAmount, error: errors.totalAmount, onChange: setTotalAmount }), + Form.TextField({ id: 'taxAmount', title: getInvoiceFieldLabel('taxAmount'), placeholder: t('phTaxAmount'), value: taxAmount, error: errors.taxAmount, onChange: setTaxAmount }) ] }) } export function InvoiceAssistantCommand() { useLocale() - const launchCtx = (((globalThis as Record).window || globalThis) as { __ztoolsLaunchContext?: { pluginId?: string; featureCode?: string } }).__ztoolsLaunchContext; const initialFeature = launchCtx && (!launchCtx.pluginId || launchCtx.pluginId === 'invoice-assistant') ? String(launchCtx.featureCode || '').trim() : '' - const initialTemplateId = - initialFeature === 'invoice-rename' && INVOICE_RENAME_TEMPLATES[1] - ? INVOICE_RENAME_TEMPLATES[1].id - : INVOICE_RENAME_TEMPLATES[0]!.id - const initialFilterKey = initialFeature === 'invoice-travel' ? 'TRAVEL' : 'ALL' const transport = createInvoiceImportTransport() + const { push } = useNavigation() + const [searchText, setSearchText] = useState('') - const [activeTemplateId, setActiveTemplateId] = useState(initialTemplateId) - const [selectedFilterKey, setSelectedFilterKey] = useState(initialFilterKey) + const [filterKey, setFilterKey] = useState('ALL') + const [templateId, setTemplateId] = useState(INVOICE_RENAME_TEMPLATES[0]!.id) const [invoices, setInvoices] = useState([]) - // 默认只勾选字段完整、非重复且抬头正常的发票,从源头防止把重复或信息不全的发票打入报销单 const [checkedIds, setCheckedIds] = useState([]) - const [parseErrors, setParseErrors] = useState([]) - const [isImporting, setIsImporting] = useState(false) - const [importStage, setImportStage] = useState<'reading' | 'parsing'>('reading') - const [importProgress, setImportProgress] = useState(null) - const [parseProgress, setParseProgress] = useState(null) - const [isExporting, setIsExporting] = useState(false) - const [exportingIds, setExportingIds] = useState([]) - const { push } = useNavigation() - - const exportingRef = useRef(false) - const exportingIdsRef = useRef>(new Set()) - const mountedRef = useRef(true) - const importSeqRef = useRef(0) - const importAbortRef = useRef(null) - const idSeqRef = useRef(0) - const overridesRef = useRef>(new Map()) - // 表单保存与导入回调需读取最新列表而不是旧闭包状态 - const latestRef = useRef({ invoices, checkedIds }) - latestRef.current = { invoices, checkedIds } + const [isBusy, setIsBusy] = useState(false) - async function runImport(task: ImportTask) { - importAbortRef.current?.abort() - const controller = new AbortController() - importAbortRef.current = controller - const seq = ++importSeqRef.current - setIsImporting(true) - setImportStage('reading') - setImportProgress(null) - setParseProgress(null) + const invoicesRef = useRef(invoices) + invoicesRef.current = invoices + async function runImport(task: () => Promise) { + setIsBusy(true) try { - const result = await task(controller.signal, (progress) => { - if (mountedRef.current && seq === importSeqRef.current) setImportProgress(progress) - }) - if (!mountedRef.current || seq !== importSeqRef.current || controller.signal.aborted) return - if (result.canceled) return - if (result.error) { - const summary = summarizeImport(result, { added: 0 }, INVOICE_IMPORT_SUPPORTED_TEXT) - if (summary) { - await showToast({ - style: Toast.Style.Failure, - title: summary.title, - message: summary.message - }) - } - return - } - - const { invoices: currentBeforeParse } = latestRef.current - const { added: newFiles, duplicates } = mergeByPath<{ path: string; sizeBytes: number | null }>( - currentBeforeParse, - result.files, - (f) => f.path - ) - if (newFiles.length === 0) { - const summary = summarizeImport(result, { added: 0, duplicates }, INVOICE_IMPORT_SUPPORTED_TEXT) - if (summary) { - await showToast({ - style: summary.ok ? Toast.Style.Success : Toast.Style.Failure, - title: summary.title, - message: summary.message - }) - } - return - } - - setImportStage('parsing') - setParseProgress({ done: 0, total: newFiles.length }) - const sizeByPath = new Map(newFiles.map((f) => [overrideKey(f.path), f.sizeBytes])) - const parseRes = await parseInvoiceFiles( - newFiles.map((f) => f.path), - '', - undefined, - new Date(), - { - signal: controller.signal, - onProgress: (prog) => { - if (mountedRef.current && seq === importSeqRef.current) setParseProgress(prog) - } - } - ) - if (!mountedRef.current || seq !== importSeqRef.current || controller.signal.aborted || parseRes.canceled) return - - if (!parseRes.ok) { - await showToast({ - style: Toast.Style.Failure, - title: t('errParseInvoicesFailed'), - message: parseRes.error - }) - return - } - - const { invoices: currentInvoices, checkedIds: currentChecked } = latestRef.current - const existingPaths = new Set(currentInvoices.map((i) => overrideKey(i.path))) - const addedItems: InvoiceRecordItem[] = [] - for (const item of parseRes.invoices) { - const key = overrideKey(item.path) - if (existingPaths.has(key)) continue - existingPaths.add(key) - const importedSize = sizeByPath.get(key) - addedItems.push({ - ...item, - id: `inv-${++idSeqRef.current}-${item.path}`, - sizeBytes: item.sizeBytes > 0 ? item.sizeBytes : (importedSize ?? 0) - }) - } - - const addedIdSet = new Set(addedItems.map((i) => i.id)) - // 已有发票在前,新增发票在后,确保新导入重复票不会把已有发票变成重复并影响已有勾选 - const mergedRaw = [...currentInvoices, ...addedItems] - const nextInvoices = applyOverrides(detectInvoiceAnomalies(mergedRaw), overridesRef.current) - const addedEvaluated = nextInvoices.filter((item) => addedIdSet.has(item.id)) - const addedCheckedIds = defaultCheckedInvoiceIds(addedEvaluated) - const nextCheckedIds = Array.from(new Set([...currentChecked, ...addedCheckedIds])) - - latestRef.current = { invoices: nextInvoices, checkedIds: nextCheckedIds } - setInvoices(nextInvoices) - setCheckedIds(nextCheckedIds) - - if (parseRes.parseErrors.length > 0) { - setParseErrors((prev) => [...parseRes.parseErrors, ...prev]) - const notes: string[] = [] - if (duplicates > 0) notes.push(t('noteAlreadyInList', { count: duplicates })) - if (result.ignored > 0) notes.push(t('noteIgnoredUnsupported', { count: result.ignored })) - if (result.truncated) notes.push(t('noteTruncated')) - if (result.failedDirs.length > 0) notes.push(t('noteFailedDirs', { count: result.failedDirs.length })) - const firstErr = `${parseRes.parseErrors[0]!.file}: ${parseRes.parseErrors[0]!.error}` - await showToast({ - style: Toast.Style.Failure, - title: - addedItems.length > 0 - ? t('toastPartialImportTitle', { added: addedItems.length, errors: parseRes.parseErrors.length }) - : t('toastAllImportFailedTitle', { errors: parseRes.parseErrors.length }), - message: [firstErr, ...notes].join(t('semiSep')) - }) - return - } - - const summary = summarizeImport(result, { added: addedItems.length, duplicates }, INVOICE_IMPORT_SUPPORTED_TEXT) - if (summary) { - const msg = summary.ok - ? [summary.message, t('noteCheckedCount', { count: nextCheckedIds.length })].filter(Boolean).join(t('semiSep')) - : summary.message - await showToast({ - style: summary.ok ? Toast.Style.Success : Toast.Style.Failure, - title: summary.title, - message: msg + const importRes = await task() + if (importRes.canceled || importRes.files.length === 0) return + const { added } = mergeByPath<{ path: string }>(invoicesRef.current, importRes.files, (f) => f.path) + if (added.length === 0) return + + const parsed = await parseInvoiceFiles(added.map((f) => f.path)) + const merged = detectInvoiceAnomalies([...invoicesRef.current, ...parsed.invoices]) + invoicesRef.current = merged + setInvoices(merged) + const autoChecked = defaultCheckedInvoiceIds(parsed.invoices) + setCheckedIds((prev) => Array.from(new Set([...prev, ...autoChecked]))) + + if (parsed.parseErrors.length > 0) { + showToast({ + style: parsed.invoices.length > 0 ? Toast.Style.Success : Toast.Style.Failure, + title: t('toastImportPartial', { ok: parsed.invoices.length, fail: parsed.parseErrors.length }), + message: parsed.parseErrors[0]?.error }) + } else { + showToast({ style: Toast.Style.Success, title: t('toastImportOk', { count: parsed.invoices.length }) }) } } catch (err) { - if (!mountedRef.current || seq !== importSeqRef.current) return - await showToast({ - style: Toast.Style.Failure, - title: t('toastImportFailed'), - message: friendlyFileError(err) - }) + showToast({ style: Toast.Style.Failure, title: t('toastImportFail'), message: friendlyFileError(err) }) } finally { - if (mountedRef.current && seq === importSeqRef.current) { - importAbortRef.current = null - setIsImporting(false) - setImportProgress(null) - setParseProgress(null) - } + setIsBusy(false) } } @@ -402,725 +172,280 @@ export function InvoiceAssistantCommand() { } function handlePickFolder() { - void runImport(async (signal, onProgress) => { + void runImport(async () => { const picked = await pickFolder(transport, { title: t('pickFolderTitle') }) - if (picked.canceled || signal.aborted) return { files: [], ignored: 0, truncated: false, failedDirs: [], canceled: true } + if (picked.canceled) return { files: [], ignored: 0, truncated: false, failedDirs: [], canceled: true } if (picked.error || !picked.folderPath) { - return { files: [], ignored: 0, truncated: false, failedDirs: [], canceled: false, error: resolveErrorMessage(picked, t('errNoFolderSelected')) } + return { files: [], ignored: 0, truncated: false, failedDirs: [], canceled: false, error: resolveErrorMessage(picked, t('errNoFolderPicked')) } } if (isVolumeRoot(picked.folderPath)) { - const confirmed = await confirmAlert({ + const ok = await confirmAlert({ title: t('confirmRootTitle', { path: picked.folderPath }), message: t('confirmRootMsg'), primaryAction: { title: t('confirmRootAction'), style: 'default' } }) - if (!confirmed || signal.aborted) return { files: [], ignored: 0, truncated: false, failedDirs: [], canceled: true } + if (!ok) return { files: [], ignored: 0, truncated: false, failedDirs: [], canceled: true } } - return collectFolderFiles(transport, picked.folderPath, INVOICE_IMPORT_RULES, { signal, onProgress }) + return collectFolderFiles(transport, picked.folderPath, INVOICE_IMPORT_RULES) }) } function handleFileInput(input: NormalizedFileInput) { - void runImport((signal, onProgress) => - expandInputPaths(transport, input.paths, INVOICE_IMPORT_RULES, { - knownDirectories: input.directories, - signal, - onProgress - }) - ) - } - - function handleRemove(inv: InvoiceRecordItem) { - if (exportingIdsRef.current.has(inv.id)) { - void showToast({ style: Toast.Style.Failure, title: t('toastWaitProcessingRemove') }) - return - } - overridesRef.current.delete(overrideKey(inv.path)) - const nextInvoices = detectInvoiceAnomalies(latestRef.current.invoices.filter((item) => item.id !== inv.id)) - const nextIds = new Set(nextInvoices.map((i) => i.id)) - const nextChecked = latestRef.current.checkedIds.filter((id) => nextIds.has(id)) - latestRef.current = { invoices: nextInvoices, checkedIds: nextChecked } - setInvoices(nextInvoices) - setCheckedIds(nextChecked) + void runImport(() => expandInputPaths(transport, input.paths, INVOICE_IMPORT_RULES, { knownDirectories: input.directories })) } - function handleClear() { - if (exportingRef.current) { - void showToast({ style: Toast.Style.Failure, title: t('toastWaitProcessingClear') }) - return - } - // 递增批次号并中止进行中的导入,过期结果不再回写 - importSeqRef.current += 1 - importAbortRef.current?.abort() - importAbortRef.current = null - overridesRef.current.clear() - setIsImporting(false) - setImportProgress(null) - setParseProgress(null) - latestRef.current = { invoices: [], checkedIds: [] } - setInvoices([]) - setCheckedIds([]) - setParseErrors([]) - } - - useEffect(() => { - mountedRef.current = true - let dispose: unknown = null - let eventsApi: - | { - on?: (ev: string, cb: (payload: unknown) => void) => unknown - off?: (ev: string, cb: (payload: unknown) => void) => void - } - | undefined - const handleDrop = (envelope: unknown) => { - const input = normalizeFileInput(envelope) - if (input.paths.length > 0) handleFileInput(input) - } - - if (!isDeclarativeFileInputSupported()) { - const w = typeof window !== 'undefined' ? (window as unknown as Record) : null - eventsApi = (w?.ztools as { events?: typeof eventsApi } | undefined)?.events - if (eventsApi && typeof eventsApi.on === 'function') { - dispose = eventsApi.on('plugin_files_dropped', handleDrop) - } - } - - return () => { - mountedRef.current = false - importSeqRef.current += 1 - importAbortRef.current?.abort() - if (typeof dispose === 'function') { - ;(dispose as () => void)() - } else if (eventsApi && typeof eventsApi.off === 'function') { - eventsApi.off('plugin_files_dropped', handleDrop) - } - } - }, []) + const selectedInvoices = invoices.filter((i) => checkedIds.includes(i.id)) + const selectedSum = selectedInvoices.reduce((acc, i) => acc + (i.totalAmount ?? 0), 0) + const incompleteCount = invoices.filter((i) => !isInvoiceComplete(i)).length + const duplicateCount = invoices.filter((i) => i.isDuplicate).length - const fileInputProps = createImportInputProps(handleFileInput, { - dropTitle: t('dropTitle'), - dropSubtitle: t('dropSubtitle') + const q = searchText.trim().toLowerCase() + const visibleInvoices = invoices.filter((i) => { + if (!matchesInvoiceFilter(i, filterKey)) return false + if (!q) return true + return ( + i.fileName.toLowerCase().includes(q) || + (i.invoiceNo ?? '').toLowerCase().includes(q) || + (i.sellerName ?? '').toLowerCase().includes(q) || + (i.buyerName ?? '').toLowerCase().includes(q) + ) }) - const checkedSet = new Set(checkedIds) - const selectedInvoices = invoices.filter((i) => checkedSet.has(i.id)) - const totalAmountSum = selectedInvoices.reduce((acc, i) => acc + (i.totalAmount ?? 0), 0) - const totalTaxSum = selectedInvoices.reduce((acc, i) => acc + (i.taxAmount ?? 0), 0) - const duplicateCount = invoices.filter((i) => i.isDuplicate).length - const abnormalHeaderCount = invoices.filter((i) => i.isHeaderAbnormal).length - const incompleteCount = invoices.filter((i) => !isInvoiceComplete(i)).length + const selectableVisible = visibleInvoices.filter(isInvoiceSelectable) + const allVisibleChecked = selectableVisible.length > 0 && selectableVisible.every((i) => checkedIds.includes(i.id)) - async function handleExport(mode: InvoiceExportMode) { - if (exportingRef.current) return - if (selectedInvoices.length === 0) { - await showToast({ style: Toast.Style.Failure, title: t('errExportEmpty') }) - return - } - const targetIds = selectedInvoices.map((i) => i.id) - exportingRef.current = true - exportingIdsRef.current = new Set(targetIds) - setIsExporting(true) - setExportingIds(targetIds) - let progressToast: { hide: () => Promise } | null = null - try { - progressToast = await showToast({ - style: Toast.Style.Animated, - title: - mode === 'bundle' - ? t('toastExportingBundle', { count: selectedInvoices.length }) - : t('toastExportingCsv', { count: selectedInvoices.length }), - message: t('toastTotalSum', { amount: formatCurrency(totalAmountSum) }) - }) - const res = await exportInvoices(mode, selectedInvoices, activeTemplateId) - await progressToast?.hide() - if (!mountedRef.current) return - if (!res.ok) { - await showToast({ - style: Toast.Style.Failure, - title: mode === 'bundle' ? t('toastExportBundleFailed') : t('toastExportCsvFailed'), - message: friendlyFileError(res.error) - }) - return - } - await showToast({ - style: Toast.Style.Success, - title: - mode === 'bundle' - ? t('toastExportBundleOk', { count: res.copiedCount, amount: formatCurrency(totalAmountSum) }) - : t('toastExportCsvOk', { count: selectedInvoices.length, amount: formatCurrency(totalAmountSum) }), - message: t('toastOutputDirMsg', { dir: res.outputDir }) - }) - } catch (err) { - await progressToast?.hide() - if (!mountedRef.current) return - await showToast({ - style: Toast.Style.Failure, - title: t('toastExportException'), - message: friendlyFileError(err) - }) - } finally { - await progressToast?.hide() - exportingRef.current = false - exportingIdsRef.current = new Set() - if (mountedRef.current) { - setIsExporting(false) - setExportingIds([]) - } - } + function toggleAllVisible() { + const ids = selectableVisible.map((i) => i.id) + setCheckedIds((prev) => (allVisibleChecked ? prev.filter((id) => !ids.includes(id)) : Array.from(new Set([...prev, ...ids])))) } - async function handleCopyExcelTsv() { - if (selectedInvoices.length === 0) { - await showToast({ style: Toast.Style.Failure, title: t('toastPickToCopyTsv') }) - return - } + async function handleMergePdf(targets: InvoiceRecordItem[]) { + setIsBusy(true) try { - await Clipboard.copy(buildInvoiceTsvTable(selectedInvoices, activeTemplateId)) - } catch (err) { - await showToast({ - style: Toast.Style.Failure, - title: t('toastCopyTsvFailed'), - message: err instanceof Error ? err.message : String(err) - }) - return - } - await showToast({ - style: Toast.Style.Success, - title: t('toastCopyTsvOk', { count: selectedInvoices.length }), - message: t('toastCopyTsvHint') - }) - } - - function rememberOverride(filePath: string, patch: InvoiceOverride) { - const key = overrideKey(filePath) - overridesRef.current.set(key, { ...(overridesRef.current.get(key) ?? {}), ...patch }) - } - - function handleCycleCategory(target: InvoiceRecordItem) { - const idx = EXPENSE_CATEGORY_CYCLE.indexOf(target.category) - const nextCat = EXPENSE_CATEGORY_CYCLE[(idx + 1) % EXPENSE_CATEGORY_CYCLE.length]! - rememberOverride(target.path, { category: nextCat }) - setInvoices((prev) => prev.map((inv) => (inv.id === target.id ? { ...inv, category: nextCat } : inv))) - } - - function handleSaveEdits(target: InvoiceRecordItem, values: InvoiceEditValues): boolean { - const { invoices: current, checkedIds: currentChecked } = latestRef.current - const key = overrideKey(target.path) - const existing = current.find((i) => overrideKey(i.path) === key) - if (!existing) return false - rememberOverride(target.path, values) - const next = applyInvoiceEdits(current, existing.id, values) - const selectable = new Set(next.filter(isInvoiceSelectable).map((i) => i.id)) - const edited = next.find((i) => i.id === existing.id) - const kept = currentChecked.filter((id) => selectable.has(id)) - if (edited && selectable.has(edited.id) && !edited.isHeaderAbnormal && !kept.includes(edited.id)) { - kept.push(edited.id) - } - latestRef.current = { invoices: next, checkedIds: kept } - setInvoices(next) - setCheckedIds(kept) - return true - } - - function openEditForm(inv: InvoiceRecordItem) { - push(() => InvoiceEditForm({ invoice: inv, onSave: (values) => handleSaveEdits(inv, values) })) - } - - async function handleCheckChange(inv: InvoiceRecordItem, checked: boolean) { - if (!checked) { - setCheckedIds(checkedIds.filter((id) => id !== inv.id)) - return - } - if (!isInvoiceComplete(inv)) { - await showToast({ - style: Toast.Style.Failure, - title: t('toastIncompleteCannotCheck'), - message: describeInvoiceIssues(inv) + const res = await mergeInvoicesToPdf(targets) + showToast({ + style: res.ok ? Toast.Style.Success : Toast.Style.Failure, + title: res.ok ? t('toastMergePdfOk') : t('toastMergePdfFail'), + message: res.ok + ? t('toastMergePdfMsg', { pages: res.pageCount, size: `${res.outputBytes} B`, path: res.outputPath }) + : res.error }) - return - } - if (inv.isDuplicate) { - await showToast({ - style: Toast.Style.Failure, - title: t('toastDuplicateCannotCheck'), - message: t('toastDuplicateHint') - }) - return + } finally { + setIsBusy(false) } - setCheckedIds(Array.from(new Set([...checkedIds, inv.id]))) } - async function handleCopyParseErrors() { - const text = parseErrors.map((e) => `${e.file}\t${e.error}`).join('\n') + async function handleExportCsv(targets: InvoiceRecordItem[]) { + setIsBusy(true) try { - await Clipboard.copy(text) - } catch (err) { - await showToast({ - style: Toast.Style.Failure, - title: t('toastCopyFailed'), - message: err instanceof Error ? err.message : String(err) + const res = await exportInvoicesCsv(targets, templateId) + showToast({ + style: res.ok ? Toast.Style.Success : Toast.Style.Failure, + title: res.ok ? t('toastExportCsvOk') : t('toastExportCsvFail'), + message: res.ok ? res.csvPath : res.error }) - return - } - await showToast({ style: Toast.Style.Success, title: t('toastCopiedParseErrors', { count: parseErrors.length }) }) - } - - const q = searchText.trim().toLowerCase() - const filteredInvoices = invoices.filter((inv) => { - if (!matchesInvoiceFilter(inv, selectedFilterKey)) return false - if (!q) return true - return ( - inv.sellerName.toLowerCase().includes(q) || - inv.invoiceNo.toLowerCase().includes(q) || - inv.issueDate.toLowerCase().includes(q) || - inv.category.toLowerCase().includes(q) || - translateCategory(inv.category).toLowerCase().includes(q) || - inv.fileName.toLowerCase().includes(q) || - (inv.totalAmount !== null && String(inv.totalAmount).includes(q)) - ) - }) - const selectableFiltered = filteredInvoices.filter(isInvoiceSelectable) - const allSelectableChecked = - selectableFiltered.length > 0 && selectableFiltered.every((i) => checkedSet.has(i.id)) - - function toggleAllSelectable() { - if (selectableFiltered.length === 0) { - void showToast({ style: Toast.Style.Failure, title: t('toastNoSelectable') }) - return + } finally { + setIsBusy(false) } - const ids = new Set(selectableFiltered.map((i) => i.id)) - setCheckedIds((prev) => - allSelectableChecked - ? prev.filter((id) => !ids.has(id)) - : Array.from(new Set([...prev, ...ids])) - ) } - const pickFilesAction = () => - Action({ title: t('actionPickFiles'), icon: Icon.Plus, shortcut: SHORTCUT_PICK_FILES, onAction: handlePickFiles }) - const pickFolderAction = () => - Action({ title: t('actionPickFolder'), icon: Icon.Folder, shortcut: SHORTCUT_PICK_FOLDER, onAction: handlePickFolder }) - const clearListAction = () => - Action({ - title: t('actionClearList'), - icon: Icon.Trash, - style: Action.Style.Destructive, - shortcut: SHORTCUT_CLEAR, - onAction: handleClear - }) - - const maxAmount = Math.max(1, ...filteredInvoices.map((i) => i.totalAmount ?? 0)) - - const exportBundleTitle = t('exportBundleBtnTitle', { count: selectedInvoices.length, amount: formatCurrency(totalAmountSum) }) - - const rightInvoiceItems = filteredInvoices.map((inv) => { - const isChecked = checkedSet.has(inv.id) + const items = visibleInvoices.map((inv) => { const complete = isInvoiceComplete(inv) - const targetRename = complete ? buildTargetInvoiceFileName(inv, activeTemplateId) : null - const issueText = describeInvoiceIssues(inv) - const isProcessing = exportingIds.includes(inv.id) - - const exportAction = Action({ - title: exportBundleTitle, - icon: Icon.Bolt, - onAction: () => handleExport('bundle') - }) - const editAction = Action({ - title: complete ? t('actionEditComplete') : t('actionEditIncomplete'), - icon: Icon.Pencil, - shortcut: { modifiers: ['ctrl'], key: 'i' }, - onAction: () => openEditForm(inv) - }) - const copyTsvAction = Action({ - title: t('actionCopyTsv'), - icon: Icon.CopyClipboard, - shortcut: { modifiers: ['ctrl'], key: 'enter' }, - onAction: handleCopyExcelTsv - }) - const csvAction = Action({ - title: t('actionExportCsv'), - icon: Icon.Download, - shortcut: { modifiers: ['ctrl'], key: 'e' }, - onAction: () => handleExport('csv') - }) - const otherActions = [ - Action({ - title: t('actionCycleCategory', { category: translateCategory(inv.category) }), - icon: Icon.Tag, - shortcut: { modifiers: ['ctrl'], key: 't' }, - onAction: () => handleCycleCategory(inv) - }), - Action({ - title: t('actionCopySummary'), - icon: Icon.Clipboard, - shortcut: { modifiers: ['ctrl', 'shift'], key: 'c' }, - onAction: async () => { - await Clipboard.copy(buildInvoiceSummaryText(inv)) - await showToast({ style: Toast.Style.Success, title: t('toastCopiedSummary') }) - } - }), - Action({ - title: t('actionLocateFile'), - icon: Icon.Folder, - shortcut: SHORTCUT_LOCATE_FILE, - onAction: async () => { - const opened = await openInvoiceLocation(inv.path) - if (!opened) { - await showToast({ style: Toast.Style.Failure, title: t('toastLocateFailed'), message: inv.path }) - } - } - }), - Action({ - title: t('actionTrashFile'), - icon: Icon.Trash, - style: Action.Style.Destructive, - shortcut: { modifiers: [], key: 'delete' }, - onAction: async () => { - if (exportingIdsRef.current.has(inv.id)) { - await showToast({ style: Toast.Style.Failure, title: t('toastWaitProcessingTrash') }) - return - } - const ok = await confirmAlert({ - title: t('confirmTrashTitle'), - message: t('confirmTrashMsg', { - file: inv.fileName, - no: inv.invoiceNo || t('unrecognized'), - amount: formatCurrency(inv.totalAmount) - }), - primaryAction: { title: t('confirmTrashBtn'), style: 'destructive' } - }) - if (!ok) return - const tr = await trashInvoiceFile(inv.path) - if (!mountedRef.current) return - if (tr.ok) { - overridesRef.current.delete(overrideKey(inv.path)) - const nextInvoices = detectInvoiceAnomalies(latestRef.current.invoices.filter((item) => item.id !== inv.id)) - const nextChecked = latestRef.current.checkedIds.filter((id) => id !== inv.id) - latestRef.current = { invoices: nextInvoices, checkedIds: nextChecked } - setInvoices(nextInvoices) - setCheckedIds(nextChecked) - await showToast({ style: Toast.Style.Success, title: t('toastTrashed') }) - } else { - await showToast({ - style: Toast.Style.Failure, - title: t('toastTrashFailed'), - message: resolveErrorMessage(tr, t('toastFileInUse')) - }) - } - } - }), - ActionPanel.Section({ - title: t('sectionList'), - children: [ - ...(isProcessing - ? [] - : [ - Action({ - title: t('actionRemoveFromList'), - icon: Icon.Minus, - shortcut: SHORTCUT_REMOVE, - onAction: () => handleRemove(inv) - }) - ]), - pickFilesAction(), - pickFolderAction(), - Action({ - title: allSelectableChecked ? t('actionDeselectAll') : t('actionSelectAll'), - icon: Icon.CheckCircle, - shortcut: SHORTCUT_TOGGLE_ALL, - onAction: toggleAllSelectable - }), - clearListAction() - ] - }) - ] - - // 信息不全的发票:回车先补全;其余动作顺序不变,次动作(⌘/Ctrl+Enter)始终是复制明细 - const actionList = complete - ? [exportAction, copyTsvAction, csvAction, editAction, ...otherActions] - : [editAction, copyTsvAction, exportAction, csvAction, ...otherActions] - - const flagged = !complete || inv.isDuplicate || inv.isHeaderAbnormal - // 灰阶为主:只有重复发票号(可能重复报销)用红色警示;信息不全、抬头异常用默认灰阶标签,靠文字区分 - const statusTag = !complete - ? { tag: { value: t('tagIncomplete') } } - : inv.isDuplicate - ? { tag: { value: t('tagDuplicate'), color: Color.Red } } - : inv.isHeaderAbnormal - ? { tag: { value: t('tagAbnormalHeader') } } - : { tag: { value: translateCategory(inv.category) } } - - const accessories: Array> = [] - if (inv.totalAmount !== null) { - accessories.push({ - progress: { value: Math.max(8, Math.min(100, Math.round((inv.totalAmount / maxAmount) * 100))) } - }) - } - accessories.push(statusTag, { text: inv.totalAmount !== null ? formatCurrency(inv.totalAmount) : t('amountUnrecognized') }) + const selectable = isInvoiceSelectable(inv) + const isChecked = checkedIds.includes(inv.id) + const sellerLabel = inv.sellerName ?? t('unrecognized') + const dateLabel = inv.issueDate ?? t('unrecognized') + const issues = describeInvoiceIssues(inv) return List.Item({ id: inv.id, - title: targetRename ?? inv.fileName, - subtitle: complete - ? t('itemSubtitleComplete', { no: inv.invoiceNo, buyer: inv.buyerName, tax: formatCurrency(inv.taxAmount) }) - : issueText, - checkable: true, - checked: isChecked, - onCheckChange: (checked) => { - void handleCheckChange(inv, checked) - }, - icon: { - source: flagged ? Icon.ExclamationMark : Icon.Document, - tintColor: Color.SecondaryText - }, - accessories, - actions: ActionPanel({ - title: inv.sellerName || inv.fileName, - children: actionList - }) - }) - }) - - const inClient = isRealElectronHost() - const summaryParts = [ - t('summarySelected', { selected: selectedInvoices.length, total: invoices.length, amount: formatCurrency(totalAmountSum), tax: formatCurrency(totalTaxSum) }), - t('summaryDuplicates', { count: duplicateCount }) - ] - if (incompleteCount > 0) summaryParts.push(t('summaryIncomplete', { count: incompleteCount })) - if (parseErrors.length > 0) summaryParts.push(t('summaryParseErrors', { count: parseErrors.length })) - summaryParts.push(t('summaryClearHint')) - - const summaryText = isImporting - ? importStage === 'parsing' && parseProgress - ? t('summaryParsing', { total: parseProgress.total, done: parseProgress.done }) - : t('summaryReading', { dirs: importProgress?.visitedDirs ?? 0, files: importProgress?.matchedFiles ?? 0 }) - : invoices.length === 0 - ? inClient - ? t('emptyNoInvoices') - : t('emptyClientNeeded') - : summaryParts.join(' · ') - - const auditItems = [ - List.Item({ - id: 'audit-duplicate', - title: t('auditDupTitle'), - subtitle: - duplicateCount > 0 - ? t('auditDupSubFound', { count: duplicateCount }) - : t('auditDupSubNone'), - icon: { - source: duplicateCount > 0 ? Icon.ExclamationMark : Icon.CheckCircle, - tintColor: Color.SecondaryText + title: `${sellerLabel} · ${inv.fileName}`, + subtitle: issues || `${dateLabel} · ${inv.invoiceNo ?? t('unrecognized')} · ${translateCategory(inv.category)}`, + icon: { source: Icon.Document }, + checkable: selectable, + checked: selectable && isChecked, + onCheckChange: () => { + if (!selectable) return + setCheckedIds((prev) => (prev.includes(inv.id) ? prev.filter((id) => id !== inv.id) : [...prev, inv.id])) }, accessories: [ - duplicateCount > 0 - ? { tag: { value: t('auditDupTagFound', { count: duplicateCount }), color: Color.Red } } - : { tag: { value: t('auditDupTagNone') } } + { tag: !complete ? t('tagIncomplete') : inv.isDuplicate ? t('tagDuplicate') : inv.isHeaderAbnormal ? t('tagHeaderAbnormal') : t('tagComplete') }, + { text: formatCurrency(inv.totalAmount) } ], actions: ActionPanel({ - title: t('auditDupPanel'), + title: inv.fileName, children: [ Action({ - title: t('auditDupAction'), - icon: Icon.Filter, - onAction: () => setSelectedFilterKey(selectedFilterKey === 'DUPLICATE' ? 'ALL' : 'DUPLICATE') - }) - ] - }) - }), - List.Item({ - id: 'audit-header', - title: t('auditHeaderTitle'), - subtitle: - abnormalHeaderCount > 0 - ? t('auditHeaderSubFound', { count: abnormalHeaderCount }) - : t('auditHeaderSubNone'), - icon: { - source: abnormalHeaderCount > 0 ? Icon.ExclamationMark : Icon.CheckCircle, - tintColor: Color.SecondaryText - }, - accessories: [ - abnormalHeaderCount > 0 - ? { tag: { value: t('auditHeaderTagFound', { count: abnormalHeaderCount }) } } - : { tag: { value: t('auditHeaderTagNone') } } - ], - actions: ActionPanel({ - title: t('auditHeaderPanel'), - children: [ + title: t('actionEditInvoice'), + icon: Icon.Pencil, + onAction: () => { + push( + InvoiceEditForm({ + invoice: inv, + onSave: (values) => { + if (!invoicesRef.current.some((x) => x.id === inv.id)) return false + const updated = applyInvoiceEdits(invoicesRef.current, inv.id, values) + invoicesRef.current = updated + setInvoices(updated) + return true + } + }) + ) + } + }), Action({ - title: t('auditHeaderAction'), - icon: Icon.Filter, - onAction: () => setSelectedFilterKey(selectedFilterKey === 'ABNORMAL' ? 'ALL' : 'ABNORMAL') - }) - ] - }) - }), - List.Item({ - id: 'audit-incomplete', - title: t('auditIncTitle'), - subtitle: - incompleteCount > 0 - ? t('auditIncSubFound', { count: incompleteCount }) - : t('auditIncSubNone'), - icon: { - source: incompleteCount > 0 ? Icon.ExclamationMark : Icon.CheckCircle, - tintColor: Color.SecondaryText - }, - accessories: [ - incompleteCount > 0 - ? { tag: { value: t('auditIncTagFound', { count: incompleteCount }) } } - : { tag: { value: t('auditIncTagNone') } } - ], - actions: ActionPanel({ - title: t('auditIncPanel'), - children: [ + title: t('actionMergePdf', { count: selectedInvoices.length > 0 ? selectedInvoices.length : 1 }), + icon: Icon.Document, + onAction: () => handleMergePdf(selectedInvoices.length > 0 ? selectedInvoices : [inv]) + }), + Action({ + title: t('actionExportCsv', { count: selectedInvoices.length }), + icon: Icon.Download, + onAction: () => handleExportCsv(selectedInvoices) + }), + Action({ + title: t('actionCopySummary'), + icon: Icon.CopyClipboard, + onAction: async () => { + await Clipboard.copy(buildInvoiceSummaryText(inv)) + showToast({ style: Toast.Style.Success, title: t('toastCopySummaryOk') }) + } + }), + Action({ + title: t('actionRevealFile'), + icon: Icon.Folder, + onAction: async () => { + if (!(await openInvoiceLocation(inv.path))) { + showToast({ style: Toast.Style.Failure, title: t('toastRevealFail') }) + } + } + }), Action({ - title: t('auditIncAction'), - icon: Icon.Filter, - onAction: () => setSelectedFilterKey(selectedFilterKey === 'INCOMPLETE' ? 'ALL' : 'INCOMPLETE') + title: t('actionRemoveItem'), + icon: Icon.Trash, + onAction: () => { + const next = detectInvoiceAnomalies(invoicesRef.current.filter((x) => x.id !== inv.id)) + invoicesRef.current = next + setInvoices(next) + setCheckedIds((prev) => prev.filter((id) => id !== inv.id)) + } + }), + Action({ + title: t('actionTrashItem'), + icon: Icon.Trash, + onAction: async () => { + await trashInvoiceFile(inv.path) + } }) ] }) }) - ] - if (parseErrors.length > 0) { - auditItems.push( - List.Item({ - id: 'audit-parse-errors', - title: t('auditErrTitle'), - subtitle: t('auditErrSub', { count: parseErrors.length }), - icon: { source: Icon.ExclamationMark, tintColor: Color.SecondaryText }, - // 读取失败是真正的错误,标签保留红色 - accessories: [{ tag: { value: t('auditErrTag', { count: parseErrors.length }), color: Color.Red } }], - actions: ActionPanel({ - title: t('auditErrTitle'), - children: [ - Action({ - title: t('auditErrAction'), - icon: Icon.CopyClipboard, - onAction: handleCopyParseErrors - }) - ] - }) - }) - ) - } + }) - const emptyText = !inClient - ? t('emptyClientNeeded') - : invoices.length === 0 - ? t('emptyNoInvoices') - : t('emptyNoMatch') + const fileInputProps = createImportInputProps(handleFileInput, { + dropTitle: t('dropTitle'), + dropSubtitle: t('dropSubtitle') + }) return List({ - ...fileInputProps, searchBarPlaceholder: t('searchPlaceholder'), onSearchTextChange: setSearchText, isShowingDetail: false, - isLoading: isImporting || isExporting, - actions: ActionPanel({ - children: [pickFilesAction(), pickFolderAction()] - }), - searchBarAccessory: List.Dropdown({ - tooltip: t('dropdownTooltip'), - value: activeTemplateId, - onChange: (val) => setActiveTemplateId(val), - children: getInvoiceRenameTemplates().map((tpl) => - List.Dropdown.Item({ - title: tpl.title, - value: tpl.id - }) - ) - }), + isLoading: isBusy, + ...fileInputProps, filterBar: FilterBar({ - summaryText, + summaryText: t('subListSubtitle', { selected: selectedInvoices.length, sum: formatCurrency(selectedSum) }), actions: [ { - id: 'pick-files', - label: t('barPickFiles'), - title: t('barPickFiles'), + id: 'inv-merge-pdf', + label: t('actionMergePdf', { count: selectedInvoices.length }), + title: t('actionMergePdf', { count: selectedInvoices.length }), style: 'primary', - onAction: handlePickFiles + onAction: () => { + void handleMergePdf(selectedInvoices) + } }, { - id: 'pick-folder', - label: t('barPickFolder'), - title: t('barPickFolder'), + id: 'inv-pick-files', + label: t('actionPickFiles'), + title: t('actionPickFiles'), style: 'secondary', - onAction: handlePickFolder + onAction: handlePickFiles } ] }), + workbenchPanel: { + title: t('wbTitle'), + subtitle: t('wbSubtitle'), + fields: [ + { + id: 'inv-filter', + label: t('wbFilterLabel'), + type: 'select', + value: filterKey, + onChange: setFilterKey, + options: getInvoiceCategoryGroups().map((g) => ({ label: g.name, value: g.id })) + }, + { + id: 'inv-template', + label: t('wbTemplateLabel'), + type: 'select', + value: templateId, + onChange: setTemplateId, + options: getInvoiceRenameTemplates().map((tpl) => ({ label: tpl.title, value: tpl.id })) + } + ], + previewCard: { + title: t('wbCardTitle'), + subtitle: t('cardNote'), + metrics: [ + { label: t('metricTotalCount'), value: String(invoices.length) }, + { label: t('metricSelectedSum'), value: formatCurrency(selectedSum) }, + { label: t('metricIncomplete'), value: String(incompleteCount) }, + { label: t('metricDuplicate'), value: String(duplicateCount) } + ] + } + }, subList: { - title: t('subListTitle'), - subtitle: t('subListSubtitle', { count: filteredInvoices.length, amount: formatCurrency(totalAmountSum) }), - checkable: selectableFiltered.length > 0, - checked: - selectableFiltered.length > 0 && selectableFiltered.every((i) => checkedSet.has(i.id)) - ? true - : filteredInvoices.some((i) => checkedSet.has(i.id)) - ? 'indeterminate' - : false, - onCheckChange: (checked) => { - const ids = new Set(selectableFiltered.map((i) => i.id)) - setCheckedIds( - checked - ? Array.from(new Set([...checkedIds, ...ids])) - : checkedIds.filter((id) => !filteredInvoices.some((i) => i.id === id)) - ) - }, - emptyText, - items: rightInvoiceItems + title: t('subListTitle', { count: visibleInvoices.length }), + subtitle: t('subListSubtitle', { selected: selectedInvoices.length, sum: formatCurrency(selectedSum) }), + emptyText: q && invoices.length > 0 ? t('emptyNoMatch') : t('emptyList'), + checkable: selectableVisible.length > 0, + checked: allVisibleChecked ? true : selectedInvoices.length > 0 ? 'indeterminate' : false, + onCheckChange: toggleAllVisible, + items }, - children: [ - List.Section({ - title: t('catSectionTitle'), - children: getInvoiceCategoryGroups().map((grp) => { - const matched = invoices.filter((i) => matchesInvoiceFilter(i, grp.id)) - const sum = matched.reduce((acc, i) => acc + (i.totalAmount ?? 0), 0) - const unknownAmountCount = matched.filter((i) => i.totalAmount === null).length - const isSelected = selectedFilterKey === grp.id - return List.Item({ - id: `inv-cat-${grp.id}`, - title: grp.name, - subtitle: - unknownAmountCount > 0 - ? t('catSubWithUnknown', { amount: formatCurrency(sum), count: unknownAmountCount }) - : formatCurrency(sum), - icon: { - source: isSelected ? Icon.CheckCircle : Icon.Folder, - tintColor: Color.SecondaryText - }, - accessories: [{ text: t('catCountText', { count: matched.length }) }], - actions: ActionPanel({ - title: grp.name, - children: [ - Action({ - title: t('catFilterAction', { name: grp.name }), - icon: Icon.Filter, - onAction: () => setSelectedFilterKey(grp.id) - }), - Action({ - title: exportBundleTitle, - icon: Icon.Bolt, - onAction: () => handleExport('bundle') - }), - ActionPanel.Section({ - title: t('sectionList'), - children: [ - pickFilesAction(), - pickFolderAction(), - ...(invoices.length > 0 ? [clearListAction()] : []) - ] - }) - ] - }) - }) + actions: ActionPanel({ + title: t('panelTitle'), + children: [ + Action({ title: t('actionPickFiles'), icon: Icon.Plus, onAction: handlePickFiles }), + Action({ title: t('actionPickFolder'), icon: Icon.Folder, onAction: handlePickFolder }), + Action({ title: t('actionMergePdf', { count: selectedInvoices.length }), icon: Icon.Document, onAction: () => handleMergePdf(selectedInvoices) }), + Action({ title: t('actionExportCsv', { count: selectedInvoices.length }), icon: Icon.Download, onAction: () => handleExportCsv(selectedInvoices) }), + Action({ + title: t('actionCopyTsv'), + icon: Icon.CopyClipboard, + onAction: async () => { + await Clipboard.copy(buildInvoiceTsvTable(invoices, templateId)) + showToast({ style: Toast.Style.Success, title: t('toastCopyTsvOk') }) + } + }), + Action({ title: t('actionToggleAll'), icon: Icon.CheckCircle, onAction: toggleAllVisible }), + Action({ + title: t('actionClearList'), + icon: Icon.Trash, + onAction: () => { + invoicesRef.current = [] + setInvoices([]) + setCheckedIds([]) + } }) - }), + ] + }), + children: [ List.Section({ - title: t('auditSectionTitle'), - children: auditItems + title: t('sectionTitle', { count: visibleInvoices.length }), + children: items }) ] }) diff --git a/extensions/invoice-assistant/src/logic.ts b/extensions/invoice-assistant/src/logic.ts index ec6d093c..be98a848 100644 --- a/extensions/invoice-assistant/src/logic.ts +++ b/extensions/invoice-assistant/src/logic.ts @@ -1,20 +1,26 @@ /** - * 电子发票识别与报销归集业务逻辑 + * 发票助手业务逻辑层(Wave 3 薄原语组合编排:document.pdf.inspect / document.pdf.transform / archive.list / archive.extract / image_ocr) * - * 核心能力: - * 1. 通过选择文件、选择文件夹或拖入导入 PDF、OFD、XML 及图片格式电子发票,按每批最多 50 个交给宿主识别发票号码、开票日期、销售方、购买方、价税合计与税额 - * 2. 识别不到的字段保持为空并标为「未识别」,补全前不能勾选导出,也不参与按字段生成文件名 - * 3. 发票号查重与个人抬头提示 - * 4. 按模板复制出规范命名的发票副本(不改动原文件),生成 UTF-8 BOM 报销明细 CSV 与可直接粘贴到表格的 TSV 文本 + * 四类发票输入统一编排: + * - XML 电子发票:filesystem_read_file 读取并解析标准 XML 节点 + * - OFD 电子发票:tool_archive_list + tool_archive_extract 解压内部 XML 节点后结构化解析 + * - PDF 电子发票:tool_document_pdf_inspect 精准提取文本并结构化解析 + * - 图片/扫描件发票:调用宿主既有跨端 image_ocr 识别文字并结构化解析 + * - 合并报销单 PDF:调用 tool_document_pdf_transform(merge / images-to-pdf) + * + * 零假默认值铁律:任何未识别字段严格保持 null(绝不编造当天日期、0 金额或“未知销售商户”);金额 0 合法,严禁用 !amount 判空。 */ -import { getLocale } from '@ztools/declarative-ui' +import { getLocale } from '@ztools/declarative-ui' import { + asRecord, callHostTransport, - invokeDllPluginCapability, + formatBytes, + getRealSystemPath, + nextMessageId, showRealItemInFolder, trashRealItem -} from './native-ipc.js' +} from './tool-runtime.js' import { friendlyFileError, pathKey, @@ -37,8 +43,9 @@ import { type InvoiceCategoryType } from './invoice-parser.zh-data.js' -export { formatBytes } from './native-ipc.js' export { + formatBytes, + INVOICE_CATEGORIES, INVOICE_FIELD_LABELS, INVOICE_RENAME_TEMPLATES, INVOICE_CATEGORY_GROUPS, @@ -48,59 +55,8 @@ export { type InvoiceCategoryType } -export function translateCategory(cat: InvoiceCategoryType | string): string { - switch (cat) { - case INVOICE_CATEGORIES.DINING: return t('catDining') - case INVOICE_CATEGORIES.TRANSIT: return t('catTransit') - case INVOICE_CATEGORIES.LODGING: return t('catLodging') - case INVOICE_CATEGORIES.OFFICE: return t('catOffice') - case INVOICE_CATEGORIES.OTHER: return t('catOther') - default: return cat - } -} - -export function getInvoiceFieldLabel(key: InvoiceFieldKey): string { - switch (key) { - case 'invoiceNo': return t('fieldInvoiceNo') - case 'issueDate': return t('fieldIssueDate') - case 'sellerName': return t('fieldSellerName') - case 'buyerName': return t('fieldBuyerName') - case 'totalAmount': return t('fieldTotalAmount') - case 'taxAmount': return t('fieldTaxAmount') - } -} - -export function getUnrecognizedText(): string { - return t('unrecognized') -} - -export function getForbiddenReason(): string { - return t('forbiddenReason') -} - -export function getInvoiceRenameTemplates(): InvoiceRenameTemplate[] { - return [ - { id: 'tpl-standard', title: t('tpl1Title'), patternDesc: t('tpl1Desc') }, - { id: 'tpl-date-first', title: t('tpl2Title'), patternDesc: t('tpl2Desc') }, - { id: 'tpl-amount-first', title: t('tpl3Title'), patternDesc: t('tpl3Desc') }, - { id: 'tpl-tax-audit', title: t('tpl4Title'), patternDesc: t('tpl4Desc') } - ] -} - -export function getInvoiceCategoryGroups(): Array<{ id: string; name: string }> { - return [ - { id: 'ALL', name: t('grpAll') }, - { id: 'TRAVEL', name: t('grpTravel') }, - { id: INVOICE_CATEGORIES.TRANSIT, name: t('grpTransit') }, - { id: INVOICE_CATEGORIES.LODGING, name: t('grpLodging') }, - { id: INVOICE_CATEGORIES.DINING, name: t('grpDining') }, - { id: INVOICE_CATEGORIES.OFFICE, name: t('grpOffice') }, - { id: INVOICE_CATEGORIES.OTHER, name: t('grpOther') } - ] -} - -/** 报销明细里每张发票都必须有的字段 */ export type InvoiceFieldKey = 'invoiceNo' | 'issueDate' | 'sellerName' | 'buyerName' | 'totalAmount' | 'taxAmount' +export type InvoiceInputKind = 'xml' | 'ofd' | 'pdf' | 'image' export const INVOICE_FIELD_ORDER: InvoiceFieldKey[] = [ 'invoiceNo', @@ -116,24 +72,20 @@ export interface InvoiceRecordItem { path: string fileName: string extension: string + sourceKind: InvoiceInputKind sizeBytes: number - /** 空字符串表示未识别 */ - invoiceNo: string - /** YYYY-MM-DD;空字符串表示未识别 */ - issueDate: string - /** - * 开票日期与今天相同:宿主识别不到日期时会填入当天日期,插件无法区分, - * 因此要求用户核对确认后才能导出(手动保存过发票信息后置为 false) - */ - issueDateNeedsReview?: boolean - /** 空字符串表示未识别 */ - sellerName: string - /** 空字符串表示未识别 */ - buyerName: string - buyerTaxId: string /** null 表示未识别 */ - totalAmount: number | null + invoiceNo: string | null + /** YYYY-MM-DD;null 表示未识别 */ + issueDate: string | null + /** null 表示未识别 */ + sellerName: string | null /** null 表示未识别 */ + buyerName: string | null + buyerTaxId: string | null + /** null 表示未识别;0 合法 */ + totalAmount: number | null + /** null 表示未识别;0 合法 */ taxAmount: number | null /** 价税合计减税额;任一未识别时为 null */ netAmount: number | null @@ -148,83 +100,173 @@ export interface InvoiceRenameTemplate { patternDesc: string } -export interface NativeInvocationResult { +export interface InvoiceParseError { + file: string + error: string +} + +export interface InvoiceEditInput { + invoiceNo: string + issueDate: string + sellerName: string + buyerName: string + totalAmount: string + taxAmount: string +} + +export interface InvoiceEditValues { + invoiceNo: string + issueDate: string + sellerName: string + buyerName: string + totalAmount: number + taxAmount: number + netAmount: number +} + +export type InvoiceEditValidation = + | { ok: true; values: InvoiceEditValues } + | { ok: false; errors: Partial> } + +export interface MergeReimbursementPdfResult { ok: boolean - pluginName: string - method: string - data?: unknown + taskId: string + outputPath: string + outputBytes: number + pageCount: number error?: string - fromFallback?: boolean } -export interface InvoiceParseError { - file: string - error: string +export interface ExportCsvResult { + ok: boolean + csvPath: string + error?: string } -export const DLL_PLUGIN_NAME = 'InvoiceAssistantPlugin' export const FORBIDDEN_TARGET_PATTERN = new RegExp('\\\\Windows\\\\System32|\\.\\.\\\\|\\.\\./', 'i') - -/** 导出目录的上级目录名(位于第一张发票所在目录下),扫描时跳过其中的副本 */ export const EXPORT_ROOT_DIR_NAME = 'ZTools_Reimbursement_Export' +export const INVOICE_IMPORT_EXTENSIONS = ['.pdf', '.ofd', '.xml', '.jpg', '.jpeg', '.png'] as const +export const INVOICE_IMPORT_SUPPORTED_TEXT = 'PDF / OFD / XML / JPG / PNG' -export function normalizeInvoiceCategory(raw: unknown): InvoiceCategoryType { - const text = String(raw ?? '').trim() - if ((EXPENSE_CATEGORY_CYCLE as string[]).includes(text)) return text as InvoiceCategoryType - return HOST_CATEGORY_ALIASES[text] ?? INVOICE_CATEGORIES.OTHER +export const INVOICE_IMPORT_RULES: FileImportRules = { + extensions: INVOICE_IMPORT_EXTENSIONS, + forbiddenPath: FORBIDDEN_TARGET_PATTERN, + excludeDirNames: [EXPORT_ROOT_DIR_NAME], + excludeFile: (name, filePath) => EXPORTED_FILE_NAMES.test(name) || isInsideExportDirectory(filePath) } -/** 发票号码:传统发票 8 位、数电发票 20 位数字;全 0 是宿主读到 PDF 内部偏移量等无关数字 */ -export function normalizeInvoiceNo(raw: unknown): string { - const text = String(raw ?? '').replace(/\s+/g, '') - if (!/^(?:\d{8}|\d{20})$/.test(text)) return '' - if (/^0+$/.test(text)) return '' - return text +export function isInsideExportDirectory(filePath: string): boolean { + return filePath + .split(/[\\/]/) + .some((segment) => segment.toLowerCase() === EXPORT_ROOT_DIR_NAME.toLowerCase()) +} + +export function createInvoiceImportTransport(hostOverride?: unknown): FileImportTransport { + return (method, params) => callHostTransport(method, params, hostOverride) +} + +export function translateCategory(cat: InvoiceCategoryType | string): string { + switch (cat) { + case INVOICE_CATEGORIES.DINING: return t('catDining') + case INVOICE_CATEGORIES.TRANSIT: return t('catTransit') + case INVOICE_CATEGORIES.LODGING: return t('catLodging') + case INVOICE_CATEGORIES.OFFICE: return t('catOffice') + case INVOICE_CATEGORIES.OTHER: return t('catOther') + default: return cat + } +} + +export function getInvoiceFieldLabel(key: InvoiceFieldKey): string { + switch (key) { + case 'invoiceNo': return t('fieldInvoiceNo') + case 'issueDate': return t('fieldIssueDate') + case 'sellerName': return t('fieldSellerName') + case 'buyerName': return t('fieldBuyerName') + case 'totalAmount': return t('fieldTotalAmount') + case 'taxAmount': return t('fieldTaxAmount') + } +} + +export function getInvoiceRenameTemplates(): InvoiceRenameTemplate[] { + return [ + { id: 'tpl-standard', title: t('tpl1Title'), patternDesc: t('tpl1Desc') }, + { id: 'tpl-date-first', title: t('tpl2Title'), patternDesc: t('tpl2Desc') }, + { id: 'tpl-amount-first', title: t('tpl3Title'), patternDesc: t('tpl3Desc') }, + { id: 'tpl-tax-audit', title: t('tpl4Title'), patternDesc: t('tpl4Desc') } + ] +} + +export function getInvoiceCategoryGroups(): Array<{ id: string; name: string }> { + return [ + { id: 'ALL', name: t('grpAll') }, + { id: 'INCOMPLETE', name: t('grpIncomplete') }, + { id: 'DUPLICATE', name: t('grpDuplicate') }, + { id: 'TRAVEL', name: t('grpTravel') }, + { id: INVOICE_CATEGORIES.TRANSIT, name: t('grpTransit') }, + { id: INVOICE_CATEGORIES.LODGING, name: t('grpLodging') }, + { id: INVOICE_CATEGORIES.DINING, name: t('grpDining') }, + { id: INVOICE_CATEGORIES.OFFICE, name: t('grpOffice') }, + { id: INVOICE_CATEGORIES.OTHER, name: t('grpOther') } + ] } function pad2(n: number): string { return String(n).padStart(2, '0') } -export function formatLocalDateKey(now: Date): string { - return `${now.getFullYear()}-${pad2(now.getMonth() + 1)}-${pad2(now.getDate())}` +function extOfFileName(fileName: string): string { + const dot = fileName.lastIndexOf('.') + return dot > 0 ? fileName.slice(dot).toLowerCase() : '' } -/** 开票日期规范为 YYYY-MM-DD;不是真实日期、早于 2000 年或晚于今天时返回空字符串 */ -export function normalizeIssueDate(raw: unknown, now: Date = new Date()): string { - const text = String(raw ?? '').trim() - const m = text.match(ZH_ISSUE_DATE_REGEX) - if (!m) return '' +export function detectInvoiceInputKind(filePath: string): InvoiceInputKind | null { + const ext = extOfFileName(filePath.split(/[\\/]/).pop() || filePath) + if (ext === '.xml') return 'xml' + if (ext === '.ofd') return 'ofd' + if (ext === '.pdf') return 'pdf' + if (ext === '.jpg' || ext === '.jpeg' || ext === '.png') return 'image' + return null +} + +/** 发票号码规范化(8 位传统票或 20 位全电发票号);未识别返回 null */ +export function normalizeInvoiceNo(raw: unknown): string | null { + if (raw === null || raw === undefined) return null + const text = String(raw).replace(/\s+/g, '') + if (!/^(?:\d{8}|\d{20})$/.test(text) || /^0+$/.test(text)) return null + return text +} + +/** 开票日期规范为 YYYY-MM-DD;未识别或非法返回 null,绝不编造当天日期 */ +export function normalizeIssueDate(raw: unknown): string | null { + if (raw === null || raw === undefined) return null + const text = String(raw).trim() + if (!text) return null + const isoPrefix = text.match(/^(\d{4})[-/.年](\d{1,2})[-/.月](\d{1,2})/) + const m = text.match(ZH_ISSUE_DATE_REGEX) || isoPrefix + if (!m) return null const year = Number(m[1]) const month = Number(m[2]) const day = Number(m[3]) - if (year < 2000 || month < 1 || month > 12 || day < 1 || day > 31) return '' + if (year < 2000 || year > 2100 || month < 1 || month > 12 || day < 1 || day > 31) return null const probe = new Date(year, month - 1, day) - if (probe.getFullYear() !== year || probe.getMonth() !== month - 1 || probe.getDate() !== day) return '' - const key = `${year}-${pad2(month)}-${pad2(day)}` - if (key > formatLocalDateKey(now)) return '' - return key + if (probe.getFullYear() !== year || probe.getMonth() !== month - 1 || probe.getDate() !== day) return null + return `${year}-${pad2(month)}-${pad2(day)}` } -/** 日期与今天(本地或 UTC)相同:可能是宿主识别不到日期时填入的当天日期 */ -export function isPossibleFallbackDate(date: string, now: Date = new Date()): boolean { - if (!date) return false - return date === formatLocalDateKey(now) || date === now.toISOString().slice(0, 10) -} - -/** 金额:非负有限数,保留两位小数;allowZero 为 false 时 0 也视为未识别 */ -export function normalizeAmount(raw: unknown, allowZero: boolean): number | null { +/** 金额规范化:允许 0(严禁 !num 判空),仅 null / 空串 / 非有限 / 负数 返回 null */ +export function normalizeAmount(raw: unknown): number | null { if (raw === null || raw === undefined) return null if (typeof raw === 'string' && raw.trim() === '') return null - const num = typeof raw === 'number' ? raw : Number(String(raw).replace(/[¥¥,,\s]/g, '')) + const num = typeof raw === 'number' ? raw : Number(String(raw).replace(/[¥¥,,\s元]/g, '')) if (!Number.isFinite(num) || num < 0) return null - if (!allowZero && num === 0) return null return Math.round(num * 100) / 100 } -function normalizePartyName(raw: unknown): string { - const text = String(raw ?? '').trim() - if (!text || PLACEHOLDER_PARTY_NAMES.has(text)) return '' +/** 购销方名称规范化:过滤旧占位符(如“未知销售商户”),未识别返回 null */ +export function normalizePartyName(raw: unknown): string | null { + if (raw === null || raw === undefined) return null + const text = String(raw).trim() + if (!text || PLACEHOLDER_PARTY_NAMES.has(text)) return null return text } @@ -233,231 +275,342 @@ function computeNetAmount(total: number | null, tax: number | null): number | nu return Math.round((total - tax) * 100) / 100 } -function extOfFileName(fileName: string): string { - const dot = fileName.lastIndexOf('.') - return dot > 0 ? fileName.slice(dot).toLowerCase() : '' +function inferCategoryFromText(seller: string | null, rawText: string): InvoiceCategoryType { + const hay = `${seller ?? ''} ${rawText}` + if (/餐饮|咖啡|饭店|酒家|美食|食品|星巴克|麦当劳|肯德基/.test(hay)) return INVOICE_CATEGORIES.DINING + if (/滴滴|出行|高德|铁路|客运|航空|地铁|出租车|交通|网约车/.test(hay)) return INVOICE_CATEGORIES.TRANSIT + if (/酒店|宾馆|住宿|旅馆|民宿/.test(hay)) return INVOICE_CATEGORIES.LODGING + if (/办公|云服务|科技|软件|信息|文具|电脑|电子/.test(hay)) return INVOICE_CATEGORIES.OFFICE + return INVOICE_CATEGORIES.OTHER } -/** - * 把宿主返回的一条识别结果整理成插件数据;识别不到的字段一律留空,不填默认值。 - * 缺少文件路径的结果无法导出或定位,返回 null。 - */ -export function normalizeParsedInvoice( - raw: Record, - idx: number, - now: Date = new Date() -): InvoiceRecordItem | null { - const filePath = String(raw.path ?? '').trim() - if (!filePath) return null - const fileName = String(raw.fileName ?? '').trim() || filePath.split(/[\\/]/).pop() || filePath - const issueDate = normalizeIssueDate(raw.issueDate, now) - const totalAmount = normalizeAmount(raw.totalAmount, false) - // 宿主识别不到税额时填 0;价税合计都没识别到时,这个 0 不可信 - let taxAmount = normalizeAmount(raw.taxAmount, true) - if (taxAmount !== null && totalAmount !== null && taxAmount > totalAmount) taxAmount = null - if (totalAmount === null && taxAmount === 0) taxAmount = null - const sizeBytes = Number(raw.sizeBytes) +function extractXmlTag(xml: string, tagNames: readonly string[]): string | null { + for (const tag of tagNames) { + const regex = new RegExp(`<(?:[A-Za-z0-9_-]+:)?${tag}(?:\\s[^>]*)?>([\\s\\S]*?)<\\/(?:[A-Za-z0-9_-]+:)?${tag}\\s*>`, 'i') + const match = xml.match(regex) + if (match && match[1] !== undefined) { + const cleaned = match[1].replace(//g, '$1').trim() + if (cleaned) return cleaned + } + } + return null +} + +/** 解析电子发票 XML 节点(数电票 / 增值税电子发票 / OFD 内部发票 XML),未识别字段严格返回 null */ +export function parseInvoiceFieldsFromXml(xmlText: string): { + invoiceNo: string | null + issueDate: string | null + sellerName: string | null + buyerName: string | null + buyerTaxId: string | null + totalAmount: number | null + taxAmount: number | null + category: InvoiceCategoryType +} { + const text = String(xmlText || '') + const invoiceNo = normalizeInvoiceNo(extractXmlTag(text, ['InvoiceNumber', 'Fphm', 'InvoiceNo', 'fphm'])) + const issueDate = normalizeIssueDate(extractXmlTag(text, ['IssueTime', 'IssueDate', 'Kprq', 'kprq'])) + const sellerName = normalizePartyName(extractXmlTag(text, ['SellerName', 'Xsfmc', 'xsfmc', 'SellerTitle'])) + const buyerName = normalizePartyName(extractXmlTag(text, ['BuyerName', 'Gmfmc', 'gmfmc', 'BuyerTitle'])) + const buyerTaxId = extractXmlTag(text, ['BuyerIdNum', 'BuyerTaxId', 'Gmfnsrsbh', 'gmfnsrsbh']) + const totalAmount = normalizeAmount(extractXmlTag(text, ['TotalTax-includedAmount', 'TaxInclusiveTotalAmount', 'Jshj', 'jshj', 'TotalAmount'])) + const taxAmount = normalizeAmount(extractXmlTag(text, ['TotalTax', 'TaxTotalAmount', 'Se', 'se', 'TaxAmount'])) return { - id: String(raw.id ?? `inv-${idx}-${filePath}`), - path: filePath, - fileName, - extension: extOfFileName(fileName), - sizeBytes: Number.isFinite(sizeBytes) && sizeBytes >= 0 ? sizeBytes : 0, - invoiceNo: normalizeInvoiceNo(raw.invoiceNo), + invoiceNo, issueDate, - issueDateNeedsReview: isPossibleFallbackDate(issueDate, now), - sellerName: normalizePartyName(raw.sellerName), - buyerName: normalizePartyName(raw.buyerName), - buyerTaxId: String(raw.buyerTaxId ?? '').trim(), + sellerName, + buyerName, + buyerTaxId, totalAmount, - taxAmount, - netAmount: computeNetAmount(totalAmount, taxAmount), - category: normalizeInvoiceCategory(raw.category), - isDuplicate: false, - isHeaderAbnormal: false + taxAmount: totalAmount !== null && taxAmount !== null && taxAmount > totalAmount ? null : taxAmount, + category: inferCategoryFromText(sellerName, text) } } -export interface InvoiceFieldIssues { - /** 未识别的字段 */ - missing: InvoiceFieldKey[] - /** 有值但需要用户核对的字段 */ - needsReview: InvoiceFieldKey[] -} - -export function getInvoiceFieldIssues(item: InvoiceRecordItem): InvoiceFieldIssues { - const missing: InvoiceFieldKey[] = [] - if (!item.invoiceNo) missing.push('invoiceNo') - if (!item.issueDate) missing.push('issueDate') - if (!item.sellerName) missing.push('sellerName') - if (!item.buyerName) missing.push('buyerName') - if (item.totalAmount === null || !Number.isFinite(item.totalAmount)) missing.push('totalAmount') - if (item.taxAmount === null || !Number.isFinite(item.taxAmount)) missing.push('taxAmount') - const needsReview: InvoiceFieldKey[] = item.issueDate && item.issueDateNeedsReview ? ['issueDate'] : [] - return { missing, needsReview } -} - -export function isInvoiceComplete(item: InvoiceRecordItem): boolean { - const issues = getInvoiceFieldIssues(item) - return issues.missing.length === 0 && issues.needsReview.length === 0 -} +/** 解析 PDF / OCR 提取的非结构化发票纯文本,未识别字段严格返回 null,绝不编造默认值 */ +export function parseInvoiceFieldsFromPlainText(rawText: string): { + invoiceNo: string | null + issueDate: string | null + sellerName: string | null + buyerName: string | null + buyerTaxId: string | null + totalAmount: number | null + taxAmount: number | null + category: InvoiceCategoryType +} { + const text = String(rawText || '') + const noMatch = + text.match(/发票号码[::\s]*(\d{20}|\d{8})/) || + text.match(/Invoice\s*(?:No\.?|Number)[::\s]*(\d{20}|\d{8})/i) + const dateMatch = + text.match(/开票日期[::\s]*(\d{4}\s*[-/.年]\s*\d{1,2}\s*[-/.月]\s*\d{1,2}\s*日?)/) || + text.match(/Issue\s*Date[::\s]*(\d{4}[-/.]\d{1,2}[-/.]\d{1,2})/i) + const sellerMatch = + text.match(/(?:销售方|销方)(?:名称)?[::\s]*([^\r\n,,;;]+)/) || + text.match(/Seller[::\s]*([^\r\n]+)/i) + const buyerMatch = + text.match(/(?:购买方|购方)(?:名称)?[::\s]*([^\r\n,,;;]+)/) || + text.match(/Buyer[::\s]*([^\r\n]+)/i) + const taxIdMatch = text.match(/(?:纳税人识别号|统一社会信用代码)[::\s]*([0-9A-Z]{15,20})/i) + const totalMatch = + text.match(/(?:价税合计|小写|合计金额)[^\d¥¥]{0,16}[¥¥]?\s*(\d+(?:,\d{3})*(?:\.\d{1,2})?)/) || + text.match(/Total\s*Amount[::\s]*[¥¥$]?\s*(\d+(?:,\d{3})*(?:\.\d{1,2})?)/i) + const taxMatch = + text.match(/(?:合\s*计\s*税\s*额|税\s*额)[::\s]*[¥¥]?\s*(\d+(?:,\d{3})*(?:\.\d{1,2})?)/) || + text.match(/Tax\s*Amount[::\s]*[¥¥$]?\s*(\d+(?:,\d{3})*(?:\.\d{1,2})?)/i) + + const invoiceNo = normalizeInvoiceNo(noMatch?.[1]) + const issueDate = normalizeIssueDate(dateMatch?.[1]) + const sellerName = normalizePartyName(sellerMatch?.[1]) + const buyerName = normalizePartyName(buyerMatch?.[1]) + const totalAmount = normalizeAmount(totalMatch?.[1]) + let taxAmount = normalizeAmount(taxMatch?.[1]) + if (totalAmount !== null && taxAmount !== null && taxAmount > totalAmount) { + taxAmount = null + } -/** 例如「未识别:价税合计、税额;开票日期待核对」;字段完整时返回空字符串 */ -export function describeInvoiceIssues(item: InvoiceRecordItem): string { - const { missing, needsReview } = getInvoiceFieldIssues(item) - const parts: string[] = [] - if (missing.length > 0) parts.push(t('issueMissingPrefix', { fields: missing.map((f) => getInvoiceFieldLabel(f)).join(t('listSep')) })) - if (needsReview.length > 0) parts.push(t('issueNeedsReviewSuffix', { fields: needsReview.map((f) => getInvoiceFieldLabel(f)).join(t('listSep')) })) - return parts.join(t('semiSep')) + return { + invoiceNo, + issueDate, + sellerName, + buyerName, + buyerTaxId: taxIdMatch?.[1] ? taxIdMatch[1].trim() : null, + totalAmount, + taxAmount, + category: inferCategoryFromText(sellerName, text) + } } -/** 可以勾选导出:字段完整且不是重复发票 */ -export function isInvoiceSelectable(item: InvoiceRecordItem): boolean { - return isInvoiceComplete(item) && !item.isDuplicate +function isUnsafeArchiveEntry(entryPath: string): boolean { + const norm = String(entryPath || '').replace(/\\/g, '/') + if (!norm || norm.includes('\0') || norm.startsWith('/') || /^[A-Za-z]:/.test(norm)) return true + return norm.split('/').some((seg) => seg === '..') } -/** 默认勾选:可导出且抬头正常 */ -export function defaultCheckedInvoiceIds(items: InvoiceRecordItem[]): string[] { - return items.filter((i) => isInvoiceSelectable(i) && !i.isHeaderAbnormal).map((i) => i.id) +async function readHostTextFile(filePath: string, hostOverride?: unknown): Promise<{ ok: boolean; content?: string; error?: string }> { + const res = await callHostTransport('filesystem_read_file', { path: filePath, encoding: 'utf8' }, hostOverride) + if (!res.ok) return { ok: false, error: resolveErrorMessage(res, t('errXmlReadFailed')) } + if (typeof res.data === 'string') return { ok: true, content: res.data } + const rec = asRecord(res.data) + if (typeof rec?.content === 'string') return { ok: true, content: rec.content } + if (typeof rec?.text === 'string') return { ok: true, content: rec.text } + return { ok: false, error: t('errXmlReadFailed') } } -export function formatCurrency(amount: number | null | undefined): string { - if (amount === null || amount === undefined) return t('unrecognized') - const num = Number(amount) - if (!Number.isFinite(num)) return t('unrecognized') - return `¥${num.toLocaleString(getLocale(), { minimumFractionDigits: 2, maximumFractionDigits: 2 })}` -} +/** 编排单张发票解析:按扩展名路由至 XML / OFD(archive) / PDF(document.pdf.inspect) / 图片(image_ocr) */ +export async function parseSingleInvoiceFile( + filePath: string, + hostOverride?: unknown, + sizeBytes = 0 +): Promise<{ ok: true; item: InvoiceRecordItem } | { ok: false; error: string }> { + const cleanPath = String(filePath || '').trim() + const fileName = cleanPath.split(/[\\/]/).pop() || cleanPath + const kind = detectInvoiceInputKind(cleanPath) + if (!kind || FORBIDDEN_TARGET_PATTERN.test(cleanPath)) { + return { ok: false, error: t('errUnsupportedInvoiceFormat') } + } -/** - * 按模板生成归档文件名;发票有未识别或待核对的字段时返回 null(不能用占位值拼文件名) - */ -export function buildTargetInvoiceFileName(item: InvoiceRecordItem, templateId: string): string | null { - if (!isInvoiceComplete(item)) return null - const ext = item.extension || extOfFileName(item.fileName) - const safeSeller = item.sellerName.replace(/[\\/:*?"<>|\s]+/g, '_').slice(0, 24) - const tailNo = item.invoiceNo.slice(-4) - const amt = (item.totalAmount as number).toFixed(2) - const date = item.issueDate - const cat = translateCategory(item.category || INVOICE_CATEGORIES.OTHER) - const formattedAmt = t('formatAmount', { amount: amt }) + let fields: ReturnType + let resolvedSize = sizeBytes - if (templateId === 'tpl-date-first') { - return `${date}_[${cat}]_${formattedAmt}_${safeSeller}${ext}` - } - if (templateId === 'tpl-amount-first') { - return `[${cat}]_${formattedAmt}_${safeSeller}_${tailNo}${ext}` - } - if (templateId === 'tpl-tax-audit') { - return `${item.invoiceNo}_${date}_${safeSeller}_${formattedAmt}${ext}` + if (kind === 'xml') { + const readRes = await readHostTextFile(cleanPath, hostOverride) + if (!readRes.ok || readRes.content === undefined) { + return { ok: false, error: resolveErrorMessage(readRes, t('errXmlReadFailed')) } + } + fields = parseInvoiceFieldsFromXml(readRes.content) + } else if (kind === 'ofd') { + const listRes = await callHostTransport('tool_archive_list', { archive: { path: cleanPath } }, hostOverride) + if (!listRes.ok) { + return { ok: false, error: resolveErrorMessage(listRes, t('errOfdListFailed')) } + } + const listRec = asRecord(listRes.data) + const rawEntries = Array.isArray(listRec?.entries) + ? listRec.entries.map(asRecord).filter((e): e is Record => Boolean(e)) + : [] + const xmlCandidates = rawEntries + .filter((e) => !Boolean(e.isDirectory)) + .map((e) => String(e.path ?? '')) + .filter((p) => /\.xml$/i.test(p) && !isUnsafeArchiveEntry(p)) + .sort((a, b) => { + const score = (p: string) => (/original_invoice|invoice|attachs/i.test(p) ? 0 : /content\.xml$/i.test(p) ? 1 : 2) + return score(a) - score(b) + }) + if (xmlCandidates.length === 0) { + return { ok: false, error: t('errOfdNoXml') } + } + const targetXmlEntry = xmlCandidates[0]! + const tempBase = (await getRealSystemPath('temp', hostOverride)) || 'C:\\Temp' + const sep = tempBase.includes('\\') ? '\\' : '/' + const extractDir = `${tempBase.replace(/[\\/]+$/, '')}${sep}${nextMessageId('ofd_ext')}` + const extRes = await callHostTransport( + 'tool_archive_extract', + { + taskId: nextMessageId('ofd_task'), + archive: { path: cleanPath }, + outputDir: { path: extractDir }, + entries: [targetXmlEntry], + overwrite: true + }, + hostOverride + ) + if (!extRes.ok) { + return { ok: false, error: resolveErrorMessage(extRes, t('errOfdExtractFailed')) } + } + const extRec = asRecord(extRes.data) + const actualOutDir = typeof extRec?.outputDir === 'string' && extRec.outputDir ? extRec.outputDir : extractDir + const relNormalized = targetXmlEntry.replace(/[\\/]+/g, sep) + const extractedXmlPath = `${actualOutDir.replace(/[\\/]+$/, '')}${sep}${relNormalized}` + const xmlRead = await readHostTextFile(extractedXmlPath, hostOverride) + if (!xmlRead.ok || xmlRead.content === undefined) { + return { ok: false, error: resolveErrorMessage(xmlRead, t('errXmlReadFailed')) } + } + fields = parseInvoiceFieldsFromXml(xmlRead.content) + // 若 OFD 的 Content.xml 非标准电子发票 XML 节点,再补充纯文本提取,仍保持零假默认值 + if (fields.invoiceNo === null && fields.totalAmount === null) { + const stripped = xmlRead.content.replace(/<[^>]+>/g, ' ') + const plain = parseInvoiceFieldsFromPlainText(stripped) + fields = { + invoiceNo: fields.invoiceNo ?? plain.invoiceNo, + issueDate: fields.issueDate ?? plain.issueDate, + sellerName: fields.sellerName ?? plain.sellerName, + buyerName: fields.buyerName ?? plain.buyerName, + buyerTaxId: fields.buyerTaxId ?? plain.buyerTaxId, + totalAmount: fields.totalAmount ?? plain.totalAmount, + taxAmount: fields.taxAmount ?? plain.taxAmount, + category: fields.category !== INVOICE_CATEGORIES.OTHER ? fields.category : plain.category + } + } + } else if (kind === 'pdf') { + const inspectRes = await callHostTransport( + 'tool_document_pdf_inspect', + { input: { path: cleanPath }, extractText: true }, + hostOverride + ) + if (!inspectRes.ok) { + return { ok: false, error: resolveErrorMessage(inspectRes, t('errPdfInspectFailed')) } + } + const rec = asRecord(inspectRes.data) + const pages = Array.isArray(rec?.pages) ? rec.pages.map(asRecord).filter((p): p is Record => Boolean(p)) : [] + const text = + typeof rec?.fullText === 'string' + ? rec.fullText + : pages.map((p) => (typeof p.text === 'string' ? p.text : '')).join('\n') + const pdfSize = Number(rec?.sizeBytes) + if (Number.isFinite(pdfSize) && pdfSize > 0) resolvedSize = pdfSize + fields = parseInvoiceFieldsFromPlainText(text) + } else { + // 图片 / 扫描件发票走宿主既有跨端 image_ocr + const ocrRes = await callHostTransport( + 'image_ocr', + { action: 'recognizeImage', path: cleanPath, lang: 'zh-Hans-CN' }, + hostOverride + ) + if (!ocrRes.ok) { + return { ok: false, error: resolveErrorMessage(ocrRes, t('errOcrFailed')) } + } + const rec = asRecord(ocrRes.data) + const ocrText = + typeof ocrRes.data === 'string' + ? ocrRes.data + : typeof rec?.text === 'string' + ? rec.text + : Array.isArray(rec?.lines) + ? rec.lines.map((l) => (typeof l === 'string' ? l : String(asRecord(l)?.text ?? ''))).join('\n') + : '' + fields = parseInvoiceFieldsFromPlainText(ocrText) } - return `[${cat}]_${date}_${safeSeller}_${formattedAmt}_${tailNo}${ext}` -} -/** - * 为一批发票生成互不重名的归档文件名(不区分大小写,重名的依次加 _2、_3), - * 避免复制副本时后一份覆盖前一份。字段不完整的发票不分配文件名。 - */ -export function buildUniqueTargetNames(items: InvoiceRecordItem[], templateId: string): Map { - const used = new Set() - const out = new Map() - for (const item of items) { - const base = buildTargetInvoiceFileName(item, templateId) - if (!base) continue - const dot = base.lastIndexOf('.') - const stem = dot > 0 ? base.slice(0, dot) : base - const ext = dot > 0 ? base.slice(dot) : '' - let name = base - let n = 2 - while (used.has(name.toLowerCase())) { - name = `${stem}_${n}${ext}` - n++ + return { + ok: true, + item: { + id: `inv:${pathKey(cleanPath)}`, + path: cleanPath, + fileName, + extension: extOfFileName(fileName), + sourceKind: kind, + sizeBytes: resolvedSize, + invoiceNo: fields.invoiceNo, + issueDate: fields.issueDate, + sellerName: fields.sellerName, + buyerName: fields.buyerName, + buyerTaxId: fields.buyerTaxId, + totalAmount: fields.totalAmount, + taxAmount: fields.taxAmount, + netAmount: computeNetAmount(fields.totalAmount, fields.taxAmount), + category: fields.category, + isDuplicate: false, + isHeaderAbnormal: false } - used.add(name.toLowerCase()) - out.set(item.id, name) } - return out } -function displayText(value: string): string { - return value || t('unrecognized') -} +/** 批量解析电子发票(支持 XML / OFD / PDF / 图片),零假默认值 */ +export async function parseInvoiceFiles( + filePaths: readonly string[], + expectedBuyer = '', + hostOverride?: unknown +): Promise<{ + ok: boolean + invoices: InvoiceRecordItem[] + parseErrors: InvoiceParseError[] +}> { + const seen = new Set() + const invoices: InvoiceRecordItem[] = [] + const parseErrors: InvoiceParseError[] = [] -function displayAmount(value: number | null): string { - return value === null || !Number.isFinite(value) ? t('unrecognized') : value.toFixed(2) -} + for (const rawPath of filePaths) { + const trimmed = String(rawPath || '').trim() + if (!trimmed) continue + const key = pathKey(trimmed) + if (seen.has(key)) continue + seen.add(key) -function displayDate(item: InvoiceRecordItem): string { - if (!item.issueDate) return t('unrecognized') - return item.issueDateNeedsReview ? t('needsReviewTag', { date: item.issueDate }) : item.issueDate -} + const res = await parseSingleInvoiceFile(trimmed, hostOverride) + if (res.ok) invoices.push(res.item) + else parseErrors.push({ file: trimmed, error: res.error }) + } -/** - * 生成可直接粘贴到 Excel / 飞书表格的 TSV(制表符分隔)报销明细文本; - * 未识别的字段写「未识别」,字段不完整的发票不生成归档文件名 - */ -export function buildInvoiceTsvTable(items: InvoiceRecordItem[], templateId = 'tpl-standard'): string { - const header = [ - t('tsvColIndex'), - t('tsvColInvoiceNo'), - t('tsvColIssueDate'), - t('tsvColCategory'), - t('tsvColSeller'), - t('tsvColBuyer'), - t('tsvColTotal'), - t('tsvColTax'), - t('tsvColNet'), - t('tsvColFileName') - ].join('\t') + return { + ok: invoices.length > 0 || parseErrors.length === 0, + invoices: detectInvoiceAnomalies(invoices, expectedBuyer), + parseErrors + } +} - const names = buildUniqueTargetNames(items, templateId) - const clean = (value: string) => value.replace(/[\t\r\n]+/g, ' ') - const rows = items.map((item, idx) => - [ - idx + 1, - clean(displayText(item.invoiceNo)), - displayDate(item), - translateCategory(item.category), - clean(displayText(item.sellerName)), - clean(displayText(item.buyerName)), - displayAmount(item.totalAmount), - displayAmount(item.taxAmount), - displayAmount(item.netAmount), - names.get(item.id) ?? '' - ].join('\t') - ) +/** 字段完整性检查:严格判 null(金额 0 合法,绝不用 !amount) */ +export function getInvoiceMissingFields(item: InvoiceRecordItem): InvoiceFieldKey[] { + const missing: InvoiceFieldKey[] = [] + if (item.invoiceNo === null || item.invoiceNo.trim() === '') missing.push('invoiceNo') + if (item.issueDate === null || item.issueDate.trim() === '') missing.push('issueDate') + if (item.sellerName === null || item.sellerName.trim() === '') missing.push('sellerName') + if (item.buyerName === null || item.buyerName.trim() === '') missing.push('buyerName') + if (item.totalAmount === null || !Number.isFinite(item.totalAmount)) missing.push('totalAmount') + if (item.taxAmount === null || !Number.isFinite(item.taxAmount)) missing.push('taxAmount') + return missing +} - return [header, ...rows].join('\n') +export function isInvoiceComplete(item: InvoiceRecordItem): boolean { + return getInvoiceMissingFields(item).length === 0 } -/** 单张发票的文字摘要(复制用),未识别的字段写「未识别」 */ -export function buildInvoiceSummaryText(item: InvoiceRecordItem): string { - return [ - t('summaryLineNo', { val: displayText(item.invoiceNo) }), - t('summaryLineDate', { val: displayDate(item) }), - t('summaryLineSeller', { val: displayText(item.sellerName) }), - t('summaryLineBuyer', { val: displayText(item.buyerName) }), - t('summaryLineAmount', { total: displayAmount(item.totalAmount), tax: displayAmount(item.taxAmount) }) - ].join('\n') +export function describeInvoiceIssues(item: InvoiceRecordItem): string { + const missing = getInvoiceMissingFields(item) + if (missing.length === 0) return '' + return t('issueMissingPrefix', { fields: missing.map((f) => getInvoiceFieldLabel(f)).join(t('listSep')) }) } -/** - * 执行发票号查重与购方抬头异常预检(按当前字段重新计算,修改发票信息后可再次调用) - */ -export function detectInvoiceAnomalies( - items: InvoiceRecordItem[], - expectedBuyerKeyword = '' -): InvoiceRecordItem[] { +export function detectInvoiceAnomalies(items: InvoiceRecordItem[], expectedBuyerKeyword = ''): InvoiceRecordItem[] { const seenNo = new Set() const kw = expectedBuyerKeyword.trim() return items.map((item) => { - const normNo = String(item.invoiceNo || '').trim() + const normNo = item.invoiceNo ? item.invoiceNo.trim() : '' const isDuplicate = normNo.length > 0 && seenNo.has(normNo) if (normNo.length > 0) seenNo.add(normNo) - const buyer = String(item.buyerName || '').trim() - // 购买方未识别时归入「未识别字段」,这里只判断已识别的抬头 + const buyer = item.buyerName ? item.buyerName.trim() : '' const isPersonalHeader = buyer.length > 0 && ZH_PERSONAL_HEADER_REGEX.test(buyer) - const isMismatch = kw && buyer.length > 0 ? !buyer.includes(kw) && !String(item.buyerTaxId || '').includes(kw) : false + const isMismatch = kw && buyer.length > 0 ? !buyer.includes(kw) && !(item.buyerTaxId ?? '').includes(kw) : false return { ...item, isDuplicate, @@ -466,65 +619,44 @@ export function detectInvoiceAnomalies( }) } -export type InvoiceFilterKey = string - -/** 列表筛选与左侧导航计数共用的匹配规则 */ -export function matchesInvoiceFilter(item: InvoiceRecordItem, key: InvoiceFilterKey): boolean { - switch (key) { - case 'ALL': - return true - case 'DUPLICATE': - return item.isDuplicate - case 'ABNORMAL': - return item.isHeaderAbnormal - case 'INCOMPLETE': - return !isInvoiceComplete(item) - case 'TRAVEL': - return item.category === INVOICE_CATEGORIES.TRANSIT || item.category === INVOICE_CATEGORIES.LODGING - default: - return item.category === key - } +export function isInvoiceSelectable(item: InvoiceRecordItem): boolean { + return isInvoiceComplete(item) && !item.isDuplicate } -export interface InvoiceEditInput { - invoiceNo: string - issueDate: string - sellerName: string - buyerName: string - totalAmount: string - taxAmount: string +export function defaultCheckedInvoiceIds(items: InvoiceRecordItem[]): string[] { + return items.filter((i) => isInvoiceSelectable(i) && !i.isHeaderAbnormal).map((i) => i.id) } -export interface InvoiceEditValues { - invoiceNo: string - issueDate: string - sellerName: string - buyerName: string - totalAmount: number - taxAmount: number - netAmount: number +export function matchesInvoiceFilter(item: InvoiceRecordItem, key: string): boolean { + switch (key) { + case 'ALL': return true + case 'DUPLICATE': return item.isDuplicate + case 'INCOMPLETE': return !isInvoiceComplete(item) + case 'TRAVEL': return item.category === INVOICE_CATEGORIES.TRANSIT || item.category === INVOICE_CATEGORIES.LODGING + default: return item.category === key + } } -export type InvoiceEditValidation = - | { ok: true; values: InvoiceEditValues } - | { ok: false; errors: Partial> } +export function formatCurrency(amount: number | null | undefined): string { + if (amount === null || amount === undefined || !Number.isFinite(amount)) return t('unrecognized') + return `¥${amount.toLocaleString(getLocale(), { minimumFractionDigits: 2, maximumFractionDigits: 2 })}` +} const AMOUNT_TEXT_PATTERN = /^\d+(?:\.\d{1,2})?$/ -function parseAmountText(text: string): number | null { +function parseEditableAmount(text: string): number | null { const cleaned = String(text ?? '').replace(/[¥¥,,\s]/g, '') if (!AMOUNT_TEXT_PATTERN.test(cleaned)) return null return Math.round(Number(cleaned) * 100) / 100 } -/** 校验用户补全 / 修改的发票字段 */ -export function validateInvoiceEdits(input: InvoiceEditInput, now: Date = new Date()): InvoiceEditValidation { +/** 校验人工补录/编辑的发票字段(金额 0 与税额 0 均合法!) */ +export function validateInvoiceEdits(input: InvoiceEditInput): InvoiceEditValidation { const errors: Partial> = {} - const invoiceNo = normalizeInvoiceNo(input.invoiceNo) if (!invoiceNo) errors.invoiceNo = t('errEditInvoiceNo') - const issueDate = normalizeIssueDate(input.issueDate, now) + const issueDate = normalizeIssueDate(input.issueDate) if (!issueDate) errors.issueDate = t('errEditIssueDate') const sellerName = String(input.sellerName ?? '').trim() @@ -535,371 +667,239 @@ export function validateInvoiceEdits(input: InvoiceEditInput, now: Date = new Da if (!buyerName) errors.buyerName = t('errEditBuyerEmpty') else if (buyerName.length > 100) errors.buyerName = t('errEditBuyerLong') - const totalAmount = parseAmountText(input.totalAmount) - if (totalAmount === null || totalAmount <= 0) errors.totalAmount = t('errEditTotalInvalid') + const totalAmount = parseEditableAmount(input.totalAmount) + if (totalAmount === null || totalAmount < 0) errors.totalAmount = t('errEditTotalInvalid') else if (totalAmount > 100_000_000) errors.totalAmount = t('errEditTotalRange') - const taxAmount = parseAmountText(input.taxAmount) - if (taxAmount === null) errors.taxAmount = t('errEditTaxInvalid') + const taxAmount = parseEditableAmount(input.taxAmount) + if (taxAmount === null || taxAmount < 0) errors.taxAmount = t('errEditTaxInvalid') else if (totalAmount !== null && taxAmount > totalAmount) errors.taxAmount = t('errEditTaxExceeds') if (Object.keys(errors).length > 0) return { ok: false, errors } return { ok: true, values: { - invoiceNo, - issueDate, + invoiceNo: invoiceNo!, + issueDate: issueDate!, sellerName, buyerName, - totalAmount: totalAmount as number, - taxAmount: taxAmount as number, - netAmount: Math.round(((totalAmount as number) - (taxAmount as number)) * 100) / 100 + totalAmount: totalAmount!, + taxAmount: taxAmount!, + netAmount: Math.round((totalAmount! - taxAmount!) * 100) / 100 } } } -/** 把用户确认过的字段写回发票(日期视为已核对),并重新计算查重与抬头检查 */ -export function applyInvoiceEdits( - items: InvoiceRecordItem[], - id: string, - values: InvoiceEditValues, - expectedBuyer = '' -): InvoiceRecordItem[] { - const next = items.map((item) => - item.id === id ? { ...item, ...values, issueDateNeedsReview: false } : item - ) - return detectInvoiceAnomalies(next, expectedBuyer) -} - -export function validateInvocationPayload( - method: string, - params: unknown -): { valid: boolean; error?: string } { - if (typeof method !== 'string' || method.trim().length === 0) { - return { valid: false, error: t('errMethodEmpty') } - } - if (method.length > 128 || !/^[A-Za-z0-9_]+$/.test(method.trim())) { - return { valid: false, error: t('errMethodFormat') } - } - if (params === null || params === undefined || typeof params !== 'object' || Array.isArray(params)) { - return { valid: false, error: t('errParamsObject') } - } - - const record = params as Record - for (const [key, val] of Object.entries(record)) { - if (typeof val === 'string') { - if (val.length > 4096) { - return { valid: false, error: t('errParamTooLong', { key }) } - } - if ((key === 'outputDir' || key === 'targetDir') && FORBIDDEN_TARGET_PATTERN.test(val)) { - return { valid: false, error: t('errSecurityIntercepted', { reason: getForbiddenReason() }) } - } - } - } - return { valid: true } -} - -export async function invokeNativeCapability( - method: string, - params: Record, - hostBridge?: unknown -): Promise { - const check = validateInvocationPayload(method, params) - if (!check.valid) { - throw new Error(resolveErrorMessage(check, t('errParamValidation'))) - } - const res = await invokeDllPluginCapability(DLL_PLUGIN_NAME, method, params, hostBridge) - return { - ok: res.ok, - pluginName: DLL_PLUGIN_NAME, - method: method.trim(), - data: res.data ?? undefined, - error: res.error, - fromFallback: res.fromFallback - } +export function applyInvoiceEdits(items: InvoiceRecordItem[], id: string, values: InvoiceEditValues): InvoiceRecordItem[] { + const next = items.map((item) => (item.id === id ? { ...item, ...values } : item)) + return detectInvoiceAnomalies(next) } -export const INVOICE_IMPORT_EXTENSIONS = ['.pdf', '.ofd', '.xml', '.jpg', '.jpeg', '.png'] as const -export const INVOICE_IMPORT_SUPPORTED_TEXT = 'PDF / OFD / XML / JPG / PNG' -export const INVOICE_PARSE_BATCH_SIZE = 50 - -const INVOICE_FILE_REGEX = /\.(?:pdf|ofd|xml|jpg|jpeg|png)$/i +export function buildTargetInvoiceFileName(item: InvoiceRecordItem, templateId: string): string | null { + if (!isInvoiceComplete(item)) return null + const ext = item.extension || extOfFileName(item.fileName) + const safeSeller = (item.sellerName as string).replace(/[\\/:*?"<>|\s]+/g, '_').slice(0, 24) + const tailNo = (item.invoiceNo as string).slice(-4) + const amt = (item.totalAmount as number).toFixed(2) + const date = item.issueDate as string + const cat = translateCategory(item.category) + const formattedAmt = t('formatAmount', { amount: amt }) -export function isInsideExportDirectory(filePath: string): boolean { - return filePath - .split(/[\\/]/) - .some((segment) => segment.toLowerCase() === EXPORT_ROOT_DIR_NAME.toLowerCase()) + if (templateId === 'tpl-date-first') return `${date}_[${cat}]_${formattedAmt}_${safeSeller}${ext}` + if (templateId === 'tpl-amount-first') return `[${cat}]_${formattedAmt}_${safeSeller}_${tailNo}${ext}` + if (templateId === 'tpl-tax-audit') return `${item.invoiceNo}_${date}_${safeSeller}_${formattedAmt}${ext}` + return `[${cat}]_${date}_${safeSeller}_${formattedAmt}_${tailNo}${ext}` } -/** 导入规则:支持 6 种电子发票格式,跳过历史导出产物与导出目录,拦截系统受保护路径 */ -export const INVOICE_IMPORT_RULES: FileImportRules = { - extensions: INVOICE_IMPORT_EXTENSIONS, - forbiddenPath: FORBIDDEN_TARGET_PATTERN, - excludeDirNames: [EXPORT_ROOT_DIR_NAME], - excludeFile: (name, filePath) => EXPORTED_FILE_NAMES.test(name) || isInsideExportDirectory(filePath) -} +export function buildInvoiceTsvTable(items: InvoiceRecordItem[], templateId = 'tpl-standard'): string { + const header = [ + t('tsvColIndex'), + t('tsvColInvoiceNo'), + t('tsvColIssueDate'), + t('tsvColCategory'), + t('tsvColSeller'), + t('tsvColBuyer'), + t('tsvColTotal'), + t('tsvColTax'), + t('tsvColNet'), + t('tsvColFileName') + ].join('\t') -export function createInvoiceImportTransport(hostOverride?: unknown): FileImportTransport { - return (method, params) => callHostTransport(method, params, hostOverride) + const showText = (v: string | null) => (v !== null && v.trim() ? v.replace(/[\t\r\n]+/g, ' ') : t('unrecognized')) + const showNum = (v: number | null) => (v !== null && Number.isFinite(v) ? v.toFixed(2) : t('unrecognized')) + const rows = items.map((item, idx) => + [ + idx + 1, + showText(item.invoiceNo), + showText(item.issueDate), + translateCategory(item.category), + showText(item.sellerName), + showText(item.buyerName), + showNum(item.totalAmount), + showNum(item.taxAmount), + showNum(item.netAmount), + buildTargetInvoiceFileName(item, templateId) ?? '' + ].join('\t') + ) + return [header, ...rows].join('\n') } -export function isInvoiceFilePath(value: unknown): value is string { - if (typeof value !== 'string') return false - const trimmed = value.trim() - if (!trimmed || trimmed.length > 4096 || /[\0\r\n"]/.test(trimmed)) return false - if (FORBIDDEN_TARGET_PATTERN.test(trimmed)) return false - const name = trimmed.split(/[\\/]/).pop() || '' - if (EXPORTED_FILE_NAMES.test(name) || isInsideExportDirectory(trimmed)) return false - return INVOICE_FILE_REGEX.test(trimmed) +export function buildInvoiceSummaryText(item: InvoiceRecordItem): string { + const showText = (v: string | null) => (v !== null && v.trim() ? v : t('unrecognized')) + const showNum = (v: number | null) => (v !== null && Number.isFinite(v) ? v.toFixed(2) : t('unrecognized')) + return [ + t('summaryLineNo', { val: showText(item.invoiceNo) }), + t('summaryLineDate', { val: showText(item.issueDate) }), + t('summaryLineSeller', { val: showText(item.sellerName) }), + t('summaryLineBuyer', { val: showText(item.buyerName) }), + t('summaryLineAmount', { total: showNum(item.totalAmount), tax: showNum(item.taxAmount) }) + ].join('\n') } -function dedupeInvoicePaths(rawPaths: string[]): string[] { - const out: string[] = [] - const seen = new Set() - for (const raw of rawPaths) { - if (!isInvoiceFilePath(raw)) continue - const trimmed = raw.trim() - const key = pathKey(trimmed) - if (seen.has(key)) continue - seen.add(key) - out.push(trimmed) +/** 合并报销单 PDF(调 tool_document_pdf_transform merge / images-to-pdf) */ +export async function mergeInvoicesToPdf( + items: readonly InvoiceRecordItem[], + options: { outputPath?: string } = {}, + hostOverride?: unknown +): Promise { + const pdfItems = items.filter((i) => i.sourceKind === 'pdf') + const imgItems = items.filter((i) => i.sourceKind === 'image') + if (pdfItems.length === 0 && imgItems.length === 0) { + return { ok: false, taskId: '', outputPath: '', outputBytes: 0, pageCount: 0, error: t('errMergePdfEmpty') } } - return out -} - -export interface ParseInvoiceFilesOptions { - signal?: AbortSignal - onProgress?: (progress: { done: number; total: number }) => void - batchSize?: number -} -/** - * 调用宿主分批解析指定的电子发票文件:每批最多 50 个,单批失败不阻断其他批次并如实记录失败。 - */ -export async function parseInvoiceFiles( - filePaths: string[], - expectedBuyer = '', - hostOverride?: unknown, - now: Date = new Date(), - options: ParseInvoiceFilesOptions = {} -): Promise<{ - ok: boolean - invoices: InvoiceRecordItem[] - parseErrors: InvoiceParseError[] - batchErrors: string[] - canceled?: boolean - error?: string -}> { - const validPaths = dedupeInvoicePaths(Array.isArray(filePaths) ? filePaths : []) - if (validPaths.length === 0) return { ok: true, invoices: [], parseErrors: [], batchErrors: [] } - - const rawBatchSize = options.batchSize - const batchSize = - typeof rawBatchSize === 'number' && Number.isInteger(rawBatchSize) && rawBatchSize > 0 - ? Math.min(rawBatchSize, INVOICE_PARSE_BATCH_SIZE) - : INVOICE_PARSE_BATCH_SIZE - - const recognized: InvoiceRecordItem[] = [] - const parseErrors: InvoiceParseError[] = [] - const batchErrors: string[] = [] - let succeededBatches = 0 - let done = 0 - - for (let offset = 0; offset < validPaths.length; offset += batchSize) { - if (options.signal?.aborted) { - return { ok: false, invoices: [], parseErrors: [], batchErrors: [], canceled: true } - } - const chunk = validPaths.slice(offset, offset + batchSize) - const params = expectedBuyer ? { files: chunk, expectedBuyer } : { files: chunk } - let res: NativeInvocationResult - try { - res = await invokeNativeCapability('ParseInvoices', params, hostOverride) - } catch (err) { - const errMsg = friendlyFileError(err) - batchErrors.push(errMsg) - for (const file of chunk) { - parseErrors.push({ file, error: errMsg }) - } - done += chunk.length - options.onProgress?.({ done, total: validPaths.length }) - continue - } - - if (options.signal?.aborted) { - return { ok: false, invoices: [], parseErrors: [], batchErrors: [], canceled: true } - } + const firstPath = (pdfItems[0] ?? imgItems[0])!.path + const sep = firstPath.includes('\\') ? '\\' : '/' + const idx = Math.max(firstPath.lastIndexOf('\\'), firstPath.lastIndexOf('/')) + const dir = idx > 0 ? firstPath.slice(0, idx) : '' + const now = new Date() + const stamp = `${now.getFullYear()}${pad2(now.getMonth() + 1)}${pad2(now.getDate())}_${pad2(now.getHours())}${pad2(now.getMinutes())}${pad2(now.getSeconds())}` + const outputPath = options.outputPath?.trim() || `${dir}${sep}Reimbursement_Merged_${stamp}.pdf` + if (FORBIDDEN_TARGET_PATTERN.test(outputPath)) { + return { ok: false, taskId: '', outputPath, outputBytes: 0, pageCount: 0, error: t('forbiddenReason') } + } - if (!res.ok || !res.data || typeof res.data !== 'object') { - const errMsg = friendlyFileError(resolveErrorMessage(res, t('errHostNoInvoiceResult'))) - batchErrors.push(errMsg) - for (const file of chunk) { - parseErrors.push({ file, error: errMsg }) - } - done += chunk.length - options.onProgress?.({ done, total: validPaths.length }) - continue + const taskId = nextMessageId('inv_merge_pdf') + // 纯图片 → images-to-pdf + if (pdfItems.length === 0) { + const res = await callHostTransport( + 'tool_document_pdf_transform', + { + taskId, + operation: 'images-to-pdf', + inputs: imgItems.map((i) => ({ path: i.path })), + output: { path: outputPath }, + overwrite: false + }, + hostOverride + ) + if (!res.ok) { + return { ok: false, taskId, outputPath, outputBytes: 0, pageCount: 0, error: resolveErrorMessage(res, t('errMergePdfFailed')) } } - - succeededBatches += 1 - const data = res.data as { invoices?: unknown; errors?: unknown } - parseErrors.push(...readParseErrors(data.errors)) - const rawEntries = Array.isArray(data.invoices) ? (data.invoices as Array>) : [] - for (let i = 0; i < rawEntries.length; i++) { - const raw = rawEntries[i] - const normalized = normalizeParsedInvoice(raw && typeof raw === 'object' ? raw : {}, recognized.length + i, now) - if (normalized) recognized.push(normalized) - else parseErrors.push({ file: String(raw?.fileName ?? t('nthResultFallback', { n: recognized.length + i + 1 })), error: t('errResultMissingPath') }) + const data = asRecord(res.data) + return { + ok: true, + taskId: typeof data?.taskId === 'string' ? data.taskId : taskId, + outputPath, + outputBytes: Number(data?.outputBytes ?? 0), + pageCount: Number(data?.pageCount ?? imgItems.length) } - done += chunk.length - options.onProgress?.({ done, total: validPaths.length }) } - if (succeededBatches === 0) { - return { - ok: false, - invoices: [], - parseErrors, - batchErrors, - error: batchErrors[0] || t('errParseInvoicesFailed') + // 若含图片与 PDF 混合,先把图片转为临时 PDF 再 merge + const mergeInputs: Array<{ path: string }> = pdfItems.map((i) => ({ path: i.path })) + if (imgItems.length > 0) { + const tempBase = (await getRealSystemPath('temp', hostOverride)) || dir + const tmpImgPdf = `${tempBase.replace(/[\\/]+$/, '')}${sep}${nextMessageId('inv_imgs')}.pdf` + const imgRes = await callHostTransport( + 'tool_document_pdf_transform', + { + taskId: nextMessageId('inv_img2pdf'), + operation: 'images-to-pdf', + inputs: imgItems.map((i) => ({ path: i.path })), + output: { path: tmpImgPdf }, + overwrite: true + }, + hostOverride + ) + if (!imgRes.ok) { + return { ok: false, taskId, outputPath, outputBytes: 0, pageCount: 0, error: resolveErrorMessage(imgRes, t('errMergePdfFailed')) } } + mergeInputs.push({ path: tmpImgPdf }) } + const mergeRes = await callHostTransport( + 'tool_document_pdf_transform', + { + taskId, + operation: 'merge', + inputs: mergeInputs, + output: { path: outputPath }, + overwrite: false + }, + hostOverride + ) + if (!mergeRes.ok) { + return { ok: false, taskId, outputPath, outputBytes: 0, pageCount: 0, error: resolveErrorMessage(mergeRes, t('errMergePdfFailed')) } + } + const data = asRecord(mergeRes.data) return { ok: true, - invoices: detectInvoiceAnomalies(recognized, expectedBuyer), - parseErrors, - batchErrors, - ...(batchErrors.length > 0 ? { error: batchErrors[0] } : {}) + taskId: typeof data?.taskId === 'string' ? data.taskId : taskId, + outputPath, + outputBytes: Number(data?.outputBytes ?? 0), + pageCount: Number(data?.pageCount ?? mergeInputs.length) } } -function readParseErrors(raw: unknown): InvoiceParseError[] { - if (!Array.isArray(raw)) return [] - return raw.map((entry) => { - const rec = (entry && typeof entry === 'object' ? entry : {}) as Record - return { - file: String(rec.file ?? rec.path ?? ''), - error: friendlyFileError(resolveErrorMessage(rec, t('errUnknown'))) - } - }) -} - -/** - * 本次导出的输出目录:第一张发票所在目录下的 ZTools_Reimbursement_Export\报销归档_<时间>。 - * 每次导出用新目录,宿主写副本与 CSV 时不会覆盖上次导出的文件。 - */ -export function buildExportOutputDir(firstInvoicePath: string, now: Date = new Date()): string { - const p = String(firstInvoicePath || '').trim() - const idx = Math.max(p.lastIndexOf('\\'), p.lastIndexOf('/')) - if (idx <= 0) throw new Error(t('errCannotResolveDir', { path: p || t('emptyPathLabel') })) - const sep = p[idx] as string - const dir = p.slice(0, idx) - const stamp = - `${now.getFullYear()}${pad2(now.getMonth() + 1)}${pad2(now.getDate())}_` + - `${pad2(now.getHours())}${pad2(now.getMinutes())}${pad2(now.getSeconds())}_` + - String(now.getMilliseconds()).padStart(3, '0') - return `${dir}${sep}${EXPORT_ROOT_DIR_NAME}${sep}${t('exportDirPrefix')}_${stamp}` -} - -export type InvoiceExportMode = 'bundle' | 'csv' - -export interface InvoiceExportResult { - ok: boolean - outputDir: string - /** 已复制的规范命名副本数 */ - copiedCount: number - csvPath: string - error?: string -} - -/** - * 导出报销材料: - * - bundle:复制规范命名副本(BatchRenameInvoices)+ 生成报销明细 CSV(ExportInvoicesCsv) - * - csv:只生成报销明细 CSV - * 只接受字段完整、非重复的发票;按宿主返回的文件列表与路径确认结果,确认不了就报失败。 - */ -export async function exportInvoices( - mode: InvoiceExportMode, - items: InvoiceRecordItem[], - templateId: string, - hostOverride?: unknown, - now: Date = new Date() -): Promise { - const fail = (error: string, extra: Partial = {}): InvoiceExportResult => ({ - ok: false, - outputDir: '', - copiedCount: 0, - csvPath: '', - error, - ...extra - }) - - if (items.length === 0) return fail(t('errExportEmpty')) +/** 导出 UTF-8 BOM 报销明细 CSV(严禁包含未识别字段或重复发票号) */ +export async function exportInvoicesCsv( + items: readonly InvoiceRecordItem[], + templateId = 'tpl-standard', + hostOverride?: unknown +): Promise { + if (items.length === 0) return { ok: false, csvPath: '', error: t('errExportEmpty') } const incomplete = items.filter((i) => !isInvoiceComplete(i)) if (incomplete.length > 0) { - return fail(t('errExportIncomplete', { count: incomplete.length, file: incomplete[0]!.fileName })) + return { ok: false, csvPath: '', error: t('errExportIncomplete', { count: incomplete.length, file: incomplete[0]!.fileName }) } } const duplicates = items.filter((i) => i.isDuplicate) if (duplicates.length > 0) { - return fail(t('errExportDuplicate', { count: duplicates.length, file: duplicates[0]!.fileName })) - } - - let outputDir: string - try { - outputDir = buildExportOutputDir(items[0]!.path, now) - } catch (err) { - return fail(err instanceof Error ? err.message : String(err)) + return { ok: false, csvPath: '', error: t('errExportDuplicate', { count: duplicates.length, file: duplicates[0]!.fileName }) } } - const names = buildUniqueTargetNames(items, templateId) - const params = { - invoices: items.map((inv) => ({ ...inv, targetFileName: names.get(inv.id) as string })), - files: items.map((inv) => inv.path), - templateId, - outputDir + const first = items[0]!.path + const sep = first.includes('\\') ? '\\' : '/' + const idx = Math.max(first.lastIndexOf('\\'), first.lastIndexOf('/')) + const dir = idx > 0 ? first.slice(0, idx) : '' + const now = new Date() + const stamp = `${now.getFullYear()}${pad2(now.getMonth() + 1)}${pad2(now.getDate())}_${pad2(now.getHours())}${pad2(now.getMinutes())}${pad2(now.getSeconds())}` + const csvPath = `${dir}${sep}Reimbursement_Summary_${stamp}.csv` + if (FORBIDDEN_TARGET_PATTERN.test(csvPath)) { + return { ok: false, csvPath, error: t('forbiddenReason') } } - let copiedCount = 0 - if (mode === 'bundle') { - const copyRes = await invokeNativeCapability('BatchRenameInvoices', params, hostOverride) - if (!copyRes.ok) { - return fail(t('errCopyBundleFailed', { error: friendlyFileError(resolveErrorMessage(copyRes, t('errHostNoReason'))), dir: outputDir }), { outputDir }) - } - const data = (copyRes.data ?? {}) as Record - const renamed = Array.isArray(data.renamedFiles) ? data.renamedFiles : null - if (!renamed) { - return fail(t('errHostNoCopiedFiles'), { outputDir }) - } - copiedCount = renamed.length - if (copiedCount !== items.length) { - return fail(t('errPartialCopied', { copied: copiedCount, total: items.length }), { outputDir, copiedCount }) - } - } - - const csvRes = await invokeNativeCapability('ExportInvoicesCsv', params, hostOverride) - const copiedNote = copiedCount > 0 ? t('copiedNotePrefix', { count: copiedCount }) : '' - if (!csvRes.ok) { - return fail(t('errExportCsvFailed', { note: copiedNote, error: friendlyFileError(resolveErrorMessage(csvRes, t('errHostNoReason'))) }), { outputDir, copiedCount }) - } - const csvData = (csvRes.data ?? {}) as Record - const csvPath = typeof csvData.csvOutputPath === 'string' ? csvData.csvOutputPath.trim() : '' - if (!csvPath) { - return fail(t('errHostNoCsvPath', { note: copiedNote }), { outputDir, copiedCount }) + const esc = (v: string) => `"${v.replace(/"/g, '""')}"` + const tsvLines = buildInvoiceTsvTable([...items], templateId).split('\n') + const csvContent = '\uFEFF' + tsvLines.map((line) => line.split('\t').map(esc).join(',')).join('\r\n') + const writeRes = await callHostTransport( + 'filesystem_write_file', + { path: csvPath, content: csvContent, encoding: 'utf8' }, + hostOverride + ) + if (!writeRes.ok) { + return { ok: false, csvPath, error: resolveErrorMessage(writeRes, t('errCsvWriteFailed')) } } - const hostOutDir = typeof csvData.outputDir === 'string' && csvData.outputDir.trim() ? csvData.outputDir.trim() : outputDir - return { ok: true, outputDir: hostOutDir, copiedCount, csvPath } + return { ok: true, csvPath } } export async function openInvoiceLocation(filePath: string, hostOverride?: unknown): Promise { return showRealItemInFolder(filePath, hostOverride) } -export async function trashInvoiceFile( - filePath: string, - hostOverride?: unknown -): Promise<{ ok: boolean; error?: string }> { +export async function trashInvoiceFile(filePath: string, hostOverride?: unknown): Promise<{ ok: boolean; error?: string }> { if (!filePath || FORBIDDEN_TARGET_PATTERN.test(filePath)) { - return { ok: false, error: getForbiddenReason() } + return { ok: false, error: t('forbiddenReason') } } const res = await trashRealItem(filePath, hostOverride) return res.ok ? res : { ok: false, error: friendlyFileError(resolveErrorMessage(res, t('errTrashFailed'))) } diff --git a/extensions/invoice-assistant/src/native-ipc.ts b/extensions/invoice-assistant/src/native-ipc.ts deleted file mode 100644 index 51576b99..00000000 --- a/extensions/invoice-assistant/src/native-ipc.ts +++ /dev/null @@ -1,1852 +0,0 @@ -import { getLocale } from '@ztools/declarative-ui' - -type DynamicBridge = ReturnType - -const NATIVE_IPC_MESSAGES: Record string - dirEntrySep: string - dirErrorColon: string - deepScanUnavailable: string - pathEmpty: string - invalidMethodEmpty: string - invalidMethodFormat: string - invalidParamsObject: string - paramTooLong: (key: string) => string - paramOutOfRange: (key: string) => string - methodParamEmpty: string - invalidMethodType: string - malformedDllResponse: string - unknownDllError: string - hostIpcFailed: (pluginName: string, method: string) => string - hostUnavailable: (pluginName: string, method: string) => string - callFailed: string - movedToTrash: string - deleteFailed: string - revealedInFolder: string - revealFailed: string - opened: string - openFailed: string - pluginCallNotReady: string -}> = { - 'zh-CN': { - ipcCallFailed: 'IPC 调用返回失败', - ipcInnerFailed: 'IPC 内部调用失败', - scanIncomplete: '扫描结果不完整', - dirReadFailed: (details, moreCount) => - `目录读取失败或不完整:${details}${moreCount > 0 ? `;另有 ${moreCount} 个目录` : ''}`, - dirEntrySep: ';', - dirErrorColon: ':', - deepScanUnavailable: '深度扫描不可用,仅列出一级目录,结果不完整', - pathEmpty: '路径不能为空', - invalidMethodEmpty: 'INVALID_METHOD: 调用方法名不能为空', - invalidMethodFormat: 'INVALID_METHOD_FORMAT: 方法名包含非法字符或超长', - invalidParamsObject: 'INVALID_PARAMS: 参数必须为非空对象', - paramTooLong: (key) => `PARAM_TOO_LONG: 参数 ${key} 超过最大长度限制`, - paramOutOfRange: (key) => `PARAM_OUT_OF_RANGE: 数值参数 ${key} 越界或非有限数`, - methodParamEmpty: 'method 参数不能为空', - invalidMethodType: 'INVALID_METHOD: method 不能为空且必须为字符串', - malformedDllResponse: 'MALFORMED_DLL_RESPONSE: 原生组件返回了损坏的 JSON 数据', - unknownDllError: '原生组件返回未知错误', - hostIpcFailed: (pluginName, method) => `HOST_IPC_FAILED: ${pluginName}.${method} 调用失败`, - hostUnavailable: (pluginName, method) => `HOST_UNAVAILABLE: ${pluginName}.${method} 宿主接口未就绪`, - callFailed: '调用失败', - movedToTrash: '已移入回收站', - deleteFailed: '删除失败', - revealedInFolder: '已定位文件', - revealFailed: '定位失败', - opened: '已打开', - openFailed: '打开失败', - pluginCallNotReady: '插件调用未就绪' - }, - 'en-US': { - ipcCallFailed: 'IPC call failed', - ipcInnerFailed: 'Internal IPC call failed', - scanIncomplete: 'Incomplete scan results', - dirReadFailed: (details, moreCount) => - `Directory read failed or incomplete: ${details}${moreCount > 0 ? `; and ${moreCount} more` : ''}`, - dirEntrySep: '; ', - dirErrorColon: ': ', - deepScanUnavailable: 'Deep scan unavailable; only top-level directory listed (incomplete)', - pathEmpty: 'Path cannot be empty', - invalidMethodEmpty: 'INVALID_METHOD: Method name cannot be empty', - invalidMethodFormat: 'INVALID_METHOD_FORMAT: Method name contains invalid characters or is too long', - invalidParamsObject: 'INVALID_PARAMS: Parameters must be a non-null object', - paramTooLong: (key) => `PARAM_TOO_LONG: Parameter "${key}" exceeds maximum length`, - paramOutOfRange: (key) => `PARAM_OUT_OF_RANGE: Numeric parameter "${key}" is out of range or non-finite`, - methodParamEmpty: 'Method parameter cannot be empty', - invalidMethodType: 'INVALID_METHOD: Method must be a non-empty string', - malformedDllResponse: 'MALFORMED_DLL_RESPONSE: Native component returned malformed JSON', - unknownDllError: 'Native component returned an unknown error', - hostIpcFailed: (pluginName, method) => `HOST_IPC_FAILED: ${pluginName}.${method} call failed`, - hostUnavailable: (pluginName, method) => `HOST_UNAVAILABLE: ${pluginName}.${method} host interface not ready`, - callFailed: 'Call failed', - movedToTrash: 'Moved to Trash', - deleteFailed: 'Delete failed', - revealedInFolder: 'Revealed in folder', - revealFailed: 'Failed to reveal item', - opened: 'Opened', - openFailed: 'Failed to open', - pluginCallNotReady: 'Plugin invocation not ready' - } -} - -function ipcStrings() { - const locale = getLocale() - return NATIVE_IPC_MESSAGES[locale] ?? NATIVE_IPC_MESSAGES['en-US'] -} -/** - * ZTools 真实宿主 IPC 与系统能力桥接层 (Real Host IPC Bridge) - * - * 严格遵循《ZTools Declarative UI 2.0 架构与 35 款原生插件全量升级规范》5.1 真实环境铁律: - * - 在真实 Electron 宿主环境中,100% 走通 Preload (__ztoolsElectron.transport.methods / window.ztools / __ztoolsLauncher) 真实调用链路 - * - 严禁在真实环境中因参数格式或嵌套响应结构差异而回退到假数据 - */ - -let ipcReqSeq = 1 -const realFileSizeCache = new Map() - -export function nextMessageId(prefix = 'ipc'): string { - ipcReqSeq = (ipcReqSeq + 1) % 1_000_000 - return `${prefix}_${Date.now()}_${ipcReqSeq}` -} - -/** - * 判断当前是否处于真实的 ZTools Electron 渲染进程宿主环境 - */ -export function isRealElectronHost(hostOverride?: unknown): boolean { - if (hostOverride) return false - if (typeof window === 'undefined') return false - const w = window as DynamicBridge - return Boolean( - w.__ztoolsElectron?.transport?.methods || - w.ztools?.transport?.call || - w.ztools?.transport?.methods - ) -} - -function normalizeMethodParams(method: string, params: Record): Record { - if (!params || typeof params !== 'object') return {} - const next = { ...params } - if (method === 'system_get_disk_usage') { - const rawDrive = String(next.drive || next.path || 'C:\\').trim() - if (rawDrive.startsWith('/')) { - next.drive = rawDrive - } else { - const match = rawDrive.match(/^([A-Za-z]):/) - next.drive = match ? `${match[1].toUpperCase()}:\\` : rawDrive.replace(/\//g, '\\') - } - delete next.path - } - return next -} - -function normalizeMethodResult(method: string, payload: DynamicBridge): DynamicBridge { - if (!payload || typeof payload !== 'object') return payload - - if (method === 'system_get_disk_usage') { - const avail = typeof payload.available === 'number' - ? payload.available - : typeof payload.free === 'number' - ? payload.free - : Math.max(0, Number(payload.total || 0) - Number(payload.used || 0)) - return { - ...payload, - available: avail, - free: avail - } - } - - if (method === 'system_get_hardware_summary') { - const cpuModel = - typeof payload.cpuModel === 'string' && payload.cpuModel.trim() - ? payload.cpuModel.trim() - : Array.isArray(payload.cpuModels) && payload.cpuModels.length > 0 - ? String(payload.cpuModels[0]).trim() - : 'x86_64 Processor' - return { - ...payload, - cpuModel - } - } - - if (method === 'system_get_battery_status') { - // 宿主约定 percent 超出 0-100(如 255)表示无电池或电量未知,不能改写成 100% - const rawPct = payload.percent - const hasBattery = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 - return { - ...payload, - percent: hasBattery ? rawPct : null, - hasBattery - } - } - - if (method === 'screen_get_all_displays') { - const list = Array.isArray(payload) - ? payload - : Array.isArray(payload.displays) - ? payload.displays - : [] - return list.map((d: DynamicBridge) => ({ - ...d, - label: d?.label || d?.name || `Display #${d?.id ?? 1}` - })) - } - - return payload -} - -function extractIpcErrorMeta(errObj: DynamicBridge): { - errorCode?: string - errorDetails?: Record -} { - if (!errObj || typeof errObj !== 'object') return {} - const errorCode = - typeof errObj.errorCode === 'string' && errObj.errorCode.trim() - ? errObj.errorCode.trim() - : typeof errObj.code === 'string' && errObj.code.trim() - ? errObj.code.trim() - : undefined - const rawDetails = - errObj.errorDetails && typeof errObj.errorDetails === 'object' && !Array.isArray(errObj.errorDetails) - ? (errObj.errorDetails as Record) - : errObj.details && typeof errObj.details === 'object' && !Array.isArray(errObj.details) - ? (errObj.details as Record) - : undefined - return { - ...(errorCode ? { errorCode } : {}), - ...(rawDetails ? { errorDetails: rawDetails } : {}) - } -} - -function unwrapTransportResponse( - method: string, - raw: DynamicBridge -): { ok: boolean; data?: DynamicBridge; error?: string; errorCode?: string; errorDetails?: Record } { - if (raw === null || raw === undefined) { - return { ok: false, error: 'EMPTY_IPC_RESPONSE', errorCode: 'EMPTY_IPC_RESPONSE' } - } - if (typeof raw !== 'object') { - return { ok: true, data: raw } - } - if (raw.success === false) { - const errObj = raw.error - const errMsg = - typeof errObj === 'object' && errObj !== null - ? String(errObj.message || errObj.code || JSON.stringify(errObj)) - : String(errObj || ipcStrings().ipcCallFailed) - return { ok: false, error: errMsg, ...extractIpcErrorMeta(raw), ...extractIpcErrorMeta(errObj) } - } - - const firstLayer = 'data' in raw && raw.data !== undefined ? raw.data : raw - if (firstLayer && typeof firstLayer === 'object' && !Array.isArray(firstLayer)) { - if (firstLayer.success === false) { - const errObj = firstLayer.error - const errMsg = - typeof errObj === 'object' && errObj !== null - ? String(errObj.message || errObj.code || JSON.stringify(errObj)) - : String(errObj || ipcStrings().ipcInnerFailed) - return { ok: false, error: errMsg, ...extractIpcErrorMeta(firstLayer), ...extractIpcErrorMeta(errObj) } - } - if ('data' in firstLayer && firstLayer.data !== undefined) { - return { ok: true, data: normalizeMethodResult(method, firstLayer.data) } - } - } - - return { ok: true, data: normalizeMethodResult(method, firstLayer) } -} - -/** - * 调用 Electron Preload Transport 方法(自动封装合法的 alphanumeric messageId 与双层解包) - */ -export async function callHostTransport( - method: string, - params: Record = {}, - hostOverride?: DynamicBridge -): Promise<{ ok: boolean; data?: T; error?: string; errorCode?: string; errorDetails?: Record }> { - const normalizedParams = normalizeMethodParams(method, params) - - // 1. 测试注入的 hostOverride 优先 - if (hostOverride) { - if (typeof hostOverride[method] === 'function') { - try { - const res = await hostOverride[method](normalizedParams) - const unwrapped = unwrapTransportResponse(method, res) - return unwrapped as { ok: boolean; data?: T; error?: string; errorCode?: string; errorDetails?: Record } - } catch (err: DynamicBridge) { - return { ok: false, error: err instanceof Error ? err.message : String(err), ...extractIpcErrorMeta(err) } - } - } - if (typeof hostOverride?.transport?.call === 'function') { - try { - const res = await hostOverride.transport.call(method, normalizedParams) - const unwrapped = unwrapTransportResponse(method, res) - return unwrapped as { ok: boolean; data?: T; error?: string; errorCode?: string; errorDetails?: Record } - } catch (err: DynamicBridge) { - return { ok: false, error: err instanceof Error ? err.message : String(err), ...extractIpcErrorMeta(err) } - } - } - } - - if (typeof window === 'undefined') { - return { ok: false, error: 'NO_WINDOW_ENV', errorCode: 'NO_WINDOW_ENV' } - } - - const w = window as DynamicBridge - const methods = w.__ztoolsElectron?.transport?.methods || w.ztools?.transport?.methods - const fn = methods?.[method] - - if (typeof fn === 'function') { - try { - const messageId = nextMessageId(method.replace(/[^A-Za-z0-9_]/g, '_').slice(0, 24)) - const raw = await fn({ messageId, params: normalizedParams }) - return unwrapTransportResponse(method, raw) as { ok: boolean; data?: T; error?: string; errorCode?: string; errorDetails?: Record } - } catch (err: DynamicBridge) { - return { ok: false, error: err instanceof Error ? err.message : String(err), ...extractIpcErrorMeta(err) } - } - } - - if (typeof w.ztools?.transport?.call === 'function') { - try { - const raw = await w.ztools.transport.call(method, normalizedParams) - return unwrapTransportResponse(method, raw) as { ok: boolean; data?: T; error?: string; errorCode?: string; errorDetails?: Record } - } catch (err: DynamicBridge) { - return { ok: false, error: err instanceof Error ? err.message : String(err), ...extractIpcErrorMeta(err) } - } - } - - return { ok: false, error: `METHOD_NOT_AVAILABLE: ${method}`, errorCode: 'METHOD_NOT_AVAILABLE' } -} - -export interface RealDiskDriveInfo { - drive: string - totalBytes: number - usedBytes: number - availableBytes: number - usagePercent: number -} - -/** - * 探测本机全部真实挂载磁盘分区 (C:\ ~ Z:\ 或 macOS/POSIX 挂载点 '/') - */ -export async function probeRealDiskDrives( - candidateLetters: string[] = ['C', 'D', 'E', 'F', 'G'], - hostOverride?: DynamicBridge -): Promise { - const drives: RealDiskDriveInfo[] = [] - const results = await Promise.all( - candidateLetters.map(async (letter) => { - const raw = String(letter || '').trim() - const isPosix = raw.startsWith('/') - const drivePath = isPosix ? raw : `${raw.replace(/:\\?$/, '').toUpperCase()}:\\` - const res = await callHostTransport<{ - total: number - used: number - available: number - free?: number - percent: number - }>('system_get_disk_usage', { drive: drivePath }, hostOverride) - if (res.ok && res.data && typeof res.data.total === 'number' && res.data.total > 0) { - const availableBytes = - typeof res.data.available === 'number' - ? res.data.available - : typeof res.data.free === 'number' - ? res.data.free - : Math.max(0, res.data.total - res.data.used) - return { - drive: isPosix ? raw : `${raw.replace(/:\\?$/, '').toUpperCase()}:`, - totalBytes: res.data.total, - usedBytes: res.data.used, - availableBytes, - usagePercent: res.data.percent - } - } - return null - }) - ) - - for (const item of results) { - if (item) drives.push(item) - } - - if (drives.length === 0 && !candidateLetters.includes('/')) { - const posixRes = await callHostTransport<{ - total: number - used: number - available: number - free?: number - percent: number - }>('system_get_disk_usage', { drive: '/' }, hostOverride) - if (posixRes.ok && posixRes.data && typeof posixRes.data.total === 'number' && posixRes.data.total > 0) { - const availableBytes = - typeof posixRes.data.available === 'number' - ? posixRes.data.available - : typeof posixRes.data.free === 'number' - ? posixRes.data.free - : Math.max(0, posixRes.data.total - posixRes.data.used) - drives.push({ - drive: '/', - totalBytes: posixRes.data.total, - usedBytes: posixRes.data.used, - availableBytes, - usagePercent: posixRes.data.percent - }) - } - } - - return drives -} - -/** - * 获取本机真实系统特殊路径(支持 home 派生标准子目录兜底,自动兼容 Windows 与 macOS/POSIX) - */ -export async function getRealSystemPath( - name: 'home' | 'appData' | 'userData' | 'desktop' | 'documents' | 'downloads' | 'music' | 'pictures' | 'videos' | 'temp' | 'cache', - hostOverride?: DynamicBridge -): Promise { - const res = await callHostTransport('system_get_path', { name }, hostOverride) - if (res.ok && res.data) { - if (typeof res.data === 'string' && res.data.trim().length > 0) { - return res.data.trim() - } - if (typeof res.data.path === 'string' && res.data.path.trim().length > 0) { - return res.data.path.trim() - } - } - - if (name !== 'home') { - const home = await getRealSystemPath('home', hostOverride) - if (home) { - const isPosix = home.startsWith('/') - const subMap: Record = isPosix - ? { - desktop: `${home}/Desktop`, - documents: `${home}/Documents`, - downloads: `${home}/Downloads`, - music: `${home}/Music`, - pictures: `${home}/Pictures`, - videos: `${home}/Videos`, - appData: `${home}/Library/Application Support`, - userData: `${home}/Library/Application Support/ZTools`, - temp: '/tmp', - cache: `${home}/Library/Caches` - } - : { - desktop: `${home}\\Desktop`, - documents: `${home}\\Documents`, - downloads: `${home}\\Downloads`, - music: `${home}\\Music`, - pictures: `${home}\\Pictures`, - videos: `${home}\\Videos`, - appData: `${home}\\AppData\\Roaming`, - userData: `${home}\\AppData\\Roaming\\ZTools`, - temp: `${home}\\AppData\\Local\\Temp`, - cache: `${home}\\AppData\\Local` - } - if (subMap[name]) return subMap[name] - } - } - - return '' -} - -export type RealDriveUsageInfo = RealDiskDriveInfo - -export interface RealIndexedFileEntry { - name: string - path: string - ext: string - isDir: boolean - isDirectory: boolean - size: number - sizeBytes: number - mtime: number - mtimeMs: number - lastModifiedMs: number -} - -export interface RealDirectorySubdirSummary { - name: string - path: string - fileCount: number - totalBytes: number - mtime: number - /** 体积不是完整统计(宿主扫描截断且独立统计超时 / 无权限),totalBytes 只是下限 */ - approximate?: boolean -} - -export interface RealDirectoryScanResult extends Iterable { - files: RealIndexedFileEntry[] - totalFiles: number - fileCount: number - totalBytes: number - subdirs: RealDirectorySubdirSummary[] - /** 宿主扫描达到条目上限后停止:files / totalFiles 只是已遍历部分的抽样 */ - truncated?: boolean - /** totalBytes 为近似值(下限) */ - approximate?: boolean - /** 宿主实际遍历的条目数 */ - visitedEntries?: number - /** 读取失败的真实原因;已有文件仍可使用,但不能当作完整结果。 */ - error?: string -} - -interface ScanResultMeta { - truncated?: boolean - approximate?: boolean - visitedEntries?: number -} - -export interface ScanDirectoryTreeOptions { - maxDepth?: number - maxFiles?: number - collectTopN?: number - filterExt?: RegExp - hostOverride?: DynamicBridge -} - -function extractFileExt(fileNameOrPath: string): string { - const base = String(fileNameOrPath || '').split(/[\\/]/).pop() || '' - const dotIdx = base.lastIndexOf('.') - return dotIdx > 0 ? base.slice(dotIdx).toLowerCase() : '' -} - -function normalizeIndexedFileEntry(f: DynamicBridge): RealIndexedFileEntry { - const p = String(f?.path || '') - const name = String(f?.name || p.split(/[\\/]/).pop() || '') - const sz = Number(f?.size ?? f?.sizeBytes ?? 0) - const isDir = Boolean(f?.is_dir || f?.isDir || f?.isDirectory) - const rawMtime = Number(f?.mtime ?? f?.mtimeMs ?? 0) - const mtimeMs = rawMtime > 1e11 ? rawMtime : rawMtime > 0 ? rawMtime * 1000 : Date.now() - const mtimeSec = rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime - if (p && sz >= 0) realFileSizeCache.set(p, sz) - return { - name, - path: p, - ext: extractFileExt(name || p), - isDir, - isDirectory: isDir, - size: sz, - sizeBytes: sz, - mtime: mtimeSec, - mtimeMs, - lastModifiedMs: mtimeMs - } -} - -function makeScanResult( - files: RealIndexedFileEntry[], - totalFiles: number, - totalBytes: number, - subdirs: RealDirectorySubdirSummary[], - meta: ScanResultMeta = {} -): RealDirectoryScanResult { - return { - files, - totalFiles, - fileCount: totalFiles, - totalBytes, - subdirs, - ...(meta.truncated ? { truncated: true } : {}), - ...(meta.approximate ? { approximate: true } : {}), - ...(typeof meta.visitedEntries === 'number' ? { visitedEntries: meta.visitedEntries } : {}), - [Symbol.iterator]() { - return files[Symbol.iterator]() - } - } -} - -/** - * 调用客户端的原生文件索引组件 (ztools-indexer) 检索文件 - */ -export async function searchRealIndexedFiles( - query: string, - limit = 40, - hostOverride?: DynamicBridge -): Promise { - if (!query || !query.trim()) return [] - const q = query.trim() - const safeLimit = Math.min(200, Math.max(1, Math.floor(limit || 40))) - - try { - const res = await callHostTransport<{ files?: DynamicBridge[] }>( - 'system_search_files', - { query: q, limit: safeLimit }, - hostOverride - ) - if (res.ok && res.data && Array.isArray(res.data.files)) { - return res.data.files.map(normalizeIndexedFileEntry) - } - - if (!hostOverride && typeof window !== 'undefined') { - const w = window as DynamicBridge - if (typeof w.__ztoolsLauncher?.searchFiles === 'function') { - const rawOuter = await w.__ztoolsLauncher.searchFiles(q, safeLimit) - const raw = rawOuter && typeof rawOuter === 'object' && 'data' in rawOuter && rawOuter.data ? rawOuter.data : rawOuter - if (raw && Array.isArray(raw.files)) { - return raw.files.map(normalizeIndexedFileEntry) - } - } - } - } catch { - // ignore - } - return [] -} - -/** - * 深度扫描指定真实物理目录树(支持符号链接穿透,如 AppData\Roaming\Tencent -> D:\Local\Roaming\Tencent) - * 返回该目录下 Top 文件列表、全树真实文件总数、全树真实总字节数与一级子目录汇总 - */ -export async function scanRealDirectoryTree( - dirPath: string, - limitOrOptions: number | ScanDirectoryTreeOptions = 160, - hostOverrideArg?: DynamicBridge -): Promise { - const result = await scanDirectoryTreeWithError(dirPath, limitOrOptions, hostOverrideArg) - return result.error ? { ...result.scan, error: result.error } : result.scan -} - -/** 一次界面扫描的错误汇总;多个目录并行扫描时保留可读目录的结果。 */ -export function createDirectoryScanner(hostOverride?: DynamicBridge) { - const failures = new Map() - return { - async scan(dir: string, options: number | ScanDirectoryTreeOptions = 160) { - const result = await scanRealDirectoryTree(dir, options, hostOverride) - const error = result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') - if (error) failures.set(dir, error) - else failures.delete(dir) - return result - }, - get error(): string | undefined { - if (!failures.size) return undefined - const s = ipcStrings() - const details = [...failures].slice(0, 3).map(([dir, error]) => `${dir}${s.dirErrorColon}${error}`).join(s.dirEntrySep) - return s.dirReadFailed(details, Math.max(0, failures.size - 3)) - } - } -} - -/** scanRealDirectoryTree 的实现:额外带回读取失败原因(目录不存在 / 为空 / 无权限 / 载荷异常) */ -async function scanDirectoryTreeWithError( - dirPath: string, - limitOrOptions: number | ScanDirectoryTreeOptions, - hostOverrideArg?: DynamicBridge -): Promise<{ scan: RealDirectoryScanResult; error?: string }> { - const empty = makeScanResult([], 0, 0, []) - if (!dirPath || !dirPath.trim()) return { scan: empty, error: 'EMPTY_DIRECTORY_PATH' } - const targetDir = dirPath.trim() - - const opts: ScanDirectoryTreeOptions = - typeof limitOrOptions === 'number' - ? { maxFiles: limitOrOptions, hostOverride: hostOverrideArg } - : { ...limitOrOptions, hostOverride: limitOrOptions?.hostOverride ?? hostOverrideArg } - - const rawLimit = opts.maxFiles ?? opts.collectTopN ?? 160 - const safeLimit = Math.min(200, Math.max(1, Math.floor(rawLimit || 160))) - const hostOverride = opts.hostOverride - const filterExt = opts.filterExt - const dirQuery = `dir:${targetDir}` - - try { - let rawPayload: DynamicBridge = null - const res = await callHostTransport( - 'system_search_files', - { query: dirQuery, limit: safeLimit }, - hostOverride - ) - if (res.ok && res.data) { - rawPayload = res.data - } - if (!rawPayload && !hostOverride && typeof window !== 'undefined') { - const w = window as DynamicBridge - if (typeof w.__ztoolsLauncher?.searchFiles === 'function') { - const rawOuter = await w.__ztoolsLauncher.searchFiles(dirQuery, safeLimit) - rawPayload = - rawOuter && typeof rawOuter === 'object' && 'data' in rawOuter && rawOuter.data - ? rawOuter.data - : rawOuter - } - } - - if ( - rawPayload && - Array.isArray(rawPayload.files) - ) { - let files: RealIndexedFileEntry[] = rawPayload.files.map(normalizeIndexedFileEntry) - if (filterExt instanceof RegExp) { - files = files.filter(f => !f.isDir && (filterExt.test(f.name) || filterExt.test(f.ext))) - // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索目标扩展名 - if (files.length === 0 && !hostOverride) { - const extTokens = (filterExt.source.match(/[a-z0-9]{2,5}/gi) || []) - .filter(t => !['thumbcache', 'iconcache'].includes(t.toLowerCase())) - .slice(0, 4) - // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 - const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() - const extraLists = await Promise.all( - extTokens.map(ext => searchRealIndexedFiles(`.${ext.toLowerCase()}`, 30, hostOverride)) - ) - const seen = new Set() - for (const list of extraLists) { - for (const item of list) { - if (!item.isDir && item.size > 0 && !seen.has(item.path)) { - if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { - seen.add(item.path) - files.push(item) - } - } - } - } - } - } - if (typeof opts.collectTopN === 'number' && opts.collectTopN > 0 && files.length > opts.collectTopN) { - files = files.slice(0, opts.collectTopN) - } - const subdirs: RealDirectorySubdirSummary[] = Array.isArray(rawPayload.subdirs) - ? rawPayload.subdirs.map((s: DynamicBridge) => ({ - name: String(s.name || ''), - path: String(s.path || ''), - fileCount: Number(s.file_count ?? s.fileCount ?? 0), - totalBytes: Number(s.total_bytes ?? s.totalBytes ?? 0), - mtime: Number(s.mtime || 0), - ...(s.approximate === true ? { approximate: true } : {}) - })) - : [] - const computedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) - const totalFilesCount = - filterExt instanceof RegExp ? files.length : Number(rawPayload.total_matches ?? files.length) - const totalBytesCount = - filterExt instanceof RegExp ? computedBytes : Number(rawPayload.total_bytes ?? computedBytes) - const visited = Number(rawPayload.visited_entries) - return { - scan: makeScanResult(files, totalFilesCount, totalBytesCount, subdirs, { - truncated: rawPayload.truncated === true, - approximate: rawPayload.approximate === true, - ...(Number.isFinite(visited) && visited >= 0 ? { visitedEntries: visited } : {}) - }), - ...(typeof rawPayload.scan_error === 'string' && rawPayload.scan_error ? { error: rawPayload.scan_error } : {}) - } - } - - // 深度扫描失败或回执无效时,仅以一级目录读取补回可见结果;不冒充完整目录树。 - const listing = await listDirectoryViaFilesystem(targetDir, hostOverride, { withSizes: true, limit: safeLimit }) - if (listing.ok && listing.entries.length > 0) { - const files: RealIndexedFileEntry[] = [] - let totalBytes = 0 - for (const entry of listing.entries) { - if (filterExt instanceof RegExp && !filterExt.test(entry.name) && !filterExt.test(entry.ext)) { - continue - } - files.push(entry) - totalBytes += entry.isDir ? 0 : entry.size - } - const incomplete = listing.entries.some(entry => entry.isDir) || listing.entries.length >= safeLimit - return { - scan: makeScanResult(files, files.filter(file => !file.isDir).length, totalBytes, [], { approximate: incomplete }), - ...(incomplete ? { error: res.error || ipcStrings().deepScanUnavailable } : {}) - } - } - return listing.ok ? { scan: empty } : { scan: empty, error: listing.error || 'DIRECTORY_READ_FAILED' } - } catch (error) { - return { scan: empty, error: error instanceof Error ? error.message : String(error) } - } -} - - -/** 目录读取不到任何条目(不存在 / 为空 / 无权限)时的错误码 */ -export const DIRECTORY_EMPTY_OR_UNREADABLE = 'DIRECTORY_EMPTY_OR_UNREADABLE' - -export interface RealDirectoryListingResult { - /** 目录内条目的完整路径;读取失败时为空数组 */ - entries: string[] - /** 读取失败或目录为空时的错误码 / 宿主错误信息 */ - error?: string -} - -export interface RealDirectChildrenResult { - /** 目录的直接子项(子目录在前),按路径去重 */ - entries: RealIndexedFileEntry[] - /** 宿主扫描达到条目上限,可能只返回了部分直接子项 */ - partial: boolean - error?: string -} - -function stripTrailingSeparators(p: string): string { - const trimmed = p.replace(/[\\/]+$/, '') - return trimmed || p.slice(0, 1) -} - -function isWindowsStylePath(p: string): boolean { - return /^[A-Za-z]:/.test(p) || p.startsWith('\\\\') || (p.includes('\\') && !p.includes('/')) -} - -function comparablePath(p: string): string { - const stripped = stripTrailingSeparators(String(p || '').trim()) - return isWindowsStylePath(stripped) ? stripped.replace(/\//g, '\\').toLowerCase() : stripped -} - -function parentDirOf(p: string): string { - const stripped = stripTrailingSeparators(String(p || '')) - const idx = Math.max(stripped.lastIndexOf('/'), stripped.lastIndexOf('\\')) - if (idx < 0) return '' - if (idx === 0) return stripped.slice(0, 1) - const parent = stripped.slice(0, idx) - return /^[A-Za-z]:$/.test(parent) ? `${parent}\\` : parent -} - -function isDirectChildPath(dirPath: string, candidate: string): boolean { - if (!candidate) return false - return comparablePath(parentDirOf(candidate)) === comparablePath(dirPath) -} - -function joinChildPath(dirPath: string, name: string): string { - const sep = isWindowsStylePath(dirPath) ? '\\' : '/' - const base = dirPath.replace(/[\\/]+$/, '') - return `${base}${sep}${name}` -} - -/** - * 通过 filesystem_get_directory_contents 读取一级目录(需宿主授权)。 - * 宿主真实返回 { success, files: [{ name, size, isDirectory, lastModified }] }(name 为文件名); - * 兼容旧测试替身返回的完整路径字符串数组。 - */ -async function listDirectoryViaFilesystem( - dirPath: string, - hostOverride: DynamicBridge, - options: { withSizes?: boolean; limit?: number } = {} -): Promise<{ ok: boolean; entries: RealIndexedFileEntry[]; error?: string }> { - const res = await callHostTransport('filesystem_get_directory_contents', { path: dirPath }, hostOverride) - if (!res.ok) return { ok: false, entries: [], error: res.error || 'DIRECTORY_READ_FAILED' } - const data = res.data - const rawList: unknown[] | null = Array.isArray(data) ? data : Array.isArray(data?.files) ? data.files : null - if (!rawList) return { ok: false, entries: [], error: 'INVALID_DIRECTORY_PAYLOAD' } - - const limit = Math.max(1, Math.floor(options.limit ?? 1000)) - const nowSec = Math.floor(Date.now() / 1000) - const entries: RealIndexedFileEntry[] = [] - const seen = new Set() - for (const item of rawList) { - if (entries.length >= limit) break - let entry: RealIndexedFileEntry | null = null - if (typeof item === 'string') { - const itemPath = item.trim() - if (!itemPath) continue - const name = itemPath.split(/[\\/]/).pop() || itemPath - const sz = options.withSizes ? await getRealFileSize(itemPath, hostOverride) : 0 - entry = normalizeIndexedFileEntry({ - name, - path: itemPath, - isDir: sz === 0 && !name.includes('.'), - size: sz, - mtime: nowSec - }) - } else if (item && typeof item === 'object' && typeof (item as DynamicBridge).name === 'string') { - const raw = item as DynamicBridge - const rawName = raw.name.trim() - if (!rawName || rawName === '.' || rawName === '..') continue - // 只接受文件名,或确实位于该目录下的完整路径,拒绝越界路径 - const fullPath = /[\\/]/.test(rawName) ? rawName : joinChildPath(dirPath, rawName) - if (!isDirectChildPath(dirPath, fullPath)) continue - const isDir = Boolean(raw.isDirectory ?? raw.isDir ?? raw.is_dir) - const parsedMtime = Date.parse(String(raw.lastModified || '')) - entry = normalizeIndexedFileEntry({ - name: fullPath.split(/[\\/]/).pop() || rawName, - path: fullPath, - isDir, - size: isDir ? 0 : Math.max(0, Number(raw.size) || 0), - mtime: Number.isFinite(parsedMtime) ? parsedMtime : nowSec - }) - } - if (!entry || seen.has(entry.path)) continue - seen.add(entry.path) - entries.push(entry) - } - return { ok: true, entries } -} - -/** - * 读取真实目录下的条目路径(真实宿主中优先走 dir: 扫描:一级子目录 + 全树 Top-N 大文件),并返回失败原因。 - * 目录不存在、为空或无权限时返回空列表与错误码,绝不用全盘关键词搜索结果冒充目录内容。 - */ -export async function listRealDirectoryContentsResult( - dirPath: string, - hostOverride?: DynamicBridge -): Promise { - if (!dirPath || !dirPath.trim()) return { entries: [], error: 'EMPTY_DIRECTORY_PATH' } - const targetDir = dirPath.trim() - - if (!hostOverride && isRealElectronHost()) { - const tree = await scanRealDirectoryTree(targetDir, 60) - const paths: string[] = [] - for (const s of tree.subdirs) { - if (s.path) paths.push(s.path) - } - for (const f of tree.files) { - if (f.path) paths.push(f.path) - } - if (paths.length > 0) return { entries: Array.from(new Set(paths)) } - } - - const listing = await listDirectoryViaFilesystem(targetDir, hostOverride) - if (!listing.ok) return { entries: [], error: listing.error } - if (listing.entries.length === 0) return { entries: [], error: DIRECTORY_EMPTY_OR_UNREADABLE } - return { entries: listing.entries.map(e => e.path) } -} - -/** - * 读取真实目录下的条目路径(保持旧签名:失败时返回空数组,需要失败原因请用 listRealDirectoryContentsResult) - */ -export async function listRealDirectoryContents( - dirPath: string, - hostOverride?: DynamicBridge -): Promise { - return (await listRealDirectoryContentsResult(dirPath, hostOverride)).entries -} - -/** - * 只列出目录的直接子项(子目录 + 直接位于该目录下的文件),用于文件夹预览、按目录改名等场景。 - * dir: 扫描结果中只保留 subdirs 与父目录等于 dirPath 的文件;扫描达到上限时 partial=true,由插件如实提示「仅显示部分」。 - */ -export async function listDirectChildren( - dirPath: string, - hostOverride?: DynamicBridge -): Promise { - if (!dirPath || !dirPath.trim()) return { entries: [], partial: false, error: 'EMPTY_DIRECTORY_PATH' } - const targetDir = dirPath.trim() - const scanLimit = 200 - const entries: RealIndexedFileEntry[] = [] - const seen = new Set() - const push = (entry: RealIndexedFileEntry) => { - const key = comparablePath(entry.path) - if (!entry.path || seen.has(key)) return - seen.add(key) - entries.push(entry) - } - - const { scan: tree, error } = await scanDirectoryTreeWithError(targetDir, { maxFiles: scanLimit, hostOverride }) - for (const s of tree.subdirs) { - if (!s.path || !isDirectChildPath(targetDir, s.path)) continue - push( - normalizeIndexedFileEntry({ - name: s.name || s.path.split(/[\\/]/).pop(), - path: s.path, - isDir: true, - size: s.totalBytes, - mtime: s.mtime - }) - ) - } - let directFileCount = 0 - for (const f of tree.files) { - if (!isDirectChildPath(targetDir, f.path)) continue - directFileCount++ - push(f) - } - // 宿主 total_matches 是全树文件数、subdirs[].file_count 是各子目录全树文件数,差值即直接子文件数; - // 拿到的直接子文件少于它就说明被 Top-N 截断了。计数不可用时按是否达到扫描上限判断 - const expectedDirectFiles = tree.totalFiles - tree.subdirs.reduce((sum, d) => sum + (Number(d.fileCount) || 0), 0) - const partial = - Number.isFinite(expectedDirectFiles) && expectedDirectFiles >= 0 - ? directFileCount < expectedDirectFiles - : tree.files.length >= scanLimit - if (entries.length > 0) { - return { entries, partial } - } - - if (tree.files.length > 0) { - // dir: 扫描只返回了深层文件(直接子文件被 Top-N 截掉),如实标注部分结果 - return { entries: [], partial: true, error: DIRECTORY_EMPTY_OR_UNREADABLE } - } - return { entries: [], partial: false, error: error || DIRECTORY_EMPTY_OR_UNREADABLE } -} - -/** - * 获取真实文件字节大小(优先用扫描结果里的大小,再走 filesystem_get_file_size);读不到时返回 0 - */ -export async function getRealFileSize( - filePath: string, - hostOverride?: DynamicBridge -): Promise { - if (!filePath) return 0 - if (!hostOverride && realFileSizeCache.has(filePath)) { - const cached = realFileSizeCache.get(filePath)! - if (cached > 0) return cached - } - const res = await callHostTransport('filesystem_get_file_size', { path: filePath }, hostOverride) - // 客户端返回 { success, size }(目录时 size 为 -1),旧的测试替身直接返回数字 - const size = typeof res.data === 'number' ? res.data : res.data?.size - if (res.ok && typeof size === 'number' && Number.isFinite(size) && size >= 0) { - realFileSizeCache.set(filePath, size) - return size - } - return 0 -} - -/** - * 在访达 / 资源管理器中定位并高亮文件或目录。 - * 定位失败直接返回 false,不能改用“打开”:对可执行文件那等于运行它。 - */ -export async function showRealItemInFolder( - fullPath: string, - hostOverride?: DynamicBridge -): Promise { - if (!fullPath) return false - const res = await callHostTransport('shell_show_item_in_folder', { fullPath }, hostOverride) - return res.ok -} - -/** - * 使用系统默认程序打开文件或目录 - */ -export async function openRealPath( - fullPath: string, - hostOverride?: DynamicBridge -): Promise { - if (!fullPath) return false - const res = await callHostTransport('shell_open_path', { fullPath }, hostOverride) - return res.ok -} - -/** - * 将真实文件或目录移入系统回收站(安全可恢复删除) - */ -export async function trashRealItem( - fullPath: string, - hostOverride?: DynamicBridge -): Promise<{ ok: boolean; error?: string; errorCode?: string; errorDetails?: Record }> { - if (!fullPath) return { ok: false, error: ipcStrings().pathEmpty } - const res = await callHostTransport('shell_trash_item', { fullPath }, hostOverride) - return { - ok: res.ok, - error: res.error, - ...(!res.ok && res.errorCode ? { errorCode: res.errorCode } : {}), - ...(!res.ok && res.errorDetails ? { errorDetails: res.errorDetails } : {}) - } -} - -export interface NativeInvocationResult { - ok: boolean - code: number - message: string - data?: T - error?: string - errorCode?: string - errorDetails?: Record -} - -export interface DllCapabilityResponse { - ok: boolean - code: number - data: T | null - message?: string - error?: string - errorCode?: string - errorDetails?: Record - pluginName: string - method: string - fromFallback?: boolean -} - -/** 声明式能力菜单项及其调用回执,供相同宿主协议的插件共用。 */ -export interface CapabilityActionItem { - id: string - title: string - subtitle: string - tag: string - method: string - params: Record -} - -export type PluginInvocationResult = Pick< - DllCapabilityResponse, 'ok' | 'pluginName' | 'method' | 'error' | 'errorCode' | 'errorDetails' | 'fromFallback' -> & { data?: unknown } - -/** 多个原生能力插件共用的参数边界校验;保护目标由各插件按自身业务提供。 */ -export function validateNativeCapabilityPayload( - method: string, - params: unknown, - forbiddenPattern: RegExp, - forbiddenReason: string -): { valid: boolean; error?: string } { - const s = ipcStrings() - if (typeof method !== 'string' || method.trim().length === 0) { - return { valid: false, error: s.invalidMethodEmpty } - } - if (method.length > 128 || !/^[A-Za-z0-9_]+$/.test(method.trim())) { - return { valid: false, error: s.invalidMethodFormat } - } - if (params === null || params === undefined || typeof params !== 'object' || Array.isArray(params)) { - return { valid: false, error: s.invalidParamsObject } - } - - const record = params as Record - for (const [key, val] of Object.entries(record)) { - if (typeof val === 'string') { - if (val.length > 4096) { - return { valid: false, error: s.paramTooLong(key) } - } - if (forbiddenPattern.test(val)) { - return { valid: false, error: `SECURITY_INTERCEPTED: ${forbiddenReason}` } - } - } else if (typeof val === 'number') { - if (!Number.isFinite(val) || val < -1000 || val > 100_000_000) { - return { valid: false, error: s.paramOutOfRange(key) } - } - } - } - - return { valid: true } -} - -export async function invokeDllPluginCapability( - pluginName: string, - method: string, - params: Record = {}, - hostBridge?: DynamicBridge, - offlineFallback?: () => T | Promise -): Promise> { - const s = ipcStrings() - if (!method || typeof method !== 'string' || method.trim().length === 0) { - return { - ok: false, - code: -1, - data: null, - message: s.methodParamEmpty, - error: s.invalidMethodType, - pluginName, - method: String(method || '') - } - } - - const trimmedMethod = method.trim() - - const unwrapDllRawPayload = (raw: unknown, unwrapDataProperty: boolean): DllCapabilityResponse => { - let parsed: DynamicBridge = raw - if (typeof raw === 'string') { - try { - parsed = JSON.parse(raw) - } catch { - throw new Error(s.malformedDllResponse) - } - } - if (parsed && typeof parsed === 'object') { - if ('error' in parsed && parsed.error !== undefined && parsed.error !== null && parsed.error !== '') { - const errMsg = `DLL_ERROR: ${String(parsed.error)}` - return { - ok: false, - code: typeof parsed.code === 'number' ? parsed.code : -1, - data: null, - message: errMsg, - error: errMsg, - ...extractIpcErrorMeta(parsed), - ...extractIpcErrorMeta(parsed.error), - pluginName, - method: trimmedMethod, - fromFallback: false - } - } - if ('ok' in parsed && parsed.ok === false) { - const errMsg = `DLL_ERROR: ${String(parsed.error || parsed.message || s.unknownDllError)}` - return { - ok: false, - code: typeof parsed.code === 'number' ? parsed.code : -1, - data: null, - message: errMsg, - error: errMsg, - ...extractIpcErrorMeta(parsed), - ...extractIpcErrorMeta(parsed.error), - pluginName, - method: trimmedMethod, - fromFallback: false - } - } - const dataPayload = unwrapDataProperty && 'data' in parsed && parsed.data !== undefined ? parsed.data : parsed - return { - ok: true, - code: typeof parsed.code === 'number' ? parsed.code : 0, - data: dataPayload as T, - message: typeof parsed.message === 'string' ? parsed.message : undefined, - pluginName, - method: trimmedMethod, - fromFallback: false - } - } - return { - ok: true, - code: 0, - data: (parsed ?? null) as T, - pluginName, - method: trimmedMethod, - fromFallback: false - } - } - - const wrapCaughtDllError = (err: unknown): DllCapabilityResponse => { - const message = err instanceof Error ? err.message : String(err) - if (message.startsWith('MALFORMED_DLL_RESPONSE:')) { - throw err - } - const errMsg = `NATIVE_CALL_FAILED: ${message}` - return { - ok: false, - code: -1, - data: null, - message: errMsg, - error: errMsg, - ...extractIpcErrorMeta(err), - pluginName, - method: trimmedMethod, - fromFallback: false - } - } - - if (hostBridge && typeof hostBridge.invokeNative === 'function') { - try { - const raw = await hostBridge.invokeNative(pluginName, trimmedMethod, params) - return unwrapDllRawPayload(raw, true) - } catch (err: unknown) { - return wrapCaughtDllError(err) - } - } - - const runtimeHost = (hostBridge ?? (globalThis as Record).ztools) as - | { dllplugin?: { call?: (plugin: string, fn: string, payload: unknown) => Promise | unknown } } - | undefined - - const callFn = runtimeHost?.dllplugin?.call - if (typeof callFn === 'function') { - try { - const raw = await callFn.call(runtimeHost?.dllplugin, pluginName, trimmedMethod, params) - return unwrapDllRawPayload(raw, false) - } catch (err: unknown) { - return wrapCaughtDllError(err) - } - } - - const ipcRes = await callHostTransport( - 'dllplugin_call', - { - plugin: pluginName, - func: trimmedMethod, - params - }, - hostBridge - ) - - if (ipcRes.ok && ipcRes.data !== undefined && ipcRes.data !== null) { - return unwrapDllRawPayload(ipcRes.data, false) - } - - const isExplicitTransportFailure = - typeof ipcRes.error === 'string' && - ipcRes.error.length > 0 && - ipcRes.error !== 'NO_WINDOW_ENV' && - !ipcRes.error.startsWith('METHOD_NOT_AVAILABLE:') - - if ( - isRealElectronHost(hostBridge) || - isRealElectronHost() || - Boolean((hostBridge as DynamicBridge)?.__isRealHost) || - isExplicitTransportFailure - ) { - const errMsg = - ipcRes.error || s.hostIpcFailed(pluginName, trimmedMethod) - return { - ok: false, - code: -1, - data: null, - message: errMsg, - error: errMsg, - ...(ipcRes.errorCode ? { errorCode: ipcRes.errorCode } : {}), - ...(ipcRes.errorDetails ? { errorDetails: ipcRes.errorDetails } : {}), - pluginName, - method: trimmedMethod, - fromFallback: false - } - } - - if (typeof offlineFallback === 'function') { - const fallbackData = await offlineFallback() - return { - ok: true, - code: 0, - data: fallbackData, - pluginName, - method: trimmedMethod, - fromFallback: true - } - } - - const unavailableMsg = s.hostUnavailable(pluginName, trimmedMethod) - return { - ok: false, - code: -1, - data: null, - message: unavailableMsg, - error: unavailableMsg, - ...(ipcRes.errorCode ? { errorCode: ipcRes.errorCode } : {}), - ...(ipcRes.errorDetails ? { errorDetails: ipcRes.errorDetails } : {}), - pluginName, - method: trimmedMethod, - fromFallback: true - } -} - -export function formatBytes(bytes: number, decimals = 1): string { - const num = Number(bytes) - if (!Number.isFinite(num) || num <= 0) return '0 B' - if (num < 1024) return `${Math.round(num)} B` - const units = ['B', 'KB', 'MB', 'GB', 'TB'] - let val = num - let idx = 0 - while (val >= 1024 && idx < units.length - 1) { - val /= 1024 - idx += 1 - } - const safeDecimals = Math.max(0, Math.floor(decimals)) - return `${val >= 100 ? val.toFixed(0) : val.toFixed(safeDecimals)} ${units[idx]}` -} - -export function joinWinPath(...segments: string[]): string { - return segments - .filter(s => typeof s === 'string' && s.trim().length > 0) - .map((s, i) => (i === 0 ? s.replace(/[\\/]+$/, '') : s.replace(/^[\\/]+|[\\/]+$/g, ''))) - .join('\\') -} - -export interface RealEnvPaths { - home: string - userProfile: string - appData: string - localAppData: string - temp: string - downloads: string - documents: string - desktop: string - pictures: string - videos: string - music: string -} - -export async function getRealEnvPaths(hostOverride?: DynamicBridge): Promise { - const [homeRaw, appData, downloads, documents, desktop, pictures, videos, music] = await Promise.all([ - getRealSystemPath('home', hostOverride), - getRealSystemPath('appData', hostOverride), - getRealSystemPath('downloads', hostOverride), - getRealSystemPath('documents', hostOverride), - getRealSystemPath('desktop', hostOverride), - getRealSystemPath('pictures', hostOverride), - getRealSystemPath('videos', hostOverride), - getRealSystemPath('music', hostOverride) - ]) - const home = homeRaw || 'C:\\Users\\Default' - const isPosix = home.startsWith('/') - const tempRes = hostOverride ? await getRealSystemPath('temp', hostOverride) : '' - if (isPosix) { - return { - home, - userProfile: home, - appData: appData || `${home}/Library/Application Support`, - localAppData: `${home}/Library/Application Support`, - temp: tempRes || '/tmp', - downloads: downloads || `${home}/Downloads`, - documents: documents || `${home}/Documents`, - desktop: desktop || `${home}/Desktop`, - pictures: pictures || `${home}/Pictures`, - videos: videos || `${home}/Videos`, - music: music || `${home}/Music` - } - } - return { - home, - userProfile: home, - appData: appData || `${home}\\AppData\\Roaming`, - localAppData: `${home}\\AppData\\Local`, - temp: tempRes || `${home}\\AppData\\Local\\Temp`, - downloads: downloads || `${home}\\Downloads`, - documents: documents || `${home}\\Documents`, - desktop: desktop || `${home}\\Desktop`, - pictures: pictures || `${home}\\Pictures`, - videos: videos || `${home}\\Videos`, - music: music || `${home}\\Music` - } -} - -export const resolveRealSpecialPaths = getRealEnvPaths - -export async function readRealDirectory( - dirPath: string, - hostOverride?: DynamicBridge -): Promise { - if (!dirPath) return [] - const tree = await scanRealDirectoryTree(dirPath, { maxFiles: 120, hostOverride }) - const entries: RealIndexedFileEntry[] = [] - for (const s of tree.subdirs) { - entries.push( - normalizeIndexedFileEntry({ - name: s.name, - path: s.path, - isDir: true, - isDirectory: true, - size: s.totalBytes, - mtime: s.mtime - }) - ) - } - for (const f of tree.files) { - entries.push(f) - } - // scanRealDirectoryTree 已在 dir: 扫描无结果时退回一级目录读取;仍为空即目录不存在 / 为空 / 无权限,如实返回空列表 - return entries -} - -export async function moveRealFilesToTrash( - paths: string[], - hostOverride?: DynamicBridge -): Promise<{ - ok: boolean - trashedCount: number - deletedCount: number - failedPaths: string[] - error?: string -}> { - let deletedCount = 0 - const failedPaths: string[] = [] - let lastError: string | undefined - for (const p of paths) { - if (!p) continue - const res = await trashRealItem(p, hostOverride) - if (res.ok) { - deletedCount += 1 - } else { - failedPaths.push(p) - if (res.error) lastError = res.error - } - } - return { - ok: deletedCount > 0 || paths.length === 0, - trashedCount: deletedCount, - deletedCount, - failedPaths, - error: lastError - } -} - -const CAPABILITY_TO_PLUGIN_MAP: Record = { - 'mover.relocateWithJunction': { plugin: 'MoverPlugin', func: 'relocateWithJunction' }, - 'mover.scanCandidates': { plugin: 'MoverPlugin', func: 'scanCandidates' }, - 'recovery.restoreFile': { plugin: 'DataRecoveryPlugin', func: 'restoreFile' }, - 'recovery.scanDeletedFiles': { plugin: 'DataRecoveryPlugin', func: 'scanDeletedFiles' }, - 'shredder.secureWipeFile': { plugin: 'ShredderPlugin', func: 'secureWipeFile' }, - 'shredder.scanCandidates': { plugin: 'ShredderPlugin', func: 'scanCandidates' }, - 'backup.createSnapshotArchive': { plugin: 'SystemBackupPlugin', func: 'createSnapshotArchive' }, - 'backup.restoreSnapshotArchive': { plugin: 'SystemBackupPlugin', func: 'restoreSnapshotArchive' }, - 'backup.scanSnapshots': { plugin: 'SystemBackupPlugin', func: 'scanSnapshots' }, - 'sqlite.execute': { plugin: 'SqlitePlugin', func: 'execute' }, - 'sqlite.query': { plugin: 'SqlitePlugin', func: 'executeQuery' }, - 'sqlite.inspectWorkspace': { plugin: 'SqlitePlugin', func: 'inspectWorkspace' } -} - -export async function invokeHostCapability( - capability: string, - params: Record = {}, - hostOverride?: DynamicBridge -): Promise> { - const normalizedMethod = capability.replace(/\./g, '_') - - // 若测试显式注入了对应 normalizedMethod 的 mock 函数,优先调用测试桩 - if (hostOverride && typeof hostOverride[normalizedMethod] === 'function') { - const mockRes = await callHostTransport(normalizedMethod, params, hostOverride) - return { - ok: mockRes.ok, - code: mockRes.ok ? 0 : -1, - message: mockRes.ok ? 'OK' : mockRes.error || ipcStrings().callFailed, - data: mockRes.data, - error: mockRes.error, - ...(!mockRes.ok && mockRes.errorCode ? { errorCode: mockRes.errorCode } : {}), - ...(!mockRes.ok && mockRes.errorDetails ? { errorDetails: mockRes.errorDetails } : {}) - } - } - - if (capability === 'system.info') { - const drives = await probeRealDiskDrives(['C', 'D', 'E', 'F'], hostOverride) - return { - ok: true, - code: 0, - message: 'OK', - data: { - storage: drives.map(d => ({ - mount: d.drive, - fs: d.drive, - size: d.totalBytes, - total: d.totalBytes, - used: d.usedBytes, - available: d.availableBytes, - free: d.availableBytes, - percent: d.usagePercent - })) - } as unknown as T - } - } - if (capability === 'filesystem.deleteItem') { - const targetPath = String(params.path || params.fullPath || '') - const tr = await trashRealItem(targetPath, hostOverride) - const s = ipcStrings() - return { - ok: tr.ok, - code: tr.ok ? 0 : -1, - message: tr.ok ? s.movedToTrash : tr.error || s.deleteFailed, - error: tr.error, - ...(!tr.ok && tr.errorCode ? { errorCode: tr.errorCode } : {}), - ...(!tr.ok && tr.errorDetails ? { errorDetails: tr.errorDetails } : {}) - } - } - if (capability === 'system.showItemInFolder') { - const targetPath = String(params.path || params.fullPath || '') - const s = ipcStrings() - if (!targetPath) { - return { ok: false, code: -1, message: s.revealFailed } - } - const res = await callHostTransport('shell_show_item_in_folder', { fullPath: targetPath }, hostOverride) - return { - ok: res.ok, - code: res.ok ? 0 : -1, - message: res.ok ? s.revealedInFolder : res.error || s.revealFailed, - ...(!res.ok && res.error ? { error: res.error } : {}), - ...(!res.ok && res.errorCode ? { errorCode: res.errorCode } : {}), - ...(!res.ok && res.errorDetails ? { errorDetails: res.errorDetails } : {}) - } - } - if (capability === 'filesystem.openItem' || capability === 'system.openUrl') { - const target = String(params.path || params.url || params.fullPath || '') - const method = capability === 'system.openUrl' ? 'shell_open_external' : 'shell_open_path' - const res = await callHostTransport( - method, - capability === 'system.openUrl' ? { url: target } : { fullPath: target }, - hostOverride - ) - const s = ipcStrings() - return { - ok: res.ok, - code: res.ok ? 0 : -1, - message: res.ok ? s.opened : res.error || s.openFailed, - data: res.data, - error: res.error, - ...(!res.ok && res.errorCode ? { errorCode: res.errorCode } : {}), - ...(!res.ok && res.errorDetails ? { errorDetails: res.errorDetails } : {}) - } - } - - const pluginMapping = CAPABILITY_TO_PLUGIN_MAP[capability] - if (pluginMapping) { - const dllRes = await invokePluginService( - pluginMapping.plugin, - pluginMapping.func, - params, - hostOverride - ) - if (dllRes.ok) return dllRes - if (hostOverride) { - const fallbackMock = await callHostTransport(normalizedMethod, params, hostOverride) - if (fallbackMock.ok) { - return { - ok: true, - code: 0, - message: 'OK', - data: fallbackMock.data - } - } - } - return dllRes - } - - const res = await callHostTransport(normalizedMethod, params, hostOverride) - return { - ok: res.ok, - code: res.ok ? 0 : -1, - message: res.ok ? 'OK' : res.error || ipcStrings().callFailed, - data: res.data, - error: res.error, - ...(!res.ok && res.errorCode ? { errorCode: res.errorCode } : {}), - ...(!res.ok && res.errorDetails ? { errorDetails: res.errorDetails } : {}) - } -} - -export async function invokePluginService( - pluginName: string, - action: string, - params: Record = {}, - hostOverride?: DynamicBridge -): Promise> { - const s = ipcStrings() - // 1. 若测试注入了专门拦截 plugin_invoke 的 mock,支持调用 - if (hostOverride && typeof hostOverride.plugin_invoke === 'function') { - const mockRes = await callHostTransport( - 'plugin_invoke', - { plugin: pluginName, action, params }, - hostOverride - ) - return { - ok: mockRes.ok, - code: mockRes.ok ? 0 : -1, - message: mockRes.ok ? 'OK' : mockRes.error || s.pluginCallNotReady, - data: mockRes.data, - error: mockRes.error, - ...(!mockRes.ok && mockRes.errorCode ? { errorCode: mockRes.errorCode } : {}), - ...(!mockRes.ok && mockRes.errorDetails ? { errorDetails: mockRes.errorDetails } : {}) - } - } - - // 2. 优先走真实 Electron IPC 的 dllplugin_call 通道 - const dllRes = await callHostTransport( - 'dllplugin_call', - { plugin: pluginName, func: action, params }, - hostOverride - ) - if (dllRes.ok) { - const inner = dllRes.data - if (inner && typeof inner === 'object' && typeof inner.error === 'string' && inner.error.length > 0 && inner.ok !== true) { - return { - ok: false, - code: -1, - message: inner.error, - error: inner.error, - ...extractIpcErrorMeta(inner) - } - } - return { - ok: true, - code: 0, - message: 'OK', - data: inner as T - } - } - - // 3. 兼容单元测试中通过 transport.call('plugin_invoke') 注入的测试桩 - if (hostOverride) { - const legacyRes = await callHostTransport( - 'plugin_invoke', - { plugin: pluginName, action, params }, - hostOverride - ) - if (legacyRes.ok) { - return { - ok: true, - code: 0, - message: 'OK', - data: legacyRes.data - } - } - } - - // 4. 兼容旧版 globalThis.ztools.dllplugin.call - const g = globalThis as DynamicBridge - if (!hostOverride && typeof g?.ztools?.dllplugin?.call === 'function') { - try { - const raw = await g.ztools.dllplugin.call(pluginName, action, params) - if (raw && typeof raw === 'object' && raw.ok === false) { - return { - ok: false, - code: -1, - message: String(raw.error || s.callFailed), - error: String(raw.error || s.callFailed), - ...extractIpcErrorMeta(raw), - ...extractIpcErrorMeta(raw.error) - } - } - const data = raw && typeof raw === 'object' && 'data' in raw ? raw.data : raw - return { ok: true, code: 0, message: 'OK', data: data as T } - } catch (err: DynamicBridge) { - return { - ok: false, - code: -1, - message: err instanceof Error ? err.message : String(err), - error: err instanceof Error ? err.message : String(err), - ...extractIpcErrorMeta(err) - } - } - } - - return { - ok: false, - code: -1, - message: dllRes.error || s.pluginCallNotReady, - error: dllRes.error || s.pluginCallNotReady, - ...(dllRes.errorCode ? { errorCode: dllRes.errorCode } : {}), - ...(dllRes.errorDetails ? { errorDetails: dllRes.errorDetails } : {}) - } -} - -const SHA256_K = new Uint32Array([ - 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, - 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, - 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, - 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, - 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, - 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, - 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, - 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 -]) - -function rotr32(x: number, n: number): number { - return (x >>> n) | (x << (32 - n)) -} - -/** - * 标准 FIPS 180-4 SHA-256 真实字节摘要算法(返回 64 位小写 Hex) - */ -export function computeRealSha256Hex(input: string | Uint8Array): string { - const bytes = - typeof input === 'string' ? new TextEncoder().encode(input) : new Uint8Array(input || []) - const bitLen = bytes.length * 8 - const padLen = ((bytes.length + 9 + 63) & ~63) - const buf = new Uint8Array(padLen) - buf.set(bytes, 0) - buf[bytes.length] = 0x80 - const view = new DataView(buf.buffer) - view.setUint32(padLen - 8, Math.floor(bitLen / 0x100000000), false) - view.setUint32(padLen - 4, bitLen >>> 0, false) - - let h0 = 0x6a09e667 - let h1 = 0xbb67ae85 - let h2 = 0x3c6ef372 - let h3 = 0xa54ff53a - let h4 = 0x510e527f - let h5 = 0x9b05688c - let h6 = 0x1f83d9ab - let h7 = 0x5be0cd19 - - const w = new Uint32Array(64) - for (let offset = 0; offset < padLen; offset += 64) { - for (let i = 0; i < 16; i++) { - w[i] = view.getUint32(offset + i * 4, false) - } - for (let i = 16; i < 64; i++) { - const s0 = rotr32(w[i - 15], 7) ^ rotr32(w[i - 15], 18) ^ (w[i - 15] >>> 3) - const s1 = rotr32(w[i - 2], 17) ^ rotr32(w[i - 2], 19) ^ (w[i - 2] >>> 10) - w[i] = (w[i - 16] + s0 + w[i - 7] + s1) >>> 0 - } - - let a = h0 - let b = h1 - let c = h2 - let d = h3 - let e = h4 - let f = h5 - let g = h6 - let h = h7 - - for (let i = 0; i < 64; i++) { - const S1 = rotr32(e, 6) ^ rotr32(e, 11) ^ rotr32(e, 25) - const ch = (e & f) ^ (~e & g) - const temp1 = (h + S1 + ch + SHA256_K[i] + w[i]) >>> 0 - const S0 = rotr32(a, 2) ^ rotr32(a, 13) ^ rotr32(a, 22) - const maj = (a & b) ^ (a & c) ^ (b & c) - const temp2 = (S0 + maj) >>> 0 - - h = g - g = f - f = e - e = (d + temp1) >>> 0 - d = c - c = b - b = a - a = (temp1 + temp2) >>> 0 - } - - h0 = (h0 + a) >>> 0 - h1 = (h1 + b) >>> 0 - h2 = (h2 + c) >>> 0 - h3 = (h3 + d) >>> 0 - h4 = (h4 + e) >>> 0 - h5 = (h5 + f) >>> 0 - h6 = (h6 + g) >>> 0 - h7 = (h7 + h) >>> 0 - } - - return [h0, h1, h2, h3, h4, h5, h6, h7] - .map(v => (v >>> 0).toString(16).padStart(8, '0')) - .join('') -} - -/** - * 读取本地文件真实字节并计算标准 SHA-256:宿主 filesearch_sha256(只接受 path 字段)优先,Windows 上再试 FileComparePlugin。 - * 都拿不到时返回空字符串,由调用方提示失败;不再把文件按 UTF-8 文本读出来再算(二进制文件会算出错误的值)。 - */ -export async function computeRealFileSha256( - filePath: string, - hostOverride?: DynamicBridge -): Promise { - if (!filePath || !filePath.trim()) return '' - const target = filePath.trim() - - const shaRes = await callHostTransport('filesearch_sha256', { fullPath: target }, hostOverride) - if (shaRes.ok && shaRes.data) { - const hash = typeof shaRes.data === 'string' ? shaRes.data : String(shaRes.data?.sha256 || shaRes.data?.hash || '') - if (/^[0-9a-f]{64}$/i.test(hash)) return hash.toLowerCase() - } - - const dllRes = await invokePluginService('FileComparePlugin', 'computeFileSha256', { path: target }, hostOverride) - if (dllRes.ok && dllRes.data) { - const hash = typeof dllRes.data === 'string' ? dllRes.data : String(dllRes.data?.sha256 || dllRes.data?.hash || '') - if (/^[0-9a-f]{64}$/i.test(hash)) return hash.toLowerCase() - } - - return '' -} - -export async function readRealClipboardText(hostOverride?: DynamicBridge): Promise { - const res = await callHostTransport('clipboard_read_text', {}, hostOverride) - if (res.ok && res.data !== undefined && res.data !== null) { - if (typeof res.data === 'string') return res.data - if (typeof res.data?.text === 'string') return res.data.text - } - try { - if (typeof navigator !== 'undefined' && navigator.clipboard?.readText) { - return await navigator.clipboard.readText() - } - } catch { - // ignore - } - return '' -} - -export async function writeRealClipboardText(text: string, hostOverride?: DynamicBridge): Promise { - const payload = { text: String(text || '') } - const res = await callHostTransport('clipboard_copy_text', payload, hostOverride) - if (res.ok) return true - const fallbackRes = await callHostTransport('clipboard_write_text', payload, hostOverride) - if (fallbackRes.ok) return true - try { - if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) { - await navigator.clipboard.writeText(String(text || '')) - return true - } - } catch { - // ignore - } - return false -} - -export async function showRealToast( - title: string, - style: 'success' | 'failure' | 'info' = 'info' -): Promise { - try { - const { showToast, Toast } = await import('@ztools/declarative-ui') - await showToast({ - title, - style: - style === 'success' - ? Toast.Style.Success - : style === 'failure' - ? Toast.Style.Failure - : Toast.Style.Animated - }) - } catch { - // ignore - } -} - diff --git a/extensions/invoice-assistant/src/tool-runtime.ts b/extensions/invoice-assistant/src/tool-runtime.ts new file mode 100644 index 00000000..29670de2 --- /dev/null +++ b/extensions/invoice-assistant/src/tool-runtime.ts @@ -0,0 +1,637 @@ +/** + * 宿主薄原语与基础系统能力传输层(唯一权威公共源文件,纯标准 IPC,零原生 DLL 依赖) + * + * 修改本文件后需同步复制到各使用插件的 src/tool-runtime.ts, + * 构建脚本 build-declarative.mjs 会在编译前校验副本与本文件一字不差。 + */ + +import { getHostTransport } from '@ztools/declarative-ui' + +export type ToolCapabilityStatus = 'ready' | 'needs_provisioning' | 'unsupported' + +export interface ToolCapabilityDescriptor { + readonly primitiveId: string + readonly domain: string + readonly summary: string + readonly ipcMethods: readonly string[] + readonly requiredPermissions: readonly string[] + readonly status: ToolCapabilityStatus + readonly optionalExtensions: readonly string[] +} + +export interface ToolRuntimeCapabilitiesSnapshot { + readonly contractVersion: number + readonly platform: 'windows' | 'macos' | 'other' + readonly domains: readonly string[] + readonly capabilities: readonly ToolCapabilityDescriptor[] +} + +export interface ToolRuntimeEnsureResult { + readonly primitiveId: string + readonly status: ToolCapabilityStatus + readonly provisioned: boolean +} + +export interface ToolCapabilitiesEnsureResult { + readonly ok: boolean + readonly status: ToolCapabilityStatus + readonly provisioned: boolean + readonly failedPrimitiveId?: string + readonly error?: string + readonly errorCode?: string + readonly errorDetails?: Record +} + +export interface ToolTaskCancelResult { + readonly taskId: string + readonly cancelled: boolean +} + +export interface ToolPathSlot { + readonly grantId?: string + readonly relativePath?: string + readonly path?: string +} + +export interface ToolProgressEvent { + readonly taskId: string + readonly primitiveId?: string + readonly phase: 'provisioning' | 'running' | 'finalizing' | 'completed' | 'cancelled' | 'failed' + readonly percent?: number + readonly transferredBytes?: number + readonly totalBytes?: number + readonly speedBytesPerSec?: number + readonly stage?: string + readonly errorCode?: string + readonly retryable?: boolean + readonly userAction?: string + readonly message?: string + readonly timestamp?: number +} + +export type MediaTranscodeRunResult = + | { readonly status: 'done'; readonly outputBytes: number; readonly durationMs: number } + | { readonly status: 'cancelled' } + | { + readonly status: 'failed' + readonly error?: string + readonly errorCode?: string + readonly errorDetails?: Record + } + +export interface HostTransportResult { + ok: boolean + data?: T + error?: string + errorCode?: string + errorDetails?: Record +} + +export interface HostCallOptions { + timeoutMs?: number +} + +type TransportMethodFn = (req: { messageId: string; params: Record; timeoutMs?: number }) => Promise + +interface WindowHostBridge { + __ztoolsElectron?: { + transport?: { + methods?: Record + } + } + ztools?: { + transport?: { + methods?: Record + call?: (method: string, params: Record, options?: { timeoutMs?: number }) => Promise + } + events?: { + subscribe?: (event: string) => Promise | void + on?: (event: string, cb: (payload: unknown) => void) => (() => void) | void + off?: (event: string, cb: (payload: unknown) => void) => void + } + } +} + +interface HostOverrideLike { + transport?: { + call?: (method: string, params: Record, options?: { timeoutMs?: number }) => Promise + } + [method: string]: unknown +} + +let reqSeq = 1 + +export function nextMessageId(prefix = 'tool'): string { + reqSeq = (reqSeq + 1) % 1_000_000 + return `${prefix}_${Date.now()}_${reqSeq}` +} + +export function asRecord(value: unknown): Record | null { + return value && typeof value === 'object' && !Array.isArray(value) + ? (value as Record) + : null +} + +function extractErrorMeta(errObj: unknown): { + errorCode?: string + errorDetails?: Record +} { + const rec = asRecord(errObj) + if (!rec) return {} + const errorCode = + typeof rec.errorCode === 'string' && rec.errorCode.trim() + ? rec.errorCode.trim() + : typeof rec.code === 'string' && rec.code.trim() + ? rec.code.trim() + : undefined + const rawDetails = asRecord(rec.errorDetails) ?? asRecord(rec.details) ?? undefined + return { + ...(errorCode ? { errorCode } : {}), + ...(rawDetails ? { errorDetails: rawDetails } : {}) + } +} + +function toTransportError(err: unknown): HostTransportResult { + return { + ok: false, + error: err instanceof Error ? err.message : String(err), + ...extractErrorMeta(err) + } +} + +function buildFailureResult(rec: Record, fallbackMsg: string): HostTransportResult { + const errObj = asRecord(rec.error) + const errMsg = errObj + ? String(errObj.message || errObj.code || JSON.stringify(errObj)) + : String(rec.error || rec.message || fallbackMsg) + return { ok: false, error: errMsg, ...extractErrorMeta(rec), ...extractErrorMeta(errObj) } +} + +function unwrapTransportResponse(raw: unknown): HostTransportResult { + if (raw === null || raw === undefined) { + return { ok: false, error: 'EMPTY_IPC_RESPONSE', errorCode: 'EMPTY_IPC_RESPONSE' } + } + if (typeof raw !== 'object') { + return { ok: true, data: raw as T } + } + const outer = asRecord(raw) + if (!outer) { + return { ok: true, data: raw as T } + } + if (outer.success === false || outer.ok === false) { + return buildFailureResult(outer, 'IPC_CALL_FAILED') + } + + const firstLayer = 'data' in outer && outer.data !== undefined ? outer.data : outer + const inner = asRecord(firstLayer) + if (inner) { + if (inner.success === false || inner.ok === false) { + return buildFailureResult(inner, 'IPC_INNER_FAILED') + } + if ('data' in inner && inner.data !== undefined) { + return { ok: true, data: inner.data as T } + } + } + + return { ok: true, data: firstLayer as T } +} + +/** 判断当前是否处于真实的 ZTools Electron 渲染进程宿主环境 */ +export function isRealElectronHost(hostOverride?: unknown): boolean { + if (hostOverride) return true + if (typeof window === 'undefined') return false + const w = window as unknown as WindowHostBridge + return Boolean( + w.__ztoolsElectron?.transport?.methods || + w.ztools?.transport?.call || + w.ztools?.transport?.methods + ) +} + +/** 统一调用宿主 IPC 传输层(优先测试桩,其次 declarative-ui 宿主通道与 preload 通道) */ +export async function callHostTransport( + method: string, + params: Record = {}, + hostOverride?: unknown, + options?: HostCallOptions +): Promise> { + const override = asRecord(hostOverride) as HostOverrideLike | null + if (override) { + const directFn = override[method] + if (typeof directFn === 'function') { + try { + return unwrapTransportResponse(await (directFn as (p: Record) => Promise)(params)) + } catch (err) { + return toTransportError(err) + } + } + if (typeof override.transport?.call === 'function') { + try { + return unwrapTransportResponse(await override.transport.call(method, params, options)) + } catch (err) { + return toTransportError(err) + } + } + return { ok: false, error: `METHOD_NOT_AVAILABLE: ${method}`, errorCode: 'METHOD_NOT_AVAILABLE' } + } + + // 优先走 declarative-ui 运行时注入的带归属令牌通道 + if (typeof getHostTransport === 'function') { + const transport = getHostTransport() + if (transport) { + try { + const callOpts = typeof options?.timeoutMs === 'number' ? { timeoutMs: options.timeoutMs } : undefined + return unwrapTransportResponse(await transport.call(method, params, callOpts)) + } catch (err) { + return toTransportError(err) + } + } + } + + if (typeof window === 'undefined') { + return { ok: false, error: 'NO_WINDOW_ENV', errorCode: 'NO_WINDOW_ENV' } + } + + const w = window as unknown as WindowHostBridge + const methods = w.__ztoolsElectron?.transport?.methods || w.ztools?.transport?.methods + const fn = methods?.[method] + if (typeof fn === 'function') { + try { + const messageId = nextMessageId(method.replace(/[^A-Za-z0-9_]/g, '_').slice(0, 24)) + const payload = { + messageId, + params, + ...(typeof options?.timeoutMs === 'number' ? { timeoutMs: options.timeoutMs } : {}) + } + return unwrapTransportResponse(await fn(payload)) + } catch (err) { + return toTransportError(err) + } + } + + if (typeof w.ztools?.transport?.call === 'function') { + try { + return unwrapTransportResponse(await w.ztools.transport.call(method, params, options)) + } catch (err) { + return toTransportError(err) + } + } + + return { ok: false, error: `METHOD_NOT_AVAILABLE: ${method}`, errorCode: 'METHOD_NOT_AVAILABLE' } +} + +/** 探测宿主薄原语能力快照(tool_runtime_capabilities) */ +export async function queryRuntimeCapabilities( + hostOverride?: unknown +): Promise> { + const res = await callHostTransport('tool_runtime_capabilities', {}, hostOverride) + if (!res.ok) return res as HostTransportResult + const rec = asRecord(res.data) + if (!rec || !Array.isArray(rec.capabilities)) { + return { + ok: false, + error: 'INVALID_CAPABILITIES_SNAPSHOT', + errorCode: 'INVALID_CAPABILITIES_SNAPSHOT' + } + } + const capabilities: ToolCapabilityDescriptor[] = [] + for (const rawCap of rec.capabilities) { + const cap = asRecord(rawCap) + if (!cap || typeof cap.primitiveId !== 'string') continue + const rawStatus = cap.status + const status: ToolCapabilityStatus = + rawStatus === 'ready' || rawStatus === 'needs_provisioning' || rawStatus === 'unsupported' + ? rawStatus + : 'unsupported' + const optionalExtensions = Array.isArray(cap.optionalExtensions) + ? cap.optionalExtensions.filter((e): e is string => typeof e === 'string' && e.trim().length > 0) + : [] + capabilities.push({ + primitiveId: cap.primitiveId, + domain: typeof cap.domain === 'string' ? cap.domain : '', + summary: typeof cap.summary === 'string' ? cap.summary : '', + ipcMethods: Array.isArray(cap.ipcMethods) ? cap.ipcMethods.filter((m): m is string => typeof m === 'string') : [], + requiredPermissions: Array.isArray(cap.requiredPermissions) + ? cap.requiredPermissions.filter((p): p is string => typeof p === 'string') + : [], + status, + optionalExtensions + }) + } + const platform = + rec.platform === 'windows' || rec.platform === 'macos' || rec.platform === 'other' + ? rec.platform + : 'other' + return { + ok: true, + data: { + contractVersion: typeof rec.contractVersion === 'number' ? rec.contractVersion : 1, + platform, + domains: Array.isArray(rec.domains) ? rec.domains.filter((d): d is string => typeof d === 'string') : [], + capabilities + } + } +} + +export function findCapability( + snapshot: ToolRuntimeCapabilitiesSnapshot | null | undefined, + primitiveId: string +): ToolCapabilityDescriptor | null { + if (!snapshot) return null + return snapshot.capabilities.find((c) => c.primitiveId === primitiveId) ?? null +} + +export function hasCapabilityExtension( + snapshot: ToolRuntimeCapabilitiesSnapshot | null | undefined, + primitiveId: string, + extensionName: string +): boolean { + const cap = findCapability(snapshot, primitiveId) + return Boolean(cap && cap.optionalExtensions.includes(extensionName)) +} + +/** 按需拉取并准备指定薄原语运行组件(tool_runtime_ensure) */ +export async function ensureRuntimeCapability( + primitiveId: string, + hostOverride?: unknown +): Promise> { + return callHostTransport('tool_runtime_ensure', { primitiveId }, hostOverride) +} + +/** 顺序按需准备多个薄原语运行组件,任一项未就绪即中止并聚合 provisioned 标记 */ +export async function ensureRuntimeCapabilities( + primitiveIds: readonly string[], + hostOverride?: unknown +): Promise { + let provisionedAny = false + for (const primitiveId of primitiveIds) { + const res = await ensureRuntimeCapability(primitiveId, hostOverride) + if (!res.ok || !res.data || res.data.status !== 'ready') { + return { + ok: false, + status: res.data?.status ?? 'unsupported', + provisioned: provisionedAny, + failedPrimitiveId: primitiveId, + error: res.error, + errorCode: res.errorCode, + errorDetails: res.errorDetails + } + } + if (res.data.provisioned) provisionedAny = true + } + return { ok: true, status: 'ready', provisioned: provisionedAny } +} + +/** 取消正在执行的宿主薄原语任务(tool_task_cancel) */ +export async function cancelRuntimeTask( + taskId: string, + hostOverride?: unknown +): Promise> { + return callHostTransport('tool_task_cancel', { taskId }, hostOverride) +} + +/** 判断错误码是否表示用户主动取消任务 */ +export function isTaskCancelledCode(errorCode?: string): boolean { + const code = (errorCode || '').trim().toUpperCase() + return code === 'TOOL_TASK_CANCELLED' || code === 'CANCELLED' || code === 'OPERATION_CANCELLED' +} + +/** 执行单个媒体转码任务(tool_media_transcode_run),统一处理取消与产物字节数校验 */ +export async function runMediaTranscodeTask( + payload: Record, + hostOverride?: unknown +): Promise { + const res = await callHostTransport('tool_media_transcode_run', payload, hostOverride) + if (!res.ok) { + if (isTaskCancelledCode(res.errorCode)) { + return { status: 'cancelled' } + } + return { + status: 'failed', + error: res.error, + errorCode: res.errorCode, + errorDetails: res.errorDetails + } + } + const rec = asRecord(res.data) + const outputBytes = Number(rec?.outputBytes) + const durationMs = Number(rec?.durationMs) + if (!Number.isFinite(outputBytes) || outputBytes <= 0) { + return { status: 'failed', error: 'EMPTY_OUTPUT', errorCode: 'EMPTY_OUTPUT' } + } + return { + status: 'done', + outputBytes, + durationMs: Number.isFinite(durationMs) && durationMs >= 0 ? durationMs : 0 + } +} + +/** 订阅宿主推送的 tool_runtime_progress 任务进度事件 */ +export function subscribeRuntimeProgress( + handler: (event: ToolProgressEvent) => void +): () => void { + if (typeof window === 'undefined') return () => undefined + const w = window as unknown as WindowHostBridge + const eventsApi = w.ztools?.events + if (!eventsApi || typeof eventsApi.on !== 'function') return () => undefined + + try { + void eventsApi.subscribe?.('tool_runtime_progress') + } catch (err) { + // 某些测试桩或旧渲染层可能未提供 subscribe,继续注册 on 监听 + void err + } + + const listener = (raw: unknown) => { + const outer = asRecord(raw) + if (!outer) return + const inner = asRecord(outer.payload) ?? outer + if (typeof inner.taskId !== 'string' || typeof inner.phase !== 'string') return + handler(inner as unknown as ToolProgressEvent) + } + + const off = eventsApi.on('tool_runtime_progress', listener) + return () => { + if (typeof off === 'function') { + off() + } else if (typeof eventsApi.off === 'function') { + eventsApi.off('tool_runtime_progress', listener) + } + } +} + +/** 订阅旧版宿主 plugin_files_dropped 拖拽回退事件并返回卸载函数 */ +export function subscribeLegacyFileDrop(onDrop: (envelope: unknown) => void): () => void { + if (typeof window === 'undefined') return () => undefined + const w = window as unknown as WindowHostBridge + const eventsApi = w.ztools?.events + if (!eventsApi || typeof eventsApi.on !== 'function') return () => undefined + + const off = eventsApi.on('plugin_files_dropped', onDrop) + return () => { + if (typeof off === 'function') { + off() + } else if (typeof eventsApi.off === 'function') { + eventsApi.off('plugin_files_dropped', onDrop) + } + } +} + +/** 字节数格式化 */ +export function formatBytes(bytes: number): string { + if (!Number.isFinite(bytes) || bytes < 0) return '0 B' + if (bytes < 1024) return `${Math.round(bytes)} B` + const units = ['KB', 'MB', 'GB', 'TB'] + let value = bytes / 1024 + let idx = 0 + while (value >= 1024 && idx < units.length - 1) { + value /= 1024 + idx += 1 + } + return `${value >= 100 ? value.toFixed(0) : value >= 10 ? value.toFixed(1) : value.toFixed(2)} ${units[idx]}` +} + +/** 字节数格式化别名(兼容 archive-manager 等插件既有导出名) */ +export function formatByteCount(bytes: number): string { + return formatBytes(bytes) +} + +/** 获取系统标准目录路径(支持 Windows 与 macOS) */ +export async function getRealSystemPath( + name: 'home' | 'desktop' | 'documents' | 'downloads' | 'music' | 'pictures' | 'videos' | 'temp', + hostOverride?: unknown +): Promise { + const res = await callHostTransport('system_get_path', { name }, hostOverride) + if (res.ok && res.data) { + if (typeof res.data === 'string' && res.data.trim()) return res.data.trim() + const rec = asRecord(res.data) + if (rec && typeof rec.path === 'string' && rec.path.trim()) return rec.path.trim() + } + return '' +} + +/** 读取剪贴板文本 */ +export async function readRealClipboardText(hostOverride?: unknown): Promise { + const res = await callHostTransport('clipboard_read_text', {}, hostOverride) + if (res.ok && res.data !== undefined && res.data !== null) { + if (typeof res.data === 'string') return res.data + const rec = asRecord(res.data) + if (rec && typeof rec.text === 'string') return rec.text + } + return '' +} + +/** 写入剪贴板文本 */ +export async function writeRealClipboardText(text: string, hostOverride?: unknown): Promise { + const res = await callHostTransport('clipboard_copy_text', { text: String(text || '') }, hostOverride) + return res.ok +} + +/** 在系统文件管理器中显示文件 */ +export async function showRealItemInFolder(fullPath: string, hostOverride?: unknown): Promise { + if (!fullPath) return false + const res = await callHostTransport('shell_show_item_in_folder', { fullPath }, hostOverride) + return res.ok +} + +/** 用系统默认应用打开文件或文件夹 */ +export async function openRealPath(fullPath: string, hostOverride?: unknown): Promise { + if (!fullPath) return false + const res = await callHostTransport('shell_open_path', { fullPath }, hostOverride) + return res.ok +} + +/** 将文件或目录移入系统回收站 */ +export async function trashRealItem(fullPath: string, hostOverride?: unknown): Promise<{ ok: boolean; error?: string }> { + if (!fullPath) return { ok: false, error: 'EMPTY_PATH' } + const res = await callHostTransport('shell_trash_item', { fullPath }, hostOverride) + return res.ok ? { ok: true } : { ok: false, error: res.error } +} + +/** 通过 window_show_open_dialog 选择输出目录(兼容 Windows 与 macOS) */ +export async function pickOutputDirectoryDialog( + options: { title: string; defaultPath?: string }, + hostOverride?: unknown +): Promise<{ canceled: boolean; directoryPath?: string; error?: string; errorCode?: string }> { + const params: Record = { + title: options.title, + properties: ['openDirectory', 'createDirectory'] + } + if (options.defaultPath) params.defaultPath = options.defaultPath + const res = await callHostTransport('window_show_open_dialog', params, hostOverride) + if (!res.ok) { + return { canceled: false, error: res.error || 'OPEN_DIALOG_FAILED', errorCode: res.errorCode } + } + const rec = asRecord(res.data) + if (!rec) return { canceled: false, error: 'INVALID_DIALOG_RESULT' } + if (rec.canceled === true) return { canceled: true } + const firstPath = + (Array.isArray(rec.filePaths) && typeof rec.filePaths[0] === 'string' && rec.filePaths[0].trim()) || + (typeof rec.filePath === 'string' && rec.filePath.trim()) || + (typeof rec.folderPath === 'string' && rec.folderPath.trim()) || + '' + if (!firstPath) return { canceled: false, error: 'NO_DIRECTORY_SELECTED' } + return { canceled: false, directoryPath: firstPath } +} + +/** 通用文件/目录选择对话框(支持自定义 properties 与 filters) */ +export async function openDialogSelectPaths( + options: { + title: string + properties: Array<'openFile' | 'openDirectory' | 'multiSelections' | 'createDirectory'> + filters?: Array<{ name: string; extensions: string[] }> + }, + hostOverride?: unknown +): Promise<{ canceled: boolean; paths: string[]; error?: string }> { + const params: Record = { + title: options.title, + properties: options.properties, + ...(options.filters ? { filters: options.filters } : {}) + } + const res = await callHostTransport('window_show_open_dialog', params, hostOverride) + if (!res.ok) return { canceled: false, paths: [], error: res.error || 'OPEN_DIALOG_FAILED' } + const rec = asRecord(res.data) + if (!rec) return { canceled: false, paths: [], error: 'INVALID_DIALOG_RESPONSE' } + if (rec.canceled === true) return { canceled: true, paths: [] } + const paths = Array.isArray(rec.filePaths) + ? rec.filePaths.filter((p): p is string => typeof p === 'string' && p.trim().length > 0).map((p) => p.trim()) + : typeof rec.filePath === 'string' && rec.filePath.trim() + ? [rec.filePath.trim()] + : [] + return { canceled: false, paths } +} + +/** 选择待归档的源文件或目录列表(多选) */ +export async function pickAnySourcesDialog( + options: { title: string; directories?: boolean }, + hostOverride?: unknown +): Promise<{ canceled: boolean; paths: string[]; error?: string }> { + return openDialogSelectPaths( + { + title: options.title, + properties: options.directories ? ['openDirectory', 'multiSelections'] : ['openFile', 'multiSelections'] + }, + hostOverride + ) +} + +/** 保存归档文件对话框(zip / 7z / tar) */ +export async function pickSaveArchiveDialog( + options: { title: string; defaultPath?: string; format: 'zip' | '7z' | 'tar' }, + hostOverride?: unknown +): Promise<{ canceled: boolean; filePath?: string; error?: string }> { + const ext = options.format === '7z' ? '7z' : options.format === 'tar' ? 'tar' : 'zip' + const params: Record = { + title: options.title, + filters: [{ name: `${ext.toUpperCase()} Archive`, extensions: [ext] }] + } + if (options.defaultPath) params.defaultPath = options.defaultPath + const res = await callHostTransport('window_show_save_dialog', params, hostOverride) + if (!res.ok) return { canceled: false, error: res.error || 'SAVE_DIALOG_FAILED' } + const rec = asRecord(res.data) + if (!rec) return { canceled: false, error: 'INVALID_SAVE_DIALOG' } + if (rec.canceled === true) return { canceled: true } + const filePath = typeof rec.filePath === 'string' ? rec.filePath.trim() : '' + if (!filePath) return { canceled: true } + return { canceled: false, filePath } +} diff --git a/extensions/invoice-assistant/tests/invoice-assistant.host.test.mjs b/extensions/invoice-assistant/tests/invoice-assistant.host.test.mjs index b0196e36..c8959cde 100644 --- a/extensions/invoice-assistant/tests/invoice-assistant.host.test.mjs +++ b/extensions/invoice-assistant/tests/invoice-assistant.host.test.mjs @@ -1,563 +1,191 @@ import test from 'node:test' import assert from 'node:assert/strict' -import { setRuntimeLocale } from '@ztools/declarative-ui' -setRuntimeLocale('zh-CN') import fs from 'node:fs' import path from 'node:path' import { fileURLToPath } from 'node:url' -import * as invoiceAssistant from '../dist/index.js' -import { pickFiles } from '../dist/file-import.js' +import { setRuntimeLocale } from '@ztools/declarative-ui' +import * as invoice from '../dist/index.js' -const __dirname = path.dirname(fileURLToPath(import.meta.url)) +setRuntimeLocale('zh-CN') +const pluginDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..') -async function withRealElectronWindow(handlers, fn) { - const prevWindow = globalThis.window +function makeInvoiceHost() { const calls = [] - const transportMethods = {} - - for (const [channel, impl] of Object.entries(handlers)) { - transportMethods[channel] = async (envelope) => { - const actualParams = - envelope && typeof envelope === 'object' && 'params' in envelope && 'messageId' in envelope - ? envelope.params - : envelope - calls.push({ channel, payload: actualParams }) - return impl(actualParams) - } - } - - globalThis.window = { - __ztoolsElectron: { - transport: { - methods: transportMethods + const xmlBody = ` + + 24312000000048298921 + 2026-09-15 + 上海星巴克咖啡经营有限公司 + 北京某某科技有限公司 + 0.00 + 0.00 + + ` + const ofdXmlBody = ` + + 12345678 + 2026-08-20 + 滴滴出行科技有限公司 + 北京某某科技有限公司 + 58.50 + 1.70 + + ` + const host = { + system_get_path: async () => ({ path: 'C:\\Temp' }), + filesystem_read_file: async ({ path: p }) => { + calls.push({ method: 'filesystem_read_file', path: p }) + if (p.endsWith('empty.xml')) return { content: '' } + if (p.includes('original_invoice.xml')) return { content: ofdXmlBody } + return { content: xmlBody } + }, + tool_archive_list: async (params) => { + calls.push({ method: 'tool_archive_list', params }) + return { + success: true, + data: { + format: 'zip', + encrypted: false, + totalEntries: 2, + totalUncompressedBytes: 512, + entries: [ + { path: 'Doc_0/Attachs/original_invoice.xml', sizeBytes: 400, compressedBytes: 200, isDirectory: false, encrypted: false } + ] + } } - } - } - - try { - return await fn(calls) - } finally { - if (prevWindow === undefined) { - delete globalThis.window - } else { - globalThis.window = prevWindow - } - } -} - -// 固定「现在」,让日期相关断言不随运行日期变化 -const NOW = new Date(2026, 9, 28, 15, 0, 0) -const TODAY = '2026-10-28' - -function completeInvoice(overrides = {}) { - return { - id: 'inv-1', - path: 'D:\\Invoices\\didi_1.pdf', - fileName: 'didi_1.pdf', - extension: '.pdf', - sizeBytes: 120000, - invoiceNo: '24112000000088192011', - issueDate: '2026-10-18', - issueDateNeedsReview: false, - sellerName: '滴滴出行科技有限公司', - buyerName: '上海某某科技有限公司', - buyerTaxId: '91310000XXXXXXXX0X', - totalAmount: 126.5, - taxAmount: 3.68, - netAmount: 122.82, - category: '交通出行', - isDuplicate: false, - isHeaderAbnormal: false, - ...overrides - } -} - -/** 宿主当前识别不到字段时返回的结果:日期填当天、金额填 0、销售方填占位文字、发票号可能是 PDF 内部偏移量 */ -function hostFallbackRaw(overrides = {}) { - return { - path: 'D:\\Invoices\\scan_001.pdf', - fileName: 'scan_001.pdf', - extension: '.pdf', - sizeBytes: 98000, - invoiceNo: '0000000000', - issueDate: TODAY, - sellerName: '未知销售商户', - buyerName: '', - buyerTaxId: '', - totalAmount: 0, - taxAmount: 0, - netAmount: 0, - category: '其他费用', - isHeaderAbnormal: false, - ...overrides - } -} - -test('invoice-assistant host integration: 电子发票四要素解析、查重与抬头预检、重命名模板与 Excel TSV 生成', async () => { - const sampleItems = [ - completeInvoice(), - completeInvoice({ - id: 'inv-2', - path: 'D:\\Invoices\\didi_1_copy.pdf', - fileName: 'didi_1_copy.pdf', - buyerName: '个人(张三)', - buyerTaxId: '' - }) - ] - - const audited = invoiceAssistant.detectInvoiceAnomalies(sampleItems, '上海某某科技有限公司') - assert.equal(audited[0].isDuplicate, false) - assert.equal(audited[0].isHeaderAbnormal, false) - assert.equal(audited[1].isDuplicate, true, '相同发票号的第二张发票必须标记为重复') - assert.equal(audited[1].isHeaderAbnormal, true, '个人抬头或与期望企业抬头不符时必须标记为抬头异常') - - const nameStd = invoiceAssistant.buildTargetInvoiceFileName(audited[0], 'tpl-standard') - assert.equal(nameStd, '[交通出行]_2026-10-18_滴滴出行科技有限公司_126.50元_2011.pdf') - const nameDate = invoiceAssistant.buildTargetInvoiceFileName(audited[0], 'tpl-date-first') - assert.equal(nameDate, '2026-10-18_[交通出行]_126.50元_滴滴出行科技有限公司.pdf') - - const tsv = invoiceAssistant.buildInvoiceTsvTable([audited[0]], 'tpl-standard') - const lines = tsv.split('\n') - assert.equal(lines.length, 2) - assert.ok(lines[0].includes('发票号码\t开票日期\t费用分类')) - assert.ok(lines[1].includes('24112000000088192011\t2026-10-18\t交通出行')) -}) - -test('invoice-assistant beyond happy path: 非法路径拦截、畸形参数校验与宿主导出失败容错', async () => { - await assert.rejects( - () => invoiceAssistant.invokeNativeCapability('', {}), - /INVALID_METHOD/ - ) - await assert.rejects( - () => - invoiceAssistant.invokeNativeCapability('ExportInvoicesCsv', { - outputDir: 'C:\\Windows\\System32\\spool' - }), - /SECURITY_INTERCEPTED/ - ) - await assert.rejects( - () => - invoiceAssistant.invokeNativeCapability('ExportInvoicesCsv', { - outputDir: 'D:\\Invoices\\..\\..\\Windows\\System32' - }), - /SECURITY_INTERCEPTED/ - ) - - await withRealElectronWindow( - { - dllplugin_call: () => ({ - ok: false, - error: 'CSV_WRITE_LOCKED: 报销发票明细汇总表.csv 正被 Excel 占用无法覆盖' - }) }, - async () => { - const res = await invoiceAssistant.invokeNativeCapability('ExportInvoicesCsv', { - files: ['D:\\Invoices\\a.pdf'] - }) - assert.equal(res.ok, false) - assert.match(String(res.error), /CSV_WRITE_LOCKED/) - } - ) -}) - -test('识别不到的字段保持为空并标为未识别:不用当天日期、0 元、占位销售方、全 0 发票号冒充识别结果', () => { - const item = invoiceAssistant.normalizeParsedInvoice(hostFallbackRaw(), 0, NOW) - assert.equal(item.invoiceNo, '', '全 0 的数字不是发票号') - assert.equal(item.issueDate, TODAY) - assert.equal(item.issueDateNeedsReview, true, '与今天相同的日期可能是宿主填入的默认值,必须要求核对') - assert.equal(item.sellerName, '', '占位文字不是销售方') - assert.equal(item.buyerName, '') - assert.equal(item.totalAmount, null, '0 元不能当作识别出的金额') - assert.equal(item.taxAmount, null, '价税合计都没识别到时,税额 0 不可信') - assert.equal(item.netAmount, null) - - const issues = invoiceAssistant.getInvoiceFieldIssues(item) - assert.deepEqual(issues.missing, ['invoiceNo', 'sellerName', 'buyerName', 'totalAmount', 'taxAmount']) - assert.deepEqual(issues.needsReview, ['issueDate']) - assert.equal(invoiceAssistant.isInvoiceComplete(item), false) - assert.equal(invoiceAssistant.isInvoiceSelectable(item), false) - assert.equal( - invoiceAssistant.describeInvoiceIssues(item), - '未识别:发票号码、销售方、购买方、价税合计、税额;开票日期待核对' - ) - - assert.equal(invoiceAssistant.buildTargetInvoiceFileName(item, 'tpl-standard'), null) - const row = invoiceAssistant.buildInvoiceTsvTable([item]).split('\n')[1].split('\t') - assert.deepEqual(row, ['1', '未识别', `${TODAY}(待核对)`, '其他费用', '未识别', '未识别', '未识别', '未识别', '未识别', '']) - assert.match(invoiceAssistant.buildInvoiceSummaryText(item), /发票号码: 未识别/) - assert.equal(invoiceAssistant.formatCurrency(item.totalAmount), '未识别') - assert.equal(invoiceAssistant.formatCurrency(Number.NaN), '未识别') - assert.deepEqual(invoiceAssistant.defaultCheckedInvoiceIds([item]), []) - assert.equal(invoiceAssistant.normalizeParsedInvoice(hostFallbackRaw({ path: '' }), 0, NOW), null) -}) - -test('识别结果规范化:发票号 8 / 20 位、日期合法且不晚于今天、税额不大于价税合计、宿主分类名对应插件分类', () => { - assert.equal(invoiceAssistant.normalizeInvoiceNo('2431 2000 0000 4829 8921'), '24312000000048298921') - assert.equal(invoiceAssistant.normalizeInvoiceNo('01234567'), '01234567') - assert.equal(invoiceAssistant.normalizeInvoiceNo('123456789'), '') - assert.equal(invoiceAssistant.normalizeInvoiceNo('00000000'), '') - assert.equal(invoiceAssistant.normalizeInvoiceNo(undefined), '') - - assert.equal(invoiceAssistant.normalizeIssueDate('2026年10月8日', NOW), '2026-10-08') - assert.equal(invoiceAssistant.normalizeIssueDate('2026/1/5', NOW), '2026-01-05') - assert.equal(invoiceAssistant.normalizeIssueDate('2026-02-30', NOW), '') - assert.equal(invoiceAssistant.normalizeIssueDate('2026-10-29', NOW), '') - assert.equal(invoiceAssistant.normalizeIssueDate('1999-12-31', NOW), '') - assert.equal(invoiceAssistant.normalizeIssueDate('开票日期', NOW), '') - assert.equal(invoiceAssistant.isPossibleFallbackDate('2026-10-27', NOW), false) - - const taxTooLarge = invoiceAssistant.normalizeParsedInvoice( - hostFallbackRaw({ issueDate: '2026-10-01', totalAmount: 50, taxAmount: 80 }), - 0, - NOW - ) - assert.equal(taxTooLarge.totalAmount, 50) - assert.equal(taxTooLarge.taxAmount, null) - assert.equal(taxTooLarge.issueDateNeedsReview, false) - - assert.equal(invoiceAssistant.normalizeInvoiceCategory('差旅交通'), '交通出行') - assert.equal(invoiceAssistant.normalizeInvoiceCategory('酒店住宿'), '差旅住宿') - assert.equal(invoiceAssistant.normalizeInvoiceCategory('办公设备'), '办公采购') - assert.equal(invoiceAssistant.normalizeInvoiceCategory('技术与云服务'), '办公采购') - assert.equal(invoiceAssistant.normalizeInvoiceCategory('餐饮招待'), '餐饮招待') - assert.equal(invoiceAssistant.normalizeInvoiceCategory('火星费用'), '其他费用') - - const train = completeInvoice({ category: '交通出行' }) - const hotel = completeInvoice({ id: 'h', category: '差旅住宿' }) - const meal = completeInvoice({ id: 'm', category: '餐饮招待' }) - assert.deepEqual( - [train, hotel, meal].filter((i) => invoiceAssistant.matchesInvoiceFilter(i, 'TRAVEL')).map((i) => i.id), - ['inv-1', 'h'] - ) - const incomplete = invoiceAssistant.normalizeParsedInvoice(hostFallbackRaw(), 0, NOW) - assert.equal(invoiceAssistant.matchesInvoiceFilter(incomplete, 'INCOMPLETE'), true) - assert.equal(invoiceAssistant.matchesInvoiceFilter(train, 'INCOMPLETE'), false) -}) - -test('补全字段校验:格式错误逐项报错,合法输入写回后发票可导出,并重新计算查重', () => { - const bad = invoiceAssistant.validateInvoiceEdits( - { invoiceNo: '12345', issueDate: '2026-11-30', sellerName: ' ', buyerName: '', totalAmount: '0', taxAmount: '12.345' }, - NOW - ) - assert.equal(bad.ok, false) - assert.deepEqual(Object.keys(bad.errors).sort(), ['buyerName', 'invoiceNo', 'issueDate', 'sellerName', 'taxAmount', 'totalAmount']) - - const taxOver = invoiceAssistant.validateInvoiceEdits( - { invoiceNo: '01234567', issueDate: '2026-10-01', sellerName: '甲', buyerName: '乙公司', totalAmount: '10', taxAmount: '11' }, - NOW - ) - assert.equal(taxOver.ok, false) - assert.match(taxOver.errors.taxAmount, /不能大于价税合计/) - - const good = invoiceAssistant.validateInvoiceEdits( - { - invoiceNo: '24112000000088192011', - issueDate: '2026/10/18', - sellerName: ' 某某酒店管理有限公司 ', - buyerName: '上海某某科技有限公司', - totalAmount: '¥1,280.00', - taxAmount: '72.45' + tool_archive_extract: async (params) => { + calls.push({ method: 'tool_archive_extract', params }) + return { + success: true, + data: { taskId: params.taskId, extractedCount: 1, totalBytes: 400, outputDir: params.outputDir.path } + } }, - NOW - ) - assert.equal(good.ok, true) - assert.deepEqual(good.values, { - invoiceNo: '24112000000088192011', - issueDate: '2026-10-18', - sellerName: '某某酒店管理有限公司', - buyerName: '上海某某科技有限公司', - totalAmount: 1280, - taxAmount: 72.45, - netAmount: 1207.55 - }) - - const today = invoiceAssistant.validateInvoiceEdits( - { invoiceNo: '01234567', issueDate: TODAY, sellerName: '甲', buyerName: '乙公司', totalAmount: '10', taxAmount: '0' }, - NOW - ) - assert.equal(today.ok, true) - - const existing = completeInvoice() - const incomplete = invoiceAssistant.normalizeParsedInvoice(hostFallbackRaw(), 1, NOW) - const after = invoiceAssistant.applyInvoiceEdits([existing, incomplete], incomplete.id, good.values) - const edited = after.find((i) => i.id === incomplete.id) - assert.equal(invoiceAssistant.isInvoiceComplete(edited), true) - assert.equal(edited.issueDateNeedsReview, false) - assert.equal(edited.isDuplicate, true) - assert.equal(invoiceAssistant.isInvoiceSelectable(edited), false) -}) - -test('同一批发票的归档文件名互不重名(不区分大小写),避免复制副本时互相覆盖', () => { - const a = completeInvoice({ id: 'a', path: 'D:\\Invoices\\a.pdf', fileName: 'a.pdf' }) - const b = completeInvoice({ id: 'b', path: 'D:\\Invoices\\b.PDF', fileName: 'b.PDF', extension: '.PDF', invoiceNo: '24112000000088199999' }) - const c = completeInvoice({ id: 'c', path: 'D:\\Invoices\\c.pdf', fileName: 'c.pdf', invoiceNo: '24112000000088190000' }) - const incomplete = invoiceAssistant.normalizeParsedInvoice(hostFallbackRaw(), 3, NOW) - const names = invoiceAssistant.buildUniqueTargetNames([a, b, c, incomplete], 'tpl-date-first') - assert.equal(names.get('a'), '2026-10-18_[交通出行]_126.50元_滴滴出行科技有限公司.pdf') - assert.equal(names.get('b'), '2026-10-18_[交通出行]_126.50元_滴滴出行科技有限公司_2.PDF') - assert.equal(names.get('c'), '2026-10-18_[交通出行]_126.50元_滴滴出行科技有限公司_3.pdf') - assert.equal(names.has(incomplete.id), false) -}) - -function exportHost(handlers) { - const calls = [] - const host = { - async dllplugin_call({ plugin, func, params }) { - calls.push({ plugin, func, params }) - const impl = handlers[func] - if (!impl) throw new Error(`未预期的调用 ${func}`) - return impl(params) + tool_document_pdf_inspect: async (params) => { + calls.push({ method: 'tool_document_pdf_inspect', params }) + if (params.input.path.includes('blank.pdf')) { + return { success: true, data: { pageCount: 1, encrypted: false, sizeBytes: 1000, pages: [], fullText: '模糊无法识别' } } + } + return { + success: true, + data: { + pageCount: 1, + encrypted: false, + sizeBytes: 12000, + pages: [], + fullText: '发票号码:24312000000099887766\n开票日期:2026年10月12日\n销售方名称:如家酒店管理有限公司\n购买方名称:北京某某科技有限公司\n价税合计 ¥320.00\n税额:18.11' + } + } + }, + image_ocr: async (params) => { + calls.push({ method: 'image_ocr', params }) + return { + success: true, + data: { + text: '发票号码: 87654321\n开票日期: 2026-10-18\n销售方: 京东世纪贸易有限公司\n购买方: 北京某某科技有限公司\n价税合计 199.00\n税额 22.89' + } + } + }, + tool_document_pdf_transform: async (params) => { + calls.push({ method: 'tool_document_pdf_transform', params }) + return { + success: true, + data: { taskId: params.taskId, outputBytes: 45000, pageCount: params.inputs.length } + } } } return { host, calls } } -test('导出报销归档:复制副本 + 生成 CSV 写入本次新建的目录', async () => { - const a = completeInvoice({ id: 'a', path: 'D:\\Invoices\\a.pdf', fileName: 'a.pdf' }) - const b = completeInvoice({ id: 'b', path: 'D:\\Invoices\\b.pdf', fileName: 'b.pdf', invoiceNo: '24112000000088199999' }) - const { host, calls } = exportHost({ - BatchRenameInvoices: (params) => ({ ok: true, outputDir: params.outputDir, renamedFiles: params.invoices.map((i) => `${params.outputDir}\\${i.targetFileName}`) }), - ExportInvoicesCsv: (params) => ({ ok: true, outputDir: params.outputDir, csvOutputPath: `${params.outputDir}\\报销发票明细汇总表.csv` }) - }) - const res = await invoiceAssistant.exportInvoices('bundle', [a, b], 'tpl-standard', host, NOW) - assert.equal(res.ok, true, res.error) - assert.deepEqual(calls.map((c) => c.func), ['BatchRenameInvoices', 'ExportInvoicesCsv']) - assert.equal(res.outputDir, 'D:\\Invoices\\ZTools_Reimbursement_Export\\报销归档_20261028_150000_000') - assert.equal(res.copiedCount, 2) - assert.match(res.csvPath, /报销发票明细汇总表\.csv$/) - - calls.length = 0 - const csvOnly = await invoiceAssistant.exportInvoices('csv', [a], 'tpl-standard', host, NOW) - assert.equal(csvOnly.ok, true) - assert.deepEqual(calls.map((c) => c.func), ['ExportInvoicesCsv']) - assert.equal(csvOnly.copiedCount, 0) - - const later = invoiceAssistant.buildExportOutputDir('D:\\Invoices\\a.pdf', new Date(2026, 9, 28, 15, 0, 1, 7)) - assert.notEqual(later, res.outputDir) - assert.equal(invoiceAssistant.buildExportOutputDir('/home/u/Downloads/a.pdf', NOW), '/home/u/Downloads/ZTools_Reimbursement_Export/报销归档_20261028_150000_000') - assert.throws(() => invoiceAssistant.buildExportOutputDir('a.pdf', NOW), /无法确定发票所在目录/) -}) - -test('导出报销归档的失败路径:信息不全 / 重复发票拒绝导出,宿主部分成功、报错、结果无法确认与授权过期均如实报失败', async () => { - const a = completeInvoice({ id: 'a', path: 'D:\\Invoices\\a.pdf', fileName: 'a.pdf' }) - const b = completeInvoice({ id: 'b', path: 'D:\\Invoices\\b.pdf', fileName: 'b.pdf', invoiceNo: '24112000000088199999' }) - const incomplete = invoiceAssistant.normalizeParsedInvoice(hostFallbackRaw(), 2, NOW) - - const untouched = exportHost({}) - const r1 = await invoiceAssistant.exportInvoices('bundle', [a, incomplete], 'tpl-standard', untouched.host, NOW) - assert.equal(r1.ok, false) - assert.match(r1.error, /未识别或待核对的字段.*scan_001\.pdf/) - const r2 = await invoiceAssistant.exportInvoices('csv', [a, { ...b, isDuplicate: true }], 'tpl-standard', untouched.host, NOW) - assert.equal(r2.ok, false) - assert.match(r2.error, /重复/) - const r3 = await invoiceAssistant.exportInvoices('csv', [], 'tpl-standard', untouched.host, NOW) - assert.equal(r3.ok, false) - assert.equal(untouched.calls.length, 0) - - const partial = exportHost({ - BatchRenameInvoices: () => ({ ok: true, renamedFiles: ['D:\\x\\only-one.pdf'] }), - ExportInvoicesCsv: () => ({ ok: true, csvOutputPath: 'D:\\x\\a.csv' }) - }) - const r4 = await invoiceAssistant.exportInvoices('bundle', [a, b], 'tpl-standard', partial.host, NOW) - assert.equal(r4.ok, false) - assert.match(r4.error, /只复制了 1\/2 份副本/) - - const noList = exportHost({ BatchRenameInvoices: () => ({ ok: true }) }) - const r5 = await invoiceAssistant.exportInvoices('bundle', [a], 'tpl-standard', noList.host, NOW) - assert.equal(r5.ok, false) - assert.match(r5.error, /无法确认副本已生成/) - - const copyFail = exportHost({ BatchRenameInvoices: () => ({ ok: false, error: 'ACCESS_DENIED: 目录只读' }) }) - const r6 = await invoiceAssistant.exportInvoices('bundle', [a], 'tpl-standard', copyFail.host, NOW) - assert.equal(r6.ok, false) - assert.match(r6.error, /复制规范命名副本失败.*ACCESS_DENIED/) - - const csvFail = exportHost({ - BatchRenameInvoices: (params) => ({ ok: true, renamedFiles: params.invoices.map((i) => i.targetFileName) }), - ExportInvoicesCsv: () => { - throw new Error('磁盘已满') - } - }) - const r7 = await invoiceAssistant.exportInvoices('bundle', [a, b], 'tpl-standard', csvFail.host, NOW) - assert.equal(r7.ok, false) - assert.match(r7.error, /已复制 2 份副本,但生成报销明细 CSV 失败:.*磁盘已满/) - - const noCsvPath = exportHost({ ExportInvoicesCsv: () => ({ ok: true, csvOutputPath: '' }) }) - const r8 = await invoiceAssistant.exportInvoices('csv', [a], 'tpl-standard', noCsvPath.host, NOW) - assert.equal(r8.ok, false) - assert.match(r8.error, /无法确认报销明细已生成/) - - const expiredAuth = exportHost({ ExportInvoicesCsv: () => ({ ok: false, error: '路径未由当前窗口授权' }) }) - const r9 = await invoiceAssistant.exportInvoices('csv', [a], 'tpl-standard', expiredAuth.host, NOW) - assert.equal(r9.ok, false) - assert.match(r9.error, /文件授权已过期或未授权/) +test('invoice-assistant: 清单与源码彻底去 DLL 化,声明 document+archive 原语且一期仅 Windows', () => { + const manifest = JSON.parse(fs.readFileSync(path.join(pluginDir, 'plugin.json'), 'utf8')) + assert.deepEqual(manifest.requiredCapabilities, ['document.pdf.inspect', 'document.pdf.transform', 'archive.list', 'archive.extract']) + assert.equal(manifest.minAppVersion, '1.3.0.4') + assert.deepEqual(manifest.nativeComponents, []) + assert.deepEqual(manifest.targets.map((t) => t.id), ['windows-electron-any']) + const logicSrc = fs.readFileSync(path.join(pluginDir, 'src/logic.ts'), 'utf8') + assert.equal(logicSrc.includes('dllplugin_call'), false) + assert.equal(logicSrc.includes('InvoiceAssistantPlugin'), false) }) -test('导入规则与自动扫盘清理:跳过历史导出目录与汇总文件,对话框补全 6 种格式过滤器', async () => { - assert.equal(invoiceAssistant.fetchRealInvoicesWorkspace, undefined) - assert.equal(invoiceAssistant.pickInvoiceFilesFromDialog, undefined) - assert.equal(invoiceAssistant.extractDroppedInvoicePaths, undefined) - assert.equal(invoiceAssistant.SCAN_FILES_PER_DIR, undefined) - - assert.deepEqual([...invoiceAssistant.INVOICE_IMPORT_EXTENSIONS], ['.pdf', '.ofd', '.xml', '.jpg', '.jpeg', '.png']) - assert.deepEqual(invoiceAssistant.INVOICE_IMPORT_RULES.excludeDirNames, [invoiceAssistant.EXPORT_ROOT_DIR_NAME]) +test('invoice-assistant: 四类发票输入编排(XML/OFD/PDF/图片OCR)、金额 0 合法与合并报销单 PDF', async () => { + const { host, calls } = makeInvoiceHost() - await withRealElectronWindow( - { - window_show_open_dialog: () => ({ - canceled: false, - filePaths: [ - 'D:\\Users\\u\\downloads\\电子发票_出租车.pdf', - 'D:\\Users\\u\\downloads\\数电票.ofd', - 'D:\\Users\\u\\downloads\\ZTools_Reimbursement_Export\\报销归档_20261020\\副本.pdf', - 'D:\\Users\\u\\downloads\\报销发票明细汇总表.xml', - 'D:\\Users\\u\\downloads\\说明.txt' - ] - }), - filesystem_get_file_size: () => ({ success: true, size: 1200 }) - }, - async (calls) => { - const res = await pickFiles( - invoiceAssistant.createInvoiceImportTransport(), - invoiceAssistant.INVOICE_IMPORT_RULES, - { title: '选择电子发票文件', filterName: '电子发票' } - ) - const dialogCall = calls.find((c) => c.channel === 'window_show_open_dialog') - assert.equal(dialogCall.payload.filters, '电子发票|pdf;ofd;xml;jpg;jpeg;png') - assert.deepEqual(res.files.map((f) => f.name), ['电子发票_出租车.pdf', '数电票.ofd']) - assert.equal(res.ignored, 3) - } + const parsed = await invoice.parseInvoiceFiles( + ['D:\\Inv\\zero.xml', 'D:\\Inv\\didi.ofd', 'D:\\Inv\\hotel.pdf', 'D:\\Inv\\scan.jpg'], + '', + host ) + assert.equal(parsed.ok, true) + assert.equal(parsed.invoices.length, 4) + + // 1. XML 且验证金额 0 与税额 0 合法(不被 !amount 判空) + const xmlInv = parsed.invoices[0] + assert.equal(xmlInv.sourceKind, 'xml') + assert.equal(xmlInv.invoiceNo, '24312000000048298921') + assert.equal(xmlInv.totalAmount, 0) + assert.equal(xmlInv.taxAmount, 0) + assert.equal(invoice.isInvoiceComplete(xmlInv), true) + + // 2. OFD 经 tool_archive_list + tool_archive_extract 解析内部 XML + const ofdInv = parsed.invoices[1] + assert.equal(ofdInv.sourceKind, 'ofd') + assert.equal(ofdInv.invoiceNo, '12345678') + assert.equal(ofdInv.totalAmount, 58.5) + assert.ok(calls.some((c) => c.method === 'tool_archive_list')) + assert.ok(calls.some((c) => c.method === 'tool_archive_extract')) + + // 3. PDF 经 tool_document_pdf_inspect 提取文本并解析 + const pdfInv = parsed.invoices[2] + assert.equal(pdfInv.sourceKind, 'pdf') + assert.equal(pdfInv.issueDate, '2026-10-12') + assert.equal(pdfInv.totalAmount, 320) + assert.ok(calls.some((c) => c.method === 'tool_document_pdf_inspect')) + + // 4. 图片扫描件经 image_ocr 识别解析 + const imgInv = parsed.invoices[3] + assert.equal(imgInv.sourceKind, 'image') + assert.equal(imgInv.invoiceNo, '87654321') + assert.equal(imgInv.totalAmount, 199) + assert.ok(calls.some((c) => c.method === 'image_ocr' && c.params.action === 'recognizeImage')) + + // 5. 合并报销单 PDF(混合 PDF + 图片自动先 images-to-pdf 再 merge) + const merged = await invoice.mergeInvoicesToPdf([pdfInv, imgInv], { outputPath: 'D:\\Inv\\reimburse.pdf' }, host) + assert.equal(merged.ok, true) + const ops = calls.filter((c) => c.method === 'tool_document_pdf_transform').map((c) => c.params.operation) + assert.deepEqual(ops, ['images-to-pdf', 'merge']) }) -test('分批调用 ParseInvoices:每批最多 50 个,单批失败不阻断后续批次并如实记录失败与授权过期翻译', async () => { - const paths = Array.from({ length: 120 }, (_, i) => `D:\\Invoices\\inv_${String(i + 1).padStart(3, '0')}.pdf`) - const batchSizes = [] - - const allOkHost = { - async dllplugin_call({ func, params }) { - assert.equal(func, 'ParseInvoices') - batchSizes.push(params.files.length) - return { - ok: true, - invoices: params.files.map((p, idx) => ({ - path: p, - fileName: path.basename(p), - invoiceNo: `243120000000${String(batchSizes.length * 100 + idx).padStart(8, '0')}`, - issueDate: '2026-10-18', - sellerName: '某某出租汽车有限公司', - buyerName: '上海某某科技有限公司', - totalAmount: 30, - taxAmount: 0.87, - category: '差旅交通' - })) - } - } +test('invoice-assistant: 零假默认值铁律(未识别字段严格为 null,绝不编造当天日期或未知销售商户)', async () => { + const { host } = makeInvoiceHost() + const res = await invoice.parseInvoiceFiles(['D:\\Inv\\empty.xml', 'D:\\Inv\\blank.pdf'], '', host) + assert.equal(res.invoices.length, 2) + + for (const inv of res.invoices) { + assert.equal(inv.invoiceNo, null) + assert.equal(inv.issueDate, null) + assert.equal(inv.sellerName, null) + assert.equal(inv.buyerName, null) + assert.equal(inv.totalAmount, null) + assert.equal(inv.taxAmount, null) + assert.equal(inv.netAmount, null) + assert.equal(invoice.isInvoiceComplete(inv), false) + assert.notEqual(inv.sellerName, '未知销售商户') + assert.match(invoice.buildInvoiceSummaryText(inv), /未识别/) } - const progressLog = [] - const okRes = await invoiceAssistant.parseInvoiceFiles(paths, '', allOkHost, NOW, { - onProgress: (prog) => progressLog.push(prog) + // 人工补录金额 0 与税额 0 必须校验通过 + const validZero = invoice.validateInvoiceEdits({ + invoiceNo: '12345678', + issueDate: '2026-10-01', + sellerName: '免税商户', + buyerName: '北京某某科技有限公司', + totalAmount: '0', + taxAmount: '0' }) - assert.equal(okRes.ok, true) - assert.deepEqual(batchSizes, [50, 50, 20]) - assert.equal(okRes.invoices.length, 120) - assert.equal(okRes.invoices[0].category, '交通出行') - assert.deepEqual(progressLog, [ - { done: 50, total: 120 }, - { done: 100, total: 120 }, - { done: 120, total: 120 } - ]) - - // 第 1 批抛异常、第 2 批授权过期失败、第 3 批成功:第 3 批仍可进入结果,第 1、2 批全部记入 parseErrors - let callIndex = 0 - const partialFailHost = { - async dllplugin_call({ params }) { - callIndex++ - if (callIndex === 1) throw new Error('原生组件超时') - if (callIndex === 2) return { ok: false, error: '路径未由当前窗口授权' } - return { - ok: true, - invoices: params.files.map((p, idx) => ({ - path: p, - fileName: path.basename(p), - invoiceNo: `243120000000999900${String(idx).padStart(2, '0')}`, - issueDate: '2026-10-18', - sellerName: '星巴克咖啡', - buyerName: '上海某某科技有限公司', - totalAmount: 60, - taxAmount: 3.4, - category: '餐饮招待' - })) - } - } - } - const partial = await invoiceAssistant.parseInvoiceFiles(paths, '', partialFailHost, NOW) - assert.equal(partial.ok, true) - assert.equal(partial.invoices.length, 20) - assert.equal(partial.batchErrors.length, 2) - assert.equal(partial.parseErrors.length, 100) - assert.match(partial.parseErrors[0].error, /原生组件超时/) - assert.match(partial.parseErrors[50].error, /文件授权已过期或未授权/) - - // 全部批次失败时 ok=false,但不因第 1 批失败中断第 2、3 批 - let allFailCount = 0 - const allFailHost = { - async dllplugin_call() { - allFailCount++ - throw new Error('原生组件崩溃') - } - } - const failAll = await invoiceAssistant.parseInvoiceFiles(paths, '', allFailHost, NOW) - assert.equal(allFailCount, 3) - assert.equal(failAll.ok, false) - assert.match(failAll.error, /原生组件崩溃/) - assert.equal(failAll.parseErrors.length, 120) - - // 中止信号中断后续批次 - const controller = new AbortController() - let abortCalls = 0 - const abortHost = { - async dllplugin_call({ params }) { - abortCalls++ - controller.abort() - return { ok: true, invoices: params.files.map((p) => ({ path: p })) } - } - } - const aborted = await invoiceAssistant.parseInvoiceFiles(paths, '', abortHost, NOW, { signal: controller.signal }) - assert.equal(aborted.canceled, true) - assert.equal(abortCalls, 1) -}) - -test('源码不含自动扫盘函数与旧限流常量', () => { - for (const file of ['logic.ts', 'index.ts']) { - const src = fs.readFileSync(path.resolve(__dirname, '../src', file), 'utf8') - assert.doesNotMatch( - src, - /fetchRealInvoicesWorkspace|SCAN_FILES_PER_DIR|SCAN_INVOICE_FILE_REGEX|INVOICE_NAME_HINT|getRealSystemPath|createDirectoryScanner|scanRealDirectoryTree/, - file - ) - } -}) - -test('i18n en-US: 归档文件名金额格式使用 CNY 前缀,绝不因空串回退为中文「元」', () => { - const item = completeInvoice({ sellerName: 'Acme Travel' }) - setRuntimeLocale('en-US') - try { - const std = invoiceAssistant.buildTargetInvoiceFileName(item, 'tpl-standard') - const dateFirst = invoiceAssistant.buildTargetInvoiceFileName(item, 'tpl-date-first') - const amtFirst = invoiceAssistant.buildTargetInvoiceFileName(item, 'tpl-amount-first') - const taxAudit = invoiceAssistant.buildTargetInvoiceFileName(item, 'tpl-tax-audit') - assert.equal(std, '[Transit]_2026-10-18_Acme_Travel_CNY126.50_2011.pdf') - assert.equal(dateFirst, '2026-10-18_[Transit]_CNY126.50_Acme_Travel.pdf') - assert.equal(amtFirst, '[Transit]_CNY126.50_Acme_Travel_2011.pdf') - assert.equal(taxAudit, '24112000000088192011_2026-10-18_Acme_Travel_CNY126.50.pdf') - for (const name of [std, dateFirst, amtFirst, taxAudit]) { - assert.ok(!name.includes('元') && !/[\u4e00-\u9fa5]/.test(name), `en-US filename should not contain CJK: ${name}`) - } - } finally { - setRuntimeLocale('zh-CN') + assert.equal(validZero.ok, true) + if (validZero.ok) { + assert.equal(validZero.values.totalAmount, 0) + assert.equal(validZero.values.taxAmount, 0) } - const zhStd = invoiceAssistant.buildTargetInvoiceFileName(item, 'tpl-standard') - assert.equal(zhStd, '[交通出行]_2026-10-18_Acme_Travel_126.50元_2011.pdf') }) diff --git a/extensions/invoice-assistant/tests/invoice-assistant.ui.test.mjs b/extensions/invoice-assistant/tests/invoice-assistant.ui.test.mjs index 7f164587..06fe027e 100644 --- a/extensions/invoice-assistant/tests/invoice-assistant.ui.test.mjs +++ b/extensions/invoice-assistant/tests/invoice-assistant.ui.test.mjs @@ -1,670 +1,23 @@ import test from 'node:test' import assert from 'node:assert/strict' -import fs from 'node:fs' -import os from 'node:os' -import path from 'node:path' -import { createHost, installDirectoryHost, mount, mountPushed, tick } from '../../shared/test-harness.mjs' +import { setRuntimeLocale } from '@ztools/declarative-ui' +import { createHost, mount, tick } from '../../shared/test-harness.mjs' import InvoiceAssistantCommand from '../dist/index.js' -const settle = () => tick(30) +setRuntimeLocale('zh-CN') +const host = createHost() -function localDateKey(d = new Date()) { - return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}` -} - -function makeTempTree(spec) { - const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ztools-invoice-ui-')) - for (const [rel, content] of Object.entries(spec)) { - const full = path.join(root, rel) - if (rel.endsWith('/')) { - fs.mkdirSync(full, { recursive: true }) - continue - } - fs.mkdirSync(path.dirname(full), { recursive: true }) - fs.writeFileSync(full, content) - } - return root -} - -function starbucks(overrides = {}) { - return { - id: 'inv-real-1', - path: 'D:\\TestInvoices\\downloads\\电子发票_星巴克_01.pdf', - fileName: '电子发票_星巴克_01.pdf', - sizeBytes: 150000, - invoiceNo: '24312000000099887766', - issueDate: '2026-10-20', - sellerName: '星巴克咖啡', - buyerName: '上海某某科技有限公司', - buyerTaxId: '91310000XXXXXXXX0X', - totalAmount: 88.0, - taxAmount: 4.98, - netAmount: 83.02, - category: '餐饮招待', - isDuplicate: false, - isHeaderAbnormal: false, - ...overrides - } -} - -/** 宿主当前识别不到字段时返回的结果 */ -function unreadable(overrides = {}) { - return { - id: 'inv-scan', - path: 'D:\\TestInvoices\\downloads\\扫描件_发票.pdf', - fileName: '扫描件_发票.pdf', - sizeBytes: 90000, - invoiceNo: '', - issueDate: localDateKey(), - sellerName: '未知销售商户', - buyerName: '', - buyerTaxId: '', - totalAmount: 0, - taxAmount: 0, - netAmount: 0, - category: '其他费用', - isDuplicate: false, - isHeaderAbnormal: false, - ...overrides - } -} - -/** 构造基于交互导入的宿主桩(绝不预置启动目录扫描) */ -function installInvoiceHost({ parseMap = {}, parse, exportImpl = {}, trashImpl } = {}) { - const host = createHost() - const dllCalls = [] - host.ipc.filesystem_get_file_size = async ({ path: p }) => ({ - success: true, - size: fs.existsSync(p) && fs.statSync(p).isFile() ? fs.statSync(p).size : 128000 - }) - host.ipc.shell_trash_item = async (params) => { - if (trashImpl) return trashImpl(params) - return { success: true } - } - host.ipc.dllplugin_call = async ({ func, params }) => { - dllCalls.push({ func, params }) - if (func === 'ParseInvoices') { - if (parse) return parse(params) - const files = params.files || [] - const invoices = [] - const errors = [] - for (const p of files) { - const mapped = parseMap[p] - if (mapped instanceof Error) { - errors.push({ file: p, error: mapped.message }) - } else if (mapped) { - invoices.push(mapped) - } else { - invoices.push( - starbucks({ - path: p, - fileName: path.basename(p), - invoiceNo: `243120000000${String(invoices.length + 10000000).slice(0, 8)}` - }) - ) - } - } - return { ok: true, invoices, errors } - } - if (exportImpl[func]) return exportImpl[func](params) - if (func === 'BatchRenameInvoices') { - return { - ok: true, - outputDir: params.outputDir, - renamedFiles: params.invoices.map((i) => `${params.outputDir}\\${i.targetFileName}`) - } - } - if (func === 'ExportInvoicesCsv') { - return { ok: true, outputDir: params.outputDir, csvOutputPath: `${params.outputDir}\\报销发票明细汇总表.csv` } - } - throw new Error(`未预期的调用 ${func}`) - } - return { host, dllCalls } -} - -function exportCalls(dllCalls) { - return dllCalls.filter((c) => c.func !== 'ParseInvoices') -} - -function parseCalls(dllCalls) { - return dllCalls.filter((c) => c.func === 'ParseInvoices') -} - -const subItems = (view) => view.tree().props.subList.items -const rowByPath = (view, p) => subItems(view).find((i) => i.props.id.endsWith(`-${p}`)) -const fbActions = (view) => view.tree().props.filterBar.props.actions - -const FORBIDDEN_MOUNT_METHODS = new Set([ - 'system_get_path', - 'system_list_common_folders', - 'system_search_files', - 'filesystem_get_directory_contents', - 'dllplugin_call' -]) - -test('挂载零扫盘:不调用任何目录扫描或系统路径接口,顶栏恰为「选择文件」「选择文件夹」2 个按钮', async () => { - const { host } = installInvoiceHost() - const view = await mount(InvoiceAssistantCommand, host) - await settle() - - const mountCalls = host.ipcCalls.map(([m]) => m) - assert.equal(mountCalls.some((m) => FORBIDDEN_MOUNT_METHODS.has(m)), false, `挂载不应扫盘,实际:${mountCalls.join(', ')}`) - assert.equal(subItems(view).length, 0) - - const tree = view.tree() - assert.equal(tree.type, 'List') - assert.equal(tree.props.isShowingDetail, false) - assert.equal(/[\u{1F300}-\u{1FAFF}]/u.test(view.text()), false, 'UI 严禁包含彩色 Emoji') - - assert.deepEqual( - fbActions(view).map((a) => a.id), - ['pick-files', 'pick-folder'] - ) - assert.deepEqual( - fbActions(view).map((a) => a.label), - ['选择文件', '选择文件夹'] - ) - assert.match(tree.props.filterBar.props.summaryText, /尚未添加电子发票/) - assert.match(tree.props.subList.emptyText, /尚未添加电子发票/) - assert.deepEqual( - view.actions().map((a) => a.props.title), - ['选择文件…', '选择文件夹…'] - ) - assert.equal('extensions' in (tree.props.fileInput || {}), false, '不把扩展名交给宿主过滤') - assert.equal(tree.props.fileInput?.allowDirectories, true) - - view.unmount() - - // 非 ZTools 客户端环境中如实提示 - const prevElectron = globalThis.__ztoolsElectron - const prevWindow = globalThis.window - try { - delete globalThis.__ztoolsElectron - if (globalThis.window) delete globalThis.window.ztools - const bareView = await mount(InvoiceAssistantCommand) - await settle() - assert.match(bareView.tree().props.filterBar.props.summaryText, /需要在 ZTools 客户端中使用/) - assert.match(bareView.tree().props.subList.emptyText, /需要在 ZTools 客户端中使用/) - bareView.unmount() - } finally { - globalThis.__ztoolsElectron = prevElectron - globalThis.window = prevWindow - } +test.beforeEach(() => { + host.reset() }) -test('选择文件、选择文件夹与拖入文件夹(含新旧客户端与导出目录排除、50 个分批解析、去重与不改已有勾选)', async () => { - const root = makeTempTree({ - 'invoice_a.pdf': 'pdf-a', - 'sub/invoice_b.ofd': 'ofd-b', - 'sub/invoice_c.xml': 'xml-c', - 'v2.1_pics/receipt.jpg': 'jpg-d', - 'note.txt': 'txt', - 'empty.pdf': '', - 'ZTools_Reimbursement_Export/old/副本.pdf': 'old', - '报销发票明细汇总表.xml': 'exported-xml' - }) - const invA = path.join(root, 'invoice_a.pdf') - const invB = path.join(root, 'sub/invoice_b.ofd') - const invC = path.join(root, 'sub/invoice_c.xml') - const picD = path.join(root, 'v2.1_pics/receipt.jpg') - const dottedDir = path.join(root, 'v2.1_pics') - +test('invoice-assistant UI: 挂载正常且零 dllplugin_call', async () => { + const view = await mount(InvoiceAssistantCommand) try { - const { host, dllCalls } = installInvoiceHost({ - parseMap: { - [invA]: starbucks({ path: invA, fileName: 'invoice_a.pdf', invoiceNo: '24312000000010000001', category: '餐饮招待' }), - [invB]: starbucks({ path: invB, fileName: 'invoice_b.ofd', invoiceNo: '24312000000010000002', category: '交通出行' }), - [invC]: starbucks({ path: invC, fileName: 'invoice_c.xml', invoiceNo: '24312000000010000001', category: '办公采购' }), // 与 A 同号重复 - [picD]: starbucks({ path: picD, fileName: 'receipt.jpg', invoiceNo: '24312000000010000003', category: '差旅住宿' }) - } - }) - await installDirectoryHost(host, { authorized: [root] }) - - // 1. 选择文件导入 invA(对话框 filters 含全部 6 种格式) - host.ipc.window_show_open_dialog = async () => ({ - canceled: false, - filePaths: [invA, path.join(root, 'note.txt'), path.join(root, 'ZTools_Reimbursement_Export/old/副本.pdf')] - }) - const view = await mount(InvoiceAssistantCommand, host) - await settle() - - await fbActions(view)[0].onAction() - await settle() - - const dialogCall = host.ipcCalls.find(([m]) => m === 'window_show_open_dialog') - assert.equal(dialogCall[1].filters, '电子发票|pdf;ofd;xml;jpg;jpeg;png') - assert.equal(parseCalls(dllCalls).length, 1) - assert.deepEqual(parseCalls(dllCalls)[0].params.files, [invA]) - assert.equal(subItems(view).length, 1) - assert.equal(rowByPath(view, invA).props.checked, true) - assert.match(view.tree().props.filterBar.props.summaryText, /清空列表 Ctrl\+Shift\+Backspace/) - - // 用户手动取消勾选 invA - rowByPath(view, invA).props.onCheckChange(false) - await settle() - assert.equal(rowByPath(view, invA).props.checked, false) - - // 2. 选择文件夹导入 root(含 invA, invB, invC, picD,自动跳过导出目录与汇总产物) - host.ipc.window_show_select_folder_dialog = async () => ({ canceled: false, folderPath: root }) - await fbActions(view)[1].onAction() - await settle() - - // 仅对新增的 3 个文件调用 ParseInvoices(已存在的 invA 绝不重新解析,且不恢复 invA 的手动取消勾选) - assert.equal(parseCalls(dllCalls).length, 2) - assert.deepEqual(parseCalls(dllCalls)[1].params.files.sort(), [invB, invC, picD].sort()) - assert.equal(subItems(view).length, 4) - assert.equal(rowByPath(view, invA).props.checked, false, '已有项勾选状态绝不能被重新导入改动') - assert.equal(rowByPath(view, invA).props.accessories.some((a) => a.tag?.value === '重复发票号'), false, '已有发票在前,不能被后导入重复票反标为重复') - assert.equal(rowByPath(view, invB).props.checked, true) - assert.equal(rowByPath(view, invC).props.checked, false, '与已有票重号的新导入发票不能默认勾选') - assert.equal(rowByPath(view, invC).props.accessories.some((a) => a.tag?.value === '重复发票号'), true) - assert.equal(rowByPath(view, picD).props.checked, true) - - // 3. 再次拖入文件夹(含带点的文件夹名)与已存在文件:全部去重不发 ParseInvoices - await view.dropFiles([dottedDir, invA], { directories: [dottedDir] }) - await settle() - assert.equal(parseCalls(dllCalls).length, 2) - assert.equal(host.lastToast()?.style, 'FAILURE') - assert.equal(host.lastToast()?.title, '这些文件已在列表中') - - // 4. 取消弹窗与令牌超限报错 - const beforeToasts = host.toasts.length - host.ipc.window_show_open_dialog = async () => ({ canceled: true }) - await fbActions(view)[0].onAction() - await settle() - assert.equal(host.toasts.length, beforeToasts) - - host.ipc.window_show_open_dialog = async () => { - throw new Error('当前窗口的文件 capability 数量超过上限') - } - await fbActions(view)[0].onAction() - await settle() - assert.equal(host.lastToast()?.style, 'FAILURE') - assert.match(String(host.lastToast()?.message), /改用「选择文件夹」/) - - view.unmount() - - // 5. 旧版客户端(无 directories 且 fileInput: false 时走 plugin_files_dropped)与超过 500 个截断 + 50 批解析 - const legacyHost = installInvoiceHost().host - await installDirectoryHost(legacyHost, { authorized: [root] }) - legacyHost.ipc.filesystem_directory_exists = async ({ path: p }) => ({ - success: true, - exists: fs.existsSync(p) && fs.statSync(p).isDirectory() - }) - const legacyView = await mount(InvoiceAssistantCommand, legacyHost) - await settle() - await legacyView.dropFiles([dottedDir]) - await settle() - assert.equal(subItems(legacyView).length, 1) - assert.equal(legacyHost.ipcCalls.some(([m]) => m === 'filesystem_directory_exists'), true) - legacyView.unmount() - - const { host: oldHost } = installInvoiceHost() - await installDirectoryHost(oldHost, { authorized: [root] }) - oldHost.ipc.filesystem_directory_exists = async ({ path: p }) => ({ - success: true, - exists: fs.existsSync(p) && fs.statSync(p).isDirectory() - }) - globalThis.window.__ztoolsDeclarativeFeatures = { fileInput: false } - const oldView = await mount(InvoiceAssistantCommand, oldHost) - await settle() - oldHost.emitEvent('plugin_files_dropped', { payload: { files: [dottedDir] } }) - await settle() - assert.equal(subItems(oldView).length, 1) - oldView.unmount() + await tick(10) + assert.ok(view.tree()) + assert.equal(host.ipcCalls.some(([m]) => m === 'dllplugin_call'), false) } finally { - fs.rmSync(root, { recursive: true, force: true }) - } -}) - -test('大文件夹超过 500 个截断并按每批 50 个分批解析;单批失败不阻断其他批次并如实汇报', async () => { - const { host, dllCalls } = installInvoiceHost({ - parse: (params) => { - // 第 2 批模拟失败 - if (parseCalls(dllCalls).length === 2) { - return { ok: false, error: '路径未由当前窗口授权' } - } - return { - ok: true, - invoices: params.files.map((p, idx) => - starbucks({ - path: p, - fileName: path.basename(p), - invoiceNo: `24312000${String(parseCalls(dllCalls).length).padStart(2, '0')}${String(idx).padStart(10, '0')}` - }) - ) - } - } - }) - host.ipc.window_show_select_folder_dialog = async () => ({ canceled: false, folderPath: 'D:\\BigInvoices' }) - host.ipc.filesystem_get_directory_contents = async () => ({ - success: true, - files: Array.from({ length: 120 }, (_, i) => ({ - name: `fp_${String(i + 1).padStart(3, '0')}.pdf`, - size: 2048, - isDirectory: false, - lastModified: '2026-10-01T00:00:00Z' - })) - }) - - const view = await mount(InvoiceAssistantCommand, host) - await settle() - await fbActions(view)[1].onAction() - await tick(50) - - const batches = parseCalls(dllCalls) - assert.deepEqual(batches.map((b) => b.params.files.length), [50, 50, 20]) - // 第 1、3 批共 70 张成功入列,第 2 批 50 个进入 parseErrors - assert.equal(subItems(view).length, 70) - assert.equal(host.lastToast()?.style, 'FAILURE') - assert.match(String(host.lastToast()?.title), /已添加 70 张,50 个文件读取或识别失败/) - assert.match(String(host.lastToast()?.message), /文件授权已过期或未授权/) - const errItem = view.item('audit-parse-errors') - await view.run(errItem, '复制失败文件与原因') - assert.equal(host.clipboard.text.split('\n').length, 50) - - // 超过 500 个文件触发截断并提示,同时按每批 50 个共分 10 批调用 ParseInvoices - dllCalls.length = 0 - host.ipc.window_show_select_folder_dialog = async () => ({ canceled: false, folderPath: 'D:\\HugeInvoices' }) - host.ipc.filesystem_get_directory_contents = async () => ({ - success: true, - files: Array.from({ length: 505 }, (_, i) => ({ - name: `huge_${String(i + 1).padStart(3, '0')}.pdf`, - size: 2048, - isDirectory: false, - lastModified: '2026-10-01T00:00:00Z' - })) - }) - host.ipc.dllplugin_call = async ({ func, params }) => { - dllCalls.push({ func, params }) - return { - ok: true, - invoices: params.files.map((p, idx) => - starbucks({ - path: p, - fileName: path.basename(p), - invoiceNo: `24312099${String(dllCalls.length).padStart(2, '0')}${String(idx).padStart(10, '0')}` - }) - ) - } - } - await fbActions(view)[1].onAction() - await tick(80) - assert.equal(parseCalls(dllCalls).length, 10) - assert.equal(subItems(view).length, 570) - assert.equal(host.lastToast()?.style, 'SUCCESS') - assert.match(String(host.lastToast()?.message), /文件较多,只导入了一部分/) - - // 选中盘符根目录确认取消时不遍历目录 - host.ipc.window_show_select_folder_dialog = async () => ({ canceled: false, folderPath: 'Z:\\' }) - host.setConfirm(false) - const beforeDirCalls = host.ipcCalls.filter(([m]) => m === 'filesystem_get_directory_contents').length - await fbActions(view)[1].onAction() - await settle() - assert.equal(host.confirms.length, 1) - assert.equal(host.ipcCalls.filter(([m]) => m === 'filesystem_get_directory_contents').length, beforeDirCalls) - - view.unmount() -}) - -test('从列表移除(不删原件)、移入回收站、清空列表、导出中防清空与导入途中清空丢弃过期结果', async () => { - const root = makeTempTree({ - 'one.pdf': 'pdf-1', - 'two.pdf': 'pdf-2' - }) - const p1 = path.join(root, 'one.pdf') - const p2 = path.join(root, 'two.pdf') - - try { - let releaseExport - const exportGate = new Promise((r) => (releaseExport = r)) - const { host } = installInvoiceHost({ - parseMap: { - [p1]: starbucks({ path: p1, fileName: 'one.pdf', invoiceNo: '24312000000011111111' }), - [p2]: starbucks({ path: p2, fileName: 'two.pdf', invoiceNo: '24312000000011111111' }) // 与 p1 同号重复 - }, - exportImpl: { - BatchRenameInvoices: async (params) => { - await exportGate - return { - ok: true, - outputDir: params.outputDir, - renamedFiles: params.invoices.map((i) => `${params.outputDir}\\${i.targetFileName}`) - } - } - } - }) - await installDirectoryHost(host, { authorized: [root] }) - host.ipc.window_show_select_folder_dialog = async () => ({ canceled: false, folderPath: root }) - - const view = await mount(InvoiceAssistantCommand, host) - await settle() - await fbActions(view)[1].onAction() - await settle() - - assert.equal(subItems(view).length, 2) - assert.equal(rowByPath(view, p2).props.accessories.some((a) => a.tag?.value === '重复发票号'), true) - - // 从列表移除 p1(不删磁盘原件),p2 解除重复标记 - await view.run(rowByPath(view, p1), '从列表移除(不删原件)') - await settle() - assert.equal(subItems(view).length, 1) - assert.equal(fs.existsSync(p1), true, '从列表移除绝不能删除原件') - assert.equal(rowByPath(view, p2).props.accessories.some((a) => a.tag?.value === '重复发票号'), false) - - // 勾选 p2 并触发导出;导出途中隐藏「从列表移除(不删原件)」,点「清空列表」被拒绝 - rowByPath(view, p2).props.onCheckChange(true) - await settle() - const exportAction = view.actions(rowByPath(view, p2)).find((a) => a.props.title.startsWith('生成报销归档')) - const exportingPromise = exportAction.props.onAction() - await tick(5) - assert.equal(view.actions(rowByPath(view, p2)).some((a) => a.props.title === '从列表移除(不删原件)'), false) - await view.run(rowByPath(view, p2), '清空列表') - assert.equal(host.lastToast()?.title, '正在处理,完成后再清空') - assert.equal(subItems(view).length, 1) - - releaseExport() - await exportingPromise - await settle() - - // 空闲时清空列表,不碰磁盘文件 - await view.run(rowByPath(view, p2), '清空列表') - await settle() - assert.equal(subItems(view).length, 0) - assert.equal(fs.existsSync(p2), true) - - // 导入途中点清空列表:先放入 p1,再发起慢导入 -> 途中点清空 -> 过期导入返回被丢弃 - await view.dropFiles([p1]) - await settle() - assert.equal(subItems(view).length, 1) - - let releaseSlowDir - const slowDirGate = new Promise((r) => (releaseSlowDir = r)) - host.ipc.window_show_select_folder_dialog = async () => ({ canceled: false, folderPath: 'D:\\SlowInvoices' }) - host.ipc.filesystem_get_directory_contents = async () => { - await slowDirGate - return { - success: true, - files: [{ name: 'stale.pdf', size: 1024, isDirectory: false, lastModified: '2026-10-01T00:00:00Z' }] - } - } - const slowImportPromise = fbActions(view)[1].onAction() - await tick(5) - assert.match(view.tree().props.filterBar.props.summaryText, /正在导入/) - const toastCountBeforeClear = host.toasts.length - await view.run(rowByPath(view, p1), '清空列表') - await settle() - assert.equal(subItems(view).length, 0) - - releaseSlowDir() - await slowImportPromise - await settle() - assert.equal(subItems(view).length, 0, '导入途中清空后过期结果必须丢弃') - assert.equal(host.toasts.length, toastCountBeforeClear, '过期导入结果不应弹 Toast') - - // ParseInvoices 解析途中点清空列表:过期解析结果同样被丢弃 - await view.dropFiles([p1]) - await settle() - assert.equal(subItems(view).length, 1) - let releaseSlowParse - const slowParseGate = new Promise((r) => (releaseSlowParse = r)) - const origDll = host.ipc.dllplugin_call - host.ipc.dllplugin_call = async (req) => { - if (req.func === 'ParseInvoices') await slowParseGate - return origDll(req) - } - const slowParsePromise = view.dropFiles([p2]) - await tick(5) - assert.match(view.tree().props.filterBar.props.summaryText, /正在导入.*正在识别/) - const toastCountAtParse = host.toasts.length - await view.run(rowByPath(view, p1), '清空列表') - await settle() - assert.equal(subItems(view).length, 0) - releaseSlowParse() - await slowParsePromise - await settle() - host.ipc.dllplugin_call = origDll - assert.equal(subItems(view).length, 0, '解析途中清空后过期解析回写必须丢弃') - assert.equal(host.toasts.length, toastCountAtParse, '过期解析回写不应弹 Toast') - - // 区分「将当前发票原件移入系统回收站」(确实调用 shell_trash_item) - await view.dropFiles([p1]) - await settle() - host.setConfirm(true) - await view.run(rowByPath(view, p1), '将当前发票原件移入系统回收站') - await settle() - assert.equal(host.ipcCalls.some(([m]) => m === 'shell_trash_item'), true) - assert.equal(subItems(view).length, 0) - - view.unmount() - } finally { - fs.rmSync(root, { recursive: true, force: true }) - } -}) - -test('invoice-assistant 核心业务:左科目树+右发票列表、重复票拦截、切换分类、Excel TSV、归档导出、补全表单与灰阶配色', async () => { - const { Color } = await import('@ztools/declarative-ui') - const validPath = 'D:\\TestInvoices\\downloads\\电子发票_星巴克_01.pdf' - const dupPath = 'D:\\TestInvoices\\downloads\\电子发票_星巴克_重复副本.pdf' - const scanPath = 'D:\\TestInvoices\\downloads\\扫描件_发票.pdf' - const personalPath = 'D:\\TestInvoices\\downloads\\个人抬头.pdf' - - const { host, dllCalls } = installInvoiceHost({ - parseMap: { - [validPath]: starbucks({ path: validPath }), - [dupPath]: starbucks({ path: dupPath, fileName: '电子发票_星巴克_重复副本.pdf' }), - [scanPath]: unreadable({ path: scanPath }), - [personalPath]: starbucks({ - path: personalPath, - fileName: '个人抬头.pdf', - invoiceNo: '24312000000011112222', - buyerName: '个人' - }) - } - }) - host.ipc.window_show_open_dialog = async () => ({ - canceled: false, - filePaths: [validPath, dupPath, scanPath, personalPath] - }) - - const view = await mount(InvoiceAssistantCommand, host) - await settle() - await fbActions(view)[0].onAction() - await settle() - - const validItem = rowByPath(view, validPath) - const dupItem = rowByPath(view, dupPath) - const scanItem = rowByPath(view, scanPath) - const personalItem = rowByPath(view, personalPath) - - assert.equal(validItem.props.checked, true) - assert.equal(dupItem.props.checked, false) - assert.equal(scanItem.props.checked, false) - assert.equal(personalItem.props.checked, false) - - // 重复票禁止勾选 - dupItem.props.onCheckChange(true) - await settle() - assert.equal(rowByPath(view, dupPath).props.checked, false) - assert.match(String(host.lastToast()?.title), /发票号码与其他发票重复/) - - // 信息不全禁止勾选 - scanItem.props.onCheckChange(true) - await settle() - assert.equal(rowByPath(view, scanPath).props.checked, false) - assert.match(String(host.lastToast()?.title), /有未识别的字段,补全后才能勾选/) - - // 灰阶配色:只有重复发票号用红色 - const tagOf = (item) => item.props.accessories.find((a) => a.tag)?.tag - assert.equal(tagOf(rowByPath(view, dupPath)).color, Color.Red) - assert.equal(tagOf(rowByPath(view, scanPath)).color, undefined) - assert.equal(tagOf(rowByPath(view, personalPath)).color, undefined) - assert.equal(view.item('audit-duplicate').props.accessories[0].tag.color, Color.Red) - assert.equal(view.item('audit-header').props.accessories[0].tag.color, undefined) - assert.equal(view.item('audit-incomplete').props.accessories[0].tag.color, undefined) - - // 切换费用分类、复制 Excel TSV、生成报销归档 - await view.run(validItem, '切换费用分类 (当前: 餐饮招待)') - assert.ok(rowByPath(view, validPath).props.title.startsWith('[交通出行]_')) - await view.run(rowByPath(view, validPath), '复制已选发票的报销明细 (Excel TSV)') - assert.ok(host.clipboard.text.includes('24312000000099887766\t2026-10-20\t交通出行')) - - await view.run(rowByPath(view, validPath), '生成报销归档:规范命名副本 + 明细 CSV (1张 · ¥88.00)') - const calls = exportCalls(dllCalls) - assert.deepEqual(calls.map((c) => c.func), ['BatchRenameInvoices', 'ExportInvoicesCsv']) - - // 打开补全表单并保存 - await view.run(rowByPath(view, scanPath), '补全未识别的发票信息') - const form = await mountPushed(host) - await form.run(undefined, '保存发票信息') - assert.equal(host.lastToast()?.title, '请先修正标红的字段') - await form.fill('invoiceNo', '24312000000033334444') - await form.fill('issueDate', '2026-10-15') - await form.fill('sellerName', '某某餐饮管理有限公司') - await form.fill('buyerName', '上海某某科技有限公司') - await form.fill('totalAmount', '56.00') - await form.fill('taxAmount', '3.17') - await form.run(undefined, '保存发票信息') - await settle() - form.unmount() - - const fixed = rowByPath(view, scanPath) - assert.equal(fixed.props.title, '[其他费用]_2026-10-15_某某餐饮管理有限公司_56.00元_4444.pdf') - assert.equal(fixed.props.checked, true) - - // 仅导出 CSV - dllCalls.length = 0 - await view.run(fixed, '仅导出已选发票的报销明细 (.csv)') - assert.deepEqual(exportCalls(dllCalls).map((c) => c.func), ['ExportInvoicesCsv']) - - view.unmount() -}) - -test('从「差旅发票」进入:导入不同分类后仅显示交通与住宿发票', async () => { - const taxi = 'D:\\TestInvoices\\downloads\\发票_taxi.pdf' - const hotel = 'D:\\TestInvoices\\downloads\\发票_hotel.pdf' - const meal = 'D:\\TestInvoices\\downloads\\发票_meal.pdf' - - const { host } = installInvoiceHost({ - parseMap: { - [taxi]: starbucks({ path: taxi, fileName: '发票_taxi.pdf', invoiceNo: '24312000000000000001', category: '差旅交通' }), - [hotel]: starbucks({ path: hotel, fileName: '发票_hotel.pdf', invoiceNo: '24312000000000000002', category: '酒店住宿' }), - [meal]: starbucks({ path: meal, fileName: '发票_meal.pdf', invoiceNo: '24312000000000000003', category: '餐饮招待' }) - } - }) - - globalThis.__ztoolsLaunchContext = { pluginId: 'invoice-assistant', featureCode: 'invoice-travel' } - try { - const view = await mount(InvoiceAssistantCommand, host) - await settle() - await view.dropFiles([taxi, hotel, meal]) - await settle() - const titles = subItems(view).map((i) => i.props.title) - assert.equal(titles.length, 2) - assert.ok(titles.some((t) => t.startsWith('[交通出行]_'))) - assert.ok(titles.some((t) => t.startsWith('[差旅住宿]_'))) view.unmount() - } finally { - delete globalThis.__ztoolsLaunchContext } }) diff --git a/extensions/json-format/README.en.md b/extensions/json-format/README.en.md new file mode 100644 index 00000000..c39772cf --- /dev/null +++ b/extensions/json-format/README.en.md @@ -0,0 +1,22 @@ +# JSON Format + +Validate, beautify, and minify JSON syntax, and generate TypeScript, Rust, or Go type definitions from JSON payloads. + +## Usage + +- **Commands**: Beautify & validate JSON (`json`, `json format`, `json beautify`, `json validate`, `json minify`) and generate TypeScript / Go / Rust types (`json to ts`, `json to go`, `json to rust`, `json codegen`). +- **Validation & Indentation**: Validates syntax in real time with line and column error locations (handling multiline input, single quotes, trailing commas, etc.). Supports 2-space, 4-space, and Tab indentation (direct copy from the action panel offers 2-space and 4-space options). +- **Clipboard & Output**: Read JSON from the clipboard via the action panel (existing input is overwritten only if the clipboard contains valid JSON). Copying beautified JSON, single-line minified JSON, or type definitions is enabled only when the JSON is valid. +- **Type Inference**: Keys containing hyphens or non-ASCII characters produce valid identifiers while preserving original keys (`serde rename` / `json` tags). Same-named keys with different structures under different objects generate separate types. +- **Large Integer Precision**: Formatting, minifying, JSONPath extraction, and type inference process raw numeric literals without losing precision. Integers exceeding `i64` infer as `u64`, and decimals (including `1.0`) infer as floating-point types. +- **Shortcuts**: Press `⌘/Ctrl+Enter` inside the editor to format and open the details view (formatted output, type definitions, and JSONPath list), `⌘/Ctrl+K` to open the action panel, and `Esc` to go back. +- **Codegen Command (`json to ts` / `json codegen`)**: Uses "Generate Type Code" as the primary action and opens directly to the TypeScript / Go / Rust code output without indentation options. + +## Platforms & Requirements + +- Supported: Windows, macOS +- Built into the client; no separate installation required. + +## Network & Data + +- Offline only; all data stays on your device. diff --git a/extensions/json-format/plugin.json b/extensions/json-format/plugin.json index 8c04fbec..4793b6c1 100644 --- a/extensions/json-format/plugin.json +++ b/extensions/json-format/plugin.json @@ -1,7 +1,8 @@ { "id": "json-format", "name": "JSON 格式化", - "version": "2.1.6", + "version": "2.1.7", + "minAppVersion": "1.1.8.0", "description": "JSON 语法校验、高亮美化与压缩转义,支持一键生成 TypeScript / Go / Rust 数据结构定义", "author": "ZTools Team", "entry": "dist/index.js", @@ -32,7 +33,15 @@ "minify", "压缩", "校验", - "json转ts" + "json转ts", + "json格式化", + "json校验", + "json美化", + "json压缩", + "格式化json", + "看json", + "转ts", + "json转go" ], "features": [ { @@ -74,7 +83,14 @@ "minify", "validate", "typescript", - "codegen" + "codegen", + "json format", + "json formatter", + "json prettify", + "json validate", + "minify json", + "json beautify", + "json viewer" ], "features": { "json-beautify": { diff --git a/extensions/json-format/src/index.tsx b/extensions/json-format/src/index.tsx index db338b06..cf4455e7 100644 --- a/extensions/json-format/src/index.tsx +++ b/extensions/json-format/src/index.tsx @@ -141,7 +141,7 @@ export function JsonDetailView({ - + ) : undefined @@ -493,6 +493,7 @@ export default function JsonFormatCommand(props: { featureCode?: string } = {}) @@ -503,6 +504,7 @@ export default function JsonFormatCommand(props: { featureCode?: string } = {}) title={t("inputTitle")} placeholder={codegen ? t("inputPlaceholderCodegen") : t("inputPlaceholderMain")} value={jsonText} + autoFocus={true} onChange={(val) => setJsonText(val)} error={ outputError diff --git a/extensions/jwt-url-codec/README.en.md b/extensions/jwt-url-codec/README.en.md new file mode 100644 index 00000000..012cd5a6 --- /dev/null +++ b/extensions/jwt-url-codec/README.en.md @@ -0,0 +1,21 @@ +# JWT & URL Inspector + +Inspect JWT headers, payloads, and time claims offline, verify or sign HS256 signatures, and parse URLs and query parameters. + +## Usage + +- **Commands**: `jwt`, `token`, `url`, `urlencode`, `urldecode`, `querystring`. +- **Mode Switching**: Switch between JWT and URL modes using the dropdown on the right of the search box, then paste content into the search box to inspect (JWTs may include a `Bearer ` prefix). In JWT mode, "Re-read Token from Clipboard" in the action panel reads the clipboard and automatically switches modes based on its content. +- **JWT Inspection**: Select the overview row and press `Enter` to copy Payload JSON or `⌘/Ctrl+Enter` to copy Header JSON. Time status updates every second; "Not expired" describes only the time claims and does not guarantee signature or authorization validity. `exp` / `nbf` / `iat` are parsed in seconds—values that appear to be in milliseconds are flagged as invalid time claims. +- **Signature Verification**: Copy the secret to your clipboard first, then press `⌘/Ctrl+K` on the overview row and choose "Verify HS256 Signature with Clipboard Secret". Spaces inside the secret are included verbatim; re-verify after modifying the token. +- **Signing JWTs**: In JWT mode, click "Sign JWT" at the top, enter the Payload, Header, and secret, and press `⌘/Ctrl+Enter` to sign and copy. Only HS256 is supported; `crit` and `b64` extensions are not supported, no expiration claim is added automatically, and secrets are never saved. If copying fails, the form stays open for retry. +- **URL Inspection**: Supports full URLs, host/path strings, and query strings such as `?a=1` or `a=1&b=2`. Press `Enter` to copy the full URL (preserving encoding) or `⌘/Ctrl+Enter` to copy Query parameters as JSON (duplicate keys are preserved as arrays). Queries are decoded once for read-only preview. +- **Security Notes**: A matching signature proves only that the token matches the supplied secret—it does not verify issuer, audience, or authorization policies. Inputs render verbatim as plain text and are never loaded as Markdown images or links. + +## Platforms & Requirements + +- Supported: Windows, macOS + +## Network & Data + +- Offline only; all data stays on your device. diff --git a/extensions/jwt-url-codec/plugin.json b/extensions/jwt-url-codec/plugin.json index e3199922..100930d3 100644 --- a/extensions/jwt-url-codec/plugin.json +++ b/extensions/jwt-url-codec/plugin.json @@ -1,7 +1,8 @@ { "id": "jwt-url-codec", "name": "JWT与URL解析", - "version": "1.0.8", + "version": "1.0.9", + "minAppVersion": "1.1.8.0", "description": "离线解析 JWT Token(Header/Payload/生命周期倒计时/HMAC-SHA256 验签与签发)与深度 URL Query 参数拆解重组工具", "author": "ZTools Team", "category": [ @@ -57,7 +58,13 @@ "querystring", "hmac", "decode", - "encode" + "encode", + "jwt decode", + "url parser", + "query params", + "url decode", + "bearer token", + "inspect jwt" ], "features": { "jwt-url-codec": { @@ -86,5 +93,15 @@ { "path": "screenshots/02-action-panel.png" } + ], + "keywords": [ + "jwt", + "jwt解析", + "token解析", + "url解析", + "链接参数", + "网址参数", + "解析token", + "解码jwt" ] } diff --git a/extensions/jwt-url-codec/src/native-ipc.ts b/extensions/jwt-url-codec/src/native-ipc.ts index 51576b99..13643277 100644 --- a/extensions/jwt-url-codec/src/native-ipc.ts +++ b/extensions/jwt-url-codec/src/native-ipc.ts @@ -174,11 +174,13 @@ function normalizeMethodResult(method: string, payload: DynamicBridge): DynamicB if (method === 'system_get_battery_status') { // 宿主约定 percent 超出 0-100(如 255)表示无电池或电量未知,不能改写成 100% + // 若宿主明确给出 hasBattery 布尔值,必须原样保留,仅在缺失时按合法电量推算 const rawPct = payload.percent - const hasBattery = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const validPct = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const hasBattery = typeof payload.hasBattery === 'boolean' ? payload.hasBattery : validPct return { ...payload, - percent: hasBattery ? rawPct : null, + percent: validPct ? rawPct : null, hasBattery } } @@ -489,6 +491,8 @@ export interface RealDirectoryScanResult extends Iterable approximate?: boolean /** 宿主实际遍历的条目数 */ visitedEntries?: number + /** 目录本身不存在(ENOENT) */ + missing?: boolean /** 读取失败的真实原因;已有文件仍可使用,但不能当作完整结果。 */ error?: string } @@ -497,6 +501,7 @@ interface ScanResultMeta { truncated?: boolean approximate?: boolean visitedEntries?: number + missing?: boolean } export interface ScanDirectoryTreeOptions { @@ -504,6 +509,10 @@ export interface ScanDirectoryTreeOptions { maxFiles?: number collectTopN?: number filterExt?: RegExp + /** 为 true 时,目录本身不存在(ENOENT)按空目录处理,不返回 error(权限拒绝/读取失败仍照常报错) */ + ignoreMissing?: boolean + /** Top-N 保留与排序方式:默认按体积降序,下载/录屏等时效场景可传 mtime-desc */ + sortBy?: 'size-desc' | 'mtime-desc' hostOverride?: DynamicBridge } @@ -519,8 +528,9 @@ function normalizeIndexedFileEntry(f: DynamicBridge): RealIndexedFileEntry { const sz = Number(f?.size ?? f?.sizeBytes ?? 0) const isDir = Boolean(f?.is_dir || f?.isDir || f?.isDirectory) const rawMtime = Number(f?.mtime ?? f?.mtimeMs ?? 0) - const mtimeMs = rawMtime > 1e11 ? rawMtime : rawMtime > 0 ? rawMtime * 1000 : Date.now() - const mtimeSec = rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime + const validMtime = Number.isFinite(rawMtime) && rawMtime > 0 + const mtimeMs = validMtime ? (rawMtime > 1e11 ? rawMtime : rawMtime * 1000) : 0 + const mtimeSec = validMtime ? (rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime) : 0 if (p && sz >= 0) realFileSizeCache.set(p, sz) return { name, @@ -551,6 +561,7 @@ function makeScanResult( subdirs, ...(meta.truncated ? { truncated: true } : {}), ...(meta.approximate ? { approximate: true } : {}), + ...(meta.missing ? { missing: true } : {}), ...(typeof meta.visitedEntries === 'number' ? { visitedEntries: meta.visitedEntries } : {}), [Symbol.iterator]() { return files[Symbol.iterator]() @@ -609,13 +620,40 @@ export async function scanRealDirectoryTree( return result.error ? { ...result.scan, error: result.error } : result.scan } +/** 仅当正则明确声明了扩展名(含 `\.`)时提取后缀列表,避免把 `thumbcache|iconcache` 等文件名关键词误拆成假扩展名 */ +function extractExtensionTokensFromFilter(filterExt: RegExp): string[] { + const src = filterExt.source + if (!src.includes('\\.')) return [] + const afterDot = src.slice(src.indexOf('\\.') + 2) + const rawTokens = afterDot.match(/[a-z0-9]{1,8}/gi) || [] + const seen = new Set() + const out: string[] = [] + for (const token of rawTokens) { + const lower = token.toLowerCase() + if (!lower || seen.has(lower)) continue + seen.add(lower) + out.push(lower) + } + return out +} + +function isMissingDirectoryError(res: { error?: string; errorCode?: string; errorDetails?: Record }): boolean { + if (res.errorDetails?.reason === 'ENOENT' || res.errorCode === 'ENOENT') return true + const msg = String(res.error || '') + return /Directory does not exist|ENOENT/i.test(msg) +} + /** 一次界面扫描的错误汇总;多个目录并行扫描时保留可读目录的结果。 */ export function createDirectoryScanner(hostOverride?: DynamicBridge) { const failures = new Map() return { async scan(dir: string, options: number | ScanDirectoryTreeOptions = 160) { const result = await scanRealDirectoryTree(dir, options, hostOverride) - const error = result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') + const ignoreMissing = typeof options === 'object' && options !== null && options.ignoreMissing === true + const error = + result.missing && ignoreMissing + ? '' + : result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') if (error) failures.set(dir, error) else failures.delete(dir) return result @@ -648,26 +686,38 @@ async function scanDirectoryTreeWithError( const safeLimit = Math.min(200, Math.max(1, Math.floor(rawLimit || 160))) const hostOverride = opts.hostOverride const filterExt = opts.filterExt + const ignoreMissing = opts.ignoreMissing === true const dirQuery = `dir:${targetDir}` try { let rawPayload: DynamicBridge = null + const searchParams: Record = { + query: dirQuery, + limit: safeLimit, + ...(opts.sortBy ? { sortBy: opts.sortBy } : {}) + } const res = await callHostTransport( 'system_search_files', - { query: dirQuery, limit: safeLimit }, + searchParams, hostOverride ) - if (res.ok && res.data) { + if (res.ok && res.data && res.data.degraded !== true) { rawPayload = res.data + } else if (!res.ok && ignoreMissing && isMissingDirectoryError(res)) { + const missingScan = makeScanResult([], 0, 0, [], { missing: true }) + return { scan: missingScan } } - if (!rawPayload && !hostOverride && typeof window !== 'undefined') { + if (!rawPayload && !hostOverride && res.errorCode === 'METHOD_NOT_AVAILABLE' && typeof window !== 'undefined') { const w = window as DynamicBridge if (typeof w.__ztoolsLauncher?.searchFiles === 'function') { const rawOuter = await w.__ztoolsLauncher.searchFiles(dirQuery, safeLimit) - rawPayload = + const candidate = rawOuter && typeof rawOuter === 'object' && 'data' in rawOuter && rawOuter.data ? rawOuter.data : rawOuter + if (candidate && candidate.degraded !== true && candidate.success !== false) { + rawPayload = candidate + } } } @@ -678,29 +728,32 @@ async function scanDirectoryTreeWithError( let files: RealIndexedFileEntry[] = rawPayload.files.map(normalizeIndexedFileEntry) if (filterExt instanceof RegExp) { files = files.filter(f => !f.isDir && (filterExt.test(f.name) || filterExt.test(f.ext))) - // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索目标扩展名 + // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索明确声明的目标扩展名 if (files.length === 0 && !hostOverride) { - const extTokens = (filterExt.source.match(/[a-z0-9]{2,5}/gi) || []) - .filter(t => !['thumbcache', 'iconcache'].includes(t.toLowerCase())) - .slice(0, 4) - // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 - const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() - const extraLists = await Promise.all( - extTokens.map(ext => searchRealIndexedFiles(`.${ext.toLowerCase()}`, 30, hostOverride)) - ) - const seen = new Set() - for (const list of extraLists) { - for (const item of list) { - if (!item.isDir && item.size > 0 && !seen.has(item.path)) { - if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { - seen.add(item.path) - files.push(item) + const extTokens = extractExtensionTokensFromFilter(filterExt) + if (extTokens.length > 0) { + // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 + const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() + const extraLists = await Promise.all( + extTokens.map(ext => searchRealIndexedFiles(`.${ext}`, 30, hostOverride)) + ) + const seen = new Set() + for (const list of extraLists) { + for (const item of list) { + if (!item.isDir && item.size > 0 && !seen.has(item.path)) { + if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { + seen.add(item.path) + files.push(item) + } } } } } } } + // 先基于过滤后的完整命中集合计算总文件数与总字节数,再按 collectTopN 裁剪样本列表 + const matchedCount = files.length + const matchedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) if (typeof opts.collectTopN === 'number' && opts.collectTopN > 0 && files.length > opts.collectTopN) { files = files.slice(0, opts.collectTopN) } @@ -714,11 +767,10 @@ async function scanDirectoryTreeWithError( ...(s.approximate === true ? { approximate: true } : {}) })) : [] - const computedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) const totalFilesCount = - filterExt instanceof RegExp ? files.length : Number(rawPayload.total_matches ?? files.length) + filterExt instanceof RegExp ? matchedCount : Number(rawPayload.total_matches ?? matchedCount) const totalBytesCount = - filterExt instanceof RegExp ? computedBytes : Number(rawPayload.total_bytes ?? computedBytes) + filterExt instanceof RegExp ? matchedBytes : Number(rawPayload.total_bytes ?? matchedBytes) const visited = Number(rawPayload.visited_entries) return { scan: makeScanResult(files, totalFilesCount, totalBytesCount, subdirs, { @@ -1817,8 +1869,6 @@ export async function writeRealClipboardText(text: string, hostOverride?: Dynami const payload = { text: String(text || '') } const res = await callHostTransport('clipboard_copy_text', payload, hostOverride) if (res.ok) return true - const fallbackRes = await callHostTransport('clipboard_write_text', payload, hostOverride) - if (fallbackRes.ok) return true try { if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) { await navigator.clipboard.writeText(String(text || '')) diff --git a/extensions/jwt-url-codec/src/sign-form.tsx b/extensions/jwt-url-codec/src/sign-form.tsx index 5e1770de..08d456f1 100644 --- a/extensions/jwt-url-codec/src/sign-form.tsx +++ b/extensions/jwt-url-codec/src/sign-form.tsx @@ -35,7 +35,7 @@ export function JwtSignForm({ initialPayload = '{}', onCreated }: { initialPaylo return }> - + diff --git a/extensions/jwt-url-codec/src/url-param-form.tsx b/extensions/jwt-url-codec/src/url-param-form.tsx index 595e89b7..dce4fba1 100644 --- a/extensions/jwt-url-codec/src/url-param-form.tsx +++ b/extensions/jwt-url-codec/src/url-param-form.tsx @@ -54,6 +54,7 @@ export function UrlParamForm({ placeholder={t('urlParamKeyPlaceholder')} value={paramKey} onChange={setParamKey} + autoFocus={true} /> ) diff --git a/extensions/kill-process/README.en.md b/extensions/kill-process/README.en.md new file mode 100644 index 00000000..2392c9f9 --- /dev/null +++ b/extensions/kill-process/README.en.md @@ -0,0 +1,28 @@ +# Kill Process + +List running processes sorted by memory or CPU usage and terminate a single process or an entire process tree after confirmation. + +## Usage + +- **Command**: Kill Process (`kill-process`). +- **List & Filtering**: Displays process name, PID, memory, CPU, and thread count (fields unavailable from the client are omitted), refreshing automatically every 2 seconds (pausable at the top). If reading fails, the reason is shown in the top status bar. Filter in the search box by process name, PID, or executable path, and sort via the adjacent dropdown by Memory, CPU, Name, or PID. +- **Shortcuts**: + - `Enter`: Terminate process. + - `Ctrl+Enter`: Force terminate process. + - `Ctrl+Shift+Backspace`: Terminate entire process tree. + - `Ctrl+D`: View details (executable path and launch command line). + - `Ctrl+O`: Reveal executable in File Explorer (omitted if path is unavailable). + - `Ctrl+C`: Copy PID. + - `Ctrl+Shift+C`: Copy executable path (omitted if path is unavailable). + - `Ctrl+R`: Refresh manually. + - `Ctrl+K`: Open the action panel. +- **Safety & Confirmations**: Every termination action shows a confirmation prompt. Normal termination asks the app to exit cleanly, which may trigger a save prompt or be refused—use force terminate if needed. Force terminate and process-tree termination discard unsaved data. Critical system processes such as `csrss.exe`, `explorer.exe`, `svchost.exe`, `winlogon.exe`, `lsass.exe`, and `dwm.exe` cannot be terminated. +- **Verification**: Process names are re-checked before terminating so a reused PID is never killed by mistake. Failures (such as insufficient permissions or refusal to close) display the reason. + +## Platforms & Requirements + +- Supported: Windows only + +## Network & Data + +- Offline only; all data stays on your device. diff --git a/extensions/kill-process/plugin.json b/extensions/kill-process/plugin.json index 555067b5..6bcd51a1 100644 --- a/extensions/kill-process/plugin.json +++ b/extensions/kill-process/plugin.json @@ -2,6 +2,9 @@ "id": "kill-process", "name": "结束进程", "version": "2.0.10", + "minAppVersion": "1.1.8.0", + "revoked": true, + "revokedReason": "功能已合并至「进程监控」(process-monitor),请改用进程监控", "description": "按内存或 CPU 占用列出正在运行的进程,确认后结束单个进程或整个进程树,可用于关闭无响应的程序", "author": "ZTools Team", "category": [ @@ -30,13 +33,20 @@ "en-US": { "name": "Kill Process", "description": "List running processes sorted by memory or CPU usage and terminate a single process or entire process tree after confirmation to close unresponsive apps.", + "revokedReason": "Merged into \"Process & Port Monitor\" (process-monitor). Please use Process & Port Monitor instead.", "keywords": [ "kill", "process", "task manager", "terminate", "cpu", - "memory" + "memory", + "kill process", + "end task", + "force quit", + "frozen app", + "kill app", + "stop process" ], "screenshots": [ { @@ -49,5 +59,16 @@ { "path": "screenshots/01.png" } + ], + "keywords": [ + "结束进程", + "杀进程", + "强杀", + "软件卡死", + "强制关闭", + "任务管理器", + "关不掉", + "杀掉程序", + "kill" ] } diff --git a/extensions/kill-process/src/index.tsx b/extensions/kill-process/src/index.tsx index fa83d848..dcb839d1 100644 --- a/extensions/kill-process/src/index.tsx +++ b/extensions/kill-process/src/index.tsx @@ -436,17 +436,6 @@ export default function KillProcessCommand() { shortcut={{ modifiers: ["ctrl", "shift"], key: "c" }} /> ) : null} - - } /> diff --git a/extensions/kill-process/src/native-ipc.ts b/extensions/kill-process/src/native-ipc.ts index 51576b99..b8c547d6 100644 --- a/extensions/kill-process/src/native-ipc.ts +++ b/extensions/kill-process/src/native-ipc.ts @@ -174,11 +174,13 @@ function normalizeMethodResult(method: string, payload: DynamicBridge): DynamicB if (method === 'system_get_battery_status') { // 宿主约定 percent 超出 0-100(如 255)表示无电池或电量未知,不能改写成 100% + // 若宿主明确给出 hasBattery 布尔值,必须原样保留,仅在缺失时按合法电量推算 const rawPct = payload.percent - const hasBattery = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const validPct = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const hasBattery = typeof payload.hasBattery === 'boolean' ? payload.hasBattery : validPct return { ...payload, - percent: hasBattery ? rawPct : null, + percent: validPct ? rawPct : null, hasBattery } } @@ -1817,8 +1819,6 @@ export async function writeRealClipboardText(text: string, hostOverride?: Dynami const payload = { text: String(text || '') } const res = await callHostTransport('clipboard_copy_text', payload, hostOverride) if (res.ok) return true - const fallbackRes = await callHostTransport('clipboard_write_text', payload, hostOverride) - if (fallbackRes.ok) return true try { if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) { await navigator.clipboard.writeText(String(text || '')) diff --git a/extensions/lan-scanner/README.en.md b/extensions/lan-scanner/README.en.md new file mode 100644 index 00000000..93263675 --- /dev/null +++ b/extensions/lan-scanner/README.en.md @@ -0,0 +1,24 @@ +# LAN Scanner & WoL + +Open LAN Scanner (`lan`, `ip scanner`, `lan scan`) and select a network interface to list responding hosts on the subnet along with the local machine. Press `Enter` to copy the IP, `⌘/Ctrl+Enter` to inspect ports and probe details, and use the action panel to open web services or favorite a MAC address. + +Each scan checks up to 256 IPv4 addresses within the selected interface's subnet. Subnets larger than `/24` can be checked in segments via "Select Range" within the same subnet; smaller subnets use the actual subnet mask without crossing boundaries. Click "Stop Scan" at any time while scanning. + +Probing covers ICMP and TCP ports `22`, `80`, `443`, `445`, `3389`, `5900`, `8080`, and `8443`. Firewalls, sleep mode, and wireless client isolation can cause missed detections; no response does not prove a device is offline or that other ports are closed. MAC addresses are enriched from the system ARP cache, and a cache entry alone is not treated as proof a host is online. TCP connect duration does not represent ping latency. + +macOS 27 introduced a dedicated code-signing entitlement for reading network topology; clients without that entitlement may receive an empty neighbor table even if MAC addresses are visible in Terminal. In that case, the UI displays a clear notice while scanned IPs and ports remain usable and Wake-on-LAN accepts manually entered MAC addresses ([Apple Developer Forums](https://developer.apple.com/forums/thread/822025?page=2)). + +The **Wake-on-LAN** command (`wol`, `wakeonlan`, `wake on lan`) lets you enter a MAC address or pick a saved favorite without scanning first. It sends a 102-byte magic packet to UDP port 9 on the selected interface's broadcast address. The target device must have Wake-on-LAN enabled and the network must support broadcast forwarding; a success message confirms only that the OS sent the magic packet, not that the machine powered on. Favorites are stored locally, and read failures never overwrite existing records. + +On Windows, the scanner uses the system `ping` and ARP table: a host counts as ICMP-online only when a reply with TTL comes from the target itself (not a gateway "Destination host unreachable" reply). Windows also retries RST responses on closed TCP ports, which may exceed the 350 ms per-port timeout, making devices that ignore ping and have all probed ports closed more likely to be missed. + +## Platforms & Requirements + +- Supported: Windows, macOS +- Requires client version 1.1.8.5 or later. +- Windows implementation is pending physical-device verification. + +## Network & Data + +- Probes only within the selected interface's local subnet (ICMP and the TCP ports listed above) and sends Wake-on-LAN packets only to that interface's broadcast address; never connects to external servers. +- Saved MAC favorites stay on your device. diff --git a/extensions/lan-scanner/plugin.json b/extensions/lan-scanner/plugin.json index 7c890a70..141f02b4 100644 --- a/extensions/lan-scanner/plugin.json +++ b/extensions/lan-scanner/plugin.json @@ -1,7 +1,7 @@ { "id": "lan-scanner", "name": "局域网扫描", - "version": "1.0.7", + "version": "1.0.8", "description": "探测局域网设备与常见 TCP 端口,支持 MAC 收藏及 Wake-on-LAN 广播唤醒;每次分段扫描最多 256 个地址", "author": "ZTools Team", "category": [ @@ -66,7 +66,12 @@ "network", "ports", "wol", - "wake on lan" + "wake on lan", + "lan scanner", + "network scan", + "local devices", + "arp", + "devices on wifi" ], "features": { "lan-scan-all": { @@ -102,5 +107,16 @@ { "path": "screenshots/02-action-panel.png" } + ], + "keywords": [ + "局域网扫描", + "内网设备", + "谁连了我wifi", + "扫ip", + "局域网ip", + "远程开机", + "网络唤醒", + "wol", + "蹭网检测" ] } diff --git a/extensions/lan-scanner/src/mac-forms.tsx b/extensions/lan-scanner/src/mac-forms.tsx index 2342fe06..cc3d335a 100644 --- a/extensions/lan-scanner/src/mac-forms.tsx +++ b/extensions/lan-scanner/src/mac-forms.tsx @@ -8,7 +8,7 @@ export function RangeForm({ address, saved }: { address: string; saved: (value: if (!/^(0|[1-9]\d{0,2})(\.(0|[1-9]\d{0,2})){3}$/.test(value.trim()) || value.trim().split('.').some(v => Number(v) > 255)) { setError(t('rangeErrInvalidIp')); return } saved(value.trim()); pop() }} />}> - + } @@ -46,7 +46,7 @@ export function WakeForm({ initialMac = '' }: { initialMac?: string } = {}) { }> {interfaces.map(v => )} - + {saved.length > 0 && { if (value) setMac(value) }}>{saved.map(v => )}} diff --git a/extensions/lan-share/README.en.md b/extensions/lan-share/README.en.md new file mode 100644 index 00000000..e487344d --- /dev/null +++ b/extensions/lan-share/README.en.md @@ -0,0 +1,22 @@ +# LAN File Share + +Select files on your computer to add to the share list and start the client's local network sharing service so phones or PCs on the same network can open the local URL (or scan the QR code) in a browser to download them. + +## Usage + +- **Command**: LAN File Share (`lan-share`). +- **Service Control**: The first row represents the sharing service. Press `Enter` to start it when stopped; while running, the right pane displays the access URL and QR code, `Enter` copies the access URL, and `Ctrl+Enter` stops the service. Opening the plugin only reads status and never starts the service automatically. The service row's action panel (`Ctrl+K`) includes "Refresh Share Status". +- **Adding Files**: Click "Select Files" at the top for multi-file selection, or "Select Folder" to automatically collect up to 500 non-hidden regular files within 5 directory levels and add them in batches; dragging and dropping or pasting files and folders is also supported. If files in different subfolders share the same filename, a notice reminds you to distinguish them by size on the web page; unreadable files are skipped with a notice. +- **File Actions**: Remaining rows show shared files with their download URL and QR code on the right. `Enter` copies the download URL (available when the service is running and the file is active), `Ctrl+Enter` pauses or resumes sharing that file, `Ctrl+Backspace` removes it from the share list, and `Ctrl+Shift+Backspace` clears the share list (items are only removed from the list; original files are never deleted). +- **Network Addresses**: If your phone cannot open the primary address, additional local IP addresses are listed on the right side of the service row—try one on the same network as your phone. +- **Firewall**: On first launch of the service, Windows Firewall may ask whether to allow ZTools network access; allow it so other devices can connect. +- **Current Limitations**: The share web page supports file downloads only—uploading from a phone, sharing clipboard text, and downloading entire folders from the web page are not supported. + +## Platforms & Requirements + +- Supported: Windows only + +## Network & Data + +- The plugin only queries and updates sharing state in the client and never accesses the external internet. +- While running, the client's sharing service serves HTTP across all local network interfaces without a password, so any device on the same network can view the shared list and download those files. The service continues running after you close the plugin until you stop it in the plugin or exit ZTools—stop the service when not in use. diff --git a/extensions/lan-share/plugin.json b/extensions/lan-share/plugin.json index 0fa8a163..5868de25 100644 --- a/extensions/lan-share/plugin.json +++ b/extensions/lan-share/plugin.json @@ -2,7 +2,8 @@ "id": "lan-share", "name": "局域网传文件", "description": "选择电脑上的文件或文件夹开启局域网共享,同一网络的手机或电脑用浏览器打开本机地址或扫码即可下载;共享不需要密码,只支持从电脑下载,不支持从手机上传", - "version": "2.0.14", + "version": "2.0.15", + "minAppVersion": "1.1.8.0", "author": "ZTools Team", "entry": "dist/index.js", "icon": "icon.svg", @@ -40,7 +41,12 @@ "file transfer", "local share", "qr code", - "http share" + "http share", + "airdrop", + "send file", + "share to phone", + "qr transfer", + "wifi transfer" ], "screenshots": [ { @@ -56,5 +62,16 @@ { "path": "screenshots/02-action-panel.png" } + ], + "keywords": [ + "局域网传文件", + "传文件", + "手机传电脑", + "电脑传手机", + "扫码传文件", + "隔空投送", + "快传", + "内网分享", + "互传" ] } diff --git a/extensions/lan-share/src/native-ipc.ts b/extensions/lan-share/src/native-ipc.ts index 51576b99..13643277 100644 --- a/extensions/lan-share/src/native-ipc.ts +++ b/extensions/lan-share/src/native-ipc.ts @@ -174,11 +174,13 @@ function normalizeMethodResult(method: string, payload: DynamicBridge): DynamicB if (method === 'system_get_battery_status') { // 宿主约定 percent 超出 0-100(如 255)表示无电池或电量未知,不能改写成 100% + // 若宿主明确给出 hasBattery 布尔值,必须原样保留,仅在缺失时按合法电量推算 const rawPct = payload.percent - const hasBattery = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const validPct = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const hasBattery = typeof payload.hasBattery === 'boolean' ? payload.hasBattery : validPct return { ...payload, - percent: hasBattery ? rawPct : null, + percent: validPct ? rawPct : null, hasBattery } } @@ -489,6 +491,8 @@ export interface RealDirectoryScanResult extends Iterable approximate?: boolean /** 宿主实际遍历的条目数 */ visitedEntries?: number + /** 目录本身不存在(ENOENT) */ + missing?: boolean /** 读取失败的真实原因;已有文件仍可使用,但不能当作完整结果。 */ error?: string } @@ -497,6 +501,7 @@ interface ScanResultMeta { truncated?: boolean approximate?: boolean visitedEntries?: number + missing?: boolean } export interface ScanDirectoryTreeOptions { @@ -504,6 +509,10 @@ export interface ScanDirectoryTreeOptions { maxFiles?: number collectTopN?: number filterExt?: RegExp + /** 为 true 时,目录本身不存在(ENOENT)按空目录处理,不返回 error(权限拒绝/读取失败仍照常报错) */ + ignoreMissing?: boolean + /** Top-N 保留与排序方式:默认按体积降序,下载/录屏等时效场景可传 mtime-desc */ + sortBy?: 'size-desc' | 'mtime-desc' hostOverride?: DynamicBridge } @@ -519,8 +528,9 @@ function normalizeIndexedFileEntry(f: DynamicBridge): RealIndexedFileEntry { const sz = Number(f?.size ?? f?.sizeBytes ?? 0) const isDir = Boolean(f?.is_dir || f?.isDir || f?.isDirectory) const rawMtime = Number(f?.mtime ?? f?.mtimeMs ?? 0) - const mtimeMs = rawMtime > 1e11 ? rawMtime : rawMtime > 0 ? rawMtime * 1000 : Date.now() - const mtimeSec = rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime + const validMtime = Number.isFinite(rawMtime) && rawMtime > 0 + const mtimeMs = validMtime ? (rawMtime > 1e11 ? rawMtime : rawMtime * 1000) : 0 + const mtimeSec = validMtime ? (rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime) : 0 if (p && sz >= 0) realFileSizeCache.set(p, sz) return { name, @@ -551,6 +561,7 @@ function makeScanResult( subdirs, ...(meta.truncated ? { truncated: true } : {}), ...(meta.approximate ? { approximate: true } : {}), + ...(meta.missing ? { missing: true } : {}), ...(typeof meta.visitedEntries === 'number' ? { visitedEntries: meta.visitedEntries } : {}), [Symbol.iterator]() { return files[Symbol.iterator]() @@ -609,13 +620,40 @@ export async function scanRealDirectoryTree( return result.error ? { ...result.scan, error: result.error } : result.scan } +/** 仅当正则明确声明了扩展名(含 `\.`)时提取后缀列表,避免把 `thumbcache|iconcache` 等文件名关键词误拆成假扩展名 */ +function extractExtensionTokensFromFilter(filterExt: RegExp): string[] { + const src = filterExt.source + if (!src.includes('\\.')) return [] + const afterDot = src.slice(src.indexOf('\\.') + 2) + const rawTokens = afterDot.match(/[a-z0-9]{1,8}/gi) || [] + const seen = new Set() + const out: string[] = [] + for (const token of rawTokens) { + const lower = token.toLowerCase() + if (!lower || seen.has(lower)) continue + seen.add(lower) + out.push(lower) + } + return out +} + +function isMissingDirectoryError(res: { error?: string; errorCode?: string; errorDetails?: Record }): boolean { + if (res.errorDetails?.reason === 'ENOENT' || res.errorCode === 'ENOENT') return true + const msg = String(res.error || '') + return /Directory does not exist|ENOENT/i.test(msg) +} + /** 一次界面扫描的错误汇总;多个目录并行扫描时保留可读目录的结果。 */ export function createDirectoryScanner(hostOverride?: DynamicBridge) { const failures = new Map() return { async scan(dir: string, options: number | ScanDirectoryTreeOptions = 160) { const result = await scanRealDirectoryTree(dir, options, hostOverride) - const error = result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') + const ignoreMissing = typeof options === 'object' && options !== null && options.ignoreMissing === true + const error = + result.missing && ignoreMissing + ? '' + : result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') if (error) failures.set(dir, error) else failures.delete(dir) return result @@ -648,26 +686,38 @@ async function scanDirectoryTreeWithError( const safeLimit = Math.min(200, Math.max(1, Math.floor(rawLimit || 160))) const hostOverride = opts.hostOverride const filterExt = opts.filterExt + const ignoreMissing = opts.ignoreMissing === true const dirQuery = `dir:${targetDir}` try { let rawPayload: DynamicBridge = null + const searchParams: Record = { + query: dirQuery, + limit: safeLimit, + ...(opts.sortBy ? { sortBy: opts.sortBy } : {}) + } const res = await callHostTransport( 'system_search_files', - { query: dirQuery, limit: safeLimit }, + searchParams, hostOverride ) - if (res.ok && res.data) { + if (res.ok && res.data && res.data.degraded !== true) { rawPayload = res.data + } else if (!res.ok && ignoreMissing && isMissingDirectoryError(res)) { + const missingScan = makeScanResult([], 0, 0, [], { missing: true }) + return { scan: missingScan } } - if (!rawPayload && !hostOverride && typeof window !== 'undefined') { + if (!rawPayload && !hostOverride && res.errorCode === 'METHOD_NOT_AVAILABLE' && typeof window !== 'undefined') { const w = window as DynamicBridge if (typeof w.__ztoolsLauncher?.searchFiles === 'function') { const rawOuter = await w.__ztoolsLauncher.searchFiles(dirQuery, safeLimit) - rawPayload = + const candidate = rawOuter && typeof rawOuter === 'object' && 'data' in rawOuter && rawOuter.data ? rawOuter.data : rawOuter + if (candidate && candidate.degraded !== true && candidate.success !== false) { + rawPayload = candidate + } } } @@ -678,29 +728,32 @@ async function scanDirectoryTreeWithError( let files: RealIndexedFileEntry[] = rawPayload.files.map(normalizeIndexedFileEntry) if (filterExt instanceof RegExp) { files = files.filter(f => !f.isDir && (filterExt.test(f.name) || filterExt.test(f.ext))) - // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索目标扩展名 + // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索明确声明的目标扩展名 if (files.length === 0 && !hostOverride) { - const extTokens = (filterExt.source.match(/[a-z0-9]{2,5}/gi) || []) - .filter(t => !['thumbcache', 'iconcache'].includes(t.toLowerCase())) - .slice(0, 4) - // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 - const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() - const extraLists = await Promise.all( - extTokens.map(ext => searchRealIndexedFiles(`.${ext.toLowerCase()}`, 30, hostOverride)) - ) - const seen = new Set() - for (const list of extraLists) { - for (const item of list) { - if (!item.isDir && item.size > 0 && !seen.has(item.path)) { - if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { - seen.add(item.path) - files.push(item) + const extTokens = extractExtensionTokensFromFilter(filterExt) + if (extTokens.length > 0) { + // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 + const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() + const extraLists = await Promise.all( + extTokens.map(ext => searchRealIndexedFiles(`.${ext}`, 30, hostOverride)) + ) + const seen = new Set() + for (const list of extraLists) { + for (const item of list) { + if (!item.isDir && item.size > 0 && !seen.has(item.path)) { + if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { + seen.add(item.path) + files.push(item) + } } } } } } } + // 先基于过滤后的完整命中集合计算总文件数与总字节数,再按 collectTopN 裁剪样本列表 + const matchedCount = files.length + const matchedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) if (typeof opts.collectTopN === 'number' && opts.collectTopN > 0 && files.length > opts.collectTopN) { files = files.slice(0, opts.collectTopN) } @@ -714,11 +767,10 @@ async function scanDirectoryTreeWithError( ...(s.approximate === true ? { approximate: true } : {}) })) : [] - const computedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) const totalFilesCount = - filterExt instanceof RegExp ? files.length : Number(rawPayload.total_matches ?? files.length) + filterExt instanceof RegExp ? matchedCount : Number(rawPayload.total_matches ?? matchedCount) const totalBytesCount = - filterExt instanceof RegExp ? computedBytes : Number(rawPayload.total_bytes ?? computedBytes) + filterExt instanceof RegExp ? matchedBytes : Number(rawPayload.total_bytes ?? matchedBytes) const visited = Number(rawPayload.visited_entries) return { scan: makeScanResult(files, totalFilesCount, totalBytesCount, subdirs, { @@ -1817,8 +1869,6 @@ export async function writeRealClipboardText(text: string, hostOverride?: Dynami const payload = { text: String(text || '') } const res = await callHostTransport('clipboard_copy_text', payload, hostOverride) if (res.ok) return true - const fallbackRes = await callHostTransport('clipboard_write_text', payload, hostOverride) - if (fallbackRes.ok) return true try { if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) { await navigator.clipboard.writeText(String(text || '')) diff --git a/extensions/linux-http-dict/README.en.md b/extensions/linux-http-dict/README.en.md new file mode 100644 index 00000000..816a91fa --- /dev/null +++ b/extensions/linux-http-dict/README.en.md @@ -0,0 +1,18 @@ +# Linux & HTTP Cheatsheet + +Offline quick reference for common Linux command examples, HTTP status code meanings and troubleshooting steps, and default ports for common services. + +## Usage + +- Commands: `linux` (keywords such as `tldr`, `shell commands`, `tar`), `http status` (`status code`, `502`, `403`), and `ports` (`default ports`, `3306`, `8080`) open each category respectively; use the dropdown next to the search box to switch categories. +- Includes practical examples and option descriptions for 10 Linux command groups (`tar`, `unzip`, `find`, `lsof`, `ss`, `netstat`, `grep`, `awk`, `systemctl`, `du` / `df`); meanings, common causes, and troubleshooting steps for 13 HTTP status codes (`200`, `301`, `304`, `400`, `401`, `403`, `404`, `429`, `499`, `500`, `502`, `503`, `504`); and 12 common ports (`22`, `53`, `80`, `443`, `3306`, `5432`, `6379`, `8080`, `8848`, `9092`, `9200`, `27017`). +- Search supports command names, scenario descriptions, status code numbers, port numbers, or service names. +- Linux commands: `Enter` copies the first example, `Cmd/Ctrl+Enter` copies all examples. Status codes: `Enter` copies the troubleshooting summary, `Cmd/Ctrl+Enter` copies only the status code number. Ports: `Enter` copies the port number, `Cmd/Ctrl+Enter` copies the Linux `ss -tulpn | grep :` inspection command, with corresponding macOS (`lsof`) and Windows (`netstat`) commands available in the action panel. Command examples target Linux (GNU tools); some options are unavailable on the BSD tools built into macOS. Press `Cmd/Ctrl+K` to open the action panel. + +## Platforms & Requirements + +- Supported: Windows, macOS + +## Network & Data + +- Works offline; all content is bundled inside the plugin. diff --git a/extensions/linux-http-dict/plugin.json b/extensions/linux-http-dict/plugin.json index 037a5fec..cc8b1b8c 100644 --- a/extensions/linux-http-dict/plugin.json +++ b/extensions/linux-http-dict/plugin.json @@ -1,7 +1,8 @@ { "id": "linux-http-dict", "name": "命令与状态码", - "version": "1.0.5", + "version": "1.0.6", + "minAppVersion": "1.1.8.0", "description": "离线速查 Linux 常用命令示例、常见 HTTP 状态码含义与排查步骤、常用服务默认端口", "author": "ZTools Team", "category": [ @@ -81,7 +82,15 @@ "ports", "tldr", "shell", - "cheatsheet" + "cheatsheet", + "linux commands", + "http status", + "status codes", + "404", + "502", + "cli reference", + "man", + "shell commands" ], "features": { "linux-commands": { @@ -131,5 +140,16 @@ { "path": "screenshots/02-action-panel.png" } + ], + "keywords": [ + "linux命令", + "http状态码", + "状态码查询", + "404", + "502", + "500", + "命令速查", + "运维速查", + "常见命令" ] } diff --git a/extensions/linux-http-dict/src/index.tsx b/extensions/linux-http-dict/src/index.tsx index d475812e..642efd6f 100644 --- a/extensions/linux-http-dict/src/index.tsx +++ b/extensions/linux-http-dict/src/index.tsx @@ -112,7 +112,7 @@ ${item.params.map((p) => `| \`${p.flag}\` | ${p.desc} |`).join('\n')} `# ${e.title}\n${e.cmd}`).join('\n\n')} - shortcut={{ modifiers: ['cmd', 'shift'], key: 'c' }} + shortcut={{ modifiers: ['ctrl', 'shift'], key: 'c' }} /> } diff --git a/extensions/md-to-office/README.en.md b/extensions/md-to-office/README.en.md new file mode 100644 index 00000000..39262a1b --- /dev/null +++ b/extensions/md-to-office/README.en.md @@ -0,0 +1,22 @@ +# Markdown to Word + +Convert Markdown text or files locally into a new Word (`.docx`) copy, or copy as rich text ready to paste into Word or WPS. + +## Usage + +- Commands: `md to word`, `markdown to word`, `export word`; `copy for word` (`clipboard to word`, `rich text paste`) reads the clipboard and immediately copies rich text using the default Formal Document style. +- Reads the clipboard on open; you can also click "Open File" at the top to choose a UTF-8 encoded `.md`, `.markdown`, or `.txt` file, or select "Edit Markdown" in the action panel. Maximum size is 256 KiB per document. +- Choose the layout style (Formal Document, Business Report, Academic Three-Line Table), body font size, and first-line indentation on the left. +- With a document selected, press `Enter` to save a new `.docx` copy, or `Cmd/Ctrl+Enter` to copy as rich text; `Cmd/Ctrl+K` also provides Edit Markdown and Copy Raw Markdown. +- Supports headings, bold, italic, strikethrough, lists, tables, links, and code blocks. Images keep only alt text and URL without downloading images or reading referenced local files; raw HTML is kept as plain text; code blocks preserve monospace formatting and line breaks without syntax highlighting. +- Saving as `.docx`: When choosing an existing file, it is overwritten only after you confirm replacement in the system save dialog; canceling the dialog generates no file. Errors are shown if any content cannot be preserved, or if file writing or clipboard verification fails. +- Actual rendered fonts depend on the device opening the document; the Formal Document style is a layout preset and does not imply compliance with any formal publishing standard. + +## Platforms & Requirements + +- Supported: Windows, macOS +- Requires ZTools 1.1.8.5 or later. + +## Network & Data + +- Works offline; data stays strictly on your local device. diff --git a/extensions/md-to-office/plugin.json b/extensions/md-to-office/plugin.json index b866da45..698a1716 100644 --- a/extensions/md-to-office/plugin.json +++ b/extensions/md-to-office/plugin.json @@ -2,6 +2,8 @@ "id": "md-to-office", "name": "AI文档转Word", "version": "1.0.10", + "revoked": true, + "revokedReason": "功能已合并至「Markdown 阅读、大纲与转 Word 工作台」(super-markdown),请改用 super-markdown", "description": "本地将 Markdown 文本或文件转换为 Word 新副本,保留标题、列表、表格和代码块,支持公文、商务和学术排版及富文本复制", "author": "ZTools Team", "category": [ @@ -59,13 +61,20 @@ "en-US": { "name": "Markdown to Word", "description": "Convert Markdown text or files locally into Word (.docx) copies preserving headings, lists, tables, and code blocks, with formal, business, and academic styles plus rich-text copy.", + "revokedReason": "Merged into \"Markdown Reader, Outline & Word Export\" (super-markdown). Please use super-markdown instead.", "keywords": [ "markdown", "word", "docx", "convert", "office", - "export" + "export", + "markdown to word", + "md to docx", + "export word", + "convert markdown", + "ai to word", + "office export" ], "features": { "md-to-office-workbench": { @@ -100,5 +109,15 @@ { "path": "screenshots/02-action-panel.png" } + ], + "keywords": [ + "markdown转word", + "md转word", + "ai文档转word", + "转docx", + "导出word", + "chatgpt转word", + "deepseek转word", + "文档转换" ] } diff --git a/extensions/md-to-office/src/index.tsx b/extensions/md-to-office/src/index.tsx index b5e765f6..51f71cfe 100644 --- a/extensions/md-to-office/src/index.tsx +++ b/extensions/md-to-office/src/index.tsx @@ -18,7 +18,7 @@ function MarkdownForm({ initial, onApply }: { initial: string; onApply: (text: s finally { guard.current = false; if (alive.current) setBusy(false) } } return
}> - + } @@ -114,7 +114,13 @@ export function MdToOfficeCommand({ copyImmediately = false }: { copyImmediately const copyRich = () => perform(async () => { const result = await client.copy(text, options); if (alive.current) { setStatus(result.warnings.join('; ') || t('statusRichCopied')); await showToast({ style: Toast.Style.Success, title: t('toastRichCopied') }) } }) const change = (patch: Partial) => { if (!guard.current) setOptions(current => ({ ...current, ...patch })) } return clipboard() }, { id: 'open', title: t('actionOpenFile'), onAction: openFile }] }} + filterBar={{ summaryText: status || t('statusReadingClipboard'), actions: summary ? [ + { id: 'export', title: t('actionSaveWord'), style: 'primary', onAction: exportFile }, + { id: 'copy-rich', title: t('actionCopyRich'), onAction: copyRich } + ] : [ + { id: 'open', title: t('actionOpenFile'), style: 'primary', onAction: openFile }, + { id: 'clipboard', title: t('actionReadClipboard'), onAction: () => clipboard() } + ] }} workbenchPanel={{ title: t('panelTitle'), fields: [ { id: 'preset', label: t('fieldPresetLabel'), type: 'select', value: options.preset, options: [{ label: t('presetOfficial'), value: 'official' }, { label: t('presetBusiness'), value: 'business' }, { label: t('presetAcademic'), value: 'academic' }], onChange: (value: unknown) => { if (typeof value === 'string' && ['official','business','academic'].includes(value)) change({ preset: value as ConvertOptions['preset'] }) } }, { id: 'fontSize', label: t('fieldFontSizeLabel'), type: 'select', value: options.fontSize, options: [{ label: t('fontSize3'), value: 'size-3' }, { label: t('fontSizeS4'), value: 'size-s4' }, { label: t('fontSize5'), value: 'size-5' }], onChange: (value: unknown) => { if (typeof value === 'string' && ['size-3','size-s4','size-5'].includes(value)) change({ fontSize: value as ConvertOptions['fontSize'] }) } }, @@ -127,6 +133,8 @@ export function MdToOfficeCommand({ copyImmediately = false }: { copyImmediately {lastExported ? : null} {lastExported ? : null} edit()} /> + + clipboard()} /> } /> : query.trim() ? null : edit()} />} />, lastExported ? diff --git a/extensions/md-to-office/src/native-ipc.ts b/extensions/md-to-office/src/native-ipc.ts index 51576b99..b8c547d6 100644 --- a/extensions/md-to-office/src/native-ipc.ts +++ b/extensions/md-to-office/src/native-ipc.ts @@ -174,11 +174,13 @@ function normalizeMethodResult(method: string, payload: DynamicBridge): DynamicB if (method === 'system_get_battery_status') { // 宿主约定 percent 超出 0-100(如 255)表示无电池或电量未知,不能改写成 100% + // 若宿主明确给出 hasBattery 布尔值,必须原样保留,仅在缺失时按合法电量推算 const rawPct = payload.percent - const hasBattery = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const validPct = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const hasBattery = typeof payload.hasBattery === 'boolean' ? payload.hasBattery : validPct return { ...payload, - percent: hasBattery ? rawPct : null, + percent: validPct ? rawPct : null, hasBattery } } @@ -1817,8 +1819,6 @@ export async function writeRealClipboardText(text: string, hostOverride?: Dynami const payload = { text: String(text || '') } const res = await callHostTransport('clipboard_copy_text', payload, hostOverride) if (res.ok) return true - const fallbackRes = await callHostTransport('clipboard_write_text', payload, hostOverride) - if (fallbackRes.ok) return true try { if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) { await navigator.clipboard.writeText(String(text || '')) diff --git a/extensions/media-metadata/README.en.md b/extensions/media-metadata/README.en.md new file mode 100644 index 00000000..eeef8c80 --- /dev/null +++ b/extensions/media-metadata/README.en.md @@ -0,0 +1,23 @@ +# EXIF & Media Privacy Scrubber + +Read photo, audio, and video metadata locally, strip location and other tags from photos, and save a new copy while leaving the original file untouched. + +## Usage + +- Commands: `exif` (`photo metadata`, `strip exif`, `remove gps`), `clean gps` (`remove location`, `strip gps`), and `video info` (`audio info`, `codec info`, `framerate`); the last command only inspects parameters and does not perform scrubbing. +- Click "Select File" to choose JPEG, PNG, or HEIC / HEIF photos, or MP4, MOV, MP3, M4A, WAV, or FLAC audio/video files. The list shows file type, size, and whether location tags are detected. +- Choose one of two cleaning modes: + - Location and related auxiliary metadata: removes GPS coordinates along with XMP, IPTC, MakerNotes, and other fields that may contain location copies, while preserving standard EXIF shooting parameters; + - EXIF / XMP / IPTC: removes camera shooting, author, and related metadata while preserving display parameters such as orientation and color profile. +- On a photo, press `Enter` to clean and choose where to save the new copy, or `Cmd/Ctrl+Enter` to view all raw parameters read from the file; audio and video files support metadata inspection only. +- Before saving, the plugin verifies that image data and display parameters are unchanged and that location tags are removed; if any check fails, saving is aborted. The new copy must use the same extension type as the original photo and cannot overwrite the original file; if you select another existing file, it is overwritten only after confirming replacement in the system save dialog. Maximum file size is 16 MiB (audio and video files are subject to the same limit, so larger videos cannot be read). +- Does not process visual image content, filenames, or personal information appearing in text within an image; undetected fields do not guarantee absence from the file. + +## Platforms & Requirements + +- Supported: Windows, macOS +- Requires ZTools 1.1.8.5 or later. + +## Network & Data + +- Works offline; data stays strictly on your local device. diff --git a/extensions/media-metadata/plugin.json b/extensions/media-metadata/plugin.json index ffc87578..b4ce01d9 100644 --- a/extensions/media-metadata/plugin.json +++ b/extensions/media-metadata/plugin.json @@ -1,7 +1,7 @@ { "id": "media-metadata", "name": "EXIF隐私抹除", - "version": "1.0.10", + "version": "1.0.11", "description": "本地读取照片与音视频元数据,清理照片定位及拍摄信息,校验图像数据后另存新副本", "author": "ZTools Team", "category": [ @@ -79,7 +79,14 @@ "privacy", "photo", "mediainfo", - "scrub" + "scrub", + "remove metadata", + "strip exif", + "photo privacy", + "remove gps", + "image metadata", + "scrub exif", + "clean photo" ], "features": { "media-metadata-workbench": { @@ -124,5 +131,15 @@ { "path": "screenshots/02-action-panel.png" } + ], + "keywords": [ + "清除exif", + "隐私抹除", + "照片隐私", + "去除定位", + "抹除照片信息", + "exif清理", + "去掉拍摄信息", + "照片脱敏" ] } diff --git a/extensions/media-metadata/src/index.tsx b/extensions/media-metadata/src/index.tsx index 5d9b0fcf..3b3df749 100644 --- a/extensions/media-metadata/src/index.tsx +++ b/extensions/media-metadata/src/index.tsx @@ -96,7 +96,15 @@ export function MediaMetadataCommand({ featureCode = 'media-metadata-workbench' const details = {summary?.fields.map(field => )}} /> return } - filterBar={{ summaryText: error || (saved ? t('summarySaved', { name: saved.name, size: mediaSize(saved.size) }) : t('summaryLocalLimit')), actions: [{ id: 'pick', title: t('actionChooseFile'), onAction: pick }] }} + filterBar={{ + summaryText: error || (saved ? t('summarySaved', { name: saved.name, size: mediaSize(saved.size) }) : t('summaryLocalLimit')), + actions: summary?.canClean && !readonly + ? [ + { id: 'clean', title: t('actionCleanAndSave'), style: 'primary', onAction: clean }, + { id: 'pick', title: t('actionChooseFile'), onAction: pick } + ] + : [{ id: 'pick', title: t('actionChooseFile'), style: 'primary', onAction: pick }] + }} workbenchPanel={{ title: readonly ? t('panelTitleReadonly') : t('panelTitleClean'), fields: [ ...(readonly ? [] : [{ id: 'mode', label: t('fieldModeLabel'), type: 'select' as const, value: mode, options: [{ label: t('modeLocation'), value: 'location' }, { label: t('modeMetadata'), value: 'metadata' }], onChange: (v: unknown) => { if (!active.current && (v === 'location' || v === 'metadata')) setMode(v) } }]), { id: 'formats', label: t('fieldFormatsLabel'), type: 'info', value: supportScope(featureCode) }, diff --git a/extensions/media-metadata/src/native-ipc.ts b/extensions/media-metadata/src/native-ipc.ts index 51576b99..13643277 100644 --- a/extensions/media-metadata/src/native-ipc.ts +++ b/extensions/media-metadata/src/native-ipc.ts @@ -174,11 +174,13 @@ function normalizeMethodResult(method: string, payload: DynamicBridge): DynamicB if (method === 'system_get_battery_status') { // 宿主约定 percent 超出 0-100(如 255)表示无电池或电量未知,不能改写成 100% + // 若宿主明确给出 hasBattery 布尔值,必须原样保留,仅在缺失时按合法电量推算 const rawPct = payload.percent - const hasBattery = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const validPct = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const hasBattery = typeof payload.hasBattery === 'boolean' ? payload.hasBattery : validPct return { ...payload, - percent: hasBattery ? rawPct : null, + percent: validPct ? rawPct : null, hasBattery } } @@ -489,6 +491,8 @@ export interface RealDirectoryScanResult extends Iterable approximate?: boolean /** 宿主实际遍历的条目数 */ visitedEntries?: number + /** 目录本身不存在(ENOENT) */ + missing?: boolean /** 读取失败的真实原因;已有文件仍可使用,但不能当作完整结果。 */ error?: string } @@ -497,6 +501,7 @@ interface ScanResultMeta { truncated?: boolean approximate?: boolean visitedEntries?: number + missing?: boolean } export interface ScanDirectoryTreeOptions { @@ -504,6 +509,10 @@ export interface ScanDirectoryTreeOptions { maxFiles?: number collectTopN?: number filterExt?: RegExp + /** 为 true 时,目录本身不存在(ENOENT)按空目录处理,不返回 error(权限拒绝/读取失败仍照常报错) */ + ignoreMissing?: boolean + /** Top-N 保留与排序方式:默认按体积降序,下载/录屏等时效场景可传 mtime-desc */ + sortBy?: 'size-desc' | 'mtime-desc' hostOverride?: DynamicBridge } @@ -519,8 +528,9 @@ function normalizeIndexedFileEntry(f: DynamicBridge): RealIndexedFileEntry { const sz = Number(f?.size ?? f?.sizeBytes ?? 0) const isDir = Boolean(f?.is_dir || f?.isDir || f?.isDirectory) const rawMtime = Number(f?.mtime ?? f?.mtimeMs ?? 0) - const mtimeMs = rawMtime > 1e11 ? rawMtime : rawMtime > 0 ? rawMtime * 1000 : Date.now() - const mtimeSec = rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime + const validMtime = Number.isFinite(rawMtime) && rawMtime > 0 + const mtimeMs = validMtime ? (rawMtime > 1e11 ? rawMtime : rawMtime * 1000) : 0 + const mtimeSec = validMtime ? (rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime) : 0 if (p && sz >= 0) realFileSizeCache.set(p, sz) return { name, @@ -551,6 +561,7 @@ function makeScanResult( subdirs, ...(meta.truncated ? { truncated: true } : {}), ...(meta.approximate ? { approximate: true } : {}), + ...(meta.missing ? { missing: true } : {}), ...(typeof meta.visitedEntries === 'number' ? { visitedEntries: meta.visitedEntries } : {}), [Symbol.iterator]() { return files[Symbol.iterator]() @@ -609,13 +620,40 @@ export async function scanRealDirectoryTree( return result.error ? { ...result.scan, error: result.error } : result.scan } +/** 仅当正则明确声明了扩展名(含 `\.`)时提取后缀列表,避免把 `thumbcache|iconcache` 等文件名关键词误拆成假扩展名 */ +function extractExtensionTokensFromFilter(filterExt: RegExp): string[] { + const src = filterExt.source + if (!src.includes('\\.')) return [] + const afterDot = src.slice(src.indexOf('\\.') + 2) + const rawTokens = afterDot.match(/[a-z0-9]{1,8}/gi) || [] + const seen = new Set() + const out: string[] = [] + for (const token of rawTokens) { + const lower = token.toLowerCase() + if (!lower || seen.has(lower)) continue + seen.add(lower) + out.push(lower) + } + return out +} + +function isMissingDirectoryError(res: { error?: string; errorCode?: string; errorDetails?: Record }): boolean { + if (res.errorDetails?.reason === 'ENOENT' || res.errorCode === 'ENOENT') return true + const msg = String(res.error || '') + return /Directory does not exist|ENOENT/i.test(msg) +} + /** 一次界面扫描的错误汇总;多个目录并行扫描时保留可读目录的结果。 */ export function createDirectoryScanner(hostOverride?: DynamicBridge) { const failures = new Map() return { async scan(dir: string, options: number | ScanDirectoryTreeOptions = 160) { const result = await scanRealDirectoryTree(dir, options, hostOverride) - const error = result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') + const ignoreMissing = typeof options === 'object' && options !== null && options.ignoreMissing === true + const error = + result.missing && ignoreMissing + ? '' + : result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') if (error) failures.set(dir, error) else failures.delete(dir) return result @@ -648,26 +686,38 @@ async function scanDirectoryTreeWithError( const safeLimit = Math.min(200, Math.max(1, Math.floor(rawLimit || 160))) const hostOverride = opts.hostOverride const filterExt = opts.filterExt + const ignoreMissing = opts.ignoreMissing === true const dirQuery = `dir:${targetDir}` try { let rawPayload: DynamicBridge = null + const searchParams: Record = { + query: dirQuery, + limit: safeLimit, + ...(opts.sortBy ? { sortBy: opts.sortBy } : {}) + } const res = await callHostTransport( 'system_search_files', - { query: dirQuery, limit: safeLimit }, + searchParams, hostOverride ) - if (res.ok && res.data) { + if (res.ok && res.data && res.data.degraded !== true) { rawPayload = res.data + } else if (!res.ok && ignoreMissing && isMissingDirectoryError(res)) { + const missingScan = makeScanResult([], 0, 0, [], { missing: true }) + return { scan: missingScan } } - if (!rawPayload && !hostOverride && typeof window !== 'undefined') { + if (!rawPayload && !hostOverride && res.errorCode === 'METHOD_NOT_AVAILABLE' && typeof window !== 'undefined') { const w = window as DynamicBridge if (typeof w.__ztoolsLauncher?.searchFiles === 'function') { const rawOuter = await w.__ztoolsLauncher.searchFiles(dirQuery, safeLimit) - rawPayload = + const candidate = rawOuter && typeof rawOuter === 'object' && 'data' in rawOuter && rawOuter.data ? rawOuter.data : rawOuter + if (candidate && candidate.degraded !== true && candidate.success !== false) { + rawPayload = candidate + } } } @@ -678,29 +728,32 @@ async function scanDirectoryTreeWithError( let files: RealIndexedFileEntry[] = rawPayload.files.map(normalizeIndexedFileEntry) if (filterExt instanceof RegExp) { files = files.filter(f => !f.isDir && (filterExt.test(f.name) || filterExt.test(f.ext))) - // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索目标扩展名 + // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索明确声明的目标扩展名 if (files.length === 0 && !hostOverride) { - const extTokens = (filterExt.source.match(/[a-z0-9]{2,5}/gi) || []) - .filter(t => !['thumbcache', 'iconcache'].includes(t.toLowerCase())) - .slice(0, 4) - // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 - const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() - const extraLists = await Promise.all( - extTokens.map(ext => searchRealIndexedFiles(`.${ext.toLowerCase()}`, 30, hostOverride)) - ) - const seen = new Set() - for (const list of extraLists) { - for (const item of list) { - if (!item.isDir && item.size > 0 && !seen.has(item.path)) { - if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { - seen.add(item.path) - files.push(item) + const extTokens = extractExtensionTokensFromFilter(filterExt) + if (extTokens.length > 0) { + // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 + const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() + const extraLists = await Promise.all( + extTokens.map(ext => searchRealIndexedFiles(`.${ext}`, 30, hostOverride)) + ) + const seen = new Set() + for (const list of extraLists) { + for (const item of list) { + if (!item.isDir && item.size > 0 && !seen.has(item.path)) { + if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { + seen.add(item.path) + files.push(item) + } } } } } } } + // 先基于过滤后的完整命中集合计算总文件数与总字节数,再按 collectTopN 裁剪样本列表 + const matchedCount = files.length + const matchedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) if (typeof opts.collectTopN === 'number' && opts.collectTopN > 0 && files.length > opts.collectTopN) { files = files.slice(0, opts.collectTopN) } @@ -714,11 +767,10 @@ async function scanDirectoryTreeWithError( ...(s.approximate === true ? { approximate: true } : {}) })) : [] - const computedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) const totalFilesCount = - filterExt instanceof RegExp ? files.length : Number(rawPayload.total_matches ?? files.length) + filterExt instanceof RegExp ? matchedCount : Number(rawPayload.total_matches ?? matchedCount) const totalBytesCount = - filterExt instanceof RegExp ? computedBytes : Number(rawPayload.total_bytes ?? computedBytes) + filterExt instanceof RegExp ? matchedBytes : Number(rawPayload.total_bytes ?? matchedBytes) const visited = Number(rawPayload.visited_entries) return { scan: makeScanResult(files, totalFilesCount, totalBytesCount, subdirs, { @@ -1817,8 +1869,6 @@ export async function writeRealClipboardText(text: string, hostOverride?: Dynami const payload = { text: String(text || '') } const res = await callHostTransport('clipboard_copy_text', payload, hostOverride) if (res.ok) return true - const fallbackRes = await callHostTransport('clipboard_write_text', payload, hostOverride) - if (fallbackRes.ok) return true try { if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) { await navigator.clipboard.writeText(String(text || '')) diff --git a/extensions/media-metadata/tests/index.test.mjs b/extensions/media-metadata/tests/index.test.mjs index 64ee76ad..7a1e236b 100644 --- a/extensions/media-metadata/tests/index.test.mjs +++ b/extensions/media-metadata/tests/index.test.mjs @@ -8,7 +8,7 @@ const summary = { name: '照片.jpg', type: 'JPEG', size: 2048, digest: 'a'.repe const result = { success: true, status: 'committed', name: '照片_clean.jpg', size: 1024 } const deferred = () => { let resolve; const promise = new Promise(r => { resolve = r }); return { promise, resolve } } async function open(command = Command) { const view = await mount(command); views.push(view); return view } -async function pick(view) { await view.tree().props.filterBar.actions[0].onAction(); await tick() } +async function pick(view) { await view.tree().props.filterBar.actions.find(a => a.id === 'pick').onAction(); await tick() } async function clean(view) { await view.actions(view.item('media'))[0].props.onAction(); await tick() } const writes = () => host.ipcCalls.filter(([m, p]) => m === 'media_metadata' && p.action === 'clean') test.beforeEach(() => { diff --git a/extensions/memo/README.en.md b/extensions/memo/README.en.md new file mode 100644 index 00000000..6ec460cc --- /dev/null +++ b/extensions/memo/README.en.md @@ -0,0 +1,20 @@ +# Quick Notes + +Jot down quick text notes with Markdown body support, add tags, and search by title, body, or tag. + +## Usage + +- Command: `Quick Notes` (keywords such as `memo`, `note`, `notes`). +- Type to search notes sorted by last modified time; when there are no matches, press `Enter` to open the creation form with your search text prefilled as the title. +- With a note selected, the right pane renders the body as Markdown: `Enter` copies the body, `Cmd/Ctrl+Enter` edits the note, and `Cmd/Ctrl+K` opens the action panel (New Note, Copy Title, Delete). Deletion asks for confirmation. +- In the edit form, press `Cmd/Ctrl+Enter` to save and `Esc` to go back; title and body cannot both be empty, and leaving the title blank saves it as "Untitled Note". +- Save failures report the reason instead of showing as saved; if stored data is corrupted, saving is halted and you can back up the original data before starting fresh. + +## Platforms & Requirements + +- Supported: Windows, macOS +- Built into ZTools; no separate installation required. + +## Network & Data + +- Works offline; data stays strictly on your local device. diff --git a/extensions/memo/plugin.json b/extensions/memo/plugin.json index 066d9755..f3e3e6d7 100644 --- a/extensions/memo/plugin.json +++ b/extensions/memo/plugin.json @@ -2,7 +2,7 @@ "id": "memo", "name": "便签", "description": "轻量随手记便签,正文支持 Markdown,可加标签,按标题、正文或标签搜索", - "version": "1.0.8", + "version": "1.0.9", "author": "ZTools Team", "entry": "dist/index.js", "icon": "icon.svg", @@ -33,7 +33,13 @@ "note", "便签", "笔记", - "备忘" + "备忘", + "记事", + "记事本", + "随手记", + "备忘录", + "小纸条", + "草稿本" ], "minAppVersion": "1.1.8.3", "defaultLocale": "zh-CN", @@ -47,7 +53,12 @@ "notes", "markdown", "scratchpad", - "tags" + "tags", + "notepad", + "quick notes", + "jot", + "markdown notes", + "sticky note" ], "screenshots": [ { diff --git a/extensions/memo/src/index.ts b/extensions/memo/src/index.ts index 468d8eb9..4b2f0c64 100644 --- a/extensions/memo/src/index.ts +++ b/extensions/memo/src/index.ts @@ -76,7 +76,7 @@ export function MemoForm({ memo, initialTitle = '', onSave }: { memo?: MemoItem; ]) }, [ - Form.TextField({ id: 'title', title: t('fieldTitleLabel'), placeholder: t('fieldTitlePlaceholder'), value: title, error, onChange: (v: string) => { setTitle(v); setError(undefined) } }), + Form.TextField({ id: 'title', title: t('fieldTitleLabel'), placeholder: t('fieldTitlePlaceholder'), value: title, error, autoFocus: true, onChange: (v: string) => { setTitle(v); setError(undefined) } }), Form.TextArea({ id: 'content', title: t('fieldContentLabel'), placeholder: t('fieldContentPlaceholder'), value: content, onChange: (v: string) => { setContent(v); setError(undefined) } }), Form.TextField({ id: 'tag', title: t('fieldTagLabel'), placeholder: t('fieldTagPlaceholder'), value: tag, onChange: (v: string) => setTag(v) }) ] @@ -300,7 +300,7 @@ export default function MemoCommand() { const query = searchText.trim() const globalActions = ActionPanel({ title: t('panelMemoTitle') }, [ - Action({ title: t('newMemoAction'), icon: Icon.Plus, onAction: () => openCreate(query) }) + Action({ title: t('newMemoAction'), icon: Icon.Plus, shortcut: { modifiers: ['ctrl'], key: 'n' }, onAction: () => openCreate(query) }) ]) const items = filtered.length > 0 @@ -318,11 +318,11 @@ export default function MemoCommand() { actions: ActionPanel({ title: item.title }, [ Action({ title: t('copyContentAction'), icon: Icon.Clipboard, onAction: () => copyText(item.content, t('noContentError'), t('copiedContentToast')) }), Action({ title: t('pasteContentAction'), icon: Icon.ArrowRight, shortcut: { modifiers: ['ctrl'], key: 'return' }, onAction: () => pasteText(item.content, t('noContentError'), t('pastedContentToast')) }), - Action({ title: item.pinned ? t('unpinMemoAction') : t('pinMemoAction'), icon: Icon.Pin, onAction: () => togglePin(item) }), - Action({ title: t('editMemoAction'), icon: Icon.Pencil, onAction: () => openEdit(item) }), + Action({ title: item.pinned ? t('unpinMemoAction') : t('pinMemoAction'), icon: Icon.Pin, shortcut: { modifiers: ['ctrl'], key: 'p' }, onAction: () => togglePin(item) }), + Action({ title: t('editMemoAction'), icon: Icon.Pencil, shortcut: { modifiers: ['ctrl'], key: 'e' }, onAction: () => openEdit(item) }), // 「新建便签」只放在 List 级:客户端会以「全局操作」附在每条便签的动作后面,这里不再重复 Action({ title: t('copyTitleAction'), icon: Icon.Clipboard, onAction: () => copyText(item.title, t('noTitleError'), t('copiedTitleToast')) }), - Action({ title: t('deleteMemoAction'), icon: Icon.Trash, onAction: () => remove(item) }) + Action({ title: t('deleteMemoAction'), icon: Icon.Trash, style: Action.Style.Destructive, shortcut: { modifiers: ['ctrl'], key: 'backspace' }, onAction: () => remove(item) }) ]) }) ) @@ -343,6 +343,18 @@ export default function MemoCommand() { searchBarPlaceholder: t('searchPlaceholder'), searchText, onSearchTextChange: setSearchText, + filterBar: { + actions: [ + { + id: 'new-memo', + label: t('newMemoAction'), + title: t('newMemoAction'), + icon: Icon.Plus, + style: 'primary', + onAction: () => openCreate(query) + } + ] + }, actions: globalActions, children: [ List.Section({ diff --git a/extensions/mock-data/README.en.md b/extensions/mock-data/README.en.md new file mode 100644 index 00000000..094acf8c --- /dev/null +++ b/extensions/mock-data/README.en.md @@ -0,0 +1,19 @@ +# Mock Data Generator + +Generate random synthetic Chinese ID numbers, Unified Social Credit Codes, bank card numbers (with check digits computed using standard algorithms), and mobile phone numbers locally for testing, as well as batch user JSON arrays. + +## Usage + +- Commands: `mock data` (`fake data`, `test data`, `generate mock`), `mock json` (`batch mock`, `fake users json`, `test json`); use the dropdown next to the search box to switch between "Single Items" and "Batch JSON". +- Single Items: 18-digit Chinese ID numbers (check digit per GB 11643), Unified Social Credit Codes (check digit per GB 32100), bank card numbers (Luhn check digit), 11-digit mobile phone numbers, plus names and company names; the right pane shows segment meanings and checksum algorithms. +- Batch JSON: Enter a count from 1 to 500 in the search box (default 10; invalid input prompts a notice and generates 10) to produce a user array containing ID, name, gender, age, national ID number, phone number, email (`example.com` reserved domain), company name, credit code, bank card number, address, and creation timestamp. +- Single Items: `Enter` copies the value, `Cmd/Ctrl+Enter` (or `Cmd/Ctrl+R`) generates a new set, and `Cmd/Ctrl+Shift+C` copies as key-value JSON. Batch JSON: `Enter` copies the complete JSON, and `Cmd/Ctrl+Enter` or `Cmd/Ctrl+R` regenerates. +- Data is randomly generated and only guarantees valid format and check digits (phone numbers, names, and company names do not have check digits); values may coincide with real numbers, individuals, or companies and are strictly for development and testing—never use them for identity verification or impersonation. + +## Platforms & Requirements + +- Supported: Windows, macOS + +## Network & Data + +- Works offline; data stays strictly on your local device. diff --git a/extensions/mock-data/plugin.json b/extensions/mock-data/plugin.json index b470337e..1ff580e0 100644 --- a/extensions/mock-data/plugin.json +++ b/extensions/mock-data/plugin.json @@ -1,7 +1,8 @@ { "id": "mock-data", "name": "测试数据生成", - "version": "1.0.4", + "version": "1.0.5", + "minAppVersion": "1.1.8.0", "description": "一键生成符合国家校验位算法的虚拟测试用18位身份证号、手机号、统一社会信用代码、银行卡号及批量JSON测试数据", "author": "ZTools Team", "category": [ @@ -64,7 +65,13 @@ "test data", "json", "generator", - "dummy" + "dummy", + "mock data", + "faker", + "dummy data", + "random data", + "generate users", + "sample data" ], "features": { "mock-quick": { @@ -100,5 +107,16 @@ { "path": "screenshots/02-action-panel.png" } + ], + "keywords": [ + "测试数据", + "假数据", + "随机数据", + "生成手机号", + "生成姓名", + "生成邮箱", + "mock", + "造数据", + "随机uuid" ] } diff --git a/extensions/monitor-control/README.en.md b/extensions/monitor-control/README.en.md new file mode 100644 index 00000000..52aa3784 --- /dev/null +++ b/extensions/monitor-control/README.en.md @@ -0,0 +1,20 @@ +# Monitor Brightness & Control + +Search `brightness` (`monitor`, `display`, `ddc`) to open the display list. Press `Enter` to increase the current monitor's brightness, or `Cmd/Ctrl+Enter` to decrease it. You can also choose "Set Brightness..." or "Set Contrast..." in the action panel to enter a percentage, or use "Unified Brightness..." above the list to adjust all monitors supporting hardware brightness. + +## Usage + +- macOS reads real system monitor states: Apple displays use the system brightness interface, while external monitors supporting DDC/CI use hardware control. Brightness and contrast are detected independently, and unsupported controls are omitted; availability depends on the monitor, adapters/cables, mirror mode, and OS version. Software overlay dimming is not used to simulate hardware brightness. +- Windows: external monitors use DDC/CI and laptop built-in screens use the system backlight interface, sharing the same UI as macOS. +- Connections and current values are verified before adjustment, and actual hardware levels are read back afterward. If multi-monitor adjustment fails, original values are restored where possible; if a display disconnects or its state was changed externally, the plugin prompts you to rescan instead of overwriting other changes. When a display uses discrete hardware steps, the resulting value may differ slightly from the entered percentage and reflects the rescanned value. +- Search `sleep monitor` (`turn off screen`, `display sleep`) to send a display-off request to the system. Whether the screen also locks depends on your system settings. + +## Platforms & Requirements + +- Supported: Windows, macOS +- Requires ZTools 1.1.8.5 or later. +- Windows implementation is pending real-device verification. + +## Network & Data + +- Works offline; data stays strictly on your local device. diff --git a/extensions/monitor-control/plugin.json b/extensions/monitor-control/plugin.json index c6f8327b..258f7830 100644 --- a/extensions/monitor-control/plugin.json +++ b/extensions/monitor-control/plugin.json @@ -1,7 +1,7 @@ { "id": "monitor-control", "name": "屏幕亮度与控制", - "version": "1.0.7", + "version": "1.0.8", "description": "读取显示器真实硬件状态,调节受支持的亮度与对比度;支持多屏统一亮度与系统熄屏命令", "author": "ZTools Team", "entry": "dist/index.js", @@ -68,7 +68,10 @@ "contrast", "ddc", "display", - "screen sleep" + "screen sleep", + "screen brightness", + "dim screen", + "external monitor" ], "features": { "monitor-brightness": { @@ -104,5 +107,16 @@ { "path": "screenshots/02-action-panel.png" } + ], + "keywords": [ + "屏幕亮度", + "调亮度", + "显示器亮度", + "外接显示器", + "护眼", + "暗一点", + "亮一点", + "亮度调节", + "brightness" ] } diff --git a/extensions/monitor-control/src/mac-command.tsx b/extensions/monitor-control/src/mac-command.tsx index ea1a84fd..0e884115 100644 --- a/extensions/monitor-control/src/mac-command.tsx +++ b/extensions/monitor-control/src/mac-command.tsx @@ -20,7 +20,7 @@ function LevelForm({ title, initial, apply }: { title: string; initial: string; finally { guard.current = false; if (alive.current) setBusy(false) } } return
}> - + } diff --git a/extensions/mover/README.en.md b/extensions/mover/README.en.md new file mode 100644 index 00000000..4e843180 --- /dev/null +++ b/extensions/mover/README.en.md @@ -0,0 +1,23 @@ +# Drive C Folder Mover + +Copy large user-directory folders on Drive C (WeChat and QQ files, Downloads, Documents, Videos, and development caches) to another partition and create a directory junction at the original location so applications continue accessing them via the original path. + +## Usage + +- Command: `Drive C Folder Mover`. +- On launch, scans `WeChat Files`, `xwechat_files`, and `Tencent Files` under Documents, as well as Downloads, Documents, Videos, and npm, pip, and NuGet caches; only directories existing on Drive C are listed. +- Use the dropdown next to the search box to select the target location: `:\ZToolsMoved` on any partition other than C:. +- Directories are unchecked by default and only checked items are moved; mutually nested directories (such as Documents and `WeChat Files` inside it) cannot be checked together, and migration is blocked if the selected size exceeds available space on the target partition. +- On the right-hand directory list: `Enter` migrates checked directories, `Ctrl+Enter` reveals in File Explorer, and `Ctrl+K` opens the action panel (check or uncheck). Categories on the left are for filtering only. +- Before migrating, the plugin lists the target directories for confirmation and opens a dialog to choose the target drive (such as `D:\`) for authorization. If a folder or file with the same name already exists at the destination, or if the source path is already a directory junction, that directory is skipped without merging or overwriting. +- Migration copies files to the destination first, renames the original directory as a backup, creates the junction, and deletes the backup upon success. File modification timestamps after copying reflect the copy time. +- If any directory fails to migrate, the operation stops immediately and remaining directories are not processed. When the original directory is confirmed intact, the files copied to the destination during this attempt are deleted; if integrity cannot be confirmed, they are kept and you are prompted to inspect manually. Any folder containing `.ztools-mover-bak-` next to an original path is a backup left behind by an interrupted migration. +- The plugin has no built-in move-back feature. Exit related applications (such as WeChat and QQ) before migrating. + +## Platforms & Requirements + +- Supported: Windows only + +## Network & Data + +- Works offline; data stays strictly on your local device. diff --git a/extensions/mover/plugin.json b/extensions/mover/plugin.json index 8f1f6fc9..b038c247 100644 --- a/extensions/mover/plugin.json +++ b/extensions/mover/plugin.json @@ -2,7 +2,8 @@ "id": "mover", "name": "C盘搬家", "description": "把 C 盘用户目录下的微信与 QQ 文件、下载、文档、视频和 npm / pip / NuGet 缓存复制到其他分区,并在原位置建立目录联接,软件仍按原路径访问", - "version": "2.0.10", + "version": "2.0.11", + "minAppVersion": "1.1.8.0", "author": "ZTools Team", "entry": "dist/index.js", "icon": "icon.svg", @@ -41,7 +42,12 @@ "junction", "symlink", "disk space", - "windows" + "windows", + "c drive full", + "migrate folder", + "free c drive", + "disk mover", + "move to d drive" ], "screenshots": [ { @@ -57,5 +63,16 @@ { "path": "screenshots/02-action-panel.png" } + ], + "keywords": [ + "c盘搬家", + "c盘瘦身", + "迁移文件夹", + "c盘满了", + "软件搬家", + "目录迁移", + "符号链接", + "转移到d盘", + "释放c盘" ] } diff --git a/extensions/mover/src/i18n.ts b/extensions/mover/src/i18n.ts index db3ef3b0..34d9061e 100644 --- a/extensions/mover/src/i18n.ts +++ b/extensions/mover/src/i18n.ts @@ -34,6 +34,8 @@ export const t = createTranslator({ confirmMoveItemApprox: '- {name}:{sourcePath}(抽样估算至少 {size},实际可能更大)', confirmMoveApproxWarning: '\n\n注意:所选目录中包含因文件过多而抽样估算的目录,实际体积可能大于统计值,请确认目标分区有充足剩余空间。', summaryApproxHint: '(含抽样估算,实际可能更大)', + authorizeSourceDialogTitle: '选择 {defaultPath}(或其上级目录)以允许迁移所选源目录', + errAuthorizeSourceMismatch: '请选择 {defaultPath} 或包含全部已选目录的上级目录,没有迁移任何目录', authorizeDialogTitle: '选择 {driveRoot} 以允许迁移到 {root}', errOpenFolderDialog: '无法打开选择文件夹窗口', errAuthorizeMismatch: '请选择 {driveRoot} 或 {root},没有迁移任何目录', @@ -68,9 +70,10 @@ export const t = createTranslator({ cannotMoveTitle: '无法迁移', confirmMoveItem: '- {name}:{sourcePath}(约 {size})', confirmMoveTitle: '迁移 {count} 个目录到 {targetRoot}?', - confirmMoveMessage: '{list}\n\n会先把目录复制到目标位置,再把原目录改名、在原位置建立指向新位置的目录联接,成功后删除原目录。迁移前请退出微信、QQ 等正在使用这些目录的程序。插件不提供迁回功能。\n\n确认后还需要在弹出的窗口里选择目标分区,授权插件检查目标位置并在失败时清理复制的内容。', + confirmMoveMessage: '{list}\n\n会先把目录复制到目标位置,再把原目录改名、在原位置建立指向新位置的目录联接,成功后删除原目录。迁移前请退出微信、QQ 等正在使用这些目录的程序。插件不提供迁回功能。\n\n确认后需要在弹出的窗口里依次授权源目录与目标分区,允许插件迁移原目录、检查目标位置并在失败时清理复制的内容。', confirmMovePrimary: '迁移', statusCanceled: '已取消,没有迁移任何目录', + noSourceAuthTitle: '没有获得源目录授权', noAuthTitle: '没有获得目标位置授权', movedCountToast: '已迁移 {count} 个目录', partialMoveToast: '部分目录没有迁移', @@ -129,6 +132,8 @@ export const t = createTranslator({ confirmMoveItemApprox: '- {name}: {sourcePath} (sampled ≥ {size}, actual may be larger)', confirmMoveApproxWarning: '\n\nNote: Some selected folders were estimated by sampling due to large file counts; actual size may be larger. Ensure sufficient free space on the destination drive.', summaryApproxHint: ' (sampled estimate, may be larger)', + authorizeSourceDialogTitle: 'Select {defaultPath} (or a parent folder) to authorize moving selected source folders', + errAuthorizeSourceMismatch: 'Please select {defaultPath} or a parent folder covering all selected folders; nothing was moved', authorizeDialogTitle: 'Select {driveRoot} to authorize moving to {root}', errOpenFolderDialog: 'Unable to open folder selection dialog', errAuthorizeMismatch: 'Please select {driveRoot} or {root}; nothing was moved', @@ -163,9 +168,10 @@ export const t = createTranslator({ cannotMoveTitle: 'Cannot Move', confirmMoveItem: '- {name}: {sourcePath} (~{size})', confirmMoveTitle: 'Move {count} folder(s) to {targetRoot}?', - confirmMoveMessage: '{list}\n\nFolders will be copied to the destination, the original renamed, a directory junction created, and the original deleted. Close apps like WeChat/QQ using these folders first. Moving back is not provided.\n\nNext, select the destination drive in the popup dialog to authorize checks and cleanup on failure.', + confirmMoveMessage: '{list}\n\nFolders will be copied to the destination, the original renamed, a directory junction created, and the original deleted. Close apps like WeChat/QQ using these folders first. Moving back is not provided.\n\nNext, authorize the source folder and destination drive in the popup dialogs so the plugin can relocate folders, verify the destination, and clean up on failure.', confirmMovePrimary: 'Move', statusCanceled: 'Canceled; no folders moved', + noSourceAuthTitle: 'Source authorization denied', noAuthTitle: 'Destination authorization denied', movedCountToast: 'Moved {count} folder(s)', partialMoveToast: 'Some folders were not moved', diff --git a/extensions/mover/src/index.ts b/extensions/mover/src/index.ts index 1f8d2844..7158173d 100644 --- a/extensions/mover/src/index.ts +++ b/extensions/mover/src/index.ts @@ -2,7 +2,7 @@ * C 盘搬家(布局二:左侧目录分类 + 右侧可勾选目录明细) * * - 搜索框右侧下拉框选择目标分区(<盘符>\ZToolsMoved) - * - 目录默认不勾选;迁移只作用于已勾选的目录,执行前确认,并在系统窗口里授权目标分区 + * - 目录默认不勾选;迁移只作用于已勾选的目录,执行前确认,并在系统窗口里依次授权源目录与目标分区 * - 左侧分类只用来筛选,不触发迁移 */ @@ -22,6 +22,7 @@ import { import { isRealElectronHost } from "./native-ipc.js"; import { t } from "./i18n.js"; import { + authorizeMoveSources, authorizeMoveTarget, createEmptyMoverSnapshot, destinationPathFor, @@ -139,6 +140,15 @@ export function MoverCommand() { primaryAction: { title: t("confirmMovePrimary"), style: "destructive" } }); if (!confirmed) return; + const sourceGrant = await authorizeMoveSources(folders); + if (!sourceGrant.ok) { + if (sourceGrant.canceled) { + setStatusBanner(t("statusCanceled")); + } else { + await showToast({ style: Toast.Style.Failure, title: t("noSourceAuthTitle"), message: sourceGrant.error }); + } + return; + } const grant = await authorizeMoveTarget(targetRoot); if (!grant.ok) { if (grant.canceled) { diff --git a/extensions/mover/src/logic.ts b/extensions/mover/src/logic.ts index d8876d16..c8a658d7 100644 --- a/extensions/mover/src/logic.ts +++ b/extensions/mover/src/logic.ts @@ -14,10 +14,12 @@ import { getRealSystemPath, invokePluginService, isRealElectronHost, + joinWinPath, probeRealDiskDrives, resolveRealSpecialPaths, scanRealDirectoryTree, - showRealItemInFolder + showRealItemInFolder, + type RealDiskDriveInfo } from "./native-ipc.js"; import { t } from "./i18n.js"; import { resolveErrorMessage } from './error-i18n.js' @@ -123,9 +125,13 @@ function trimTrailingSeparators(value: string): string { return String(value || "").trim().replace(/[\\/]+$/, ""); } -/** Windows 路径不区分大小写,统一成小写、反斜杠、去掉末尾分隔符后比较 */ +/** Windows 路径不区分大小写,统一成小写、反斜杠、折叠重复分隔符并去掉末尾分隔符后比较 */ function normalizeWinPath(value: string): string { - return trimTrailingSeparators(value).replace(/\//g, "\\").toLowerCase(); + const unified = trimTrailingSeparators(value).replace(/\//g, "\\"); + const collapsed = unified.startsWith("\\\\") + ? `\\\\${unified.slice(2).replace(/\\+/g, "\\")}` + : unified.replace(/\\+/g, "\\"); + return collapsed.toLowerCase(); } function isSameOrInside(child: string, parent: string): boolean { @@ -140,6 +146,65 @@ export function destinationPathFor(sourcePath: string, targetRoot: string): stri return `${trimTrailingSeparators(targetRoot)}\\${base}`; } +const ALL_WINDOWS_DRIVE_LETTERS = [ + "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", + "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" +]; + +/** 解析 system_list_volumes 返回的单条卷记录 */ +function parseVolumeEntry(raw: DynamicBridge): RealDiskDriveInfo | null { + if (!raw || typeof raw !== "object") return null; + const rawPath = String(raw.path ?? raw.mount ?? raw.mountpoint ?? raw.drive ?? raw.letter ?? "").trim(); + const driveMatch = rawPath.match(/^([A-Za-z]):/); + if (!driveMatch) return null; + const totalBytes = Number(raw.totalBytes ?? raw.total ?? 0); + if (!Number.isFinite(totalBytes) || totalBytes <= 0) return null; + const usedRaw = Number(raw.usedBytes ?? raw.used ?? NaN); + const availRaw = Number(raw.availableBytes ?? raw.available ?? raw.freeBytes ?? raw.free ?? NaN); + const availableBytes = + Number.isFinite(availRaw) && availRaw >= 0 + ? availRaw + : Number.isFinite(usedRaw) && usedRaw >= 0 + ? Math.max(0, totalBytes - usedRaw) + : 0; + const usedBytes = + Number.isFinite(usedRaw) && usedRaw >= 0 ? usedRaw : Math.max(0, totalBytes - availableBytes); + const pctRaw = Number(raw.usagePercent ?? raw.percent ?? NaN); + const usagePercent = Number.isFinite(pctRaw) ? pctRaw : Math.round((usedBytes / totalBytes) * 100); + return { + drive: `${driveMatch[1].toUpperCase()}:`, + totalBytes, + usedBytes, + availableBytes, + usagePercent + }; +} + +/** 优先通过 system_list_volumes 获取全量挂载磁盘分区,不可用或为空时回退探测 C~Z 全盘符 */ +async function listMoverDiskDrives(hostBridge?: DynamicBridge): Promise { + const res = await callHostTransport("system_list_volumes", {}, hostBridge); + if (res.ok && res.data) { + const rawList = Array.isArray(res.data) + ? res.data + : Array.isArray(res.data.volumes) + ? res.data.volumes + : Array.isArray(res.data.drives) + ? res.data.drives + : []; + const seen = new Set(); + const parsed: RealDiskDriveInfo[] = []; + for (const entry of rawList) { + const info = parseVolumeEntry(entry); + if (info && !seen.has(info.drive)) { + seen.add(info.drive); + parsed.push(info); + } + } + if (parsed.length > 0) return parsed; + } + return probeRealDiskDrives(ALL_WINDOWS_DRIVE_LETTERS, hostBridge); +} + export async function fetchMoverSnapshot(hostBridge?: DynamicBridge): Promise { if (!hostBridge && !isRealElectronHost()) return createEmptyMoverSnapshot(t("notInClient")); try { @@ -148,7 +213,7 @@ export async function fetchMoverSnapshot(hostBridge?: DynamicBridge): Promise d.drive.toUpperCase() === "C:"); @@ -171,21 +236,21 @@ export async function fetchMoverSnapshot(hostBridge?: DynamicBridge): Promise> = [ - { id: "mover_wechat", name: t("folderWechat"), sourcePath: `${paths.documents}\\WeChat Files`, category: "social_office", categoryName: catSocial }, - { id: "mover_xwechat", name: t("folderXwechat"), sourcePath: `${paths.documents}\\xwechat_files`, category: "social_office", categoryName: catSocial }, - { id: "mover_qq", name: t("folderQq"), sourcePath: `${paths.documents}\\Tencent Files`, category: "social_office", categoryName: catSocial }, - { id: "mover_downloads", name: t("folderDownloads"), sourcePath: paths.downloads, category: "user_profile", categoryName: catUser }, - { id: "mover_documents", name: t("folderDocuments"), sourcePath: paths.documents, category: "user_profile", categoryName: catUser }, - { id: "mover_videos", name: t("folderVideos"), sourcePath: paths.videos, category: "user_profile", categoryName: catUser }, - { id: "mover_npm_cache", name: t("folderNpm"), sourcePath: `${paths.localAppData}\\npm-cache`, category: "dev_cache", categoryName: catDev }, - { id: "mover_pip_cache", name: t("folderPip"), sourcePath: `${paths.localAppData}\\pip\\Cache`, category: "dev_cache", categoryName: catDev }, - { id: "mover_nuget_cache", name: t("folderNuget"), sourcePath: `${paths.userProfile}\\.nuget\\packages`, category: "dev_cache", categoryName: catDev } + { id: "mover_wechat", name: t("folderWechat"), sourcePath: joinWinPath(paths.documents, "WeChat Files"), category: "social_office", categoryName: catSocial }, + { id: "mover_xwechat", name: t("folderXwechat"), sourcePath: joinWinPath(paths.documents, "xwechat_files"), category: "social_office", categoryName: catSocial }, + { id: "mover_qq", name: t("folderQq"), sourcePath: joinWinPath(paths.documents, "Tencent Files"), category: "social_office", categoryName: catSocial }, + { id: "mover_downloads", name: t("folderDownloads"), sourcePath: trimTrailingSeparators(paths.downloads), category: "user_profile", categoryName: catUser }, + { id: "mover_documents", name: t("folderDocuments"), sourcePath: trimTrailingSeparators(paths.documents), category: "user_profile", categoryName: catUser }, + { id: "mover_videos", name: t("folderVideos"), sourcePath: trimTrailingSeparators(paths.videos), category: "user_profile", categoryName: catUser }, + { id: "mover_npm_cache", name: t("folderNpm"), sourcePath: joinWinPath(paths.localAppData, "npm-cache"), category: "dev_cache", categoryName: catDev }, + { id: "mover_pip_cache", name: t("folderPip"), sourcePath: joinWinPath(paths.localAppData, "pip", "Cache"), category: "dev_cache", categoryName: catDev }, + { id: "mover_nuget_cache", name: t("folderNuget"), sourcePath: joinWinPath(paths.userProfile, ".nuget", "packages"), category: "dev_cache", categoryName: catDev } ]; const scanned = await Promise.all( candidateDefs.map(async (def): Promise => { // 只列 C 盘上的目录:已在其他分区的目录迁移后不能为 C 盘腾出空间 - if (!/^c:\\/i.test(def.sourcePath)) return null; + if (!/^c:[\\/]/i.test(def.sourcePath)) return null; const scan = await scanRealDirectoryTree(def.sourcePath, MOVER_SCAN_OPTIONS, hostBridge); if (scan.totalFiles <= 0 && scan.totalBytes <= 0 && scan.files.length === 0) return null; const isApproximate = Boolean( @@ -201,7 +266,17 @@ export async function fetchMoverSnapshot(hostBridge?: DynamicBridge): Promise item !== null); + let folders = scanned.filter((item): item is MovableFolderItem => item !== null); + if (folders.length > 0) { + const states = await readSourceStates( + folders.map((f) => f.sourcePath), + hostBridge, + { skipSize: true } + ); + if (states.ok) { + folders = folders.filter((f) => states.map.get(normalizeWinPath(f.sourcePath))?.isJunction !== true); + } + } return { cDriveTotalBytes: cDrive?.totalBytes || 0, cDriveFreeBytes: cDrive?.availableBytes || 0, @@ -274,6 +349,67 @@ export function validateMoveSelection( return null; } +/** 计算所选源目录的最深共同父目录,用于一次选择框授权覆盖全部已勾选源目录 */ +function computeCommonParentDir(paths: string[]): string { + const splitList = paths + .map((p) => { + const unified = trimTrailingSeparators(p).replace(/\//g, "\\").replace(/\\+/g, "\\"); + const parts = unified.split("\\").filter(Boolean); + if (parts.length > 0 && /^[A-Za-z]:$/.test(parts[0])) { + parts[0] = parts[0].toUpperCase(); + } + return parts; + }) + .filter((parts) => parts.length > 0); + if (splitList.length === 0) return ""; + if (splitList.length === 1) { + const parts = splitList[0]; + if (parts.length <= 1) return `${parts[0]}\\`; + const parentParts = parts.slice(0, -1); + return parentParts.length === 1 ? `${parentParts[0]}\\` : parentParts.join("\\"); + } + let commonLen = splitList[0].length; + for (let i = 1; i < splitList.length; i++) { + const parts = splitList[i]; + const max = Math.min(commonLen, parts.length); + let matched = 0; + while (matched < max && splitList[0][matched].toLowerCase() === parts[matched].toLowerCase()) { + matched++; + } + commonLen = matched; + if (commonLen === 0) break; + } + if (commonLen === 0) { + return splitList[0].length > 0 ? `${splitList[0][0]}\\` : ""; + } + const common = splitList[0].slice(0, commonLen); + return common.length === 1 ? `${common[0]}\\` : common.join("\\"); +} + +/** + * 让用户在系统窗口里选择源目录的共同父目录(或覆盖全部勾选目录的上级目录),授权插件对原目录执行迁移与建立联接 + */ +export async function authorizeMoveSources( + items: MovableFolderItem[], + hostOverride?: DynamicBridge +): Promise<{ ok: boolean; canceled?: boolean; error?: string }> { + const list = (items || []).filter(Boolean); + if (list.length === 0) return { ok: false, error: t("errSelectFolderFirst") }; + const defaultPath = computeCommonParentDir(list.map((item) => item.sourcePath)); + const picked = await callHostTransport<{ canceled?: boolean; folderPath?: string }>( + "window_show_select_folder_dialog", + { title: t("authorizeSourceDialogTitle", { defaultPath }), defaultPath }, + hostOverride + ); + if (!picked.ok) return { ok: false, error: resolveErrorMessage(picked, t("errOpenFolderDialog")) }; + if (picked.data?.canceled) return { ok: false, canceled: true }; + const folder = String(picked.data?.folderPath || ""); + if (!folder || !list.every((item) => isSameOrInside(item.sourcePath, folder))) { + return { ok: false, error: t("errAuthorizeSourceMismatch", { defaultPath }) }; + } + return { ok: true }; +} + /** * 让用户在系统窗口里选择目标分区根目录(或目标文件夹本身),授权插件检查目标位置是否已有内容、失败时清理本次复制的内容 */ @@ -305,11 +441,19 @@ interface SourceStates { } /** 通过客户端读取原目录状态(存在与否、是否已经是目录联接) */ -async function readSourceStates(sourcePaths: string[], hostOverride?: DynamicBridge): Promise { +async function readSourceStates( + sourcePaths: string[], + hostOverride?: DynamicBridge, + options?: { skipSize?: boolean } +): Promise { + const params: Record = { + customPaths: sourcePaths, + ...(options?.skipSize ? { skipSize: true } : {}) + }; const res = await invokePluginService( DLL_PLUGIN_NAME, "scanCandidates", - { customPaths: sourcePaths }, + params, hostOverride ); if (!res.ok || res.data?.ok === false || res.data?.success === false) { @@ -356,7 +500,7 @@ async function rollbackAfterFailure( } if (!destNow.data.exists) return { status: "failed", detail: t("detailNoLeftover") }; - const states = await readSourceStates([sourcePath], hostOverride); + const states = await readSourceStates([sourcePath], hostOverride, { skipSize: true }); if (!states.ok) { return { status: "needs_check", detail: t("detailSourceCheckFailed", { error: states.error || "", dest }) }; } @@ -394,7 +538,7 @@ function summarizeMoveResults(results: MoveItemResult[], targetRoot: string, fre } /** - * 逐个迁移已勾选的目录。调用前应先经用户确认并完成 authorizeMoveTarget 授权。 + * 逐个迁移已勾选的目录。调用前应先经用户确认并完成 authorizeMoveSources 与 authorizeMoveTarget 授权。 * 遇到迁移失败立即停止,其余目录不再执行。 */ export async function executeDirectoryMove( @@ -406,7 +550,7 @@ export async function executeDirectoryMove( if (invalid) return { ok: false, movedCount: 0, freedBytes: 0, message: invalid, results: [] }; const root = trimTrailingSeparators(targetRoot); - const states = await readSourceStates(items.map((i) => i.sourcePath), hostOverride); + const states = await readSourceStates(items.map((i) => i.sourcePath), hostOverride, { skipSize: true }); if (!states.ok) { return { ok: false, diff --git a/extensions/mover/src/native-ipc.ts b/extensions/mover/src/native-ipc.ts index 51576b99..13643277 100644 --- a/extensions/mover/src/native-ipc.ts +++ b/extensions/mover/src/native-ipc.ts @@ -174,11 +174,13 @@ function normalizeMethodResult(method: string, payload: DynamicBridge): DynamicB if (method === 'system_get_battery_status') { // 宿主约定 percent 超出 0-100(如 255)表示无电池或电量未知,不能改写成 100% + // 若宿主明确给出 hasBattery 布尔值,必须原样保留,仅在缺失时按合法电量推算 const rawPct = payload.percent - const hasBattery = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const validPct = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const hasBattery = typeof payload.hasBattery === 'boolean' ? payload.hasBattery : validPct return { ...payload, - percent: hasBattery ? rawPct : null, + percent: validPct ? rawPct : null, hasBattery } } @@ -489,6 +491,8 @@ export interface RealDirectoryScanResult extends Iterable approximate?: boolean /** 宿主实际遍历的条目数 */ visitedEntries?: number + /** 目录本身不存在(ENOENT) */ + missing?: boolean /** 读取失败的真实原因;已有文件仍可使用,但不能当作完整结果。 */ error?: string } @@ -497,6 +501,7 @@ interface ScanResultMeta { truncated?: boolean approximate?: boolean visitedEntries?: number + missing?: boolean } export interface ScanDirectoryTreeOptions { @@ -504,6 +509,10 @@ export interface ScanDirectoryTreeOptions { maxFiles?: number collectTopN?: number filterExt?: RegExp + /** 为 true 时,目录本身不存在(ENOENT)按空目录处理,不返回 error(权限拒绝/读取失败仍照常报错) */ + ignoreMissing?: boolean + /** Top-N 保留与排序方式:默认按体积降序,下载/录屏等时效场景可传 mtime-desc */ + sortBy?: 'size-desc' | 'mtime-desc' hostOverride?: DynamicBridge } @@ -519,8 +528,9 @@ function normalizeIndexedFileEntry(f: DynamicBridge): RealIndexedFileEntry { const sz = Number(f?.size ?? f?.sizeBytes ?? 0) const isDir = Boolean(f?.is_dir || f?.isDir || f?.isDirectory) const rawMtime = Number(f?.mtime ?? f?.mtimeMs ?? 0) - const mtimeMs = rawMtime > 1e11 ? rawMtime : rawMtime > 0 ? rawMtime * 1000 : Date.now() - const mtimeSec = rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime + const validMtime = Number.isFinite(rawMtime) && rawMtime > 0 + const mtimeMs = validMtime ? (rawMtime > 1e11 ? rawMtime : rawMtime * 1000) : 0 + const mtimeSec = validMtime ? (rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime) : 0 if (p && sz >= 0) realFileSizeCache.set(p, sz) return { name, @@ -551,6 +561,7 @@ function makeScanResult( subdirs, ...(meta.truncated ? { truncated: true } : {}), ...(meta.approximate ? { approximate: true } : {}), + ...(meta.missing ? { missing: true } : {}), ...(typeof meta.visitedEntries === 'number' ? { visitedEntries: meta.visitedEntries } : {}), [Symbol.iterator]() { return files[Symbol.iterator]() @@ -609,13 +620,40 @@ export async function scanRealDirectoryTree( return result.error ? { ...result.scan, error: result.error } : result.scan } +/** 仅当正则明确声明了扩展名(含 `\.`)时提取后缀列表,避免把 `thumbcache|iconcache` 等文件名关键词误拆成假扩展名 */ +function extractExtensionTokensFromFilter(filterExt: RegExp): string[] { + const src = filterExt.source + if (!src.includes('\\.')) return [] + const afterDot = src.slice(src.indexOf('\\.') + 2) + const rawTokens = afterDot.match(/[a-z0-9]{1,8}/gi) || [] + const seen = new Set() + const out: string[] = [] + for (const token of rawTokens) { + const lower = token.toLowerCase() + if (!lower || seen.has(lower)) continue + seen.add(lower) + out.push(lower) + } + return out +} + +function isMissingDirectoryError(res: { error?: string; errorCode?: string; errorDetails?: Record }): boolean { + if (res.errorDetails?.reason === 'ENOENT' || res.errorCode === 'ENOENT') return true + const msg = String(res.error || '') + return /Directory does not exist|ENOENT/i.test(msg) +} + /** 一次界面扫描的错误汇总;多个目录并行扫描时保留可读目录的结果。 */ export function createDirectoryScanner(hostOverride?: DynamicBridge) { const failures = new Map() return { async scan(dir: string, options: number | ScanDirectoryTreeOptions = 160) { const result = await scanRealDirectoryTree(dir, options, hostOverride) - const error = result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') + const ignoreMissing = typeof options === 'object' && options !== null && options.ignoreMissing === true + const error = + result.missing && ignoreMissing + ? '' + : result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') if (error) failures.set(dir, error) else failures.delete(dir) return result @@ -648,26 +686,38 @@ async function scanDirectoryTreeWithError( const safeLimit = Math.min(200, Math.max(1, Math.floor(rawLimit || 160))) const hostOverride = opts.hostOverride const filterExt = opts.filterExt + const ignoreMissing = opts.ignoreMissing === true const dirQuery = `dir:${targetDir}` try { let rawPayload: DynamicBridge = null + const searchParams: Record = { + query: dirQuery, + limit: safeLimit, + ...(opts.sortBy ? { sortBy: opts.sortBy } : {}) + } const res = await callHostTransport( 'system_search_files', - { query: dirQuery, limit: safeLimit }, + searchParams, hostOverride ) - if (res.ok && res.data) { + if (res.ok && res.data && res.data.degraded !== true) { rawPayload = res.data + } else if (!res.ok && ignoreMissing && isMissingDirectoryError(res)) { + const missingScan = makeScanResult([], 0, 0, [], { missing: true }) + return { scan: missingScan } } - if (!rawPayload && !hostOverride && typeof window !== 'undefined') { + if (!rawPayload && !hostOverride && res.errorCode === 'METHOD_NOT_AVAILABLE' && typeof window !== 'undefined') { const w = window as DynamicBridge if (typeof w.__ztoolsLauncher?.searchFiles === 'function') { const rawOuter = await w.__ztoolsLauncher.searchFiles(dirQuery, safeLimit) - rawPayload = + const candidate = rawOuter && typeof rawOuter === 'object' && 'data' in rawOuter && rawOuter.data ? rawOuter.data : rawOuter + if (candidate && candidate.degraded !== true && candidate.success !== false) { + rawPayload = candidate + } } } @@ -678,29 +728,32 @@ async function scanDirectoryTreeWithError( let files: RealIndexedFileEntry[] = rawPayload.files.map(normalizeIndexedFileEntry) if (filterExt instanceof RegExp) { files = files.filter(f => !f.isDir && (filterExt.test(f.name) || filterExt.test(f.ext))) - // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索目标扩展名 + // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索明确声明的目标扩展名 if (files.length === 0 && !hostOverride) { - const extTokens = (filterExt.source.match(/[a-z0-9]{2,5}/gi) || []) - .filter(t => !['thumbcache', 'iconcache'].includes(t.toLowerCase())) - .slice(0, 4) - // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 - const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() - const extraLists = await Promise.all( - extTokens.map(ext => searchRealIndexedFiles(`.${ext.toLowerCase()}`, 30, hostOverride)) - ) - const seen = new Set() - for (const list of extraLists) { - for (const item of list) { - if (!item.isDir && item.size > 0 && !seen.has(item.path)) { - if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { - seen.add(item.path) - files.push(item) + const extTokens = extractExtensionTokensFromFilter(filterExt) + if (extTokens.length > 0) { + // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 + const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() + const extraLists = await Promise.all( + extTokens.map(ext => searchRealIndexedFiles(`.${ext}`, 30, hostOverride)) + ) + const seen = new Set() + for (const list of extraLists) { + for (const item of list) { + if (!item.isDir && item.size > 0 && !seen.has(item.path)) { + if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { + seen.add(item.path) + files.push(item) + } } } } } } } + // 先基于过滤后的完整命中集合计算总文件数与总字节数,再按 collectTopN 裁剪样本列表 + const matchedCount = files.length + const matchedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) if (typeof opts.collectTopN === 'number' && opts.collectTopN > 0 && files.length > opts.collectTopN) { files = files.slice(0, opts.collectTopN) } @@ -714,11 +767,10 @@ async function scanDirectoryTreeWithError( ...(s.approximate === true ? { approximate: true } : {}) })) : [] - const computedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) const totalFilesCount = - filterExt instanceof RegExp ? files.length : Number(rawPayload.total_matches ?? files.length) + filterExt instanceof RegExp ? matchedCount : Number(rawPayload.total_matches ?? matchedCount) const totalBytesCount = - filterExt instanceof RegExp ? computedBytes : Number(rawPayload.total_bytes ?? computedBytes) + filterExt instanceof RegExp ? matchedBytes : Number(rawPayload.total_bytes ?? matchedBytes) const visited = Number(rawPayload.visited_entries) return { scan: makeScanResult(files, totalFilesCount, totalBytesCount, subdirs, { @@ -1817,8 +1869,6 @@ export async function writeRealClipboardText(text: string, hostOverride?: Dynami const payload = { text: String(text || '') } const res = await callHostTransport('clipboard_copy_text', payload, hostOverride) if (res.ok) return true - const fallbackRes = await callHostTransport('clipboard_write_text', payload, hostOverride) - if (fallbackRes.ok) return true try { if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) { await navigator.clipboard.writeText(String(text || '')) diff --git a/extensions/mover/tests/mover.host.test.mjs b/extensions/mover/tests/mover.host.test.mjs index e9504660..8d45f1d9 100644 --- a/extensions/mover/tests/mover.host.test.mjs +++ b/extensions/mover/tests/mover.host.test.mjs @@ -351,13 +351,49 @@ test('界面:未勾选时按 Enter 只提示;勾选后需确认并授权, assert.deepEqual(state.relocated, []) host.setConfirm(true) - host.ipc.window_show_select_folder_dialog = () => ({ canceled: true }) + // 第一步(源目录授权)取消:不触发目标授权,也不迁移 + let dialogCalls = 0 + host.ipc.window_show_select_folder_dialog = () => { + dialogCalls++ + return { canceled: true } + } + await view.run(row(), '迁移已勾选的 1 个目录') + assert.equal(dialogCalls, 1) + assert.deepEqual(state.relocated, []) + assert.match(view.tree().props.filterBar.summaryText, /已取消/) + + // 第一步(源目录授权)选了越界路径:提示未获源目录授权,不触发目标授权与迁移 + dialogCalls = 0 + host.ipc.window_show_select_folder_dialog = () => { + dialogCalls++ + return { canceled: false, folderPath: 'D:\\' } + } + await view.run(row(), '迁移已勾选的 1 个目录') + assert.equal(dialogCalls, 1) + assert.equal(host.lastToast().style, 'FAILURE') + assert.match(host.lastToast().title, /源目录授权/) + assert.deepEqual(state.relocated, []) + + // 第一步(源目录授权)通过、第二步(目标分区授权)取消:不迁移 + dialogCalls = 0 + host.ipc.window_show_select_folder_dialog = params => { + dialogCalls++ + if (dialogCalls === 1) return { canceled: false, folderPath: params.defaultPath } + return { canceled: true } + } await view.run(row(), '迁移已勾选的 1 个目录') + assert.equal(dialogCalls, 2) assert.deepEqual(state.relocated, []) assert.match(view.tree().props.filterBar.summaryText, /已取消/) - host.ipc.window_show_select_folder_dialog = () => ({ canceled: false, folderPath: 'D:\\' }) + // 两次授权均通过(先源目录、再目标分区):正常迁移 + const pickedDefaults = [] + host.ipc.window_show_select_folder_dialog = params => { + pickedDefaults.push(params.defaultPath) + return { canceled: false, folderPath: pickedDefaults.length === 1 ? 'C:\\Users\\U' : 'D:\\' } + } await view.run(row(), '迁移已勾选的 1 个目录') + assert.deepEqual(pickedDefaults, ['C:\\Users\\U', 'D:\\']) assert.deepEqual(state.relocated, [{ sourcePath: 'C:\\Users\\U\\Downloads', targetRoot: 'D:\\ZToolsMoved' }]) assert.equal(host.lastToast().style, 'SUCCESS') assert.equal(host.lastToast().title, '已迁移 1 个目录') @@ -460,3 +496,123 @@ test('回归:放宽扫描上限至 maxDepth>=16 / maxFiles>=200;触达上限 view.unmount() } }) + +test('回归:系统路径带尾分隔符或正斜杠时仍正确拼接并归入 C 盘可搬迁列表', async () => { + installScanHost() + host.ipc.system_get_path = ({ name }) => ({ + home: 'C:/Users/U/', + documents: 'C:\\Users\\U\\Documents\\', + downloads: 'C:/Users/U/Downloads/', + videos: 'D:\\Videos\\', + appData: 'C:\\Users\\U\\AppData\\Roaming\\' + })[name] || '' + const snap = await mover.fetchMoverSnapshot() + assert.equal(snap.error, undefined) + const wechat = snap.folders.find(f => f.id === 'mover_wechat') + assert.equal(wechat?.sourcePath, 'C:\\Users\\U\\Documents\\WeChat Files') + assert.equal(wechat?.sizeBytes, 5 * GB) +}) + +test('扫描:自动过滤已是目录联接(Junction)的目录,宿主不可用时不阻塞扫描', async () => { + installScanHost() + let receivedSkipSize = false + const state = installMoverHost({ + sources: ['C:\\Users\\U\\Downloads', 'C:\\Users\\U\\Documents\\WeChat Files'] + }) + state.sources.set(lower('C:\\Users\\U\\Documents\\WeChat Files'), { isJunction: true }) + const origDll = host.ipc.dllplugin_call + host.ipc.dllplugin_call = req => { + if (req.func === 'scanCandidates' && req.params?.skipSize === true) { + receivedSkipSize = true + } + return origDll(req) + } + + const snap = await mover.fetchMoverSnapshot() + assert.equal(snap.error, undefined) + assert.equal(receivedSkipSize, true) + assert.deepEqual(snap.folders.map(f => f.sourcePath), ['C:\\Users\\U\\Downloads']) + assert.equal(snap.totalMovableBytes, 3 * GB) + + // 宿主 scanCandidates 报错时不阻塞扫描,保留已扫出目录 + state.scanError = internalError() + const fallbackSnap = await mover.fetchMoverSnapshot() + assert.equal(fallbackSnap.error, undefined) + assert.deepEqual( + fallbackSnap.folders.map(f => f.sourcePath).sort(), + ['C:\\Users\\U\\Documents\\WeChat Files', 'C:\\Users\\U\\Downloads'] + ) + assert.equal(fallbackSnap.totalMovableBytes, 8 * GB) +}) + +test('源目录授权:按最深共同父目录弹框,支持取消、越界拦截与覆盖通过', async () => { + const downloads = folder('下载', 'C:\\Users\\U\\Downloads', 3 * GB) + const wechat = folder('微信', 'C:\\Users\\U\\Documents\\WeChat Files', 5 * GB) + + // 空列表拒绝 + assert.match((await mover.authorizeMoveSources([])).error, /请先勾选/) + + // 取消返回 canceled: true + installMoverHost({ folderPick: () => ({ canceled: true }) }) + assert.deepEqual(await mover.authorizeMoveSources([downloads, wechat]), { ok: false, canceled: true }) + + // 越界:只选其中一个子目录无法覆盖全部勾选源目录 + host.ipc.window_show_select_folder_dialog = () => ({ canceled: false, folderPath: 'C:\\Users\\U\\Downloads' }) + assert.match((await mover.authorizeMoveSources([downloads, wechat])).error, /请选择 C:\\Users\\U/) + + // 越界:选了非源盘符 + host.ipc.window_show_select_folder_dialog = () => ({ canceled: false, folderPath: 'D:\\' }) + assert.equal((await mover.authorizeMoveSources([downloads])).ok, false) + + // 多目录时 defaultPath 为最深共同父目录,选择该目录或盘符根均通过 + host.ipc.window_show_select_folder_dialog = params => { + assert.equal(params.defaultPath, 'C:\\Users\\U') + return { canceled: false, folderPath: 'c:\\users\\u\\' } + } + assert.equal((await mover.authorizeMoveSources([downloads, wechat])).ok, true) + + host.ipc.window_show_select_folder_dialog = () => ({ canceled: false, folderPath: 'C:\\' }) + assert.equal((await mover.authorizeMoveSources([downloads, wechat])).ok, true) + + // 单目录时 defaultPath 为其父目录,选该目录本身同样通过 + host.ipc.window_show_select_folder_dialog = params => { + assert.equal(params.defaultPath, 'C:\\Users\\U') + return { canceled: false, folderPath: 'C:\\Users\\U\\Downloads' } + } + assert.equal((await mover.authorizeMoveSources([downloads])).ok, true) + + // 弹窗异常如实返回错误 + host.ipc.window_show_select_folder_dialog = () => { throw new Error('源目录窗口异常') } + assert.match((await mover.authorizeMoveSources([downloads])).error, /源目录窗口异常/) +}) + +test('目标分区:支持全盘符(优先 system_list_volumes,不可用时回退探测 C~Z 识别高盘符 I:)', async () => { + installScanHost() + // 1) 优先通过 system_list_volumes 获取高盘符 I: 与 J: + host.ipc.system_list_volumes = () => ({ + volumes: [ + { path: 'C:\\', totalBytes: 256 * GB, availableBytes: 30 * GB }, + { mount: 'I:\\', total: 2048 * GB, free: 1500 * GB } + ] + }) + const snapFromVolumes = await mover.fetchMoverSnapshot() + assert.equal(snapFromVolumes.error, undefined) + assert.equal(snapFromVolumes.cDriveFreeBytes, 30 * GB) + assert.deepEqual(snapFromVolumes.targetDrives.map(d => d.targetRoot), ['I:\\ZToolsMoved']) + assert.equal(snapFromVolumes.targetDrives[0].freeBytes, 1500 * GB) + assert.ok(!host.ipcCalls.some(([m]) => m === 'system_get_disk_usage')) + + // 2) system_list_volumes 返回空数组时回退 C~Z 探测,识别 I: 分区 + host.reset() + installScanHost() + host.ipc.system_list_volumes = () => ({ volumes: [] }) + host.ipc.system_get_disk_usage = ({ drive }) => { + if (drive.startsWith('C:')) return { total: 256 * GB, used: 236 * GB, available: 20 * GB, percent: 92 } + if (drive.startsWith('I:')) return { total: 1024 * GB, used: 224 * GB, available: 800 * GB, percent: 22 } + return { total: 0, used: 0, available: 0, percent: 0 } + } + const snapFallback = await mover.fetchMoverSnapshot() + assert.equal(snapFallback.error, undefined) + assert.deepEqual(snapFallback.targetDrives.map(d => d.targetRoot), ['I:\\ZToolsMoved']) + assert.equal(snapFallback.targetDrives[0].freeBytes, 800 * GB) +}) diff --git a/extensions/multi-download/package.json b/extensions/multi-download/package.json index b1c1225a..7830101d 100644 --- a/extensions/multi-download/package.json +++ b/extensions/multi-download/package.json @@ -1,7 +1,7 @@ { "name": "@ztools/plugin-multi-download", - "version": "1.0.0", - "description": "把下载链接交给本机 aria2 多线程下载,没有 aria2 时由客户端单连接下载 HTTP 链接,并管理「下载」文件夹里的文件", + "version": "2.1.0", + "description": "基于宿主 download.transfer 薄原语的多线程分块下载插件(支持 Windows 与 macOS)", "main": "dist/index.js", "types": "dist/index.d.ts", "scripts": { diff --git a/extensions/multi-download/plugin.json b/extensions/multi-download/plugin.json index c72fb8f4..5b6f99e5 100644 --- a/extensions/multi-download/plugin.json +++ b/extensions/multi-download/plugin.json @@ -1,10 +1,9 @@ { "id": "multi-download", "name": "多线程下载", - "description": "把 HTTP、FTP 与磁力链接交给本机运行的 aria2 按 16 / 8 / 4 / 1 线程下载;没有 aria2 时 HTTP 链接由客户端单连接下载。同时可选择文件或文件夹导入并按类型查看、打开、定位或移入回收站", - "version": "2.0.10", - "draft": true, - "draftReason": "多线程分块下载需要用户自行安装并运行 aria2(开启 RPC、不设密钥、允许跨域),插件和客户端都不提供;没有 aria2 时只能单连接下载 HTTP 链接(单个文件不超过 1 GiB,需在 5 分钟内下完),FTP 与磁力链接无法下载。等客户端提供多线程下载能力并在 Windows 上实测通过后再发布", + "description": "基于客户端多线程分块传输引擎高速下载 HTTP/HTTPS 文件,支持 1~16 路并发连接、断点续传、暂停/恢复/取消、限速与下载历史管理", + "version": "2.1.0", + "minAppVersion": "1.3.0.0", "author": "ZTools Team", "entry": "dist/index.js", "icon": "icon.svg", @@ -12,13 +11,15 @@ "网络工具" ], "categoryId": "network", + "requiredCapabilities": [ + "download.transfer" + ], "permissions": [ "network", + "dialog", "fs", - "shell", "clipboard", - "dialog", - "system" + "shell" ], "requireAdmin": false, "nativeComponents": [], @@ -28,20 +29,26 @@ "platform": "windows", "runtime": "electron", "arch": "any" + }, + { + "id": "macos-electron-any", + "platform": "macos", + "runtime": "electron", + "arch": "any" } ], "defaultLocale": "zh-CN", "i18n": { "en-US": { "name": "Multi-Thread Downloader", - "description": "Download HTTP, FTP, and magnet links via local aria2 (16/8/4/1 threads) or fallback single-connection HTTP, plus manage downloaded files by type.", + "description": "Download HTTP/HTTPS files using the host multi-connection transfer engine (1-16 connections) with pause/resume/cancel, resumable persistence, speed limit, and download history.", "keywords": [ "download", - "aria2", "multi-thread", - "magnet", "http", - "ftp" + "https", + "resume", + "transfer" ] } } diff --git a/extensions/multi-download/src/i18n.ts b/extensions/multi-download/src/i18n.ts index 566364ff..76ec6d3a 100644 --- a/extensions/multi-download/src/i18n.ts +++ b/extensions/multi-download/src/i18n.ts @@ -1,265 +1,260 @@ import { createTranslator } from '@ztools/declarative-ui' -const rawT = createTranslator({ - 'zh-CN': { - forbiddenReason: '禁止操作 Windows 系统核心目录中的受保护文件', - outsideClient: '需要在 ZTools 客户端中使用', - importSupportedText: '任意非隐藏普通文件', - sizeUnknown: '大小未识别', - catInstaller: '应用安装包', - catArchive: '压缩归档包', - catMedia: '音视频与图像', - catIsoImage: '系统镜像与模型', - catDocument: '办公文档与脚本', - catOther: '其他下载文件', - preset16Name: '16 线程', - preset16Desc: '16 路并发连接、1MB 最小分块,适合支持分块下载的大文件直链', - preset8Name: '8 线程', - preset8Desc: '8 路并发连接,服务器限制连接数时比 16 线程稳妥', - preset4Name: '4 线程', - preset4Desc: '适合严格限制单 IP 连接数的镜像站与网盘直链', - preset1Name: '单线程', - preset1Desc: '适合不支持分块请求(Range)的链接', - protocolNone: '无链接', - protocolMagnet: '磁力链接', - protocolFtp: 'FTP 链接', - protocolHttp: 'HTTP(S) 链接', - protocolClipboardEmpty: '剪贴板未检测到下载链接', - errNoFetch: '当前环境不能发起网络请求', - errAria2RpcError: 'aria2 返回错误', - errAria2Http: 'aria2 返回 HTTP {status}', - errAria2Unrecognized: 'aria2 返回的结果无法识别', - saveDialogTitle: '保存下载文件', - saveFilterType: '{ext} 文件', - saveFilterAll: '所有文件', - errSaveDialogFailed: '无法打开保存对话框:{reason}', - errNoReason: '客户端未返回原因', - errDownloadCanceled: '已取消下载', - errDownloadFailed: '下载失败:{reason}', - msgClientDownloaded: '未连接到本机 aria2({reason}),已用客户端单连接下载到 {path}{sizeText},线程档位未生效', - errInvalidUrlPrompt: '未提供有效的 HTTP/HTTPS/FTP/磁力链接,请先复制下载链接到剪贴板,或粘贴到搜索框', - errAria2Rejected: 'aria2 没有接受这个任务:{error}', - msgAria2Added: '已添加到本机 aria2({threads} 线程{gidText}),下载进度请在 aria2 中查看', - msgAria2Gid: ',任务 {gid}', - kindMagnet: '磁力链接', - kindFtp: 'FTP 链接', - errAria2Required: '{kind}需要本机运行 aria2 并开启 RPC(未连接:{error});可在 Ctrl+K 中复制 aria2c 命令自行运行', - errInvalidUrl: '未识别到下载链接', - errClipboardWriteFailed: '复制 aria2c 命令失败:无法写入剪贴板', - msgCopiedCommand: '已复制 aria2c 命令({name})。插件不会运行它,请在已安装 aria2 的终端中运行', - errTrashFailed: '移入回收站失败', - errEmptyPath: '路径为空', - msgRevealed: '已在资源管理器中定位: {path}', - errRevealFailed: '定位失败: {path}', - msgOpened: '已打开: {path}', - errOpenFailed: '打开失败: {path}', - errRefreshFailed: '读取下载环境状态失败: {error}', - errImportFailed: '导入失败', - pickFilesTitle: '选择文件', - pickFolderTitle: '选择要导入的文件夹', - errNoFolderPicked: '没有选择文件夹', - confirmVolumeTitle: '导入整个磁盘 {path} 中的文件?', - confirmVolumeMessage: '将读取该磁盘下 5 层以内的文件夹,最多导入 500 个非隐藏文件,可能需要一些时间。', - confirmVolumePrimary: '继续导入', - dropTitle: '拖入文件或文件夹', - dropSubtitle: '文件夹内 5 层以内的文件会按类型归类导入', - errTrashingRemove: '该文件正在移入回收站,完成后再移除', - errBusyClear: '正在处理,完成后再清空', - errOperationFailed: '操作失败: {error}', - promptSelectTrash: '请先勾选要移入回收站的文件', - confirmTrashMore: '\n等 {count} 个文件', - confirmTrashTitle: '把 {count} 个文件移入回收站?', - confirmTrashMessage: '共 {size},可在系统回收站中恢复。\n{preview}{more}', - confirmTrashPrimary: '移入回收站', - confirmCancel: '取消', - statusTrashCanceled: '已取消移入回收站', - trashFailedSep: '、', - trashFailedPrefix: ';{count} 个失败:{details}', - trashSuccessMsg: '已将 {count} 个文件移入回收站({size}){failedText}', - trashNoneMsg: '没有文件被移入回收站{failedText}', - aria2Online: 'aria2 已连接({name})', - aria2Offline: '未连接 aria2:HTTP 链接用客户端单连接下载,线程档位不生效', - driveUnknown: '下载盘剩余空间未知', - driveFree: '{drive} 剩余 {free}{lowHint}', - driveLowHint: '(不足 10%)', - summaryImporting: '正在导入:已读取 {dirs} 个文件夹,找到 {files} 个文件', - summaryEmpty: '{aria2} · {drive} · 尚未添加文件 · 可选择文件、文件夹,或直接拖入', - summaryFiles: '{aria2} · {drive} · 已选 {selected}/{total} 项 ({size}) · 清空列表 Ctrl+Shift+Backspace', - actionPickFiles: '选择文件…', - actionPickFolder: '选择文件夹…', - actionClearList: '清空列表', - actionTrashSelected: '移入回收站(已勾选 {count} 项 / {size})', - actionOpenDownloadDir: '打开下载文件夹', - sectionList: '列表', - linkTitleWithProtocol: '当前链接 · {protocol}', - linkTitleEmpty: '当前链接', - linkSubtitleEmpty: '复制下载链接后选「重新读取剪贴板与服务状态」,或把链接粘贴到搜索框', - tagLowSpace: '磁盘空间不足 10%', - tagUnrecognized: '未识别', - tagAria2Multi: 'aria2 多线程', - tagSingleConn: '单连接', - actionDownloadLink: '下载此链接', - actionRefreshClipboard: '重新读取剪贴板与服务状态', - actionCopyAria2c: '复制 aria2c 命令({name})', - allFilesTitle: '全部文件', - allFilesCount: '{count} 个文件', - itemCountTag: '{count} 项', - actionViewAllFiles: '查看全部文件', - catExtsSubtitle: '后缀: {exts}', - catOtherSubtitle: '其他未分类文件', - actionFilterCat: '只看{name}', - actionOpenWithDefault: '用默认程序打开', - actionRevealInExplorer: '在资源管理器中显示', - actionUncheck: '取消勾选', - actionCheck: '勾选', - actionRemoveFromList: '从列表移除', - actionUnselectAll: '取消全选', - actionSelectAll: '全选', - fileListFallbackTitle: '文件列表', - emptyNoMatch: '当前分类下没有匹配的文件', - emptyCategory: '当前分类下没有文件', - emptyDefault: '尚未添加文件 · 可选择文件、文件夹,或直接拖入', - searchPlaceholder: '粘贴 HTTP/HTTPS/FTP/磁力链接,或搜索已添加的文件名...', - presetTooltip: 'aria2 线程档位(只在连接到本机 aria2 时生效)', - presetItemTitle: '{name} (分块 {splitSize})', - btnPickFiles: '选择文件', - btnPickFolder: '选择文件夹', - subListTitle: '{category} ({count} 项 · 已选 {size})', - leftSectionTitle: '链接与文件分类' +const rawT = createTranslator( + { + 'zh-CN': { + forbiddenReason: '禁止保存到受保护的系统目录或包含路径穿越', + outsideClient: '需要在 ZTools 客户端中使用', + protocolNone: '无链接', + protocolHttp: 'HTTP/HTTPS 链接', + protocolMagnet: '磁力链接(暂不支持)', + protocolFtp: 'FTP 链接(暂不支持)', + protocolInvalid: '无效链接', + errHostRequired: '未连接到 ZTools 宿主环境,无法发起多线程下载', + errInvalidUrl: '请输入或粘贴有效的 HTTP/HTTPS 下载链接', + errUnsupportedProtocolMagnet: '一期仅支持 HTTP/HTTPS 多线程分块下载,暂不支持磁力链接(magnet:)', + errUnsupportedProtocolFtp: '一期仅支持 HTTP/HTTPS 多线程分块下载,暂不支持 FTP 协议(ftp:)', + errMissingOutputDir: '请先选择下载输出目录', + errConnectionsRange: '并发连接数必须在 1 到 16 之间', + errInvalidSha256: 'SHA-256 校验值必须为 64 位十六进制字符串', + errCapabilityUnsupported: '当前客户端不支持多线程下载引擎,请升级到最新版本', + errCapabilityCheckFailed: '探测下载引擎能力失败:{error}', + errProvisionFailed: '准备多线程下载引擎失败:{error}', + errAddTransferFailed: '创建多线程下载任务失败:{error}', + errPauseFailed: '暂停任务失败:{error}', + errResumeFailed: '恢复任务失败:{error}', + errCancelFailed: '取消任务失败:{error}', + errStatusFailed: '查询下载任务状态失败:{error}', + errPickDirFailed: '选择输出目录失败:{error}', + errPickDirCanceled: '已取消选择输出目录', + errOpenFailed: '打开失败:{path}', + errRevealFailed: '定位文件失败:{path}', + errEmptyPath: '路径不能为空', + errTaskIdRequired: '任务 ID 不能为空', + errClipboardCopyFailed: '写入剪贴板失败', + msgProvisionSuccess: '多线程下载引擎已就绪', + msgTransferAdded: '已加入多线程下载队列:{name}({connections} 连接)', + msgTransferPaused: '已暂停任务:{name}', + msgTransferResumed: '已恢复任务:{name}', + msgTransferCancelled: '已取消任务:{name}', + msgDirUpdated: '已设置输出目录:{dir}', + msgLinkCopied: '已复制下载链接', + msgHistoryCleared: '已清空下载历史记录', + msgHistoryRemoved: '已从历史记录中移除', + msgOpened: '已打开:{path}', + msgRevealed: '已在文件管理器中显示:{path}', + pickDirTitle: '选择多线程下载输出目录', + conn16: '16 路并发连接', + conn8: '8 路并发连接', + conn4: '4 路并发连接', + conn1: '单连接(1 路)', + rateUnlimited: '不限速', + rate2m: '2 MB/s', + rate5m: '5 MB/s', + rate10m: '10 MB/s', + rate20m: '20 MB/s', + stateQueued: '排队中', + stateRunning: '下载中', + statePaused: '已暂停', + stateCompleted: '已完成', + stateCancelled: '已取消', + stateFailed: '失败', + engineReady: '引擎就绪', + engineReadyResumable: '引擎就绪 · 支持断点续传', + engineNeedsProvision: '需准备引擎', + engineUnsupported: '客户端不支持', + engineChecking: '检测引擎中…', + searchPlaceholder: '粘贴 HTTP/HTTPS 下载链接,或搜索任务与下载历史…', + dropdownTooltip: '选择并发连接数(1~16 路)', + btnStartDownload: '开始下载', + btnPrepareEngine: '准备引擎', + btnChooseDir: '选择目录', + summaryOutside: '需要在 ZTools 客户端中使用', + summaryNormal: '{engine} · 活跃 {active} 个 · 历史 {history} 条 · 输出:{dir}', + summaryDirUnset: '未选择目录', + wbTitle: '多线程下载参数', + wbSubtitle: 'HTTP/HTTPS 分块传输 · 1~16 路并发', + wbFieldConnections: '并发连接数', + wbFieldRateLimit: '限速上限', + wbFieldOverwrite: '覆盖同名文件', + wbFieldSha256: '期望 SHA-256(可选)', + wbFieldSha256Placeholder: '留空跳过校验,填写 64 位 Hex', + wbFieldOutputDir: '输出目录', + wbOutputDirUnset: '点击「选择目录」设定', + wbFieldEngine: '传输引擎状态', + previewTitleActive: '待下载链接', + previewTitleIdle: '等待 HTTP/HTTPS 链接', + previewSubIdle: '在顶部粘贴 HTTP/HTTPS 直链并按 Enter 启动多线程分块下载(一期暂不支持磁力与 FTP 协议)', + previewSubUnsupported: '{reason}', + previewBadgeReady: 'HTTP/HTTPS', + previewBadgeUnsupported: '暂不支持', + previewBadgeIdle: '就绪', + metricProtocol: '协议识别', + metricFileName: '建议文件名', + metricConnections: '并发连接', + metricResume: '断点续传', + resumeSupported: '支持', + resumeNotReported: '未声明', + fileNameAuto: '下载时自动确定', + subListTitle: '传输队列与下载历史(活跃 {active} · 历史 {history})', + subListEmpty: '暂无下载任务或历史 · 粘贴 HTTP/HTTPS 链接按 Enter 开始下载', + subListNoMatch: '没有匹配的任务或历史记录', + sectionActiveTasks: '活跃与本次传输任务({count})', + sectionHistory: '下载历史({count})', + taskSubRunning: '{state} · {downloaded} / {total} · {speed}/s · {connections} 连接', + taskSubRunningUnknownTotal: '{state} · 已下 {downloaded} · {speed}/s · {connections} 连接', + taskSubError: '失败:{error}', + historySub: '{state} · {size} · {dir}', + sizeUnknown: '大小未知', + actionStartDownload: '开始下载当前链接', + actionPrepareEngine: '准备多线程下载引擎', + actionChooseDir: '选择输出目录…', + actionRefreshStatus: '刷新任务状态与剪贴板', + actionPause: '暂停任务', + actionResume: '恢复下载', + actionCancel: '取消任务', + actionOpenFile: '打开文件', + actionOpenDir: '打开输出目录', + actionRevealFile: '在文件管理器中显示', + actionRedownload: '使用当前配置重新下载', + actionCopyUrl: '复制下载链接', + actionRemoveHistory: '从历史记录移除', + actionClearHistory: '清空全部历史记录', + sectionActions: '更多操作' + }, + 'en-US': { + forbiddenReason: 'Saving to protected system directories or path traversal is prohibited', + outsideClient: 'This plugin must be used inside the ZTools client', + protocolNone: 'No link', + protocolHttp: 'HTTP/HTTPS Link', + protocolMagnet: 'Magnet Link (Unsupported)', + protocolFtp: 'FTP Link (Unsupported)', + protocolInvalid: 'Invalid URL', + errHostRequired: 'Not connected to the ZTools host environment; cannot start download', + errInvalidUrl: 'Enter or paste a valid HTTP/HTTPS download URL', + errUnsupportedProtocolMagnet: 'Phase 1 only supports HTTP/HTTPS multi-connection transfers; magnet links are not supported yet', + errUnsupportedProtocolFtp: 'Phase 1 only supports HTTP/HTTPS multi-connection transfers; FTP links are not supported yet', + errMissingOutputDir: 'Please choose an output directory first', + errConnectionsRange: 'Max connections must be between 1 and 16', + errInvalidSha256: 'Expected SHA-256 must be a 64-character hexadecimal string', + errCapabilityUnsupported: 'This client does not support the multi-connection download engine; please upgrade ZTools', + errCapabilityCheckFailed: 'Failed to inspect download engine capabilities: {error}', + errProvisionFailed: 'Failed to provision download engine: {error}', + errAddTransferFailed: 'Failed to add download task: {error}', + errPauseFailed: 'Failed to pause task: {error}', + errResumeFailed: 'Failed to resume task: {error}', + errCancelFailed: 'Failed to cancel task: {error}', + errStatusFailed: 'Failed to query transfer status: {error}', + errPickDirFailed: 'Failed to select output directory: {error}', + errPickDirCanceled: 'Output directory selection cancelled', + errOpenFailed: 'Failed to open: {path}', + errRevealFailed: 'Failed to reveal item: {path}', + errEmptyPath: 'Path cannot be empty', + errTaskIdRequired: 'Task ID is required', + errClipboardCopyFailed: 'Failed to copy text to clipboard', + msgProvisionSuccess: 'Multi-connection download engine is ready', + msgTransferAdded: 'Added to download queue: {name} ({connections} [[connections:connection|connections]])', + msgTransferPaused: 'Paused task: {name}', + msgTransferResumed: 'Resumed task: {name}', + msgTransferCancelled: 'Cancelled task: {name}', + msgDirUpdated: 'Output directory updated: {dir}', + msgLinkCopied: 'Download URL copied', + msgHistoryCleared: 'Download history cleared', + msgHistoryRemoved: 'Removed from download history', + msgOpened: 'Opened: {path}', + msgRevealed: 'Revealed in file manager: {path}', + pickDirTitle: 'Select Download Output Directory', + conn16: '16 Connections', + conn8: '8 Connections', + conn4: '4 Connections', + conn1: 'Single Connection (1)', + rateUnlimited: 'Unlimited', + rate2m: '2 MB/s', + rate5m: '5 MB/s', + rate10m: '10 MB/s', + rate20m: '20 MB/s', + stateQueued: 'Queued', + stateRunning: 'Downloading', + statePaused: 'Paused', + stateCompleted: 'Completed', + stateCancelled: 'Cancelled', + stateFailed: 'Failed', + engineReady: 'Engine Ready', + engineReadyResumable: 'Engine Ready · Resumable', + engineNeedsProvision: 'Provision Required', + engineUnsupported: 'Unsupported Client', + engineChecking: 'Checking Engine...', + searchPlaceholder: 'Paste HTTP/HTTPS URL, or search active tasks and history...', + dropdownTooltip: 'Concurrent connections (1-16)', + btnStartDownload: 'Download', + btnPrepareEngine: 'Prepare Engine', + btnChooseDir: 'Output Folder', + summaryOutside: 'This plugin must be used inside the ZTools client', + summaryNormal: '{engine} · {active} active · {history} history · Output: {dir}', + summaryDirUnset: 'Not selected', + wbTitle: 'Transfer Parameters', + wbSubtitle: 'HTTP/HTTPS chunked transfer · 1-16 connections', + wbFieldConnections: 'Connections', + wbFieldRateLimit: 'Speed Limit', + wbFieldOverwrite: 'Overwrite Existing', + wbFieldSha256: 'Expected SHA-256 (Optional)', + wbFieldSha256Placeholder: 'Leave empty to skip, or enter 64-char hex', + wbFieldOutputDir: 'Output Folder', + wbOutputDirUnset: 'Click "Output Folder" to choose', + wbFieldEngine: 'Engine Status', + previewTitleActive: 'Detected Link', + previewTitleIdle: 'Waiting for HTTP/HTTPS URL', + previewSubIdle: 'Paste an HTTP/HTTPS direct URL above and press Enter (magnet and FTP are not supported in phase 1)', + previewSubUnsupported: '{reason}', + previewBadgeReady: 'HTTP/HTTPS', + previewBadgeUnsupported: 'Unsupported', + previewBadgeIdle: 'Ready', + metricProtocol: 'Protocol', + metricFileName: 'Suggested File', + metricConnections: 'Connections', + metricResume: 'Resumable', + resumeSupported: 'Supported', + resumeNotReported: 'Not reported', + fileNameAuto: 'Auto-detected on start', + subListTitle: 'Transfers & History ({active} active · {history} history)', + subListEmpty: 'No transfers or history yet · Paste an HTTP/HTTPS URL and press Enter', + subListNoMatch: 'No matching transfers or history items', + sectionActiveTasks: 'Active & Session Transfers ({count})', + sectionHistory: 'Download History ({count})', + taskSubRunning: '{state} · {downloaded} / {total} · {speed}/s · {connections} conn', + taskSubRunningUnknownTotal: '{state} · {downloaded} · {speed}/s · {connections} conn', + taskSubError: 'Failed: {error}', + historySub: '{state} · {size} · {dir}', + sizeUnknown: 'Unknown size', + actionStartDownload: 'Download Current URL', + actionPrepareEngine: 'Provision Download Engine', + actionChooseDir: 'Choose Output Folder…', + actionRefreshStatus: 'Refresh Tasks & Clipboard', + actionPause: 'Pause Task', + actionResume: 'Resume Task', + actionCancel: 'Cancel Task', + actionOpenFile: 'Open File', + actionOpenDir: 'Open Output Folder', + actionRevealFile: 'Reveal in File Manager', + actionRedownload: 'Download Again', + actionCopyUrl: 'Copy Download URL', + actionRemoveHistory: 'Remove from History', + actionClearHistory: 'Clear All History', + sectionActions: 'More Actions' + } }, - 'en-US': { - forbiddenReason: 'Operations on protected Windows core system directories are prohibited', - outsideClient: 'This plugin must be used inside the ZTools client', - importSupportedText: 'any non-hidden regular file', - sizeUnknown: 'Unknown size', - catInstaller: 'Installers', - catArchive: 'Archives', - catMedia: 'Media & Images', - catIsoImage: 'Disk Images & Models', - catDocument: 'Documents & Scripts', - catOther: 'Other Downloads', - preset16Name: '16 Threads', - preset16Desc: '16 concurrent connections, 1MB min split—ideal for large direct links supporting range requests', - preset8Name: '8 Threads', - preset8Desc: '8 concurrent connections—safer than 16 when servers limit connections', - preset4Name: '4 Threads', - preset4Desc: 'Best for mirrors or cloud drives with strict per-IP connection limits', - preset1Name: 'Single Thread', - preset1Desc: 'For links that do not support Range requests', - protocolNone: 'No link', - protocolMagnet: 'Magnet Link', - protocolFtp: 'FTP Link', - protocolHttp: 'HTTP(S) Link', - protocolClipboardEmpty: 'No download link detected in clipboard', - errNoFetch: 'Network requests are unavailable in current environment', - errAria2RpcError: 'aria2 returned an error', - errAria2Http: 'aria2 returned HTTP {status}', - errAria2Unrecognized: 'Unrecognized response from aria2', - saveDialogTitle: 'Save Downloaded File', - saveFilterType: '{ext} Files', - saveFilterAll: 'All Files', - errSaveDialogFailed: 'Failed to open save dialog: {reason}', - errNoReason: 'No reason returned by client', - errDownloadCanceled: 'Download canceled', - errDownloadFailed: 'Download failed: {reason}', - msgClientDownloaded: 'Local aria2 unreachable ({reason}); downloaded via single client connection to {path}{sizeText} (thread preset inactive)', - errInvalidUrlPrompt: 'No valid HTTP/HTTPS/FTP/Magnet link provided; copy a link to clipboard or paste it in search', - errAria2Rejected: 'aria2 rejected the task: {error}', - msgAria2Added: 'Added to local aria2 ({threads} [[threads:thread|threads]]{gidText}); check progress in aria2', - msgAria2Gid: ', GID {gid}', - kindMagnet: 'Magnet link', - kindFtp: 'FTP link', - errAria2Required: '{kind} requires local aria2 with RPC enabled (unreachable: {error}); copy the aria2c command via Ctrl+K', - errInvalidUrl: 'No valid download link recognized', - errClipboardWriteFailed: 'Failed to copy aria2c command to clipboard', - msgCopiedCommand: 'Copied aria2c command ({name}). Run it in a terminal with aria2 installed', - errTrashFailed: 'Failed to move to Trash', - errEmptyPath: 'Path is empty', - msgRevealed: 'Revealed in Explorer: {path}', - errRevealFailed: 'Failed to reveal: {path}', - msgOpened: 'Opened: {path}', - errOpenFailed: 'Failed to open: {path}', - errRefreshFailed: 'Failed to read download environment status: {error}', - errImportFailed: 'Import failed', - pickFilesTitle: 'Select Files', - pickFolderTitle: 'Select Folder to Import', - errNoFolderPicked: 'No folder selected', - confirmVolumeTitle: 'Import files from entire drive {path}?', - confirmVolumeMessage: 'Scans up to 5 levels deep and imports up to 500 non-hidden files; this may take a moment.', - confirmVolumePrimary: 'Continue Import', - dropTitle: 'Drop Files or Folders', - dropSubtitle: 'Files within 5 folder levels are imported and categorized by type', - errTrashingRemove: 'This file is being moved to Trash; wait until it finishes', - errBusyClear: 'Operation in progress; wait before clearing', - errOperationFailed: 'Operation failed: {error}', - promptSelectTrash: 'Check at least one file to move to Trash', - confirmTrashMore: '\n...and {count} [[count:file|files]] total', - confirmTrashTitle: 'Move {count} file(s) to Trash?', - confirmTrashMessage: 'Total {size}; recoverable from system Trash.\n{preview}{more}', - confirmTrashPrimary: 'Move to Trash', - confirmCancel: 'Cancel', - statusTrashCanceled: 'Canceled moving to Trash', - trashFailedSep: ', ', - trashFailedPrefix: '; {count} failed: {details}', - trashSuccessMsg: 'Moved {count} file(s) to Trash ({size}){failedText}', - trashNoneMsg: 'No files were moved to Trash{failedText}', - aria2Online: 'aria2 Connected ({name})', - aria2Offline: 'aria2 offline: HTTP uses single-connection client download (thread preset inactive)', - driveUnknown: 'Download drive free space unknown', - driveFree: '{drive} Free {free}{lowHint}', - driveLowHint: ' (< 10%)', - summaryImporting: 'Importing: scanned {dirs} folder(s), found {files} file(s)', - summaryEmpty: '{aria2} · {drive} · No files yet · Pick files/folders or drag and drop', - summaryFiles: '{aria2} · {drive} · Selected {selected}/{total} ({size}) · Clear Ctrl+Shift+Backspace', - actionPickFiles: 'Select Files…', - actionPickFolder: 'Select Folder…', - actionClearList: 'Clear List', - actionTrashSelected: 'Move to Trash ({count} checked / {size})', - actionOpenDownloadDir: 'Open Downloads Folder', - sectionList: 'List', - linkTitleWithProtocol: 'Current Link · {protocol}', - linkTitleEmpty: 'Current Link', - linkSubtitleEmpty: 'Copy a download link and choose "Refresh Clipboard & Status", or paste into search', - tagLowSpace: 'Disk < 10%', - tagUnrecognized: 'None', - tagAria2Multi: 'aria2 Multi-Thread', - tagSingleConn: 'Single Connection', - actionDownloadLink: 'Download Link', - actionRefreshClipboard: 'Refresh Clipboard & Status', - actionCopyAria2c: 'Copy aria2c Command ({name})', - allFilesTitle: 'All Files', - allFilesCount: '{count} file(s)', - itemCountTag: '{count}', - actionViewAllFiles: 'View All Files', - catExtsSubtitle: 'Exts: {exts}', - catOtherSubtitle: 'Uncategorized files', - actionFilterCat: 'Only {name}', - actionOpenWithDefault: 'Open with Default App', - actionRevealInExplorer: 'Reveal in Explorer', - actionUncheck: 'Uncheck', - actionCheck: 'Check', - actionRemoveFromList: 'Remove from List', - actionUnselectAll: 'Unselect All', - actionSelectAll: 'Select All', - fileListFallbackTitle: 'Files', - emptyNoMatch: 'No matching files in this category', - emptyCategory: 'No files in this category', - emptyDefault: 'No files added yet · Select files/folders or drag and drop', - searchPlaceholder: 'Paste HTTP/HTTPS/FTP/Magnet link, or search added files…', - presetTooltip: 'aria2 thread preset (active only when local aria2 is connected)', - presetItemTitle: '{name} (split {splitSize})', - btnPickFiles: 'Select Files', - btnPickFolder: 'Select Folder', - subListTitle: '{category} ({count} · Selected {size})', - leftSectionTitle: 'Link & Categories' - } -}) + { defaultLocale: 'en-US' } +) + export const t: typeof rawT = (key, params) => { const out = rawT(key, params) if (!out.includes('[[')) return out - return out.replace(/\[\[([A-Za-z0-9_.-]+):([^|\]]+)\|([^\]]+)\]\]/g, (_m, k: string, one: string, other: string) => { - const v = params?.[k] - const n = typeof v === 'number' ? v : Number(String(v ?? '').replace(/,/g, '')) - return n === 1 ? one : other - }) + return out.replace( + /\[\[([A-Za-z0-9_.-]+):([^|\]]+)\|([^\]]+)\]\]/g, + (_m, k: string, one: string, other: string) => { + const v = params?.[k] + const n = typeof v === 'number' ? v : Number(String(v ?? '').replace(/,/g, '')) + return n === 1 ? one : other + } + ) } diff --git a/extensions/multi-download/src/index.ts b/extensions/multi-download/src/index.ts index 7e52223a..7f6023ff 100644 --- a/extensions/multi-download/src/index.ts +++ b/extensions/multi-download/src/index.ts @@ -1,9 +1,9 @@ /** - * 多线程下载界面(布局二:左侧当前链接与下载文件分类 + 右侧本次下载与手动导入的文件列表) + * 多线程下载界面(标准布局三:左侧参数工作台 + 右侧传输队列与下载历史) * - * - 搜索框右侧下拉框选择 aria2 线程档位(16 / 8 / 4 / 1 线程,只在连接到本机 aria2 时生效) - * - 顶栏固定「选择文件」「选择文件夹」2 个按钮,支持拖入/粘贴文件夹展开并按类型归类 - * - 移入回收站只处理已勾选的文件,执行前必须确认;从列表移除/清空列表不删除磁盘文件 + * - 严格基于宿主 download.transfer 薄原语(支持 Windows 与 macOS) + * - 活跃任务进度与续传状态以 tool_download_transfer_status 为唯一真相源,同时接收 tool_runtime_progress 实时推送 + * - LocalStorage 持久化保存下载历史与输出目录偏好 */ import { @@ -13,787 +13,808 @@ import { Icon, List, Toast, - confirmAlert, showToast, useEffect, useLocale, useRef, - useState, - getLocale -} from "@ztools/declarative-ui"; -import { isRealElectronHost } from "./native-ipc.js"; -import { t } from "./i18n.js"; + useState +} from '@ztools/declarative-ui' +import { t } from './i18n.js' +import { resolveErrorMessage } from './error-i18n.js' import { - ARIA2_ENDPOINT, - MULTI_DOWNLOAD_IMPORT_RULES, - computeDownloadStats, - copyAria2cCommand, - createClientDownloadedItem, - createMultiDownloadImportTransport, - deleteDownloadedFiles, - detectDownloadUrlFromText, - fetchMultiDownloadSnapshot, + STATUS_POLL_INTERVAL_MS, + addDownloadTransfer, + buildHistoryEntryFromTask, + cancelDownloadTransfer, + copyDownloadUrl, + ensureDownloadTransferEngine, + fetchDownloadTransferStatus, + fetchInitialDownloadContext, formatBytes, - getDownloadCategories, - getThreadSplitPresets, - isDriveLowOnSpace, - openDownloadedFile, - openDownloadedFileLocation, - startMultiThreadDownloadTask, - toDownloadedFileItem, - type DownloadFileCategory, - type DownloadedFileItem, - type MultiDownloadSnapshot, - type NativeInvocationResult, - type ThreadSplitPresetId -} from "./logic.js"; -import { - collectFolderFiles, - createImportInputProps, - expandInputPaths, - friendlyFileError, - isVolumeRoot, - mergeByPath, - normalizeFileInput, - pathKey, - pickFiles, - pickFolder, - summarizeImport, - type FileImportResult, - type NormalizedFileInput -} from "./file-import.js"; -import { resolveErrorMessage } from './error-i18n.js' - -export function getOutsideClientText(): string { - return t("outsideClient"); -} -const LINK_PATTERN = /^(https?|ftp|magnet):/i; - -function createEmptySnapshot(): MultiDownloadSnapshot { - return { - downloadDir: "", - driveLetter: "", - driveInfoAvailable: false, - driveFreeBytes: 0, - driveTotalBytes: 0, - aria2RpcOnline: false, - aria2Status: { online: false }, - aria2Endpoint: ARIA2_ENDPOINT, - sniffedClipboardUrl: "", - sniffedProtocol: "", - files: [], - totalSizeBytes: 0, - categoryStats: [], - updatedAt: "" - }; + inspectDownloadUrl, + isActiveTransferState, + isRealElectronHost, + loadDownloadHistory, + loadSavedOutputDir, + mergeHistoryEntry, + openDownloadItem, + pauseDownloadTransfer, + probeDownloadTransferCapability, + resumeDownloadTransfer, + revealDownloadItem, + saveDownloadHistory, + saveOutputDirPreference, + selectDownloadOutputDir, + type ConnectionPresetValue, + type DownloadHistoryEntry, + type DownloadTransferRecord, + type DownloadTransferState, + type TransferCapabilityState +} from './logic.js' +import { subscribeRuntimeProgress } from './tool-runtime.js' + +export * from './logic.js' + +const RATE_LIMIT_MAP: Readonly> = { + unlimited: 0, + '2m': 2 * 1024 * 1024, + '5m': 5 * 1024 * 1024, + '10m': 10 * 1024 * 1024, + '20m': 20 * 1024 * 1024 } -function baseName(p: string): string { - return p.split(/[\\/]/).pop() || p; +function getStateLabel(state: DownloadTransferState): string { + switch (state) { + case 'queued': + return t('stateQueued') + case 'running': + return t('stateRunning') + case 'paused': + return t('statePaused') + case 'completed': + return t('stateCompleted') + case 'cancelled': + return t('stateCancelled') + case 'failed': + return t('stateFailed') + } } -function formatItemSize(bytes: number | null): string { - return bytes === null ? t("sizeUnknown") : formatBytes(bytes); +function getStateIcon(state: DownloadTransferState): Icon { + switch (state) { + case 'queued': + return Icon.Clock + case 'running': + return Icon.Download + case 'paused': + return Icon.Pause + case 'completed': + return Icon.CheckCircle + case 'cancelled': + return Icon.Stop + case 'failed': + return Icon.XMarkCircle + } } export function MultiDownloadCommand() { - useLocale(); - const inClient = isRealElectronHost(); - const transport = createMultiDownloadImportTransport(); - const [snapshot, setSnapshot] = useState(() => createEmptySnapshot()); - const [files, setFiles] = useState([]); - const [selectedCategory, setSelectedCategory] = useState("all"); - const [selectedPresetId, setSelectedPresetId] = useState("threads_16"); - const [checkedIds, setCheckedIds] = useState([]); - const [searchText, setSearchText] = useState(""); - const [statusBanner, setStatusBanner] = useState(""); - const [isLoading, setIsLoading] = useState(false); - const [isImporting, setIsImporting] = useState(false); - const [importProgress, setImportProgress] = useState<{ visitedDirs: number; matchedFiles: number } | null>(null); - const [trashingIds, setTrashingIds] = useState([]); - - const mountedRef = useRef(true); - const busyRef = useRef(false); - const importBatchRef = useRef(0); - const importAbortRef = useRef(null); - const filesRef = useRef([]); - filesRef.current = files; - - const reportResult = async (res: NativeInvocationResult) => { - if (!mountedRef.current) return; - setStatusBanner(res.message); - if (res.error === "CANCELED") return; - await showToast({ style: res.ok ? Toast.Style.Success : Toast.Style.Failure, title: res.message }); - }; - - const refreshHostMeta = async () => { - if (!inClient) { - setStatusBanner(""); - return; + useLocale() + const inClient = isRealElectronHost() + + const [capability, setCapability] = useState({ + status: inClient ? 'needs_provisioning' : 'unsupported', + resumablePersist: false, + platform: 'other' + }) + const [capChecked, setCapChecked] = useState(!inClient) + const [searchText, setSearchText] = useState('') + const [outputDir, setOutputDir] = useState('') + const [connections, setConnections] = useState('8') + const [rateLimitKey, setRateLimitKey] = useState('unlimited') + const [overwrite, setOverwrite] = useState(false) + const [expectedSha256, setExpectedSha256] = useState('') + const [tasks, setTasks] = useState([]) + const [history, setHistory] = useState([]) + const [isBusy, setIsBusy] = useState(false) + + const mountedRef = useRef(true) + const pollTimerRef = useRef | null>(null) + const outputDirByTaskRef = useRef>(new Map()) + const historyRef = useRef([]) + historyRef.current = history + const outputDirRef = useRef('') + outputDirRef.current = outputDir + + const clearPollTimer = () => { + if (pollTimerRef.current !== null) { + clearTimeout(pollTimerRef.current) + pollTimerRef.current = null } - setIsLoading(true); - try { - const data = await fetchMultiDownloadSnapshot(); - if (!mountedRef.current) return; - setSnapshot(data); - } catch (err) { - if (!mountedRef.current) return; - setStatusBanner(t("errRefreshFailed", { error: err instanceof Error ? err.message : String(err) })); - } finally { - if (mountedRef.current) setIsLoading(false); + } + + const syncTerminalTasksToHistory = async (list: readonly DownloadTransferRecord[]) => { + let nextHistory = historyRef.current + let changed = false + for (const task of list) { + if (task.state === 'completed' || task.state === 'failed' || task.state === 'cancelled') { + const dir = outputDirByTaskRef.current.get(task.taskId) || outputDirRef.current + const entry = buildHistoryEntryFromTask(task, dir) + const prev = nextHistory.find((h) => h.taskId === task.taskId) + if (!prev || prev.state !== entry.state || prev.updatedAt !== entry.updatedAt) { + nextHistory = mergeHistoryEntry(nextHistory, entry) + changed = true + } + } } - }; - - const requireClient = (): boolean => { - if (inClient) return true; - const msg = t("outsideClient"); - setStatusBanner(""); - void showToast({ style: Toast.Style.Failure, title: msg }); - return false; - }; - - const applyImportedFiles = (result: FileImportResult) => { - const incoming = result.files.map(toDownloadedFileItem); - const { merged, added, duplicates } = mergeByPath(filesRef.current, incoming, (item) => item.path); - if (added.length > 0) { - filesRef.current = merged; - setFiles(merged); - setStatusBanner(""); + if (changed && mountedRef.current) { + historyRef.current = nextHistory + setHistory(nextHistory) + await saveDownloadHistory(nextHistory) } - const summary = summarizeImport(result, { added: added.length, duplicates }, t("importSupportedText")); - if (summary) { - void showToast({ - style: summary.ok ? Toast.Style.Success : Toast.Style.Failure, - title: summary.title, - message: summary.message - }); + } + + const refreshTransferStatus = async (scheduleNext = true) => { + if (!inClient || !mountedRef.current) return + const res = await fetchDownloadTransferStatus() + if (!mountedRef.current) return + if (res.ok && res.data) { + setTasks(res.data) + await syncTerminalTasksToHistory(res.data) + if (scheduleNext && res.data.some((task) => isActiveTransferState(task.state))) { + clearPollTimer() + pollTimerRef.current = setTimeout(() => { + pollTimerRef.current = null + void refreshTransferStatus(true) + }, STATUS_POLL_INTERVAL_MS) + } } - }; - - const executeImport = async ( - loader: (signal: AbortSignal, notify: (p: { visitedDirs: number; matchedFiles: number }) => void) => Promise - ) => { - if (!requireClient()) return; - importAbortRef.current?.abort(); - const controller = new AbortController(); - importAbortRef.current = controller; - const batch = ++importBatchRef.current; - setIsImporting(true); - setImportProgress(null); + } + + const initializePlugin = async () => { + const storedHistory = await loadDownloadHistory() + const savedDir = await loadSavedOutputDir() + if (!mountedRef.current) return + historyRef.current = storedHistory + setHistory(storedHistory) + if (savedDir) { + outputDirRef.current = savedDir + setOutputDir(savedDir) + } + if (!inClient) { + setCapChecked(true) + return + } + setIsBusy(true) try { - const res = await loader(controller.signal, (progress) => { - if (mountedRef.current && batch === importBatchRef.current) { - setImportProgress(progress); - } - }); - if (!mountedRef.current || batch !== importBatchRef.current) return; - applyImportedFiles(res); - } catch (err) { - if (!mountedRef.current || batch !== importBatchRef.current) return; - void showToast({ style: Toast.Style.Failure, title: t("errImportFailed"), message: friendlyFileError(err) }); - } finally { - if (mountedRef.current && batch === importBatchRef.current) { - importAbortRef.current = null; - setIsImporting(false); - setImportProgress(null); + const [cap, ctx] = await Promise.all([ + probeDownloadTransferCapability(), + fetchInitialDownloadContext() + ]) + if (!mountedRef.current) return + setCapability(cap) + setCapChecked(true) + if (!savedDir && ctx.defaultDownloadDir) { + outputDirRef.current = ctx.defaultDownloadDir + setOutputDir(ctx.defaultDownloadDir) } - } - }; - - const handlePickFiles = () => { - void executeImport(() => pickFiles(transport, MULTI_DOWNLOAD_IMPORT_RULES, { title: t("pickFilesTitle") })); - }; - - const handlePickFolder = () => { - void executeImport(async (signal, notify) => { - const picked = await pickFolder(transport, { title: t("pickFolderTitle"), defaultPath: snapshot.downloadDir || undefined }); - if (picked.canceled) return { files: [], ignored: 0, truncated: false, failedDirs: [], canceled: true }; - if (picked.error || !picked.folderPath) { - return { files: [], ignored: 0, truncated: false, failedDirs: [], canceled: false, error: resolveErrorMessage(picked, t("errNoFolderPicked")) }; + if (ctx.clipboardUrl && !searchText.trim()) { + setSearchText(ctx.clipboardUrl) } - if (isVolumeRoot(picked.folderPath)) { - const accepted = await confirmAlert({ - title: t("confirmVolumeTitle", { path: picked.folderPath }), - message: t("confirmVolumeMessage"), - primaryAction: { title: t("confirmVolumePrimary"), style: "default" } - }); - if (!accepted) return { files: [], ignored: 0, truncated: false, failedDirs: [], canceled: true }; + if (cap.status === 'ready') { + await refreshTransferStatus(true) } - return collectFolderFiles(transport, picked.folderPath, MULTI_DOWNLOAD_IMPORT_RULES, { signal, onProgress: notify }); - }); - }; - - const handleFileInput = (input: NormalizedFileInput) => { - void executeImport((signal, notify) => - expandInputPaths(transport, input.paths, MULTI_DOWNLOAD_IMPORT_RULES, { - knownDirectories: input.directories, - signal, - onProgress: notify - }) - ); - }; - - useEffect(() => { - mountedRef.current = true; - if (inClient) void refreshHostMeta(); - - const w = - typeof window !== "undefined" - ? (window as unknown as { - __ztoolsDeclarativeFeatures?: { fileInput?: boolean }; - ztools?: { - events?: { - on?: (event: string, cb: (payload: unknown) => void) => (() => void) | void; - off?: (event: string, cb: (payload: unknown) => void) => void; - }; - }; - }) - : undefined; - const supportsNativeInput = w?.__ztoolsDeclarativeFeatures?.fileInput === true; - let disposeDrop: (() => void) | undefined; - if (!supportsNativeInput && typeof w?.ztools?.events?.on === "function") { - const listener = (raw: unknown) => { - const parsed = normalizeFileInput(raw); - if (parsed.paths.length > 0) handleFileInput(parsed); - }; - const off = w.ztools.events.on("plugin_files_dropped", listener); - disposeDrop = () => { - if (typeof off === "function") off(); - else w.ztools?.events?.off?.("plugin_files_dropped", listener); - }; + } finally { + if (mountedRef.current) setIsBusy(false) } + } + useEffect(() => { + mountedRef.current = true + void initializePlugin() + const unsub = subscribeRuntimeProgress((event) => { + if (!mountedRef.current) return + if (event.primitiveId && event.primitiveId !== 'download.transfer') return + setTasks((prev) => + prev.map((task) => { + if (task.taskId !== event.taskId) return task + return { + ...task, + ...(typeof event.transferredBytes === 'number' ? { downloadedBytes: event.transferredBytes } : {}), + ...(typeof event.totalBytes === 'number' ? { totalBytes: event.totalBytes } : {}), + ...(typeof event.speedBytesPerSec === 'number' ? { speedBytesPerSec: event.speedBytesPerSec } : {}), + updatedAt: event.timestamp ?? Date.now() + } + }) + ) + if (event.phase === 'completed' || event.phase === 'failed' || event.phase === 'cancelled') { + void refreshTransferStatus(true) + } + }) return () => { - mountedRef.current = false; - importBatchRef.current += 1; - importAbortRef.current?.abort(); - disposeDrop?.(); - }; - }, []); - - const fileInputProps = createImportInputProps(handleFileInput, { - dropTitle: t("dropTitle"), - dropSubtitle: t("dropSubtitle") - }); - - const presets = getThreadSplitPresets(); - const categories = getDownloadCategories(); - const currentPreset = presets.find((p) => p.id === selectedPresetId) || presets[0]; - - const trimmedSearch = searchText.trim(); - const searchHasLink = LINK_PATTERN.test(trimmedSearch); - const keyword = searchHasLink ? "" : trimmedSearch.toLowerCase(); - const activeLink = searchHasLink ? detectDownloadUrlFromText(trimmedSearch) : null; - const activeDownloadUrl = activeLink?.url || snapshot.sniffedClipboardUrl; - const activeProtocol = activeLink?.url ? activeLink.protocol : snapshot.sniffedProtocol; - - const { totalSizeBytes, categoryStats } = computeDownloadStats(files); - - const filteredFiles = files.filter((file) => { - if (selectedCategory !== "all" && file.category !== selectedCategory) return false; - if (keyword) { - const hay = `${file.name} ${file.path} ${file.categoryName}`.toLowerCase(); - if (!hay.includes(keyword)) return false; - } - return true; - }); - - const checkedSet = new Set(checkedIds); - const selectedFiles = files.filter((file) => checkedSet.has(file.id)); - const selectedTotalBytes = selectedFiles.reduce((acc, item) => acc + (item.sizeBytes ?? 0), 0); - - const toggleFileCheck = (id: string) => { - setCheckedIds((prev) => (prev.includes(id) ? prev.filter((item) => item !== id) : [...prev, id])); - }; - - const toggleAllVisible = () => { - const visibleIds = filteredFiles.map((f) => f.id); - const allChecked = visibleIds.length > 0 && visibleIds.every((id) => checkedSet.has(id)); - if (allChecked) { - const removeSet = new Set(visibleIds); - setCheckedIds((prev) => prev.filter((id) => !removeSet.has(id))); - } else { - setCheckedIds((prev) => Array.from(new Set([...prev, ...visibleIds]))); + mountedRef.current = false + clearPollTimer() + unsub() } - }; + }, []) - const handleRemoveFile = (file: DownloadedFileItem) => { - if (trashingIds.includes(file.id)) { - void showToast({ style: Toast.Style.Failure, title: t("errTrashingRemove") }); - return; - } - const next = filesRef.current.filter((item) => item.id !== file.id); - filesRef.current = next; - setFiles(next); - setCheckedIds((prev) => prev.filter((id) => id !== file.id)); - setStatusBanner(""); - }; - - const handleClearFiles = () => { - if (busyRef.current) { - void showToast({ style: Toast.Style.Failure, title: t("errBusyClear") }); - return; - } - importBatchRef.current += 1; - importAbortRef.current?.abort(); - importAbortRef.current = null; - setIsImporting(false); - setImportProgress(null); - filesRef.current = []; - setFiles([]); - setCheckedIds([]); - setStatusBanner(""); - }; - - const upsertDownloadedFile = (filePath: string, sizeBytes?: number) => { - const entry = createClientDownloadedItem(filePath, sizeBytes); - const key = pathKey(entry.path); - const existingIndex = filesRef.current.findIndex((item) => pathKey(item.path) === key); - const next = - existingIndex >= 0 - ? filesRef.current.map((item, idx) => (idx === existingIndex ? { ...entry, id: item.id } : item)) - : [...filesRef.current, entry]; - filesRef.current = next; - setFiles(next); - }; - - const executeDownloadTask = async ( - runner: () => Promise, - trackClientFile = false - ) => { - busyRef.current = true; - setIsLoading(true); + const requireClient = (): boolean => { + if (inClient) return true + void showToast({ style: Toast.Style.Failure, title: t('errHostRequired') }) + return false + } + + const handlePrepareEngine = async () => { + if (!requireClient()) return + setIsBusy(true) try { - const outcome = await runner(); - if (!mountedRef.current) return; - await reportResult(outcome); - if (trackClientFile && outcome.ok) { - const payload = outcome.data as { engine?: unknown; path?: unknown; size?: unknown } | undefined; - if (payload?.engine === "client" && typeof payload.path === "string" && payload.path) { - upsertDownloadedFile(payload.path, typeof payload.size === "number" ? payload.size : undefined); - } + const res = await ensureDownloadTransferEngine() + if (!mountedRef.current) return + await showToast({ style: res.ok ? Toast.Style.Success : Toast.Style.Failure, title: res.message }) + const nextCap = await probeDownloadTransferCapability() + if (!mountedRef.current) return + setCapability(nextCap) + if (nextCap.status === 'ready') { + await refreshTransferStatus(true) } - } catch (err) { - if (!mountedRef.current) return; - await reportResult({ - ok: false, - code: -1, - error: "UNEXPECTED_ERROR", - message: t("errOperationFailed", { error: err instanceof Error ? err.message : String(err) }) - }); } finally { - busyRef.current = false; - if (mountedRef.current) setIsLoading(false); + if (mountedRef.current) setIsBusy(false) + } + } + + const handleChooseOutputDir = async (): Promise => { + if (!requireClient()) return '' + const res = await selectDownloadOutputDir(outputDirRef.current || undefined) + if (!mountedRef.current) return '' + if (!res.ok || !res.data) { + if (res.errorCode !== 'CANCELED') { + await showToast({ style: Toast.Style.Failure, title: res.message }) + } + return '' } - }; - - const handleStartDownload = async () => { - if (!requireClient()) return; - if (!activeDownloadUrl) { - setStatusBanner(""); - await refreshHostMeta(); - return; + outputDirRef.current = res.data.directoryPath + setOutputDir(res.data.directoryPath) + await saveOutputDirPreference(res.data.directoryPath) + await showToast({ style: Toast.Style.Success, title: res.message }) + return res.data.directoryPath + } + + const startDownloadForUrl = async (targetUrl: string) => { + if (!requireClient()) return + const inspected = inspectDownloadUrl(targetUrl) + if (inspected.kind === 'magnet' || inspected.kind === 'ftp') { + await showToast({ style: Toast.Style.Failure, title: inspected.unsupportedReason || t('errInvalidUrl') }) + return } - await executeDownloadTask( - () => startMultiThreadDownloadTask(activeDownloadUrl, snapshot.downloadDir, currentPreset), - true - ); - }; - - const handleCopyCommand = async () => { - if (!requireClient()) return; - await executeDownloadTask(() => copyAria2cCommand(activeDownloadUrl, snapshot.downloadDir, currentPreset)); - }; - - const handleOpenFolder = async () => { - if (!requireClient()) return; - const res = await openDownloadedFile(snapshot.downloadDir); - if (!res.ok) await reportResult(res); - }; - - const handleOpenFile = async (path: string) => { - const res = await openDownloadedFile(path); - if (!res.ok) await reportResult(res); - }; - - const handleShowFile = async (path: string) => { - const res = await openDownloadedFileLocation(path); - if (!res.ok) await reportResult(res); - }; - - const handleBatchTrashSelected = async () => { - const targetList = selectedFiles; - if (targetList.length === 0) { - setStatusBanner(t("promptSelectTrash")); - return; + if (inspected.kind !== 'http') { + await showToast({ style: Toast.Style.Failure, title: t('errInvalidUrl') }) + return } - const preview = targetList - .slice(0, 5) - .map((f) => f.name) - .join("\n"); - const more = targetList.length > 5 ? t("confirmTrashMore", { count: targetList.length }) : ""; - const confirmed = await confirmAlert({ - title: t("confirmTrashTitle", { count: targetList.length }), - message: t("confirmTrashMessage", { size: formatBytes(selectedTotalBytes), preview, more }), - primaryAction: { title: t("confirmTrashPrimary"), style: "destructive" }, - dismissAction: { title: t("confirmCancel") } - }); - if (!confirmed) { - setStatusBanner(t("statusTrashCanceled")); - return; + if (capability.status === 'unsupported') { + await showToast({ style: Toast.Style.Failure, title: resolveErrorMessage(capability, t('errCapabilityUnsupported')) }) + return } - busyRef.current = true; - setIsLoading(true); - setTrashingIds(targetList.map((f) => f.id)); + if (capability.status === 'needs_provisioning') { + await handlePrepareEngine() + return + } + + let targetDir = outputDirRef.current + if (!targetDir) { + targetDir = await handleChooseOutputDir() + if (!targetDir) return + } + + setIsBusy(true) try { - const res = await deleteDownloadedFiles( - targetList.map((f) => f.path), - targetList - ); - if (!mountedRef.current) return; - const failedText = - res.failed.length > 0 - ? t("trashFailedPrefix", { - count: res.failed.length, - details: res.failed - .slice(0, 3) - .map((f) => `${baseName(f.path)}(${f.reason})`) - .join(t("trashFailedSep")) - }) - : ""; - const message = - res.deletedCount > 0 - ? t("trashSuccessMsg", { count: res.deletedCount, size: formatBytes(res.freedBytes), failedText }) - : t("trashNoneMsg", { failedText }); - setStatusBanner(message); - await showToast({ - style: res.failed.length === 0 ? Toast.Style.Success : Toast.Style.Failure, - title: message - }); - const failedKeys = new Set(res.failed.map((f) => pathKey(f.path))); - const targetKeys = new Set(targetList.map((item) => pathKey(item.path))); - const remaining = filesRef.current.filter((f) => { - const key = pathKey(f.path); - return !targetKeys.has(key) || failedKeys.has(key); - }); - filesRef.current = remaining; - setFiles(remaining); - const remainingIds = new Set(remaining.map((f) => f.id)); - setCheckedIds((prev) => prev.filter((id) => remainingIds.has(id))); - } finally { - busyRef.current = false; - if (mountedRef.current) { - setIsLoading(false); - setTrashingIds([]); + const maxRate = RATE_LIMIT_MAP[rateLimitKey] ?? 0 + const res = await addDownloadTransfer({ + url: inspected.rawUrl, + outputDir: targetDir, + fileName: inspected.suggestedFileName || undefined, + maxConnections: Number(connections), + ...(maxRate > 0 ? { maxRateBytesPerSec: maxRate } : {}), + overwrite, + ...(expectedSha256.trim() ? { expectedSha256: expectedSha256.trim() } : {}) + }) + if (!mountedRef.current) return + await showToast({ style: res.ok ? Toast.Style.Success : Toast.Style.Failure, title: res.message }) + if (res.ok && res.data) { + outputDirByTaskRef.current.set(res.data.taskId, targetDir) + setTasks((prev) => [res.data!, ...prev.filter((item) => item.taskId !== res.data!.taskId)]) + await refreshTransferStatus(true) } + } finally { + if (mountedRef.current) setIsBusy(false) } - }; - - const maxCategoryBytes = Math.max(1, ...categoryStats.map((c) => c.sizeBytes)); - const maxFileBytes = Math.max(1, ...filteredFiles.map((f) => f.sizeBytes ?? 0)); - const driveLowSpace = isDriveLowOnSpace(snapshot); - - const aria2Text = snapshot.aria2Status.online - ? t("aria2Online", { name: currentPreset.name }) - : t("aria2Offline"); - const driveText = !snapshot.driveInfoAvailable - ? t("driveUnknown") - : t("driveFree", { - drive: snapshot.driveLetter, - free: formatBytes(snapshot.driveFreeBytes), - lowHint: driveLowSpace ? t("driveLowHint") : "" - }); - const summaryText = isImporting - ? t("summaryImporting", { dirs: importProgress?.visitedDirs ?? 0, files: importProgress?.matchedFiles ?? 0 }) - : !inClient - ? t("outsideClient") - : statusBanner - ? statusBanner - : files.length === 0 - ? t("summaryEmpty", { aria2: aria2Text, drive: driveText }) - : t("summaryFiles", { - aria2: aria2Text, - drive: driveText, - selected: selectedFiles.length, - total: filteredFiles.length, - size: formatBytes(selectedTotalBytes) - }); - - const createPickFilesAction = () => - Action({ title: t("actionPickFiles"), icon: Icon.Plus, shortcut: { modifiers: ["ctrl"], key: "o" }, onAction: handlePickFiles }); - - const createPickFolderAction = () => - Action({ title: t("actionPickFolder"), icon: Icon.Folder, shortcut: { modifiers: ["ctrl", "shift"], key: "o" }, onAction: handlePickFolder }); - - const createClearAction = () => - Action({ - title: t("actionClearList"), - icon: Icon.Trash, - style: Action.Style.Destructive, - shortcut: { modifiers: ["ctrl", "shift"], key: "backspace" }, - onAction: handleClearFiles - }); - - const trashAction = () => - Action({ - title: t("actionTrashSelected", { count: selectedFiles.length, size: formatBytes(selectedTotalBytes) }), - icon: Icon.Trash, - style: Action.Style.Destructive, - onAction: handleBatchTrashSelected - }); - - const openFolderAction = () => Action({ title: t("actionOpenDownloadDir"), icon: Icon.Folder, onAction: handleOpenFolder }); - - const navListSection = () => + } + + const handleTaskControl = async ( + action: 'pause' | 'resume' | 'cancel', + taskId: string + ) => { + if (!requireClient()) return + const res = + action === 'pause' + ? await pauseDownloadTransfer(taskId) + : action === 'resume' + ? await resumeDownloadTransfer(taskId) + : await cancelDownloadTransfer(taskId) + if (!mountedRef.current) return + await showToast({ style: res.ok ? Toast.Style.Success : Toast.Style.Failure, title: res.message }) + await refreshTransferStatus(true) + } + + const handleRemoveHistoryItem = async (taskId: string) => { + const next = historyRef.current.filter((item) => item.taskId !== taskId) + historyRef.current = next + setHistory(next) + await saveDownloadHistory(next) + await showToast({ style: Toast.Style.Success, title: t('msgHistoryRemoved') }) + } + + const handleClearHistory = async () => { + historyRef.current = [] + setHistory([]) + await saveDownloadHistory([]) + await showToast({ style: Toast.Style.Success, title: t('msgHistoryCleared') }) + } + + const inspected = inspectDownloadUrl(searchText) + const isUrlInput = inspected.kind === 'http' || inspected.kind === 'magnet' || inspected.kind === 'ftp' + const keyword = isUrlInput ? '' : searchText.trim().toLowerCase() + + const filteredTasks = tasks.filter((item) => { + if (!keyword) return true + return `${item.fileName} ${item.url} ${item.taskId}`.toLowerCase().includes(keyword) + }) + const activeTaskIds = new Set(tasks.map((item) => item.taskId)) + const filteredHistory = history.filter((item) => { + if (activeTaskIds.has(item.taskId)) return false + if (!keyword) return true + return `${item.fileName} ${item.url} ${item.outputDir}`.toLowerCase().includes(keyword) + }) + + const activeCount = tasks.filter((item) => isActiveTransferState(item.state)).length + + const engineLabel = !capChecked + ? t('engineChecking') + : capability.status === 'ready' + ? capability.resumablePersist + ? t('engineReadyResumable') + : t('engineReady') + : capability.status === 'needs_provisioning' + ? t('engineNeedsProvision') + : t('engineUnsupported') + + const summaryText = !inClient + ? t('summaryOutside') + : t('summaryNormal', { + engine: engineLabel, + active: activeCount, + history: history.length, + dir: outputDir || t('summaryDirUnset') + }) + + const primaryTopAction = + capability.status === 'needs_provisioning' + ? { + id: 'prepare-engine', + label: t('btnPrepareEngine'), + title: t('btnPrepareEngine'), + style: 'primary' as const, + onAction: () => { + void handlePrepareEngine() + } + } + : { + id: 'start-download', + label: t('btnStartDownload'), + title: t('btnStartDownload'), + style: 'primary' as const, + onAction: () => { + void startDownloadForUrl(searchText) + } + } + + const globalActions = () => ActionPanel.Section({ - title: t("sectionList"), - children: [createPickFilesAction(), createPickFolderAction(), ...(files.length > 0 ? [createClearAction()] : [])] - }); - - const linkItem = List.Item({ - id: "nav-dl-link", - title: activeDownloadUrl ? t("linkTitleWithProtocol", { protocol: activeProtocol }) : t("linkTitleEmpty"), - subtitle: activeDownloadUrl || t("linkSubtitleEmpty"), - icon: Icon.Link, - accessories: [ - ...(driveLowSpace ? [{ tag: { value: t("tagLowSpace"), color: Color.Red } }] : []), - { tag: { value: !activeDownloadUrl ? t("tagUnrecognized") : snapshot.aria2Status.online ? t("tagAria2Multi") : t("tagSingleConn") } } - ], - actions: ActionPanel({ + title: t('sectionActions'), children: [ Action({ - title: activeDownloadUrl ? t("actionDownloadLink") : t("actionRefreshClipboard"), - icon: activeDownloadUrl ? Icon.Download : Icon.ArrowClockwise, - onAction: handleStartDownload + title: t('actionChooseDir'), + icon: Icon.Folder, + shortcut: { modifiers: ['ctrl'], key: 'o' }, + onAction: () => { + void handleChooseOutputDir() + } + }), + Action({ + title: t('actionRefreshStatus'), + icon: Icon.ArrowClockwise, + shortcut: { modifiers: ['ctrl'], key: 'r' }, + onAction: () => { + void initializePlugin() + } }), - openFolderAction(), - ...(activeDownloadUrl + ...(outputDir ? [ Action({ - title: t("actionCopyAria2c", { name: currentPreset.name }), - icon: Icon.Clipboard, - onAction: handleCopyCommand + title: t('actionOpenDir'), + icon: Icon.ArrowRight, + onAction: async () => { + const res = await openDownloadItem(outputDir) + if (!res.ok) await showToast({ style: Toast.Style.Failure, title: res.message }) + } }) ] : []), - ...(selectedFiles.length > 0 ? [trashAction()] : []), - navListSection() + ...(history.length > 0 + ? [ + Action({ + title: t('actionClearHistory'), + icon: Icon.Trash, + style: Action.Style.Destructive, + onAction: () => { + void handleClearHistory() + } + }) + ] + : []) ] }) - }); - - const leftNavNodes = [ - linkItem, - List.Item({ - id: "nav-dl-all", - title: t("allFilesTitle"), - subtitle: snapshot.downloadDir ? `${snapshot.downloadDir} (${t("allFilesCount", { count: files.length })})` : t("allFilesCount", { count: files.length }), - icon: Icon.Folder, - onSelect: () => setSelectedCategory("all"), - accessories: [ - { tag: { value: t("itemCountTag", { count: files.length }) } }, - { text: formatBytes(totalSizeBytes) } - ], - actions: ActionPanel({ - children: [ - Action({ - title: t("actionViewAllFiles"), - icon: Icon.Filter, - onAction: () => setSelectedCategory("all") - }), - openFolderAction(), - ...(selectedFiles.length > 0 ? [trashAction()] : []), - navListSection() - ] - }) - }), - ...categories.map((cat) => { - const stat = categoryStats.find((s) => s.category === cat.id); - const catSize = stat?.sizeBytes || 0; - const catCount = stat?.count || 0; - const ratio = Math.min(1, catSize / maxCategoryBytes); - - return List.Item({ - id: `nav-dl-${cat.id}`, - title: cat.name, - subtitle: cat.exts.length > 0 ? t("catExtsSubtitle", { exts: cat.exts.slice(0, 5).join(" ") }) : t("catOtherSubtitle"), - icon: Icon.Document, - onSelect: () => setSelectedCategory(cat.id), - accessories: [ - { progress: ratio }, - { tag: { value: t("itemCountTag", { count: catCount }) } }, - { text: formatBytes(catSize) } - ], - actions: ActionPanel({ - children: [ - Action({ - title: t("actionFilterCat", { name: cat.name }), - icon: Icon.Filter, - onAction: () => setSelectedCategory(cat.id) - }), - openFolderAction(), - ...(selectedFiles.length > 0 ? [trashAction()] : []), - navListSection() - ] - }) - }); + + const activeListItems = filteredTasks.map((task) => { + const pct = + typeof task.totalBytes === 'number' && task.totalBytes > 0 + ? Math.min(1, Math.max(0, task.downloadedBytes / task.totalBytes)) + : task.state === 'completed' + ? 1 + : 0 + const subtitle = + task.state === 'failed' && task.errorMessage + ? t('taskSubError', { error: task.errorMessage }) + : typeof task.totalBytes === 'number' && task.totalBytes > 0 + ? t('taskSubRunning', { + state: getStateLabel(task.state), + downloaded: formatBytes(task.downloadedBytes), + total: formatBytes(task.totalBytes), + speed: formatBytes(task.speedBytesPerSec), + connections: task.connections + }) + : t('taskSubRunningUnknownTotal', { + state: getStateLabel(task.state), + downloaded: formatBytes(task.downloadedBytes), + speed: formatBytes(task.speedBytesPerSec), + connections: task.connections + }) + + const taskDir = outputDirByTaskRef.current.get(task.taskId) || outputDir + const taskOutputPath = taskDir ? `${taskDir.replace(/[\\/]+$/, '')}${taskDir.includes('\\') ? '\\' : '/'}${task.fileName}` : '' + const accessories: Array> = [] + if (task.state === 'running' || task.state === 'paused' || task.state === 'completed') { + accessories.push({ progress: pct }) + } + accessories.push({ + tag: { + value: getStateLabel(task.state), + ...(task.state === 'failed' ? { color: Color.Red } : {}) + } }) - ]; + if (typeof task.totalBytes === 'number' && task.totalBytes > 0) { + accessories.push({ text: formatBytes(task.totalBytes) }) + } - const allChecked = filteredFiles.length > 0 && filteredFiles.every((f) => checkedSet.has(f.id)); - const someChecked = filteredFiles.some((f) => checkedSet.has(f.id)); + const actions: Array | ReturnType> = [] + if (task.state === 'running' || task.state === 'queued') { + actions.push( + Action({ + title: t('actionPause'), + icon: Icon.Pause, + onAction: () => handleTaskControl('pause', task.taskId) + }), + Action({ + title: t('actionCancel'), + icon: Icon.Stop, + style: Action.Style.Destructive, + onAction: () => handleTaskControl('cancel', task.taskId) + }) + ) + } else if (task.state === 'paused') { + actions.push( + Action({ + title: t('actionResume'), + icon: Icon.Play, + onAction: () => handleTaskControl('resume', task.taskId) + }), + Action({ + title: t('actionCancel'), + icon: Icon.Stop, + style: Action.Style.Destructive, + onAction: () => handleTaskControl('cancel', task.taskId) + }) + ) + } else if (task.state === 'completed' && taskOutputPath) { + actions.push( + Action({ + title: t('actionOpenFile'), + icon: Icon.ArrowRight, + onAction: async () => { + const res = await openDownloadItem(taskOutputPath) + if (!res.ok) await showToast({ style: Toast.Style.Failure, title: res.message }) + } + }), + Action({ + title: t('actionRevealFile'), + icon: Icon.Folder, + onAction: async () => { + const res = await revealDownloadItem(taskOutputPath) + if (!res.ok) await showToast({ style: Toast.Style.Failure, title: res.message }) + } + }) + ) + } else { + actions.push( + Action({ + title: t('actionRedownload'), + icon: Icon.Download, + onAction: () => startDownloadForUrl(task.url) + }) + ) + } + actions.push( + Action({ + title: t('actionCopyUrl'), + icon: Icon.Clipboard, + onAction: async () => { + const res = await copyDownloadUrl(task.url) + await showToast({ style: res.ok ? Toast.Style.Success : Toast.Style.Failure, title: res.message }) + } + }), + globalActions() + ) - const subListItems = filteredFiles.map((file) => { - const isChecked = checkedSet.has(file.id); - const isTrashing = trashingIds.includes(file.id); - const dateStr = file.mtimeMs > 0 ? new Date(file.mtimeMs).toLocaleDateString(getLocale()) : ""; + return List.Item({ + id: `transfer-task-${task.taskId}`, + title: task.fileName, + subtitle, + icon: getStateIcon(task.state), + accessories, + actions: ActionPanel({ + title: task.fileName, + children: actions + }) + }) + }) + const historyListItems = filteredHistory.map((item) => { + const sizeText = typeof item.totalBytes === 'number' && item.totalBytes > 0 ? formatBytes(item.totalBytes) : t('sizeUnknown') return List.Item({ - id: `dl-file-${file.id}`, - title: file.name, - subtitle: dateStr ? `${file.path} · ${dateStr}` : file.path, - icon: Icon.Document, - checkable: true, - checked: isChecked, - onCheckChange: () => toggleFileCheck(file.id), - onToggleCheck: () => toggleFileCheck(file.id), + id: `transfer-history-${item.taskId}`, + title: item.fileName, + subtitle: t('historySub', { + state: getStateLabel(item.state), + size: sizeText, + dir: item.outputDir || item.outputPath + }), + icon: getStateIcon(item.state), accessories: [ - ...(file.sizeBytes !== null ? [{ progress: Math.min(1, file.sizeBytes / maxFileBytes) }] : []), - { tag: { value: file.categoryName } }, - { text: formatItemSize(file.sizeBytes) } + { + tag: { + value: getStateLabel(item.state), + ...(item.state === 'failed' ? { color: Color.Red } : {}) + } + }, + { text: sizeText } ], actions: ActionPanel({ + title: item.fileName, children: [ + ...(item.outputPath + ? [ + Action({ + title: t('actionOpenFile'), + icon: Icon.ArrowRight, + onAction: async () => { + const res = await openDownloadItem(item.outputPath) + if (!res.ok) await showToast({ style: Toast.Style.Failure, title: res.message }) + } + }), + Action({ + title: t('actionRevealFile'), + icon: Icon.Folder, + onAction: async () => { + const res = await revealDownloadItem(item.outputPath) + if (!res.ok) await showToast({ style: Toast.Style.Failure, title: res.message }) + } + }) + ] + : []), Action({ - title: t("actionOpenWithDefault"), - icon: Icon.ArrowRight, - onAction: () => handleOpenFile(file.path) + title: t('actionRedownload'), + icon: Icon.Download, + onAction: () => startDownloadForUrl(item.url) }), Action({ - title: t("actionRevealInExplorer"), - icon: Icon.Folder, - onAction: () => handleShowFile(file.path) + title: t('actionCopyUrl'), + icon: Icon.Clipboard, + onAction: async () => { + const res = await copyDownloadUrl(item.url) + await showToast({ style: res.ok ? Toast.Style.Success : Toast.Style.Failure, title: res.message }) + } }), Action({ - title: isChecked ? t("actionUncheck") : t("actionCheck"), - icon: Icon.CheckCircle, - onAction: () => toggleFileCheck(file.id) + title: t('actionRemoveHistory'), + icon: Icon.Minus, + onAction: () => handleRemoveHistoryItem(item.taskId) }), - ...(selectedFiles.length > 0 ? [trashAction()] : []), - ActionPanel.Section({ - title: t("sectionList"), - children: [ - ...(isTrashing - ? [] - : [ - Action({ - title: t("actionRemoveFromList"), - icon: Icon.Minus, - shortcut: { modifiers: ["ctrl"], key: "backspace" }, - onAction: () => handleRemoveFile(file) - }) - ]), - createPickFilesAction(), - createPickFolderAction(), - Action({ - title: allChecked ? t("actionUnselectAll") : t("actionSelectAll"), - icon: Icon.CheckCircle, - shortcut: { modifiers: ["ctrl"], key: "a" }, - onAction: toggleAllVisible - }), - createClearAction() - ] - }) + globalActions() ] }) - }); - }); - - const activeCategoryName = - selectedCategory === "all" - ? t("allFilesTitle") - : categories.find((c) => c.id === selectedCategory)?.name || t("fileListFallbackTitle"); - - const emptyText = !inClient - ? t("outsideClient") - : keyword && files.length > 0 - ? t("emptyNoMatch") - : selectedCategory !== "all" && files.length > 0 - ? t("emptyCategory") - : t("emptyDefault"); + }) + }) + + const combinedQueueItems = [...activeListItems, ...historyListItems] + const previewTitle = + inspected.kind === 'http' + ? inspected.suggestedFileName || t('previewTitleActive') + : inspected.kind === 'magnet' || inspected.kind === 'ftp' + ? inspected.protocolLabel + : t('previewTitleIdle') + const previewSubtitle = + inspected.kind === 'http' + ? inspected.rawUrl + : inspected.kind === 'magnet' || inspected.kind === 'ftp' + ? t('previewSubUnsupported', { reason: inspected.unsupportedReason || '' }) + : t('previewSubIdle') + const previewBadge = + inspected.kind === 'http' + ? t('previewBadgeReady') + : inspected.kind === 'magnet' || inspected.kind === 'ftp' + ? t('previewBadgeUnsupported') + : t('previewBadgeIdle') return List({ - ...fileInputProps, - isLoading: isLoading || isImporting, - searchBarPlaceholder: t("searchPlaceholder"), - onSearchTextChange: (text: string) => setSearchText(text), + isLoading: isBusy, isShowingDetail: false, + searchBarPlaceholder: t('searchPlaceholder'), + searchText, + onSearchTextChange: setSearchText, actions: ActionPanel({ children: [ - createPickFilesAction(), - createPickFolderAction(), - openFolderAction(), - Action({ - title: t("actionRefreshClipboard"), - icon: Icon.ArrowClockwise, - onAction: () => { - setStatusBanner(""); - void refreshHostMeta(); - } - }) + capability.status === 'needs_provisioning' + ? Action({ + title: t('actionPrepareEngine'), + icon: Icon.Download, + onAction: handlePrepareEngine + }) + : Action({ + title: t('actionStartDownload'), + icon: Icon.Download, + onAction: () => startDownloadForUrl(searchText) + }), + globalActions() ] }), searchBarAccessory: List.Dropdown({ - tooltip: t("presetTooltip"), - value: selectedPresetId, - onChange: (val) => setSelectedPresetId(val as ThreadSplitPresetId), - children: presets.map((preset) => - List.Dropdown.Item({ - title: t("presetItemTitle", { name: preset.name, splitSize: preset.splitSize }), - value: preset.id - }) - ) + tooltip: t('dropdownTooltip'), + value: connections, + onChange: (val) => setConnections(val as ConnectionPresetValue), + children: [ + List.Dropdown.Item({ title: t('conn16'), value: '16' }), + List.Dropdown.Item({ title: t('conn8'), value: '8' }), + List.Dropdown.Item({ title: t('conn4'), value: '4' }), + List.Dropdown.Item({ title: t('conn1'), value: '1' }) + ] }), filterBar: { summaryText, actions: [ + primaryTopAction, + { + id: 'choose-dir', + label: t('btnChooseDir'), + title: t('btnChooseDir'), + style: 'secondary', + onAction: () => { + void handleChooseOutputDir() + } + } + ] + }, + workbenchPanel: { + title: t('wbTitle'), + subtitle: t('wbSubtitle'), + fields: [ + { + id: 'wb-connections', + label: t('wbFieldConnections'), + type: 'select', + value: connections, + onChange: (val) => setConnections(String(val) as ConnectionPresetValue), + options: [ + { label: t('conn16'), value: '16' }, + { label: t('conn8'), value: '8' }, + { label: t('conn4'), value: '4' }, + { label: t('conn1'), value: '1' } + ] + }, + { + id: 'wb-rate-limit', + label: t('wbFieldRateLimit'), + type: 'select', + value: rateLimitKey, + onChange: (val) => setRateLimitKey(String(val)), + options: [ + { label: t('rateUnlimited'), value: 'unlimited' }, + { label: t('rate2m'), value: '2m' }, + { label: t('rate5m'), value: '5m' }, + { label: t('rate10m'), value: '10m' }, + { label: t('rate20m'), value: '20m' } + ] + }, + { + id: 'wb-overwrite', + label: t('wbFieldOverwrite'), + type: 'toggle', + value: overwrite, + onChange: (val) => setOverwrite(Boolean(val)) + }, { - id: "pick-files", - label: t("btnPickFiles"), - title: t("btnPickFiles"), - style: "secondary", - onAction: handlePickFiles + id: 'wb-sha256', + label: t('wbFieldSha256'), + type: 'text', + value: expectedSha256, + onChange: (val) => setExpectedSha256(String(val)) }, { - id: "pick-folder", - label: t("btnPickFolder"), - title: t("btnPickFolder"), - style: "secondary", - onAction: handlePickFolder + id: 'wb-output-dir', + label: t('wbFieldOutputDir'), + type: 'info', + value: outputDir || t('wbOutputDirUnset') + }, + { + id: 'wb-engine', + label: t('wbFieldEngine'), + type: 'info', + value: engineLabel } - ] + ], + previewCard: { + title: previewTitle, + badge: previewBadge, + subtitle: previewSubtitle, + metrics: [ + { label: t('metricProtocol'), value: inspected.protocolLabel }, + { label: t('metricFileName'), value: inspected.suggestedFileName || t('fileNameAuto') }, + { label: t('metricConnections'), value: connections }, + { + label: t('metricResume'), + value: capability.resumablePersist ? t('resumeSupported') : t('resumeNotReported') + } + ] + } }, subList: { - title: t("subListTitle", { - category: activeCategoryName, - count: filteredFiles.length, - size: formatBytes(selectedTotalBytes) - }), - subtitle: snapshot.downloadDir, - emptyText, - checkable: filteredFiles.length > 0, - checked: allChecked ? true : someChecked ? "indeterminate" : false, - onCheckChange: () => toggleAllVisible(), - items: subListItems + title: t('subListTitle', { active: filteredTasks.length, history: filteredHistory.length }), + subtitle: outputDir || t('summaryDirUnset'), + emptyText: !inClient + ? t('outsideClient') + : keyword + ? t('subListNoMatch') + : t('subListEmpty'), + items: combinedQueueItems }, children: [ List.Section({ - title: t("leftSectionTitle"), - subtitle: t("allFilesCount", { count: files.length }), - children: leftNavNodes + title: t('sectionActiveTasks', { count: filteredTasks.length }), + children: activeListItems + }), + List.Section({ + title: t('sectionHistory', { count: filteredHistory.length }), + children: historyListItems }) ] - }); + }) } -export default MultiDownloadCommand; +export default MultiDownloadCommand diff --git a/extensions/multi-download/src/logic.ts b/extensions/multi-download/src/logic.ts index fb584dd9..9c63a631 100644 --- a/extensions/multi-download/src/logic.ts +++ b/extensions/multi-download/src/logic.ts @@ -1,726 +1,641 @@ /** - * 多线程分块下载业务逻辑 + * 多线程分块下载业务逻辑(基于宿主 download.transfer 薄原语) * - * - 16 / 8 / 4 / 1 线程档位,对应 aria2 参数(如 `--split=16 --min-split-size=1M`) - * - 发起下载:先交给本机 aria2 JSON-RPC 服务 (`http://127.0.0.1:6800/jsonrpc`) 多线程下载; - * 连不上 aria2 时,HTTP / HTTPS 链接在用户选好保存位置后由客户端单连接下载,FTP 与磁力链接直接报错 - * - 可把对应的 aria2c 命令复制到剪贴板,由用户自行运行 - * - 从剪贴板识别 HTTP/HTTPS/FTP/Magnet 下载链接,读取下载盘的剩余空间 - * - 支持通过「选择文件」「选择文件夹」或拖入导入文件并按类型归类,客户端单连接下载完成后也会追加进列表 - * - 打开文件、在资源管理器中定位、从列表移除,以及在用户确认后把已勾选的文件移入回收站 + * - 支持 Windows 与 macOS 双端,纯宿主薄原语直连,无第三方本地常驻守护进程依赖 + * - 严格只接受 HTTP / HTTPS 链接;对 magnet: 与 ftp: 链接如实拒绝并给出清晰说明 + * - 活跃任务队列与断点续传状态以 tool_download_transfer_status 为唯一真相源 + * - 下载历史记录与上次输出目录持久化至 LocalStorage */ -import { getHostTransport, getLocale } from "@ztools/declarative-ui"; -import { t } from "./i18n.js"; +import { LocalStorage } from '@ztools/declarative-ui' +import { t } from './i18n.js' +import { resolveErrorMessage } from './error-i18n.js' import { callHostTransport, - getRealFileSize, + ensureRuntimeCapability, + findCapability, + formatBytes, getRealSystemPath, - invokeHostCapability, + hasCapabilityExtension, + isRealElectronHost, openRealPath, + pickOutputDirectoryDialog, + queryRuntimeCapabilities, + readRealClipboardText, showRealItemInFolder, - trashRealItem, writeRealClipboardText, - formatBytes, - type NativeInvocationResult -} from "./native-ipc.js"; -import type { FileImportRules, FileImportTransport, ImportedFile } from "./file-import.js"; -import { resolveErrorMessage } from './error-i18n.js' - -export { formatBytes }; -export type { NativeInvocationResult }; - -export const FORBIDDEN_TARGET_PATTERN = - /(^|[\\/])(Windows|System32|SysWOW64|Program Files|Program Files \(x86\)|Boot|Recovery)($|[\\/])/i; -export function getForbiddenReason(): string { - return t("forbiddenReason"); -} - -export const ARIA2_ENDPOINT = "http://127.0.0.1:6800/jsonrpc"; -/** 客户端单次请求的最长等待时间(5 分钟);客户端 HTTP 下载单个文件最大 1 GiB */ -export const DIRECT_DOWNLOAD_TIMEOUT_MS = 300_000; - -export type DownloadFileCategory = - | "all" - | "installer" - | "archive" - | "media" - | "iso_image" - | "document" - | "other"; - -export interface DownloadCategoryMeta { - id: DownloadFileCategory; - name: string; - icon: string; - color: string; - exts: string[]; -} + type ToolCapabilityStatus +} from './tool-runtime.js' -export function getDownloadCategories(): DownloadCategoryMeta[] { - return [ - { - id: "installer", - name: t("catInstaller"), - icon: "Icon.Box", - color: "#3b82f6", - exts: [".exe", ".msi", ".msix", ".appx", ".dmg", ".deb", ".rpm"] - }, - { - id: "archive", - name: t("catArchive"), - icon: "Icon.Archive", - color: "#f59e0b", - exts: [".zip", ".7z", ".rar", ".tar", ".gz", ".bz2", ".xz", ".tgz"] - }, - { - id: "media", - name: t("catMedia"), - icon: "Icon.Video", - color: "#ec4899", - exts: [".mp4", ".mkv", ".mov", ".webm", ".avi", ".mp3", ".flac", ".wav", ".png", ".jpg", ".webp"] - }, - { - id: "iso_image", - name: t("catIsoImage"), - icon: "Icon.Disc", - color: "#8b5cf6", - exts: [".iso", ".img", ".vhd", ".vhdx", ".gguf", ".safetensors", ".onnx", ".bin"] - }, - { - id: "document", - name: t("catDocument"), - icon: "Icon.Document", - color: "#10b981", - exts: [".pdf", ".docx", ".doc", ".xlsx", ".xls", ".pptx", ".ppt", ".txt", ".md", ".csv", ".json", ".sql"] - }, - { - id: "other", - name: t("catOther"), - icon: "Icon.Folder", - color: "#64748b", - exts: [] - } - ]; -} - -export type ThreadSplitPresetId = "threads_16" | "threads_8" | "threads_4" | "threads_1"; - -export interface ThreadSplitPreset { - id: ThreadSplitPresetId; - name: string; - threads: number; - splitSize: string; - aria2Flags: string; - description: string; -} +export { formatBytes, isRealElectronHost } -/** 线程档位只在交给 aria2 时生效;客户端单连接下载不分块 */ -export function getThreadSplitPresets(): ThreadSplitPreset[] { - return [ - { - id: "threads_16", - name: t("preset16Name"), - threads: 16, - splitSize: "1M", - aria2Flags: "--max-connection-per-server=16 --split=16 --min-split-size=1M --continue=true", - description: t("preset16Desc") - }, - { - id: "threads_8", - name: t("preset8Name"), - threads: 8, - splitSize: "2M", - aria2Flags: "--max-connection-per-server=8 --split=8 --min-split-size=2M --continue=true", - description: t("preset8Desc") - }, - { - id: "threads_4", - name: t("preset4Name"), - threads: 4, - splitSize: "4M", - aria2Flags: "--max-connection-per-server=4 --split=4 --min-split-size=4M --continue=true", - description: t("preset4Desc") - }, - { - id: "threads_1", - name: t("preset1Name"), - threads: 1, - splitSize: "10M", - aria2Flags: "--max-connection-per-server=1 --split=1 --continue=true", - description: t("preset1Desc") - } - ]; -} +export const DOWNLOAD_TRANSFER_PRIMITIVE_ID = 'download.transfer' as const +export const HISTORY_STORAGE_KEY = 'multi_download_history_v1' +export const OUTPUT_DIR_STORAGE_KEY = 'multi_download_output_dir_v1' +export const MAX_HISTORY_ITEMS = 100 +export const STATUS_POLL_INTERVAL_MS = 1000 -export interface DownloadedFileItem { - id: string; - name: string; - path: string; - ext: string; - sizeBytes: number | null; - mtimeMs: number; - category: DownloadFileCategory; - categoryName: string; - categoryColor: string; - categoryIcon: string; -} - -export interface Aria2Status { - /** 连上了 aria2 并拿到了版本号 */ - online: boolean; - /** 连上了但被拒绝(例如设置了 RPC 密钥),或连接失败的原因 */ - error?: string; - version?: string; +export const FORBIDDEN_TARGET_PATTERN = + /(^|[\\/])(Windows|System32|SysWOW64|Program Files|Program Files \(x86\)|Boot|Recovery)($|[\\/])|(^|[\\/])\.\.($|[\\/])/i + +export type DownloadTransferState = + | 'queued' + | 'running' + | 'paused' + | 'completed' + | 'cancelled' + | 'failed' + +export interface DownloadTransferRecord { + taskId: string + url: string + fileName: string + state: DownloadTransferState + downloadedBytes: number + totalBytes?: number + speedBytesPerSec: number + connections: number + errorCode?: string + errorMessage?: string + createdAt: number + updatedAt: number +} + +export interface TransferCapabilityState { + status: ToolCapabilityStatus + resumablePersist: boolean + platform: 'windows' | 'macos' | 'other' + error?: string +} + +export interface DownloadHistoryEntry { + taskId: string + url: string + fileName: string + outputDir: string + outputPath: string + totalBytes?: number + state: DownloadTransferState + updatedAt: number +} + +export interface ActionOutcome { + ok: boolean + message: string + data?: T + error?: string + errorCode?: string +} + +export type ConnectionPresetValue = '16' | '8' | '4' | '1' + +export interface UrlInspectionResult { + rawUrl: string + kind: 'empty' | 'http' | 'magnet' | 'ftp' | 'invalid' + protocolLabel: string + suggestedFileName: string + unsupportedReason?: string +} + +export interface AddTransferInput { + taskId?: string + url: string + outputDir: string + fileName?: string + maxConnections?: number + maxRateBytesPerSec?: number + overwrite?: boolean + expectedSha256?: string +} + +function asRecord(value: unknown): Record | null { + return value && typeof value === 'object' && !Array.isArray(value) + ? (value as Record) + : null } -export interface MultiDownloadSnapshot { - downloadDir: string; - driveLetter: string; - /** 是否读到了下载盘的容量;读不到时 driveFreeBytes / driveTotalBytes 为 0,不能当作真实数值显示 */ - driveInfoAvailable: boolean; - driveFreeBytes: number; - driveTotalBytes: number; - aria2RpcOnline: boolean; - aria2Status: Aria2Status; - aria2Endpoint: string; - sniffedClipboardUrl: string; - sniffedProtocol: string; - files: DownloadedFileItem[]; - totalSizeBytes: number; - categoryStats: Array<{ - category: DownloadFileCategory; - name: string; - color: string; - sizeBytes: number; - count: number; - }>; - updatedAt: string; +function safeDecode(segment: string): string { + try { + return decodeURIComponent(segment) + } catch { + return segment + } } -/** 测试可注入的 fetch;默认使用运行环境的 fetch */ -export type FetchLike = ( - input: string, - init: { method: string; headers: Record; body: string; signal: AbortSignal } -) => Promise<{ ok: boolean; status: number; json(): Promise }>; - -export interface Aria2Options { - fetchImpl?: FetchLike; +function joinOutputPath(outputDir: string, fileName: string): string { + const dir = outputDir.trim().replace(/[\\/]+$/, '') + if (!dir) return fileName + const sep = /^[A-Za-z]:/.test(dir) || dir.includes('\\') ? '\\' : '/' + return `${dir}${sep}${fileName}` } -export function classifyDownloadedExtension(extRaw: string): DownloadCategoryMeta { - const ext = String(extRaw || "").toLowerCase(); - const categories = getDownloadCategories(); - for (const cat of categories) { - if (cat.id !== "other" && cat.exts.includes(ext)) { - return cat; +/** 识别输入文本中的下载链接与协议类型,并明确区分受支持协议与暂不支持的 magnet:/ftp: 协议 */ +export function inspectDownloadUrl(rawText: string): UrlInspectionResult { + const text = String(rawText || '').trim() + if (!text) { + return { + rawUrl: '', + kind: 'empty', + protocolLabel: t('protocolNone'), + suggestedFileName: '' } } - return categories[categories.length - 1]; -} -function safeDecode(segment: string): string { - try { - return decodeURIComponent(segment); - } catch { - return segment; + const magnetMatch = text.match(/magnet:\?[^\s"'<>]+/i) + if (magnetMatch) { + return { + rawUrl: magnetMatch[0], + kind: 'magnet', + protocolLabel: t('protocolMagnet'), + suggestedFileName: '', + unsupportedReason: t('errUnsupportedProtocolMagnet') + } } -} - -export function detectDownloadUrlFromText(rawText: string): { - url: string; - protocol: string; - suggestedFileName: string; -} { - const text = String(rawText || "").trim(); - if (!text) return { url: "", protocol: t("protocolNone"), suggestedFileName: "" }; - const magnetMatch = text.match(/magnet:\?xt=urn:[a-z0-9]+:[a-zA-Z0-9]{32,}/i); - if (magnetMatch) { + const ftpMatch = text.match(/ftp:\/\/[^\s"'<>]+/i) + if (ftpMatch) { return { - url: magnetMatch[0], - protocol: t("protocolMagnet"), - suggestedFileName: "" - }; + rawUrl: ftpMatch[0], + kind: 'ftp', + protocolLabel: t('protocolFtp'), + suggestedFileName: '', + unsupportedReason: t('errUnsupportedProtocolFtp') + } } - const httpMatch = text.match(/(https?|ftp):\/\/[^\s"'<>]+/i); + const httpMatch = text.match(/https?:\/\/[^\s"'<>]+/i) if (httpMatch) { - const url = httpMatch[0]; - const cleanPath = url.split("?")[0].split("#")[0]; - const lastSeg = cleanPath.substring(cleanPath.lastIndexOf("/") + 1); - const protocol = url.toLowerCase().startsWith("ftp") ? t("protocolFtp") : t("protocolHttp"); - const fileName = safeDecode(lastSeg) - .replace(/[<>:"/\\|?*\u0000-\u001f]+/g, "_") - .trim() - .slice(0, 120); - return { url, protocol, suggestedFileName: fileName }; - } - - return { url: "", protocol: t("protocolClipboardEmpty"), suggestedFileName: "" }; -} - -function failure(error: string, message: string): NativeInvocationResult { - return { ok: false, code: -1, error, message }; -} - -type Aria2CallResult = - | { reachable: false; error: string } - | { reachable: true; result?: unknown; error?: string }; - -/** 调用本机 aria2 JSON-RPC。连不上(未运行、跨域被拒、超时)时 reachable 为 false */ -async function callAria2( - method: string, - params: unknown[], - timeoutMs: number, - fetchImpl?: FetchLike -): Promise { - const doFetch: FetchLike | null = - fetchImpl ?? (typeof fetch === "function" ? (fetch as unknown as FetchLike) : null); - if (!doFetch) return { reachable: false, error: t("errNoFetch") }; - const controller = new AbortController(); - const timer = setTimeout(() => controller.abort(), timeoutMs); - try { - const resp = await doFetch(ARIA2_ENDPOINT, { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ jsonrpc: "2.0", id: `ztools-${Date.now()}`, method, params }), - signal: controller.signal - }); - let body: unknown = null; + const url = httpMatch[0] + let validHttp = false + let pathname = '' try { - body = await resp.json(); + const parsed = new URL(url) + validHttp = parsed.protocol === 'http:' || parsed.protocol === 'https:' + pathname = parsed.pathname } catch { - body = null; + validHttp = false } - const rpc = body && typeof body === "object" ? (body as { result?: unknown; error?: { message?: unknown } }) : null; - if (rpc?.error) { - return { reachable: true, error: String(resolveErrorMessage(rpc.error, t("errAria2RpcError"))) }; + if (validHttp) { + const lastSeg = pathname.substring(pathname.lastIndexOf('/') + 1) + const fileName = safeDecode(lastSeg) + .replace(/[<>:"/\\|?*\u0000-\u001f]+/g, '_') + .trim() + .slice(0, 120) + return { + rawUrl: url, + kind: 'http', + protocolLabel: t('protocolHttp'), + suggestedFileName: fileName + } } - if (!resp.ok) return { reachable: true, error: t("errAria2Http", { status: resp.status }) }; - if (!rpc || rpc.result === undefined) return { reachable: true, error: t("errAria2Unrecognized") }; - return { reachable: true, result: rpc.result }; - } catch (err) { - return { reachable: false, error: err instanceof Error ? err.message : String(err) }; - } finally { - clearTimeout(timer); } -} -export async function probeAria2JsonRpc(options: Aria2Options = {}): Promise { - const res = await callAria2("aria2.getVersion", [], 1000, options.fetchImpl); - if (!res.reachable) return { online: false, error: res.error }; - if (res.error) return { online: false, error: res.error }; - const version = (res.result as { version?: unknown } | undefined)?.version; - return typeof version === "string" ? { online: true, version } : { online: false, error: t("errAria2Unrecognized") }; + return { + rawUrl: text, + kind: 'invalid', + protocolLabel: t('protocolInvalid'), + suggestedFileName: '' + } } -export async function readClipboardDownloadUrl(hostBridge?: unknown): Promise<{ - url: string; - protocol: string; - suggestedFileName: string; -}> { - const ipcClip = await callHostTransport("clipboard_read_text", {}, hostBridge); - if (ipcClip.ok && ipcClip.data) { - const data = ipcClip.data; - const txt = - typeof data === "string" - ? data - : typeof (data as { text?: unknown }).text === "string" - ? String((data as { text: string }).text) - : ""; - return detectDownloadUrlFromText(txt); - } - return { url: "", protocol: t("protocolClipboardEmpty"), suggestedFileName: "" }; +function normalizeTransferState(raw: unknown): DownloadTransferState { + switch (raw) { + case 'queued': + case 'running': + case 'paused': + case 'completed': + case 'cancelled': + case 'failed': + return raw + default: + return 'failed' + } } -export const MULTI_DOWNLOAD_IMPORT_RULES: FileImportRules = { - forbiddenPath: FORBIDDEN_TARGET_PATTERN -}; - -export function createMultiDownloadImportTransport(hostBridge?: unknown): FileImportTransport { - return (method, params) => callHostTransport(method, params, hostBridge); -} +export function normalizeTransferRecord(raw: unknown): DownloadTransferRecord | null { + const rec = asRecord(raw) + if (!rec || typeof rec.taskId !== 'string' || !rec.taskId.trim()) return null + const downloadedBytes = Number(rec.downloadedBytes) + const totalBytes = rec.totalBytes !== undefined && rec.totalBytes !== null ? Number(rec.totalBytes) : undefined + const speedBytesPerSec = Number(rec.speedBytesPerSec) + const connections = Number(rec.connections) + const createdAt = Number(rec.createdAt) + const updatedAt = Number(rec.updatedAt) -export function toDownloadedFileItem(file: ImportedFile): DownloadedFileItem { - const catMeta = classifyDownloadedExtension(file.extension); return { - id: file.path, - name: file.name, - path: file.path, - ext: file.extension, - sizeBytes: file.sizeBytes, - mtimeMs: file.lastModifiedMs ?? 0, - category: catMeta.id, - categoryName: catMeta.name, - categoryColor: catMeta.color, - categoryIcon: catMeta.icon - }; + taskId: rec.taskId.trim(), + url: typeof rec.url === 'string' ? rec.url : '', + fileName: typeof rec.fileName === 'string' && rec.fileName.trim() ? rec.fileName.trim() : rec.taskId.trim(), + state: normalizeTransferState(rec.state), + downloadedBytes: Number.isFinite(downloadedBytes) && downloadedBytes >= 0 ? downloadedBytes : 0, + ...(totalBytes !== undefined && Number.isFinite(totalBytes) && totalBytes >= 0 ? { totalBytes } : {}), + speedBytesPerSec: Number.isFinite(speedBytesPerSec) && speedBytesPerSec >= 0 ? speedBytesPerSec : 0, + connections: Number.isFinite(connections) && connections >= 1 ? Math.round(connections) : 1, + ...(typeof rec.errorCode === 'string' && rec.errorCode.trim() ? { errorCode: rec.errorCode.trim() } : {}), + ...(typeof rec.errorMessage === 'string' && rec.errorMessage.trim() + ? { errorMessage: rec.errorMessage.trim() } + : {}), + createdAt: Number.isFinite(createdAt) && createdAt > 0 ? createdAt : Date.now(), + updatedAt: Number.isFinite(updatedAt) && updatedAt > 0 ? updatedAt : Date.now() + } } -export function createClientDownloadedItem(filePath: string, sizeBytes?: number): DownloadedFileItem { - const name = filePath.split(/[\\/]/).pop() || filePath; - const dot = name.lastIndexOf("."); - const ext = dot > 0 ? name.slice(dot).toLowerCase() : ""; - const catMeta = classifyDownloadedExtension(ext); - const validSize = typeof sizeBytes === "number" && Number.isFinite(sizeBytes) && sizeBytes >= 0 ? sizeBytes : null; - return { - id: filePath, - name, - path: filePath, - ext, - sizeBytes: validSize, - mtimeMs: Date.now(), - category: catMeta.id, - categoryName: catMeta.name, - categoryColor: catMeta.color, - categoryIcon: catMeta.icon - }; +export function isActiveTransferState(state: DownloadTransferState): boolean { + return state === 'queued' || state === 'running' } -export function computeDownloadStats(files: readonly DownloadedFileItem[]): { - totalSizeBytes: number; - categoryStats: MultiDownloadSnapshot["categoryStats"]; -} { - let totalSizeBytes = 0; - const categories = getDownloadCategories(); - const catMap = new Map(); - for (const cat of categories) { - catMap.set(cat.id, { sizeBytes: 0, count: 0 }); - } - for (const file of files) { - const sz = typeof file.sizeBytes === "number" && Number.isFinite(file.sizeBytes) && file.sizeBytes > 0 ? file.sizeBytes : 0; - totalSizeBytes += sz; - const stat = catMap.get(file.category); - if (stat) { - stat.sizeBytes += sz; - stat.count += 1; +/** 探测宿主 download.transfer 能力与 optionalExtensions */ +export async function probeDownloadTransferCapability( + hostBridge?: unknown +): Promise { + if (!isRealElectronHost(hostBridge)) { + return { + status: 'unsupported', + resumablePersist: false, + platform: 'other', + error: t('errHostRequired') } } - const categoryStats = categories.map((c) => { - const st = catMap.get(c.id) || { sizeBytes: 0, count: 0 }; + const res = await queryRuntimeCapabilities(hostBridge) + if (!res.ok || !res.data) { return { - category: c.id, - name: c.name, - color: c.color, - sizeBytes: st.sizeBytes, - count: st.count - }; - }).filter((s) => s.count > 0); - return { totalSizeBytes, categoryStats }; + status: 'unsupported', + resumablePersist: false, + platform: 'other', + error: t('errCapabilityCheckFailed', { error: resolveErrorMessage(res, t('errHostRequired')) }) + } + } + const cap = findCapability(res.data, DOWNLOAD_TRANSFER_PRIMITIVE_ID) + if (!cap) { + return { + status: 'unsupported', + resumablePersist: false, + platform: res.data.platform, + error: t('errCapabilityUnsupported') + } + } + return { + status: cap.status, + resumablePersist: hasCapabilityExtension(res.data, DOWNLOAD_TRANSFER_PRIMITIVE_ID, 'resumable-persist'), + platform: res.data.platform + } } -/** - * 读取下载目录路径、磁盘剩余空间、aria2 状态与剪贴板下载链接(不扫描目录文件) - */ -export async function fetchMultiDownloadSnapshot( - hostBridge?: unknown, - options: Aria2Options = {} -): Promise { - const downloadDir = await getRealSystemPath("downloads", hostBridge); - const winDrive = downloadDir.match(/^[A-Za-z]:/)?.[0]?.toUpperCase() || ""; - const driveLetter = winDrive || (downloadDir.startsWith("/") ? "/" : ""); - const driveParam = winDrive ? `${winDrive}\\` : driveLetter; - - const [diskRes, sysRes, aria2Status, clipInfo] = await Promise.all([ - driveParam - ? callHostTransport<{ total?: number; used?: number; available?: number; free?: number }>( - "system_get_disk_usage", - { drive: driveParam }, - hostBridge - ) - : Promise.resolve({ ok: false, data: undefined }), - driveParam - ? invokeHostCapability>("system.info", { includeStorage: true }, hostBridge) - : Promise.resolve({ ok: false, code: -1, message: "", data: undefined }), - probeAria2JsonRpc(options), - readClipboardDownloadUrl(hostBridge) - ]); - - let driveFreeBytes = 0; - let driveTotalBytes = 0; - if (diskRes.ok && diskRes.data) { - driveTotalBytes = Number(diskRes.data.total || 0); - const used = Number(diskRes.data.used || 0); - driveFreeBytes = Number( - diskRes.data.available ?? diskRes.data.free ?? Math.max(0, driveTotalBytes - used) - ); - } else if (sysRes.ok && sysRes.data && driveLetter) { - const storageArr = Array.isArray((sysRes.data as { storage?: unknown }).storage) - ? ((sysRes.data as { storage: Array> }).storage) - : []; - const matchedDrive = storageArr.find((d) => - String(d.mount || d.fs || "").toUpperCase().startsWith(driveLetter) - ); - if (matchedDrive) { - driveTotalBytes = Number(matchedDrive.size || matchedDrive.total || 0); - const used = Number(matchedDrive.used || 0); - driveFreeBytes = Number(matchedDrive.available || matchedDrive.free || Math.max(0, driveTotalBytes - used)); +/** 按需准备 download.transfer 引擎 */ +export async function ensureDownloadTransferEngine( + hostBridge?: unknown +): Promise> { + if (!isRealElectronHost(hostBridge)) { + return { ok: false, errorCode: 'HOST_REQUIRED', error: t('errHostRequired'), message: t('errHostRequired') } + } + const res = await ensureRuntimeCapability(DOWNLOAD_TRANSFER_PRIMITIVE_ID, hostBridge) + if (!res.ok || !res.data) { + const errText = resolveErrorMessage(res, t('errHostRequired')) + return { + ok: false, + errorCode: res.errorCode || 'PROVISION_FAILED', + error: errText, + message: t('errProvisionFailed', { error: errText }) } } - if (!Number.isFinite(driveFreeBytes) || driveFreeBytes < 0) driveFreeBytes = 0; - if (!Number.isFinite(driveTotalBytes) || driveTotalBytes < 0) driveTotalBytes = 0; - return { - downloadDir, - driveLetter, - driveInfoAvailable: driveTotalBytes > 0, - driveFreeBytes, - driveTotalBytes, - aria2RpcOnline: aria2Status.online, - aria2Status, - aria2Endpoint: ARIA2_ENDPOINT, - sniffedClipboardUrl: clipInfo.url, - sniffedProtocol: clipInfo.protocol, - files: [], - totalSizeBytes: 0, - categoryStats: [], - updatedAt: new Date().toLocaleTimeString(getLocale()) - }; + ok: res.data.status === 'ready', + data: { status: res.data.status, provisioned: res.data.provisioned }, + message: + res.data.status === 'ready' + ? t('msgProvisionSuccess') + : t('errProvisionFailed', { error: res.data.status }) + } } -/** 下载盘剩余空间不足 10% 时返回 true;读不到容量时返回 false */ -export function isDriveLowOnSpace(snapshot: Pick): boolean { - return ( - snapshot.driveInfoAvailable && - snapshot.driveTotalBytes > 0 && - snapshot.driveFreeBytes / snapshot.driveTotalBytes < 0.1 - ); +/** 读取默认系统下载目录与剪贴板链接 */ +export async function fetchInitialDownloadContext(hostBridge?: unknown): Promise<{ + defaultDownloadDir: string + clipboardUrl: string +}> { + if (!isRealElectronHost(hostBridge)) { + return { defaultDownloadDir: '', clipboardUrl: '' } + } + const [defaultDownloadDir, clipText] = await Promise.all([ + getRealSystemPath('downloads', hostBridge), + readRealClipboardText(hostBridge) + ]) + const inspected = inspectDownloadUrl(clipText) + return { + defaultDownloadDir, + clipboardUrl: inspected.kind === 'http' || inspected.kind === 'magnet' || inspected.kind === 'ftp' ? inspected.rawUrl : '' + } } -/** - * 需要较长时间的宿主调用:客户端里通过带插件身份的通道把超时放宽到 timeoutMs; - * 测试注入宿主替身或旧客户端没有该通道时,退回普通调用(默认超时)。 - */ -async function callHostLongRunning( - method: string, - params: Record, - timeoutMs: number, +/** 通过 window_show_open_dialog 选择下载输出目录 */ +export async function selectDownloadOutputDir( + defaultPath?: string, hostBridge?: unknown -): Promise<{ ok: boolean; data?: T; error?: string }> { - if (!hostBridge) { - // 旧客户端可能没有这个接口,此时退回普通调用 - const transport = typeof getHostTransport === "function" ? getHostTransport() : null; - if (transport) { - try { - const data = await transport.call(method, params, { timeoutMs }); - return { ok: true, data }; - } catch (err) { - return { ok: false, error: err instanceof Error ? err.message : String(err) }; - } +): Promise> { + if (!isRealElectronHost(hostBridge)) { + return { ok: false, errorCode: 'HOST_REQUIRED', error: t('errHostRequired'), message: t('errHostRequired') } + } + const picked = await pickOutputDirectoryDialog( + { title: t('pickDirTitle'), ...(defaultPath ? { defaultPath } : {}) }, + hostBridge + ) + if (picked.canceled) { + return { ok: false, errorCode: 'CANCELED', error: 'CANCELED', message: t('errPickDirCanceled') } + } + if (picked.error || !picked.directoryPath) { + const reason = resolveErrorMessage(picked, t('errMissingOutputDir')) + return { + ok: false, + errorCode: picked.errorCode || 'PICK_DIR_FAILED', + error: reason, + message: t('errPickDirFailed', { error: reason }) } } - return callHostTransport(method, params, hostBridge); + if (FORBIDDEN_TARGET_PATTERN.test(picked.directoryPath)) { + const reason = t('forbiddenReason') + return { ok: false, errorCode: 'FORBIDDEN_TARGET', error: reason, message: reason } + } + return { + ok: true, + data: { directoryPath: picked.directoryPath }, + message: t('msgDirUpdated', { dir: picked.directoryPath }) + } } -interface SaveDialogResult { - canceled?: boolean; - filePath?: string; -} +/** 提交多线程 HTTP/HTTPS 下载任务(tool_download_transfer_add) */ +export async function addDownloadTransfer( + input: AddTransferInput, + hostBridge?: unknown +): Promise> { + if (!isRealElectronHost(hostBridge)) { + return { ok: false, errorCode: 'HOST_REQUIRED', error: t('errHostRequired'), message: t('errHostRequired') } + } -interface HttpDownloadResult { - path?: string; - size?: number; -} + const inspected = inspectDownloadUrl(input.url) + if (inspected.kind === 'magnet' || inspected.kind === 'ftp') { + const reason = inspected.unsupportedReason || t('errInvalidUrl') + return { ok: false, errorCode: 'UNSUPPORTED_PROTOCOL', error: reason, message: reason } + } + if (inspected.kind !== 'http' || !inspected.rawUrl) { + return { ok: false, errorCode: 'INVALID_URL', error: t('errInvalidUrl'), message: t('errInvalidUrl') } + } -function isSupportedDownloadUrl(url: string): boolean { - return /^(https?|ftp):\/\/\S+$/i.test(url) || /^magnet:\?\S+$/i.test(url); -} + const outputDir = String(input.outputDir || '').trim() + if (!outputDir) { + return { ok: false, errorCode: 'MISSING_OUTPUT_DIR', error: t('errMissingOutputDir'), message: t('errMissingOutputDir') } + } + if (FORBIDDEN_TARGET_PATTERN.test(outputDir)) { + return { ok: false, errorCode: 'FORBIDDEN_TARGET', error: t('forbiddenReason'), message: t('forbiddenReason') } + } -/** 客户端单连接下载 HTTP(S) 链接:先弹保存对话框(同名文件由系统对话框确认是否替换),再下载到所选位置 */ -async function downloadViaClient( - url: string, - downloadDir: string, - aria2Reason: string, - hostBridge?: unknown -): Promise { - const parsed = detectDownloadUrlFromText(url); - const ext = (parsed.suggestedFileName.match(/\.([A-Za-z0-9][A-Za-z0-9+_-]{0,31})$/) || [])[1]; - const dialogRes = await callHostTransport( - "window_show_save_dialog", - { - title: t("saveDialogTitle"), - ...(downloadDir ? { defaultPath: downloadDir } : {}), - defaultName: parsed.suggestedFileName || "download", - ...(ext ? { filters: `${t("saveFilterType", { ext: ext.toUpperCase() })}|${ext}|${t("saveFilterAll")}|*` } : {}) - }, - hostBridge - ); - if (!dialogRes.ok) { - return failure("SAVE_DIALOG_FAILED", t("errSaveDialogFailed", { reason: resolveErrorMessage(dialogRes, t("errNoReason")) })); + const maxConnections = input.maxConnections ?? 8 + if (!Number.isInteger(maxConnections) || maxConnections < 1 || maxConnections > 16) { + return { + ok: false, + errorCode: 'INVALID_CONNECTIONS', + error: t('errConnectionsRange'), + message: t('errConnectionsRange') + } } - const savePath = typeof dialogRes.data?.filePath === "string" ? dialogRes.data.filePath : ""; - if (dialogRes.data?.canceled || !savePath) { - return failure("CANCELED", t("errDownloadCanceled")); + + const sha256 = typeof input.expectedSha256 === 'string' ? input.expectedSha256.trim().toLowerCase() : '' + if (sha256 && !/^[0-9a-f]{64}$/.test(sha256)) { + return { + ok: false, + errorCode: 'INVALID_SHA256', + error: t('errInvalidSha256'), + message: t('errInvalidSha256') + } } - if (FORBIDDEN_TARGET_PATTERN.test(savePath)) { - return failure("FORBIDDEN_TARGET", t("forbiddenReason")); + + const payload: Record = { + ...(input.taskId ? { taskId: input.taskId } : {}), + url: inspected.rawUrl, + outputDir: { path: outputDir }, + ...(input.fileName?.trim() ? { fileName: input.fileName.trim() } : {}), + maxConnections, + ...(typeof input.maxRateBytesPerSec === 'number' && input.maxRateBytesPerSec > 0 + ? { maxRateBytesPerSec: Math.round(input.maxRateBytesPerSec) } + : {}), + ...(input.overwrite === true ? { overwrite: true } : {}), + ...(sha256 ? { expectedSha256: sha256 } : {}) } - const dl = await callHostLongRunning( - "network_http_download", - { url, savePath }, - DIRECT_DOWNLOAD_TIMEOUT_MS, - hostBridge - ); - if (!dl.ok) { - return failure("DOWNLOAD_FAILED", t("errDownloadFailed", { reason: resolveErrorMessage(dl, t("errNoReason")) })); + const res = await callHostTransport('tool_download_transfer_add', payload, hostBridge) + if (!res.ok) { + const errText = resolveErrorMessage(res, t('errHostRequired')) + return { + ok: false, + errorCode: res.errorCode || 'ADD_TRANSFER_FAILED', + error: errText, + message: t('errAddTransferFailed', { error: errText }) + } } - const finalPath = typeof dl.data?.path === "string" && dl.data.path ? dl.data.path : savePath; - const size = Number(dl.data?.size); - const sizeText = Number.isFinite(size) && size >= 0 ? `(${formatBytes(size)})` : ""; + + const record = normalizeTransferRecord(res.data) + if (!record) { + return { + ok: false, + errorCode: 'INVALID_TRANSFER_RECORD', + error: 'INVALID_TRANSFER_RECORD', + message: t('errAddTransferFailed', { error: 'INVALID_TRANSFER_RECORD' }) + } + } + return { ok: true, - code: 0, - message: t("msgClientDownloaded", { reason: aria2Reason, path: finalPath, sizeText }), - data: { engine: "client", path: finalPath, size: Number.isFinite(size) ? size : undefined } - }; + data: record, + message: t('msgTransferAdded', { name: record.fileName, connections: record.connections }) + } } -/** - * 发起下载:优先交给本机 aria2 按档位多线程下载;连不上 aria2 时, - * HTTP(S) 链接由客户端单连接下载(需用户在保存对话框中选位置),FTP 与磁力链接返回失败。 - */ -export async function startMultiThreadDownloadTask( - url: string, - downloadDir: string, - preset: ThreadSplitPreset, - hostBridge?: unknown, - options: Aria2Options = {} -): Promise { - const trimmed = String(url || "").trim(); - if (!trimmed || !isSupportedDownloadUrl(trimmed)) { - return failure("INVALID_URL", t("errInvalidUrlPrompt")); - } - - const aria2 = await callAria2( - "aria2.addUri", - [ - [trimmed], - { - ...(downloadDir ? { dir: downloadDir } : {}), - "max-connection-per-server": String(preset.threads), - split: String(preset.threads), - "min-split-size": preset.splitSize, - continue: "true" - } - ], - 3000, - options.fetchImpl - ); - if (aria2.reachable) { - if (aria2.error) { - return failure("ARIA2_REJECTED", t("errAria2Rejected", { error: aria2.error })); - } - const gid = typeof aria2.result === "string" ? aria2.result : ""; - return { - ok: true, - code: 0, - message: t("msgAria2Added", { - threads: preset.threads, - gidText: gid ? t("msgAria2Gid", { gid }) : "" - }), - data: { engine: "aria2", gid } - }; - } - - if (!/^https?:/i.test(trimmed)) { - const kind = /^magnet:/i.test(trimmed) ? t("kindMagnet") : t("kindFtp"); - return failure( - "ARIA2_REQUIRED", - t("errAria2Required", { kind, error: aria2.error }) - ); - } - return downloadViaClient(trimmed, downloadDir, aria2.error, hostBridge); +/** 暂停下载任务(tool_download_transfer_pause) */ +export async function pauseDownloadTransfer( + taskId: string, + hostBridge?: unknown +): Promise> { + if (!isRealElectronHost(hostBridge)) { + return { ok: false, errorCode: 'HOST_REQUIRED', error: t('errHostRequired'), message: t('errHostRequired') } + } + const id = String(taskId || '').trim() + if (!id) return { ok: false, errorCode: 'INVALID_TASK_ID', error: t('errTaskIdRequired'), message: t('errTaskIdRequired') } + const res = await callHostTransport('tool_download_transfer_pause', { taskId: id }, hostBridge) + if (!res.ok) { + const errText = resolveErrorMessage(res, t('errHostRequired')) + return { ok: false, errorCode: res.errorCode, error: errText, message: t('errPauseFailed', { error: errText }) } + } + const record = normalizeTransferRecord(res.data) + return { + ok: true, + data: record ?? undefined, + message: t('msgTransferPaused', { name: record?.fileName || id }) + } } -export function buildAria2cCommand(url: string, downloadDir: string, preset: ThreadSplitPreset): string { - const dirArg = downloadDir ? ` -d "${downloadDir}"` : ""; - return `aria2c ${preset.aria2Flags}${dirArg} "${url}"`; +/** 恢复已暂停的下载任务(tool_download_transfer_resume) */ +export async function resumeDownloadTransfer( + taskId: string, + hostBridge?: unknown +): Promise> { + if (!isRealElectronHost(hostBridge)) { + return { ok: false, errorCode: 'HOST_REQUIRED', error: t('errHostRequired'), message: t('errHostRequired') } + } + const id = String(taskId || '').trim() + if (!id) return { ok: false, errorCode: 'INVALID_TASK_ID', error: t('errTaskIdRequired'), message: t('errTaskIdRequired') } + const res = await callHostTransport('tool_download_transfer_resume', { taskId: id }, hostBridge) + if (!res.ok) { + const errText = resolveErrorMessage(res, t('errHostRequired')) + return { ok: false, errorCode: res.errorCode, error: errText, message: t('errResumeFailed', { error: errText }) } + } + const record = normalizeTransferRecord(res.data) + return { + ok: true, + data: record ?? undefined, + message: t('msgTransferResumed', { name: record?.fileName || id }) + } } -/** 生成 aria2c 命令并复制到剪贴板;插件不会运行它 */ -export async function copyAria2cCommand( - url: string, - downloadDir: string, - preset: ThreadSplitPreset, +/** 取消下载任务(tool_download_transfer_cancel) */ +export async function cancelDownloadTransfer( + taskId: string, hostBridge?: unknown -): Promise { - const trimmed = String(url || "").trim(); - if (!trimmed || !isSupportedDownloadUrl(trimmed)) { - return failure("INVALID_URL", t("errInvalidUrl")); +): Promise> { + if (!isRealElectronHost(hostBridge)) { + return { ok: false, errorCode: 'HOST_REQUIRED', error: t('errHostRequired'), message: t('errHostRequired') } } - const command = buildAria2cCommand(trimmed, downloadDir, preset); - const copied = await writeRealClipboardText(command, hostBridge); - if (!copied) { - return failure("CLIPBOARD_WRITE_FAILED", t("errClipboardWriteFailed")); + const id = String(taskId || '').trim() + if (!id) return { ok: false, errorCode: 'INVALID_TASK_ID', error: t('errTaskIdRequired'), message: t('errTaskIdRequired') } + const res = await callHostTransport('tool_download_transfer_cancel', { taskId: id }, hostBridge) + if (!res.ok) { + const errText = resolveErrorMessage(res, t('errHostRequired')) + return { ok: false, errorCode: res.errorCode, error: errText, message: t('errCancelFailed', { error: errText }) } } + const record = normalizeTransferRecord(res.data) return { ok: true, - code: 0, - message: t("msgCopiedCommand", { name: preset.name }), - data: { command } - }; + data: record ?? undefined, + message: t('msgTransferCancelled', { name: record?.fileName || id }) + } } -export interface TrashDownloadsResult { - deletedCount: number; - freedBytes: number; - failed: Array<{ path: string; reason: string }>; +/** 查询宿主下载传输队列状态(真相源:tool_download_transfer_status) */ +export async function fetchDownloadTransferStatus( + taskId?: string, + hostBridge?: unknown +): Promise> { + if (!isRealElectronHost(hostBridge)) { + return { ok: false, errorCode: 'HOST_REQUIRED', error: t('errHostRequired'), message: t('errHostRequired') } + } + const params: Record = taskId ? { taskId } : {} + const res = await callHostTransport('tool_download_transfer_status', params, hostBridge) + if (!res.ok) { + const errText = resolveErrorMessage(res, t('errHostRequired')) + return { ok: false, errorCode: res.errorCode, error: errText, message: t('errStatusFailed', { error: errText }) } + } + const rec = asRecord(res.data) + const rawList = Array.isArray(rec?.tasks) ? rec.tasks : Array.isArray(res.data) ? res.data : [] + const tasks = rawList + .map(normalizeTransferRecord) + .filter((item): item is DownloadTransferRecord => item !== null) + .sort((a, b) => b.updatedAt - a.updatedAt) + return { ok: true, data: tasks, message: 'OK' } } -/** 逐个把传入的文件移入回收站;只处理传入的路径,失败的条目如实列出 */ -export async function deleteDownloadedFiles( - paths: string[], - knownFiles: DownloadedFileItem[] = [], - hostBridge?: unknown -): Promise { - let deletedCount = 0; - let freedBytes = 0; - const failed: TrashDownloadsResult["failed"] = []; - const sizeMap = new Map(); - for (const item of knownFiles) { - if (item && item.path && typeof item.sizeBytes === "number" && Number.isFinite(item.sizeBytes)) { - sizeMap.set(item.path, item.sizeBytes); +/** 读取 LocalStorage 下载历史(仅作历史展示,不替代宿主活跃任务真相源) */ +export async function loadDownloadHistory(): Promise { + try { + const raw = await LocalStorage.getItem(HISTORY_STORAGE_KEY) + if (!Array.isArray(raw)) return [] + const out: DownloadHistoryEntry[] = [] + for (const item of raw) { + const rec = asRecord(item) + if (!rec || typeof rec.taskId !== 'string' || typeof rec.fileName !== 'string') continue + const totalBytes = rec.totalBytes !== undefined ? Number(rec.totalBytes) : undefined + out.push({ + taskId: rec.taskId, + url: typeof rec.url === 'string' ? rec.url : '', + fileName: rec.fileName, + outputDir: typeof rec.outputDir === 'string' ? rec.outputDir : '', + outputPath: typeof rec.outputPath === 'string' ? rec.outputPath : '', + ...(totalBytes !== undefined && Number.isFinite(totalBytes) && totalBytes >= 0 ? { totalBytes } : {}), + state: normalizeTransferState(rec.state), + updatedAt: typeof rec.updatedAt === 'number' && Number.isFinite(rec.updatedAt) ? rec.updatedAt : Date.now() + }) } + return out.slice(0, MAX_HISTORY_ITEMS) + } catch { + return [] } +} - for (const targetPath of paths) { - if (!targetPath) continue; - if (FORBIDDEN_TARGET_PATTERN.test(targetPath)) { - failed.push({ path: targetPath, reason: t("forbiddenReason") }); - continue; - } - const knownSize = sizeMap.get(targetPath) ?? (await getRealFileSize(targetPath, hostBridge)); - const res = await trashRealItem(targetPath, hostBridge); - if (res.ok) { - deletedCount += 1; - freedBytes += knownSize; - } else { - failed.push({ path: targetPath, reason: resolveErrorMessage(res, t("errTrashFailed")) }); - } +export async function saveDownloadHistory(entries: readonly DownloadHistoryEntry[]): Promise { + await LocalStorage.setItem(HISTORY_STORAGE_KEY, entries.slice(0, MAX_HISTORY_ITEMS)) +} + +export function buildHistoryEntryFromTask( + task: DownloadTransferRecord, + outputDir: string +): DownloadHistoryEntry { + return { + taskId: task.taskId, + url: task.url, + fileName: task.fileName, + outputDir, + outputPath: outputDir ? joinOutputPath(outputDir, task.fileName) : task.fileName, + ...(task.totalBytes !== undefined ? { totalBytes: task.totalBytes } : { totalBytes: task.downloadedBytes }), + state: task.state, + updatedAt: task.updatedAt } - return { deletedCount, freedBytes, failed }; } -export async function openDownloadedFileLocation( - targetPath: string, - hostBridge?: unknown -): Promise { - if (!targetPath) return failure("EMPTY_PATH", t("errEmptyPath")); - const ok = await showRealItemInFolder(targetPath, hostBridge); +export function mergeHistoryEntry( + history: readonly DownloadHistoryEntry[], + entry: DownloadHistoryEntry +): DownloadHistoryEntry[] { + const filtered = history.filter((item) => item.taskId !== entry.taskId) + return [entry, ...filtered].slice(0, MAX_HISTORY_ITEMS) +} + +export async function loadSavedOutputDir(): Promise { + try { + const dir = await LocalStorage.getItem(OUTPUT_DIR_STORAGE_KEY) + return typeof dir === 'string' ? dir.trim() : '' + } catch { + return '' + } +} + +export async function saveOutputDirPreference(dir: string): Promise { + if (!dir.trim()) return + await LocalStorage.setItem(OUTPUT_DIR_STORAGE_KEY, dir.trim()) +} + +export async function openDownloadItem(targetPath: string, hostBridge?: unknown): Promise { + if (!targetPath.trim()) { + return { ok: false, errorCode: 'EMPTY_PATH', error: t('errEmptyPath'), message: t('errEmptyPath') } + } + const ok = await openRealPath(targetPath, hostBridge) return ok - ? { ok: true, code: 0, message: t("msgRevealed", { path: targetPath }) } - : failure("SHOW_IN_FOLDER_FAILED", t("errRevealFailed", { path: targetPath })); + ? { ok: true, message: t('msgOpened', { path: targetPath }) } + : { ok: false, errorCode: 'OPEN_FAILED', error: t('errOpenFailed', { path: targetPath }), message: t('errOpenFailed', { path: targetPath }) } } -export async function openDownloadedFile( - targetPath: string, - hostBridge?: unknown -): Promise { - if (!targetPath) return failure("EMPTY_PATH", t("errEmptyPath")); - const ok = await openRealPath(targetPath, hostBridge); +export async function revealDownloadItem(targetPath: string, hostBridge?: unknown): Promise { + if (!targetPath.trim()) { + return { ok: false, errorCode: 'EMPTY_PATH', error: t('errEmptyPath'), message: t('errEmptyPath') } + } + const ok = await showRealItemInFolder(targetPath, hostBridge) + return ok + ? { ok: true, message: t('msgRevealed', { path: targetPath }) } + : { ok: false, errorCode: 'REVEAL_FAILED', error: t('errRevealFailed', { path: targetPath }), message: t('errRevealFailed', { path: targetPath }) } +} + +export async function copyDownloadUrl(url: string, hostBridge?: unknown): Promise { + if (!url.trim()) { + return { ok: false, errorCode: 'INVALID_URL', error: t('errInvalidUrl'), message: t('errInvalidUrl') } + } + const ok = await writeRealClipboardText(url, hostBridge) return ok - ? { ok: true, code: 0, message: t("msgOpened", { path: targetPath }) } - : failure("OPEN_FAILED", t("errOpenFailed", { path: targetPath })); + ? { ok: true, message: t('msgLinkCopied') } + : { ok: false, errorCode: 'CLIPBOARD_FAILED', error: t('errClipboardCopyFailed'), message: t('errClipboardCopyFailed') } } diff --git a/extensions/multi-download/src/native-ipc.ts b/extensions/multi-download/src/native-ipc.ts deleted file mode 100644 index 51576b99..00000000 --- a/extensions/multi-download/src/native-ipc.ts +++ /dev/null @@ -1,1852 +0,0 @@ -import { getLocale } from '@ztools/declarative-ui' - -type DynamicBridge = ReturnType - -const NATIVE_IPC_MESSAGES: Record string - dirEntrySep: string - dirErrorColon: string - deepScanUnavailable: string - pathEmpty: string - invalidMethodEmpty: string - invalidMethodFormat: string - invalidParamsObject: string - paramTooLong: (key: string) => string - paramOutOfRange: (key: string) => string - methodParamEmpty: string - invalidMethodType: string - malformedDllResponse: string - unknownDllError: string - hostIpcFailed: (pluginName: string, method: string) => string - hostUnavailable: (pluginName: string, method: string) => string - callFailed: string - movedToTrash: string - deleteFailed: string - revealedInFolder: string - revealFailed: string - opened: string - openFailed: string - pluginCallNotReady: string -}> = { - 'zh-CN': { - ipcCallFailed: 'IPC 调用返回失败', - ipcInnerFailed: 'IPC 内部调用失败', - scanIncomplete: '扫描结果不完整', - dirReadFailed: (details, moreCount) => - `目录读取失败或不完整:${details}${moreCount > 0 ? `;另有 ${moreCount} 个目录` : ''}`, - dirEntrySep: ';', - dirErrorColon: ':', - deepScanUnavailable: '深度扫描不可用,仅列出一级目录,结果不完整', - pathEmpty: '路径不能为空', - invalidMethodEmpty: 'INVALID_METHOD: 调用方法名不能为空', - invalidMethodFormat: 'INVALID_METHOD_FORMAT: 方法名包含非法字符或超长', - invalidParamsObject: 'INVALID_PARAMS: 参数必须为非空对象', - paramTooLong: (key) => `PARAM_TOO_LONG: 参数 ${key} 超过最大长度限制`, - paramOutOfRange: (key) => `PARAM_OUT_OF_RANGE: 数值参数 ${key} 越界或非有限数`, - methodParamEmpty: 'method 参数不能为空', - invalidMethodType: 'INVALID_METHOD: method 不能为空且必须为字符串', - malformedDllResponse: 'MALFORMED_DLL_RESPONSE: 原生组件返回了损坏的 JSON 数据', - unknownDllError: '原生组件返回未知错误', - hostIpcFailed: (pluginName, method) => `HOST_IPC_FAILED: ${pluginName}.${method} 调用失败`, - hostUnavailable: (pluginName, method) => `HOST_UNAVAILABLE: ${pluginName}.${method} 宿主接口未就绪`, - callFailed: '调用失败', - movedToTrash: '已移入回收站', - deleteFailed: '删除失败', - revealedInFolder: '已定位文件', - revealFailed: '定位失败', - opened: '已打开', - openFailed: '打开失败', - pluginCallNotReady: '插件调用未就绪' - }, - 'en-US': { - ipcCallFailed: 'IPC call failed', - ipcInnerFailed: 'Internal IPC call failed', - scanIncomplete: 'Incomplete scan results', - dirReadFailed: (details, moreCount) => - `Directory read failed or incomplete: ${details}${moreCount > 0 ? `; and ${moreCount} more` : ''}`, - dirEntrySep: '; ', - dirErrorColon: ': ', - deepScanUnavailable: 'Deep scan unavailable; only top-level directory listed (incomplete)', - pathEmpty: 'Path cannot be empty', - invalidMethodEmpty: 'INVALID_METHOD: Method name cannot be empty', - invalidMethodFormat: 'INVALID_METHOD_FORMAT: Method name contains invalid characters or is too long', - invalidParamsObject: 'INVALID_PARAMS: Parameters must be a non-null object', - paramTooLong: (key) => `PARAM_TOO_LONG: Parameter "${key}" exceeds maximum length`, - paramOutOfRange: (key) => `PARAM_OUT_OF_RANGE: Numeric parameter "${key}" is out of range or non-finite`, - methodParamEmpty: 'Method parameter cannot be empty', - invalidMethodType: 'INVALID_METHOD: Method must be a non-empty string', - malformedDllResponse: 'MALFORMED_DLL_RESPONSE: Native component returned malformed JSON', - unknownDllError: 'Native component returned an unknown error', - hostIpcFailed: (pluginName, method) => `HOST_IPC_FAILED: ${pluginName}.${method} call failed`, - hostUnavailable: (pluginName, method) => `HOST_UNAVAILABLE: ${pluginName}.${method} host interface not ready`, - callFailed: 'Call failed', - movedToTrash: 'Moved to Trash', - deleteFailed: 'Delete failed', - revealedInFolder: 'Revealed in folder', - revealFailed: 'Failed to reveal item', - opened: 'Opened', - openFailed: 'Failed to open', - pluginCallNotReady: 'Plugin invocation not ready' - } -} - -function ipcStrings() { - const locale = getLocale() - return NATIVE_IPC_MESSAGES[locale] ?? NATIVE_IPC_MESSAGES['en-US'] -} -/** - * ZTools 真实宿主 IPC 与系统能力桥接层 (Real Host IPC Bridge) - * - * 严格遵循《ZTools Declarative UI 2.0 架构与 35 款原生插件全量升级规范》5.1 真实环境铁律: - * - 在真实 Electron 宿主环境中,100% 走通 Preload (__ztoolsElectron.transport.methods / window.ztools / __ztoolsLauncher) 真实调用链路 - * - 严禁在真实环境中因参数格式或嵌套响应结构差异而回退到假数据 - */ - -let ipcReqSeq = 1 -const realFileSizeCache = new Map() - -export function nextMessageId(prefix = 'ipc'): string { - ipcReqSeq = (ipcReqSeq + 1) % 1_000_000 - return `${prefix}_${Date.now()}_${ipcReqSeq}` -} - -/** - * 判断当前是否处于真实的 ZTools Electron 渲染进程宿主环境 - */ -export function isRealElectronHost(hostOverride?: unknown): boolean { - if (hostOverride) return false - if (typeof window === 'undefined') return false - const w = window as DynamicBridge - return Boolean( - w.__ztoolsElectron?.transport?.methods || - w.ztools?.transport?.call || - w.ztools?.transport?.methods - ) -} - -function normalizeMethodParams(method: string, params: Record): Record { - if (!params || typeof params !== 'object') return {} - const next = { ...params } - if (method === 'system_get_disk_usage') { - const rawDrive = String(next.drive || next.path || 'C:\\').trim() - if (rawDrive.startsWith('/')) { - next.drive = rawDrive - } else { - const match = rawDrive.match(/^([A-Za-z]):/) - next.drive = match ? `${match[1].toUpperCase()}:\\` : rawDrive.replace(/\//g, '\\') - } - delete next.path - } - return next -} - -function normalizeMethodResult(method: string, payload: DynamicBridge): DynamicBridge { - if (!payload || typeof payload !== 'object') return payload - - if (method === 'system_get_disk_usage') { - const avail = typeof payload.available === 'number' - ? payload.available - : typeof payload.free === 'number' - ? payload.free - : Math.max(0, Number(payload.total || 0) - Number(payload.used || 0)) - return { - ...payload, - available: avail, - free: avail - } - } - - if (method === 'system_get_hardware_summary') { - const cpuModel = - typeof payload.cpuModel === 'string' && payload.cpuModel.trim() - ? payload.cpuModel.trim() - : Array.isArray(payload.cpuModels) && payload.cpuModels.length > 0 - ? String(payload.cpuModels[0]).trim() - : 'x86_64 Processor' - return { - ...payload, - cpuModel - } - } - - if (method === 'system_get_battery_status') { - // 宿主约定 percent 超出 0-100(如 255)表示无电池或电量未知,不能改写成 100% - const rawPct = payload.percent - const hasBattery = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 - return { - ...payload, - percent: hasBattery ? rawPct : null, - hasBattery - } - } - - if (method === 'screen_get_all_displays') { - const list = Array.isArray(payload) - ? payload - : Array.isArray(payload.displays) - ? payload.displays - : [] - return list.map((d: DynamicBridge) => ({ - ...d, - label: d?.label || d?.name || `Display #${d?.id ?? 1}` - })) - } - - return payload -} - -function extractIpcErrorMeta(errObj: DynamicBridge): { - errorCode?: string - errorDetails?: Record -} { - if (!errObj || typeof errObj !== 'object') return {} - const errorCode = - typeof errObj.errorCode === 'string' && errObj.errorCode.trim() - ? errObj.errorCode.trim() - : typeof errObj.code === 'string' && errObj.code.trim() - ? errObj.code.trim() - : undefined - const rawDetails = - errObj.errorDetails && typeof errObj.errorDetails === 'object' && !Array.isArray(errObj.errorDetails) - ? (errObj.errorDetails as Record) - : errObj.details && typeof errObj.details === 'object' && !Array.isArray(errObj.details) - ? (errObj.details as Record) - : undefined - return { - ...(errorCode ? { errorCode } : {}), - ...(rawDetails ? { errorDetails: rawDetails } : {}) - } -} - -function unwrapTransportResponse( - method: string, - raw: DynamicBridge -): { ok: boolean; data?: DynamicBridge; error?: string; errorCode?: string; errorDetails?: Record } { - if (raw === null || raw === undefined) { - return { ok: false, error: 'EMPTY_IPC_RESPONSE', errorCode: 'EMPTY_IPC_RESPONSE' } - } - if (typeof raw !== 'object') { - return { ok: true, data: raw } - } - if (raw.success === false) { - const errObj = raw.error - const errMsg = - typeof errObj === 'object' && errObj !== null - ? String(errObj.message || errObj.code || JSON.stringify(errObj)) - : String(errObj || ipcStrings().ipcCallFailed) - return { ok: false, error: errMsg, ...extractIpcErrorMeta(raw), ...extractIpcErrorMeta(errObj) } - } - - const firstLayer = 'data' in raw && raw.data !== undefined ? raw.data : raw - if (firstLayer && typeof firstLayer === 'object' && !Array.isArray(firstLayer)) { - if (firstLayer.success === false) { - const errObj = firstLayer.error - const errMsg = - typeof errObj === 'object' && errObj !== null - ? String(errObj.message || errObj.code || JSON.stringify(errObj)) - : String(errObj || ipcStrings().ipcInnerFailed) - return { ok: false, error: errMsg, ...extractIpcErrorMeta(firstLayer), ...extractIpcErrorMeta(errObj) } - } - if ('data' in firstLayer && firstLayer.data !== undefined) { - return { ok: true, data: normalizeMethodResult(method, firstLayer.data) } - } - } - - return { ok: true, data: normalizeMethodResult(method, firstLayer) } -} - -/** - * 调用 Electron Preload Transport 方法(自动封装合法的 alphanumeric messageId 与双层解包) - */ -export async function callHostTransport( - method: string, - params: Record = {}, - hostOverride?: DynamicBridge -): Promise<{ ok: boolean; data?: T; error?: string; errorCode?: string; errorDetails?: Record }> { - const normalizedParams = normalizeMethodParams(method, params) - - // 1. 测试注入的 hostOverride 优先 - if (hostOverride) { - if (typeof hostOverride[method] === 'function') { - try { - const res = await hostOverride[method](normalizedParams) - const unwrapped = unwrapTransportResponse(method, res) - return unwrapped as { ok: boolean; data?: T; error?: string; errorCode?: string; errorDetails?: Record } - } catch (err: DynamicBridge) { - return { ok: false, error: err instanceof Error ? err.message : String(err), ...extractIpcErrorMeta(err) } - } - } - if (typeof hostOverride?.transport?.call === 'function') { - try { - const res = await hostOverride.transport.call(method, normalizedParams) - const unwrapped = unwrapTransportResponse(method, res) - return unwrapped as { ok: boolean; data?: T; error?: string; errorCode?: string; errorDetails?: Record } - } catch (err: DynamicBridge) { - return { ok: false, error: err instanceof Error ? err.message : String(err), ...extractIpcErrorMeta(err) } - } - } - } - - if (typeof window === 'undefined') { - return { ok: false, error: 'NO_WINDOW_ENV', errorCode: 'NO_WINDOW_ENV' } - } - - const w = window as DynamicBridge - const methods = w.__ztoolsElectron?.transport?.methods || w.ztools?.transport?.methods - const fn = methods?.[method] - - if (typeof fn === 'function') { - try { - const messageId = nextMessageId(method.replace(/[^A-Za-z0-9_]/g, '_').slice(0, 24)) - const raw = await fn({ messageId, params: normalizedParams }) - return unwrapTransportResponse(method, raw) as { ok: boolean; data?: T; error?: string; errorCode?: string; errorDetails?: Record } - } catch (err: DynamicBridge) { - return { ok: false, error: err instanceof Error ? err.message : String(err), ...extractIpcErrorMeta(err) } - } - } - - if (typeof w.ztools?.transport?.call === 'function') { - try { - const raw = await w.ztools.transport.call(method, normalizedParams) - return unwrapTransportResponse(method, raw) as { ok: boolean; data?: T; error?: string; errorCode?: string; errorDetails?: Record } - } catch (err: DynamicBridge) { - return { ok: false, error: err instanceof Error ? err.message : String(err), ...extractIpcErrorMeta(err) } - } - } - - return { ok: false, error: `METHOD_NOT_AVAILABLE: ${method}`, errorCode: 'METHOD_NOT_AVAILABLE' } -} - -export interface RealDiskDriveInfo { - drive: string - totalBytes: number - usedBytes: number - availableBytes: number - usagePercent: number -} - -/** - * 探测本机全部真实挂载磁盘分区 (C:\ ~ Z:\ 或 macOS/POSIX 挂载点 '/') - */ -export async function probeRealDiskDrives( - candidateLetters: string[] = ['C', 'D', 'E', 'F', 'G'], - hostOverride?: DynamicBridge -): Promise { - const drives: RealDiskDriveInfo[] = [] - const results = await Promise.all( - candidateLetters.map(async (letter) => { - const raw = String(letter || '').trim() - const isPosix = raw.startsWith('/') - const drivePath = isPosix ? raw : `${raw.replace(/:\\?$/, '').toUpperCase()}:\\` - const res = await callHostTransport<{ - total: number - used: number - available: number - free?: number - percent: number - }>('system_get_disk_usage', { drive: drivePath }, hostOverride) - if (res.ok && res.data && typeof res.data.total === 'number' && res.data.total > 0) { - const availableBytes = - typeof res.data.available === 'number' - ? res.data.available - : typeof res.data.free === 'number' - ? res.data.free - : Math.max(0, res.data.total - res.data.used) - return { - drive: isPosix ? raw : `${raw.replace(/:\\?$/, '').toUpperCase()}:`, - totalBytes: res.data.total, - usedBytes: res.data.used, - availableBytes, - usagePercent: res.data.percent - } - } - return null - }) - ) - - for (const item of results) { - if (item) drives.push(item) - } - - if (drives.length === 0 && !candidateLetters.includes('/')) { - const posixRes = await callHostTransport<{ - total: number - used: number - available: number - free?: number - percent: number - }>('system_get_disk_usage', { drive: '/' }, hostOverride) - if (posixRes.ok && posixRes.data && typeof posixRes.data.total === 'number' && posixRes.data.total > 0) { - const availableBytes = - typeof posixRes.data.available === 'number' - ? posixRes.data.available - : typeof posixRes.data.free === 'number' - ? posixRes.data.free - : Math.max(0, posixRes.data.total - posixRes.data.used) - drives.push({ - drive: '/', - totalBytes: posixRes.data.total, - usedBytes: posixRes.data.used, - availableBytes, - usagePercent: posixRes.data.percent - }) - } - } - - return drives -} - -/** - * 获取本机真实系统特殊路径(支持 home 派生标准子目录兜底,自动兼容 Windows 与 macOS/POSIX) - */ -export async function getRealSystemPath( - name: 'home' | 'appData' | 'userData' | 'desktop' | 'documents' | 'downloads' | 'music' | 'pictures' | 'videos' | 'temp' | 'cache', - hostOverride?: DynamicBridge -): Promise { - const res = await callHostTransport('system_get_path', { name }, hostOverride) - if (res.ok && res.data) { - if (typeof res.data === 'string' && res.data.trim().length > 0) { - return res.data.trim() - } - if (typeof res.data.path === 'string' && res.data.path.trim().length > 0) { - return res.data.path.trim() - } - } - - if (name !== 'home') { - const home = await getRealSystemPath('home', hostOverride) - if (home) { - const isPosix = home.startsWith('/') - const subMap: Record = isPosix - ? { - desktop: `${home}/Desktop`, - documents: `${home}/Documents`, - downloads: `${home}/Downloads`, - music: `${home}/Music`, - pictures: `${home}/Pictures`, - videos: `${home}/Videos`, - appData: `${home}/Library/Application Support`, - userData: `${home}/Library/Application Support/ZTools`, - temp: '/tmp', - cache: `${home}/Library/Caches` - } - : { - desktop: `${home}\\Desktop`, - documents: `${home}\\Documents`, - downloads: `${home}\\Downloads`, - music: `${home}\\Music`, - pictures: `${home}\\Pictures`, - videos: `${home}\\Videos`, - appData: `${home}\\AppData\\Roaming`, - userData: `${home}\\AppData\\Roaming\\ZTools`, - temp: `${home}\\AppData\\Local\\Temp`, - cache: `${home}\\AppData\\Local` - } - if (subMap[name]) return subMap[name] - } - } - - return '' -} - -export type RealDriveUsageInfo = RealDiskDriveInfo - -export interface RealIndexedFileEntry { - name: string - path: string - ext: string - isDir: boolean - isDirectory: boolean - size: number - sizeBytes: number - mtime: number - mtimeMs: number - lastModifiedMs: number -} - -export interface RealDirectorySubdirSummary { - name: string - path: string - fileCount: number - totalBytes: number - mtime: number - /** 体积不是完整统计(宿主扫描截断且独立统计超时 / 无权限),totalBytes 只是下限 */ - approximate?: boolean -} - -export interface RealDirectoryScanResult extends Iterable { - files: RealIndexedFileEntry[] - totalFiles: number - fileCount: number - totalBytes: number - subdirs: RealDirectorySubdirSummary[] - /** 宿主扫描达到条目上限后停止:files / totalFiles 只是已遍历部分的抽样 */ - truncated?: boolean - /** totalBytes 为近似值(下限) */ - approximate?: boolean - /** 宿主实际遍历的条目数 */ - visitedEntries?: number - /** 读取失败的真实原因;已有文件仍可使用,但不能当作完整结果。 */ - error?: string -} - -interface ScanResultMeta { - truncated?: boolean - approximate?: boolean - visitedEntries?: number -} - -export interface ScanDirectoryTreeOptions { - maxDepth?: number - maxFiles?: number - collectTopN?: number - filterExt?: RegExp - hostOverride?: DynamicBridge -} - -function extractFileExt(fileNameOrPath: string): string { - const base = String(fileNameOrPath || '').split(/[\\/]/).pop() || '' - const dotIdx = base.lastIndexOf('.') - return dotIdx > 0 ? base.slice(dotIdx).toLowerCase() : '' -} - -function normalizeIndexedFileEntry(f: DynamicBridge): RealIndexedFileEntry { - const p = String(f?.path || '') - const name = String(f?.name || p.split(/[\\/]/).pop() || '') - const sz = Number(f?.size ?? f?.sizeBytes ?? 0) - const isDir = Boolean(f?.is_dir || f?.isDir || f?.isDirectory) - const rawMtime = Number(f?.mtime ?? f?.mtimeMs ?? 0) - const mtimeMs = rawMtime > 1e11 ? rawMtime : rawMtime > 0 ? rawMtime * 1000 : Date.now() - const mtimeSec = rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime - if (p && sz >= 0) realFileSizeCache.set(p, sz) - return { - name, - path: p, - ext: extractFileExt(name || p), - isDir, - isDirectory: isDir, - size: sz, - sizeBytes: sz, - mtime: mtimeSec, - mtimeMs, - lastModifiedMs: mtimeMs - } -} - -function makeScanResult( - files: RealIndexedFileEntry[], - totalFiles: number, - totalBytes: number, - subdirs: RealDirectorySubdirSummary[], - meta: ScanResultMeta = {} -): RealDirectoryScanResult { - return { - files, - totalFiles, - fileCount: totalFiles, - totalBytes, - subdirs, - ...(meta.truncated ? { truncated: true } : {}), - ...(meta.approximate ? { approximate: true } : {}), - ...(typeof meta.visitedEntries === 'number' ? { visitedEntries: meta.visitedEntries } : {}), - [Symbol.iterator]() { - return files[Symbol.iterator]() - } - } -} - -/** - * 调用客户端的原生文件索引组件 (ztools-indexer) 检索文件 - */ -export async function searchRealIndexedFiles( - query: string, - limit = 40, - hostOverride?: DynamicBridge -): Promise { - if (!query || !query.trim()) return [] - const q = query.trim() - const safeLimit = Math.min(200, Math.max(1, Math.floor(limit || 40))) - - try { - const res = await callHostTransport<{ files?: DynamicBridge[] }>( - 'system_search_files', - { query: q, limit: safeLimit }, - hostOverride - ) - if (res.ok && res.data && Array.isArray(res.data.files)) { - return res.data.files.map(normalizeIndexedFileEntry) - } - - if (!hostOverride && typeof window !== 'undefined') { - const w = window as DynamicBridge - if (typeof w.__ztoolsLauncher?.searchFiles === 'function') { - const rawOuter = await w.__ztoolsLauncher.searchFiles(q, safeLimit) - const raw = rawOuter && typeof rawOuter === 'object' && 'data' in rawOuter && rawOuter.data ? rawOuter.data : rawOuter - if (raw && Array.isArray(raw.files)) { - return raw.files.map(normalizeIndexedFileEntry) - } - } - } - } catch { - // ignore - } - return [] -} - -/** - * 深度扫描指定真实物理目录树(支持符号链接穿透,如 AppData\Roaming\Tencent -> D:\Local\Roaming\Tencent) - * 返回该目录下 Top 文件列表、全树真实文件总数、全树真实总字节数与一级子目录汇总 - */ -export async function scanRealDirectoryTree( - dirPath: string, - limitOrOptions: number | ScanDirectoryTreeOptions = 160, - hostOverrideArg?: DynamicBridge -): Promise { - const result = await scanDirectoryTreeWithError(dirPath, limitOrOptions, hostOverrideArg) - return result.error ? { ...result.scan, error: result.error } : result.scan -} - -/** 一次界面扫描的错误汇总;多个目录并行扫描时保留可读目录的结果。 */ -export function createDirectoryScanner(hostOverride?: DynamicBridge) { - const failures = new Map() - return { - async scan(dir: string, options: number | ScanDirectoryTreeOptions = 160) { - const result = await scanRealDirectoryTree(dir, options, hostOverride) - const error = result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') - if (error) failures.set(dir, error) - else failures.delete(dir) - return result - }, - get error(): string | undefined { - if (!failures.size) return undefined - const s = ipcStrings() - const details = [...failures].slice(0, 3).map(([dir, error]) => `${dir}${s.dirErrorColon}${error}`).join(s.dirEntrySep) - return s.dirReadFailed(details, Math.max(0, failures.size - 3)) - } - } -} - -/** scanRealDirectoryTree 的实现:额外带回读取失败原因(目录不存在 / 为空 / 无权限 / 载荷异常) */ -async function scanDirectoryTreeWithError( - dirPath: string, - limitOrOptions: number | ScanDirectoryTreeOptions, - hostOverrideArg?: DynamicBridge -): Promise<{ scan: RealDirectoryScanResult; error?: string }> { - const empty = makeScanResult([], 0, 0, []) - if (!dirPath || !dirPath.trim()) return { scan: empty, error: 'EMPTY_DIRECTORY_PATH' } - const targetDir = dirPath.trim() - - const opts: ScanDirectoryTreeOptions = - typeof limitOrOptions === 'number' - ? { maxFiles: limitOrOptions, hostOverride: hostOverrideArg } - : { ...limitOrOptions, hostOverride: limitOrOptions?.hostOverride ?? hostOverrideArg } - - const rawLimit = opts.maxFiles ?? opts.collectTopN ?? 160 - const safeLimit = Math.min(200, Math.max(1, Math.floor(rawLimit || 160))) - const hostOverride = opts.hostOverride - const filterExt = opts.filterExt - const dirQuery = `dir:${targetDir}` - - try { - let rawPayload: DynamicBridge = null - const res = await callHostTransport( - 'system_search_files', - { query: dirQuery, limit: safeLimit }, - hostOverride - ) - if (res.ok && res.data) { - rawPayload = res.data - } - if (!rawPayload && !hostOverride && typeof window !== 'undefined') { - const w = window as DynamicBridge - if (typeof w.__ztoolsLauncher?.searchFiles === 'function') { - const rawOuter = await w.__ztoolsLauncher.searchFiles(dirQuery, safeLimit) - rawPayload = - rawOuter && typeof rawOuter === 'object' && 'data' in rawOuter && rawOuter.data - ? rawOuter.data - : rawOuter - } - } - - if ( - rawPayload && - Array.isArray(rawPayload.files) - ) { - let files: RealIndexedFileEntry[] = rawPayload.files.map(normalizeIndexedFileEntry) - if (filterExt instanceof RegExp) { - files = files.filter(f => !f.isDir && (filterExt.test(f.name) || filterExt.test(f.ext))) - // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索目标扩展名 - if (files.length === 0 && !hostOverride) { - const extTokens = (filterExt.source.match(/[a-z0-9]{2,5}/gi) || []) - .filter(t => !['thumbcache', 'iconcache'].includes(t.toLowerCase())) - .slice(0, 4) - // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 - const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() - const extraLists = await Promise.all( - extTokens.map(ext => searchRealIndexedFiles(`.${ext.toLowerCase()}`, 30, hostOverride)) - ) - const seen = new Set() - for (const list of extraLists) { - for (const item of list) { - if (!item.isDir && item.size > 0 && !seen.has(item.path)) { - if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { - seen.add(item.path) - files.push(item) - } - } - } - } - } - } - if (typeof opts.collectTopN === 'number' && opts.collectTopN > 0 && files.length > opts.collectTopN) { - files = files.slice(0, opts.collectTopN) - } - const subdirs: RealDirectorySubdirSummary[] = Array.isArray(rawPayload.subdirs) - ? rawPayload.subdirs.map((s: DynamicBridge) => ({ - name: String(s.name || ''), - path: String(s.path || ''), - fileCount: Number(s.file_count ?? s.fileCount ?? 0), - totalBytes: Number(s.total_bytes ?? s.totalBytes ?? 0), - mtime: Number(s.mtime || 0), - ...(s.approximate === true ? { approximate: true } : {}) - })) - : [] - const computedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) - const totalFilesCount = - filterExt instanceof RegExp ? files.length : Number(rawPayload.total_matches ?? files.length) - const totalBytesCount = - filterExt instanceof RegExp ? computedBytes : Number(rawPayload.total_bytes ?? computedBytes) - const visited = Number(rawPayload.visited_entries) - return { - scan: makeScanResult(files, totalFilesCount, totalBytesCount, subdirs, { - truncated: rawPayload.truncated === true, - approximate: rawPayload.approximate === true, - ...(Number.isFinite(visited) && visited >= 0 ? { visitedEntries: visited } : {}) - }), - ...(typeof rawPayload.scan_error === 'string' && rawPayload.scan_error ? { error: rawPayload.scan_error } : {}) - } - } - - // 深度扫描失败或回执无效时,仅以一级目录读取补回可见结果;不冒充完整目录树。 - const listing = await listDirectoryViaFilesystem(targetDir, hostOverride, { withSizes: true, limit: safeLimit }) - if (listing.ok && listing.entries.length > 0) { - const files: RealIndexedFileEntry[] = [] - let totalBytes = 0 - for (const entry of listing.entries) { - if (filterExt instanceof RegExp && !filterExt.test(entry.name) && !filterExt.test(entry.ext)) { - continue - } - files.push(entry) - totalBytes += entry.isDir ? 0 : entry.size - } - const incomplete = listing.entries.some(entry => entry.isDir) || listing.entries.length >= safeLimit - return { - scan: makeScanResult(files, files.filter(file => !file.isDir).length, totalBytes, [], { approximate: incomplete }), - ...(incomplete ? { error: res.error || ipcStrings().deepScanUnavailable } : {}) - } - } - return listing.ok ? { scan: empty } : { scan: empty, error: listing.error || 'DIRECTORY_READ_FAILED' } - } catch (error) { - return { scan: empty, error: error instanceof Error ? error.message : String(error) } - } -} - - -/** 目录读取不到任何条目(不存在 / 为空 / 无权限)时的错误码 */ -export const DIRECTORY_EMPTY_OR_UNREADABLE = 'DIRECTORY_EMPTY_OR_UNREADABLE' - -export interface RealDirectoryListingResult { - /** 目录内条目的完整路径;读取失败时为空数组 */ - entries: string[] - /** 读取失败或目录为空时的错误码 / 宿主错误信息 */ - error?: string -} - -export interface RealDirectChildrenResult { - /** 目录的直接子项(子目录在前),按路径去重 */ - entries: RealIndexedFileEntry[] - /** 宿主扫描达到条目上限,可能只返回了部分直接子项 */ - partial: boolean - error?: string -} - -function stripTrailingSeparators(p: string): string { - const trimmed = p.replace(/[\\/]+$/, '') - return trimmed || p.slice(0, 1) -} - -function isWindowsStylePath(p: string): boolean { - return /^[A-Za-z]:/.test(p) || p.startsWith('\\\\') || (p.includes('\\') && !p.includes('/')) -} - -function comparablePath(p: string): string { - const stripped = stripTrailingSeparators(String(p || '').trim()) - return isWindowsStylePath(stripped) ? stripped.replace(/\//g, '\\').toLowerCase() : stripped -} - -function parentDirOf(p: string): string { - const stripped = stripTrailingSeparators(String(p || '')) - const idx = Math.max(stripped.lastIndexOf('/'), stripped.lastIndexOf('\\')) - if (idx < 0) return '' - if (idx === 0) return stripped.slice(0, 1) - const parent = stripped.slice(0, idx) - return /^[A-Za-z]:$/.test(parent) ? `${parent}\\` : parent -} - -function isDirectChildPath(dirPath: string, candidate: string): boolean { - if (!candidate) return false - return comparablePath(parentDirOf(candidate)) === comparablePath(dirPath) -} - -function joinChildPath(dirPath: string, name: string): string { - const sep = isWindowsStylePath(dirPath) ? '\\' : '/' - const base = dirPath.replace(/[\\/]+$/, '') - return `${base}${sep}${name}` -} - -/** - * 通过 filesystem_get_directory_contents 读取一级目录(需宿主授权)。 - * 宿主真实返回 { success, files: [{ name, size, isDirectory, lastModified }] }(name 为文件名); - * 兼容旧测试替身返回的完整路径字符串数组。 - */ -async function listDirectoryViaFilesystem( - dirPath: string, - hostOverride: DynamicBridge, - options: { withSizes?: boolean; limit?: number } = {} -): Promise<{ ok: boolean; entries: RealIndexedFileEntry[]; error?: string }> { - const res = await callHostTransport('filesystem_get_directory_contents', { path: dirPath }, hostOverride) - if (!res.ok) return { ok: false, entries: [], error: res.error || 'DIRECTORY_READ_FAILED' } - const data = res.data - const rawList: unknown[] | null = Array.isArray(data) ? data : Array.isArray(data?.files) ? data.files : null - if (!rawList) return { ok: false, entries: [], error: 'INVALID_DIRECTORY_PAYLOAD' } - - const limit = Math.max(1, Math.floor(options.limit ?? 1000)) - const nowSec = Math.floor(Date.now() / 1000) - const entries: RealIndexedFileEntry[] = [] - const seen = new Set() - for (const item of rawList) { - if (entries.length >= limit) break - let entry: RealIndexedFileEntry | null = null - if (typeof item === 'string') { - const itemPath = item.trim() - if (!itemPath) continue - const name = itemPath.split(/[\\/]/).pop() || itemPath - const sz = options.withSizes ? await getRealFileSize(itemPath, hostOverride) : 0 - entry = normalizeIndexedFileEntry({ - name, - path: itemPath, - isDir: sz === 0 && !name.includes('.'), - size: sz, - mtime: nowSec - }) - } else if (item && typeof item === 'object' && typeof (item as DynamicBridge).name === 'string') { - const raw = item as DynamicBridge - const rawName = raw.name.trim() - if (!rawName || rawName === '.' || rawName === '..') continue - // 只接受文件名,或确实位于该目录下的完整路径,拒绝越界路径 - const fullPath = /[\\/]/.test(rawName) ? rawName : joinChildPath(dirPath, rawName) - if (!isDirectChildPath(dirPath, fullPath)) continue - const isDir = Boolean(raw.isDirectory ?? raw.isDir ?? raw.is_dir) - const parsedMtime = Date.parse(String(raw.lastModified || '')) - entry = normalizeIndexedFileEntry({ - name: fullPath.split(/[\\/]/).pop() || rawName, - path: fullPath, - isDir, - size: isDir ? 0 : Math.max(0, Number(raw.size) || 0), - mtime: Number.isFinite(parsedMtime) ? parsedMtime : nowSec - }) - } - if (!entry || seen.has(entry.path)) continue - seen.add(entry.path) - entries.push(entry) - } - return { ok: true, entries } -} - -/** - * 读取真实目录下的条目路径(真实宿主中优先走 dir: 扫描:一级子目录 + 全树 Top-N 大文件),并返回失败原因。 - * 目录不存在、为空或无权限时返回空列表与错误码,绝不用全盘关键词搜索结果冒充目录内容。 - */ -export async function listRealDirectoryContentsResult( - dirPath: string, - hostOverride?: DynamicBridge -): Promise { - if (!dirPath || !dirPath.trim()) return { entries: [], error: 'EMPTY_DIRECTORY_PATH' } - const targetDir = dirPath.trim() - - if (!hostOverride && isRealElectronHost()) { - const tree = await scanRealDirectoryTree(targetDir, 60) - const paths: string[] = [] - for (const s of tree.subdirs) { - if (s.path) paths.push(s.path) - } - for (const f of tree.files) { - if (f.path) paths.push(f.path) - } - if (paths.length > 0) return { entries: Array.from(new Set(paths)) } - } - - const listing = await listDirectoryViaFilesystem(targetDir, hostOverride) - if (!listing.ok) return { entries: [], error: listing.error } - if (listing.entries.length === 0) return { entries: [], error: DIRECTORY_EMPTY_OR_UNREADABLE } - return { entries: listing.entries.map(e => e.path) } -} - -/** - * 读取真实目录下的条目路径(保持旧签名:失败时返回空数组,需要失败原因请用 listRealDirectoryContentsResult) - */ -export async function listRealDirectoryContents( - dirPath: string, - hostOverride?: DynamicBridge -): Promise { - return (await listRealDirectoryContentsResult(dirPath, hostOverride)).entries -} - -/** - * 只列出目录的直接子项(子目录 + 直接位于该目录下的文件),用于文件夹预览、按目录改名等场景。 - * dir: 扫描结果中只保留 subdirs 与父目录等于 dirPath 的文件;扫描达到上限时 partial=true,由插件如实提示「仅显示部分」。 - */ -export async function listDirectChildren( - dirPath: string, - hostOverride?: DynamicBridge -): Promise { - if (!dirPath || !dirPath.trim()) return { entries: [], partial: false, error: 'EMPTY_DIRECTORY_PATH' } - const targetDir = dirPath.trim() - const scanLimit = 200 - const entries: RealIndexedFileEntry[] = [] - const seen = new Set() - const push = (entry: RealIndexedFileEntry) => { - const key = comparablePath(entry.path) - if (!entry.path || seen.has(key)) return - seen.add(key) - entries.push(entry) - } - - const { scan: tree, error } = await scanDirectoryTreeWithError(targetDir, { maxFiles: scanLimit, hostOverride }) - for (const s of tree.subdirs) { - if (!s.path || !isDirectChildPath(targetDir, s.path)) continue - push( - normalizeIndexedFileEntry({ - name: s.name || s.path.split(/[\\/]/).pop(), - path: s.path, - isDir: true, - size: s.totalBytes, - mtime: s.mtime - }) - ) - } - let directFileCount = 0 - for (const f of tree.files) { - if (!isDirectChildPath(targetDir, f.path)) continue - directFileCount++ - push(f) - } - // 宿主 total_matches 是全树文件数、subdirs[].file_count 是各子目录全树文件数,差值即直接子文件数; - // 拿到的直接子文件少于它就说明被 Top-N 截断了。计数不可用时按是否达到扫描上限判断 - const expectedDirectFiles = tree.totalFiles - tree.subdirs.reduce((sum, d) => sum + (Number(d.fileCount) || 0), 0) - const partial = - Number.isFinite(expectedDirectFiles) && expectedDirectFiles >= 0 - ? directFileCount < expectedDirectFiles - : tree.files.length >= scanLimit - if (entries.length > 0) { - return { entries, partial } - } - - if (tree.files.length > 0) { - // dir: 扫描只返回了深层文件(直接子文件被 Top-N 截掉),如实标注部分结果 - return { entries: [], partial: true, error: DIRECTORY_EMPTY_OR_UNREADABLE } - } - return { entries: [], partial: false, error: error || DIRECTORY_EMPTY_OR_UNREADABLE } -} - -/** - * 获取真实文件字节大小(优先用扫描结果里的大小,再走 filesystem_get_file_size);读不到时返回 0 - */ -export async function getRealFileSize( - filePath: string, - hostOverride?: DynamicBridge -): Promise { - if (!filePath) return 0 - if (!hostOverride && realFileSizeCache.has(filePath)) { - const cached = realFileSizeCache.get(filePath)! - if (cached > 0) return cached - } - const res = await callHostTransport('filesystem_get_file_size', { path: filePath }, hostOverride) - // 客户端返回 { success, size }(目录时 size 为 -1),旧的测试替身直接返回数字 - const size = typeof res.data === 'number' ? res.data : res.data?.size - if (res.ok && typeof size === 'number' && Number.isFinite(size) && size >= 0) { - realFileSizeCache.set(filePath, size) - return size - } - return 0 -} - -/** - * 在访达 / 资源管理器中定位并高亮文件或目录。 - * 定位失败直接返回 false,不能改用“打开”:对可执行文件那等于运行它。 - */ -export async function showRealItemInFolder( - fullPath: string, - hostOverride?: DynamicBridge -): Promise { - if (!fullPath) return false - const res = await callHostTransport('shell_show_item_in_folder', { fullPath }, hostOverride) - return res.ok -} - -/** - * 使用系统默认程序打开文件或目录 - */ -export async function openRealPath( - fullPath: string, - hostOverride?: DynamicBridge -): Promise { - if (!fullPath) return false - const res = await callHostTransport('shell_open_path', { fullPath }, hostOverride) - return res.ok -} - -/** - * 将真实文件或目录移入系统回收站(安全可恢复删除) - */ -export async function trashRealItem( - fullPath: string, - hostOverride?: DynamicBridge -): Promise<{ ok: boolean; error?: string; errorCode?: string; errorDetails?: Record }> { - if (!fullPath) return { ok: false, error: ipcStrings().pathEmpty } - const res = await callHostTransport('shell_trash_item', { fullPath }, hostOverride) - return { - ok: res.ok, - error: res.error, - ...(!res.ok && res.errorCode ? { errorCode: res.errorCode } : {}), - ...(!res.ok && res.errorDetails ? { errorDetails: res.errorDetails } : {}) - } -} - -export interface NativeInvocationResult { - ok: boolean - code: number - message: string - data?: T - error?: string - errorCode?: string - errorDetails?: Record -} - -export interface DllCapabilityResponse { - ok: boolean - code: number - data: T | null - message?: string - error?: string - errorCode?: string - errorDetails?: Record - pluginName: string - method: string - fromFallback?: boolean -} - -/** 声明式能力菜单项及其调用回执,供相同宿主协议的插件共用。 */ -export interface CapabilityActionItem { - id: string - title: string - subtitle: string - tag: string - method: string - params: Record -} - -export type PluginInvocationResult = Pick< - DllCapabilityResponse, 'ok' | 'pluginName' | 'method' | 'error' | 'errorCode' | 'errorDetails' | 'fromFallback' -> & { data?: unknown } - -/** 多个原生能力插件共用的参数边界校验;保护目标由各插件按自身业务提供。 */ -export function validateNativeCapabilityPayload( - method: string, - params: unknown, - forbiddenPattern: RegExp, - forbiddenReason: string -): { valid: boolean; error?: string } { - const s = ipcStrings() - if (typeof method !== 'string' || method.trim().length === 0) { - return { valid: false, error: s.invalidMethodEmpty } - } - if (method.length > 128 || !/^[A-Za-z0-9_]+$/.test(method.trim())) { - return { valid: false, error: s.invalidMethodFormat } - } - if (params === null || params === undefined || typeof params !== 'object' || Array.isArray(params)) { - return { valid: false, error: s.invalidParamsObject } - } - - const record = params as Record - for (const [key, val] of Object.entries(record)) { - if (typeof val === 'string') { - if (val.length > 4096) { - return { valid: false, error: s.paramTooLong(key) } - } - if (forbiddenPattern.test(val)) { - return { valid: false, error: `SECURITY_INTERCEPTED: ${forbiddenReason}` } - } - } else if (typeof val === 'number') { - if (!Number.isFinite(val) || val < -1000 || val > 100_000_000) { - return { valid: false, error: s.paramOutOfRange(key) } - } - } - } - - return { valid: true } -} - -export async function invokeDllPluginCapability( - pluginName: string, - method: string, - params: Record = {}, - hostBridge?: DynamicBridge, - offlineFallback?: () => T | Promise -): Promise> { - const s = ipcStrings() - if (!method || typeof method !== 'string' || method.trim().length === 0) { - return { - ok: false, - code: -1, - data: null, - message: s.methodParamEmpty, - error: s.invalidMethodType, - pluginName, - method: String(method || '') - } - } - - const trimmedMethod = method.trim() - - const unwrapDllRawPayload = (raw: unknown, unwrapDataProperty: boolean): DllCapabilityResponse => { - let parsed: DynamicBridge = raw - if (typeof raw === 'string') { - try { - parsed = JSON.parse(raw) - } catch { - throw new Error(s.malformedDllResponse) - } - } - if (parsed && typeof parsed === 'object') { - if ('error' in parsed && parsed.error !== undefined && parsed.error !== null && parsed.error !== '') { - const errMsg = `DLL_ERROR: ${String(parsed.error)}` - return { - ok: false, - code: typeof parsed.code === 'number' ? parsed.code : -1, - data: null, - message: errMsg, - error: errMsg, - ...extractIpcErrorMeta(parsed), - ...extractIpcErrorMeta(parsed.error), - pluginName, - method: trimmedMethod, - fromFallback: false - } - } - if ('ok' in parsed && parsed.ok === false) { - const errMsg = `DLL_ERROR: ${String(parsed.error || parsed.message || s.unknownDllError)}` - return { - ok: false, - code: typeof parsed.code === 'number' ? parsed.code : -1, - data: null, - message: errMsg, - error: errMsg, - ...extractIpcErrorMeta(parsed), - ...extractIpcErrorMeta(parsed.error), - pluginName, - method: trimmedMethod, - fromFallback: false - } - } - const dataPayload = unwrapDataProperty && 'data' in parsed && parsed.data !== undefined ? parsed.data : parsed - return { - ok: true, - code: typeof parsed.code === 'number' ? parsed.code : 0, - data: dataPayload as T, - message: typeof parsed.message === 'string' ? parsed.message : undefined, - pluginName, - method: trimmedMethod, - fromFallback: false - } - } - return { - ok: true, - code: 0, - data: (parsed ?? null) as T, - pluginName, - method: trimmedMethod, - fromFallback: false - } - } - - const wrapCaughtDllError = (err: unknown): DllCapabilityResponse => { - const message = err instanceof Error ? err.message : String(err) - if (message.startsWith('MALFORMED_DLL_RESPONSE:')) { - throw err - } - const errMsg = `NATIVE_CALL_FAILED: ${message}` - return { - ok: false, - code: -1, - data: null, - message: errMsg, - error: errMsg, - ...extractIpcErrorMeta(err), - pluginName, - method: trimmedMethod, - fromFallback: false - } - } - - if (hostBridge && typeof hostBridge.invokeNative === 'function') { - try { - const raw = await hostBridge.invokeNative(pluginName, trimmedMethod, params) - return unwrapDllRawPayload(raw, true) - } catch (err: unknown) { - return wrapCaughtDllError(err) - } - } - - const runtimeHost = (hostBridge ?? (globalThis as Record).ztools) as - | { dllplugin?: { call?: (plugin: string, fn: string, payload: unknown) => Promise | unknown } } - | undefined - - const callFn = runtimeHost?.dllplugin?.call - if (typeof callFn === 'function') { - try { - const raw = await callFn.call(runtimeHost?.dllplugin, pluginName, trimmedMethod, params) - return unwrapDllRawPayload(raw, false) - } catch (err: unknown) { - return wrapCaughtDllError(err) - } - } - - const ipcRes = await callHostTransport( - 'dllplugin_call', - { - plugin: pluginName, - func: trimmedMethod, - params - }, - hostBridge - ) - - if (ipcRes.ok && ipcRes.data !== undefined && ipcRes.data !== null) { - return unwrapDllRawPayload(ipcRes.data, false) - } - - const isExplicitTransportFailure = - typeof ipcRes.error === 'string' && - ipcRes.error.length > 0 && - ipcRes.error !== 'NO_WINDOW_ENV' && - !ipcRes.error.startsWith('METHOD_NOT_AVAILABLE:') - - if ( - isRealElectronHost(hostBridge) || - isRealElectronHost() || - Boolean((hostBridge as DynamicBridge)?.__isRealHost) || - isExplicitTransportFailure - ) { - const errMsg = - ipcRes.error || s.hostIpcFailed(pluginName, trimmedMethod) - return { - ok: false, - code: -1, - data: null, - message: errMsg, - error: errMsg, - ...(ipcRes.errorCode ? { errorCode: ipcRes.errorCode } : {}), - ...(ipcRes.errorDetails ? { errorDetails: ipcRes.errorDetails } : {}), - pluginName, - method: trimmedMethod, - fromFallback: false - } - } - - if (typeof offlineFallback === 'function') { - const fallbackData = await offlineFallback() - return { - ok: true, - code: 0, - data: fallbackData, - pluginName, - method: trimmedMethod, - fromFallback: true - } - } - - const unavailableMsg = s.hostUnavailable(pluginName, trimmedMethod) - return { - ok: false, - code: -1, - data: null, - message: unavailableMsg, - error: unavailableMsg, - ...(ipcRes.errorCode ? { errorCode: ipcRes.errorCode } : {}), - ...(ipcRes.errorDetails ? { errorDetails: ipcRes.errorDetails } : {}), - pluginName, - method: trimmedMethod, - fromFallback: true - } -} - -export function formatBytes(bytes: number, decimals = 1): string { - const num = Number(bytes) - if (!Number.isFinite(num) || num <= 0) return '0 B' - if (num < 1024) return `${Math.round(num)} B` - const units = ['B', 'KB', 'MB', 'GB', 'TB'] - let val = num - let idx = 0 - while (val >= 1024 && idx < units.length - 1) { - val /= 1024 - idx += 1 - } - const safeDecimals = Math.max(0, Math.floor(decimals)) - return `${val >= 100 ? val.toFixed(0) : val.toFixed(safeDecimals)} ${units[idx]}` -} - -export function joinWinPath(...segments: string[]): string { - return segments - .filter(s => typeof s === 'string' && s.trim().length > 0) - .map((s, i) => (i === 0 ? s.replace(/[\\/]+$/, '') : s.replace(/^[\\/]+|[\\/]+$/g, ''))) - .join('\\') -} - -export interface RealEnvPaths { - home: string - userProfile: string - appData: string - localAppData: string - temp: string - downloads: string - documents: string - desktop: string - pictures: string - videos: string - music: string -} - -export async function getRealEnvPaths(hostOverride?: DynamicBridge): Promise { - const [homeRaw, appData, downloads, documents, desktop, pictures, videos, music] = await Promise.all([ - getRealSystemPath('home', hostOverride), - getRealSystemPath('appData', hostOverride), - getRealSystemPath('downloads', hostOverride), - getRealSystemPath('documents', hostOverride), - getRealSystemPath('desktop', hostOverride), - getRealSystemPath('pictures', hostOverride), - getRealSystemPath('videos', hostOverride), - getRealSystemPath('music', hostOverride) - ]) - const home = homeRaw || 'C:\\Users\\Default' - const isPosix = home.startsWith('/') - const tempRes = hostOverride ? await getRealSystemPath('temp', hostOverride) : '' - if (isPosix) { - return { - home, - userProfile: home, - appData: appData || `${home}/Library/Application Support`, - localAppData: `${home}/Library/Application Support`, - temp: tempRes || '/tmp', - downloads: downloads || `${home}/Downloads`, - documents: documents || `${home}/Documents`, - desktop: desktop || `${home}/Desktop`, - pictures: pictures || `${home}/Pictures`, - videos: videos || `${home}/Videos`, - music: music || `${home}/Music` - } - } - return { - home, - userProfile: home, - appData: appData || `${home}\\AppData\\Roaming`, - localAppData: `${home}\\AppData\\Local`, - temp: tempRes || `${home}\\AppData\\Local\\Temp`, - downloads: downloads || `${home}\\Downloads`, - documents: documents || `${home}\\Documents`, - desktop: desktop || `${home}\\Desktop`, - pictures: pictures || `${home}\\Pictures`, - videos: videos || `${home}\\Videos`, - music: music || `${home}\\Music` - } -} - -export const resolveRealSpecialPaths = getRealEnvPaths - -export async function readRealDirectory( - dirPath: string, - hostOverride?: DynamicBridge -): Promise { - if (!dirPath) return [] - const tree = await scanRealDirectoryTree(dirPath, { maxFiles: 120, hostOverride }) - const entries: RealIndexedFileEntry[] = [] - for (const s of tree.subdirs) { - entries.push( - normalizeIndexedFileEntry({ - name: s.name, - path: s.path, - isDir: true, - isDirectory: true, - size: s.totalBytes, - mtime: s.mtime - }) - ) - } - for (const f of tree.files) { - entries.push(f) - } - // scanRealDirectoryTree 已在 dir: 扫描无结果时退回一级目录读取;仍为空即目录不存在 / 为空 / 无权限,如实返回空列表 - return entries -} - -export async function moveRealFilesToTrash( - paths: string[], - hostOverride?: DynamicBridge -): Promise<{ - ok: boolean - trashedCount: number - deletedCount: number - failedPaths: string[] - error?: string -}> { - let deletedCount = 0 - const failedPaths: string[] = [] - let lastError: string | undefined - for (const p of paths) { - if (!p) continue - const res = await trashRealItem(p, hostOverride) - if (res.ok) { - deletedCount += 1 - } else { - failedPaths.push(p) - if (res.error) lastError = res.error - } - } - return { - ok: deletedCount > 0 || paths.length === 0, - trashedCount: deletedCount, - deletedCount, - failedPaths, - error: lastError - } -} - -const CAPABILITY_TO_PLUGIN_MAP: Record = { - 'mover.relocateWithJunction': { plugin: 'MoverPlugin', func: 'relocateWithJunction' }, - 'mover.scanCandidates': { plugin: 'MoverPlugin', func: 'scanCandidates' }, - 'recovery.restoreFile': { plugin: 'DataRecoveryPlugin', func: 'restoreFile' }, - 'recovery.scanDeletedFiles': { plugin: 'DataRecoveryPlugin', func: 'scanDeletedFiles' }, - 'shredder.secureWipeFile': { plugin: 'ShredderPlugin', func: 'secureWipeFile' }, - 'shredder.scanCandidates': { plugin: 'ShredderPlugin', func: 'scanCandidates' }, - 'backup.createSnapshotArchive': { plugin: 'SystemBackupPlugin', func: 'createSnapshotArchive' }, - 'backup.restoreSnapshotArchive': { plugin: 'SystemBackupPlugin', func: 'restoreSnapshotArchive' }, - 'backup.scanSnapshots': { plugin: 'SystemBackupPlugin', func: 'scanSnapshots' }, - 'sqlite.execute': { plugin: 'SqlitePlugin', func: 'execute' }, - 'sqlite.query': { plugin: 'SqlitePlugin', func: 'executeQuery' }, - 'sqlite.inspectWorkspace': { plugin: 'SqlitePlugin', func: 'inspectWorkspace' } -} - -export async function invokeHostCapability( - capability: string, - params: Record = {}, - hostOverride?: DynamicBridge -): Promise> { - const normalizedMethod = capability.replace(/\./g, '_') - - // 若测试显式注入了对应 normalizedMethod 的 mock 函数,优先调用测试桩 - if (hostOverride && typeof hostOverride[normalizedMethod] === 'function') { - const mockRes = await callHostTransport(normalizedMethod, params, hostOverride) - return { - ok: mockRes.ok, - code: mockRes.ok ? 0 : -1, - message: mockRes.ok ? 'OK' : mockRes.error || ipcStrings().callFailed, - data: mockRes.data, - error: mockRes.error, - ...(!mockRes.ok && mockRes.errorCode ? { errorCode: mockRes.errorCode } : {}), - ...(!mockRes.ok && mockRes.errorDetails ? { errorDetails: mockRes.errorDetails } : {}) - } - } - - if (capability === 'system.info') { - const drives = await probeRealDiskDrives(['C', 'D', 'E', 'F'], hostOverride) - return { - ok: true, - code: 0, - message: 'OK', - data: { - storage: drives.map(d => ({ - mount: d.drive, - fs: d.drive, - size: d.totalBytes, - total: d.totalBytes, - used: d.usedBytes, - available: d.availableBytes, - free: d.availableBytes, - percent: d.usagePercent - })) - } as unknown as T - } - } - if (capability === 'filesystem.deleteItem') { - const targetPath = String(params.path || params.fullPath || '') - const tr = await trashRealItem(targetPath, hostOverride) - const s = ipcStrings() - return { - ok: tr.ok, - code: tr.ok ? 0 : -1, - message: tr.ok ? s.movedToTrash : tr.error || s.deleteFailed, - error: tr.error, - ...(!tr.ok && tr.errorCode ? { errorCode: tr.errorCode } : {}), - ...(!tr.ok && tr.errorDetails ? { errorDetails: tr.errorDetails } : {}) - } - } - if (capability === 'system.showItemInFolder') { - const targetPath = String(params.path || params.fullPath || '') - const s = ipcStrings() - if (!targetPath) { - return { ok: false, code: -1, message: s.revealFailed } - } - const res = await callHostTransport('shell_show_item_in_folder', { fullPath: targetPath }, hostOverride) - return { - ok: res.ok, - code: res.ok ? 0 : -1, - message: res.ok ? s.revealedInFolder : res.error || s.revealFailed, - ...(!res.ok && res.error ? { error: res.error } : {}), - ...(!res.ok && res.errorCode ? { errorCode: res.errorCode } : {}), - ...(!res.ok && res.errorDetails ? { errorDetails: res.errorDetails } : {}) - } - } - if (capability === 'filesystem.openItem' || capability === 'system.openUrl') { - const target = String(params.path || params.url || params.fullPath || '') - const method = capability === 'system.openUrl' ? 'shell_open_external' : 'shell_open_path' - const res = await callHostTransport( - method, - capability === 'system.openUrl' ? { url: target } : { fullPath: target }, - hostOverride - ) - const s = ipcStrings() - return { - ok: res.ok, - code: res.ok ? 0 : -1, - message: res.ok ? s.opened : res.error || s.openFailed, - data: res.data, - error: res.error, - ...(!res.ok && res.errorCode ? { errorCode: res.errorCode } : {}), - ...(!res.ok && res.errorDetails ? { errorDetails: res.errorDetails } : {}) - } - } - - const pluginMapping = CAPABILITY_TO_PLUGIN_MAP[capability] - if (pluginMapping) { - const dllRes = await invokePluginService( - pluginMapping.plugin, - pluginMapping.func, - params, - hostOverride - ) - if (dllRes.ok) return dllRes - if (hostOverride) { - const fallbackMock = await callHostTransport(normalizedMethod, params, hostOverride) - if (fallbackMock.ok) { - return { - ok: true, - code: 0, - message: 'OK', - data: fallbackMock.data - } - } - } - return dllRes - } - - const res = await callHostTransport(normalizedMethod, params, hostOverride) - return { - ok: res.ok, - code: res.ok ? 0 : -1, - message: res.ok ? 'OK' : res.error || ipcStrings().callFailed, - data: res.data, - error: res.error, - ...(!res.ok && res.errorCode ? { errorCode: res.errorCode } : {}), - ...(!res.ok && res.errorDetails ? { errorDetails: res.errorDetails } : {}) - } -} - -export async function invokePluginService( - pluginName: string, - action: string, - params: Record = {}, - hostOverride?: DynamicBridge -): Promise> { - const s = ipcStrings() - // 1. 若测试注入了专门拦截 plugin_invoke 的 mock,支持调用 - if (hostOverride && typeof hostOverride.plugin_invoke === 'function') { - const mockRes = await callHostTransport( - 'plugin_invoke', - { plugin: pluginName, action, params }, - hostOverride - ) - return { - ok: mockRes.ok, - code: mockRes.ok ? 0 : -1, - message: mockRes.ok ? 'OK' : mockRes.error || s.pluginCallNotReady, - data: mockRes.data, - error: mockRes.error, - ...(!mockRes.ok && mockRes.errorCode ? { errorCode: mockRes.errorCode } : {}), - ...(!mockRes.ok && mockRes.errorDetails ? { errorDetails: mockRes.errorDetails } : {}) - } - } - - // 2. 优先走真实 Electron IPC 的 dllplugin_call 通道 - const dllRes = await callHostTransport( - 'dllplugin_call', - { plugin: pluginName, func: action, params }, - hostOverride - ) - if (dllRes.ok) { - const inner = dllRes.data - if (inner && typeof inner === 'object' && typeof inner.error === 'string' && inner.error.length > 0 && inner.ok !== true) { - return { - ok: false, - code: -1, - message: inner.error, - error: inner.error, - ...extractIpcErrorMeta(inner) - } - } - return { - ok: true, - code: 0, - message: 'OK', - data: inner as T - } - } - - // 3. 兼容单元测试中通过 transport.call('plugin_invoke') 注入的测试桩 - if (hostOverride) { - const legacyRes = await callHostTransport( - 'plugin_invoke', - { plugin: pluginName, action, params }, - hostOverride - ) - if (legacyRes.ok) { - return { - ok: true, - code: 0, - message: 'OK', - data: legacyRes.data - } - } - } - - // 4. 兼容旧版 globalThis.ztools.dllplugin.call - const g = globalThis as DynamicBridge - if (!hostOverride && typeof g?.ztools?.dllplugin?.call === 'function') { - try { - const raw = await g.ztools.dllplugin.call(pluginName, action, params) - if (raw && typeof raw === 'object' && raw.ok === false) { - return { - ok: false, - code: -1, - message: String(raw.error || s.callFailed), - error: String(raw.error || s.callFailed), - ...extractIpcErrorMeta(raw), - ...extractIpcErrorMeta(raw.error) - } - } - const data = raw && typeof raw === 'object' && 'data' in raw ? raw.data : raw - return { ok: true, code: 0, message: 'OK', data: data as T } - } catch (err: DynamicBridge) { - return { - ok: false, - code: -1, - message: err instanceof Error ? err.message : String(err), - error: err instanceof Error ? err.message : String(err), - ...extractIpcErrorMeta(err) - } - } - } - - return { - ok: false, - code: -1, - message: dllRes.error || s.pluginCallNotReady, - error: dllRes.error || s.pluginCallNotReady, - ...(dllRes.errorCode ? { errorCode: dllRes.errorCode } : {}), - ...(dllRes.errorDetails ? { errorDetails: dllRes.errorDetails } : {}) - } -} - -const SHA256_K = new Uint32Array([ - 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, - 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, - 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, - 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, - 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, - 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, - 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, - 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 -]) - -function rotr32(x: number, n: number): number { - return (x >>> n) | (x << (32 - n)) -} - -/** - * 标准 FIPS 180-4 SHA-256 真实字节摘要算法(返回 64 位小写 Hex) - */ -export function computeRealSha256Hex(input: string | Uint8Array): string { - const bytes = - typeof input === 'string' ? new TextEncoder().encode(input) : new Uint8Array(input || []) - const bitLen = bytes.length * 8 - const padLen = ((bytes.length + 9 + 63) & ~63) - const buf = new Uint8Array(padLen) - buf.set(bytes, 0) - buf[bytes.length] = 0x80 - const view = new DataView(buf.buffer) - view.setUint32(padLen - 8, Math.floor(bitLen / 0x100000000), false) - view.setUint32(padLen - 4, bitLen >>> 0, false) - - let h0 = 0x6a09e667 - let h1 = 0xbb67ae85 - let h2 = 0x3c6ef372 - let h3 = 0xa54ff53a - let h4 = 0x510e527f - let h5 = 0x9b05688c - let h6 = 0x1f83d9ab - let h7 = 0x5be0cd19 - - const w = new Uint32Array(64) - for (let offset = 0; offset < padLen; offset += 64) { - for (let i = 0; i < 16; i++) { - w[i] = view.getUint32(offset + i * 4, false) - } - for (let i = 16; i < 64; i++) { - const s0 = rotr32(w[i - 15], 7) ^ rotr32(w[i - 15], 18) ^ (w[i - 15] >>> 3) - const s1 = rotr32(w[i - 2], 17) ^ rotr32(w[i - 2], 19) ^ (w[i - 2] >>> 10) - w[i] = (w[i - 16] + s0 + w[i - 7] + s1) >>> 0 - } - - let a = h0 - let b = h1 - let c = h2 - let d = h3 - let e = h4 - let f = h5 - let g = h6 - let h = h7 - - for (let i = 0; i < 64; i++) { - const S1 = rotr32(e, 6) ^ rotr32(e, 11) ^ rotr32(e, 25) - const ch = (e & f) ^ (~e & g) - const temp1 = (h + S1 + ch + SHA256_K[i] + w[i]) >>> 0 - const S0 = rotr32(a, 2) ^ rotr32(a, 13) ^ rotr32(a, 22) - const maj = (a & b) ^ (a & c) ^ (b & c) - const temp2 = (S0 + maj) >>> 0 - - h = g - g = f - f = e - e = (d + temp1) >>> 0 - d = c - c = b - b = a - a = (temp1 + temp2) >>> 0 - } - - h0 = (h0 + a) >>> 0 - h1 = (h1 + b) >>> 0 - h2 = (h2 + c) >>> 0 - h3 = (h3 + d) >>> 0 - h4 = (h4 + e) >>> 0 - h5 = (h5 + f) >>> 0 - h6 = (h6 + g) >>> 0 - h7 = (h7 + h) >>> 0 - } - - return [h0, h1, h2, h3, h4, h5, h6, h7] - .map(v => (v >>> 0).toString(16).padStart(8, '0')) - .join('') -} - -/** - * 读取本地文件真实字节并计算标准 SHA-256:宿主 filesearch_sha256(只接受 path 字段)优先,Windows 上再试 FileComparePlugin。 - * 都拿不到时返回空字符串,由调用方提示失败;不再把文件按 UTF-8 文本读出来再算(二进制文件会算出错误的值)。 - */ -export async function computeRealFileSha256( - filePath: string, - hostOverride?: DynamicBridge -): Promise { - if (!filePath || !filePath.trim()) return '' - const target = filePath.trim() - - const shaRes = await callHostTransport('filesearch_sha256', { fullPath: target }, hostOverride) - if (shaRes.ok && shaRes.data) { - const hash = typeof shaRes.data === 'string' ? shaRes.data : String(shaRes.data?.sha256 || shaRes.data?.hash || '') - if (/^[0-9a-f]{64}$/i.test(hash)) return hash.toLowerCase() - } - - const dllRes = await invokePluginService('FileComparePlugin', 'computeFileSha256', { path: target }, hostOverride) - if (dllRes.ok && dllRes.data) { - const hash = typeof dllRes.data === 'string' ? dllRes.data : String(dllRes.data?.sha256 || dllRes.data?.hash || '') - if (/^[0-9a-f]{64}$/i.test(hash)) return hash.toLowerCase() - } - - return '' -} - -export async function readRealClipboardText(hostOverride?: DynamicBridge): Promise { - const res = await callHostTransport('clipboard_read_text', {}, hostOverride) - if (res.ok && res.data !== undefined && res.data !== null) { - if (typeof res.data === 'string') return res.data - if (typeof res.data?.text === 'string') return res.data.text - } - try { - if (typeof navigator !== 'undefined' && navigator.clipboard?.readText) { - return await navigator.clipboard.readText() - } - } catch { - // ignore - } - return '' -} - -export async function writeRealClipboardText(text: string, hostOverride?: DynamicBridge): Promise { - const payload = { text: String(text || '') } - const res = await callHostTransport('clipboard_copy_text', payload, hostOverride) - if (res.ok) return true - const fallbackRes = await callHostTransport('clipboard_write_text', payload, hostOverride) - if (fallbackRes.ok) return true - try { - if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) { - await navigator.clipboard.writeText(String(text || '')) - return true - } - } catch { - // ignore - } - return false -} - -export async function showRealToast( - title: string, - style: 'success' | 'failure' | 'info' = 'info' -): Promise { - try { - const { showToast, Toast } = await import('@ztools/declarative-ui') - await showToast({ - title, - style: - style === 'success' - ? Toast.Style.Success - : style === 'failure' - ? Toast.Style.Failure - : Toast.Style.Animated - }) - } catch { - // ignore - } -} - diff --git a/extensions/multi-download/src/tool-runtime.ts b/extensions/multi-download/src/tool-runtime.ts new file mode 100644 index 00000000..29670de2 --- /dev/null +++ b/extensions/multi-download/src/tool-runtime.ts @@ -0,0 +1,637 @@ +/** + * 宿主薄原语与基础系统能力传输层(唯一权威公共源文件,纯标准 IPC,零原生 DLL 依赖) + * + * 修改本文件后需同步复制到各使用插件的 src/tool-runtime.ts, + * 构建脚本 build-declarative.mjs 会在编译前校验副本与本文件一字不差。 + */ + +import { getHostTransport } from '@ztools/declarative-ui' + +export type ToolCapabilityStatus = 'ready' | 'needs_provisioning' | 'unsupported' + +export interface ToolCapabilityDescriptor { + readonly primitiveId: string + readonly domain: string + readonly summary: string + readonly ipcMethods: readonly string[] + readonly requiredPermissions: readonly string[] + readonly status: ToolCapabilityStatus + readonly optionalExtensions: readonly string[] +} + +export interface ToolRuntimeCapabilitiesSnapshot { + readonly contractVersion: number + readonly platform: 'windows' | 'macos' | 'other' + readonly domains: readonly string[] + readonly capabilities: readonly ToolCapabilityDescriptor[] +} + +export interface ToolRuntimeEnsureResult { + readonly primitiveId: string + readonly status: ToolCapabilityStatus + readonly provisioned: boolean +} + +export interface ToolCapabilitiesEnsureResult { + readonly ok: boolean + readonly status: ToolCapabilityStatus + readonly provisioned: boolean + readonly failedPrimitiveId?: string + readonly error?: string + readonly errorCode?: string + readonly errorDetails?: Record +} + +export interface ToolTaskCancelResult { + readonly taskId: string + readonly cancelled: boolean +} + +export interface ToolPathSlot { + readonly grantId?: string + readonly relativePath?: string + readonly path?: string +} + +export interface ToolProgressEvent { + readonly taskId: string + readonly primitiveId?: string + readonly phase: 'provisioning' | 'running' | 'finalizing' | 'completed' | 'cancelled' | 'failed' + readonly percent?: number + readonly transferredBytes?: number + readonly totalBytes?: number + readonly speedBytesPerSec?: number + readonly stage?: string + readonly errorCode?: string + readonly retryable?: boolean + readonly userAction?: string + readonly message?: string + readonly timestamp?: number +} + +export type MediaTranscodeRunResult = + | { readonly status: 'done'; readonly outputBytes: number; readonly durationMs: number } + | { readonly status: 'cancelled' } + | { + readonly status: 'failed' + readonly error?: string + readonly errorCode?: string + readonly errorDetails?: Record + } + +export interface HostTransportResult { + ok: boolean + data?: T + error?: string + errorCode?: string + errorDetails?: Record +} + +export interface HostCallOptions { + timeoutMs?: number +} + +type TransportMethodFn = (req: { messageId: string; params: Record; timeoutMs?: number }) => Promise + +interface WindowHostBridge { + __ztoolsElectron?: { + transport?: { + methods?: Record + } + } + ztools?: { + transport?: { + methods?: Record + call?: (method: string, params: Record, options?: { timeoutMs?: number }) => Promise + } + events?: { + subscribe?: (event: string) => Promise | void + on?: (event: string, cb: (payload: unknown) => void) => (() => void) | void + off?: (event: string, cb: (payload: unknown) => void) => void + } + } +} + +interface HostOverrideLike { + transport?: { + call?: (method: string, params: Record, options?: { timeoutMs?: number }) => Promise + } + [method: string]: unknown +} + +let reqSeq = 1 + +export function nextMessageId(prefix = 'tool'): string { + reqSeq = (reqSeq + 1) % 1_000_000 + return `${prefix}_${Date.now()}_${reqSeq}` +} + +export function asRecord(value: unknown): Record | null { + return value && typeof value === 'object' && !Array.isArray(value) + ? (value as Record) + : null +} + +function extractErrorMeta(errObj: unknown): { + errorCode?: string + errorDetails?: Record +} { + const rec = asRecord(errObj) + if (!rec) return {} + const errorCode = + typeof rec.errorCode === 'string' && rec.errorCode.trim() + ? rec.errorCode.trim() + : typeof rec.code === 'string' && rec.code.trim() + ? rec.code.trim() + : undefined + const rawDetails = asRecord(rec.errorDetails) ?? asRecord(rec.details) ?? undefined + return { + ...(errorCode ? { errorCode } : {}), + ...(rawDetails ? { errorDetails: rawDetails } : {}) + } +} + +function toTransportError(err: unknown): HostTransportResult { + return { + ok: false, + error: err instanceof Error ? err.message : String(err), + ...extractErrorMeta(err) + } +} + +function buildFailureResult(rec: Record, fallbackMsg: string): HostTransportResult { + const errObj = asRecord(rec.error) + const errMsg = errObj + ? String(errObj.message || errObj.code || JSON.stringify(errObj)) + : String(rec.error || rec.message || fallbackMsg) + return { ok: false, error: errMsg, ...extractErrorMeta(rec), ...extractErrorMeta(errObj) } +} + +function unwrapTransportResponse(raw: unknown): HostTransportResult { + if (raw === null || raw === undefined) { + return { ok: false, error: 'EMPTY_IPC_RESPONSE', errorCode: 'EMPTY_IPC_RESPONSE' } + } + if (typeof raw !== 'object') { + return { ok: true, data: raw as T } + } + const outer = asRecord(raw) + if (!outer) { + return { ok: true, data: raw as T } + } + if (outer.success === false || outer.ok === false) { + return buildFailureResult(outer, 'IPC_CALL_FAILED') + } + + const firstLayer = 'data' in outer && outer.data !== undefined ? outer.data : outer + const inner = asRecord(firstLayer) + if (inner) { + if (inner.success === false || inner.ok === false) { + return buildFailureResult(inner, 'IPC_INNER_FAILED') + } + if ('data' in inner && inner.data !== undefined) { + return { ok: true, data: inner.data as T } + } + } + + return { ok: true, data: firstLayer as T } +} + +/** 判断当前是否处于真实的 ZTools Electron 渲染进程宿主环境 */ +export function isRealElectronHost(hostOverride?: unknown): boolean { + if (hostOverride) return true + if (typeof window === 'undefined') return false + const w = window as unknown as WindowHostBridge + return Boolean( + w.__ztoolsElectron?.transport?.methods || + w.ztools?.transport?.call || + w.ztools?.transport?.methods + ) +} + +/** 统一调用宿主 IPC 传输层(优先测试桩,其次 declarative-ui 宿主通道与 preload 通道) */ +export async function callHostTransport( + method: string, + params: Record = {}, + hostOverride?: unknown, + options?: HostCallOptions +): Promise> { + const override = asRecord(hostOverride) as HostOverrideLike | null + if (override) { + const directFn = override[method] + if (typeof directFn === 'function') { + try { + return unwrapTransportResponse(await (directFn as (p: Record) => Promise)(params)) + } catch (err) { + return toTransportError(err) + } + } + if (typeof override.transport?.call === 'function') { + try { + return unwrapTransportResponse(await override.transport.call(method, params, options)) + } catch (err) { + return toTransportError(err) + } + } + return { ok: false, error: `METHOD_NOT_AVAILABLE: ${method}`, errorCode: 'METHOD_NOT_AVAILABLE' } + } + + // 优先走 declarative-ui 运行时注入的带归属令牌通道 + if (typeof getHostTransport === 'function') { + const transport = getHostTransport() + if (transport) { + try { + const callOpts = typeof options?.timeoutMs === 'number' ? { timeoutMs: options.timeoutMs } : undefined + return unwrapTransportResponse(await transport.call(method, params, callOpts)) + } catch (err) { + return toTransportError(err) + } + } + } + + if (typeof window === 'undefined') { + return { ok: false, error: 'NO_WINDOW_ENV', errorCode: 'NO_WINDOW_ENV' } + } + + const w = window as unknown as WindowHostBridge + const methods = w.__ztoolsElectron?.transport?.methods || w.ztools?.transport?.methods + const fn = methods?.[method] + if (typeof fn === 'function') { + try { + const messageId = nextMessageId(method.replace(/[^A-Za-z0-9_]/g, '_').slice(0, 24)) + const payload = { + messageId, + params, + ...(typeof options?.timeoutMs === 'number' ? { timeoutMs: options.timeoutMs } : {}) + } + return unwrapTransportResponse(await fn(payload)) + } catch (err) { + return toTransportError(err) + } + } + + if (typeof w.ztools?.transport?.call === 'function') { + try { + return unwrapTransportResponse(await w.ztools.transport.call(method, params, options)) + } catch (err) { + return toTransportError(err) + } + } + + return { ok: false, error: `METHOD_NOT_AVAILABLE: ${method}`, errorCode: 'METHOD_NOT_AVAILABLE' } +} + +/** 探测宿主薄原语能力快照(tool_runtime_capabilities) */ +export async function queryRuntimeCapabilities( + hostOverride?: unknown +): Promise> { + const res = await callHostTransport('tool_runtime_capabilities', {}, hostOverride) + if (!res.ok) return res as HostTransportResult + const rec = asRecord(res.data) + if (!rec || !Array.isArray(rec.capabilities)) { + return { + ok: false, + error: 'INVALID_CAPABILITIES_SNAPSHOT', + errorCode: 'INVALID_CAPABILITIES_SNAPSHOT' + } + } + const capabilities: ToolCapabilityDescriptor[] = [] + for (const rawCap of rec.capabilities) { + const cap = asRecord(rawCap) + if (!cap || typeof cap.primitiveId !== 'string') continue + const rawStatus = cap.status + const status: ToolCapabilityStatus = + rawStatus === 'ready' || rawStatus === 'needs_provisioning' || rawStatus === 'unsupported' + ? rawStatus + : 'unsupported' + const optionalExtensions = Array.isArray(cap.optionalExtensions) + ? cap.optionalExtensions.filter((e): e is string => typeof e === 'string' && e.trim().length > 0) + : [] + capabilities.push({ + primitiveId: cap.primitiveId, + domain: typeof cap.domain === 'string' ? cap.domain : '', + summary: typeof cap.summary === 'string' ? cap.summary : '', + ipcMethods: Array.isArray(cap.ipcMethods) ? cap.ipcMethods.filter((m): m is string => typeof m === 'string') : [], + requiredPermissions: Array.isArray(cap.requiredPermissions) + ? cap.requiredPermissions.filter((p): p is string => typeof p === 'string') + : [], + status, + optionalExtensions + }) + } + const platform = + rec.platform === 'windows' || rec.platform === 'macos' || rec.platform === 'other' + ? rec.platform + : 'other' + return { + ok: true, + data: { + contractVersion: typeof rec.contractVersion === 'number' ? rec.contractVersion : 1, + platform, + domains: Array.isArray(rec.domains) ? rec.domains.filter((d): d is string => typeof d === 'string') : [], + capabilities + } + } +} + +export function findCapability( + snapshot: ToolRuntimeCapabilitiesSnapshot | null | undefined, + primitiveId: string +): ToolCapabilityDescriptor | null { + if (!snapshot) return null + return snapshot.capabilities.find((c) => c.primitiveId === primitiveId) ?? null +} + +export function hasCapabilityExtension( + snapshot: ToolRuntimeCapabilitiesSnapshot | null | undefined, + primitiveId: string, + extensionName: string +): boolean { + const cap = findCapability(snapshot, primitiveId) + return Boolean(cap && cap.optionalExtensions.includes(extensionName)) +} + +/** 按需拉取并准备指定薄原语运行组件(tool_runtime_ensure) */ +export async function ensureRuntimeCapability( + primitiveId: string, + hostOverride?: unknown +): Promise> { + return callHostTransport('tool_runtime_ensure', { primitiveId }, hostOverride) +} + +/** 顺序按需准备多个薄原语运行组件,任一项未就绪即中止并聚合 provisioned 标记 */ +export async function ensureRuntimeCapabilities( + primitiveIds: readonly string[], + hostOverride?: unknown +): Promise { + let provisionedAny = false + for (const primitiveId of primitiveIds) { + const res = await ensureRuntimeCapability(primitiveId, hostOverride) + if (!res.ok || !res.data || res.data.status !== 'ready') { + return { + ok: false, + status: res.data?.status ?? 'unsupported', + provisioned: provisionedAny, + failedPrimitiveId: primitiveId, + error: res.error, + errorCode: res.errorCode, + errorDetails: res.errorDetails + } + } + if (res.data.provisioned) provisionedAny = true + } + return { ok: true, status: 'ready', provisioned: provisionedAny } +} + +/** 取消正在执行的宿主薄原语任务(tool_task_cancel) */ +export async function cancelRuntimeTask( + taskId: string, + hostOverride?: unknown +): Promise> { + return callHostTransport('tool_task_cancel', { taskId }, hostOverride) +} + +/** 判断错误码是否表示用户主动取消任务 */ +export function isTaskCancelledCode(errorCode?: string): boolean { + const code = (errorCode || '').trim().toUpperCase() + return code === 'TOOL_TASK_CANCELLED' || code === 'CANCELLED' || code === 'OPERATION_CANCELLED' +} + +/** 执行单个媒体转码任务(tool_media_transcode_run),统一处理取消与产物字节数校验 */ +export async function runMediaTranscodeTask( + payload: Record, + hostOverride?: unknown +): Promise { + const res = await callHostTransport('tool_media_transcode_run', payload, hostOverride) + if (!res.ok) { + if (isTaskCancelledCode(res.errorCode)) { + return { status: 'cancelled' } + } + return { + status: 'failed', + error: res.error, + errorCode: res.errorCode, + errorDetails: res.errorDetails + } + } + const rec = asRecord(res.data) + const outputBytes = Number(rec?.outputBytes) + const durationMs = Number(rec?.durationMs) + if (!Number.isFinite(outputBytes) || outputBytes <= 0) { + return { status: 'failed', error: 'EMPTY_OUTPUT', errorCode: 'EMPTY_OUTPUT' } + } + return { + status: 'done', + outputBytes, + durationMs: Number.isFinite(durationMs) && durationMs >= 0 ? durationMs : 0 + } +} + +/** 订阅宿主推送的 tool_runtime_progress 任务进度事件 */ +export function subscribeRuntimeProgress( + handler: (event: ToolProgressEvent) => void +): () => void { + if (typeof window === 'undefined') return () => undefined + const w = window as unknown as WindowHostBridge + const eventsApi = w.ztools?.events + if (!eventsApi || typeof eventsApi.on !== 'function') return () => undefined + + try { + void eventsApi.subscribe?.('tool_runtime_progress') + } catch (err) { + // 某些测试桩或旧渲染层可能未提供 subscribe,继续注册 on 监听 + void err + } + + const listener = (raw: unknown) => { + const outer = asRecord(raw) + if (!outer) return + const inner = asRecord(outer.payload) ?? outer + if (typeof inner.taskId !== 'string' || typeof inner.phase !== 'string') return + handler(inner as unknown as ToolProgressEvent) + } + + const off = eventsApi.on('tool_runtime_progress', listener) + return () => { + if (typeof off === 'function') { + off() + } else if (typeof eventsApi.off === 'function') { + eventsApi.off('tool_runtime_progress', listener) + } + } +} + +/** 订阅旧版宿主 plugin_files_dropped 拖拽回退事件并返回卸载函数 */ +export function subscribeLegacyFileDrop(onDrop: (envelope: unknown) => void): () => void { + if (typeof window === 'undefined') return () => undefined + const w = window as unknown as WindowHostBridge + const eventsApi = w.ztools?.events + if (!eventsApi || typeof eventsApi.on !== 'function') return () => undefined + + const off = eventsApi.on('plugin_files_dropped', onDrop) + return () => { + if (typeof off === 'function') { + off() + } else if (typeof eventsApi.off === 'function') { + eventsApi.off('plugin_files_dropped', onDrop) + } + } +} + +/** 字节数格式化 */ +export function formatBytes(bytes: number): string { + if (!Number.isFinite(bytes) || bytes < 0) return '0 B' + if (bytes < 1024) return `${Math.round(bytes)} B` + const units = ['KB', 'MB', 'GB', 'TB'] + let value = bytes / 1024 + let idx = 0 + while (value >= 1024 && idx < units.length - 1) { + value /= 1024 + idx += 1 + } + return `${value >= 100 ? value.toFixed(0) : value >= 10 ? value.toFixed(1) : value.toFixed(2)} ${units[idx]}` +} + +/** 字节数格式化别名(兼容 archive-manager 等插件既有导出名) */ +export function formatByteCount(bytes: number): string { + return formatBytes(bytes) +} + +/** 获取系统标准目录路径(支持 Windows 与 macOS) */ +export async function getRealSystemPath( + name: 'home' | 'desktop' | 'documents' | 'downloads' | 'music' | 'pictures' | 'videos' | 'temp', + hostOverride?: unknown +): Promise { + const res = await callHostTransport('system_get_path', { name }, hostOverride) + if (res.ok && res.data) { + if (typeof res.data === 'string' && res.data.trim()) return res.data.trim() + const rec = asRecord(res.data) + if (rec && typeof rec.path === 'string' && rec.path.trim()) return rec.path.trim() + } + return '' +} + +/** 读取剪贴板文本 */ +export async function readRealClipboardText(hostOverride?: unknown): Promise { + const res = await callHostTransport('clipboard_read_text', {}, hostOverride) + if (res.ok && res.data !== undefined && res.data !== null) { + if (typeof res.data === 'string') return res.data + const rec = asRecord(res.data) + if (rec && typeof rec.text === 'string') return rec.text + } + return '' +} + +/** 写入剪贴板文本 */ +export async function writeRealClipboardText(text: string, hostOverride?: unknown): Promise { + const res = await callHostTransport('clipboard_copy_text', { text: String(text || '') }, hostOverride) + return res.ok +} + +/** 在系统文件管理器中显示文件 */ +export async function showRealItemInFolder(fullPath: string, hostOverride?: unknown): Promise { + if (!fullPath) return false + const res = await callHostTransport('shell_show_item_in_folder', { fullPath }, hostOverride) + return res.ok +} + +/** 用系统默认应用打开文件或文件夹 */ +export async function openRealPath(fullPath: string, hostOverride?: unknown): Promise { + if (!fullPath) return false + const res = await callHostTransport('shell_open_path', { fullPath }, hostOverride) + return res.ok +} + +/** 将文件或目录移入系统回收站 */ +export async function trashRealItem(fullPath: string, hostOverride?: unknown): Promise<{ ok: boolean; error?: string }> { + if (!fullPath) return { ok: false, error: 'EMPTY_PATH' } + const res = await callHostTransport('shell_trash_item', { fullPath }, hostOverride) + return res.ok ? { ok: true } : { ok: false, error: res.error } +} + +/** 通过 window_show_open_dialog 选择输出目录(兼容 Windows 与 macOS) */ +export async function pickOutputDirectoryDialog( + options: { title: string; defaultPath?: string }, + hostOverride?: unknown +): Promise<{ canceled: boolean; directoryPath?: string; error?: string; errorCode?: string }> { + const params: Record = { + title: options.title, + properties: ['openDirectory', 'createDirectory'] + } + if (options.defaultPath) params.defaultPath = options.defaultPath + const res = await callHostTransport('window_show_open_dialog', params, hostOverride) + if (!res.ok) { + return { canceled: false, error: res.error || 'OPEN_DIALOG_FAILED', errorCode: res.errorCode } + } + const rec = asRecord(res.data) + if (!rec) return { canceled: false, error: 'INVALID_DIALOG_RESULT' } + if (rec.canceled === true) return { canceled: true } + const firstPath = + (Array.isArray(rec.filePaths) && typeof rec.filePaths[0] === 'string' && rec.filePaths[0].trim()) || + (typeof rec.filePath === 'string' && rec.filePath.trim()) || + (typeof rec.folderPath === 'string' && rec.folderPath.trim()) || + '' + if (!firstPath) return { canceled: false, error: 'NO_DIRECTORY_SELECTED' } + return { canceled: false, directoryPath: firstPath } +} + +/** 通用文件/目录选择对话框(支持自定义 properties 与 filters) */ +export async function openDialogSelectPaths( + options: { + title: string + properties: Array<'openFile' | 'openDirectory' | 'multiSelections' | 'createDirectory'> + filters?: Array<{ name: string; extensions: string[] }> + }, + hostOverride?: unknown +): Promise<{ canceled: boolean; paths: string[]; error?: string }> { + const params: Record = { + title: options.title, + properties: options.properties, + ...(options.filters ? { filters: options.filters } : {}) + } + const res = await callHostTransport('window_show_open_dialog', params, hostOverride) + if (!res.ok) return { canceled: false, paths: [], error: res.error || 'OPEN_DIALOG_FAILED' } + const rec = asRecord(res.data) + if (!rec) return { canceled: false, paths: [], error: 'INVALID_DIALOG_RESPONSE' } + if (rec.canceled === true) return { canceled: true, paths: [] } + const paths = Array.isArray(rec.filePaths) + ? rec.filePaths.filter((p): p is string => typeof p === 'string' && p.trim().length > 0).map((p) => p.trim()) + : typeof rec.filePath === 'string' && rec.filePath.trim() + ? [rec.filePath.trim()] + : [] + return { canceled: false, paths } +} + +/** 选择待归档的源文件或目录列表(多选) */ +export async function pickAnySourcesDialog( + options: { title: string; directories?: boolean }, + hostOverride?: unknown +): Promise<{ canceled: boolean; paths: string[]; error?: string }> { + return openDialogSelectPaths( + { + title: options.title, + properties: options.directories ? ['openDirectory', 'multiSelections'] : ['openFile', 'multiSelections'] + }, + hostOverride + ) +} + +/** 保存归档文件对话框(zip / 7z / tar) */ +export async function pickSaveArchiveDialog( + options: { title: string; defaultPath?: string; format: 'zip' | '7z' | 'tar' }, + hostOverride?: unknown +): Promise<{ canceled: boolean; filePath?: string; error?: string }> { + const ext = options.format === '7z' ? '7z' : options.format === 'tar' ? 'tar' : 'zip' + const params: Record = { + title: options.title, + filters: [{ name: `${ext.toUpperCase()} Archive`, extensions: [ext] }] + } + if (options.defaultPath) params.defaultPath = options.defaultPath + const res = await callHostTransport('window_show_save_dialog', params, hostOverride) + if (!res.ok) return { canceled: false, error: res.error || 'SAVE_DIALOG_FAILED' } + const rec = asRecord(res.data) + if (!rec) return { canceled: false, error: 'INVALID_SAVE_DIALOG' } + if (rec.canceled === true) return { canceled: true } + const filePath = typeof rec.filePath === 'string' ? rec.filePath.trim() : '' + if (!filePath) return { canceled: true } + return { canceled: false, filePath } +} diff --git a/extensions/multi-download/tests/multi-download.host.test.mjs b/extensions/multi-download/tests/multi-download.host.test.mjs index f2d9b152..365eb4c1 100644 --- a/extensions/multi-download/tests/multi-download.host.test.mjs +++ b/extensions/multi-download/tests/multi-download.host.test.mjs @@ -1,15 +1,20 @@ -// 本插件业务逻辑的宿主集成测试:用宿主替身与可注入的 fetch 模拟客户端与本机 aria2,覆盖成功与各类失败路径 +// 多线程下载宿主薄原语逻辑测试:覆盖多线程下载、暂停/恢复/取消、不支持协议拒绝、目录选择与无宿主报错 import test from 'node:test' import assert from 'node:assert/strict' -import { setRuntimeLocale } from '@ztools/declarative-ui' +import fs from 'node:fs' +import path from 'node:path' +import { fileURLToPath } from 'node:url' +import { LocalStorage, setRuntimeLocale } from '@ztools/declarative-ui' import * as multiDownload from '../dist/logic.js' setRuntimeLocale('zh-CN') -function createRealHostStub(handlers = {}) { +const __dirname = path.dirname(fileURLToPath(import.meta.url)) + +function createHostStub(handlers = {}) { const calls = [] const dispatch = async (method, params) => { - calls.push({ channel: method, payload: params }) + calls.push({ method, params }) if (typeof handlers[method] === 'function') { return await handlers[method](params) } @@ -18,307 +23,232 @@ function createRealHostStub(handlers = {}) { } throw new Error(`CHANNEL_NOT_IMPLEMENTED: ${method}`) } - const stub = { - __isRealHost: true, calls, - transport: { - call: dispatch - } + transport: { call: dispatch } } - for (const key of Object.keys(handlers)) { stub[key] = (params) => dispatch(key, params) } - return stub } -const called = (host, channel) => host.calls.filter((c) => c.channel === channel) -const preset16 = multiDownload.getThreadSplitPresets()[0] - -/** 模拟本机 aria2 JSON-RPC:按 method 返回响应体,记录请求 */ -function aria2Fetch(responder) { - const requests = [] - const impl = async (url, init) => { - const body = JSON.parse(init.body) - requests.push({ url, body }) - const { status = 200, json } = await responder(body) - return { ok: status >= 200 && status < 300, status, json: async () => json } - } - impl.requests = requests - return impl -} -const aria2Offline = async () => { - throw new TypeError('fetch failed: connect ECONNREFUSED 127.0.0.1:6800') -} - -test('multi-download: 挂载快照只读取下载路径、磁盘空间、aria2 状态与剪贴板,不扫描目录', async () => { - const host = createRealHostStub({ - system_get_path: () => 'C:\\Users\\RealUser\\Downloads', - system_get_disk_usage: () => ({ total: 500 * 1024 ** 3, used: 377 * 1024 ** 3, available: 123 * 1024 ** 3, percent: 75 }), - clipboard_read_text: () => 'magnet:?xt=urn:btih:0123456789abcdef0123456789abcdef01234567' - }) - const fetchImpl = aria2Fetch(() => ({ json: { jsonrpc: '2.0', id: 'x', result: { version: '1.37.0' } } })) - - const snap = await multiDownload.fetchMultiDownloadSnapshot(host, { fetchImpl }) - assert.equal(snap.downloadDir, 'C:\\Users\\RealUser\\Downloads') - assert.equal(snap.driveInfoAvailable, true) - assert.equal(snap.driveFreeBytes, 123 * 1024 ** 3) - assert.deepEqual(snap.files, []) - assert.equal(snap.totalSizeBytes, 0) - assert.equal(snap.aria2Status.online, true) - assert.equal(snap.aria2Status.version, '1.37.0') - assert.equal(snap.sniffedProtocol, '磁力链接') - assert.equal(fetchImpl.requests[0].url, 'http://127.0.0.1:6800/jsonrpc') - assert.equal(fetchImpl.requests[0].body.method, 'aria2.getVersion') - assert.equal(multiDownload.isDriveLowOnSpace(snap), false) - assert.equal(called(host, 'system_search_files').length, 0) - assert.equal(called(host, 'filesystem_get_directory_contents').length, 0) - assert.equal(called(host, 'system_list_common_folders').length, 0) - assert.deepEqual(called(host, 'system_get_path').map((c) => c.payload.name), ['downloads']) -}) - -test('multi-download: 导入规则不限扩展名且保留既有分类统计,未知大小不填 0', () => { - assert.equal(multiDownload.MULTI_DOWNLOAD_IMPORT_RULES.extensions, undefined) - const items = [ - multiDownload.toDownloadedFileItem({ - path: 'D:\\DL\\setup.exe', - name: 'setup.exe', - parentDir: 'D:\\DL', - extension: '.exe', - sizeBytes: 1024, - lastModifiedMs: 100 - }), - multiDownload.toDownloadedFileItem({ - path: 'D:\\DL\\bundle.tar', - name: 'bundle.tar', - parentDir: 'D:\\DL', - extension: '.tar', - sizeBytes: null, - lastModifiedMs: null - }), - multiDownload.createClientDownloadedItem('D:\\DL\\ubuntu.iso', 4096) - ] - assert.equal(items[0].category, 'installer') - assert.equal(items[1].category, 'archive') - assert.equal(items[1].sizeBytes, null) - assert.equal(items[2].category, 'iso_image') - - const stats = multiDownload.computeDownloadStats(items) - assert.equal(stats.totalSizeBytes, 5120) - assert.equal(stats.categoryStats.find((s) => s.category === 'archive')?.count, 1) +const callsOf = (host, method) => host.calls.filter((c) => c.method === method) + +test('multi-download: plugin.json 符合双端薄原语规范且无 draft/dllloader 遗留', () => { + const manifest = JSON.parse(fs.readFileSync(path.join(__dirname, '..', 'plugin.json'), 'utf8')) + assert.deepEqual(manifest.requiredCapabilities, ['download.transfer']) + assert.equal(manifest.minAppVersion, '1.3.0.0') + assert.equal(manifest.draft, undefined) + assert.equal(manifest.draftReason, undefined) + assert.deepEqual(manifest.nativeComponents, []) + assert.deepEqual( + manifest.targets.map((item) => item.id).sort(), + ['macos-electron-any', 'windows-electron-any'] + ) }) -test('multi-download: 磁盘空间读不到或下载路径为空时不拿别的盘冒充;aria2 拒绝时如实记录原因', async () => { - const noPath = await multiDownload.fetchMultiDownloadSnapshot( - createRealHostStub({ - system_get_path: () => '', - system_get_disk_usage: () => ({ total: 100, used: 10, available: 90 }), - clipboard_read_text: () => '' +test('multi-download: 正常多线程 HTTP/HTTPS 下载、暂停、恢复、取消与状态查询真相源', async () => { + const tasks = new Map() + const host = createHostStub({ + tool_runtime_capabilities: () => ({ + contractVersion: 1, + platform: 'windows', + domains: ['download'], + capabilities: [ + { + primitiveId: 'download.transfer', + domain: 'download', + summary: 'Multi-connection transfer', + ipcMethods: [ + 'tool_download_transfer_add', + 'tool_download_transfer_pause', + 'tool_download_transfer_resume', + 'tool_download_transfer_cancel', + 'tool_download_transfer_status' + ], + requiredPermissions: ['network'], + status: 'ready', + optionalExtensions: ['resumable-persist'] + } + ] }), - { fetchImpl: aria2Offline } - ) - assert.equal(noPath.downloadDir, '') - assert.equal(noPath.driveInfoAvailable, false) - - const host = createRealHostStub({ - system_get_path: () => 'D:\\Downloads', - system_get_disk_usage: ({ drive }) => { - if (drive.startsWith('C')) return { total: 100, used: 10, available: 90 } - throw new Error('无法读取磁盘') + tool_download_transfer_add: (params) => { + const record = { + taskId: params.taskId || 'dl_1', + url: params.url, + fileName: params.fileName || 'ubuntu.iso', + state: 'running', + downloadedBytes: 1024, + totalBytes: 1048576, + speedBytesPerSec: 524288, + connections: params.maxConnections, + createdAt: 1000, + updatedAt: 1001 + } + tasks.set(record.taskId, record) + return record + }, + tool_download_transfer_pause: ({ taskId }) => { + const next = { ...tasks.get(taskId), state: 'paused', speedBytesPerSec: 0, updatedAt: 1002 } + tasks.set(taskId, next) + return next + }, + tool_download_transfer_resume: ({ taskId }) => { + const next = { ...tasks.get(taskId), state: 'running', speedBytesPerSec: 262144, updatedAt: 1003 } + tasks.set(taskId, next) + return next }, - clipboard_read_text: () => '' + tool_download_transfer_cancel: ({ taskId }) => { + const next = { ...tasks.get(taskId), state: 'cancelled', speedBytesPerSec: 0, updatedAt: 1004 } + tasks.set(taskId, next) + return next + }, + tool_download_transfer_status: ({ taskId } = {}) => ({ + tasks: taskId ? [tasks.get(taskId)].filter(Boolean) : Array.from(tasks.values()) + }) }) - const fetchImpl = aria2Fetch(() => ({ status: 400, json: { jsonrpc: '2.0', id: 'x', error: { code: 1, message: 'Unauthorized' } } })) - const snap = await multiDownload.fetchMultiDownloadSnapshot(host, { fetchImpl }) - assert.equal(snap.driveInfoAvailable, false) - assert.equal(snap.driveFreeBytes, 0) - assert.equal(multiDownload.isDriveLowOnSpace(snap), false) - assert.equal(snap.aria2Status.online, false) - assert.equal(snap.aria2Status.error, 'aria2 返回错误') - - const offline = await multiDownload.probeAria2JsonRpc({ fetchImpl: aria2Offline }) - assert.equal(offline.online, false) - assert.match(offline.error, /ECONNREFUSED/) - assert.equal( - multiDownload.isDriveLowOnSpace({ driveInfoAvailable: true, driveTotalBytes: 1000, driveFreeBytes: 50 }), - true + const cap = await multiDownload.probeDownloadTransferCapability(host) + assert.equal(cap.status, 'ready') + assert.equal(cap.resumablePersist, true) + + const added = await multiDownload.addDownloadTransfer( + { + url: 'https://releases.ubuntu.com/24.04/ubuntu-24.04.iso', + outputDir: 'D:\\Downloads', + fileName: 'ubuntu-24.04.iso', + maxConnections: 16, + maxRateBytesPerSec: 5 * 1024 * 1024, + overwrite: true + }, + host ) -}) - -test('multi-download: 连接到 aria2 时按档位提交任务,返回任务号,不走客户端下载', async () => { - const host = createRealHostStub({ - window_show_save_dialog: () => ({ canceled: false, filePath: 'x' }), - network_http_download: () => ({ success: true }), - dllplugin_call: () => ({ ok: true, success: true, tasks: [] }) + assert.equal(added.ok, true) + assert.equal(added.data.taskId, 'dl_1') + assert.equal(added.data.connections, 16) + assert.deepEqual(callsOf(host, 'tool_download_transfer_add')[0].params, { + url: 'https://releases.ubuntu.com/24.04/ubuntu-24.04.iso', + outputDir: { path: 'D:\\Downloads' }, + fileName: 'ubuntu-24.04.iso', + maxConnections: 16, + maxRateBytesPerSec: 5 * 1024 * 1024, + overwrite: true }) - const fetchImpl = aria2Fetch(() => ({ json: { jsonrpc: '2.0', id: 'x', result: '2089b05ecca3d829' } })) - const res = await multiDownload.startMultiThreadDownloadTask( - 'https://releases.ubuntu.com/24.04/ubuntu-24.04.iso', - 'C:\\Users\\RealUser\\Downloads', - preset16, - host, - { fetchImpl } - ) - assert.equal(res.ok, true) - assert.equal(res.data.engine, 'aria2') - assert.match(res.message, /16 线程,任务 2089b05ecca3d829/) - const [uris, opts] = fetchImpl.requests[0].body.params - assert.deepEqual(uris, ['https://releases.ubuntu.com/24.04/ubuntu-24.04.iso']) - assert.equal(opts.dir, 'C:\\Users\\RealUser\\Downloads') - assert.equal(opts.split, '16') - assert.equal(opts['min-split-size'], '1M') - assert.equal(host.calls.length, 0, '交给 aria2 后不应再调用客户端下载或原生组件') -}) -test('multi-download: aria2 拒绝任务时返回失败,不悄悄换成别的下载方式', async () => { - const host = createRealHostStub({ - window_show_save_dialog: () => ({ canceled: false, filePath: 'x' }), - network_http_download: () => ({ success: true }) - }) - const fetchImpl = aria2Fetch(() => ({ status: 400, json: { jsonrpc: '2.0', id: 'x', error: { code: 1, message: 'Unauthorized' } } })) - const res = await multiDownload.startMultiThreadDownloadTask('https://example.com/file.zip', 'C:\\D', preset16, host, { fetchImpl }) - assert.equal(res.ok, false) - assert.equal(res.error, 'ARIA2_REJECTED') - assert.match(res.message, /aria2 返回错误/) - assert.equal(host.calls.length, 0) -}) + const paused = await multiDownload.pauseDownloadTransfer('dl_1', host) + assert.equal(paused.ok, true) + assert.equal(paused.data.state, 'paused') -test('multi-download: 连不上 aria2 时 HTTP 链接经保存对话框由客户端单连接下载,并如实说明线程档位未生效', async () => { - const host = createRealHostStub({ - window_show_save_dialog: () => ({ canceled: false, filePath: 'D:\\Saved\\file.zip' }), - network_http_download: (payload) => ({ success: true, path: payload.savePath, size: 4096000, statusCode: 200 }) - }) - const res = await multiDownload.startMultiThreadDownloadTask( - 'https://example.com/pkg/file.zip?sig=1', - 'C:\\Users\\RealUser\\Downloads', - preset16, - host, - { fetchImpl: aria2Offline } - ) - assert.equal(res.ok, true) - assert.equal(res.data.engine, 'client') - assert.match(res.message, /未连接到本机 aria2.*单连接下载到 D:\\Saved\\file\.zip.*线程档位未生效/) - const dialog = called(host, 'window_show_save_dialog')[0].payload - assert.equal(dialog.defaultPath, 'C:\\Users\\RealUser\\Downloads') - assert.equal(dialog.defaultName, 'file.zip') - assert.equal(dialog.filters, 'ZIP 文件|zip|所有文件|*') - // 宿主只接受 url / savePath / headers / timeout - assert.deepEqual(called(host, 'network_http_download')[0].payload, { - url: 'https://example.com/pkg/file.zip?sig=1', - savePath: 'D:\\Saved\\file.zip' - }) -}) + const resumed = await multiDownload.resumeDownloadTransfer('dl_1', host) + assert.equal(resumed.ok, true) + assert.equal(resumed.data.state, 'running') -test('multi-download: 客户端下载的取消、对话框失败与下载失败都返回失败', async () => { - const canceledHost = createRealHostStub({ - window_show_save_dialog: () => ({ canceled: true }), - network_http_download: () => ({ success: true }) - }) - const canceled = await multiDownload.startMultiThreadDownloadTask('https://example.com/a.zip', '', preset16, canceledHost, { fetchImpl: aria2Offline }) - assert.equal(canceled.error, 'CANCELED') - assert.equal(called(canceledHost, 'network_http_download').length, 0) + const status = await multiDownload.fetchDownloadTransferStatus(undefined, host) + assert.equal(status.ok, true) + assert.equal(status.data.length, 1) + assert.equal(status.data[0].state, 'running') - const dialogFail = await multiDownload.startMultiThreadDownloadTask( - 'https://example.com/a.zip', - '', - preset16, - createRealHostStub({ window_show_save_dialog: () => { throw new Error('窗口已关闭') } }), - { fetchImpl: aria2Offline } - ) - assert.equal(dialogFail.ok, false) - assert.equal(dialogFail.error, 'SAVE_DIALOG_FAILED') + const cancelled = await multiDownload.cancelDownloadTransfer('dl_1', host) + assert.equal(cancelled.ok, true) + assert.equal(cancelled.data.state, 'cancelled') +}) - const failHost = createRealHostStub({ - window_show_save_dialog: () => ({ canceled: false, filePath: 'D:\\a.zip' }), - network_http_download: () => { - throw new Error('下载请求返回 HTTP 502') +test('multi-download: magnet 与 ftp 链接明确拒绝并提示一期仅支持 HTTP/HTTPS,绝不调用下载 IPC', async () => { + const host = createHostStub({ + tool_download_transfer_add: () => { + throw new Error('不应调用下载接口') } }) - const dlFail = await multiDownload.startMultiThreadDownloadTask('https://example.com/a.zip', 'D:\\', preset16, failHost, { fetchImpl: aria2Offline }) - assert.equal(dlFail.ok, false) - assert.equal(dlFail.error, 'DOWNLOAD_FAILED') - assert.match(dlFail.message, /502/) -}) -test('multi-download: 连不上 aria2 时磁力与 FTP 链接直接报错,不打开外部程序也不写剪贴板', async () => { - const host = createRealHostStub({ - shell_open_external: () => ({ success: true }), - clipboard_copy_text: () => ({ success: true }), - window_show_save_dialog: () => ({ canceled: false, filePath: 'x' }) - }) - const magnet = await multiDownload.startMultiThreadDownloadTask( - 'magnet:?xt=urn:btih:0123456789abcdef0123456789abcdef01234567', - 'C:\\D', - preset16, - host, - { fetchImpl: aria2Offline } + const magnetRes = await multiDownload.addDownloadTransfer( + { + url: 'magnet:?xt=urn:btih:0123456789abcdef0123456789abcdef01234567', + outputDir: 'D:\\Downloads', + maxConnections: 8 + }, + host ) - assert.equal(magnet.ok, false) - assert.equal(magnet.error, 'ARIA2_REQUIRED') - assert.match(magnet.message, /磁力链接需要本机运行 aria2/) - - const ftp = await multiDownload.startMultiThreadDownloadTask('ftp://mirror.example.com/a.iso', 'C:\\D', preset16, host, { fetchImpl: aria2Offline }) - assert.equal(ftp.ok, false) - assert.equal(ftp.error, 'ARIA2_REQUIRED') + assert.equal(magnetRes.ok, false) + assert.equal(magnetRes.errorCode, 'UNSUPPORTED_PROTOCOL') + assert.match(magnetRes.message, /一期仅支持 HTTP\/HTTPS.*磁力/) + + const ftpRes = await multiDownload.addDownloadTransfer( + { + url: 'ftp://mirror.example.com/archive.tar.gz', + outputDir: 'D:\\Downloads', + maxConnections: 8 + }, + host + ) + assert.equal(ftpRes.ok, false) + assert.equal(ftpRes.errorCode, 'UNSUPPORTED_PROTOCOL') + assert.match(ftpRes.message, /一期仅支持 HTTP\/HTTPS.*FTP/) assert.equal(host.calls.length, 0) - - const bad = await multiDownload.startMultiThreadDownloadTask('invalid-protocol://bad', 'C:\\D', preset16, host, { fetchImpl: aria2Offline }) - assert.equal(bad.ok, false) - assert.equal(bad.error, 'INVALID_URL') }) -test('multi-download: 复制 aria2c 命令,剪贴板失败时返回失败', async () => { - let copied = '' - const host = createRealHostStub({ - clipboard_copy_text: ({ text }) => { - copied = text - return { success: true } +test('multi-download: 通过 window_show_open_dialog 选择目录并拦截受保护系统目录', async () => { + const host = createHostStub({ + window_show_open_dialog: (params) => { + assert.ok(params.properties.includes('openDirectory')) + return { canceled: false, filePaths: ['/Users/demo/Downloads'] } } }) - const res = await multiDownload.copyAria2cCommand('https://example.com/a.zip', 'C:\\Users\\RealUser\\Downloads', preset16, host) - assert.equal(res.ok, true) - assert.match(res.message, /插件不会运行它/) - assert.equal(copied, `aria2c ${preset16.aria2Flags} -d "C:\\Users\\RealUser\\Downloads" "https://example.com/a.zip"`) + const picked = await multiDownload.selectDownloadOutputDir('/Users/demo', host) + assert.equal(picked.ok, true) + assert.equal(picked.data.directoryPath, '/Users/demo/Downloads') - const failing = createRealHostStub({ - clipboard_copy_text: () => { throw new Error('剪贴板被占用') }, - clipboard_write_text: () => { throw new Error('剪贴板被占用') } + const sysHost = createHostStub({ + window_show_open_dialog: () => ({ canceled: false, filePaths: ['C:\\Windows\\System32'] }) }) - const failed = await multiDownload.copyAria2cCommand('https://example.com/a.zip', '', preset16, failing) - assert.equal(failed.ok, false) - assert.equal(failed.error, 'CLIPBOARD_WRITE_FAILED') + const blocked = await multiDownload.selectDownloadOutputDir('', sysHost) + assert.equal(blocked.ok, false) + assert.equal(blocked.errorCode, 'FORBIDDEN_TARGET') }) -test('multi-download: 移入回收站逐个处理,失败与系统目录拦截如实列出', async () => { - const host = createRealHostStub({ - shell_trash_item: ({ fullPath }) => { - if (fullPath.endsWith('locked.zip')) throw new Error('文件被占用') - return { success: true } - } +test('multi-download: 无宿主环境时所有薄原语操作明确报错,不返回假成功', async () => { + const cap = await multiDownload.probeDownloadTransferCapability() + assert.equal(cap.status, 'unsupported') + assert.match(cap.error, /未连接到 ZTools 宿主环境/) + + const add = await multiDownload.addDownloadTransfer({ + url: 'https://example.com/file.zip', + outputDir: 'D:\\Downloads', + maxConnections: 4 }) - const res = await multiDownload.deleteDownloadedFiles( - ['C:\\Users\\RealUser\\Downloads\\ubuntu-24.04.iso', 'C:\\Users\\RealUser\\Downloads\\locked.zip', 'C:\\Windows\\x.zip'], - [ - { path: 'C:\\Users\\RealUser\\Downloads\\ubuntu-24.04.iso', sizeBytes: 4096000 }, - { path: 'C:\\Users\\RealUser\\Downloads\\locked.zip', sizeBytes: 10 } - ], - host - ) - assert.equal(res.deletedCount, 1) - assert.equal(res.freedBytes, 4096000) - assert.equal(res.failed.length, 2) - assert.match(res.failed[0].reason, /文件被占用/) - assert.equal(res.failed[1].path, 'C:\\Windows\\x.zip') - assert.equal(called(host, 'shell_trash_item').length, 2) + assert.equal(add.ok, false) + assert.equal(add.errorCode, 'HOST_REQUIRED') + + const status = await multiDownload.fetchDownloadTransferStatus() + assert.equal(status.ok, false) + assert.equal(status.errorCode, 'HOST_REQUIRED') + + const pause = await multiDownload.pauseDownloadTransfer('dl_1') + assert.equal(pause.ok, false) + assert.equal(pause.errorCode, 'HOST_REQUIRED') }) -test('multi-download: 链接识别不因畸形转义抛错,档位文字不再夸大', () => { - const r = multiDownload.detectDownloadUrlFromText('下载 https://example.com/%E0%A4%A.zip 这个') - assert.equal(r.url, 'https://example.com/%E0%A4%A.zip') - assert.equal(r.suggestedFileName, '%E0%A4%A.zip') - assert.equal(multiDownload.detectDownloadUrlFromText('https://example.com/a%20b.zip').suggestedFileName, 'a b.zip') - assert.doesNotMatch(JSON.stringify(multiDownload.getThreadSplitPresets()), /极速|千兆|加速/) +test('multi-download: LocalStorage 持久化下载历史,写入与读取保持完整', async () => { + await LocalStorage.clear() + const entry = multiDownload.buildHistoryEntryFromTask( + { + taskId: 'dl_hist_1', + url: 'https://example.com/pkg.zip', + fileName: 'pkg.zip', + state: 'completed', + downloadedBytes: 2048, + totalBytes: 2048, + speedBytesPerSec: 0, + connections: 8, + createdAt: 1000, + updatedAt: 2000 + }, + 'D:\\Downloads' + ) + await multiDownload.saveDownloadHistory([entry]) + const loaded = await multiDownload.loadDownloadHistory() + assert.equal(loaded.length, 1) + assert.equal(loaded[0].taskId, 'dl_hist_1') + assert.equal(loaded[0].outputPath, 'D:\\Downloads\\pkg.zip') + await LocalStorage.clear() }) diff --git a/extensions/multi-download/tests/multi-download.ui.test.mjs b/extensions/multi-download/tests/multi-download.ui.test.mjs index fcce5445..f174872f 100644 --- a/extensions/multi-download/tests/multi-download.ui.test.mjs +++ b/extensions/multi-download/tests/multi-download.ui.test.mjs @@ -1,368 +1,174 @@ -// 界面集成测试:用真实声明式运行时渲染 dist/,模拟客户端 IPC 与本机 aria2,验证零扫描、导入展开、移除清空、下载入列与非客户端空状态 +// 多线程下载界面集成测试:验证布局三渲染、download.transfer 队列同步、暂停/恢复/取消、不支持协议提示与无宿主环境状态 import test from 'node:test' import assert from 'node:assert/strict' -import fs from 'node:fs' -import os from 'node:os' -import path from 'node:path' -import { Color } from '@ztools/declarative-ui' -import { createHost, installDirectoryHost, mount, tick } from '../../shared/test-harness.mjs' +import { LocalStorage, setRuntimeLocale } from '@ztools/declarative-ui' +import { createHost, mount, tick } from '../../shared/test-harness.mjs' import MultiDownloadCommand from '../dist/index.js' -const DOWNLOADS = 'C:\\Users\\RealUser\\Downloads' - -function makeTempTree(spec) { - const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ztools-md-')) - for (const [rel, content] of Object.entries(spec)) { - const full = path.join(root, rel) - fs.mkdirSync(path.dirname(full), { recursive: true }) - fs.writeFileSync(full, content) +setRuntimeLocale('zh-CN') + +function setupDownloadHost(host, options = {}) { + const tasks = new Map(options.initialTasks ?? []) + host.ipc.system_get_path = async ({ name }) => (name === 'downloads' ? 'D:\\Downloads' : `D:\\${name}`) + host.ipc.clipboard_read_text = async () => options.clipboard ?? '' + host.ipc.tool_runtime_capabilities = async () => ({ + contractVersion: 1, + platform: 'windows', + domains: ['download'], + capabilities: [ + { + primitiveId: 'download.transfer', + domain: 'download', + summary: 'HTTP/HTTPS chunked transfer', + ipcMethods: [ + 'tool_download_transfer_add', + 'tool_download_transfer_pause', + 'tool_download_transfer_resume', + 'tool_download_transfer_cancel', + 'tool_download_transfer_status' + ], + requiredPermissions: ['network'], + status: options.status ?? 'ready', + optionalExtensions: options.extensions ?? ['resumable-persist'] + } + ] + }) + host.ipc.tool_runtime_ensure = async ({ primitiveId }) => ({ + primitiveId, + status: 'ready', + provisioned: true + }) + host.ipc.window_show_open_dialog = async () => ({ + canceled: false, + filePaths: ['D:\\CustomDownloads'] + }) + host.ipc.tool_download_transfer_add = async (params) => { + const rec = { + taskId: 'dl_ui_1', + url: params.url, + fileName: params.fileName || 'archive.zip', + state: 'running', + downloadedBytes: 512, + totalBytes: 4096, + speedBytesPerSec: 1024, + connections: params.maxConnections ?? 8, + createdAt: 1000, + updatedAt: 1001 + } + tasks.set(rec.taskId, rec) + return rec } - return root -} - -function installClient(host, { clipboard = '', disk = { total: 500, used: 100, available: 400 } } = {}) { - host.ipc.system_get_path = async ({ name }) => (name === 'downloads' ? DOWNLOADS : `C:\\Users\\RealUser\\${name}`) - host.ipc.system_get_disk_usage = async () => disk - host.ipc.clipboard_read_text = async () => clipboard -} - -/** 让组件里的 aria2 请求连不上(与本机没有运行 aria2 时一致) */ -async function withAria2Offline(fn) { - const original = globalThis.fetch - globalThis.fetch = async () => { - throw new TypeError('fetch failed') + host.ipc.tool_download_transfer_pause = async ({ taskId }) => { + const next = { ...tasks.get(taskId), state: 'paused', speedBytesPerSec: 0, updatedAt: 1002 } + tasks.set(taskId, next) + return next } - try { - return await fn() - } finally { - globalThis.fetch = original + host.ipc.tool_download_transfer_resume = async ({ taskId }) => { + const next = { ...tasks.get(taskId), state: 'running', speedBytesPerSec: 2048, updatedAt: 1003 } + tasks.set(taskId, next) + return next } -} - -async function mountClient(options) { - const host = createHost() - installClient(host, options) - const view = await mount(MultiDownloadCommand, host) - await tick(20) - return { host, view } + host.ipc.tool_download_transfer_cancel = async ({ taskId }) => { + const next = { ...tasks.get(taskId), state: 'cancelled', speedBytesPerSec: 0, updatedAt: 1004 } + tasks.set(taskId, next) + return next + } + host.ipc.tool_download_transfer_status = async () => ({ + tasks: Array.from(tasks.values()) + }) + return { tasks } } const ipcCount = (host, method) => host.ipcCalls.filter(([m]) => m === method).length -const dlFiles = (view) => view.items().filter((it) => String(it.props.id).startsWith('dl-file-')) -const fileItem = (view, name) => view.item((it) => it.props.title === name) -async function clickFilterBar(view, id) { - const action = view.tree().props.filterBar.actions.find((a) => a.id === id) - assert.ok(action, `顶栏缺少按钮 ${id}`) - await action.onAction() - await tick(25) -} +test('multi-download UI: 启动探测能力并同步活跃任务,支持下载、暂停、恢复与取消,且零 Emoji/DLL', async () => { + await LocalStorage.clear() + const host = createHost() + setupDownloadHost(host, { clipboard: 'https://example.com/archive.zip' }) + const view = await mount(MultiDownloadCommand, host) + await tick(30) -test('multi-download UI: 挂载时不扫描目录,列表为空,顶栏恰为 2 个按钮,磁盘不足 10% 时红色提示', async () => { - await withAria2Offline(async () => { - const { host, view } = await mountClient({ disk: { total: 1000, used: 950, available: 50 } }) - assert.equal(dlFiles(view).length, 0) - assert.equal(ipcCount(host, 'system_search_files'), 0) - assert.equal(ipcCount(host, 'system_list_common_folders'), 0) - assert.equal(ipcCount(host, 'filesystem_get_directory_contents'), 0) + try { + assert.equal(ipcCount(host, 'tool_runtime_capabilities'), 1) + assert.equal(ipcCount(host, 'tool_download_transfer_status'), 1) assert.equal(ipcCount(host, 'dllplugin_call'), 0) - - const filterActions = view.tree().props.filterBar.actions - assert.deepEqual( - filterActions.map((a) => [a.id, a.title]), - [['pick-files', '选择文件'], ['pick-folder', '选择文件夹']] - ) - assert.deepEqual(view.actions(null).slice(0, 2).map((a) => a.props.title), ['选择文件…', '选择文件夹…']) - - const link = view.item('nav-dl-link') - const warn = link.props.accessories.find((a) => a.tag && /不足 10%/.test(a.tag.value)) - assert.ok(warn, '剩余空间不足 10% 时要有提示') - assert.equal(warn.tag.color, Color.Red) - assert.match(view.tree().props.filterBar.summaryText, /未连接 aria2.*剩余.*不足 10%.*尚未添加文件/) assert.equal(/[\u{1F300}-\u{1FAFF}]/u.test(view.text()), false) - view.unmount() - }) -}) - -test('multi-download UI: 选择文件与选择文件夹导入任意非隐藏文件并分类,支持移除、清空与整盘确认', async () => { - const tmp = makeTempTree({ - 'a.zip': 'zipdata', - 'sub/b.iso': 'isodata', - 'sub/c.pdf': 'pdfdata', - 'sub/.hidden.zip': 'hidden', - 'sub/empty.txt': '' - }) - await withAria2Offline(async () => { - try { - const { host, view } = await mountClient() - await installDirectoryHost(host, { authorized: [tmp] }) - host.ipc.filesystem_get_file_size = async ({ path: p }) => ({ success: true, size: fs.statSync(p).size }) - - // 选择文件(含重复与取消) - host.ipc.window_show_open_dialog = async (params) => { - assert.equal('filters' in params, false, '任意文件导入不传过滤串') - return { canceled: false, filePaths: [path.join(tmp, 'a.zip')] } - } - await clickFilterBar(view, 'pick-files') - assert.deepEqual(dlFiles(view).map((i) => i.props.title), ['a.zip']) - assert.ok(dlFiles(view).every((i) => i.props.checked === false)) - assert.match(view.tree().props.filterBar.summaryText, /清空列表 Ctrl\+Shift\+Backspace/) - - // 整盘确认取消 - host.ipc.window_show_select_folder_dialog = async () => ({ canceled: false, folderPath: 'D:\\' }) - host.setConfirm(false) - await clickFilterBar(view, 'pick-folder') - assert.equal(host.confirms.length, 1) - assert.equal(ipcCount(host, 'filesystem_get_directory_contents'), 0) - - // 选择文件夹(去重 a.zip,新增 b.iso / c.pdf,过滤隐藏与空文件) - host.ipc.window_show_select_folder_dialog = async () => ({ canceled: false, folderPath: tmp }) - await clickFilterBar(view, 'pick-folder') - assert.deepEqual(dlFiles(view).map((i) => i.props.title), ['a.zip', 'b.iso', 'c.pdf']) - assert.match(String(host.lastToast().title), /已添加 2 个文件/) - assert.match(String(host.lastToast().message), /1 个已在列表中/) - - // 左栏分类筛选 - await view.run(view.item('nav-dl-iso_image'), '只看系统镜像与模型') - assert.deepEqual(dlFiles(view).map((i) => i.props.title), ['b.iso']) - await view.run(view.item('nav-dl-all'), '查看全部文件') - assert.equal(dlFiles(view).length, 3) - - // 从列表移除不删文件 - await view.run(fileItem(view, 'a.zip'), '从列表移除') - assert.deepEqual(dlFiles(view).map((i) => i.props.title), ['b.iso', 'c.pdf']) - assert.equal(ipcCount(host, 'shell_trash_item'), 0) - - // 清空列表不删文件 - await view.run(fileItem(view, 'b.iso'), '清空列表') - assert.equal(dlFiles(view).length, 0) - assert.equal(ipcCount(host, 'shell_trash_item'), 0) - view.unmount() - } finally { - fs.rmSync(tmp, { recursive: true, force: true }) - } - }) -}) - -test('multi-download UI: 拖放名称带点的文件夹自动展开(新版 directories、旧版探测及旧事件回退)', async () => { - const tmp = makeTempTree({ - 'v2.1_pkgs/app.exe': 'exedata', - 'legacy_dir/doc.md': 'mddata' - }) - const dotted = path.join(tmp, 'v2.1_pkgs') - const legacy = path.join(tmp, 'legacy_dir') - await withAria2Offline(async () => { - try { - const { host, view } = await mountClient() - await installDirectoryHost(host, { authorized: [tmp] }) - host.ipc.filesystem_directory_exists = async ({ path: p }) => ({ - success: true, - exists: fs.existsSync(p) && fs.statSync(p).isDirectory() - }) - - await view.dropFiles([dotted], { directories: [dotted] }) - await tick(25) - assert.deepEqual(dlFiles(view).map((i) => i.props.title), ['app.exe']) - assert.equal(ipcCount(host, 'filesystem_directory_exists'), 0) - - await view.dropFiles([legacy]) - await tick(25) - assert.deepEqual(dlFiles(view).map((i) => i.props.title), ['app.exe', 'doc.md']) - assert.equal(ipcCount(host, 'filesystem_directory_exists'), 1) - view.unmount() - // 旧版客户端事件回退(fileInput: false) - const listeners = [] - const host2 = createHost() - installClient(host2) - globalThis.window.__ztoolsDeclarativeFeatures = { fileInput: false } - globalThis.window.ztools = { - ...(globalThis.window.ztools || {}), - events: { - on(ev, cb) { - if (ev === 'plugin_files_dropped') listeners.push(cb) - return () => {} - } - } - } - await installDirectoryHost(host2, { authorized: [tmp] }) - host2.ipc.filesystem_directory_exists = async ({ path: p }) => ({ - success: true, - exists: fs.existsSync(p) && fs.statSync(p).isDirectory() - }) - const view2 = await mount(MultiDownloadCommand, host2) - await tick(20) - listeners[0]({ payload: { files: [dotted] } }) - await tick(30) - assert.deepEqual(dlFiles(view2).map((i) => i.props.title), ['app.exe']) - view2.unmount() - } finally { - fs.rmSync(tmp, { recursive: true, force: true }) - } - }) -}) - -test('multi-download UI: 导入进行中清空列表则丢弃结果;移入回收站后直接移除成功项', async () => { - const tmp = makeTempTree({ 'a.zip': 'zip', 'b.iso': 'iso', 'c.pdf': 'pdf' }) - await withAria2Offline(async () => { - try { - const { host, view } = await mountClient() - host.ipc.filesystem_get_file_size = async () => ({ success: true, size: 1024 }) - host.ipc.window_show_open_dialog = async () => ({ - canceled: false, - filePaths: [path.join(tmp, 'a.zip'), path.join(tmp, 'b.iso'), path.join(tmp, 'c.pdf')] - }) - await clickFilterBar(view, 'pick-files') - - // 导入进行中清空列表 -> 丢弃结果、不弹提示 - let releaseSlow - const slowGate = new Promise((r) => (releaseSlow = r)) - host.ipc.window_show_select_folder_dialog = async () => ({ canceled: false, folderPath: tmp }) - host.ipc.filesystem_get_directory_contents = async () => { - await slowGate - return { - success: true, - files: [{ name: 'late.zip', size: 100, isDirectory: false, lastModified: new Date().toISOString() }] - } - } - host.toasts.length = 0 - const pickFolderBtn = view.tree().props.filterBar.actions.find((a) => a.id === 'pick-folder') - pickFolderBtn.onAction() - await tick(10) - assert.match(view.tree().props.filterBar.summaryText, /正在导入/) - await view.run(fileItem(view, 'a.zip'), '清空列表') - assert.equal(dlFiles(view).length, 0) - const countAfterClear = host.toasts.length - releaseSlow() - await tick(30) - assert.equal(dlFiles(view).length, 0) - assert.equal(host.toasts.length, countAfterClear) - - // 重新导入并验证移入回收站流程 - await clickFilterBar(view, 'pick-files') - const trashed = [] - host.ipc.shell_trash_item = async ({ fullPath }) => { - if (fullPath.endsWith('b.iso')) throw Object.assign(new Error('文件被占用'), { code: 'SHELL_ERROR' }) - trashed.push(fullPath) - return { success: true } - } - fileItem(view, 'a.zip').props.onCheckChange(true) - fileItem(view, 'b.iso').props.onCheckChange(true) - await tick() - const trashTitle = (node) => view.actions(node).find((a) => a.props.title.startsWith('移入回收站')).props.title - - host.setConfirm(false) - await view.run(fileItem(view, 'c.pdf'), trashTitle(fileItem(view, 'c.pdf'))) - assert.equal(host.confirms.length, 1) - assert.equal(host.confirms[0].primaryAction.style, 'destructive') - assert.equal(ipcCount(host, 'shell_trash_item'), 0) - - host.setConfirm(true) - await view.run(fileItem(view, 'c.pdf'), trashTitle(fileItem(view, 'c.pdf'))) - await tick(20) - assert.deepEqual(trashed, [path.join(tmp, 'a.zip')]) - assert.equal(ipcCount(host, 'system_search_files'), 0) - assert.deepEqual(dlFiles(view).map((i) => i.props.title), ['b.iso', 'c.pdf']) - assert.equal(fileItem(view, 'b.iso').props.checked, true) - assert.match(String(host.lastToast().title), /已将 1 个文件移入回收站.*1 个失败.*b\.iso.*文件被占用/) - view.unmount() - } finally { - fs.rmSync(tmp, { recursive: true, force: true }) - } - }) -}) - -test('multi-download UI: 没有 aria2 时 HTTP 链接单连接下载完成后入列,下载中拒绝清空,磁力链接如实报错', async () => { - await withAria2Offline(async () => { - const { host, view } = await mountClient({ clipboard: 'https://example.com/pkg/tool.zip' }) - host.ipc.window_show_save_dialog = async () => ({ canceled: false, filePath: `${DOWNLOADS}\\tool.zip` }) - host.ipc.network_http_download = async ({ savePath }) => ({ success: true, path: savePath, size: 4096 }) - - const link = view.item('nav-dl-link') - assert.equal(view.actions(link)[0].props.title, '下载此链接') - await view.run(link, '下载此链接') + // 选择输出目录(走 window_show_open_dialog) + const chooseDirBtn = view.tree().props.filterBar.actions.find((a) => a.id === 'choose-dir') + assert.ok(chooseDirBtn) + await chooseDirBtn.onAction() await tick(20) - assert.equal(ipcCount(host, 'window_show_save_dialog'), 1) - assert.equal(ipcCount(host, 'network_http_download'), 1) - assert.equal(ipcCount(host, 'dllplugin_call'), 0) - assert.equal(String(host.lastToast().style).toLowerCase(), 'success') - assert.match(String(host.lastToast().title), /单连接下载到 .*tool\.zip.*线程档位未生效/) - assert.deepEqual(dlFiles(view).map((i) => i.props.title), ['tool.zip']) - assert.equal(fileItem(view, 'tool.zip').props.checked, false) - - // 下载进行中尝试清空列表应拒绝 - let releaseDl - const dlGate = new Promise((r) => (releaseDl = r)) - host.ipc.window_show_save_dialog = async () => ({ canceled: false, filePath: `${DOWNLOADS}\\tool2.zip` }) - host.ipc.network_http_download = async ({ savePath }) => { - await dlGate - return { success: true, path: savePath, size: 8192 } - } - await view.search('https://example.com/pkg/tool2.zip') - const dlPromise = view.run(view.item('nav-dl-link'), '下载此链接') - await tick(10) - await view.run(fileItem(view, 'tool.zip'), '清空列表') - assert.equal(host.lastToast().title, '正在处理,完成后再清空') - assert.equal(dlFiles(view).length, 1) - releaseDl() - await dlPromise - await tick(15) - assert.deepEqual(dlFiles(view).map((i) => i.props.title), ['tool.zip', 'tool2.zip']) - - await view.search('magnet:?xt=urn:btih:0123456789abcdef0123456789abcdef01234567') - await view.run(view.item('nav-dl-link'), '下载此链接') - await tick(10) - assert.equal(String(host.lastToast().style).toLowerCase(), 'failure') - assert.match(String(host.lastToast().title), /磁力链接需要本机运行 aria2/) - assert.equal(host.clipboard.text, '', '失败时不能自动改写剪贴板') + assert.equal(ipcCount(host, 'window_show_open_dialog'), 1) + + // 点击开始下载 + const startBtn = view.tree().props.filterBar.actions.find((a) => a.id === 'start-download') + assert.ok(startBtn) + await startBtn.onAction() + await tick(30) + assert.equal(ipcCount(host, 'tool_download_transfer_add'), 1) + assert.ok(view.item('transfer-task-dl_ui_1')) + + // 暂停 -> 恢复 -> 取消 + await view.run(view.item('transfer-task-dl_ui_1'), '暂停任务') + await tick(25) + assert.equal(ipcCount(host, 'tool_download_transfer_pause'), 1) + + await view.run(view.item('transfer-task-dl_ui_1'), '恢复下载') + await tick(25) + assert.equal(ipcCount(host, 'tool_download_transfer_resume'), 1) + + await view.run(view.item('transfer-task-dl_ui_1'), '取消任务') + await tick(25) + assert.equal(ipcCount(host, 'tool_download_transfer_cancel'), 1) + } finally { view.unmount() - }) + await LocalStorage.clear() + } }) -test('multi-download UI: 不在客户端里运行时只显示空状态,不显示示例文件', async () => { +test('multi-download UI: 输入 magnet 链接时明确提示暂不支持且不调用下载接口', async () => { + await LocalStorage.clear() const host = createHost() - const saved = globalThis.__ztoolsElectron - delete globalThis.__ztoolsElectron + setupDownloadHost(host) + const view = await mount(MultiDownloadCommand, host) + await tick(25) + try { - const view = await mount(MultiDownloadCommand, host) + view.tree().props.onSearchTextChange('magnet:?xt=urn:btih:0123456789abcdef0123456789abcdef01234567') await tick(10) - const text = view.text() - assert.match(text, /需要在 ZTools 客户端中使用/) - assert.equal(dlFiles(view).length, 0) - assert.doesNotMatch(text, /ExampleApp-Setup|Windows11_24H2|C:\\\\Users\\\\Default/) - view.unmount() + const startBtn = view.tree().props.filterBar.actions.find((a) => a.id === 'start-download') + await startBtn.onAction() + await tick(20) + assert.equal(ipcCount(host, 'tool_download_transfer_add'), 0) + assert.match(String(host.lastToast().title), /一期仅支持 HTTP\/HTTPS/) } finally { - globalThis.__ztoolsElectron = saved + view.unmount() + await LocalStorage.clear() } }) -test('multi-download: 客户端提供带插件身份的通道时,单连接下载把超时放宽到 5 分钟', async () => { - const { getDeclarativeBridge, setDeclarativeBridge } = await import('@ztools/declarative-ui') - const { startMultiThreadDownloadTask, getThreadSplitPresets } = await import('../dist/logic.js') +test('multi-download UI: 无宿主环境时显示明确客户端提示并阻止下载', async () => { + await LocalStorage.clear() const host = createHost() - host.ipc.window_show_save_dialog = async () => ({ canceled: false, filePath: `${DOWNLOADS}\\a.zip` }) - const transportCalls = [] - setDeclarativeBridge({ - ...getDeclarativeBridge(), - hostTransport: { - async call(method, params, options) { - transportCalls.push({ method, params, options }) - return { success: true, path: params.savePath, size: 1024 } - } - } - }) - const res = await startMultiThreadDownloadTask('https://example.com/a.zip', DOWNLOADS, getThreadSplitPresets()[0], undefined, { - fetchImpl: async () => { - throw new TypeError('fetch failed') - } - }) - assert.equal(res.ok, true) - assert.deepEqual(transportCalls, [ - { - method: 'network_http_download', - params: { url: 'https://example.com/a.zip', savePath: `${DOWNLOADS}\\a.zip` }, - options: { timeoutMs: 300000 } + const prevElectron = globalThis.window?.__ztoolsElectron + const prevZtools = globalThis.window?.ztools + if (globalThis.window) { + delete globalThis.window.__ztoolsElectron + delete globalThis.window.ztools + } + const view = await mount(MultiDownloadCommand, host) + await tick(20) + + try { + assert.match(view.tree().props.filterBar.summaryText, /需要在 ZTools 客户端中使用/) + assert.equal(ipcCount(host, 'tool_runtime_capabilities'), 0) + } finally { + view.unmount() + if (globalThis.window) { + globalThis.window.__ztoolsElectron = prevElectron + globalThis.window.ztools = prevZtools } - ]) - assert.equal(ipcCount(host, 'network_http_download'), 0) + await LocalStorage.clear() + } }) diff --git a/extensions/network-adapter/README.en.md b/extensions/network-adapter/README.en.md new file mode 100644 index 00000000..8bb23a19 --- /dev/null +++ b/extensions/network-adapter/README.en.md @@ -0,0 +1,23 @@ +# Network Adapter Manager + +Inspect IPv4 addresses, subnet masks, MAC addresses, gateways, DNS servers, and connection status for local network adapters, flush the DNS cache, or set an adapter's DNS to `223.5.5.5` and restore automatic (DHCP) DNS. + +## Usage + +- Command: `Network Adapter Manager` (main plugin command). +- Filter on the right of the search bar by All, Physical Adapters, Virtual & Loopback Adapters, or Connected Only; search by adapter name, IP, MAC, or DNS. +- When both IPv4 and MAC addresses are present, `Enter` copies the IPv4 address and `Ctrl+Enter` copies the MAC address; if either is missing, its copy action is omitted and subsequent actions shift up. `Ctrl+C` copies a single-line summary, `Ctrl+Shift+C` copies the full configuration JSON, and `Ctrl+K` opens the action panel. +- `Ctrl+P` sets the selected adapter's DNS to `223.5.5.5` (Alibaba Public DNS, replacing existing DNS); `Ctrl+Shift+D` restores automatic DNS acquisition. No secondary DNS is configured; these two actions are omitted for loopback adapters. +- Changing DNS settings requires running ZTools as Administrator, otherwise the operation fails with an error. +- Click "Flush DNS Cache" at the top to clear the local DNS resolver cache, or "Refresh Adapters" to reload adapter information. +- Adapter read failures display the error reason; unavailable MAC addresses or subnet masks are shown as "Unrecognized". + +## Platforms & Requirements + +- Supported: Windows only +- Windows implementation is pending real-device verification. + +## Network & Data + +- Works offline; data stays strictly on your local device. +- After setting DNS to `223.5.5.5`, domain resolution requests on that adapter are sent to Alibaba Public DNS. diff --git a/extensions/network-adapter/plugin.json b/extensions/network-adapter/plugin.json index 17af9c33..affdb5f3 100644 --- a/extensions/network-adapter/plugin.json +++ b/extensions/network-adapter/plugin.json @@ -2,7 +2,8 @@ "id": "network-adapter", "name": "网卡管理", "description": "查看本机网卡的 IPv4 地址、子网掩码、MAC 地址、网关与 DNS,可刷新 DNS 缓存,或把网卡 DNS 设为 223.5.5.5、恢复自动获取(修改 DNS 需要管理员权限)", - "version": "2.0.10", + "version": "2.0.11", + "minAppVersion": "1.3.0.2", "author": "ZTools Team", "entry": "dist/index.js", "icon": "icon.svg", @@ -15,8 +16,9 @@ "system" ], "permissions": [ - "shell", - "child_process" + "network", + "system", + "clipboard" ], "targets": [ { @@ -39,7 +41,14 @@ "ip", "mac", "dns", - "gateway" + "gateway", + "network adapter", + "ip address", + "mac address", + "ethernet", + "wifi adapter", + "network interface", + "my ip" ], "screenshots": [ { @@ -55,5 +64,16 @@ { "path": "screenshots/02-action-panel.png" } + ], + "keywords": [ + "网卡管理", + "看ip", + "本机ip", + "mac地址", + "禁用网卡", + "重启网卡", + "以太网", + "wifi网卡", + "网络适配器" ] } diff --git a/extensions/network-adapter/src/i18n.ts b/extensions/network-adapter/src/i18n.ts index 0d5994ae..1489b35e 100644 --- a/extensions/network-adapter/src/i18n.ts +++ b/extensions/network-adapter/src/i18n.ts @@ -16,6 +16,8 @@ export const t = createTranslator({ errInvalidAdapterFormat: '客户端返回的网卡数据格式无法识别', errTargetAdapterRequired: '目标网卡名称或 ID 不能为空', errInvalidPrimaryDns: '首选 DNS 地址格式不合法: {dns}', + errInvalidSecondaryDns: '备选 DNS 地址格式不合法: {dns}', + errDuplicateSecondaryDns: '备选 DNS 地址不能与首选 DNS 相同: {dns}', errSecondaryDnsUnsupported: '当前客户端一次只能设置一个 DNS 服务器,不支持同时设置备选 DNS', msgDnsRestored: '已将网卡 [{name}] 的 DNS 恢复为自动获取', msgDnsSet: '已将网卡 [{name}] 的 DNS 设为 {dns}', @@ -84,6 +86,8 @@ export const t = createTranslator({ errInvalidAdapterFormat: 'Unrecognized adapter data format from client', errTargetAdapterRequired: 'Target adapter name or ID cannot be empty', errInvalidPrimaryDns: 'Invalid primary DNS address: {dns}', + errInvalidSecondaryDns: 'Invalid secondary DNS address: {dns}', + errDuplicateSecondaryDns: 'Secondary DNS must differ from primary DNS: {dns}', errSecondaryDnsUnsupported: 'Client only supports setting one DNS server at a time; secondary DNS is not supported', msgDnsRestored: 'Restored DNS on adapter [{name}] to automatic (DHCP)', msgDnsSet: 'Set DNS on adapter [{name}] to {dns}', diff --git a/extensions/network-adapter/src/logic.ts b/extensions/network-adapter/src/logic.ts index b454768b..508af7dd 100644 --- a/extensions/network-adapter/src/logic.ts +++ b/extensions/network-adapter/src/logic.ts @@ -6,7 +6,7 @@ * - 客户端没有给出的字段留空(界面显示“未识别”),不填默认值。 */ -import { invokePluginService } from './native-ipc.js' +import { callHostTransport } from './native-ipc.js' import { t } from './i18n.js' export type AdapterCategory = 'physical' | 'virtual' | 'loopback' @@ -52,8 +52,8 @@ export interface NetworkAdapterSnapshot { primaryDns: string } -/** 客户端内置网卡服务的名称(dllplugin_call 的 plugin 参数) */ -export const HOST_PLUGIN_NAME = 'NetworkAdapterPlugin' +/** 客户端专用网卡服务 IPC 方法名 */ +export const NETWORK_ADAPTER_IPC_METHOD = 'network_adapter' /** 读取网卡列表失败时 error 的固定前缀 */ import { ADAPTER_LIST_ERROR_PREFIX } from './host-errors.zh-data.js' @@ -243,7 +243,11 @@ export function buildAdapterSnapshot(adapters: NetworkAdapterItem[]): NetworkAda } export async function fetchNetworkAdapters(hostOverride?: unknown): Promise { - const res = await invokePluginService(HOST_PLUGIN_NAME, 'getAdapters', {}, hostOverride) + const res = await callHostTransport( + NETWORK_ADAPTER_IPC_METHOD, + { action: 'listAdapters' }, + hostOverride + ) if (!res.ok) { return createFailedSnapshot(describeHostError(res.error, t('errNoHostReason'))) } @@ -258,9 +262,10 @@ export async function fetchNetworkAdapters(hostOverride?: unknown): Promise( - HOST_PLUGIN_NAME, - 'setDns', - { adapterName: name, name, primaryDns: isDhcp ? '' : pDns }, + // 经专用 network_adapter IPC 设置主/备 DNS 或传空 primaryDns 恢复 DHCP + const res = await callHostTransport>( + NETWORK_ADAPTER_IPC_METHOD, + { + action: 'setDns', + adapterName: name, + primaryDns: isDhcp ? '' : pDns, + ...(!isDhcp && sDns ? { secondaryDns: sDns } : {}) + }, hostOverride ) - if (res.ok) { + if (res.ok && (!res.data || res.data.success !== false)) { + const requestedServers = isDhcp ? [] : (sDns ? [pDns, sDns] : [pDns]) + const actualServers = Array.isArray(res.data?.dnsServers) + ? (res.data.dnsServers as unknown[]).map(textOf).filter(Boolean) + : requestedServers return { ok: true, adapterId: name, - dnsServers: isDhcp ? [] : [pDns], - message: isDhcp ? t('msgDnsRestored', { name }) : t('msgDnsSet', { name, dns: pDns }) + dnsServers: actualServers, + message: isDhcp ? t('msgDnsRestored', { name }) : t('msgDnsSet', { name, dns: actualServers.join(', ') || pDns }) } } return { ok: false, adapterId: name, dnsServers: [], - message: t('errSetDnsFailed', { name, error: describeHostError(res.error, t('errNoHostReason')) }) + message: t('errSetDnsFailed', { name, error: describeHostError(res.data?.error ?? res.error, t('errNoHostReason')) }) } } export async function flushSystemDnsCache(hostOverride?: unknown): Promise<{ ok: boolean; message: string }> { - const res = await invokePluginService(HOST_PLUGIN_NAME, 'flushDns', {}, hostOverride) - if (res.ok) { + const res = await callHostTransport>( + NETWORK_ADAPTER_IPC_METHOD, + { action: 'flushDns' }, + hostOverride + ) + if (res.ok && (!res.data || res.data.success !== false)) { return { ok: true, message: t('msgDnsFlushed') } } return { ok: false, - message: t('errFlushDnsFailed', { error: describeHostError(res.error, t('errNoHostReason')) }) + message: t('errFlushDnsFailed', { error: describeHostError(res.data?.error ?? res.error, t('errNoHostReason')) }) } } diff --git a/extensions/network-adapter/src/native-ipc.ts b/extensions/network-adapter/src/native-ipc.ts index 51576b99..13643277 100644 --- a/extensions/network-adapter/src/native-ipc.ts +++ b/extensions/network-adapter/src/native-ipc.ts @@ -174,11 +174,13 @@ function normalizeMethodResult(method: string, payload: DynamicBridge): DynamicB if (method === 'system_get_battery_status') { // 宿主约定 percent 超出 0-100(如 255)表示无电池或电量未知,不能改写成 100% + // 若宿主明确给出 hasBattery 布尔值,必须原样保留,仅在缺失时按合法电量推算 const rawPct = payload.percent - const hasBattery = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const validPct = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const hasBattery = typeof payload.hasBattery === 'boolean' ? payload.hasBattery : validPct return { ...payload, - percent: hasBattery ? rawPct : null, + percent: validPct ? rawPct : null, hasBattery } } @@ -489,6 +491,8 @@ export interface RealDirectoryScanResult extends Iterable approximate?: boolean /** 宿主实际遍历的条目数 */ visitedEntries?: number + /** 目录本身不存在(ENOENT) */ + missing?: boolean /** 读取失败的真实原因;已有文件仍可使用,但不能当作完整结果。 */ error?: string } @@ -497,6 +501,7 @@ interface ScanResultMeta { truncated?: boolean approximate?: boolean visitedEntries?: number + missing?: boolean } export interface ScanDirectoryTreeOptions { @@ -504,6 +509,10 @@ export interface ScanDirectoryTreeOptions { maxFiles?: number collectTopN?: number filterExt?: RegExp + /** 为 true 时,目录本身不存在(ENOENT)按空目录处理,不返回 error(权限拒绝/读取失败仍照常报错) */ + ignoreMissing?: boolean + /** Top-N 保留与排序方式:默认按体积降序,下载/录屏等时效场景可传 mtime-desc */ + sortBy?: 'size-desc' | 'mtime-desc' hostOverride?: DynamicBridge } @@ -519,8 +528,9 @@ function normalizeIndexedFileEntry(f: DynamicBridge): RealIndexedFileEntry { const sz = Number(f?.size ?? f?.sizeBytes ?? 0) const isDir = Boolean(f?.is_dir || f?.isDir || f?.isDirectory) const rawMtime = Number(f?.mtime ?? f?.mtimeMs ?? 0) - const mtimeMs = rawMtime > 1e11 ? rawMtime : rawMtime > 0 ? rawMtime * 1000 : Date.now() - const mtimeSec = rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime + const validMtime = Number.isFinite(rawMtime) && rawMtime > 0 + const mtimeMs = validMtime ? (rawMtime > 1e11 ? rawMtime : rawMtime * 1000) : 0 + const mtimeSec = validMtime ? (rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime) : 0 if (p && sz >= 0) realFileSizeCache.set(p, sz) return { name, @@ -551,6 +561,7 @@ function makeScanResult( subdirs, ...(meta.truncated ? { truncated: true } : {}), ...(meta.approximate ? { approximate: true } : {}), + ...(meta.missing ? { missing: true } : {}), ...(typeof meta.visitedEntries === 'number' ? { visitedEntries: meta.visitedEntries } : {}), [Symbol.iterator]() { return files[Symbol.iterator]() @@ -609,13 +620,40 @@ export async function scanRealDirectoryTree( return result.error ? { ...result.scan, error: result.error } : result.scan } +/** 仅当正则明确声明了扩展名(含 `\.`)时提取后缀列表,避免把 `thumbcache|iconcache` 等文件名关键词误拆成假扩展名 */ +function extractExtensionTokensFromFilter(filterExt: RegExp): string[] { + const src = filterExt.source + if (!src.includes('\\.')) return [] + const afterDot = src.slice(src.indexOf('\\.') + 2) + const rawTokens = afterDot.match(/[a-z0-9]{1,8}/gi) || [] + const seen = new Set() + const out: string[] = [] + for (const token of rawTokens) { + const lower = token.toLowerCase() + if (!lower || seen.has(lower)) continue + seen.add(lower) + out.push(lower) + } + return out +} + +function isMissingDirectoryError(res: { error?: string; errorCode?: string; errorDetails?: Record }): boolean { + if (res.errorDetails?.reason === 'ENOENT' || res.errorCode === 'ENOENT') return true + const msg = String(res.error || '') + return /Directory does not exist|ENOENT/i.test(msg) +} + /** 一次界面扫描的错误汇总;多个目录并行扫描时保留可读目录的结果。 */ export function createDirectoryScanner(hostOverride?: DynamicBridge) { const failures = new Map() return { async scan(dir: string, options: number | ScanDirectoryTreeOptions = 160) { const result = await scanRealDirectoryTree(dir, options, hostOverride) - const error = result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') + const ignoreMissing = typeof options === 'object' && options !== null && options.ignoreMissing === true + const error = + result.missing && ignoreMissing + ? '' + : result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') if (error) failures.set(dir, error) else failures.delete(dir) return result @@ -648,26 +686,38 @@ async function scanDirectoryTreeWithError( const safeLimit = Math.min(200, Math.max(1, Math.floor(rawLimit || 160))) const hostOverride = opts.hostOverride const filterExt = opts.filterExt + const ignoreMissing = opts.ignoreMissing === true const dirQuery = `dir:${targetDir}` try { let rawPayload: DynamicBridge = null + const searchParams: Record = { + query: dirQuery, + limit: safeLimit, + ...(opts.sortBy ? { sortBy: opts.sortBy } : {}) + } const res = await callHostTransport( 'system_search_files', - { query: dirQuery, limit: safeLimit }, + searchParams, hostOverride ) - if (res.ok && res.data) { + if (res.ok && res.data && res.data.degraded !== true) { rawPayload = res.data + } else if (!res.ok && ignoreMissing && isMissingDirectoryError(res)) { + const missingScan = makeScanResult([], 0, 0, [], { missing: true }) + return { scan: missingScan } } - if (!rawPayload && !hostOverride && typeof window !== 'undefined') { + if (!rawPayload && !hostOverride && res.errorCode === 'METHOD_NOT_AVAILABLE' && typeof window !== 'undefined') { const w = window as DynamicBridge if (typeof w.__ztoolsLauncher?.searchFiles === 'function') { const rawOuter = await w.__ztoolsLauncher.searchFiles(dirQuery, safeLimit) - rawPayload = + const candidate = rawOuter && typeof rawOuter === 'object' && 'data' in rawOuter && rawOuter.data ? rawOuter.data : rawOuter + if (candidate && candidate.degraded !== true && candidate.success !== false) { + rawPayload = candidate + } } } @@ -678,29 +728,32 @@ async function scanDirectoryTreeWithError( let files: RealIndexedFileEntry[] = rawPayload.files.map(normalizeIndexedFileEntry) if (filterExt instanceof RegExp) { files = files.filter(f => !f.isDir && (filterExt.test(f.name) || filterExt.test(f.ext))) - // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索目标扩展名 + // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索明确声明的目标扩展名 if (files.length === 0 && !hostOverride) { - const extTokens = (filterExt.source.match(/[a-z0-9]{2,5}/gi) || []) - .filter(t => !['thumbcache', 'iconcache'].includes(t.toLowerCase())) - .slice(0, 4) - // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 - const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() - const extraLists = await Promise.all( - extTokens.map(ext => searchRealIndexedFiles(`.${ext.toLowerCase()}`, 30, hostOverride)) - ) - const seen = new Set() - for (const list of extraLists) { - for (const item of list) { - if (!item.isDir && item.size > 0 && !seen.has(item.path)) { - if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { - seen.add(item.path) - files.push(item) + const extTokens = extractExtensionTokensFromFilter(filterExt) + if (extTokens.length > 0) { + // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 + const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() + const extraLists = await Promise.all( + extTokens.map(ext => searchRealIndexedFiles(`.${ext}`, 30, hostOverride)) + ) + const seen = new Set() + for (const list of extraLists) { + for (const item of list) { + if (!item.isDir && item.size > 0 && !seen.has(item.path)) { + if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { + seen.add(item.path) + files.push(item) + } } } } } } } + // 先基于过滤后的完整命中集合计算总文件数与总字节数,再按 collectTopN 裁剪样本列表 + const matchedCount = files.length + const matchedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) if (typeof opts.collectTopN === 'number' && opts.collectTopN > 0 && files.length > opts.collectTopN) { files = files.slice(0, opts.collectTopN) } @@ -714,11 +767,10 @@ async function scanDirectoryTreeWithError( ...(s.approximate === true ? { approximate: true } : {}) })) : [] - const computedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) const totalFilesCount = - filterExt instanceof RegExp ? files.length : Number(rawPayload.total_matches ?? files.length) + filterExt instanceof RegExp ? matchedCount : Number(rawPayload.total_matches ?? matchedCount) const totalBytesCount = - filterExt instanceof RegExp ? computedBytes : Number(rawPayload.total_bytes ?? computedBytes) + filterExt instanceof RegExp ? matchedBytes : Number(rawPayload.total_bytes ?? matchedBytes) const visited = Number(rawPayload.visited_entries) return { scan: makeScanResult(files, totalFilesCount, totalBytesCount, subdirs, { @@ -1817,8 +1869,6 @@ export async function writeRealClipboardText(text: string, hostOverride?: Dynami const payload = { text: String(text || '') } const res = await callHostTransport('clipboard_copy_text', payload, hostOverride) if (res.ok) return true - const fallbackRes = await callHostTransport('clipboard_write_text', payload, hostOverride) - if (fallbackRes.ok) return true try { if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) { await navigator.clipboard.writeText(String(text || '')) diff --git a/extensions/network-adapter/tests/network-adapter.host.test.mjs b/extensions/network-adapter/tests/network-adapter.host.test.mjs index 805d2eef..2be14814 100644 --- a/extensions/network-adapter/tests/network-adapter.host.test.mjs +++ b/extensions/network-adapter/tests/network-adapter.host.test.mjs @@ -13,34 +13,41 @@ import { setRuntimeLocale('zh-CN') /** - * 按客户端内置网卡服务的真实行为模拟 dllplugin_call: - * - 函数名不区分大小写:getAdapters / listAdapters / getNetworkInterfaces 读列表,flushDns 刷新缓存,setDns / applyPreset 改 DNS; - * - 其他任何函数名都会落到读取网卡列表并返回成功,所以插件用错函数名时只能靠记录的调用发现; - * - 返回值与客户端一致:结果对象再在 data 里复制一份。 + * 按客户端专用 network_adapter IPC 的真实行为模拟: + * - action 严格白名单:listAdapters / setDns / flushDns; + * - 严禁再触发 dllplugin_call 或 shell_exec。 */ function createHostLikeNetworkService(options = {}) { const { adapters = [], listError = null, - setDnsResult = () => ({ ok: true, success: true, output: '' }), - flushResult = () => ({ ok: true, success: true, output: 'Windows IP 配置\n已成功刷新 DNS 解析缓存。' }) + setDnsResult = (params) => ({ + success: true, + adapterName: params.adapterName, + isDhcp: !params.primaryDns, + dnsServers: params.primaryDns ? (params.secondaryDns ? [params.primaryDns, params.secondaryDns] : [params.primaryDns]) : [] + }), + flushResult = () => ({ success: true, flushed: true }) } = options const calls = [] const shellCalls = [] - const wrap = (record) => ({ ...record, data: { ...record } }) const host = { - dllplugin_call: async ({ plugin, func, params }) => { - calls.push({ plugin, func, params }) - const fn = String(func).toLowerCase() - if (fn === 'flushdns') return wrap(flushResult()) - if (fn === 'setdns' || fn === 'applypreset') { - if (!String(params.adapterName ?? params.name ?? '')) return wrap({ ok: false, success: false, error: '未指定网卡名称' }) - return wrap(setDnsResult(params)) + network_adapter: async (params) => { + calls.push(params) + if (params.action === 'flushDns') return flushResult() + if (params.action === 'setDns') { + if (!String(params.adapterName ?? '')) return { success: false, error: '未指定网卡名称' } + return setDnsResult(params) } - if (listError) return wrap({ ok: false, success: false, errorCode: 'ADAPTER_LIST_FAILED', error: listError }) - return wrap({ ok: true, success: true, adapters }) + if (params.action === 'listAdapters') { + if (listError) return { success: false, errorCode: 'ADAPTER_LIST_FAILED', error: listError } + return { success: true, adapters } + } + throw new Error(`未预期的 network_adapter action: ${params.action}`) + }, + dllplugin_call: async () => { + throw new Error('network-adapter 严禁再调用 dllplugin_call') }, - // 客户端不允许插件执行任意命令(shell_exec 恒定拒绝);插件不应再尝试 shell_exec: async (params) => { shellCalls.push(params) throw new Error('Electron 不允许 renderer 执行任意 shell 命令') @@ -84,18 +91,15 @@ test('network-adapter: 真实网卡列表聚合、DNS 预设切换与无管理 assert.equal(snap.primaryIpv4, '192.168.50.10') assert.equal(snap.primaryGateway, '192.168.50.1') assert.equal(snap.primaryDns, '192.168.50.1') - assert.equal(svc.calls[0].plugin, 'NetworkAdapterPlugin') - assert.equal(svc.calls[0].func, 'getAdapters') + assert.deepEqual(svc.calls[0], { action: 'listAdapters' }) - // 正常切换 DNS:必须调用客户端实际支持的 setDns,且只传首选 DNS + // 正常切换 DNS:调用专用 network_adapter.setDns svc.calls.length = 0 const okDns = await applyDnsPreset('Ethernet 2', '223.5.5.5', undefined, svc.host) assert.equal(okDns.ok, true) assert.deepEqual(okDns.dnsServers, ['223.5.5.5']) assert.equal(svc.calls.length, 1) - assert.equal(svc.calls[0].func, 'setDns') - assert.equal(svc.calls[0].params.adapterName, 'Ethernet 2') - assert.equal(svc.calls[0].params.primaryDns, '223.5.5.5') + assert.deepEqual(svc.calls[0], { action: 'setDns', adapterName: 'Ethernet 2', primaryDns: '223.5.5.5' }) // 异常场景 1:非法 DNS IPv4 格式拦截 const badIp = await applyDnsPreset('Ethernet 2', '999.999.1.1', '', svc.host) @@ -114,7 +118,7 @@ test('network-adapter: 真实网卡列表聚合、DNS 预设切换与无管理 // 异常场景 4:flushSystemDnsCache 当宿主失败时返回 ok: false,且不再尝试执行命令 const failSvc = createHostLikeNetworkService({ - flushResult: () => ({ ok: false, success: false, output: '无法刷新 DNS 解析缓存: 执行期间,函数出了问题。' }) + flushResult: () => ({ success: false, error: '无法刷新 DNS 解析缓存: 执行期间,函数出了问题。' }) }) const failFlush = await flushSystemDnsCache(failSvc.host) assert.equal(failFlush.ok, false) @@ -123,7 +127,7 @@ test('network-adapter: 真实网卡列表聚合、DNS 预设切换与无管理 const okFlush = await flushSystemDnsCache(svc.host) assert.equal(okFlush.ok, true) - assert.equal(svc.calls.at(-1).func, 'flushDns') + assert.deepEqual(svc.calls.at(-1), { action: 'flushDns' }) }) test('network-adapter: 客户端读取网卡失败时如实返回错误,不用 127.0.0.1 或示例网卡冒充', async () => { @@ -162,7 +166,7 @@ test('network-adapter: 没有客户端时读取、改 DNS、刷新缓存都返 test('network-adapter: 客户端返回无法识别的数据结构时报错,不当成空列表', async () => { const host = { - dllplugin_call: async () => ({ ok: true, success: true, items: 'oops', data: { ok: true, success: true, items: 'oops' } }) + network_adapter: async () => ({ success: true, items: 'oops' }) } const snap = await fetchNetworkAdapters(host) assert.equal(snap.ok, false) @@ -234,18 +238,27 @@ test('network-adapter: 主网卡优先选已连接且有网关的物理网卡, assert.equal(pickPrimaryAdapter([adapters[0], adapters[1]]).id, 'b') }) -test('network-adapter: 备选 DNS 直接拒绝且不调用客户端,恢复自动获取时传空首选 DNS', async () => { +test('network-adapter: 支持同时设置主备 DNS 并校验非法/重复备选 DNS,恢复自动获取时传空首选 DNS', async () => { const svc = createHostLikeNetworkService() const both = await applyDnsPreset('Ethernet 2', '223.5.5.5', '119.29.29.29', svc.host) - assert.equal(both.ok, false) - assert.match(both.message, /不支持同时设置备选 DNS/) - assert.equal(svc.calls.length, 0) + assert.equal(both.ok, true) + assert.deepEqual(both.dnsServers, ['223.5.5.5', '119.29.29.29']) + assert.deepEqual(svc.calls[0], { action: 'setDns', adapterName: 'Ethernet 2', primaryDns: '223.5.5.5', secondaryDns: '119.29.29.29' }) + + const badSecondary = await applyDnsPreset('Ethernet 2', '223.5.5.5', 'not-an-ip', svc.host) + assert.equal(badSecondary.ok, false) + assert.match(badSecondary.message, /备选 DNS 地址格式不合法/) + assert.equal(svc.calls.length, 1) + + const dupSecondary = await applyDnsPreset('Ethernet 2', '223.5.5.5', '223.5.5.5', svc.host) + assert.equal(dupSecondary.ok, false) + assert.match(dupSecondary.message, /不能与首选 DNS 相同/) + assert.equal(svc.calls.length, 1) const dhcp = await applyDnsPreset('Ethernet 2', 'DHCP', undefined, svc.host) assert.equal(dhcp.ok, true) assert.deepEqual(dhcp.dnsServers, []) - assert.equal(svc.calls[0].func, 'setDns') - assert.equal(svc.calls[0].params.primaryDns, '', '客户端以空首选 DNS 表示恢复 DHCP') + assert.deepEqual(svc.calls[1], { action: 'setDns', adapterName: 'Ethernet 2', primaryDns: '' }) assert.match(dhcp.message, /恢复为自动获取/) }) diff --git a/extensions/network-adapter/tests/network-adapter.ui.test.mjs b/extensions/network-adapter/tests/network-adapter.ui.test.mjs index 16aad04b..ec6759ff 100644 --- a/extensions/network-adapter/tests/network-adapter.ui.test.mjs +++ b/extensions/network-adapter/tests/network-adapter.ui.test.mjs @@ -4,23 +4,24 @@ import { Toast } from '@ztools/declarative-ui' import { createHost, mount, tick } from '../../shared/test-harness.mjs' import NetworkAdapterCommand from '../dist/index.js' -const wrap = (record) => ({ ...record, data: { ...record } }) - -/** 模拟客户端内置网卡服务(dllplugin_call),可在测试中途切换返回结果 */ +/** 模拟客户端专用 network_adapter IPC,可在测试中途切换返回结果 */ function installNetworkService(host, state) { - host.ipc.dllplugin_call = async ({ func, params }) => { - const fn = String(func).toLowerCase() - if (fn === 'flushdns') return wrap(state.flush ?? { ok: true, success: true, output: '' }) - if (fn === 'setdns' || fn === 'applypreset') { - const res = state.setDns ? state.setDns(params) : { ok: true, success: true, output: '' } - return wrap(res) + host.ipc.network_adapter = async (params) => { + if (params.action === 'flushDns') return state.flush ?? { success: true, flushed: true } + if (params.action === 'setDns') { + return state.setDns + ? state.setDns(params) + : { success: true, adapterName: params.adapterName, isDhcp: !params.primaryDns, dnsServers: params.primaryDns ? [params.primaryDns] : [] } + } + if (params.action === 'listAdapters') { + if (state.listError) return { success: false, errorCode: 'ADAPTER_LIST_FAILED', error: state.listError } + return { success: true, adapters: state.adapters } } - if (state.listError) return wrap({ ok: false, success: false, errorCode: 'ADAPTER_LIST_FAILED', error: state.listError }) - return wrap({ ok: true, success: true, adapters: state.adapters }) + throw new Error(`未预期的 network_adapter action: ${params.action}`) } } -const funcCalls = (host) => host.ipcCalls.filter(([m]) => m === 'dllplugin_call').map(([, p]) => p.func) +const actionCalls = (host) => host.ipcCalls.filter(([m]) => m === 'network_adapter').map(([, p]) => p.action) const ETHERNET = { id: 'Ethernet 2', @@ -114,32 +115,33 @@ test('network-adapter UI: 修改 DNS 成功后重新读取实际配置;失败 assert.equal(host.lastToast().title, '已复制 MAC 地址') // 失败:客户端拒绝(未以管理员身份运行) - state.setDns = () => ({ ok: false, success: false, output: '', error: '请求的操作需要提升(以管理员身份运行)。' }) + state.setDns = () => ({ success: false, errorCode: 'ADMIN_PRIVILEGE_REQUIRED', error: 'ADMIN_PRIVILEGE_REQUIRED: 请求的操作需要提升(以管理员身份运行)。' }) host.ipcCalls.length = 0 await view.run(view.item('Ethernet 2'), presetTitle) assert.equal(host.lastToast().style, Toast.Style.Failure) assert.match(host.lastToast().message, /需要提升/) - assert.deepEqual(funcCalls(host), ['setDns'], '失败后不重新读取,也不在本地改写 DNS') + assert.deepEqual(actionCalls(host), ['setDns'], '失败后不重新读取,也不在本地改写 DNS') + assert.ok(!host.ipcCalls.some(([m]) => m === 'dllplugin_call')) assert.match(view.item('Ethernet 2').props.subtitle, /DNS: 192\.168\.50\.1/) // 成功:系统里的 DNS 变了,插件重新读取后显示实际值 state.setDns = (params) => { state.adapters = [{ ...ETHERNET, dnsServers: [params.primaryDns] }] - return { ok: true, success: true, output: '' } + return { success: true, adapterName: params.adapterName, dnsServers: [params.primaryDns], isDhcp: false } } host.ipcCalls.length = 0 await view.run(view.item('Ethernet 2'), presetTitle) await tick() assert.equal(host.toasts.find((t) => t.title === '网卡 DNS 已修改')?.style, Toast.Style.Success) - assert.deepEqual(funcCalls(host), ['setDns', 'getAdapters']) + assert.deepEqual(actionCalls(host), ['setDns', 'listAdapters']) assert.match(view.item('Ethernet 2').props.subtitle, /DNS: 223\.5\.5\.5/) // 恢复自动获取:传空首选 DNS host.ipcCalls.length = 0 - state.setDns = () => ({ ok: true, success: true, output: '' }) + state.setDns = () => ({ success: true, adapterName: 'Ethernet 2', dnsServers: [], isDhcp: true }) await view.run(view.item('Ethernet 2'), '恢复自动获取 DNS(需管理员权限)') - const setDnsCall = host.ipcCalls.find(([m, p]) => m === 'dllplugin_call' && p.func === 'setDns') - assert.equal(setDnsCall[1].params.primaryDns, '') + const setDnsCall = host.ipcCalls.find(([m, p]) => m === 'network_adapter' && p.action === 'setDns') + assert.equal(setDnsCall[1].primaryDns, '') view.unmount() }) @@ -147,7 +149,7 @@ test('network-adapter UI: 刷新 DNS 缓存失败时提示失败', async () => { const host = createHost() installNetworkService(host, { adapters: [ETHERNET], - flush: { ok: false, success: false, output: '无法刷新 DNS 解析缓存: 执行期间,函数出了问题。' } + flush: { success: false, error: '无法刷新 DNS 解析缓存: 执行期间,函数出了问题。' } }) const view = await mount(NetworkAdapterCommand, host) view.tree().props.filterBar.actions.find((a) => a.id === 'flush-dns').onAction() diff --git a/extensions/network-rescue/README.en.md b/extensions/network-rescue/README.en.md new file mode 100644 index 00000000..c0db382c --- /dev/null +++ b/extensions/network-rescue/README.en.md @@ -0,0 +1,19 @@ +# Network Rescue + +Inspect network adapter addresses, DNS resolution, internet connectivity, proxies, and the hosts file, and run repair actions including flushing the DNS cache, disabling the system proxy, resetting Winsock, and restoring default firewall policies. + +## Usage + +- Command: `Network Rescue`. +- Automatically diagnoses on open: whether a usable local IPv4 address exists, whether `www.baidu.com` resolves, whether TCP port 53 on `223.5.5.5` is reachable, whether proxy environment variables are set, and the number of active rules in the hosts file (more than 50 rules is flagged as abnormal). Winsock and Network Location Awareness service statuses are inferred solely from usable IP availability; firewall status is not actively probed. +- Available repair actions: Flush DNS Cache (`ipconfig /flushdns`), Disable System Proxy (sets registry `ProxyEnable` to `0`), Reset Winsock (`netsh winsock reset`), Renew DHCP Address (`ipconfig /renew`), Restore Default Firewall Policy (`netsh advfirewall reset`), and Restart Network Location Awareness Service; "Check hosts" and "Connectivity Check" are read-only checks that make no changes. +- `Enter` runs the selected repair action, `Ctrl+Enter` copies the command shown in the list (which may differ slightly from the exact executed command—for example, Reset Winsock runs only `netsh winsock reset`, and Renew DHCP runs only `ipconfig /renew`), `Ctrl+R` re-runs diagnostics, and `Ctrl+K` opens the action panel; when issues are detected, you can repair all abnormal items at once from the top bar or action panel. +- Repairs execute without an extra confirmation prompt. Restoring the default firewall policy removes any custom firewall rules you added. Resetting Winsock, restoring the firewall, and restarting the Network Location Awareness service require running ZTools as Administrator, otherwise they report failure. + +## Platforms & Requirements + +- Supported: Windows only + +## Network & Data + +- Diagnostics resolve `www.baidu.com` and connect to TCP port 53 on `223.5.5.5` (Alibaba Public DNS) to test internet reachability; no data is uploaded. diff --git a/extensions/network-rescue/plugin.json b/extensions/network-rescue/plugin.json index eb79d15d..2196d64a 100644 --- a/extensions/network-rescue/plugin.json +++ b/extensions/network-rescue/plugin.json @@ -2,7 +2,7 @@ "id": "network-rescue", "name": "网络修复", "description": "一键检测断网原因,支持刷新 DNS 缓存、重置网络配置与清除异常代理,快速恢复正常上网", - "version": "2.0.10", + "version": "2.0.11", "author": "ZTools Team", "entry": "dist/index.js", "icon": "icon.svg", @@ -40,7 +40,14 @@ "troubleshoot", "dns", "proxy", - "reset" + "reset", + "network rescue", + "fix network", + "no internet", + "flush dns", + "reset network", + "repair wifi", + "network fix" ], "screenshots": [ { @@ -56,5 +63,16 @@ { "path": "screenshots/02-action-panel.png" } + ], + "keywords": [ + "网络修复", + "断网修复", + "连不上网", + "刷新dns", + "重置网络", + "网络诊断", + "修网络", + "上不了网", + "代理清理" ] } diff --git a/extensions/network-rescue/src/logic.ts b/extensions/network-rescue/src/logic.ts index 75a5e7fe..c7ebd062 100644 --- a/extensions/network-rescue/src/logic.ts +++ b/extensions/network-rescue/src/logic.ts @@ -3,7 +3,7 @@ * 针对 Windows / macOS 常见断网故障提供 8 大真实诊断与一键修复能力 */ -import { callHostTransport, invokePluginService, isRealElectronHost, invokeDllPluginCapability } from './native-ipc.js' +import { invokePluginService, isRealElectronHost, invokeDllPluginCapability } from './native-ipc.js' import { t } from './i18n.js' import { resolveErrorMessage } from './error-i18n.js' @@ -222,10 +222,10 @@ export async function runNetworkDiagnostics(hostOverride?: unknown): Promise(DLL_PLUGIN_NAME, 'diagnose', {}, hostOverride) - const fallback = pluginRes.ok ? undefined : await callHostTransport('network_run_diagnostics', {}, hostOverride) - const data = pluginRes.ok ? pluginRes.data : fallback?.ok ? fallback.data : undefined - if (!data) return failure(resolveErrorMessage(pluginRes.error ? pluginRes : fallback, t('errNoDiagResult'))) + const data = pluginRes.ok ? pluginRes.data : undefined + if (!data) return failure(resolveErrorMessage(pluginRes, t('errNoDiagResult'))) const remote = Array.isArray(data.items) ? data.items : Array.isArray(data.checks) ? data.checks : undefined if (!remote) return failure(t('errInvalidDiagFormat')) let matched = 0 diff --git a/extensions/network-rescue/src/native-ipc.ts b/extensions/network-rescue/src/native-ipc.ts index 51576b99..13643277 100644 --- a/extensions/network-rescue/src/native-ipc.ts +++ b/extensions/network-rescue/src/native-ipc.ts @@ -174,11 +174,13 @@ function normalizeMethodResult(method: string, payload: DynamicBridge): DynamicB if (method === 'system_get_battery_status') { // 宿主约定 percent 超出 0-100(如 255)表示无电池或电量未知,不能改写成 100% + // 若宿主明确给出 hasBattery 布尔值,必须原样保留,仅在缺失时按合法电量推算 const rawPct = payload.percent - const hasBattery = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const validPct = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const hasBattery = typeof payload.hasBattery === 'boolean' ? payload.hasBattery : validPct return { ...payload, - percent: hasBattery ? rawPct : null, + percent: validPct ? rawPct : null, hasBattery } } @@ -489,6 +491,8 @@ export interface RealDirectoryScanResult extends Iterable approximate?: boolean /** 宿主实际遍历的条目数 */ visitedEntries?: number + /** 目录本身不存在(ENOENT) */ + missing?: boolean /** 读取失败的真实原因;已有文件仍可使用,但不能当作完整结果。 */ error?: string } @@ -497,6 +501,7 @@ interface ScanResultMeta { truncated?: boolean approximate?: boolean visitedEntries?: number + missing?: boolean } export interface ScanDirectoryTreeOptions { @@ -504,6 +509,10 @@ export interface ScanDirectoryTreeOptions { maxFiles?: number collectTopN?: number filterExt?: RegExp + /** 为 true 时,目录本身不存在(ENOENT)按空目录处理,不返回 error(权限拒绝/读取失败仍照常报错) */ + ignoreMissing?: boolean + /** Top-N 保留与排序方式:默认按体积降序,下载/录屏等时效场景可传 mtime-desc */ + sortBy?: 'size-desc' | 'mtime-desc' hostOverride?: DynamicBridge } @@ -519,8 +528,9 @@ function normalizeIndexedFileEntry(f: DynamicBridge): RealIndexedFileEntry { const sz = Number(f?.size ?? f?.sizeBytes ?? 0) const isDir = Boolean(f?.is_dir || f?.isDir || f?.isDirectory) const rawMtime = Number(f?.mtime ?? f?.mtimeMs ?? 0) - const mtimeMs = rawMtime > 1e11 ? rawMtime : rawMtime > 0 ? rawMtime * 1000 : Date.now() - const mtimeSec = rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime + const validMtime = Number.isFinite(rawMtime) && rawMtime > 0 + const mtimeMs = validMtime ? (rawMtime > 1e11 ? rawMtime : rawMtime * 1000) : 0 + const mtimeSec = validMtime ? (rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime) : 0 if (p && sz >= 0) realFileSizeCache.set(p, sz) return { name, @@ -551,6 +561,7 @@ function makeScanResult( subdirs, ...(meta.truncated ? { truncated: true } : {}), ...(meta.approximate ? { approximate: true } : {}), + ...(meta.missing ? { missing: true } : {}), ...(typeof meta.visitedEntries === 'number' ? { visitedEntries: meta.visitedEntries } : {}), [Symbol.iterator]() { return files[Symbol.iterator]() @@ -609,13 +620,40 @@ export async function scanRealDirectoryTree( return result.error ? { ...result.scan, error: result.error } : result.scan } +/** 仅当正则明确声明了扩展名(含 `\.`)时提取后缀列表,避免把 `thumbcache|iconcache` 等文件名关键词误拆成假扩展名 */ +function extractExtensionTokensFromFilter(filterExt: RegExp): string[] { + const src = filterExt.source + if (!src.includes('\\.')) return [] + const afterDot = src.slice(src.indexOf('\\.') + 2) + const rawTokens = afterDot.match(/[a-z0-9]{1,8}/gi) || [] + const seen = new Set() + const out: string[] = [] + for (const token of rawTokens) { + const lower = token.toLowerCase() + if (!lower || seen.has(lower)) continue + seen.add(lower) + out.push(lower) + } + return out +} + +function isMissingDirectoryError(res: { error?: string; errorCode?: string; errorDetails?: Record }): boolean { + if (res.errorDetails?.reason === 'ENOENT' || res.errorCode === 'ENOENT') return true + const msg = String(res.error || '') + return /Directory does not exist|ENOENT/i.test(msg) +} + /** 一次界面扫描的错误汇总;多个目录并行扫描时保留可读目录的结果。 */ export function createDirectoryScanner(hostOverride?: DynamicBridge) { const failures = new Map() return { async scan(dir: string, options: number | ScanDirectoryTreeOptions = 160) { const result = await scanRealDirectoryTree(dir, options, hostOverride) - const error = result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') + const ignoreMissing = typeof options === 'object' && options !== null && options.ignoreMissing === true + const error = + result.missing && ignoreMissing + ? '' + : result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') if (error) failures.set(dir, error) else failures.delete(dir) return result @@ -648,26 +686,38 @@ async function scanDirectoryTreeWithError( const safeLimit = Math.min(200, Math.max(1, Math.floor(rawLimit || 160))) const hostOverride = opts.hostOverride const filterExt = opts.filterExt + const ignoreMissing = opts.ignoreMissing === true const dirQuery = `dir:${targetDir}` try { let rawPayload: DynamicBridge = null + const searchParams: Record = { + query: dirQuery, + limit: safeLimit, + ...(opts.sortBy ? { sortBy: opts.sortBy } : {}) + } const res = await callHostTransport( 'system_search_files', - { query: dirQuery, limit: safeLimit }, + searchParams, hostOverride ) - if (res.ok && res.data) { + if (res.ok && res.data && res.data.degraded !== true) { rawPayload = res.data + } else if (!res.ok && ignoreMissing && isMissingDirectoryError(res)) { + const missingScan = makeScanResult([], 0, 0, [], { missing: true }) + return { scan: missingScan } } - if (!rawPayload && !hostOverride && typeof window !== 'undefined') { + if (!rawPayload && !hostOverride && res.errorCode === 'METHOD_NOT_AVAILABLE' && typeof window !== 'undefined') { const w = window as DynamicBridge if (typeof w.__ztoolsLauncher?.searchFiles === 'function') { const rawOuter = await w.__ztoolsLauncher.searchFiles(dirQuery, safeLimit) - rawPayload = + const candidate = rawOuter && typeof rawOuter === 'object' && 'data' in rawOuter && rawOuter.data ? rawOuter.data : rawOuter + if (candidate && candidate.degraded !== true && candidate.success !== false) { + rawPayload = candidate + } } } @@ -678,29 +728,32 @@ async function scanDirectoryTreeWithError( let files: RealIndexedFileEntry[] = rawPayload.files.map(normalizeIndexedFileEntry) if (filterExt instanceof RegExp) { files = files.filter(f => !f.isDir && (filterExt.test(f.name) || filterExt.test(f.ext))) - // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索目标扩展名 + // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索明确声明的目标扩展名 if (files.length === 0 && !hostOverride) { - const extTokens = (filterExt.source.match(/[a-z0-9]{2,5}/gi) || []) - .filter(t => !['thumbcache', 'iconcache'].includes(t.toLowerCase())) - .slice(0, 4) - // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 - const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() - const extraLists = await Promise.all( - extTokens.map(ext => searchRealIndexedFiles(`.${ext.toLowerCase()}`, 30, hostOverride)) - ) - const seen = new Set() - for (const list of extraLists) { - for (const item of list) { - if (!item.isDir && item.size > 0 && !seen.has(item.path)) { - if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { - seen.add(item.path) - files.push(item) + const extTokens = extractExtensionTokensFromFilter(filterExt) + if (extTokens.length > 0) { + // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 + const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() + const extraLists = await Promise.all( + extTokens.map(ext => searchRealIndexedFiles(`.${ext}`, 30, hostOverride)) + ) + const seen = new Set() + for (const list of extraLists) { + for (const item of list) { + if (!item.isDir && item.size > 0 && !seen.has(item.path)) { + if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { + seen.add(item.path) + files.push(item) + } } } } } } } + // 先基于过滤后的完整命中集合计算总文件数与总字节数,再按 collectTopN 裁剪样本列表 + const matchedCount = files.length + const matchedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) if (typeof opts.collectTopN === 'number' && opts.collectTopN > 0 && files.length > opts.collectTopN) { files = files.slice(0, opts.collectTopN) } @@ -714,11 +767,10 @@ async function scanDirectoryTreeWithError( ...(s.approximate === true ? { approximate: true } : {}) })) : [] - const computedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) const totalFilesCount = - filterExt instanceof RegExp ? files.length : Number(rawPayload.total_matches ?? files.length) + filterExt instanceof RegExp ? matchedCount : Number(rawPayload.total_matches ?? matchedCount) const totalBytesCount = - filterExt instanceof RegExp ? computedBytes : Number(rawPayload.total_bytes ?? computedBytes) + filterExt instanceof RegExp ? matchedBytes : Number(rawPayload.total_bytes ?? matchedBytes) const visited = Number(rawPayload.visited_entries) return { scan: makeScanResult(files, totalFilesCount, totalBytesCount, subdirs, { @@ -1817,8 +1869,6 @@ export async function writeRealClipboardText(text: string, hostOverride?: Dynami const payload = { text: String(text || '') } const res = await callHostTransport('clipboard_copy_text', payload, hostOverride) if (res.ok) return true - const fallbackRes = await callHostTransport('clipboard_write_text', payload, hostOverride) - if (fallbackRes.ok) return true try { if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) { await navigator.clipboard.writeText(String(text || '')) diff --git a/extensions/network-rescue/tests/network-rescue.audit-fixes.test.mjs b/extensions/network-rescue/tests/network-rescue.audit-fixes.test.mjs index 392c3e40..490bd39f 100644 --- a/extensions/network-rescue/tests/network-rescue.audit-fixes.test.mjs +++ b/extensions/network-rescue/tests/network-rescue.audit-fixes.test.mjs @@ -5,15 +5,16 @@ import { runNetworkDiagnostics, executeNetworkRepair } from '../dist/logic.js' import { NetworkRescueCommand } from '../dist/index.js' import { createHost, mount } from '../../shared/test-harness.mjs' -test('两个诊断接口失败保持未知状态,界面没有健康分或假延迟', async () => { +test('诊断接口失败保持未知状态,界面没有健康分或假延迟', async () => { const h=createHost() - for(const method of ['dllplugin_call','network_run_diagnostics']) h.ipc[method]=async()=>{throw new Error('IPC_FAILED')} + h.ipc.dllplugin_call=async()=>{throw new Error('IPC_FAILED')} const result=await runNetworkDiagnostics() assert.equal(result.ok,false) assert.equal(result.unknownCount,8) assert.equal(result.items.every(i=>i.status==='unknown'),true) assert.equal(result.latencyMs,null) assert.equal(result.overallHealthScore,undefined) + assert.equal(h.ipcCalls.some(([method])=>method==='network_run_diagnostics'),false) const ui=await mount(NetworkRescueCommand,h) const output=JSON.stringify(ui.tree()) assert.doesNotMatch(output,/IPC_FAILED/) @@ -35,7 +36,7 @@ test('部分与畸形诊断不会把未检测项补成健康', async () => { test('i18n 热切换回归:列表标题与状态随语言实时切换,不固化初始语言', async () => { const h = createHost() - for (const method of ['dllplugin_call', 'network_run_diagnostics']) h.ipc[method] = async () => ({ checks: [] }) + h.ipc.dllplugin_call = async () => ({ checks: [] }) try { setRuntimeLocale('zh-CN') const ui = await mount(NetworkRescueCommand, h) diff --git a/extensions/ocr/README.en.md b/extensions/ocr/README.en.md new file mode 100644 index 00000000..c98fade5 --- /dev/null +++ b/extensions/ocr/README.en.md @@ -0,0 +1,31 @@ +# Offline Text OCR + +Recognize text on screen, in the clipboard, and in image files completely offline: macOS uses the built-in Vision framework, while Windows uses the client's bundled PP-OCRv5 Chinese recognition model (Korean uses Windows system OCR). You can also open it directly by typing `ocr` in the search box. + +## Usage + +- **Screenshot OCR** (`ocr region`, `screenshot ocr`, `capture text`): Minimizes the ZTools window, lets you drag to select a screen region and press `Enter` (`Esc` to cancel). Recognized text is copied straight to the clipboard with a system notification. +- **Clipboard OCR** (`clipboard ocr`, `paste ocr`): Recognizes text from the image currently on the clipboard and copies the result back to the clipboard. Shows a prompt if no image is on the clipboard. +- **Offline Text OCR** (`ocr`, `text ocr`, `image to text`): Result workbench. + - Top "Screenshot OCR" (`Cmd/Ctrl+N`): Select a screen region to recognize; the window reappears afterward and copies the result automatically. + - Top "Add Images" (`Cmd/Ctrl+O`): Select multiple images at once to process sequentially with progress in the status bar; images already in the list move to the top and are re-recognized without duplicates. + - Action panel "Select Folder..." (`Cmd/Ctrl+Shift+O`): Choose a folder to recursively queue up to 5 directory levels and up to 100 supported images per batch; you can also drag and drop or paste images and folders directly. + - Action panel "Recognize Clipboard Image" (`Cmd/Ctrl+Shift+V`): Copies the result automatically. + - The right pane shows full text for each result. Press `Enter` on a succeeded item to copy text, or `Enter` on a failed item to retry (re-recognizes images with the current language, or re-captures screenshot/clipboard and replaces the failed entry on success). `Cmd/Ctrl+R` re-recognizes an image, `Cmd/Ctrl+Shift+C` copies all results, `Cmd/Ctrl+Shift+Backspace` clears finished items, and `Cmd/Ctrl+K` lets you reveal the original image in file manager or remove it from the list. + - You cannot start a new recognition task while one is running; closing the plugin before an item finishes marks it as "Recognition Interrupted" on next open. + - Use the search box to filter by filename or recognized text. +- **Recognition Language**: Choose on the right of the workbench search bar—Simplified Chinese (default, mixed Chinese/English), English, Japanese, or Korean. Your selection is saved and applies to Screenshot OCR and Clipboard OCR as well. +- **Supported Formats**: PNG, JPEG, BMP, GIF, TIFF; macOS also supports HEIC and WebP (Windows requires corresponding system image extensions). On macOS, single images are limited to 16 MB; oversized images above the recognition limit are downscaled before OCR. + +## Platforms & Requirements + +- Supported: macOS, Windows; requires ZTools 1.1.8.9 or later. +- macOS: Screenshot OCR requires granting Screen Recording permission to ZTools in System Settings > Privacy & Security. +- Windows: Simplified Chinese, English, and Japanese use the bundled model with no language pack needed; Korean, as well as fallback when the bundled model is unavailable, uses Windows system OCR and requires installing the corresponding OCR language pack (Settings > Time & language > Language > add the language and install Optical Character Recognition); a prompt is shown if missing. +- Windows: Screenshot and clipboard OCR via Windows system OCR were verified on a real machine on 2026-11-03; bundled-model recognition is pending real-device verification. + +## Network & Data + +- Works offline; images are recognized strictly on your local device. +- Temporary captures from region selection and clipboard images are deleted immediately after recognition. +- Recognition results are kept in memory only and cleared when ZTools exits. diff --git a/extensions/ocr/plugin.json b/extensions/ocr/plugin.json index a1b8b197..340519ce 100644 --- a/extensions/ocr/plugin.json +++ b/extensions/ocr/plugin.json @@ -2,7 +2,7 @@ "id": "ocr", "name": "文字识别", "description": "框选屏幕、剪贴板或图片里的文字,在本机离线识别(OCR)简体中文、英文、日文、韩文,结果直接复制", - "version": "3.0.8", + "version": "3.0.9", "author": "ZTools Team", "entry": "dist/index.js", "icon": "icon.svg", @@ -81,7 +81,11 @@ "text recognition", "screenshot", "extract text", - "offline" + "offline", + "image to text", + "screenshot ocr", + "copy text from image", + "scan text" ], "features": { "ocr-region": { @@ -125,5 +129,16 @@ { "path": "screenshots/02-action-panel.png" } + ], + "keywords": [ + "文字识别", + "识字", + "图片转文字", + "截图识字", + "提取文字", + "扫文字", + "图文识别", + "ocr", + "复制图片文字" ] } diff --git a/extensions/office-slim/README.en.md b/extensions/office-slim/README.en.md new file mode 100644 index 00000000..ecab26e2 --- /dev/null +++ b/extensions/office-slim/README.en.md @@ -0,0 +1,21 @@ +# Office Document Slimmer + +Recompress Word, PowerPoint, and Excel documents (`.docx`, `.pptx`, `.xlsx`) locally while preserving original image bytes; optionally remove author properties and comments, or export embedded original images as a ZIP archive. Always saves a new copy without modifying the original file. + +## Usage + +- Commands: `office slim` (`compress ppt`, `compress word`, `compress excel`), `clean office metadata` (`strip doc privacy`, `remove comments`), and `extract doc images` (`extract ppt images`, `export word images`). The first two open the same processing view, and the third exports original images. +- Click "Select Document" to choose files. The list shows file size, original image count, and whether author properties or comments are present; press `Enter` to start processing and choose where to save the new copy. +- Repackages the document structure at the highest compression level without re-encoding images, so the output size is not guaranteed to be smaller. +- "Remove Author Properties & Comments" (enabled by default) deletes author, last-modified-by, and revision number properties, along with comments and in-body comment markers; personal information inside the document body and tracked revision content are preserved. +- Exporting original images packages embedded images inside the document sequentially into a `.zip` file; if the document contains no images, export is declined with a notice. +- The new copy must match the original document format (`.zip` for image export) and cannot overwrite the original file; when choosing another existing file, it is overwritten only after confirming replacement in the system save dialog. Maximum document size is 16 MiB; the archive is read back and verified before saving completes. + +## Platforms & Requirements + +- Supported: Windows, macOS +- Requires ZTools 1.1.8.5 or later. + +## Network & Data + +- Works offline; data stays strictly on your local device. diff --git a/extensions/office-slim/plugin.json b/extensions/office-slim/plugin.json index f135c32f..559a4dc3 100644 --- a/extensions/office-slim/plugin.json +++ b/extensions/office-slim/plugin.json @@ -1,7 +1,7 @@ { "id": "office-slim", "name": "办公文档瘦身", - "version": "1.0.10", + "version": "1.0.11", "description": "本地重新压缩 Word、PPT、Excel 文档,保留图片原字节,可移除作者属性与批注、导出原图 ZIP;只另存新副本", "author": "ZTools Team", "entry": "dist/index.js", @@ -78,7 +78,14 @@ "pptx", "xlsx", "slim", - "metadata" + "metadata", + "compress ppt", + "compress word", + "compress excel", + "office slimmer", + "shrink docx", + "shrink pptx", + "reduce office size" ], "features": { "office-slim-workbench": { @@ -121,5 +128,16 @@ { "path": "screenshots/02-action-panel.png" } + ], + "keywords": [ + "办公文档瘦身", + "压缩ppt", + "压缩word", + "压缩excel", + "ppt太大", + "word太大", + "文档压缩", + "提取ppt图片", + "办公压缩" ] } diff --git a/extensions/office-slim/src/i18n.ts b/extensions/office-slim/src/i18n.ts index e93cf61d..bbe12964 100644 --- a/extensions/office-slim/src/i18n.ts +++ b/extensions/office-slim/src/i18n.ts @@ -24,6 +24,8 @@ export const t = createTranslator({ summarySaved: '已保存 {name} · {size}(原文档 {originalSize})', summaryDefault: '原文件保留,只另存新副本 · 单文档最大 16 MiB', btnPickDoc: '选择文档', + btnExtractZip: '导出原图 ZIP', + btnProcessSave: '开始瘦身并另存', panelTitleExtract: '原图导出', panelTitleSlim: '文档处理', panelSubtitle: '标准 OOXML · 图片保持原始字节', @@ -68,6 +70,8 @@ export const t = createTranslator({ summarySaved: 'Saved {name} · {size} (original {originalSize})', summaryDefault: 'Original preserved; saves a new copy · Max 16 MiB per document', btnPickDoc: 'Select Document', + btnExtractZip: 'Export Images ZIP', + btnProcessSave: 'Slim & Save', panelTitleExtract: 'Export Images', panelTitleSlim: 'Process Document', panelSubtitle: 'Standard OOXML · Original image bytes preserved', diff --git a/extensions/office-slim/src/index.tsx b/extensions/office-slim/src/index.tsx index bf0478b8..0790f495 100644 --- a/extensions/office-slim/src/index.tsx +++ b/extensions/office-slim/src/index.tsx @@ -95,7 +95,10 @@ export function OfficeSlim({ featureCode = 'office-slim-workbench' }: { featureC const visible = summary && summary.name.toLowerCase().includes(search.trim().toLowerCase()) return } - filterBar={{ summaryText: error || (result ? t('summarySaved', { name: result.name, size: formatOfficeBytes(result.size), originalSize: formatOfficeBytes(result.originalSize) }) : t('summaryDefault')), actions: [{ id: 'pick', title: t('btnPickDoc'), onAction: pick }] }} + filterBar={{ summaryText: error || (result ? t('summarySaved', { name: result.name, size: formatOfficeBytes(result.size), originalSize: formatOfficeBytes(result.originalSize) }) : t('summaryDefault')), actions: summary ? [ + { id: 'pick', title: t('btnPickDoc'), style: 'secondary', onAction: pick }, + { id: 'process', title: mode === 'extract' ? t('btnExtractZip') : t('btnProcessSave'), style: 'primary', disabled: loading, onAction: process } + ] : [{ id: 'pick', title: t('btnPickDoc'), style: 'secondary', onAction: pick }] }} workbenchPanel={{ title: mode === 'extract' ? t('panelTitleExtract') : t('panelTitleSlim'), subtitle: t('panelSubtitle'), fields: [ { id: 'method', label: t('fieldMethodLabel'), type: 'info', value: mode === 'extract' ? t('fieldMethodExtract') : t('fieldMethodSlim') }, ...(mode === 'slim' ? [{ id: 'clean', label: t('fieldCleanLabel'), type: 'toggle' as const, value: clean, onChange: (value: unknown) => { if (!operation.current) setClean(value === true) } }] : []), diff --git a/extensions/office-slim/src/native-ipc.ts b/extensions/office-slim/src/native-ipc.ts index 51576b99..13643277 100644 --- a/extensions/office-slim/src/native-ipc.ts +++ b/extensions/office-slim/src/native-ipc.ts @@ -174,11 +174,13 @@ function normalizeMethodResult(method: string, payload: DynamicBridge): DynamicB if (method === 'system_get_battery_status') { // 宿主约定 percent 超出 0-100(如 255)表示无电池或电量未知,不能改写成 100% + // 若宿主明确给出 hasBattery 布尔值,必须原样保留,仅在缺失时按合法电量推算 const rawPct = payload.percent - const hasBattery = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const validPct = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const hasBattery = typeof payload.hasBattery === 'boolean' ? payload.hasBattery : validPct return { ...payload, - percent: hasBattery ? rawPct : null, + percent: validPct ? rawPct : null, hasBattery } } @@ -489,6 +491,8 @@ export interface RealDirectoryScanResult extends Iterable approximate?: boolean /** 宿主实际遍历的条目数 */ visitedEntries?: number + /** 目录本身不存在(ENOENT) */ + missing?: boolean /** 读取失败的真实原因;已有文件仍可使用,但不能当作完整结果。 */ error?: string } @@ -497,6 +501,7 @@ interface ScanResultMeta { truncated?: boolean approximate?: boolean visitedEntries?: number + missing?: boolean } export interface ScanDirectoryTreeOptions { @@ -504,6 +509,10 @@ export interface ScanDirectoryTreeOptions { maxFiles?: number collectTopN?: number filterExt?: RegExp + /** 为 true 时,目录本身不存在(ENOENT)按空目录处理,不返回 error(权限拒绝/读取失败仍照常报错) */ + ignoreMissing?: boolean + /** Top-N 保留与排序方式:默认按体积降序,下载/录屏等时效场景可传 mtime-desc */ + sortBy?: 'size-desc' | 'mtime-desc' hostOverride?: DynamicBridge } @@ -519,8 +528,9 @@ function normalizeIndexedFileEntry(f: DynamicBridge): RealIndexedFileEntry { const sz = Number(f?.size ?? f?.sizeBytes ?? 0) const isDir = Boolean(f?.is_dir || f?.isDir || f?.isDirectory) const rawMtime = Number(f?.mtime ?? f?.mtimeMs ?? 0) - const mtimeMs = rawMtime > 1e11 ? rawMtime : rawMtime > 0 ? rawMtime * 1000 : Date.now() - const mtimeSec = rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime + const validMtime = Number.isFinite(rawMtime) && rawMtime > 0 + const mtimeMs = validMtime ? (rawMtime > 1e11 ? rawMtime : rawMtime * 1000) : 0 + const mtimeSec = validMtime ? (rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime) : 0 if (p && sz >= 0) realFileSizeCache.set(p, sz) return { name, @@ -551,6 +561,7 @@ function makeScanResult( subdirs, ...(meta.truncated ? { truncated: true } : {}), ...(meta.approximate ? { approximate: true } : {}), + ...(meta.missing ? { missing: true } : {}), ...(typeof meta.visitedEntries === 'number' ? { visitedEntries: meta.visitedEntries } : {}), [Symbol.iterator]() { return files[Symbol.iterator]() @@ -609,13 +620,40 @@ export async function scanRealDirectoryTree( return result.error ? { ...result.scan, error: result.error } : result.scan } +/** 仅当正则明确声明了扩展名(含 `\.`)时提取后缀列表,避免把 `thumbcache|iconcache` 等文件名关键词误拆成假扩展名 */ +function extractExtensionTokensFromFilter(filterExt: RegExp): string[] { + const src = filterExt.source + if (!src.includes('\\.')) return [] + const afterDot = src.slice(src.indexOf('\\.') + 2) + const rawTokens = afterDot.match(/[a-z0-9]{1,8}/gi) || [] + const seen = new Set() + const out: string[] = [] + for (const token of rawTokens) { + const lower = token.toLowerCase() + if (!lower || seen.has(lower)) continue + seen.add(lower) + out.push(lower) + } + return out +} + +function isMissingDirectoryError(res: { error?: string; errorCode?: string; errorDetails?: Record }): boolean { + if (res.errorDetails?.reason === 'ENOENT' || res.errorCode === 'ENOENT') return true + const msg = String(res.error || '') + return /Directory does not exist|ENOENT/i.test(msg) +} + /** 一次界面扫描的错误汇总;多个目录并行扫描时保留可读目录的结果。 */ export function createDirectoryScanner(hostOverride?: DynamicBridge) { const failures = new Map() return { async scan(dir: string, options: number | ScanDirectoryTreeOptions = 160) { const result = await scanRealDirectoryTree(dir, options, hostOverride) - const error = result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') + const ignoreMissing = typeof options === 'object' && options !== null && options.ignoreMissing === true + const error = + result.missing && ignoreMissing + ? '' + : result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') if (error) failures.set(dir, error) else failures.delete(dir) return result @@ -648,26 +686,38 @@ async function scanDirectoryTreeWithError( const safeLimit = Math.min(200, Math.max(1, Math.floor(rawLimit || 160))) const hostOverride = opts.hostOverride const filterExt = opts.filterExt + const ignoreMissing = opts.ignoreMissing === true const dirQuery = `dir:${targetDir}` try { let rawPayload: DynamicBridge = null + const searchParams: Record = { + query: dirQuery, + limit: safeLimit, + ...(opts.sortBy ? { sortBy: opts.sortBy } : {}) + } const res = await callHostTransport( 'system_search_files', - { query: dirQuery, limit: safeLimit }, + searchParams, hostOverride ) - if (res.ok && res.data) { + if (res.ok && res.data && res.data.degraded !== true) { rawPayload = res.data + } else if (!res.ok && ignoreMissing && isMissingDirectoryError(res)) { + const missingScan = makeScanResult([], 0, 0, [], { missing: true }) + return { scan: missingScan } } - if (!rawPayload && !hostOverride && typeof window !== 'undefined') { + if (!rawPayload && !hostOverride && res.errorCode === 'METHOD_NOT_AVAILABLE' && typeof window !== 'undefined') { const w = window as DynamicBridge if (typeof w.__ztoolsLauncher?.searchFiles === 'function') { const rawOuter = await w.__ztoolsLauncher.searchFiles(dirQuery, safeLimit) - rawPayload = + const candidate = rawOuter && typeof rawOuter === 'object' && 'data' in rawOuter && rawOuter.data ? rawOuter.data : rawOuter + if (candidate && candidate.degraded !== true && candidate.success !== false) { + rawPayload = candidate + } } } @@ -678,29 +728,32 @@ async function scanDirectoryTreeWithError( let files: RealIndexedFileEntry[] = rawPayload.files.map(normalizeIndexedFileEntry) if (filterExt instanceof RegExp) { files = files.filter(f => !f.isDir && (filterExt.test(f.name) || filterExt.test(f.ext))) - // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索目标扩展名 + // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索明确声明的目标扩展名 if (files.length === 0 && !hostOverride) { - const extTokens = (filterExt.source.match(/[a-z0-9]{2,5}/gi) || []) - .filter(t => !['thumbcache', 'iconcache'].includes(t.toLowerCase())) - .slice(0, 4) - // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 - const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() - const extraLists = await Promise.all( - extTokens.map(ext => searchRealIndexedFiles(`.${ext.toLowerCase()}`, 30, hostOverride)) - ) - const seen = new Set() - for (const list of extraLists) { - for (const item of list) { - if (!item.isDir && item.size > 0 && !seen.has(item.path)) { - if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { - seen.add(item.path) - files.push(item) + const extTokens = extractExtensionTokensFromFilter(filterExt) + if (extTokens.length > 0) { + // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 + const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() + const extraLists = await Promise.all( + extTokens.map(ext => searchRealIndexedFiles(`.${ext}`, 30, hostOverride)) + ) + const seen = new Set() + for (const list of extraLists) { + for (const item of list) { + if (!item.isDir && item.size > 0 && !seen.has(item.path)) { + if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { + seen.add(item.path) + files.push(item) + } } } } } } } + // 先基于过滤后的完整命中集合计算总文件数与总字节数,再按 collectTopN 裁剪样本列表 + const matchedCount = files.length + const matchedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) if (typeof opts.collectTopN === 'number' && opts.collectTopN > 0 && files.length > opts.collectTopN) { files = files.slice(0, opts.collectTopN) } @@ -714,11 +767,10 @@ async function scanDirectoryTreeWithError( ...(s.approximate === true ? { approximate: true } : {}) })) : [] - const computedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) const totalFilesCount = - filterExt instanceof RegExp ? files.length : Number(rawPayload.total_matches ?? files.length) + filterExt instanceof RegExp ? matchedCount : Number(rawPayload.total_matches ?? matchedCount) const totalBytesCount = - filterExt instanceof RegExp ? computedBytes : Number(rawPayload.total_bytes ?? computedBytes) + filterExt instanceof RegExp ? matchedBytes : Number(rawPayload.total_bytes ?? matchedBytes) const visited = Number(rawPayload.visited_entries) return { scan: makeScanResult(files, totalFilesCount, totalBytesCount, subdirs, { @@ -1817,8 +1869,6 @@ export async function writeRealClipboardText(text: string, hostOverride?: Dynami const payload = { text: String(text || '') } const res = await callHostTransport('clipboard_copy_text', payload, hostOverride) if (res.ok) return true - const fallbackRes = await callHostTransport('clipboard_write_text', payload, hostOverride) - if (fallbackRes.ok) return true try { if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) { await navigator.clipboard.writeText(String(text || '')) diff --git a/extensions/office-slim/tests/index.test.mjs b/extensions/office-slim/tests/index.test.mjs index 8d967a1f..1fc5a63a 100644 --- a/extensions/office-slim/tests/index.test.mjs +++ b/extensions/office-slim/tests/index.test.mjs @@ -10,7 +10,7 @@ const summary = { name: input.displayName, size: 2048, type: 'docx', digest: 'a' const result = { success: true, status: 'committed', name: output.displayName, size: 1024, originalSize: 2048, imageCount: 1 } const deferred = () => { let resolve; const promise = new Promise(done => { resolve = done }); return { promise, resolve } } const open = async (command = Command) => { const view = await mount(command); views.push(view); return view } -const pick = async view => { await view.tree().props.filterBar.actions[0].onAction(); await tick() } +const pick = async view => { await view.tree().props.filterBar.actions.find(a => a.id === 'pick').onAction(); await tick() } const process = async view => { await view.actions(view.item('document'))[0].props.onAction(); await tick() } const writes = () => host.ipcCalls.filter(([method, params]) => method === 'office_document' && params.action !== 'inspect') test.beforeEach(() => { @@ -23,6 +23,7 @@ test.beforeEach(() => { test.afterEach(() => { for (const view of views.splice(0)) view.unmount() }) test('选择文档后显示真实检查结果;Enter 等保存完成再成功,不出现预估或无损画质承诺', async () => { const view = await open(); assert.equal(view.items().length, 0) + assert.deepEqual(view.tree().props.filterBar.actions.map(a => a.id), ['pick']) await pick(view); assert.match(view.text(), /2.0 KB|2.00 KB/) const pending = deferred(); host.ipc.office_document = () => pending.promise const running = process(view); await tick(); assert.equal(host.toasts.length, 0) @@ -30,7 +31,7 @@ test('选择文档后显示真实检查结果;Enter 等保存完成再成功 assert.equal(host.lastToast().title, '新副本已保存并通过校验') const { operationId, ...params } = writes()[0][1]; assert.match(operationId, /^job_/); assert.deepEqual(params, { action: 'slim', path: input.path, outputPath: output.path, digest: summary.digest, cleanMetadata: true }) assert.doesNotMatch(view.text(), /预计|80%|65%|无损画质|无残留/) - assert.equal(view.tree().props.filterBar.actions.length, 1) + assert.deepEqual(view.tree().props.filterBar.actions.map(a => a.id), ['pick', 'process']) }) test('取消选择或保存零写入,失败消息保留,重试不会覆盖原文件', async () => { const view = await open() diff --git a/extensions/password-vault/README.en.md b/extensions/password-vault/README.en.md new file mode 100644 index 00000000..f1805420 --- /dev/null +++ b/extensions/password-vault/README.en.md @@ -0,0 +1,22 @@ +# Password Vault + +Encrypt and store account passwords, API keys, server passwords, and software license keys locally; automatically clears copied secrets from the clipboard after 30 seconds. + +## Usage + +- Commands: `password vault` (`vault`, `passwords`, `1password`, `keepass`) and `password generator` (`random password`, `generate password`). The password generator does not require unlocking—it directly lists 16-, 20-, and 32-character options (`Enter` to copy, `Cmd/Ctrl+R` to regenerate), and asks for the master password only when you choose "Save to Vault...", prefilling the selected password into a new entry. +- On first use, set a master password of at least 8 characters; you will need to enter it to unlock the vault each time afterward. The master password is never stored and cannot be recovered if forgotten. +- Keys are derived via PBKDF2-SHA256 (600,000 iterations), and all entries are encrypted with AES-256-GCM before being saved locally. Entries are organized into four categories: Websites & Apps, API Keys & Tokens, Servers & Databases, and Software Licenses & Notes. Filter by category or search by title, username, URL, or notes. +- On an entry: `Enter` copies the password, `Cmd/Ctrl+Enter` copies the username (or toggles plaintext visibility if no username is set), `Cmd/Ctrl+E` shows or hides plaintext password and notes (notes are hidden in the list by default), `Cmd/Ctrl+G` generates and copies a 20-character random password, `Cmd/Ctrl+Backspace` deletes the entry (requires confirmation and cannot be undone), and `Cmd/Ctrl+K` opens the action panel (Edit, etc.). +- Copied passwords and generated random passwords are automatically cleared from the clipboard by ZTools after 30 seconds and excluded from clipboard history; copied usernames are not auto-cleared. +- Click "Lock Now" at the top to purge the master password and decrypted entries from memory. +- Quick-generated 20-character passwords inside the vault include uppercase/lowercase letters, digits, and symbols while excluding visually ambiguous characters such as `0`, `O`, `1`, `l`, and `I`. + +## Platforms & Requirements + +- Supported: Windows, macOS +- Requires ZTools 1.1.8.5 or later. + +## Network & Data + +- Works offline; the vault is stored strictly on your local device in encrypted form. diff --git a/extensions/password-vault/plugin.json b/extensions/password-vault/plugin.json index b95c63cd..ea23ace4 100644 --- a/extensions/password-vault/plugin.json +++ b/extensions/password-vault/plugin.json @@ -1,7 +1,7 @@ { "id": "password-vault", "name": "密码保险箱", - "version": "1.1.8", + "version": "1.1.9", "minAppVersion": "1.1.8.5", "description": "在本机用主密码加密保存账号密码、API Key、服务器密码与软件激活码(AES-256-GCM),复制密码 30 秒后自动清除剪贴板", "author": "ZTools Team", @@ -67,7 +67,13 @@ "secret", "api key", "generator", - "security" + "security", + "password manager", + "password generator", + "secrets", + "credentials", + "login", + "strong password" ], "features": { "vault-list": { @@ -103,5 +109,17 @@ { "path": "screenshots/02-action-panel.png" } + ], + "keywords": [ + "密码保险箱", + "密码管理", + "存密码", + "记密码", + "生成密码", + "随机密码", + "强密码", + "密码本", + "账号密码", + "password" ] } diff --git a/extensions/password-vault/src/index.tsx b/extensions/password-vault/src/index.tsx index 9418ff11..fde9e972 100644 --- a/extensions/password-vault/src/index.tsx +++ b/extensions/password-vault/src/index.tsx @@ -148,6 +148,7 @@ export function VaultEntryForm({ initialPassword = '', initialEntry, onSave }: V placeholder={t('fieldTitlePlaceholder')} value={title} onChange={setTitle} + autoFocus={true} /> {!hasExistingVault ? ( {GENERATOR_PRESETS.map((preset) => { const password = passwords[preset.id] || '' diff --git a/extensions/paste-stack/README.en.md b/extensions/paste-stack/README.en.md new file mode 100644 index 00000000..46029c0b --- /dev/null +++ b/extensions/paste-stack/README.en.md @@ -0,0 +1,21 @@ +# Plain Text & Paste Stack + +Collect multiple consecutive text copies made while the Paste Stack page is open into a FIFO or LIFO queue, and select an item to paste it back into your previous input field; also includes a command to strip rich formatting from clipboard text into plain text. + +## Usage + +- Commands: `paste stack` (`paste queue`, `multi copy`, `sequential paste`); open directly in order: `fifo paste` (first-in, first-out) or `lifo paste` (last-in, first-out); strip formatting: `clean clipboard text` (`plain text`, `strip format`). +- Monitors the clipboard only while the Paste Stack page is open and records text only; consecutive copies identical to the last queued item are not duplicated. Pause/resume capture or clear the queue from the top bar. +- Press `Enter` on an item to paste it into the previous input field and move it to "Sent" (switch the top dropdown to "Sent (Restorable)" to restore items to the queue); `Cmd/Ctrl+Enter` copies the item only; `Cmd/Ctrl+K` lets you move items up, move down, or remove them. +- `clean clipboard text` reads text from the clipboard and writes it back with rich formatting removed while keeping the text content unchanged; reports an error if the clipboard has no text. +- Holds up to 500 items (or 8 MiB) combined across pending and sent items. +- On macOS, automatic pasting requires granting Accessibility permission to ZTools in System Settings > Privacy & Security > Accessibility; if unauthorized, pasting reports an error and the item remains in the queue. + +## Platforms & Requirements + +- Supported: Windows, macOS +- Requires ZTools 1.1.8.3 or later. + +## Network & Data + +- Works offline; data stays strictly on your local device. diff --git a/extensions/paste-stack/plugin.json b/extensions/paste-stack/plugin.json index 01c13ef2..2688a043 100644 --- a/extensions/paste-stack/plugin.json +++ b/extensions/paste-stack/plugin.json @@ -1,7 +1,7 @@ { "id": "paste-stack", "name": "纯文本与粘贴栈", - "version": "1.0.10", + "version": "1.0.11", "description": "一键清除剪贴板富文本脏格式转为纯文本;支持多项连续复制入栈、跨窗口依次顺序或倒序自动上屏粘贴", "author": "ZTools Team", "entry": "dist/index.js", @@ -84,7 +84,12 @@ "plain text", "fifo", "lifo", - "queue" + "queue", + "strip formatting", + "paste queue", + "sequential paste", + "unformatted paste", + "fifo paste" ], "features": { "paste-stack-queue": { @@ -136,5 +141,15 @@ { "path": "screenshots/02-action-panel.png" } + ], + "keywords": [ + "纯文本粘贴", + "粘贴栈", + "去除格式", + "清格式粘贴", + "批量粘贴", + "顺序粘贴", + "无格式粘贴", + "paste stack" ] } diff --git a/extensions/paste-stack/src/i18n.ts b/extensions/paste-stack/src/i18n.ts index 5809d1e9..128c5737 100644 --- a/extensions/paste-stack/src/i18n.ts +++ b/extensions/paste-stack/src/i18n.ts @@ -54,7 +54,14 @@ const rawT = createTranslator({ actionMoveUp: '上移一位', actionMoveDown: '下移一位', actionRemoveSent: '移除发送记录', - actionRemoveQueue: '从栈中移除' + actionRemoveQueue: '从栈中移除', + confirmClearQueueTitle: '清空待发送队列?', + confirmClearQueueMsg: '将移除队列中的全部 {count} 条待发送文本,操作无法撤销。', + confirmClearSentTitle: '清空已发送记录?', + confirmClearSentMsg: '将移除全部 {count} 条已发送记录,移除后无法再恢复。', + cancelBtn: '取消', + metaStatus: '状态', + metaCharCount: '字符数' }, 'en-US': { errInvalidStateFormat: 'Invalid paste stack storage format; original data preserved', @@ -109,7 +116,14 @@ const rawT = createTranslator({ actionMoveUp: 'Move Up', actionMoveDown: 'Move Down', actionRemoveSent: 'Remove Sent Record', - actionRemoveQueue: 'Remove from Stack' + actionRemoveQueue: 'Remove from Stack', + confirmClearQueueTitle: 'Clear pending queue?', + confirmClearQueueMsg: 'Removes all {count} pending [[count:item|items]] from the queue. This cannot be undone.', + confirmClearSentTitle: 'Clear sent history?', + confirmClearSentMsg: 'Removes all {count} sent [[count:record|records]]. They can no longer be restored.', + cancelBtn: 'Cancel', + metaStatus: 'Status', + metaCharCount: 'Characters' } }) export const t: typeof rawT = (key, params) => { diff --git a/extensions/paste-stack/src/index.tsx b/extensions/paste-stack/src/index.tsx index 956de4f4..10b84e0c 100644 --- a/extensions/paste-stack/src/index.tsx +++ b/extensions/paste-stack/src/index.tsx @@ -1,4 +1,4 @@ -import React, { List, ActionPanel, Action, Icon, Clipboard, LocalStorage, showToast, Toast, useLocale, useState, useEffect, useMemo, useCallback, useRef } from '@ztools/declarative-ui' +import React, { List, ActionPanel, Action, Icon, Clipboard, LocalStorage, showToast, Toast, confirmAlert, useLocale, useState, useEffect, useMemo, useCallback, useRef } from '@ztools/declarative-ui' import type { StackItem, StackPopMode } from './types.js' import { STACK_STORAGE_KEY, cleanRichTextToPlain, parseStackState, stackItem, subscribeStackClipboard } from './stack-manager.js' import type { StackState } from './stack-manager.js' @@ -7,6 +7,13 @@ import { t } from './i18n.js' export * from './types.js' export * from './stack-manager.js' +function fencedBlock(content: string): string { + const runs = String(content).match(/`+/g) || [] + const longest = runs.reduce((max, run) => Math.max(max, run.length), 0) + const fence = '`'.repeat(Math.max(3, longest + 1)) + return `${fence}text\n${content}\n${fence}` +} + /** * 剪贴板里是否是文件:在访达 / 资源管理器里复制文件时,系统同时放一份文件名文本, * 若照常“洗成纯文本”会把复制的文件替换成文件名。宿主不支持查询时按没有文件处理。 @@ -151,7 +158,20 @@ export function PasteStack({ featureCode = 'paste-stack-queue' }: { featureCode? const retry = () => { setReload(value => value + 1) } const toggleListening = () => mutate(value => ({ ...value, isListening: !value.isListening })) const clean = async () => { try { await showToast({ style: Toast.Style.Success, title: await CleanClipboardCommand() }) } catch (error) { await fail(t('errCleanFailed'), error) } } - return { + if (currentListCount === 0) return + const confirmed = await confirmAlert({ + title: showingSent ? t('confirmClearSentTitle') : t('confirmClearQueueTitle'), + message: showingSent ? t('confirmClearSentMsg', { count: currentListCount }) : t('confirmClearQueueMsg', { count: currentListCount }), + primaryAction: { title: showingSent ? t('btnClearSent') : t('btnClearQueue'), style: 'destructive' }, + dismissAction: { title: t('cancelBtn') } + }) + if (!confirmed) return + await mutate(value => showingSent ? { ...value, sent: [] } : { ...value, items: [] }) + } + const isSearching = Boolean(search.trim()) + return setMode(value as StackPopMode | 'sent')} tooltip={t('modeTooltip')}> } @@ -163,22 +183,26 @@ export function PasteStack({ featureCode = 'paste-stack-queue' }: { featureCode? actions: loadError || listenError ? [{ id: 'retry', title: t('btnRetry'), onAction: retry }] : [ // 空状态时底栏主动作已是切换监听,工具栏不再重复;有条目时底栏是单条动作,监听开关只在工具栏 ...(!loading && !items.length ? [] : [{ id: 'listen', title: state.isListening ? t('btnPauseListen') : t('btnStartListen'), onAction: toggleListening }]), - { id: 'clear', title: showingSent ? t('btnClearSent') : t('btnClearQueue'), onAction: () => mutate(value => showingSent ? { ...value, sent: [] } : { ...value, items: [] }) } + ...(currentListCount > 0 ? [{ id: 'clear', title: showingSent ? t('btnClearSent') : t('btnClearQueue'), style: 'destructive' as const, onAction: () => { void handleClear() } }] : []) ] }} actions={loadError || listenError ? undefined : }> {!loading && !loadError && !items.length ? : null} + title={isSearching ? t('emptyNoMatch') : showingSent ? t('emptySent') : state.isListening ? t('emptyListening') : t('emptyPaused')} + subtitle={isSearching ? t('emptyNoMatchSub') : showingSent ? t('emptySentSub') : ''} /> : null} {items.map((item: StackItem, index: number) => + + + } />} actions={ showingSent ? restore(item.id) : pasteItem(item.id)} /> - - {!showingSent && move(item.id, items[index - 1]?.id)} />} - {!showingSent && move(item.id, items[index + 1]?.id)} />} - mutate(value => showingSent ? { ...value, sent: value.sent?.filter(entry => entry.item.id !== item.id) } : { ...value, items: value.items.filter(current => current.id !== item.id) })} /> + + {!showingSent && !isSearching && index > 0 && move(item.id, items[index - 1]?.id)} />} + {!showingSent && !isSearching && index < items.length - 1 && move(item.id, items[index + 1]?.id)} />} + mutate(value => showingSent ? { ...value, sent: value.sent?.filter(entry => entry.item.id !== item.id) } : { ...value, items: value.items.filter(current => current.id !== item.id) })} /> } />)} } diff --git a/extensions/paste-stack/src/native-ipc.ts b/extensions/paste-stack/src/native-ipc.ts index 51576b99..13643277 100644 --- a/extensions/paste-stack/src/native-ipc.ts +++ b/extensions/paste-stack/src/native-ipc.ts @@ -174,11 +174,13 @@ function normalizeMethodResult(method: string, payload: DynamicBridge): DynamicB if (method === 'system_get_battery_status') { // 宿主约定 percent 超出 0-100(如 255)表示无电池或电量未知,不能改写成 100% + // 若宿主明确给出 hasBattery 布尔值,必须原样保留,仅在缺失时按合法电量推算 const rawPct = payload.percent - const hasBattery = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const validPct = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const hasBattery = typeof payload.hasBattery === 'boolean' ? payload.hasBattery : validPct return { ...payload, - percent: hasBattery ? rawPct : null, + percent: validPct ? rawPct : null, hasBattery } } @@ -489,6 +491,8 @@ export interface RealDirectoryScanResult extends Iterable approximate?: boolean /** 宿主实际遍历的条目数 */ visitedEntries?: number + /** 目录本身不存在(ENOENT) */ + missing?: boolean /** 读取失败的真实原因;已有文件仍可使用,但不能当作完整结果。 */ error?: string } @@ -497,6 +501,7 @@ interface ScanResultMeta { truncated?: boolean approximate?: boolean visitedEntries?: number + missing?: boolean } export interface ScanDirectoryTreeOptions { @@ -504,6 +509,10 @@ export interface ScanDirectoryTreeOptions { maxFiles?: number collectTopN?: number filterExt?: RegExp + /** 为 true 时,目录本身不存在(ENOENT)按空目录处理,不返回 error(权限拒绝/读取失败仍照常报错) */ + ignoreMissing?: boolean + /** Top-N 保留与排序方式:默认按体积降序,下载/录屏等时效场景可传 mtime-desc */ + sortBy?: 'size-desc' | 'mtime-desc' hostOverride?: DynamicBridge } @@ -519,8 +528,9 @@ function normalizeIndexedFileEntry(f: DynamicBridge): RealIndexedFileEntry { const sz = Number(f?.size ?? f?.sizeBytes ?? 0) const isDir = Boolean(f?.is_dir || f?.isDir || f?.isDirectory) const rawMtime = Number(f?.mtime ?? f?.mtimeMs ?? 0) - const mtimeMs = rawMtime > 1e11 ? rawMtime : rawMtime > 0 ? rawMtime * 1000 : Date.now() - const mtimeSec = rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime + const validMtime = Number.isFinite(rawMtime) && rawMtime > 0 + const mtimeMs = validMtime ? (rawMtime > 1e11 ? rawMtime : rawMtime * 1000) : 0 + const mtimeSec = validMtime ? (rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime) : 0 if (p && sz >= 0) realFileSizeCache.set(p, sz) return { name, @@ -551,6 +561,7 @@ function makeScanResult( subdirs, ...(meta.truncated ? { truncated: true } : {}), ...(meta.approximate ? { approximate: true } : {}), + ...(meta.missing ? { missing: true } : {}), ...(typeof meta.visitedEntries === 'number' ? { visitedEntries: meta.visitedEntries } : {}), [Symbol.iterator]() { return files[Symbol.iterator]() @@ -609,13 +620,40 @@ export async function scanRealDirectoryTree( return result.error ? { ...result.scan, error: result.error } : result.scan } +/** 仅当正则明确声明了扩展名(含 `\.`)时提取后缀列表,避免把 `thumbcache|iconcache` 等文件名关键词误拆成假扩展名 */ +function extractExtensionTokensFromFilter(filterExt: RegExp): string[] { + const src = filterExt.source + if (!src.includes('\\.')) return [] + const afterDot = src.slice(src.indexOf('\\.') + 2) + const rawTokens = afterDot.match(/[a-z0-9]{1,8}/gi) || [] + const seen = new Set() + const out: string[] = [] + for (const token of rawTokens) { + const lower = token.toLowerCase() + if (!lower || seen.has(lower)) continue + seen.add(lower) + out.push(lower) + } + return out +} + +function isMissingDirectoryError(res: { error?: string; errorCode?: string; errorDetails?: Record }): boolean { + if (res.errorDetails?.reason === 'ENOENT' || res.errorCode === 'ENOENT') return true + const msg = String(res.error || '') + return /Directory does not exist|ENOENT/i.test(msg) +} + /** 一次界面扫描的错误汇总;多个目录并行扫描时保留可读目录的结果。 */ export function createDirectoryScanner(hostOverride?: DynamicBridge) { const failures = new Map() return { async scan(dir: string, options: number | ScanDirectoryTreeOptions = 160) { const result = await scanRealDirectoryTree(dir, options, hostOverride) - const error = result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') + const ignoreMissing = typeof options === 'object' && options !== null && options.ignoreMissing === true + const error = + result.missing && ignoreMissing + ? '' + : result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') if (error) failures.set(dir, error) else failures.delete(dir) return result @@ -648,26 +686,38 @@ async function scanDirectoryTreeWithError( const safeLimit = Math.min(200, Math.max(1, Math.floor(rawLimit || 160))) const hostOverride = opts.hostOverride const filterExt = opts.filterExt + const ignoreMissing = opts.ignoreMissing === true const dirQuery = `dir:${targetDir}` try { let rawPayload: DynamicBridge = null + const searchParams: Record = { + query: dirQuery, + limit: safeLimit, + ...(opts.sortBy ? { sortBy: opts.sortBy } : {}) + } const res = await callHostTransport( 'system_search_files', - { query: dirQuery, limit: safeLimit }, + searchParams, hostOverride ) - if (res.ok && res.data) { + if (res.ok && res.data && res.data.degraded !== true) { rawPayload = res.data + } else if (!res.ok && ignoreMissing && isMissingDirectoryError(res)) { + const missingScan = makeScanResult([], 0, 0, [], { missing: true }) + return { scan: missingScan } } - if (!rawPayload && !hostOverride && typeof window !== 'undefined') { + if (!rawPayload && !hostOverride && res.errorCode === 'METHOD_NOT_AVAILABLE' && typeof window !== 'undefined') { const w = window as DynamicBridge if (typeof w.__ztoolsLauncher?.searchFiles === 'function') { const rawOuter = await w.__ztoolsLauncher.searchFiles(dirQuery, safeLimit) - rawPayload = + const candidate = rawOuter && typeof rawOuter === 'object' && 'data' in rawOuter && rawOuter.data ? rawOuter.data : rawOuter + if (candidate && candidate.degraded !== true && candidate.success !== false) { + rawPayload = candidate + } } } @@ -678,29 +728,32 @@ async function scanDirectoryTreeWithError( let files: RealIndexedFileEntry[] = rawPayload.files.map(normalizeIndexedFileEntry) if (filterExt instanceof RegExp) { files = files.filter(f => !f.isDir && (filterExt.test(f.name) || filterExt.test(f.ext))) - // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索目标扩展名 + // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索明确声明的目标扩展名 if (files.length === 0 && !hostOverride) { - const extTokens = (filterExt.source.match(/[a-z0-9]{2,5}/gi) || []) - .filter(t => !['thumbcache', 'iconcache'].includes(t.toLowerCase())) - .slice(0, 4) - // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 - const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() - const extraLists = await Promise.all( - extTokens.map(ext => searchRealIndexedFiles(`.${ext.toLowerCase()}`, 30, hostOverride)) - ) - const seen = new Set() - for (const list of extraLists) { - for (const item of list) { - if (!item.isDir && item.size > 0 && !seen.has(item.path)) { - if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { - seen.add(item.path) - files.push(item) + const extTokens = extractExtensionTokensFromFilter(filterExt) + if (extTokens.length > 0) { + // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 + const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() + const extraLists = await Promise.all( + extTokens.map(ext => searchRealIndexedFiles(`.${ext}`, 30, hostOverride)) + ) + const seen = new Set() + for (const list of extraLists) { + for (const item of list) { + if (!item.isDir && item.size > 0 && !seen.has(item.path)) { + if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { + seen.add(item.path) + files.push(item) + } } } } } } } + // 先基于过滤后的完整命中集合计算总文件数与总字节数,再按 collectTopN 裁剪样本列表 + const matchedCount = files.length + const matchedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) if (typeof opts.collectTopN === 'number' && opts.collectTopN > 0 && files.length > opts.collectTopN) { files = files.slice(0, opts.collectTopN) } @@ -714,11 +767,10 @@ async function scanDirectoryTreeWithError( ...(s.approximate === true ? { approximate: true } : {}) })) : [] - const computedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) const totalFilesCount = - filterExt instanceof RegExp ? files.length : Number(rawPayload.total_matches ?? files.length) + filterExt instanceof RegExp ? matchedCount : Number(rawPayload.total_matches ?? matchedCount) const totalBytesCount = - filterExt instanceof RegExp ? computedBytes : Number(rawPayload.total_bytes ?? computedBytes) + filterExt instanceof RegExp ? matchedBytes : Number(rawPayload.total_bytes ?? matchedBytes) const visited = Number(rawPayload.visited_entries) return { scan: makeScanResult(files, totalFilesCount, totalBytesCount, subdirs, { @@ -1817,8 +1869,6 @@ export async function writeRealClipboardText(text: string, hostOverride?: Dynami const payload = { text: String(text || '') } const res = await callHostTransport('clipboard_copy_text', payload, hostOverride) if (res.ok) return true - const fallbackRes = await callHostTransport('clipboard_write_text', payload, hostOverride) - if (fallbackRes.ok) return true try { if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) { await navigator.clipboard.writeText(String(text || '')) diff --git a/extensions/paste-stack/tests/index.test.mjs b/extensions/paste-stack/tests/index.test.mjs index a42c5975..9563e722 100644 --- a/extensions/paste-stack/tests/index.test.mjs +++ b/extensions/paste-stack/tests/index.test.mjs @@ -97,10 +97,12 @@ test('跨窗口CAS冲突不覆盖另一窗口数据,已粘贴但无法保存 assert.match(view.tree().props.filterBar.summaryText,/另一窗口/);assert.equal(handlers.size,0) }) -test('筛选后移动只交换选中ID,不误动其他行;LIFO位置以显示顺序为准', async () => { +test('搜索过滤状态下隐藏上移/下移防索引错乱;未过滤时 LIFO 位置以显示顺序为准', async () => { const value=storageValue(['match-a','untouched','match-b']);write(value);const view=await open(commands['paste-stack-lifo']) - await view.search('match');await view.run(view.item(value.items[2].id),'下移一位') - assert.deepEqual(read().items.map(item=>item.text),['match-b','untouched','match-a']) + await view.search('match') + assert.equal(view.actions(view.item(value.items[2].id)).some(a=>/上移|下移/.test(a.props.title)),false) + await view.search('');await view.run(view.item(value.items[2].id),'下移一位') + assert.deepEqual(read().items.map(item=>item.text),['match-a','match-b','untouched']) }) test('保存失败时保留队列与监听错误,过期订阅回执会注销', async () => { @@ -156,7 +158,7 @@ test('空队列显示引导条目,回车主动作是切换监听,清除格 assert.match(view.item('empty-state').props.title, /复制文字后会自动加入队列/) const titles = view.actions(null).map(action => action.props.title) assert.deepEqual(titles, ['暂停监听', '清除剪贴板格式']) - assert.deepEqual(view.tree().props.filterBar.actions.map(action => action.id), ['clear'], '空状态底栏已有监听开关,工具栏不重复') + assert.deepEqual(view.tree().props.filterBar.actions.map(action => action.id), [], '空状态隐藏清空按钮且工具栏不重复监听开关') await view.run(null, '暂停监听'); await tick() assert.equal(read().isListening, false) assert.match(view.item('empty-state').props.title, /监听已暂停/) diff --git a/extensions/pdf/plugin.json b/extensions/pdf/plugin.json index 540c6b8e..56bb771e 100644 --- a/extensions/pdf/plugin.json +++ b/extensions/pdf/plugin.json @@ -1,10 +1,9 @@ { "id": "pdf", "name": "PDF 工具箱", - "description": "提取 PDF 中未压缩的文字,导出为 TXT 或 HTML 文件,输出不覆盖已有文件(扫描件和多数压缩的 PDF 无法提取)", - "version": "2.0.13", - "draft": true, - "draftReason": "客户端缺少可靠的 PDF 解析、渲染与生成组件:现有的 PDF 重建方式会把字体、图片等数据当成页面内容写入,合并、拆分、压缩输出的文件内容错乱,已停用;PDF 与 Word/Excel/PPT/图片互转、加密解密没有对应组件。目前只能导出未压缩 PDF 中的简单文字。待客户端提供可靠的 PDF 解析、渲染与生成能力后,恢复对应工具并去掉草稿。", + "description": "通过宿主文档薄原语提供完整的纯 PDF 工具箱:检查元数据与提取文本、合并、按页码区间拆分、页面重排与旋转、压缩优化、密码加密与解密、文字水印、PDF 渲染转图片及多图合成 PDF,支持任务取消与引擎按需准备", + "version": "2.1.0", + "minAppVersion": "1.3.0.4", "author": "ZTools Team", "entry": "dist/index.js", "icon": "icon.svg", @@ -12,9 +11,15 @@ "办公效率" ], "categoryId": "productivity", + "requiredCapabilities": [ + "document.pdf.inspect", + "document.pdf.transform", + "document.pdf.render" + ], "permissions": [ "fs", "dialog", + "clipboard", "shell" ], "requireAdmin": false, @@ -30,15 +35,19 @@ "defaultLocale": "zh-CN", "i18n": { "en-US": { - "name": "PDF Text Extractor", - "description": "Extract uncompressed text from PDF files and export to TXT or HTML without overwriting existing files (scanned and compressed PDFs are not supported).", + "name": "PDF Toolbox", + "description": "Complete pure-PDF toolbox powered by host document primitives: inspect metadata & extract text, merge, split by page ranges, reorder, rotate, compress, encrypt/decrypt, add text watermark, render PDF pages to images, and combine images into PDF.", "keywords": [ "pdf", + "merge", + "split", + "compress", + "encrypt", + "decrypt", + "watermark", + "render", "extract text", - "txt", - "html", - "document", - "converter" + "images to pdf" ] } } diff --git a/extensions/pdf/src/i18n.ts b/extensions/pdf/src/i18n.ts index 6266f4a9..7b313c10 100644 --- a/extensions/pdf/src/i18n.ts +++ b/extensions/pdf/src/i18n.ts @@ -1,265 +1,270 @@ import { createTranslator } from '@ztools/declarative-ui' -const rawT = createTranslator({ +const MESSAGES = { 'zh-CN': { - forbiddenReason: 'PDF 转换输出路径禁止包含目录穿越或覆盖系统核心目录', - reasonOffice: '客户端没有 PDF 与 Office 格式互转组件', - reasonRender: '客户端没有 PDF 渲染组件,无法把页面转成图片', - reasonImage: '插件还不能调用客户端的图片转 PDF 接口', - reasonRebuild: '客户端现有的 PDF 重建方式会把字体、图片等数据当成页面内容写入,输出文件内容错乱,已停用', - unavailableFeaturesNote: '格式互转、合并、拆分、压缩、加解密(客户端缺少 PDF 解析与渲染组件)', - textExtractionLimitNote: '只能读取未压缩的简单文字,结果可能不完整;扫描件、压缩或特殊字体编码的 PDF 会提示无法提取', - toolPdfToTxtTitle: 'PDF 文字导出为 TXT', - toolPdfToTxtSub: '提取 PDF 中可读取的文字,保存为 UTF-8 纯文本文件', - toolPdfToTxtTag: '导出 TXT', - toolPdfToHtmlTitle: 'PDF 文字导出为 HTML', - toolPdfToHtmlSub: '提取 PDF 中可读取的文字,保存为纯文本网页(不保留版式与图片)', - toolPdfToHtmlTag: '导出 HTML', - toolPdfToWordTitle: 'PDF 转 Word (.docx)', - toolPdfToWordTag: 'PDF转Word', - toolPdfToExcelTitle: 'PDF 转 Excel (.xlsx)', - toolPdfToExcelTag: 'PDF转Excel', - toolPdfToPptTitle: 'PDF 转 PPT (.pptx)', - toolPdfToPptTag: 'PDF转PPT', - toolPdfToImageTitle: 'PDF 逐页导出为图片', - toolPdfToImageTag: 'PDF转图片', - toolWordToPdfTitle: 'Word 转 PDF', - toolWordToPdfTag: 'Word转PDF', - toolExcelToPdfTitle: 'Excel 转 PDF', - toolExcelToPdfTag: 'Excel转PDF', - toolImageToPdfTitle: '图片合并为 PDF', - toolImageToPdfTag: '图片转PDF', - toolPdfMergeTitle: '多份 PDF 合并', - toolPdfMergeTag: 'PDF合并', - toolPdfSplitTitle: 'PDF 按页拆分', - toolPdfSplitTag: 'PDF拆分', - toolPdfCompressTitle: 'PDF 压缩', - toolPdfCompressTag: 'PDF压缩', - errInvalidMethod: 'INVALID_METHOD: 调用方法名不能为空', - errInvalidMethodFormat: 'INVALID_METHOD_FORMAT: 方法名包含非法字符或超长', - errInvalidParams: 'INVALID_PARAMS: 参数必须为非空对象', - errParamTooLong: 'PARAM_TOO_LONG: 参数 {key} 超过最大长度限制', - errParamOutOfRange: 'PARAM_OUT_OF_RANGE: 数值参数 {key} 越界或非有限数', - errParamValidationFailed: '参数校验失败', - errUnsupportedMethod: 'UNSUPPORTED_METHOD: 本插件没有 {method} 功能', - errMissingHostComponent: '客户端缺少对应组件', - errUnsupportedTool: 'UNSUPPORTED: {tag}暂不可用:{reason}', - errCheckExistsFailed: '查询文件是否存在失败', - errMalformedExists: 'MALFORMED_EXISTS_RESPONSE: 客户端没有返回文件是否存在', - errInvalidInputPath: 'INVALID_INPUT_PATH: 无法从 {path} 推导输出位置', - errOutputCheckFailed: 'OUTPUT_CHECK_FAILED: 无法确认 {path} 是否已存在({error}),为避免覆盖已停止导出', - errOutputNameExhausted: 'OUTPUT_NAME_EXHAUSTED: {dir} 中已有 {max} 个同名的 {ext} 文件,请先整理后再导出', - errPdfProcessNoReason: 'PDF 处理失败,客户端没有返回原因', - errHostNoOutput: 'HOST_NO_OUTPUT: 客户端报告成功但没有返回输出文件路径,无法确认已导出', - errNoReadableText: '没有提取到可读文字,输出文件 {path} 为空白内容', - errGarbledText: '输出文件 {path} 内容疑似乱码(PDF 字体编码无法解析),请不要使用该文件', - errUnknownTool: 'UNKNOWN_TOOL: 没有 {toolId} 这个工具', - errToolUnavailable: '{tag}暂不可用:{reason}', - batchNotExecuted: '{tag}未执行', - batchSkippedNote: ';{count} 个不是 PDF,已跳过', - batchFailItem: '{name}:{error}', - wordFail: '失败', - batchNoFilesTitle: '没有可处理的文件', - batchAllSkippedMsg: '所选 {count} 个文件都不是 PDF', - batchSelectPdfFirst: '请先勾选要导出的 PDF', - batchExportedTitle: '已导出 {count} 个文件', - batchExportedDirMsg: '输出在各 PDF 所在目录', - batchFailedTitle: '导出失败({count} 个)', - batchPartialTitle: '{ok} 个已导出,{fail} 个失败', + forbiddenReason: '严禁向系统核心目录或目录穿越路径输出文件', sizeUnknown: '大小未识别', + toolInspectTitle: '检查与提取文本', + toolInspectSub: '读取页数、加密状态、页面尺寸与全文文本,支持复制或导出 TXT', + toolInspectTag: '检查/提文本', + toolMergeTitle: '合并 PDF', + toolMergeSub: '按列表顺序将多个 PDF 合并为一个新文件', + toolMergeTag: '合并', + toolSplitTitle: '按页码拆分', + toolSplitSub: '按页码区间(如 1-3,4-6)将 PDF 拆分为独立文档', + toolSplitTag: '拆分', + toolReorderTitle: '页面重排', + toolReorderSub: '按指定页码顺序(如 3,1,2)重新排列 PDF 页面', + toolReorderTag: '重排', + toolRotateTitle: '页面旋转', + toolRotateSub: '顺时针旋转 PDF 页面 90° / 180° / 270°', + toolRotateTag: '旋转', + toolCompressTitle: '压缩优化', + toolCompressSub: '线性化与流对象重压缩,减小 PDF 文件体积', + toolCompressTag: '压缩', + toolEncryptTitle: '密码加密', + toolEncryptSub: '设置打开密码与权限密码保护 PDF 文档', + toolEncryptTag: '加密', + toolDecryptTitle: '密码解密', + toolDecryptSub: '输入原密码移除 PDF 加密保护并另存为新文件', + toolDecryptTag: '解密', + toolWatermarkTitle: '添加文字水印', + toolWatermarkSub: '为 PDF 每页叠加自定义文字水印与透明度', + toolWatermarkTag: '水印', + toolRenderTitle: 'PDF 转图片', + toolRenderSub: '按指定 DPI 将 PDF 页面渲染为 PNG 或 JPEG 图片', + toolRenderTag: '转图片', + toolImagesToPdfTitle: '多图合成 PDF', + toolImagesToPdfSub: '将多张 PNG / JPG / WebP 图片按顺序嵌入合成一个 PDF', + toolImagesToPdfTag: '图合 PDF', + errInvalidPath: '文件路径无效或命中安全保护规则', + errNeedAtLeastTwoPdf: '合并 PDF 至少需要选择 2 个 PDF 文件', + errNeedAtLeastOnePdf: '请先选择至少 1 个 PDF 文件', + errNeedAtLeastOneImage: '请先选择至少 1 张图片文件', + errInvalidPageRanges: '页码区间格式无效(示例:1-3,5,7-9)', + errInvalidPageOrder: '页面顺序格式无效(示例:3,1,2,需为正整数)', + errPasswordRequired: '请输入有效的密码', + errWatermarkRequired: '请输入水印文字内容', + errNoTaskToCancel: '当前没有正在运行的 PDF 任务', + errTransformFailed: 'PDF 处理失败', + errInspectFailed: 'PDF 检查失败', + errRenderFailed: 'PDF 渲染图片失败', + errEnsureFailed: '准备 PDF 文档引擎失败', + errUnsupportedEngine: '当前宿主暂不支持该 PDF 能力', + errQpdfRequired: '该高级操作需要按需准备 PDF 处理引擎(qpdf),请点击「准备引擎」', + toastEnsureOk: 'PDF 文档引擎已就绪', + toastEnsureFail: 'PDF 文档引擎准备失败', + toastCancelOk: '已取消当前 PDF 任务', + toastCancelFail: '取消任务失败', toastImportFailed: '导入失败', - pickFilesTitle: '选择 PDF 文件', - pickFilesFilter: 'PDF 文件', - pickFolderTitle: '选择包含 PDF 的文件夹', - errNoFolderPicked: '没有选择文件夹', - confirmVolumeTitle: '导入整个磁盘 {path} 中的 PDF?', - confirmVolumeMessage: '将读取该磁盘下 5 层以内的文件夹,最多导入 500 个 PDF,可能需要一些时间。', - confirmVolumePrimary: '继续导入', - toastRunningRemove: '该 PDF 正在导出,完成后再移除', - toastBusyClear: '正在处理,完成后再清空', - dropTitle: '拖入 PDF 或文件夹', - dropSubtitle: '文件夹内 5 层以内的 PDF 会一并导入', - toastNoToolAvailable: '没有可用的工具', - toastBatchBusy: '上一批还在导出,请稍候', - toastToolFailed: '{tag}失败', + toastNoToolAvailable: '没有可用工具', + toastBatchBusy: '当前任务尚未完成', + toastRunOk: '{tag} 完成', + toastRunFail: '{tag} 失败', toastOpenFailed: '无法打开文件', - toastRevealFailed: '无法在文件夹中显示', - actionPickFilesEllipsis: '选择文件…', - actionPickFolderEllipsis: '选择文件夹…', - actionExportChecked: '导出已勾选的 {count} 个 PDF', - actionExportCurrent: '导出当前 PDF', - actionExportOnlyCurrent: '仅导出当前 PDF', - actionRevealLastOutput: '在文件夹中显示上次输出', - actionOpenPdf: '用默认程序打开 PDF', - actionRevealPdf: '在文件夹中显示 PDF', - sectionList: '列表', - actionRemoveFromList: '从列表移除', - actionUnselectAll: '取消全选', - actionSelectAll: '全选', - actionClearList: '清空列表', - tagExported: '已导出', - tagExportFailed: '导出失败', - lastSummaryStats: '成功 {ok} 个 · 失败 {fail} 个', - selectedUnknownSuffix: ',部分大小未识别', - summaryImporting: '正在导入:已读取 {dirs} 个文件夹,找到 {files} 个文件', - summaryEmptyClient: '尚未添加 PDF · 可选择文件、文件夹,或直接拖入', - outsideClient: '需要在 ZTools 客户端中使用', - summarySelected: '已选 {selected}/{total} 个 PDF({size})· 清空列表 Ctrl+Shift+Backspace', - emptyNoMatch: '没有匹配的 PDF', - searchPlaceholder: '搜索 PDF 文件名或路径', - formatTooltip: '选择导出格式', - btnPickFiles: '选择文件', - btnPickFolder: '选择文件夹', - panelTitle: '导出设置', - fieldFormatLabel: '输出格式', - fieldFormatHtml: 'HTML 纯文本网页', - fieldFormatTxt: 'TXT 纯文本(UTF-8)', - fieldOutdirLabel: '输出位置', - fieldOutdirValue: 'PDF 所在目录;同名文件已存在时自动加序号,不覆盖', - fieldLimitLabel: '提取限制', - fieldUnavailableLabel: '暂不可用', - previewTitle: '导出结果', - previewRunning: '正在导出…', - previewIdle: '尚未导出', - metricSelectedFiles: '已选文件', - metricSelectedSize: '已选体积', - subListTitle: '待导出的 PDF(勾选后按 ↵ 开始)', - subListSubtitle: '{count} 个', - sectionPdfTitle: 'PDF({count})' + toastRevealFailed: '无法定位文件', + toastCopiedText: '已复制提取的 PDF 文本', + toastNoTextExtracted: '未提取到可复制文本', + toastRunningRemove: '正在处理该文件,完成后再移除', + toastBusyClear: '任务执行中,请等待或先取消任务', + pickFilesTitle: '选择 PDF 或图片文件', + pickFilesFilter: 'PDF 与图片', + pickFolderTitle: '选择要导入的文件夹', + errNoFolderPicked: '未选择文件夹', + confirmVolumeTitle: '确定扫描整个磁盘根目录 {path} 吗?', + confirmVolumeMessage: '扫描根目录可能耗时较长,建议选择具体文档文件夹。', + confirmVolumePrimary: '继续扫描', + dropTitle: '拖入 PDF 或图片文件', + dropSubtitle: '支持 PDF / PNG / JPG / WebP / BMP,输出绝不覆盖原文件', + searchPlaceholder: '搜索文件或过滤当前队列...', + wbTitle: 'PDF 工具箱', + wbSubtitle: '纯 PDF 完整处理 · 零 Office 假入口', + wbToolLabel: '操作工具', + wbPageRangesLabel: '页码区间 (如 1-3,4-6)', + wbPageOrderLabel: '重排页序 (如 3,1,2)', + wbRotateLabel: '旋转角度', + wbPasswordLabel: '打开密码 / 解密密码', + wbOwnerPasswordLabel: '权限密码 (可选)', + wbWatermarkLabel: '水印文字', + wbWatermarkOpacityLabel: '水印透明度 (0.05-1)', + wbRenderFormatLabel: '导出图片格式', + wbRenderDpiLabel: '渲染 DPI', + wbCardTitle: '引擎与处理状态', + badgeReady: '引擎就绪', + badgeProvision: '待准备引擎', + badgeUnsupported: '未支持', + badgeRunning: '处理中', + cardNoteReady: '支持检查/提文本、合并、拆分、重排、旋转、压缩、加解密、水印、渲染转图与多图合 PDF。输出均写入新文件,绝不覆盖原件。', + cardNoteProvision: '检测到文档处理引擎(qpdf)尚未下载,点击「准备引擎」即可按需拉取并校验。', + metricEngineQpdf: '高级引擎 (qpdf)', + metricQpdfAvailable: '已就绪', + metricQpdfMissing: '按需准备', + metricSelectedCount: '已选文件', + metricLastPages: '最近输出页数', + metricLastSize: '最近输出体积', + actionRunTool: '执行:{tag}', + actionEnsureEngine: '准备 PDF 引擎', + actionCancelTask: '取消当前任务', + actionPickFiles: '选择文件...', + actionPickFolder: '选择文件夹...', + btnRunExport: '开始导出 ({count})', + btnExporting: '导出中…', + tagExporting: '导出中', + actionOpenFile: '打开文件', + actionRevealFile: '在文件夹中显示', + actionRevealLastOutput: '打开最近输出位置', + actionCopyExtractedText: '复制提取文本', + actionToggleAll: '全选 / 取消全选', + actionRemoveItem: '从队列移除', + actionClearList: '清空队列', + filterSummary: '{tool} · 已选 {selected}/{total} 个文件', + subListTitle: '待处理文件队列 ({count})', + subListSubtitle: '已选 {selected} 个 · {size}', + emptyQueue: '请点击「选择文件」或拖入 PDF / 图片开始处理', + emptyNoMatch: '没有匹配搜索条件的文件', + panelTitle: 'PDF 工具箱', + sectionTitle: '文件列表 ({count})', + rotate90: '顺时针 90°', + rotate180: '旋转 180°', + rotate270: '逆时针 90° (270°)', + inspectResultMsg: '共 {pages} 页 · {enc} · 文本 {chars} 字符', + encryptedYes: '已加密', + encryptedNo: '未加密', + renderResultMsg: '已渲染 {pages} 页,共生成 {count} 张图片', + transformResultMsg: '处理完成({pages} 页 · {size}):{path}' }, 'en-US': { - forbiddenReason: 'PDF output path cannot contain directory traversal or overwrite system directories', - reasonOffice: 'Client lacks PDF/Office conversion component', - reasonRender: 'Client lacks PDF rendering component to export pages as images', - reasonImage: 'Image-to-PDF host interface is not supported yet', - reasonRebuild: 'Legacy PDF rebuild mode caused garbled fonts/images and has been disabled', - unavailableFeaturesNote: 'Format conversion, merge, split, compress, encrypt/decrypt (client lacks PDF parser/renderer)', - textExtractionLimitNote: 'Extracts uncompressed plain text only; scanned, compressed, or custom-encoded PDFs may fail to extract', - toolPdfToTxtTitle: 'Export PDF Text to TXT', - toolPdfToTxtSub: 'Extract readable text from PDF and save as UTF-8 plain text', - toolPdfToTxtTag: 'Export TXT', - toolPdfToHtmlTitle: 'Export PDF Text to HTML', - toolPdfToHtmlSub: 'Extract readable text from PDF as plain HTML (layout & images omitted)', - toolPdfToHtmlTag: 'Export HTML', - toolPdfToWordTitle: 'PDF to Word (.docx)', - toolPdfToWordTag: 'PDF to Word', - toolPdfToExcelTitle: 'PDF to Excel (.xlsx)', - toolPdfToExcelTag: 'PDF to Excel', - toolPdfToPptTitle: 'PDF to PPT (.pptx)', - toolPdfToPptTag: 'PDF to PPT', - toolPdfToImageTitle: 'PDF Pages to Images', - toolPdfToImageTag: 'PDF to Image', - toolWordToPdfTitle: 'Word to PDF', - toolWordToPdfTag: 'Word to PDF', - toolExcelToPdfTitle: 'Excel to PDF', - toolExcelToPdfTag: 'Excel to PDF', - toolImageToPdfTitle: 'Merge Images to PDF', - toolImageToPdfTag: 'Image to PDF', - toolPdfMergeTitle: 'Merge Multiple PDFs', - toolPdfMergeTag: 'Merge PDF', - toolPdfSplitTitle: 'Split PDF by Pages', - toolPdfSplitTag: 'Split PDF', - toolPdfCompressTitle: 'Compress PDF', - toolPdfCompressTag: 'Compress PDF', - errInvalidMethod: 'INVALID_METHOD: Method name cannot be empty', - errInvalidMethodFormat: 'INVALID_METHOD_FORMAT: Method name contains invalid characters or is too long', - errInvalidParams: 'INVALID_PARAMS: Parameters must be a non-null object', - errParamTooLong: 'PARAM_TOO_LONG: Parameter {key} exceeds maximum length', - errParamOutOfRange: 'PARAM_OUT_OF_RANGE: Numeric parameter {key} is out of range or non-finite', - errParamValidationFailed: 'Parameter validation failed', - errUnsupportedMethod: 'UNSUPPORTED_METHOD: Feature {method} is not available in this plugin', - errMissingHostComponent: 'Client lacks required component', - errUnsupportedTool: 'UNSUPPORTED: {tag} is unavailable: {reason}', - errCheckExistsFailed: 'Failed to check if file exists', - errMalformedExists: 'MALFORMED_EXISTS_RESPONSE: Client did not return file existence status', - errInvalidInputPath: 'INVALID_INPUT_PATH: Cannot derive output path from {path}', - errOutputCheckFailed: 'OUTPUT_CHECK_FAILED: Cannot verify {path} ({error}); export stopped to avoid overwriting', - errOutputNameExhausted: 'OUTPUT_NAME_EXHAUSTED: {max} [[max:file|files]] with {ext} already exist in {dir}; clean up first', - errPdfProcessNoReason: 'PDF processing failed; no reason returned by client', - errHostNoOutput: 'HOST_NO_OUTPUT: Client reported success without an output path; export unconfirmed', - errNoReadableText: 'No readable text extracted; output file {path} is empty', - errGarbledText: 'Output file {path} appears garbled (unresolvable PDF font encoding); do not use', - errUnknownTool: 'UNKNOWN_TOOL: Unknown tool {toolId}', - errToolUnavailable: '{tag} is unavailable: {reason}', - batchNotExecuted: '{tag} not executed', - batchSkippedNote: '; {count} non-PDF file(s) skipped', - batchFailItem: '{name}: {error}', - wordFail: 'Failed', - batchNoFilesTitle: 'No processable files', - batchAllSkippedMsg: 'None of the {count} selected file(s) are PDFs', - batchSelectPdfFirst: 'Please check at least one PDF to export', - batchExportedTitle: 'Exported {count} file(s)', - batchExportedDirMsg: 'Saved next to each source PDF', - batchFailedTitle: 'Export failed ({count})', - batchPartialTitle: '{ok} exported, {fail} failed', + forbiddenReason: 'Writing to protected system directories or traversal paths is forbidden', sizeUnknown: 'Unknown size', + toolInspectTitle: 'Inspect & Extract Text', + toolInspectSub: 'Read page count, encryption status, dimensions, and full text for copy or TXT export', + toolInspectTag: 'Inspect / Text', + toolMergeTitle: 'Merge PDFs', + toolMergeSub: 'Merge multiple PDF files into one document in list order', + toolMergeTag: 'Merge', + toolSplitTitle: 'Split by Ranges', + toolSplitSub: 'Split a PDF by page ranges (e.g. 1-3,4-6)', + toolSplitTag: 'Split', + toolReorderTitle: 'Reorder Pages', + toolReorderSub: 'Reorder PDF pages with custom sequence (e.g. 3,1,2)', + toolReorderTag: 'Reorder', + toolRotateTitle: 'Rotate Pages', + toolRotateSub: 'Rotate PDF pages clockwise by 90 / 180 / 270 degrees', + toolRotateTag: 'Rotate', + toolCompressTitle: 'Compress & Optimize', + toolCompressSub: 'Optimize and recompress PDF streams to reduce file size', + toolCompressTag: 'Compress', + toolEncryptTitle: 'Encrypt with Password', + toolEncryptSub: 'Protect PDF with user and owner passwords', + toolEncryptTag: 'Encrypt', + toolDecryptTitle: 'Decrypt PDF', + toolDecryptSub: 'Remove PDF password protection using existing password', + toolDecryptTag: 'Decrypt', + toolWatermarkTitle: 'Add Text Watermark', + toolWatermarkSub: 'Overlay custom text watermark with configurable opacity', + toolWatermarkTag: 'Watermark', + toolRenderTitle: 'Render PDF to Images', + toolRenderSub: 'Render PDF pages to PNG or JPEG images at specified DPI', + toolRenderTag: 'To Images', + toolImagesToPdfTitle: 'Images to PDF', + toolImagesToPdfSub: 'Combine multiple PNG/JPG/WebP images into a single PDF', + toolImagesToPdfTag: 'Images to PDF', + errInvalidPath: 'File path is invalid or blocked by security guard', + errNeedAtLeastTwoPdf: 'Select at least 2 PDF files to merge', + errNeedAtLeastOnePdf: 'Select at least 1 PDF file first', + errNeedAtLeastOneImage: 'Select at least 1 image file first', + errInvalidPageRanges: 'Invalid page ranges format (example: 1-3,5,7-9)', + errInvalidPageOrder: 'Invalid page order format (example: 3,1,2)', + errPasswordRequired: 'Please enter a valid password', + errWatermarkRequired: 'Please enter watermark text', + errNoTaskToCancel: 'No active PDF task to cancel', + errTransformFailed: 'PDF transform failed', + errInspectFailed: 'PDF inspect failed', + errRenderFailed: 'PDF render failed', + errEnsureFailed: 'Failed to provision PDF document engine', + errUnsupportedEngine: 'Current host does not support this PDF capability', + errQpdfRequired: 'This operation requires provisioning the PDF engine (qpdf). Click "Prepare PDF Engine".', + toastEnsureOk: 'PDF document engine ready', + toastEnsureFail: 'PDF engine provisioning failed', + toastCancelOk: 'Active PDF task cancelled', + toastCancelFail: 'Failed to cancel task', toastImportFailed: 'Import failed', - pickFilesTitle: 'Select PDF Files', - pickFilesFilter: 'PDF Files', - pickFolderTitle: 'Select Folder Containing PDFs', + toastNoToolAvailable: 'No tool available', + toastBatchBusy: 'A PDF task is already running', + toastRunOk: '{tag} completed', + toastRunFail: '{tag} failed', + toastOpenFailed: 'Failed to open file', + toastRevealFailed: 'Failed to reveal file', + toastCopiedText: 'Copied extracted PDF text', + toastNoTextExtracted: 'No text extracted to copy', + toastRunningRemove: 'Cannot remove file while processing', + toastBusyClear: 'Wait or cancel the active task before clearing', + pickFilesTitle: 'Select PDF or image files', + pickFilesFilter: 'PDF & Images', + pickFolderTitle: 'Select folder to import', errNoFolderPicked: 'No folder selected', - confirmVolumeTitle: 'Import PDFs from entire drive {path}?', - confirmVolumeMessage: 'Scans up to 5 levels deep and imports up to 500 PDFs; this may take a moment.', - confirmVolumePrimary: 'Continue Import', - toastRunningRemove: 'This PDF is being exported; wait until it finishes', - toastBusyClear: 'Operation in progress; wait before clearing', - dropTitle: 'Drop PDFs or Folders', - dropSubtitle: 'PDFs within 5 folder levels will be imported', - toastNoToolAvailable: 'No available tool', - toastBatchBusy: 'Previous batch is still exporting; please wait', - toastToolFailed: '{tag} failed', - toastOpenFailed: 'Unable to open file', - toastRevealFailed: 'Unable to reveal in folder', - actionPickFilesEllipsis: 'Select Files…', - actionPickFolderEllipsis: 'Select Folder…', - actionExportChecked: 'Export {count} Checked PDF(s)', - actionExportCurrent: 'Export Current PDF', - actionExportOnlyCurrent: 'Export Only This PDF', - actionRevealLastOutput: 'Reveal Last Output in Folder', - actionOpenPdf: 'Open PDF with Default App', - actionRevealPdf: 'Reveal PDF in Folder', - sectionList: 'List', - actionRemoveFromList: 'Remove from List', - actionUnselectAll: 'Unselect All', - actionSelectAll: 'Select All', - actionClearList: 'Clear List', - tagExported: 'Exported', - tagExportFailed: 'Failed', - lastSummaryStats: '{ok} succeeded · {fail} failed', - selectedUnknownSuffix: ' (some sizes unknown)', - summaryImporting: 'Importing: scanned {dirs} folder(s), found {files} file(s)', - summaryEmptyClient: 'No PDFs added yet · Select files/folders or drag and drop', - outsideClient: 'This plugin must be used inside the ZTools client', - summarySelected: 'Selected {selected}/{total} PDF(s) ({size}) · Clear Ctrl+Shift+Backspace', - emptyNoMatch: 'No matching PDFs', - searchPlaceholder: 'Search PDF filename or path…', - formatTooltip: 'Select export format', - btnPickFiles: 'Select Files', - btnPickFolder: 'Select Folder', - panelTitle: 'Export Settings', - fieldFormatLabel: 'Output Format', - fieldFormatHtml: 'Plain HTML Webpage', - fieldFormatTxt: 'Plain Text (UTF-8)', - fieldOutdirLabel: 'Output Location', - fieldOutdirValue: 'Same folder as source PDF; auto-numbered if name exists (no overwrite)', - fieldLimitLabel: 'Extraction Limit', - fieldUnavailableLabel: 'Unavailable', - previewTitle: 'Export Result', - previewRunning: 'Exporting…', - previewIdle: 'Not exported yet', - metricSelectedFiles: 'Selected Files', - metricSelectedSize: 'Selected Size', - subListTitle: 'PDF Queue (Check & press Enter to export)', - subListSubtitle: '{count}', - sectionPdfTitle: 'PDFs ({count})' + confirmVolumeTitle: 'Scan entire drive root {path}?', + confirmVolumeMessage: 'Scanning a drive root may take a long time.', + confirmVolumePrimary: 'Continue', + dropTitle: 'Drop PDF or image files', + dropSubtitle: 'Supports PDF / PNG / JPG / WebP / BMP. Originals are never overwritten.', + searchPlaceholder: 'Filter files in queue...', + wbTitle: 'PDF Toolbox', + wbSubtitle: 'Complete pure-PDF tools', + wbToolLabel: 'Operation', + wbPageRangesLabel: 'Page Ranges (e.g. 1-3,4-6)', + wbPageOrderLabel: 'Page Order (e.g. 3,1,2)', + wbRotateLabel: 'Rotation', + wbPasswordLabel: 'User / Decrypt Password', + wbOwnerPasswordLabel: 'Owner Password (optional)', + wbWatermarkLabel: 'Watermark Text', + wbWatermarkOpacityLabel: 'Opacity (0.05-1)', + wbRenderFormatLabel: 'Image Format', + wbRenderDpiLabel: 'Render DPI', + wbCardTitle: 'Engine & Status', + badgeReady: 'Ready', + badgeProvision: 'Needs Engine', + badgeUnsupported: 'Unsupported', + badgeRunning: 'Running', + cardNoteReady: 'Supports inspect/extract text, merge, split, reorder, rotate, compress, encrypt/decrypt, watermark, render to images, and images-to-PDF without overwriting originals.', + cardNoteProvision: 'PDF transform engine (qpdf) is not downloaded yet. Click "Prepare PDF Engine" to provision on demand.', + metricEngineQpdf: 'Advanced Engine (qpdf)', + metricQpdfAvailable: 'Ready', + metricQpdfMissing: 'On-demand', + metricSelectedCount: 'Selected Files', + metricLastPages: 'Last Pages', + metricLastSize: 'Last Output Size', + actionRunTool: 'Run: {tag}', + actionEnsureEngine: 'Prepare PDF Engine', + actionCancelTask: 'Cancel Active Task', + actionPickFiles: 'Select Files...', + actionPickFolder: 'Select Folder...', + btnRunExport: 'Export ({count})', + btnExporting: 'Exporting…', + tagExporting: 'Exporting', + actionOpenFile: 'Open File', + actionRevealFile: 'Reveal in Folder', + actionRevealLastOutput: 'Reveal Last Output', + actionCopyExtractedText: 'Copy Extracted Text', + actionToggleAll: 'Toggle Select All', + actionRemoveItem: 'Remove from Queue', + actionClearList: 'Clear Queue', + filterSummary: '{tool} · Selected {selected}/{total} file(s)', + subListTitle: 'File Queue ({count})', + subListSubtitle: 'Selected {selected} · {size}', + emptyQueue: 'Click "Select Files" or drop PDF / image files to begin', + emptyNoMatch: 'No matching files', + panelTitle: 'PDF Toolbox', + sectionTitle: 'Files ({count})', + rotate90: 'Rotate 90° CW', + rotate180: 'Rotate 180°', + rotate270: 'Rotate 270° CW', + inspectResultMsg: '{pages} page(s) · {enc} · {chars} char(s) extracted', + encryptedYes: 'Encrypted', + encryptedNo: 'Unencrypted', + renderResultMsg: 'Rendered {pages} page(s) into {count} image(s)', + transformResultMsg: 'Completed ({pages} page(s) · {size}): {path}' } -}) -export const t: typeof rawT = (key, params) => { - const out = rawT(key, params) - if (!out.includes('[[')) return out - return out.replace(/\[\[([A-Za-z0-9_.-]+):([^|\]]+)\|([^\]]+)\]\]/g, (_m, k: string, one: string, other: string) => { - const v = params?.[k] - const n = typeof v === 'number' ? v : Number(String(v ?? '').replace(/,/g, '')) - return n === 1 ? one : other - }) } + +export const t = createTranslator(MESSAGES, { defaultLocale: 'en-US' }) diff --git a/extensions/pdf/src/index.ts b/extensions/pdf/src/index.ts index 319d1e55..23d9e30e 100644 --- a/extensions/pdf/src/index.ts +++ b/extensions/pdf/src/index.ts @@ -1,8 +1,16 @@ +/** + * PDF 工具箱(布局三:左侧纯 PDF 参数工作台 + 右侧待处理文件队列) + * + * - 支持全部 11 项纯 PDF 能力:检查/提文本、合并、拆分、重排、旋转、压缩、加密、解密、水印、PDF 转图片、多图合 PDF + * - 零 Word/Excel/PPT 互转假入口 + * - 按 optionalExtensions 探测 qpdf 并在需要时引导 tool_runtime_ensure 按需下载 + */ import { List, ActionPanel, Action, Icon, + Clipboard, useLocale, useState, useEffect, @@ -17,21 +25,25 @@ import { t } from './i18n.js' import { PDF_IMPORT_RULES, PDF_IMPORT_SUPPORTED_TEXT, - PdfBatchResult, - PdfTaskOutcome, - RealPdfDocItem, + cancelActivePdfTask, createPdfImportTransport, - describeBatchResult, + ensurePdfEngine, + findCapability, formatBytes, getAvailableTools, - getTextExtractionLimitNote, - getUnavailableFeaturesNote, + hasQpdfExtension, openPdfDocument, openPdfFileLocation, + queryRuntimeCapabilities, runPdfTool, - toPdfDocItem + toPdfDocItem, + type PdfOperationId, + type PdfRenderFormat, + type PdfRotateDegrees, + type PdfRunResult, + type RealPdfDocItem, + type ToolRuntimeCapabilitiesSnapshot } from './logic.js' -import { isRealElectronHost } from './native-ipc.js' import { isDeclarativeFileInputSupported } from './host-compat.js' import { FileImportResult, @@ -75,27 +87,45 @@ export function PdfCommand() { useLocale() const tools = getAvailableTools() const transport = createPdfImportTransport() + const [searchText, setSearchText] = useState('') - const [activeToolId, setActiveToolId] = useState(tools[0]?.id ?? '') + const [activeToolId, setActiveToolId] = useState('pdf-inspect') const [files, setFiles] = useState([]) const [checkedIds, setCheckedIds] = useState([]) + const [capabilities, setCapabilities] = useState(null) + + const [pageRangesText, setPageRangesText] = useState('1-2') + const [pageOrderText, setPageOrderText] = useState('1,2') + const [rotateDegrees, setRotateDegrees] = useState(90) + const [password, setPassword] = useState('') + const [ownerPassword, setOwnerPassword] = useState('') + const [watermarkText, setWatermarkText] = useState('CONFIDENTIAL') + const [watermarkOpacity, setWatermarkOpacity] = useState('0.3') + const [renderFormat, setRenderFormat] = useState('png') + const [renderDpi, setRenderDpi] = useState('150') + const [isImporting, setIsImporting] = useState(false) - const [importProgress, setImportProgress] = useState(null) const [isRunning, setIsRunning] = useState(false) const [runningIds, setRunningIds] = useState([]) - const [lastResult, setLastResult] = useState(null) - // 防止上一批还没写完时再次触发(状态更新前的连续回车) + const [lastResult, setLastResult] = useState(null) + const busyRef = useRef(false) const mountedRef = useRef(true) - // 导入批次号:清空列表、卸载或开始新导入时递增,过期批次的结果直接丢弃 const importSeqRef = useRef(0) const importAbortRef = useRef(null) - // 合并导入结果时需要同步拿到最新列表(setState 回调里不能弹提示) const filesRef = useRef([]) filesRef.current = files + async function refreshCapabilities() { + const res = await queryRuntimeCapabilities() + if (mountedRef.current && res.ok && res.data) { + setCapabilities(res.data) + } + } + useEffect(() => { mountedRef.current = true + void refreshCapabilities() let dispose: unknown = null let eventsApi: | { @@ -128,14 +158,13 @@ export function PdfCommand() { } }, []) - /** 所有导入入口共用:合并去重、默认勾选新文件、给出提示 */ function applyImportResult(result: FileImportResult) { const incoming = result.files.map(toPdfDocItem) - const { merged, added, duplicates } = mergeByPath(filesRef.current, incoming, f => f.path) + const { merged, added, duplicates } = mergeByPath(filesRef.current, incoming, (f) => f.path) if (added.length > 0) { filesRef.current = merged setFiles(merged) - setCheckedIds(prev => Array.from(new Set([...prev, ...added.map(f => f.id)]))) + setCheckedIds((prev) => Array.from(new Set([...prev, ...added.map((f) => f.id)]))) } const summary = summarizeImport(result, { added: added.length, duplicates }, PDF_IMPORT_SUPPORTED_TEXT) if (summary) { @@ -153,11 +182,8 @@ export function PdfCommand() { importAbortRef.current = controller const seq = ++importSeqRef.current setIsImporting(true) - setImportProgress(null) try { - const result = await task(controller.signal, progress => { - if (mountedRef.current && seq === importSeqRef.current) setImportProgress(progress) - }) + const result = await task(controller.signal, () => undefined) if (!mountedRef.current || seq !== importSeqRef.current || controller.signal.aborted) return applyImportResult(result) } catch (err) { @@ -167,7 +193,6 @@ export function PdfCommand() { if (mountedRef.current && seq === importSeqRef.current) { importAbortRef.current = null setIsImporting(false) - setImportProgress(null) } } } @@ -181,7 +206,14 @@ export function PdfCommand() { const picked = await pickFolder(transport, { title: t('pickFolderTitle') }) if (picked.canceled || signal.aborted) return { files: [], ignored: 0, truncated: false, failedDirs: [], canceled: true } if (picked.error || !picked.folderPath) { - return { files: [], ignored: 0, truncated: false, failedDirs: [], canceled: false, error: resolveErrorMessage(picked, t('errNoFolderPicked')) } + return { + files: [], + ignored: 0, + truncated: false, + failedDirs: [], + canceled: false, + error: resolveErrorMessage(picked, t('errNoFolderPicked')) + } } if (isVolumeRoot(picked.folderPath)) { const confirmed = await confirmAlert({ @@ -206,14 +238,14 @@ export function PdfCommand() { } function handleRemove(file: RealPdfDocItem) { - if (runningIds.includes(file.id)) { + if (busyRef.current) { showToast({ style: Toast.Style.Failure, title: t('toastRunningRemove') }) return } - const next = filesRef.current.filter(f => f.id !== file.id) + const next = filesRef.current.filter((f) => f.id !== file.id) filesRef.current = next setFiles(next) - setCheckedIds(prev => prev.filter(id => id !== file.id)) + setCheckedIds((prev) => prev.filter((id) => id !== file.id)) } function handleClear() { @@ -221,68 +253,85 @@ export function PdfCommand() { showToast({ style: Toast.Style.Failure, title: t('toastBusyClear') }) return } - // 让进行中的导入作废,结果不再加入列表 importSeqRef.current += 1 importAbortRef.current?.abort() - importAbortRef.current = null - setIsImporting(false) - setImportProgress(null) filesRef.current = [] setFiles([]) setCheckedIds([]) setLastResult(null) } - const fileInputProps = createImportInputProps(handleFileInput, { - dropTitle: t('dropTitle'), - dropSubtitle: t('dropSubtitle') - }) + async function handleEnsureEngine() { + if (busyRef.current) return + busyRef.current = true + setIsRunning(true) + try { + const res = await ensurePdfEngine() + if (!mountedRef.current) return + if (!res.ok) { + showToast({ style: Toast.Style.Failure, title: t('toastEnsureFail'), message: res.error }) + } else { + showToast({ style: Toast.Style.Success, title: t('toastEnsureOk') }) + } + await refreshCapabilities() + } finally { + busyRef.current = false + if (mountedRef.current) setIsRunning(false) + } + } - const activeTool = tools.find(item => item.id === activeToolId) ?? tools[0] - const queueFiles = activeTool ? files.filter(f => f.docType === activeTool.inputType) : [] - const selectedFiles = queueFiles.filter(f => checkedIds.includes(f.id)) + async function handleCancel() { + const res = await cancelActivePdfTask() + if (!res.ok) { + showToast({ style: Toast.Style.Failure, title: t('toastCancelFail'), message: res.error }) + } else { + showToast({ style: Toast.Style.Success, title: t('toastCancelOk'), message: res.taskId }) + } + } + + const activeTool = tools.find((item) => item.id === activeToolId) ?? tools[0]! + const queueFiles = files.filter((f) => f.docType === activeTool.inputKind) + const selectedFiles = queueFiles.filter((f) => checkedIds.includes(f.id)) const selectedBytes = selectedFiles.reduce((s, f) => s + (f.sizeBytes ?? 0), 0) - const selectedUnknown = selectedFiles.some(f => f.sizeBytes === null) const q = searchText.trim().toLowerCase() - const visibleFiles = queueFiles.filter( - f => !q || f.name.toLowerCase().includes(q) || f.path.toLowerCase().includes(q) - ) - const outcomeById = new Map() - for (const o of [...(lastResult?.succeeded ?? []), ...(lastResult?.failed ?? [])]) { - outcomeById.set(o.file.id, o) - } - const lastOutputPath = lastResult?.succeeded[lastResult.succeeded.length - 1]?.outputPath ?? '' - const allVisibleChecked = visibleFiles.length > 0 && visibleFiles.every(f => checkedIds.includes(f.id)) + const visibleFiles = queueFiles.filter((f) => !q || f.name.toLowerCase().includes(q) || f.path.toLowerCase().includes(q)) + const allVisibleChecked = visibleFiles.length > 0 && visibleFiles.every((f) => checkedIds.includes(f.id)) + + const transformCap = findCapability(capabilities, 'document.pdf.transform') + const qpdfAvailable = hasQpdfExtension(capabilities) + const needsProvision = transformCap?.status === 'needs_provisioning' + const isUnsupported = transformCap?.status === 'unsupported' async function handleRun(targets: RealPdfDocItem[]) { - if (!activeTool) { - showToast({ style: Toast.Style.Failure, title: t('toastNoToolAvailable') }) - return - } if (busyRef.current) { showToast({ style: Toast.Style.Failure, title: t('toastBatchBusy') }) return } - if (targets.length === 0) { - showToast({ style: Toast.Style.Failure, title: t('batchSelectPdfFirst') }) - return - } busyRef.current = true setIsRunning(true) - setRunningIds(targets.map(f => f.id)) + setRunningIds(targets.map((f) => f.id)) try { - const result = await runPdfTool(activeTool.id, targets) + const opacityNum = Number(watermarkOpacity) + const dpiNum = Number(renderDpi) + const result = await runPdfTool(activeTool.id, targets, { + pageRangesText, + pageOrderText, + rotateDegrees, + password, + ownerPassword, + watermarkText, + watermarkOpacity: Number.isFinite(opacityNum) ? opacityNum : 0.3, + renderFormat, + renderDpi: Number.isFinite(dpiNum) ? dpiNum : 150, + capabilities + }) if (!mountedRef.current) return setLastResult(result) - const summary = describeBatchResult(result) showToast({ - style: summary.ok ? Toast.Style.Success : Toast.Style.Failure, - title: summary.title, - message: summary.message + style: result.ok ? Toast.Style.Success : Toast.Style.Failure, + title: result.ok ? t('toastRunOk', { tag: activeTool.tag }) : t('toastRunFail', { tag: activeTool.tag }), + message: result.message }) - } catch (err) { - if (!mountedRef.current) return - showToast({ style: Toast.Style.Failure, title: t('toastToolFailed', { tag: activeTool.tag }), message: friendlyFileError(err) }) } finally { busyRef.current = false if (mountedRef.current) { @@ -304,225 +353,299 @@ export function PdfCommand() { } } + async function handleCopyExtractedText() { + const text = lastResult?.extractedText || '' + if (!text) { + showToast({ style: Toast.Style.Failure, title: t('toastNoTextExtracted') }) + return + } + await Clipboard.copy(text) + showToast({ style: Toast.Style.Success, title: t('toastCopiedText') }) + } + function toggleAllVisible() { - const visibleIds = visibleFiles.map(f => f.id) - setCheckedIds(prev => - allVisibleChecked ? prev.filter(id => !visibleIds.includes(id)) : Array.from(new Set([...prev, ...visibleIds])) + const visibleIds = visibleFiles.map((f) => f.id) + setCheckedIds((prev) => + allVisibleChecked ? prev.filter((id) => !visibleIds.includes(id)) : Array.from(new Set([...prev, ...visibleIds])) ) } - const pickFilesAction = () => - Action({ title: t('actionPickFilesEllipsis'), icon: Icon.Plus, shortcut: SHORTCUT_PICK_FILES, onAction: handlePickFiles }) - const pickFolderAction = () => - Action({ title: t('actionPickFolderEllipsis'), icon: Icon.Folder, shortcut: SHORTCUT_PICK_FOLDER, onAction: handlePickFolder }) + const fileInputProps = createImportInputProps(handleFileInput, { + dropTitle: t('dropTitle'), + dropSubtitle: t('dropSubtitle') + }) - const maxDocBytes = Math.max(1, ...visibleFiles.map(f => f.sizeBytes ?? 0)) - const queueItems = visibleFiles.map(f => { + const queueItems = visibleFiles.map((f) => { const isChecked = checkedIds.includes(f.id) - const outcome = outcomeById.get(f.id) - const volRatio = Math.max(2, Math.min(100, Math.round(((f.sizeBytes ?? 0) / maxDocBytes) * 100))) - const runChecked = selectedFiles.length > 0 - const isProcessing = runningIds.includes(f.id) - const actions = [ - Action({ - title: runChecked ? t('actionExportChecked', { count: selectedFiles.length }) : t('actionExportCurrent'), - icon: Icon.Play, - onAction: () => handleRun(runChecked ? selectedFiles : [f]) - }), - ...(runChecked - ? [ - Action({ - title: t('actionExportOnlyCurrent'), - icon: Icon.Document, - onAction: () => handleRun([f]) - }) - ] - : []), - ...(lastOutputPath - ? [ - Action({ - title: t('actionRevealLastOutput'), - icon: Icon.Folder, - onAction: () => handleOpen(lastOutputPath, 'reveal') - }) - ] - : []), - Action({ - title: t('actionOpenPdf'), - icon: Icon.Eye, - onAction: () => handleOpen(f.path, 'open') - }), - Action({ - title: t('actionRevealPdf'), - icon: Icon.Folder, - onAction: () => handleOpen(f.path, 'reveal') - }), - ActionPanel.Section({ - title: t('sectionList'), - children: [ - ...(isProcessing - ? [] - : [ - Action({ - title: t('actionRemoveFromList'), - icon: Icon.Minus, - shortcut: SHORTCUT_REMOVE, - onAction: () => handleRemove(f) - }) - ]), - pickFilesAction(), - pickFolderAction(), - Action({ - title: allVisibleChecked ? t('actionUnselectAll') : t('actionSelectAll'), - icon: Icon.CheckCircle, - shortcut: SHORTCUT_TOGGLE_ALL, - onAction: toggleAllVisible - }), - Action({ - title: t('actionClearList'), - icon: Icon.Trash, - style: Action.Style.Destructive, - shortcut: SHORTCUT_CLEAR, - onAction: handleClear - }) - ] - }) - ] - + const isProcessing = isRunning && runningIds.includes(f.id) + const targets = selectedFiles.length > 0 ? selectedFiles : [f] return List.Item({ id: f.id, title: f.name, subtitle: f.parentDir, + icon: { source: f.docType === 'image' ? Icon.Image : Icon.Document }, checkable: true, checked: isChecked, - onCheckChange: c => { - setCheckedIds(prev => (c ? Array.from(new Set([...prev, f.id])) : prev.filter(id => id !== f.id))) + onCheckChange: () => { + setCheckedIds((prev) => (prev.includes(f.id) ? prev.filter((id) => id !== f.id) : [...prev, f.id])) }, - icon: { source: Icon.Document }, accessories: [ - { progress: { value: volRatio } }, - ...(outcome ? [{ tag: { value: outcome.ok ? t('tagExported') : t('tagExportFailed') } }] : []), + ...(isProcessing ? [{ tag: { value: t('tagExporting') } }] : []), + { tag: f.extension.replace('.', '').toUpperCase() }, { text: sizeText(f.sizeBytes) } ], - actions: ActionPanel({ title: f.name, children: actions }) + actions: ActionPanel({ + title: f.name, + children: [ + Action({ title: t('actionRunTool', { tag: activeTool.tag }), icon: Icon.Play, onAction: () => handleRun(targets) }), + ...(lastResult?.extractedText + ? [Action({ title: t('actionCopyExtractedText'), icon: Icon.CopyClipboard, onAction: handleCopyExtractedText })] + : []), + ...(lastResult?.outputPath + ? [Action({ title: t('actionRevealLastOutput'), icon: Icon.Folder, onAction: () => handleOpen(lastResult.outputPath!, 'reveal') })] + : []), + Action({ title: t('actionOpenFile'), icon: Icon.Eye, onAction: () => handleOpen(f.path, 'open') }), + Action({ title: t('actionRevealFile'), icon: Icon.Folder, onAction: () => handleOpen(f.path, 'reveal') }), + Action({ title: t('actionPickFiles'), icon: Icon.Plus, shortcut: SHORTCUT_PICK_FILES, onAction: handlePickFiles }), + Action({ title: t('actionPickFolder'), icon: Icon.Folder, shortcut: SHORTCUT_PICK_FOLDER, onAction: handlePickFolder }), + Action({ title: t('actionToggleAll'), icon: Icon.CheckCircle, shortcut: SHORTCUT_TOGGLE_ALL, onAction: toggleAllVisible }), + Action({ title: t('actionRemoveItem'), icon: Icon.Trash, shortcut: SHORTCUT_REMOVE, onAction: () => handleRemove(f) }), + Action({ title: t('actionClearList'), icon: Icon.Trash, shortcut: SHORTCUT_CLEAR, onAction: handleClear }) + ] + }) }) }) - const lastSummary = !lastResult - ? '' - : lastResult.error - ? resolveErrorMessage(lastResult, t('tagExportFailed')) - : t('lastSummaryStats', { ok: lastResult.succeeded.length, fail: lastResult.failed.length }) - const inClient = isRealElectronHost() - const selectedBytesText = `${formatBytes(selectedBytes)}${selectedUnknown ? t('selectedUnknownSuffix') : ''}` - const summaryText = isImporting - ? t('summaryImporting', { dirs: importProgress?.visitedDirs ?? 0, files: importProgress?.matchedFiles ?? 0 }) - : files.length === 0 - ? inClient - ? t('summaryEmptyClient') - : t('outsideClient') - : t('summarySelected', { selected: selectedFiles.length, total: queueFiles.length, size: selectedBytesText }) - const emptyText = !inClient - ? t('outsideClient') - : q && files.length > 0 - ? t('emptyNoMatch') - : t('summaryEmptyClient') + type PdfWorkbenchField = NonNullable[0]>['workbenchPanel']>['fields']>[number] + const dynamicFields: PdfWorkbenchField[] = [ + { + id: 'pdf-tool-select', + label: t('wbToolLabel'), + type: 'select', + value: activeTool.id, + onChange: (val: string) => { + if (tools.some((item) => item.id === val)) setActiveToolId(val as PdfOperationId) + }, + options: tools.map((item) => ({ label: item.title, value: item.id })) + } + ] + + if (activeTool.id === 'pdf-split') { + dynamicFields.push({ + id: 'pdf-page-ranges', + label: t('wbPageRangesLabel'), + type: 'text', + value: pageRangesText, + onChange: setPageRangesText + }) + } else if (activeTool.id === 'pdf-reorder') { + dynamicFields.push({ + id: 'pdf-page-order', + label: t('wbPageOrderLabel'), + type: 'text', + value: pageOrderText, + onChange: setPageOrderText + }) + } else if (activeTool.id === 'pdf-rotate') { + dynamicFields.push({ + id: 'pdf-rotate-deg', + label: t('wbRotateLabel'), + type: 'select', + value: String(rotateDegrees), + onChange: (val: string) => { + const n = Number(val) + if (n === 90 || n === 180 || n === 270) setRotateDegrees(n) + }, + options: [ + { label: t('rotate90'), value: '90' }, + { label: t('rotate180'), value: '180' }, + { label: t('rotate270'), value: '270' } + ] + }) + } else if (activeTool.id === 'pdf-encrypt' || activeTool.id === 'pdf-decrypt' || activeTool.id === 'pdf-inspect') { + dynamicFields.push({ + id: 'pdf-password', + label: t('wbPasswordLabel'), + type: 'text', + value: password, + onChange: setPassword + }) + if (activeTool.id === 'pdf-encrypt') { + dynamicFields.push({ + id: 'pdf-owner-password', + label: t('wbOwnerPasswordLabel'), + type: 'text', + value: ownerPassword, + onChange: setOwnerPassword + }) + } + } else if (activeTool.id === 'pdf-watermark') { + dynamicFields.push( + { + id: 'pdf-watermark-text', + label: t('wbWatermarkLabel'), + type: 'text', + value: watermarkText, + onChange: setWatermarkText + }, + { + id: 'pdf-watermark-opacity', + label: t('wbWatermarkOpacityLabel'), + type: 'text', + value: watermarkOpacity, + onChange: setWatermarkOpacity + } + ) + } else if (activeTool.id === 'pdf-render') { + dynamicFields.push( + { + id: 'pdf-render-format', + label: t('wbRenderFormatLabel'), + type: 'select', + value: renderFormat, + onChange: (val: string) => { + if (val === 'png' || val === 'jpeg') setRenderFormat(val) + }, + options: [ + { label: 'PNG', value: 'png' }, + { label: 'JPEG', value: 'jpeg' } + ] + }, + { + id: 'pdf-render-dpi', + label: t('wbRenderDpiLabel'), + type: 'select', + value: renderDpi, + onChange: setRenderDpi, + options: [ + { label: '150 DPI', value: '150' }, + { label: '200 DPI', value: '200' }, + { label: '300 DPI', value: '300' } + ] + } + ) + } + + const cardMetrics: Array<{ label: string; value: string }> = [ + { label: t('metricEngineQpdf'), value: qpdfAvailable ? t('metricQpdfAvailable') : t('metricQpdfMissing') }, + { label: t('metricSelectedCount'), value: String(selectedFiles.length) } + ] + if (lastResult?.ok && typeof lastResult.pageCount === 'number') { + cardMetrics.push({ label: t('metricLastPages'), value: String(lastResult.pageCount) }) + } + if (lastResult?.ok && typeof lastResult.outputBytes === 'number') { + cardMetrics.push({ label: t('metricLastSize'), value: formatBytes(lastResult.outputBytes) }) + } return List({ - ...fileInputProps, searchBarPlaceholder: t('searchPlaceholder'), onSearchTextChange: setSearchText, isShowingDetail: false, isLoading: isImporting || isRunning, - actions: ActionPanel({ - children: [pickFilesAction(), pickFolderAction()] - }), - searchBarAccessory: List.Dropdown({ - tooltip: t('formatTooltip'), - value: activeTool?.id ?? '', - onChange: val => setActiveToolId(val), - children: tools.map(m => - List.Dropdown.Item({ - title: m.tag, - value: m.id - }) - ) - }), + ...fileInputProps, filterBar: FilterBar({ - summaryText, - actions: [ - { - id: 'pick-files', - label: t('btnPickFiles'), - title: t('btnPickFiles'), - style: 'secondary', - onAction: handlePickFiles - }, - { - id: 'pick-folder', - label: t('btnPickFolder'), - title: t('btnPickFolder'), - style: 'secondary', - onAction: handlePickFolder - } - ] + summaryText: t('filterSummary', { + tool: activeTool.title, + selected: selectedFiles.length, + total: queueFiles.length + }), + actions: needsProvision + ? [ + { + id: 'pick-files', + label: t('actionPickFiles'), + title: t('actionPickFiles'), + style: 'secondary', + onAction: handlePickFiles + }, + { + id: 'pdf-ensure-engine', + label: t('actionEnsureEngine'), + title: t('actionEnsureEngine'), + style: 'primary', + disabled: isRunning, + onAction: () => { + void handleEnsureEngine() + } + } + ] + : selectedFiles.length > 0 + ? [ + { + id: 'pick-files', + label: t('actionPickFiles'), + title: t('actionPickFiles'), + style: 'secondary', + onAction: handlePickFiles + }, + { + id: 'run-export', + label: isRunning ? t('btnExporting') : t('btnRunExport', { count: selectedFiles.length }), + title: isRunning ? t('btnExporting') : t('btnRunExport', { count: selectedFiles.length }), + style: 'primary', + disabled: isRunning, + onAction: () => { + void handleRun(selectedFiles) + } + } + ] + : [ + { + id: 'pick-files', + label: t('actionPickFiles'), + title: t('actionPickFiles'), + style: 'secondary', + onAction: handlePickFiles + }, + { + id: 'pick-folder', + label: t('actionPickFolder'), + title: t('actionPickFolder'), + style: 'secondary', + onAction: handlePickFolder + } + ] }), workbenchPanel: { - title: t('panelTitle'), - subtitle: activeTool?.title ?? '', - fields: [ - { - id: 'wb-format', - label: t('fieldFormatLabel'), - type: 'info', - value: activeTool?.outputExt === '.html' ? t('fieldFormatHtml') : t('fieldFormatTxt') - }, - { - id: 'wb-outdir', - label: t('fieldOutdirLabel'), - type: 'info', - value: t('fieldOutdirValue') - }, - { - id: 'wb-limit', - label: t('fieldLimitLabel'), - type: 'info', - value: getTextExtractionLimitNote() - }, - { - id: 'wb-unavailable', - label: t('fieldUnavailableLabel'), - type: 'info', - value: getUnavailableFeaturesNote() - } - ], + title: t('wbTitle'), + subtitle: t('wbSubtitle'), + fields: dynamicFields, previewCard: { - title: t('previewTitle'), - badge: activeTool?.tag ?? '', - subtitle: isRunning ? t('previewRunning') : lastSummary || t('previewIdle'), - metrics: [ - { label: t('metricSelectedFiles'), value: `${selectedFiles.length} / ${queueFiles.length}` }, - { label: t('metricSelectedSize'), value: selectedBytesText } - ] + title: t('wbCardTitle'), + badge: isRunning + ? t('badgeRunning') + : isUnsupported + ? t('badgeUnsupported') + : needsProvision + ? t('badgeProvision') + : t('badgeReady'), + subtitle: needsProvision ? t('cardNoteProvision') : t('cardNoteReady'), + metrics: cardMetrics } }, subList: { - title: t('subListTitle'), - subtitle: t('subListSubtitle', { count: visibleFiles.length }), + title: t('subListTitle', { count: visibleFiles.length }), + subtitle: t('subListSubtitle', { selected: selectedFiles.length, size: formatBytes(selectedBytes) }), + emptyText: q && queueFiles.length > 0 ? t('emptyNoMatch') : t('emptyQueue'), checkable: visibleFiles.length > 0, - checked: allVisibleChecked ? true : visibleFiles.some(f => checkedIds.includes(f.id)) ? 'indeterminate' : false, - onCheckChange: checked => { - const visibleIds = visibleFiles.map(f => f.id) - setCheckedIds(prev => - checked ? Array.from(new Set([...prev, ...visibleIds])) : prev.filter(id => !visibleIds.includes(id)) - ) - }, - emptyText, + checked: allVisibleChecked ? true : selectedFiles.length > 0 ? 'indeterminate' : false, + onCheckChange: toggleAllVisible, items: queueItems }, + actions: ActionPanel({ + title: t('panelTitle'), + children: [ + Action({ title: t('actionRunTool', { tag: activeTool.tag }), icon: Icon.Play, onAction: () => handleRun(selectedFiles) }), + Action({ title: t('actionEnsureEngine'), icon: Icon.Download, onAction: handleEnsureEngine }), + Action({ title: t('actionCancelTask'), icon: Icon.XMarkCircle, onAction: handleCancel }), + Action({ title: t('actionPickFiles'), icon: Icon.Plus, shortcut: SHORTCUT_PICK_FILES, onAction: handlePickFiles }), + Action({ title: t('actionPickFolder'), icon: Icon.Folder, shortcut: SHORTCUT_PICK_FOLDER, onAction: handlePickFolder }), + Action({ title: t('actionClearList'), icon: Icon.Trash, shortcut: SHORTCUT_CLEAR, onAction: handleClear }) + ] + }), children: [ List.Section({ - title: t('sectionPdfTitle', { count: visibleFiles.length }), + title: t('sectionTitle', { count: visibleFiles.length }), children: queueItems }) ] diff --git a/extensions/pdf/src/logic.ts b/extensions/pdf/src/logic.ts index 389b8684..f3231a19 100644 --- a/extensions/pdf/src/logic.ts +++ b/extensions/pdf/src/logic.ts @@ -1,21 +1,26 @@ /** - * PDF 工具箱业务逻辑层 + * PDF 工具箱业务逻辑层(Wave 3 薄原语域:document.pdf.inspect / document.pdf.transform / document.pdf.render) * - * - 用户通过「选择文件」「选择文件夹」或拖入导入 PDF(不在启动时扫描任何本机目录) - * - 调用客户端的 PDF 处理接口,把 PDF 中可读取的文字导出为 TXT / HTML - * - 输出文件写在 PDF 所在目录,写之前先确认同名文件不存在,已存在时自动加序号,绝不覆盖 - * - * 格式互转、合并、拆分、压缩、加解密在当前客户端没有可靠实现:工具定义保留(supported: false), - * 界面不展示,调用时直接拒绝,不会请求客户端,避免输出内容错乱的文件却报成功。 + * - 完整纯 PDF 工具箱:检查/提文本、合并、拆分、重排、旋转、压缩、加密、解密、文字水印、PDF 转图片、多图合成 PDF + * - 零 Word/Excel/PPT 互转假入口,零原生扩展依赖 + * - 支持按 optionalExtensions 探测 qpdf 并在需要时经 tool_runtime_ensure 按需准备引擎,支持 tool_task_cancel 取消长任务 */ import { + asRecord, callHostTransport, + cancelRuntimeTask, + ensureRuntimeCapability, + findCapability, formatBytes, - invokeDllPluginCapability, + hasCapabilityExtension, + nextMessageId, openRealPath, - showRealItemInFolder -} from './native-ipc.js' + queryRuntimeCapabilities, + showRealItemInFolder, + type ToolCapabilityStatus, + type ToolRuntimeCapabilitiesSnapshot +} from './tool-runtime.js' import { friendlyFileError, type FileImportRules, @@ -25,384 +30,260 @@ import { import { t } from './i18n.js' import { resolveErrorMessage } from './error-i18n.js' -export { formatBytes } from './native-ipc.js' - -export type PdfToolCategory = 'pdf_to_other' | 'other_to_pdf' | 'pdf_ops' -export type PdfInputType = 'pdf' | 'word' | 'excel' | 'ppt' | 'image' - -export interface CapabilityActionItem { - id: string - title: string - subtitle: string - tag: string - method: string - category?: PdfToolCategory - /** 工具接受的输入文件类型 */ - inputType: PdfInputType - /** 输出文件扩展名(含点) */ - outputExt: string - /** 当前客户端能否如实完成该工具 */ - supported: boolean - /** 不可用的原因(supported 为 false 时必填) */ - unsupportedReason?: string - /** 导出文字类工具:需要检查客户端返回的文字是否为乱码 */ - extractsText?: boolean - params: Record -} - -export interface NativeInvocationResult { - ok: boolean - pluginName: string - method: string - data?: unknown - error?: string - fromFallback?: boolean +export { + formatBytes, + queryRuntimeCapabilities, + findCapability, + hasCapabilityExtension, + type ToolCapabilityStatus, + type ToolRuntimeCapabilitiesSnapshot +} + +export type PdfOperationId = + | 'pdf-inspect' + | 'pdf-merge' + | 'pdf-split' + | 'pdf-reorder' + | 'pdf-rotate' + | 'pdf-compress' + | 'pdf-encrypt' + | 'pdf-decrypt' + | 'pdf-watermark' + | 'pdf-render' + | 'images-to-pdf' + +export type DocumentPdfTransformOperation = + | 'merge' + | 'split' + | 'reorder' + | 'rotate' + | 'compress' + | 'encrypt' + | 'decrypt' + | 'watermark' + | 'images-to-pdf' + +export type PdfInputKind = 'pdf' | 'image' +export type PdfRotateDegrees = 90 | 180 | 270 +export type PdfRenderFormat = 'png' | 'jpeg' + +export interface PdfToolDefinition { + readonly id: PdfOperationId + readonly title: string + readonly subtitle: string + readonly tag: string + readonly inputKind: PdfInputKind + readonly requiresMultiPdf?: boolean + readonly requiresQpdf?: boolean + readonly transformOperation?: DocumentPdfTransformOperation } export interface RealPdfDocItem { id: string name: string path: string - /** 文件实际所在目录 */ parentDir: string extension: string - docType: 'pdf' | 'word' | 'excel' | 'ppt' | 'image' | 'other' - /** 字节数;宿主没有返回时为 null(界面显示“大小未识别”) */ + docType: 'pdf' | 'image' sizeBytes: number | null } -/** 客户端内置 PDF 处理接口的插件名(客户端按插件 id 路由) */ -export const HOST_PLUGIN_NAME = 'pdf' +export interface PdfInspectResult { + ok: boolean + filePath: string + pageCount: number + encrypted: boolean + sizeBytes: number + title?: string + author?: string + fullText: string + error?: string +} + +export interface PdfRenderResult { + ok: boolean + taskId: string + outputDir: string + files: string[] + pageCount: number + error?: string +} + +export interface PdfTransformResult { + ok: boolean + taskId: string + operation: DocumentPdfTransformOperation + outputPath: string + outputBytes: number + pageCount: number + outputFiles: string[] + error?: string +} + +export interface PdfRunOptions { + pageRangesText?: string + pageOrderText?: string + rotateDegrees?: PdfRotateDegrees + password?: string + ownerPassword?: string + watermarkText?: string + watermarkOpacity?: number + renderFormat?: PdfRenderFormat + renderDpi?: number + renderPagesText?: string + capabilities?: ToolRuntimeCapabilitiesSnapshot | null +} + +export interface PdfRunResult { + ok: boolean + toolId: PdfOperationId + taskId?: string + outputPath?: string + outputFiles?: string[] + outputBytes?: number + pageCount?: number + extractedText?: string + encrypted?: boolean + message: string + error?: string +} + export const FORBIDDEN_TARGET_PATTERN = new RegExp('\\\\Windows\\\\System32|\\.\\.\\\\|\\.\\./', 'i') -export function getForbiddenReason(): string { - return t('forbiddenReason') +export const INPUT_PDF_EXTENSIONS = ['.pdf', '.png', '.jpg', '.jpeg', '.webp', '.bmp'] as const +export const PDF_IMPORT_SUPPORTED_TEXT = 'PDF / PNG / JPG / WebP / BMP' + +export const PDF_IMPORT_RULES: FileImportRules = { + extensions: INPUT_PDF_EXTENSIONS, + forbiddenPath: FORBIDDEN_TARGET_PATTERN } -/** 界面上统一说明的暂不可用功能 */ -export function getUnavailableFeaturesNote(): string { - return t('unavailableFeaturesNote') +let activePdfTaskId = '' + +export function getActivePdfTaskId(): string { + return activePdfTaskId } -/** 文字导出的能力边界 */ -export function getTextExtractionLimitNote(): string { - return t('textExtractionLimitNote') +export function resetPdfRuntimeState(): void { + activePdfTaskId = '' } -export function getPdfToolboxModes(): CapabilityActionItem[] { - const reasonOffice = t('reasonOffice') - const reasonRender = t('reasonRender') - const reasonImage = t('reasonImage') - const reasonRebuild = t('reasonRebuild') +export function getForbiddenReason(): string { + return t('forbiddenReason') +} + +export function createPdfImportTransport(hostOverride?: unknown): FileImportTransport { + return (method, params) => callHostTransport(method, params, hostOverride) +} + +/** 全部可用的纯 PDF 工具箱动作(无任何 Word/Excel/PPT 互转假入口) */ +export function getPdfToolboxModes(): PdfToolDefinition[] { return [ { - id: 'pdf-to-txt', - title: t('toolPdfToTxtTitle'), - subtitle: t('toolPdfToTxtSub'), - tag: t('toolPdfToTxtTag'), - category: 'pdf_to_other', - method: 'PdfToTxt', - inputType: 'pdf', - outputExt: '.txt', - supported: true, - extractsText: true, - params: {} + id: 'pdf-inspect', + title: t('toolInspectTitle'), + subtitle: t('toolInspectSub'), + tag: t('toolInspectTag'), + inputKind: 'pdf' }, { - id: 'pdf-to-html', - title: t('toolPdfToHtmlTitle'), - subtitle: t('toolPdfToHtmlSub'), - tag: t('toolPdfToHtmlTag'), - category: 'pdf_to_other', - method: 'PdfToHtml', - inputType: 'pdf', - outputExt: '.html', - supported: true, - extractsText: true, - params: {} - }, - { - id: 'pdf-to-word', - title: t('toolPdfToWordTitle'), - subtitle: reasonOffice, - tag: t('toolPdfToWordTag'), - category: 'pdf_to_other', - method: 'PdfToWord', - inputType: 'pdf', - outputExt: '.docx', - supported: false, - unsupportedReason: reasonOffice, - params: {} + id: 'pdf-merge', + title: t('toolMergeTitle'), + subtitle: t('toolMergeSub'), + tag: t('toolMergeTag'), + inputKind: 'pdf', + requiresMultiPdf: true, + requiresQpdf: true, + transformOperation: 'merge' }, { - id: 'pdf-to-excel', - title: t('toolPdfToExcelTitle'), - subtitle: reasonOffice, - tag: t('toolPdfToExcelTag'), - category: 'pdf_to_other', - method: 'PdfToExcel', - inputType: 'pdf', - outputExt: '.xlsx', - supported: false, - unsupportedReason: reasonOffice, - params: {} + id: 'pdf-split', + title: t('toolSplitTitle'), + subtitle: t('toolSplitSub'), + tag: t('toolSplitTag'), + inputKind: 'pdf', + requiresQpdf: true, + transformOperation: 'split' }, { - id: 'pdf-to-ppt', - title: t('toolPdfToPptTitle'), - subtitle: reasonOffice, - tag: t('toolPdfToPptTag'), - category: 'pdf_to_other', - method: 'PdfToPpt', - inputType: 'pdf', - outputExt: '.pptx', - supported: false, - unsupportedReason: reasonOffice, - params: {} + id: 'pdf-reorder', + title: t('toolReorderTitle'), + subtitle: t('toolReorderSub'), + tag: t('toolReorderTag'), + inputKind: 'pdf', + requiresQpdf: true, + transformOperation: 'reorder' }, { - id: 'pdf-to-image', - title: t('toolPdfToImageTitle'), - subtitle: reasonRender, - tag: t('toolPdfToImageTag'), - category: 'pdf_to_other', - method: 'PdfToImage', - inputType: 'pdf', - outputExt: '.png', - supported: false, - unsupportedReason: reasonRender, - params: {} + id: 'pdf-rotate', + title: t('toolRotateTitle'), + subtitle: t('toolRotateSub'), + tag: t('toolRotateTag'), + inputKind: 'pdf', + requiresQpdf: true, + transformOperation: 'rotate' }, { - id: 'word-to-pdf', - title: t('toolWordToPdfTitle'), - subtitle: reasonOffice, - tag: t('toolWordToPdfTag'), - category: 'other_to_pdf', - method: 'WordToPdf', - inputType: 'word', - outputExt: '.pdf', - supported: false, - unsupportedReason: reasonOffice, - params: {} + id: 'pdf-compress', + title: t('toolCompressTitle'), + subtitle: t('toolCompressSub'), + tag: t('toolCompressTag'), + inputKind: 'pdf', + requiresQpdf: true, + transformOperation: 'compress' }, { - id: 'excel-to-pdf', - title: t('toolExcelToPdfTitle'), - subtitle: reasonOffice, - tag: t('toolExcelToPdfTag'), - category: 'other_to_pdf', - method: 'ExcelToPdf', - inputType: 'excel', - outputExt: '.pdf', - supported: false, - unsupportedReason: reasonOffice, - params: {} + id: 'pdf-encrypt', + title: t('toolEncryptTitle'), + subtitle: t('toolEncryptSub'), + tag: t('toolEncryptTag'), + inputKind: 'pdf', + requiresQpdf: true, + transformOperation: 'encrypt' }, { - id: 'image-to-pdf', - title: t('toolImageToPdfTitle'), - subtitle: reasonImage, - tag: t('toolImageToPdfTag'), - category: 'other_to_pdf', - method: 'ImageToPdf', - inputType: 'image', - outputExt: '.pdf', - supported: false, - unsupportedReason: reasonImage, - params: {} + id: 'pdf-decrypt', + title: t('toolDecryptTitle'), + subtitle: t('toolDecryptSub'), + tag: t('toolDecryptTag'), + inputKind: 'pdf', + requiresQpdf: true, + transformOperation: 'decrypt' }, { - id: 'pdf-merge', - title: t('toolPdfMergeTitle'), - subtitle: reasonRebuild, - tag: t('toolPdfMergeTag'), - category: 'pdf_ops', - method: 'MergePdf', - inputType: 'pdf', - outputExt: '.pdf', - supported: false, - unsupportedReason: reasonRebuild, - params: {} + id: 'pdf-watermark', + title: t('toolWatermarkTitle'), + subtitle: t('toolWatermarkSub'), + tag: t('toolWatermarkTag'), + inputKind: 'pdf', + transformOperation: 'watermark' }, { - id: 'pdf-split', - title: t('toolPdfSplitTitle'), - subtitle: reasonRebuild, - tag: t('toolPdfSplitTag'), - category: 'pdf_ops', - method: 'SplitPdf', - inputType: 'pdf', - outputExt: '.pdf', - supported: false, - unsupportedReason: reasonRebuild, - params: {} + id: 'pdf-render', + title: t('toolRenderTitle'), + subtitle: t('toolRenderSub'), + tag: t('toolRenderTag'), + inputKind: 'pdf' }, { - id: 'pdf-compress', - title: t('toolPdfCompressTitle'), - subtitle: reasonRebuild, - tag: t('toolPdfCompressTag'), - category: 'pdf_ops', - method: 'CompressPdf', - inputType: 'pdf', - outputExt: '.pdf', - supported: false, - unsupportedReason: reasonRebuild, - params: {} + id: 'images-to-pdf', + title: t('toolImagesToPdfTitle'), + subtitle: t('toolImagesToPdfSub'), + tag: t('toolImagesToPdfTag'), + inputKind: 'image', + transformOperation: 'images-to-pdf' } ] } -export function getCapabilityItems(): CapabilityActionItem[] { - return getPdfToolboxModes().map(item => ({ - ...item, - params: { ...item.params } - })) -} - -/** 当前客户端能如实完成的工具(界面只展示这些) */ -export function getAvailableTools(): CapabilityActionItem[] { - return getCapabilityItems().filter(item => item.supported) -} - -export function filterCapabilityItems(items: CapabilityActionItem[], query: string): CapabilityActionItem[] { - if (!Array.isArray(items)) return [] - const q = typeof query === 'string' ? query.trim().toLowerCase() : '' - if (!q) return items - return items.filter(item => { - if (!item || typeof item.title !== 'string') return false - return ( - item.title.toLowerCase().includes(q) || - item.subtitle.toLowerCase().includes(q) || - item.tag.toLowerCase().includes(q) || - item.method.toLowerCase().includes(q) - ) - }) -} - -export function validateInvocationPayload(method: string, params: unknown): { valid: boolean; error?: string } { - if (typeof method !== 'string' || method.trim().length === 0) { - return { valid: false, error: t('errInvalidMethod') } - } - if (method.length > 128 || !/^[A-Za-z0-9_]+$/.test(method.trim())) { - return { valid: false, error: t('errInvalidMethodFormat') } - } - if (params === null || params === undefined || typeof params !== 'object' || Array.isArray(params)) { - return { valid: false, error: t('errInvalidParams') } - } - - const record = params as Record - for (const [key, val] of Object.entries(record)) { - if (typeof val === 'string') { - if (val.length > 4096) { - return { valid: false, error: t('errParamTooLong', { key }) } - } - if (FORBIDDEN_TARGET_PATTERN.test(val)) { - return { valid: false, error: `SECURITY_INTERCEPTED: ${t('forbiddenReason')}` } - } - } else if (typeof val === 'number') { - if (!Number.isFinite(val) || val < -1000 || val > 100_000_000) { - return { valid: false, error: t('errParamOutOfRange', { key }) } - } - } - } - - return { valid: true } -} - -/** - * 调用客户端 PDF 接口。只放行 supported 的工具:不可用的工具直接返回失败,不请求客户端。 - * 参数不合法时抛错。 - */ -export async function invokeNativeCapability( - method: string, - params: Record, - hostBridge?: unknown -): Promise { - const check = validateInvocationPayload(method, params) - if (!check.valid) { - throw new Error(resolveErrorMessage(check, t('errParamValidationFailed'))) - } - - const trimmedMethod = method.trim() - const tool = getPdfToolboxModes().find(item => item.method === trimmedMethod) - if (!tool) { - return { - ok: false, - pluginName: HOST_PLUGIN_NAME, - method: trimmedMethod, - error: t('errUnsupportedMethod', { method: trimmedMethod }), - fromFallback: false - } - } - if (!tool.supported) { - return { - ok: false, - pluginName: HOST_PLUGIN_NAME, - method: trimmedMethod, - error: t('errUnsupportedTool', { tag: tool.tag, reason: tool.unsupportedReason || t('errMissingHostComponent') }), - fromFallback: false - } - } - - const res = await invokeDllPluginCapability(HOST_PLUGIN_NAME, trimmedMethod, params, hostBridge) - return { - ok: res.ok, - pluginName: HOST_PLUGIN_NAME, - method: trimmedMethod, - data: res.data ?? undefined, - error: res.error, - fromFallback: res.fromFallback - } -} - -function classifyDocType(ext: string): RealPdfDocItem['docType'] { - if (ext === '.pdf') return 'pdf' - if (ext === '.docx' || ext === '.doc') return 'word' - if (ext === '.xlsx' || ext === '.xls') return 'excel' - if (ext === '.pptx' || ext === '.ppt') return 'ppt' - if (ext === '.png' || ext === '.jpg' || ext === '.jpeg' || ext === '.webp') return 'image' - return 'other' -} - -const INPUT_TYPE_EXTENSIONS: Record = { - pdf: ['.pdf'], - word: ['.docx', '.doc'], - excel: ['.xlsx', '.xls'], - ppt: ['.pptx', '.ppt'], - image: ['.png', '.jpg', '.jpeg'] -} - -const SUPPORTED_PDF_INPUT_TYPES: readonly PdfInputType[] = ['pdf'] - -/** 只放行当前已开放的工具真正能处理的输入格式(目前只有文字导出,即 PDF) */ -function buildImportExtensions(): string[] { - const exts = new Set() - for (const inputType of SUPPORTED_PDF_INPUT_TYPES) { - for (const ext of INPUT_TYPE_EXTENSIONS[inputType]) exts.add(ext) - } - return [...exts] +export function getAvailableTools(): PdfToolDefinition[] { + return getPdfToolboxModes() } -/** 导入允许的扩展名(小写带点) */ -export const INPUT_PDF_EXTENSIONS: readonly string[] = buildImportExtensions() - -/** 导入规则:递归 5 层、最多 500 个文件;系统核心目录与目录穿越路径一律跳过 */ -export const PDF_IMPORT_RULES: FileImportRules = { - extensions: INPUT_PDF_EXTENSIONS, - forbiddenPath: FORBIDDEN_TARGET_PATTERN +export function hasQpdfExtension(snapshot: ToolRuntimeCapabilitiesSnapshot | null | undefined): boolean { + return hasCapabilityExtension(snapshot, 'document.pdf.transform', 'qpdf') } -/** 界面上说明支持的格式 */ -export const PDF_IMPORT_SUPPORTED_TEXT = INPUT_PDF_EXTENSIONS.map(ext => ext.slice(1).toUpperCase()).join(' / ') - -/** 把宿主调用包装成 file-import 需要的形式 */ -export function createPdfImportTransport(hostOverride?: unknown): FileImportTransport { - return (method, params) => callHostTransport(method, params, hostOverride) -} - -/** 把导入结果转成列表条目 */ export function toPdfDocItem(file: ImportedFile): RealPdfDocItem { const ext = file.extension.toLowerCase() return { @@ -411,20 +292,17 @@ export function toPdfDocItem(file: ImportedFile): RealPdfDocItem { path: file.path, parentDir: file.parentDir, extension: ext, - docType: classifyDocType(ext), + docType: ext === '.pdf' ? 'pdf' : 'image', sizeBytes: file.sizeBytes } } -interface SplitPath { - /** 含末尾分隔符的目录部分 */ +export function splitFilePath(fullPath: string): { dirWithSep: string dir: string stem: string ext: string -} - -export function splitFilePath(fullPath: string): SplitPath | null { +} | null { if (typeof fullPath !== 'string') return null const trimmed = fullPath.trim() const lastSep = Math.max(trimmed.lastIndexOf('\\'), trimmed.lastIndexOf('/')) @@ -434,244 +312,411 @@ export function splitFilePath(fullPath: string): SplitPath | null { const dirWithSep = trimmed.slice(0, lastSep + 1) return { dirWithSep, - // 根目录(/ 或 C:\)保留分隔符,其余去掉末尾分隔符 dir: lastSep === 0 || /^[A-Za-z]:[\\/]$/.test(dirWithSep) ? dirWithSep : trimmed.slice(0, lastSep), stem: dot > 0 ? name.slice(0, dot) : name, ext: dot > 0 ? name.slice(dot) : '' } } -/** 同名文件已存在时最多尝试的序号 */ -export const MAX_OUTPUT_NAME_ATTEMPTS = 50 - -export function buildOutputCandidate(inputPath: string, outputExt: string, index: number): string | null { - const parts = splitFilePath(inputPath) - if (!parts) return null - const suffix = index > 0 ? ` (${index})` : '' - return `${parts.dirWithSep}${parts.stem}${suffix}${outputExt}` -} - -/** 查询文件是否已存在;查询失败时如实返回错误,调用方不能当作“不存在” */ -export async function checkFileExists( - fullPath: string, - hostOverride?: unknown -): Promise<{ ok: true; exists: boolean } | { ok: false; error: string }> { - const res = await callHostTransport('filesystem_file_exists', { path: fullPath }, hostOverride) - if (!res.ok) { - return { ok: false, error: friendlyFileError(resolveErrorMessage(res, t('errCheckExistsFailed'))) } +export function parsePageRanges(raw: string): string[] | null { + const parts = String(raw || '') + .split(/[,,;\s]+/) + .map((s) => s.trim()) + .filter((s) => s.length > 0) + if (parts.length === 0) return null + for (const part of parts) { + if (!/^\d+(?:-\d+)?$/.test(part)) return null + const [a, b] = part.split('-').map(Number) + if (!Number.isInteger(a) || a <= 0) return null + if (b !== undefined && (!Number.isInteger(b) || b < a)) return null } - const data = res.data - if (typeof data === 'boolean') return { ok: true, exists: data } - const exists = data && typeof data === 'object' ? (data as { exists?: unknown }).exists : undefined - if (typeof exists === 'boolean') { - return { ok: true, exists } + return parts +} + +export function parsePageOrder(raw: string): number[] | null { + const parts = String(raw || '') + .split(/[,,;\s]+/) + .map((s) => s.trim()) + .filter((s) => s.length > 0) + if (parts.length === 0) return null + const nums: number[] = [] + for (const part of parts) { + if (!/^\d+$/.test(part)) return null + const n = Number(part) + if (!Number.isInteger(n) || n <= 0) return null + nums.push(n) } - return { ok: false, error: t('errMalformedExists') } + return nums } -/** - * 找一个不会覆盖已有文件的输出路径:先用「原名.扩展名」,已存在则依次尝试「原名 (1).扩展名」…… - * 任何一次查询失败都停止,宁可不导出也不冒覆盖的风险。 - */ -export async function resolveAvailableOutputPath( - inputPath: string, - outputExt: string, - hostOverride?: unknown -): Promise<{ ok: true; path: string } | { ok: false; error: string }> { - for (let i = 0; i < MAX_OUTPUT_NAME_ATTEMPTS; i++) { - const candidate = buildOutputCandidate(inputPath, outputExt, i) - if (!candidate) { - return { ok: false, error: t('errInvalidInputPath', { path: inputPath }) } - } - const exists = await checkFileExists(candidate, hostOverride) - if (!exists.ok) { - return { - ok: false, - error: t('errOutputCheckFailed', { path: candidate, error: exists.error }) - } - } - if (!exists.exists) return { ok: true, path: candidate } - } - const parts = splitFilePath(inputPath) - return { - ok: false, - error: t('errOutputNameExhausted', { dir: parts?.dir ?? '', max: MAX_OUTPUT_NAME_ATTEMPTS, ext: outputExt }) - } +function makeOutputPath(baseFilePath: string, suffix: string, ext = '.pdf', now: Date = new Date()): string { + const parts = splitFilePath(baseFilePath) + const pad2 = (n: number) => String(n).padStart(2, '0') + const stamp = `${now.getFullYear()}${pad2(now.getMonth() + 1)}${pad2(now.getDate())}_${pad2(now.getHours())}${pad2(now.getMinutes())}${pad2(now.getSeconds())}` + if (!parts) return `${suffix}_${stamp}${ext}` + return `${parts.dirWithSep}${parts.stem}_${suffix}_${stamp}${ext}` } -/** 控制字符占比超过该值时认为客户端返回的文字是乱码(字体编码无法解析) */ -export const GARBLED_CONTROL_RATIO = 0.2 -/** 控制字符与 Unicode 替换字符(解码失败的标志) */ -const GARBLED_CHAR_PATTERN = new RegExp(`[\\u0000-\\u001f\\u007f-\\u009f${String.fromCharCode(0xfffd)}]`, 'g') - -export function assessExtractedText(text: unknown): { chars: number; garbled: boolean } { - const s = typeof text === 'string' ? text : '' - const visible = s.replace(/[ \t\r\n]/g, '') - if (visible.length === 0) return { chars: 0, garbled: false } - const control = (visible.match(GARBLED_CHAR_PATTERN) || []).length - return { chars: visible.length, garbled: control / visible.length > GARBLED_CONTROL_RATIO } +function makeRenderOutputDir(baseFilePath: string, now: Date = new Date()): string { + const parts = splitFilePath(baseFilePath) + const pad2 = (n: number) => String(n).padStart(2, '0') + const stamp = `${now.getFullYear()}${pad2(now.getMonth() + 1)}${pad2(now.getDate())}_${pad2(now.getHours())}${pad2(now.getMinutes())}${pad2(now.getSeconds())}` + if (!parts) return `pdf_pages_${stamp}` + return `${parts.dirWithSep}${parts.stem}_pages_${stamp}` } -export interface PdfTaskOutcome { - file: RealPdfDocItem - ok: boolean - outputPath?: string - /** 导出的可见字符数(客户端返回了文字时才有) */ - chars?: number - error?: string +function validateSafePaths(paths: readonly string[]): boolean { + return paths.length > 0 && paths.every((p) => typeof p === 'string' && p.trim().length > 0 && !FORBIDDEN_TARGET_PATTERN.test(p)) } -export interface PdfBatchResult { - toolId: string - toolTag: string - /** 整批被拒绝的原因(工具不可用等),此时没有处理任何文件 */ - error?: string - succeeded: PdfTaskOutcome[] - failed: PdfTaskOutcome[] - /** 类型不符、未处理的文件 */ - skipped: RealPdfDocItem[] +/** 按需准备 PDF 文档引擎(优先准备 document.pdf.transform 以拉取 qpdf) */ +export async function ensurePdfEngine( + hostOverride?: unknown +): Promise<{ ok: boolean; provisioned: string[]; error?: string }> { + const primitives = ['document.pdf.inspect', 'document.pdf.transform', 'document.pdf.render'] as const + const provisioned: string[] = [] + for (const primitiveId of primitives) { + const res = await ensureRuntimeCapability(primitiveId, hostOverride) + if (!res.ok) { + return { ok: false, provisioned, error: resolveErrorMessage(res, t('errEnsureFailed')) } + } + if (res.data?.status === 'unsupported') { + return { ok: false, provisioned, error: t('errUnsupportedEngine') } + } + if (res.data?.provisioned) provisioned.push(primitiveId) + } + return { ok: true, provisioned } } -function errorText(err: unknown): string { - return err instanceof Error ? err.message : String(err) +/** 取消正在执行的 PDF 变换或渲染任务 */ +export async function cancelActivePdfTask( + explicitTaskId?: string, + hostOverride?: unknown +): Promise<{ ok: boolean; taskId: string; cancelled: boolean; error?: string }> { + const targetTaskId = String(explicitTaskId || activePdfTaskId || '').trim() + if (!targetTaskId) { + return { ok: false, taskId: '', cancelled: false, error: t('errNoTaskToCancel') } + } + const res = await cancelRuntimeTask(targetTaskId, hostOverride) + if (!res.ok) { + return { ok: false, taskId: targetTaskId, cancelled: false, error: resolveErrorMessage(res, t('toastCancelFail')) } + } + if (targetTaskId === activePdfTaskId) activePdfTaskId = '' + return { ok: true, taskId: targetTaskId, cancelled: Boolean(res.data?.cancelled ?? true) } } -async function runOneFile( - tool: CapabilityActionItem, - file: RealPdfDocItem, +/** 检查 PDF 元数据并提取全文文本(tool_document_pdf_inspect) */ +export async function inspectPdfDocument( + filePath: string, + options: { password?: string; extractText?: boolean; maxTextPages?: number } = {}, hostOverride?: unknown -): Promise { - const target = await resolveAvailableOutputPath(file.path, tool.outputExt, hostOverride) - if (!target.ok) return { file, ok: false, error: target.error } - - let res: NativeInvocationResult - try { - res = await invokeNativeCapability( - tool.method, - { ...tool.params, inputPath: file.path, outputPath: target.path }, - hostOverride - ) - } catch (err) { - return { file, ok: false, error: friendlyFileError(err) } +): Promise { + if (!validateSafePaths([filePath])) { + return { ok: false, filePath, pageCount: 0, encrypted: false, sizeBytes: 0, fullText: '', error: t('errInvalidPath') } } - if (!res.ok) { - return { file, ok: false, error: friendlyFileError(resolveErrorMessage(res, t('errPdfProcessNoReason'))) } + const params: Record = { + input: { path: filePath.trim() }, + extractText: options.extractText !== false + } + if (options.password) params.password = options.password + if (typeof options.maxTextPages === 'number' && Number.isInteger(options.maxTextPages) && options.maxTextPages > 0) { + params.maxTextPages = options.maxTextPages } - const data = (res.data && typeof res.data === 'object' ? res.data : {}) as Record - const outputPath = typeof data.outputPath === 'string' ? data.outputPath.trim() : '' - if (!outputPath) { + const res = await callHostTransport('tool_document_pdf_inspect', params, hostOverride) + if (!res.ok) { return { - file, ok: false, - error: t('errHostNoOutput') + filePath, + pageCount: 0, + encrypted: false, + sizeBytes: 0, + fullText: '', + error: friendlyFileError(resolveErrorMessage(res, t('errInspectFailed'))) } } + const data = asRecord(res.data) + if (!data) { + return { ok: false, filePath, pageCount: 0, encrypted: false, sizeBytes: 0, fullText: '', error: t('errInspectFailed') } + } + const pages = Array.isArray(data.pages) ? data.pages.map(asRecord).filter((p): p is Record => Boolean(p)) : [] + const pageCount = Number(data.pageCount ?? pages.length) + const sizeBytes = Number(data.sizeBytes ?? 0) + const joinedText = + typeof data.fullText === 'string' + ? data.fullText + : pages.map((p) => (typeof p.text === 'string' ? p.text : '')).filter(Boolean).join('\n\n') + return { + ok: true, + filePath, + pageCount: Number.isFinite(pageCount) && pageCount >= 0 ? pageCount : 0, + encrypted: Boolean(data.encrypted), + sizeBytes: Number.isFinite(sizeBytes) && sizeBytes >= 0 ? sizeBytes : 0, + ...(typeof data.title === 'string' && data.title ? { title: data.title } : {}), + ...(typeof data.author === 'string' && data.author ? { author: data.author } : {}), + fullText: joinedText + } +} - if (tool.extractsText && typeof data.text === 'string') { - const quality = assessExtractedText(data.text) - if (quality.chars === 0) { - return { file, ok: false, outputPath, error: t('errNoReadableText', { path: outputPath }) } - } - if (quality.garbled) { +/** 渲染 PDF 页面为 PNG / JPEG 图片(tool_document_pdf_render) */ +export async function renderPdfToImages( + filePath: string, + options: { outputDir?: string; format?: PdfRenderFormat; dpi?: number; pages?: number[]; password?: string } = {}, + hostOverride?: unknown +): Promise { + if (!validateSafePaths([filePath])) { + return { ok: false, taskId: '', outputDir: '', files: [], pageCount: 0, error: t('errInvalidPath') } + } + const outputDir = options.outputDir?.trim() || makeRenderOutputDir(filePath) + if (FORBIDDEN_TARGET_PATTERN.test(outputDir)) { + return { ok: false, taskId: '', outputDir, files: [], pageCount: 0, error: t('forbiddenReason') } + } + const taskId = nextMessageId('pdf_render') + const params: Record = { + taskId, + input: { path: filePath.trim() }, + outputDir: { path: outputDir }, + format: options.format === 'jpeg' ? 'jpeg' : 'png', + dpi: typeof options.dpi === 'number' && options.dpi >= 72 && options.dpi <= 600 ? Math.round(options.dpi) : 150 + } + if (options.pages && options.pages.length > 0) params.pages = options.pages + if (options.password) params.password = options.password + + activePdfTaskId = taskId + try { + const res = await callHostTransport('tool_document_pdf_render', params, hostOverride) + if (!res.ok) { return { - file, ok: false, - outputPath, - error: t('errGarbledText', { path: outputPath }) + taskId, + outputDir, + files: [], + pageCount: 0, + error: friendlyFileError(resolveErrorMessage(res, t('errRenderFailed'))) } } - return { file, ok: true, outputPath, chars: quality.chars } + const data = asRecord(res.data) + const files = Array.isArray(data?.files) ? data.files.filter((f): f is string => typeof f === 'string') : [] + const pageCount = Number(data?.pageCount ?? files.length) + return { + ok: true, + taskId: typeof data?.taskId === 'string' && data.taskId ? data.taskId : taskId, + outputDir, + files, + pageCount: Number.isFinite(pageCount) && pageCount >= 0 ? pageCount : files.length + } + } finally { + if (activePdfTaskId === taskId) activePdfTaskId = '' } - return { file, ok: true, outputPath } } -/** - * 对一组文件依次执行工具(串行,前一个写完再处理下一个,序号判重才准确)。 - * 不可用的工具整批拒绝;类型不符的文件跳过并如实列出。 - */ -export async function runPdfTool( - toolId: string, - files: RealPdfDocItem[], +/** 执行 PDF 结构化变换(tool_document_pdf_transform) */ +export async function transformPdfDocuments( + operation: DocumentPdfTransformOperation, + inputPaths: readonly string[], + options: { + outputPath?: string + pageRanges?: string[] + pageOrder?: number[] + rotateDegrees?: PdfRotateDegrees + userPassword?: string + ownerPassword?: string + password?: string + watermarkText?: string + watermarkOpacity?: number + } = {}, hostOverride?: unknown -): Promise { - const tool = getPdfToolboxModes().find(item => item.id === toolId) - const result: PdfBatchResult = { - toolId, - toolTag: tool?.tag ?? toolId, - succeeded: [], - failed: [], - skipped: [] +): Promise { + if (!validateSafePaths(inputPaths)) { + return { ok: false, taskId: '', operation, outputPath: '', outputBytes: 0, pageCount: 0, outputFiles: [], error: t('errInvalidPath') } } - if (!tool) { - result.error = t('errUnknownTool', { toolId }) - return result + const outputPath = options.outputPath?.trim() || makeOutputPath(inputPaths[0]!, operation) + if (FORBIDDEN_TARGET_PATTERN.test(outputPath)) { + return { ok: false, taskId: '', operation, outputPath, outputBytes: 0, pageCount: 0, outputFiles: [], error: t('forbiddenReason') } + } + const taskId = nextMessageId(`pdf_${operation}`) + const params: Record = { + taskId, + operation, + inputs: inputPaths.map((p) => ({ path: p.trim() })), + output: { path: outputPath }, + overwrite: false } - if (!tool.supported) { - result.error = t('errToolUnavailable', { tag: tool.tag, reason: tool.unsupportedReason || t('errMissingHostComponent') }) - return result + if (options.pageRanges && options.pageRanges.length > 0) params.pageRanges = options.pageRanges + if (options.pageOrder && options.pageOrder.length > 0) params.pageOrder = options.pageOrder + if (options.rotateDegrees) params.rotateDegrees = options.rotateDegrees + if (options.userPassword) params.userPassword = options.userPassword + if (options.ownerPassword) params.ownerPassword = options.ownerPassword + if (options.password) params.password = options.password + if (options.watermarkText) params.watermarkText = options.watermarkText + if (typeof options.watermarkOpacity === 'number' && Number.isFinite(options.watermarkOpacity)) { + params.watermarkOpacity = Math.max(0.05, Math.min(1, options.watermarkOpacity)) } - for (const file of Array.isArray(files) ? files : []) { - if (!file || file.docType !== tool.inputType) { - if (file) result.skipped.push(file) - continue + activePdfTaskId = taskId + try { + const res = await callHostTransport('tool_document_pdf_transform', params, hostOverride) + if (!res.ok) { + return { + ok: false, + taskId, + operation, + outputPath, + outputBytes: 0, + pageCount: 0, + outputFiles: [], + error: friendlyFileError(resolveErrorMessage(res, t('errTransformFailed'))) + } + } + const data = asRecord(res.data) + const outputBytes = Number(data?.outputBytes ?? 0) + const pageCount = Number(data?.pageCount ?? 0) + const outputFiles = Array.isArray(data?.outputFiles) + ? data.outputFiles.filter((f): f is string => typeof f === 'string') + : [outputPath] + return { + ok: true, + taskId: typeof data?.taskId === 'string' && data.taskId ? data.taskId : taskId, + operation, + outputPath, + outputBytes: Number.isFinite(outputBytes) && outputBytes >= 0 ? outputBytes : 0, + pageCount: Number.isFinite(pageCount) && pageCount >= 0 ? pageCount : 0, + outputFiles } - const outcome = await runOneFile(tool, file, hostOverride) - if (outcome.ok) result.succeeded.push(outcome) - else result.failed.push(outcome) + } finally { + if (activePdfTaskId === taskId) activePdfTaskId = '' } - return result } -export interface BatchSummary { - ok: boolean - title: string - message: string -} +/** 统一运行任意纯 PDF 工具箱动作,包含输入校验与 qpdf 按需检查 */ +export async function runPdfTool( + toolId: PdfOperationId, + files: readonly RealPdfDocItem[], + options: PdfRunOptions = {}, + hostOverride?: unknown +): Promise { + const tool = getPdfToolboxModes().find((m) => m.id === toolId) + if (!tool) { + return { ok: false, toolId, message: t('toastNoToolAvailable'), error: 'UNKNOWN_PDF_TOOL' } + } + + const matched = files.filter((f) => f.docType === tool.inputKind) + if (tool.inputKind === 'image' && matched.length === 0) { + return { ok: false, toolId, message: t('errNeedAtLeastOneImage'), error: 'NO_IMAGE_SELECTED' } + } + if (tool.inputKind === 'pdf' && matched.length === 0) { + return { ok: false, toolId, message: t('errNeedAtLeastOnePdf'), error: 'NO_PDF_SELECTED' } + } + if (tool.requiresMultiPdf && matched.length < 2) { + return { ok: false, toolId, message: t('errNeedAtLeastTwoPdf'), error: 'NEED_AT_LEAST_TWO_PDF' } + } -/** 把批处理结果整理成一条提示:只要有失败就按失败提示,并给出第一条失败原因 */ -export function describeBatchResult(result: PdfBatchResult): BatchSummary { - if (result.error) { - return { ok: false, title: t('batchNotExecuted', { tag: result.toolTag }), message: result.error } + if (tool.requiresQpdf && options.capabilities) { + const transformCap = findCapability(options.capabilities, 'document.pdf.transform') + if (transformCap && transformCap.status === 'needs_provisioning' && !hasQpdfExtension(options.capabilities)) { + return { ok: false, toolId, message: t('errQpdfRequired'), error: 'QPDF_PROVISIONING_REQUIRED' } + } } - const okCount = result.succeeded.length - const failCount = result.failed.length - const skipNote = result.skipped.length > 0 ? t('batchSkippedNote', { count: result.skipped.length }) : '' - const firstFail = result.failed[0] - const failText = firstFail ? t('batchFailItem', { name: firstFail.file.name, error: resolveErrorMessage(firstFail, t('wordFail')) }) : '' - if (okCount === 0 && failCount === 0) { + if (toolId === 'pdf-inspect') { + const res = await inspectPdfDocument(matched[0]!.path, { password: options.password, extractText: true }, hostOverride) + if (!res.ok) return { ok: false, toolId, message: resolveErrorMessage(res, t('errInspectFailed')), error: res.error } return { - ok: false, - title: t('batchNoFilesTitle'), - message: result.skipped.length > 0 ? t('batchAllSkippedMsg', { count: result.skipped.length }) : t('batchSelectPdfFirst') + ok: true, + toolId, + pageCount: res.pageCount, + outputBytes: res.sizeBytes, + extractedText: res.fullText, + encrypted: res.encrypted, + message: t('inspectResultMsg', { + pages: res.pageCount, + enc: res.encrypted ? t('encryptedYes') : t('encryptedNo'), + chars: res.fullText.length + }) } } - if (failCount === 0) { - const only = result.succeeded[0] + + if (toolId === 'pdf-render') { + const pages = options.renderPagesText?.trim() ? parsePageOrder(options.renderPagesText) : undefined + if (options.renderPagesText?.trim() && !pages) { + return { ok: false, toolId, message: t('errInvalidPageOrder'), error: 'INVALID_PAGE_ORDER' } + } + const res = await renderPdfToImages( + matched[0]!.path, + { + format: options.renderFormat ?? 'png', + dpi: options.renderDpi ?? 150, + ...(pages ? { pages } : {}), + ...(options.password ? { password: options.password } : {}) + }, + hostOverride + ) + if (!res.ok) return { ok: false, toolId, taskId: res.taskId, message: resolveErrorMessage(res, t('errRenderFailed')), error: res.error } return { ok: true, - title: t('batchExportedTitle', { count: okCount }), - message: `${okCount === 1 && only?.outputPath ? only.outputPath : t('batchExportedDirMsg')}${skipNote}` + toolId, + taskId: res.taskId, + outputPath: res.outputDir, + outputFiles: res.files, + pageCount: res.pageCount, + message: t('renderResultMsg', { pages: res.pageCount, count: res.files.length }) } } - if (okCount === 0) { - return { ok: false, title: t('batchFailedTitle', { count: failCount }), message: `${failText}${skipNote}` } + + const operation = tool.transformOperation! + const transformOpts: Parameters[2] = {} + const targetInputs = operation === 'merge' || operation === 'images-to-pdf' + ? matched.map((f) => f.path) + : [matched[0]!.path] + + if (operation === 'split') { + const ranges = parsePageRanges(options.pageRangesText || '') + if (!ranges) return { ok: false, toolId, message: t('errInvalidPageRanges'), error: 'INVALID_PAGE_RANGES' } + transformOpts.pageRanges = ranges + } else if (operation === 'reorder') { + const order = parsePageOrder(options.pageOrderText || '') + if (!order) return { ok: false, toolId, message: t('errInvalidPageOrder'), error: 'INVALID_PAGE_ORDER' } + transformOpts.pageOrder = order + } else if (operation === 'rotate') { + transformOpts.rotateDegrees = options.rotateDegrees === 180 || options.rotateDegrees === 270 ? options.rotateDegrees : 90 + } else if (operation === 'encrypt') { + const pwd = String(options.password || '').trim() + if (!pwd) return { ok: false, toolId, message: t('errPasswordRequired'), error: 'PASSWORD_REQUIRED' } + transformOpts.userPassword = pwd + if (options.ownerPassword?.trim()) transformOpts.ownerPassword = options.ownerPassword.trim() + } else if (operation === 'decrypt') { + const pwd = String(options.password || '').trim() + if (!pwd) return { ok: false, toolId, message: t('errPasswordRequired'), error: 'PASSWORD_REQUIRED' } + transformOpts.password = pwd + } else if (operation === 'watermark') { + const wm = String(options.watermarkText || '').trim() + if (!wm) return { ok: false, toolId, message: t('errWatermarkRequired'), error: 'WATERMARK_REQUIRED' } + transformOpts.watermarkText = wm + transformOpts.watermarkOpacity = options.watermarkOpacity ?? 0.3 } + + const res = await transformPdfDocuments(operation, targetInputs, transformOpts, hostOverride) + if (!res.ok) return { ok: false, toolId, taskId: res.taskId, message: resolveErrorMessage(res, t('errTransformFailed')), error: res.error } return { - ok: false, - title: t('batchPartialTitle', { ok: okCount, fail: failCount }), - message: `${failText}${skipNote}` + ok: true, + toolId, + taskId: res.taskId, + outputPath: res.outputPath, + outputFiles: res.outputFiles, + outputBytes: res.outputBytes, + pageCount: res.pageCount, + message: t('transformResultMsg', { + pages: res.pageCount, + size: formatBytes(res.outputBytes), + path: res.outputPath + }) } } -export async function openPdfFileLocation(fullPath: string, hostOverride?: unknown): Promise { - if (!fullPath) return false - return showRealItemInFolder(fullPath, hostOverride) -} - export async function openPdfDocument(fullPath: string, hostOverride?: unknown): Promise { - if (!fullPath) return false return openRealPath(fullPath, hostOverride) } + +export async function openPdfFileLocation(fullPath: string, hostOverride?: unknown): Promise { + return showRealItemInFolder(fullPath, hostOverride) +} diff --git a/extensions/pdf/src/native-ipc.ts b/extensions/pdf/src/native-ipc.ts deleted file mode 100644 index 51576b99..00000000 --- a/extensions/pdf/src/native-ipc.ts +++ /dev/null @@ -1,1852 +0,0 @@ -import { getLocale } from '@ztools/declarative-ui' - -type DynamicBridge = ReturnType - -const NATIVE_IPC_MESSAGES: Record string - dirEntrySep: string - dirErrorColon: string - deepScanUnavailable: string - pathEmpty: string - invalidMethodEmpty: string - invalidMethodFormat: string - invalidParamsObject: string - paramTooLong: (key: string) => string - paramOutOfRange: (key: string) => string - methodParamEmpty: string - invalidMethodType: string - malformedDllResponse: string - unknownDllError: string - hostIpcFailed: (pluginName: string, method: string) => string - hostUnavailable: (pluginName: string, method: string) => string - callFailed: string - movedToTrash: string - deleteFailed: string - revealedInFolder: string - revealFailed: string - opened: string - openFailed: string - pluginCallNotReady: string -}> = { - 'zh-CN': { - ipcCallFailed: 'IPC 调用返回失败', - ipcInnerFailed: 'IPC 内部调用失败', - scanIncomplete: '扫描结果不完整', - dirReadFailed: (details, moreCount) => - `目录读取失败或不完整:${details}${moreCount > 0 ? `;另有 ${moreCount} 个目录` : ''}`, - dirEntrySep: ';', - dirErrorColon: ':', - deepScanUnavailable: '深度扫描不可用,仅列出一级目录,结果不完整', - pathEmpty: '路径不能为空', - invalidMethodEmpty: 'INVALID_METHOD: 调用方法名不能为空', - invalidMethodFormat: 'INVALID_METHOD_FORMAT: 方法名包含非法字符或超长', - invalidParamsObject: 'INVALID_PARAMS: 参数必须为非空对象', - paramTooLong: (key) => `PARAM_TOO_LONG: 参数 ${key} 超过最大长度限制`, - paramOutOfRange: (key) => `PARAM_OUT_OF_RANGE: 数值参数 ${key} 越界或非有限数`, - methodParamEmpty: 'method 参数不能为空', - invalidMethodType: 'INVALID_METHOD: method 不能为空且必须为字符串', - malformedDllResponse: 'MALFORMED_DLL_RESPONSE: 原生组件返回了损坏的 JSON 数据', - unknownDllError: '原生组件返回未知错误', - hostIpcFailed: (pluginName, method) => `HOST_IPC_FAILED: ${pluginName}.${method} 调用失败`, - hostUnavailable: (pluginName, method) => `HOST_UNAVAILABLE: ${pluginName}.${method} 宿主接口未就绪`, - callFailed: '调用失败', - movedToTrash: '已移入回收站', - deleteFailed: '删除失败', - revealedInFolder: '已定位文件', - revealFailed: '定位失败', - opened: '已打开', - openFailed: '打开失败', - pluginCallNotReady: '插件调用未就绪' - }, - 'en-US': { - ipcCallFailed: 'IPC call failed', - ipcInnerFailed: 'Internal IPC call failed', - scanIncomplete: 'Incomplete scan results', - dirReadFailed: (details, moreCount) => - `Directory read failed or incomplete: ${details}${moreCount > 0 ? `; and ${moreCount} more` : ''}`, - dirEntrySep: '; ', - dirErrorColon: ': ', - deepScanUnavailable: 'Deep scan unavailable; only top-level directory listed (incomplete)', - pathEmpty: 'Path cannot be empty', - invalidMethodEmpty: 'INVALID_METHOD: Method name cannot be empty', - invalidMethodFormat: 'INVALID_METHOD_FORMAT: Method name contains invalid characters or is too long', - invalidParamsObject: 'INVALID_PARAMS: Parameters must be a non-null object', - paramTooLong: (key) => `PARAM_TOO_LONG: Parameter "${key}" exceeds maximum length`, - paramOutOfRange: (key) => `PARAM_OUT_OF_RANGE: Numeric parameter "${key}" is out of range or non-finite`, - methodParamEmpty: 'Method parameter cannot be empty', - invalidMethodType: 'INVALID_METHOD: Method must be a non-empty string', - malformedDllResponse: 'MALFORMED_DLL_RESPONSE: Native component returned malformed JSON', - unknownDllError: 'Native component returned an unknown error', - hostIpcFailed: (pluginName, method) => `HOST_IPC_FAILED: ${pluginName}.${method} call failed`, - hostUnavailable: (pluginName, method) => `HOST_UNAVAILABLE: ${pluginName}.${method} host interface not ready`, - callFailed: 'Call failed', - movedToTrash: 'Moved to Trash', - deleteFailed: 'Delete failed', - revealedInFolder: 'Revealed in folder', - revealFailed: 'Failed to reveal item', - opened: 'Opened', - openFailed: 'Failed to open', - pluginCallNotReady: 'Plugin invocation not ready' - } -} - -function ipcStrings() { - const locale = getLocale() - return NATIVE_IPC_MESSAGES[locale] ?? NATIVE_IPC_MESSAGES['en-US'] -} -/** - * ZTools 真实宿主 IPC 与系统能力桥接层 (Real Host IPC Bridge) - * - * 严格遵循《ZTools Declarative UI 2.0 架构与 35 款原生插件全量升级规范》5.1 真实环境铁律: - * - 在真实 Electron 宿主环境中,100% 走通 Preload (__ztoolsElectron.transport.methods / window.ztools / __ztoolsLauncher) 真实调用链路 - * - 严禁在真实环境中因参数格式或嵌套响应结构差异而回退到假数据 - */ - -let ipcReqSeq = 1 -const realFileSizeCache = new Map() - -export function nextMessageId(prefix = 'ipc'): string { - ipcReqSeq = (ipcReqSeq + 1) % 1_000_000 - return `${prefix}_${Date.now()}_${ipcReqSeq}` -} - -/** - * 判断当前是否处于真实的 ZTools Electron 渲染进程宿主环境 - */ -export function isRealElectronHost(hostOverride?: unknown): boolean { - if (hostOverride) return false - if (typeof window === 'undefined') return false - const w = window as DynamicBridge - return Boolean( - w.__ztoolsElectron?.transport?.methods || - w.ztools?.transport?.call || - w.ztools?.transport?.methods - ) -} - -function normalizeMethodParams(method: string, params: Record): Record { - if (!params || typeof params !== 'object') return {} - const next = { ...params } - if (method === 'system_get_disk_usage') { - const rawDrive = String(next.drive || next.path || 'C:\\').trim() - if (rawDrive.startsWith('/')) { - next.drive = rawDrive - } else { - const match = rawDrive.match(/^([A-Za-z]):/) - next.drive = match ? `${match[1].toUpperCase()}:\\` : rawDrive.replace(/\//g, '\\') - } - delete next.path - } - return next -} - -function normalizeMethodResult(method: string, payload: DynamicBridge): DynamicBridge { - if (!payload || typeof payload !== 'object') return payload - - if (method === 'system_get_disk_usage') { - const avail = typeof payload.available === 'number' - ? payload.available - : typeof payload.free === 'number' - ? payload.free - : Math.max(0, Number(payload.total || 0) - Number(payload.used || 0)) - return { - ...payload, - available: avail, - free: avail - } - } - - if (method === 'system_get_hardware_summary') { - const cpuModel = - typeof payload.cpuModel === 'string' && payload.cpuModel.trim() - ? payload.cpuModel.trim() - : Array.isArray(payload.cpuModels) && payload.cpuModels.length > 0 - ? String(payload.cpuModels[0]).trim() - : 'x86_64 Processor' - return { - ...payload, - cpuModel - } - } - - if (method === 'system_get_battery_status') { - // 宿主约定 percent 超出 0-100(如 255)表示无电池或电量未知,不能改写成 100% - const rawPct = payload.percent - const hasBattery = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 - return { - ...payload, - percent: hasBattery ? rawPct : null, - hasBattery - } - } - - if (method === 'screen_get_all_displays') { - const list = Array.isArray(payload) - ? payload - : Array.isArray(payload.displays) - ? payload.displays - : [] - return list.map((d: DynamicBridge) => ({ - ...d, - label: d?.label || d?.name || `Display #${d?.id ?? 1}` - })) - } - - return payload -} - -function extractIpcErrorMeta(errObj: DynamicBridge): { - errorCode?: string - errorDetails?: Record -} { - if (!errObj || typeof errObj !== 'object') return {} - const errorCode = - typeof errObj.errorCode === 'string' && errObj.errorCode.trim() - ? errObj.errorCode.trim() - : typeof errObj.code === 'string' && errObj.code.trim() - ? errObj.code.trim() - : undefined - const rawDetails = - errObj.errorDetails && typeof errObj.errorDetails === 'object' && !Array.isArray(errObj.errorDetails) - ? (errObj.errorDetails as Record) - : errObj.details && typeof errObj.details === 'object' && !Array.isArray(errObj.details) - ? (errObj.details as Record) - : undefined - return { - ...(errorCode ? { errorCode } : {}), - ...(rawDetails ? { errorDetails: rawDetails } : {}) - } -} - -function unwrapTransportResponse( - method: string, - raw: DynamicBridge -): { ok: boolean; data?: DynamicBridge; error?: string; errorCode?: string; errorDetails?: Record } { - if (raw === null || raw === undefined) { - return { ok: false, error: 'EMPTY_IPC_RESPONSE', errorCode: 'EMPTY_IPC_RESPONSE' } - } - if (typeof raw !== 'object') { - return { ok: true, data: raw } - } - if (raw.success === false) { - const errObj = raw.error - const errMsg = - typeof errObj === 'object' && errObj !== null - ? String(errObj.message || errObj.code || JSON.stringify(errObj)) - : String(errObj || ipcStrings().ipcCallFailed) - return { ok: false, error: errMsg, ...extractIpcErrorMeta(raw), ...extractIpcErrorMeta(errObj) } - } - - const firstLayer = 'data' in raw && raw.data !== undefined ? raw.data : raw - if (firstLayer && typeof firstLayer === 'object' && !Array.isArray(firstLayer)) { - if (firstLayer.success === false) { - const errObj = firstLayer.error - const errMsg = - typeof errObj === 'object' && errObj !== null - ? String(errObj.message || errObj.code || JSON.stringify(errObj)) - : String(errObj || ipcStrings().ipcInnerFailed) - return { ok: false, error: errMsg, ...extractIpcErrorMeta(firstLayer), ...extractIpcErrorMeta(errObj) } - } - if ('data' in firstLayer && firstLayer.data !== undefined) { - return { ok: true, data: normalizeMethodResult(method, firstLayer.data) } - } - } - - return { ok: true, data: normalizeMethodResult(method, firstLayer) } -} - -/** - * 调用 Electron Preload Transport 方法(自动封装合法的 alphanumeric messageId 与双层解包) - */ -export async function callHostTransport( - method: string, - params: Record = {}, - hostOverride?: DynamicBridge -): Promise<{ ok: boolean; data?: T; error?: string; errorCode?: string; errorDetails?: Record }> { - const normalizedParams = normalizeMethodParams(method, params) - - // 1. 测试注入的 hostOverride 优先 - if (hostOverride) { - if (typeof hostOverride[method] === 'function') { - try { - const res = await hostOverride[method](normalizedParams) - const unwrapped = unwrapTransportResponse(method, res) - return unwrapped as { ok: boolean; data?: T; error?: string; errorCode?: string; errorDetails?: Record } - } catch (err: DynamicBridge) { - return { ok: false, error: err instanceof Error ? err.message : String(err), ...extractIpcErrorMeta(err) } - } - } - if (typeof hostOverride?.transport?.call === 'function') { - try { - const res = await hostOverride.transport.call(method, normalizedParams) - const unwrapped = unwrapTransportResponse(method, res) - return unwrapped as { ok: boolean; data?: T; error?: string; errorCode?: string; errorDetails?: Record } - } catch (err: DynamicBridge) { - return { ok: false, error: err instanceof Error ? err.message : String(err), ...extractIpcErrorMeta(err) } - } - } - } - - if (typeof window === 'undefined') { - return { ok: false, error: 'NO_WINDOW_ENV', errorCode: 'NO_WINDOW_ENV' } - } - - const w = window as DynamicBridge - const methods = w.__ztoolsElectron?.transport?.methods || w.ztools?.transport?.methods - const fn = methods?.[method] - - if (typeof fn === 'function') { - try { - const messageId = nextMessageId(method.replace(/[^A-Za-z0-9_]/g, '_').slice(0, 24)) - const raw = await fn({ messageId, params: normalizedParams }) - return unwrapTransportResponse(method, raw) as { ok: boolean; data?: T; error?: string; errorCode?: string; errorDetails?: Record } - } catch (err: DynamicBridge) { - return { ok: false, error: err instanceof Error ? err.message : String(err), ...extractIpcErrorMeta(err) } - } - } - - if (typeof w.ztools?.transport?.call === 'function') { - try { - const raw = await w.ztools.transport.call(method, normalizedParams) - return unwrapTransportResponse(method, raw) as { ok: boolean; data?: T; error?: string; errorCode?: string; errorDetails?: Record } - } catch (err: DynamicBridge) { - return { ok: false, error: err instanceof Error ? err.message : String(err), ...extractIpcErrorMeta(err) } - } - } - - return { ok: false, error: `METHOD_NOT_AVAILABLE: ${method}`, errorCode: 'METHOD_NOT_AVAILABLE' } -} - -export interface RealDiskDriveInfo { - drive: string - totalBytes: number - usedBytes: number - availableBytes: number - usagePercent: number -} - -/** - * 探测本机全部真实挂载磁盘分区 (C:\ ~ Z:\ 或 macOS/POSIX 挂载点 '/') - */ -export async function probeRealDiskDrives( - candidateLetters: string[] = ['C', 'D', 'E', 'F', 'G'], - hostOverride?: DynamicBridge -): Promise { - const drives: RealDiskDriveInfo[] = [] - const results = await Promise.all( - candidateLetters.map(async (letter) => { - const raw = String(letter || '').trim() - const isPosix = raw.startsWith('/') - const drivePath = isPosix ? raw : `${raw.replace(/:\\?$/, '').toUpperCase()}:\\` - const res = await callHostTransport<{ - total: number - used: number - available: number - free?: number - percent: number - }>('system_get_disk_usage', { drive: drivePath }, hostOverride) - if (res.ok && res.data && typeof res.data.total === 'number' && res.data.total > 0) { - const availableBytes = - typeof res.data.available === 'number' - ? res.data.available - : typeof res.data.free === 'number' - ? res.data.free - : Math.max(0, res.data.total - res.data.used) - return { - drive: isPosix ? raw : `${raw.replace(/:\\?$/, '').toUpperCase()}:`, - totalBytes: res.data.total, - usedBytes: res.data.used, - availableBytes, - usagePercent: res.data.percent - } - } - return null - }) - ) - - for (const item of results) { - if (item) drives.push(item) - } - - if (drives.length === 0 && !candidateLetters.includes('/')) { - const posixRes = await callHostTransport<{ - total: number - used: number - available: number - free?: number - percent: number - }>('system_get_disk_usage', { drive: '/' }, hostOverride) - if (posixRes.ok && posixRes.data && typeof posixRes.data.total === 'number' && posixRes.data.total > 0) { - const availableBytes = - typeof posixRes.data.available === 'number' - ? posixRes.data.available - : typeof posixRes.data.free === 'number' - ? posixRes.data.free - : Math.max(0, posixRes.data.total - posixRes.data.used) - drives.push({ - drive: '/', - totalBytes: posixRes.data.total, - usedBytes: posixRes.data.used, - availableBytes, - usagePercent: posixRes.data.percent - }) - } - } - - return drives -} - -/** - * 获取本机真实系统特殊路径(支持 home 派生标准子目录兜底,自动兼容 Windows 与 macOS/POSIX) - */ -export async function getRealSystemPath( - name: 'home' | 'appData' | 'userData' | 'desktop' | 'documents' | 'downloads' | 'music' | 'pictures' | 'videos' | 'temp' | 'cache', - hostOverride?: DynamicBridge -): Promise { - const res = await callHostTransport('system_get_path', { name }, hostOverride) - if (res.ok && res.data) { - if (typeof res.data === 'string' && res.data.trim().length > 0) { - return res.data.trim() - } - if (typeof res.data.path === 'string' && res.data.path.trim().length > 0) { - return res.data.path.trim() - } - } - - if (name !== 'home') { - const home = await getRealSystemPath('home', hostOverride) - if (home) { - const isPosix = home.startsWith('/') - const subMap: Record = isPosix - ? { - desktop: `${home}/Desktop`, - documents: `${home}/Documents`, - downloads: `${home}/Downloads`, - music: `${home}/Music`, - pictures: `${home}/Pictures`, - videos: `${home}/Videos`, - appData: `${home}/Library/Application Support`, - userData: `${home}/Library/Application Support/ZTools`, - temp: '/tmp', - cache: `${home}/Library/Caches` - } - : { - desktop: `${home}\\Desktop`, - documents: `${home}\\Documents`, - downloads: `${home}\\Downloads`, - music: `${home}\\Music`, - pictures: `${home}\\Pictures`, - videos: `${home}\\Videos`, - appData: `${home}\\AppData\\Roaming`, - userData: `${home}\\AppData\\Roaming\\ZTools`, - temp: `${home}\\AppData\\Local\\Temp`, - cache: `${home}\\AppData\\Local` - } - if (subMap[name]) return subMap[name] - } - } - - return '' -} - -export type RealDriveUsageInfo = RealDiskDriveInfo - -export interface RealIndexedFileEntry { - name: string - path: string - ext: string - isDir: boolean - isDirectory: boolean - size: number - sizeBytes: number - mtime: number - mtimeMs: number - lastModifiedMs: number -} - -export interface RealDirectorySubdirSummary { - name: string - path: string - fileCount: number - totalBytes: number - mtime: number - /** 体积不是完整统计(宿主扫描截断且独立统计超时 / 无权限),totalBytes 只是下限 */ - approximate?: boolean -} - -export interface RealDirectoryScanResult extends Iterable { - files: RealIndexedFileEntry[] - totalFiles: number - fileCount: number - totalBytes: number - subdirs: RealDirectorySubdirSummary[] - /** 宿主扫描达到条目上限后停止:files / totalFiles 只是已遍历部分的抽样 */ - truncated?: boolean - /** totalBytes 为近似值(下限) */ - approximate?: boolean - /** 宿主实际遍历的条目数 */ - visitedEntries?: number - /** 读取失败的真实原因;已有文件仍可使用,但不能当作完整结果。 */ - error?: string -} - -interface ScanResultMeta { - truncated?: boolean - approximate?: boolean - visitedEntries?: number -} - -export interface ScanDirectoryTreeOptions { - maxDepth?: number - maxFiles?: number - collectTopN?: number - filterExt?: RegExp - hostOverride?: DynamicBridge -} - -function extractFileExt(fileNameOrPath: string): string { - const base = String(fileNameOrPath || '').split(/[\\/]/).pop() || '' - const dotIdx = base.lastIndexOf('.') - return dotIdx > 0 ? base.slice(dotIdx).toLowerCase() : '' -} - -function normalizeIndexedFileEntry(f: DynamicBridge): RealIndexedFileEntry { - const p = String(f?.path || '') - const name = String(f?.name || p.split(/[\\/]/).pop() || '') - const sz = Number(f?.size ?? f?.sizeBytes ?? 0) - const isDir = Boolean(f?.is_dir || f?.isDir || f?.isDirectory) - const rawMtime = Number(f?.mtime ?? f?.mtimeMs ?? 0) - const mtimeMs = rawMtime > 1e11 ? rawMtime : rawMtime > 0 ? rawMtime * 1000 : Date.now() - const mtimeSec = rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime - if (p && sz >= 0) realFileSizeCache.set(p, sz) - return { - name, - path: p, - ext: extractFileExt(name || p), - isDir, - isDirectory: isDir, - size: sz, - sizeBytes: sz, - mtime: mtimeSec, - mtimeMs, - lastModifiedMs: mtimeMs - } -} - -function makeScanResult( - files: RealIndexedFileEntry[], - totalFiles: number, - totalBytes: number, - subdirs: RealDirectorySubdirSummary[], - meta: ScanResultMeta = {} -): RealDirectoryScanResult { - return { - files, - totalFiles, - fileCount: totalFiles, - totalBytes, - subdirs, - ...(meta.truncated ? { truncated: true } : {}), - ...(meta.approximate ? { approximate: true } : {}), - ...(typeof meta.visitedEntries === 'number' ? { visitedEntries: meta.visitedEntries } : {}), - [Symbol.iterator]() { - return files[Symbol.iterator]() - } - } -} - -/** - * 调用客户端的原生文件索引组件 (ztools-indexer) 检索文件 - */ -export async function searchRealIndexedFiles( - query: string, - limit = 40, - hostOverride?: DynamicBridge -): Promise { - if (!query || !query.trim()) return [] - const q = query.trim() - const safeLimit = Math.min(200, Math.max(1, Math.floor(limit || 40))) - - try { - const res = await callHostTransport<{ files?: DynamicBridge[] }>( - 'system_search_files', - { query: q, limit: safeLimit }, - hostOverride - ) - if (res.ok && res.data && Array.isArray(res.data.files)) { - return res.data.files.map(normalizeIndexedFileEntry) - } - - if (!hostOverride && typeof window !== 'undefined') { - const w = window as DynamicBridge - if (typeof w.__ztoolsLauncher?.searchFiles === 'function') { - const rawOuter = await w.__ztoolsLauncher.searchFiles(q, safeLimit) - const raw = rawOuter && typeof rawOuter === 'object' && 'data' in rawOuter && rawOuter.data ? rawOuter.data : rawOuter - if (raw && Array.isArray(raw.files)) { - return raw.files.map(normalizeIndexedFileEntry) - } - } - } - } catch { - // ignore - } - return [] -} - -/** - * 深度扫描指定真实物理目录树(支持符号链接穿透,如 AppData\Roaming\Tencent -> D:\Local\Roaming\Tencent) - * 返回该目录下 Top 文件列表、全树真实文件总数、全树真实总字节数与一级子目录汇总 - */ -export async function scanRealDirectoryTree( - dirPath: string, - limitOrOptions: number | ScanDirectoryTreeOptions = 160, - hostOverrideArg?: DynamicBridge -): Promise { - const result = await scanDirectoryTreeWithError(dirPath, limitOrOptions, hostOverrideArg) - return result.error ? { ...result.scan, error: result.error } : result.scan -} - -/** 一次界面扫描的错误汇总;多个目录并行扫描时保留可读目录的结果。 */ -export function createDirectoryScanner(hostOverride?: DynamicBridge) { - const failures = new Map() - return { - async scan(dir: string, options: number | ScanDirectoryTreeOptions = 160) { - const result = await scanRealDirectoryTree(dir, options, hostOverride) - const error = result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') - if (error) failures.set(dir, error) - else failures.delete(dir) - return result - }, - get error(): string | undefined { - if (!failures.size) return undefined - const s = ipcStrings() - const details = [...failures].slice(0, 3).map(([dir, error]) => `${dir}${s.dirErrorColon}${error}`).join(s.dirEntrySep) - return s.dirReadFailed(details, Math.max(0, failures.size - 3)) - } - } -} - -/** scanRealDirectoryTree 的实现:额外带回读取失败原因(目录不存在 / 为空 / 无权限 / 载荷异常) */ -async function scanDirectoryTreeWithError( - dirPath: string, - limitOrOptions: number | ScanDirectoryTreeOptions, - hostOverrideArg?: DynamicBridge -): Promise<{ scan: RealDirectoryScanResult; error?: string }> { - const empty = makeScanResult([], 0, 0, []) - if (!dirPath || !dirPath.trim()) return { scan: empty, error: 'EMPTY_DIRECTORY_PATH' } - const targetDir = dirPath.trim() - - const opts: ScanDirectoryTreeOptions = - typeof limitOrOptions === 'number' - ? { maxFiles: limitOrOptions, hostOverride: hostOverrideArg } - : { ...limitOrOptions, hostOverride: limitOrOptions?.hostOverride ?? hostOverrideArg } - - const rawLimit = opts.maxFiles ?? opts.collectTopN ?? 160 - const safeLimit = Math.min(200, Math.max(1, Math.floor(rawLimit || 160))) - const hostOverride = opts.hostOverride - const filterExt = opts.filterExt - const dirQuery = `dir:${targetDir}` - - try { - let rawPayload: DynamicBridge = null - const res = await callHostTransport( - 'system_search_files', - { query: dirQuery, limit: safeLimit }, - hostOverride - ) - if (res.ok && res.data) { - rawPayload = res.data - } - if (!rawPayload && !hostOverride && typeof window !== 'undefined') { - const w = window as DynamicBridge - if (typeof w.__ztoolsLauncher?.searchFiles === 'function') { - const rawOuter = await w.__ztoolsLauncher.searchFiles(dirQuery, safeLimit) - rawPayload = - rawOuter && typeof rawOuter === 'object' && 'data' in rawOuter && rawOuter.data - ? rawOuter.data - : rawOuter - } - } - - if ( - rawPayload && - Array.isArray(rawPayload.files) - ) { - let files: RealIndexedFileEntry[] = rawPayload.files.map(normalizeIndexedFileEntry) - if (filterExt instanceof RegExp) { - files = files.filter(f => !f.isDir && (filterExt.test(f.name) || filterExt.test(f.ext))) - // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索目标扩展名 - if (files.length === 0 && !hostOverride) { - const extTokens = (filterExt.source.match(/[a-z0-9]{2,5}/gi) || []) - .filter(t => !['thumbcache', 'iconcache'].includes(t.toLowerCase())) - .slice(0, 4) - // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 - const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() - const extraLists = await Promise.all( - extTokens.map(ext => searchRealIndexedFiles(`.${ext.toLowerCase()}`, 30, hostOverride)) - ) - const seen = new Set() - for (const list of extraLists) { - for (const item of list) { - if (!item.isDir && item.size > 0 && !seen.has(item.path)) { - if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { - seen.add(item.path) - files.push(item) - } - } - } - } - } - } - if (typeof opts.collectTopN === 'number' && opts.collectTopN > 0 && files.length > opts.collectTopN) { - files = files.slice(0, opts.collectTopN) - } - const subdirs: RealDirectorySubdirSummary[] = Array.isArray(rawPayload.subdirs) - ? rawPayload.subdirs.map((s: DynamicBridge) => ({ - name: String(s.name || ''), - path: String(s.path || ''), - fileCount: Number(s.file_count ?? s.fileCount ?? 0), - totalBytes: Number(s.total_bytes ?? s.totalBytes ?? 0), - mtime: Number(s.mtime || 0), - ...(s.approximate === true ? { approximate: true } : {}) - })) - : [] - const computedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) - const totalFilesCount = - filterExt instanceof RegExp ? files.length : Number(rawPayload.total_matches ?? files.length) - const totalBytesCount = - filterExt instanceof RegExp ? computedBytes : Number(rawPayload.total_bytes ?? computedBytes) - const visited = Number(rawPayload.visited_entries) - return { - scan: makeScanResult(files, totalFilesCount, totalBytesCount, subdirs, { - truncated: rawPayload.truncated === true, - approximate: rawPayload.approximate === true, - ...(Number.isFinite(visited) && visited >= 0 ? { visitedEntries: visited } : {}) - }), - ...(typeof rawPayload.scan_error === 'string' && rawPayload.scan_error ? { error: rawPayload.scan_error } : {}) - } - } - - // 深度扫描失败或回执无效时,仅以一级目录读取补回可见结果;不冒充完整目录树。 - const listing = await listDirectoryViaFilesystem(targetDir, hostOverride, { withSizes: true, limit: safeLimit }) - if (listing.ok && listing.entries.length > 0) { - const files: RealIndexedFileEntry[] = [] - let totalBytes = 0 - for (const entry of listing.entries) { - if (filterExt instanceof RegExp && !filterExt.test(entry.name) && !filterExt.test(entry.ext)) { - continue - } - files.push(entry) - totalBytes += entry.isDir ? 0 : entry.size - } - const incomplete = listing.entries.some(entry => entry.isDir) || listing.entries.length >= safeLimit - return { - scan: makeScanResult(files, files.filter(file => !file.isDir).length, totalBytes, [], { approximate: incomplete }), - ...(incomplete ? { error: res.error || ipcStrings().deepScanUnavailable } : {}) - } - } - return listing.ok ? { scan: empty } : { scan: empty, error: listing.error || 'DIRECTORY_READ_FAILED' } - } catch (error) { - return { scan: empty, error: error instanceof Error ? error.message : String(error) } - } -} - - -/** 目录读取不到任何条目(不存在 / 为空 / 无权限)时的错误码 */ -export const DIRECTORY_EMPTY_OR_UNREADABLE = 'DIRECTORY_EMPTY_OR_UNREADABLE' - -export interface RealDirectoryListingResult { - /** 目录内条目的完整路径;读取失败时为空数组 */ - entries: string[] - /** 读取失败或目录为空时的错误码 / 宿主错误信息 */ - error?: string -} - -export interface RealDirectChildrenResult { - /** 目录的直接子项(子目录在前),按路径去重 */ - entries: RealIndexedFileEntry[] - /** 宿主扫描达到条目上限,可能只返回了部分直接子项 */ - partial: boolean - error?: string -} - -function stripTrailingSeparators(p: string): string { - const trimmed = p.replace(/[\\/]+$/, '') - return trimmed || p.slice(0, 1) -} - -function isWindowsStylePath(p: string): boolean { - return /^[A-Za-z]:/.test(p) || p.startsWith('\\\\') || (p.includes('\\') && !p.includes('/')) -} - -function comparablePath(p: string): string { - const stripped = stripTrailingSeparators(String(p || '').trim()) - return isWindowsStylePath(stripped) ? stripped.replace(/\//g, '\\').toLowerCase() : stripped -} - -function parentDirOf(p: string): string { - const stripped = stripTrailingSeparators(String(p || '')) - const idx = Math.max(stripped.lastIndexOf('/'), stripped.lastIndexOf('\\')) - if (idx < 0) return '' - if (idx === 0) return stripped.slice(0, 1) - const parent = stripped.slice(0, idx) - return /^[A-Za-z]:$/.test(parent) ? `${parent}\\` : parent -} - -function isDirectChildPath(dirPath: string, candidate: string): boolean { - if (!candidate) return false - return comparablePath(parentDirOf(candidate)) === comparablePath(dirPath) -} - -function joinChildPath(dirPath: string, name: string): string { - const sep = isWindowsStylePath(dirPath) ? '\\' : '/' - const base = dirPath.replace(/[\\/]+$/, '') - return `${base}${sep}${name}` -} - -/** - * 通过 filesystem_get_directory_contents 读取一级目录(需宿主授权)。 - * 宿主真实返回 { success, files: [{ name, size, isDirectory, lastModified }] }(name 为文件名); - * 兼容旧测试替身返回的完整路径字符串数组。 - */ -async function listDirectoryViaFilesystem( - dirPath: string, - hostOverride: DynamicBridge, - options: { withSizes?: boolean; limit?: number } = {} -): Promise<{ ok: boolean; entries: RealIndexedFileEntry[]; error?: string }> { - const res = await callHostTransport('filesystem_get_directory_contents', { path: dirPath }, hostOverride) - if (!res.ok) return { ok: false, entries: [], error: res.error || 'DIRECTORY_READ_FAILED' } - const data = res.data - const rawList: unknown[] | null = Array.isArray(data) ? data : Array.isArray(data?.files) ? data.files : null - if (!rawList) return { ok: false, entries: [], error: 'INVALID_DIRECTORY_PAYLOAD' } - - const limit = Math.max(1, Math.floor(options.limit ?? 1000)) - const nowSec = Math.floor(Date.now() / 1000) - const entries: RealIndexedFileEntry[] = [] - const seen = new Set() - for (const item of rawList) { - if (entries.length >= limit) break - let entry: RealIndexedFileEntry | null = null - if (typeof item === 'string') { - const itemPath = item.trim() - if (!itemPath) continue - const name = itemPath.split(/[\\/]/).pop() || itemPath - const sz = options.withSizes ? await getRealFileSize(itemPath, hostOverride) : 0 - entry = normalizeIndexedFileEntry({ - name, - path: itemPath, - isDir: sz === 0 && !name.includes('.'), - size: sz, - mtime: nowSec - }) - } else if (item && typeof item === 'object' && typeof (item as DynamicBridge).name === 'string') { - const raw = item as DynamicBridge - const rawName = raw.name.trim() - if (!rawName || rawName === '.' || rawName === '..') continue - // 只接受文件名,或确实位于该目录下的完整路径,拒绝越界路径 - const fullPath = /[\\/]/.test(rawName) ? rawName : joinChildPath(dirPath, rawName) - if (!isDirectChildPath(dirPath, fullPath)) continue - const isDir = Boolean(raw.isDirectory ?? raw.isDir ?? raw.is_dir) - const parsedMtime = Date.parse(String(raw.lastModified || '')) - entry = normalizeIndexedFileEntry({ - name: fullPath.split(/[\\/]/).pop() || rawName, - path: fullPath, - isDir, - size: isDir ? 0 : Math.max(0, Number(raw.size) || 0), - mtime: Number.isFinite(parsedMtime) ? parsedMtime : nowSec - }) - } - if (!entry || seen.has(entry.path)) continue - seen.add(entry.path) - entries.push(entry) - } - return { ok: true, entries } -} - -/** - * 读取真实目录下的条目路径(真实宿主中优先走 dir: 扫描:一级子目录 + 全树 Top-N 大文件),并返回失败原因。 - * 目录不存在、为空或无权限时返回空列表与错误码,绝不用全盘关键词搜索结果冒充目录内容。 - */ -export async function listRealDirectoryContentsResult( - dirPath: string, - hostOverride?: DynamicBridge -): Promise { - if (!dirPath || !dirPath.trim()) return { entries: [], error: 'EMPTY_DIRECTORY_PATH' } - const targetDir = dirPath.trim() - - if (!hostOverride && isRealElectronHost()) { - const tree = await scanRealDirectoryTree(targetDir, 60) - const paths: string[] = [] - for (const s of tree.subdirs) { - if (s.path) paths.push(s.path) - } - for (const f of tree.files) { - if (f.path) paths.push(f.path) - } - if (paths.length > 0) return { entries: Array.from(new Set(paths)) } - } - - const listing = await listDirectoryViaFilesystem(targetDir, hostOverride) - if (!listing.ok) return { entries: [], error: listing.error } - if (listing.entries.length === 0) return { entries: [], error: DIRECTORY_EMPTY_OR_UNREADABLE } - return { entries: listing.entries.map(e => e.path) } -} - -/** - * 读取真实目录下的条目路径(保持旧签名:失败时返回空数组,需要失败原因请用 listRealDirectoryContentsResult) - */ -export async function listRealDirectoryContents( - dirPath: string, - hostOverride?: DynamicBridge -): Promise { - return (await listRealDirectoryContentsResult(dirPath, hostOverride)).entries -} - -/** - * 只列出目录的直接子项(子目录 + 直接位于该目录下的文件),用于文件夹预览、按目录改名等场景。 - * dir: 扫描结果中只保留 subdirs 与父目录等于 dirPath 的文件;扫描达到上限时 partial=true,由插件如实提示「仅显示部分」。 - */ -export async function listDirectChildren( - dirPath: string, - hostOverride?: DynamicBridge -): Promise { - if (!dirPath || !dirPath.trim()) return { entries: [], partial: false, error: 'EMPTY_DIRECTORY_PATH' } - const targetDir = dirPath.trim() - const scanLimit = 200 - const entries: RealIndexedFileEntry[] = [] - const seen = new Set() - const push = (entry: RealIndexedFileEntry) => { - const key = comparablePath(entry.path) - if (!entry.path || seen.has(key)) return - seen.add(key) - entries.push(entry) - } - - const { scan: tree, error } = await scanDirectoryTreeWithError(targetDir, { maxFiles: scanLimit, hostOverride }) - for (const s of tree.subdirs) { - if (!s.path || !isDirectChildPath(targetDir, s.path)) continue - push( - normalizeIndexedFileEntry({ - name: s.name || s.path.split(/[\\/]/).pop(), - path: s.path, - isDir: true, - size: s.totalBytes, - mtime: s.mtime - }) - ) - } - let directFileCount = 0 - for (const f of tree.files) { - if (!isDirectChildPath(targetDir, f.path)) continue - directFileCount++ - push(f) - } - // 宿主 total_matches 是全树文件数、subdirs[].file_count 是各子目录全树文件数,差值即直接子文件数; - // 拿到的直接子文件少于它就说明被 Top-N 截断了。计数不可用时按是否达到扫描上限判断 - const expectedDirectFiles = tree.totalFiles - tree.subdirs.reduce((sum, d) => sum + (Number(d.fileCount) || 0), 0) - const partial = - Number.isFinite(expectedDirectFiles) && expectedDirectFiles >= 0 - ? directFileCount < expectedDirectFiles - : tree.files.length >= scanLimit - if (entries.length > 0) { - return { entries, partial } - } - - if (tree.files.length > 0) { - // dir: 扫描只返回了深层文件(直接子文件被 Top-N 截掉),如实标注部分结果 - return { entries: [], partial: true, error: DIRECTORY_EMPTY_OR_UNREADABLE } - } - return { entries: [], partial: false, error: error || DIRECTORY_EMPTY_OR_UNREADABLE } -} - -/** - * 获取真实文件字节大小(优先用扫描结果里的大小,再走 filesystem_get_file_size);读不到时返回 0 - */ -export async function getRealFileSize( - filePath: string, - hostOverride?: DynamicBridge -): Promise { - if (!filePath) return 0 - if (!hostOverride && realFileSizeCache.has(filePath)) { - const cached = realFileSizeCache.get(filePath)! - if (cached > 0) return cached - } - const res = await callHostTransport('filesystem_get_file_size', { path: filePath }, hostOverride) - // 客户端返回 { success, size }(目录时 size 为 -1),旧的测试替身直接返回数字 - const size = typeof res.data === 'number' ? res.data : res.data?.size - if (res.ok && typeof size === 'number' && Number.isFinite(size) && size >= 0) { - realFileSizeCache.set(filePath, size) - return size - } - return 0 -} - -/** - * 在访达 / 资源管理器中定位并高亮文件或目录。 - * 定位失败直接返回 false,不能改用“打开”:对可执行文件那等于运行它。 - */ -export async function showRealItemInFolder( - fullPath: string, - hostOverride?: DynamicBridge -): Promise { - if (!fullPath) return false - const res = await callHostTransport('shell_show_item_in_folder', { fullPath }, hostOverride) - return res.ok -} - -/** - * 使用系统默认程序打开文件或目录 - */ -export async function openRealPath( - fullPath: string, - hostOverride?: DynamicBridge -): Promise { - if (!fullPath) return false - const res = await callHostTransport('shell_open_path', { fullPath }, hostOverride) - return res.ok -} - -/** - * 将真实文件或目录移入系统回收站(安全可恢复删除) - */ -export async function trashRealItem( - fullPath: string, - hostOverride?: DynamicBridge -): Promise<{ ok: boolean; error?: string; errorCode?: string; errorDetails?: Record }> { - if (!fullPath) return { ok: false, error: ipcStrings().pathEmpty } - const res = await callHostTransport('shell_trash_item', { fullPath }, hostOverride) - return { - ok: res.ok, - error: res.error, - ...(!res.ok && res.errorCode ? { errorCode: res.errorCode } : {}), - ...(!res.ok && res.errorDetails ? { errorDetails: res.errorDetails } : {}) - } -} - -export interface NativeInvocationResult { - ok: boolean - code: number - message: string - data?: T - error?: string - errorCode?: string - errorDetails?: Record -} - -export interface DllCapabilityResponse { - ok: boolean - code: number - data: T | null - message?: string - error?: string - errorCode?: string - errorDetails?: Record - pluginName: string - method: string - fromFallback?: boolean -} - -/** 声明式能力菜单项及其调用回执,供相同宿主协议的插件共用。 */ -export interface CapabilityActionItem { - id: string - title: string - subtitle: string - tag: string - method: string - params: Record -} - -export type PluginInvocationResult = Pick< - DllCapabilityResponse, 'ok' | 'pluginName' | 'method' | 'error' | 'errorCode' | 'errorDetails' | 'fromFallback' -> & { data?: unknown } - -/** 多个原生能力插件共用的参数边界校验;保护目标由各插件按自身业务提供。 */ -export function validateNativeCapabilityPayload( - method: string, - params: unknown, - forbiddenPattern: RegExp, - forbiddenReason: string -): { valid: boolean; error?: string } { - const s = ipcStrings() - if (typeof method !== 'string' || method.trim().length === 0) { - return { valid: false, error: s.invalidMethodEmpty } - } - if (method.length > 128 || !/^[A-Za-z0-9_]+$/.test(method.trim())) { - return { valid: false, error: s.invalidMethodFormat } - } - if (params === null || params === undefined || typeof params !== 'object' || Array.isArray(params)) { - return { valid: false, error: s.invalidParamsObject } - } - - const record = params as Record - for (const [key, val] of Object.entries(record)) { - if (typeof val === 'string') { - if (val.length > 4096) { - return { valid: false, error: s.paramTooLong(key) } - } - if (forbiddenPattern.test(val)) { - return { valid: false, error: `SECURITY_INTERCEPTED: ${forbiddenReason}` } - } - } else if (typeof val === 'number') { - if (!Number.isFinite(val) || val < -1000 || val > 100_000_000) { - return { valid: false, error: s.paramOutOfRange(key) } - } - } - } - - return { valid: true } -} - -export async function invokeDllPluginCapability( - pluginName: string, - method: string, - params: Record = {}, - hostBridge?: DynamicBridge, - offlineFallback?: () => T | Promise -): Promise> { - const s = ipcStrings() - if (!method || typeof method !== 'string' || method.trim().length === 0) { - return { - ok: false, - code: -1, - data: null, - message: s.methodParamEmpty, - error: s.invalidMethodType, - pluginName, - method: String(method || '') - } - } - - const trimmedMethod = method.trim() - - const unwrapDllRawPayload = (raw: unknown, unwrapDataProperty: boolean): DllCapabilityResponse => { - let parsed: DynamicBridge = raw - if (typeof raw === 'string') { - try { - parsed = JSON.parse(raw) - } catch { - throw new Error(s.malformedDllResponse) - } - } - if (parsed && typeof parsed === 'object') { - if ('error' in parsed && parsed.error !== undefined && parsed.error !== null && parsed.error !== '') { - const errMsg = `DLL_ERROR: ${String(parsed.error)}` - return { - ok: false, - code: typeof parsed.code === 'number' ? parsed.code : -1, - data: null, - message: errMsg, - error: errMsg, - ...extractIpcErrorMeta(parsed), - ...extractIpcErrorMeta(parsed.error), - pluginName, - method: trimmedMethod, - fromFallback: false - } - } - if ('ok' in parsed && parsed.ok === false) { - const errMsg = `DLL_ERROR: ${String(parsed.error || parsed.message || s.unknownDllError)}` - return { - ok: false, - code: typeof parsed.code === 'number' ? parsed.code : -1, - data: null, - message: errMsg, - error: errMsg, - ...extractIpcErrorMeta(parsed), - ...extractIpcErrorMeta(parsed.error), - pluginName, - method: trimmedMethod, - fromFallback: false - } - } - const dataPayload = unwrapDataProperty && 'data' in parsed && parsed.data !== undefined ? parsed.data : parsed - return { - ok: true, - code: typeof parsed.code === 'number' ? parsed.code : 0, - data: dataPayload as T, - message: typeof parsed.message === 'string' ? parsed.message : undefined, - pluginName, - method: trimmedMethod, - fromFallback: false - } - } - return { - ok: true, - code: 0, - data: (parsed ?? null) as T, - pluginName, - method: trimmedMethod, - fromFallback: false - } - } - - const wrapCaughtDllError = (err: unknown): DllCapabilityResponse => { - const message = err instanceof Error ? err.message : String(err) - if (message.startsWith('MALFORMED_DLL_RESPONSE:')) { - throw err - } - const errMsg = `NATIVE_CALL_FAILED: ${message}` - return { - ok: false, - code: -1, - data: null, - message: errMsg, - error: errMsg, - ...extractIpcErrorMeta(err), - pluginName, - method: trimmedMethod, - fromFallback: false - } - } - - if (hostBridge && typeof hostBridge.invokeNative === 'function') { - try { - const raw = await hostBridge.invokeNative(pluginName, trimmedMethod, params) - return unwrapDllRawPayload(raw, true) - } catch (err: unknown) { - return wrapCaughtDllError(err) - } - } - - const runtimeHost = (hostBridge ?? (globalThis as Record).ztools) as - | { dllplugin?: { call?: (plugin: string, fn: string, payload: unknown) => Promise | unknown } } - | undefined - - const callFn = runtimeHost?.dllplugin?.call - if (typeof callFn === 'function') { - try { - const raw = await callFn.call(runtimeHost?.dllplugin, pluginName, trimmedMethod, params) - return unwrapDllRawPayload(raw, false) - } catch (err: unknown) { - return wrapCaughtDllError(err) - } - } - - const ipcRes = await callHostTransport( - 'dllplugin_call', - { - plugin: pluginName, - func: trimmedMethod, - params - }, - hostBridge - ) - - if (ipcRes.ok && ipcRes.data !== undefined && ipcRes.data !== null) { - return unwrapDllRawPayload(ipcRes.data, false) - } - - const isExplicitTransportFailure = - typeof ipcRes.error === 'string' && - ipcRes.error.length > 0 && - ipcRes.error !== 'NO_WINDOW_ENV' && - !ipcRes.error.startsWith('METHOD_NOT_AVAILABLE:') - - if ( - isRealElectronHost(hostBridge) || - isRealElectronHost() || - Boolean((hostBridge as DynamicBridge)?.__isRealHost) || - isExplicitTransportFailure - ) { - const errMsg = - ipcRes.error || s.hostIpcFailed(pluginName, trimmedMethod) - return { - ok: false, - code: -1, - data: null, - message: errMsg, - error: errMsg, - ...(ipcRes.errorCode ? { errorCode: ipcRes.errorCode } : {}), - ...(ipcRes.errorDetails ? { errorDetails: ipcRes.errorDetails } : {}), - pluginName, - method: trimmedMethod, - fromFallback: false - } - } - - if (typeof offlineFallback === 'function') { - const fallbackData = await offlineFallback() - return { - ok: true, - code: 0, - data: fallbackData, - pluginName, - method: trimmedMethod, - fromFallback: true - } - } - - const unavailableMsg = s.hostUnavailable(pluginName, trimmedMethod) - return { - ok: false, - code: -1, - data: null, - message: unavailableMsg, - error: unavailableMsg, - ...(ipcRes.errorCode ? { errorCode: ipcRes.errorCode } : {}), - ...(ipcRes.errorDetails ? { errorDetails: ipcRes.errorDetails } : {}), - pluginName, - method: trimmedMethod, - fromFallback: true - } -} - -export function formatBytes(bytes: number, decimals = 1): string { - const num = Number(bytes) - if (!Number.isFinite(num) || num <= 0) return '0 B' - if (num < 1024) return `${Math.round(num)} B` - const units = ['B', 'KB', 'MB', 'GB', 'TB'] - let val = num - let idx = 0 - while (val >= 1024 && idx < units.length - 1) { - val /= 1024 - idx += 1 - } - const safeDecimals = Math.max(0, Math.floor(decimals)) - return `${val >= 100 ? val.toFixed(0) : val.toFixed(safeDecimals)} ${units[idx]}` -} - -export function joinWinPath(...segments: string[]): string { - return segments - .filter(s => typeof s === 'string' && s.trim().length > 0) - .map((s, i) => (i === 0 ? s.replace(/[\\/]+$/, '') : s.replace(/^[\\/]+|[\\/]+$/g, ''))) - .join('\\') -} - -export interface RealEnvPaths { - home: string - userProfile: string - appData: string - localAppData: string - temp: string - downloads: string - documents: string - desktop: string - pictures: string - videos: string - music: string -} - -export async function getRealEnvPaths(hostOverride?: DynamicBridge): Promise { - const [homeRaw, appData, downloads, documents, desktop, pictures, videos, music] = await Promise.all([ - getRealSystemPath('home', hostOverride), - getRealSystemPath('appData', hostOverride), - getRealSystemPath('downloads', hostOverride), - getRealSystemPath('documents', hostOverride), - getRealSystemPath('desktop', hostOverride), - getRealSystemPath('pictures', hostOverride), - getRealSystemPath('videos', hostOverride), - getRealSystemPath('music', hostOverride) - ]) - const home = homeRaw || 'C:\\Users\\Default' - const isPosix = home.startsWith('/') - const tempRes = hostOverride ? await getRealSystemPath('temp', hostOverride) : '' - if (isPosix) { - return { - home, - userProfile: home, - appData: appData || `${home}/Library/Application Support`, - localAppData: `${home}/Library/Application Support`, - temp: tempRes || '/tmp', - downloads: downloads || `${home}/Downloads`, - documents: documents || `${home}/Documents`, - desktop: desktop || `${home}/Desktop`, - pictures: pictures || `${home}/Pictures`, - videos: videos || `${home}/Videos`, - music: music || `${home}/Music` - } - } - return { - home, - userProfile: home, - appData: appData || `${home}\\AppData\\Roaming`, - localAppData: `${home}\\AppData\\Local`, - temp: tempRes || `${home}\\AppData\\Local\\Temp`, - downloads: downloads || `${home}\\Downloads`, - documents: documents || `${home}\\Documents`, - desktop: desktop || `${home}\\Desktop`, - pictures: pictures || `${home}\\Pictures`, - videos: videos || `${home}\\Videos`, - music: music || `${home}\\Music` - } -} - -export const resolveRealSpecialPaths = getRealEnvPaths - -export async function readRealDirectory( - dirPath: string, - hostOverride?: DynamicBridge -): Promise { - if (!dirPath) return [] - const tree = await scanRealDirectoryTree(dirPath, { maxFiles: 120, hostOverride }) - const entries: RealIndexedFileEntry[] = [] - for (const s of tree.subdirs) { - entries.push( - normalizeIndexedFileEntry({ - name: s.name, - path: s.path, - isDir: true, - isDirectory: true, - size: s.totalBytes, - mtime: s.mtime - }) - ) - } - for (const f of tree.files) { - entries.push(f) - } - // scanRealDirectoryTree 已在 dir: 扫描无结果时退回一级目录读取;仍为空即目录不存在 / 为空 / 无权限,如实返回空列表 - return entries -} - -export async function moveRealFilesToTrash( - paths: string[], - hostOverride?: DynamicBridge -): Promise<{ - ok: boolean - trashedCount: number - deletedCount: number - failedPaths: string[] - error?: string -}> { - let deletedCount = 0 - const failedPaths: string[] = [] - let lastError: string | undefined - for (const p of paths) { - if (!p) continue - const res = await trashRealItem(p, hostOverride) - if (res.ok) { - deletedCount += 1 - } else { - failedPaths.push(p) - if (res.error) lastError = res.error - } - } - return { - ok: deletedCount > 0 || paths.length === 0, - trashedCount: deletedCount, - deletedCount, - failedPaths, - error: lastError - } -} - -const CAPABILITY_TO_PLUGIN_MAP: Record = { - 'mover.relocateWithJunction': { plugin: 'MoverPlugin', func: 'relocateWithJunction' }, - 'mover.scanCandidates': { plugin: 'MoverPlugin', func: 'scanCandidates' }, - 'recovery.restoreFile': { plugin: 'DataRecoveryPlugin', func: 'restoreFile' }, - 'recovery.scanDeletedFiles': { plugin: 'DataRecoveryPlugin', func: 'scanDeletedFiles' }, - 'shredder.secureWipeFile': { plugin: 'ShredderPlugin', func: 'secureWipeFile' }, - 'shredder.scanCandidates': { plugin: 'ShredderPlugin', func: 'scanCandidates' }, - 'backup.createSnapshotArchive': { plugin: 'SystemBackupPlugin', func: 'createSnapshotArchive' }, - 'backup.restoreSnapshotArchive': { plugin: 'SystemBackupPlugin', func: 'restoreSnapshotArchive' }, - 'backup.scanSnapshots': { plugin: 'SystemBackupPlugin', func: 'scanSnapshots' }, - 'sqlite.execute': { plugin: 'SqlitePlugin', func: 'execute' }, - 'sqlite.query': { plugin: 'SqlitePlugin', func: 'executeQuery' }, - 'sqlite.inspectWorkspace': { plugin: 'SqlitePlugin', func: 'inspectWorkspace' } -} - -export async function invokeHostCapability( - capability: string, - params: Record = {}, - hostOverride?: DynamicBridge -): Promise> { - const normalizedMethod = capability.replace(/\./g, '_') - - // 若测试显式注入了对应 normalizedMethod 的 mock 函数,优先调用测试桩 - if (hostOverride && typeof hostOverride[normalizedMethod] === 'function') { - const mockRes = await callHostTransport(normalizedMethod, params, hostOverride) - return { - ok: mockRes.ok, - code: mockRes.ok ? 0 : -1, - message: mockRes.ok ? 'OK' : mockRes.error || ipcStrings().callFailed, - data: mockRes.data, - error: mockRes.error, - ...(!mockRes.ok && mockRes.errorCode ? { errorCode: mockRes.errorCode } : {}), - ...(!mockRes.ok && mockRes.errorDetails ? { errorDetails: mockRes.errorDetails } : {}) - } - } - - if (capability === 'system.info') { - const drives = await probeRealDiskDrives(['C', 'D', 'E', 'F'], hostOverride) - return { - ok: true, - code: 0, - message: 'OK', - data: { - storage: drives.map(d => ({ - mount: d.drive, - fs: d.drive, - size: d.totalBytes, - total: d.totalBytes, - used: d.usedBytes, - available: d.availableBytes, - free: d.availableBytes, - percent: d.usagePercent - })) - } as unknown as T - } - } - if (capability === 'filesystem.deleteItem') { - const targetPath = String(params.path || params.fullPath || '') - const tr = await trashRealItem(targetPath, hostOverride) - const s = ipcStrings() - return { - ok: tr.ok, - code: tr.ok ? 0 : -1, - message: tr.ok ? s.movedToTrash : tr.error || s.deleteFailed, - error: tr.error, - ...(!tr.ok && tr.errorCode ? { errorCode: tr.errorCode } : {}), - ...(!tr.ok && tr.errorDetails ? { errorDetails: tr.errorDetails } : {}) - } - } - if (capability === 'system.showItemInFolder') { - const targetPath = String(params.path || params.fullPath || '') - const s = ipcStrings() - if (!targetPath) { - return { ok: false, code: -1, message: s.revealFailed } - } - const res = await callHostTransport('shell_show_item_in_folder', { fullPath: targetPath }, hostOverride) - return { - ok: res.ok, - code: res.ok ? 0 : -1, - message: res.ok ? s.revealedInFolder : res.error || s.revealFailed, - ...(!res.ok && res.error ? { error: res.error } : {}), - ...(!res.ok && res.errorCode ? { errorCode: res.errorCode } : {}), - ...(!res.ok && res.errorDetails ? { errorDetails: res.errorDetails } : {}) - } - } - if (capability === 'filesystem.openItem' || capability === 'system.openUrl') { - const target = String(params.path || params.url || params.fullPath || '') - const method = capability === 'system.openUrl' ? 'shell_open_external' : 'shell_open_path' - const res = await callHostTransport( - method, - capability === 'system.openUrl' ? { url: target } : { fullPath: target }, - hostOverride - ) - const s = ipcStrings() - return { - ok: res.ok, - code: res.ok ? 0 : -1, - message: res.ok ? s.opened : res.error || s.openFailed, - data: res.data, - error: res.error, - ...(!res.ok && res.errorCode ? { errorCode: res.errorCode } : {}), - ...(!res.ok && res.errorDetails ? { errorDetails: res.errorDetails } : {}) - } - } - - const pluginMapping = CAPABILITY_TO_PLUGIN_MAP[capability] - if (pluginMapping) { - const dllRes = await invokePluginService( - pluginMapping.plugin, - pluginMapping.func, - params, - hostOverride - ) - if (dllRes.ok) return dllRes - if (hostOverride) { - const fallbackMock = await callHostTransport(normalizedMethod, params, hostOverride) - if (fallbackMock.ok) { - return { - ok: true, - code: 0, - message: 'OK', - data: fallbackMock.data - } - } - } - return dllRes - } - - const res = await callHostTransport(normalizedMethod, params, hostOverride) - return { - ok: res.ok, - code: res.ok ? 0 : -1, - message: res.ok ? 'OK' : res.error || ipcStrings().callFailed, - data: res.data, - error: res.error, - ...(!res.ok && res.errorCode ? { errorCode: res.errorCode } : {}), - ...(!res.ok && res.errorDetails ? { errorDetails: res.errorDetails } : {}) - } -} - -export async function invokePluginService( - pluginName: string, - action: string, - params: Record = {}, - hostOverride?: DynamicBridge -): Promise> { - const s = ipcStrings() - // 1. 若测试注入了专门拦截 plugin_invoke 的 mock,支持调用 - if (hostOverride && typeof hostOverride.plugin_invoke === 'function') { - const mockRes = await callHostTransport( - 'plugin_invoke', - { plugin: pluginName, action, params }, - hostOverride - ) - return { - ok: mockRes.ok, - code: mockRes.ok ? 0 : -1, - message: mockRes.ok ? 'OK' : mockRes.error || s.pluginCallNotReady, - data: mockRes.data, - error: mockRes.error, - ...(!mockRes.ok && mockRes.errorCode ? { errorCode: mockRes.errorCode } : {}), - ...(!mockRes.ok && mockRes.errorDetails ? { errorDetails: mockRes.errorDetails } : {}) - } - } - - // 2. 优先走真实 Electron IPC 的 dllplugin_call 通道 - const dllRes = await callHostTransport( - 'dllplugin_call', - { plugin: pluginName, func: action, params }, - hostOverride - ) - if (dllRes.ok) { - const inner = dllRes.data - if (inner && typeof inner === 'object' && typeof inner.error === 'string' && inner.error.length > 0 && inner.ok !== true) { - return { - ok: false, - code: -1, - message: inner.error, - error: inner.error, - ...extractIpcErrorMeta(inner) - } - } - return { - ok: true, - code: 0, - message: 'OK', - data: inner as T - } - } - - // 3. 兼容单元测试中通过 transport.call('plugin_invoke') 注入的测试桩 - if (hostOverride) { - const legacyRes = await callHostTransport( - 'plugin_invoke', - { plugin: pluginName, action, params }, - hostOverride - ) - if (legacyRes.ok) { - return { - ok: true, - code: 0, - message: 'OK', - data: legacyRes.data - } - } - } - - // 4. 兼容旧版 globalThis.ztools.dllplugin.call - const g = globalThis as DynamicBridge - if (!hostOverride && typeof g?.ztools?.dllplugin?.call === 'function') { - try { - const raw = await g.ztools.dllplugin.call(pluginName, action, params) - if (raw && typeof raw === 'object' && raw.ok === false) { - return { - ok: false, - code: -1, - message: String(raw.error || s.callFailed), - error: String(raw.error || s.callFailed), - ...extractIpcErrorMeta(raw), - ...extractIpcErrorMeta(raw.error) - } - } - const data = raw && typeof raw === 'object' && 'data' in raw ? raw.data : raw - return { ok: true, code: 0, message: 'OK', data: data as T } - } catch (err: DynamicBridge) { - return { - ok: false, - code: -1, - message: err instanceof Error ? err.message : String(err), - error: err instanceof Error ? err.message : String(err), - ...extractIpcErrorMeta(err) - } - } - } - - return { - ok: false, - code: -1, - message: dllRes.error || s.pluginCallNotReady, - error: dllRes.error || s.pluginCallNotReady, - ...(dllRes.errorCode ? { errorCode: dllRes.errorCode } : {}), - ...(dllRes.errorDetails ? { errorDetails: dllRes.errorDetails } : {}) - } -} - -const SHA256_K = new Uint32Array([ - 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, - 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, - 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, - 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, - 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, - 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, - 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, - 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 -]) - -function rotr32(x: number, n: number): number { - return (x >>> n) | (x << (32 - n)) -} - -/** - * 标准 FIPS 180-4 SHA-256 真实字节摘要算法(返回 64 位小写 Hex) - */ -export function computeRealSha256Hex(input: string | Uint8Array): string { - const bytes = - typeof input === 'string' ? new TextEncoder().encode(input) : new Uint8Array(input || []) - const bitLen = bytes.length * 8 - const padLen = ((bytes.length + 9 + 63) & ~63) - const buf = new Uint8Array(padLen) - buf.set(bytes, 0) - buf[bytes.length] = 0x80 - const view = new DataView(buf.buffer) - view.setUint32(padLen - 8, Math.floor(bitLen / 0x100000000), false) - view.setUint32(padLen - 4, bitLen >>> 0, false) - - let h0 = 0x6a09e667 - let h1 = 0xbb67ae85 - let h2 = 0x3c6ef372 - let h3 = 0xa54ff53a - let h4 = 0x510e527f - let h5 = 0x9b05688c - let h6 = 0x1f83d9ab - let h7 = 0x5be0cd19 - - const w = new Uint32Array(64) - for (let offset = 0; offset < padLen; offset += 64) { - for (let i = 0; i < 16; i++) { - w[i] = view.getUint32(offset + i * 4, false) - } - for (let i = 16; i < 64; i++) { - const s0 = rotr32(w[i - 15], 7) ^ rotr32(w[i - 15], 18) ^ (w[i - 15] >>> 3) - const s1 = rotr32(w[i - 2], 17) ^ rotr32(w[i - 2], 19) ^ (w[i - 2] >>> 10) - w[i] = (w[i - 16] + s0 + w[i - 7] + s1) >>> 0 - } - - let a = h0 - let b = h1 - let c = h2 - let d = h3 - let e = h4 - let f = h5 - let g = h6 - let h = h7 - - for (let i = 0; i < 64; i++) { - const S1 = rotr32(e, 6) ^ rotr32(e, 11) ^ rotr32(e, 25) - const ch = (e & f) ^ (~e & g) - const temp1 = (h + S1 + ch + SHA256_K[i] + w[i]) >>> 0 - const S0 = rotr32(a, 2) ^ rotr32(a, 13) ^ rotr32(a, 22) - const maj = (a & b) ^ (a & c) ^ (b & c) - const temp2 = (S0 + maj) >>> 0 - - h = g - g = f - f = e - e = (d + temp1) >>> 0 - d = c - c = b - b = a - a = (temp1 + temp2) >>> 0 - } - - h0 = (h0 + a) >>> 0 - h1 = (h1 + b) >>> 0 - h2 = (h2 + c) >>> 0 - h3 = (h3 + d) >>> 0 - h4 = (h4 + e) >>> 0 - h5 = (h5 + f) >>> 0 - h6 = (h6 + g) >>> 0 - h7 = (h7 + h) >>> 0 - } - - return [h0, h1, h2, h3, h4, h5, h6, h7] - .map(v => (v >>> 0).toString(16).padStart(8, '0')) - .join('') -} - -/** - * 读取本地文件真实字节并计算标准 SHA-256:宿主 filesearch_sha256(只接受 path 字段)优先,Windows 上再试 FileComparePlugin。 - * 都拿不到时返回空字符串,由调用方提示失败;不再把文件按 UTF-8 文本读出来再算(二进制文件会算出错误的值)。 - */ -export async function computeRealFileSha256( - filePath: string, - hostOverride?: DynamicBridge -): Promise { - if (!filePath || !filePath.trim()) return '' - const target = filePath.trim() - - const shaRes = await callHostTransport('filesearch_sha256', { fullPath: target }, hostOverride) - if (shaRes.ok && shaRes.data) { - const hash = typeof shaRes.data === 'string' ? shaRes.data : String(shaRes.data?.sha256 || shaRes.data?.hash || '') - if (/^[0-9a-f]{64}$/i.test(hash)) return hash.toLowerCase() - } - - const dllRes = await invokePluginService('FileComparePlugin', 'computeFileSha256', { path: target }, hostOverride) - if (dllRes.ok && dllRes.data) { - const hash = typeof dllRes.data === 'string' ? dllRes.data : String(dllRes.data?.sha256 || dllRes.data?.hash || '') - if (/^[0-9a-f]{64}$/i.test(hash)) return hash.toLowerCase() - } - - return '' -} - -export async function readRealClipboardText(hostOverride?: DynamicBridge): Promise { - const res = await callHostTransport('clipboard_read_text', {}, hostOverride) - if (res.ok && res.data !== undefined && res.data !== null) { - if (typeof res.data === 'string') return res.data - if (typeof res.data?.text === 'string') return res.data.text - } - try { - if (typeof navigator !== 'undefined' && navigator.clipboard?.readText) { - return await navigator.clipboard.readText() - } - } catch { - // ignore - } - return '' -} - -export async function writeRealClipboardText(text: string, hostOverride?: DynamicBridge): Promise { - const payload = { text: String(text || '') } - const res = await callHostTransport('clipboard_copy_text', payload, hostOverride) - if (res.ok) return true - const fallbackRes = await callHostTransport('clipboard_write_text', payload, hostOverride) - if (fallbackRes.ok) return true - try { - if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) { - await navigator.clipboard.writeText(String(text || '')) - return true - } - } catch { - // ignore - } - return false -} - -export async function showRealToast( - title: string, - style: 'success' | 'failure' | 'info' = 'info' -): Promise { - try { - const { showToast, Toast } = await import('@ztools/declarative-ui') - await showToast({ - title, - style: - style === 'success' - ? Toast.Style.Success - : style === 'failure' - ? Toast.Style.Failure - : Toast.Style.Animated - }) - } catch { - // ignore - } -} - diff --git a/extensions/pdf/src/tool-runtime.ts b/extensions/pdf/src/tool-runtime.ts new file mode 100644 index 00000000..29670de2 --- /dev/null +++ b/extensions/pdf/src/tool-runtime.ts @@ -0,0 +1,637 @@ +/** + * 宿主薄原语与基础系统能力传输层(唯一权威公共源文件,纯标准 IPC,零原生 DLL 依赖) + * + * 修改本文件后需同步复制到各使用插件的 src/tool-runtime.ts, + * 构建脚本 build-declarative.mjs 会在编译前校验副本与本文件一字不差。 + */ + +import { getHostTransport } from '@ztools/declarative-ui' + +export type ToolCapabilityStatus = 'ready' | 'needs_provisioning' | 'unsupported' + +export interface ToolCapabilityDescriptor { + readonly primitiveId: string + readonly domain: string + readonly summary: string + readonly ipcMethods: readonly string[] + readonly requiredPermissions: readonly string[] + readonly status: ToolCapabilityStatus + readonly optionalExtensions: readonly string[] +} + +export interface ToolRuntimeCapabilitiesSnapshot { + readonly contractVersion: number + readonly platform: 'windows' | 'macos' | 'other' + readonly domains: readonly string[] + readonly capabilities: readonly ToolCapabilityDescriptor[] +} + +export interface ToolRuntimeEnsureResult { + readonly primitiveId: string + readonly status: ToolCapabilityStatus + readonly provisioned: boolean +} + +export interface ToolCapabilitiesEnsureResult { + readonly ok: boolean + readonly status: ToolCapabilityStatus + readonly provisioned: boolean + readonly failedPrimitiveId?: string + readonly error?: string + readonly errorCode?: string + readonly errorDetails?: Record +} + +export interface ToolTaskCancelResult { + readonly taskId: string + readonly cancelled: boolean +} + +export interface ToolPathSlot { + readonly grantId?: string + readonly relativePath?: string + readonly path?: string +} + +export interface ToolProgressEvent { + readonly taskId: string + readonly primitiveId?: string + readonly phase: 'provisioning' | 'running' | 'finalizing' | 'completed' | 'cancelled' | 'failed' + readonly percent?: number + readonly transferredBytes?: number + readonly totalBytes?: number + readonly speedBytesPerSec?: number + readonly stage?: string + readonly errorCode?: string + readonly retryable?: boolean + readonly userAction?: string + readonly message?: string + readonly timestamp?: number +} + +export type MediaTranscodeRunResult = + | { readonly status: 'done'; readonly outputBytes: number; readonly durationMs: number } + | { readonly status: 'cancelled' } + | { + readonly status: 'failed' + readonly error?: string + readonly errorCode?: string + readonly errorDetails?: Record + } + +export interface HostTransportResult { + ok: boolean + data?: T + error?: string + errorCode?: string + errorDetails?: Record +} + +export interface HostCallOptions { + timeoutMs?: number +} + +type TransportMethodFn = (req: { messageId: string; params: Record; timeoutMs?: number }) => Promise + +interface WindowHostBridge { + __ztoolsElectron?: { + transport?: { + methods?: Record + } + } + ztools?: { + transport?: { + methods?: Record + call?: (method: string, params: Record, options?: { timeoutMs?: number }) => Promise + } + events?: { + subscribe?: (event: string) => Promise | void + on?: (event: string, cb: (payload: unknown) => void) => (() => void) | void + off?: (event: string, cb: (payload: unknown) => void) => void + } + } +} + +interface HostOverrideLike { + transport?: { + call?: (method: string, params: Record, options?: { timeoutMs?: number }) => Promise + } + [method: string]: unknown +} + +let reqSeq = 1 + +export function nextMessageId(prefix = 'tool'): string { + reqSeq = (reqSeq + 1) % 1_000_000 + return `${prefix}_${Date.now()}_${reqSeq}` +} + +export function asRecord(value: unknown): Record | null { + return value && typeof value === 'object' && !Array.isArray(value) + ? (value as Record) + : null +} + +function extractErrorMeta(errObj: unknown): { + errorCode?: string + errorDetails?: Record +} { + const rec = asRecord(errObj) + if (!rec) return {} + const errorCode = + typeof rec.errorCode === 'string' && rec.errorCode.trim() + ? rec.errorCode.trim() + : typeof rec.code === 'string' && rec.code.trim() + ? rec.code.trim() + : undefined + const rawDetails = asRecord(rec.errorDetails) ?? asRecord(rec.details) ?? undefined + return { + ...(errorCode ? { errorCode } : {}), + ...(rawDetails ? { errorDetails: rawDetails } : {}) + } +} + +function toTransportError(err: unknown): HostTransportResult { + return { + ok: false, + error: err instanceof Error ? err.message : String(err), + ...extractErrorMeta(err) + } +} + +function buildFailureResult(rec: Record, fallbackMsg: string): HostTransportResult { + const errObj = asRecord(rec.error) + const errMsg = errObj + ? String(errObj.message || errObj.code || JSON.stringify(errObj)) + : String(rec.error || rec.message || fallbackMsg) + return { ok: false, error: errMsg, ...extractErrorMeta(rec), ...extractErrorMeta(errObj) } +} + +function unwrapTransportResponse(raw: unknown): HostTransportResult { + if (raw === null || raw === undefined) { + return { ok: false, error: 'EMPTY_IPC_RESPONSE', errorCode: 'EMPTY_IPC_RESPONSE' } + } + if (typeof raw !== 'object') { + return { ok: true, data: raw as T } + } + const outer = asRecord(raw) + if (!outer) { + return { ok: true, data: raw as T } + } + if (outer.success === false || outer.ok === false) { + return buildFailureResult(outer, 'IPC_CALL_FAILED') + } + + const firstLayer = 'data' in outer && outer.data !== undefined ? outer.data : outer + const inner = asRecord(firstLayer) + if (inner) { + if (inner.success === false || inner.ok === false) { + return buildFailureResult(inner, 'IPC_INNER_FAILED') + } + if ('data' in inner && inner.data !== undefined) { + return { ok: true, data: inner.data as T } + } + } + + return { ok: true, data: firstLayer as T } +} + +/** 判断当前是否处于真实的 ZTools Electron 渲染进程宿主环境 */ +export function isRealElectronHost(hostOverride?: unknown): boolean { + if (hostOverride) return true + if (typeof window === 'undefined') return false + const w = window as unknown as WindowHostBridge + return Boolean( + w.__ztoolsElectron?.transport?.methods || + w.ztools?.transport?.call || + w.ztools?.transport?.methods + ) +} + +/** 统一调用宿主 IPC 传输层(优先测试桩,其次 declarative-ui 宿主通道与 preload 通道) */ +export async function callHostTransport( + method: string, + params: Record = {}, + hostOverride?: unknown, + options?: HostCallOptions +): Promise> { + const override = asRecord(hostOverride) as HostOverrideLike | null + if (override) { + const directFn = override[method] + if (typeof directFn === 'function') { + try { + return unwrapTransportResponse(await (directFn as (p: Record) => Promise)(params)) + } catch (err) { + return toTransportError(err) + } + } + if (typeof override.transport?.call === 'function') { + try { + return unwrapTransportResponse(await override.transport.call(method, params, options)) + } catch (err) { + return toTransportError(err) + } + } + return { ok: false, error: `METHOD_NOT_AVAILABLE: ${method}`, errorCode: 'METHOD_NOT_AVAILABLE' } + } + + // 优先走 declarative-ui 运行时注入的带归属令牌通道 + if (typeof getHostTransport === 'function') { + const transport = getHostTransport() + if (transport) { + try { + const callOpts = typeof options?.timeoutMs === 'number' ? { timeoutMs: options.timeoutMs } : undefined + return unwrapTransportResponse(await transport.call(method, params, callOpts)) + } catch (err) { + return toTransportError(err) + } + } + } + + if (typeof window === 'undefined') { + return { ok: false, error: 'NO_WINDOW_ENV', errorCode: 'NO_WINDOW_ENV' } + } + + const w = window as unknown as WindowHostBridge + const methods = w.__ztoolsElectron?.transport?.methods || w.ztools?.transport?.methods + const fn = methods?.[method] + if (typeof fn === 'function') { + try { + const messageId = nextMessageId(method.replace(/[^A-Za-z0-9_]/g, '_').slice(0, 24)) + const payload = { + messageId, + params, + ...(typeof options?.timeoutMs === 'number' ? { timeoutMs: options.timeoutMs } : {}) + } + return unwrapTransportResponse(await fn(payload)) + } catch (err) { + return toTransportError(err) + } + } + + if (typeof w.ztools?.transport?.call === 'function') { + try { + return unwrapTransportResponse(await w.ztools.transport.call(method, params, options)) + } catch (err) { + return toTransportError(err) + } + } + + return { ok: false, error: `METHOD_NOT_AVAILABLE: ${method}`, errorCode: 'METHOD_NOT_AVAILABLE' } +} + +/** 探测宿主薄原语能力快照(tool_runtime_capabilities) */ +export async function queryRuntimeCapabilities( + hostOverride?: unknown +): Promise> { + const res = await callHostTransport('tool_runtime_capabilities', {}, hostOverride) + if (!res.ok) return res as HostTransportResult + const rec = asRecord(res.data) + if (!rec || !Array.isArray(rec.capabilities)) { + return { + ok: false, + error: 'INVALID_CAPABILITIES_SNAPSHOT', + errorCode: 'INVALID_CAPABILITIES_SNAPSHOT' + } + } + const capabilities: ToolCapabilityDescriptor[] = [] + for (const rawCap of rec.capabilities) { + const cap = asRecord(rawCap) + if (!cap || typeof cap.primitiveId !== 'string') continue + const rawStatus = cap.status + const status: ToolCapabilityStatus = + rawStatus === 'ready' || rawStatus === 'needs_provisioning' || rawStatus === 'unsupported' + ? rawStatus + : 'unsupported' + const optionalExtensions = Array.isArray(cap.optionalExtensions) + ? cap.optionalExtensions.filter((e): e is string => typeof e === 'string' && e.trim().length > 0) + : [] + capabilities.push({ + primitiveId: cap.primitiveId, + domain: typeof cap.domain === 'string' ? cap.domain : '', + summary: typeof cap.summary === 'string' ? cap.summary : '', + ipcMethods: Array.isArray(cap.ipcMethods) ? cap.ipcMethods.filter((m): m is string => typeof m === 'string') : [], + requiredPermissions: Array.isArray(cap.requiredPermissions) + ? cap.requiredPermissions.filter((p): p is string => typeof p === 'string') + : [], + status, + optionalExtensions + }) + } + const platform = + rec.platform === 'windows' || rec.platform === 'macos' || rec.platform === 'other' + ? rec.platform + : 'other' + return { + ok: true, + data: { + contractVersion: typeof rec.contractVersion === 'number' ? rec.contractVersion : 1, + platform, + domains: Array.isArray(rec.domains) ? rec.domains.filter((d): d is string => typeof d === 'string') : [], + capabilities + } + } +} + +export function findCapability( + snapshot: ToolRuntimeCapabilitiesSnapshot | null | undefined, + primitiveId: string +): ToolCapabilityDescriptor | null { + if (!snapshot) return null + return snapshot.capabilities.find((c) => c.primitiveId === primitiveId) ?? null +} + +export function hasCapabilityExtension( + snapshot: ToolRuntimeCapabilitiesSnapshot | null | undefined, + primitiveId: string, + extensionName: string +): boolean { + const cap = findCapability(snapshot, primitiveId) + return Boolean(cap && cap.optionalExtensions.includes(extensionName)) +} + +/** 按需拉取并准备指定薄原语运行组件(tool_runtime_ensure) */ +export async function ensureRuntimeCapability( + primitiveId: string, + hostOverride?: unknown +): Promise> { + return callHostTransport('tool_runtime_ensure', { primitiveId }, hostOverride) +} + +/** 顺序按需准备多个薄原语运行组件,任一项未就绪即中止并聚合 provisioned 标记 */ +export async function ensureRuntimeCapabilities( + primitiveIds: readonly string[], + hostOverride?: unknown +): Promise { + let provisionedAny = false + for (const primitiveId of primitiveIds) { + const res = await ensureRuntimeCapability(primitiveId, hostOverride) + if (!res.ok || !res.data || res.data.status !== 'ready') { + return { + ok: false, + status: res.data?.status ?? 'unsupported', + provisioned: provisionedAny, + failedPrimitiveId: primitiveId, + error: res.error, + errorCode: res.errorCode, + errorDetails: res.errorDetails + } + } + if (res.data.provisioned) provisionedAny = true + } + return { ok: true, status: 'ready', provisioned: provisionedAny } +} + +/** 取消正在执行的宿主薄原语任务(tool_task_cancel) */ +export async function cancelRuntimeTask( + taskId: string, + hostOverride?: unknown +): Promise> { + return callHostTransport('tool_task_cancel', { taskId }, hostOverride) +} + +/** 判断错误码是否表示用户主动取消任务 */ +export function isTaskCancelledCode(errorCode?: string): boolean { + const code = (errorCode || '').trim().toUpperCase() + return code === 'TOOL_TASK_CANCELLED' || code === 'CANCELLED' || code === 'OPERATION_CANCELLED' +} + +/** 执行单个媒体转码任务(tool_media_transcode_run),统一处理取消与产物字节数校验 */ +export async function runMediaTranscodeTask( + payload: Record, + hostOverride?: unknown +): Promise { + const res = await callHostTransport('tool_media_transcode_run', payload, hostOverride) + if (!res.ok) { + if (isTaskCancelledCode(res.errorCode)) { + return { status: 'cancelled' } + } + return { + status: 'failed', + error: res.error, + errorCode: res.errorCode, + errorDetails: res.errorDetails + } + } + const rec = asRecord(res.data) + const outputBytes = Number(rec?.outputBytes) + const durationMs = Number(rec?.durationMs) + if (!Number.isFinite(outputBytes) || outputBytes <= 0) { + return { status: 'failed', error: 'EMPTY_OUTPUT', errorCode: 'EMPTY_OUTPUT' } + } + return { + status: 'done', + outputBytes, + durationMs: Number.isFinite(durationMs) && durationMs >= 0 ? durationMs : 0 + } +} + +/** 订阅宿主推送的 tool_runtime_progress 任务进度事件 */ +export function subscribeRuntimeProgress( + handler: (event: ToolProgressEvent) => void +): () => void { + if (typeof window === 'undefined') return () => undefined + const w = window as unknown as WindowHostBridge + const eventsApi = w.ztools?.events + if (!eventsApi || typeof eventsApi.on !== 'function') return () => undefined + + try { + void eventsApi.subscribe?.('tool_runtime_progress') + } catch (err) { + // 某些测试桩或旧渲染层可能未提供 subscribe,继续注册 on 监听 + void err + } + + const listener = (raw: unknown) => { + const outer = asRecord(raw) + if (!outer) return + const inner = asRecord(outer.payload) ?? outer + if (typeof inner.taskId !== 'string' || typeof inner.phase !== 'string') return + handler(inner as unknown as ToolProgressEvent) + } + + const off = eventsApi.on('tool_runtime_progress', listener) + return () => { + if (typeof off === 'function') { + off() + } else if (typeof eventsApi.off === 'function') { + eventsApi.off('tool_runtime_progress', listener) + } + } +} + +/** 订阅旧版宿主 plugin_files_dropped 拖拽回退事件并返回卸载函数 */ +export function subscribeLegacyFileDrop(onDrop: (envelope: unknown) => void): () => void { + if (typeof window === 'undefined') return () => undefined + const w = window as unknown as WindowHostBridge + const eventsApi = w.ztools?.events + if (!eventsApi || typeof eventsApi.on !== 'function') return () => undefined + + const off = eventsApi.on('plugin_files_dropped', onDrop) + return () => { + if (typeof off === 'function') { + off() + } else if (typeof eventsApi.off === 'function') { + eventsApi.off('plugin_files_dropped', onDrop) + } + } +} + +/** 字节数格式化 */ +export function formatBytes(bytes: number): string { + if (!Number.isFinite(bytes) || bytes < 0) return '0 B' + if (bytes < 1024) return `${Math.round(bytes)} B` + const units = ['KB', 'MB', 'GB', 'TB'] + let value = bytes / 1024 + let idx = 0 + while (value >= 1024 && idx < units.length - 1) { + value /= 1024 + idx += 1 + } + return `${value >= 100 ? value.toFixed(0) : value >= 10 ? value.toFixed(1) : value.toFixed(2)} ${units[idx]}` +} + +/** 字节数格式化别名(兼容 archive-manager 等插件既有导出名) */ +export function formatByteCount(bytes: number): string { + return formatBytes(bytes) +} + +/** 获取系统标准目录路径(支持 Windows 与 macOS) */ +export async function getRealSystemPath( + name: 'home' | 'desktop' | 'documents' | 'downloads' | 'music' | 'pictures' | 'videos' | 'temp', + hostOverride?: unknown +): Promise { + const res = await callHostTransport('system_get_path', { name }, hostOverride) + if (res.ok && res.data) { + if (typeof res.data === 'string' && res.data.trim()) return res.data.trim() + const rec = asRecord(res.data) + if (rec && typeof rec.path === 'string' && rec.path.trim()) return rec.path.trim() + } + return '' +} + +/** 读取剪贴板文本 */ +export async function readRealClipboardText(hostOverride?: unknown): Promise { + const res = await callHostTransport('clipboard_read_text', {}, hostOverride) + if (res.ok && res.data !== undefined && res.data !== null) { + if (typeof res.data === 'string') return res.data + const rec = asRecord(res.data) + if (rec && typeof rec.text === 'string') return rec.text + } + return '' +} + +/** 写入剪贴板文本 */ +export async function writeRealClipboardText(text: string, hostOverride?: unknown): Promise { + const res = await callHostTransport('clipboard_copy_text', { text: String(text || '') }, hostOverride) + return res.ok +} + +/** 在系统文件管理器中显示文件 */ +export async function showRealItemInFolder(fullPath: string, hostOverride?: unknown): Promise { + if (!fullPath) return false + const res = await callHostTransport('shell_show_item_in_folder', { fullPath }, hostOverride) + return res.ok +} + +/** 用系统默认应用打开文件或文件夹 */ +export async function openRealPath(fullPath: string, hostOverride?: unknown): Promise { + if (!fullPath) return false + const res = await callHostTransport('shell_open_path', { fullPath }, hostOverride) + return res.ok +} + +/** 将文件或目录移入系统回收站 */ +export async function trashRealItem(fullPath: string, hostOverride?: unknown): Promise<{ ok: boolean; error?: string }> { + if (!fullPath) return { ok: false, error: 'EMPTY_PATH' } + const res = await callHostTransport('shell_trash_item', { fullPath }, hostOverride) + return res.ok ? { ok: true } : { ok: false, error: res.error } +} + +/** 通过 window_show_open_dialog 选择输出目录(兼容 Windows 与 macOS) */ +export async function pickOutputDirectoryDialog( + options: { title: string; defaultPath?: string }, + hostOverride?: unknown +): Promise<{ canceled: boolean; directoryPath?: string; error?: string; errorCode?: string }> { + const params: Record = { + title: options.title, + properties: ['openDirectory', 'createDirectory'] + } + if (options.defaultPath) params.defaultPath = options.defaultPath + const res = await callHostTransport('window_show_open_dialog', params, hostOverride) + if (!res.ok) { + return { canceled: false, error: res.error || 'OPEN_DIALOG_FAILED', errorCode: res.errorCode } + } + const rec = asRecord(res.data) + if (!rec) return { canceled: false, error: 'INVALID_DIALOG_RESULT' } + if (rec.canceled === true) return { canceled: true } + const firstPath = + (Array.isArray(rec.filePaths) && typeof rec.filePaths[0] === 'string' && rec.filePaths[0].trim()) || + (typeof rec.filePath === 'string' && rec.filePath.trim()) || + (typeof rec.folderPath === 'string' && rec.folderPath.trim()) || + '' + if (!firstPath) return { canceled: false, error: 'NO_DIRECTORY_SELECTED' } + return { canceled: false, directoryPath: firstPath } +} + +/** 通用文件/目录选择对话框(支持自定义 properties 与 filters) */ +export async function openDialogSelectPaths( + options: { + title: string + properties: Array<'openFile' | 'openDirectory' | 'multiSelections' | 'createDirectory'> + filters?: Array<{ name: string; extensions: string[] }> + }, + hostOverride?: unknown +): Promise<{ canceled: boolean; paths: string[]; error?: string }> { + const params: Record = { + title: options.title, + properties: options.properties, + ...(options.filters ? { filters: options.filters } : {}) + } + const res = await callHostTransport('window_show_open_dialog', params, hostOverride) + if (!res.ok) return { canceled: false, paths: [], error: res.error || 'OPEN_DIALOG_FAILED' } + const rec = asRecord(res.data) + if (!rec) return { canceled: false, paths: [], error: 'INVALID_DIALOG_RESPONSE' } + if (rec.canceled === true) return { canceled: true, paths: [] } + const paths = Array.isArray(rec.filePaths) + ? rec.filePaths.filter((p): p is string => typeof p === 'string' && p.trim().length > 0).map((p) => p.trim()) + : typeof rec.filePath === 'string' && rec.filePath.trim() + ? [rec.filePath.trim()] + : [] + return { canceled: false, paths } +} + +/** 选择待归档的源文件或目录列表(多选) */ +export async function pickAnySourcesDialog( + options: { title: string; directories?: boolean }, + hostOverride?: unknown +): Promise<{ canceled: boolean; paths: string[]; error?: string }> { + return openDialogSelectPaths( + { + title: options.title, + properties: options.directories ? ['openDirectory', 'multiSelections'] : ['openFile', 'multiSelections'] + }, + hostOverride + ) +} + +/** 保存归档文件对话框(zip / 7z / tar) */ +export async function pickSaveArchiveDialog( + options: { title: string; defaultPath?: string; format: 'zip' | '7z' | 'tar' }, + hostOverride?: unknown +): Promise<{ canceled: boolean; filePath?: string; error?: string }> { + const ext = options.format === '7z' ? '7z' : options.format === 'tar' ? 'tar' : 'zip' + const params: Record = { + title: options.title, + filters: [{ name: `${ext.toUpperCase()} Archive`, extensions: [ext] }] + } + if (options.defaultPath) params.defaultPath = options.defaultPath + const res = await callHostTransport('window_show_save_dialog', params, hostOverride) + if (!res.ok) return { canceled: false, error: res.error || 'SAVE_DIALOG_FAILED' } + const rec = asRecord(res.data) + if (!rec) return { canceled: false, error: 'INVALID_SAVE_DIALOG' } + if (rec.canceled === true) return { canceled: true } + const filePath = typeof rec.filePath === 'string' ? rec.filePath.trim() : '' + if (!filePath) return { canceled: true } + return { canceled: false, filePath } +} diff --git a/extensions/pdf/tests/pdf.host.test.mjs b/extensions/pdf/tests/pdf.host.test.mjs index 87da1e96..e5974979 100644 --- a/extensions/pdf/tests/pdf.host.test.mjs +++ b/extensions/pdf/tests/pdf.host.test.mjs @@ -1,128 +1,222 @@ -// 本插件现行代码的宿主集成测试(导入改为本插件的 dist/) import test from 'node:test' import assert from 'node:assert/strict' +import { setRuntimeLocale } from '@ztools/declarative-ui' import * as pdf from '../dist/index.js' -import { collectFolderFiles, pickFiles } from '../dist/file-import.js' -async function withRealElectronWindow(handlers, fn) { - const prevWindow = globalThis.window - const calls = [] - const transportMethods = {} - - for (const [channel, impl] of Object.entries(handlers)) { - transportMethods[channel] = async envelope => { - const actualParams = - envelope && typeof envelope === 'object' && 'params' in envelope && 'messageId' in envelope - ? envelope.params - : envelope - calls.push({ channel, payload: actualParams }) - return impl(actualParams) - } - } +setRuntimeLocale('zh-CN') - globalThis.window = { - __ztoolsElectron: { - transport: { - methods: transportMethods - } - } - } +const pdfDoc = (name, dir = 'D:\\Docs') => ({ + id: `pdf:${dir}\\${name}`.toLowerCase(), + name, + path: `${dir}\\${name}`, + parentDir: dir, + extension: '.pdf', + docType: 'pdf', + sizeBytes: 20480 +}) - try { - return await fn(calls) - } finally { - if (prevWindow === undefined) { - delete globalThis.window - } else { - globalThis.window = prevWindow - } - } -} +const imgDoc = (name, dir = 'D:\\Pics') => ({ + id: `pdf:${dir}\\${name}`.toLowerCase(), + name, + path: `${dir}\\${name}`, + parentDir: dir, + extension: '.png', + docType: 'image', + sizeBytes: 10240 +}) -test('pdf host integration: 导出不再包含自动扫盘接口,选择文件/文件夹与真实 dllplugin_call 对接完整', async () => { - assert.equal(pdf.fetchRealPdfWorkspace, undefined) - assert.equal(pdf.scanLocalPdfQueue, undefined) - assert.deepEqual(pdf.INPUT_PDF_EXTENSIONS, ['.pdf']) - - await withRealElectronWindow( - { - window_show_open_dialog: () => ({ - canceled: false, - filePaths: ['D:\\Media\\Docs\\arch.pdf', 'D:\\Media\\Docs\\notes.txt'] - }), - filesystem_get_file_size: ({ path: p }) => ({ - success: true, - size: p.endsWith('arch.pdf') ? 640000 : 120 - }), - filesystem_get_directory_contents: () => ({ - success: true, - files: [ - { name: 'arch.pdf', size: 640000, isDirectory: false, lastModified: '2026-10-01T00:00:00Z' }, - { name: 'notes.docx', size: 1000, isDirectory: false, lastModified: '2026-10-01T00:00:00Z' } +function makePdfHost({ failMethod = '' } = {}) { + const calls = [] + const host = { + tool_runtime_capabilities: async () => ({ + success: true, + data: { + contractVersion: 1, + platform: 'windows', + domains: ['document'], + capabilities: [ + { + primitiveId: 'document.pdf.inspect', + domain: 'document', + summary: 'inspect', + ipcMethods: ['tool_document_pdf_inspect'], + requiredPermissions: ['fs'], + status: 'ready', + optionalExtensions: [] + }, + { + primitiveId: 'document.pdf.transform', + domain: 'document', + summary: 'transform', + ipcMethods: ['tool_document_pdf_transform'], + requiredPermissions: ['fs'], + status: 'ready', + optionalExtensions: ['qpdf'] + }, + { + primitiveId: 'document.pdf.render', + domain: 'document', + summary: 'render', + ipcMethods: ['tool_document_pdf_render'], + requiredPermissions: ['fs'], + status: 'ready', + optionalExtensions: [] + } ] - }), - filesystem_file_exists: () => ({ success: true, exists: false }), - dllplugin_call: ({ plugin, func, params }) => ({ - ok: true, + } + }), + tool_runtime_ensure: async (params) => { + calls.push({ method: 'tool_runtime_ensure', params }) + return { success: true, data: { primitiveId: params.primitiveId, status: 'ready', provisioned: true } } + }, + tool_task_cancel: async (params) => { + calls.push({ method: 'tool_task_cancel', params }) + return { success: true, data: { taskId: params.taskId, cancelled: true } } + }, + tool_document_pdf_inspect: async (params) => { + calls.push({ method: 'tool_document_pdf_inspect', params }) + if (failMethod === 'tool_document_pdf_inspect') return { success: false, error: { code: 'CORRUPT_PDF', message: 'PDF 已损坏' } } + return { success: true, - plugin, - operation: func, - outputPath: params.outputPath, - text: 'Hello PDF' - }), - shell_open_path: () => ({ success: true }), - shell_show_item_in_folder: () => ({ success: true }) + data: { + pageCount: 3, + encrypted: false, + sizeBytes: 20480, + title: 'Report', + pages: [{ pageNumber: 1, widthPt: 595, heightPt: 842, text: '第一页内容' }], + fullText: '第一页内容\n第二页内容' + } + } }, - async calls => { - const transport = pdf.createPdfImportTransport() - const picked = await pickFiles(transport, pdf.PDF_IMPORT_RULES, { title: '选择 PDF 文件', filterName: 'PDF 文件' }) - assert.equal(picked.files.length, 1) - assert.equal(picked.files[0].name, 'arch.pdf') - assert.equal(picked.ignored, 1) - const dialogCall = calls.find(c => c.channel === 'window_show_open_dialog') - assert.equal(dialogCall.payload.filters, 'PDF 文件|pdf') - - const collected = await collectFolderFiles(transport, 'D:\\Media\\Docs', pdf.PDF_IMPORT_RULES) - assert.equal(collected.files.length, 1) - assert.equal(collected.ignored, 1) - - const docItem = pdf.toPdfDocItem(collected.files[0]) - const batch = await pdf.runPdfTool('pdf-to-txt', [docItem]) - assert.equal(batch.succeeded.length, 1) - assert.equal(batch.succeeded[0].outputPath, 'D:\\Media\\Docs\\arch.txt') - - const pRes = await pdf.invokeNativeCapability('PdfToTxt', { - inputPath: 'D:\\Media\\Docs\\arch.pdf', - outputPath: 'D:\\Media\\Docs\\arch.txt' - }) - assert.equal(pRes.ok, true) - assert.equal(pRes.fromFallback, false) - assert.equal(pRes.data.plugin, 'pdf') - assert.equal(pRes.data.outputPath, 'D:\\Media\\Docs\\arch.txt') - - // 客户端做不到的转换(PDF 转 Word)直接拒绝,不能拿到成功结果,也不请求客户端 - const before = calls.filter(c => c.channel === 'dllplugin_call').length - const wordRes = await pdf.invokeNativeCapability('PdfToWord', { inputPath: 'D:\\Media\\Docs\\arch.pdf' }) - assert.equal(wordRes.ok, false) - assert.match(wordRes.error, /UNSUPPORTED/) - assert.equal(calls.filter(c => c.channel === 'dllplugin_call').length, before) - - assert.equal(await pdf.openPdfDocument('D:\\Media\\Docs\\arch.pdf'), true) - assert.equal(await pdf.openPdfFileLocation('D:\\Media\\Docs\\arch.txt'), true) - } - ) - - await withRealElectronWindow( - { - dllplugin_call: () => { - throw new Error('FFMPEG_BINARY_MISSING') + tool_document_pdf_transform: async (params) => { + calls.push({ method: 'tool_document_pdf_transform', params }) + if (failMethod === 'tool_document_pdf_transform') { + return { success: false, error: { code: 'TRANSFORM_FAILED', message: '变换失败' } } + } + return { + success: true, + data: { + taskId: params.taskId, + outputBytes: 18432, + pageCount: params.operation === 'merge' ? 6 : 3, + outputFiles: [params.output.path] + } } }, - async () => { - const pFail = await pdf.invokeNativeCapability('PdfToTxt', { inputPath: 'D:\\Media\\Docs\\arch.pdf' }) - assert.equal(pFail.ok, false) - assert.match(pFail.error, /FFMPEG_BINARY_MISSING/) - assert.equal(pFail.data?.simulated, undefined) + tool_document_pdf_render: async (params) => { + calls.push({ method: 'tool_document_pdf_render', params }) + if (failMethod === 'tool_document_pdf_render') { + return { success: false, error: { code: 'RENDER_FAILED', message: '渲染失败' } } + } + return { + success: true, + data: { + taskId: params.taskId, + files: [`${params.outputDir.path}\\page-1.${params.format}`], + pageCount: 1 + } + } } - ) + } + return { host, calls } +} + +test('pdf: 全部 11 项纯 PDF 动作精准对接 document.pdf.* 薄原语', async () => { + const { host, calls } = makePdfHost() + const a = pdfDoc('a.pdf') + const b = pdfDoc('b.pdf') + const p1 = imgDoc('1.png') + const p2 = imgDoc('2.png') + + // 1. inspect + const inspectRes = await pdf.runPdfTool('pdf-inspect', [a], {}, host) + assert.equal(inspectRes.ok, true) + assert.equal(inspectRes.pageCount, 3) + assert.match(inspectRes.extractedText, /第一页内容/) + + // 2. merge + const mergeRes = await pdf.runPdfTool('pdf-merge', [a, b], {}, host) + assert.equal(mergeRes.ok, true) + assert.equal(mergeRes.pageCount, 6) + + // 3. split + const splitRes = await pdf.runPdfTool('pdf-split', [a], { pageRangesText: '1-2,3' }, host) + assert.equal(splitRes.ok, true) + + // 4. reorder + const reorderRes = await pdf.runPdfTool('pdf-reorder', [a], { pageOrderText: '3,1,2' }, host) + assert.equal(reorderRes.ok, true) + + // 5. rotate + const rotateRes = await pdf.runPdfTool('pdf-rotate', [a], { rotateDegrees: 180 }, host) + assert.equal(rotateRes.ok, true) + + // 6. compress + const compressRes = await pdf.runPdfTool('pdf-compress', [a], {}, host) + assert.equal(compressRes.ok, true) + + // 7. encrypt + const encryptRes = await pdf.runPdfTool('pdf-encrypt', [a], { password: 'u123', ownerPassword: 'o456' }, host) + assert.equal(encryptRes.ok, true) + + // 8. decrypt + const decryptRes = await pdf.runPdfTool('pdf-decrypt', [a], { password: 'u123' }, host) + assert.equal(decryptRes.ok, true) + + // 9. watermark + const wmRes = await pdf.runPdfTool('pdf-watermark', [a], { watermarkText: 'DRAFT', watermarkOpacity: 0.25 }, host) + assert.equal(wmRes.ok, true) + + // 10. render + const renderRes = await pdf.runPdfTool('pdf-render', [a], { renderFormat: 'jpeg', renderDpi: 200 }, host) + assert.equal(renderRes.ok, true) + assert.equal(renderRes.outputFiles.length, 1) + + // 11. images-to-pdf + const img2pdfRes = await pdf.runPdfTool('images-to-pdf', [p1, p2], {}, host) + assert.equal(img2pdfRes.ok, true) + + const ops = calls.filter((c) => c.method === 'tool_document_pdf_transform').map((c) => c.params.operation) + assert.deepEqual(ops, ['merge', 'split', 'reorder', 'rotate', 'compress', 'encrypt', 'decrypt', 'watermark', 'images-to-pdf']) +}) + +test('pdf: qpdf 按需下载引导、取消任务与宿主失败如实报错', async () => { + const { host, calls } = makePdfHost({ failMethod: 'tool_document_pdf_transform' }) + const a = pdfDoc('a.pdf') + + // qpdf 缺失且需按需准备时明确拦截引导 + const pendingCaps = { + contractVersion: 1, + platform: 'windows', + domains: ['document'], + capabilities: [ + { + primitiveId: 'document.pdf.transform', + domain: 'document', + summary: 'transform', + ipcMethods: ['tool_document_pdf_transform'], + requiredPermissions: ['fs'], + status: 'needs_provisioning', + optionalExtensions: [] + } + ] + } + const blocked = await pdf.runPdfTool('pdf-compress', [a], { capabilities: pendingCaps }, host) + assert.equal(blocked.ok, false) + assert.equal(blocked.error, 'QPDF_PROVISIONING_REQUIRED') + + // 调用按需准备 + const ensured = await pdf.ensurePdfEngine(host) + assert.equal(ensured.ok, true) + assert.equal(calls.filter((c) => c.method === 'tool_runtime_ensure').length, 3) + + // 取消任务透传 tool_task_cancel + const cancelled = await pdf.cancelActivePdfTask('pdf_task_99', host) + assert.equal(cancelled.ok, true) + assert.equal(cancelled.cancelled, true) + + // 宿主返回失败如实报错 + const failed = await pdf.runPdfTool('pdf-compress', [a], {}, host) + assert.equal(failed.ok, false) + assert.match(failed.message, /变换失败/) }) diff --git a/extensions/pdf/tests/pdf.logic.test.mjs b/extensions/pdf/tests/pdf.logic.test.mjs index fabcc9ad..62758f60 100644 --- a/extensions/pdf/tests/pdf.logic.test.mjs +++ b/extensions/pdf/tests/pdf.logic.test.mjs @@ -1,4 +1,3 @@ -// PDF 文字导出流程:扫描 → 选不覆盖的输出名 → 调用客户端 → 校验返回 → 汇总提示(含失败路径) import test from 'node:test' import assert from 'node:assert/strict' import fs from 'node:fs' @@ -8,311 +7,53 @@ import { setRuntimeLocale } from '@ztools/declarative-ui' import * as pdf from '../dist/index.js' setRuntimeLocale('zh-CN') - -const __dirname = path.dirname(fileURLToPath(import.meta.url)) - -function pdfFile(p, sizeBytes = 4096) { - const parts = pdf.splitFilePath(p) - return { - id: `pdf:${p.toLowerCase()}`, - name: p.split(/[\\/]/).pop(), - path: p, - parentDir: parts.dir, - extension: parts.ext.toLowerCase(), - docType: parts.ext.toLowerCase() === '.pdf' ? 'pdf' : 'other', - sizeBytes - } -} - -/** 测试宿主:按方法名提供实现(与 callHostTransport 的 hostOverride 约定一致),记录全部调用 */ -function makeHost({ existing = [], exists, dll } = {}) { - const calls = [] - const existingSet = new Set(existing.map(p => p.toLowerCase())) - const host = { - filesystem_file_exists: async params => { - calls.push(['filesystem_file_exists', params]) - if (exists) return exists(params) - return { success: true, exists: existingSet.has(params.path.toLowerCase()) } - }, - dllplugin_call: async params => { - calls.push(['dllplugin_call', params]) - if (dll) return dll(params) - const record = { - ok: true, - success: true, - operation: params.func, - outputPath: params.params.outputPath, - text: 'Quarterly report\nRevenue grew' - } - // 与客户端路由返回结构一致:结果外再套一层 data - return { success: true, data: { ...record, data: { ...record } } } - } - } - return { host, calls, dllCalls: () => calls.filter(c => c[0] === 'dllplugin_call') } -} - -test('路径拆分与输出候选名:Windows / POSIX / 根目录,不能推导时返回 null', () => { - assert.deepEqual(pdf.splitFilePath('D:\\Docs\\sub\\Report.PDF'), { - dirWithSep: 'D:\\Docs\\sub\\', - dir: 'D:\\Docs\\sub', - stem: 'Report', - ext: '.PDF' - }) - assert.equal(pdf.splitFilePath('C:\\a.pdf').dir, 'C:\\') - assert.equal(pdf.splitFilePath('/a.pdf').dir, '/') - assert.equal(pdf.splitFilePath('/home/u/Docs/a.b.pdf').stem, 'a.b') - assert.equal(pdf.splitFilePath('no-separator.pdf'), null) - assert.equal(pdf.splitFilePath('D:\\Docs\\'), null) - assert.equal(pdf.splitFilePath(undefined), null) - - assert.equal(pdf.buildOutputCandidate('D:\\Docs\\a.pdf', '.txt', 0), 'D:\\Docs\\a.txt') - assert.equal(pdf.buildOutputCandidate('D:\\Docs\\a.pdf', '.txt', 3), 'D:\\Docs\\a (3).txt') - assert.equal(pdf.buildOutputCandidate('/home/u/a.pdf', '.html', 1), '/home/u/a (1).html') - assert.equal(pdf.buildOutputCandidate('a.pdf', '.txt', 0), null) -}) - -test('乱码判定:控制字符占比过高才算乱码,空白内容字符数为 0', () => { - assert.deepEqual(pdf.assessExtractedText('Hello World'), { chars: 10, garbled: false }) - assert.deepEqual(pdf.assessExtractedText(' \n\t '), { chars: 0, garbled: false }) - assert.deepEqual(pdf.assessExtractedText(undefined), { chars: 0, garbled: false }) - // 双字节字形编号按单字节解出时充满 \u0000 一类控制字符 - assert.equal(pdf.assessExtractedText('\u0000\u0024\u0000\u0031\u0000\u0042AB').garbled, true) - assert.equal(pdf.assessExtractedText('Café résumé naïve').garbled, false) - // 解码失败留下的替换字符同样算乱码 - assert.equal(pdf.assessExtractedText(`${String.fromCharCode(0xfffd).repeat(3)}ab`).garbled, true) -}) - -test('工具清单:界面只给出客户端能如实完成的文字导出;其余工具标为不可用并写明原因', () => { - const available = pdf.getAvailableTools() - assert.deepEqual(available.map(t => t.method), ['PdfToTxt', 'PdfToHtml']) - const unsupported = pdf.getCapabilityItems().filter(t => !t.supported) - for (const method of ['PdfToWord', 'PdfToExcel', 'PdfToPpt', 'PdfToImage', 'WordToPdf', 'ExcelToPdf', 'ImageToPdf', 'MergePdf', 'SplitPdf', 'CompressPdf']) { - const tool = unsupported.find(t => t.method === method) - assert.ok(tool, `${method} 应标为不可用`) - assert.ok(tool.unsupportedReason && tool.unsupportedReason.length > 4) - } - // 宣传性的说法不能再出现在工具文案里 - const text = JSON.stringify(pdf.getCapabilityItems()) - assert.doesNotMatch(text, /无损|300DPI|精准保留|PRD\s*\d|缩减 40%/) -}) - -test('不可用或未知的方法:直接返回失败,不请求客户端', async () => { - const { host, calls } = makeHost() - for (const method of ['MergePdf', 'SplitPdf', 'CompressPdf', 'PdfToWord', 'PdfToImage', 'WordToPdf', 'ImageToPdf']) { - const res = await pdf.invokeNativeCapability(method, { inputPath: 'D:\\Docs\\a.pdf' }, host) - assert.equal(res.ok, false, method) - assert.match(res.error, /^UNSUPPORTED: /) +const pluginDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..') + +test('pdf: 清单移除草稿标记、声明 document.pdf.* 薄原语且一期仅 Windows', () => { + const manifest = JSON.parse(fs.readFileSync(path.join(pluginDir, 'plugin.json'), 'utf8')) + assert.equal('draft' in manifest, false) + assert.equal('draftReason' in manifest, false) + assert.equal(manifest.minAppVersion, '1.3.0.4') + assert.deepEqual(manifest.requiredCapabilities, ['document.pdf.inspect', 'document.pdf.transform', 'document.pdf.render']) + assert.deepEqual(manifest.nativeComponents, []) + assert.deepEqual(manifest.targets.map((t) => t.id), ['windows-electron-any']) + for (const p of ['fs', 'dialog', 'clipboard']) { + assert.ok(manifest.permissions.includes(p)) } - const unknown = await pdf.invokeNativeCapability('InspectPdf', { inputPath: 'D:\\Docs\\a.pdf' }, host) - assert.equal(unknown.ok, false) - assert.match(unknown.error, /UNSUPPORTED_METHOD/) - assert.equal(calls.length, 0) - await assert.rejects(() => pdf.invokeNativeCapability('PdfToTxt', null, host), /INVALID_PARAMS/) -}) - -test('导出成功:输出写在 PDF 所在目录,发送给客户端的插件名为 pdf,带输出路径与源路径', async () => { - const { host, dllCalls } = makeHost() - const file = pdfFile('D:\\Docs\\sub\\Report.pdf') - const result = await pdf.runPdfTool('pdf-to-txt', [file], host) - assert.equal(result.error, undefined) - assert.equal(result.failed.length, 0) - assert.equal(result.succeeded.length, 1) - assert.equal(result.succeeded[0].outputPath, 'D:\\Docs\\sub\\Report.txt') - assert.equal(result.succeeded[0].chars, 'QuarterlyreportRevenuegrew'.length) - const [, payload] = dllCalls()[0] - assert.equal(payload.plugin, 'pdf') - assert.equal(payload.func, 'PdfToTxt') - assert.deepEqual(payload.params, { inputPath: 'D:\\Docs\\sub\\Report.pdf', outputPath: 'D:\\Docs\\sub\\Report.txt' }) - - const summary = pdf.describeBatchResult(result) - assert.equal(summary.ok, true) - assert.equal(summary.title, '已导出 1 个文件') - assert.equal(summary.message, 'D:\\Docs\\sub\\Report.txt') - - const html = await pdf.runPdfTool('pdf-to-html', [file], host) - assert.equal(html.succeeded[0].outputPath, 'D:\\Docs\\sub\\Report.html') -}) - -test('同名文件已存在:依次加序号,绝不把已有文件路径交给客户端', async () => { - const { host, dllCalls } = makeHost({ existing: ['D:\\Docs\\Report.txt', 'D:\\Docs\\Report (1).txt'] }) - const result = await pdf.runPdfTool('pdf-to-txt', [pdfFile('D:\\Docs\\Report.pdf')], host) - assert.equal(result.succeeded[0].outputPath, 'D:\\Docs\\Report (2).txt') - assert.equal(dllCalls()[0][1].params.outputPath, 'D:\\Docs\\Report (2).txt') -}) - -test('同名序号用尽:停止导出并说明原因', async () => { - const { host, calls, dllCalls } = makeHost({ exists: () => ({ success: true, exists: true }) }) - const result = await pdf.runPdfTool('pdf-to-txt', [pdfFile('D:\\Docs\\Report.pdf')], host) - assert.equal(result.succeeded.length, 0) - assert.match(result.failed[0].error, /OUTPUT_NAME_EXHAUSTED/) - assert.equal(calls.filter(c => c[0] === 'filesystem_file_exists').length, pdf.MAX_OUTPUT_NAME_ATTEMPTS) - assert.equal(dllCalls().length, 0) -}) - -test('无法确认输出文件是否存在(查询报错 / 返回结构异常):停止导出,不调用客户端写文件', async () => { - const thrown = makeHost({ - exists: () => { - throw new Error('PERMISSION_DENIED: 路径未授权') - } - }) - const r1 = await pdf.runPdfTool('pdf-to-txt', [pdfFile('D:\\Docs\\a.pdf')], thrown.host) - assert.match(r1.failed[0].error, /OUTPUT_CHECK_FAILED.*PERMISSION_DENIED/) - assert.equal(thrown.dllCalls().length, 0) - - const failed = makeHost({ exists: () => ({ success: false, error: { code: 'FILE_ERROR', message: '磁盘不可读' } }) }) - const r2 = await pdf.runPdfTool('pdf-to-txt', [pdfFile('D:\\Docs\\a.pdf')], failed.host) - assert.match(r2.failed[0].error, /OUTPUT_CHECK_FAILED.*磁盘不可读/) - assert.equal(failed.dllCalls().length, 0) - - const malformed = makeHost({ exists: () => ({ success: true }) }) - const r3 = await pdf.runPdfTool('pdf-to-txt', [pdfFile('D:\\Docs\\a.pdf')], malformed.host) - assert.match(r3.failed[0].error, /MALFORMED_EXISTS_RESPONSE/) - assert.equal(malformed.dllCalls().length, 0) -}) - -test('客户端失败如实记为失败;部分成功时按失败提示并给出第一条原因', async () => { - const { host } = makeHost({ - dll: ({ params }) => - params.inputPath.endsWith('scan.pdf') - ? { ok: false, success: false, error: '未能从 PDF 中提取到文字:可能是扫描件' } - : { ok: true, success: true, outputPath: params.outputPath, text: 'Plain text' } - }) - const result = await pdf.runPdfTool( - 'pdf-to-txt', - [pdfFile('D:\\Docs\\good.pdf'), pdfFile('D:\\Docs\\scan.pdf')], - host - ) - assert.equal(result.succeeded.length, 1) - assert.equal(result.failed.length, 1) - assert.match(result.failed[0].error, /扫描件/) - const summary = pdf.describeBatchResult(result) - assert.equal(summary.ok, false) - assert.equal(summary.title, '1 个已导出,1 个失败') - assert.match(summary.message, /^scan\.pdf:.*扫描件/) - - const allFail = makeHost({ dll: () => { throw new Error('IPC_CLOSED') } }) - const r2 = await pdf.runPdfTool('pdf-to-txt', [pdfFile('D:\\Docs\\a.pdf')], allFail.host) - const s2 = pdf.describeBatchResult(r2) - assert.equal(s2.ok, false) - assert.equal(s2.title, '导出失败(1 个)') - assert.match(s2.message, /a\.pdf:PDF 处理失败/) -}) - -test('客户端报告成功却没有输出路径 / 文字为空白 / 文字为乱码:都不能算成功', async () => { - const noPath = makeHost({ dll: () => ({ ok: true, success: true, text: 'abc' }) }) - const r1 = await pdf.runPdfTool('pdf-to-txt', [pdfFile('D:\\Docs\\a.pdf')], noPath.host) - assert.match(r1.failed[0].error, /HOST_NO_OUTPUT/) - - const blank = makeHost({ dll: ({ params }) => ({ ok: true, success: true, outputPath: params.outputPath, text: '\n\n \n' }) }) - const r2 = await pdf.runPdfTool('pdf-to-txt', [pdfFile('D:\\Docs\\a.pdf')], blank.host) - assert.equal(r2.succeeded.length, 0) - assert.match(r2.failed[0].error, /没有提取到可读文字/) - assert.equal(r2.failed[0].outputPath, 'D:\\Docs\\a.txt') - - const garbled = makeHost({ - dll: ({ params }) => ({ ok: true, success: true, outputPath: params.outputPath, text: '\u0000\u0021\u0000\u0035\u0000\u0047\u0000\u0013' }) - }) - const r3 = await pdf.runPdfTool('pdf-to-txt', [pdfFile('D:\\Docs\\a.pdf')], garbled.host) - assert.equal(r3.succeeded.length, 0) - assert.match(r3.failed[0].error, /疑似乱码/) - assert.match(r3.failed[0].error, /D:\\Docs\\a\.txt/) -}) - -test('类型不符的文件跳过并如实说明;不可用 / 未知工具整批拒绝且不请求客户端', async () => { - const { host, calls } = makeHost() - const docx = { ...pdfFile('D:\\Docs\\spec.docx'), docType: 'word' } - const skipped = await pdf.runPdfTool('pdf-to-txt', [docx], host) - assert.equal(skipped.skipped.length, 1) - const s = pdf.describeBatchResult(skipped) - assert.equal(s.ok, false) - assert.match(s.message, /都不是 PDF/) - - const merge = await pdf.runPdfTool('pdf-merge', [pdfFile('D:\\Docs\\a.pdf'), pdfFile('D:\\Docs\\b.pdf')], host) - assert.match(merge.error, /PDF合并暂不可用/) - assert.equal(pdf.describeBatchResult(merge).ok, false) - const unknown = await pdf.runPdfTool('nope', [pdfFile('D:\\Docs\\a.pdf')], host) - assert.match(unknown.error, /UNKNOWN_TOOL/) - assert.equal(calls.length, 0) - - const empty = pdf.describeBatchResult(await pdf.runPdfTool('pdf-to-txt', [], host)) - assert.equal(empty.ok, false) - assert.match(empty.message, /请先勾选/) -}) - -test('源路径不能推导输出位置或被安全规则拦截:记为失败,不调用客户端', async () => { - const { host, dllCalls } = makeHost() - const bad = { ...pdfFile('D:\\Docs\\a.pdf'), path: 'a.pdf' } - const r1 = await pdf.runPdfTool('pdf-to-txt', [bad], host) - assert.match(r1.failed[0].error, /INVALID_INPUT_PATH/) - - const traversal = { ...pdfFile('D:\\Docs\\a.pdf'), path: 'D:\\Docs\\..\\Windows\\a.pdf' } - const r2 = await pdf.runPdfTool('pdf-to-txt', [traversal], host) - assert.match(r2.failed[0].error, /SECURITY_INTERCEPTED/) - assert.equal(dllCalls().length, 0) -}) - -test('导入规则与授权过期翻译:只允许 .pdf,拦截受保护路径,大小未知保留 null,授权失效友好提示', async () => { - assert.deepEqual(pdf.INPUT_PDF_EXTENSIONS, ['.pdf']) - assert.equal(pdf.PDF_IMPORT_SUPPORTED_TEXT, 'PDF') - assert.deepEqual(pdf.PDF_IMPORT_RULES.extensions, ['.pdf']) - - const doc = pdf.toPdfDocItem({ - path: 'D:\\Docs\\Reports\\big.PDF', - name: 'big.PDF', - parentDir: 'D:\\Docs\\Reports', - extension: '.pdf', - sizeBytes: null, - lastModifiedMs: null - }) - assert.equal(doc.docType, 'pdf') - assert.equal(doc.parentDir, 'D:\\Docs\\Reports') - assert.equal(doc.sizeBytes, null) - - // 授权过期时输出检查与原生调用都会翻译为用户可读的提示 - const expiredExists = makeHost({ - exists: () => ({ success: false, error: { code: 'EXPIRED', message: '路径未由当前窗口授权' } }) - }) - const rExpired1 = await pdf.runPdfTool('pdf-to-txt', [pdfFile('D:\\Docs\\a.pdf')], expiredExists.host) - assert.match(rExpired1.failed[0].error, /文件授权已过期或未授权/) - - const expiredDll = makeHost({ - dll: () => { - throw new Error('路径未由当前窗口授权') - } - }) - const rExpired2 = await pdf.runPdfTool('pdf-to-txt', [pdfFile('D:\\Docs\\a.pdf')], expiredDll.host) - assert.match(rExpired2.failed[0].error, /文件授权已过期或未授权/) -}) - -test('源码不含需求编号、示例假数据、估算页数与自动扫盘函数', () => { - for (const file of ['logic.ts', 'index.ts']) { - const src = fs.readFileSync(path.resolve(__dirname, '../src', file), 'utf8') - assert.doesNotMatch(src, /PRD\s*\d/, file) - assert.doesNotMatch(src, /estimatedPages|INITIAL_SAMPLE|D:\\\\Workspace/, file) - assert.doesNotMatch(src, /fetchRealPdfWorkspace|scanLocalPdfQueue|SCAN_EXT_REGEX|getRealSystemPath|scanRealDirectoryTree/, file) + const logicSrc = fs.readFileSync(path.join(pluginDir, 'src/logic.ts'), 'utf8') + assert.equal(logicSrc.includes('dllplugin_call'), false) + assert.equal(logicSrc.includes('PdfPlugin'), false) +}) + +test('pdf: 纯 PDF 完整工具箱含 11 项动作且零 Office 互转假入口', () => { + const tools = pdf.getPdfToolboxModes() + const ids = tools.map((t) => t.id) + assert.deepEqual(ids, [ + 'pdf-inspect', + 'pdf-merge', + 'pdf-split', + 'pdf-reorder', + 'pdf-rotate', + 'pdf-compress', + 'pdf-encrypt', + 'pdf-decrypt', + 'pdf-watermark', + 'pdf-render', + 'images-to-pdf' + ]) + for (const item of tools) { + assert.doesNotMatch(item.id, /word|excel|ppt/i) + assert.doesNotMatch(item.title, /word|excel|ppt/i) } }) -test('i18n: PDF 限制说明与受保护路径报错通过函数动态跟随 locale 切换', () => { - assert.match(pdf.getForbiddenReason(), /目录穿越/) - assert.match(pdf.getUnavailableFeaturesNote(), /格式互转/) - assert.match(pdf.getTextExtractionLimitNote(), /未压缩/) +test('pdf: 页码区间与页面顺序解析校验正确拦截非法输入', () => { + assert.deepEqual(pdf.parsePageRanges('1-3, 5, 7-9'), ['1-3', '5', '7-9']) + assert.equal(pdf.parsePageRanges('3-1'), null) + assert.equal(pdf.parsePageRanges('0-2'), null) + assert.equal(pdf.parsePageRanges('abc'), null) - setRuntimeLocale('en-US') - try { - const texts = [ - pdf.getForbiddenReason(), - pdf.getUnavailableFeaturesNote(), - pdf.getTextExtractionLimitNote(), - ...pdf.getPdfToolboxModes().map(m => `${m.title} ${m.subtitle} ${m.tag} ${m.unsupportedReason || ''}`) - ] - for (const txt of texts) { - assert.ok(txt.length > 0 && !/[\u4e00-\u9fa5]/.test(txt), `en-US pdf text should not contain CJK: ${txt}`) - } - assert.match(pdf.getForbiddenReason(), /directory traversal/i) - assert.match(pdf.getUnavailableFeaturesNote(), /Format conversion/i) - assert.match(pdf.getTextExtractionLimitNote(), /uncompressed plain text/i) - } finally { - setRuntimeLocale('zh-CN') - } + assert.deepEqual(pdf.parsePageOrder('3, 1, 2'), [3, 1, 2]) + assert.equal(pdf.parsePageOrder('0,1'), null) + assert.equal(pdf.parsePageOrder('1,a'), null) }) diff --git a/extensions/pdf/tests/pdf.ui.test.mjs b/extensions/pdf/tests/pdf.ui.test.mjs index d72bbb6a..afa03eb2 100644 --- a/extensions/pdf/tests/pdf.ui.test.mjs +++ b/extensions/pdf/tests/pdf.ui.test.mjs @@ -1,484 +1,44 @@ -// 界面集成:挂载零扫盘、选择文件/文件夹、拖入文件夹、移除与清空列表、竞态保护及导出流程 import test from 'node:test' import assert from 'node:assert/strict' -import fs from 'node:fs' -import os from 'node:os' -import path from 'node:path' -import { createHost, installDirectoryHost, mount, tick } from '../../shared/test-harness.mjs' +import { setRuntimeLocale } from '@ztools/declarative-ui' +import { createHost, mount, tick } from '../../shared/test-harness.mjs' import PdfCommand from '../dist/index.js' -const subItems = view => view.tree().props.subList.items +setRuntimeLocale('zh-CN') +const host = createHost() -function makeTempTree(spec) { - const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ztools-pdf-ui-')) - for (const [rel, content] of Object.entries(spec)) { - const full = path.join(root, rel) - if (rel.endsWith('/')) { - fs.mkdirSync(full, { recursive: true }) - continue - } - fs.mkdirSync(path.dirname(full), { recursive: true }) - fs.writeFileSync(full, content) - } - return root -} - -const FORBIDDEN_MOUNT_METHODS = new Set([ - 'system_get_path', - 'system_list_common_folders', - 'system_search_files', - 'filesystem_get_directory_contents', - 'dllplugin_call' -]) - -test('挂载零扫盘:不调用任何目录扫描或系统路径接口,顶栏恰为 2 个按钮,空状态支持选择文件与文件夹', async () => { - const host = createHost() - const view = await mount(PdfCommand, host) - await tick(10) - - const mountCalls = host.ipcCalls.map(([m]) => m) - assert.equal(mountCalls.some(m => FORBIDDEN_MOUNT_METHODS.has(m)), false, `挂载不应调用扫盘接口,实际:${mountCalls.join(', ')}`) - assert.equal(subItems(view).length, 0) - - const tree = view.tree() - const fbActions = tree.props.filterBar.props.actions - assert.deepEqual( - fbActions.map(a => a.id), - ['pick-files', 'pick-folder'] - ) - assert.deepEqual( - fbActions.map(a => a.label), - ['选择文件', '选择文件夹'] - ) - assert.match(tree.props.filterBar.props.summaryText, /尚未添加 PDF/) - assert.match(tree.props.subList.emptyText, /尚未添加 PDF/) - - // 空状态动作依次为「选择文件…」「选择文件夹…」 - assert.deepEqual( - view.actions().map(a => a.props.title), - ['选择文件…', '选择文件夹…'] - ) - assert.equal('extensions' in (tree.props.fileInput || {}), false, '不把扩展名交给宿主过滤') - assert.equal(tree.props.fileInput?.allowDirectories, true) - - // 只展示可用格式且无彩色 Emoji - const dd = tree.props.searchBarAccessory - const dropdownValues = (dd.children ?? dd.props.children).map(c => c.props.value) - assert.deepEqual(dropdownValues, ['pdf-to-txt', 'pdf-to-html']) - const fieldIds = tree.props.workbenchPanel.fields.map(f => f.id) - assert.deepEqual(fieldIds, ['wb-format', 'wb-outdir', 'wb-limit', 'wb-unavailable']) - assert.equal(/[\u{1F300}-\u{1FAFF}]/u.test(view.text()), false) - - view.unmount() - - // 非 ZTools 客户端环境中如实提示 - const prevElectron = globalThis.__ztoolsElectron - const prevWindow = globalThis.window - try { - delete globalThis.__ztoolsElectron - if (globalThis.window) delete globalThis.window.ztools - const bareView = await mount(PdfCommand) - await tick(5) - assert.match(bareView.tree().props.filterBar.props.summaryText, /需要在 ZTools 客户端中使用/) - assert.match(bareView.tree().props.subList.emptyText, /需要在 ZTools 客户端中使用/) - bareView.unmount() - } finally { - globalThis.__ztoolsElectron = prevElectron - globalThis.window = prevWindow - } +test.beforeEach(() => { + host.reset() }) -test('选择文件:过滤非 PDF、去重并默认勾选;取消不报错;读取令牌超限提示改用选择文件夹', async () => { - const host = createHost() - host.ipc.filesystem_get_file_size = async ({ path: p }) => ({ +test('pdf UI: 挂载后仅请求薄原语能力探测,零 dllplugin_call', async () => { + host.ipc.tool_runtime_capabilities = () => ({ success: true, - size: p.endsWith('empty.pdf') ? 0 : 128000 - }) - host.ipc.window_show_open_dialog = async () => ({ - canceled: false, - filePaths: ['D:\\Docs\\report.pdf', 'D:\\Docs\\notes.txt', 'D:\\Docs\\empty.pdf'] - }) - - const view = await mount(PdfCommand, host) - await tick(10) - - const fbActions = view.tree().props.filterBar.props.actions - await fbActions[0].onAction() - await tick(10) - - const dialogCall = host.ipcCalls.find(([m]) => m === 'window_show_open_dialog') - assert.equal(dialogCall[1].filters, 'PDF 文件|pdf') - assert.deepEqual(subItems(view).map(i => i.props.title), ['report.pdf']) - assert.equal(subItems(view)[0].props.checked, true) - assert.equal(host.lastToast().style, 'SUCCESS') - assert.equal(host.lastToast().title, '已添加 1 个文件') - assert.match(host.lastToast().message, /忽略 2 个不支持的文件/) - assert.match(view.tree().props.filterBar.props.summaryText, /清空列表 Ctrl\+Shift\+Backspace/) - - // 取消选择不弹错误 - const toastCountBefore = host.toasts.length - host.ipc.window_show_open_dialog = async () => ({ canceled: true }) - await fbActions[0].onAction() - await tick(5) - assert.equal(host.toasts.length, toastCountBefore) - - // 宿主令牌超限如实给出改用选择文件夹的提示 - host.ipc.window_show_open_dialog = async () => { - throw new Error('当前窗口的文件 capability 数量超过上限') - } - await fbActions[0].onAction() - await tick(5) - assert.equal(host.lastToast().style, 'FAILURE') - assert.equal(host.lastToast().title, '导入失败') - assert.match(host.lastToast().message, /改用「选择文件夹」/) - - view.unmount() -}) - -test('选择文件夹:递归收集 .pdf、跳过无关与受保护目录、整盘确认与上限截断', async () => { - const root = makeTempTree({ - 'a.pdf': 'pdf-a', - 'sub/b.PDF': 'pdf-b', - 'sub/notes.docx': 'doc', - 'empty.pdf': '', - '.hidden.pdf': 'hidden', - 'node_modules/x.pdf': 'nm', - // 受保护规则匹配 Windows 的 \Windows\System32;macOS 上同名文件夹只是普通目录,不在这里断言跳过 - ...(process.platform === 'win32' ? { 'Windows/System32/sys.pdf': 'sys' } : {}) - }) - try { - const host = createHost() - await installDirectoryHost(host, { authorized: [root] }) - host.ipc.window_show_select_folder_dialog = async () => ({ canceled: false, folderPath: root }) - - const view = await mount(PdfCommand, host) - await tick(10) - - const fbActions = view.tree().props.filterBar.props.actions - await fbActions[1].onAction() - await tick(15) - - assert.deepEqual(subItems(view).map(i => i.props.title), ['a.pdf', 'b.PDF']) - assert.equal(subItems(view)[1].props.subtitle, path.join(root, 'sub')) - assert.equal(host.lastToast().style, 'SUCCESS') - assert.equal(host.lastToast().title, '已添加 2 个文件') - - // 重复选择同一文件夹去重不重复添加 - await fbActions[1].onAction() - await tick(15) - assert.equal(subItems(view).length, 2) - assert.equal(host.lastToast().style, 'FAILURE') - assert.equal(host.lastToast().title, '这些文件已在列表中') - - // 选中盘符根目录先确认:取消则不读取目录 - host.ipc.window_show_select_folder_dialog = async () => ({ canceled: false, folderPath: 'Z:\\' }) - host.setConfirm(false) - const beforeDirCalls = host.ipcCalls.filter(([m]) => m === 'filesystem_get_directory_contents').length - await fbActions[1].onAction() - await tick(10) - assert.equal(host.confirms.length, 1) - assert.match(host.confirms[0].title, /导入整个磁盘 Z:\\/) - assert.equal(host.ipcCalls.filter(([m]) => m === 'filesystem_get_directory_contents').length, beforeDirCalls) - - // 超过 500 个文件触发截断提示 - host.ipc.window_show_select_folder_dialog = async () => ({ canceled: false, folderPath: 'D:\\BigPdfDir' }) - host.ipc.filesystem_get_directory_contents = async () => ({ - success: true, - files: Array.from({ length: 505 }, (_, i) => ({ - name: `doc_${i + 1}.pdf`, - size: 1024, - isDirectory: false, - lastModified: '2026-10-01T00:00:00Z' - })) - }) - await fbActions[1].onAction() - await tick(15) - assert.equal(subItems(view).length, 502) - assert.equal(host.lastToast().style, 'SUCCESS') - assert.match(host.lastToast().message, /文件较多,只导入了一部分/) - - // 子目录读取失败只记录不中断、根目录失败整体报错 - const lockedDir = path.join(root, 'sub') - await installDirectoryHost(host, { authorized: [root] }) - const origList = host.ipc.filesystem_get_directory_contents - host.ipc.window_show_select_folder_dialog = async () => ({ canceled: false, folderPath: root }) - host.ipc.filesystem_get_directory_contents = async params => { - if (params.path === lockedDir) throw new Error('PERMISSION_DENIED') - return origList(params) + data: { + contractVersion: 1, + platform: 'windows', + domains: ['document'], + capabilities: [ + { + primitiveId: 'document.pdf.transform', + domain: 'document', + summary: 'transform', + ipcMethods: ['tool_document_pdf_transform'], + requiredPermissions: ['fs'], + status: 'ready', + optionalExtensions: ['qpdf'] + } + ] } - await fbActions[1].onAction() - await tick(15) - // a.pdf 和 sub/b.PDF 之前已经在了,sub 失败应给出子文件夹无法读取或已有提示 - assert.ok(host.lastToast().message.includes('无法读取') || host.lastToast().title === '这些文件已在列表中') - - host.ipc.window_show_select_folder_dialog = async () => ({ canceled: false, folderPath: 'D:\\UnauthorizedDir' }) - host.ipc.filesystem_get_directory_contents = async () => { - throw new Error('路径未由当前窗口授权') - } - await fbActions[1].onAction() - await tick(10) - assert.equal(host.lastToast().style, 'FAILURE') - assert.equal(host.lastToast().title, '导入失败') - assert.match(host.lastToast().message, /文件授权已过期或未授权/) - - view.unmount() - } finally { - fs.rmSync(root, { recursive: true, force: true }) - } -}) - -test('拖入文件夹(含新旧客户端路径与旧版 plugin_files_dropped 回退)并去重', async () => { - const root = makeTempTree({ - 'v1.2_reports/inner.pdf': 'pdf-inner', - 'v1.2_reports/pic.png': 'png', - 'direct.pdf': 'pdf-direct' }) - const dottedDir = path.join(root, 'v1.2_reports') - const directPdf = path.join(root, 'direct.pdf') + const view = await mount(PdfCommand) try { - // 1. 新版宿主:传入 directories 集合(名称带点的文件夹也能展开) - const host = createHost() - await installDirectoryHost(host, { authorized: [root] }) - host.ipc.filesystem_get_file_size = async ({ path: p }) => ({ - success: true, - size: fs.statSync(p).size - }) - - const view = await mount(PdfCommand, host) - await tick(10) - await view.dropFiles([dottedDir, directPdf], { directories: [dottedDir] }) - await tick(15) - assert.deepEqual(subItems(view).map(i => i.props.title), ['inner.pdf', 'direct.pdf']) - assert.equal(host.ipcCalls.some(([m]) => m === 'filesystem_directory_exists'), false) - view.unmount() - - // 2. 旧版客户端(不带 directories):通过 filesystem_directory_exists 探测展开 - const legacyHost = createHost() - await installDirectoryHost(legacyHost, { authorized: [root] }) - legacyHost.ipc.filesystem_directory_exists = async ({ path: p }) => ({ - success: true, - exists: fs.existsSync(p) && fs.statSync(p).isDirectory() - }) - legacyHost.ipc.filesystem_get_file_size = async ({ path: p }) => ({ - success: true, - size: fs.statSync(p).size - }) - const legacyView = await mount(PdfCommand, legacyHost) - await tick(10) - await legacyView.dropFiles([dottedDir, directPdf]) - await tick(15) - assert.deepEqual(subItems(legacyView).map(i => i.props.title), ['inner.pdf', 'direct.pdf']) - assert.equal(legacyHost.ipcCalls.some(([m]) => m === 'filesystem_directory_exists'), true) - legacyView.unmount() - - // 3. 更旧客户端(fileInput: false):走 plugin_files_dropped 事件回退 - const oldHost = createHost() - await installDirectoryHost(oldHost, { authorized: [root] }) - oldHost.ipc.filesystem_directory_exists = async ({ path: p }) => ({ - success: true, - exists: fs.existsSync(p) && fs.statSync(p).isDirectory() - }) - oldHost.ipc.filesystem_get_file_size = async ({ path: p }) => ({ - success: true, - size: fs.statSync(p).size - }) - globalThis.window.__ztoolsDeclarativeFeatures = { fileInput: false } - const oldView = await mount(PdfCommand, oldHost) await tick(10) - oldHost.emitEvent('plugin_files_dropped', { payload: { files: [dottedDir] } }) - await tick(15) - assert.deepEqual(subItems(oldView).map(i => i.props.title), ['inner.pdf']) - oldView.unmount() + assert.ok(view.tree) + assert.equal(host.ipcCalls.some(([m]) => m === 'dllplugin_call'), false) + assert.ok(host.ipcCalls.some(([m]) => m === 'tool_runtime_capabilities')) } finally { - fs.rmSync(root, { recursive: true, force: true }) - } -}) - -test('从列表移除(不删磁盘文件)、清空列表、导出中禁止清空与导入中清空丢弃过期结果', async () => { - const root = makeTempTree({ - 'one.pdf': 'pdf-1', - 'two.pdf': 'pdf-2' - }) - const onePath = path.join(root, 'one.pdf') - const twoPath = path.join(root, 'two.pdf') - - try { - const host = createHost() - await installDirectoryHost(host, { authorized: [root] }) - host.ipc.window_show_select_folder_dialog = async () => ({ canceled: false, folderPath: root }) - host.ipc.filesystem_file_exists = async () => ({ success: true, exists: false }) - - let releaseExport - const exportGate = new Promise(r => (releaseExport = r)) - host.ipc.dllplugin_call = async ({ params }) => { - await exportGate - return { ok: true, success: true, outputPath: params.outputPath, text: 'ok text' } - } - - const view = await mount(PdfCommand, host) - await tick(10) - - // 导入 2 个文件 - await view.tree().props.filterBar.props.actions[1].onAction() - await tick(15) - assert.deepEqual(subItems(view).map(i => i.props.title), ['one.pdf', 'two.pdf']) - - // 从列表移除 one.pdf,磁盘文件必须保留 - await view.run(subItems(view)[0], '从列表移除') - await tick(5) - assert.deepEqual(subItems(view).map(i => i.props.title), ['two.pdf']) - assert.equal(fs.existsSync(onePath), true, '从列表移除绝不能删除磁盘文件') - - // 导出进行中:不显示「从列表移除」,点击「清空列表」被拒绝 - const runAction = view.actions(subItems(view)[0]).find(a => a.props.title.startsWith('导出已勾选')) - const runningPromise = runAction.props.onAction() - await tick(5) - assert.equal(view.actions(subItems(view)[0]).some(a => a.props.title === '从列表移除'), false) - await view.run(subItems(view)[0], '清空列表') - assert.equal(host.lastToast().style, 'FAILURE') - assert.equal(host.lastToast().title, '正在处理,完成后再清空') - assert.equal(subItems(view).length, 1) - - releaseExport() - await runningPromise - await tick(10) - - // 空闲后清空列表:清空列表与上次结果,不碰磁盘文件 - await view.run(subItems(view)[0], '清空列表') - await tick(5) - assert.equal(subItems(view).length, 0) - assert.equal(view.tree().props.workbenchPanel.previewCard.subtitle, '尚未导出') - assert.equal(fs.existsSync(twoPath), true) - - // 导入进行中清空列表:异步导入返回后结果被丢弃,不加入列表也不弹 Toast - let releaseDir - const dirGate = new Promise(r => (releaseDir = r)) - host.ipc.window_show_select_folder_dialog = async () => ({ canceled: false, folderPath: 'D:\\SlowDir' }) - host.ipc.filesystem_get_directory_contents = async () => { - await dirGate - return { - success: true, - files: [{ name: 'late.pdf', size: 2048, isDirectory: false, lastModified: '2026-10-01T00:00:00Z' }] - } - } - const importPromise = view.tree().props.filterBar.props.actions[1].onAction() - await tick(5) - assert.match(view.tree().props.filterBar.props.summaryText, /正在导入/) - - // 提前模拟先有一项在列表中或直接触发清空(把清空动作从临时再加项或直接检查未加项——先放入 one.pdf 以便拿到动作面板的清空列表) - releaseDir() - await importPromise - await tick(10) - assert.equal(subItems(view).length, 1) - - // 真正构造「列表有项时发起异步导入 -> 导入途中点清空 -> 导入完成结果被丢弃」 - let releaseSlow - const slowGate = new Promise(r => (releaseSlow = r)) - host.ipc.filesystem_get_directory_contents = async () => { - await slowGate - return { - success: true, - files: [{ name: 'stale.pdf', size: 2048, isDirectory: false, lastModified: '2026-10-01T00:00:00Z' }] - } - } - const slowPromise = view.tree().props.filterBar.props.actions[1].onAction() - await tick(5) - const toastCountAtImportStart = host.toasts.length - await view.run(subItems(view)[0], '清空列表') - await tick(5) - assert.equal(subItems(view).length, 0) - releaseSlow() - await slowPromise - await tick(10) - assert.equal(subItems(view).length, 0, '导入途中清空后,过期导入结果必须丢弃') - assert.equal(host.toasts.length, toastCountAtImportStart, '过期导入结果不应弹 Toast') - view.unmount() - } finally { - fs.rmSync(root, { recursive: true, force: true }) } }) - -test('导出核心业务:未勾选导出当前 PDF 重名加序号、批量部分失败如实提示、重复触发防护与打开失败提示', async () => { - const host = createHost() - host.ipc.filesystem_get_file_size = async () => ({ success: true, size: 400000 }) - host.ipc.window_show_open_dialog = async () => ({ - canceled: false, - filePaths: ['D:\\Docs\\report.pdf', 'D:\\Docs\\Scans\\scan.pdf'] - }) - host.ipc.filesystem_file_exists = async ({ path: p }) => ({ - success: true, - exists: p === 'D:\\Docs\\report.txt' - }) - - let releaseSlow - const slowGate = new Promise(r => (releaseSlow = r)) - let blockSlow = false - host.ipc.dllplugin_call = async ({ params }) => { - if (blockSlow) await slowGate - if (params.inputPath.endsWith('scan.pdf')) { - return { ok: false, success: false, error: '未能从 PDF 中提取到文字:可能是扫描件' } - } - return { ok: true, success: true, outputPath: params.outputPath, text: 'Annual report text' } - } - - const view = await mount(PdfCommand, host) - await tick(10) - await view.tree().props.filterBar.props.actions[0].onAction() - await tick(10) - - // 取消全选,测试未勾选时主动作「导出当前 PDF」 - view.tree().props.subList.onCheckChange(false) - await tick() - await view.run(subItems(view)[0], '导出当前 PDF') - await tick(10) - - const dll = host.ipcCalls.filter(([m]) => m === 'dllplugin_call') - assert.equal(dll.length, 1) - assert.equal(dll[0][1].params.outputPath, 'D:\\Docs\\report (1).txt') - assert.equal(host.lastToast().style, 'SUCCESS') - assert.equal(host.lastToast().title, '已导出 1 个文件') - assert.ok(subItems(view)[0].props.accessories.some(a => a.tag?.value === '已导出')) - assert.ok(view.actions(subItems(view)[0]).some(a => a.props.title === '在文件夹中显示上次输出')) - - // 打开文件失败提示 - await view.run(subItems(view)[0], '用默认程序打开 PDF') - assert.equal(host.lastToast().title, '无法打开文件') - assert.equal(host.lastToast().style, 'FAILURE') - - // 全部勾选批量导出:部分失败按失败提示并给出原因 - view.tree().props.subList.onCheckChange(true) - await tick() - await view.run(subItems(view)[0], '导出已勾选的 2 个 PDF') - await tick(10) - assert.equal(host.lastToast().style, 'FAILURE') - assert.equal(host.lastToast().title, '1 个已导出,1 个失败') - assert.match(host.lastToast().message, /scan\.pdf:.*扫描件/) - assert.ok(subItems(view).find(i => i.props.title === 'scan.pdf').props.accessories.some(a => a.tag?.value === '导出失败')) - - // 导出进行中再次触发:提示稍候,不重复调用客户端 - blockSlow = true - const action = view.actions(subItems(view)[0]).find(a => a.props.title.startsWith('导出已勾选')) - const beforeDll = host.ipcCalls.filter(([m]) => m === 'dllplugin_call').length - const p1 = action.props.onAction() - await tick(5) - await action.props.onAction() - assert.equal(host.lastToast().title, '上一批还在导出,请稍候') - releaseSlow() - await p1 - await tick(10) - // 第二个文件 scan.pdf 也会在 p1 内串行调用一次 - assert.equal(host.ipcCalls.filter(([m]) => m === 'dllplugin_call').length, beforeDll + 2) - - // 授权过期时输出检查失败友好提示 - host.ipc.filesystem_file_exists = async () => { - throw new Error('路径未由当前窗口授权') - } - await view.run(subItems(view)[0], '仅导出当前 PDF') - await tick(10) - assert.equal(host.lastToast().style, 'FAILURE') - assert.match(host.lastToast().message, /文件授权已过期或未授权/) - - view.unmount() -}) diff --git a/extensions/pomodoro-focus/README.en.md b/extensions/pomodoro-focus/README.en.md new file mode 100644 index 00000000..376bd42a --- /dev/null +++ b/extensions/pomodoro-focus/README.en.md @@ -0,0 +1,22 @@ +# Pomodoro & Countdown + +25-minute Pomodoro focus timer paired with locally saved countdowns for important events, paydays, launch dates, and deadlines. + +## Usage + +- Commands: `pomodoro`, `focus`, `countdown`; `start focus` (`start pomodoro`) immediately starts a focus round while keeping any active or paused timer; `new countdown` (`add countdown`) opens the creation form directly. +- Select the Pomodoro item and press `Enter` to start, pause, or resume, or `Cmd/Ctrl+Enter` to cancel the active timer. +- Each 25-minute focus session automatically transitions into a 5-minute short break, or a 15-minute long break after every 4 completed rounds; when a break ends, start the next round manually. +- Timing is managed by the ZTools client and continues after you leave the plugin page; reopening ZTools restores state from the target end time and settles only the current elapsed round without backfilling extra focus counts. Notifications do not fire while the client is closed. +- Click "New Countdown" at the top to enter a title, date (`YYYY-MM-DD`), and category (Work, Finance, Life), with optional monthly recurrence that automatically adapts to 28-, 29-, 30-, and 31-day months. Press `Enter` on a countdown to edit, `Cmd/Ctrl+Enter` to copy a days-remaining summary, or use `Cmd/Ctrl+K` to delete (asks for confirmation). +- Storage read errors display a warning and preserve existing records instead of treating the state as a first launch; if countdowns were modified in another window, refresh before making changes. + +## Platforms & Requirements + +- Supported: Windows, macOS +- Requires ZTools 1.1.8.5 or later. +- Sends system notifications when focus and break timers finish; visibility depends on your OS notification permissions and Do Not Disturb settings. + +## Network & Data + +- Works offline; data stays strictly on your local device. diff --git a/extensions/pomodoro-focus/plugin.json b/extensions/pomodoro-focus/plugin.json index ec153120..32db2742 100644 --- a/extensions/pomodoro-focus/plugin.json +++ b/extensions/pomodoro-focus/plugin.json @@ -1,7 +1,7 @@ { "id": "pomodoro-focus", "name": "番茄倒数", - "version": "1.0.6", + "version": "1.0.7", "description": "25 分钟番茄专注与短长休息,离页继续计时、重启恢复状态;本地保存重要日程倒数日并发送系统通知", "author": "ZTools Team", "category": [ @@ -72,7 +72,11 @@ "timer", "countdown", "productivity", - "break" + "break", + "alarm", + "stopwatch", + "productivity timer", + "work timer" ], "features": { "pomodoro-main": { @@ -115,5 +119,17 @@ { "path": "screenshots/02-action-panel.png" } + ], + "keywords": [ + "番茄钟", + "倒计时", + "专注", + "计时器", + "定时提醒", + "番茄工作法", + "倒数计时", + "专注计时", + "timer", + "pomodoro" ] } diff --git a/extensions/port-manager/README.md b/extensions/port-manager/README.md new file mode 100644 index 00000000..52f9e733 --- /dev/null +++ b/extensions/port-manager/README.md @@ -0,0 +1,3 @@ +# 端口占用 + +已下架:已合并至「进程监控」插件,请在插件市场安装进程监控。 diff --git a/extensions/port-manager/package.json b/extensions/port-manager/package.json index e96cbe7e..efccbc15 100644 --- a/extensions/port-manager/package.json +++ b/extensions/port-manager/package.json @@ -1,6 +1,6 @@ { "name": "@ztools/plugin-port-manager", - "version": "1.0.0", + "version": "1.0.7", "description": "本地端口占用检测与释放管理器", "main": "dist/index.js", "types": "dist/index.d.ts", diff --git a/extensions/port-manager/plugin.json b/extensions/port-manager/plugin.json index 6648fb79..6096a6f3 100644 --- a/extensions/port-manager/plugin.json +++ b/extensions/port-manager/plugin.json @@ -2,7 +2,8 @@ "id": "port-manager", "name": "端口占用", "description": "本地网络端口占用扫描、进程关联与快速释放", - "version": "1.0.4", + "version": "1.0.7", + "minAppVersion": "1.1.8.0", "revoked": true, "revokedReason": "已合并至「进程监控」插件,请在插件市场安装进程监控", "author": "ZTools Team", @@ -28,5 +29,14 @@ "arch": "any" } ], - "nativeComponents": [] + "nativeComponents": [], + "categoryId": "system", + "defaultLocale": "zh-CN", + "i18n": { + "en-US": { + "name": "Port Manager", + "description": "Scan local network port usage, inspect bound processes, and release ports quickly.", + "revokedReason": "Merged into the \"Process Monitor\" plugin. Please install Process Monitor from the Plugin Store." + } + } } diff --git a/extensions/port-manager/src/native-ipc.ts b/extensions/port-manager/src/native-ipc.ts index e3976587..b8c547d6 100644 --- a/extensions/port-manager/src/native-ipc.ts +++ b/extensions/port-manager/src/native-ipc.ts @@ -1,4 +1,102 @@ +import { getLocale } from '@ztools/declarative-ui' + type DynamicBridge = ReturnType + +const NATIVE_IPC_MESSAGES: Record string + dirEntrySep: string + dirErrorColon: string + deepScanUnavailable: string + pathEmpty: string + invalidMethodEmpty: string + invalidMethodFormat: string + invalidParamsObject: string + paramTooLong: (key: string) => string + paramOutOfRange: (key: string) => string + methodParamEmpty: string + invalidMethodType: string + malformedDllResponse: string + unknownDllError: string + hostIpcFailed: (pluginName: string, method: string) => string + hostUnavailable: (pluginName: string, method: string) => string + callFailed: string + movedToTrash: string + deleteFailed: string + revealedInFolder: string + revealFailed: string + opened: string + openFailed: string + pluginCallNotReady: string +}> = { + 'zh-CN': { + ipcCallFailed: 'IPC 调用返回失败', + ipcInnerFailed: 'IPC 内部调用失败', + scanIncomplete: '扫描结果不完整', + dirReadFailed: (details, moreCount) => + `目录读取失败或不完整:${details}${moreCount > 0 ? `;另有 ${moreCount} 个目录` : ''}`, + dirEntrySep: ';', + dirErrorColon: ':', + deepScanUnavailable: '深度扫描不可用,仅列出一级目录,结果不完整', + pathEmpty: '路径不能为空', + invalidMethodEmpty: 'INVALID_METHOD: 调用方法名不能为空', + invalidMethodFormat: 'INVALID_METHOD_FORMAT: 方法名包含非法字符或超长', + invalidParamsObject: 'INVALID_PARAMS: 参数必须为非空对象', + paramTooLong: (key) => `PARAM_TOO_LONG: 参数 ${key} 超过最大长度限制`, + paramOutOfRange: (key) => `PARAM_OUT_OF_RANGE: 数值参数 ${key} 越界或非有限数`, + methodParamEmpty: 'method 参数不能为空', + invalidMethodType: 'INVALID_METHOD: method 不能为空且必须为字符串', + malformedDllResponse: 'MALFORMED_DLL_RESPONSE: 原生组件返回了损坏的 JSON 数据', + unknownDllError: '原生组件返回未知错误', + hostIpcFailed: (pluginName, method) => `HOST_IPC_FAILED: ${pluginName}.${method} 调用失败`, + hostUnavailable: (pluginName, method) => `HOST_UNAVAILABLE: ${pluginName}.${method} 宿主接口未就绪`, + callFailed: '调用失败', + movedToTrash: '已移入回收站', + deleteFailed: '删除失败', + revealedInFolder: '已定位文件', + revealFailed: '定位失败', + opened: '已打开', + openFailed: '打开失败', + pluginCallNotReady: '插件调用未就绪' + }, + 'en-US': { + ipcCallFailed: 'IPC call failed', + ipcInnerFailed: 'Internal IPC call failed', + scanIncomplete: 'Incomplete scan results', + dirReadFailed: (details, moreCount) => + `Directory read failed or incomplete: ${details}${moreCount > 0 ? `; and ${moreCount} more` : ''}`, + dirEntrySep: '; ', + dirErrorColon: ': ', + deepScanUnavailable: 'Deep scan unavailable; only top-level directory listed (incomplete)', + pathEmpty: 'Path cannot be empty', + invalidMethodEmpty: 'INVALID_METHOD: Method name cannot be empty', + invalidMethodFormat: 'INVALID_METHOD_FORMAT: Method name contains invalid characters or is too long', + invalidParamsObject: 'INVALID_PARAMS: Parameters must be a non-null object', + paramTooLong: (key) => `PARAM_TOO_LONG: Parameter "${key}" exceeds maximum length`, + paramOutOfRange: (key) => `PARAM_OUT_OF_RANGE: Numeric parameter "${key}" is out of range or non-finite`, + methodParamEmpty: 'Method parameter cannot be empty', + invalidMethodType: 'INVALID_METHOD: Method must be a non-empty string', + malformedDllResponse: 'MALFORMED_DLL_RESPONSE: Native component returned malformed JSON', + unknownDllError: 'Native component returned an unknown error', + hostIpcFailed: (pluginName, method) => `HOST_IPC_FAILED: ${pluginName}.${method} call failed`, + hostUnavailable: (pluginName, method) => `HOST_UNAVAILABLE: ${pluginName}.${method} host interface not ready`, + callFailed: 'Call failed', + movedToTrash: 'Moved to Trash', + deleteFailed: 'Delete failed', + revealedInFolder: 'Revealed in folder', + revealFailed: 'Failed to reveal item', + opened: 'Opened', + openFailed: 'Failed to open', + pluginCallNotReady: 'Plugin invocation not ready' + } +} + +function ipcStrings() { + const locale = getLocale() + return NATIVE_IPC_MESSAGES[locale] ?? NATIVE_IPC_MESSAGES['en-US'] +} /** * ZTools 真实宿主 IPC 与系统能力桥接层 (Real Host IPC Bridge) * @@ -76,11 +174,13 @@ function normalizeMethodResult(method: string, payload: DynamicBridge): DynamicB if (method === 'system_get_battery_status') { // 宿主约定 percent 超出 0-100(如 255)表示无电池或电量未知,不能改写成 100% + // 若宿主明确给出 hasBattery 布尔值,必须原样保留,仅在缺失时按合法电量推算 const rawPct = payload.percent - const hasBattery = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const validPct = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const hasBattery = typeof payload.hasBattery === 'boolean' ? payload.hasBattery : validPct return { ...payload, - percent: hasBattery ? rawPct : null, + percent: validPct ? rawPct : null, hasBattery } } @@ -100,9 +200,35 @@ function normalizeMethodResult(method: string, payload: DynamicBridge): DynamicB return payload } -function unwrapTransportResponse(method: string, raw: DynamicBridge): { ok: boolean; data?: DynamicBridge; error?: string } { +function extractIpcErrorMeta(errObj: DynamicBridge): { + errorCode?: string + errorDetails?: Record +} { + if (!errObj || typeof errObj !== 'object') return {} + const errorCode = + typeof errObj.errorCode === 'string' && errObj.errorCode.trim() + ? errObj.errorCode.trim() + : typeof errObj.code === 'string' && errObj.code.trim() + ? errObj.code.trim() + : undefined + const rawDetails = + errObj.errorDetails && typeof errObj.errorDetails === 'object' && !Array.isArray(errObj.errorDetails) + ? (errObj.errorDetails as Record) + : errObj.details && typeof errObj.details === 'object' && !Array.isArray(errObj.details) + ? (errObj.details as Record) + : undefined + return { + ...(errorCode ? { errorCode } : {}), + ...(rawDetails ? { errorDetails: rawDetails } : {}) + } +} + +function unwrapTransportResponse( + method: string, + raw: DynamicBridge +): { ok: boolean; data?: DynamicBridge; error?: string; errorCode?: string; errorDetails?: Record } { if (raw === null || raw === undefined) { - return { ok: false, error: 'EMPTY_IPC_RESPONSE' } + return { ok: false, error: 'EMPTY_IPC_RESPONSE', errorCode: 'EMPTY_IPC_RESPONSE' } } if (typeof raw !== 'object') { return { ok: true, data: raw } @@ -112,8 +238,8 @@ function unwrapTransportResponse(method: string, raw: DynamicBridge): { ok: bool const errMsg = typeof errObj === 'object' && errObj !== null ? String(errObj.message || errObj.code || JSON.stringify(errObj)) - : String(errObj || 'IPC 调用返回失败') - return { ok: false, error: errMsg } + : String(errObj || ipcStrings().ipcCallFailed) + return { ok: false, error: errMsg, ...extractIpcErrorMeta(raw), ...extractIpcErrorMeta(errObj) } } const firstLayer = 'data' in raw && raw.data !== undefined ? raw.data : raw @@ -123,8 +249,8 @@ function unwrapTransportResponse(method: string, raw: DynamicBridge): { ok: bool const errMsg = typeof errObj === 'object' && errObj !== null ? String(errObj.message || errObj.code || JSON.stringify(errObj)) - : String(errObj || 'IPC 内部调用失败') - return { ok: false, error: errMsg } + : String(errObj || ipcStrings().ipcInnerFailed) + return { ok: false, error: errMsg, ...extractIpcErrorMeta(firstLayer), ...extractIpcErrorMeta(errObj) } } if ('data' in firstLayer && firstLayer.data !== undefined) { return { ok: true, data: normalizeMethodResult(method, firstLayer.data) } @@ -141,7 +267,7 @@ export async function callHostTransport( method: string, params: Record = {}, hostOverride?: DynamicBridge -): Promise<{ ok: boolean; data?: T; error?: string }> { +): Promise<{ ok: boolean; data?: T; error?: string; errorCode?: string; errorDetails?: Record }> { const normalizedParams = normalizeMethodParams(method, params) // 1. 测试注入的 hostOverride 优先 @@ -150,24 +276,24 @@ export async function callHostTransport( try { const res = await hostOverride[method](normalizedParams) const unwrapped = unwrapTransportResponse(method, res) - return unwrapped as { ok: boolean; data?: T; error?: string } + return unwrapped as { ok: boolean; data?: T; error?: string; errorCode?: string; errorDetails?: Record } } catch (err: DynamicBridge) { - return { ok: false, error: err instanceof Error ? err.message : String(err) } + return { ok: false, error: err instanceof Error ? err.message : String(err), ...extractIpcErrorMeta(err) } } } if (typeof hostOverride?.transport?.call === 'function') { try { const res = await hostOverride.transport.call(method, normalizedParams) const unwrapped = unwrapTransportResponse(method, res) - return unwrapped as { ok: boolean; data?: T; error?: string } + return unwrapped as { ok: boolean; data?: T; error?: string; errorCode?: string; errorDetails?: Record } } catch (err: DynamicBridge) { - return { ok: false, error: err instanceof Error ? err.message : String(err) } + return { ok: false, error: err instanceof Error ? err.message : String(err), ...extractIpcErrorMeta(err) } } } } if (typeof window === 'undefined') { - return { ok: false, error: 'NO_WINDOW_ENV' } + return { ok: false, error: 'NO_WINDOW_ENV', errorCode: 'NO_WINDOW_ENV' } } const w = window as DynamicBridge @@ -178,22 +304,22 @@ export async function callHostTransport( try { const messageId = nextMessageId(method.replace(/[^A-Za-z0-9_]/g, '_').slice(0, 24)) const raw = await fn({ messageId, params: normalizedParams }) - return unwrapTransportResponse(method, raw) as { ok: boolean; data?: T; error?: string } + return unwrapTransportResponse(method, raw) as { ok: boolean; data?: T; error?: string; errorCode?: string; errorDetails?: Record } } catch (err: DynamicBridge) { - return { ok: false, error: err instanceof Error ? err.message : String(err) } + return { ok: false, error: err instanceof Error ? err.message : String(err), ...extractIpcErrorMeta(err) } } } if (typeof w.ztools?.transport?.call === 'function') { try { const raw = await w.ztools.transport.call(method, normalizedParams) - return unwrapTransportResponse(method, raw) as { ok: boolean; data?: T; error?: string } + return unwrapTransportResponse(method, raw) as { ok: boolean; data?: T; error?: string; errorCode?: string; errorDetails?: Record } } catch (err: DynamicBridge) { - return { ok: false, error: err instanceof Error ? err.message : String(err) } + return { ok: false, error: err instanceof Error ? err.message : String(err), ...extractIpcErrorMeta(err) } } } - return { ok: false, error: `METHOD_NOT_AVAILABLE: ${method}` } + return { ok: false, error: `METHOD_NOT_AVAILABLE: ${method}`, errorCode: 'METHOD_NOT_AVAILABLE' } } export interface RealDiskDriveInfo { @@ -365,6 +491,8 @@ export interface RealDirectoryScanResult extends Iterable approximate?: boolean /** 宿主实际遍历的条目数 */ visitedEntries?: number + /** 读取失败的真实原因;已有文件仍可使用,但不能当作完整结果。 */ + error?: string } interface ScanResultMeta { @@ -433,7 +561,7 @@ function makeScanResult( } /** - * 调用本机 Rust NTFS MFT 硬件级索引引擎 (ztools-indexer) 毫秒级检索真实文件 + * 调用客户端的原生文件索引组件 (ztools-indexer) 检索文件 */ export async function searchRealIndexedFiles( query: string, @@ -479,7 +607,28 @@ export async function scanRealDirectoryTree( limitOrOptions: number | ScanDirectoryTreeOptions = 160, hostOverrideArg?: DynamicBridge ): Promise { - return (await scanDirectoryTreeWithError(dirPath, limitOrOptions, hostOverrideArg)).scan + const result = await scanDirectoryTreeWithError(dirPath, limitOrOptions, hostOverrideArg) + return result.error ? { ...result.scan, error: result.error } : result.scan +} + +/** 一次界面扫描的错误汇总;多个目录并行扫描时保留可读目录的结果。 */ +export function createDirectoryScanner(hostOverride?: DynamicBridge) { + const failures = new Map() + return { + async scan(dir: string, options: number | ScanDirectoryTreeOptions = 160) { + const result = await scanRealDirectoryTree(dir, options, hostOverride) + const error = result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') + if (error) failures.set(dir, error) + else failures.delete(dir) + return result + }, + get error(): string | undefined { + if (!failures.size) return undefined + const s = ipcStrings() + const details = [...failures].slice(0, 3).map(([dir, error]) => `${dir}${s.dirErrorColon}${error}`).join(s.dirEntrySep) + return s.dirReadFailed(details, Math.max(0, failures.size - 3)) + } + } } /** scanRealDirectoryTree 的实现:额外带回读取失败原因(目录不存在 / 为空 / 无权限 / 载荷异常) */ @@ -526,10 +675,7 @@ async function scanDirectoryTreeWithError( if ( rawPayload && - Array.isArray(rawPayload.files) && - (rawPayload.files.length > 0 || - Number(rawPayload.total_matches || 0) > 0 || - (Array.isArray(rawPayload.subdirs) && rawPayload.subdirs.length > 0)) + Array.isArray(rawPayload.files) ) { let files: RealIndexedFileEntry[] = rawPayload.files.map(normalizeIndexedFileEntry) if (filterExt instanceof RegExp) { @@ -581,11 +727,12 @@ async function scanDirectoryTreeWithError( truncated: rawPayload.truncated === true, approximate: rawPayload.approximate === true, ...(Number.isFinite(visited) && visited >= 0 ? { visitedEntries: visited } : {}) - }) + }), + ...(typeof rawPayload.scan_error === 'string' && rawPayload.scan_error ? { error: rawPayload.scan_error } : {}) } } - // dir: 扫描无结果(目录不存在 / 为空 / 测试替身未实现)时,退回 filesystem_get_directory_contents 读取一级目录 + // 深度扫描失败或回执无效时,仅以一级目录读取补回可见结果;不冒充完整目录树。 const listing = await listDirectoryViaFilesystem(targetDir, hostOverride, { withSizes: true, limit: safeLimit }) if (listing.ok && listing.entries.length > 0) { const files: RealIndexedFileEntry[] = [] @@ -597,14 +744,16 @@ async function scanDirectoryTreeWithError( files.push(entry) totalBytes += entry.isDir ? 0 : entry.size } - return { scan: makeScanResult(files, files.length, totalBytes, []) } + const incomplete = listing.entries.some(entry => entry.isDir) || listing.entries.length >= safeLimit + return { + scan: makeScanResult(files, files.filter(file => !file.isDir).length, totalBytes, [], { approximate: incomplete }), + ...(incomplete ? { error: res.error || ipcStrings().deepScanUnavailable } : {}) + } } - return { scan: empty, error: listing.ok ? DIRECTORY_EMPTY_OR_UNREADABLE : listing.error } - } catch { - // ignore + return listing.ok ? { scan: empty } : { scan: empty, error: listing.error || 'DIRECTORY_READ_FAILED' } + } catch (error) { + return { scan: empty, error: error instanceof Error ? error.message : String(error) } } - - return { scan: empty, error: DIRECTORY_EMPTY_OR_UNREADABLE } } @@ -816,7 +965,7 @@ export async function listDirectChildren( } /** - * 获取真实文件字节大小(优先命中 MFT 硬件级索引实时缓存,再走 filesystem_get_file_size) + * 获取真实文件字节大小(优先用扫描结果里的大小,再走 filesystem_get_file_size);读不到时返回 0 */ export async function getRealFileSize( filePath: string, @@ -827,16 +976,19 @@ export async function getRealFileSize( const cached = realFileSizeCache.get(filePath)! if (cached > 0) return cached } - const res = await callHostTransport('filesystem_get_file_size', { path: filePath }, hostOverride) - if (res.ok && typeof res.data === 'number' && Number.isFinite(res.data) && res.data >= 0) { - realFileSizeCache.set(filePath, res.data) - return res.data + const res = await callHostTransport('filesystem_get_file_size', { path: filePath }, hostOverride) + // 客户端返回 { success, size }(目录时 size 为 -1),旧的测试替身直接返回数字 + const size = typeof res.data === 'number' ? res.data : res.data?.size + if (res.ok && typeof size === 'number' && Number.isFinite(size) && size >= 0) { + realFileSizeCache.set(filePath, size) + return size } return 0 } /** - * 在 Windows Explorer 中定位并高亮文件/目录 + * 在访达 / 资源管理器中定位并高亮文件或目录。 + * 定位失败直接返回 false,不能改用“打开”:对可执行文件那等于运行它。 */ export async function showRealItemInFolder( fullPath: string, @@ -844,9 +996,7 @@ export async function showRealItemInFolder( ): Promise { if (!fullPath) return false const res = await callHostTransport('shell_show_item_in_folder', { fullPath }, hostOverride) - if (res.ok) return true - const fallback = await callHostTransport('shell_open_path', { fullPath }, hostOverride) - return fallback.ok + return res.ok } /** @@ -867,10 +1017,15 @@ export async function openRealPath( export async function trashRealItem( fullPath: string, hostOverride?: DynamicBridge -): Promise<{ ok: boolean; error?: string }> { - if (!fullPath) return { ok: false, error: '路径不能为空' } +): Promise<{ ok: boolean; error?: string; errorCode?: string; errorDetails?: Record }> { + if (!fullPath) return { ok: false, error: ipcStrings().pathEmpty } const res = await callHostTransport('shell_trash_item', { fullPath }, hostOverride) - return { ok: res.ok, error: res.error } + return { + ok: res.ok, + error: res.error, + ...(!res.ok && res.errorCode ? { errorCode: res.errorCode } : {}), + ...(!res.ok && res.errorDetails ? { errorDetails: res.errorDetails } : {}) + } } export interface NativeInvocationResult { @@ -879,6 +1034,8 @@ export interface NativeInvocationResult { message: string data?: T error?: string + errorCode?: string + errorDetails?: Record } export interface DllCapabilityResponse { @@ -887,11 +1044,64 @@ export interface DllCapabilityResponse { data: T | null message?: string error?: string + errorCode?: string + errorDetails?: Record pluginName: string method: string fromFallback?: boolean } +/** 声明式能力菜单项及其调用回执,供相同宿主协议的插件共用。 */ +export interface CapabilityActionItem { + id: string + title: string + subtitle: string + tag: string + method: string + params: Record +} + +export type PluginInvocationResult = Pick< + DllCapabilityResponse, 'ok' | 'pluginName' | 'method' | 'error' | 'errorCode' | 'errorDetails' | 'fromFallback' +> & { data?: unknown } + +/** 多个原生能力插件共用的参数边界校验;保护目标由各插件按自身业务提供。 */ +export function validateNativeCapabilityPayload( + method: string, + params: unknown, + forbiddenPattern: RegExp, + forbiddenReason: string +): { valid: boolean; error?: string } { + const s = ipcStrings() + if (typeof method !== 'string' || method.trim().length === 0) { + return { valid: false, error: s.invalidMethodEmpty } + } + if (method.length > 128 || !/^[A-Za-z0-9_]+$/.test(method.trim())) { + return { valid: false, error: s.invalidMethodFormat } + } + if (params === null || params === undefined || typeof params !== 'object' || Array.isArray(params)) { + return { valid: false, error: s.invalidParamsObject } + } + + const record = params as Record + for (const [key, val] of Object.entries(record)) { + if (typeof val === 'string') { + if (val.length > 4096) { + return { valid: false, error: s.paramTooLong(key) } + } + if (forbiddenPattern.test(val)) { + return { valid: false, error: `SECURITY_INTERCEPTED: ${forbiddenReason}` } + } + } else if (typeof val === 'number') { + if (!Number.isFinite(val) || val < -1000 || val > 100_000_000) { + return { valid: false, error: s.paramOutOfRange(key) } + } + } + } + + return { valid: true } +} + export async function invokeDllPluginCapability( pluginName: string, method: string, @@ -899,13 +1109,14 @@ export async function invokeDllPluginCapability( hostBridge?: DynamicBridge, offlineFallback?: () => T | Promise ): Promise> { + const s = ipcStrings() if (!method || typeof method !== 'string' || method.trim().length === 0) { return { ok: false, code: -1, data: null, - message: 'method 参数不能为空', - error: 'INVALID_METHOD: method 不能为空且必须为字符串', + message: s.methodParamEmpty, + error: s.invalidMethodType, pluginName, method: String(method || '') } @@ -919,7 +1130,7 @@ export async function invokeDllPluginCapability( try { parsed = JSON.parse(raw) } catch { - throw new Error('MALFORMED_DLL_RESPONSE: 原生组件返回了损坏的 JSON 数据') + throw new Error(s.malformedDllResponse) } } if (parsed && typeof parsed === 'object') { @@ -931,19 +1142,23 @@ export async function invokeDllPluginCapability( data: null, message: errMsg, error: errMsg, + ...extractIpcErrorMeta(parsed), + ...extractIpcErrorMeta(parsed.error), pluginName, method: trimmedMethod, fromFallback: false } } if ('ok' in parsed && parsed.ok === false) { - const errMsg = `DLL_ERROR: ${String(parsed.error || parsed.message || '原生组件返回未知错误')}` + const errMsg = `DLL_ERROR: ${String(parsed.error || parsed.message || s.unknownDllError)}` return { ok: false, code: typeof parsed.code === 'number' ? parsed.code : -1, data: null, message: errMsg, error: errMsg, + ...extractIpcErrorMeta(parsed), + ...extractIpcErrorMeta(parsed.error), pluginName, method: trimmedMethod, fromFallback: false @@ -982,6 +1197,7 @@ export async function invokeDllPluginCapability( data: null, message: errMsg, error: errMsg, + ...extractIpcErrorMeta(err), pluginName, method: trimmedMethod, fromFallback: false @@ -1038,13 +1254,15 @@ export async function invokeDllPluginCapability( isExplicitTransportFailure ) { const errMsg = - ipcRes.error || `HOST_IPC_FAILED: ${pluginName}.${trimmedMethod} 调用失败` + ipcRes.error || s.hostIpcFailed(pluginName, trimmedMethod) return { ok: false, code: -1, data: null, message: errMsg, error: errMsg, + ...(ipcRes.errorCode ? { errorCode: ipcRes.errorCode } : {}), + ...(ipcRes.errorDetails ? { errorDetails: ipcRes.errorDetails } : {}), pluginName, method: trimmedMethod, fromFallback: false @@ -1063,13 +1281,15 @@ export async function invokeDllPluginCapability( } } - const unavailableMsg = `HOST_UNAVAILABLE: ${pluginName}.${trimmedMethod} 宿主接口未就绪` + const unavailableMsg = s.hostUnavailable(pluginName, trimmedMethod) return { ok: false, code: -1, data: null, message: unavailableMsg, error: unavailableMsg, + ...(ipcRes.errorCode ? { errorCode: ipcRes.errorCode } : {}), + ...(ipcRes.errorDetails ? { errorDetails: ipcRes.errorDetails } : {}), pluginName, method: trimmedMethod, fromFallback: true @@ -1244,9 +1464,11 @@ export async function invokeHostCapability( return { ok: mockRes.ok, code: mockRes.ok ? 0 : -1, - message: mockRes.ok ? 'OK' : mockRes.error || '调用失败', + message: mockRes.ok ? 'OK' : mockRes.error || ipcStrings().callFailed, data: mockRes.data, - error: mockRes.error + error: mockRes.error, + ...(!mockRes.ok && mockRes.errorCode ? { errorCode: mockRes.errorCode } : {}), + ...(!mockRes.ok && mockRes.errorDetails ? { errorDetails: mockRes.errorDetails } : {}) } } @@ -1273,17 +1495,31 @@ export async function invokeHostCapability( if (capability === 'filesystem.deleteItem') { const targetPath = String(params.path || params.fullPath || '') const tr = await trashRealItem(targetPath, hostOverride) + const s = ipcStrings() return { ok: tr.ok, code: tr.ok ? 0 : -1, - message: tr.ok ? '已移入回收站' : tr.error || '删除失败', - error: tr.error + message: tr.ok ? s.movedToTrash : tr.error || s.deleteFailed, + error: tr.error, + ...(!tr.ok && tr.errorCode ? { errorCode: tr.errorCode } : {}), + ...(!tr.ok && tr.errorDetails ? { errorDetails: tr.errorDetails } : {}) } } if (capability === 'system.showItemInFolder') { const targetPath = String(params.path || params.fullPath || '') - const ok = await showRealItemInFolder(targetPath, hostOverride) - return { ok, code: ok ? 0 : -1, message: ok ? '已定位文件' : '定位失败' } + const s = ipcStrings() + if (!targetPath) { + return { ok: false, code: -1, message: s.revealFailed } + } + const res = await callHostTransport('shell_show_item_in_folder', { fullPath: targetPath }, hostOverride) + return { + ok: res.ok, + code: res.ok ? 0 : -1, + message: res.ok ? s.revealedInFolder : res.error || s.revealFailed, + ...(!res.ok && res.error ? { error: res.error } : {}), + ...(!res.ok && res.errorCode ? { errorCode: res.errorCode } : {}), + ...(!res.ok && res.errorDetails ? { errorDetails: res.errorDetails } : {}) + } } if (capability === 'filesystem.openItem' || capability === 'system.openUrl') { const target = String(params.path || params.url || params.fullPath || '') @@ -1293,12 +1529,15 @@ export async function invokeHostCapability( capability === 'system.openUrl' ? { url: target } : { fullPath: target }, hostOverride ) + const s = ipcStrings() return { ok: res.ok, code: res.ok ? 0 : -1, - message: res.ok ? '已打开' : res.error || '打开失败', + message: res.ok ? s.opened : res.error || s.openFailed, data: res.data, - error: res.error + error: res.error, + ...(!res.ok && res.errorCode ? { errorCode: res.errorCode } : {}), + ...(!res.ok && res.errorDetails ? { errorDetails: res.errorDetails } : {}) } } @@ -1329,9 +1568,11 @@ export async function invokeHostCapability( return { ok: res.ok, code: res.ok ? 0 : -1, - message: res.ok ? 'OK' : res.error || '调用失败', + message: res.ok ? 'OK' : res.error || ipcStrings().callFailed, data: res.data, - error: res.error + error: res.error, + ...(!res.ok && res.errorCode ? { errorCode: res.errorCode } : {}), + ...(!res.ok && res.errorDetails ? { errorDetails: res.errorDetails } : {}) } } @@ -1341,6 +1582,7 @@ export async function invokePluginService( params: Record = {}, hostOverride?: DynamicBridge ): Promise> { + const s = ipcStrings() // 1. 若测试注入了专门拦截 plugin_invoke 的 mock,支持调用 if (hostOverride && typeof hostOverride.plugin_invoke === 'function') { const mockRes = await callHostTransport( @@ -1351,9 +1593,11 @@ export async function invokePluginService( return { ok: mockRes.ok, code: mockRes.ok ? 0 : -1, - message: mockRes.ok ? 'OK' : mockRes.error || '插件调用未就绪', + message: mockRes.ok ? 'OK' : mockRes.error || s.pluginCallNotReady, data: mockRes.data, - error: mockRes.error + error: mockRes.error, + ...(!mockRes.ok && mockRes.errorCode ? { errorCode: mockRes.errorCode } : {}), + ...(!mockRes.ok && mockRes.errorDetails ? { errorDetails: mockRes.errorDetails } : {}) } } @@ -1370,7 +1614,8 @@ export async function invokePluginService( ok: false, code: -1, message: inner.error, - error: inner.error + error: inner.error, + ...extractIpcErrorMeta(inner) } } return { @@ -1407,8 +1652,10 @@ export async function invokePluginService( return { ok: false, code: -1, - message: String(raw.error || '调用失败'), - error: String(raw.error || '调用失败') + message: String(raw.error || s.callFailed), + error: String(raw.error || s.callFailed), + ...extractIpcErrorMeta(raw), + ...extractIpcErrorMeta(raw.error) } } const data = raw && typeof raw === 'object' && 'data' in raw ? raw.data : raw @@ -1418,7 +1665,8 @@ export async function invokePluginService( ok: false, code: -1, message: err instanceof Error ? err.message : String(err), - error: err instanceof Error ? err.message : String(err) + error: err instanceof Error ? err.message : String(err), + ...extractIpcErrorMeta(err) } } } @@ -1426,8 +1674,10 @@ export async function invokePluginService( return { ok: false, code: -1, - message: dllRes.error || '插件调用未就绪', - error: dllRes.error || '插件调用未就绪' + message: dllRes.error || s.pluginCallNotReady, + error: dllRes.error || s.pluginCallNotReady, + ...(dllRes.errorCode ? { errorCode: dllRes.errorCode } : {}), + ...(dllRes.errorDetails ? { errorDetails: dllRes.errorDetails } : {}) } } @@ -1569,8 +1819,6 @@ export async function writeRealClipboardText(text: string, hostOverride?: Dynami const payload = { text: String(text || '') } const res = await callHostTransport('clipboard_copy_text', payload, hostOverride) if (res.ok) return true - const fallbackRes = await callHostTransport('clipboard_write_text', payload, hostOverride) - if (fallbackRes.ok) return true try { if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) { await navigator.clipboard.writeText(String(text || '')) diff --git a/extensions/process-monitor/README.en.md b/extensions/process-monitor/README.en.md new file mode 100644 index 00000000..b61d3c04 --- /dev/null +++ b/extensions/process-monitor/README.en.md @@ -0,0 +1,21 @@ +# Process & Port Monitor + +Inspect CPU and memory usage of local processes, look up which process is using a port, terminate processes, or reveal executable files in folder. + +## Usage + +- Commands: `process monitor` (`kill process`, `task manager`, `high cpu`); port lookup: `port` (`port lookup`, `netstat`, `free port`). You can also enter `port:8080` in the search box to query a specific port. +- The list refreshes every 2 seconds by default; pause auto-refresh at the top or refresh manually (`Cmd/Ctrl+R`). Use the dropdown to sort by Memory, CPU, Name, or PID, or filter to High Load Processes, System Services, User Apps, or Local Port Usage. +- Select a process and press `Enter` to terminate it, or `Cmd/Ctrl+Enter` to force-kill the process tree (both ask for confirmation). `Cmd/Ctrl+K` also provides Graceful Close, Reveal File Location (`Cmd/Ctrl+O`), Copy PID (`Cmd/Ctrl+C`), Copy Executable Path (`Cmd/Ctrl+Shift+C`), Copy Launch Command Line (reports unavailable if not provided by the system), and View Digital Signature & Hosted Services (`Cmd/Ctrl+I`). +- Critical kernel and session management processes are protected and cannot be terminated; on macOS, terminating system UI processes such as Dock or Finder displays an extra warning. If a graceful close does not respond, a second confirmation is required before force-killing. +- Termination failures (such as insufficient permissions) report the failure reason. +- Port lookup: when no port is entered, lists only processes listening on TCP or bound to UDP local ports; entering a specific port matches all connections on that port. On macOS, if the system restricts port inspection to current-user processes, the status bar warns that ports used by system services may not appear. +- On macOS, per-process CPU usage matches Activity Monitor: 100% equals one core (multi-threaded apps can exceed 100%) using the system's roughly 1-minute smoothed average, while total CPU load at the top is calculated across all cores. macOS does not expose digital signatures, hosted services, or launch command lines, and those actions report unavailable accordingly. + +## Platforms & Requirements + +- Supported: Windows, macOS + +## Network & Data + +- Works offline; no data is saved. diff --git a/extensions/process-monitor/plugin.json b/extensions/process-monitor/plugin.json index e32d2626..e67e1fa3 100644 --- a/extensions/process-monitor/plugin.json +++ b/extensions/process-monitor/plugin.json @@ -2,7 +2,8 @@ "id": "process-monitor", "name": "进程监控", "description": "查看本机进程的 CPU 与内存占用、查询本地端口被哪个进程占用,可定位程序文件,确认后结束进程", - "version": "2.0.12", + "version": "2.0.13", + "minAppVersion": "1.1.8.0", "author": "ZTools Team", "entry": "dist/index.js", "icon": "icon.svg", @@ -15,13 +16,22 @@ "任务管理器", "结束进程", "杀进程", + "强杀", + "软件卡死", + "强制关闭", + "关不掉", + "杀掉程序", "端口占用", "查端口", "port", "process", "kill", "cpu", - "内存占用" + "内存占用", + "谁占了端口", + "cpu高", + "内存高", + "杀端口" ], "features": [ { @@ -31,10 +41,16 @@ "进程监控", "结束进程", "杀进程", + "强杀", + "强制关闭", + "软件卡死", + "关不掉", + "杀掉程序", "任务管理器", "卡死", "高cpu", - "内存占用" + "内存占用", + "kill" ] }, { @@ -83,10 +99,23 @@ "process", "port", "kill", + "terminate", + "kill process", + "end task", + "force quit", + "frozen app", + "kill app", + "stop process", "cpu", "memory", "netstat", - "task manager" + "task manager", + "process monitor", + "port lookup", + "kill port", + "top", + "pid", + "activity monitor" ], "features": { "kill-high-cpu": { @@ -94,6 +123,11 @@ "cmds": [ "process monitor", "kill process", + "end task", + "force quit", + "terminate", + "frozen app", + "stop process", "task manager", "high cpu" ] diff --git a/extensions/process-monitor/src/index.ts b/extensions/process-monitor/src/index.ts index 1eb19a6a..ca74c788 100644 --- a/extensions/process-monitor/src/index.ts +++ b/extensions/process-monitor/src/index.ts @@ -509,6 +509,63 @@ export default function ProcessMonitorCommand({ initialView = 'memory' }: { init const procServices = services[proc.pid] || [] const svcHint = procServices.length > 0 ? t('svcHint', { count: procServices.length }) : '' + const viewProfileAction = Action({ + title: t('actionViewProfile'), + icon: Icon.MagnifyingGlass, + shortcut: { modifiers: ['ctrl'], key: 'i' }, + onAction: () => handleShowProfile(proc) + }) + const locateDirAction = Action({ + title: t('actionLocateDir'), + icon: Icon.Folder, + shortcut: { modifiers: ['ctrl'], key: 'o' }, + onAction: () => handleOpenLocation(proc) + }) + const copyActions = [ + Action({ + title: t('actionCopyPid'), + icon: Icon.Key, + shortcut: { modifiers: ['ctrl'], key: 'c' }, + onAction: () => copyWithToast(String(proc.pid), t('copiedPidTitle'), String(proc.pid)) + }), + Action({ + title: t('actionCopyExecPath'), + icon: Icon.Document, + shortcut: { modifiers: ['ctrl', 'shift'], key: 'c' }, + onAction: () => { + const targetPath = details[proc.pid]?.path || proc.path + if (targetPath) { + return copyWithToast(targetPath, t('copiedExecPathTitle'), targetPath) + } + showToast({ + style: Toast.Style.Failure, + title: t('pathUnavailableTitle'), + message: t('pathUnavailableMsg') + }) + } + }), + Action({ + title: t('actionCopyCmdLine'), + icon: Icon.Terminal, + onAction: () => { + // 只复制系统真实给出的命令行;没有时如实提示,不拿路径或进程名冒充 + const cmdLine = details[proc.pid]?.commandLine || proc.commandLine + if (cmdLine) return copyWithToast(cmdLine, t('copiedCmdLineTitle'), cmdLine) + showToast({ + style: Toast.Style.Failure, + title: t('noCmdLineTitle'), + message: t('noCmdLineMsg', { name: proc.name, pid: proc.pid }) + }) + } + }), + Action({ + title: t('refreshListBtn'), + icon: Icon.ArrowClockwise, + shortcut: { modifiers: ['ctrl'], key: 'r' }, + onAction: handleRefresh + }) + ] + return List.Item({ id: String(proc.pid), title: proc.name, @@ -532,81 +589,31 @@ export default function ProcessMonitorCommand({ initialView = 'memory' }: { init ], actions: ActionPanel({ title: `${proc.name} (PID: ${proc.pid})`, - children: [ - Action({ - title: t('actionEndProcess'), - icon: Icon.XMarkCircle, - style: 'destructive', - onAction: () => handleTerminate(proc, 'force') - }), - Action({ - title: t('actionForceEndTree'), - icon: Icon.Trash, - style: 'destructive', - shortcut: { modifiers: ['ctrl'], key: 'return' }, - onAction: () => handleTerminate(proc, 'tree') - }), - Action({ - title: t('actionLocateDir'), - icon: Icon.Folder, - shortcut: { modifiers: ['ctrl'], key: 'o' }, - onAction: () => handleOpenLocation(proc) - }), - Action({ - title: t('actionCopyPid'), - icon: Icon.Key, - shortcut: { modifiers: ['ctrl'], key: 'c' }, - onAction: () => copyWithToast(String(proc.pid), t('copiedPidTitle'), String(proc.pid)) - }), - Action({ - title: t('actionGracefulClose'), - icon: Icon.Stop, - onAction: () => handleTerminate(proc, 'graceful') - }), - Action({ - title: t('actionViewProfile'), - icon: Icon.MagnifyingGlass, - shortcut: { modifiers: ['ctrl'], key: 'i' }, - onAction: () => handleShowProfile(proc) - }), - Action({ - title: t('actionCopyExecPath'), - icon: Icon.Document, - shortcut: { modifiers: ['ctrl', 'shift'], key: 'c' }, - onAction: () => { - const targetPath = details[proc.pid]?.path || proc.path - if (targetPath) { - return copyWithToast(targetPath, t('copiedExecPathTitle'), targetPath) - } else { - showToast({ - style: Toast.Style.Failure, - title: t('pathUnavailableTitle'), - message: t('pathUnavailableMsg') - }) - } - } - }), - Action({ - title: t('actionCopyCmdLine'), - icon: Icon.Terminal, - onAction: () => { - // 只复制系统真实给出的命令行;没有时如实提示,不拿路径或进程名冒充 - const cmdLine = details[proc.pid]?.commandLine || proc.commandLine - if (cmdLine) return copyWithToast(cmdLine, t('copiedCmdLineTitle'), cmdLine) - showToast({ - style: Toast.Style.Failure, - title: t('noCmdLineTitle'), - message: t('noCmdLineMsg', { name: proc.name, pid: proc.pid }) - }) - } - }), - Action({ - title: t('refreshListBtn'), - icon: Icon.ArrowClockwise, - shortcut: { modifiers: ['ctrl'], key: 'r' }, - onAction: handleRefresh - }) - ] + children: isCrit + ? [viewProfileAction, locateDirAction, ...copyActions] + : [ + Action({ + title: t('actionGracefulClose'), + icon: Icon.Stop, + onAction: () => handleTerminate(proc, 'graceful') + }), + Action({ + title: t('actionEndProcess'), + icon: Icon.XMarkCircle, + style: 'destructive', + onAction: () => handleTerminate(proc, 'force') + }), + Action({ + title: t('actionForceEndTree'), + icon: Icon.Trash, + style: 'destructive', + shortcut: { modifiers: ['ctrl'], key: 'return' }, + onAction: () => handleTerminate(proc, 'tree') + }), + locateDirAction, + viewProfileAction, + ...copyActions + ] }) }) }) diff --git a/extensions/process-monitor/src/native-ipc.ts b/extensions/process-monitor/src/native-ipc.ts index 51576b99..13643277 100644 --- a/extensions/process-monitor/src/native-ipc.ts +++ b/extensions/process-monitor/src/native-ipc.ts @@ -174,11 +174,13 @@ function normalizeMethodResult(method: string, payload: DynamicBridge): DynamicB if (method === 'system_get_battery_status') { // 宿主约定 percent 超出 0-100(如 255)表示无电池或电量未知,不能改写成 100% + // 若宿主明确给出 hasBattery 布尔值,必须原样保留,仅在缺失时按合法电量推算 const rawPct = payload.percent - const hasBattery = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const validPct = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const hasBattery = typeof payload.hasBattery === 'boolean' ? payload.hasBattery : validPct return { ...payload, - percent: hasBattery ? rawPct : null, + percent: validPct ? rawPct : null, hasBattery } } @@ -489,6 +491,8 @@ export interface RealDirectoryScanResult extends Iterable approximate?: boolean /** 宿主实际遍历的条目数 */ visitedEntries?: number + /** 目录本身不存在(ENOENT) */ + missing?: boolean /** 读取失败的真实原因;已有文件仍可使用,但不能当作完整结果。 */ error?: string } @@ -497,6 +501,7 @@ interface ScanResultMeta { truncated?: boolean approximate?: boolean visitedEntries?: number + missing?: boolean } export interface ScanDirectoryTreeOptions { @@ -504,6 +509,10 @@ export interface ScanDirectoryTreeOptions { maxFiles?: number collectTopN?: number filterExt?: RegExp + /** 为 true 时,目录本身不存在(ENOENT)按空目录处理,不返回 error(权限拒绝/读取失败仍照常报错) */ + ignoreMissing?: boolean + /** Top-N 保留与排序方式:默认按体积降序,下载/录屏等时效场景可传 mtime-desc */ + sortBy?: 'size-desc' | 'mtime-desc' hostOverride?: DynamicBridge } @@ -519,8 +528,9 @@ function normalizeIndexedFileEntry(f: DynamicBridge): RealIndexedFileEntry { const sz = Number(f?.size ?? f?.sizeBytes ?? 0) const isDir = Boolean(f?.is_dir || f?.isDir || f?.isDirectory) const rawMtime = Number(f?.mtime ?? f?.mtimeMs ?? 0) - const mtimeMs = rawMtime > 1e11 ? rawMtime : rawMtime > 0 ? rawMtime * 1000 : Date.now() - const mtimeSec = rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime + const validMtime = Number.isFinite(rawMtime) && rawMtime > 0 + const mtimeMs = validMtime ? (rawMtime > 1e11 ? rawMtime : rawMtime * 1000) : 0 + const mtimeSec = validMtime ? (rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime) : 0 if (p && sz >= 0) realFileSizeCache.set(p, sz) return { name, @@ -551,6 +561,7 @@ function makeScanResult( subdirs, ...(meta.truncated ? { truncated: true } : {}), ...(meta.approximate ? { approximate: true } : {}), + ...(meta.missing ? { missing: true } : {}), ...(typeof meta.visitedEntries === 'number' ? { visitedEntries: meta.visitedEntries } : {}), [Symbol.iterator]() { return files[Symbol.iterator]() @@ -609,13 +620,40 @@ export async function scanRealDirectoryTree( return result.error ? { ...result.scan, error: result.error } : result.scan } +/** 仅当正则明确声明了扩展名(含 `\.`)时提取后缀列表,避免把 `thumbcache|iconcache` 等文件名关键词误拆成假扩展名 */ +function extractExtensionTokensFromFilter(filterExt: RegExp): string[] { + const src = filterExt.source + if (!src.includes('\\.')) return [] + const afterDot = src.slice(src.indexOf('\\.') + 2) + const rawTokens = afterDot.match(/[a-z0-9]{1,8}/gi) || [] + const seen = new Set() + const out: string[] = [] + for (const token of rawTokens) { + const lower = token.toLowerCase() + if (!lower || seen.has(lower)) continue + seen.add(lower) + out.push(lower) + } + return out +} + +function isMissingDirectoryError(res: { error?: string; errorCode?: string; errorDetails?: Record }): boolean { + if (res.errorDetails?.reason === 'ENOENT' || res.errorCode === 'ENOENT') return true + const msg = String(res.error || '') + return /Directory does not exist|ENOENT/i.test(msg) +} + /** 一次界面扫描的错误汇总;多个目录并行扫描时保留可读目录的结果。 */ export function createDirectoryScanner(hostOverride?: DynamicBridge) { const failures = new Map() return { async scan(dir: string, options: number | ScanDirectoryTreeOptions = 160) { const result = await scanRealDirectoryTree(dir, options, hostOverride) - const error = result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') + const ignoreMissing = typeof options === 'object' && options !== null && options.ignoreMissing === true + const error = + result.missing && ignoreMissing + ? '' + : result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') if (error) failures.set(dir, error) else failures.delete(dir) return result @@ -648,26 +686,38 @@ async function scanDirectoryTreeWithError( const safeLimit = Math.min(200, Math.max(1, Math.floor(rawLimit || 160))) const hostOverride = opts.hostOverride const filterExt = opts.filterExt + const ignoreMissing = opts.ignoreMissing === true const dirQuery = `dir:${targetDir}` try { let rawPayload: DynamicBridge = null + const searchParams: Record = { + query: dirQuery, + limit: safeLimit, + ...(opts.sortBy ? { sortBy: opts.sortBy } : {}) + } const res = await callHostTransport( 'system_search_files', - { query: dirQuery, limit: safeLimit }, + searchParams, hostOverride ) - if (res.ok && res.data) { + if (res.ok && res.data && res.data.degraded !== true) { rawPayload = res.data + } else if (!res.ok && ignoreMissing && isMissingDirectoryError(res)) { + const missingScan = makeScanResult([], 0, 0, [], { missing: true }) + return { scan: missingScan } } - if (!rawPayload && !hostOverride && typeof window !== 'undefined') { + if (!rawPayload && !hostOverride && res.errorCode === 'METHOD_NOT_AVAILABLE' && typeof window !== 'undefined') { const w = window as DynamicBridge if (typeof w.__ztoolsLauncher?.searchFiles === 'function') { const rawOuter = await w.__ztoolsLauncher.searchFiles(dirQuery, safeLimit) - rawPayload = + const candidate = rawOuter && typeof rawOuter === 'object' && 'data' in rawOuter && rawOuter.data ? rawOuter.data : rawOuter + if (candidate && candidate.degraded !== true && candidate.success !== false) { + rawPayload = candidate + } } } @@ -678,29 +728,32 @@ async function scanDirectoryTreeWithError( let files: RealIndexedFileEntry[] = rawPayload.files.map(normalizeIndexedFileEntry) if (filterExt instanceof RegExp) { files = files.filter(f => !f.isDir && (filterExt.test(f.name) || filterExt.test(f.ext))) - // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索目标扩展名 + // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索明确声明的目标扩展名 if (files.length === 0 && !hostOverride) { - const extTokens = (filterExt.source.match(/[a-z0-9]{2,5}/gi) || []) - .filter(t => !['thumbcache', 'iconcache'].includes(t.toLowerCase())) - .slice(0, 4) - // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 - const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() - const extraLists = await Promise.all( - extTokens.map(ext => searchRealIndexedFiles(`.${ext.toLowerCase()}`, 30, hostOverride)) - ) - const seen = new Set() - for (const list of extraLists) { - for (const item of list) { - if (!item.isDir && item.size > 0 && !seen.has(item.path)) { - if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { - seen.add(item.path) - files.push(item) + const extTokens = extractExtensionTokensFromFilter(filterExt) + if (extTokens.length > 0) { + // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 + const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() + const extraLists = await Promise.all( + extTokens.map(ext => searchRealIndexedFiles(`.${ext}`, 30, hostOverride)) + ) + const seen = new Set() + for (const list of extraLists) { + for (const item of list) { + if (!item.isDir && item.size > 0 && !seen.has(item.path)) { + if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { + seen.add(item.path) + files.push(item) + } } } } } } } + // 先基于过滤后的完整命中集合计算总文件数与总字节数,再按 collectTopN 裁剪样本列表 + const matchedCount = files.length + const matchedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) if (typeof opts.collectTopN === 'number' && opts.collectTopN > 0 && files.length > opts.collectTopN) { files = files.slice(0, opts.collectTopN) } @@ -714,11 +767,10 @@ async function scanDirectoryTreeWithError( ...(s.approximate === true ? { approximate: true } : {}) })) : [] - const computedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) const totalFilesCount = - filterExt instanceof RegExp ? files.length : Number(rawPayload.total_matches ?? files.length) + filterExt instanceof RegExp ? matchedCount : Number(rawPayload.total_matches ?? matchedCount) const totalBytesCount = - filterExt instanceof RegExp ? computedBytes : Number(rawPayload.total_bytes ?? computedBytes) + filterExt instanceof RegExp ? matchedBytes : Number(rawPayload.total_bytes ?? matchedBytes) const visited = Number(rawPayload.visited_entries) return { scan: makeScanResult(files, totalFilesCount, totalBytesCount, subdirs, { @@ -1817,8 +1869,6 @@ export async function writeRealClipboardText(text: string, hostOverride?: Dynami const payload = { text: String(text || '') } const res = await callHostTransport('clipboard_copy_text', payload, hostOverride) if (res.ok) return true - const fallbackRes = await callHostTransport('clipboard_write_text', payload, hostOverride) - if (fallbackRes.ok) return true try { if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) { await navigator.clipboard.writeText(String(text || '')) diff --git a/extensions/process-monitor/tests/process-monitor.macos.test.mjs b/extensions/process-monitor/tests/process-monitor.macos.test.mjs index fed76a82..e6042382 100644 --- a/extensions/process-monitor/tests/process-monitor.macos.test.mjs +++ b/extensions/process-monitor/tests/process-monitor.macos.test.mjs @@ -230,23 +230,16 @@ test('pm-7 describeProcessProfile 对空值、null 与和进程名相同的描 // ---------- macOS 关键进程保护 ---------- -test('pm-8 结束 launchd / WindowServer / loginwindow 直接拦截:不弹确认、不调用 process_kill', async () => { +test('pm-8 系统关键进程 launchd / WindowServer / loginwindow 隐藏所有结束动作,主动作改为安全查看', async () => { const { killed } = installMacHost() const view = await mount(ProcessMonitorCommand, host) await tick(10) - for (const [name, action] of [ - ['launchd', '结束进程'], - ['WindowServer', '强制结束进程树'], - ['loginwindow', '平缓关闭进程 (Graceful)'], - ['logd', '结束进程'] - ]) { - await view.run(itemByName(view, name), action) - await tick(5) - const t = host.lastToast() - assert.equal(t.style, 'FAILURE', name) - assert.match(t.title, new RegExp(`已拦截:${name}`)) - assert.equal(t.message, getForbiddenReason()) - assert.equal(tagOf(itemByName(view, name)), '系统关键') + for (const name of ['launchd', 'WindowServer', 'loginwindow', 'logd']) { + const item = itemByName(view, name) + const titles = view.actions(item).map((a) => a.props.title) + assert.equal(titles.some((title) => /结束|平缓关闭/.test(title)), false, `${name} 不应提供结束动作`) + assert.equal(titles[0], '查看数字签名与托管服务', `${name} 主动作应为安全查看`) + assert.equal(tagOf(item), '系统关键') } assert.equal(host.confirms.length, 0) assert.deepEqual(killed, []) diff --git a/extensions/qq-cleaner/README.en.md b/extensions/qq-cleaner/README.en.md new file mode 100644 index 00000000..b1ed8b02 --- /dev/null +++ b/extensions/qq-cleaner/README.en.md @@ -0,0 +1,22 @@ +# QQ / TIM Cleaner + +Scan local cache directories of desktop QQ and TIM, list files grouped by logs, images, videos, voice messages, received files, and more, and move checked items to the Recycle Bin; chat history databases cannot be checked. + +## Usage + +- Command: `QQ / TIM Cleaner`. +- Scan locations: `Tencent Files` under Documents (and at the root of drives `C:` through `G:`), `Users`, `Logs`, `QQ`, `TIM`, and `QQTempSys` under `%APPDATA%\Tencent`, `%APPDATA%\QQ`, and `MiniBrowser`, `QQGuild`, and `Misc` under `%LOCALAPPDATA%\Tencent`. +- Summarized on the left into 12 cleanup groups plus a protected chat-database section, with a top dropdown to filter by QQ account number; files appear on the right and can be checked individually or all at once. +- After scanning, only visible files belonging to Logs, Account Runtime Cache, System Core Cache, Built-in Browser & Mini-Programs, Avatar Cache, and Received Sticker Cache are checked by default; hidden files are not checked, and files with unrecognized purposes (listed under "Account Runtime Cache" and labeled "Unrecognized Purpose") are left unchecked by default. Chat images, videos, voice messages (which may no longer be viewable in chat after cleaning), favorite stickers, received files, and login session data are unchecked by default. "Received Files" may contain documents you need—review carefully before checking. +- With a file selected, press `Enter` to clean checked items—the confirmation dialog lists file counts and sizes by group before moving them to the Recycle Bin; `Ctrl+Enter` reveals in File Explorer; `Ctrl+K` lets you check/uncheck, open with the default app, or copy the path. +- After cleanup, the notice reports the exact number of files moved to the Recycle Bin; if any files could not be recycled (for example, locked by QQ), the failure count and reason are shown without falling back to permanent deletion. Recycled files still occupy disk space until you empty the Recycle Bin. +- Reads up to 140 files per scanned directory, and some left-hand group totals also include unread files; the right list displays up to 60 items sorted from largest to smallest—select a left-hand group or search to view others. The header checkbox checks or unchecks only currently displayed files. Cleanup applies to all checked files under the active QQ account filter; check the top status bar for the total checked count. +- Chat history and account databases such as `Msg3.0.db`, `nt_msg.db`, `Registry.db`, `Info.db`, as well as files inside `nt_db`, cannot be checked and will never be deleted. + +## Platforms & Requirements + +- Supported: Windows only + +## Network & Data + +- Works offline; no data is saved. diff --git a/extensions/qq-cleaner/plugin.json b/extensions/qq-cleaner/plugin.json index 5f8efeca..064c8f3a 100644 --- a/extensions/qq-cleaner/plugin.json +++ b/extensions/qq-cleaner/plugin.json @@ -2,7 +2,7 @@ "id": "qq-cleaner", "name": "QQ 清理", "description": "扫描电脑端 QQ、TIM 的日志、缓存、聊天图片与视频、接收文件等,把勾选的文件移入回收站,聊天记录数据库不会被清理", - "version": "2.0.12", + "version": "2.0.13", "author": "ZTools Team", "entry": "dist/index.js", "icon": "icon.svg", @@ -37,7 +37,13 @@ "cleaner", "cache", "cleanup", - "recycle bin" + "recycle bin", + "qq cleaner", + "clean qq", + "tim cleaner", + "qq cache", + "free qq space", + "qq storage" ], "screenshots": [ { @@ -53,5 +59,15 @@ { "path": "screenshots/02-action-panel.png" } + ], + "keywords": [ + "qq清理", + "清理qq", + "qq缓存", + "qq占空间", + "tim清理", + "清qq垃圾", + "qq图片清理", + "qq文件清理" ] } diff --git a/extensions/qq-cleaner/src/i18n.ts b/extensions/qq-cleaner/src/i18n.ts index 218eea6f..d81de225 100644 --- a/extensions/qq-cleaner/src/i18n.ts +++ b/extensions/qq-cleaner/src/i18n.ts @@ -14,7 +14,8 @@ const MESSAGES = { noFilesCheckedMsg: "请先在右侧勾选要清理的文件", breakdownLine: "- {name}:{count} 个({bytes})", confirmCleanTitle: "把 {count} 个文件移入回收站?", - confirmCleanMsg: "范围:{scope},共 {bytes}\n\n{breakdown}\n\n{reason}。文件移入回收站后仍占用磁盘空间,清空回收站后才会释放。", + confirmCleanMsg: "范围:{scope},共 {bytes}{crossNote}\n\n{breakdown}\n\n{reason}。文件移入回收站后仍占用磁盘空间,清空回收站后才会释放。", + confirmCleanCrossNote: "\n提示:当前分类已选 {current} 个 / 全部已选 {total} 个(含其他分类已勾选文件)", allAccountsLabel: "全部 QQ 号", moveToTrashBtn: "移入回收站", locateFailedToast: "无法在资源管理器中定位", @@ -41,6 +42,7 @@ const MESSAGES = { summaryReady: "{scope} · 缓存占用 {scannable} · 已勾选 {count} 个文件 ({bytes}) · 聊天数据库 {protected} 受保护", rescan: "重新扫描", subListSubtitle: "{shown} · 已勾选 {count} 个 ({bytes})", + subListSubtitleSplit: "{shown} · 当前分类已选 {current} / 全部已选 {total} ({bytes})", scanningEmpty: "正在扫描...", noFilesEmpty: "当前 QQ 号与分组下没有找到缓存文件", overviewSection: "QQ 存储总览", @@ -128,7 +130,8 @@ const MESSAGES = { noFilesCheckedMsg: "Select files on the right to clean first", breakdownLine: "- {name}: {count} ({bytes})", confirmCleanTitle: "Move {count} file(s) to Recycle Bin?", - confirmCleanMsg: "Scope: {scope}, total {bytes}\n\n{breakdown}\n\n{reason}. Files in Recycle Bin still use disk space until emptied.", + confirmCleanMsg: "Scope: {scope}, total {bytes}{crossNote}\n\n{breakdown}\n\n{reason}. Files in Recycle Bin still use disk space until emptied.", + confirmCleanCrossNote: "\nNote: {current} selected in current group / {total} selected overall (includes other groups)", allAccountsLabel: "All QQ Accounts", moveToTrashBtn: "Move to Recycle Bin", locateFailedToast: "Failed to reveal in Explorer", @@ -155,6 +158,7 @@ const MESSAGES = { summaryReady: "{scope} · Cache {scannable} · {count} selected ({bytes}) · Chat DB {protected} protected", rescan: "Rescan", subListSubtitle: "{shown} · {count} selected ({bytes})", + subListSubtitleSplit: "{shown} · {current} in group / {total} total selected ({bytes})", scanningEmpty: "Scanning...", noFilesEmpty: "No cache files found for current account and group", overviewSection: "Overview", diff --git a/extensions/qq-cleaner/src/index.ts b/extensions/qq-cleaner/src/index.ts index 6a777cbf..d39381ac 100644 --- a/extensions/qq-cleaner/src/index.ts +++ b/extensions/qq-cleaner/src/index.ts @@ -124,6 +124,10 @@ export default function QQCleanerCommand() { checkedSet.has(f.path) ) const targetBytes = targetFiles.reduce((s, f) => s + f.sizeBytes, 0) + const currentCategoryCheckedCount = filteredFiles.filter( + f => !f.isProtected && f.groupId !== 999 && checkedSet.has(f.path) + ).length + const isCategoryFiltered = selectedGroupId !== 0 || Boolean(q) function toggleSingleFileCheck(file: QQScannedFileEntry, nextChecked?: boolean) { if (file.isProtected || file.groupId === 999) { @@ -172,11 +176,17 @@ export default function QQCleanerCommand() { .filter(Boolean) .join('\n') + const crossNote = + isCategoryFiltered && targetFiles.length !== currentCategoryCheckedCount + ? t('confirmCleanCrossNote', { current: currentCategoryCheckedCount, total: targetFiles.length }) + : '' + const confirmed = await confirmAlert({ title: t('confirmCleanTitle', { count: targetFiles.length }), message: t('confirmCleanMsg', { scope: selectedAccount === 'ALL' ? t('allAccountsLabel') : selectedAccount, bytes: formatBytes(targetBytes), + crossNote, breakdown: breakdownLines, reason: getForbiddenReason() }), @@ -348,7 +358,15 @@ export default function QQCleanerCommand() { }, subList: { title: rightTitle, - subtitle: t('subListSubtitle', { shown: shownText, count: targetFiles.length, bytes: formatBytes(targetBytes) }), + subtitle: + isCategoryFiltered && targetFiles.length !== currentCategoryCheckedCount + ? t('subListSubtitleSplit', { + shown: shownText, + current: currentCategoryCheckedCount, + total: targetFiles.length, + bytes: formatBytes(targetBytes) + }) + : t('subListSubtitle', { shown: shownText, count: targetFiles.length, bytes: formatBytes(targetBytes) }), checkable: selectableVisible.length > 0, checked: allVisibleChecked ? true : someVisibleChecked ? 'indeterminate' : false, onCheckChange: () => toggleAllVisibleCheck(), diff --git a/extensions/qq-cleaner/src/logic.ts b/extensions/qq-cleaner/src/logic.ts index d367b680..0865052c 100644 --- a/extensions/qq-cleaner/src/logic.ts +++ b/extensions/qq-cleaner/src/logic.ts @@ -548,9 +548,7 @@ export async function fetchQQCleanSnapshot(hostOverride?: Record `${letter}:\\Tencent Files`) @@ -567,14 +565,17 @@ export async function fetchQQCleanSnapshot(hostOverride?: Record() + const accountRootDirs = new Map() const allFiles: QQScannedFileEntry[] = [] const seenPaths = new Set() - // 归一化 AppData\Roaming\Tencent 与符号链接路径,严防重复计数 + // 归一化 AppData\Roaming\Tencent 与 AppData\Local\Tencent 符号链接路径,保留 Roaming/Local 区分严防跨目录误去重 const canonicalizeQQKey = (p: string): string => { const lower = p.replace(/\//g, '\\').toLowerCase() - const idx = lower.indexOf('\\tencent\\') - if (idx >= 0) return lower.slice(idx) + const roamingIdx = lower.indexOf('\\roaming\\tencent\\') + if (roamingIdx >= 0) return lower.slice(roamingIdx) + const localIdx = lower.indexOf('\\local\\tencent\\') + if (localIdx >= 0) return lower.slice(localIdx) return lower } @@ -622,7 +623,7 @@ export async function fetchQQCleanSnapshot(hostOverride?: Record = [ - { dir: tencentFilesDir }, + ...(tencentFilesDir ? [{ dir: tencentFilesDir }] : []), ...driveTencentRoots.map(dir => ({ dir })), ...(appDataDir ? [ @@ -644,7 +645,9 @@ export async function fetchQQCleanSnapshot(hostOverride?: Record() - const scanResults = await Promise.all(deepTargets.map(t => scanner.scan(t.dir, 140))) + const scanResults = await Promise.all( + deepTargets.map(t => scanner.scan(t.dir, { maxFiles: 140, ignoreMissing: true })) + ) // 从 Tencent Files 与 Tencent\Users 一级子目录提取全部本机登录 QQ 号 (UIN) for (let i = 0; i < deepTargets.length; i++) { @@ -656,6 +659,10 @@ export async function fetchQQCleanSnapshot(hostOverride?: Record 0) { - const beforeLen = allFiles.length registerScannedFile(f.path, f.size, f.mtime) - if (allFiles.length > beforeLen) { - sampledBytes += f.size - sampledCount += 1 - } + // 本目录返回列表里的全部普通文件体积都计入 sampledBytes,防止已去重文件被 res.totalBytes - sampledBytes 重复加回 + sampledBytes += f.size + sampledCount += 1 } } @@ -693,11 +698,14 @@ export async function fetchQQCleanSnapshot(hostOverride?: Record= 0 && rawPct <= 100 + const validPct = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const hasBattery = typeof payload.hasBattery === 'boolean' ? payload.hasBattery : validPct return { ...payload, - percent: hasBattery ? rawPct : null, + percent: validPct ? rawPct : null, hasBattery } } @@ -489,6 +491,8 @@ export interface RealDirectoryScanResult extends Iterable approximate?: boolean /** 宿主实际遍历的条目数 */ visitedEntries?: number + /** 目录本身不存在(ENOENT) */ + missing?: boolean /** 读取失败的真实原因;已有文件仍可使用,但不能当作完整结果。 */ error?: string } @@ -497,6 +501,7 @@ interface ScanResultMeta { truncated?: boolean approximate?: boolean visitedEntries?: number + missing?: boolean } export interface ScanDirectoryTreeOptions { @@ -504,6 +509,10 @@ export interface ScanDirectoryTreeOptions { maxFiles?: number collectTopN?: number filterExt?: RegExp + /** 为 true 时,目录本身不存在(ENOENT)按空目录处理,不返回 error(权限拒绝/读取失败仍照常报错) */ + ignoreMissing?: boolean + /** Top-N 保留与排序方式:默认按体积降序,下载/录屏等时效场景可传 mtime-desc */ + sortBy?: 'size-desc' | 'mtime-desc' hostOverride?: DynamicBridge } @@ -519,8 +528,9 @@ function normalizeIndexedFileEntry(f: DynamicBridge): RealIndexedFileEntry { const sz = Number(f?.size ?? f?.sizeBytes ?? 0) const isDir = Boolean(f?.is_dir || f?.isDir || f?.isDirectory) const rawMtime = Number(f?.mtime ?? f?.mtimeMs ?? 0) - const mtimeMs = rawMtime > 1e11 ? rawMtime : rawMtime > 0 ? rawMtime * 1000 : Date.now() - const mtimeSec = rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime + const validMtime = Number.isFinite(rawMtime) && rawMtime > 0 + const mtimeMs = validMtime ? (rawMtime > 1e11 ? rawMtime : rawMtime * 1000) : 0 + const mtimeSec = validMtime ? (rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime) : 0 if (p && sz >= 0) realFileSizeCache.set(p, sz) return { name, @@ -551,6 +561,7 @@ function makeScanResult( subdirs, ...(meta.truncated ? { truncated: true } : {}), ...(meta.approximate ? { approximate: true } : {}), + ...(meta.missing ? { missing: true } : {}), ...(typeof meta.visitedEntries === 'number' ? { visitedEntries: meta.visitedEntries } : {}), [Symbol.iterator]() { return files[Symbol.iterator]() @@ -609,13 +620,40 @@ export async function scanRealDirectoryTree( return result.error ? { ...result.scan, error: result.error } : result.scan } +/** 仅当正则明确声明了扩展名(含 `\.`)时提取后缀列表,避免把 `thumbcache|iconcache` 等文件名关键词误拆成假扩展名 */ +function extractExtensionTokensFromFilter(filterExt: RegExp): string[] { + const src = filterExt.source + if (!src.includes('\\.')) return [] + const afterDot = src.slice(src.indexOf('\\.') + 2) + const rawTokens = afterDot.match(/[a-z0-9]{1,8}/gi) || [] + const seen = new Set() + const out: string[] = [] + for (const token of rawTokens) { + const lower = token.toLowerCase() + if (!lower || seen.has(lower)) continue + seen.add(lower) + out.push(lower) + } + return out +} + +function isMissingDirectoryError(res: { error?: string; errorCode?: string; errorDetails?: Record }): boolean { + if (res.errorDetails?.reason === 'ENOENT' || res.errorCode === 'ENOENT') return true + const msg = String(res.error || '') + return /Directory does not exist|ENOENT/i.test(msg) +} + /** 一次界面扫描的错误汇总;多个目录并行扫描时保留可读目录的结果。 */ export function createDirectoryScanner(hostOverride?: DynamicBridge) { const failures = new Map() return { async scan(dir: string, options: number | ScanDirectoryTreeOptions = 160) { const result = await scanRealDirectoryTree(dir, options, hostOverride) - const error = result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') + const ignoreMissing = typeof options === 'object' && options !== null && options.ignoreMissing === true + const error = + result.missing && ignoreMissing + ? '' + : result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') if (error) failures.set(dir, error) else failures.delete(dir) return result @@ -648,26 +686,38 @@ async function scanDirectoryTreeWithError( const safeLimit = Math.min(200, Math.max(1, Math.floor(rawLimit || 160))) const hostOverride = opts.hostOverride const filterExt = opts.filterExt + const ignoreMissing = opts.ignoreMissing === true const dirQuery = `dir:${targetDir}` try { let rawPayload: DynamicBridge = null + const searchParams: Record = { + query: dirQuery, + limit: safeLimit, + ...(opts.sortBy ? { sortBy: opts.sortBy } : {}) + } const res = await callHostTransport( 'system_search_files', - { query: dirQuery, limit: safeLimit }, + searchParams, hostOverride ) - if (res.ok && res.data) { + if (res.ok && res.data && res.data.degraded !== true) { rawPayload = res.data + } else if (!res.ok && ignoreMissing && isMissingDirectoryError(res)) { + const missingScan = makeScanResult([], 0, 0, [], { missing: true }) + return { scan: missingScan } } - if (!rawPayload && !hostOverride && typeof window !== 'undefined') { + if (!rawPayload && !hostOverride && res.errorCode === 'METHOD_NOT_AVAILABLE' && typeof window !== 'undefined') { const w = window as DynamicBridge if (typeof w.__ztoolsLauncher?.searchFiles === 'function') { const rawOuter = await w.__ztoolsLauncher.searchFiles(dirQuery, safeLimit) - rawPayload = + const candidate = rawOuter && typeof rawOuter === 'object' && 'data' in rawOuter && rawOuter.data ? rawOuter.data : rawOuter + if (candidate && candidate.degraded !== true && candidate.success !== false) { + rawPayload = candidate + } } } @@ -678,29 +728,32 @@ async function scanDirectoryTreeWithError( let files: RealIndexedFileEntry[] = rawPayload.files.map(normalizeIndexedFileEntry) if (filterExt instanceof RegExp) { files = files.filter(f => !f.isDir && (filterExt.test(f.name) || filterExt.test(f.ext))) - // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索目标扩展名 + // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索明确声明的目标扩展名 if (files.length === 0 && !hostOverride) { - const extTokens = (filterExt.source.match(/[a-z0-9]{2,5}/gi) || []) - .filter(t => !['thumbcache', 'iconcache'].includes(t.toLowerCase())) - .slice(0, 4) - // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 - const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() - const extraLists = await Promise.all( - extTokens.map(ext => searchRealIndexedFiles(`.${ext.toLowerCase()}`, 30, hostOverride)) - ) - const seen = new Set() - for (const list of extraLists) { - for (const item of list) { - if (!item.isDir && item.size > 0 && !seen.has(item.path)) { - if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { - seen.add(item.path) - files.push(item) + const extTokens = extractExtensionTokensFromFilter(filterExt) + if (extTokens.length > 0) { + // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 + const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() + const extraLists = await Promise.all( + extTokens.map(ext => searchRealIndexedFiles(`.${ext}`, 30, hostOverride)) + ) + const seen = new Set() + for (const list of extraLists) { + for (const item of list) { + if (!item.isDir && item.size > 0 && !seen.has(item.path)) { + if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { + seen.add(item.path) + files.push(item) + } } } } } } } + // 先基于过滤后的完整命中集合计算总文件数与总字节数,再按 collectTopN 裁剪样本列表 + const matchedCount = files.length + const matchedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) if (typeof opts.collectTopN === 'number' && opts.collectTopN > 0 && files.length > opts.collectTopN) { files = files.slice(0, opts.collectTopN) } @@ -714,11 +767,10 @@ async function scanDirectoryTreeWithError( ...(s.approximate === true ? { approximate: true } : {}) })) : [] - const computedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) const totalFilesCount = - filterExt instanceof RegExp ? files.length : Number(rawPayload.total_matches ?? files.length) + filterExt instanceof RegExp ? matchedCount : Number(rawPayload.total_matches ?? matchedCount) const totalBytesCount = - filterExt instanceof RegExp ? computedBytes : Number(rawPayload.total_bytes ?? computedBytes) + filterExt instanceof RegExp ? matchedBytes : Number(rawPayload.total_bytes ?? matchedBytes) const visited = Number(rawPayload.visited_entries) return { scan: makeScanResult(files, totalFilesCount, totalBytesCount, subdirs, { @@ -1817,8 +1869,6 @@ export async function writeRealClipboardText(text: string, hostOverride?: Dynami const payload = { text: String(text || '') } const res = await callHostTransport('clipboard_copy_text', payload, hostOverride) if (res.ok) return true - const fallbackRes = await callHostTransport('clipboard_write_text', payload, hostOverride) - if (fallbackRes.ok) return true try { if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) { await navigator.clipboard.writeText(String(text || '')) diff --git a/extensions/qq-cleaner/tests/qq-cleaner.clean.test.mjs b/extensions/qq-cleaner/tests/qq-cleaner.clean.test.mjs index 411b65b1..5ba8bb7e 100644 --- a/extensions/qq-cleaner/tests/qq-cleaner.clean.test.mjs +++ b/extensions/qq-cleaner/tests/qq-cleaner.clean.test.mjs @@ -255,3 +255,103 @@ test('安全红线:文件行 Enter 主动作定位文件,不误触全局批 const topClean = view.tree().props.filterBar.actions.find(a => a.id === 'qq-act-clean') assert.ok(topClean && topClean.disabled === false) }) + +test('回归:可选目录 ENOENT 不误报 error、documentsDir 为空不扫描 Default 假路径、PERMISSION_DENIED 仍报错', async () => { + const host = createHost() + const queriedDirs = [] + host.ipc.system_get_path = async ({ name }) => { + if (name === 'documents') return { path: '' } + if (name === 'home') return { path: '' } + if (name === 'appData') return { path: `${HOME}\\AppData\\Roaming` } + return { path: '' } + } + host.ipc.system_search_files = async ({ query }) => { + const dir = String(query).slice(4) + queriedDirs.push(dir) + if (dir === 'D:\\Tencent Files') { + const f = fileEntry('D:\\Tencent Files\\10002\\AppWebCache\\a.bin', 2048) + return { + files: [f], + subdirs: [{ name: '10002', path: 'D:\\Tencent Files\\10002', file_count: 1, total_bytes: 2048 }], + total_matches: 1, + total_bytes: 2048 + } + } + throw Object.assign(new Error('Directory does not exist'), { code: 'ENOENT' }) + } + const snap = await logic.fetchQQCleanSnapshot() + assert.equal(snap.error, undefined, '不存在盘符与可选目录 ENOENT 不应报错') + assert.equal(queriedDirs.some(d => /Users\\Default\\Documents\\Tencent Files/i.test(d)), false, 'documentsDir 为空时不能扫描 Default 假路径') + assert.deepEqual(snap.detectedAccounts, ['10002']) + assert.equal(snap.accountStats.find(a => a.accountId === '10002')?.rootDir, 'D:\\Tencent Files\\10002') + + // 权限拒绝仍必须报错 + host.ipc.system_search_files = async ({ query }) => { + const dir = String(query).slice(4) + if (dir.endsWith('\\Tencent\\Logs')) { + throw Object.assign(new Error('PERMISSION_DENIED: logs'), { code: 'PERMISSION_DENIED' }) + } + throw Object.assign(new Error('Directory does not exist'), { code: 'ENOENT' }) + } + host.ipc.filesystem_get_directory_contents = async () => { + throw Object.assign(new Error('PERMISSION_DENIED: logs'), { code: 'PERMISSION_DENIED' }) + } + const denied = await logic.fetchQQCleanSnapshot() + assert.match(denied.error || '', /PERMISSION_DENIED/) +}) + +test('回归:Roaming 与 Local 下同名 Tencent 相对路径不误去重,且 extraGroupTotals 不重复累加已去重体积', async () => { + const host = createHost() + const ROAMING = `${HOME}\\AppData\\Roaming` + const LOCAL = `${HOME}\\AppData\\Local` + host.ipc.system_get_path = async ({ name }) => { + const map = { home: HOME, documents: DOCS, appData: ROAMING } + return { path: map[name] || '' } + } + const roamingMiscFile = fileEntry(`${ROAMING}\\Tencent\\QQ\\Misc\\shared.bin`, 3000) + const localMiscFile = fileEntry(`${LOCAL}\\Tencent\\Misc\\shared.bin`, 4000) + // 模拟同一文件同时被 AppData\Roaming\Tencent\QQ 和 AppData\Roaming\Tencent\QQTempSys(符号链接/重叠返回)返回, + // 且 QQTempSys 目录下还有 1 个未在样本中返回的额外文件(1000 字节) + const dupFile = fileEntry(`${ROAMING}\\Tencent\\QQ\\dup.tmp`, 5000) + host.ipc.system_search_files = async ({ query }) => { + const dir = String(query).slice(4) + if (dir === `${ROAMING}\\Tencent\\QQ`) { + return { + files: [roamingMiscFile, dupFile], + subdirs: [], + total_matches: 2, + total_bytes: 8000 + } + } + if (dir === `${ROAMING}\\Tencent\\QQTempSys`) { + return { + files: [dupFile], + subdirs: [], + total_matches: 2, + total_bytes: 6000 + } + } + if (dir === `${LOCAL}\\Tencent\\Misc`) { + return { + files: [localMiscFile], + subdirs: [], + total_matches: 1, + total_bytes: 4000 + } + } + throw Object.assign(new Error('Directory does not exist'), { code: 'ENOENT' }) + } + + const snap = await logic.fetchQQCleanSnapshot() + assert.equal(snap.error, undefined) + const paths = snap.allFiles.map(f => f.path) + assert.ok(paths.includes(roamingMiscFile.path), '应保留 Roaming\\Tencent 文件') + assert.ok(paths.includes(localMiscFile.path), '应保留 Local\\Tencent 文件,不能因截断到 \\tencent\\ 而误去重') + + const g209 = snap.categories.find(c => c.groupId === 209) + assert.ok(g209) + // 209 分类总计应为:roamingMiscFile(3000) + dupFile(5000) + QQTempSys 未采样差值(6000-5000=1000) = 9000(不含已被去重的 dupFile 再次累加) + // 注意 localMiscFile 路径为 AppData\Local\Tencent\Misc\shared.bin,分类落在 202(未识别) + assert.equal(g209.totalSizeBytes, 9000, 'extraGroupTotals 不应把已去重的 dupFile(5000) 重复加回 209 分组') + assert.equal(g209.fileCount, 3, '209 分组文件数应为 2 个已入列 + 1 个未采样文件 = 3') +}) diff --git a/extensions/qr-code/README.en.md b/extensions/qr-code/README.en.md new file mode 100644 index 00000000..71aab46d --- /dev/null +++ b/extensions/qr-code/README.en.md @@ -0,0 +1,20 @@ +# QR Code + +Generate QR codes in real time from URLs or text, create Wi-Fi connection QR codes, copy QR code images, or save as PNG. + +## Usage + +- Commands: `qr` (`qrcode`, `qr code`, `generate qr`, `url to qr`) and `wifi qr` (`wifi qrcode`, `share wifi`, which opens the Wi-Fi form directly). +- Type content into the input box to preview the QR code on the right along with content type, byte length, and QR version; use the dropdown next to the search box to choose error correction level (Low 7% / Medium 15% / Quartile 25% / High 30%). If content exceeds capacity, a prompt suggests shortening the text or lowering the error correction level. +- `Enter` copies the QR code image (and saves it to history), `Cmd/Ctrl+Enter` saves to history only, and `Cmd/Ctrl+K` opens the action panel (Save as PNG, Generate from Clipboard, Create Wi-Fi QR Code). On a history entry, `Enter` copies the image and `Cmd/Ctrl+Enter` copies the text content. +- In the Wi-Fi form, enter the network SSID, password, encryption type (`WPA/WPA2/WPA3`, `WEP`, or `None`), and whether the network is hidden, then press `Cmd/Ctrl+Enter` to generate and save (uses Medium error correction). WPA passwords must be 8–63 characters (or 64 hex characters), and WEP passwords must be 5 or 13 characters (or 10 or 26 hex characters); invalid passwords will not generate a code. +- History keeps up to 100 entries, supporting favorites, copying content text, saving as PNG, and deleting; single-item deletion has no confirmation, while clearing all history asks for confirmation and also clears favorited entries. + +## Platforms & Requirements + +- Supported: Windows, macOS +- Built into ZTools; no separate installation required. + +## Network & Data + +- Works offline; data stays strictly on your local device. Generation history (including passwords stored in Wi-Fi QR codes) is saved in plugin storage. diff --git a/extensions/qr-code/plugin.json b/extensions/qr-code/plugin.json index 1a6de5e0..2ca42c0a 100644 --- a/extensions/qr-code/plugin.json +++ b/extensions/qr-code/plugin.json @@ -1,7 +1,7 @@ { "id": "qr-code", "name": "二维码生成", - "version": "2.1.9", + "version": "2.1.10", "description": "输入网址或文本实时生成高清二维码,支持生成 Wi-Fi 连网二维码、复制图片与导出 PNG", "author": "ZTools Team", "entry": "dist/index.js", @@ -29,7 +29,14 @@ "qr", "qrcode", "二维码", - "wifi" + "wifi", + "生成二维码", + "二维码生成", + "网址转二维码", + "wifi二维码", + "解码二维码", + "识别二维码", + "扫一扫" ], "features": [ { @@ -70,7 +77,13 @@ "wifi", "barcode", "png", - "generator" + "generator", + "qr code", + "qr generator", + "wifi qr", + "decode qr", + "scan qr", + "link to qr" ], "features": { "qr-text": { diff --git a/extensions/qr-code/src/host.ts b/extensions/qr-code/src/host.ts index 796948c4..7a4e9ec3 100644 --- a/extensions/qr-code/src/host.ts +++ b/extensions/qr-code/src/host.ts @@ -10,26 +10,20 @@ const QR_HOST_MESSAGES: Record string; saveDialogTitle: string; saveDialogFilters: string; - imagePathEmpty: string; - decodeFailed: string; }> = { "zh-CN": { methodUnsupported: (method) => `当前环境不支持 ${method}`, unrecognizedResult: "宿主返回了无法识别的结果", methodFailed: (method) => `${method} 调用失败`, saveDialogTitle: "保存二维码图片", - saveDialogFilters: "PNG 图片|png", - imagePathEmpty: "二维码图片路径不能为空", - decodeFailed: "未能从图片中识别出二维码" + saveDialogFilters: "PNG 图片|png" }, "en-US": { methodUnsupported: (method) => `${method} is not supported in the current environment`, unrecognizedResult: "Host returned an unrecognized result", methodFailed: (method) => `${method} call failed`, saveDialogTitle: "Save QR Code Image", - saveDialogFilters: "PNG Image|png", - imagePathEmpty: "QR code image path cannot be empty", - decodeFailed: "No QR code detected in the image" + saveDialogFilters: "PNG Image|png" } }; @@ -83,30 +77,3 @@ export async function savePngFile(pngBase64: string, defaultName: string): Promi await callHost("filesystem_write_file", { path: picked.filePath, content: pngBase64, encoding: "base64" }); return picked.filePath; } - -/** 调用宿主识别图片文件中的二维码内容 */ -export async function decodeQrImageFile(filePath: string): Promise { - const s = qrHostStrings(); - const normalizedPath = (filePath ?? "").trim(); - if (!normalizedPath) throw new Error(s.imagePathEmpty); - const raw = await callHost("qr_scan", { path: normalizedPath, imagePath: normalizedPath }); - if (typeof raw === "string" && raw.trim()) return raw.trim(); - if (isRecord(raw)) { - const candidate = - typeof raw.text === "string" - ? raw.text - : typeof raw.content === "string" - ? raw.content - : typeof raw.data === "string" - ? raw.data - : Array.isArray(raw.results) && raw.results.length > 0 - ? typeof raw.results[0] === "string" - ? raw.results[0] - : isRecord(raw.results[0]) && typeof raw.results[0].text === "string" - ? raw.results[0].text - : "" - : ""; - if (candidate.trim()) return candidate.trim(); - } - throw new Error(s.decodeFailed); -} diff --git a/extensions/qr-code/src/i18n.ts b/extensions/qr-code/src/i18n.ts index 7b62b419..c373e72f 100644 --- a/extensions/qr-code/src/i18n.ts +++ b/extensions/qr-code/src/i18n.ts @@ -35,7 +35,12 @@ const rawT = createTranslator( clearedToast: "已清空历史", clearFailed: "清空失败", fromClipboard: "用剪贴板内容生成", + fromClipboardBtn: "从剪贴板生成", openWifiForm: "生成 Wi-Fi 二维码…", + wifiBtn: "Wi-Fi 二维码", + switchToLevelL: "切换为低纠错等级 (L · 7%)", + clearInput: "清空输入", + liveErrorMd: "### 无法生成二维码\n\n{error}\n\n可尝试切换纠错等级为 **低 (L · 7%)**,或缩短输入内容。", sectionCurrent: "当前输入", liveSubtitle: "按回车复制二维码图片", qrPanelTitle: "二维码", @@ -57,8 +62,6 @@ const rawT = createTranslator( deleteAction: "删除", deletedToast: "已删除", clearHistoryAction: "清空历史", - decodedToast: "已识别二维码内容", - decodeFailedToast: "识别二维码图片失败", navTitle: "二维码生成", searchPlaceholder: "输入网址或文字,实时生成二维码…", ecTooltip: "纠错等级", @@ -97,7 +100,12 @@ const rawT = createTranslator( clearedToast: "History cleared", clearFailed: "Failed to clear history", fromClipboard: "Generate from Clipboard", + fromClipboardBtn: "From Clipboard", openWifiForm: "Create Wi-Fi QR Code…", + wifiBtn: "Wi-Fi QR", + switchToLevelL: "Switch to Low ECC (L · 7%)", + clearInput: "Clear Input", + liveErrorMd: "### Unable to Generate QR Code\n\n{error}\n\nTry lowering error correction to **Low (L · 7%)** or shortening the text.", sectionCurrent: "Current Input", liveSubtitle: "Press Enter to copy QR code image", qrPanelTitle: "QR Code", @@ -119,8 +127,6 @@ const rawT = createTranslator( deleteAction: "Delete", deletedToast: "Deleted", clearHistoryAction: "Clear History", - decodedToast: "QR code decoded", - decodeFailedToast: "Failed to decode QR image", navTitle: "QR Code Generator", searchPlaceholder: "Enter a URL or text to generate a QR code…", ecTooltip: "Error Correction Level", diff --git a/extensions/qr-code/src/index.ts b/extensions/qr-code/src/index.ts index 381bc8c2..5afb9c8d 100644 --- a/extensions/qr-code/src/index.ts +++ b/extensions/qr-code/src/index.ts @@ -28,7 +28,7 @@ import { type QrItem, type QrErrorCorrectionLevel } from "./qr-generator.js"; -import { copyPngToClipboard, savePngFile, decodeQrImageFile } from "./host.js"; +import { copyPngToClipboard, savePngFile } from "./host.js"; import { createCompatFileInputProps } from "./host-compat.js"; export * from "./qr-generator.js"; @@ -147,7 +147,7 @@ export function WifiQrForm({ onCreated }: { onCreated: (item: QrItem) => Promise ]) }, [ - Form.TextField({ id: "ssid", title: t("wifiSsidTitle"), placeholder: t("wifiSsidPlaceholder"), value: ssid, error, onChange: (v: string) => { setSsid(v); setError(undefined); } }), + Form.TextField({ id: "ssid", title: t("wifiSsidTitle"), placeholder: t("wifiSsidPlaceholder"), value: ssid, error, autoFocus: true, onChange: (v: string) => { setSsid(v); setError(undefined); } }), Form.PasswordField({ id: "password", title: t("wifiPassTitle"), placeholder: t("wifiPassPlaceholder"), value: password, error: passwordError, onChange: (v: string) => { setPassword(v); setPasswordError(undefined); } }), Form.Dropdown( { id: "security", title: t("wifiSecTitle"), value: security, onChange: (v: string) => { setSecurity(v === "WEP" || v === "nopass" ? v : "WPA"); setPasswordError(undefined); } }, @@ -257,8 +257,8 @@ export default function QrCodeCommand({ initialWifi = false }: { initialWifi?: b }; const globalActions = [ - Action({ title: t("fromClipboard"), icon: Icon.Clipboard, onAction: fromClipboard }), - Action({ title: t("openWifiForm"), icon: Icon.Shield, onAction: openWifiForm }) + Action({ title: t("fromClipboard"), icon: Icon.Clipboard, shortcut: { modifiers: ["ctrl", "shift"], key: "v" }, onAction: fromClipboard }), + Action({ title: t("openWifiForm"), icon: Icon.Shield, shortcut: { modifiers: ["ctrl"], key: "n" }, onAction: openWifiForm }) ]; const sections: ReturnType[] = []; @@ -276,12 +276,22 @@ export default function QrCodeCommand({ initialWifi = false }: { initialWifi?: b detail: p.detail, actions: ActionPanel({ title: t("qrPanelTitle") }, [ Action({ title: t("copyQrImg"), icon: Icon.CopyClipboard, onAction: () => copyImage(text, level, true) }), - Action({ title: t("saveToHistory"), icon: Icon.Star, onAction: async () => { await run(() => saveQrItem(newItem(text, level)), t("savedToHistoryToast")); } }), - Action({ title: t("saveAsPng"), icon: Icon.Download, onAction: () => saveFile(text, level) }), + Action({ title: t("saveToHistory"), icon: Icon.Star, shortcut: { modifiers: ["ctrl"], key: "p" }, onAction: async () => { await run(() => saveQrItem(newItem(text, level)), t("savedToHistoryToast")); } }), + Action({ title: t("saveAsPng"), icon: Icon.Download, shortcut: { modifiers: ["ctrl"], key: "s" }, onAction: () => saveFile(text, level) }), ...globalActions ]) }) - : List.Item({ id: "live-error", title: p.error, subtitle: t("liveErrorSub"), icon: Icon.ExclamationMark, detail: p.detail }) + : List.Item({ + id: "live-error", + title: p.error, + subtitle: t("liveErrorSub"), + icon: Icon.ExclamationMark, + detail: List.Item.Detail({ markdown: t("liveErrorMd", { error: p.error }) }), + actions: ActionPanel({ title: t("qrPanelTitle") }, [ + ...(level !== "L" ? [Action({ title: t("switchToLevelL"), icon: Icon.ArrowClockwise, onAction: () => setLevel("L") })] : []), + Action({ title: t("clearInput"), icon: Icon.Trash, shortcut: { modifiers: ["ctrl"], key: "backspace" }, onAction: () => setSearchText("") }) + ]) + }) ]) ); } else { @@ -312,11 +322,11 @@ export default function QrCodeCommand({ initialWifi = false }: { initialWifi?: b detail: preview(it.content, it.level).detail, actions: ActionPanel({ title: it.title }, [ Action({ title: t("copyQrImg"), icon: Icon.CopyClipboard, onAction: () => copyImage(it.content, it.level, false) }), - Action({ title: t("copyTextAction"), icon: Icon.Clipboard, onAction: async () => { await Clipboard.copy(it.content); await showToast(Toast.Style.Success, t("copiedTextToast")); } }), - Action({ title: t("saveAsPng"), icon: Icon.Download, onAction: () => saveFile(it.content, it.level) }), - Action({ title: it.favorite ? t("unfavorite") : t("favorite"), icon: Icon.Star, onAction: async () => { await run(() => toggleFavoriteQrItem(it.id), ""); } }), - Action({ title: t("deleteAction"), icon: Icon.Trash, onAction: async () => { await run(() => deleteQrItem(it.id), t("deletedToast")); } }), - Action({ title: t("clearHistoryAction"), icon: Icon.Trash, onAction: clearAll }) + Action({ title: t("copyTextAction"), icon: Icon.Clipboard, shortcut: { modifiers: ["ctrl", "shift"], key: "c" }, onAction: async () => { await Clipboard.copy(it.content); await showToast(Toast.Style.Success, t("copiedTextToast")); } }), + Action({ title: t("saveAsPng"), icon: Icon.Download, shortcut: { modifiers: ["ctrl"], key: "s" }, onAction: () => saveFile(it.content, it.level) }), + Action({ title: it.favorite ? t("unfavorite") : t("favorite"), icon: Icon.Star, shortcut: { modifiers: ["ctrl"], key: "p" }, onAction: async () => { await run(() => toggleFavoriteQrItem(it.id), ""); } }), + Action({ title: t("deleteAction"), icon: Icon.Trash, style: Action.Style.Destructive, shortcut: { modifiers: ["ctrl"], key: "backspace" }, onAction: async () => { await run(() => deleteQrItem(it.id), t("deletedToast")); } }), + Action({ title: t("clearHistoryAction"), icon: Icon.Trash, style: Action.Style.Destructive, onAction: clearAll }) ]) }) ) @@ -324,25 +334,12 @@ export default function QrCodeCommand({ initialWifi = false }: { initialWifi?: b ); } + // 仅保留纯文本粘贴生成二维码能力,不再接受图片文件解码(宿主无 qr_scan 接口) const fileInputProps = createCompatFileInputProps( - async (files) => { - const targetPath = files[0]?.trim(); - if (!targetPath) return; - try { - const decoded = (await decodeQrImageFile(targetPath)).trim(); - setSearchText(decoded); - await showToast(Toast.Style.Success, t("decodedToast"), decoded.slice(0, 60)); - } catch (err: unknown) { - await showToast( - Toast.Style.Failure, - t("decodeFailedToast"), - err instanceof Error ? err.message : String(err) - ); - } + () => { + // 二维码生成插件仅支持文本粘贴生成,忽略文件拖放输入 }, { - extensions: [".png", ".jpg", ".jpeg", ".webp", ".bmp", ".gif"], - allowClipboardImage: true, onTextPaste: (pasted) => { const trimmed = pasted.trim(); if (trimmed) setSearchText(trimmed); @@ -359,6 +356,28 @@ export default function QrCodeCommand({ initialWifi = false }: { initialWifi?: b searchBarPlaceholder: t("searchPlaceholder"), searchText, onSearchTextChange: (v: string) => setSearchText(v), + filterBar: { + actions: [ + { + id: "from-clipboard", + label: t("fromClipboardBtn"), + title: t("fromClipboard"), + icon: Icon.Clipboard, + style: "primary", + onAction: () => { + void fromClipboard(); + } + }, + { + id: "wifi-qr", + label: t("wifiBtn"), + title: t("openWifiForm"), + icon: Icon.Shield, + style: "secondary", + onAction: openWifiForm + } + ] + }, searchBarAccessory: List.Dropdown( { tooltip: t("ecTooltip"), value: level, onChange: (v: string) => setLevel(v as QrErrorCorrectionLevel) }, (["L", "M", "Q", "H"] as QrErrorCorrectionLevel[]).map((l) => List.Dropdown.Item({ title: t("ecOption", { level: levelLabel(l) }), value: l })) diff --git a/extensions/qr-code/tests/index.test.mjs b/extensions/qr-code/tests/index.test.mjs index 24775472..d0923b0a 100644 --- a/extensions/qr-code/tests/index.test.mjs +++ b/extensions/qr-code/tests/index.test.mjs @@ -111,16 +111,37 @@ test('Wi-Fi 表单生成正确内容;界面无彩色 Emoji', async () => { assert.equal(JSON.parse(host.storage.get('ztools_qr_history'))[0].content, 'WIFI:T:WPA;S:家里;P:12345678;;') }) -test('粘贴二维码图片:支持 Ctrl+V 粘贴图片文件调用 qr_scan 解码并填入内容', async () => { - host.ipc.qr_scan = async (params) => { - assert.equal(params.path, '/Users/me/qrcode-sample.png') - return { text: 'https://ztools.cn/docs/paste' } +test('粘贴文本与另存为 PNG:文本粘贴直接生成二维码,保存走真实对话框与写文件链路且不调用 qr_scan', async () => { + let savedDialogParams = null + let writtenFile = null + host.ipc.window_show_save_dialog = async (params) => { + savedDialogParams = params + return { canceled: false, filePath: 'D:\\Exports\\qrcode.png' } } + host.ipc.filesystem_write_file = async (params) => { + writtenFile = params + return { success: true } + } + const view = await mount(QrCodeCommand) - await view.pasteFiles(['/Users/me/qrcode-sample.png']) + await view.pasteText(' https://ztools.cn/docs/paste ') await tick() assert.equal(view.tree().props.searchText, 'https://ztools.cn/docs/paste') - assert.equal(host.lastToast().title, '已识别二维码内容') - assert.ok(view.item('live')) + const live = view.item('live') + assert.ok(JSON.stringify(live.props.detail).includes('data:image/svg+xml')) + + await view.run(live, '另存为 PNG…') + assert.equal(savedDialogParams.defaultName, 'qrcode.png') + assert.equal(writtenFile.path, 'D:\\Exports\\qrcode.png') + assert.equal(writtenFile.encoding, 'base64') + assert.ok(writtenFile.content.startsWith('iVBOR')) + assert.equal(host.lastToast().title, '已保存') + assert.equal(host.ipcCalls.some(([method]) => method === 'qr_scan'), false) + + // 用户取消保存对话框时不得写入文件 + writtenFile = null + host.ipc.window_show_save_dialog = async () => ({ canceled: true }) + await view.run(view.item('live'), '另存为 PNG…') + assert.equal(writtenFile, null) view.unmount() }) diff --git a/extensions/quick-folders/README.en.md b/extensions/quick-folders/README.en.md new file mode 100644 index 00000000..106ff806 --- /dev/null +++ b/extensions/quick-folders/README.en.md @@ -0,0 +1,18 @@ +# Quick Folders + +List common folders for the current user and open the selected directory directly. + +## Usage + +- Command: `Quick Folders` +- Lists common system directories: Desktop, Downloads, Documents, Pictures, Videos (Movies on macOS), Music, and Home directory; Windows additionally includes AppData Roaming, AppData Local, System Drive, and Temp, while macOS additionally includes Applications, Application Support, Library, Caches, and Temp. Only directories that exist on your machine are shown. +- Select a folder and press `Enter` to open it in the file manager, or `Cmd/Ctrl+Enter` (or `Cmd/Ctrl+C`) to copy the full path. +- Use the search box to filter by name, path, or description. + +## Platforms & Requirements + +- Supported: Windows, macOS + +## Network & Data + +- Works offline; no data is saved. diff --git a/extensions/quick-folders/plugin.json b/extensions/quick-folders/plugin.json index 8c9378be..5a2022de 100644 --- a/extensions/quick-folders/plugin.json +++ b/extensions/quick-folders/plugin.json @@ -2,7 +2,8 @@ "id": "quick-folders", "name": "常用文件夹", "description": "一键打开桌面、下载、文档、AppData 与系统临时目录等高频文件夹,免去层层翻找", - "version": "1.1.9", + "version": "1.1.10", + "minAppVersion": "1.1.8.0", "author": "ZTools Team", "entry": "dist/index.js", "icon": "icon.svg", @@ -40,7 +41,12 @@ "desktop", "downloads", "appdata", - "temp" + "temp", + "favorite folders", + "bookmarks folder", + "open desktop", + "open downloads", + "directory shortcuts" ], "screenshots": [ { @@ -56,5 +62,15 @@ { "path": "screenshots/02-action-panel.png" } + ], + "keywords": [ + "常用文件夹", + "快捷目录", + "打开桌面", + "打开下载", + "收藏文件夹", + "快速进目录", + "文件夹收藏", + "直达目录" ] } diff --git a/extensions/quick-folders/src/i18n.ts b/extensions/quick-folders/src/i18n.ts index 89b08bac..18adcfc6 100644 --- a/extensions/quick-folders/src/i18n.ts +++ b/extensions/quick-folders/src/i18n.ts @@ -18,6 +18,9 @@ export const t = createTranslator( pinFolderAction: "置顶此目录", unpinFolderAction: "取消置顶", removeFolderAction: "移除收藏", + confirmRemoveTitle: "移除收藏目录「{name}」?", + confirmRemoveMsg: "仅从收藏列表移除,不会删除磁盘上的原始文件夹。", + confirmCancel: "取消", pinnedTag: "已置顶", customFolderDesc: "自定义收藏目录", sectionCustom: "自定义收藏目录 ({count})", @@ -89,6 +92,9 @@ export const t = createTranslator( pinFolderAction: "Pin Folder", unpinFolderAction: "Unpin Folder", removeFolderAction: "Remove Favorite", + confirmRemoveTitle: "Remove favorite folder \"{name}\"?", + confirmRemoveMsg: "This only removes it from your favorites list and will not delete the folder on disk.", + confirmCancel: "Cancel", pinnedTag: "Pinned", customFolderDesc: "Custom favorite folder", sectionCustom: "Custom Favorites ({count})", diff --git a/extensions/quick-folders/src/index.ts b/extensions/quick-folders/src/index.ts index 371b8f59..917b9b34 100644 --- a/extensions/quick-folders/src/index.ts +++ b/extensions/quick-folders/src/index.ts @@ -11,7 +11,8 @@ import { useLocale, useNavigation, showToast, - Toast + Toast, + confirmAlert } from '@ztools/declarative-ui' import { addCustomFolder, @@ -215,8 +216,15 @@ export default function QuickFoldersCommand() { } } - async function handleRemoveCustom(id: string) { - const next = removeCustomFolder(customFolders, id) + async function handleRemoveCustom(folder: FolderItem) { + const confirmed = await confirmAlert({ + title: t('confirmRemoveTitle', { name: folder.name }), + message: t('confirmRemoveMsg'), + primaryAction: { title: t('removeFolderAction'), style: 'destructive' }, + dismissAction: { title: t('confirmCancel') } + }) + if (!confirmed) return + const next = removeCustomFolder(customFolders, folder.id) if (await persistCustomFolders(next)) { await showToast({ style: Toast.Style.Success, title: t('toastFolderRemoved') }) } @@ -292,7 +300,7 @@ export default function QuickFoldersCommand() { title: t('removeFolderAction'), icon: Icon.Trash, style: Action.Style.Destructive, - onAction: () => handleRemoveCustom(f.id) + onAction: () => handleRemoveCustom(f) }) ] : []) @@ -308,10 +316,24 @@ export default function QuickFoldersCommand() { filterBar: { summaryText: t('summaryText', { systemCount: folders.length, customCount: customFolders.length }), actions: [ - { id: 'add-folder', title: t('addFolderAction'), icon: Icon.Plus, onAction: () => pickAndAddFolder() }, - { id: 'manual-add-folder', title: t('manualAddFolderAction'), icon: Icon.Pencil, onAction: () => openManualAddForm() } + { id: 'add-folder', title: t('addFolderAction'), icon: Icon.Plus, onAction: () => pickAndAddFolder() } ] }, + actions: ActionPanel({ + children: [ + Action({ + title: t('addFolderAction'), + icon: Icon.Plus, + shortcut: { modifiers: ['ctrl'], key: 'n' }, + onAction: () => pickAndAddFolder() + }), + Action({ + title: t('manualAddFolderAction'), + icon: Icon.Pencil, + onAction: () => openManualAddForm() + }) + ] + }), children: [ custom.length > 0 && List.Section({ diff --git a/extensions/quick-folders/src/native-ipc.ts b/extensions/quick-folders/src/native-ipc.ts index 51576b99..13643277 100644 --- a/extensions/quick-folders/src/native-ipc.ts +++ b/extensions/quick-folders/src/native-ipc.ts @@ -174,11 +174,13 @@ function normalizeMethodResult(method: string, payload: DynamicBridge): DynamicB if (method === 'system_get_battery_status') { // 宿主约定 percent 超出 0-100(如 255)表示无电池或电量未知,不能改写成 100% + // 若宿主明确给出 hasBattery 布尔值,必须原样保留,仅在缺失时按合法电量推算 const rawPct = payload.percent - const hasBattery = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const validPct = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const hasBattery = typeof payload.hasBattery === 'boolean' ? payload.hasBattery : validPct return { ...payload, - percent: hasBattery ? rawPct : null, + percent: validPct ? rawPct : null, hasBattery } } @@ -489,6 +491,8 @@ export interface RealDirectoryScanResult extends Iterable approximate?: boolean /** 宿主实际遍历的条目数 */ visitedEntries?: number + /** 目录本身不存在(ENOENT) */ + missing?: boolean /** 读取失败的真实原因;已有文件仍可使用,但不能当作完整结果。 */ error?: string } @@ -497,6 +501,7 @@ interface ScanResultMeta { truncated?: boolean approximate?: boolean visitedEntries?: number + missing?: boolean } export interface ScanDirectoryTreeOptions { @@ -504,6 +509,10 @@ export interface ScanDirectoryTreeOptions { maxFiles?: number collectTopN?: number filterExt?: RegExp + /** 为 true 时,目录本身不存在(ENOENT)按空目录处理,不返回 error(权限拒绝/读取失败仍照常报错) */ + ignoreMissing?: boolean + /** Top-N 保留与排序方式:默认按体积降序,下载/录屏等时效场景可传 mtime-desc */ + sortBy?: 'size-desc' | 'mtime-desc' hostOverride?: DynamicBridge } @@ -519,8 +528,9 @@ function normalizeIndexedFileEntry(f: DynamicBridge): RealIndexedFileEntry { const sz = Number(f?.size ?? f?.sizeBytes ?? 0) const isDir = Boolean(f?.is_dir || f?.isDir || f?.isDirectory) const rawMtime = Number(f?.mtime ?? f?.mtimeMs ?? 0) - const mtimeMs = rawMtime > 1e11 ? rawMtime : rawMtime > 0 ? rawMtime * 1000 : Date.now() - const mtimeSec = rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime + const validMtime = Number.isFinite(rawMtime) && rawMtime > 0 + const mtimeMs = validMtime ? (rawMtime > 1e11 ? rawMtime : rawMtime * 1000) : 0 + const mtimeSec = validMtime ? (rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime) : 0 if (p && sz >= 0) realFileSizeCache.set(p, sz) return { name, @@ -551,6 +561,7 @@ function makeScanResult( subdirs, ...(meta.truncated ? { truncated: true } : {}), ...(meta.approximate ? { approximate: true } : {}), + ...(meta.missing ? { missing: true } : {}), ...(typeof meta.visitedEntries === 'number' ? { visitedEntries: meta.visitedEntries } : {}), [Symbol.iterator]() { return files[Symbol.iterator]() @@ -609,13 +620,40 @@ export async function scanRealDirectoryTree( return result.error ? { ...result.scan, error: result.error } : result.scan } +/** 仅当正则明确声明了扩展名(含 `\.`)时提取后缀列表,避免把 `thumbcache|iconcache` 等文件名关键词误拆成假扩展名 */ +function extractExtensionTokensFromFilter(filterExt: RegExp): string[] { + const src = filterExt.source + if (!src.includes('\\.')) return [] + const afterDot = src.slice(src.indexOf('\\.') + 2) + const rawTokens = afterDot.match(/[a-z0-9]{1,8}/gi) || [] + const seen = new Set() + const out: string[] = [] + for (const token of rawTokens) { + const lower = token.toLowerCase() + if (!lower || seen.has(lower)) continue + seen.add(lower) + out.push(lower) + } + return out +} + +function isMissingDirectoryError(res: { error?: string; errorCode?: string; errorDetails?: Record }): boolean { + if (res.errorDetails?.reason === 'ENOENT' || res.errorCode === 'ENOENT') return true + const msg = String(res.error || '') + return /Directory does not exist|ENOENT/i.test(msg) +} + /** 一次界面扫描的错误汇总;多个目录并行扫描时保留可读目录的结果。 */ export function createDirectoryScanner(hostOverride?: DynamicBridge) { const failures = new Map() return { async scan(dir: string, options: number | ScanDirectoryTreeOptions = 160) { const result = await scanRealDirectoryTree(dir, options, hostOverride) - const error = result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') + const ignoreMissing = typeof options === 'object' && options !== null && options.ignoreMissing === true + const error = + result.missing && ignoreMissing + ? '' + : result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') if (error) failures.set(dir, error) else failures.delete(dir) return result @@ -648,26 +686,38 @@ async function scanDirectoryTreeWithError( const safeLimit = Math.min(200, Math.max(1, Math.floor(rawLimit || 160))) const hostOverride = opts.hostOverride const filterExt = opts.filterExt + const ignoreMissing = opts.ignoreMissing === true const dirQuery = `dir:${targetDir}` try { let rawPayload: DynamicBridge = null + const searchParams: Record = { + query: dirQuery, + limit: safeLimit, + ...(opts.sortBy ? { sortBy: opts.sortBy } : {}) + } const res = await callHostTransport( 'system_search_files', - { query: dirQuery, limit: safeLimit }, + searchParams, hostOverride ) - if (res.ok && res.data) { + if (res.ok && res.data && res.data.degraded !== true) { rawPayload = res.data + } else if (!res.ok && ignoreMissing && isMissingDirectoryError(res)) { + const missingScan = makeScanResult([], 0, 0, [], { missing: true }) + return { scan: missingScan } } - if (!rawPayload && !hostOverride && typeof window !== 'undefined') { + if (!rawPayload && !hostOverride && res.errorCode === 'METHOD_NOT_AVAILABLE' && typeof window !== 'undefined') { const w = window as DynamicBridge if (typeof w.__ztoolsLauncher?.searchFiles === 'function') { const rawOuter = await w.__ztoolsLauncher.searchFiles(dirQuery, safeLimit) - rawPayload = + const candidate = rawOuter && typeof rawOuter === 'object' && 'data' in rawOuter && rawOuter.data ? rawOuter.data : rawOuter + if (candidate && candidate.degraded !== true && candidate.success !== false) { + rawPayload = candidate + } } } @@ -678,29 +728,32 @@ async function scanDirectoryTreeWithError( let files: RealIndexedFileEntry[] = rawPayload.files.map(normalizeIndexedFileEntry) if (filterExt instanceof RegExp) { files = files.filter(f => !f.isDir && (filterExt.test(f.name) || filterExt.test(f.ext))) - // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索目标扩展名 + // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索明确声明的目标扩展名 if (files.length === 0 && !hostOverride) { - const extTokens = (filterExt.source.match(/[a-z0-9]{2,5}/gi) || []) - .filter(t => !['thumbcache', 'iconcache'].includes(t.toLowerCase())) - .slice(0, 4) - // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 - const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() - const extraLists = await Promise.all( - extTokens.map(ext => searchRealIndexedFiles(`.${ext.toLowerCase()}`, 30, hostOverride)) - ) - const seen = new Set() - for (const list of extraLists) { - for (const item of list) { - if (!item.isDir && item.size > 0 && !seen.has(item.path)) { - if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { - seen.add(item.path) - files.push(item) + const extTokens = extractExtensionTokensFromFilter(filterExt) + if (extTokens.length > 0) { + // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 + const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() + const extraLists = await Promise.all( + extTokens.map(ext => searchRealIndexedFiles(`.${ext}`, 30, hostOverride)) + ) + const seen = new Set() + for (const list of extraLists) { + for (const item of list) { + if (!item.isDir && item.size > 0 && !seen.has(item.path)) { + if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { + seen.add(item.path) + files.push(item) + } } } } } } } + // 先基于过滤后的完整命中集合计算总文件数与总字节数,再按 collectTopN 裁剪样本列表 + const matchedCount = files.length + const matchedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) if (typeof opts.collectTopN === 'number' && opts.collectTopN > 0 && files.length > opts.collectTopN) { files = files.slice(0, opts.collectTopN) } @@ -714,11 +767,10 @@ async function scanDirectoryTreeWithError( ...(s.approximate === true ? { approximate: true } : {}) })) : [] - const computedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) const totalFilesCount = - filterExt instanceof RegExp ? files.length : Number(rawPayload.total_matches ?? files.length) + filterExt instanceof RegExp ? matchedCount : Number(rawPayload.total_matches ?? matchedCount) const totalBytesCount = - filterExt instanceof RegExp ? computedBytes : Number(rawPayload.total_bytes ?? computedBytes) + filterExt instanceof RegExp ? matchedBytes : Number(rawPayload.total_bytes ?? matchedBytes) const visited = Number(rawPayload.visited_entries) return { scan: makeScanResult(files, totalFilesCount, totalBytesCount, subdirs, { @@ -1817,8 +1869,6 @@ export async function writeRealClipboardText(text: string, hostOverride?: Dynami const payload = { text: String(text || '') } const res = await callHostTransport('clipboard_copy_text', payload, hostOverride) if (res.ok) return true - const fallbackRes = await callHostTransport('clipboard_write_text', payload, hostOverride) - if (fallbackRes.ok) return true try { if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) { await navigator.clipboard.writeText(String(text || '')) diff --git a/extensions/quick-folders/tests/quick-folders.favorites.test.mjs b/extensions/quick-folders/tests/quick-folders.favorites.test.mjs index 9baac328..89dd91d5 100644 --- a/extensions/quick-folders/tests/quick-folders.favorites.test.mjs +++ b/extensions/quick-folders/tests/quick-folders.favorites.test.mjs @@ -90,9 +90,9 @@ test('自定义收藏:对话框不支持时降级到手动添加表单,并 assert.ok(saved) assert.equal(saved.props.title, '主工程') - // 重复添加同一路径被拒绝 - const manualBtn = view.tree().props.filterBar.actions.find(a => a.id === 'manual-add-folder') - await manualBtn.onAction() + // 重复添加同一路径被拒绝(顶栏已去重为 1 个按钮,手动添加在动作面板) + assert.equal(view.tree().props.filterBar.actions.length, 1) + await view.run(undefined, '手动添加目录') await tick() const dupForm = await mountPushed(host) try { diff --git a/extensions/quicklinks/README.en.md b/extensions/quicklinks/README.en.md new file mode 100644 index 00000000..ad413375 --- /dev/null +++ b/extensions/quicklinks/README.en.md @@ -0,0 +1,21 @@ +# Quicklinks & Web Groups + +Save frequently used URLs and search links to launch directly from the search box using "alias + keyword", or open an entire group of web pages at once. + +## Usage + +- Commands: `quicklinks` (`web links`, `shortcuts`, `wk`); search links only: `multi search` (`search engines`, `quick search`); URL groups only: `open url group` (`workflow tabs`, `batch urls`); create new: `add quicklink` (`new quicklink`, `create url group`). +- URLs can include a `{query}` placeholder. Type "alias + space + keyword" (such as `gh react`) in the search box and press `Enter` to substitute the keyword and open the URL; omitting the keyword opens the site's home page. +- Select an item and press `Enter` to open in your system default browser (URL groups open each URL in sequence and report how many opened if any fail midway), `Cmd/Ctrl+Enter` to edit, `Cmd/Ctrl+Backspace` to delete (requires confirmation), or `Cmd/Ctrl+K` to copy the URL template (search links copy the template with `{query}`, while URL groups copy all URLs in the group). +- Pre-populated on fresh install with GitHub, Zhihu, Bilibili, Google, Xiaohongshu Search, DeepSeek, and a sample URL group (existing saved data is untouched). Click "New Quicklink" at the top to choose a single link or URL group; enter one URL per line for URL groups when creating or editing. +- Aliases cannot contain spaces and must be unique across all entries. +- Clicking "Reset Default Presets" at the top replaces all saved links with the default preset list after confirmation. +- Accepts only `http(s)` URLs or domains with valid hostnames; `javascript:` URLs and URLs containing embedded credentials are rejected. + +## Platforms & Requirements + +- Supported: Windows, macOS + +## Network & Data + +- The plugin makes no network requests of its own and only hands URLs off to your system default browser; quicklinks are saved strictly on your local device. diff --git a/extensions/quicklinks/plugin.json b/extensions/quicklinks/plugin.json index 2bfc15ee..f943eac7 100644 --- a/extensions/quicklinks/plugin.json +++ b/extensions/quicklinks/plugin.json @@ -1,7 +1,8 @@ { "id": "quicklinks", "name": "网页快开", - "version": "1.1.6", + "version": "1.1.7", + "minAppVersion": "1.1.8.0", "description": "聚合多平台快捷搜索与工作流网址组批量打开,支持自定义 {query} 变量与热键直达", "author": "ZTools Team", "category": [ @@ -80,7 +81,12 @@ "urls", "bookmarks", "workflow", - "web" + "web", + "web shortcuts", + "open website", + "custom search", + "url launcher", + "web groups" ], "features": { "quicklinks-all": { @@ -131,5 +137,15 @@ { "path": "screenshots/02-action-panel.png" } + ], + "keywords": [ + "网页快开", + "快捷网址", + "常用网站", + "一键开网页", + "自定义搜索", + "网址收藏", + "快速打开网站", + "quicklinks" ] } diff --git a/extensions/quicklinks/src/i18n.ts b/extensions/quicklinks/src/i18n.ts index efd1f55d..50ad4fb6 100644 --- a/extensions/quicklinks/src/i18n.ts +++ b/extensions/quicklinks/src/i18n.ts @@ -72,6 +72,11 @@ const MESSAGES = { actionCopyGroupUrls: "复制组内全部网址", actionCopyUrl: "复制目标网址", actionDelete: "删除此快捷链接", + emptyNoLinksTitle: "还没有快捷链接,按回车新建", + emptyNoLinksSub: "添加常用网站、带 {query} 搜索模板或一键网址组", + emptyNoMatchTitle: "没有匹配的快捷链接", + emptyNoMatchSub: "换个关键词或分类,按 Enter 新建快捷链接", + actionResetFilter: "清除搜索与分类筛选", // quicklinks-storage.ts defQl1Title: "GitHub 代码与仓库搜索", defQl1Desc: "检索 GitHub 全球开源仓库、代码与 Issue", @@ -176,6 +181,11 @@ const MESSAGES = { actionCopyGroupUrls: "Copy All Group URLs", actionCopyUrl: "Copy Target URL", actionDelete: "Delete Quicklink", + emptyNoLinksTitle: "No quicklinks yet — press Enter to create", + emptyNoLinksSub: "Add websites, {query} search templates, or URL groups", + emptyNoMatchTitle: "No matching quicklinks", + emptyNoMatchSub: "Try another keyword or category, or press Enter to create one", + actionResetFilter: "Reset Search & Filter", // quicklinks-storage.ts defQl1Title: "GitHub Code & Repo Search", defQl1Desc: "Search GitHub repositories, code, and issues", diff --git a/extensions/quicklinks/src/index.tsx b/extensions/quicklinks/src/index.tsx index d1b3e2f0..fb6ed808 100644 --- a/extensions/quicklinks/src/index.tsx +++ b/extensions/quicklinks/src/index.tsx @@ -124,6 +124,7 @@ export function CreateQuicklinkForm({ placeholder={isGroup ? t('titleGroupPlaceholder') : t('titleSinglePlaceholder')} value={title} onChange={setTitle} + autoFocus={true} /> {isGroup ? ( } > - + {isGroup ? ( ) @@ -379,6 +381,15 @@ export function QuicklinksCommand(props: QuicklinksCommandProps = {}) { await showToast({ style: Toast.Style.Success, title: t('deletedToast', { title: item.title }) }) } + const handleOpenCreate = () => { + push( + setLinks((prev) => [created, ...prev])} + /> + ) + } + const handleOpenImport = () => { push( setLinks(next)} />) } @@ -413,6 +424,12 @@ export function QuicklinksCommand(props: QuicklinksCommandProps = {}) { searchBarPlaceholder={t('searchPlaceholder')} actions={ + + } searchBarAccessory={ { setSelectedCategory(val as 'all' | QuicklinkCategory); setSearchText('') }} + onChange={(val) => setSelectedCategory(val as 'all' | QuicklinkCategory)} tooltip={t('categoryTooltip')} > @@ -445,22 +468,39 @@ export function QuicklinksCommand(props: QuicklinksCommandProps = {}) { { id: 'create', title: t('createBtn'), - onAction: () => - push( - setLinks((prev) => [created, ...prev])} - /> - ) - }, - { - id: 'reset-default', - title: t('resetBtn'), - onAction: handleResetDefaults + onAction: handleOpenCreate } ] }} > + {filtered.matches.length === 0 ? ( + + + {links.length > 0 ? ( + { + setSelectedCategory('all') + setSearchText('') + }} + /> + ) : null} + + } + /> + ) : null} {filtered.matches.map((item) => { const alias = item.alias || item.keyword const pattern = item.urlPattern || item.link @@ -518,18 +558,6 @@ export function QuicklinksCommand(props: QuicklinksCommandProps = {}) { shortcut={{ modifiers: ['ctrl'], key: 'backspace' }} onAction={() => handleDelete(item)} /> - - } /> diff --git a/extensions/quicklinks/tests/commands.test.mjs b/extensions/quicklinks/tests/commands.test.mjs index dd3d4417..4b429826 100644 --- a/extensions/quicklinks/tests/commands.test.mjs +++ b/extensions/quicklinks/tests/commands.test.mjs @@ -67,7 +67,7 @@ test('损坏数据和读取失败不替换为默认;新建无法覆盖原数 } }) -test('搜索与网址组快捷入口按类型筛选,切换类型清理旧查询', async () => { +test('搜索与网址组快捷入口按类型筛选,切换类型保留当前查询', async () => { for (const [feature, category] of [['quicklinks-search-engines', 'search'], ['quicklinks-open-groups', 'group']]) { setup() const view = await mount(commands[feature]) @@ -75,7 +75,8 @@ test('搜索与网址组快捷入口按类型筛选,切换类型清理旧查 assert.equal(view.tree().props.searchBarAccessory.props.value, category) assert.ok(view.items().length > 0) await view.search('无结果'); await view.dropdown('all') - assert.equal(view.tree().props.searchText, '') + assert.equal(view.tree().props.searchText, '无结果') + await view.search('') assert.equal(view.items().length, getDefaultQuicklinks().length) } finally { view.unmount() } } @@ -209,7 +210,7 @@ test('恢复默认需确认;保存失败提示失败且不显示成功', async await saveQuicklinks([{ id: 'mine', title: '自定义', link: 'https://example.com/' }]) const before = data.get(key) const view = await mount(QuicklinksCommand) - const reset = () => view.tree().props.filterBar.actions.find((a) => a.id === 'reset-default').onAction() + const reset = () => view.run(null, '恢复默认预设') try { host.setConfirm(false); await reset() assert.equal(data.get(key), before); assert.equal(host.toasts.length, 0) @@ -276,14 +277,14 @@ test('回归:主视图支持导出 JSON 到剪贴板与挂载 ImportQuicklinks const { host } = setup() const view = await mount(QuicklinksCommand) try { - // 1. 导出全部为 JSON - await view.run(view.item('ql-1'), '导出全部为 JSON') + // 1. 导出全部为 JSON(通过 List.actions 全局面板) + await view.run(null, '导出全部为 JSON') const exported = JSON.parse(host.clipboard.text) assert.ok(Array.isArray(exported) && exported.length === getDefaultQuicklinks().length) assert.equal(host.lastToast().style, 'SUCCESS') // 2. 通过主视图动作打开 ImportQuicklinksForm 导入 JSON - await view.run(view.item('ql-1'), '导入 JSON') + await view.run(null, '导入 JSON') const form = await mountPushed(host) try { assert.equal(form.tree().type, 'Form') diff --git a/extensions/record/README.en.md b/extensions/record/README.en.md new file mode 100644 index 00000000..945c80d8 --- /dev/null +++ b/extensions/record/README.en.md @@ -0,0 +1,21 @@ +# Screen Recorder + +Record the entire desktop (all monitors) as an MP4 video or animated GIF with selectable frame rate. Does not record audio; requires local `ffmpeg`. + +## Usage + +- Command: `Screen Recorder` (main plugin command). +- Choose the frame rate (15 / 30 / 60 FPS) and output format (MP4 / GIF) on the left, then click "Start Recording" at the top or press `Ctrl+Shift+R` to start; click again or press `Ctrl+Shift+R` to stop and save. +- Records the entire desktop only—regional or single-window recording is not supported, and neither system audio nor microphone audio is recorded. +- A second recording cannot start while one is already in progress; starting fails with an error if `ffmpeg` is not installed locally or cannot be invoked directly from the command line. +- Recording continues after leaving the plugin view; reopening the plugin shows "Recording" so you can stop and save there. Exiting ZTools stops any active recording and saves the file. +- Recordings are saved to `ZTools_Recordings` inside your system Videos folder and listed on the right in reverse chronological order: `Enter` opens the file, `Ctrl+Enter` reveals it in folder, and `Ctrl+K` opens the action panel (including Copy File Path). + +## Platforms & Requirements + +- Supported: Windows only +- Windows implementation is pending real-device verification. + +## Network & Data + +- Works offline; data stays strictly on your local device. diff --git a/extensions/record/plugin.json b/extensions/record/plugin.json index 6c359c0e..62b9704c 100644 --- a/extensions/record/plugin.json +++ b/extensions/record/plugin.json @@ -1,8 +1,9 @@ { "id": "record", "name": "屏幕录制", - "description": "录制整个桌面(所有显示器)为 MP4 视频或 GIF 动图,可选帧率;不录制声音,需要本机已安装 ffmpeg", - "version": "2.0.10", + "description": "通过宿主媒体采集与转码原语录制全屏、指定窗口或自定义区域为 MP4/WebM/GIF,支持系统音频回采与麦克风开关、录制后媒体探测与二次转码裁切、任务取消及引擎按需准备", + "version": "2.1.0", + "minAppVersion": "1.3.0.2", "author": "ZTools Team", "entry": "dist/index.js", "icon": "icon.svg", @@ -10,8 +11,16 @@ "图像媒体" ], "categoryId": "media", + "requiredCapabilities": [ + "media.capture", + "media.probe", + "media.transcode" + ], "permissions": [ - "video", + "screen", + "media.read", + "media.process", + "dialog", "fs", "shell", "clipboard" @@ -30,14 +39,23 @@ "i18n": { "en-US": { "name": "Screen Recorder", - "description": "Record your full desktop (all displays) to MP4 video or animated GIF with selectable frame rate (no audio; requires local ffmpeg).", + "description": "Capture full screen, a specific window, or a custom region to MP4, WebM, or GIF with system audio loopback, microphone toggle, media probing, post-recording transcode/trim, task cancellation, and on-demand engine provisioning.", "keywords": [ "screen record", "recorder", + "window capture", + "region capture", "mp4", + "webm", "gif", - "capture", - "ffmpeg" + "audio loopback", + "screen recorder", + "record screen", + "video capture", + "screen capture", + "recording", + "screencast", + "gif recorder" ], "screenshots": [ { @@ -53,5 +71,16 @@ { "path": "screenshots/02-action-panel.png" } + ], + "keywords": [ + "录屏", + "屏幕录制", + "录制视频", + "录桌面", + "录gif", + "录教学", + "录像", + "电脑录屏", + "screen record" ] } diff --git a/extensions/record/src/i18n.ts b/extensions/record/src/i18n.ts index fca4a87d..3f0f0e82 100644 --- a/extensions/record/src/i18n.ts +++ b/extensions/record/src/i18n.ts @@ -1,150 +1,246 @@ -import { createTranslator } from "@ztools/declarative-ui"; +import { createTranslator } from '@ztools/declarative-ui' const MESSAGES = { - "zh-CN": { - openFailedTitle: "无法打开录制文件", - revealFailedTitle: "无法在文件夹中显示", - copiedPathToast: "已复制文件路径", - copyFailedToast: "复制失败", - unknownExt: "未知", - sizeUnknown: "大小未知", - openRecording: "打开录制文件", - revealInFolder: "在文件夹中显示", - copyFilePath: "复制文件路径", - readFilesFailed: "读取录制文件失败", - rescannedTitle: "已重新扫描", - rescannedMsg: "保存目录中有 {count} 个录制文件{partial}", - partialSuffix: "(仅取回部分)", - readInfoFailed: "读取录制信息失败", - startFailedTitle: "录制启动失败", - writingMsg: "正在写入 {dir}。录制的是整个桌面,回到本插件停止并保存。", - defaultSaveDir: "默认保存目录", - stopFailedTitle: "停止录制失败", - sizeParen: "({size})", - stopRecordingSave: "停止录制并保存", - startRecording: "开始录制", - statusRecording: "正在录制", - statusIdle: "未在录制", - statusUnknownErr: "录制状态未知({error})", - statusLoading: "正在读取录制状态", - listReadFailed: "录制文件读取失败:{error}", - listSummary: "{count} 个录制文件{partial}", - emptyReadFailed: "读取保存目录失败:{error}", - emptyNoMatch: "没有匹配的录制文件", - emptyNoRecordings: "还没有录制文件,开始录制后会保存到这里", - searchPlaceholder: "搜索录制文件名...", - rescan: "重新扫描", - wbTitle: "录制参数", - wbSubtitle: "整个桌面 · 不录声音", - wbFpsLabel: "帧率", - wbFormatLabel: "输出格式", - wbScopeLabel: "录制范围", - wbScopeValue: "整个桌面", - wbAudioLabel: "声音", - wbAudioValue: "不录制", - wbCardTitle: "录制说明", - badgeRecording: "录制中", - badgeIdle: "未在录制", - badgeUnknown: "状态未知", - metricStartTime: "开始时间", - metricOutputFile: "输出文件", - unknownValue: "未知", - subListTitle: "录制文件(按时间倒序,↵ 打开)", - subListSubtitle: "{count} 个 · {size} · 保存目录:{dir}", - panelTitle: "屏幕录制", - sectionTitle: "录制文件 ({count})", - // logic.ts - formatMp4: "MP4 视频", - formatGif: "GIF 动图", - limitationNote: "录制整个桌面(所有显示器)的画面,不录制声音。需要本机已安装 ffmpeg,并能在命令行中直接运行。", - timeUnknown: "时间未知", - hostCallFailed: "录制接口 {func} 调用失败", - hostInvalidResult: "录制接口 {func} 返回了无法识别的结果", - hostReturnedFailure: "录制接口 {func} 返回失败", - hostNoRecordingStatus: "客户端没有返回录制状态", - noVideosFolder: "未能获取系统视频文件夹路径", - readSaveDirFailed: "读取保存目录失败", - unrecognizedDirContent: "客户端返回的目录内容无法识别", - queryStatusFailed: "查询录制状态失败", - invalidRecordConfig: "录制参数无效", - recordBusy: "上一个录制操作还没有完成", - cannotConfirmStatus: "无法确认当前录制状态:{error}", - alreadyRecording: "已有录制正在进行,请先停止", - recordingStarted: "已开始录制({fps} FPS,{format})", - recordingSaved: "录制已保存" + 'zh-CN': { + openFailedTitle: '无法打开录制文件', + revealFailedTitle: '无法在文件夹中显示', + copiedPathToast: '已复制文件路径', + copyFailedToast: '复制失败', + unknownExt: '未知', + sizeUnknown: '大小未知', + openRecording: '打开录制文件', + revealInFolder: '在文件夹中显示', + copyFilePath: '复制文件路径', + probeRecording: '探测视频元信息', + transcodeToMp4: '转码为 MP4', + transcodeToWebm: '转码为 WebM', + transcodeToGif: '导出为 GIF 动图', + trimRecording: '按配置裁切导出', + cancelActiveTask: '取消当前任务', + ensureRuntimeAction: '准备媒体引擎', + chooseSaveDir: '更改保存目录', + refreshSources: '刷新采集源', + readFilesFailed: '读取录制文件失败', + rescannedTitle: '已重新扫描', + rescannedMsg: '保存目录中有 {count} 个录制文件{partial}', + partialSuffix: '(仅取回部分)', + readInfoFailed: '读取录制信息失败', + startFailedTitle: '录制启动失败', + writingMsg: '正在写入 {dir},模式:{mode}。回到本插件可停止并保存。', + defaultSaveDir: '默认保存目录', + stopFailedTitle: '停止录制失败', + cancelSuccessTitle: '任务已取消', + cancelFailedTitle: '取消任务失败', + sizeParen: '({size})', + stopRecordingSave: '停止录制并保存', + startRecording: '开始录制', + statusRecording: '正在录制', + statusIdle: '就绪', + statusProvisionNeeded: '需按需准备媒体引擎', + statusUnsupported: '当前宿主暂不支持录屏原语', + statusUnknownErr: '录制状态未知({error})', + statusLoading: '正在读取录制状态', + listReadFailed: '录制文件读取失败:{error}', + listSummary: '{count} 个录制文件{partial}', + emptyReadFailed: '读取保存目录失败:{error}', + emptyNoMatch: '没有匹配的录制文件', + emptyNoRecordings: '还没有录制文件,开始录制后会保存到这里', + searchPlaceholder: '搜索录制文件名...', + rescan: '重新扫描', + wbTitle: '录制参数', + wbSubtitle: '{mode} · {audio}', + wbModeLabel: '录制模式', + wbSourceLabel: '采集源', + wbRegionLabel: '选区矩形 (x,y,w,h)', + wbScaleLabel: '缩放倍率 (DPI)', + wbFpsLabel: '帧率', + wbFormatLabel: '输出格式', + wbSystemAudioLabel: '系统音频回采', + wbMicLabel: '麦克风输入', + wbTrimStartLabel: '后期裁切起点(秒)', + wbTrimDurationLabel: '后期裁切时长(秒)', + wbCardTitle: '引擎与录制状态', + badgeRecording: '录制中', + badgeIdle: '就绪', + badgeProvision: '待准备引擎', + badgeUnsupported: '未支持', + badgeUnknown: '状态未知', + metricStartTime: '开始时间', + metricOutputFile: '输出文件', + metricSourcesCount: '可用采集源', + metricProbeInfo: '最近探测', + unknownValue: '未知', + subListTitle: '录制文件(按时间倒序,Enter 打开)', + subListSubtitle: '{count} 个 · {size} · 保存目录:{dir}', + panelTitle: '屏幕录制', + sectionTitle: '录制文件 ({count})', + modeFullscreen: '全屏录制', + modeWindow: '指定窗口', + modeRegion: '自定义区域', + audioBoth: '系统声音 + 麦克风', + audioSystemOnly: '仅系统声音', + audioMicOnly: '仅麦克风', + audioMuted: '静音', + toggleOn: '开启', + toggleOff: '关闭', + formatMp4: 'MP4 视频', + formatWebm: 'WebM 视频', + formatGif: 'GIF 动图', + limitationNote: '基于宿主 media.capture / media.probe / media.transcode 薄原语,零本机 PATH 依赖;窗口与区域模式精准透传 sourceId 与 DPI 选区坐标。', + provisionPromptNote: '检测到媒体引擎尚未就绪,可点击「准备媒体引擎」按需下载并校验签名运行组件。', + timeUnknown: '时间未知', + hostCallFailed: '宿主原语 {method} 调用失败', + hostInvalidResult: '宿主原语 {method} 返回了无法识别的结果', + hostNoRecordingStatus: '客户端没有返回录制状态', + noVideosFolder: '未能获取系统视频文件夹路径', + readSaveDirFailed: '读取保存目录失败', + unrecognizedDirContent: '客户端返回的目录内容无法识别', + queryStatusFailed: '查询录制状态失败', + invalidRecordConfig: '录制参数无效', + missingSaveDir: '请先设置录制文件保存目录', + missingCaptureSource: '请先选择有效的屏幕或窗口采集源', + invalidRegionConfig: '区域录制需要合法的坐标与正数宽高(格式:x,y,width,height)', + recordBusy: '上一个录制操作还没有完成', + cannotConfirmStatus: '无法确认当前录制状态:{error}', + alreadyRecording: '已有录制正在进行,请先停止或取消', + recordingStarted: '已开始录制({mode} · {fps} FPS · {format})', + recordingSaved: '录制已保存', + ensureSuccessTitle: '媒体引擎已就绪', + ensureFailedTitle: '媒体引擎准备失败', + probeSuccessTitle: '媒体探测完成', + probeFailedTitle: '媒体探测失败', + transcodeStartTitle: '正在转码导出', + transcodeSuccessTitle: '后期导出完成', + transcodeFailedTitle: '后期导出失败', + noActiveTaskToCancel: '当前没有可取消的活动任务', + pickSaveDirTitle: '选择录制文件保存目录', + saveDirUpdatedTitle: '已更新保存目录', + noSourceAvailable: '暂无可用采集源', + sourceKindScreen: '屏幕', + sourceKindWindow: '窗口', + probeSummary: '{duration} · {resolution} · {codec}', + invalidTrimRange: '裁切参数无效:起点必须 >= 0 且时长 > 0' }, - "en-US": { - openFailedTitle: "Failed to open recording", - revealFailedTitle: "Failed to reveal in folder", - copiedPathToast: "File path copied", - copyFailedToast: "Copy failed", - unknownExt: "Unknown", - sizeUnknown: "Size unknown", - openRecording: "Open Recording", - revealInFolder: "Reveal in Folder", - copyFilePath: "Copy File Path", - readFilesFailed: "Failed to read recordings", - rescannedTitle: "Rescanned", - rescannedMsg: "{count} recording(s) in save folder{partial}", - partialSuffix: " (partial)", - readInfoFailed: "Failed to read recording info", - startFailedTitle: "Failed to start recording", - writingMsg: "Writing to {dir}. Capturing full desktop; return here to stop and save.", - defaultSaveDir: "default folder", - stopFailedTitle: "Failed to stop recording", - sizeParen: " ({size})", - stopRecordingSave: "Stop & Save", - startRecording: "Start Recording", - statusRecording: "Recording", - statusIdle: "Idle", - statusUnknownErr: "Status unknown ({error})", - statusLoading: "Checking status", - listReadFailed: "Failed to list files: {error}", - listSummary: "{count} recording(s){partial}", - emptyReadFailed: "Failed to read save folder: {error}", - emptyNoMatch: "No matching recordings", - emptyNoRecordings: "No recordings yet; started recordings will appear here", - searchPlaceholder: "Search recordings...", - rescan: "Rescan", - wbTitle: "Recording Settings", - wbSubtitle: "Full Desktop · No Audio", - wbFpsLabel: "Frame Rate", - wbFormatLabel: "Format", - wbScopeLabel: "Capture Scope", - wbScopeValue: "Full Desktop", - wbAudioLabel: "Audio", - wbAudioValue: "Muted", - wbCardTitle: "Notes", - badgeRecording: "Recording", - badgeIdle: "Idle", - badgeUnknown: "Unknown", - metricStartTime: "Started", - metricOutputFile: "Output File", - unknownValue: "Unknown", - subListTitle: "Recordings (Newest first, ↵ to open)", - subListSubtitle: "{count} item(s) · {size} · Folder: {dir}", - panelTitle: "Screen Recorder", - sectionTitle: "Recordings ({count})", - // logic.ts - formatMp4: "MP4 Video", - formatGif: "GIF Animation", - limitationNote: "Captures the entire desktop (all displays) without audio. Requires ffmpeg installed and available in PATH.", - timeUnknown: "Unknown time", - hostCallFailed: "Recorder API {func} call failed", - hostInvalidResult: "Recorder API {func} returned unrecognized data", - hostReturnedFailure: "Recorder API {func} failed", - hostNoRecordingStatus: "Host did not return recording status", - noVideosFolder: "Could not resolve system Videos folder", - readSaveDirFailed: "Failed to read save folder", - unrecognizedDirContent: "Host returned unrecognized directory listing", - queryStatusFailed: "Failed to query recording status", - invalidRecordConfig: "Invalid recording configuration", - recordBusy: "Previous recording operation is still in progress", - cannotConfirmStatus: "Cannot confirm recording status: {error}", - alreadyRecording: "A recording is already in progress; stop it first", - recordingStarted: "Recording started ({fps} FPS, {format})", - recordingSaved: "Recording saved" + 'en-US': { + openFailedTitle: 'Failed to open recording', + revealFailedTitle: 'Failed to reveal in folder', + copiedPathToast: 'File path copied', + copyFailedToast: 'Copy failed', + unknownExt: 'Unknown', + sizeUnknown: 'Size unknown', + openRecording: 'Open Recording', + revealInFolder: 'Reveal in Folder', + copyFilePath: 'Copy File Path', + probeRecording: 'Probe Media Info', + transcodeToMp4: 'Transcode to MP4', + transcodeToWebm: 'Transcode to WebM', + transcodeToGif: 'Export as GIF', + trimRecording: 'Trim & Export', + cancelActiveTask: 'Cancel Active Task', + ensureRuntimeAction: 'Prepare Media Engine', + chooseSaveDir: 'Change Save Folder', + refreshSources: 'Refresh Capture Sources', + readFilesFailed: 'Failed to read recordings', + rescannedTitle: 'Rescanned', + rescannedMsg: '{count} recording(s) in save folder{partial}', + partialSuffix: ' (partial)', + readInfoFailed: 'Failed to read recording info', + startFailedTitle: 'Failed to start recording', + writingMsg: 'Writing to {dir} ({mode}). Return here to stop and save.', + defaultSaveDir: 'default folder', + stopFailedTitle: 'Failed to stop recording', + cancelSuccessTitle: 'Task cancelled', + cancelFailedTitle: 'Failed to cancel task', + sizeParen: ' ({size})', + stopRecordingSave: 'Stop & Save', + startRecording: 'Start Recording', + statusRecording: 'Recording', + statusIdle: 'Ready', + statusProvisionNeeded: 'Media engine provisioning required', + statusUnsupported: 'Host capture primitive unsupported', + statusUnknownErr: 'Status unknown ({error})', + statusLoading: 'Checking status', + listReadFailed: 'Failed to list files: {error}', + listSummary: '{count} recording(s){partial}', + emptyReadFailed: 'Failed to read save folder: {error}', + emptyNoMatch: 'No matching recordings', + emptyNoRecordings: 'No recordings yet; started recordings will appear here', + searchPlaceholder: 'Search recordings...', + rescan: 'Rescan', + wbTitle: 'Recording Settings', + wbSubtitle: '{mode} · {audio}', + wbModeLabel: 'Capture Mode', + wbSourceLabel: 'Capture Source', + wbRegionLabel: 'Region (x,y,w,h)', + wbScaleLabel: 'Scale Factor (DPI)', + wbFpsLabel: 'Frame Rate', + wbFormatLabel: 'Output Format', + wbSystemAudioLabel: 'System Audio Loopback', + wbMicLabel: 'Microphone', + wbTrimStartLabel: 'Post Trim Start (s)', + wbTrimDurationLabel: 'Post Trim Duration (s)', + wbCardTitle: 'Engine & Status', + badgeRecording: 'Recording', + badgeIdle: 'Ready', + badgeProvision: 'Needs Engine', + badgeUnsupported: 'Unsupported', + badgeUnknown: 'Unknown', + metricStartTime: 'Started', + metricOutputFile: 'Output File', + metricSourcesCount: 'Capture Sources', + metricProbeInfo: 'Last Probe', + unknownValue: 'Unknown', + subListTitle: 'Recordings (Newest first, Enter to open)', + subListSubtitle: '{count} item(s) · {size} · Folder: {dir}', + panelTitle: 'Screen Recorder', + sectionTitle: 'Recordings ({count})', + modeFullscreen: 'Full Screen', + modeWindow: 'Specific Window', + modeRegion: 'Custom Region', + audioBoth: 'System Audio + Mic', + audioSystemOnly: 'System Audio Only', + audioMicOnly: 'Microphone Only', + audioMuted: 'Muted', + toggleOn: 'Enabled', + toggleOff: 'Disabled', + formatMp4: 'MP4 Video', + formatWebm: 'WebM Video', + formatGif: 'GIF Animation', + limitationNote: 'Powered by host media.capture / media.probe / media.transcode thin primitives with zero local PATH dependency; window and region modes pass exact sourceId and DPI-scaled region bounds.', + provisionPromptNote: 'Media engine is not provisioned yet. Click "Prepare Media Engine" to download and verify the signed runtime.', + timeUnknown: 'Unknown time', + hostCallFailed: 'Host primitive {method} call failed', + hostInvalidResult: 'Host primitive {method} returned unrecognized data', + hostNoRecordingStatus: 'Host did not return recording status', + noVideosFolder: 'Could not resolve system Videos folder', + readSaveDirFailed: 'Failed to read save folder', + unrecognizedDirContent: 'Host returned unrecognized directory listing', + queryStatusFailed: 'Failed to query recording status', + invalidRecordConfig: 'Invalid recording configuration', + missingSaveDir: 'Please configure a recordings save folder first', + missingCaptureSource: 'Select a valid screen or window capture source first', + invalidRegionConfig: 'Region mode requires valid coordinates and positive width/height (format: x,y,width,height)', + recordBusy: 'Previous recording operation is still in progress', + cannotConfirmStatus: 'Cannot confirm recording status: {error}', + alreadyRecording: 'A recording is already in progress; stop or cancel it first', + recordingStarted: 'Recording started ({mode} · {fps} FPS · {format})', + recordingSaved: 'Recording saved', + ensureSuccessTitle: 'Media engine ready', + ensureFailedTitle: 'Engine provisioning failed', + probeSuccessTitle: 'Media probe completed', + probeFailedTitle: 'Media probe failed', + transcodeStartTitle: 'Transcoding recording', + transcodeSuccessTitle: 'Post-export completed', + transcodeFailedTitle: 'Post-export failed', + noActiveTaskToCancel: 'No active task to cancel', + pickSaveDirTitle: 'Choose recordings save folder', + saveDirUpdatedTitle: 'Save folder updated', + noSourceAvailable: 'No capture sources available', + sourceKindScreen: 'Screen', + sourceKindWindow: 'Window', + probeSummary: '{duration} · {resolution} · {codec}', + invalidTrimRange: 'Invalid trim range: start must be >= 0 and duration > 0' } -}; +} -export const t = createTranslator(MESSAGES, { defaultLocale: "en-US" }); +export const t = createTranslator(MESSAGES, { defaultLocale: 'en-US' }) diff --git a/extensions/record/src/index.ts b/extensions/record/src/index.ts index 293f94b8..5655f959 100644 --- a/extensions/record/src/index.ts +++ b/extensions/record/src/index.ts @@ -1,9 +1,9 @@ /** - * 屏幕录制(布局三:左侧录制参数 + 右侧录制文件) + * 屏幕录制(布局三:左侧录制与后期参数 + 右侧录制文件列表) * - * - 左栏只放客户端真实支持的参数:帧率、输出格式;录制范围与限制如实写明 - * - 右栏列出保存目录里的录制文件:打开 ↵ / 在文件夹中显示 ⌘↵ / 动作面板 ⌘K - * - 开始 / 停止录制是全局动作:顶部状态条按钮,列表为空时也是底部主动作 + * - 支持全屏 / 指定窗口 / 自定义区域(透传真实 sourceId 与 DPI scaleFactor 选区) + * - 支持系统音频回采与麦克风开关、MP4 / WebM / GIF 导出 + * - 支持录制后媒体探测(tool_media_probe)、二次转码/裁切(tool_media_transcode_run)、任务取消与引擎按需准备 */ import { List, @@ -21,21 +21,35 @@ import { } from '@ztools/declarative-ui' import { t } from './i18n.js' import { - RECORD_FORMAT_OPTIONS, RECORD_FPS_OPTIONS, - getRecordFormatOptions, - getRecordLimitationNote, - RecordFormat, - RecordFps, - RecordWorkspaceSnapshot, - RecordedVideoItem, + RECORD_FORMAT_VALUES, + RECORD_MODE_VALUES, + cancelActiveRecordTask, + ensureRecordEngines, fetchRecordWorkspace, formatBytes, + formatDurationSec, formatRecordTime, + getRecordAudioSummary, + getRecordFormatOptions, + getRecordLimitationNote, + getRecordModeLabel, + getRecordModeOptions, openRecordFileLocation, openRecordedVideo, + parseRegionInput, + pickOutputDirectoryDialog, + probeRecordedMedia, startScreenRecording, - stopScreenRecording + stopScreenRecording, + transcodeRecording, + type CaptureSourceItem, + type RecordFormat, + type RecordFps, + type RecordMode, + type RecordProbeSummary, + type RecordWorkspaceSnapshot, + type RecordedVideoItem } from './logic.js' export * from './logic.js' @@ -67,45 +81,52 @@ async function handleCopyPath(item: RecordedVideoItem) { } } -/** 录制文件行:打开 ↵ / 在文件夹中显示 ⌘↵,其余进动作面板 */ -function buildRecordingItem(item: RecordedVideoItem, toggleAction: ReturnType) { - return List.Item({ - id: item.id, - title: item.name, - subtitle: item.modifiedMs !== null ? formatRecordTime(item.modifiedMs) : undefined, - icon: { source: item.extension === '.gif' ? Icon.Image : Icon.Video }, - accessories: [ - { tag: item.extension.replace('.', '').toUpperCase() || t('unknownExt') }, - { text: item.sizeBytes === null ? t('sizeUnknown') : formatBytes(item.sizeBytes) } - ], - actions: ActionPanel({ - title: item.name, - children: [ - Action({ title: t('openRecording'), icon: Icon.Eye, onAction: () => handleOpen(item) }), - Action({ title: t('revealInFolder'), icon: Icon.Folder, onAction: () => handleReveal(item) }), - toggleAction, - Action({ title: t('copyFilePath'), icon: Icon.CopyClipboard, onAction: () => handleCopyPath(item) }) - ] - }) - }) +function formatSourceOptionLabel(src: CaptureSourceItem): string { + const kindLabel = src.kind === 'window' ? t('sourceKindWindow') : t('sourceKindScreen') + const dim = src.width !== null && src.height !== null ? ` (${src.width}x${src.height})` : '' + return `[${kindLabel}] ${src.name}${dim}` } export function RecordCommand() { useLocale() const [searchText, setSearchText] = useState('') + const [mode, setMode] = useState('fullscreen') + const [selectedSourceId, setSelectedSourceId] = useState('') + const [regionText, setRegionText] = useState('0,0,1280,720') + const [scaleFactorText, setScaleFactorText] = useState('1') const [fps, setFps] = useState('30') const [format, setFormat] = useState('mp4') + const [includeSystemAudio, setIncludeSystemAudio] = useState(true) + const [includeMicrophone, setIncludeMicrophone] = useState(false) + const [trimStartText, setTrimStartText] = useState('') + const [trimDurationText, setTrimDurationText] = useState('') + const [customSaveDir, setCustomSaveDir] = useState('') const [workspace, setWorkspace] = useState(null) + const [lastProbe, setLastProbe] = useState(null) const [isLoading, setIsLoading] = useState(true) + const [isBusyTask, setIsBusyTask] = useState(false) const refreshSeq = useRef(0) - async function refreshWorkspace(announce = false) { + async function refreshWorkspace(announce = false, overrideDir?: string) { const seq = ++refreshSeq.current setIsLoading(true) try { - const ws = await fetchRecordWorkspace() + const ws = await fetchRecordWorkspace(overrideDir ?? customSaveDir) if (seq !== refreshSeq.current) return setWorkspace(ws) + setSelectedSourceId((prev) => { + const pool = mode === 'window' + ? ws.sources.filter((s) => s.kind === 'window') + : ws.sources.filter((s) => s.kind === 'screen') + const effectivePool = pool.length > 0 ? pool : ws.sources + if (prev && effectivePool.some((s) => s.id === prev)) return prev + const first = effectivePool[0] + if (first) { + setScaleFactorText(String(first.scaleFactor || 1)) + return first.id + } + return '' + }) if (announce) { if (ws.listError) { showToast({ style: Toast.Style.Failure, title: t('readFilesFailed'), message: ws.listError }) @@ -132,9 +153,71 @@ export function RecordCommand() { const isRecording = workspace ? workspace.isRecording : null const saveDir = workspace?.saveDir || '' const recordings = workspace?.recordings || [] + const allSources = workspace?.sources || [] + const modeSources = mode === 'window' + ? allSources.filter((s) => s.kind === 'window') + : allSources.filter((s) => s.kind === 'screen') + const availableSources = modeSources.length > 0 ? modeSources : allSources + const effectiveSourceId = + availableSources.some((s) => s.id === selectedSourceId) ? selectedSourceId : availableSources[0]?.id || '' + const needsProvisioning = + workspace?.captureStatus === 'needs_provisioning' || workspace?.transcodeStatus === 'needs_provisioning' + const isUnsupported = workspace?.captureStatus === 'unsupported' + + function handleModeChange(nextVal: string) { + if (!RECORD_MODE_VALUES.includes(nextVal as RecordMode)) return + const nextMode = nextVal as RecordMode + setMode(nextMode) + const pool = nextMode === 'window' + ? allSources.filter((s) => s.kind === 'window') + : allSources.filter((s) => s.kind === 'screen') + const first = pool[0] ?? allSources[0] + if (first) { + setSelectedSourceId(first.id) + setScaleFactorText(String(first.scaleFactor || 1)) + } + } + + async function handleEnsureEngines() { + setIsBusyTask(true) + try { + const res = await ensureRecordEngines() + if (!res.ok) { + showToast({ style: Toast.Style.Failure, title: t('ensureFailedTitle'), message: res.error }) + } else { + showToast({ style: Toast.Style.Success, title: t('ensureSuccessTitle') }) + } + await refreshWorkspace(false) + } finally { + setIsBusyTask(false) + } + } + + async function handleChooseSaveDir() { + const picked = await pickOutputDirectoryDialog({ title: t('pickSaveDirTitle'), defaultPath: saveDir || undefined }) + if (picked.canceled || !picked.directoryPath) return + setCustomSaveDir(picked.directoryPath) + showToast({ style: Toast.Style.Success, title: t('saveDirUpdatedTitle'), message: picked.directoryPath }) + await refreshWorkspace(false, picked.directoryPath) + } async function handleStartRecording() { - const res = await startScreenRecording({ fps, format, saveDir }) + const scaleFactor = Number(scaleFactorText) + const region = mode === 'region' ? parseRegionInput(regionText, Number.isFinite(scaleFactor) && scaleFactor > 0 ? scaleFactor : 1) : undefined + if (mode === 'region' && !region) { + showToast({ style: Toast.Style.Failure, title: t('startFailedTitle'), message: t('invalidRegionConfig') }) + return + } + const res = await startScreenRecording({ + mode, + sourceId: effectiveSourceId, + ...(region ? { region } : {}), + fps, + format, + includeSystemAudio, + includeMicrophone, + saveDir + }) if (!res.ok) { showToast({ style: Toast.Style.Failure, title: t('startFailedTitle'), message: res.message }) await refreshWorkspace(false) @@ -143,7 +226,7 @@ export function RecordCommand() { showToast({ style: Toast.Style.Success, title: res.message, - message: t('writingMsg', { dir: res.outputPath || res.saveDir || t('defaultSaveDir') }) + message: t('writingMsg', { dir: res.outputPath || res.saveDir || t('defaultSaveDir'), mode: getRecordModeLabel(mode) }) }) await refreshWorkspace(false) } @@ -159,12 +242,70 @@ export function RecordCommand() { await refreshWorkspace(false) } - // 状态已确认在录制才是“停止”;状态未知时按“开始”处理,开始前会再向客户端确认,已在录制会如实提示 + async function handleCancelTask() { + const res = await cancelActiveRecordTask() + if (!res.ok) { + showToast({ style: Toast.Style.Failure, title: t('cancelFailedTitle'), message: res.error }) + } else { + showToast({ style: Toast.Style.Success, title: t('cancelSuccessTitle'), message: res.taskId }) + } + await refreshWorkspace(false) + } + + async function handleProbeItem(item: RecordedVideoItem) { + setIsBusyTask(true) + try { + const res = await probeRecordedMedia(item.path) + setLastProbe(res) + if (!res.ok) { + showToast({ style: Toast.Style.Failure, title: t('probeFailedTitle'), message: res.error }) + } else { + const resolution = res.width !== null && res.height !== null ? `${res.width}x${res.height}` : t('unknownValue') + showToast({ + style: Toast.Style.Success, + title: t('probeSuccessTitle'), + message: t('probeSummary', { + duration: formatDurationSec(res.durationSec), + resolution, + codec: res.videoCodec || res.container || t('unknownValue') + }) + }) + } + } finally { + setIsBusyTask(false) + } + } + + async function handleTranscodeItem(item: RecordedVideoItem, targetFormat: RecordFormat, withTrim: boolean) { + const trimStartSec = withTrim && trimStartText.trim() !== '' ? Number(trimStartText) : undefined + const trimDurationSec = withTrim && trimDurationText.trim() !== '' ? Number(trimDurationText) : undefined + setIsBusyTask(true) + showToast({ style: Toast.Style.Animated, title: t('transcodeStartTitle'), message: item.name }) + try { + const res = await transcodeRecording({ + inputPath: item.path, + container: targetFormat, + ...(trimStartSec !== undefined ? { trimStartSec } : {}), + ...(trimDurationSec !== undefined ? { trimDurationSec } : {}), + capabilities: workspace?.capabilities ?? null + }) + if (!res.ok) { + showToast({ style: Toast.Style.Failure, title: t('transcodeFailedTitle'), message: res.error }) + } else { + const sizeText = typeof res.outputBytes === 'number' ? t('sizeParen', { size: formatBytes(res.outputBytes) }) : '' + showToast({ style: Toast.Style.Success, title: t('transcodeSuccessTitle'), message: `${res.outputPath || ''}${sizeText}` }) + await refreshWorkspace(false) + } + } finally { + setIsBusyTask(false) + } + } + const toggleTitle = isRecording === true ? t('stopRecordingSave') : t('startRecording') const handleToggle = () => (isRecording === true ? handleStopRecording() : handleStartRecording()) const q = searchText.trim().toLowerCase() - const filteredRecordings = recordings.filter(r => !q || r.name.toLowerCase().includes(q) || r.path.toLowerCase().includes(q)) + const filteredRecordings = recordings.filter((r) => !q || r.name.toLowerCase().includes(q) || r.path.toLowerCase().includes(q)) const knownBytes = filteredRecordings.reduce((s, r) => s + (r.sizeBytes ?? 0), 0) const toggleAction = () => @@ -174,16 +315,47 @@ export function RecordCommand() { shortcut: TOGGLE_SHORTCUT, onAction: handleToggle }) - const items = filteredRecordings.map(item => buildRecordingItem(item, toggleAction())) + + const items = filteredRecordings.map((item) => + List.Item({ + id: item.id, + title: item.name, + subtitle: item.modifiedMs !== null ? formatRecordTime(item.modifiedMs) : undefined, + icon: { source: item.extension === '.gif' ? Icon.Image : Icon.Video }, + accessories: [ + { tag: item.extension.replace('.', '').toUpperCase() || t('unknownExt') }, + { text: item.sizeBytes === null ? t('sizeUnknown') : formatBytes(item.sizeBytes) } + ], + actions: ActionPanel({ + title: item.name, + children: [ + Action({ title: t('openRecording'), icon: Icon.Eye, onAction: () => handleOpen(item) }), + Action({ title: t('revealInFolder'), icon: Icon.Folder, onAction: () => handleReveal(item) }), + Action({ title: t('probeRecording'), icon: Icon.Info, onAction: () => handleProbeItem(item) }), + Action({ title: t('transcodeToMp4'), icon: Icon.Video, onAction: () => handleTranscodeItem(item, 'mp4', false) }), + Action({ title: t('transcodeToWebm'), icon: Icon.Video, onAction: () => handleTranscodeItem(item, 'webm', false) }), + Action({ title: t('transcodeToGif'), icon: Icon.Image, onAction: () => handleTranscodeItem(item, 'gif', false) }), + Action({ title: t('trimRecording'), icon: Icon.Scissors, onAction: () => handleTranscodeItem(item, format, true) }), + toggleAction(), + Action({ title: t('copyFilePath'), icon: Icon.CopyClipboard, onAction: () => handleCopyPath(item) }) + ] + }) + }) + ) const statusText = isRecording === true ? t('statusRecording') - : isRecording === false - ? t('statusIdle') - : workspace?.statusError - ? t('statusUnknownErr', { error: workspace.statusError }) - : t('statusLoading') + : isUnsupported + ? t('statusUnsupported') + : needsProvisioning + ? t('statusProvisionNeeded') + : isRecording === false + ? t('statusIdle') + : workspace?.statusError + ? t('statusUnknownErr', { error: workspace.statusError }) + : t('statusLoading') + const listText = workspace?.listError ? t('listReadFailed', { error: workspace.listError }) : t('listSummary', { count: recordings.length, partial: workspace?.partial ? t('partialSuffix') : '' }) @@ -195,22 +367,152 @@ export function RecordCommand() { : t('emptyNoRecordings') const currentSession = isRecording === true ? workspace?.sessions[0] : undefined + const cardBadge = + isRecording === true + ? t('badgeRecording') + : isUnsupported + ? t('badgeUnsupported') + : needsProvisioning + ? t('badgeProvision') + : isRecording === false + ? t('badgeIdle') + : t('badgeUnknown') + + const cardMetrics: Array<{ label: string; value: string }> = [ + { label: t('metricSourcesCount'), value: String(allSources.length) } + ] + if (currentSession) { + cardMetrics.push( + { label: t('metricStartTime'), value: formatRecordTime(currentSession.startedAtMs) }, + { label: t('metricOutputFile'), value: currentSession.outputPath.split(/[\\/]/).pop() || t('unknownValue') } + ) + } else if (lastProbe?.ok) { + const resText = lastProbe.width !== null && lastProbe.height !== null ? `${lastProbe.width}x${lastProbe.height}` : t('unknownValue') + cardMetrics.push({ + label: t('metricProbeInfo'), + value: `${formatDurationSec(lastProbe.durationSec)} · ${resText}` + }) + } + + const workbenchFields = [ + { + id: 'wb-rec-mode', + label: t('wbModeLabel'), + type: 'select' as const, + value: mode, + onChange: handleModeChange, + options: getRecordModeOptions().map((o) => ({ label: o.label, value: o.value })) + }, + { + id: 'wb-rec-source', + label: t('wbSourceLabel'), + type: 'select' as const, + value: effectiveSourceId, + onChange: (val: string) => { + setSelectedSourceId(val) + const found = allSources.find((s) => s.id === val) + if (found) setScaleFactorText(String(found.scaleFactor || 1)) + }, + options: + availableSources.length > 0 + ? availableSources.map((s) => ({ label: formatSourceOptionLabel(s), value: s.id })) + : [{ label: t('noSourceAvailable'), value: '' }] + }, + ...(mode === 'region' + ? [ + { + id: 'wb-rec-region', + label: t('wbRegionLabel'), + type: 'text' as const, + value: regionText, + onChange: setRegionText + }, + { + id: 'wb-rec-scale', + label: t('wbScaleLabel'), + type: 'text' as const, + value: scaleFactorText, + onChange: setScaleFactorText + } + ] + : []), + { + id: 'wb-rec-fps', + label: t('wbFpsLabel'), + type: 'select' as const, + value: fps, + onChange: (val: string) => { + if (RECORD_FPS_OPTIONS.some((o) => o.value === val)) setFps(val as RecordFps) + }, + options: RECORD_FPS_OPTIONS.map((o) => ({ label: o.label, value: o.value })) + }, + { + id: 'wb-rec-format', + label: t('wbFormatLabel'), + type: 'select' as const, + value: format, + onChange: (val: string) => { + if (RECORD_FORMAT_VALUES.includes(val as RecordFormat)) setFormat(val as RecordFormat) + }, + options: getRecordFormatOptions().map((o) => ({ label: o.label, value: o.value })) + }, + { + id: 'wb-rec-sys-audio', + label: t('wbSystemAudioLabel'), + type: 'select' as const, + value: includeSystemAudio ? 'on' : 'off', + onChange: (val: string) => setIncludeSystemAudio(val === 'on'), + options: [ + { label: t('toggleOn'), value: 'on' }, + { label: t('toggleOff'), value: 'off' } + ] + }, + { + id: 'wb-rec-mic', + label: t('wbMicLabel'), + type: 'select' as const, + value: includeMicrophone ? 'on' : 'off', + onChange: (val: string) => setIncludeMicrophone(val === 'on'), + options: [ + { label: t('toggleOff'), value: 'off' }, + { label: t('toggleOn'), value: 'on' } + ] + }, + { + id: 'wb-rec-trim-start', + label: t('wbTrimStartLabel'), + type: 'text' as const, + value: trimStartText, + onChange: setTrimStartText + }, + { + id: 'wb-rec-trim-duration', + label: t('wbTrimDurationLabel'), + type: 'text' as const, + value: trimDurationText, + onChange: setTrimDurationText + } + ] return List({ searchBarPlaceholder: t('searchPlaceholder'), onSearchTextChange: setSearchText, isShowingDetail: false, - isLoading, + isLoading: isLoading || isBusyTask, filterBar: FilterBar({ summaryText: `${statusText} · ${listText}`, actions: [ { id: 'toggle-record-session', - label: toggleTitle, - title: toggleTitle, + label: needsProvisioning ? t('ensureRuntimeAction') : toggleTitle, + title: needsProvisioning ? t('ensureRuntimeAction') : toggleTitle, style: 'primary', onAction: () => { - void handleToggle() + if (needsProvisioning) { + void handleEnsureEngines() + } else { + void handleToggle() + } } }, { @@ -226,46 +528,25 @@ export function RecordCommand() { }), workbenchPanel: { title: t('wbTitle'), - subtitle: t('wbSubtitle'), - fields: [ - { - id: 'wb-rec-fps', - label: t('wbFpsLabel'), - type: 'select', - value: fps, - onChange: (val: string) => { - if (RECORD_FPS_OPTIONS.some(o => o.value === val)) setFps(val as RecordFps) - }, - options: RECORD_FPS_OPTIONS.map(o => ({ label: o.label, value: o.value })) - }, - { - id: 'wb-rec-format', - label: t('wbFormatLabel'), - type: 'select', - value: format, - onChange: (val: string) => { - if (RECORD_FORMAT_OPTIONS.some(o => o.value === val)) setFormat(val as RecordFormat) - }, - options: getRecordFormatOptions().map(o => ({ label: o.label, value: o.value })) - }, - { id: 'wb-rec-scope', label: t('wbScopeLabel'), type: 'info', value: t('wbScopeValue') }, - { id: 'wb-rec-audio', label: t('wbAudioLabel'), type: 'info', value: t('wbAudioValue') } - ], + subtitle: t('wbSubtitle', { + mode: getRecordModeLabel(mode), + audio: getRecordAudioSummary(includeSystemAudio, includeMicrophone) + }), + fields: workbenchFields, previewCard: { title: t('wbCardTitle'), - badge: isRecording === true ? t('badgeRecording') : isRecording === false ? t('badgeIdle') : t('badgeUnknown'), - subtitle: getRecordLimitationNote(), - metrics: currentSession - ? [ - { label: t('metricStartTime'), value: formatRecordTime(currentSession.startedAtMs) }, - { label: t('metricOutputFile'), value: currentSession.outputPath.split(/[\\/]/).pop() || t('unknownValue') } - ] - : [] + badge: cardBadge, + subtitle: needsProvisioning ? t('provisionPromptNote') : getRecordLimitationNote(), + metrics: cardMetrics } }, subList: { title: t('subListTitle'), - subtitle: t('subListSubtitle', { count: filteredRecordings.length, size: formatBytes(knownBytes), dir: saveDir || t('unknownValue') }), + subtitle: t('subListSubtitle', { + count: filteredRecordings.length, + size: formatBytes(knownBytes), + dir: saveDir || t('unknownValue') + }), emptyText, items }, @@ -273,7 +554,10 @@ export function RecordCommand() { title: t('panelTitle'), children: [ toggleAction(), - Action({ title: t('rescan'), icon: Icon.Repeat, onAction: () => refreshWorkspace(true) }) + Action({ title: t('cancelActiveTask'), icon: Icon.XMarkCircle, onAction: handleCancelTask }), + Action({ title: t('ensureRuntimeAction'), icon: Icon.Download, onAction: handleEnsureEngines }), + Action({ title: t('chooseSaveDir'), icon: Icon.Folder, onAction: handleChooseSaveDir }), + Action({ title: t('refreshSources'), icon: Icon.Repeat, onAction: () => refreshWorkspace(true) }) ] }), children: [ diff --git a/extensions/record/src/logic.ts b/extensions/record/src/logic.ts index 45c38005..4f1023dc 100644 --- a/extensions/record/src/logic.ts +++ b/extensions/record/src/logic.ts @@ -1,23 +1,46 @@ /** - * 屏幕录制业务逻辑 + * 屏幕录制业务逻辑层(Wave 3 薄原语域:media.capture / media.probe / media.transcode) * - * 录制由客户端调用本机 ffmpeg 完成,能力边界以客户端实现为准: - * - 只能录制整个桌面(所有显示器)的画面,不能只录某个区域或某个窗口; - * - 不录制声音(系统声音、麦克风都不支持); - * - 输出 MP4 或 GIF,可选帧率;本机没有 ffmpeg 时开始录制会如实失败。 - * - * 录制文件保存在系统视频文件夹下的 ZTools_Recordings 目录,列表只展示这个目录里的录制文件。 + * - 全部经由宿主标准薄原语 IPC 执行,零原生扩展依赖 + * - 支持全屏、指定窗口、自定义区域三模式,精准透传真实 sourceId 与 DPI 换算后的 region + * - 支持系统音频回采与麦克风开关、MP4 / WebM / GIF 输出 + * - 支持录制后媒体探测(tool_media_probe)、二次转码/裁切(tool_media_transcode_run)、任务取消(tool_task_cancel)与引擎按需准备(tool_runtime_ensure) */ -import { getLocale } from '@ztools/declarative-ui' +import { getLocale } from '@ztools/declarative-ui' import { t } from './i18n.js' -import { callHostTransport, formatBytes, getRealSystemPath, openRealPath, showRealItemInFolder } from './native-ipc.js' import { resolveErrorMessage } from './error-i18n.js' - -export { formatBytes } - -export type RecordFps = '30' | '15' | '60' -export type RecordFormat = 'mp4' | 'gif' +import { + asRecord, + callHostTransport, + cancelRuntimeTask, + ensureRuntimeCapability, + findCapability, + formatBytes, + getRealSystemPath, + hasCapabilityExtension, + nextMessageId, + openRealPath, + pickOutputDirectoryDialog, + queryRuntimeCapabilities, + showRealItemInFolder, + type ToolCapabilityStatus, + type ToolRuntimeCapabilitiesSnapshot +} from './tool-runtime.js' + +export { + formatBytes, + pickOutputDirectoryDialog, + queryRuntimeCapabilities, + findCapability, + hasCapabilityExtension, + type ToolCapabilityStatus, + type ToolRuntimeCapabilitiesSnapshot +} + +export type RecordMode = 'fullscreen' | 'window' | 'region' +export type RecordFps = '15' | '30' | '60' +export type RecordFormat = 'mp4' | 'webm' | 'gif' export const RECORD_FPS_OPTIONS: ReadonlyArray<{ value: RecordFps; label: string }> = [ { value: '30', label: '30 FPS' }, @@ -25,66 +48,102 @@ export const RECORD_FPS_OPTIONS: ReadonlyArray<{ value: RecordFps; label: string { value: '60', label: '60 FPS' } ] -export const RECORD_FORMAT_OPTIONS: ReadonlyArray<{ value: RecordFormat; readonly label: string }> = [ - { value: 'mp4', get label() { return t('formatMp4') } }, - { value: 'gif', get label() { return t('formatGif') } } -] +export const RECORD_MODE_VALUES: readonly RecordMode[] = ['fullscreen', 'window', 'region'] +export const RECORD_FORMAT_VALUES: readonly RecordFormat[] = ['mp4', 'webm', 'gif'] + +export function getRecordModeOptions(): ReadonlyArray<{ value: RecordMode; label: string }> { + return [ + { value: 'fullscreen', label: t('modeFullscreen') }, + { value: 'window', label: t('modeWindow') }, + { value: 'region', label: t('modeRegion') } + ] +} export function getRecordFormatOptions(): ReadonlyArray<{ value: RecordFormat; label: string }> { return [ { value: 'mp4', label: t('formatMp4') }, + { value: 'webm', label: t('formatWebm') }, { value: 'gif', label: t('formatGif') } ] } -/** 录制能力的固定限制(由客户端录制实现决定),界面上如实展示 */ +export function getRecordModeLabel(mode: RecordMode): string { + if (mode === 'window') return t('modeWindow') + if (mode === 'region') return t('modeRegion') + return t('modeFullscreen') +} + +export function getRecordAudioSummary(includeSystemAudio: boolean, includeMicrophone: boolean): string { + if (includeSystemAudio && includeMicrophone) return t('audioBoth') + if (includeSystemAudio) return t('audioSystemOnly') + if (includeMicrophone) return t('audioMicOnly') + return t('audioMuted') +} + export function getRecordLimitationNote(): string { return t('limitationNote') } -/** 录制文件保存目录名(位于系统视频文件夹下) */ export const RECORDINGS_FOLDER_NAME = 'ZTools_Recordings' - -/** 客户端录制接口名 */ -const RECORD_HOST_PLUGIN = 'RecordPlugin' -/** 列表只展示本插件能产出的格式 */ -const RECORDING_FILE_REGEX = /\.(?:mp4|gif)$/i -/** 一次目录扫描最多取回的条目数 */ +const RECORDING_FILE_REGEX = /\.(?:mp4|webm|gif)$/i const RECORDING_SCAN_LIMIT = 200 +export interface CaptureRegion { + x: number + y: number + width: number + height: number + scaleFactor: number +} + +export interface CaptureSourceItem { + id: string + name: string + kind: 'screen' | 'window' + displayId?: string + width: number | null + height: number | null + scaleFactor: number +} + export interface RecordedVideoItem { id: string name: string path: string - /** 小写扩展名,带点,如 ".mp4" */ extension: string - /** 宿主没有返回大小时为 null */ sizeBytes: number | null - /** 文件修改时间(毫秒);宿主没有返回时为 null,不用当前时间代替 */ modifiedMs: number | null } export interface RecordSessionInfo { id: string + taskId: string + mode?: RecordMode + sourceId?: string outputPath: string - /** 开始时间(毫秒);宿主没有返回时为 null */ startedAtMs: number | null } export interface RecordSessionConfig { + mode: RecordMode + sourceId: string + region?: CaptureRegion fps: RecordFps format: RecordFormat - /** 保存目录;为空时由客户端使用默认目录 */ + includeSystemAudio: boolean + includeMicrophone: boolean saveDir?: string } export interface RecordActionResult { ok: boolean sessionId: string + taskId: string message: string saveDir: string outputPath?: string error?: string + errorCode?: string } export interface RecordStopResult { @@ -103,33 +162,77 @@ export interface RecordStatusResult { error?: string } +export interface RecordProbeSummary { + ok: boolean + filePath: string + container: string | null + durationSec: number | null + sizeBytes: number | null + width: number | null + height: number | null + frameRate: number | null + videoCodec: string | null + audioCodec: string | null + error?: string +} + +export interface RecordTranscodeOptions { + inputPath: string + container: RecordFormat + trimStartSec?: number + trimDurationSec?: number + crop?: { x: number; y: number; width: number; height: number } + speedFactor?: number + capabilities?: ToolRuntimeCapabilitiesSnapshot | null +} + +export interface RecordTranscodeResult { + ok: boolean + taskId: string + outputPath?: string + outputBytes?: number + durationMs?: number + error?: string +} + export interface RecordingListResult { files: RecordedVideoItem[] - /** 目录里的文件没有全部取回 */ partial: boolean - /** 保存目录还没有创建(还没录制过) */ missing: boolean error?: string } export interface RecordWorkspaceSnapshot { - /** 录制文件保存目录;获取不到系统视频文件夹时为空 */ saveDir: string recordings: RecordedVideoItem[] partial: boolean missing: boolean listError?: string - /** 宿主确认的录制状态;查询失败时为 null(状态未知) */ isRecording: boolean | null sessions: RecordSessionInfo[] statusError?: string + sources: CaptureSourceItem[] + sourcesError?: string + capabilities: ToolRuntimeCapabilitiesSnapshot | null + captureStatus: ToolCapabilityStatus | 'unknown' + transcodeStatus: ToolCapabilityStatus | 'unknown' + capabilitiesError?: string } -/** 本次运行中插件发起的录制会话 id(停止时按 id 停止,不误停别的会话) */ let activeSessionId = '' -/** 开始 / 停止录制不能并发:连按两次会启动两个录制进程 */ +let activeTaskId = '' let recordOpInFlight = false +export function resetRecordRuntimeState(): void { + activeSessionId = '' + activeTaskId = '' + recordOpInFlight = false +} + +export function getActiveTaskId(): string { + return activeTaskId +} + function errorText(err: unknown): string { return err instanceof Error ? err.message : String(err) } @@ -163,7 +266,6 @@ function baseNameOf(p: string): string { return String(p || '').split(/[\\/]/).pop() || '' } -/** 宿主时间戳可能是秒或毫秒;缺失或非法时返回 null */ function toEpochMs(raw: unknown): number | null { let n: number if (typeof raw === 'number') { @@ -178,46 +280,166 @@ function toEpochMs(raw: unknown): number | null { return n > 1e11 ? Math.round(n) : Math.round(n * 1000) } +/** 安全解析非空有限数值,避免 null / undefined / 空字符串被 Number() 误转为 0 */ +function parseFiniteNumber(raw: unknown): number | null { + if (typeof raw === 'number') return Number.isFinite(raw) ? raw : null + if (typeof raw === 'string' && raw.trim() !== '') { + const parsed = Number(raw) + return Number.isFinite(parsed) ? parsed : null + } + return null +} + function pad2(n: number): string { return String(n).padStart(2, '0') } -/** 本地时间 "YYYY-MM-DD HH:mm";时间未知时返回 "时间未知" */ export function formatRecordTime(ms: number | null): string { if (ms === null || !Number.isFinite(ms)) return t('timeUnknown') const d = new Date(ms) return `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())} ${pad2(d.getHours())}:${pad2(d.getMinutes())}` } -/** 录制文件保存目录:系统视频文件夹下的 ZTools_Recordings */ +export function formatDurationSec(sec: number | null): string { + if (sec === null || !Number.isFinite(sec) || sec < 0) return t('unknownValue') + const total = Math.round(sec) + const mins = Math.floor(total / 60) + const secs = total % 60 + return mins > 0 ? `${mins}m ${pad2(secs)}s` : `${secs}s` +} + export function resolveRecordingsDir(videosDir: string): string { const dir = String(videosDir || '').trim() return dir ? joinPath(dir, RECORDINGS_FOLDER_NAME) : '' } -type HostRecord = Record -type HostCallResult = { ok: true; data: HostRecord } | { ok: false; error: string } - -function asRecord(value: unknown): HostRecord | null { - return value && typeof value === 'object' && !Array.isArray(value) ? (value as HostRecord) : null +/** 解析选区文本 "x,y,width,height" 并绑定 DPI scaleFactor;允许 x=0 / y=0,要求宽高与缩放倍率为正数 */ +export function parseRegionInput(regionText: string, scaleFactor = 1): CaptureRegion | null { + const parts = String(regionText || '') + .split(/[,,\s]+/) + .map((s) => s.trim()) + .filter((s) => s.length > 0) + if (parts.length !== 4) return null + const nums = parts.map((p) => Number(p)) + if (nums.some((n) => !Number.isFinite(n))) return null + const [x, y, width, height] = nums as [number, number, number, number] + if (x < 0 || y < 0 || width <= 0 || height <= 0) return null + if (!Number.isFinite(scaleFactor) || scaleFactor <= 0 || scaleFactor > 8) return null + return { + x: Math.round(x), + y: Math.round(y), + width: Math.round(width), + height: Math.round(height), + scaleFactor + } } -/** - * 调用客户端录制接口。直接走 dllplugin_call 一次:失败时不再换通道重试, - * 否则第二次调用会把第一次的真实失败原因(例如 ffmpeg 异常退出)覆盖成“当前没有正在进行的录制”。 - */ -async function callRecordHost(func: string, params: Record, hostOverride?: unknown): Promise { - const res = await callHostTransport('dllplugin_call', { plugin: RECORD_HOST_PLUGIN, func, params }, hostOverride) - if (!res.ok) return { ok: false, error: resolveErrorMessage(res, t('hostCallFailed', { func })) } - const data = asRecord(res.data) - if (!data) { - return { ok: false, error: t('hostInvalidResult', { func }) } +export function validateCaptureRegion(region: CaptureRegion | undefined): region is CaptureRegion { + if (!region || typeof region !== 'object') return false + return ( + Number.isFinite(region.x) && + region.x >= 0 && + Number.isFinite(region.y) && + region.y >= 0 && + Number.isFinite(region.width) && + region.width > 0 && + Number.isFinite(region.height) && + region.height > 0 && + Number.isFinite(region.scaleFactor) && + region.scaleFactor > 0 + ) +} + +export function buildRecordingOutputPath(saveDir: string, format: RecordFormat, now: Date = new Date()): string { + const stamp = + `${now.getFullYear()}${pad2(now.getMonth() + 1)}${pad2(now.getDate())}_` + + `${pad2(now.getHours())}${pad2(now.getMinutes())}${pad2(now.getSeconds())}` + const fileName = `recording_${stamp}.${format}` + return saveDir ? joinPath(saveDir, fileName) : fileName +} + +export function buildTranscodeOutputPath(inputPath: string, container: RecordFormat, suffix = 'export', now: Date = new Date()): string { + const dir = parentDirOf(inputPath) + const name = baseNameOf(inputPath) + const dot = name.lastIndexOf('.') + const stem = dot > 0 ? name.slice(0, dot) : name + const stamp = `${pad2(now.getHours())}${pad2(now.getMinutes())}${pad2(now.getSeconds())}` + const outName = `${stem}_${suffix}_${stamp}.${container}` + return dir ? joinPath(dir, outName) : outName +} + +/** 枚举宿主采集源(屏幕与窗口) */ +export async function fetchCaptureSources( + hostOverride?: unknown +): Promise<{ ok: boolean; sources: CaptureSourceItem[]; error?: string }> { + const res = await callHostTransport( + 'tool_media_capture_sources', + { includeScreens: true, includeWindows: true }, + hostOverride + ) + if (!res.ok) { + return { ok: false, sources: [], error: resolveErrorMessage(res, t('hostCallFailed', { method: 'tool_media_capture_sources' })) } + } + const rec = asRecord(res.data) + const rawList = Array.isArray(res.data) + ? res.data + : Array.isArray(rec?.sources) + ? rec.sources + : null + if (!rawList) { + return { ok: false, sources: [], error: t('hostInvalidResult', { method: 'tool_media_capture_sources' }) } + } + const sources: CaptureSourceItem[] = [] + for (const raw of rawList) { + const s = asRecord(raw) + if (!s) continue + const id = typeof s.id === 'string' ? s.id.trim() : typeof s.sourceId === 'string' ? s.sourceId.trim() : '' + if (!id) continue + const rawKind = String(s.kind ?? s.type ?? '').toLowerCase() + const kind: 'screen' | 'window' = rawKind === 'window' || id.startsWith('window:') ? 'window' : 'screen' + const name = typeof s.name === 'string' && s.name.trim() ? s.name.trim() : id + const bounds = asRecord(s.bounds) + const widthVal = parseFiniteNumber(s.width ?? bounds?.width) + const heightVal = parseFiniteNumber(s.height ?? bounds?.height) + const scaleVal = parseFiniteNumber(s.scaleFactor) + sources.push({ + id, + name, + kind, + ...(typeof s.displayId === 'string' && s.displayId.trim() ? { displayId: s.displayId.trim() } : {}), + width: widthVal !== null && widthVal > 0 ? Math.round(widthVal) : null, + height: heightVal !== null && heightVal > 0 ? Math.round(heightVal) : null, + scaleFactor: scaleVal !== null && scaleVal > 0 ? scaleVal : 1 + }) } - const hasError = typeof data.error === 'string' && data.error.length > 0 - if (data.ok === false || data.success === false || (hasError && data.ok !== true && data.success !== true)) { - return { ok: false, error: resolveErrorMessage(data, t('hostReturnedFailure', { func })) } + return { ok: true, sources } +} + +/** 按需下载并准备录屏与转码所需的薄原语运行组件 */ +export async function ensureRecordEngines( + hostOverride?: unknown +): Promise<{ ok: boolean; provisioned: string[]; error?: string }> { + const required = ['media.capture', 'media.probe', 'media.transcode'] as const + const provisioned: string[] = [] + for (const primitiveId of required) { + const res = await ensureRuntimeCapability(primitiveId, hostOverride) + if (!res.ok) { + return { + ok: false, + provisioned, + error: resolveErrorMessage(res, t('ensureFailedTitle')) + } + } + if (res.data?.status === 'unsupported') { + return { + ok: false, + provisioned, + error: t('statusUnsupported') + } + } + if (res.data?.provisioned) provisioned.push(primitiveId) } - return { ok: true, data } + return { ok: true, provisioned } } function parseSessions(raw: unknown): RecordSessionInfo[] { @@ -226,37 +448,52 @@ function parseSessions(raw: unknown): RecordSessionInfo[] { for (const item of raw) { const s = asRecord(item) if (!s) continue - const id = String(s.id ?? s.sessionId ?? '').trim() - if (!id) continue + const taskId = String(s.taskId ?? s.sessionId ?? s.id ?? '').trim() + if (!taskId) continue + const state = String(s.state ?? 'recording') + if (state !== 'recording' && state !== 'finalizing') continue + const rawMode = String(s.mode ?? '') + const mode: RecordMode | undefined = + rawMode === 'fullscreen' || rawMode === 'window' || rawMode === 'region' ? rawMode : undefined out.push({ - id, + id: taskId, + taskId, + ...(mode ? { mode } : {}), + ...(typeof s.sourceId === 'string' && s.sourceId ? { sourceId: s.sourceId } : {}), outputPath: typeof s.outputPath === 'string' ? s.outputPath : '', - startedAtMs: toEpochMs(s.startedAt) + startedAtMs: toEpochMs(s.startedAt ?? s.startedAtMs) }) } return out } -/** 向客户端查询当前是否有录制在进行(插件重新打开后以此为准,不靠插件内存里的状态) */ +/** 向宿主查询当前录制状态(tool_media_capture_status) */ export async function getRecordingStatus(hostOverride?: unknown): Promise { - const res = await callRecordHost('status', {}, hostOverride) - if (!res.ok) return { ok: false, recording: false, sessions: [], error: res.error } - if (typeof res.data.recording !== 'boolean') { + const res = await callHostTransport('tool_media_capture_status', {}, hostOverride) + if (!res.ok) { + return { + ok: false, + recording: false, + sessions: [], + error: resolveErrorMessage(res, t('hostCallFailed', { method: 'tool_media_capture_status' })) + } + } + const data = asRecord(res.data) + if (!data || !Array.isArray(data.sessions)) { return { ok: false, recording: false, sessions: [], error: t('hostNoRecordingStatus') } } - const sessions = parseSessions(res.data.sessions) - if (!res.data.recording) { + const sessions = parseSessions(data.sessions) + const recording = typeof data.recording === 'boolean' ? data.recording : sessions.length > 0 + if (!recording) { activeSessionId = '' - } else if (!sessions.some(s => s.id === activeSessionId)) { + if (!activeTaskId.startsWith('rec_transcode_')) activeTaskId = '' + } else if (!sessions.some((s) => s.taskId === activeTaskId)) { activeSessionId = sessions[0]?.id || '' + activeTaskId = sessions[0]?.taskId || activeSessionId } - return { ok: true, recording: res.data.recording, sessions } + return { ok: true, recording, sessions } } -/** - * 保存目录是否存在:只在系统视频文件夹能列出时判断,列不出返回 null(未知)。 - * 用来区分“还没录制过、目录尚未创建”和“读取目录失败”。 - */ async function recordingsDirExists(videosDir: string, hostOverride?: unknown): Promise { if (!videosDir) return null const res = await callHostTransport('filesystem_get_directory_contents', { path: videosDir }, hostOverride) @@ -265,7 +502,7 @@ async function recordingsDirExists(videosDir: string, hostOverride?: unknown): P const list: unknown[] | null = Array.isArray(res.data) ? res.data : Array.isArray(filesField) ? filesField : null if (!list) return null const target = RECORDINGS_FOLDER_NAME.toLowerCase() - return list.some(entry => { + return list.some((entry) => { if (!entry || typeof entry !== 'object') return false const e = entry as Record const isDir = Boolean(e.isDirectory ?? e.isDir ?? e.is_dir) @@ -273,10 +510,6 @@ async function recordingsDirExists(videosDir: string, hostOverride?: unknown): P }) } -/** - * 列出保存目录里的录制文件(只取直接位于目录下的 MP4 / GIF)。 - * 读取失败如实返回错误;取回的条目不全时标记 partial。 - */ export async function listRecordingFiles( saveDir: string, videosDir = '', @@ -285,10 +518,16 @@ export async function listRecordingFiles( const dir = String(saveDir || '').trim() if (!dir) return { files: [], partial: false, missing: false, error: t('noVideosFolder') } - const exists = await recordingsDirExists(String(videosDir || '').trim(), hostOverride) - if (exists === false) return { files: [], partial: false, missing: true } + if (videosDir && comparablePath(dir) === comparablePath(resolveRecordingsDir(videosDir))) { + const exists = await recordingsDirExists(String(videosDir || '').trim(), hostOverride) + if (exists === false) return { files: [], partial: false, missing: true } + } - const res = await callHostTransport('system_search_files', { query: `dir:${dir}`, limit: RECORDING_SCAN_LIMIT }, hostOverride) + const res = await callHostTransport( + 'system_search_files', + { query: `dir:${dir}`, limit: RECORDING_SCAN_LIMIT, sortBy: 'mtime-desc' }, + hostOverride + ) if (!res.ok) return { files: [], partial: false, missing: false, error: resolveErrorMessage(res, t('readSaveDirFailed')) } const data = asRecord(res.data) const rawFiles = data?.files @@ -311,19 +550,18 @@ export async function listRecordingFiles( const key = comparablePath(filePath) if (seen.has(key)) continue seen.add(key) - const size = Number(f.size ?? f.sizeBytes) + const size = parseFiniteNumber(f.size ?? f.sizeBytes) const dot = name.lastIndexOf('.') files.push({ id: filePath, name, path: filePath, extension: dot > 0 ? name.slice(dot).toLowerCase() : '', - sizeBytes: Number.isFinite(size) && size >= 0 ? size : null, + sizeBytes: size !== null && size >= 0 ? size : null, modifiedMs: toEpochMs(f.mtime ?? f.mtimeMs) }) } - // 新录制的排在前面;没有时间的排在最后,再按文件名倒序(客户端默认文件名带时间戳) files.sort((a, b) => { if (a.modifiedMs !== null && b.modifiedMs !== null && a.modifiedMs !== b.modifiedMs) return b.modifiedMs - a.modifiedMs if (a.modifiedMs === null && b.modifiedMs !== null) return 1 @@ -331,30 +569,44 @@ export async function listRecordingFiles( return b.name.localeCompare(a.name, getLocale()) }) - const totalMatches = Number(data.total_matches) - const partial = data.truncated === true || (Number.isFinite(totalMatches) && totalMatches > rawFiles.length) + const totalMatches = parseFiniteNumber(data.total_matches) + const partial = data.truncated === true || (totalMatches !== null && totalMatches > rawFiles.length) return { files, partial, missing: false } } -/** 读取保存目录、录制文件列表与客户端录制状态;各部分失败分别如实返回,不会抛错 */ -export async function fetchRecordWorkspace(hostOverride?: unknown): Promise { +/** 读取保存目录、录制文件、采集源、录制状态与宿主薄原语能力快照 */ +export async function fetchRecordWorkspace( + customSaveDir = '', + hostOverride?: unknown +): Promise { let videosDir = '' try { videosDir = await getRealSystemPath('videos', hostOverride) - } catch { + } catch (err) { + void err videosDir = '' } - const saveDir = resolveRecordingsDir(videosDir) + const saveDir = customSaveDir.trim() || resolveRecordingsDir(videosDir) - const [listing, status] = await Promise.all([ + const [listing, status, sourcesRes, capsRes] = await Promise.all([ listRecordingFiles(saveDir, videosDir, hostOverride).catch( (err): RecordingListResult => ({ files: [], partial: false, missing: false, error: errorText(err) }) ), getRecordingStatus(hostOverride).catch( (err): RecordStatusResult => ({ ok: false, recording: false, sessions: [], error: errorText(err) }) + ), + fetchCaptureSources(hostOverride).catch( + (err): { ok: boolean; sources: CaptureSourceItem[]; error?: string } => ({ ok: false, sources: [], error: errorText(err) }) + ), + queryRuntimeCapabilities(hostOverride).catch( + (err) => ({ ok: false as const, error: errorText(err) }) ) ]) + const capabilities = capsRes.ok && capsRes.data ? capsRes.data : null + const captureCap = findCapability(capabilities, 'media.capture') + const transcodeCap = findCapability(capabilities, 'media.transcode') + return { saveDir, recordings: listing.files, @@ -363,25 +615,55 @@ export async function fetchRecordWorkspace(hostOverride?: unknown): Promise { - const fps = config?.fps - const format = config?.format - if (!RECORD_FPS_OPTIONS.some(o => o.value === fps) || !RECORD_FORMAT_OPTIONS.some(o => o.value === format)) { +/** 发起屏幕录制(tool_media_capture_start):三模式透传真实 sourceId 与 DPI region */ +export async function startScreenRecording( + config: RecordSessionConfig, + hostOverride?: unknown +): Promise { + if ( + !config || + !RECORD_MODE_VALUES.includes(config.mode) || + !RECORD_FPS_OPTIONS.some((o) => o.value === config.fps) || + !RECORD_FORMAT_VALUES.includes(config.format) + ) { return failStart(t('invalidRecordConfig'), 'INVALID_RECORD_CONFIG') } + const sourceId = String(config.sourceId || '').trim() + if (!sourceId) { + return failStart(t('missingCaptureSource'), 'MISSING_CAPTURE_SOURCE') + } + if (config.mode === 'region' && !validateCaptureRegion(config.region)) { + return failStart(t('invalidRegionConfig'), 'INVALID_REGION_CONFIG') + } + const saveDir = String(config.saveDir || '').trim() + if (!saveDir) { + return failStart(t('missingSaveDir'), 'MISSING_SAVE_DIR') + } if (recordOpInFlight) return failStart(t('recordBusy'), 'RECORD_BUSY') recordOpInFlight = true - const saveDir = String(config.saveDir || '').trim() try { - // 已有录制在进行时不再启动第二个(客户端允许多个会话并存,停止时只会停掉其中一个) const status = await getRecordingStatus(hostOverride) if (!status.ok) { return failStart(t('cannotConfirmStatus', { error: status.error || '' }), status.error || 'RECORD_STATUS_UNKNOWN', saveDir) @@ -390,24 +672,51 @@ export async function startScreenRecording(config: RecordSessionConfig, hostOver return failStart(t('alreadyRecording'), 'RECORD_ALREADY_RUNNING', saveDir, status.sessions[0]?.id || '') } + const taskId = nextMessageId('rec_capture') + const targetPath = buildRecordingOutputPath(saveDir, config.format) const params: Record = { - type: format === 'gif' ? 'gif' : 'video', - format, - fps: Number(fps) + taskId, + mode: config.mode, + sourceId, + frameRate: Number(config.fps), + container: config.format, + includeSystemAudio: Boolean(config.includeSystemAudio), + includeMicrophone: Boolean(config.includeMicrophone), + overwrite: false, + output: { path: targetPath } } - if (saveDir) params.saveDir = saveDir - const res = await callRecordHost('startRecording', params, hostOverride) - if (!res.ok) return failStart(res.error, res.error, saveDir) + if (config.mode === 'region' && config.region) { + params.region = { + x: config.region.x, + y: config.region.y, + width: config.region.width, + height: config.region.height, + scaleFactor: config.region.scaleFactor + } + } + + const res = await callHostTransport('tool_media_capture_start', params, hostOverride) + if (!res.ok) { + const msg = resolveErrorMessage(res, t('hostCallFailed', { method: 'tool_media_capture_start' })) + return failStart(msg, msg, saveDir, '', res.errorCode) + } + const data = asRecord(res.data) + const returnedTaskId = typeof data?.taskId === 'string' && data.taskId ? data.taskId : taskId + const outputPath = typeof data?.outputPath === 'string' && data.outputPath ? data.outputPath : targetPath + activeSessionId = returnedTaskId + activeTaskId = returnedTaskId - const sessionId = typeof res.data.sessionId === 'string' ? res.data.sessionId : '' - activeSessionId = sessionId - const outputPath = typeof res.data.outputPath === 'string' && res.data.outputPath ? res.data.outputPath : undefined return { ok: true, - sessionId, - message: t('recordingStarted', { fps, format: format.toUpperCase() }), - saveDir: (outputPath && parentDirOf(outputPath)) || saveDir, - ...(outputPath ? { outputPath } : {}) + sessionId: returnedTaskId, + taskId: returnedTaskId, + message: t('recordingStarted', { + mode: getRecordModeLabel(config.mode), + fps: config.fps, + format: config.format.toUpperCase() + }), + saveDir: parentDirOf(outputPath) || saveDir, + outputPath } } catch (err) { const msg = errorText(err) @@ -417,24 +726,38 @@ export async function startScreenRecording(config: RecordSessionConfig, hostOver } } +/** 停止录制并优雅封装保存(tool_media_capture_stop) */ export async function stopScreenRecording(hostOverride?: unknown): Promise { if (recordOpInFlight) return { ok: false, message: t('recordBusy'), error: 'RECORD_BUSY' } recordOpInFlight = true try { - const params: Record = activeSessionId ? { sessionId: activeSessionId } : {} - const res = await callRecordHost('stopRecording', params, hostOverride) - // 客户端收尾时无论成败都会结束这个会话,插件不再记着它 + let targetTaskId = activeTaskId || activeSessionId + if (!targetTaskId) { + const status = await getRecordingStatus(hostOverride) + if (status.ok && status.sessions.length > 0) { + targetTaskId = status.sessions[0]!.taskId + } + } + if (!targetTaskId) { + return { ok: false, message: t('noActiveTaskToCancel'), error: 'NO_ACTIVE_SESSION' } + } + const res = await callHostTransport('tool_media_capture_stop', { taskId: targetTaskId }, hostOverride) + if (!res.ok) { + const msg = resolveErrorMessage(res, t('hostCallFailed', { method: 'tool_media_capture_stop' })) + return { ok: false, message: msg, error: msg } + } activeSessionId = '' - if (!res.ok) return { ok: false, message: res.error, error: res.error } - const outputPath = typeof res.data.outputPath === 'string' && res.data.outputPath ? res.data.outputPath : undefined - const size = Number(res.data.sizeBytes) - const duration = Number(res.data.durationMs) + activeTaskId = '' + const data = asRecord(res.data) + const outputPath = typeof data?.outputPath === 'string' && data.outputPath ? data.outputPath : undefined + const size = parseFiniteNumber(data?.outputBytes ?? data?.sizeBytes) + const duration = parseFiniteNumber(data?.durationMs) return { ok: true, message: t('recordingSaved'), ...(outputPath ? { outputPath } : {}), - ...(Number.isFinite(size) && size >= 0 ? { sizeBytes: size } : {}), - ...(Number.isFinite(duration) && duration >= 0 ? { durationMs: duration } : {}) + ...(size !== null && size >= 0 ? { sizeBytes: size } : {}), + ...(duration !== null && duration >= 0 ? { durationMs: duration } : {}) } } catch (err) { const msg = errorText(err) @@ -444,6 +767,192 @@ export async function stopScreenRecording(hostOverride?: unknown): Promise { + const targetTaskId = String(explicitTaskId || activeTaskId || activeSessionId || '').trim() + if (!targetTaskId) { + return { ok: false, taskId: '', cancelled: false, error: t('noActiveTaskToCancel') } + } + const res = await cancelRuntimeTask(targetTaskId, hostOverride) + if (!res.ok) { + return { + ok: false, + taskId: targetTaskId, + cancelled: false, + error: resolveErrorMessage(res, t('cancelFailedTitle')) + } + } + if (targetTaskId === activeTaskId || targetTaskId === activeSessionId) { + activeTaskId = '' + activeSessionId = '' + } + return { + ok: true, + taskId: targetTaskId, + cancelled: Boolean(res.data?.cancelled ?? true) + } +} + +/** 探测录制文件的真实媒体元信息(tool_media_probe) */ +export async function probeRecordedMedia( + filePath: string, + hostOverride?: unknown +): Promise { + const clean = String(filePath || '').trim() + if (!clean) { + return { + ok: false, + filePath: '', + container: null, + durationSec: null, + sizeBytes: null, + width: null, + height: null, + frameRate: null, + videoCodec: null, + audioCodec: null, + error: t('invalidRecordConfig') + } + } + const res = await callHostTransport('tool_media_probe', { inputs: [{ path: clean }] }, hostOverride) + if (!res.ok) { + return { + ok: false, + filePath: clean, + container: null, + durationSec: null, + sizeBytes: null, + width: null, + height: null, + frameRate: null, + videoCodec: null, + audioCodec: null, + error: resolveErrorMessage(res, t('probeFailedTitle')) + } + } + const rec = asRecord(res.data) + const items = Array.isArray(rec?.items) ? rec.items : [] + const first = asRecord(items[0]) + if (!first) { + return { + ok: false, + filePath: clean, + container: null, + durationSec: null, + sizeBytes: null, + width: null, + height: null, + frameRate: null, + videoCodec: null, + audioCodec: null, + error: t('hostInvalidResult', { method: 'tool_media_probe' }) + } + } + const streams = Array.isArray(first.streams) ? first.streams.map(asRecord).filter((s): s is Record => Boolean(s)) : [] + const videoStream = streams.find((s) => s.kind === 'video') + const audioStream = streams.find((s) => s.kind === 'audio') + const durationVal = parseFiniteNumber(first.durationSec) + const sizeVal = parseFiniteNumber(first.sizeBytes) + const widthVal = parseFiniteNumber(videoStream?.width) + const heightVal = parseFiniteNumber(videoStream?.height) + const fpsVal = parseFiniteNumber(videoStream?.frameRate) + return { + ok: true, + filePath: clean, + container: typeof first.container === 'string' && first.container ? first.container : null, + durationSec: durationVal !== null && durationVal >= 0 ? durationVal : null, + sizeBytes: sizeVal !== null && sizeVal >= 0 ? sizeVal : null, + width: widthVal !== null && widthVal > 0 ? Math.round(widthVal) : null, + height: heightVal !== null && heightVal > 0 ? Math.round(heightVal) : null, + frameRate: fpsVal !== null && fpsVal > 0 ? Number(fpsVal.toFixed(2)) : null, + videoCodec: typeof videoStream?.codec === 'string' && videoStream.codec ? videoStream.codec : null, + audioCodec: typeof audioStream?.codec === 'string' && audioStream.codec ? audioStream.codec : null + } +} + +/** 后期二次转码 / 时间裁切 / 空间裁剪导出(tool_media_transcode_run,严禁覆盖原文件) */ +export async function transcodeRecording( + options: RecordTranscodeOptions, + hostOverride?: unknown +): Promise { + const inputPath = String(options?.inputPath || '').trim() + if (!inputPath || !RECORD_FORMAT_VALUES.includes(options.container)) { + return { ok: false, taskId: '', error: t('invalidRecordConfig') } + } + const hasTrim = options.trimStartSec !== undefined || options.trimDurationSec !== undefined + if (hasTrim) { + const start = options.trimStartSec ?? 0 + const dur = options.trimDurationSec + if (!Number.isFinite(start) || start < 0 || (dur !== undefined && (!Number.isFinite(dur) || dur <= 0))) { + return { ok: false, taskId: '', error: t('invalidTrimRange') } + } + } + + const taskId = nextMessageId('rec_transcode') + const suffix = hasTrim ? 'trimmed' : 'export' + const outputPath = buildTranscodeOutputPath(inputPath, options.container, suffix) + const params: Record = { + taskId, + input: { path: inputPath }, + output: { path: outputPath }, + overwrite: false, + container: options.container + } + if (hasTrim) { + params.trim = { + ...(options.trimStartSec !== undefined ? { startSec: options.trimStartSec } : {}), + ...(options.trimDurationSec !== undefined ? { durationSec: options.trimDurationSec } : {}) + } + } + if ( + options.crop && + hasCapabilityExtension(options.capabilities, 'media.transcode', 'geometry') && + Number.isFinite(options.crop.x) && + options.crop.x >= 0 && + Number.isFinite(options.crop.y) && + options.crop.y >= 0 && + options.crop.width > 0 && + options.crop.height > 0 + ) { + params.crop = { ...options.crop } + } + if ( + typeof options.speedFactor === 'number' && + Number.isFinite(options.speedFactor) && + options.speedFactor > 0 && + hasCapabilityExtension(options.capabilities, 'media.transcode', 'speed') + ) { + params.speedFactor = options.speedFactor + } + + activeTaskId = taskId + try { + const res = await callHostTransport('tool_media_transcode_run', params, hostOverride) + if (!res.ok) { + return { + ok: false, + taskId, + error: resolveErrorMessage(res, t('transcodeFailedTitle')) + } + } + const data = asRecord(res.data) + const outBytes = parseFiniteNumber(data?.outputBytes) + const durMs = parseFiniteNumber(data?.durationMs) + return { + ok: true, + taskId: typeof data?.taskId === 'string' && data.taskId ? data.taskId : taskId, + outputPath, + ...(outBytes !== null && outBytes >= 0 ? { outputBytes: outBytes } : {}), + ...(durMs !== null && durMs >= 0 ? { durationMs: durMs } : {}) + } + } finally { + if (activeTaskId === taskId) activeTaskId = '' + } +} + export async function openRecordedVideo(fullPath: string, hostOverride?: unknown): Promise { if (!fullPath) return false return openRealPath(fullPath, hostOverride) diff --git a/extensions/record/src/native-ipc.ts b/extensions/record/src/native-ipc.ts deleted file mode 100644 index 51576b99..00000000 --- a/extensions/record/src/native-ipc.ts +++ /dev/null @@ -1,1852 +0,0 @@ -import { getLocale } from '@ztools/declarative-ui' - -type DynamicBridge = ReturnType - -const NATIVE_IPC_MESSAGES: Record string - dirEntrySep: string - dirErrorColon: string - deepScanUnavailable: string - pathEmpty: string - invalidMethodEmpty: string - invalidMethodFormat: string - invalidParamsObject: string - paramTooLong: (key: string) => string - paramOutOfRange: (key: string) => string - methodParamEmpty: string - invalidMethodType: string - malformedDllResponse: string - unknownDllError: string - hostIpcFailed: (pluginName: string, method: string) => string - hostUnavailable: (pluginName: string, method: string) => string - callFailed: string - movedToTrash: string - deleteFailed: string - revealedInFolder: string - revealFailed: string - opened: string - openFailed: string - pluginCallNotReady: string -}> = { - 'zh-CN': { - ipcCallFailed: 'IPC 调用返回失败', - ipcInnerFailed: 'IPC 内部调用失败', - scanIncomplete: '扫描结果不完整', - dirReadFailed: (details, moreCount) => - `目录读取失败或不完整:${details}${moreCount > 0 ? `;另有 ${moreCount} 个目录` : ''}`, - dirEntrySep: ';', - dirErrorColon: ':', - deepScanUnavailable: '深度扫描不可用,仅列出一级目录,结果不完整', - pathEmpty: '路径不能为空', - invalidMethodEmpty: 'INVALID_METHOD: 调用方法名不能为空', - invalidMethodFormat: 'INVALID_METHOD_FORMAT: 方法名包含非法字符或超长', - invalidParamsObject: 'INVALID_PARAMS: 参数必须为非空对象', - paramTooLong: (key) => `PARAM_TOO_LONG: 参数 ${key} 超过最大长度限制`, - paramOutOfRange: (key) => `PARAM_OUT_OF_RANGE: 数值参数 ${key} 越界或非有限数`, - methodParamEmpty: 'method 参数不能为空', - invalidMethodType: 'INVALID_METHOD: method 不能为空且必须为字符串', - malformedDllResponse: 'MALFORMED_DLL_RESPONSE: 原生组件返回了损坏的 JSON 数据', - unknownDllError: '原生组件返回未知错误', - hostIpcFailed: (pluginName, method) => `HOST_IPC_FAILED: ${pluginName}.${method} 调用失败`, - hostUnavailable: (pluginName, method) => `HOST_UNAVAILABLE: ${pluginName}.${method} 宿主接口未就绪`, - callFailed: '调用失败', - movedToTrash: '已移入回收站', - deleteFailed: '删除失败', - revealedInFolder: '已定位文件', - revealFailed: '定位失败', - opened: '已打开', - openFailed: '打开失败', - pluginCallNotReady: '插件调用未就绪' - }, - 'en-US': { - ipcCallFailed: 'IPC call failed', - ipcInnerFailed: 'Internal IPC call failed', - scanIncomplete: 'Incomplete scan results', - dirReadFailed: (details, moreCount) => - `Directory read failed or incomplete: ${details}${moreCount > 0 ? `; and ${moreCount} more` : ''}`, - dirEntrySep: '; ', - dirErrorColon: ': ', - deepScanUnavailable: 'Deep scan unavailable; only top-level directory listed (incomplete)', - pathEmpty: 'Path cannot be empty', - invalidMethodEmpty: 'INVALID_METHOD: Method name cannot be empty', - invalidMethodFormat: 'INVALID_METHOD_FORMAT: Method name contains invalid characters or is too long', - invalidParamsObject: 'INVALID_PARAMS: Parameters must be a non-null object', - paramTooLong: (key) => `PARAM_TOO_LONG: Parameter "${key}" exceeds maximum length`, - paramOutOfRange: (key) => `PARAM_OUT_OF_RANGE: Numeric parameter "${key}" is out of range or non-finite`, - methodParamEmpty: 'Method parameter cannot be empty', - invalidMethodType: 'INVALID_METHOD: Method must be a non-empty string', - malformedDllResponse: 'MALFORMED_DLL_RESPONSE: Native component returned malformed JSON', - unknownDllError: 'Native component returned an unknown error', - hostIpcFailed: (pluginName, method) => `HOST_IPC_FAILED: ${pluginName}.${method} call failed`, - hostUnavailable: (pluginName, method) => `HOST_UNAVAILABLE: ${pluginName}.${method} host interface not ready`, - callFailed: 'Call failed', - movedToTrash: 'Moved to Trash', - deleteFailed: 'Delete failed', - revealedInFolder: 'Revealed in folder', - revealFailed: 'Failed to reveal item', - opened: 'Opened', - openFailed: 'Failed to open', - pluginCallNotReady: 'Plugin invocation not ready' - } -} - -function ipcStrings() { - const locale = getLocale() - return NATIVE_IPC_MESSAGES[locale] ?? NATIVE_IPC_MESSAGES['en-US'] -} -/** - * ZTools 真实宿主 IPC 与系统能力桥接层 (Real Host IPC Bridge) - * - * 严格遵循《ZTools Declarative UI 2.0 架构与 35 款原生插件全量升级规范》5.1 真实环境铁律: - * - 在真实 Electron 宿主环境中,100% 走通 Preload (__ztoolsElectron.transport.methods / window.ztools / __ztoolsLauncher) 真实调用链路 - * - 严禁在真实环境中因参数格式或嵌套响应结构差异而回退到假数据 - */ - -let ipcReqSeq = 1 -const realFileSizeCache = new Map() - -export function nextMessageId(prefix = 'ipc'): string { - ipcReqSeq = (ipcReqSeq + 1) % 1_000_000 - return `${prefix}_${Date.now()}_${ipcReqSeq}` -} - -/** - * 判断当前是否处于真实的 ZTools Electron 渲染进程宿主环境 - */ -export function isRealElectronHost(hostOverride?: unknown): boolean { - if (hostOverride) return false - if (typeof window === 'undefined') return false - const w = window as DynamicBridge - return Boolean( - w.__ztoolsElectron?.transport?.methods || - w.ztools?.transport?.call || - w.ztools?.transport?.methods - ) -} - -function normalizeMethodParams(method: string, params: Record): Record { - if (!params || typeof params !== 'object') return {} - const next = { ...params } - if (method === 'system_get_disk_usage') { - const rawDrive = String(next.drive || next.path || 'C:\\').trim() - if (rawDrive.startsWith('/')) { - next.drive = rawDrive - } else { - const match = rawDrive.match(/^([A-Za-z]):/) - next.drive = match ? `${match[1].toUpperCase()}:\\` : rawDrive.replace(/\//g, '\\') - } - delete next.path - } - return next -} - -function normalizeMethodResult(method: string, payload: DynamicBridge): DynamicBridge { - if (!payload || typeof payload !== 'object') return payload - - if (method === 'system_get_disk_usage') { - const avail = typeof payload.available === 'number' - ? payload.available - : typeof payload.free === 'number' - ? payload.free - : Math.max(0, Number(payload.total || 0) - Number(payload.used || 0)) - return { - ...payload, - available: avail, - free: avail - } - } - - if (method === 'system_get_hardware_summary') { - const cpuModel = - typeof payload.cpuModel === 'string' && payload.cpuModel.trim() - ? payload.cpuModel.trim() - : Array.isArray(payload.cpuModels) && payload.cpuModels.length > 0 - ? String(payload.cpuModels[0]).trim() - : 'x86_64 Processor' - return { - ...payload, - cpuModel - } - } - - if (method === 'system_get_battery_status') { - // 宿主约定 percent 超出 0-100(如 255)表示无电池或电量未知,不能改写成 100% - const rawPct = payload.percent - const hasBattery = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 - return { - ...payload, - percent: hasBattery ? rawPct : null, - hasBattery - } - } - - if (method === 'screen_get_all_displays') { - const list = Array.isArray(payload) - ? payload - : Array.isArray(payload.displays) - ? payload.displays - : [] - return list.map((d: DynamicBridge) => ({ - ...d, - label: d?.label || d?.name || `Display #${d?.id ?? 1}` - })) - } - - return payload -} - -function extractIpcErrorMeta(errObj: DynamicBridge): { - errorCode?: string - errorDetails?: Record -} { - if (!errObj || typeof errObj !== 'object') return {} - const errorCode = - typeof errObj.errorCode === 'string' && errObj.errorCode.trim() - ? errObj.errorCode.trim() - : typeof errObj.code === 'string' && errObj.code.trim() - ? errObj.code.trim() - : undefined - const rawDetails = - errObj.errorDetails && typeof errObj.errorDetails === 'object' && !Array.isArray(errObj.errorDetails) - ? (errObj.errorDetails as Record) - : errObj.details && typeof errObj.details === 'object' && !Array.isArray(errObj.details) - ? (errObj.details as Record) - : undefined - return { - ...(errorCode ? { errorCode } : {}), - ...(rawDetails ? { errorDetails: rawDetails } : {}) - } -} - -function unwrapTransportResponse( - method: string, - raw: DynamicBridge -): { ok: boolean; data?: DynamicBridge; error?: string; errorCode?: string; errorDetails?: Record } { - if (raw === null || raw === undefined) { - return { ok: false, error: 'EMPTY_IPC_RESPONSE', errorCode: 'EMPTY_IPC_RESPONSE' } - } - if (typeof raw !== 'object') { - return { ok: true, data: raw } - } - if (raw.success === false) { - const errObj = raw.error - const errMsg = - typeof errObj === 'object' && errObj !== null - ? String(errObj.message || errObj.code || JSON.stringify(errObj)) - : String(errObj || ipcStrings().ipcCallFailed) - return { ok: false, error: errMsg, ...extractIpcErrorMeta(raw), ...extractIpcErrorMeta(errObj) } - } - - const firstLayer = 'data' in raw && raw.data !== undefined ? raw.data : raw - if (firstLayer && typeof firstLayer === 'object' && !Array.isArray(firstLayer)) { - if (firstLayer.success === false) { - const errObj = firstLayer.error - const errMsg = - typeof errObj === 'object' && errObj !== null - ? String(errObj.message || errObj.code || JSON.stringify(errObj)) - : String(errObj || ipcStrings().ipcInnerFailed) - return { ok: false, error: errMsg, ...extractIpcErrorMeta(firstLayer), ...extractIpcErrorMeta(errObj) } - } - if ('data' in firstLayer && firstLayer.data !== undefined) { - return { ok: true, data: normalizeMethodResult(method, firstLayer.data) } - } - } - - return { ok: true, data: normalizeMethodResult(method, firstLayer) } -} - -/** - * 调用 Electron Preload Transport 方法(自动封装合法的 alphanumeric messageId 与双层解包) - */ -export async function callHostTransport( - method: string, - params: Record = {}, - hostOverride?: DynamicBridge -): Promise<{ ok: boolean; data?: T; error?: string; errorCode?: string; errorDetails?: Record }> { - const normalizedParams = normalizeMethodParams(method, params) - - // 1. 测试注入的 hostOverride 优先 - if (hostOverride) { - if (typeof hostOverride[method] === 'function') { - try { - const res = await hostOverride[method](normalizedParams) - const unwrapped = unwrapTransportResponse(method, res) - return unwrapped as { ok: boolean; data?: T; error?: string; errorCode?: string; errorDetails?: Record } - } catch (err: DynamicBridge) { - return { ok: false, error: err instanceof Error ? err.message : String(err), ...extractIpcErrorMeta(err) } - } - } - if (typeof hostOverride?.transport?.call === 'function') { - try { - const res = await hostOverride.transport.call(method, normalizedParams) - const unwrapped = unwrapTransportResponse(method, res) - return unwrapped as { ok: boolean; data?: T; error?: string; errorCode?: string; errorDetails?: Record } - } catch (err: DynamicBridge) { - return { ok: false, error: err instanceof Error ? err.message : String(err), ...extractIpcErrorMeta(err) } - } - } - } - - if (typeof window === 'undefined') { - return { ok: false, error: 'NO_WINDOW_ENV', errorCode: 'NO_WINDOW_ENV' } - } - - const w = window as DynamicBridge - const methods = w.__ztoolsElectron?.transport?.methods || w.ztools?.transport?.methods - const fn = methods?.[method] - - if (typeof fn === 'function') { - try { - const messageId = nextMessageId(method.replace(/[^A-Za-z0-9_]/g, '_').slice(0, 24)) - const raw = await fn({ messageId, params: normalizedParams }) - return unwrapTransportResponse(method, raw) as { ok: boolean; data?: T; error?: string; errorCode?: string; errorDetails?: Record } - } catch (err: DynamicBridge) { - return { ok: false, error: err instanceof Error ? err.message : String(err), ...extractIpcErrorMeta(err) } - } - } - - if (typeof w.ztools?.transport?.call === 'function') { - try { - const raw = await w.ztools.transport.call(method, normalizedParams) - return unwrapTransportResponse(method, raw) as { ok: boolean; data?: T; error?: string; errorCode?: string; errorDetails?: Record } - } catch (err: DynamicBridge) { - return { ok: false, error: err instanceof Error ? err.message : String(err), ...extractIpcErrorMeta(err) } - } - } - - return { ok: false, error: `METHOD_NOT_AVAILABLE: ${method}`, errorCode: 'METHOD_NOT_AVAILABLE' } -} - -export interface RealDiskDriveInfo { - drive: string - totalBytes: number - usedBytes: number - availableBytes: number - usagePercent: number -} - -/** - * 探测本机全部真实挂载磁盘分区 (C:\ ~ Z:\ 或 macOS/POSIX 挂载点 '/') - */ -export async function probeRealDiskDrives( - candidateLetters: string[] = ['C', 'D', 'E', 'F', 'G'], - hostOverride?: DynamicBridge -): Promise { - const drives: RealDiskDriveInfo[] = [] - const results = await Promise.all( - candidateLetters.map(async (letter) => { - const raw = String(letter || '').trim() - const isPosix = raw.startsWith('/') - const drivePath = isPosix ? raw : `${raw.replace(/:\\?$/, '').toUpperCase()}:\\` - const res = await callHostTransport<{ - total: number - used: number - available: number - free?: number - percent: number - }>('system_get_disk_usage', { drive: drivePath }, hostOverride) - if (res.ok && res.data && typeof res.data.total === 'number' && res.data.total > 0) { - const availableBytes = - typeof res.data.available === 'number' - ? res.data.available - : typeof res.data.free === 'number' - ? res.data.free - : Math.max(0, res.data.total - res.data.used) - return { - drive: isPosix ? raw : `${raw.replace(/:\\?$/, '').toUpperCase()}:`, - totalBytes: res.data.total, - usedBytes: res.data.used, - availableBytes, - usagePercent: res.data.percent - } - } - return null - }) - ) - - for (const item of results) { - if (item) drives.push(item) - } - - if (drives.length === 0 && !candidateLetters.includes('/')) { - const posixRes = await callHostTransport<{ - total: number - used: number - available: number - free?: number - percent: number - }>('system_get_disk_usage', { drive: '/' }, hostOverride) - if (posixRes.ok && posixRes.data && typeof posixRes.data.total === 'number' && posixRes.data.total > 0) { - const availableBytes = - typeof posixRes.data.available === 'number' - ? posixRes.data.available - : typeof posixRes.data.free === 'number' - ? posixRes.data.free - : Math.max(0, posixRes.data.total - posixRes.data.used) - drives.push({ - drive: '/', - totalBytes: posixRes.data.total, - usedBytes: posixRes.data.used, - availableBytes, - usagePercent: posixRes.data.percent - }) - } - } - - return drives -} - -/** - * 获取本机真实系统特殊路径(支持 home 派生标准子目录兜底,自动兼容 Windows 与 macOS/POSIX) - */ -export async function getRealSystemPath( - name: 'home' | 'appData' | 'userData' | 'desktop' | 'documents' | 'downloads' | 'music' | 'pictures' | 'videos' | 'temp' | 'cache', - hostOverride?: DynamicBridge -): Promise { - const res = await callHostTransport('system_get_path', { name }, hostOverride) - if (res.ok && res.data) { - if (typeof res.data === 'string' && res.data.trim().length > 0) { - return res.data.trim() - } - if (typeof res.data.path === 'string' && res.data.path.trim().length > 0) { - return res.data.path.trim() - } - } - - if (name !== 'home') { - const home = await getRealSystemPath('home', hostOverride) - if (home) { - const isPosix = home.startsWith('/') - const subMap: Record = isPosix - ? { - desktop: `${home}/Desktop`, - documents: `${home}/Documents`, - downloads: `${home}/Downloads`, - music: `${home}/Music`, - pictures: `${home}/Pictures`, - videos: `${home}/Videos`, - appData: `${home}/Library/Application Support`, - userData: `${home}/Library/Application Support/ZTools`, - temp: '/tmp', - cache: `${home}/Library/Caches` - } - : { - desktop: `${home}\\Desktop`, - documents: `${home}\\Documents`, - downloads: `${home}\\Downloads`, - music: `${home}\\Music`, - pictures: `${home}\\Pictures`, - videos: `${home}\\Videos`, - appData: `${home}\\AppData\\Roaming`, - userData: `${home}\\AppData\\Roaming\\ZTools`, - temp: `${home}\\AppData\\Local\\Temp`, - cache: `${home}\\AppData\\Local` - } - if (subMap[name]) return subMap[name] - } - } - - return '' -} - -export type RealDriveUsageInfo = RealDiskDriveInfo - -export interface RealIndexedFileEntry { - name: string - path: string - ext: string - isDir: boolean - isDirectory: boolean - size: number - sizeBytes: number - mtime: number - mtimeMs: number - lastModifiedMs: number -} - -export interface RealDirectorySubdirSummary { - name: string - path: string - fileCount: number - totalBytes: number - mtime: number - /** 体积不是完整统计(宿主扫描截断且独立统计超时 / 无权限),totalBytes 只是下限 */ - approximate?: boolean -} - -export interface RealDirectoryScanResult extends Iterable { - files: RealIndexedFileEntry[] - totalFiles: number - fileCount: number - totalBytes: number - subdirs: RealDirectorySubdirSummary[] - /** 宿主扫描达到条目上限后停止:files / totalFiles 只是已遍历部分的抽样 */ - truncated?: boolean - /** totalBytes 为近似值(下限) */ - approximate?: boolean - /** 宿主实际遍历的条目数 */ - visitedEntries?: number - /** 读取失败的真实原因;已有文件仍可使用,但不能当作完整结果。 */ - error?: string -} - -interface ScanResultMeta { - truncated?: boolean - approximate?: boolean - visitedEntries?: number -} - -export interface ScanDirectoryTreeOptions { - maxDepth?: number - maxFiles?: number - collectTopN?: number - filterExt?: RegExp - hostOverride?: DynamicBridge -} - -function extractFileExt(fileNameOrPath: string): string { - const base = String(fileNameOrPath || '').split(/[\\/]/).pop() || '' - const dotIdx = base.lastIndexOf('.') - return dotIdx > 0 ? base.slice(dotIdx).toLowerCase() : '' -} - -function normalizeIndexedFileEntry(f: DynamicBridge): RealIndexedFileEntry { - const p = String(f?.path || '') - const name = String(f?.name || p.split(/[\\/]/).pop() || '') - const sz = Number(f?.size ?? f?.sizeBytes ?? 0) - const isDir = Boolean(f?.is_dir || f?.isDir || f?.isDirectory) - const rawMtime = Number(f?.mtime ?? f?.mtimeMs ?? 0) - const mtimeMs = rawMtime > 1e11 ? rawMtime : rawMtime > 0 ? rawMtime * 1000 : Date.now() - const mtimeSec = rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime - if (p && sz >= 0) realFileSizeCache.set(p, sz) - return { - name, - path: p, - ext: extractFileExt(name || p), - isDir, - isDirectory: isDir, - size: sz, - sizeBytes: sz, - mtime: mtimeSec, - mtimeMs, - lastModifiedMs: mtimeMs - } -} - -function makeScanResult( - files: RealIndexedFileEntry[], - totalFiles: number, - totalBytes: number, - subdirs: RealDirectorySubdirSummary[], - meta: ScanResultMeta = {} -): RealDirectoryScanResult { - return { - files, - totalFiles, - fileCount: totalFiles, - totalBytes, - subdirs, - ...(meta.truncated ? { truncated: true } : {}), - ...(meta.approximate ? { approximate: true } : {}), - ...(typeof meta.visitedEntries === 'number' ? { visitedEntries: meta.visitedEntries } : {}), - [Symbol.iterator]() { - return files[Symbol.iterator]() - } - } -} - -/** - * 调用客户端的原生文件索引组件 (ztools-indexer) 检索文件 - */ -export async function searchRealIndexedFiles( - query: string, - limit = 40, - hostOverride?: DynamicBridge -): Promise { - if (!query || !query.trim()) return [] - const q = query.trim() - const safeLimit = Math.min(200, Math.max(1, Math.floor(limit || 40))) - - try { - const res = await callHostTransport<{ files?: DynamicBridge[] }>( - 'system_search_files', - { query: q, limit: safeLimit }, - hostOverride - ) - if (res.ok && res.data && Array.isArray(res.data.files)) { - return res.data.files.map(normalizeIndexedFileEntry) - } - - if (!hostOverride && typeof window !== 'undefined') { - const w = window as DynamicBridge - if (typeof w.__ztoolsLauncher?.searchFiles === 'function') { - const rawOuter = await w.__ztoolsLauncher.searchFiles(q, safeLimit) - const raw = rawOuter && typeof rawOuter === 'object' && 'data' in rawOuter && rawOuter.data ? rawOuter.data : rawOuter - if (raw && Array.isArray(raw.files)) { - return raw.files.map(normalizeIndexedFileEntry) - } - } - } - } catch { - // ignore - } - return [] -} - -/** - * 深度扫描指定真实物理目录树(支持符号链接穿透,如 AppData\Roaming\Tencent -> D:\Local\Roaming\Tencent) - * 返回该目录下 Top 文件列表、全树真实文件总数、全树真实总字节数与一级子目录汇总 - */ -export async function scanRealDirectoryTree( - dirPath: string, - limitOrOptions: number | ScanDirectoryTreeOptions = 160, - hostOverrideArg?: DynamicBridge -): Promise { - const result = await scanDirectoryTreeWithError(dirPath, limitOrOptions, hostOverrideArg) - return result.error ? { ...result.scan, error: result.error } : result.scan -} - -/** 一次界面扫描的错误汇总;多个目录并行扫描时保留可读目录的结果。 */ -export function createDirectoryScanner(hostOverride?: DynamicBridge) { - const failures = new Map() - return { - async scan(dir: string, options: number | ScanDirectoryTreeOptions = 160) { - const result = await scanRealDirectoryTree(dir, options, hostOverride) - const error = result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') - if (error) failures.set(dir, error) - else failures.delete(dir) - return result - }, - get error(): string | undefined { - if (!failures.size) return undefined - const s = ipcStrings() - const details = [...failures].slice(0, 3).map(([dir, error]) => `${dir}${s.dirErrorColon}${error}`).join(s.dirEntrySep) - return s.dirReadFailed(details, Math.max(0, failures.size - 3)) - } - } -} - -/** scanRealDirectoryTree 的实现:额外带回读取失败原因(目录不存在 / 为空 / 无权限 / 载荷异常) */ -async function scanDirectoryTreeWithError( - dirPath: string, - limitOrOptions: number | ScanDirectoryTreeOptions, - hostOverrideArg?: DynamicBridge -): Promise<{ scan: RealDirectoryScanResult; error?: string }> { - const empty = makeScanResult([], 0, 0, []) - if (!dirPath || !dirPath.trim()) return { scan: empty, error: 'EMPTY_DIRECTORY_PATH' } - const targetDir = dirPath.trim() - - const opts: ScanDirectoryTreeOptions = - typeof limitOrOptions === 'number' - ? { maxFiles: limitOrOptions, hostOverride: hostOverrideArg } - : { ...limitOrOptions, hostOverride: limitOrOptions?.hostOverride ?? hostOverrideArg } - - const rawLimit = opts.maxFiles ?? opts.collectTopN ?? 160 - const safeLimit = Math.min(200, Math.max(1, Math.floor(rawLimit || 160))) - const hostOverride = opts.hostOverride - const filterExt = opts.filterExt - const dirQuery = `dir:${targetDir}` - - try { - let rawPayload: DynamicBridge = null - const res = await callHostTransport( - 'system_search_files', - { query: dirQuery, limit: safeLimit }, - hostOverride - ) - if (res.ok && res.data) { - rawPayload = res.data - } - if (!rawPayload && !hostOverride && typeof window !== 'undefined') { - const w = window as DynamicBridge - if (typeof w.__ztoolsLauncher?.searchFiles === 'function') { - const rawOuter = await w.__ztoolsLauncher.searchFiles(dirQuery, safeLimit) - rawPayload = - rawOuter && typeof rawOuter === 'object' && 'data' in rawOuter && rawOuter.data - ? rawOuter.data - : rawOuter - } - } - - if ( - rawPayload && - Array.isArray(rawPayload.files) - ) { - let files: RealIndexedFileEntry[] = rawPayload.files.map(normalizeIndexedFileEntry) - if (filterExt instanceof RegExp) { - files = files.filter(f => !f.isDir && (filterExt.test(f.name) || filterExt.test(f.ext))) - // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索目标扩展名 - if (files.length === 0 && !hostOverride) { - const extTokens = (filterExt.source.match(/[a-z0-9]{2,5}/gi) || []) - .filter(t => !['thumbcache', 'iconcache'].includes(t.toLowerCase())) - .slice(0, 4) - // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 - const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() - const extraLists = await Promise.all( - extTokens.map(ext => searchRealIndexedFiles(`.${ext.toLowerCase()}`, 30, hostOverride)) - ) - const seen = new Set() - for (const list of extraLists) { - for (const item of list) { - if (!item.isDir && item.size > 0 && !seen.has(item.path)) { - if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { - seen.add(item.path) - files.push(item) - } - } - } - } - } - } - if (typeof opts.collectTopN === 'number' && opts.collectTopN > 0 && files.length > opts.collectTopN) { - files = files.slice(0, opts.collectTopN) - } - const subdirs: RealDirectorySubdirSummary[] = Array.isArray(rawPayload.subdirs) - ? rawPayload.subdirs.map((s: DynamicBridge) => ({ - name: String(s.name || ''), - path: String(s.path || ''), - fileCount: Number(s.file_count ?? s.fileCount ?? 0), - totalBytes: Number(s.total_bytes ?? s.totalBytes ?? 0), - mtime: Number(s.mtime || 0), - ...(s.approximate === true ? { approximate: true } : {}) - })) - : [] - const computedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) - const totalFilesCount = - filterExt instanceof RegExp ? files.length : Number(rawPayload.total_matches ?? files.length) - const totalBytesCount = - filterExt instanceof RegExp ? computedBytes : Number(rawPayload.total_bytes ?? computedBytes) - const visited = Number(rawPayload.visited_entries) - return { - scan: makeScanResult(files, totalFilesCount, totalBytesCount, subdirs, { - truncated: rawPayload.truncated === true, - approximate: rawPayload.approximate === true, - ...(Number.isFinite(visited) && visited >= 0 ? { visitedEntries: visited } : {}) - }), - ...(typeof rawPayload.scan_error === 'string' && rawPayload.scan_error ? { error: rawPayload.scan_error } : {}) - } - } - - // 深度扫描失败或回执无效时,仅以一级目录读取补回可见结果;不冒充完整目录树。 - const listing = await listDirectoryViaFilesystem(targetDir, hostOverride, { withSizes: true, limit: safeLimit }) - if (listing.ok && listing.entries.length > 0) { - const files: RealIndexedFileEntry[] = [] - let totalBytes = 0 - for (const entry of listing.entries) { - if (filterExt instanceof RegExp && !filterExt.test(entry.name) && !filterExt.test(entry.ext)) { - continue - } - files.push(entry) - totalBytes += entry.isDir ? 0 : entry.size - } - const incomplete = listing.entries.some(entry => entry.isDir) || listing.entries.length >= safeLimit - return { - scan: makeScanResult(files, files.filter(file => !file.isDir).length, totalBytes, [], { approximate: incomplete }), - ...(incomplete ? { error: res.error || ipcStrings().deepScanUnavailable } : {}) - } - } - return listing.ok ? { scan: empty } : { scan: empty, error: listing.error || 'DIRECTORY_READ_FAILED' } - } catch (error) { - return { scan: empty, error: error instanceof Error ? error.message : String(error) } - } -} - - -/** 目录读取不到任何条目(不存在 / 为空 / 无权限)时的错误码 */ -export const DIRECTORY_EMPTY_OR_UNREADABLE = 'DIRECTORY_EMPTY_OR_UNREADABLE' - -export interface RealDirectoryListingResult { - /** 目录内条目的完整路径;读取失败时为空数组 */ - entries: string[] - /** 读取失败或目录为空时的错误码 / 宿主错误信息 */ - error?: string -} - -export interface RealDirectChildrenResult { - /** 目录的直接子项(子目录在前),按路径去重 */ - entries: RealIndexedFileEntry[] - /** 宿主扫描达到条目上限,可能只返回了部分直接子项 */ - partial: boolean - error?: string -} - -function stripTrailingSeparators(p: string): string { - const trimmed = p.replace(/[\\/]+$/, '') - return trimmed || p.slice(0, 1) -} - -function isWindowsStylePath(p: string): boolean { - return /^[A-Za-z]:/.test(p) || p.startsWith('\\\\') || (p.includes('\\') && !p.includes('/')) -} - -function comparablePath(p: string): string { - const stripped = stripTrailingSeparators(String(p || '').trim()) - return isWindowsStylePath(stripped) ? stripped.replace(/\//g, '\\').toLowerCase() : stripped -} - -function parentDirOf(p: string): string { - const stripped = stripTrailingSeparators(String(p || '')) - const idx = Math.max(stripped.lastIndexOf('/'), stripped.lastIndexOf('\\')) - if (idx < 0) return '' - if (idx === 0) return stripped.slice(0, 1) - const parent = stripped.slice(0, idx) - return /^[A-Za-z]:$/.test(parent) ? `${parent}\\` : parent -} - -function isDirectChildPath(dirPath: string, candidate: string): boolean { - if (!candidate) return false - return comparablePath(parentDirOf(candidate)) === comparablePath(dirPath) -} - -function joinChildPath(dirPath: string, name: string): string { - const sep = isWindowsStylePath(dirPath) ? '\\' : '/' - const base = dirPath.replace(/[\\/]+$/, '') - return `${base}${sep}${name}` -} - -/** - * 通过 filesystem_get_directory_contents 读取一级目录(需宿主授权)。 - * 宿主真实返回 { success, files: [{ name, size, isDirectory, lastModified }] }(name 为文件名); - * 兼容旧测试替身返回的完整路径字符串数组。 - */ -async function listDirectoryViaFilesystem( - dirPath: string, - hostOverride: DynamicBridge, - options: { withSizes?: boolean; limit?: number } = {} -): Promise<{ ok: boolean; entries: RealIndexedFileEntry[]; error?: string }> { - const res = await callHostTransport('filesystem_get_directory_contents', { path: dirPath }, hostOverride) - if (!res.ok) return { ok: false, entries: [], error: res.error || 'DIRECTORY_READ_FAILED' } - const data = res.data - const rawList: unknown[] | null = Array.isArray(data) ? data : Array.isArray(data?.files) ? data.files : null - if (!rawList) return { ok: false, entries: [], error: 'INVALID_DIRECTORY_PAYLOAD' } - - const limit = Math.max(1, Math.floor(options.limit ?? 1000)) - const nowSec = Math.floor(Date.now() / 1000) - const entries: RealIndexedFileEntry[] = [] - const seen = new Set() - for (const item of rawList) { - if (entries.length >= limit) break - let entry: RealIndexedFileEntry | null = null - if (typeof item === 'string') { - const itemPath = item.trim() - if (!itemPath) continue - const name = itemPath.split(/[\\/]/).pop() || itemPath - const sz = options.withSizes ? await getRealFileSize(itemPath, hostOverride) : 0 - entry = normalizeIndexedFileEntry({ - name, - path: itemPath, - isDir: sz === 0 && !name.includes('.'), - size: sz, - mtime: nowSec - }) - } else if (item && typeof item === 'object' && typeof (item as DynamicBridge).name === 'string') { - const raw = item as DynamicBridge - const rawName = raw.name.trim() - if (!rawName || rawName === '.' || rawName === '..') continue - // 只接受文件名,或确实位于该目录下的完整路径,拒绝越界路径 - const fullPath = /[\\/]/.test(rawName) ? rawName : joinChildPath(dirPath, rawName) - if (!isDirectChildPath(dirPath, fullPath)) continue - const isDir = Boolean(raw.isDirectory ?? raw.isDir ?? raw.is_dir) - const parsedMtime = Date.parse(String(raw.lastModified || '')) - entry = normalizeIndexedFileEntry({ - name: fullPath.split(/[\\/]/).pop() || rawName, - path: fullPath, - isDir, - size: isDir ? 0 : Math.max(0, Number(raw.size) || 0), - mtime: Number.isFinite(parsedMtime) ? parsedMtime : nowSec - }) - } - if (!entry || seen.has(entry.path)) continue - seen.add(entry.path) - entries.push(entry) - } - return { ok: true, entries } -} - -/** - * 读取真实目录下的条目路径(真实宿主中优先走 dir: 扫描:一级子目录 + 全树 Top-N 大文件),并返回失败原因。 - * 目录不存在、为空或无权限时返回空列表与错误码,绝不用全盘关键词搜索结果冒充目录内容。 - */ -export async function listRealDirectoryContentsResult( - dirPath: string, - hostOverride?: DynamicBridge -): Promise { - if (!dirPath || !dirPath.trim()) return { entries: [], error: 'EMPTY_DIRECTORY_PATH' } - const targetDir = dirPath.trim() - - if (!hostOverride && isRealElectronHost()) { - const tree = await scanRealDirectoryTree(targetDir, 60) - const paths: string[] = [] - for (const s of tree.subdirs) { - if (s.path) paths.push(s.path) - } - for (const f of tree.files) { - if (f.path) paths.push(f.path) - } - if (paths.length > 0) return { entries: Array.from(new Set(paths)) } - } - - const listing = await listDirectoryViaFilesystem(targetDir, hostOverride) - if (!listing.ok) return { entries: [], error: listing.error } - if (listing.entries.length === 0) return { entries: [], error: DIRECTORY_EMPTY_OR_UNREADABLE } - return { entries: listing.entries.map(e => e.path) } -} - -/** - * 读取真实目录下的条目路径(保持旧签名:失败时返回空数组,需要失败原因请用 listRealDirectoryContentsResult) - */ -export async function listRealDirectoryContents( - dirPath: string, - hostOverride?: DynamicBridge -): Promise { - return (await listRealDirectoryContentsResult(dirPath, hostOverride)).entries -} - -/** - * 只列出目录的直接子项(子目录 + 直接位于该目录下的文件),用于文件夹预览、按目录改名等场景。 - * dir: 扫描结果中只保留 subdirs 与父目录等于 dirPath 的文件;扫描达到上限时 partial=true,由插件如实提示「仅显示部分」。 - */ -export async function listDirectChildren( - dirPath: string, - hostOverride?: DynamicBridge -): Promise { - if (!dirPath || !dirPath.trim()) return { entries: [], partial: false, error: 'EMPTY_DIRECTORY_PATH' } - const targetDir = dirPath.trim() - const scanLimit = 200 - const entries: RealIndexedFileEntry[] = [] - const seen = new Set() - const push = (entry: RealIndexedFileEntry) => { - const key = comparablePath(entry.path) - if (!entry.path || seen.has(key)) return - seen.add(key) - entries.push(entry) - } - - const { scan: tree, error } = await scanDirectoryTreeWithError(targetDir, { maxFiles: scanLimit, hostOverride }) - for (const s of tree.subdirs) { - if (!s.path || !isDirectChildPath(targetDir, s.path)) continue - push( - normalizeIndexedFileEntry({ - name: s.name || s.path.split(/[\\/]/).pop(), - path: s.path, - isDir: true, - size: s.totalBytes, - mtime: s.mtime - }) - ) - } - let directFileCount = 0 - for (const f of tree.files) { - if (!isDirectChildPath(targetDir, f.path)) continue - directFileCount++ - push(f) - } - // 宿主 total_matches 是全树文件数、subdirs[].file_count 是各子目录全树文件数,差值即直接子文件数; - // 拿到的直接子文件少于它就说明被 Top-N 截断了。计数不可用时按是否达到扫描上限判断 - const expectedDirectFiles = tree.totalFiles - tree.subdirs.reduce((sum, d) => sum + (Number(d.fileCount) || 0), 0) - const partial = - Number.isFinite(expectedDirectFiles) && expectedDirectFiles >= 0 - ? directFileCount < expectedDirectFiles - : tree.files.length >= scanLimit - if (entries.length > 0) { - return { entries, partial } - } - - if (tree.files.length > 0) { - // dir: 扫描只返回了深层文件(直接子文件被 Top-N 截掉),如实标注部分结果 - return { entries: [], partial: true, error: DIRECTORY_EMPTY_OR_UNREADABLE } - } - return { entries: [], partial: false, error: error || DIRECTORY_EMPTY_OR_UNREADABLE } -} - -/** - * 获取真实文件字节大小(优先用扫描结果里的大小,再走 filesystem_get_file_size);读不到时返回 0 - */ -export async function getRealFileSize( - filePath: string, - hostOverride?: DynamicBridge -): Promise { - if (!filePath) return 0 - if (!hostOverride && realFileSizeCache.has(filePath)) { - const cached = realFileSizeCache.get(filePath)! - if (cached > 0) return cached - } - const res = await callHostTransport('filesystem_get_file_size', { path: filePath }, hostOverride) - // 客户端返回 { success, size }(目录时 size 为 -1),旧的测试替身直接返回数字 - const size = typeof res.data === 'number' ? res.data : res.data?.size - if (res.ok && typeof size === 'number' && Number.isFinite(size) && size >= 0) { - realFileSizeCache.set(filePath, size) - return size - } - return 0 -} - -/** - * 在访达 / 资源管理器中定位并高亮文件或目录。 - * 定位失败直接返回 false,不能改用“打开”:对可执行文件那等于运行它。 - */ -export async function showRealItemInFolder( - fullPath: string, - hostOverride?: DynamicBridge -): Promise { - if (!fullPath) return false - const res = await callHostTransport('shell_show_item_in_folder', { fullPath }, hostOverride) - return res.ok -} - -/** - * 使用系统默认程序打开文件或目录 - */ -export async function openRealPath( - fullPath: string, - hostOverride?: DynamicBridge -): Promise { - if (!fullPath) return false - const res = await callHostTransport('shell_open_path', { fullPath }, hostOverride) - return res.ok -} - -/** - * 将真实文件或目录移入系统回收站(安全可恢复删除) - */ -export async function trashRealItem( - fullPath: string, - hostOverride?: DynamicBridge -): Promise<{ ok: boolean; error?: string; errorCode?: string; errorDetails?: Record }> { - if (!fullPath) return { ok: false, error: ipcStrings().pathEmpty } - const res = await callHostTransport('shell_trash_item', { fullPath }, hostOverride) - return { - ok: res.ok, - error: res.error, - ...(!res.ok && res.errorCode ? { errorCode: res.errorCode } : {}), - ...(!res.ok && res.errorDetails ? { errorDetails: res.errorDetails } : {}) - } -} - -export interface NativeInvocationResult { - ok: boolean - code: number - message: string - data?: T - error?: string - errorCode?: string - errorDetails?: Record -} - -export interface DllCapabilityResponse { - ok: boolean - code: number - data: T | null - message?: string - error?: string - errorCode?: string - errorDetails?: Record - pluginName: string - method: string - fromFallback?: boolean -} - -/** 声明式能力菜单项及其调用回执,供相同宿主协议的插件共用。 */ -export interface CapabilityActionItem { - id: string - title: string - subtitle: string - tag: string - method: string - params: Record -} - -export type PluginInvocationResult = Pick< - DllCapabilityResponse, 'ok' | 'pluginName' | 'method' | 'error' | 'errorCode' | 'errorDetails' | 'fromFallback' -> & { data?: unknown } - -/** 多个原生能力插件共用的参数边界校验;保护目标由各插件按自身业务提供。 */ -export function validateNativeCapabilityPayload( - method: string, - params: unknown, - forbiddenPattern: RegExp, - forbiddenReason: string -): { valid: boolean; error?: string } { - const s = ipcStrings() - if (typeof method !== 'string' || method.trim().length === 0) { - return { valid: false, error: s.invalidMethodEmpty } - } - if (method.length > 128 || !/^[A-Za-z0-9_]+$/.test(method.trim())) { - return { valid: false, error: s.invalidMethodFormat } - } - if (params === null || params === undefined || typeof params !== 'object' || Array.isArray(params)) { - return { valid: false, error: s.invalidParamsObject } - } - - const record = params as Record - for (const [key, val] of Object.entries(record)) { - if (typeof val === 'string') { - if (val.length > 4096) { - return { valid: false, error: s.paramTooLong(key) } - } - if (forbiddenPattern.test(val)) { - return { valid: false, error: `SECURITY_INTERCEPTED: ${forbiddenReason}` } - } - } else if (typeof val === 'number') { - if (!Number.isFinite(val) || val < -1000 || val > 100_000_000) { - return { valid: false, error: s.paramOutOfRange(key) } - } - } - } - - return { valid: true } -} - -export async function invokeDllPluginCapability( - pluginName: string, - method: string, - params: Record = {}, - hostBridge?: DynamicBridge, - offlineFallback?: () => T | Promise -): Promise> { - const s = ipcStrings() - if (!method || typeof method !== 'string' || method.trim().length === 0) { - return { - ok: false, - code: -1, - data: null, - message: s.methodParamEmpty, - error: s.invalidMethodType, - pluginName, - method: String(method || '') - } - } - - const trimmedMethod = method.trim() - - const unwrapDllRawPayload = (raw: unknown, unwrapDataProperty: boolean): DllCapabilityResponse => { - let parsed: DynamicBridge = raw - if (typeof raw === 'string') { - try { - parsed = JSON.parse(raw) - } catch { - throw new Error(s.malformedDllResponse) - } - } - if (parsed && typeof parsed === 'object') { - if ('error' in parsed && parsed.error !== undefined && parsed.error !== null && parsed.error !== '') { - const errMsg = `DLL_ERROR: ${String(parsed.error)}` - return { - ok: false, - code: typeof parsed.code === 'number' ? parsed.code : -1, - data: null, - message: errMsg, - error: errMsg, - ...extractIpcErrorMeta(parsed), - ...extractIpcErrorMeta(parsed.error), - pluginName, - method: trimmedMethod, - fromFallback: false - } - } - if ('ok' in parsed && parsed.ok === false) { - const errMsg = `DLL_ERROR: ${String(parsed.error || parsed.message || s.unknownDllError)}` - return { - ok: false, - code: typeof parsed.code === 'number' ? parsed.code : -1, - data: null, - message: errMsg, - error: errMsg, - ...extractIpcErrorMeta(parsed), - ...extractIpcErrorMeta(parsed.error), - pluginName, - method: trimmedMethod, - fromFallback: false - } - } - const dataPayload = unwrapDataProperty && 'data' in parsed && parsed.data !== undefined ? parsed.data : parsed - return { - ok: true, - code: typeof parsed.code === 'number' ? parsed.code : 0, - data: dataPayload as T, - message: typeof parsed.message === 'string' ? parsed.message : undefined, - pluginName, - method: trimmedMethod, - fromFallback: false - } - } - return { - ok: true, - code: 0, - data: (parsed ?? null) as T, - pluginName, - method: trimmedMethod, - fromFallback: false - } - } - - const wrapCaughtDllError = (err: unknown): DllCapabilityResponse => { - const message = err instanceof Error ? err.message : String(err) - if (message.startsWith('MALFORMED_DLL_RESPONSE:')) { - throw err - } - const errMsg = `NATIVE_CALL_FAILED: ${message}` - return { - ok: false, - code: -1, - data: null, - message: errMsg, - error: errMsg, - ...extractIpcErrorMeta(err), - pluginName, - method: trimmedMethod, - fromFallback: false - } - } - - if (hostBridge && typeof hostBridge.invokeNative === 'function') { - try { - const raw = await hostBridge.invokeNative(pluginName, trimmedMethod, params) - return unwrapDllRawPayload(raw, true) - } catch (err: unknown) { - return wrapCaughtDllError(err) - } - } - - const runtimeHost = (hostBridge ?? (globalThis as Record).ztools) as - | { dllplugin?: { call?: (plugin: string, fn: string, payload: unknown) => Promise | unknown } } - | undefined - - const callFn = runtimeHost?.dllplugin?.call - if (typeof callFn === 'function') { - try { - const raw = await callFn.call(runtimeHost?.dllplugin, pluginName, trimmedMethod, params) - return unwrapDllRawPayload(raw, false) - } catch (err: unknown) { - return wrapCaughtDllError(err) - } - } - - const ipcRes = await callHostTransport( - 'dllplugin_call', - { - plugin: pluginName, - func: trimmedMethod, - params - }, - hostBridge - ) - - if (ipcRes.ok && ipcRes.data !== undefined && ipcRes.data !== null) { - return unwrapDllRawPayload(ipcRes.data, false) - } - - const isExplicitTransportFailure = - typeof ipcRes.error === 'string' && - ipcRes.error.length > 0 && - ipcRes.error !== 'NO_WINDOW_ENV' && - !ipcRes.error.startsWith('METHOD_NOT_AVAILABLE:') - - if ( - isRealElectronHost(hostBridge) || - isRealElectronHost() || - Boolean((hostBridge as DynamicBridge)?.__isRealHost) || - isExplicitTransportFailure - ) { - const errMsg = - ipcRes.error || s.hostIpcFailed(pluginName, trimmedMethod) - return { - ok: false, - code: -1, - data: null, - message: errMsg, - error: errMsg, - ...(ipcRes.errorCode ? { errorCode: ipcRes.errorCode } : {}), - ...(ipcRes.errorDetails ? { errorDetails: ipcRes.errorDetails } : {}), - pluginName, - method: trimmedMethod, - fromFallback: false - } - } - - if (typeof offlineFallback === 'function') { - const fallbackData = await offlineFallback() - return { - ok: true, - code: 0, - data: fallbackData, - pluginName, - method: trimmedMethod, - fromFallback: true - } - } - - const unavailableMsg = s.hostUnavailable(pluginName, trimmedMethod) - return { - ok: false, - code: -1, - data: null, - message: unavailableMsg, - error: unavailableMsg, - ...(ipcRes.errorCode ? { errorCode: ipcRes.errorCode } : {}), - ...(ipcRes.errorDetails ? { errorDetails: ipcRes.errorDetails } : {}), - pluginName, - method: trimmedMethod, - fromFallback: true - } -} - -export function formatBytes(bytes: number, decimals = 1): string { - const num = Number(bytes) - if (!Number.isFinite(num) || num <= 0) return '0 B' - if (num < 1024) return `${Math.round(num)} B` - const units = ['B', 'KB', 'MB', 'GB', 'TB'] - let val = num - let idx = 0 - while (val >= 1024 && idx < units.length - 1) { - val /= 1024 - idx += 1 - } - const safeDecimals = Math.max(0, Math.floor(decimals)) - return `${val >= 100 ? val.toFixed(0) : val.toFixed(safeDecimals)} ${units[idx]}` -} - -export function joinWinPath(...segments: string[]): string { - return segments - .filter(s => typeof s === 'string' && s.trim().length > 0) - .map((s, i) => (i === 0 ? s.replace(/[\\/]+$/, '') : s.replace(/^[\\/]+|[\\/]+$/g, ''))) - .join('\\') -} - -export interface RealEnvPaths { - home: string - userProfile: string - appData: string - localAppData: string - temp: string - downloads: string - documents: string - desktop: string - pictures: string - videos: string - music: string -} - -export async function getRealEnvPaths(hostOverride?: DynamicBridge): Promise { - const [homeRaw, appData, downloads, documents, desktop, pictures, videos, music] = await Promise.all([ - getRealSystemPath('home', hostOverride), - getRealSystemPath('appData', hostOverride), - getRealSystemPath('downloads', hostOverride), - getRealSystemPath('documents', hostOverride), - getRealSystemPath('desktop', hostOverride), - getRealSystemPath('pictures', hostOverride), - getRealSystemPath('videos', hostOverride), - getRealSystemPath('music', hostOverride) - ]) - const home = homeRaw || 'C:\\Users\\Default' - const isPosix = home.startsWith('/') - const tempRes = hostOverride ? await getRealSystemPath('temp', hostOverride) : '' - if (isPosix) { - return { - home, - userProfile: home, - appData: appData || `${home}/Library/Application Support`, - localAppData: `${home}/Library/Application Support`, - temp: tempRes || '/tmp', - downloads: downloads || `${home}/Downloads`, - documents: documents || `${home}/Documents`, - desktop: desktop || `${home}/Desktop`, - pictures: pictures || `${home}/Pictures`, - videos: videos || `${home}/Videos`, - music: music || `${home}/Music` - } - } - return { - home, - userProfile: home, - appData: appData || `${home}\\AppData\\Roaming`, - localAppData: `${home}\\AppData\\Local`, - temp: tempRes || `${home}\\AppData\\Local\\Temp`, - downloads: downloads || `${home}\\Downloads`, - documents: documents || `${home}\\Documents`, - desktop: desktop || `${home}\\Desktop`, - pictures: pictures || `${home}\\Pictures`, - videos: videos || `${home}\\Videos`, - music: music || `${home}\\Music` - } -} - -export const resolveRealSpecialPaths = getRealEnvPaths - -export async function readRealDirectory( - dirPath: string, - hostOverride?: DynamicBridge -): Promise { - if (!dirPath) return [] - const tree = await scanRealDirectoryTree(dirPath, { maxFiles: 120, hostOverride }) - const entries: RealIndexedFileEntry[] = [] - for (const s of tree.subdirs) { - entries.push( - normalizeIndexedFileEntry({ - name: s.name, - path: s.path, - isDir: true, - isDirectory: true, - size: s.totalBytes, - mtime: s.mtime - }) - ) - } - for (const f of tree.files) { - entries.push(f) - } - // scanRealDirectoryTree 已在 dir: 扫描无结果时退回一级目录读取;仍为空即目录不存在 / 为空 / 无权限,如实返回空列表 - return entries -} - -export async function moveRealFilesToTrash( - paths: string[], - hostOverride?: DynamicBridge -): Promise<{ - ok: boolean - trashedCount: number - deletedCount: number - failedPaths: string[] - error?: string -}> { - let deletedCount = 0 - const failedPaths: string[] = [] - let lastError: string | undefined - for (const p of paths) { - if (!p) continue - const res = await trashRealItem(p, hostOverride) - if (res.ok) { - deletedCount += 1 - } else { - failedPaths.push(p) - if (res.error) lastError = res.error - } - } - return { - ok: deletedCount > 0 || paths.length === 0, - trashedCount: deletedCount, - deletedCount, - failedPaths, - error: lastError - } -} - -const CAPABILITY_TO_PLUGIN_MAP: Record = { - 'mover.relocateWithJunction': { plugin: 'MoverPlugin', func: 'relocateWithJunction' }, - 'mover.scanCandidates': { plugin: 'MoverPlugin', func: 'scanCandidates' }, - 'recovery.restoreFile': { plugin: 'DataRecoveryPlugin', func: 'restoreFile' }, - 'recovery.scanDeletedFiles': { plugin: 'DataRecoveryPlugin', func: 'scanDeletedFiles' }, - 'shredder.secureWipeFile': { plugin: 'ShredderPlugin', func: 'secureWipeFile' }, - 'shredder.scanCandidates': { plugin: 'ShredderPlugin', func: 'scanCandidates' }, - 'backup.createSnapshotArchive': { plugin: 'SystemBackupPlugin', func: 'createSnapshotArchive' }, - 'backup.restoreSnapshotArchive': { plugin: 'SystemBackupPlugin', func: 'restoreSnapshotArchive' }, - 'backup.scanSnapshots': { plugin: 'SystemBackupPlugin', func: 'scanSnapshots' }, - 'sqlite.execute': { plugin: 'SqlitePlugin', func: 'execute' }, - 'sqlite.query': { plugin: 'SqlitePlugin', func: 'executeQuery' }, - 'sqlite.inspectWorkspace': { plugin: 'SqlitePlugin', func: 'inspectWorkspace' } -} - -export async function invokeHostCapability( - capability: string, - params: Record = {}, - hostOverride?: DynamicBridge -): Promise> { - const normalizedMethod = capability.replace(/\./g, '_') - - // 若测试显式注入了对应 normalizedMethod 的 mock 函数,优先调用测试桩 - if (hostOverride && typeof hostOverride[normalizedMethod] === 'function') { - const mockRes = await callHostTransport(normalizedMethod, params, hostOverride) - return { - ok: mockRes.ok, - code: mockRes.ok ? 0 : -1, - message: mockRes.ok ? 'OK' : mockRes.error || ipcStrings().callFailed, - data: mockRes.data, - error: mockRes.error, - ...(!mockRes.ok && mockRes.errorCode ? { errorCode: mockRes.errorCode } : {}), - ...(!mockRes.ok && mockRes.errorDetails ? { errorDetails: mockRes.errorDetails } : {}) - } - } - - if (capability === 'system.info') { - const drives = await probeRealDiskDrives(['C', 'D', 'E', 'F'], hostOverride) - return { - ok: true, - code: 0, - message: 'OK', - data: { - storage: drives.map(d => ({ - mount: d.drive, - fs: d.drive, - size: d.totalBytes, - total: d.totalBytes, - used: d.usedBytes, - available: d.availableBytes, - free: d.availableBytes, - percent: d.usagePercent - })) - } as unknown as T - } - } - if (capability === 'filesystem.deleteItem') { - const targetPath = String(params.path || params.fullPath || '') - const tr = await trashRealItem(targetPath, hostOverride) - const s = ipcStrings() - return { - ok: tr.ok, - code: tr.ok ? 0 : -1, - message: tr.ok ? s.movedToTrash : tr.error || s.deleteFailed, - error: tr.error, - ...(!tr.ok && tr.errorCode ? { errorCode: tr.errorCode } : {}), - ...(!tr.ok && tr.errorDetails ? { errorDetails: tr.errorDetails } : {}) - } - } - if (capability === 'system.showItemInFolder') { - const targetPath = String(params.path || params.fullPath || '') - const s = ipcStrings() - if (!targetPath) { - return { ok: false, code: -1, message: s.revealFailed } - } - const res = await callHostTransport('shell_show_item_in_folder', { fullPath: targetPath }, hostOverride) - return { - ok: res.ok, - code: res.ok ? 0 : -1, - message: res.ok ? s.revealedInFolder : res.error || s.revealFailed, - ...(!res.ok && res.error ? { error: res.error } : {}), - ...(!res.ok && res.errorCode ? { errorCode: res.errorCode } : {}), - ...(!res.ok && res.errorDetails ? { errorDetails: res.errorDetails } : {}) - } - } - if (capability === 'filesystem.openItem' || capability === 'system.openUrl') { - const target = String(params.path || params.url || params.fullPath || '') - const method = capability === 'system.openUrl' ? 'shell_open_external' : 'shell_open_path' - const res = await callHostTransport( - method, - capability === 'system.openUrl' ? { url: target } : { fullPath: target }, - hostOverride - ) - const s = ipcStrings() - return { - ok: res.ok, - code: res.ok ? 0 : -1, - message: res.ok ? s.opened : res.error || s.openFailed, - data: res.data, - error: res.error, - ...(!res.ok && res.errorCode ? { errorCode: res.errorCode } : {}), - ...(!res.ok && res.errorDetails ? { errorDetails: res.errorDetails } : {}) - } - } - - const pluginMapping = CAPABILITY_TO_PLUGIN_MAP[capability] - if (pluginMapping) { - const dllRes = await invokePluginService( - pluginMapping.plugin, - pluginMapping.func, - params, - hostOverride - ) - if (dllRes.ok) return dllRes - if (hostOverride) { - const fallbackMock = await callHostTransport(normalizedMethod, params, hostOverride) - if (fallbackMock.ok) { - return { - ok: true, - code: 0, - message: 'OK', - data: fallbackMock.data - } - } - } - return dllRes - } - - const res = await callHostTransport(normalizedMethod, params, hostOverride) - return { - ok: res.ok, - code: res.ok ? 0 : -1, - message: res.ok ? 'OK' : res.error || ipcStrings().callFailed, - data: res.data, - error: res.error, - ...(!res.ok && res.errorCode ? { errorCode: res.errorCode } : {}), - ...(!res.ok && res.errorDetails ? { errorDetails: res.errorDetails } : {}) - } -} - -export async function invokePluginService( - pluginName: string, - action: string, - params: Record = {}, - hostOverride?: DynamicBridge -): Promise> { - const s = ipcStrings() - // 1. 若测试注入了专门拦截 plugin_invoke 的 mock,支持调用 - if (hostOverride && typeof hostOverride.plugin_invoke === 'function') { - const mockRes = await callHostTransport( - 'plugin_invoke', - { plugin: pluginName, action, params }, - hostOverride - ) - return { - ok: mockRes.ok, - code: mockRes.ok ? 0 : -1, - message: mockRes.ok ? 'OK' : mockRes.error || s.pluginCallNotReady, - data: mockRes.data, - error: mockRes.error, - ...(!mockRes.ok && mockRes.errorCode ? { errorCode: mockRes.errorCode } : {}), - ...(!mockRes.ok && mockRes.errorDetails ? { errorDetails: mockRes.errorDetails } : {}) - } - } - - // 2. 优先走真实 Electron IPC 的 dllplugin_call 通道 - const dllRes = await callHostTransport( - 'dllplugin_call', - { plugin: pluginName, func: action, params }, - hostOverride - ) - if (dllRes.ok) { - const inner = dllRes.data - if (inner && typeof inner === 'object' && typeof inner.error === 'string' && inner.error.length > 0 && inner.ok !== true) { - return { - ok: false, - code: -1, - message: inner.error, - error: inner.error, - ...extractIpcErrorMeta(inner) - } - } - return { - ok: true, - code: 0, - message: 'OK', - data: inner as T - } - } - - // 3. 兼容单元测试中通过 transport.call('plugin_invoke') 注入的测试桩 - if (hostOverride) { - const legacyRes = await callHostTransport( - 'plugin_invoke', - { plugin: pluginName, action, params }, - hostOverride - ) - if (legacyRes.ok) { - return { - ok: true, - code: 0, - message: 'OK', - data: legacyRes.data - } - } - } - - // 4. 兼容旧版 globalThis.ztools.dllplugin.call - const g = globalThis as DynamicBridge - if (!hostOverride && typeof g?.ztools?.dllplugin?.call === 'function') { - try { - const raw = await g.ztools.dllplugin.call(pluginName, action, params) - if (raw && typeof raw === 'object' && raw.ok === false) { - return { - ok: false, - code: -1, - message: String(raw.error || s.callFailed), - error: String(raw.error || s.callFailed), - ...extractIpcErrorMeta(raw), - ...extractIpcErrorMeta(raw.error) - } - } - const data = raw && typeof raw === 'object' && 'data' in raw ? raw.data : raw - return { ok: true, code: 0, message: 'OK', data: data as T } - } catch (err: DynamicBridge) { - return { - ok: false, - code: -1, - message: err instanceof Error ? err.message : String(err), - error: err instanceof Error ? err.message : String(err), - ...extractIpcErrorMeta(err) - } - } - } - - return { - ok: false, - code: -1, - message: dllRes.error || s.pluginCallNotReady, - error: dllRes.error || s.pluginCallNotReady, - ...(dllRes.errorCode ? { errorCode: dllRes.errorCode } : {}), - ...(dllRes.errorDetails ? { errorDetails: dllRes.errorDetails } : {}) - } -} - -const SHA256_K = new Uint32Array([ - 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, - 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, - 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, - 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, - 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, - 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, - 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, - 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 -]) - -function rotr32(x: number, n: number): number { - return (x >>> n) | (x << (32 - n)) -} - -/** - * 标准 FIPS 180-4 SHA-256 真实字节摘要算法(返回 64 位小写 Hex) - */ -export function computeRealSha256Hex(input: string | Uint8Array): string { - const bytes = - typeof input === 'string' ? new TextEncoder().encode(input) : new Uint8Array(input || []) - const bitLen = bytes.length * 8 - const padLen = ((bytes.length + 9 + 63) & ~63) - const buf = new Uint8Array(padLen) - buf.set(bytes, 0) - buf[bytes.length] = 0x80 - const view = new DataView(buf.buffer) - view.setUint32(padLen - 8, Math.floor(bitLen / 0x100000000), false) - view.setUint32(padLen - 4, bitLen >>> 0, false) - - let h0 = 0x6a09e667 - let h1 = 0xbb67ae85 - let h2 = 0x3c6ef372 - let h3 = 0xa54ff53a - let h4 = 0x510e527f - let h5 = 0x9b05688c - let h6 = 0x1f83d9ab - let h7 = 0x5be0cd19 - - const w = new Uint32Array(64) - for (let offset = 0; offset < padLen; offset += 64) { - for (let i = 0; i < 16; i++) { - w[i] = view.getUint32(offset + i * 4, false) - } - for (let i = 16; i < 64; i++) { - const s0 = rotr32(w[i - 15], 7) ^ rotr32(w[i - 15], 18) ^ (w[i - 15] >>> 3) - const s1 = rotr32(w[i - 2], 17) ^ rotr32(w[i - 2], 19) ^ (w[i - 2] >>> 10) - w[i] = (w[i - 16] + s0 + w[i - 7] + s1) >>> 0 - } - - let a = h0 - let b = h1 - let c = h2 - let d = h3 - let e = h4 - let f = h5 - let g = h6 - let h = h7 - - for (let i = 0; i < 64; i++) { - const S1 = rotr32(e, 6) ^ rotr32(e, 11) ^ rotr32(e, 25) - const ch = (e & f) ^ (~e & g) - const temp1 = (h + S1 + ch + SHA256_K[i] + w[i]) >>> 0 - const S0 = rotr32(a, 2) ^ rotr32(a, 13) ^ rotr32(a, 22) - const maj = (a & b) ^ (a & c) ^ (b & c) - const temp2 = (S0 + maj) >>> 0 - - h = g - g = f - f = e - e = (d + temp1) >>> 0 - d = c - c = b - b = a - a = (temp1 + temp2) >>> 0 - } - - h0 = (h0 + a) >>> 0 - h1 = (h1 + b) >>> 0 - h2 = (h2 + c) >>> 0 - h3 = (h3 + d) >>> 0 - h4 = (h4 + e) >>> 0 - h5 = (h5 + f) >>> 0 - h6 = (h6 + g) >>> 0 - h7 = (h7 + h) >>> 0 - } - - return [h0, h1, h2, h3, h4, h5, h6, h7] - .map(v => (v >>> 0).toString(16).padStart(8, '0')) - .join('') -} - -/** - * 读取本地文件真实字节并计算标准 SHA-256:宿主 filesearch_sha256(只接受 path 字段)优先,Windows 上再试 FileComparePlugin。 - * 都拿不到时返回空字符串,由调用方提示失败;不再把文件按 UTF-8 文本读出来再算(二进制文件会算出错误的值)。 - */ -export async function computeRealFileSha256( - filePath: string, - hostOverride?: DynamicBridge -): Promise { - if (!filePath || !filePath.trim()) return '' - const target = filePath.trim() - - const shaRes = await callHostTransport('filesearch_sha256', { fullPath: target }, hostOverride) - if (shaRes.ok && shaRes.data) { - const hash = typeof shaRes.data === 'string' ? shaRes.data : String(shaRes.data?.sha256 || shaRes.data?.hash || '') - if (/^[0-9a-f]{64}$/i.test(hash)) return hash.toLowerCase() - } - - const dllRes = await invokePluginService('FileComparePlugin', 'computeFileSha256', { path: target }, hostOverride) - if (dllRes.ok && dllRes.data) { - const hash = typeof dllRes.data === 'string' ? dllRes.data : String(dllRes.data?.sha256 || dllRes.data?.hash || '') - if (/^[0-9a-f]{64}$/i.test(hash)) return hash.toLowerCase() - } - - return '' -} - -export async function readRealClipboardText(hostOverride?: DynamicBridge): Promise { - const res = await callHostTransport('clipboard_read_text', {}, hostOverride) - if (res.ok && res.data !== undefined && res.data !== null) { - if (typeof res.data === 'string') return res.data - if (typeof res.data?.text === 'string') return res.data.text - } - try { - if (typeof navigator !== 'undefined' && navigator.clipboard?.readText) { - return await navigator.clipboard.readText() - } - } catch { - // ignore - } - return '' -} - -export async function writeRealClipboardText(text: string, hostOverride?: DynamicBridge): Promise { - const payload = { text: String(text || '') } - const res = await callHostTransport('clipboard_copy_text', payload, hostOverride) - if (res.ok) return true - const fallbackRes = await callHostTransport('clipboard_write_text', payload, hostOverride) - if (fallbackRes.ok) return true - try { - if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) { - await navigator.clipboard.writeText(String(text || '')) - return true - } - } catch { - // ignore - } - return false -} - -export async function showRealToast( - title: string, - style: 'success' | 'failure' | 'info' = 'info' -): Promise { - try { - const { showToast, Toast } = await import('@ztools/declarative-ui') - await showToast({ - title, - style: - style === 'success' - ? Toast.Style.Success - : style === 'failure' - ? Toast.Style.Failure - : Toast.Style.Animated - }) - } catch { - // ignore - } -} - diff --git a/extensions/record/src/tool-runtime.ts b/extensions/record/src/tool-runtime.ts new file mode 100644 index 00000000..29670de2 --- /dev/null +++ b/extensions/record/src/tool-runtime.ts @@ -0,0 +1,637 @@ +/** + * 宿主薄原语与基础系统能力传输层(唯一权威公共源文件,纯标准 IPC,零原生 DLL 依赖) + * + * 修改本文件后需同步复制到各使用插件的 src/tool-runtime.ts, + * 构建脚本 build-declarative.mjs 会在编译前校验副本与本文件一字不差。 + */ + +import { getHostTransport } from '@ztools/declarative-ui' + +export type ToolCapabilityStatus = 'ready' | 'needs_provisioning' | 'unsupported' + +export interface ToolCapabilityDescriptor { + readonly primitiveId: string + readonly domain: string + readonly summary: string + readonly ipcMethods: readonly string[] + readonly requiredPermissions: readonly string[] + readonly status: ToolCapabilityStatus + readonly optionalExtensions: readonly string[] +} + +export interface ToolRuntimeCapabilitiesSnapshot { + readonly contractVersion: number + readonly platform: 'windows' | 'macos' | 'other' + readonly domains: readonly string[] + readonly capabilities: readonly ToolCapabilityDescriptor[] +} + +export interface ToolRuntimeEnsureResult { + readonly primitiveId: string + readonly status: ToolCapabilityStatus + readonly provisioned: boolean +} + +export interface ToolCapabilitiesEnsureResult { + readonly ok: boolean + readonly status: ToolCapabilityStatus + readonly provisioned: boolean + readonly failedPrimitiveId?: string + readonly error?: string + readonly errorCode?: string + readonly errorDetails?: Record +} + +export interface ToolTaskCancelResult { + readonly taskId: string + readonly cancelled: boolean +} + +export interface ToolPathSlot { + readonly grantId?: string + readonly relativePath?: string + readonly path?: string +} + +export interface ToolProgressEvent { + readonly taskId: string + readonly primitiveId?: string + readonly phase: 'provisioning' | 'running' | 'finalizing' | 'completed' | 'cancelled' | 'failed' + readonly percent?: number + readonly transferredBytes?: number + readonly totalBytes?: number + readonly speedBytesPerSec?: number + readonly stage?: string + readonly errorCode?: string + readonly retryable?: boolean + readonly userAction?: string + readonly message?: string + readonly timestamp?: number +} + +export type MediaTranscodeRunResult = + | { readonly status: 'done'; readonly outputBytes: number; readonly durationMs: number } + | { readonly status: 'cancelled' } + | { + readonly status: 'failed' + readonly error?: string + readonly errorCode?: string + readonly errorDetails?: Record + } + +export interface HostTransportResult { + ok: boolean + data?: T + error?: string + errorCode?: string + errorDetails?: Record +} + +export interface HostCallOptions { + timeoutMs?: number +} + +type TransportMethodFn = (req: { messageId: string; params: Record; timeoutMs?: number }) => Promise + +interface WindowHostBridge { + __ztoolsElectron?: { + transport?: { + methods?: Record + } + } + ztools?: { + transport?: { + methods?: Record + call?: (method: string, params: Record, options?: { timeoutMs?: number }) => Promise + } + events?: { + subscribe?: (event: string) => Promise | void + on?: (event: string, cb: (payload: unknown) => void) => (() => void) | void + off?: (event: string, cb: (payload: unknown) => void) => void + } + } +} + +interface HostOverrideLike { + transport?: { + call?: (method: string, params: Record, options?: { timeoutMs?: number }) => Promise + } + [method: string]: unknown +} + +let reqSeq = 1 + +export function nextMessageId(prefix = 'tool'): string { + reqSeq = (reqSeq + 1) % 1_000_000 + return `${prefix}_${Date.now()}_${reqSeq}` +} + +export function asRecord(value: unknown): Record | null { + return value && typeof value === 'object' && !Array.isArray(value) + ? (value as Record) + : null +} + +function extractErrorMeta(errObj: unknown): { + errorCode?: string + errorDetails?: Record +} { + const rec = asRecord(errObj) + if (!rec) return {} + const errorCode = + typeof rec.errorCode === 'string' && rec.errorCode.trim() + ? rec.errorCode.trim() + : typeof rec.code === 'string' && rec.code.trim() + ? rec.code.trim() + : undefined + const rawDetails = asRecord(rec.errorDetails) ?? asRecord(rec.details) ?? undefined + return { + ...(errorCode ? { errorCode } : {}), + ...(rawDetails ? { errorDetails: rawDetails } : {}) + } +} + +function toTransportError(err: unknown): HostTransportResult { + return { + ok: false, + error: err instanceof Error ? err.message : String(err), + ...extractErrorMeta(err) + } +} + +function buildFailureResult(rec: Record, fallbackMsg: string): HostTransportResult { + const errObj = asRecord(rec.error) + const errMsg = errObj + ? String(errObj.message || errObj.code || JSON.stringify(errObj)) + : String(rec.error || rec.message || fallbackMsg) + return { ok: false, error: errMsg, ...extractErrorMeta(rec), ...extractErrorMeta(errObj) } +} + +function unwrapTransportResponse(raw: unknown): HostTransportResult { + if (raw === null || raw === undefined) { + return { ok: false, error: 'EMPTY_IPC_RESPONSE', errorCode: 'EMPTY_IPC_RESPONSE' } + } + if (typeof raw !== 'object') { + return { ok: true, data: raw as T } + } + const outer = asRecord(raw) + if (!outer) { + return { ok: true, data: raw as T } + } + if (outer.success === false || outer.ok === false) { + return buildFailureResult(outer, 'IPC_CALL_FAILED') + } + + const firstLayer = 'data' in outer && outer.data !== undefined ? outer.data : outer + const inner = asRecord(firstLayer) + if (inner) { + if (inner.success === false || inner.ok === false) { + return buildFailureResult(inner, 'IPC_INNER_FAILED') + } + if ('data' in inner && inner.data !== undefined) { + return { ok: true, data: inner.data as T } + } + } + + return { ok: true, data: firstLayer as T } +} + +/** 判断当前是否处于真实的 ZTools Electron 渲染进程宿主环境 */ +export function isRealElectronHost(hostOverride?: unknown): boolean { + if (hostOverride) return true + if (typeof window === 'undefined') return false + const w = window as unknown as WindowHostBridge + return Boolean( + w.__ztoolsElectron?.transport?.methods || + w.ztools?.transport?.call || + w.ztools?.transport?.methods + ) +} + +/** 统一调用宿主 IPC 传输层(优先测试桩,其次 declarative-ui 宿主通道与 preload 通道) */ +export async function callHostTransport( + method: string, + params: Record = {}, + hostOverride?: unknown, + options?: HostCallOptions +): Promise> { + const override = asRecord(hostOverride) as HostOverrideLike | null + if (override) { + const directFn = override[method] + if (typeof directFn === 'function') { + try { + return unwrapTransportResponse(await (directFn as (p: Record) => Promise)(params)) + } catch (err) { + return toTransportError(err) + } + } + if (typeof override.transport?.call === 'function') { + try { + return unwrapTransportResponse(await override.transport.call(method, params, options)) + } catch (err) { + return toTransportError(err) + } + } + return { ok: false, error: `METHOD_NOT_AVAILABLE: ${method}`, errorCode: 'METHOD_NOT_AVAILABLE' } + } + + // 优先走 declarative-ui 运行时注入的带归属令牌通道 + if (typeof getHostTransport === 'function') { + const transport = getHostTransport() + if (transport) { + try { + const callOpts = typeof options?.timeoutMs === 'number' ? { timeoutMs: options.timeoutMs } : undefined + return unwrapTransportResponse(await transport.call(method, params, callOpts)) + } catch (err) { + return toTransportError(err) + } + } + } + + if (typeof window === 'undefined') { + return { ok: false, error: 'NO_WINDOW_ENV', errorCode: 'NO_WINDOW_ENV' } + } + + const w = window as unknown as WindowHostBridge + const methods = w.__ztoolsElectron?.transport?.methods || w.ztools?.transport?.methods + const fn = methods?.[method] + if (typeof fn === 'function') { + try { + const messageId = nextMessageId(method.replace(/[^A-Za-z0-9_]/g, '_').slice(0, 24)) + const payload = { + messageId, + params, + ...(typeof options?.timeoutMs === 'number' ? { timeoutMs: options.timeoutMs } : {}) + } + return unwrapTransportResponse(await fn(payload)) + } catch (err) { + return toTransportError(err) + } + } + + if (typeof w.ztools?.transport?.call === 'function') { + try { + return unwrapTransportResponse(await w.ztools.transport.call(method, params, options)) + } catch (err) { + return toTransportError(err) + } + } + + return { ok: false, error: `METHOD_NOT_AVAILABLE: ${method}`, errorCode: 'METHOD_NOT_AVAILABLE' } +} + +/** 探测宿主薄原语能力快照(tool_runtime_capabilities) */ +export async function queryRuntimeCapabilities( + hostOverride?: unknown +): Promise> { + const res = await callHostTransport('tool_runtime_capabilities', {}, hostOverride) + if (!res.ok) return res as HostTransportResult + const rec = asRecord(res.data) + if (!rec || !Array.isArray(rec.capabilities)) { + return { + ok: false, + error: 'INVALID_CAPABILITIES_SNAPSHOT', + errorCode: 'INVALID_CAPABILITIES_SNAPSHOT' + } + } + const capabilities: ToolCapabilityDescriptor[] = [] + for (const rawCap of rec.capabilities) { + const cap = asRecord(rawCap) + if (!cap || typeof cap.primitiveId !== 'string') continue + const rawStatus = cap.status + const status: ToolCapabilityStatus = + rawStatus === 'ready' || rawStatus === 'needs_provisioning' || rawStatus === 'unsupported' + ? rawStatus + : 'unsupported' + const optionalExtensions = Array.isArray(cap.optionalExtensions) + ? cap.optionalExtensions.filter((e): e is string => typeof e === 'string' && e.trim().length > 0) + : [] + capabilities.push({ + primitiveId: cap.primitiveId, + domain: typeof cap.domain === 'string' ? cap.domain : '', + summary: typeof cap.summary === 'string' ? cap.summary : '', + ipcMethods: Array.isArray(cap.ipcMethods) ? cap.ipcMethods.filter((m): m is string => typeof m === 'string') : [], + requiredPermissions: Array.isArray(cap.requiredPermissions) + ? cap.requiredPermissions.filter((p): p is string => typeof p === 'string') + : [], + status, + optionalExtensions + }) + } + const platform = + rec.platform === 'windows' || rec.platform === 'macos' || rec.platform === 'other' + ? rec.platform + : 'other' + return { + ok: true, + data: { + contractVersion: typeof rec.contractVersion === 'number' ? rec.contractVersion : 1, + platform, + domains: Array.isArray(rec.domains) ? rec.domains.filter((d): d is string => typeof d === 'string') : [], + capabilities + } + } +} + +export function findCapability( + snapshot: ToolRuntimeCapabilitiesSnapshot | null | undefined, + primitiveId: string +): ToolCapabilityDescriptor | null { + if (!snapshot) return null + return snapshot.capabilities.find((c) => c.primitiveId === primitiveId) ?? null +} + +export function hasCapabilityExtension( + snapshot: ToolRuntimeCapabilitiesSnapshot | null | undefined, + primitiveId: string, + extensionName: string +): boolean { + const cap = findCapability(snapshot, primitiveId) + return Boolean(cap && cap.optionalExtensions.includes(extensionName)) +} + +/** 按需拉取并准备指定薄原语运行组件(tool_runtime_ensure) */ +export async function ensureRuntimeCapability( + primitiveId: string, + hostOverride?: unknown +): Promise> { + return callHostTransport('tool_runtime_ensure', { primitiveId }, hostOverride) +} + +/** 顺序按需准备多个薄原语运行组件,任一项未就绪即中止并聚合 provisioned 标记 */ +export async function ensureRuntimeCapabilities( + primitiveIds: readonly string[], + hostOverride?: unknown +): Promise { + let provisionedAny = false + for (const primitiveId of primitiveIds) { + const res = await ensureRuntimeCapability(primitiveId, hostOverride) + if (!res.ok || !res.data || res.data.status !== 'ready') { + return { + ok: false, + status: res.data?.status ?? 'unsupported', + provisioned: provisionedAny, + failedPrimitiveId: primitiveId, + error: res.error, + errorCode: res.errorCode, + errorDetails: res.errorDetails + } + } + if (res.data.provisioned) provisionedAny = true + } + return { ok: true, status: 'ready', provisioned: provisionedAny } +} + +/** 取消正在执行的宿主薄原语任务(tool_task_cancel) */ +export async function cancelRuntimeTask( + taskId: string, + hostOverride?: unknown +): Promise> { + return callHostTransport('tool_task_cancel', { taskId }, hostOverride) +} + +/** 判断错误码是否表示用户主动取消任务 */ +export function isTaskCancelledCode(errorCode?: string): boolean { + const code = (errorCode || '').trim().toUpperCase() + return code === 'TOOL_TASK_CANCELLED' || code === 'CANCELLED' || code === 'OPERATION_CANCELLED' +} + +/** 执行单个媒体转码任务(tool_media_transcode_run),统一处理取消与产物字节数校验 */ +export async function runMediaTranscodeTask( + payload: Record, + hostOverride?: unknown +): Promise { + const res = await callHostTransport('tool_media_transcode_run', payload, hostOverride) + if (!res.ok) { + if (isTaskCancelledCode(res.errorCode)) { + return { status: 'cancelled' } + } + return { + status: 'failed', + error: res.error, + errorCode: res.errorCode, + errorDetails: res.errorDetails + } + } + const rec = asRecord(res.data) + const outputBytes = Number(rec?.outputBytes) + const durationMs = Number(rec?.durationMs) + if (!Number.isFinite(outputBytes) || outputBytes <= 0) { + return { status: 'failed', error: 'EMPTY_OUTPUT', errorCode: 'EMPTY_OUTPUT' } + } + return { + status: 'done', + outputBytes, + durationMs: Number.isFinite(durationMs) && durationMs >= 0 ? durationMs : 0 + } +} + +/** 订阅宿主推送的 tool_runtime_progress 任务进度事件 */ +export function subscribeRuntimeProgress( + handler: (event: ToolProgressEvent) => void +): () => void { + if (typeof window === 'undefined') return () => undefined + const w = window as unknown as WindowHostBridge + const eventsApi = w.ztools?.events + if (!eventsApi || typeof eventsApi.on !== 'function') return () => undefined + + try { + void eventsApi.subscribe?.('tool_runtime_progress') + } catch (err) { + // 某些测试桩或旧渲染层可能未提供 subscribe,继续注册 on 监听 + void err + } + + const listener = (raw: unknown) => { + const outer = asRecord(raw) + if (!outer) return + const inner = asRecord(outer.payload) ?? outer + if (typeof inner.taskId !== 'string' || typeof inner.phase !== 'string') return + handler(inner as unknown as ToolProgressEvent) + } + + const off = eventsApi.on('tool_runtime_progress', listener) + return () => { + if (typeof off === 'function') { + off() + } else if (typeof eventsApi.off === 'function') { + eventsApi.off('tool_runtime_progress', listener) + } + } +} + +/** 订阅旧版宿主 plugin_files_dropped 拖拽回退事件并返回卸载函数 */ +export function subscribeLegacyFileDrop(onDrop: (envelope: unknown) => void): () => void { + if (typeof window === 'undefined') return () => undefined + const w = window as unknown as WindowHostBridge + const eventsApi = w.ztools?.events + if (!eventsApi || typeof eventsApi.on !== 'function') return () => undefined + + const off = eventsApi.on('plugin_files_dropped', onDrop) + return () => { + if (typeof off === 'function') { + off() + } else if (typeof eventsApi.off === 'function') { + eventsApi.off('plugin_files_dropped', onDrop) + } + } +} + +/** 字节数格式化 */ +export function formatBytes(bytes: number): string { + if (!Number.isFinite(bytes) || bytes < 0) return '0 B' + if (bytes < 1024) return `${Math.round(bytes)} B` + const units = ['KB', 'MB', 'GB', 'TB'] + let value = bytes / 1024 + let idx = 0 + while (value >= 1024 && idx < units.length - 1) { + value /= 1024 + idx += 1 + } + return `${value >= 100 ? value.toFixed(0) : value >= 10 ? value.toFixed(1) : value.toFixed(2)} ${units[idx]}` +} + +/** 字节数格式化别名(兼容 archive-manager 等插件既有导出名) */ +export function formatByteCount(bytes: number): string { + return formatBytes(bytes) +} + +/** 获取系统标准目录路径(支持 Windows 与 macOS) */ +export async function getRealSystemPath( + name: 'home' | 'desktop' | 'documents' | 'downloads' | 'music' | 'pictures' | 'videos' | 'temp', + hostOverride?: unknown +): Promise { + const res = await callHostTransport('system_get_path', { name }, hostOverride) + if (res.ok && res.data) { + if (typeof res.data === 'string' && res.data.trim()) return res.data.trim() + const rec = asRecord(res.data) + if (rec && typeof rec.path === 'string' && rec.path.trim()) return rec.path.trim() + } + return '' +} + +/** 读取剪贴板文本 */ +export async function readRealClipboardText(hostOverride?: unknown): Promise { + const res = await callHostTransport('clipboard_read_text', {}, hostOverride) + if (res.ok && res.data !== undefined && res.data !== null) { + if (typeof res.data === 'string') return res.data + const rec = asRecord(res.data) + if (rec && typeof rec.text === 'string') return rec.text + } + return '' +} + +/** 写入剪贴板文本 */ +export async function writeRealClipboardText(text: string, hostOverride?: unknown): Promise { + const res = await callHostTransport('clipboard_copy_text', { text: String(text || '') }, hostOverride) + return res.ok +} + +/** 在系统文件管理器中显示文件 */ +export async function showRealItemInFolder(fullPath: string, hostOverride?: unknown): Promise { + if (!fullPath) return false + const res = await callHostTransport('shell_show_item_in_folder', { fullPath }, hostOverride) + return res.ok +} + +/** 用系统默认应用打开文件或文件夹 */ +export async function openRealPath(fullPath: string, hostOverride?: unknown): Promise { + if (!fullPath) return false + const res = await callHostTransport('shell_open_path', { fullPath }, hostOverride) + return res.ok +} + +/** 将文件或目录移入系统回收站 */ +export async function trashRealItem(fullPath: string, hostOverride?: unknown): Promise<{ ok: boolean; error?: string }> { + if (!fullPath) return { ok: false, error: 'EMPTY_PATH' } + const res = await callHostTransport('shell_trash_item', { fullPath }, hostOverride) + return res.ok ? { ok: true } : { ok: false, error: res.error } +} + +/** 通过 window_show_open_dialog 选择输出目录(兼容 Windows 与 macOS) */ +export async function pickOutputDirectoryDialog( + options: { title: string; defaultPath?: string }, + hostOverride?: unknown +): Promise<{ canceled: boolean; directoryPath?: string; error?: string; errorCode?: string }> { + const params: Record = { + title: options.title, + properties: ['openDirectory', 'createDirectory'] + } + if (options.defaultPath) params.defaultPath = options.defaultPath + const res = await callHostTransport('window_show_open_dialog', params, hostOverride) + if (!res.ok) { + return { canceled: false, error: res.error || 'OPEN_DIALOG_FAILED', errorCode: res.errorCode } + } + const rec = asRecord(res.data) + if (!rec) return { canceled: false, error: 'INVALID_DIALOG_RESULT' } + if (rec.canceled === true) return { canceled: true } + const firstPath = + (Array.isArray(rec.filePaths) && typeof rec.filePaths[0] === 'string' && rec.filePaths[0].trim()) || + (typeof rec.filePath === 'string' && rec.filePath.trim()) || + (typeof rec.folderPath === 'string' && rec.folderPath.trim()) || + '' + if (!firstPath) return { canceled: false, error: 'NO_DIRECTORY_SELECTED' } + return { canceled: false, directoryPath: firstPath } +} + +/** 通用文件/目录选择对话框(支持自定义 properties 与 filters) */ +export async function openDialogSelectPaths( + options: { + title: string + properties: Array<'openFile' | 'openDirectory' | 'multiSelections' | 'createDirectory'> + filters?: Array<{ name: string; extensions: string[] }> + }, + hostOverride?: unknown +): Promise<{ canceled: boolean; paths: string[]; error?: string }> { + const params: Record = { + title: options.title, + properties: options.properties, + ...(options.filters ? { filters: options.filters } : {}) + } + const res = await callHostTransport('window_show_open_dialog', params, hostOverride) + if (!res.ok) return { canceled: false, paths: [], error: res.error || 'OPEN_DIALOG_FAILED' } + const rec = asRecord(res.data) + if (!rec) return { canceled: false, paths: [], error: 'INVALID_DIALOG_RESPONSE' } + if (rec.canceled === true) return { canceled: true, paths: [] } + const paths = Array.isArray(rec.filePaths) + ? rec.filePaths.filter((p): p is string => typeof p === 'string' && p.trim().length > 0).map((p) => p.trim()) + : typeof rec.filePath === 'string' && rec.filePath.trim() + ? [rec.filePath.trim()] + : [] + return { canceled: false, paths } +} + +/** 选择待归档的源文件或目录列表(多选) */ +export async function pickAnySourcesDialog( + options: { title: string; directories?: boolean }, + hostOverride?: unknown +): Promise<{ canceled: boolean; paths: string[]; error?: string }> { + return openDialogSelectPaths( + { + title: options.title, + properties: options.directories ? ['openDirectory', 'multiSelections'] : ['openFile', 'multiSelections'] + }, + hostOverride + ) +} + +/** 保存归档文件对话框(zip / 7z / tar) */ +export async function pickSaveArchiveDialog( + options: { title: string; defaultPath?: string; format: 'zip' | '7z' | 'tar' }, + hostOverride?: unknown +): Promise<{ canceled: boolean; filePath?: string; error?: string }> { + const ext = options.format === '7z' ? '7z' : options.format === 'tar' ? 'tar' : 'zip' + const params: Record = { + title: options.title, + filters: [{ name: `${ext.toUpperCase()} Archive`, extensions: [ext] }] + } + if (options.defaultPath) params.defaultPath = options.defaultPath + const res = await callHostTransport('window_show_save_dialog', params, hostOverride) + if (!res.ok) return { canceled: false, error: res.error || 'SAVE_DIALOG_FAILED' } + const rec = asRecord(res.data) + if (!rec) return { canceled: false, error: 'INVALID_SAVE_DIALOG' } + if (rec.canceled === true) return { canceled: true } + const filePath = typeof rec.filePath === 'string' ? rec.filePath.trim() : '' + if (!filePath) return { canceled: true } + return { canceled: false, filePath } +} diff --git a/extensions/record/tests/record.host.test.mjs b/extensions/record/tests/record.host.test.mjs index b6db3864..c0648814 100644 --- a/extensions/record/tests/record.host.test.mjs +++ b/extensions/record/tests/record.host.test.mjs @@ -1,10 +1,15 @@ -// 本插件现行代码的宿主集成测试(从 packages/declarative-ui/tests/real-layout3-plugins.test.mjs 按插件拆出,导入改为本插件的 dist/) import test from 'node:test' import assert from 'node:assert/strict' -import { Toast } from '@ztools/declarative-ui' +import fs from 'node:fs' +import path from 'node:path' +import { fileURLToPath } from 'node:url' +import { setRuntimeLocale } from '@ztools/declarative-ui' import { createHost, mount, tick } from '../../shared/test-harness.mjs' import Command, * as record from '../dist/index.js' +setRuntimeLocale('zh-CN') + +const pluginDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..') const host = createHost() const views = [] const open = async () => { @@ -16,6 +21,7 @@ const open = async () => { test.beforeEach(() => { host.reset() + record.resetRecordRuntimeState() }) test.afterEach(() => { @@ -26,372 +32,374 @@ const VIDEOS = 'D:\\Videos' const SAVE_DIR = 'D:\\Videos\\ZTools_Recordings' const hostError = (message, code = 'INTERNAL_ERROR') => Object.assign(new Error(message), { code }) -/** - * 按客户端真实行为模拟录制相关接口: - * - dllplugin_call RecordPlugin:status / startRecording / stopRecording,返回结构与客户端一致(结果外再包一层 data) - * - system_get_path('videos')、filesystem_get_directory_contents(只授权视频文件夹本身)、system_search_files(dir: 扫描) - */ +function makeCapabilitiesSnapshot({ + captureStatus = 'ready', + probeStatus = 'ready', + transcodeStatus = 'ready', + transcodeExtensions = ['geometry', 'speed', 'audio-filters'] +} = {}) { + return { + contractVersion: 1, + platform: 'windows', + domains: ['media'], + capabilities: [ + { + primitiveId: 'media.capture', + domain: 'media', + summary: 'Capture screen or window', + ipcMethods: ['tool_media_capture_sources', 'tool_media_capture_start', 'tool_media_capture_stop', 'tool_media_capture_status'], + requiredPermissions: ['screen', 'media.process'], + status: captureStatus, + optionalExtensions: [] + }, + { + primitiveId: 'media.probe', + domain: 'media', + summary: 'Probe media streams', + ipcMethods: ['tool_media_probe'], + requiredPermissions: ['media.read'], + status: probeStatus, + optionalExtensions: [] + }, + { + primitiveId: 'media.transcode', + domain: 'media', + summary: 'Transcode media files', + ipcMethods: ['tool_media_transcode_run'], + requiredPermissions: ['media.process'], + status: transcodeStatus, + optionalExtensions: transcodeExtensions + } + ] + } +} + function installRecordHost({ folderExists = true, files = [], - totalMatches, + sources = [ + { id: 'screen:1:0', name: '主显示器', kind: 'screen', width: 2560, height: 1440, scaleFactor: 1.5 }, + { id: 'window:42:0', name: 'Visual Studio Code', kind: 'window', width: 1600, height: 900, scaleFactor: 1.5 } + ], + capabilities = makeCapabilitiesSnapshot(), startError = null, stopError = null, statusError = null, - scanError = null, sessions: initialSessions = [] } = {}) { - const sessions = new Map(initialSessions.map(s => [s.id, s])) + const sessions = new Map(initialSessions.map((s) => [s.sessionId || s.id, s])) const calls = [] let seq = 0 - const reply = r => ({ ...r, data: { ...r } }) host.ipc.system_get_path = ({ name }) => { if (name !== 'videos') throw hostError(`未模拟 ${name}`) return { path: VIDEOS } } - host.ipc.filesystem_get_directory_contents = ({ path }) => { - if (path !== VIDEOS) throw hostError('路径未由当前窗口授权', 'PERMISSION_DENIED') + host.ipc.filesystem_get_directory_contents = ({ path: dir }) => { + if (dir !== VIDEOS) throw hostError('路径未授权', 'PERMISSION_DENIED') return { success: true, - writeAuthorized: false, - files: [ - ...(folderExists ? [{ name: 'ZTools_Recordings', size: 0, isDirectory: true }] : []), - { name: 'holiday.mp4', size: 999, isDirectory: false } - ] + files: folderExists ? [{ name: 'ZTools_Recordings', size: 0, isDirectory: true }] : [] } } host.ipc.system_search_files = ({ query }) => { - if (scanError) throw hostError(scanError) - if (query !== `dir:${SAVE_DIR}` || !folderExists) throw hostError('宿主内部错误') - return { files, total_matches: totalMatches ?? files.length } + if (query !== `dir:${SAVE_DIR}` || !folderExists) throw hostError('目录读取失败') + return { files, total_matches: files.length } + } + host.ipc.tool_runtime_capabilities = () => { + calls.push({ method: 'tool_runtime_capabilities', params: {} }) + return { success: true, data: capabilities } + } + host.ipc.tool_runtime_ensure = (params) => { + calls.push({ method: 'tool_runtime_ensure', params }) + return { success: true, data: { primitiveId: params.primitiveId, status: 'ready', provisioned: true } } + } + host.ipc.tool_media_capture_sources = (params) => { + calls.push({ method: 'tool_media_capture_sources', params }) + assert.equal(params.includeScreens, true) + assert.equal(params.includeWindows, true) + return { success: true, data: { sources } } + } + host.ipc.tool_media_capture_status = (params) => { + calls.push({ method: 'tool_media_capture_status', params }) + if (statusError) throw hostError(statusError) + return { success: true, data: { sessions: [...sessions.values()] } } + } + host.ipc.tool_media_capture_start = (params) => { + calls.push({ method: 'tool_media_capture_start', params }) + if (startError) return { success: false, error: { code: 'CAPTURE_FAILED', message: startError } } + const taskId = params.taskId || `cap-${++seq}` + const outputPath = params.output?.path || `${SAVE_DIR}\\rec_${seq}.${params.container}` + sessions.set(taskId, { + taskId, + state: 'recording', + mode: params.mode, + durationMs: 0, + bytesWritten: 0, + outputPath, + startedAt: 1700000000000 + }) + return { success: true, data: { taskId, state: 'recording', startedAt: 1700000000000 } } } - host.ipc.dllplugin_call = ({ plugin, func, params }) => { - calls.push({ plugin, func, params }) - assert.equal(plugin, 'RecordPlugin') - if (func === 'status') { - if (statusError) throw hostError(statusError) - return reply({ ok: true, success: true, recording: sessions.size > 0, sessions: [...sessions.values()] }) + host.ipc.tool_media_capture_stop = (params) => { + calls.push({ method: 'tool_media_capture_stop', params }) + assert.equal(typeof params.taskId, 'string') + const active = sessions.get(params.taskId) + if (!active) return { success: false, error: { code: 'NO_ACTIVE_SESSION', message: '当前没有正在进行的录制' } } + sessions.delete(active.taskId) + if (stopError) return { success: false, error: { code: 'STOP_FAILED', message: stopError } } + return { + success: true, + data: { taskId: active.taskId, outputBytes: 4096, durationMs: 8500, container: 'mp4' } } - if (func === 'startRecording') { - if (startError) return reply({ ok: false, success: false, recording: false, error: startError }) - const id = `rec-${++seq}` - const outputPath = `${params.saveDir}\\record-170000000000${seq}.${params.format === 'gif' ? 'gif' : 'mp4'}` - sessions.set(id, { id, type: params.type, outputPath, startedAt: 1700000000000, fps: params.fps }) - return reply({ ok: true, success: true, recording: true, sessionId: id, outputPath, startedAt: new Date(1700000000000).toISOString() }) + } + host.ipc.tool_task_cancel = (params) => { + calls.push({ method: 'tool_task_cancel', params }) + for (const [k, s] of sessions.entries()) { + if (s.taskId === params.taskId || k === params.taskId) sessions.delete(k) } - if (func === 'stopRecording') { - const active = params.sessionId ? sessions.get(params.sessionId) : [...sessions.values()][0] - if (!active) { - return reply({ - ok: false, - success: false, - recording: false, - error: params.sessionId ? `录制会话不存在或已结束:${params.sessionId}` : '当前没有正在进行的录制' - }) - } - sessions.delete(active.id) - if (stopError) { - return reply({ ok: false, success: false, recording: false, sessionId: active.id, outputPath: active.outputPath, error: stopError }) + return { success: true, data: { taskId: params.taskId, cancelled: true } } + } + host.ipc.tool_media_probe = (params) => { + calls.push({ method: 'tool_media_probe', params }) + return { + success: true, + data: { + items: [ + { + displayName: 'demo.mp4', + container: 'mp4', + durationSec: 12.5, + sizeBytes: 102400, + streams: [ + { index: 0, kind: 'video', codec: 'h264', width: 1920, height: 1080, frameRate: 60 }, + { index: 1, kind: 'audio', codec: 'aac', sampleRateHz: 48000, channels: 2 } + ] + } + ] } - return reply({ ok: true, success: true, recording: false, sessionId: active.id, outputPath: active.outputPath, durationMs: 5000, sizeBytes: 2048 }) } - throw hostError(`未模拟 ${func}`) + } + host.ipc.tool_media_transcode_run = (params) => { + calls.push({ method: 'tool_media_transcode_run', params }) + return { + success: true, + data: { taskId: params.taskId, outputBytes: 51200, durationMs: 1200, container: params.container } + } } return { calls, sessions } } -const file = (name, size, mtime, dir = SAVE_DIR) => ({ name, path: `${dir}\\${name}`, is_dir: false, size, mtime }) - -test('record: 只列出保存目录里的 MP4 / GIF,不编造时长、分辨率与帧率,按时间倒序', async () => { - installRecordHost({ - files: [ - file('record-1.mp4', 30 * 1024 * 1024, 1700000000000), - file('record-2.gif', 2 * 1024 * 1024, 1700000600000), - file('no-time.mp4', 1024, undefined), - file('notes.txt', 10, 1700000000000), - file('deep.mp4', 5000, 1700000900000, `${SAVE_DIR}\\old`), - file('movie.mp4', 5000, 1700000900000, 'D:\\Other') - ], - totalMatches: 6 - }) - const ws = await record.fetchRecordWorkspace() - assert.equal(ws.saveDir, SAVE_DIR) - assert.deepEqual(ws.recordings.map(r => r.name), ['record-2.gif', 'record-1.mp4', 'no-time.mp4']) - assert.equal(ws.recordings[2].modifiedMs, null) - assert.equal(ws.recordings[1].sizeBytes, 30 * 1024 * 1024) - for (const r of ws.recordings) { - assert.equal('durationText' in r, false) - assert.equal('resolutionText' in r, false) - assert.equal('fps' in r, false) +test('record: 清单与源码彻底去 DLL 化,声明薄原语能力且一期仅 Windows', () => { + const manifest = JSON.parse(fs.readFileSync(path.join(pluginDir, 'plugin.json'), 'utf8')) + assert.deepEqual(manifest.requiredCapabilities, ['media.capture', 'media.probe', 'media.transcode']) + assert.equal(manifest.minAppVersion, '1.3.0.2') + assert.deepEqual(manifest.nativeComponents, []) + assert.deepEqual(manifest.targets.map((t) => t.id), ['windows-electron-any']) + for (const perm of ['screen', 'media.read', 'media.process', 'dialog', 'fs']) { + assert.ok(manifest.permissions.includes(perm), `missing permission ${perm}`) } - assert.equal(ws.partial, false) - assert.equal(ws.missing, false) - assert.equal(ws.listError, undefined) - assert.equal(ws.isRecording, false) - // 视频文件夹里别的视频不算录制文件 - assert.ok(!ws.recordings.some(r => r.name === 'holiday.mp4')) -}) - -test('record: 目录条目没有全部取回时标记为部分结果', async () => { - installRecordHost({ files: [file('record-1.mp4', 100, 1700000000000)], totalMatches: 500 }) - const ws = await record.fetchRecordWorkspace() - assert.equal(ws.recordings.length, 1) - assert.equal(ws.partial, true) -}) - -test('record: 保存目录还没创建时显示为空,不报错也不扫描', async () => { - installRecordHost({ folderExists: false }) - const ws = await record.fetchRecordWorkspace() - assert.equal(ws.missing, true) - assert.equal(ws.listError, undefined) - assert.deepEqual(ws.recordings, []) - assert.ok(!host.ipcCalls.some(([m]) => m === 'system_search_files')) -}) - -test('record: 目录扫描失败如实返回错误,不用空列表冒充', async () => { - installRecordHost({ scanError: '索引服务不可用' }) - const ws = await record.fetchRecordWorkspace() - assert.deepEqual(ws.recordings, []) - assert.match(ws.listError, /索引服务不可用/) + const logicSource = fs.readFileSync(path.join(pluginDir, 'src/logic.ts'), 'utf8') + assert.equal(logicSource.includes('dllplugin_call'), false) + assert.equal(logicSource.includes('RecordPlugin'), false) }) -test('record: 录制状态查询失败时状态为未知,而不是假定没有在录制', async () => { - installRecordHost({ statusError: '录制服务未响应' }) - const ws = await record.fetchRecordWorkspace() - assert.equal(ws.isRecording, null) - assert.match(ws.statusError, /录制服务未响应/) -}) - -test('record: 没有宿主接口时开始录制如实失败,工作台不返回示例数据', async () => { - const start = await record.startScreenRecording({ fps: '30', format: 'mp4', saveDir: SAVE_DIR }) - assert.equal(start.ok, false) - assert.equal(start.sessionId, '') - assert.match(start.error, /dllplugin_call/) - const stop = await record.stopScreenRecording() - assert.equal(stop.ok, false) - const ws = await record.fetchRecordWorkspace() - assert.deepEqual(ws.recordings, []) - assert.equal(ws.isRecording, null) - assert.ok(ws.listError) - assert.equal(record.INITIAL_RECORDED_VIDEOS, undefined) - assert.equal(record.RECORD_SOURCE_MODES, undefined) -}) - -test('record: 开始录制只发送客户端支持的参数,停止时按会话 id 停止并返回真实输出文件', async () => { +test('record: 三模式(全屏 / 窗口 / 区域选区含 scaleFactor)精准透传 sourceId 与 region,零全屏偷换', async () => { const { calls } = installRecordHost() - const start = await record.startScreenRecording({ fps: '15', format: 'gif', saveDir: SAVE_DIR }) - assert.equal(start.ok, true) - assert.equal(start.sessionId, 'rec-1') - assert.equal(start.outputPath, `${SAVE_DIR}\\record-1700000000001.gif`) - const startCall = calls.find(c => c.func === 'startRecording') - assert.deepEqual(startCall.params, { type: 'gif', format: 'gif', fps: 15, saveDir: SAVE_DIR }) - // 录制前先确认没有正在进行的录制 - assert.deepEqual(calls.map(c => c.func), ['status', 'startRecording']) - // 不再调用参数不合规、一直失败的录制控制条接口,也不再尝试不存在的通道 - assert.ok(!host.ipcCalls.some(([m]) => m === 'window_show_record_bar' || m === 'screen_record_start')) - const stop = await record.stopScreenRecording() - assert.equal(stop.ok, true) - assert.equal(stop.outputPath, `${SAVE_DIR}\\record-1700000000001.gif`) - assert.equal(stop.sizeBytes, 2048) - assert.deepEqual(calls.find(c => c.func === 'stopRecording').params, { sessionId: 'rec-1' }) -}) - -test('record: 已有录制在进行时不再启动第二个', async () => { - const { calls } = installRecordHost({ sessions: [{ id: 'rec-old', outputPath: `${SAVE_DIR}\\record-1.mp4`, startedAt: 1700000000000 }] }) - const res = await record.startScreenRecording({ fps: '30', format: 'mp4', saveDir: SAVE_DIR }) - assert.equal(res.ok, false) - assert.equal(res.error, 'RECORD_ALREADY_RUNNING') - assert.equal(res.sessionId, 'rec-old') - assert.ok(!calls.some(c => c.func === 'startRecording')) - // 插件重新打开后,停止的是客户端报告的那个会话 - const stop = await record.stopScreenRecording() - assert.equal(stop.ok, true) - assert.deepEqual(calls.find(c => c.func === 'stopRecording').params, { sessionId: 'rec-old' }) -}) - -test('record: 开始失败(如本机没有 ffmpeg)如实返回客户端原因,只调用一次', async () => { - const { calls } = installRecordHost({ startError: '本机未检测到 ffmpeg,无法启动屏幕视频或音频录制' }) - const res = await record.startScreenRecording({ fps: '30', format: 'mp4', saveDir: SAVE_DIR }) - assert.equal(res.ok, false) - assert.equal(res.sessionId, '') - assert.match(res.error, /ffmpeg/) - assert.equal(calls.filter(c => c.func === 'startRecording').length, 1) -}) - -test('record: 无法确认录制状态时不盲目启动', async () => { - const { calls } = installRecordHost({ statusError: '录制服务未响应' }) - const res = await record.startScreenRecording({ fps: '30', format: 'mp4', saveDir: SAVE_DIR }) - assert.equal(res.ok, false) - assert.match(res.message, /无法确认当前录制状态/) - assert.ok(!calls.some(c => c.func === 'startRecording')) -}) - -test('record: 停止失败时保留客户端的真实原因,不被重试结果覆盖', async () => { - const { calls } = installRecordHost({ stopError: '屏幕录制失败:ffmpeg 录制异常退出(退出码 1)' }) - assert.equal((await record.startScreenRecording({ fps: '30', format: 'mp4', saveDir: SAVE_DIR })).ok, true) - const stop = await record.stopScreenRecording() - assert.equal(stop.ok, false) - assert.match(stop.error, /ffmpeg 录制异常退出/) - assert.equal(calls.filter(c => c.func === 'stopRecording').length, 1) -}) - -test('record: 连按两次开始只启动一次录制', async () => { - const { calls } = installRecordHost() - const [a, b] = await Promise.all([ - record.startScreenRecording({ fps: '30', format: 'mp4', saveDir: SAVE_DIR }), - record.startScreenRecording({ fps: '30', format: 'mp4', saveDir: SAVE_DIR }) - ]) - assert.deepEqual([a.ok, b.ok].sort(), [false, true]) - assert.equal([a, b].find(r => !r.ok).error, 'RECORD_BUSY') - assert.equal(calls.filter(c => c.func === 'startRecording').length, 1) + // 1. 全屏模式(含系统音频回采 + 麦克风) + const fullRes = await record.startScreenRecording({ + mode: 'fullscreen', + sourceId: 'screen:1:0', + fps: '60', + format: 'mp4', + includeSystemAudio: true, + includeMicrophone: true, + saveDir: SAVE_DIR + }) + assert.equal(fullRes.ok, true) + const fullCall = calls.find((c) => c.method === 'tool_media_capture_start') + assert.equal(fullCall.params.mode, 'fullscreen') + assert.equal(fullCall.params.sourceId, 'screen:1:0') + assert.equal(fullCall.params.includeSystemAudio, true) + assert.equal(fullCall.params.includeMicrophone, true) + assert.equal(fullCall.params.region, undefined) + + const stopFull = await record.stopScreenRecording() + assert.equal(stopFull.ok, true) + assert.equal(stopFull.sizeBytes, 4096) + + // 2. 指定窗口模式(导出 WebM) + const winRes = await record.startScreenRecording({ + mode: 'window', + sourceId: 'window:42:0', + fps: '30', + format: 'webm', + includeSystemAudio: true, + includeMicrophone: false, + saveDir: SAVE_DIR + }) + assert.equal(winRes.ok, true) + const winCall = calls.filter((c) => c.method === 'tool_media_capture_start')[1] + assert.equal(winCall.params.mode, 'window') + assert.equal(winCall.params.sourceId, 'window:42:0') + assert.equal(winCall.params.container, 'webm') + assert.equal(winCall.params.frameRate, 30) + assert.equal(winCall.params.includeMicrophone, false) await record.stopScreenRecording() -}) -test('record: 客户端做不到的参数(HEVC、区域 / 窗口模式、音频)直接拒绝', async () => { - const { calls } = installRecordHost() - for (const config of [ - { fps: '30', format: 'mp4_hevc' }, - { fps: '120', format: 'mp4' }, - { sourceModeId: 'rec-custom-region', fps: '30', codecContainer: 'mp4_h264' }, - null - ]) { - const res = await record.startScreenRecording(config) - assert.equal(res.ok, false) - assert.equal(res.error, 'INVALID_RECORD_CONFIG') - } - assert.equal(calls.length, 0) -}) - -test('record 界面:只提供真实支持的选项,不出现录音、区域、窗口、HEVC 等做不到的设置', async () => { - installRecordHost({ files: [file('record-1.mp4', 100, 1700000000000)] }) - const view = await open() - const tree = view.tree() - assert.equal(tree.props.searchBarAccessory, undefined) - const fields = tree.props.workbenchPanel.fields - assert.deepEqual(fields.map(f => f.id), ['wb-rec-fps', 'wb-rec-format', 'wb-rec-scope', 'wb-rec-audio']) - assert.ok(!fields.some(f => f.type === 'toggle')) - assert.deepEqual(fields[1].options.map(o => o.value), ['mp4', 'gif']) - const text = view.text() - for (const word of ['WASAPI', '麦克风', 'HEVC', 'H.265', '硬件编码', '区域', '窗口', '鼠标', 'MB/分钟', 'DXGI']) { - assert.ok(!text.includes(word), `界面不应出现「${word}」`) - } - assert.match(tree.props.filterBar.props.summaryText, /^未在录制 · 1 个录制文件$/) - assert.deepEqual(view.actions(view.items()[0]).map(a => a.props.title), ['打开录制文件', '在文件夹中显示', '开始录制', '复制文件路径']) + // 3. 区域选区模式(允许 x=0, y=0,精准透传 scaleFactor,导出 GIF) + const parsedRegion = record.parseRegionInput('0,0,1280,720', 1.5) + assert.deepEqual(parsedRegion, { x: 0, y: 0, width: 1280, height: 720, scaleFactor: 1.5 }) + const regRes = await record.startScreenRecording({ + mode: 'region', + sourceId: 'screen:1:0', + region: parsedRegion, + fps: '15', + format: 'gif', + includeSystemAudio: false, + includeMicrophone: false, + saveDir: SAVE_DIR + }) + assert.equal(regRes.ok, true) + const regCall = calls.filter((c) => c.method === 'tool_media_capture_start')[2] + assert.equal(regCall.params.mode, 'region') + assert.equal(regCall.params.sourceId, 'screen:1:0') + assert.deepEqual(regCall.params.region, { x: 0, y: 0, width: 1280, height: 720, scaleFactor: 1.5 }) + + // 4. 取消任务透传 tool_task_cancel + const cancelRes = await record.cancelActiveRecordTask() + assert.equal(cancelRes.ok, true) + assert.equal(cancelRes.cancelled, true) + assert.ok(calls.some((c) => c.method === 'tool_task_cancel' && c.params.taskId === regRes.taskId)) }) -test('record 界面:开始、停止录制走真实结果并刷新状态', async () => { +test('record: 后期探测与二次转码裁切调用 tool_media_probe / tool_media_transcode_run 且不覆盖原文件', async () => { const { calls } = installRecordHost() - const view = await open() - const fields = () => view.tree().props.workbenchPanel.fields - fields().find(f => f.id === 'wb-rec-format').onChange('mp4_hevc') - fields().find(f => f.id === 'wb-rec-fps').onChange('60') - await tick() - assert.equal(fields().find(f => f.id === 'wb-rec-format').value, 'mp4') - - await view.run(undefined, '开始录制') - await tick(10) - assert.deepEqual(calls.find(c => c.func === 'startRecording').params, { type: 'video', format: 'mp4', fps: 60, saveDir: SAVE_DIR }) - assert.equal(host.toasts.find(t => t.title === '已开始录制(60 FPS,MP4)')?.style, Toast.Style.Success) - const tree = view.tree() - assert.match(tree.props.filterBar.props.summaryText, /^正在录制/) - assert.equal(tree.props.filterBar.props.actions[0].title, '停止录制并保存') - assert.equal(tree.props.workbenchPanel.previewCard.badge, '录制中') - assert.ok(tree.props.workbenchPanel.previewCard.metrics.some(m => m.value === 'record-1700000000001.mp4')) - - tree.props.filterBar.props.actions[0].onAction() - await tick(10) - const saved = host.toasts.find(t => t.title === '录制已保存') - assert.equal(saved?.style, Toast.Style.Success) - assert.match(saved.message, /record-1700000000001\.mp4/) - assert.match(view.tree().props.filterBar.props.summaryText, /^未在录制/) -}) - -test('record 界面:开始失败显示失败提示,状态不变', async () => { - installRecordHost({ startError: '本机未检测到 ffmpeg,无法启动屏幕视频或音频录制' }) - const view = await open() - await view.run(undefined, '开始录制') - await tick(10) - const toast = host.lastToast() - assert.equal(toast.style, Toast.Style.Failure) - assert.equal(toast.title, '录制启动失败') - assert.match(toast.message, /ffmpeg/) - assert.match(view.tree().props.filterBar.props.summaryText, /^未在录制/) -}) - -test('record 界面:状态未知、目录读取失败都如实显示', async () => { - installRecordHost({ statusError: '录制服务未响应', scanError: '索引服务不可用' }) - const view = await open() - const tree = view.tree() - assert.match(tree.props.filterBar.props.summaryText, /录制状态未知(.*录制服务未响应.*)/) - assert.match(tree.props.filterBar.props.summaryText, /录制文件读取失败/) - assert.equal(tree.props.workbenchPanel.previewCard.badge, '状态未知') - assert.match(tree.props.subList.emptyText, /读取保存目录失败/) -}) - -test('record 界面:还没有录制文件时提示为空,底部主动作是开始录制', async () => { - installRecordHost({ folderExists: false }) - const view = await open() - const tree = view.tree() - assert.equal(tree.props.subList.emptyText, '还没有录制文件,开始录制后会保存到这里') - assert.equal(view.actions()[0].props.title, '开始录制') + const inputPath = `${SAVE_DIR}\\clip.webm` + + const probe = await record.probeRecordedMedia(inputPath) + assert.equal(probe.ok, true) + assert.equal(probe.width, 1920) + assert.equal(probe.height, 1080) + assert.equal(probe.videoCodec, 'h264') + assert.equal(probe.durationSec, 12.5) + + const caps = makeCapabilitiesSnapshot({ transcodeExtensions: ['geometry', 'speed'] }) + const trans = await record.transcodeRecording({ + inputPath, + container: 'mp4', + trimStartSec: 0, + trimDurationSec: 5, + crop: { x: 0, y: 0, width: 1280, height: 720 }, + speedFactor: 1.5, + capabilities: caps + }) + assert.equal(trans.ok, true) + assert.notEqual(trans.outputPath, inputPath) + const transCall = calls.find((c) => c.method === 'tool_media_transcode_run') + assert.equal(transCall.params.overwrite, false) + assert.deepEqual(transCall.params.input, { path: inputPath }) + assert.deepEqual(transCall.params.trim, { startSec: 0, durationSec: 5 }) + assert.deepEqual(transCall.params.crop, { x: 0, y: 0, width: 1280, height: 720 }) + assert.equal(transCall.params.speedFactor, 1.5) }) -test('record 界面:打开 / 定位失败显示失败提示,复制路径写入剪贴板', async () => { - installRecordHost({ files: [file('record-1.mp4', 100, 1700000000000)] }) - const view = await open() - const item = view.items()[0] - await view.run(item, '打开录制文件') - assert.equal(host.lastToast().style, Toast.Style.Failure) - assert.equal(host.lastToast().title, '无法打开录制文件') - await view.run(item, '在文件夹中显示') - assert.equal(host.lastToast().title, '无法在文件夹中显示') +test('record: 引擎按需下载引导与无宿主环境明确报错', async () => { + const { calls } = installRecordHost({ + capabilities: makeCapabilitiesSnapshot({ captureStatus: 'needs_provisioning', transcodeStatus: 'needs_provisioning' }) + }) + const ws = await record.fetchRecordWorkspace() + assert.equal(ws.captureStatus, 'needs_provisioning') - host.ipc.shell_open_path = () => ({ success: true }) - const before = host.toasts.length - await view.run(item, '打开录制文件') - assert.equal(host.toasts.length, before) + const ensured = await record.ensureRecordEngines() + assert.equal(ensured.ok, true) + assert.deepEqual( + calls.filter((c) => c.method === 'tool_runtime_ensure').map((c) => c.params.primitiveId), + ['media.capture', 'media.probe', 'media.transcode'] + ) - await view.run(item, '复制文件路径') - assert.equal(host.clipboard.text, `${SAVE_DIR}\\record-1.mp4`) - assert.equal(host.lastToast().style, Toast.Style.Success) + // 无宿主通道时开始录制如实报错,不假装成功 + host.reset() + const noHostStart = await record.startScreenRecording({ + mode: 'fullscreen', + sourceId: 'screen:1:0', + fps: '30', + format: 'mp4', + includeSystemAudio: false, + includeMicrophone: false, + saveDir: SAVE_DIR + }) + assert.equal(noHostStart.ok, false) + assert.ok(noHostStart.error) }) -test('record 界面:已有录制时开始给出可读原因;停止失败显示客户端原因并回到真实状态', async () => { +test('record: 渲染视图挂载并支持查看采集源与录制状态', async () => { installRecordHost({ - stopError: '屏幕录制失败:ffmpeg 录制异常退出(退出码 1)', - sessions: [{ id: 'rec-old', outputPath: `${SAVE_DIR}\\record-1.mp4`, startedAt: 1700000000000 }] + files: [{ name: 'rec_1.webm', path: `${SAVE_DIR}\\rec_1.webm`, is_dir: false, size: 8192, mtime: 1700000000000 }] }) const view = await open() - assert.match(view.tree().props.filterBar.props.summaryText, /^正在录制/) - // 插件重新打开时以客户端状态为准:主动作是停止 - assert.equal(view.actions()[0].props.title, '停止录制并保存') - - const started = await record.startScreenRecording({ fps: '30', format: 'mp4', saveDir: SAVE_DIR }) - assert.equal(started.message, '已有录制正在进行,请先停止') - - await view.run(undefined, '停止录制并保存') - await tick(10) - const toast = host.lastToast() - assert.equal(toast.style, Toast.Style.Failure) - assert.equal(toast.title, '停止录制失败') - assert.match(toast.message, /ffmpeg 录制异常退出/) - assert.match(view.tree().props.filterBar.props.summaryText, /^未在录制/) + assert.ok(view.tree) + assert.equal(host.ipcCalls.some(([m]) => m === 'dllplugin_call'), false) }) -test('i18n: RECORD_FORMAT_OPTIONS 与 getRecordLimitationNote 随 locale 实时切换不冻结', () => { - assert.deepEqual(record.RECORD_FORMAT_OPTIONS.map(o => o.label), ['MP4 视频', 'GIF 动图']) - assert.match(record.getRecordLimitationNote(), /整个桌面/) - host.setLocale('en-US') - try { - assert.deepEqual(record.RECORD_FORMAT_OPTIONS.map(o => o.label), ['MP4 Video', 'GIF Animation']) - assert.deepEqual(record.getRecordFormatOptions().map(o => o.label), ['MP4 Video', 'GIF Animation']) - const noteEn = record.getRecordLimitationNote() - assert.match(noteEn, /entire desktop/i) - assert.ok(!/[\u4e00-\u9fa5]/.test(noteEn)) - } finally { - host.setLocale('zh-CN') +test('record: listRecordingFiles 传 mtime-desc 且安全解析空数值,空 saveDir 被拦截,stop 失败保留 activeTaskId', async () => { + installRecordHost() + let searchParams = null + host.ipc.system_search_files = (params) => { + searchParams = params + return { + files: [ + { name: 'null_size.mp4', path: `${SAVE_DIR}\\null_size.mp4`, is_dir: false, size: null, mtime: 1700000000000 }, + { name: 'empty_size.mp4', path: `${SAVE_DIR}\\empty_size.mp4`, is_dir: false, size: '', mtime: 1700000001000 }, + { name: 'zero_size.mp4', path: `${SAVE_DIR}\\zero_size.mp4`, is_dir: false, size: 0, mtime: 1700000002000 } + ], + total_matches: 3 + } } - assert.deepEqual(record.RECORD_FORMAT_OPTIONS.map(o => o.label), ['MP4 视频', 'GIF 动图']) + const listing = await record.listRecordingFiles(SAVE_DIR, VIDEOS) + assert.equal(searchParams.sortBy, 'mtime-desc') + assert.equal(listing.files.find((f) => f.name === 'null_size.mp4').sizeBytes, null) + assert.equal(listing.files.find((f) => f.name === 'empty_size.mp4').sizeBytes, null) + assert.equal(listing.files.find((f) => f.name === 'zero_size.mp4').sizeBytes, 0) + + // probeRecordedMedia 对 null / "" 返回 null 而非 0 + host.ipc.tool_media_probe = () => ({ + success: true, + data: { items: [{ container: 'mp4', durationSec: null, sizeBytes: '', streams: [] }] } + }) + const probe = await record.probeRecordedMedia(`${SAVE_DIR}\\null_size.mp4`) + assert.equal(probe.ok, true) + assert.equal(probe.durationSec, null) + assert.equal(probe.sizeBytes, null) + + // 空 saveDir 拦截,不生成相对路径 + const emptyDirRes = await record.startScreenRecording({ + mode: 'fullscreen', + sourceId: 'screen:1:0', + fps: '30', + format: 'mp4', + includeSystemAudio: false, + includeMicrophone: false, + saveDir: ' ' + }) + assert.equal(emptyDirRes.ok, false) + assert.equal(emptyDirRes.error, 'MISSING_SAVE_DIR') + + // stopScreenRecording 失败时保留 activeTaskId 以便重试或取消 + installRecordHost({ stopError: '编码器繁忙' }) + const started = await record.startScreenRecording({ + mode: 'fullscreen', + sourceId: 'screen:1:0', + fps: '30', + format: 'mp4', + includeSystemAudio: false, + includeMicrophone: false, + saveDir: SAVE_DIR + }) + assert.equal(started.ok, true) + assert.equal(record.getActiveTaskId(), started.taskId) + const failedStop = await record.stopScreenRecording() + assert.equal(failedStop.ok, false) + assert.equal(record.getActiveTaskId(), started.taskId, '停止失败后必须保留 activeTaskId 以便重试或取消') }) diff --git a/extensions/regex-cron/README.en.md b/extensions/regex-cron/README.en.md new file mode 100644 index 00000000..b61034db --- /dev/null +++ b/extensions/regex-cron/README.en.md @@ -0,0 +1,18 @@ +# Regex & Cron Toolkit + +Quick reference for common regular expressions, live regex pattern testing, and Cron expression parsing. + +## Usage + +- Commands: `regex` (`regex presets`, `common regex`), `regex test` (`regex tester`, `test regex`), and `cron` (`crontab`, `cron parser`, `cron schedule`). All three commands open the same workbench and can be switched via the top dropdown. +- Common Regex: 9 presets covering Chinese ID numbers, mobile phone numbers, Unified Social Credit Codes, license plates, landline numbers, bank card numbers, IPv4 addresses, port numbers, and email addresses, with matching and non-matching examples. `Enter` copies the pattern, `Cmd/Ctrl+Enter` (or `Cmd/Ctrl+T`) loads it into the tester, and `Cmd/Ctrl+C` copies the `/pattern/flags` notation. +- Regex Tester: Enter a pattern in the search box (supports `/pattern/flags`; defaults to `g` when flags are omitted), press `Enter` to edit the test text, and view every match and capture group on the right; `Cmd/Ctrl+Enter` copies the pattern. Matching stops automatically after 1 second; pattern length is capped at 2,000 characters, test text at 50,000 characters, and displayed matches at 200. +- Cron: Parses 5-field and 6-field Cron expressions and calculates the next 5 run times (in your local timezone; Quartz day numbering and `L`/`W`/`#` modifiers are not supported). 5-field uses Linux syntax (`minute hour day month weekday`), and 6-field uses Spring syntax with leading seconds. `Enter` copies the expression and `Cmd/Ctrl+Enter` copies the next 5 run times; common templates below can be calculated directly. + +## Platforms & Requirements + +- Supported: Windows, macOS + +## Network & Data + +- Works offline; no data is saved. diff --git a/extensions/regex-cron/plugin.json b/extensions/regex-cron/plugin.json index 11e3e125..6d6f768a 100644 --- a/extensions/regex-cron/plugin.json +++ b/extensions/regex-cron/plugin.json @@ -1,7 +1,8 @@ { "id": "regex-cron", "name": "正则与Cron", - "version": "1.0.5", + "version": "1.0.6", + "minAppVersion": "1.1.8.0", "description": "中国本土常用正则速查与实时测试高亮,支持Cron表达式中文语义解析与未来5次执行时间推算", "author": "ZTools Team", "category": [ @@ -76,7 +77,11 @@ "cron", "crontab", "tester", - "schedule" + "schedule", + "regular expression", + "cron parser", + "regex tester", + "pattern" ], "features": { "regex-dict": { @@ -124,5 +129,15 @@ { "path": "screenshots/03-interactive.png" } + ], + "keywords": [ + "正则", + "正则表达式", + "测正则", + "cron", + "定时任务表达式", + "crontab", + "正则测试", + "regex" ] } diff --git a/extensions/regex-cron/src/index.tsx b/extensions/regex-cron/src/index.tsx index aa82d9c2..b55ebc5d 100644 --- a/extensions/regex-cron/src/index.tsx +++ b/extensions/regex-cron/src/index.tsx @@ -77,7 +77,7 @@ export function EditRegexText({ sample, onSave }: { sample: string; onSave: (val return
{ onSave(value); pop() }} /> }> - + } @@ -164,6 +164,17 @@ export function RegexCronCommand(props: RegexCronCommandProps = {}) { filterBar={currentMode === 'cron' ? { summaryText: cronResult.calculatedAt ? t('cronSummaryAt', { at: cronResult.calculatedAt }) : t('cronSummaryDefault'), actions: [{ id: 'refresh-cron', title: t('cronRefreshAction'), onAction: () => setCronRefresh(value => value + 1) }] + } : currentMode === 'tester' ? { + summaryText: testSample + ? (regexMatchResult?.isValidRegex + ? t('testerMatchedTitle', { + prefix: regexMatchResult.truncated ? t('testerPrefixTruncated') : t('testerPrefixTotal'), + count: regexMatchResult.totalMatches, + ms: regexMatchResult.elapsedMs + }) + : t('testerSampleHeading')) + : t('testerSampleEmpty').replace(/\*/g, ''), + actions: [{ id: 'edit-sample', title: t('editSampleAction'), style: 'primary', onAction: editSample }] } : undefined} > {currentMode === 'dict' && ( @@ -209,13 +220,13 @@ ${item.invalidExamples.map((ex) => `- \`${ex}\` ${t('dictInvalidNote')}`).join(' handleLoadIntoTester(item)} /> } diff --git a/extensions/screen-color-picker/README.en.md b/extensions/screen-color-picker/README.en.md new file mode 100644 index 00000000..492b3538 --- /dev/null +++ b/extensions/screen-color-picker/README.en.md @@ -0,0 +1,21 @@ +# Screen Color Picker + +Read the pixel color at the mouse cursor position on screen, and convert and copy between HEX, RGB, HSL, HSV, CMYK, and other formats. + +## Usage + +- Command: `Screen Color Picker` +- Enter HEX (such as `#0A84FF`), `rgb(...)`, `hsl(...)`, or a color name in the search box to view converted formats and WCAG contrast ratios in the list. +- Picking colors: Click the "Screen Eyedropper" button at the top or choose "Screen Eyedropper" in the action panel. It samples the single pixel under the mouse cursor at the moment of trigger with no magnifying glass UI, then writes to the clipboard according to your "Default Copy Color Format". The plugin window stays visible during picking, so clicking the button samples the button's color; to sample elsewhere on screen, first move the cursor to the target spot (not covered by the ZTools window), then press `Ctrl+K` on the HEX row to open the action panel and select "Screen Eyedropper". +- Select a format and press `Enter` to copy (on the HEX row, `Enter` opens color details and `Ctrl+Enter` copies); the detail view lets you copy any format, inspect color harmonies, or paste the color directly into the foreground app. +- Save colors to your palette (up to 30 swatches), remove individual colors, or clear the palette. +- Picking failures report the failure reason. + +## Platforms & Requirements + +- Supported: Windows only +- Windows implementation is pending real-device verification. + +## Network & Data + +- Works offline; the color palette is saved strictly on your local device. diff --git a/extensions/screen-color-picker/plugin.json b/extensions/screen-color-picker/plugin.json index 4e2ac39e..19dbeb9b 100644 --- a/extensions/screen-color-picker/plugin.json +++ b/extensions/screen-color-picker/plugin.json @@ -2,7 +2,7 @@ "id": "screen-color-picker", "name": "屏幕取色", "description": "鼠标跟随像素级放大镜取色器,一键拾取屏幕任意位置颜色并复制 HEX / RGB / HSL 色值", - "version": "2.0.11", + "version": "2.0.12", "minAppVersion": "1.1.8.7", "author": "ZTools Team", "entry": "dist/index.js", @@ -40,7 +40,13 @@ "screen color", "hex", "rgb", - "hsl" + "hsl", + "screen color picker", + "pipette", + "pick color", + "grab color", + "color sampler", + "hex picker" ], "screenshots": [ { @@ -56,5 +62,16 @@ { "path": "screenshots/02-action-panel.png" } + ], + "keywords": [ + "屏幕取色", + "吸管", + "吸色", + "取屏幕颜色", + "抓颜色", + "屏幕吸管", + "滴管", + "拾色器", + "eyedropper" ] } diff --git a/extensions/screen-color-picker/src/converter.ts b/extensions/screen-color-picker/src/converter.ts index de5557c8..37dc64f6 100644 --- a/extensions/screen-color-picker/src/converter.ts +++ b/extensions/screen-color-picker/src/converter.ts @@ -673,7 +673,7 @@ function buildPickedColorResultFromRaw( /** * 屏幕拾色器核心 (Screen Eyedropper) - * 结合 screen_get_cursor_pos 与 ColorPickerPlugin.pickScreenPixel / screen_pick_color 获取真实屏幕像素 RGB/HEX 值; + * 结合 screen_get_cursor_pos 与 ColorPickerPlugin.pickScreenPixel 获取真实屏幕像素 RGB/HEX 值; * 真实宿主下若失败则如实抛出错误,彻底清零随机伪造假颜色的代码。 */ export async function pickScreenColor(hostOverride?: unknown): Promise { @@ -702,7 +702,7 @@ export async function pickScreenColor(hostOverride?: unknown): Promise( "ColorPickerPlugin", "pickScreenPixel", @@ -715,34 +715,9 @@ export async function pickScreenColor(hostOverride?: unknown): Promise( - "screen_pick_color", - { x: cursorX, y: cursorY }, - hostOverride - ); - checkPermissionError(String(pickRes.error || pickRes.data?.error || ""), pickRes.data); - if (pickRes.ok && pickRes.data?.ok !== false) { - const picked = buildPickedColorResultFromRaw(pickRes.data, cursorX, cursorY); - if (picked) return picked; - } - - // 4. 兼容宿主 screen_capture (mode: "color") - const capRes = await callHostTransport( - "screen_capture", - { mode: "color", x: cursorX, y: cursorY }, - hostOverride - ); - checkPermissionError(String(capRes.error || capRes.data?.error || ""), capRes.data); - if (capRes.ok && capRes.data?.ok !== false) { - const picked = buildPickedColorResultFromRaw(capRes.data, cursorX, cursorY); - if (picked) return picked; - } - const errMsg = pluginRes.error || - pickRes.error || - capRes.error || + (typeof pluginRes.data?.error === "string" && pluginRes.data.error ? pluginRes.data.error : "") || t("errColorPickerFailed"); throw new Error(errMsg); } diff --git a/extensions/screen-color-picker/src/index.tsx b/extensions/screen-color-picker/src/index.tsx index 5d6fe97c..a16c1446 100644 --- a/extensions/screen-color-picker/src/index.tsx +++ b/extensions/screen-color-picker/src/index.tsx @@ -541,17 +541,12 @@ export function ColorPickerCommand() { }} actions={ - - + - - - - - - + + } > diff --git a/extensions/screen-color-picker/src/native-ipc.ts b/extensions/screen-color-picker/src/native-ipc.ts index 51576b99..13643277 100644 --- a/extensions/screen-color-picker/src/native-ipc.ts +++ b/extensions/screen-color-picker/src/native-ipc.ts @@ -174,11 +174,13 @@ function normalizeMethodResult(method: string, payload: DynamicBridge): DynamicB if (method === 'system_get_battery_status') { // 宿主约定 percent 超出 0-100(如 255)表示无电池或电量未知,不能改写成 100% + // 若宿主明确给出 hasBattery 布尔值,必须原样保留,仅在缺失时按合法电量推算 const rawPct = payload.percent - const hasBattery = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const validPct = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const hasBattery = typeof payload.hasBattery === 'boolean' ? payload.hasBattery : validPct return { ...payload, - percent: hasBattery ? rawPct : null, + percent: validPct ? rawPct : null, hasBattery } } @@ -489,6 +491,8 @@ export interface RealDirectoryScanResult extends Iterable approximate?: boolean /** 宿主实际遍历的条目数 */ visitedEntries?: number + /** 目录本身不存在(ENOENT) */ + missing?: boolean /** 读取失败的真实原因;已有文件仍可使用,但不能当作完整结果。 */ error?: string } @@ -497,6 +501,7 @@ interface ScanResultMeta { truncated?: boolean approximate?: boolean visitedEntries?: number + missing?: boolean } export interface ScanDirectoryTreeOptions { @@ -504,6 +509,10 @@ export interface ScanDirectoryTreeOptions { maxFiles?: number collectTopN?: number filterExt?: RegExp + /** 为 true 时,目录本身不存在(ENOENT)按空目录处理,不返回 error(权限拒绝/读取失败仍照常报错) */ + ignoreMissing?: boolean + /** Top-N 保留与排序方式:默认按体积降序,下载/录屏等时效场景可传 mtime-desc */ + sortBy?: 'size-desc' | 'mtime-desc' hostOverride?: DynamicBridge } @@ -519,8 +528,9 @@ function normalizeIndexedFileEntry(f: DynamicBridge): RealIndexedFileEntry { const sz = Number(f?.size ?? f?.sizeBytes ?? 0) const isDir = Boolean(f?.is_dir || f?.isDir || f?.isDirectory) const rawMtime = Number(f?.mtime ?? f?.mtimeMs ?? 0) - const mtimeMs = rawMtime > 1e11 ? rawMtime : rawMtime > 0 ? rawMtime * 1000 : Date.now() - const mtimeSec = rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime + const validMtime = Number.isFinite(rawMtime) && rawMtime > 0 + const mtimeMs = validMtime ? (rawMtime > 1e11 ? rawMtime : rawMtime * 1000) : 0 + const mtimeSec = validMtime ? (rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime) : 0 if (p && sz >= 0) realFileSizeCache.set(p, sz) return { name, @@ -551,6 +561,7 @@ function makeScanResult( subdirs, ...(meta.truncated ? { truncated: true } : {}), ...(meta.approximate ? { approximate: true } : {}), + ...(meta.missing ? { missing: true } : {}), ...(typeof meta.visitedEntries === 'number' ? { visitedEntries: meta.visitedEntries } : {}), [Symbol.iterator]() { return files[Symbol.iterator]() @@ -609,13 +620,40 @@ export async function scanRealDirectoryTree( return result.error ? { ...result.scan, error: result.error } : result.scan } +/** 仅当正则明确声明了扩展名(含 `\.`)时提取后缀列表,避免把 `thumbcache|iconcache` 等文件名关键词误拆成假扩展名 */ +function extractExtensionTokensFromFilter(filterExt: RegExp): string[] { + const src = filterExt.source + if (!src.includes('\\.')) return [] + const afterDot = src.slice(src.indexOf('\\.') + 2) + const rawTokens = afterDot.match(/[a-z0-9]{1,8}/gi) || [] + const seen = new Set() + const out: string[] = [] + for (const token of rawTokens) { + const lower = token.toLowerCase() + if (!lower || seen.has(lower)) continue + seen.add(lower) + out.push(lower) + } + return out +} + +function isMissingDirectoryError(res: { error?: string; errorCode?: string; errorDetails?: Record }): boolean { + if (res.errorDetails?.reason === 'ENOENT' || res.errorCode === 'ENOENT') return true + const msg = String(res.error || '') + return /Directory does not exist|ENOENT/i.test(msg) +} + /** 一次界面扫描的错误汇总;多个目录并行扫描时保留可读目录的结果。 */ export function createDirectoryScanner(hostOverride?: DynamicBridge) { const failures = new Map() return { async scan(dir: string, options: number | ScanDirectoryTreeOptions = 160) { const result = await scanRealDirectoryTree(dir, options, hostOverride) - const error = result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') + const ignoreMissing = typeof options === 'object' && options !== null && options.ignoreMissing === true + const error = + result.missing && ignoreMissing + ? '' + : result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') if (error) failures.set(dir, error) else failures.delete(dir) return result @@ -648,26 +686,38 @@ async function scanDirectoryTreeWithError( const safeLimit = Math.min(200, Math.max(1, Math.floor(rawLimit || 160))) const hostOverride = opts.hostOverride const filterExt = opts.filterExt + const ignoreMissing = opts.ignoreMissing === true const dirQuery = `dir:${targetDir}` try { let rawPayload: DynamicBridge = null + const searchParams: Record = { + query: dirQuery, + limit: safeLimit, + ...(opts.sortBy ? { sortBy: opts.sortBy } : {}) + } const res = await callHostTransport( 'system_search_files', - { query: dirQuery, limit: safeLimit }, + searchParams, hostOverride ) - if (res.ok && res.data) { + if (res.ok && res.data && res.data.degraded !== true) { rawPayload = res.data + } else if (!res.ok && ignoreMissing && isMissingDirectoryError(res)) { + const missingScan = makeScanResult([], 0, 0, [], { missing: true }) + return { scan: missingScan } } - if (!rawPayload && !hostOverride && typeof window !== 'undefined') { + if (!rawPayload && !hostOverride && res.errorCode === 'METHOD_NOT_AVAILABLE' && typeof window !== 'undefined') { const w = window as DynamicBridge if (typeof w.__ztoolsLauncher?.searchFiles === 'function') { const rawOuter = await w.__ztoolsLauncher.searchFiles(dirQuery, safeLimit) - rawPayload = + const candidate = rawOuter && typeof rawOuter === 'object' && 'data' in rawOuter && rawOuter.data ? rawOuter.data : rawOuter + if (candidate && candidate.degraded !== true && candidate.success !== false) { + rawPayload = candidate + } } } @@ -678,29 +728,32 @@ async function scanDirectoryTreeWithError( let files: RealIndexedFileEntry[] = rawPayload.files.map(normalizeIndexedFileEntry) if (filterExt instanceof RegExp) { files = files.filter(f => !f.isDir && (filterExt.test(f.name) || filterExt.test(f.ext))) - // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索目标扩展名 + // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索明确声明的目标扩展名 if (files.length === 0 && !hostOverride) { - const extTokens = (filterExt.source.match(/[a-z0-9]{2,5}/gi) || []) - .filter(t => !['thumbcache', 'iconcache'].includes(t.toLowerCase())) - .slice(0, 4) - // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 - const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() - const extraLists = await Promise.all( - extTokens.map(ext => searchRealIndexedFiles(`.${ext.toLowerCase()}`, 30, hostOverride)) - ) - const seen = new Set() - for (const list of extraLists) { - for (const item of list) { - if (!item.isDir && item.size > 0 && !seen.has(item.path)) { - if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { - seen.add(item.path) - files.push(item) + const extTokens = extractExtensionTokensFromFilter(filterExt) + if (extTokens.length > 0) { + // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 + const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() + const extraLists = await Promise.all( + extTokens.map(ext => searchRealIndexedFiles(`.${ext}`, 30, hostOverride)) + ) + const seen = new Set() + for (const list of extraLists) { + for (const item of list) { + if (!item.isDir && item.size > 0 && !seen.has(item.path)) { + if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { + seen.add(item.path) + files.push(item) + } } } } } } } + // 先基于过滤后的完整命中集合计算总文件数与总字节数,再按 collectTopN 裁剪样本列表 + const matchedCount = files.length + const matchedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) if (typeof opts.collectTopN === 'number' && opts.collectTopN > 0 && files.length > opts.collectTopN) { files = files.slice(0, opts.collectTopN) } @@ -714,11 +767,10 @@ async function scanDirectoryTreeWithError( ...(s.approximate === true ? { approximate: true } : {}) })) : [] - const computedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) const totalFilesCount = - filterExt instanceof RegExp ? files.length : Number(rawPayload.total_matches ?? files.length) + filterExt instanceof RegExp ? matchedCount : Number(rawPayload.total_matches ?? matchedCount) const totalBytesCount = - filterExt instanceof RegExp ? computedBytes : Number(rawPayload.total_bytes ?? computedBytes) + filterExt instanceof RegExp ? matchedBytes : Number(rawPayload.total_bytes ?? matchedBytes) const visited = Number(rawPayload.visited_entries) return { scan: makeScanResult(files, totalFilesCount, totalBytesCount, subdirs, { @@ -1817,8 +1869,6 @@ export async function writeRealClipboardText(text: string, hostOverride?: Dynami const payload = { text: String(text || '') } const res = await callHostTransport('clipboard_copy_text', payload, hostOverride) if (res.ok) return true - const fallbackRes = await callHostTransport('clipboard_write_text', payload, hostOverride) - if (fallbackRes.ok) return true try { if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) { await navigator.clipboard.writeText(String(text || '')) diff --git a/extensions/screen-color-picker/tests/screen-color-picker.host.test.mjs b/extensions/screen-color-picker/tests/screen-color-picker.host.test.mjs index 1d7b4351..d89dbe7c 100644 --- a/extensions/screen-color-picker/tests/screen-color-picker.host.test.mjs +++ b/extensions/screen-color-picker/tests/screen-color-picker.host.test.mjs @@ -73,22 +73,22 @@ test('color-picker: 结合 screen_get_cursor_pos 与 ColorPickerPlugin.pickScree } ) - // 3. 异常边界测试:真实宿主下取色失败或无权限时必须抛出异常,严禁静默降级返回随机颜色 + // 3. 异常边界测试:真实宿主下取色失败或无权限时必须抛出真实异常,且不再调用不存在的 screen_pick_color 或非法参数的 screen_capture await withRealElectronWindow( { screen_get_cursor_pos: () => ({ x: 100, y: 100 }), - dllplugin_call: () => { - throw new Error('GDI_GETPIXEL_FAILED') - }, - screen_pick_color: () => { - throw new Error('GDI_GETPIXEL_FAILED') - }, - screen_capture: () => { + dllplugin_call: ({ plugin, func, params }) => { + assert.equal(plugin, 'ColorPickerPlugin') + assert.equal(func, 'pickScreenPixel') + assert.equal(params.x, 100) + assert.equal(params.y, 100) throw new Error('GDI_GETPIXEL_FAILED') } }, - async () => { + async calls => { await assert.rejects(() => colorConverter.pickScreenColor(), /GDI_GETPIXEL_FAILED/) + assert.equal(calls.some(c => c.channel === 'screen_pick_color'), false) + assert.equal(calls.some(c => c.channel === 'screen_capture'), false) } ) }) diff --git a/extensions/screenshot/README.en.md b/extensions/screenshot/README.en.md new file mode 100644 index 00000000..0fd7d6b7 --- /dev/null +++ b/extensions/screenshot/README.en.md @@ -0,0 +1,22 @@ +# Screenshot History + +Browse local screenshot directories to paste back, copy, reveal in folder, pin, and batch clean up screenshots; you can also capture all screens immediately. + +## Usage + +- Command: `Screenshot History`. +- Screenshot sources: macOS scans the system-configured screenshot location, screenshot-named files on the Desktop, `Pictures/Screenshots`, and files tagged as screenshots by Spotlight; Windows scans `Pictures\Screenshots`, OneDrive's `Pictures\Screenshots`, and image files under `Pictures`. Pinned items appear first, and the rest are sorted by modification time from newest to oldest. +- Capture now: Captures all displays (automatically hiding the ZTools window beforehand). The PNG file is saved in the ZTools cache directory and appears in the list only for the current session; you can choose in the workbench whether to copy it to the clipboard after capture. +- Press `Enter` to paste back into the active window, `⌘/Ctrl+Enter` to copy the image, and `⌘/Ctrl+K` to open the action panel (copy path, reveal in folder, open, pin, delete, etc.). When automatic paste is unavailable, it copies the image instead and prompts you to paste manually; on macOS, automatic paste requires granting ZTools Accessibility permission in System Settings. +- If copying, pasting, opening, or revealing reports an unauthorized path, select "Grant Access to Screenshot Folder" in the action panel, choose the folder containing the screenshots, and try again. +- Single-item deletion runs without confirmation: scanned screenshots are moved to Trash / Recycle Bin, while images captured in the current session via Capture Now are deleted directly. Batch cleanup affects only checked and unpinned screenshots in the current list and asks for confirmation before running. +- Region selection, annotation, and floating pin windows are not provided. + +## Platforms & Requirements + +- Supported: Windows, macOS +- Optical Character Recognition (OCR) is available only on Windows; other platforms do not display the recognition entry. + +## Network & Data + +- Offline only; all data is stored locally. diff --git a/extensions/screenshot/plugin.json b/extensions/screenshot/plugin.json index d00c4131..54b7162c 100644 --- a/extensions/screenshot/plugin.json +++ b/extensions/screenshot/plugin.json @@ -2,7 +2,8 @@ "id": "screenshot", "name": "截图历史", "description": "截取全部屏幕,浏览本机截图历史,支持复制、回贴、列表置顶与批量清理", - "version": "2.0.15", + "version": "2.0.16", + "minAppVersion": "1.1.8.0", "author": "ZTools Team", "entry": "dist/index.js", "icon": "icon.svg", @@ -17,7 +18,9 @@ "permissions": [ "screen", "clipboard", - "fs" + "fs", + "shell", + "dialog" ], "requireAdmin": false, "nativeComponents": [], @@ -46,7 +49,13 @@ "history", "screen", "image", - "pin" + "pin", + "screen capture", + "snip", + "snipping tool", + "capture screen", + "screenshot history", + "print screen" ], "screenshots": [ { @@ -62,5 +71,16 @@ { "path": "screenshots/02-action-panel.png" } + ], + "keywords": [ + "截图", + "截屏", + "截图历史", + "刚才的截图", + "找截图", + "区域截图", + "全屏截图", + "抓图", + "screenshot" ] } diff --git a/extensions/screenshot/src/i18n.ts b/extensions/screenshot/src/i18n.ts index aba09206..072ba179 100644 --- a/extensions/screenshot/src/i18n.ts +++ b/extensions/screenshot/src/i18n.ts @@ -30,7 +30,12 @@ const MESSAGES = { confirmCaptureNote: ",其中 {count} 张本次立即截取的截图会直接删除、无法恢复", confirmMoreItems: "\n… 等 {count} 张", cleanBtn: "清理", + deleteBtn: "删除", cancelBtn: "取消", + confirmDeleteTitle: "删除截图「{name}」?", + confirmDeleteMsgTrash: "该截图将被移入{trash}。", + confirmDeleteMsgPermanent: "该截图位于 ZTools 缓存目录,删除后将永久丢失、无法恢复。", + btnCaptureNow: "立即截屏", batchCleanSuccess: "已清理 {count} 张截图", batchCleanPartial: "已清理 {ok} 张,{fail} 张失败", pinFailedToast: "置顶操作失败", @@ -170,7 +175,12 @@ const MESSAGES = { confirmCaptureNote: " ({count} recent capture(s) will be permanently deleted)", confirmMoreItems: "\n...and {count} more", cleanBtn: "Clean", + deleteBtn: "Delete", cancelBtn: "Cancel", + confirmDeleteTitle: "Delete screenshot \"{name}\"?", + confirmDeleteMsgTrash: "This screenshot will be moved to {trash}.", + confirmDeleteMsgPermanent: "This screenshot is stored in ZTools cache and will be permanently deleted without recovery.", + btnCaptureNow: "Capture Screen", batchCleanSuccess: "Cleaned {count} screenshot(s)", batchCleanPartial: "Cleaned {ok}, {fail} failed", pinFailedToast: "Pin toggle failed", diff --git a/extensions/screenshot/src/index.tsx b/extensions/screenshot/src/index.tsx index 676288cd..69379423 100644 --- a/extensions/screenshot/src/index.tsx +++ b/extensions/screenshot/src/index.tsx @@ -178,6 +178,7 @@ export function ScreenshotsCommand() { const ocrEnabled = isOcrSupported(); const initialList = isRealHost ? [] : [...INITIAL_SCREENSHOTS]; const [items, setItems] = useState(() => initialList); + const [isLoading, setIsLoading] = useState(isRealHost); // 默认不勾选任何截图:批量清理是破坏性操作,必须由用户主动勾选 const [checkedIds, setCheckedIds] = useState([]); const [scanError, setScanError] = useState(""); @@ -200,19 +201,27 @@ export function ScreenshotsCommand() { useEffect(() => { let active = true; + setIsLoading(true); defaultScreenshotsManager.loadScreenshots().then((list) => { if (active) applyList(list); - }).catch((error) => { if (active) setScanError(error instanceof Error ? error.message : String(error)); }); + }).catch((error) => { + if (active) setScanError(error instanceof Error ? error.message : String(error)); + }).finally(() => { + if (active) setIsLoading(false); + }); return () => { active = false; }; }, [refreshCount]); const reloadScreenshots = (force = false) => { + setIsLoading(true); defaultScreenshotsManager.loadScreenshots(force).then(applyList).catch((error) => { const message = error instanceof Error ? error.message : String(error); setScanError(message); void showToast({ style: Toast.Style.Failure, title: t("scanFailedToast"), message }); + }).finally(() => { + setIsLoading(false); }); }; @@ -292,6 +301,17 @@ export function ScreenshotsCommand() { }; const handleDelete = async (item: ScreenshotItem) => { + const confirmed = await confirmAlert({ + title: t("confirmDeleteTitle", { name: item.filename }), + message: + item.source === "capture" + ? t("confirmDeleteMsgPermanent") + : t("confirmDeleteMsgTrash", { trash: trashName() }), + primaryAction: { title: t("deleteBtn"), style: "destructive" }, + dismissAction: { title: t("cancelBtn") } + }); + if (!confirmed) return; + const res = await defaultScreenshotsManager.deleteScreenshot(item); if (res.success) { setItems((prev) => prev.filter((s) => s.id !== item.id)); @@ -386,7 +406,7 @@ export function ScreenshotsCommand() { } /> handleOpenWithDefault(item)} /> - handleTogglePin(item)} /> - handleDelete(item)} /> @@ -481,6 +491,7 @@ export function ScreenshotsCommand() { return ( { - void handlePasteLatest(); + void handleCaptureScreenNow(); } }, { - id: "rescan", - label: t("btnRescanQueue"), - title: t("btnRescanQueue"), + id: "paste-latest", + label: t("btnPasteLatest"), + title: t("actionPasteLatest"), + icon: Icon.Clock, style: "secondary", onAction: () => { - reloadScreenshots(true); + void handlePasteLatest(); } } ] @@ -613,7 +626,7 @@ export function ScreenshotsCommand() { title={item.filename} subtitle={item.dimensions} accessories={[ - ...(item.pinned ? [{ text: "PINNED" }] : []), + ...(item.pinned ? [{ tag: t("tagPinned") }] : []), { text: item.formattedSize }, { text: item.formattedDate } ]} diff --git a/extensions/screenshot/src/native-ipc.ts b/extensions/screenshot/src/native-ipc.ts index 51576b99..13643277 100644 --- a/extensions/screenshot/src/native-ipc.ts +++ b/extensions/screenshot/src/native-ipc.ts @@ -174,11 +174,13 @@ function normalizeMethodResult(method: string, payload: DynamicBridge): DynamicB if (method === 'system_get_battery_status') { // 宿主约定 percent 超出 0-100(如 255)表示无电池或电量未知,不能改写成 100% + // 若宿主明确给出 hasBattery 布尔值,必须原样保留,仅在缺失时按合法电量推算 const rawPct = payload.percent - const hasBattery = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const validPct = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const hasBattery = typeof payload.hasBattery === 'boolean' ? payload.hasBattery : validPct return { ...payload, - percent: hasBattery ? rawPct : null, + percent: validPct ? rawPct : null, hasBattery } } @@ -489,6 +491,8 @@ export interface RealDirectoryScanResult extends Iterable approximate?: boolean /** 宿主实际遍历的条目数 */ visitedEntries?: number + /** 目录本身不存在(ENOENT) */ + missing?: boolean /** 读取失败的真实原因;已有文件仍可使用,但不能当作完整结果。 */ error?: string } @@ -497,6 +501,7 @@ interface ScanResultMeta { truncated?: boolean approximate?: boolean visitedEntries?: number + missing?: boolean } export interface ScanDirectoryTreeOptions { @@ -504,6 +509,10 @@ export interface ScanDirectoryTreeOptions { maxFiles?: number collectTopN?: number filterExt?: RegExp + /** 为 true 时,目录本身不存在(ENOENT)按空目录处理,不返回 error(权限拒绝/读取失败仍照常报错) */ + ignoreMissing?: boolean + /** Top-N 保留与排序方式:默认按体积降序,下载/录屏等时效场景可传 mtime-desc */ + sortBy?: 'size-desc' | 'mtime-desc' hostOverride?: DynamicBridge } @@ -519,8 +528,9 @@ function normalizeIndexedFileEntry(f: DynamicBridge): RealIndexedFileEntry { const sz = Number(f?.size ?? f?.sizeBytes ?? 0) const isDir = Boolean(f?.is_dir || f?.isDir || f?.isDirectory) const rawMtime = Number(f?.mtime ?? f?.mtimeMs ?? 0) - const mtimeMs = rawMtime > 1e11 ? rawMtime : rawMtime > 0 ? rawMtime * 1000 : Date.now() - const mtimeSec = rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime + const validMtime = Number.isFinite(rawMtime) && rawMtime > 0 + const mtimeMs = validMtime ? (rawMtime > 1e11 ? rawMtime : rawMtime * 1000) : 0 + const mtimeSec = validMtime ? (rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime) : 0 if (p && sz >= 0) realFileSizeCache.set(p, sz) return { name, @@ -551,6 +561,7 @@ function makeScanResult( subdirs, ...(meta.truncated ? { truncated: true } : {}), ...(meta.approximate ? { approximate: true } : {}), + ...(meta.missing ? { missing: true } : {}), ...(typeof meta.visitedEntries === 'number' ? { visitedEntries: meta.visitedEntries } : {}), [Symbol.iterator]() { return files[Symbol.iterator]() @@ -609,13 +620,40 @@ export async function scanRealDirectoryTree( return result.error ? { ...result.scan, error: result.error } : result.scan } +/** 仅当正则明确声明了扩展名(含 `\.`)时提取后缀列表,避免把 `thumbcache|iconcache` 等文件名关键词误拆成假扩展名 */ +function extractExtensionTokensFromFilter(filterExt: RegExp): string[] { + const src = filterExt.source + if (!src.includes('\\.')) return [] + const afterDot = src.slice(src.indexOf('\\.') + 2) + const rawTokens = afterDot.match(/[a-z0-9]{1,8}/gi) || [] + const seen = new Set() + const out: string[] = [] + for (const token of rawTokens) { + const lower = token.toLowerCase() + if (!lower || seen.has(lower)) continue + seen.add(lower) + out.push(lower) + } + return out +} + +function isMissingDirectoryError(res: { error?: string; errorCode?: string; errorDetails?: Record }): boolean { + if (res.errorDetails?.reason === 'ENOENT' || res.errorCode === 'ENOENT') return true + const msg = String(res.error || '') + return /Directory does not exist|ENOENT/i.test(msg) +} + /** 一次界面扫描的错误汇总;多个目录并行扫描时保留可读目录的结果。 */ export function createDirectoryScanner(hostOverride?: DynamicBridge) { const failures = new Map() return { async scan(dir: string, options: number | ScanDirectoryTreeOptions = 160) { const result = await scanRealDirectoryTree(dir, options, hostOverride) - const error = result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') + const ignoreMissing = typeof options === 'object' && options !== null && options.ignoreMissing === true + const error = + result.missing && ignoreMissing + ? '' + : result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') if (error) failures.set(dir, error) else failures.delete(dir) return result @@ -648,26 +686,38 @@ async function scanDirectoryTreeWithError( const safeLimit = Math.min(200, Math.max(1, Math.floor(rawLimit || 160))) const hostOverride = opts.hostOverride const filterExt = opts.filterExt + const ignoreMissing = opts.ignoreMissing === true const dirQuery = `dir:${targetDir}` try { let rawPayload: DynamicBridge = null + const searchParams: Record = { + query: dirQuery, + limit: safeLimit, + ...(opts.sortBy ? { sortBy: opts.sortBy } : {}) + } const res = await callHostTransport( 'system_search_files', - { query: dirQuery, limit: safeLimit }, + searchParams, hostOverride ) - if (res.ok && res.data) { + if (res.ok && res.data && res.data.degraded !== true) { rawPayload = res.data + } else if (!res.ok && ignoreMissing && isMissingDirectoryError(res)) { + const missingScan = makeScanResult([], 0, 0, [], { missing: true }) + return { scan: missingScan } } - if (!rawPayload && !hostOverride && typeof window !== 'undefined') { + if (!rawPayload && !hostOverride && res.errorCode === 'METHOD_NOT_AVAILABLE' && typeof window !== 'undefined') { const w = window as DynamicBridge if (typeof w.__ztoolsLauncher?.searchFiles === 'function') { const rawOuter = await w.__ztoolsLauncher.searchFiles(dirQuery, safeLimit) - rawPayload = + const candidate = rawOuter && typeof rawOuter === 'object' && 'data' in rawOuter && rawOuter.data ? rawOuter.data : rawOuter + if (candidate && candidate.degraded !== true && candidate.success !== false) { + rawPayload = candidate + } } } @@ -678,29 +728,32 @@ async function scanDirectoryTreeWithError( let files: RealIndexedFileEntry[] = rawPayload.files.map(normalizeIndexedFileEntry) if (filterExt instanceof RegExp) { files = files.filter(f => !f.isDir && (filterExt.test(f.name) || filterExt.test(f.ext))) - // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索目标扩展名 + // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索明确声明的目标扩展名 if (files.length === 0 && !hostOverride) { - const extTokens = (filterExt.source.match(/[a-z0-9]{2,5}/gi) || []) - .filter(t => !['thumbcache', 'iconcache'].includes(t.toLowerCase())) - .slice(0, 4) - // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 - const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() - const extraLists = await Promise.all( - extTokens.map(ext => searchRealIndexedFiles(`.${ext.toLowerCase()}`, 30, hostOverride)) - ) - const seen = new Set() - for (const list of extraLists) { - for (const item of list) { - if (!item.isDir && item.size > 0 && !seen.has(item.path)) { - if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { - seen.add(item.path) - files.push(item) + const extTokens = extractExtensionTokensFromFilter(filterExt) + if (extTokens.length > 0) { + // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 + const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() + const extraLists = await Promise.all( + extTokens.map(ext => searchRealIndexedFiles(`.${ext}`, 30, hostOverride)) + ) + const seen = new Set() + for (const list of extraLists) { + for (const item of list) { + if (!item.isDir && item.size > 0 && !seen.has(item.path)) { + if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { + seen.add(item.path) + files.push(item) + } } } } } } } + // 先基于过滤后的完整命中集合计算总文件数与总字节数,再按 collectTopN 裁剪样本列表 + const matchedCount = files.length + const matchedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) if (typeof opts.collectTopN === 'number' && opts.collectTopN > 0 && files.length > opts.collectTopN) { files = files.slice(0, opts.collectTopN) } @@ -714,11 +767,10 @@ async function scanDirectoryTreeWithError( ...(s.approximate === true ? { approximate: true } : {}) })) : [] - const computedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) const totalFilesCount = - filterExt instanceof RegExp ? files.length : Number(rawPayload.total_matches ?? files.length) + filterExt instanceof RegExp ? matchedCount : Number(rawPayload.total_matches ?? matchedCount) const totalBytesCount = - filterExt instanceof RegExp ? computedBytes : Number(rawPayload.total_bytes ?? computedBytes) + filterExt instanceof RegExp ? matchedBytes : Number(rawPayload.total_bytes ?? matchedBytes) const visited = Number(rawPayload.visited_entries) return { scan: makeScanResult(files, totalFilesCount, totalBytesCount, subdirs, { @@ -1817,8 +1869,6 @@ export async function writeRealClipboardText(text: string, hostOverride?: Dynami const payload = { text: String(text || '') } const res = await callHostTransport('clipboard_copy_text', payload, hostOverride) if (res.ok) return true - const fallbackRes = await callHostTransport('clipboard_write_text', payload, hostOverride) - if (fallbackRes.ok) return true try { if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) { await navigator.clipboard.writeText(String(text || '')) diff --git a/extensions/screenshot/src/screenshots-service.ts b/extensions/screenshot/src/screenshots-service.ts index 22682741..0da895d0 100644 --- a/extensions/screenshot/src/screenshots-service.ts +++ b/extensions/screenshot/src/screenshots-service.ts @@ -10,8 +10,6 @@ import { callHostTransport, invokePluginService, isRealElectronHost, - getRealSystemPath, - readRealDirectory, writeRealClipboardText } from "./native-ipc.js"; import { extractErrorCode, extractHostCode, resolveErrorMessage } from './error-i18n.js' @@ -344,14 +342,7 @@ export function buildScreenshotDetailMarkdown( ocrEnabled && item.ocrText ? t("detailOcrSection", { text: item.ocrText }) : ""; - return `${previewBlock} - ---- -${ocrBlock} -${t("detailPathLine", { path: inlineCode(item.path) })} -${t("detailResLine", { dims: item.dimensions })} -${t("detailSizeLine", { size: item.formattedSize, bytes: item.sizeBytes === null ? "" : ` (${item.sizeBytes.toLocaleString(getLocale())} ${item.sizeBytes === 1 ? "byte" : "bytes"})` })} -${t("detailTimeLine", { date: item.formattedDate })}`; + return ocrBlock ? `${previewBlock}\n\n---\n${ocrBlock}` : previewBlock; } /** @@ -874,8 +865,8 @@ export class ScreenshotsManager { /** * 提取指定截图的真实 OCR 文字并写入剪贴板 - * 调用文字识别服务 invokePluginService('OcrPlugin', 'recognizeImage', { path: item.path }, hostBridge); - * 该服务只有 Windows 实现,其他平台直接报不支持,不再发出注定失败的 dllplugin_call + * 优先调用宿主 image_ocr 接口(不受跨插件 dllplugin_call 归属拦截); + * 仅当 image_ocr 不可用(METHOD_NOT_AVAILABLE 或测试桩仅 mock 了 dllplugin_call/invokeNative)时回退 invokePluginService('OcrPlugin', 'recognizeImage')。 */ public async extractOcr(item: ScreenshotItem, hostOverride?: unknown): Promise { if (!item || !item.path) { @@ -887,22 +878,51 @@ export class ScreenshotsManager { throw new Error(t("errOcrUnsupported")); } - // 1. 优先调用文字识别服务的 recognizeImage - const pluginRes = await invokePluginService( - "OcrPlugin", - "recognizeImage", - { path: item.path }, + type OcrPayload = string | { text?: unknown; content?: unknown; result?: unknown }; + const extractOcrText = (data: OcrPayload | undefined | null): string => { + if (data === undefined || data === null) return ""; + if (typeof data === "string") return data.trim(); + if (typeof data === "object") { + return String(data.text ?? data.content ?? data.result ?? "").trim(); + } + return ""; + }; + const isMethodUnavailable = (res: { ok: boolean; error?: string; errorCode?: string; errorDetails?: Record }): boolean => { + if (res.ok) return false; + const code = extractErrorCode(res).toUpperCase(); + const hostCode = extractHostCode(res).toUpperCase(); + if ( + code === "METHOD_NOT_AVAILABLE" || + code === "METHOD_NOT_FOUND" || + hostCode === "METHOD_NOT_AVAILABLE" || + hostCode === "METHOD_NOT_FOUND" + ) { + return true; + } + const raw = String(res.error || ""); + // i18n-allow: legacy host fallback + return /\b(?:METHOD_NOT_AVAILABLE|METHOD_NOT_FOUND|CHANNEL_NOT_IMPLEMENTED)\b|unknown method|未知方法/i.test(raw); + }; + + // 1. 优先调用宿主统一 image_ocr 接口 + let finalRes = await callHostTransport( + "image_ocr", + { action: "recognizeImage", path: item.path }, hostOverride ); - if (pluginRes.ok && pluginRes.data !== undefined && pluginRes.data !== null) { - const data = pluginRes.data; - const text = - typeof data === "string" - ? data.trim() - : typeof data === "object" - ? String(data.text ?? data.content ?? data.result ?? "").trim() - : ""; + // 2. 仅当宿主未实现 image_ocr(旧客户端或仅 mock 了 dllplugin_call / invokeNative 的测试桩)时回退 + if (isMethodUnavailable(finalRes)) { + finalRes = await invokePluginService( + "OcrPlugin", + "recognizeImage", + { path: item.path }, + hostOverride + ); + } + + if (finalRes.ok) { + const text = extractOcrText(finalRes.data); if (text) { ;(item as { ocrText?: string; ocrStatus?: string }).ocrText = text; ;(item as { ocrText?: string; ocrStatus?: string }).ocrStatus = "ready"; @@ -915,7 +935,7 @@ export class ScreenshotsManager { if (strictReal) { ;(item as { ocrStatus?: string }).ocrStatus = "failed"; throw new Error( - resolveErrorMessage(pluginRes, t("errOcrFailed", { name: item.filename })) + resolveErrorMessage(finalRes, t("errOcrFailed", { name: item.filename })) ); } diff --git a/extensions/screenshot/tests/screenshot.host.test.mjs b/extensions/screenshot/tests/screenshot.host.test.mjs index 055cf7f4..5d9d5ae7 100644 --- a/extensions/screenshot/tests/screenshot.host.test.mjs +++ b/extensions/screenshot/tests/screenshot.host.test.mjs @@ -108,7 +108,7 @@ test('screenshots: 真实 PNG/GIF/BMP 文件头尺寸解析、真实剪贴板回 assert.equal(params.path, 'D:\\RealShots\\capture_real.png') return { text: '截图中的真实报错信息: ECONNREFUSED 127.0.0.1:8080' } }, - clipboard_write_text: ({ text }) => { + clipboard_copy_text: ({ text }) => { copiedText = text return true } @@ -174,4 +174,80 @@ test('screenshots: 真实 PNG/GIF/BMP 文件头尺寸解析、真实剪贴板回 ) } ) + + // 优先调用宿主 image_ocr 接口(不受跨插件 dllplugin_call 拦截);非方法缺失错误不回退 dllplugin_call + let copiedFromImageOcr = '' + await withRealElectronWindow( + { + image_ocr: ({ action, path: targetPath }) => { + assert.equal(action, 'recognizeImage') + assert.equal(targetPath, 'D:\\RealShots\\host_ocr.png') + return { text: '宿主 image_ocr 识别结果' } + }, + dllplugin_call: () => { + throw new Error('不应在 image_ocr 可用时调用 dllplugin_call') + }, + clipboard_copy_text: ({ text }) => { + copiedFromImageOcr = text + return true + } + }, + async () => { + const mgr = new screenshotsService.ScreenshotsManager() + const text = await mgr.extractOcr({ + id: 'ss-host-ocr', + filename: 'host_ocr.png', + path: 'D:\\RealShots\\host_ocr.png', + width: 100, + height: 100, + dimensions: '100 x 100', + sizeBytes: 1000, + formattedSize: '1 KB', + createdAt: Date.now(), + modifiedAt: Date.now(), + formattedDate: '刚刚', + pinned: false, + ocrText: '', + ocrStatus: 'pending' + }) + assert.equal(text, '宿主 image_ocr 识别结果') + assert.equal(copiedFromImageOcr, '宿主 image_ocr 识别结果') + } + ) + + await withRealElectronWindow( + { + image_ocr: () => ({ success: false, error: '路径未由当前窗口授权', errorCode: 'PERMISSION_DENIED' }), + dllplugin_call: () => { + throw new Error('非 METHOD_NOT_AVAILABLE 错误不应回退 dllplugin_call') + } + }, + async () => { + const mgr = new screenshotsService.ScreenshotsManager() + await assert.rejects( + () => + mgr.extractOcr({ + id: 'ss-host-ocr-err', + filename: 'denied.png', + path: 'D:\\RealShots\\denied.png', + width: 100, + height: 100, + dimensions: '100 x 100', + sizeBytes: 1000, + formattedSize: '1 KB', + createdAt: Date.now(), + modifiedAt: Date.now(), + formattedDate: '刚刚', + pinned: false, + ocrText: '', + ocrStatus: 'pending' + }), + /Permission denied|权限|授权/ + ) + } + ) + + const manifest = JSON.parse(fs.readFileSync(path.resolve(__dirname, '../plugin.json'), 'utf8')) + assert.ok(manifest.permissions.includes('shell'), 'screenshot plugin.json 必须包含 shell 权限') + assert.ok(manifest.permissions.includes('dialog'), 'screenshot plugin.json 必须包含 dialog 权限') })) diff --git a/extensions/screenshot/tests/screenshot.preview.test.mjs b/extensions/screenshot/tests/screenshot.preview.test.mjs index 56bceb1e..c8aca0de 100644 --- a/extensions/screenshot/tests/screenshot.preview.test.mjs +++ b/extensions/screenshot/tests/screenshot.preview.test.mjs @@ -139,13 +139,12 @@ test('sniffImageMime:只认真实图片魔数', () => { assert.equal(sniffImageMime(new Uint8Array([])), null) }) -test('详情 Markdown:成功时只嵌真实图片;失败时写原因、无图片语法;未知尺寸如实显示', () => { +test('详情 Markdown:成功时只嵌真实图片且不重复元信息;失败时写原因、无图片语法', () => { const it = item('we[ird]`name.png', { path: `${DIR}/a\`b.png` }) const ready = buildScreenshotDetailMarkdown(it, { status: 'ready', dataUrl: 'data:image/png;base64,AAAA' }, false) - assert.match(ready, /^!\[we ird `name\.png\]\(data:image\/png;base64,AAAA\)/) + assert.match(ready, /^!\[we ird `name\.png\]\(data:image\/png;base64,AAAA\)$/) assert.ok(!ready.includes('svg')) - assert.match(ready, /\*\*分辨率\*\*: 未知尺寸/) - assert.ok(ready.includes("`/Users/me/Desktop/a'b.png`")) + assert.ok(!ready.includes('**分辨率**'), '元信息由 Detail.Metadata 展示,不在正文重复') const bad = buildScreenshotDetailMarkdown(it, { status: 'unavailable', reason: '读取图片失败: 无权限\n第二行' }, false) assert.ok(!bad.includes(']('), '失败时不能出现图片语法') @@ -214,7 +213,7 @@ test('界面:列表动作「查看截图预览」打开真实图片详情; const detail = await mountPushed(host) await tick(10) assert.ok(detail.tree().props.markdown.includes(`(data:image/png;base64,${content})`)) - assert.match(detail.tree().props.markdown, /320 x 180/) + assert.match(detail.text(), /320 x 180/) detail.unmount() view.unmount() }) diff --git a/extensions/shared/native-ipc.ts b/extensions/shared/native-ipc.ts index 51576b99..13643277 100644 --- a/extensions/shared/native-ipc.ts +++ b/extensions/shared/native-ipc.ts @@ -174,11 +174,13 @@ function normalizeMethodResult(method: string, payload: DynamicBridge): DynamicB if (method === 'system_get_battery_status') { // 宿主约定 percent 超出 0-100(如 255)表示无电池或电量未知,不能改写成 100% + // 若宿主明确给出 hasBattery 布尔值,必须原样保留,仅在缺失时按合法电量推算 const rawPct = payload.percent - const hasBattery = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const validPct = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const hasBattery = typeof payload.hasBattery === 'boolean' ? payload.hasBattery : validPct return { ...payload, - percent: hasBattery ? rawPct : null, + percent: validPct ? rawPct : null, hasBattery } } @@ -489,6 +491,8 @@ export interface RealDirectoryScanResult extends Iterable approximate?: boolean /** 宿主实际遍历的条目数 */ visitedEntries?: number + /** 目录本身不存在(ENOENT) */ + missing?: boolean /** 读取失败的真实原因;已有文件仍可使用,但不能当作完整结果。 */ error?: string } @@ -497,6 +501,7 @@ interface ScanResultMeta { truncated?: boolean approximate?: boolean visitedEntries?: number + missing?: boolean } export interface ScanDirectoryTreeOptions { @@ -504,6 +509,10 @@ export interface ScanDirectoryTreeOptions { maxFiles?: number collectTopN?: number filterExt?: RegExp + /** 为 true 时,目录本身不存在(ENOENT)按空目录处理,不返回 error(权限拒绝/读取失败仍照常报错) */ + ignoreMissing?: boolean + /** Top-N 保留与排序方式:默认按体积降序,下载/录屏等时效场景可传 mtime-desc */ + sortBy?: 'size-desc' | 'mtime-desc' hostOverride?: DynamicBridge } @@ -519,8 +528,9 @@ function normalizeIndexedFileEntry(f: DynamicBridge): RealIndexedFileEntry { const sz = Number(f?.size ?? f?.sizeBytes ?? 0) const isDir = Boolean(f?.is_dir || f?.isDir || f?.isDirectory) const rawMtime = Number(f?.mtime ?? f?.mtimeMs ?? 0) - const mtimeMs = rawMtime > 1e11 ? rawMtime : rawMtime > 0 ? rawMtime * 1000 : Date.now() - const mtimeSec = rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime + const validMtime = Number.isFinite(rawMtime) && rawMtime > 0 + const mtimeMs = validMtime ? (rawMtime > 1e11 ? rawMtime : rawMtime * 1000) : 0 + const mtimeSec = validMtime ? (rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime) : 0 if (p && sz >= 0) realFileSizeCache.set(p, sz) return { name, @@ -551,6 +561,7 @@ function makeScanResult( subdirs, ...(meta.truncated ? { truncated: true } : {}), ...(meta.approximate ? { approximate: true } : {}), + ...(meta.missing ? { missing: true } : {}), ...(typeof meta.visitedEntries === 'number' ? { visitedEntries: meta.visitedEntries } : {}), [Symbol.iterator]() { return files[Symbol.iterator]() @@ -609,13 +620,40 @@ export async function scanRealDirectoryTree( return result.error ? { ...result.scan, error: result.error } : result.scan } +/** 仅当正则明确声明了扩展名(含 `\.`)时提取后缀列表,避免把 `thumbcache|iconcache` 等文件名关键词误拆成假扩展名 */ +function extractExtensionTokensFromFilter(filterExt: RegExp): string[] { + const src = filterExt.source + if (!src.includes('\\.')) return [] + const afterDot = src.slice(src.indexOf('\\.') + 2) + const rawTokens = afterDot.match(/[a-z0-9]{1,8}/gi) || [] + const seen = new Set() + const out: string[] = [] + for (const token of rawTokens) { + const lower = token.toLowerCase() + if (!lower || seen.has(lower)) continue + seen.add(lower) + out.push(lower) + } + return out +} + +function isMissingDirectoryError(res: { error?: string; errorCode?: string; errorDetails?: Record }): boolean { + if (res.errorDetails?.reason === 'ENOENT' || res.errorCode === 'ENOENT') return true + const msg = String(res.error || '') + return /Directory does not exist|ENOENT/i.test(msg) +} + /** 一次界面扫描的错误汇总;多个目录并行扫描时保留可读目录的结果。 */ export function createDirectoryScanner(hostOverride?: DynamicBridge) { const failures = new Map() return { async scan(dir: string, options: number | ScanDirectoryTreeOptions = 160) { const result = await scanRealDirectoryTree(dir, options, hostOverride) - const error = result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') + const ignoreMissing = typeof options === 'object' && options !== null && options.ignoreMissing === true + const error = + result.missing && ignoreMissing + ? '' + : result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') if (error) failures.set(dir, error) else failures.delete(dir) return result @@ -648,26 +686,38 @@ async function scanDirectoryTreeWithError( const safeLimit = Math.min(200, Math.max(1, Math.floor(rawLimit || 160))) const hostOverride = opts.hostOverride const filterExt = opts.filterExt + const ignoreMissing = opts.ignoreMissing === true const dirQuery = `dir:${targetDir}` try { let rawPayload: DynamicBridge = null + const searchParams: Record = { + query: dirQuery, + limit: safeLimit, + ...(opts.sortBy ? { sortBy: opts.sortBy } : {}) + } const res = await callHostTransport( 'system_search_files', - { query: dirQuery, limit: safeLimit }, + searchParams, hostOverride ) - if (res.ok && res.data) { + if (res.ok && res.data && res.data.degraded !== true) { rawPayload = res.data + } else if (!res.ok && ignoreMissing && isMissingDirectoryError(res)) { + const missingScan = makeScanResult([], 0, 0, [], { missing: true }) + return { scan: missingScan } } - if (!rawPayload && !hostOverride && typeof window !== 'undefined') { + if (!rawPayload && !hostOverride && res.errorCode === 'METHOD_NOT_AVAILABLE' && typeof window !== 'undefined') { const w = window as DynamicBridge if (typeof w.__ztoolsLauncher?.searchFiles === 'function') { const rawOuter = await w.__ztoolsLauncher.searchFiles(dirQuery, safeLimit) - rawPayload = + const candidate = rawOuter && typeof rawOuter === 'object' && 'data' in rawOuter && rawOuter.data ? rawOuter.data : rawOuter + if (candidate && candidate.degraded !== true && candidate.success !== false) { + rawPayload = candidate + } } } @@ -678,29 +728,32 @@ async function scanDirectoryTreeWithError( let files: RealIndexedFileEntry[] = rawPayload.files.map(normalizeIndexedFileEntry) if (filterExt instanceof RegExp) { files = files.filter(f => !f.isDir && (filterExt.test(f.name) || filterExt.test(f.ext))) - // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索目标扩展名 + // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索明确声明的目标扩展名 if (files.length === 0 && !hostOverride) { - const extTokens = (filterExt.source.match(/[a-z0-9]{2,5}/gi) || []) - .filter(t => !['thumbcache', 'iconcache'].includes(t.toLowerCase())) - .slice(0, 4) - // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 - const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() - const extraLists = await Promise.all( - extTokens.map(ext => searchRealIndexedFiles(`.${ext.toLowerCase()}`, 30, hostOverride)) - ) - const seen = new Set() - for (const list of extraLists) { - for (const item of list) { - if (!item.isDir && item.size > 0 && !seen.has(item.path)) { - if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { - seen.add(item.path) - files.push(item) + const extTokens = extractExtensionTokensFromFilter(filterExt) + if (extTokens.length > 0) { + // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 + const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() + const extraLists = await Promise.all( + extTokens.map(ext => searchRealIndexedFiles(`.${ext}`, 30, hostOverride)) + ) + const seen = new Set() + for (const list of extraLists) { + for (const item of list) { + if (!item.isDir && item.size > 0 && !seen.has(item.path)) { + if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { + seen.add(item.path) + files.push(item) + } } } } } } } + // 先基于过滤后的完整命中集合计算总文件数与总字节数,再按 collectTopN 裁剪样本列表 + const matchedCount = files.length + const matchedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) if (typeof opts.collectTopN === 'number' && opts.collectTopN > 0 && files.length > opts.collectTopN) { files = files.slice(0, opts.collectTopN) } @@ -714,11 +767,10 @@ async function scanDirectoryTreeWithError( ...(s.approximate === true ? { approximate: true } : {}) })) : [] - const computedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) const totalFilesCount = - filterExt instanceof RegExp ? files.length : Number(rawPayload.total_matches ?? files.length) + filterExt instanceof RegExp ? matchedCount : Number(rawPayload.total_matches ?? matchedCount) const totalBytesCount = - filterExt instanceof RegExp ? computedBytes : Number(rawPayload.total_bytes ?? computedBytes) + filterExt instanceof RegExp ? matchedBytes : Number(rawPayload.total_bytes ?? matchedBytes) const visited = Number(rawPayload.visited_entries) return { scan: makeScanResult(files, totalFilesCount, totalBytesCount, subdirs, { @@ -1817,8 +1869,6 @@ export async function writeRealClipboardText(text: string, hostOverride?: Dynami const payload = { text: String(text || '') } const res = await callHostTransport('clipboard_copy_text', payload, hostOverride) if (res.ok) return true - const fallbackRes = await callHostTransport('clipboard_write_text', payload, hostOverride) - if (fallbackRes.ok) return true try { if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) { await navigator.clipboard.writeText(String(text || '')) diff --git a/extensions/shared/tool-runtime.ts b/extensions/shared/tool-runtime.ts new file mode 100644 index 00000000..29670de2 --- /dev/null +++ b/extensions/shared/tool-runtime.ts @@ -0,0 +1,637 @@ +/** + * 宿主薄原语与基础系统能力传输层(唯一权威公共源文件,纯标准 IPC,零原生 DLL 依赖) + * + * 修改本文件后需同步复制到各使用插件的 src/tool-runtime.ts, + * 构建脚本 build-declarative.mjs 会在编译前校验副本与本文件一字不差。 + */ + +import { getHostTransport } from '@ztools/declarative-ui' + +export type ToolCapabilityStatus = 'ready' | 'needs_provisioning' | 'unsupported' + +export interface ToolCapabilityDescriptor { + readonly primitiveId: string + readonly domain: string + readonly summary: string + readonly ipcMethods: readonly string[] + readonly requiredPermissions: readonly string[] + readonly status: ToolCapabilityStatus + readonly optionalExtensions: readonly string[] +} + +export interface ToolRuntimeCapabilitiesSnapshot { + readonly contractVersion: number + readonly platform: 'windows' | 'macos' | 'other' + readonly domains: readonly string[] + readonly capabilities: readonly ToolCapabilityDescriptor[] +} + +export interface ToolRuntimeEnsureResult { + readonly primitiveId: string + readonly status: ToolCapabilityStatus + readonly provisioned: boolean +} + +export interface ToolCapabilitiesEnsureResult { + readonly ok: boolean + readonly status: ToolCapabilityStatus + readonly provisioned: boolean + readonly failedPrimitiveId?: string + readonly error?: string + readonly errorCode?: string + readonly errorDetails?: Record +} + +export interface ToolTaskCancelResult { + readonly taskId: string + readonly cancelled: boolean +} + +export interface ToolPathSlot { + readonly grantId?: string + readonly relativePath?: string + readonly path?: string +} + +export interface ToolProgressEvent { + readonly taskId: string + readonly primitiveId?: string + readonly phase: 'provisioning' | 'running' | 'finalizing' | 'completed' | 'cancelled' | 'failed' + readonly percent?: number + readonly transferredBytes?: number + readonly totalBytes?: number + readonly speedBytesPerSec?: number + readonly stage?: string + readonly errorCode?: string + readonly retryable?: boolean + readonly userAction?: string + readonly message?: string + readonly timestamp?: number +} + +export type MediaTranscodeRunResult = + | { readonly status: 'done'; readonly outputBytes: number; readonly durationMs: number } + | { readonly status: 'cancelled' } + | { + readonly status: 'failed' + readonly error?: string + readonly errorCode?: string + readonly errorDetails?: Record + } + +export interface HostTransportResult { + ok: boolean + data?: T + error?: string + errorCode?: string + errorDetails?: Record +} + +export interface HostCallOptions { + timeoutMs?: number +} + +type TransportMethodFn = (req: { messageId: string; params: Record; timeoutMs?: number }) => Promise + +interface WindowHostBridge { + __ztoolsElectron?: { + transport?: { + methods?: Record + } + } + ztools?: { + transport?: { + methods?: Record + call?: (method: string, params: Record, options?: { timeoutMs?: number }) => Promise + } + events?: { + subscribe?: (event: string) => Promise | void + on?: (event: string, cb: (payload: unknown) => void) => (() => void) | void + off?: (event: string, cb: (payload: unknown) => void) => void + } + } +} + +interface HostOverrideLike { + transport?: { + call?: (method: string, params: Record, options?: { timeoutMs?: number }) => Promise + } + [method: string]: unknown +} + +let reqSeq = 1 + +export function nextMessageId(prefix = 'tool'): string { + reqSeq = (reqSeq + 1) % 1_000_000 + return `${prefix}_${Date.now()}_${reqSeq}` +} + +export function asRecord(value: unknown): Record | null { + return value && typeof value === 'object' && !Array.isArray(value) + ? (value as Record) + : null +} + +function extractErrorMeta(errObj: unknown): { + errorCode?: string + errorDetails?: Record +} { + const rec = asRecord(errObj) + if (!rec) return {} + const errorCode = + typeof rec.errorCode === 'string' && rec.errorCode.trim() + ? rec.errorCode.trim() + : typeof rec.code === 'string' && rec.code.trim() + ? rec.code.trim() + : undefined + const rawDetails = asRecord(rec.errorDetails) ?? asRecord(rec.details) ?? undefined + return { + ...(errorCode ? { errorCode } : {}), + ...(rawDetails ? { errorDetails: rawDetails } : {}) + } +} + +function toTransportError(err: unknown): HostTransportResult { + return { + ok: false, + error: err instanceof Error ? err.message : String(err), + ...extractErrorMeta(err) + } +} + +function buildFailureResult(rec: Record, fallbackMsg: string): HostTransportResult { + const errObj = asRecord(rec.error) + const errMsg = errObj + ? String(errObj.message || errObj.code || JSON.stringify(errObj)) + : String(rec.error || rec.message || fallbackMsg) + return { ok: false, error: errMsg, ...extractErrorMeta(rec), ...extractErrorMeta(errObj) } +} + +function unwrapTransportResponse(raw: unknown): HostTransportResult { + if (raw === null || raw === undefined) { + return { ok: false, error: 'EMPTY_IPC_RESPONSE', errorCode: 'EMPTY_IPC_RESPONSE' } + } + if (typeof raw !== 'object') { + return { ok: true, data: raw as T } + } + const outer = asRecord(raw) + if (!outer) { + return { ok: true, data: raw as T } + } + if (outer.success === false || outer.ok === false) { + return buildFailureResult(outer, 'IPC_CALL_FAILED') + } + + const firstLayer = 'data' in outer && outer.data !== undefined ? outer.data : outer + const inner = asRecord(firstLayer) + if (inner) { + if (inner.success === false || inner.ok === false) { + return buildFailureResult(inner, 'IPC_INNER_FAILED') + } + if ('data' in inner && inner.data !== undefined) { + return { ok: true, data: inner.data as T } + } + } + + return { ok: true, data: firstLayer as T } +} + +/** 判断当前是否处于真实的 ZTools Electron 渲染进程宿主环境 */ +export function isRealElectronHost(hostOverride?: unknown): boolean { + if (hostOverride) return true + if (typeof window === 'undefined') return false + const w = window as unknown as WindowHostBridge + return Boolean( + w.__ztoolsElectron?.transport?.methods || + w.ztools?.transport?.call || + w.ztools?.transport?.methods + ) +} + +/** 统一调用宿主 IPC 传输层(优先测试桩,其次 declarative-ui 宿主通道与 preload 通道) */ +export async function callHostTransport( + method: string, + params: Record = {}, + hostOverride?: unknown, + options?: HostCallOptions +): Promise> { + const override = asRecord(hostOverride) as HostOverrideLike | null + if (override) { + const directFn = override[method] + if (typeof directFn === 'function') { + try { + return unwrapTransportResponse(await (directFn as (p: Record) => Promise)(params)) + } catch (err) { + return toTransportError(err) + } + } + if (typeof override.transport?.call === 'function') { + try { + return unwrapTransportResponse(await override.transport.call(method, params, options)) + } catch (err) { + return toTransportError(err) + } + } + return { ok: false, error: `METHOD_NOT_AVAILABLE: ${method}`, errorCode: 'METHOD_NOT_AVAILABLE' } + } + + // 优先走 declarative-ui 运行时注入的带归属令牌通道 + if (typeof getHostTransport === 'function') { + const transport = getHostTransport() + if (transport) { + try { + const callOpts = typeof options?.timeoutMs === 'number' ? { timeoutMs: options.timeoutMs } : undefined + return unwrapTransportResponse(await transport.call(method, params, callOpts)) + } catch (err) { + return toTransportError(err) + } + } + } + + if (typeof window === 'undefined') { + return { ok: false, error: 'NO_WINDOW_ENV', errorCode: 'NO_WINDOW_ENV' } + } + + const w = window as unknown as WindowHostBridge + const methods = w.__ztoolsElectron?.transport?.methods || w.ztools?.transport?.methods + const fn = methods?.[method] + if (typeof fn === 'function') { + try { + const messageId = nextMessageId(method.replace(/[^A-Za-z0-9_]/g, '_').slice(0, 24)) + const payload = { + messageId, + params, + ...(typeof options?.timeoutMs === 'number' ? { timeoutMs: options.timeoutMs } : {}) + } + return unwrapTransportResponse(await fn(payload)) + } catch (err) { + return toTransportError(err) + } + } + + if (typeof w.ztools?.transport?.call === 'function') { + try { + return unwrapTransportResponse(await w.ztools.transport.call(method, params, options)) + } catch (err) { + return toTransportError(err) + } + } + + return { ok: false, error: `METHOD_NOT_AVAILABLE: ${method}`, errorCode: 'METHOD_NOT_AVAILABLE' } +} + +/** 探测宿主薄原语能力快照(tool_runtime_capabilities) */ +export async function queryRuntimeCapabilities( + hostOverride?: unknown +): Promise> { + const res = await callHostTransport('tool_runtime_capabilities', {}, hostOverride) + if (!res.ok) return res as HostTransportResult + const rec = asRecord(res.data) + if (!rec || !Array.isArray(rec.capabilities)) { + return { + ok: false, + error: 'INVALID_CAPABILITIES_SNAPSHOT', + errorCode: 'INVALID_CAPABILITIES_SNAPSHOT' + } + } + const capabilities: ToolCapabilityDescriptor[] = [] + for (const rawCap of rec.capabilities) { + const cap = asRecord(rawCap) + if (!cap || typeof cap.primitiveId !== 'string') continue + const rawStatus = cap.status + const status: ToolCapabilityStatus = + rawStatus === 'ready' || rawStatus === 'needs_provisioning' || rawStatus === 'unsupported' + ? rawStatus + : 'unsupported' + const optionalExtensions = Array.isArray(cap.optionalExtensions) + ? cap.optionalExtensions.filter((e): e is string => typeof e === 'string' && e.trim().length > 0) + : [] + capabilities.push({ + primitiveId: cap.primitiveId, + domain: typeof cap.domain === 'string' ? cap.domain : '', + summary: typeof cap.summary === 'string' ? cap.summary : '', + ipcMethods: Array.isArray(cap.ipcMethods) ? cap.ipcMethods.filter((m): m is string => typeof m === 'string') : [], + requiredPermissions: Array.isArray(cap.requiredPermissions) + ? cap.requiredPermissions.filter((p): p is string => typeof p === 'string') + : [], + status, + optionalExtensions + }) + } + const platform = + rec.platform === 'windows' || rec.platform === 'macos' || rec.platform === 'other' + ? rec.platform + : 'other' + return { + ok: true, + data: { + contractVersion: typeof rec.contractVersion === 'number' ? rec.contractVersion : 1, + platform, + domains: Array.isArray(rec.domains) ? rec.domains.filter((d): d is string => typeof d === 'string') : [], + capabilities + } + } +} + +export function findCapability( + snapshot: ToolRuntimeCapabilitiesSnapshot | null | undefined, + primitiveId: string +): ToolCapabilityDescriptor | null { + if (!snapshot) return null + return snapshot.capabilities.find((c) => c.primitiveId === primitiveId) ?? null +} + +export function hasCapabilityExtension( + snapshot: ToolRuntimeCapabilitiesSnapshot | null | undefined, + primitiveId: string, + extensionName: string +): boolean { + const cap = findCapability(snapshot, primitiveId) + return Boolean(cap && cap.optionalExtensions.includes(extensionName)) +} + +/** 按需拉取并准备指定薄原语运行组件(tool_runtime_ensure) */ +export async function ensureRuntimeCapability( + primitiveId: string, + hostOverride?: unknown +): Promise> { + return callHostTransport('tool_runtime_ensure', { primitiveId }, hostOverride) +} + +/** 顺序按需准备多个薄原语运行组件,任一项未就绪即中止并聚合 provisioned 标记 */ +export async function ensureRuntimeCapabilities( + primitiveIds: readonly string[], + hostOverride?: unknown +): Promise { + let provisionedAny = false + for (const primitiveId of primitiveIds) { + const res = await ensureRuntimeCapability(primitiveId, hostOverride) + if (!res.ok || !res.data || res.data.status !== 'ready') { + return { + ok: false, + status: res.data?.status ?? 'unsupported', + provisioned: provisionedAny, + failedPrimitiveId: primitiveId, + error: res.error, + errorCode: res.errorCode, + errorDetails: res.errorDetails + } + } + if (res.data.provisioned) provisionedAny = true + } + return { ok: true, status: 'ready', provisioned: provisionedAny } +} + +/** 取消正在执行的宿主薄原语任务(tool_task_cancel) */ +export async function cancelRuntimeTask( + taskId: string, + hostOverride?: unknown +): Promise> { + return callHostTransport('tool_task_cancel', { taskId }, hostOverride) +} + +/** 判断错误码是否表示用户主动取消任务 */ +export function isTaskCancelledCode(errorCode?: string): boolean { + const code = (errorCode || '').trim().toUpperCase() + return code === 'TOOL_TASK_CANCELLED' || code === 'CANCELLED' || code === 'OPERATION_CANCELLED' +} + +/** 执行单个媒体转码任务(tool_media_transcode_run),统一处理取消与产物字节数校验 */ +export async function runMediaTranscodeTask( + payload: Record, + hostOverride?: unknown +): Promise { + const res = await callHostTransport('tool_media_transcode_run', payload, hostOverride) + if (!res.ok) { + if (isTaskCancelledCode(res.errorCode)) { + return { status: 'cancelled' } + } + return { + status: 'failed', + error: res.error, + errorCode: res.errorCode, + errorDetails: res.errorDetails + } + } + const rec = asRecord(res.data) + const outputBytes = Number(rec?.outputBytes) + const durationMs = Number(rec?.durationMs) + if (!Number.isFinite(outputBytes) || outputBytes <= 0) { + return { status: 'failed', error: 'EMPTY_OUTPUT', errorCode: 'EMPTY_OUTPUT' } + } + return { + status: 'done', + outputBytes, + durationMs: Number.isFinite(durationMs) && durationMs >= 0 ? durationMs : 0 + } +} + +/** 订阅宿主推送的 tool_runtime_progress 任务进度事件 */ +export function subscribeRuntimeProgress( + handler: (event: ToolProgressEvent) => void +): () => void { + if (typeof window === 'undefined') return () => undefined + const w = window as unknown as WindowHostBridge + const eventsApi = w.ztools?.events + if (!eventsApi || typeof eventsApi.on !== 'function') return () => undefined + + try { + void eventsApi.subscribe?.('tool_runtime_progress') + } catch (err) { + // 某些测试桩或旧渲染层可能未提供 subscribe,继续注册 on 监听 + void err + } + + const listener = (raw: unknown) => { + const outer = asRecord(raw) + if (!outer) return + const inner = asRecord(outer.payload) ?? outer + if (typeof inner.taskId !== 'string' || typeof inner.phase !== 'string') return + handler(inner as unknown as ToolProgressEvent) + } + + const off = eventsApi.on('tool_runtime_progress', listener) + return () => { + if (typeof off === 'function') { + off() + } else if (typeof eventsApi.off === 'function') { + eventsApi.off('tool_runtime_progress', listener) + } + } +} + +/** 订阅旧版宿主 plugin_files_dropped 拖拽回退事件并返回卸载函数 */ +export function subscribeLegacyFileDrop(onDrop: (envelope: unknown) => void): () => void { + if (typeof window === 'undefined') return () => undefined + const w = window as unknown as WindowHostBridge + const eventsApi = w.ztools?.events + if (!eventsApi || typeof eventsApi.on !== 'function') return () => undefined + + const off = eventsApi.on('plugin_files_dropped', onDrop) + return () => { + if (typeof off === 'function') { + off() + } else if (typeof eventsApi.off === 'function') { + eventsApi.off('plugin_files_dropped', onDrop) + } + } +} + +/** 字节数格式化 */ +export function formatBytes(bytes: number): string { + if (!Number.isFinite(bytes) || bytes < 0) return '0 B' + if (bytes < 1024) return `${Math.round(bytes)} B` + const units = ['KB', 'MB', 'GB', 'TB'] + let value = bytes / 1024 + let idx = 0 + while (value >= 1024 && idx < units.length - 1) { + value /= 1024 + idx += 1 + } + return `${value >= 100 ? value.toFixed(0) : value >= 10 ? value.toFixed(1) : value.toFixed(2)} ${units[idx]}` +} + +/** 字节数格式化别名(兼容 archive-manager 等插件既有导出名) */ +export function formatByteCount(bytes: number): string { + return formatBytes(bytes) +} + +/** 获取系统标准目录路径(支持 Windows 与 macOS) */ +export async function getRealSystemPath( + name: 'home' | 'desktop' | 'documents' | 'downloads' | 'music' | 'pictures' | 'videos' | 'temp', + hostOverride?: unknown +): Promise { + const res = await callHostTransport('system_get_path', { name }, hostOverride) + if (res.ok && res.data) { + if (typeof res.data === 'string' && res.data.trim()) return res.data.trim() + const rec = asRecord(res.data) + if (rec && typeof rec.path === 'string' && rec.path.trim()) return rec.path.trim() + } + return '' +} + +/** 读取剪贴板文本 */ +export async function readRealClipboardText(hostOverride?: unknown): Promise { + const res = await callHostTransport('clipboard_read_text', {}, hostOverride) + if (res.ok && res.data !== undefined && res.data !== null) { + if (typeof res.data === 'string') return res.data + const rec = asRecord(res.data) + if (rec && typeof rec.text === 'string') return rec.text + } + return '' +} + +/** 写入剪贴板文本 */ +export async function writeRealClipboardText(text: string, hostOverride?: unknown): Promise { + const res = await callHostTransport('clipboard_copy_text', { text: String(text || '') }, hostOverride) + return res.ok +} + +/** 在系统文件管理器中显示文件 */ +export async function showRealItemInFolder(fullPath: string, hostOverride?: unknown): Promise { + if (!fullPath) return false + const res = await callHostTransport('shell_show_item_in_folder', { fullPath }, hostOverride) + return res.ok +} + +/** 用系统默认应用打开文件或文件夹 */ +export async function openRealPath(fullPath: string, hostOverride?: unknown): Promise { + if (!fullPath) return false + const res = await callHostTransport('shell_open_path', { fullPath }, hostOverride) + return res.ok +} + +/** 将文件或目录移入系统回收站 */ +export async function trashRealItem(fullPath: string, hostOverride?: unknown): Promise<{ ok: boolean; error?: string }> { + if (!fullPath) return { ok: false, error: 'EMPTY_PATH' } + const res = await callHostTransport('shell_trash_item', { fullPath }, hostOverride) + return res.ok ? { ok: true } : { ok: false, error: res.error } +} + +/** 通过 window_show_open_dialog 选择输出目录(兼容 Windows 与 macOS) */ +export async function pickOutputDirectoryDialog( + options: { title: string; defaultPath?: string }, + hostOverride?: unknown +): Promise<{ canceled: boolean; directoryPath?: string; error?: string; errorCode?: string }> { + const params: Record = { + title: options.title, + properties: ['openDirectory', 'createDirectory'] + } + if (options.defaultPath) params.defaultPath = options.defaultPath + const res = await callHostTransport('window_show_open_dialog', params, hostOverride) + if (!res.ok) { + return { canceled: false, error: res.error || 'OPEN_DIALOG_FAILED', errorCode: res.errorCode } + } + const rec = asRecord(res.data) + if (!rec) return { canceled: false, error: 'INVALID_DIALOG_RESULT' } + if (rec.canceled === true) return { canceled: true } + const firstPath = + (Array.isArray(rec.filePaths) && typeof rec.filePaths[0] === 'string' && rec.filePaths[0].trim()) || + (typeof rec.filePath === 'string' && rec.filePath.trim()) || + (typeof rec.folderPath === 'string' && rec.folderPath.trim()) || + '' + if (!firstPath) return { canceled: false, error: 'NO_DIRECTORY_SELECTED' } + return { canceled: false, directoryPath: firstPath } +} + +/** 通用文件/目录选择对话框(支持自定义 properties 与 filters) */ +export async function openDialogSelectPaths( + options: { + title: string + properties: Array<'openFile' | 'openDirectory' | 'multiSelections' | 'createDirectory'> + filters?: Array<{ name: string; extensions: string[] }> + }, + hostOverride?: unknown +): Promise<{ canceled: boolean; paths: string[]; error?: string }> { + const params: Record = { + title: options.title, + properties: options.properties, + ...(options.filters ? { filters: options.filters } : {}) + } + const res = await callHostTransport('window_show_open_dialog', params, hostOverride) + if (!res.ok) return { canceled: false, paths: [], error: res.error || 'OPEN_DIALOG_FAILED' } + const rec = asRecord(res.data) + if (!rec) return { canceled: false, paths: [], error: 'INVALID_DIALOG_RESPONSE' } + if (rec.canceled === true) return { canceled: true, paths: [] } + const paths = Array.isArray(rec.filePaths) + ? rec.filePaths.filter((p): p is string => typeof p === 'string' && p.trim().length > 0).map((p) => p.trim()) + : typeof rec.filePath === 'string' && rec.filePath.trim() + ? [rec.filePath.trim()] + : [] + return { canceled: false, paths } +} + +/** 选择待归档的源文件或目录列表(多选) */ +export async function pickAnySourcesDialog( + options: { title: string; directories?: boolean }, + hostOverride?: unknown +): Promise<{ canceled: boolean; paths: string[]; error?: string }> { + return openDialogSelectPaths( + { + title: options.title, + properties: options.directories ? ['openDirectory', 'multiSelections'] : ['openFile', 'multiSelections'] + }, + hostOverride + ) +} + +/** 保存归档文件对话框(zip / 7z / tar) */ +export async function pickSaveArchiveDialog( + options: { title: string; defaultPath?: string; format: 'zip' | '7z' | 'tar' }, + hostOverride?: unknown +): Promise<{ canceled: boolean; filePath?: string; error?: string }> { + const ext = options.format === '7z' ? '7z' : options.format === 'tar' ? 'tar' : 'zip' + const params: Record = { + title: options.title, + filters: [{ name: `${ext.toUpperCase()} Archive`, extensions: [ext] }] + } + if (options.defaultPath) params.defaultPath = options.defaultPath + const res = await callHostTransport('window_show_save_dialog', params, hostOverride) + if (!res.ok) return { canceled: false, error: res.error || 'SAVE_DIALOG_FAILED' } + const rec = asRecord(res.data) + if (!rec) return { canceled: false, error: 'INVALID_SAVE_DIALOG' } + if (rec.canceled === true) return { canceled: true } + const filePath = typeof rec.filePath === 'string' ? rec.filePath.trim() : '' + if (!filePath) return { canceled: true } + return { canceled: false, filePath } +} diff --git a/extensions/shared/volume-ipc.ts b/extensions/shared/volume-ipc.ts index 4be65bd7..0059623b 100644 --- a/extensions/shared/volume-ipc.ts +++ b/extensions/shared/volume-ipc.ts @@ -50,23 +50,97 @@ export interface RealDiskDriveInfo { usagePercent: number } +export interface RealDiskDrivesProbeResult { + drives: RealDiskDriveInfo[] + partial: boolean + warnings: string[] +} + /** - * 读取宿主枚举的已挂载卷,不猜测盘符或挂载点。 + * 读取宿主枚举的已挂载卷,并返回部分失败状态与告警; + * 当 partial 为 true 且存在有效卷时保留有效卷并透传 warnings,仅在无任何有效卷时抛错。 */ -export async function probeRealDiskDrives(_letters: string[] = [], hostOverride?: unknown): Promise { +export async function probeRealDiskDrivesWithStatus( + _letters: string[] = [], + hostOverride?: unknown +): Promise { const s = volumeIpcStrings() const res = await callHostTransport>('system_list_volumes', {}, hostOverride) if (!res.ok && isHostMethodMissing(res.error)) throw hostUpgradeError(s.listVolumesFeature) if (!res.ok || !Array.isArray(res.data?.volumes)) throw new Error(res.error || s.unableToReadVolumes) - if (res.data.partial) throw new Error(s.incompleteVolumeList(Array.isArray(res.data.errors) ? res.data.errors.join(s.errorSep) : s.capacityReadFailed)) - const drives = res.data.volumes.map((value: unknown) => { - if (!value || typeof value !== 'object') throw new Error(s.invalidVolumeData) + + const hostPartial = res.data.partial === true + const warnings: string[] = Array.isArray(res.data.errors) + ? res.data.errors.map(err => String(err ?? '').trim()).filter(Boolean) + : [] + if (hostPartial && warnings.length === 0) { + warnings.push(s.capacityReadFailed) + } + + const drives: RealDiskDriveInfo[] = [] + let invalidCount = 0 + for (const value of res.data.volumes as unknown[]) { + if (!value || typeof value !== 'object') { + invalidCount += 1 + warnings.push(s.invalidVolumeData) + continue + } const v = value as Record - const total = Number(v.totalBytes), used = Number(v.usedBytes), available = Number(v.availableBytes) - if (typeof v.path !== 'string' || !v.path || !Number.isFinite(total) || total <= 0 || !Number.isFinite(used) || used < 0 || !Number.isFinite(available) || available < 0) throw new Error(s.invalidVolumeData) - return { drive: v.path.replace(/^([A-Za-z]:)[\\/]$/, '$1'), label: String(v.label || v.path), fileSystem: String(v.fileSystem || s.unknownFs), capacityGroup: String(v.capacityGroup || v.path), totalBytes: total, usedBytes: used, availableBytes: available, usagePercent: Math.round(used / total * 100) } - }) - if (!drives.length) throw new Error(s.noMountedVolumes) + const total = Number(v.totalBytes) + const used = Number(v.usedBytes) + const available = Number(v.availableBytes) + const valid = + typeof v.path === 'string' && + v.path.length > 0 && + typeof v.totalBytes === 'number' && + typeof v.usedBytes === 'number' && + typeof v.availableBytes === 'number' && + Number.isFinite(total) && + total > 0 && + Number.isFinite(used) && + used >= 0 && + Number.isFinite(available) && + available >= 0 + if (!valid) { + invalidCount += 1 + warnings.push(typeof v.path === 'string' && v.path ? `${v.path}: ${s.invalidVolumeData}` : s.invalidVolumeData) + continue + } + const volumePath = v.path as string + drives.push({ + drive: volumePath.replace(/^([A-Za-z]:)[\\/]$/, '$1'), + label: String(v.label || volumePath), + fileSystem: String(v.fileSystem || s.unknownFs), + capacityGroup: String(v.capacityGroup || volumePath), + totalBytes: total, + usedBytes: used, + availableBytes: available, + usagePercent: Math.round((used / total) * 100) + }) + } + + const partial = hostPartial || invalidCount > 0 + if (!drives.length) { + if (hostPartial) { + throw Object.assign(new Error(s.incompleteVolumeList(warnings.join(s.errorSep))), { + code: 'VOLUME_PARTIAL_EMPTY', + warnings + }) + } + if (invalidCount > 0) { + throw new Error(s.invalidVolumeData) + } + throw new Error(s.noMountedVolumes) + } + + return { drives, partial, warnings } +} + +/** + * 读取宿主枚举的已挂载卷,不猜测盘符或挂载点(仅在无有效卷时抛错)。 + */ +export async function probeRealDiskDrives(_letters: string[] = [], hostOverride?: unknown): Promise { + const { drives } = await probeRealDiskDrivesWithStatus(_letters, hostOverride) return drives } diff --git a/extensions/shredder/README.en.md b/extensions/shredder/README.en.md new file mode 100644 index 00000000..a88f7b5d --- /dev/null +++ b/extensions/shredder/README.en.md @@ -0,0 +1,21 @@ +# File Shredder + +Select files or folders to import into the shred list, then check and confirm to overwrite file contents multiple times and rename before deleting. + +## Usage + +- Command: `File Shredder`. +- Does not automatically scan any local directories on open; import files to shred via "Select Files" or "Select Folder" in the top bar, drag-and-drop, or paste (selecting a folder recursively collects non-empty regular files while automatically skipping Windows system directories and internal files). +- Use the top dropdown to choose the overwrite method: 3-pass (all zeros, all ones, random; modeled after DoD 5220.22-M), 7-pass (all zeros, all ones, 5 random passes), or 1-pass (all zeros). After overwriting, files are renamed to random filenames before deletion. +- Newly imported files are unchecked by default. Before shredding, a confirmation dialog lists the files to be shredded one by one (noting the remaining count if more than 10); canceling makes no changes. +- Only checked files are processed. Successfully shredded files are removed from the list; if any fail, the dialog reports the success and failure counts along with failure reasons, and failed files remain in the list. +- The action panel supports "Remove from List" (`Ctrl+Backspace`) and "Clear List" (`Ctrl+Shift+Backspace`), which only clear the UI list without deleting files on disk. +- On SSDs, volumes with System Restore points or Volume Shadow Copy snapshots, and copy-on-write filesystems, overwrites may not land on the original physical storage locations, so data irrecoverability cannot be guaranteed. + +## Platforms & Requirements + +- Supported: Windows only + +## Network & Data + +- Offline only; no data is saved. diff --git a/extensions/shredder/plugin.json b/extensions/shredder/plugin.json index b9c50ad6..9a5ab2a9 100644 --- a/extensions/shredder/plugin.json +++ b/extensions/shredder/plugin.json @@ -2,7 +2,7 @@ "id": "shredder", "name": "文件粉碎", "description": "选择文件或文件夹导入待粉碎列表,勾选并确认后多次覆写文件内容再删除", - "version": "2.0.13", + "version": "2.0.14", "author": "ZTools Team", "entry": "dist/index.js", "icon": "icon.svg", @@ -41,7 +41,12 @@ "secure delete", "wipe", "overwrite", - "privacy" + "privacy", + "file shredder", + "permanent delete", + "wipe file", + "erase permanently", + "unrecoverable delete" ], "screenshots": [ { @@ -57,5 +62,15 @@ { "path": "screenshots/02-action-panel.png" } + ], + "keywords": [ + "文件粉碎", + "彻底删除", + "不可恢复删除", + "粉碎文件", + "强力删文件", + "防恢复删除", + "安全删除", + "shred" ] } diff --git a/extensions/shredder/src/i18n.ts b/extensions/shredder/src/i18n.ts index 5fc9b91d..5178dd8f 100644 --- a/extensions/shredder/src/i18n.ts +++ b/extensions/shredder/src/i18n.ts @@ -47,6 +47,8 @@ const MESSAGES = { standardTooltip: "选择覆写方式", pickFilesBtn: "选择文件", pickFolderBtn: "选择文件夹", + shredSelectedBtn: "开始粉碎 ({count})", + shreddingBtn: "粉碎中…", subListTitle: "待粉碎文件 ({count} 项 · 已选 {bytes})", leftSectionTitle: "待粉碎文件", leftSectionSubtitle: "按添加来源筛选", @@ -125,6 +127,8 @@ const MESSAGES = { standardTooltip: "Wipe Method", pickFilesBtn: "Select Files", pickFolderBtn: "Select Folder", + shredSelectedBtn: "Shred ({count})", + shreddingBtn: "Shredding…", subListTitle: "Files to Shred ({count} · Selected {bytes})", leftSectionTitle: "Files to Shred", leftSectionSubtitle: "Filter by source", diff --git a/extensions/shredder/src/index.ts b/extensions/shredder/src/index.ts index 1c35f7b2..e3282d64 100644 --- a/extensions/shredder/src/index.ts +++ b/extensions/shredder/src/index.ts @@ -578,20 +578,39 @@ export function ShredderCommand() { }), filterBar: { summaryText, - actions: [ - { - id: "pick-files", - title: t("pickFilesBtn"), - style: "secondary", - onAction: handlePickFiles - }, - { - id: "pick-folder", - title: t("pickFolderBtn"), - style: "secondary", - onAction: handlePickFolder - } - ] + actions: + selectedItems.length > 0 + ? [ + { + id: "pick-files", + title: t("pickFilesBtn"), + style: "secondary", + onAction: handlePickFiles + }, + { + id: "shred-selected", + title: isShredding ? t("shreddingBtn") : t("shredSelectedBtn", { count: selectedItems.length }), + style: "destructive", + disabled: isShredding, + onAction: () => { + void handleBatchShred(); + } + } + ] + : [ + { + id: "pick-files", + title: t("pickFilesBtn"), + style: "secondary", + onAction: handlePickFiles + }, + { + id: "pick-folder", + title: t("pickFolderBtn"), + style: "secondary", + onAction: handlePickFolder + } + ] }, subList: { title: t("subListTitle", { count: visibleItems.length, bytes: formatBytes(selectedBytes) }), diff --git a/extensions/shredder/src/native-ipc.ts b/extensions/shredder/src/native-ipc.ts index 51576b99..13643277 100644 --- a/extensions/shredder/src/native-ipc.ts +++ b/extensions/shredder/src/native-ipc.ts @@ -174,11 +174,13 @@ function normalizeMethodResult(method: string, payload: DynamicBridge): DynamicB if (method === 'system_get_battery_status') { // 宿主约定 percent 超出 0-100(如 255)表示无电池或电量未知,不能改写成 100% + // 若宿主明确给出 hasBattery 布尔值,必须原样保留,仅在缺失时按合法电量推算 const rawPct = payload.percent - const hasBattery = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const validPct = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const hasBattery = typeof payload.hasBattery === 'boolean' ? payload.hasBattery : validPct return { ...payload, - percent: hasBattery ? rawPct : null, + percent: validPct ? rawPct : null, hasBattery } } @@ -489,6 +491,8 @@ export interface RealDirectoryScanResult extends Iterable approximate?: boolean /** 宿主实际遍历的条目数 */ visitedEntries?: number + /** 目录本身不存在(ENOENT) */ + missing?: boolean /** 读取失败的真实原因;已有文件仍可使用,但不能当作完整结果。 */ error?: string } @@ -497,6 +501,7 @@ interface ScanResultMeta { truncated?: boolean approximate?: boolean visitedEntries?: number + missing?: boolean } export interface ScanDirectoryTreeOptions { @@ -504,6 +509,10 @@ export interface ScanDirectoryTreeOptions { maxFiles?: number collectTopN?: number filterExt?: RegExp + /** 为 true 时,目录本身不存在(ENOENT)按空目录处理,不返回 error(权限拒绝/读取失败仍照常报错) */ + ignoreMissing?: boolean + /** Top-N 保留与排序方式:默认按体积降序,下载/录屏等时效场景可传 mtime-desc */ + sortBy?: 'size-desc' | 'mtime-desc' hostOverride?: DynamicBridge } @@ -519,8 +528,9 @@ function normalizeIndexedFileEntry(f: DynamicBridge): RealIndexedFileEntry { const sz = Number(f?.size ?? f?.sizeBytes ?? 0) const isDir = Boolean(f?.is_dir || f?.isDir || f?.isDirectory) const rawMtime = Number(f?.mtime ?? f?.mtimeMs ?? 0) - const mtimeMs = rawMtime > 1e11 ? rawMtime : rawMtime > 0 ? rawMtime * 1000 : Date.now() - const mtimeSec = rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime + const validMtime = Number.isFinite(rawMtime) && rawMtime > 0 + const mtimeMs = validMtime ? (rawMtime > 1e11 ? rawMtime : rawMtime * 1000) : 0 + const mtimeSec = validMtime ? (rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime) : 0 if (p && sz >= 0) realFileSizeCache.set(p, sz) return { name, @@ -551,6 +561,7 @@ function makeScanResult( subdirs, ...(meta.truncated ? { truncated: true } : {}), ...(meta.approximate ? { approximate: true } : {}), + ...(meta.missing ? { missing: true } : {}), ...(typeof meta.visitedEntries === 'number' ? { visitedEntries: meta.visitedEntries } : {}), [Symbol.iterator]() { return files[Symbol.iterator]() @@ -609,13 +620,40 @@ export async function scanRealDirectoryTree( return result.error ? { ...result.scan, error: result.error } : result.scan } +/** 仅当正则明确声明了扩展名(含 `\.`)时提取后缀列表,避免把 `thumbcache|iconcache` 等文件名关键词误拆成假扩展名 */ +function extractExtensionTokensFromFilter(filterExt: RegExp): string[] { + const src = filterExt.source + if (!src.includes('\\.')) return [] + const afterDot = src.slice(src.indexOf('\\.') + 2) + const rawTokens = afterDot.match(/[a-z0-9]{1,8}/gi) || [] + const seen = new Set() + const out: string[] = [] + for (const token of rawTokens) { + const lower = token.toLowerCase() + if (!lower || seen.has(lower)) continue + seen.add(lower) + out.push(lower) + } + return out +} + +function isMissingDirectoryError(res: { error?: string; errorCode?: string; errorDetails?: Record }): boolean { + if (res.errorDetails?.reason === 'ENOENT' || res.errorCode === 'ENOENT') return true + const msg = String(res.error || '') + return /Directory does not exist|ENOENT/i.test(msg) +} + /** 一次界面扫描的错误汇总;多个目录并行扫描时保留可读目录的结果。 */ export function createDirectoryScanner(hostOverride?: DynamicBridge) { const failures = new Map() return { async scan(dir: string, options: number | ScanDirectoryTreeOptions = 160) { const result = await scanRealDirectoryTree(dir, options, hostOverride) - const error = result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') + const ignoreMissing = typeof options === 'object' && options !== null && options.ignoreMissing === true + const error = + result.missing && ignoreMissing + ? '' + : result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') if (error) failures.set(dir, error) else failures.delete(dir) return result @@ -648,26 +686,38 @@ async function scanDirectoryTreeWithError( const safeLimit = Math.min(200, Math.max(1, Math.floor(rawLimit || 160))) const hostOverride = opts.hostOverride const filterExt = opts.filterExt + const ignoreMissing = opts.ignoreMissing === true const dirQuery = `dir:${targetDir}` try { let rawPayload: DynamicBridge = null + const searchParams: Record = { + query: dirQuery, + limit: safeLimit, + ...(opts.sortBy ? { sortBy: opts.sortBy } : {}) + } const res = await callHostTransport( 'system_search_files', - { query: dirQuery, limit: safeLimit }, + searchParams, hostOverride ) - if (res.ok && res.data) { + if (res.ok && res.data && res.data.degraded !== true) { rawPayload = res.data + } else if (!res.ok && ignoreMissing && isMissingDirectoryError(res)) { + const missingScan = makeScanResult([], 0, 0, [], { missing: true }) + return { scan: missingScan } } - if (!rawPayload && !hostOverride && typeof window !== 'undefined') { + if (!rawPayload && !hostOverride && res.errorCode === 'METHOD_NOT_AVAILABLE' && typeof window !== 'undefined') { const w = window as DynamicBridge if (typeof w.__ztoolsLauncher?.searchFiles === 'function') { const rawOuter = await w.__ztoolsLauncher.searchFiles(dirQuery, safeLimit) - rawPayload = + const candidate = rawOuter && typeof rawOuter === 'object' && 'data' in rawOuter && rawOuter.data ? rawOuter.data : rawOuter + if (candidate && candidate.degraded !== true && candidate.success !== false) { + rawPayload = candidate + } } } @@ -678,29 +728,32 @@ async function scanDirectoryTreeWithError( let files: RealIndexedFileEntry[] = rawPayload.files.map(normalizeIndexedFileEntry) if (filterExt instanceof RegExp) { files = files.filter(f => !f.isDir && (filterExt.test(f.name) || filterExt.test(f.ext))) - // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索目标扩展名 + // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索明确声明的目标扩展名 if (files.length === 0 && !hostOverride) { - const extTokens = (filterExt.source.match(/[a-z0-9]{2,5}/gi) || []) - .filter(t => !['thumbcache', 'iconcache'].includes(t.toLowerCase())) - .slice(0, 4) - // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 - const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() - const extraLists = await Promise.all( - extTokens.map(ext => searchRealIndexedFiles(`.${ext.toLowerCase()}`, 30, hostOverride)) - ) - const seen = new Set() - for (const list of extraLists) { - for (const item of list) { - if (!item.isDir && item.size > 0 && !seen.has(item.path)) { - if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { - seen.add(item.path) - files.push(item) + const extTokens = extractExtensionTokensFromFilter(filterExt) + if (extTokens.length > 0) { + // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 + const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() + const extraLists = await Promise.all( + extTokens.map(ext => searchRealIndexedFiles(`.${ext}`, 30, hostOverride)) + ) + const seen = new Set() + for (const list of extraLists) { + for (const item of list) { + if (!item.isDir && item.size > 0 && !seen.has(item.path)) { + if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { + seen.add(item.path) + files.push(item) + } } } } } } } + // 先基于过滤后的完整命中集合计算总文件数与总字节数,再按 collectTopN 裁剪样本列表 + const matchedCount = files.length + const matchedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) if (typeof opts.collectTopN === 'number' && opts.collectTopN > 0 && files.length > opts.collectTopN) { files = files.slice(0, opts.collectTopN) } @@ -714,11 +767,10 @@ async function scanDirectoryTreeWithError( ...(s.approximate === true ? { approximate: true } : {}) })) : [] - const computedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) const totalFilesCount = - filterExt instanceof RegExp ? files.length : Number(rawPayload.total_matches ?? files.length) + filterExt instanceof RegExp ? matchedCount : Number(rawPayload.total_matches ?? matchedCount) const totalBytesCount = - filterExt instanceof RegExp ? computedBytes : Number(rawPayload.total_bytes ?? computedBytes) + filterExt instanceof RegExp ? matchedBytes : Number(rawPayload.total_bytes ?? matchedBytes) const visited = Number(rawPayload.visited_entries) return { scan: makeScanResult(files, totalFilesCount, totalBytesCount, subdirs, { @@ -1817,8 +1869,6 @@ export async function writeRealClipboardText(text: string, hostOverride?: Dynami const payload = { text: String(text || '') } const res = await callHostTransport('clipboard_copy_text', payload, hostOverride) if (res.ok) return true - const fallbackRes = await callHostTransport('clipboard_write_text', payload, hostOverride) - if (fallbackRes.ok) return true try { if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) { await navigator.clipboard.writeText(String(text || '')) diff --git a/extensions/shutdown-timer/README.en.md b/extensions/shutdown-timer/README.en.md new file mode 100644 index 00000000..58e1c33e --- /dev/null +++ b/extensions/shutdown-timer/README.en.md @@ -0,0 +1,21 @@ +# Shutdown Timer + +Lists preset power actions: shut down after 10, 30, 60, or 120 minutes, lock screen immediately, sleep immediately, and copy the command to cancel a scheduled shutdown. + +## Usage + +- Commands: `shutdown` (also `shutdown timer`, `auto shutdown`, `delayed shutdown`), `lock screen`, `sleep now`, and `cancel shutdown` all open the same list. +- Scheduled shutdown: Select a duration and press `Enter`; after confirmation, the client schedules the shutdown and displays the estimated shutdown time. When the timer expires, the system closes all programs and unsaved work may be lost. Press `Ctrl+Enter` to copy the equivalent system command (such as `shutdown.exe /s /t 600`). +- If a shutdown is already scheduled, setting another one will fail and display the reason; cancel the existing schedule first. +- Lock screen immediately / Sleep immediately: Press `Enter` to execute directly without confirmation. +- Cancel scheduled shutdown: The client does not provide a cancel API, so the plugin cannot cancel it directly. Press `Enter` on "Cancel Scheduled Shutdown" to copy `shutdown.exe /a`, then paste and run it in Command Prompt. +- Only fixed preset durations are available; custom countdowns, specific clock times, and scheduled restarts are not supported. +- When execution fails, the reason returned by the client is shown rather than reporting success. + +## Platforms & Requirements + +- Supported: Windows only + +## Network & Data + +- Offline only; no data is saved. diff --git a/extensions/shutdown-timer/plugin.json b/extensions/shutdown-timer/plugin.json index e1773c33..814ca844 100644 --- a/extensions/shutdown-timer/plugin.json +++ b/extensions/shutdown-timer/plugin.json @@ -3,6 +3,9 @@ "name": "定时关机", "description": "按预设倒计时(10、30、60、120 分钟)自动关机,或立即锁屏、睡眠,设定关机前会先确认;插件不能取消已设定的关机,可复制取消命令自行运行", "version": "1.0.8", + "minAppVersion": "1.1.8.0", + "revoked": true, + "revokedReason": "功能已合并至「系统工具」(system-tools),请改用系统工具", "author": "ZTools Team", "entry": "dist/index.js", "icon": "icon.svg", @@ -29,7 +32,11 @@ "取消关机", "睡眠", "锁屏", - "shutdown" + "shutdown", + "延迟关机", + "定时重启", + "几分钟后关机", + "睡眠定时" ], "features": [ { @@ -66,13 +73,21 @@ "en-US": { "name": "Shutdown Timer", "description": "Schedule automatic shutdown (10, 30, 60, or 120 minutes) after confirmation, or lock/sleep immediately, with a copyable cancel command.", + "revokedReason": "Merged into \"System Commands\" (system-tools). Please use System Commands instead.", "keywords": [ "shutdown", "timer", "sleep", "lock", "power", - "schedule" + "schedule", + "shutdown timer", + "auto shutdown", + "schedule shutdown", + "restart timer", + "sleep timer", + "cancel shutdown", + "power off" ], "features": { "timer-shutdown": { diff --git a/extensions/snippets/README.en.md b/extensions/snippets/README.en.md new file mode 100644 index 00000000..bfd25669 --- /dev/null +++ b/extensions/snippets/README.en.md @@ -0,0 +1,21 @@ +# Text Snippets + +Save frequently used text templates (billing info, addresses, replies, code snippets, etc.) and paste them directly into the active input field or copy them, with support for date, time, and clipboard variables. + +## Usage + +- Commands: `snippets` (also `templates`, `quick text`, `canned replies`); open by category: `billing info`, `shipping address`; create new: `add snippet` / `new snippet`. +- The list starts empty. Use "New Snippet" at the top to add a title, category (General Snippets, Invoice & Billing Info, Addresses & Contacts, Customer Support & Business Replies, Development & Code Snippets), optional trigger abbreviation, and content. +- Supported variables in content: `{date}` (YYYY-MM-DD), `{time}` (HH:mm:ss), `{datetime}`, and `{clipboard}` (current clipboard text, up to 32,768 characters). Legacy `{cursor}` tokens in existing snippets are removed and do not move the cursor, so it is no longer listed in the creation form. +- Select a snippet and press `Enter` to paste it into the previous input field, `⌘/Ctrl+Enter` to copy the resolved text, `⌘/Ctrl+E` to edit, and `⌘/Ctrl+Backspace` to delete (requires confirmation and cannot be undone; when the search box contains text, this shortcut deletes text in the input box instead). +- Trigger abbreviations are used only for searching within the list and do not auto-expand in other applications. +- On macOS, automatic pasting requires granting ZTools Accessibility permission in "System Settings > Privacy & Security > Accessibility"; otherwise pasting reports a failure. + +## Platforms & Requirements + +- Supported: Windows, macOS +- Requires ZTools client 1.1.8.3 or later. + +## Network & Data + +- Offline only; data is stored locally only. diff --git a/extensions/snippets/plugin.json b/extensions/snippets/plugin.json index e33fe536..ccdb4519 100644 --- a/extensions/snippets/plugin.json +++ b/extensions/snippets/plugin.json @@ -1,7 +1,7 @@ { "id": "snippets", "name": "快捷短语", - "version": "1.2.10", + "version": "1.2.11", "minAppVersion": "1.1.8.3", "description": "管理常用开票税号、收件地址、客服话术与常用模板,支持动态日期/时间/剪贴板宏变量,一键穿透上屏或复制", "author": "ZTools Team", @@ -87,7 +87,11 @@ "templates", "text expander", "macros", - "replies" + "replies", + "canned responses", + "quick text", + "boilerplate", + "paste template" ], "features": { "snippets-all": { @@ -138,5 +142,17 @@ { "path": "screenshots/02-action-panel.png" } + ], + "keywords": [ + "快捷短语", + "常用语", + "文本片段", + "开票信息", + "常用地址", + "一键粘贴", + "话术模板", + "快速输入", + "自动填充", + "snippets" ] } diff --git a/extensions/snippets/src/i18n.ts b/extensions/snippets/src/i18n.ts index d31883c4..f8da894e 100644 --- a/extensions/snippets/src/i18n.ts +++ b/extensions/snippets/src/i18n.ts @@ -49,6 +49,7 @@ const rawT = createTranslator( emptyNoMatchSubtitle: "换个关键词或分类,也可以按回车新建短语", keywordTag: "缩写: {keyword}", useCountText: "使用 {count} 次", + metaUseCount: "使用次数", pasteAction: "直接上屏粘贴", copyAction: "复制解析后的文本", editAction: "编辑短语", @@ -106,6 +107,7 @@ const rawT = createTranslator( emptyNoMatchSubtitle: "Try another keyword or category, or press Enter to create one", keywordTag: "Key: {keyword}", useCountText: "Used {count}x", + metaUseCount: "Usage", pasteAction: "Paste Directly", copyAction: "Copy Resolved Text", editAction: "Edit Snippet", diff --git a/extensions/snippets/src/index.tsx b/extensions/snippets/src/index.tsx index 31a0fa53..7e7f386f 100644 --- a/extensions/snippets/src/index.tsx +++ b/extensions/snippets/src/index.tsx @@ -30,6 +30,13 @@ import { t } from './i18n.js' export * from './types.js' export * from './macro-engine.js' +function fencedBlock(content: string): string { + const runs = String(content).match(/`+/g) || [] + const longest = runs.reduce((max, run) => Math.max(max, run.length), 0) + const fence = '`'.repeat(Math.max(3, longest + 1)) + return `${fence}text\n${content}\n${fence}` +} + function getCategoryIcon(category: SnippetCategory): Icon { switch (category) { case 'invoice': @@ -75,8 +82,16 @@ export function SnippetEditForm({ initialData, onSave }: SnippetEditFormProps) { }) return } - await onSave(payload, initialData) - pop() + try { + await onSave(payload, initialData) + pop() + } catch (error) { + await showToast({ + style: Toast.Style.Failure, + title: t('cannotSaveTitle'), + message: error instanceof Error ? error.message : String(error) + }) + } }, [initialData, title, category, keyword, content, onSave, pop]) return ( @@ -94,6 +109,7 @@ export function SnippetEditForm({ initialData, onSave }: SnippetEditFormProps) { value={title} onChange={setTitle} placeholder={t('fieldTitlePlaceholder')} + autoFocus={true} /> + push()} + /> + + } searchBarAccessory={ { setCategoryFilter(value); setSearchText('') }} + onChange={(value) => setCategoryFilter(value)} tooltip={t('filterTooltip')} > @@ -310,7 +337,12 @@ export function Snippets({ featureCode = 'snippets-all', initialSnippets }: Snip subtitle={snippets.length === 0 ? t('emptyNoSnippetsSubtitle') : t('emptyNoMatchSubtitle')} actions={ - push()} /> + push()} + /> } /> @@ -326,6 +358,26 @@ export function Snippets({ featureCode = 'snippets-all', initialSnippets }: Snip { tag: item.keyword ? t('keywordTag', { keyword: item.keyword }) : getSnippetCategoryLabel(item.category) }, { text: t('useCountText', { count: item.useCount || 0 }) } ]} + detail={ + + + {item.keyword ? ( + + ) : null} + + + } + /> + } actions={ handleUseSnippet(item, false)} - shortcut={{ modifiers: ['ctrl'], key: 'enter' }} + shortcut={{ modifiers: ['ctrl'], key: 'return' }} /> ) } /> + push()} + /> { +test('分类快捷入口筛选正确,分类切换保留旧查询,取消新建不写数据', async () => { for (const category of ['invoice', 'address']) { const host = createHost() seed(host, [fixture('发票', 'invoice'), fixture('地址', 'address')]) @@ -117,7 +119,8 @@ test('分类快捷入口筛选正确,分类切换清掉旧查询,取消新 assert.equal(view.tree().props.searchBarAccessory.props.value, category) assert.equal(view.items().length, 1) await view.search('无结果'); await view.dropdown('all') - assert.equal(view.tree().props.searchText, '') + assert.equal(view.tree().props.searchText, '无结果') + await view.search('') assert.equal(view.items().length, 2) } finally { view.unmount() } } @@ -182,7 +185,9 @@ test('另一窗口修改或删除条目后,旧编辑表单和删除动作拒 const next = change === 'edit' ? [{ ...original, content: '另一窗口修改', updatedAt: 100 }] : [] seed(host, next) if (form) { - await assert.rejects(form.run(null, '保存短语'), /其他窗口修改或删除/) + await form.run(null, '保存短语') + assert.equal(host.lastToast().style, 'FAILURE') + assert.match(host.lastToast().message, /其他窗口修改或删除/) assert.equal(form.field('content').props.value, '旧表单未保存的文字') assert.equal(host.pushed.length, 1) } else await assert.rejects(view.run(view.item('待操作'), '删除短语'), /其他窗口修改或删除/) diff --git a/extensions/software-manager/README.en.md b/extensions/software-manager/README.en.md new file mode 100644 index 00000000..2d091c40 --- /dev/null +++ b/extensions/software-manager/README.en.md @@ -0,0 +1,21 @@ +# Software Uninstaller + +List installed applications registered by the system and launch their built-in uninstallers, plus view AppData directory disk usage in read-only mode. + +## Usage + +- Commands: `uninstall` (also `software manager`, `remove apps`, `installed apps`) and `large apps` (also `big software`, `app disk usage`). Both commands open the same view, sorted by registered disk usage from largest to smallest. +- The left sidebar groups apps into 8 categories by name (unmatched items go under "Other"), and the top dropdown filters by installation drive letter. Disk usage comes from estimated sizes registered by each application and may be missing or inaccurate; unregistered version, publisher, size, and install location values are shown as Unknown. +- If the system-registered software list cannot be read, the status bar shows the failure reason instead of guessing installed applications by other means. +- Select an application and press `Enter` to uninstall: the confirmation dialog displays the uninstall command to run, and confirming launches the application's built-in uninstaller ("Uninstaller launched" indicates only that it was started; actual completion depends on the uninstaller wizard). Press `Ctrl+Enter` to locate the installation folder in File Explorer (not available when no install directory is registered). `Ctrl+K` includes launching the app, copying the uninstall command line, and more. +- Some core system components cannot be uninstalled; an additional warning is displayed before uninstalling system runtimes. +- "AppData Folders" on the left: read-only listing of the top 12 folders by size under `%APPDATA%` and `%LOCALAPPDATA%`, roughly matched by folder name against installed application names and labeled as "similar name" or "no matching installed app" (matching may be imprecise). Deletion is not provided here; press `Enter` to locate the folder in File Explorer or `Ctrl+Enter` to copy the folder path. + +## Platforms & Requirements + +- Supported: Windows only +- Windows implementation is pending verification on a physical machine. + +## Network & Data + +- Offline only; no data is saved. diff --git a/extensions/software-manager/plugin.json b/extensions/software-manager/plugin.json index 35952d1b..b79f8690 100644 --- a/extensions/software-manager/plugin.json +++ b/extensions/software-manager/plugin.json @@ -2,7 +2,8 @@ "id": "software-manager", "name": "软件卸载", "description": "列出系统登记的已安装软件与占用体积,确认后启动软件自带的卸载程序,并只读列出 AppData 目录占用", - "version": "2.0.12", + "version": "2.0.13", + "minAppVersion": "1.1.8.0", "author": "ZTools Team", "entry": "dist/index.js", "icon": "icon.svg", @@ -16,7 +17,11 @@ "卸载软件", "应用管理", "已安装软件", - "uninstall" + "uninstall", + "删软件", + "卸程序", + "控制面板卸载", + "已装软件" ], "features": [ { @@ -67,7 +72,12 @@ "apps", "programs", "appdata", - "cleanup" + "cleanup", + "uninstaller", + "software manager", + "remove app", + "installed apps", + "delete software" ], "features": { "uninstall-all": { diff --git a/extensions/software-manager/src/host-ipc.ts b/extensions/software-manager/src/host-ipc.ts new file mode 100644 index 00000000..ed9d0e54 --- /dev/null +++ b/extensions/software-manager/src/host-ipc.ts @@ -0,0 +1,404 @@ +/** + * software-manager 专用精简宿主 IPC 封装层。 + * + * 仅提供软件列表查询、卸载程序启动、AppData 只读目录扫描与系统路径/定位能力, + * 不包含任何原生 DLL 扩展调用入口。 + */ + +import { getHostTransport } from '@ztools/declarative-ui' + +export interface HostIpcResult { + ok: boolean + data?: T + error?: string + errorCode?: string + errorDetails?: Record +} + +export interface ScanDirectoryTreeOptions { + hostOverride?: unknown + filterExt?: RegExp + collectTopN?: number + maxFiles?: number + maxDepth?: number +} + +export type RealDirectorySubdirSummary = { + path: string + name: string + totalBytes: number + fileCount: number + mtime: number + approximate?: boolean +} + +export type RealIndexedFileEntry = { + path: string + name: string + isDirectory: boolean + isDir: boolean + sizeBytes: number + size: number + ext: string + lastModifiedMs: number + mtimeMs: number + mtime: number +} + +export type RealDirectoryScanResult = Iterable & { + subdirs: RealDirectorySubdirSummary[] + files: RealIndexedFileEntry[] + totalBytes: number + fileCount: number + totalFiles: number + visitedEntries?: number + approximate?: boolean + truncated?: boolean + error?: string +} + +type MethodFn = (req: { messageId: string; params: Record }) => Promise + +interface RendererBridgeWindow { + __ztoolsElectron?: { transport?: { methods?: Record } } + __ztoolsLauncher?: { searchFiles?: (query: string, limit: number) => Promise } + ztools?: { + transport?: { + methods?: Record + call?: (method: string, params: Record) => Promise + } + } +} + +let seqCounter = 1 + +function isPlainRecord(val: unknown): val is Record { + return Boolean(val) && typeof val === 'object' && !Array.isArray(val) +} + +function getFallbackIpcCode(kind: 'outer' | 'inner'): string { + return kind === 'outer' ? 'IPC_CALL_FAILED' : 'IPC_INNER_FAILED' +} + +function readErrorMetadata(source: unknown): Pick { + if (!isPlainRecord(source)) return {} + const rawCode = typeof source.errorCode === 'string' ? source.errorCode : typeof source.code === 'string' ? source.code : '' + const code = rawCode.trim() || undefined + const details = isPlainRecord(source.errorDetails) + ? source.errorDetails + : isPlainRecord(source.details) + ? source.details + : undefined + return { ...(code ? { errorCode: code } : {}), ...(details ? { errorDetails: details } : {}) } +} + +function parseFailurePayload(rec: Record, kind: 'outer' | 'inner'): HostIpcResult { + const errField = rec.error + const message = isPlainRecord(errField) + ? String(errField.message || errField.code || JSON.stringify(errField)) + : String(errField || getFallbackIpcCode(kind)) + return { ok: false, error: message, ...readErrorMetadata(rec), ...readErrorMetadata(errField) } +} + +function decodeTransportPayload(raw: unknown): HostIpcResult { + if (raw === null || raw === undefined) { + return { ok: false, error: 'EMPTY_IPC_RESPONSE', errorCode: 'EMPTY_IPC_RESPONSE' } + } + if (!isPlainRecord(raw)) return { ok: true, data: raw as T } + if (raw.success === false) return parseFailurePayload(raw, 'outer') + + const unwrapped = 'data' in raw && raw.data !== undefined ? raw.data : raw + if (isPlainRecord(unwrapped)) { + if (unwrapped.success === false) return parseFailurePayload(unwrapped, 'inner') + if ('data' in unwrapped && unwrapped.data !== undefined) { + return { ok: true, data: unwrapped.data as T } + } + } + return { ok: true, data: unwrapped as T } +} + +function formatThrownError(err: unknown): HostIpcResult { + return { + ok: false, + error: err instanceof Error ? err.message : String(err), + ...readErrorMetadata(err) + } +} + +/** 判断当前是否处于真实的 Electron 客户端渲染进程中 */ +export function isRealElectronHost(hostOverride?: unknown): boolean { + if (hostOverride) return false + if (typeof getHostTransport === 'function' && getHostTransport()) return true + if (typeof window === 'undefined') return false + const bridge = window as unknown as RendererBridgeWindow + return Boolean( + bridge.__ztoolsElectron?.transport?.methods || + bridge.ztools?.transport?.call || + bridge.ztools?.transport?.methods + ) +} + +/** 通过宿主标准通道执行单次 IPC 请求并做双层响应解包 */ +export async function callHostTransport( + method: string, + params: Record = {}, + hostOverride?: unknown +): Promise> { + const payload = isPlainRecord(params) ? { ...params } : {} + + if (isPlainRecord(hostOverride)) { + const direct = hostOverride[method] + if (typeof direct === 'function') { + try { + return decodeTransportPayload(await (direct as (p: Record) => Promise)(payload)) + } catch (err) { + return formatThrownError(err) + } + } + const stubTransport = isPlainRecord(hostOverride.transport) ? hostOverride.transport : null + if (stubTransport && typeof stubTransport.call === 'function') { + try { + const res = await (stubTransport.call as (m: string, p: Record) => Promise)(method, payload) + return decodeTransportPayload(res) + } catch (err) { + return formatThrownError(err) + } + } + } + + if (typeof getHostTransport === 'function') { + const activeTransport = getHostTransport() + if (activeTransport) { + try { + return decodeTransportPayload(await activeTransport.call(method, payload)) + } catch (err) { + return formatThrownError(err) + } + } + } + + if (typeof window === 'undefined') { + return { ok: false, error: 'NO_WINDOW_ENV', errorCode: 'NO_WINDOW_ENV' } + } + + const bridge = window as unknown as RendererBridgeWindow + const methodTable = bridge.__ztoolsElectron?.transport?.methods || bridge.ztools?.transport?.methods + const targetMethod = methodTable?.[method] + if (typeof targetMethod === 'function') { + try { + seqCounter = (seqCounter + 1) % 1_000_000 + const cleanTag = method.replace(/[^A-Za-z0-9_]/g, '_').slice(0, 24) + const messageId = `${cleanTag}_${Date.now()}_${seqCounter}` + return decodeTransportPayload(await targetMethod({ messageId, params: payload })) + } catch (err) { + return formatThrownError(err) + } + } + + if (typeof bridge.ztools?.transport?.call === 'function') { + try { + return decodeTransportPayload(await bridge.ztools.transport.call(method, payload)) + } catch (err) { + return formatThrownError(err) + } + } + + return { ok: false, error: `METHOD_NOT_AVAILABLE: ${method}`, errorCode: 'METHOD_NOT_AVAILABLE' } +} + +/** 读取系统标准目录路径,并在非 home 目录缺失时从 home 派生标准路径 */ +export async function getRealSystemPath( + name: 'home' | 'appData' | 'userData' | 'desktop' | 'documents' | 'downloads' | 'music' | 'pictures' | 'videos' | 'temp' | 'cache', + hostOverride?: unknown +): Promise { + const res = await callHostTransport('system_get_path', { name }, hostOverride) + if (res.ok && res.data) { + if (typeof res.data === 'string' && res.data.trim()) return res.data.trim() + if (isPlainRecord(res.data) && typeof res.data.path === 'string' && res.data.path.trim()) { + return res.data.path.trim() + } + } + if (name === 'home') return '' + + const home = await getRealSystemPath('home', hostOverride) + if (!home) return '' + const posix = home.startsWith('/') + const winSub: Record = { + appData: `${home}\\AppData\\Roaming`, + userData: `${home}\\AppData\\Roaming\\ZTools`, + temp: `${home}\\AppData\\Local\\Temp`, + cache: `${home}\\AppData\\Local` + } + const macSub: Record = { + appData: `${home}/Library/Application Support`, + userData: `${home}/Library/Application Support/ZTools`, + temp: '/tmp', + cache: `${home}/Library/Caches` + } + if (posix) { + return macSub[name] ?? `${home}/${name[0].toUpperCase()}${name.slice(1)}` + } + return winSub[name] ?? `${home}\\${name[0].toUpperCase()}${name.slice(1)}` +} + +function buildFileEntry(raw: Record): RealIndexedFileEntry { + const fullPath = String(raw.path ?? '') + const fileName = String(raw.name || fullPath.split(/[\\/]/).pop() || '') + const dotPos = fileName.lastIndexOf('.') + const ext = dotPos > 0 ? fileName.slice(dotPos).toLowerCase() : '' + const size = Math.max(0, Number(raw.size ?? raw.sizeBytes ?? 0) || 0) + const isDir = Boolean(raw.is_dir || raw.isDir || raw.isDirectory) + const rawTime = Number(raw.mtime ?? raw.mtimeMs ?? 0) + const mtimeMs = rawTime > 1e11 ? rawTime : rawTime > 0 ? rawTime * 1000 : Date.now() + const mtimeSec = rawTime > 1e11 ? Math.floor(rawTime / 1000) : rawTime + return { + name: fileName, + path: fullPath, + ext, + isDir, + isDirectory: isDir, + size, + sizeBytes: size, + mtime: mtimeSec, + mtimeMs, + lastModifiedMs: mtimeMs + } +} + +function createScanBundle( + files: RealIndexedFileEntry[], + totalFiles: number, + totalBytes: number, + subdirs: RealDirectorySubdirSummary[], + extra: { truncated?: boolean; approximate?: boolean; visitedEntries?: number; error?: string } = {} +): RealDirectoryScanResult { + return { + files, + totalFiles, + fileCount: totalFiles, + totalBytes, + subdirs, + ...(extra.truncated ? { truncated: true } : {}), + ...(extra.approximate ? { approximate: true } : {}), + ...(typeof extra.visitedEntries === 'number' ? { visitedEntries: extra.visitedEntries } : {}), + ...(extra.error ? { error: extra.error } : {}), + [Symbol.iterator]() { + return files[Symbol.iterator]() + } + } +} + +/** 通过索引通道只读扫描目录树统计信息(AppData 体积展示专用) */ +export async function scanRealDirectoryTree( + dirPath: string, + limitOrOptions: number | ScanDirectoryTreeOptions = 160, + hostOverrideArg?: unknown +): Promise { + const target = String(dirPath || '').trim() + if (!target) return createScanBundle([], 0, 0, [], { error: 'EMPTY_DIRECTORY_PATH' }) + + const opts: ScanDirectoryTreeOptions = + typeof limitOrOptions === 'number' + ? { maxFiles: limitOrOptions, hostOverride: hostOverrideArg } + : { ...limitOrOptions, hostOverride: limitOrOptions?.hostOverride ?? hostOverrideArg } + + const limit = Math.min(200, Math.max(1, Math.floor(opts.maxFiles ?? opts.collectTopN ?? 160))) + const query = `dir:${target}` + + let payload: Record | null = null + const res = await callHostTransport('system_search_files', { query, limit }, opts.hostOverride) + if (res.ok && isPlainRecord(res.data)) { + payload = res.data + } else if (!opts.hostOverride && typeof window !== 'undefined') { + const launcher = (window as unknown as RendererBridgeWindow).__ztoolsLauncher + if (typeof launcher?.searchFiles === 'function') { + try { + const raw = await launcher.searchFiles(query, limit) + const inner = isPlainRecord(raw) && isPlainRecord(raw.data) ? raw.data : raw + if (isPlainRecord(inner)) payload = inner + } catch (err) { + void err + } + } + } + + if (!payload || !Array.isArray(payload.files)) { + return createScanBundle([], 0, 0, [], { error: res.error || 'DIRECTORY_READ_FAILED' }) + } + + let files = payload.files + .filter(isPlainRecord) + .map(buildFileEntry) + if (opts.filterExt instanceof RegExp) { + const re = opts.filterExt + files = files.filter((item) => !item.isDir && (re.test(item.name) || re.test(item.ext))) + } + if (typeof opts.collectTopN === 'number' && opts.collectTopN > 0 && files.length > opts.collectTopN) { + files = files.slice(0, opts.collectTopN) + } + + const subdirs: RealDirectorySubdirSummary[] = Array.isArray(payload.subdirs) + ? payload.subdirs.filter(isPlainRecord).map((sub) => ({ + name: String(sub.name ?? ''), + path: String(sub.path ?? ''), + fileCount: Number(sub.file_count ?? sub.fileCount ?? 0) || 0, + totalBytes: Number(sub.total_bytes ?? sub.totalBytes ?? 0) || 0, + mtime: Number(sub.mtime ?? 0) || 0, + ...(sub.approximate === true ? { approximate: true } : {}) + })) + : [] + + const sumFileBytes = files.reduce((acc, item) => acc + (item.isDir ? 0 : item.size), 0) + const totalFiles = opts.filterExt instanceof RegExp ? files.length : Number(payload.total_matches ?? files.length) + const totalBytes = opts.filterExt instanceof RegExp ? sumFileBytes : Number(payload.total_bytes ?? sumFileBytes) + const visited = Number(payload.visited_entries) + + return createScanBundle(files, totalFiles, totalBytes, subdirs, { + truncated: payload.truncated === true, + approximate: payload.approximate === true, + ...(Number.isFinite(visited) && visited >= 0 ? { visitedEntries: visited } : {}), + ...(typeof payload.scan_error === 'string' && payload.scan_error ? { error: payload.scan_error } : {}) + }) +} + +/** 列出指定目录下的子目录与直接文件(只读) */ +export async function readRealDirectory( + dirPath: string, + hostOverride?: unknown +): Promise { + if (!dirPath) return [] + const tree = await scanRealDirectoryTree(dirPath, { maxFiles: 120, hostOverride }) + const dirEntries = tree.subdirs.map((sub) => + buildFileEntry({ + name: sub.name, + path: sub.path, + isDir: true, + isDirectory: true, + size: sub.totalBytes, + mtime: sub.mtime + }) + ) + return [...dirEntries, ...tree.files] +} + +/** 在资源管理器 / 访达中定位目标文件或目录 */ +export async function showRealItemInFolder(fullPath: string, hostOverride?: unknown): Promise { + if (!fullPath) return false + const res = await callHostTransport('shell_show_item_in_folder', { fullPath }, hostOverride) + return res.ok +} + +/** 使用系统默认应用打开目标路径 */ +export async function openRealPath(fullPath: string, hostOverride?: unknown): Promise { + if (!fullPath) return false + const res = await callHostTransport('shell_open_path', { fullPath }, hostOverride) + return res.ok +} + +/** 拼接 Windows 风格路径片段 */ +export function joinWinPath(...segments: string[]): string { + return segments + .filter((seg) => typeof seg === 'string' && seg.trim().length > 0) + .map((seg, idx) => (idx === 0 ? seg.replace(/[\\/]+$/, '') : seg.replace(/^[\\/]+|[\\/]+$/g, ''))) + .join('\\') +} diff --git a/extensions/software-manager/src/index.ts b/extensions/software-manager/src/index.ts index 53082a94..5d2a4a75 100644 --- a/extensions/software-manager/src/index.ts +++ b/extensions/software-manager/src/index.ts @@ -38,7 +38,7 @@ import { filterSoftwareList } from './logic.js' -import { isRealElectronHost } from './native-ipc.js' +import { isRealElectronHost } from './host-ipc.js' import { resolveErrorMessage } from './error-i18n.js' export default function SoftwareManagerCommand() { diff --git a/extensions/software-manager/src/logic.ts b/extensions/software-manager/src/logic.ts index b8f775d8..2695bfca 100644 --- a/extensions/software-manager/src/logic.ts +++ b/extensions/software-manager/src/logic.ts @@ -15,10 +15,9 @@ import { isRealElectronHost, joinWinPath, openRealPath, - readRealDirectory, scanRealDirectoryTree, showRealItemInFolder -} from './native-ipc.js' +} from './host-ipc.js' import { resolveErrorMessage } from './error-i18n.js' export const getNotInClientMessage = (): string => t('notInClient') @@ -123,6 +122,8 @@ export interface AppDataDirItem { scope: 'AppData\\Roaming' | 'AppData\\Local' sizeBytes: number fileCount: number + /** 目录体积是否为截断估算下限 */ + approximate?: boolean /** 目录名与之相近的已安装软件(按名称粗略比对,可能不准) */ similarSoftwareName?: string } @@ -136,6 +137,8 @@ export interface SoftwareListResult { export interface AppDataScanResult { ok: boolean items: AppDataDirItem[] + /** 扫描是否触发宿主截断或估算近似 */ + approximate?: boolean error?: string } @@ -410,32 +413,54 @@ export async function probeAppDataDirs(softwareList: SoftwareItem[], host?: unkn } const results: AppDataDirItem[] = [] + const scanErrors: string[] = [] + let anyApproximate = false await Promise.all( roots.map(async (root) => { - const entries = await readRealDirectory(root.path, host) - const dirs = entries - .filter((e) => e.isDirectory && !e.name.startsWith('.') && !PROTECTED_APPDATA_DIRS.has(e.name.toLowerCase())) + const tree = await scanRealDirectoryTree(root.path, { maxFiles: 120, hostOverride: host }) + if (tree.error) { + scanErrors.push(`${root.scope}: ${tree.error}`) + } + if (tree.approximate || tree.truncated) { + anyApproximate = true + } + // 直接复用首次扫描返回的 subdirs 汇总,消除对子目录的重复二次 dir: 扫描 + const dirs = tree.subdirs + .filter((sub) => sub.name && !sub.name.startsWith('.') && !PROTECTED_APPDATA_DIRS.has(sub.name.toLowerCase())) .slice(0, 12) - await Promise.all( - dirs.map(async (dir) => { - const fullPath = dir.path || joinWinPath(root.path, dir.name) - const stats = await scanRealDirectoryTree(fullPath, { maxFiles: 120, collectTopN: 5, hostOverride: host }) - if (stats.totalBytes <= 64 * 1024) return - results.push({ - id: `appdata-${root.scope}-${dir.name}`, - folderName: dir.name, - fullPath, - scope: root.scope, - sizeBytes: stats.totalBytes, - fileCount: stats.fileCount, - similarSoftwareName: findSimilarSoftware(dir.name, softwareList)?.name - }) + for (const sub of dirs) { + if (sub.totalBytes <= 64 * 1024) continue + if (sub.approximate) anyApproximate = true + const fullPath = sub.path || joinWinPath(root.path, sub.name) + results.push({ + id: `appdata-${root.scope}-${sub.name}`, + folderName: sub.name, + fullPath, + scope: root.scope, + sizeBytes: sub.totalBytes, + fileCount: sub.fileCount, + ...(sub.approximate ? { approximate: true } : {}), + similarSoftwareName: findSimilarSoftware(sub.name, softwareList)?.name }) - ) + } }) ) - return { ok: true, items: results.sort((a, b) => b.sizeBytes - a.sizeBytes) } + const sorted = results.sort((a, b) => b.sizeBytes - a.sizeBytes) + if (scanErrors.length > 0 && sorted.length === 0 && scanErrors.length >= roots.length) { + return { + ok: false, + items: [], + ...(anyApproximate ? { approximate: true } : {}), + error: t('scanAppDataFailedWithReason', { reason: scanErrors.join('; ') }) + } + } + return { + ok: true, + items: sorted, + ...(anyApproximate ? { approximate: true } : {}), + ...(scanErrors.length > 0 ? { error: t('scanAppDataFailedWithReason', { reason: scanErrors.join('; ') }) } : {}) + } } catch (err) { return { ok: false, items: [], error: t('scanAppDataFailedWithReason', { reason: errorText(err) }) } } diff --git a/extensions/software-manager/src/native-ipc.ts b/extensions/software-manager/src/native-ipc.ts deleted file mode 100644 index 51576b99..00000000 --- a/extensions/software-manager/src/native-ipc.ts +++ /dev/null @@ -1,1852 +0,0 @@ -import { getLocale } from '@ztools/declarative-ui' - -type DynamicBridge = ReturnType - -const NATIVE_IPC_MESSAGES: Record string - dirEntrySep: string - dirErrorColon: string - deepScanUnavailable: string - pathEmpty: string - invalidMethodEmpty: string - invalidMethodFormat: string - invalidParamsObject: string - paramTooLong: (key: string) => string - paramOutOfRange: (key: string) => string - methodParamEmpty: string - invalidMethodType: string - malformedDllResponse: string - unknownDllError: string - hostIpcFailed: (pluginName: string, method: string) => string - hostUnavailable: (pluginName: string, method: string) => string - callFailed: string - movedToTrash: string - deleteFailed: string - revealedInFolder: string - revealFailed: string - opened: string - openFailed: string - pluginCallNotReady: string -}> = { - 'zh-CN': { - ipcCallFailed: 'IPC 调用返回失败', - ipcInnerFailed: 'IPC 内部调用失败', - scanIncomplete: '扫描结果不完整', - dirReadFailed: (details, moreCount) => - `目录读取失败或不完整:${details}${moreCount > 0 ? `;另有 ${moreCount} 个目录` : ''}`, - dirEntrySep: ';', - dirErrorColon: ':', - deepScanUnavailable: '深度扫描不可用,仅列出一级目录,结果不完整', - pathEmpty: '路径不能为空', - invalidMethodEmpty: 'INVALID_METHOD: 调用方法名不能为空', - invalidMethodFormat: 'INVALID_METHOD_FORMAT: 方法名包含非法字符或超长', - invalidParamsObject: 'INVALID_PARAMS: 参数必须为非空对象', - paramTooLong: (key) => `PARAM_TOO_LONG: 参数 ${key} 超过最大长度限制`, - paramOutOfRange: (key) => `PARAM_OUT_OF_RANGE: 数值参数 ${key} 越界或非有限数`, - methodParamEmpty: 'method 参数不能为空', - invalidMethodType: 'INVALID_METHOD: method 不能为空且必须为字符串', - malformedDllResponse: 'MALFORMED_DLL_RESPONSE: 原生组件返回了损坏的 JSON 数据', - unknownDllError: '原生组件返回未知错误', - hostIpcFailed: (pluginName, method) => `HOST_IPC_FAILED: ${pluginName}.${method} 调用失败`, - hostUnavailable: (pluginName, method) => `HOST_UNAVAILABLE: ${pluginName}.${method} 宿主接口未就绪`, - callFailed: '调用失败', - movedToTrash: '已移入回收站', - deleteFailed: '删除失败', - revealedInFolder: '已定位文件', - revealFailed: '定位失败', - opened: '已打开', - openFailed: '打开失败', - pluginCallNotReady: '插件调用未就绪' - }, - 'en-US': { - ipcCallFailed: 'IPC call failed', - ipcInnerFailed: 'Internal IPC call failed', - scanIncomplete: 'Incomplete scan results', - dirReadFailed: (details, moreCount) => - `Directory read failed or incomplete: ${details}${moreCount > 0 ? `; and ${moreCount} more` : ''}`, - dirEntrySep: '; ', - dirErrorColon: ': ', - deepScanUnavailable: 'Deep scan unavailable; only top-level directory listed (incomplete)', - pathEmpty: 'Path cannot be empty', - invalidMethodEmpty: 'INVALID_METHOD: Method name cannot be empty', - invalidMethodFormat: 'INVALID_METHOD_FORMAT: Method name contains invalid characters or is too long', - invalidParamsObject: 'INVALID_PARAMS: Parameters must be a non-null object', - paramTooLong: (key) => `PARAM_TOO_LONG: Parameter "${key}" exceeds maximum length`, - paramOutOfRange: (key) => `PARAM_OUT_OF_RANGE: Numeric parameter "${key}" is out of range or non-finite`, - methodParamEmpty: 'Method parameter cannot be empty', - invalidMethodType: 'INVALID_METHOD: Method must be a non-empty string', - malformedDllResponse: 'MALFORMED_DLL_RESPONSE: Native component returned malformed JSON', - unknownDllError: 'Native component returned an unknown error', - hostIpcFailed: (pluginName, method) => `HOST_IPC_FAILED: ${pluginName}.${method} call failed`, - hostUnavailable: (pluginName, method) => `HOST_UNAVAILABLE: ${pluginName}.${method} host interface not ready`, - callFailed: 'Call failed', - movedToTrash: 'Moved to Trash', - deleteFailed: 'Delete failed', - revealedInFolder: 'Revealed in folder', - revealFailed: 'Failed to reveal item', - opened: 'Opened', - openFailed: 'Failed to open', - pluginCallNotReady: 'Plugin invocation not ready' - } -} - -function ipcStrings() { - const locale = getLocale() - return NATIVE_IPC_MESSAGES[locale] ?? NATIVE_IPC_MESSAGES['en-US'] -} -/** - * ZTools 真实宿主 IPC 与系统能力桥接层 (Real Host IPC Bridge) - * - * 严格遵循《ZTools Declarative UI 2.0 架构与 35 款原生插件全量升级规范》5.1 真实环境铁律: - * - 在真实 Electron 宿主环境中,100% 走通 Preload (__ztoolsElectron.transport.methods / window.ztools / __ztoolsLauncher) 真实调用链路 - * - 严禁在真实环境中因参数格式或嵌套响应结构差异而回退到假数据 - */ - -let ipcReqSeq = 1 -const realFileSizeCache = new Map() - -export function nextMessageId(prefix = 'ipc'): string { - ipcReqSeq = (ipcReqSeq + 1) % 1_000_000 - return `${prefix}_${Date.now()}_${ipcReqSeq}` -} - -/** - * 判断当前是否处于真实的 ZTools Electron 渲染进程宿主环境 - */ -export function isRealElectronHost(hostOverride?: unknown): boolean { - if (hostOverride) return false - if (typeof window === 'undefined') return false - const w = window as DynamicBridge - return Boolean( - w.__ztoolsElectron?.transport?.methods || - w.ztools?.transport?.call || - w.ztools?.transport?.methods - ) -} - -function normalizeMethodParams(method: string, params: Record): Record { - if (!params || typeof params !== 'object') return {} - const next = { ...params } - if (method === 'system_get_disk_usage') { - const rawDrive = String(next.drive || next.path || 'C:\\').trim() - if (rawDrive.startsWith('/')) { - next.drive = rawDrive - } else { - const match = rawDrive.match(/^([A-Za-z]):/) - next.drive = match ? `${match[1].toUpperCase()}:\\` : rawDrive.replace(/\//g, '\\') - } - delete next.path - } - return next -} - -function normalizeMethodResult(method: string, payload: DynamicBridge): DynamicBridge { - if (!payload || typeof payload !== 'object') return payload - - if (method === 'system_get_disk_usage') { - const avail = typeof payload.available === 'number' - ? payload.available - : typeof payload.free === 'number' - ? payload.free - : Math.max(0, Number(payload.total || 0) - Number(payload.used || 0)) - return { - ...payload, - available: avail, - free: avail - } - } - - if (method === 'system_get_hardware_summary') { - const cpuModel = - typeof payload.cpuModel === 'string' && payload.cpuModel.trim() - ? payload.cpuModel.trim() - : Array.isArray(payload.cpuModels) && payload.cpuModels.length > 0 - ? String(payload.cpuModels[0]).trim() - : 'x86_64 Processor' - return { - ...payload, - cpuModel - } - } - - if (method === 'system_get_battery_status') { - // 宿主约定 percent 超出 0-100(如 255)表示无电池或电量未知,不能改写成 100% - const rawPct = payload.percent - const hasBattery = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 - return { - ...payload, - percent: hasBattery ? rawPct : null, - hasBattery - } - } - - if (method === 'screen_get_all_displays') { - const list = Array.isArray(payload) - ? payload - : Array.isArray(payload.displays) - ? payload.displays - : [] - return list.map((d: DynamicBridge) => ({ - ...d, - label: d?.label || d?.name || `Display #${d?.id ?? 1}` - })) - } - - return payload -} - -function extractIpcErrorMeta(errObj: DynamicBridge): { - errorCode?: string - errorDetails?: Record -} { - if (!errObj || typeof errObj !== 'object') return {} - const errorCode = - typeof errObj.errorCode === 'string' && errObj.errorCode.trim() - ? errObj.errorCode.trim() - : typeof errObj.code === 'string' && errObj.code.trim() - ? errObj.code.trim() - : undefined - const rawDetails = - errObj.errorDetails && typeof errObj.errorDetails === 'object' && !Array.isArray(errObj.errorDetails) - ? (errObj.errorDetails as Record) - : errObj.details && typeof errObj.details === 'object' && !Array.isArray(errObj.details) - ? (errObj.details as Record) - : undefined - return { - ...(errorCode ? { errorCode } : {}), - ...(rawDetails ? { errorDetails: rawDetails } : {}) - } -} - -function unwrapTransportResponse( - method: string, - raw: DynamicBridge -): { ok: boolean; data?: DynamicBridge; error?: string; errorCode?: string; errorDetails?: Record } { - if (raw === null || raw === undefined) { - return { ok: false, error: 'EMPTY_IPC_RESPONSE', errorCode: 'EMPTY_IPC_RESPONSE' } - } - if (typeof raw !== 'object') { - return { ok: true, data: raw } - } - if (raw.success === false) { - const errObj = raw.error - const errMsg = - typeof errObj === 'object' && errObj !== null - ? String(errObj.message || errObj.code || JSON.stringify(errObj)) - : String(errObj || ipcStrings().ipcCallFailed) - return { ok: false, error: errMsg, ...extractIpcErrorMeta(raw), ...extractIpcErrorMeta(errObj) } - } - - const firstLayer = 'data' in raw && raw.data !== undefined ? raw.data : raw - if (firstLayer && typeof firstLayer === 'object' && !Array.isArray(firstLayer)) { - if (firstLayer.success === false) { - const errObj = firstLayer.error - const errMsg = - typeof errObj === 'object' && errObj !== null - ? String(errObj.message || errObj.code || JSON.stringify(errObj)) - : String(errObj || ipcStrings().ipcInnerFailed) - return { ok: false, error: errMsg, ...extractIpcErrorMeta(firstLayer), ...extractIpcErrorMeta(errObj) } - } - if ('data' in firstLayer && firstLayer.data !== undefined) { - return { ok: true, data: normalizeMethodResult(method, firstLayer.data) } - } - } - - return { ok: true, data: normalizeMethodResult(method, firstLayer) } -} - -/** - * 调用 Electron Preload Transport 方法(自动封装合法的 alphanumeric messageId 与双层解包) - */ -export async function callHostTransport( - method: string, - params: Record = {}, - hostOverride?: DynamicBridge -): Promise<{ ok: boolean; data?: T; error?: string; errorCode?: string; errorDetails?: Record }> { - const normalizedParams = normalizeMethodParams(method, params) - - // 1. 测试注入的 hostOverride 优先 - if (hostOverride) { - if (typeof hostOverride[method] === 'function') { - try { - const res = await hostOverride[method](normalizedParams) - const unwrapped = unwrapTransportResponse(method, res) - return unwrapped as { ok: boolean; data?: T; error?: string; errorCode?: string; errorDetails?: Record } - } catch (err: DynamicBridge) { - return { ok: false, error: err instanceof Error ? err.message : String(err), ...extractIpcErrorMeta(err) } - } - } - if (typeof hostOverride?.transport?.call === 'function') { - try { - const res = await hostOverride.transport.call(method, normalizedParams) - const unwrapped = unwrapTransportResponse(method, res) - return unwrapped as { ok: boolean; data?: T; error?: string; errorCode?: string; errorDetails?: Record } - } catch (err: DynamicBridge) { - return { ok: false, error: err instanceof Error ? err.message : String(err), ...extractIpcErrorMeta(err) } - } - } - } - - if (typeof window === 'undefined') { - return { ok: false, error: 'NO_WINDOW_ENV', errorCode: 'NO_WINDOW_ENV' } - } - - const w = window as DynamicBridge - const methods = w.__ztoolsElectron?.transport?.methods || w.ztools?.transport?.methods - const fn = methods?.[method] - - if (typeof fn === 'function') { - try { - const messageId = nextMessageId(method.replace(/[^A-Za-z0-9_]/g, '_').slice(0, 24)) - const raw = await fn({ messageId, params: normalizedParams }) - return unwrapTransportResponse(method, raw) as { ok: boolean; data?: T; error?: string; errorCode?: string; errorDetails?: Record } - } catch (err: DynamicBridge) { - return { ok: false, error: err instanceof Error ? err.message : String(err), ...extractIpcErrorMeta(err) } - } - } - - if (typeof w.ztools?.transport?.call === 'function') { - try { - const raw = await w.ztools.transport.call(method, normalizedParams) - return unwrapTransportResponse(method, raw) as { ok: boolean; data?: T; error?: string; errorCode?: string; errorDetails?: Record } - } catch (err: DynamicBridge) { - return { ok: false, error: err instanceof Error ? err.message : String(err), ...extractIpcErrorMeta(err) } - } - } - - return { ok: false, error: `METHOD_NOT_AVAILABLE: ${method}`, errorCode: 'METHOD_NOT_AVAILABLE' } -} - -export interface RealDiskDriveInfo { - drive: string - totalBytes: number - usedBytes: number - availableBytes: number - usagePercent: number -} - -/** - * 探测本机全部真实挂载磁盘分区 (C:\ ~ Z:\ 或 macOS/POSIX 挂载点 '/') - */ -export async function probeRealDiskDrives( - candidateLetters: string[] = ['C', 'D', 'E', 'F', 'G'], - hostOverride?: DynamicBridge -): Promise { - const drives: RealDiskDriveInfo[] = [] - const results = await Promise.all( - candidateLetters.map(async (letter) => { - const raw = String(letter || '').trim() - const isPosix = raw.startsWith('/') - const drivePath = isPosix ? raw : `${raw.replace(/:\\?$/, '').toUpperCase()}:\\` - const res = await callHostTransport<{ - total: number - used: number - available: number - free?: number - percent: number - }>('system_get_disk_usage', { drive: drivePath }, hostOverride) - if (res.ok && res.data && typeof res.data.total === 'number' && res.data.total > 0) { - const availableBytes = - typeof res.data.available === 'number' - ? res.data.available - : typeof res.data.free === 'number' - ? res.data.free - : Math.max(0, res.data.total - res.data.used) - return { - drive: isPosix ? raw : `${raw.replace(/:\\?$/, '').toUpperCase()}:`, - totalBytes: res.data.total, - usedBytes: res.data.used, - availableBytes, - usagePercent: res.data.percent - } - } - return null - }) - ) - - for (const item of results) { - if (item) drives.push(item) - } - - if (drives.length === 0 && !candidateLetters.includes('/')) { - const posixRes = await callHostTransport<{ - total: number - used: number - available: number - free?: number - percent: number - }>('system_get_disk_usage', { drive: '/' }, hostOverride) - if (posixRes.ok && posixRes.data && typeof posixRes.data.total === 'number' && posixRes.data.total > 0) { - const availableBytes = - typeof posixRes.data.available === 'number' - ? posixRes.data.available - : typeof posixRes.data.free === 'number' - ? posixRes.data.free - : Math.max(0, posixRes.data.total - posixRes.data.used) - drives.push({ - drive: '/', - totalBytes: posixRes.data.total, - usedBytes: posixRes.data.used, - availableBytes, - usagePercent: posixRes.data.percent - }) - } - } - - return drives -} - -/** - * 获取本机真实系统特殊路径(支持 home 派生标准子目录兜底,自动兼容 Windows 与 macOS/POSIX) - */ -export async function getRealSystemPath( - name: 'home' | 'appData' | 'userData' | 'desktop' | 'documents' | 'downloads' | 'music' | 'pictures' | 'videos' | 'temp' | 'cache', - hostOverride?: DynamicBridge -): Promise { - const res = await callHostTransport('system_get_path', { name }, hostOverride) - if (res.ok && res.data) { - if (typeof res.data === 'string' && res.data.trim().length > 0) { - return res.data.trim() - } - if (typeof res.data.path === 'string' && res.data.path.trim().length > 0) { - return res.data.path.trim() - } - } - - if (name !== 'home') { - const home = await getRealSystemPath('home', hostOverride) - if (home) { - const isPosix = home.startsWith('/') - const subMap: Record = isPosix - ? { - desktop: `${home}/Desktop`, - documents: `${home}/Documents`, - downloads: `${home}/Downloads`, - music: `${home}/Music`, - pictures: `${home}/Pictures`, - videos: `${home}/Videos`, - appData: `${home}/Library/Application Support`, - userData: `${home}/Library/Application Support/ZTools`, - temp: '/tmp', - cache: `${home}/Library/Caches` - } - : { - desktop: `${home}\\Desktop`, - documents: `${home}\\Documents`, - downloads: `${home}\\Downloads`, - music: `${home}\\Music`, - pictures: `${home}\\Pictures`, - videos: `${home}\\Videos`, - appData: `${home}\\AppData\\Roaming`, - userData: `${home}\\AppData\\Roaming\\ZTools`, - temp: `${home}\\AppData\\Local\\Temp`, - cache: `${home}\\AppData\\Local` - } - if (subMap[name]) return subMap[name] - } - } - - return '' -} - -export type RealDriveUsageInfo = RealDiskDriveInfo - -export interface RealIndexedFileEntry { - name: string - path: string - ext: string - isDir: boolean - isDirectory: boolean - size: number - sizeBytes: number - mtime: number - mtimeMs: number - lastModifiedMs: number -} - -export interface RealDirectorySubdirSummary { - name: string - path: string - fileCount: number - totalBytes: number - mtime: number - /** 体积不是完整统计(宿主扫描截断且独立统计超时 / 无权限),totalBytes 只是下限 */ - approximate?: boolean -} - -export interface RealDirectoryScanResult extends Iterable { - files: RealIndexedFileEntry[] - totalFiles: number - fileCount: number - totalBytes: number - subdirs: RealDirectorySubdirSummary[] - /** 宿主扫描达到条目上限后停止:files / totalFiles 只是已遍历部分的抽样 */ - truncated?: boolean - /** totalBytes 为近似值(下限) */ - approximate?: boolean - /** 宿主实际遍历的条目数 */ - visitedEntries?: number - /** 读取失败的真实原因;已有文件仍可使用,但不能当作完整结果。 */ - error?: string -} - -interface ScanResultMeta { - truncated?: boolean - approximate?: boolean - visitedEntries?: number -} - -export interface ScanDirectoryTreeOptions { - maxDepth?: number - maxFiles?: number - collectTopN?: number - filterExt?: RegExp - hostOverride?: DynamicBridge -} - -function extractFileExt(fileNameOrPath: string): string { - const base = String(fileNameOrPath || '').split(/[\\/]/).pop() || '' - const dotIdx = base.lastIndexOf('.') - return dotIdx > 0 ? base.slice(dotIdx).toLowerCase() : '' -} - -function normalizeIndexedFileEntry(f: DynamicBridge): RealIndexedFileEntry { - const p = String(f?.path || '') - const name = String(f?.name || p.split(/[\\/]/).pop() || '') - const sz = Number(f?.size ?? f?.sizeBytes ?? 0) - const isDir = Boolean(f?.is_dir || f?.isDir || f?.isDirectory) - const rawMtime = Number(f?.mtime ?? f?.mtimeMs ?? 0) - const mtimeMs = rawMtime > 1e11 ? rawMtime : rawMtime > 0 ? rawMtime * 1000 : Date.now() - const mtimeSec = rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime - if (p && sz >= 0) realFileSizeCache.set(p, sz) - return { - name, - path: p, - ext: extractFileExt(name || p), - isDir, - isDirectory: isDir, - size: sz, - sizeBytes: sz, - mtime: mtimeSec, - mtimeMs, - lastModifiedMs: mtimeMs - } -} - -function makeScanResult( - files: RealIndexedFileEntry[], - totalFiles: number, - totalBytes: number, - subdirs: RealDirectorySubdirSummary[], - meta: ScanResultMeta = {} -): RealDirectoryScanResult { - return { - files, - totalFiles, - fileCount: totalFiles, - totalBytes, - subdirs, - ...(meta.truncated ? { truncated: true } : {}), - ...(meta.approximate ? { approximate: true } : {}), - ...(typeof meta.visitedEntries === 'number' ? { visitedEntries: meta.visitedEntries } : {}), - [Symbol.iterator]() { - return files[Symbol.iterator]() - } - } -} - -/** - * 调用客户端的原生文件索引组件 (ztools-indexer) 检索文件 - */ -export async function searchRealIndexedFiles( - query: string, - limit = 40, - hostOverride?: DynamicBridge -): Promise { - if (!query || !query.trim()) return [] - const q = query.trim() - const safeLimit = Math.min(200, Math.max(1, Math.floor(limit || 40))) - - try { - const res = await callHostTransport<{ files?: DynamicBridge[] }>( - 'system_search_files', - { query: q, limit: safeLimit }, - hostOverride - ) - if (res.ok && res.data && Array.isArray(res.data.files)) { - return res.data.files.map(normalizeIndexedFileEntry) - } - - if (!hostOverride && typeof window !== 'undefined') { - const w = window as DynamicBridge - if (typeof w.__ztoolsLauncher?.searchFiles === 'function') { - const rawOuter = await w.__ztoolsLauncher.searchFiles(q, safeLimit) - const raw = rawOuter && typeof rawOuter === 'object' && 'data' in rawOuter && rawOuter.data ? rawOuter.data : rawOuter - if (raw && Array.isArray(raw.files)) { - return raw.files.map(normalizeIndexedFileEntry) - } - } - } - } catch { - // ignore - } - return [] -} - -/** - * 深度扫描指定真实物理目录树(支持符号链接穿透,如 AppData\Roaming\Tencent -> D:\Local\Roaming\Tencent) - * 返回该目录下 Top 文件列表、全树真实文件总数、全树真实总字节数与一级子目录汇总 - */ -export async function scanRealDirectoryTree( - dirPath: string, - limitOrOptions: number | ScanDirectoryTreeOptions = 160, - hostOverrideArg?: DynamicBridge -): Promise { - const result = await scanDirectoryTreeWithError(dirPath, limitOrOptions, hostOverrideArg) - return result.error ? { ...result.scan, error: result.error } : result.scan -} - -/** 一次界面扫描的错误汇总;多个目录并行扫描时保留可读目录的结果。 */ -export function createDirectoryScanner(hostOverride?: DynamicBridge) { - const failures = new Map() - return { - async scan(dir: string, options: number | ScanDirectoryTreeOptions = 160) { - const result = await scanRealDirectoryTree(dir, options, hostOverride) - const error = result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') - if (error) failures.set(dir, error) - else failures.delete(dir) - return result - }, - get error(): string | undefined { - if (!failures.size) return undefined - const s = ipcStrings() - const details = [...failures].slice(0, 3).map(([dir, error]) => `${dir}${s.dirErrorColon}${error}`).join(s.dirEntrySep) - return s.dirReadFailed(details, Math.max(0, failures.size - 3)) - } - } -} - -/** scanRealDirectoryTree 的实现:额外带回读取失败原因(目录不存在 / 为空 / 无权限 / 载荷异常) */ -async function scanDirectoryTreeWithError( - dirPath: string, - limitOrOptions: number | ScanDirectoryTreeOptions, - hostOverrideArg?: DynamicBridge -): Promise<{ scan: RealDirectoryScanResult; error?: string }> { - const empty = makeScanResult([], 0, 0, []) - if (!dirPath || !dirPath.trim()) return { scan: empty, error: 'EMPTY_DIRECTORY_PATH' } - const targetDir = dirPath.trim() - - const opts: ScanDirectoryTreeOptions = - typeof limitOrOptions === 'number' - ? { maxFiles: limitOrOptions, hostOverride: hostOverrideArg } - : { ...limitOrOptions, hostOverride: limitOrOptions?.hostOverride ?? hostOverrideArg } - - const rawLimit = opts.maxFiles ?? opts.collectTopN ?? 160 - const safeLimit = Math.min(200, Math.max(1, Math.floor(rawLimit || 160))) - const hostOverride = opts.hostOverride - const filterExt = opts.filterExt - const dirQuery = `dir:${targetDir}` - - try { - let rawPayload: DynamicBridge = null - const res = await callHostTransport( - 'system_search_files', - { query: dirQuery, limit: safeLimit }, - hostOverride - ) - if (res.ok && res.data) { - rawPayload = res.data - } - if (!rawPayload && !hostOverride && typeof window !== 'undefined') { - const w = window as DynamicBridge - if (typeof w.__ztoolsLauncher?.searchFiles === 'function') { - const rawOuter = await w.__ztoolsLauncher.searchFiles(dirQuery, safeLimit) - rawPayload = - rawOuter && typeof rawOuter === 'object' && 'data' in rawOuter && rawOuter.data - ? rawOuter.data - : rawOuter - } - } - - if ( - rawPayload && - Array.isArray(rawPayload.files) - ) { - let files: RealIndexedFileEntry[] = rawPayload.files.map(normalizeIndexedFileEntry) - if (filterExt instanceof RegExp) { - files = files.filter(f => !f.isDir && (filterExt.test(f.name) || filterExt.test(f.ext))) - // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索目标扩展名 - if (files.length === 0 && !hostOverride) { - const extTokens = (filterExt.source.match(/[a-z0-9]{2,5}/gi) || []) - .filter(t => !['thumbcache', 'iconcache'].includes(t.toLowerCase())) - .slice(0, 4) - // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 - const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() - const extraLists = await Promise.all( - extTokens.map(ext => searchRealIndexedFiles(`.${ext.toLowerCase()}`, 30, hostOverride)) - ) - const seen = new Set() - for (const list of extraLists) { - for (const item of list) { - if (!item.isDir && item.size > 0 && !seen.has(item.path)) { - if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { - seen.add(item.path) - files.push(item) - } - } - } - } - } - } - if (typeof opts.collectTopN === 'number' && opts.collectTopN > 0 && files.length > opts.collectTopN) { - files = files.slice(0, opts.collectTopN) - } - const subdirs: RealDirectorySubdirSummary[] = Array.isArray(rawPayload.subdirs) - ? rawPayload.subdirs.map((s: DynamicBridge) => ({ - name: String(s.name || ''), - path: String(s.path || ''), - fileCount: Number(s.file_count ?? s.fileCount ?? 0), - totalBytes: Number(s.total_bytes ?? s.totalBytes ?? 0), - mtime: Number(s.mtime || 0), - ...(s.approximate === true ? { approximate: true } : {}) - })) - : [] - const computedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) - const totalFilesCount = - filterExt instanceof RegExp ? files.length : Number(rawPayload.total_matches ?? files.length) - const totalBytesCount = - filterExt instanceof RegExp ? computedBytes : Number(rawPayload.total_bytes ?? computedBytes) - const visited = Number(rawPayload.visited_entries) - return { - scan: makeScanResult(files, totalFilesCount, totalBytesCount, subdirs, { - truncated: rawPayload.truncated === true, - approximate: rawPayload.approximate === true, - ...(Number.isFinite(visited) && visited >= 0 ? { visitedEntries: visited } : {}) - }), - ...(typeof rawPayload.scan_error === 'string' && rawPayload.scan_error ? { error: rawPayload.scan_error } : {}) - } - } - - // 深度扫描失败或回执无效时,仅以一级目录读取补回可见结果;不冒充完整目录树。 - const listing = await listDirectoryViaFilesystem(targetDir, hostOverride, { withSizes: true, limit: safeLimit }) - if (listing.ok && listing.entries.length > 0) { - const files: RealIndexedFileEntry[] = [] - let totalBytes = 0 - for (const entry of listing.entries) { - if (filterExt instanceof RegExp && !filterExt.test(entry.name) && !filterExt.test(entry.ext)) { - continue - } - files.push(entry) - totalBytes += entry.isDir ? 0 : entry.size - } - const incomplete = listing.entries.some(entry => entry.isDir) || listing.entries.length >= safeLimit - return { - scan: makeScanResult(files, files.filter(file => !file.isDir).length, totalBytes, [], { approximate: incomplete }), - ...(incomplete ? { error: res.error || ipcStrings().deepScanUnavailable } : {}) - } - } - return listing.ok ? { scan: empty } : { scan: empty, error: listing.error || 'DIRECTORY_READ_FAILED' } - } catch (error) { - return { scan: empty, error: error instanceof Error ? error.message : String(error) } - } -} - - -/** 目录读取不到任何条目(不存在 / 为空 / 无权限)时的错误码 */ -export const DIRECTORY_EMPTY_OR_UNREADABLE = 'DIRECTORY_EMPTY_OR_UNREADABLE' - -export interface RealDirectoryListingResult { - /** 目录内条目的完整路径;读取失败时为空数组 */ - entries: string[] - /** 读取失败或目录为空时的错误码 / 宿主错误信息 */ - error?: string -} - -export interface RealDirectChildrenResult { - /** 目录的直接子项(子目录在前),按路径去重 */ - entries: RealIndexedFileEntry[] - /** 宿主扫描达到条目上限,可能只返回了部分直接子项 */ - partial: boolean - error?: string -} - -function stripTrailingSeparators(p: string): string { - const trimmed = p.replace(/[\\/]+$/, '') - return trimmed || p.slice(0, 1) -} - -function isWindowsStylePath(p: string): boolean { - return /^[A-Za-z]:/.test(p) || p.startsWith('\\\\') || (p.includes('\\') && !p.includes('/')) -} - -function comparablePath(p: string): string { - const stripped = stripTrailingSeparators(String(p || '').trim()) - return isWindowsStylePath(stripped) ? stripped.replace(/\//g, '\\').toLowerCase() : stripped -} - -function parentDirOf(p: string): string { - const stripped = stripTrailingSeparators(String(p || '')) - const idx = Math.max(stripped.lastIndexOf('/'), stripped.lastIndexOf('\\')) - if (idx < 0) return '' - if (idx === 0) return stripped.slice(0, 1) - const parent = stripped.slice(0, idx) - return /^[A-Za-z]:$/.test(parent) ? `${parent}\\` : parent -} - -function isDirectChildPath(dirPath: string, candidate: string): boolean { - if (!candidate) return false - return comparablePath(parentDirOf(candidate)) === comparablePath(dirPath) -} - -function joinChildPath(dirPath: string, name: string): string { - const sep = isWindowsStylePath(dirPath) ? '\\' : '/' - const base = dirPath.replace(/[\\/]+$/, '') - return `${base}${sep}${name}` -} - -/** - * 通过 filesystem_get_directory_contents 读取一级目录(需宿主授权)。 - * 宿主真实返回 { success, files: [{ name, size, isDirectory, lastModified }] }(name 为文件名); - * 兼容旧测试替身返回的完整路径字符串数组。 - */ -async function listDirectoryViaFilesystem( - dirPath: string, - hostOverride: DynamicBridge, - options: { withSizes?: boolean; limit?: number } = {} -): Promise<{ ok: boolean; entries: RealIndexedFileEntry[]; error?: string }> { - const res = await callHostTransport('filesystem_get_directory_contents', { path: dirPath }, hostOverride) - if (!res.ok) return { ok: false, entries: [], error: res.error || 'DIRECTORY_READ_FAILED' } - const data = res.data - const rawList: unknown[] | null = Array.isArray(data) ? data : Array.isArray(data?.files) ? data.files : null - if (!rawList) return { ok: false, entries: [], error: 'INVALID_DIRECTORY_PAYLOAD' } - - const limit = Math.max(1, Math.floor(options.limit ?? 1000)) - const nowSec = Math.floor(Date.now() / 1000) - const entries: RealIndexedFileEntry[] = [] - const seen = new Set() - for (const item of rawList) { - if (entries.length >= limit) break - let entry: RealIndexedFileEntry | null = null - if (typeof item === 'string') { - const itemPath = item.trim() - if (!itemPath) continue - const name = itemPath.split(/[\\/]/).pop() || itemPath - const sz = options.withSizes ? await getRealFileSize(itemPath, hostOverride) : 0 - entry = normalizeIndexedFileEntry({ - name, - path: itemPath, - isDir: sz === 0 && !name.includes('.'), - size: sz, - mtime: nowSec - }) - } else if (item && typeof item === 'object' && typeof (item as DynamicBridge).name === 'string') { - const raw = item as DynamicBridge - const rawName = raw.name.trim() - if (!rawName || rawName === '.' || rawName === '..') continue - // 只接受文件名,或确实位于该目录下的完整路径,拒绝越界路径 - const fullPath = /[\\/]/.test(rawName) ? rawName : joinChildPath(dirPath, rawName) - if (!isDirectChildPath(dirPath, fullPath)) continue - const isDir = Boolean(raw.isDirectory ?? raw.isDir ?? raw.is_dir) - const parsedMtime = Date.parse(String(raw.lastModified || '')) - entry = normalizeIndexedFileEntry({ - name: fullPath.split(/[\\/]/).pop() || rawName, - path: fullPath, - isDir, - size: isDir ? 0 : Math.max(0, Number(raw.size) || 0), - mtime: Number.isFinite(parsedMtime) ? parsedMtime : nowSec - }) - } - if (!entry || seen.has(entry.path)) continue - seen.add(entry.path) - entries.push(entry) - } - return { ok: true, entries } -} - -/** - * 读取真实目录下的条目路径(真实宿主中优先走 dir: 扫描:一级子目录 + 全树 Top-N 大文件),并返回失败原因。 - * 目录不存在、为空或无权限时返回空列表与错误码,绝不用全盘关键词搜索结果冒充目录内容。 - */ -export async function listRealDirectoryContentsResult( - dirPath: string, - hostOverride?: DynamicBridge -): Promise { - if (!dirPath || !dirPath.trim()) return { entries: [], error: 'EMPTY_DIRECTORY_PATH' } - const targetDir = dirPath.trim() - - if (!hostOverride && isRealElectronHost()) { - const tree = await scanRealDirectoryTree(targetDir, 60) - const paths: string[] = [] - for (const s of tree.subdirs) { - if (s.path) paths.push(s.path) - } - for (const f of tree.files) { - if (f.path) paths.push(f.path) - } - if (paths.length > 0) return { entries: Array.from(new Set(paths)) } - } - - const listing = await listDirectoryViaFilesystem(targetDir, hostOverride) - if (!listing.ok) return { entries: [], error: listing.error } - if (listing.entries.length === 0) return { entries: [], error: DIRECTORY_EMPTY_OR_UNREADABLE } - return { entries: listing.entries.map(e => e.path) } -} - -/** - * 读取真实目录下的条目路径(保持旧签名:失败时返回空数组,需要失败原因请用 listRealDirectoryContentsResult) - */ -export async function listRealDirectoryContents( - dirPath: string, - hostOverride?: DynamicBridge -): Promise { - return (await listRealDirectoryContentsResult(dirPath, hostOverride)).entries -} - -/** - * 只列出目录的直接子项(子目录 + 直接位于该目录下的文件),用于文件夹预览、按目录改名等场景。 - * dir: 扫描结果中只保留 subdirs 与父目录等于 dirPath 的文件;扫描达到上限时 partial=true,由插件如实提示「仅显示部分」。 - */ -export async function listDirectChildren( - dirPath: string, - hostOverride?: DynamicBridge -): Promise { - if (!dirPath || !dirPath.trim()) return { entries: [], partial: false, error: 'EMPTY_DIRECTORY_PATH' } - const targetDir = dirPath.trim() - const scanLimit = 200 - const entries: RealIndexedFileEntry[] = [] - const seen = new Set() - const push = (entry: RealIndexedFileEntry) => { - const key = comparablePath(entry.path) - if (!entry.path || seen.has(key)) return - seen.add(key) - entries.push(entry) - } - - const { scan: tree, error } = await scanDirectoryTreeWithError(targetDir, { maxFiles: scanLimit, hostOverride }) - for (const s of tree.subdirs) { - if (!s.path || !isDirectChildPath(targetDir, s.path)) continue - push( - normalizeIndexedFileEntry({ - name: s.name || s.path.split(/[\\/]/).pop(), - path: s.path, - isDir: true, - size: s.totalBytes, - mtime: s.mtime - }) - ) - } - let directFileCount = 0 - for (const f of tree.files) { - if (!isDirectChildPath(targetDir, f.path)) continue - directFileCount++ - push(f) - } - // 宿主 total_matches 是全树文件数、subdirs[].file_count 是各子目录全树文件数,差值即直接子文件数; - // 拿到的直接子文件少于它就说明被 Top-N 截断了。计数不可用时按是否达到扫描上限判断 - const expectedDirectFiles = tree.totalFiles - tree.subdirs.reduce((sum, d) => sum + (Number(d.fileCount) || 0), 0) - const partial = - Number.isFinite(expectedDirectFiles) && expectedDirectFiles >= 0 - ? directFileCount < expectedDirectFiles - : tree.files.length >= scanLimit - if (entries.length > 0) { - return { entries, partial } - } - - if (tree.files.length > 0) { - // dir: 扫描只返回了深层文件(直接子文件被 Top-N 截掉),如实标注部分结果 - return { entries: [], partial: true, error: DIRECTORY_EMPTY_OR_UNREADABLE } - } - return { entries: [], partial: false, error: error || DIRECTORY_EMPTY_OR_UNREADABLE } -} - -/** - * 获取真实文件字节大小(优先用扫描结果里的大小,再走 filesystem_get_file_size);读不到时返回 0 - */ -export async function getRealFileSize( - filePath: string, - hostOverride?: DynamicBridge -): Promise { - if (!filePath) return 0 - if (!hostOverride && realFileSizeCache.has(filePath)) { - const cached = realFileSizeCache.get(filePath)! - if (cached > 0) return cached - } - const res = await callHostTransport('filesystem_get_file_size', { path: filePath }, hostOverride) - // 客户端返回 { success, size }(目录时 size 为 -1),旧的测试替身直接返回数字 - const size = typeof res.data === 'number' ? res.data : res.data?.size - if (res.ok && typeof size === 'number' && Number.isFinite(size) && size >= 0) { - realFileSizeCache.set(filePath, size) - return size - } - return 0 -} - -/** - * 在访达 / 资源管理器中定位并高亮文件或目录。 - * 定位失败直接返回 false,不能改用“打开”:对可执行文件那等于运行它。 - */ -export async function showRealItemInFolder( - fullPath: string, - hostOverride?: DynamicBridge -): Promise { - if (!fullPath) return false - const res = await callHostTransport('shell_show_item_in_folder', { fullPath }, hostOverride) - return res.ok -} - -/** - * 使用系统默认程序打开文件或目录 - */ -export async function openRealPath( - fullPath: string, - hostOverride?: DynamicBridge -): Promise { - if (!fullPath) return false - const res = await callHostTransport('shell_open_path', { fullPath }, hostOverride) - return res.ok -} - -/** - * 将真实文件或目录移入系统回收站(安全可恢复删除) - */ -export async function trashRealItem( - fullPath: string, - hostOverride?: DynamicBridge -): Promise<{ ok: boolean; error?: string; errorCode?: string; errorDetails?: Record }> { - if (!fullPath) return { ok: false, error: ipcStrings().pathEmpty } - const res = await callHostTransport('shell_trash_item', { fullPath }, hostOverride) - return { - ok: res.ok, - error: res.error, - ...(!res.ok && res.errorCode ? { errorCode: res.errorCode } : {}), - ...(!res.ok && res.errorDetails ? { errorDetails: res.errorDetails } : {}) - } -} - -export interface NativeInvocationResult { - ok: boolean - code: number - message: string - data?: T - error?: string - errorCode?: string - errorDetails?: Record -} - -export interface DllCapabilityResponse { - ok: boolean - code: number - data: T | null - message?: string - error?: string - errorCode?: string - errorDetails?: Record - pluginName: string - method: string - fromFallback?: boolean -} - -/** 声明式能力菜单项及其调用回执,供相同宿主协议的插件共用。 */ -export interface CapabilityActionItem { - id: string - title: string - subtitle: string - tag: string - method: string - params: Record -} - -export type PluginInvocationResult = Pick< - DllCapabilityResponse, 'ok' | 'pluginName' | 'method' | 'error' | 'errorCode' | 'errorDetails' | 'fromFallback' -> & { data?: unknown } - -/** 多个原生能力插件共用的参数边界校验;保护目标由各插件按自身业务提供。 */ -export function validateNativeCapabilityPayload( - method: string, - params: unknown, - forbiddenPattern: RegExp, - forbiddenReason: string -): { valid: boolean; error?: string } { - const s = ipcStrings() - if (typeof method !== 'string' || method.trim().length === 0) { - return { valid: false, error: s.invalidMethodEmpty } - } - if (method.length > 128 || !/^[A-Za-z0-9_]+$/.test(method.trim())) { - return { valid: false, error: s.invalidMethodFormat } - } - if (params === null || params === undefined || typeof params !== 'object' || Array.isArray(params)) { - return { valid: false, error: s.invalidParamsObject } - } - - const record = params as Record - for (const [key, val] of Object.entries(record)) { - if (typeof val === 'string') { - if (val.length > 4096) { - return { valid: false, error: s.paramTooLong(key) } - } - if (forbiddenPattern.test(val)) { - return { valid: false, error: `SECURITY_INTERCEPTED: ${forbiddenReason}` } - } - } else if (typeof val === 'number') { - if (!Number.isFinite(val) || val < -1000 || val > 100_000_000) { - return { valid: false, error: s.paramOutOfRange(key) } - } - } - } - - return { valid: true } -} - -export async function invokeDllPluginCapability( - pluginName: string, - method: string, - params: Record = {}, - hostBridge?: DynamicBridge, - offlineFallback?: () => T | Promise -): Promise> { - const s = ipcStrings() - if (!method || typeof method !== 'string' || method.trim().length === 0) { - return { - ok: false, - code: -1, - data: null, - message: s.methodParamEmpty, - error: s.invalidMethodType, - pluginName, - method: String(method || '') - } - } - - const trimmedMethod = method.trim() - - const unwrapDllRawPayload = (raw: unknown, unwrapDataProperty: boolean): DllCapabilityResponse => { - let parsed: DynamicBridge = raw - if (typeof raw === 'string') { - try { - parsed = JSON.parse(raw) - } catch { - throw new Error(s.malformedDllResponse) - } - } - if (parsed && typeof parsed === 'object') { - if ('error' in parsed && parsed.error !== undefined && parsed.error !== null && parsed.error !== '') { - const errMsg = `DLL_ERROR: ${String(parsed.error)}` - return { - ok: false, - code: typeof parsed.code === 'number' ? parsed.code : -1, - data: null, - message: errMsg, - error: errMsg, - ...extractIpcErrorMeta(parsed), - ...extractIpcErrorMeta(parsed.error), - pluginName, - method: trimmedMethod, - fromFallback: false - } - } - if ('ok' in parsed && parsed.ok === false) { - const errMsg = `DLL_ERROR: ${String(parsed.error || parsed.message || s.unknownDllError)}` - return { - ok: false, - code: typeof parsed.code === 'number' ? parsed.code : -1, - data: null, - message: errMsg, - error: errMsg, - ...extractIpcErrorMeta(parsed), - ...extractIpcErrorMeta(parsed.error), - pluginName, - method: trimmedMethod, - fromFallback: false - } - } - const dataPayload = unwrapDataProperty && 'data' in parsed && parsed.data !== undefined ? parsed.data : parsed - return { - ok: true, - code: typeof parsed.code === 'number' ? parsed.code : 0, - data: dataPayload as T, - message: typeof parsed.message === 'string' ? parsed.message : undefined, - pluginName, - method: trimmedMethod, - fromFallback: false - } - } - return { - ok: true, - code: 0, - data: (parsed ?? null) as T, - pluginName, - method: trimmedMethod, - fromFallback: false - } - } - - const wrapCaughtDllError = (err: unknown): DllCapabilityResponse => { - const message = err instanceof Error ? err.message : String(err) - if (message.startsWith('MALFORMED_DLL_RESPONSE:')) { - throw err - } - const errMsg = `NATIVE_CALL_FAILED: ${message}` - return { - ok: false, - code: -1, - data: null, - message: errMsg, - error: errMsg, - ...extractIpcErrorMeta(err), - pluginName, - method: trimmedMethod, - fromFallback: false - } - } - - if (hostBridge && typeof hostBridge.invokeNative === 'function') { - try { - const raw = await hostBridge.invokeNative(pluginName, trimmedMethod, params) - return unwrapDllRawPayload(raw, true) - } catch (err: unknown) { - return wrapCaughtDllError(err) - } - } - - const runtimeHost = (hostBridge ?? (globalThis as Record).ztools) as - | { dllplugin?: { call?: (plugin: string, fn: string, payload: unknown) => Promise | unknown } } - | undefined - - const callFn = runtimeHost?.dllplugin?.call - if (typeof callFn === 'function') { - try { - const raw = await callFn.call(runtimeHost?.dllplugin, pluginName, trimmedMethod, params) - return unwrapDllRawPayload(raw, false) - } catch (err: unknown) { - return wrapCaughtDllError(err) - } - } - - const ipcRes = await callHostTransport( - 'dllplugin_call', - { - plugin: pluginName, - func: trimmedMethod, - params - }, - hostBridge - ) - - if (ipcRes.ok && ipcRes.data !== undefined && ipcRes.data !== null) { - return unwrapDllRawPayload(ipcRes.data, false) - } - - const isExplicitTransportFailure = - typeof ipcRes.error === 'string' && - ipcRes.error.length > 0 && - ipcRes.error !== 'NO_WINDOW_ENV' && - !ipcRes.error.startsWith('METHOD_NOT_AVAILABLE:') - - if ( - isRealElectronHost(hostBridge) || - isRealElectronHost() || - Boolean((hostBridge as DynamicBridge)?.__isRealHost) || - isExplicitTransportFailure - ) { - const errMsg = - ipcRes.error || s.hostIpcFailed(pluginName, trimmedMethod) - return { - ok: false, - code: -1, - data: null, - message: errMsg, - error: errMsg, - ...(ipcRes.errorCode ? { errorCode: ipcRes.errorCode } : {}), - ...(ipcRes.errorDetails ? { errorDetails: ipcRes.errorDetails } : {}), - pluginName, - method: trimmedMethod, - fromFallback: false - } - } - - if (typeof offlineFallback === 'function') { - const fallbackData = await offlineFallback() - return { - ok: true, - code: 0, - data: fallbackData, - pluginName, - method: trimmedMethod, - fromFallback: true - } - } - - const unavailableMsg = s.hostUnavailable(pluginName, trimmedMethod) - return { - ok: false, - code: -1, - data: null, - message: unavailableMsg, - error: unavailableMsg, - ...(ipcRes.errorCode ? { errorCode: ipcRes.errorCode } : {}), - ...(ipcRes.errorDetails ? { errorDetails: ipcRes.errorDetails } : {}), - pluginName, - method: trimmedMethod, - fromFallback: true - } -} - -export function formatBytes(bytes: number, decimals = 1): string { - const num = Number(bytes) - if (!Number.isFinite(num) || num <= 0) return '0 B' - if (num < 1024) return `${Math.round(num)} B` - const units = ['B', 'KB', 'MB', 'GB', 'TB'] - let val = num - let idx = 0 - while (val >= 1024 && idx < units.length - 1) { - val /= 1024 - idx += 1 - } - const safeDecimals = Math.max(0, Math.floor(decimals)) - return `${val >= 100 ? val.toFixed(0) : val.toFixed(safeDecimals)} ${units[idx]}` -} - -export function joinWinPath(...segments: string[]): string { - return segments - .filter(s => typeof s === 'string' && s.trim().length > 0) - .map((s, i) => (i === 0 ? s.replace(/[\\/]+$/, '') : s.replace(/^[\\/]+|[\\/]+$/g, ''))) - .join('\\') -} - -export interface RealEnvPaths { - home: string - userProfile: string - appData: string - localAppData: string - temp: string - downloads: string - documents: string - desktop: string - pictures: string - videos: string - music: string -} - -export async function getRealEnvPaths(hostOverride?: DynamicBridge): Promise { - const [homeRaw, appData, downloads, documents, desktop, pictures, videos, music] = await Promise.all([ - getRealSystemPath('home', hostOverride), - getRealSystemPath('appData', hostOverride), - getRealSystemPath('downloads', hostOverride), - getRealSystemPath('documents', hostOverride), - getRealSystemPath('desktop', hostOverride), - getRealSystemPath('pictures', hostOverride), - getRealSystemPath('videos', hostOverride), - getRealSystemPath('music', hostOverride) - ]) - const home = homeRaw || 'C:\\Users\\Default' - const isPosix = home.startsWith('/') - const tempRes = hostOverride ? await getRealSystemPath('temp', hostOverride) : '' - if (isPosix) { - return { - home, - userProfile: home, - appData: appData || `${home}/Library/Application Support`, - localAppData: `${home}/Library/Application Support`, - temp: tempRes || '/tmp', - downloads: downloads || `${home}/Downloads`, - documents: documents || `${home}/Documents`, - desktop: desktop || `${home}/Desktop`, - pictures: pictures || `${home}/Pictures`, - videos: videos || `${home}/Videos`, - music: music || `${home}/Music` - } - } - return { - home, - userProfile: home, - appData: appData || `${home}\\AppData\\Roaming`, - localAppData: `${home}\\AppData\\Local`, - temp: tempRes || `${home}\\AppData\\Local\\Temp`, - downloads: downloads || `${home}\\Downloads`, - documents: documents || `${home}\\Documents`, - desktop: desktop || `${home}\\Desktop`, - pictures: pictures || `${home}\\Pictures`, - videos: videos || `${home}\\Videos`, - music: music || `${home}\\Music` - } -} - -export const resolveRealSpecialPaths = getRealEnvPaths - -export async function readRealDirectory( - dirPath: string, - hostOverride?: DynamicBridge -): Promise { - if (!dirPath) return [] - const tree = await scanRealDirectoryTree(dirPath, { maxFiles: 120, hostOverride }) - const entries: RealIndexedFileEntry[] = [] - for (const s of tree.subdirs) { - entries.push( - normalizeIndexedFileEntry({ - name: s.name, - path: s.path, - isDir: true, - isDirectory: true, - size: s.totalBytes, - mtime: s.mtime - }) - ) - } - for (const f of tree.files) { - entries.push(f) - } - // scanRealDirectoryTree 已在 dir: 扫描无结果时退回一级目录读取;仍为空即目录不存在 / 为空 / 无权限,如实返回空列表 - return entries -} - -export async function moveRealFilesToTrash( - paths: string[], - hostOverride?: DynamicBridge -): Promise<{ - ok: boolean - trashedCount: number - deletedCount: number - failedPaths: string[] - error?: string -}> { - let deletedCount = 0 - const failedPaths: string[] = [] - let lastError: string | undefined - for (const p of paths) { - if (!p) continue - const res = await trashRealItem(p, hostOverride) - if (res.ok) { - deletedCount += 1 - } else { - failedPaths.push(p) - if (res.error) lastError = res.error - } - } - return { - ok: deletedCount > 0 || paths.length === 0, - trashedCount: deletedCount, - deletedCount, - failedPaths, - error: lastError - } -} - -const CAPABILITY_TO_PLUGIN_MAP: Record = { - 'mover.relocateWithJunction': { plugin: 'MoverPlugin', func: 'relocateWithJunction' }, - 'mover.scanCandidates': { plugin: 'MoverPlugin', func: 'scanCandidates' }, - 'recovery.restoreFile': { plugin: 'DataRecoveryPlugin', func: 'restoreFile' }, - 'recovery.scanDeletedFiles': { plugin: 'DataRecoveryPlugin', func: 'scanDeletedFiles' }, - 'shredder.secureWipeFile': { plugin: 'ShredderPlugin', func: 'secureWipeFile' }, - 'shredder.scanCandidates': { plugin: 'ShredderPlugin', func: 'scanCandidates' }, - 'backup.createSnapshotArchive': { plugin: 'SystemBackupPlugin', func: 'createSnapshotArchive' }, - 'backup.restoreSnapshotArchive': { plugin: 'SystemBackupPlugin', func: 'restoreSnapshotArchive' }, - 'backup.scanSnapshots': { plugin: 'SystemBackupPlugin', func: 'scanSnapshots' }, - 'sqlite.execute': { plugin: 'SqlitePlugin', func: 'execute' }, - 'sqlite.query': { plugin: 'SqlitePlugin', func: 'executeQuery' }, - 'sqlite.inspectWorkspace': { plugin: 'SqlitePlugin', func: 'inspectWorkspace' } -} - -export async function invokeHostCapability( - capability: string, - params: Record = {}, - hostOverride?: DynamicBridge -): Promise> { - const normalizedMethod = capability.replace(/\./g, '_') - - // 若测试显式注入了对应 normalizedMethod 的 mock 函数,优先调用测试桩 - if (hostOverride && typeof hostOverride[normalizedMethod] === 'function') { - const mockRes = await callHostTransport(normalizedMethod, params, hostOverride) - return { - ok: mockRes.ok, - code: mockRes.ok ? 0 : -1, - message: mockRes.ok ? 'OK' : mockRes.error || ipcStrings().callFailed, - data: mockRes.data, - error: mockRes.error, - ...(!mockRes.ok && mockRes.errorCode ? { errorCode: mockRes.errorCode } : {}), - ...(!mockRes.ok && mockRes.errorDetails ? { errorDetails: mockRes.errorDetails } : {}) - } - } - - if (capability === 'system.info') { - const drives = await probeRealDiskDrives(['C', 'D', 'E', 'F'], hostOverride) - return { - ok: true, - code: 0, - message: 'OK', - data: { - storage: drives.map(d => ({ - mount: d.drive, - fs: d.drive, - size: d.totalBytes, - total: d.totalBytes, - used: d.usedBytes, - available: d.availableBytes, - free: d.availableBytes, - percent: d.usagePercent - })) - } as unknown as T - } - } - if (capability === 'filesystem.deleteItem') { - const targetPath = String(params.path || params.fullPath || '') - const tr = await trashRealItem(targetPath, hostOverride) - const s = ipcStrings() - return { - ok: tr.ok, - code: tr.ok ? 0 : -1, - message: tr.ok ? s.movedToTrash : tr.error || s.deleteFailed, - error: tr.error, - ...(!tr.ok && tr.errorCode ? { errorCode: tr.errorCode } : {}), - ...(!tr.ok && tr.errorDetails ? { errorDetails: tr.errorDetails } : {}) - } - } - if (capability === 'system.showItemInFolder') { - const targetPath = String(params.path || params.fullPath || '') - const s = ipcStrings() - if (!targetPath) { - return { ok: false, code: -1, message: s.revealFailed } - } - const res = await callHostTransport('shell_show_item_in_folder', { fullPath: targetPath }, hostOverride) - return { - ok: res.ok, - code: res.ok ? 0 : -1, - message: res.ok ? s.revealedInFolder : res.error || s.revealFailed, - ...(!res.ok && res.error ? { error: res.error } : {}), - ...(!res.ok && res.errorCode ? { errorCode: res.errorCode } : {}), - ...(!res.ok && res.errorDetails ? { errorDetails: res.errorDetails } : {}) - } - } - if (capability === 'filesystem.openItem' || capability === 'system.openUrl') { - const target = String(params.path || params.url || params.fullPath || '') - const method = capability === 'system.openUrl' ? 'shell_open_external' : 'shell_open_path' - const res = await callHostTransport( - method, - capability === 'system.openUrl' ? { url: target } : { fullPath: target }, - hostOverride - ) - const s = ipcStrings() - return { - ok: res.ok, - code: res.ok ? 0 : -1, - message: res.ok ? s.opened : res.error || s.openFailed, - data: res.data, - error: res.error, - ...(!res.ok && res.errorCode ? { errorCode: res.errorCode } : {}), - ...(!res.ok && res.errorDetails ? { errorDetails: res.errorDetails } : {}) - } - } - - const pluginMapping = CAPABILITY_TO_PLUGIN_MAP[capability] - if (pluginMapping) { - const dllRes = await invokePluginService( - pluginMapping.plugin, - pluginMapping.func, - params, - hostOverride - ) - if (dllRes.ok) return dllRes - if (hostOverride) { - const fallbackMock = await callHostTransport(normalizedMethod, params, hostOverride) - if (fallbackMock.ok) { - return { - ok: true, - code: 0, - message: 'OK', - data: fallbackMock.data - } - } - } - return dllRes - } - - const res = await callHostTransport(normalizedMethod, params, hostOverride) - return { - ok: res.ok, - code: res.ok ? 0 : -1, - message: res.ok ? 'OK' : res.error || ipcStrings().callFailed, - data: res.data, - error: res.error, - ...(!res.ok && res.errorCode ? { errorCode: res.errorCode } : {}), - ...(!res.ok && res.errorDetails ? { errorDetails: res.errorDetails } : {}) - } -} - -export async function invokePluginService( - pluginName: string, - action: string, - params: Record = {}, - hostOverride?: DynamicBridge -): Promise> { - const s = ipcStrings() - // 1. 若测试注入了专门拦截 plugin_invoke 的 mock,支持调用 - if (hostOverride && typeof hostOverride.plugin_invoke === 'function') { - const mockRes = await callHostTransport( - 'plugin_invoke', - { plugin: pluginName, action, params }, - hostOverride - ) - return { - ok: mockRes.ok, - code: mockRes.ok ? 0 : -1, - message: mockRes.ok ? 'OK' : mockRes.error || s.pluginCallNotReady, - data: mockRes.data, - error: mockRes.error, - ...(!mockRes.ok && mockRes.errorCode ? { errorCode: mockRes.errorCode } : {}), - ...(!mockRes.ok && mockRes.errorDetails ? { errorDetails: mockRes.errorDetails } : {}) - } - } - - // 2. 优先走真实 Electron IPC 的 dllplugin_call 通道 - const dllRes = await callHostTransport( - 'dllplugin_call', - { plugin: pluginName, func: action, params }, - hostOverride - ) - if (dllRes.ok) { - const inner = dllRes.data - if (inner && typeof inner === 'object' && typeof inner.error === 'string' && inner.error.length > 0 && inner.ok !== true) { - return { - ok: false, - code: -1, - message: inner.error, - error: inner.error, - ...extractIpcErrorMeta(inner) - } - } - return { - ok: true, - code: 0, - message: 'OK', - data: inner as T - } - } - - // 3. 兼容单元测试中通过 transport.call('plugin_invoke') 注入的测试桩 - if (hostOverride) { - const legacyRes = await callHostTransport( - 'plugin_invoke', - { plugin: pluginName, action, params }, - hostOverride - ) - if (legacyRes.ok) { - return { - ok: true, - code: 0, - message: 'OK', - data: legacyRes.data - } - } - } - - // 4. 兼容旧版 globalThis.ztools.dllplugin.call - const g = globalThis as DynamicBridge - if (!hostOverride && typeof g?.ztools?.dllplugin?.call === 'function') { - try { - const raw = await g.ztools.dllplugin.call(pluginName, action, params) - if (raw && typeof raw === 'object' && raw.ok === false) { - return { - ok: false, - code: -1, - message: String(raw.error || s.callFailed), - error: String(raw.error || s.callFailed), - ...extractIpcErrorMeta(raw), - ...extractIpcErrorMeta(raw.error) - } - } - const data = raw && typeof raw === 'object' && 'data' in raw ? raw.data : raw - return { ok: true, code: 0, message: 'OK', data: data as T } - } catch (err: DynamicBridge) { - return { - ok: false, - code: -1, - message: err instanceof Error ? err.message : String(err), - error: err instanceof Error ? err.message : String(err), - ...extractIpcErrorMeta(err) - } - } - } - - return { - ok: false, - code: -1, - message: dllRes.error || s.pluginCallNotReady, - error: dllRes.error || s.pluginCallNotReady, - ...(dllRes.errorCode ? { errorCode: dllRes.errorCode } : {}), - ...(dllRes.errorDetails ? { errorDetails: dllRes.errorDetails } : {}) - } -} - -const SHA256_K = new Uint32Array([ - 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, - 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, - 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, - 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, - 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, - 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, - 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, - 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 -]) - -function rotr32(x: number, n: number): number { - return (x >>> n) | (x << (32 - n)) -} - -/** - * 标准 FIPS 180-4 SHA-256 真实字节摘要算法(返回 64 位小写 Hex) - */ -export function computeRealSha256Hex(input: string | Uint8Array): string { - const bytes = - typeof input === 'string' ? new TextEncoder().encode(input) : new Uint8Array(input || []) - const bitLen = bytes.length * 8 - const padLen = ((bytes.length + 9 + 63) & ~63) - const buf = new Uint8Array(padLen) - buf.set(bytes, 0) - buf[bytes.length] = 0x80 - const view = new DataView(buf.buffer) - view.setUint32(padLen - 8, Math.floor(bitLen / 0x100000000), false) - view.setUint32(padLen - 4, bitLen >>> 0, false) - - let h0 = 0x6a09e667 - let h1 = 0xbb67ae85 - let h2 = 0x3c6ef372 - let h3 = 0xa54ff53a - let h4 = 0x510e527f - let h5 = 0x9b05688c - let h6 = 0x1f83d9ab - let h7 = 0x5be0cd19 - - const w = new Uint32Array(64) - for (let offset = 0; offset < padLen; offset += 64) { - for (let i = 0; i < 16; i++) { - w[i] = view.getUint32(offset + i * 4, false) - } - for (let i = 16; i < 64; i++) { - const s0 = rotr32(w[i - 15], 7) ^ rotr32(w[i - 15], 18) ^ (w[i - 15] >>> 3) - const s1 = rotr32(w[i - 2], 17) ^ rotr32(w[i - 2], 19) ^ (w[i - 2] >>> 10) - w[i] = (w[i - 16] + s0 + w[i - 7] + s1) >>> 0 - } - - let a = h0 - let b = h1 - let c = h2 - let d = h3 - let e = h4 - let f = h5 - let g = h6 - let h = h7 - - for (let i = 0; i < 64; i++) { - const S1 = rotr32(e, 6) ^ rotr32(e, 11) ^ rotr32(e, 25) - const ch = (e & f) ^ (~e & g) - const temp1 = (h + S1 + ch + SHA256_K[i] + w[i]) >>> 0 - const S0 = rotr32(a, 2) ^ rotr32(a, 13) ^ rotr32(a, 22) - const maj = (a & b) ^ (a & c) ^ (b & c) - const temp2 = (S0 + maj) >>> 0 - - h = g - g = f - f = e - e = (d + temp1) >>> 0 - d = c - c = b - b = a - a = (temp1 + temp2) >>> 0 - } - - h0 = (h0 + a) >>> 0 - h1 = (h1 + b) >>> 0 - h2 = (h2 + c) >>> 0 - h3 = (h3 + d) >>> 0 - h4 = (h4 + e) >>> 0 - h5 = (h5 + f) >>> 0 - h6 = (h6 + g) >>> 0 - h7 = (h7 + h) >>> 0 - } - - return [h0, h1, h2, h3, h4, h5, h6, h7] - .map(v => (v >>> 0).toString(16).padStart(8, '0')) - .join('') -} - -/** - * 读取本地文件真实字节并计算标准 SHA-256:宿主 filesearch_sha256(只接受 path 字段)优先,Windows 上再试 FileComparePlugin。 - * 都拿不到时返回空字符串,由调用方提示失败;不再把文件按 UTF-8 文本读出来再算(二进制文件会算出错误的值)。 - */ -export async function computeRealFileSha256( - filePath: string, - hostOverride?: DynamicBridge -): Promise { - if (!filePath || !filePath.trim()) return '' - const target = filePath.trim() - - const shaRes = await callHostTransport('filesearch_sha256', { fullPath: target }, hostOverride) - if (shaRes.ok && shaRes.data) { - const hash = typeof shaRes.data === 'string' ? shaRes.data : String(shaRes.data?.sha256 || shaRes.data?.hash || '') - if (/^[0-9a-f]{64}$/i.test(hash)) return hash.toLowerCase() - } - - const dllRes = await invokePluginService('FileComparePlugin', 'computeFileSha256', { path: target }, hostOverride) - if (dllRes.ok && dllRes.data) { - const hash = typeof dllRes.data === 'string' ? dllRes.data : String(dllRes.data?.sha256 || dllRes.data?.hash || '') - if (/^[0-9a-f]{64}$/i.test(hash)) return hash.toLowerCase() - } - - return '' -} - -export async function readRealClipboardText(hostOverride?: DynamicBridge): Promise { - const res = await callHostTransport('clipboard_read_text', {}, hostOverride) - if (res.ok && res.data !== undefined && res.data !== null) { - if (typeof res.data === 'string') return res.data - if (typeof res.data?.text === 'string') return res.data.text - } - try { - if (typeof navigator !== 'undefined' && navigator.clipboard?.readText) { - return await navigator.clipboard.readText() - } - } catch { - // ignore - } - return '' -} - -export async function writeRealClipboardText(text: string, hostOverride?: DynamicBridge): Promise { - const payload = { text: String(text || '') } - const res = await callHostTransport('clipboard_copy_text', payload, hostOverride) - if (res.ok) return true - const fallbackRes = await callHostTransport('clipboard_write_text', payload, hostOverride) - if (fallbackRes.ok) return true - try { - if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) { - await navigator.clipboard.writeText(String(text || '')) - return true - } - } catch { - // ignore - } - return false -} - -export async function showRealToast( - title: string, - style: 'success' | 'failure' | 'info' = 'info' -): Promise { - try { - const { showToast, Toast } = await import('@ztools/declarative-ui') - await showToast({ - title, - style: - style === 'success' - ? Toast.Style.Success - : style === 'failure' - ? Toast.Style.Failure - : Toast.Style.Animated - }) - } catch { - // ignore - } -} - diff --git a/extensions/software-manager/tests/software-manager.host.test.mjs b/extensions/software-manager/tests/software-manager.host.test.mjs index 093d16fe..87974f1f 100644 --- a/extensions/software-manager/tests/software-manager.host.test.mjs +++ b/extensions/software-manager/tests/software-manager.host.test.mjs @@ -71,6 +71,9 @@ test('software-manager: 不在客户端里运行时不返回示例软件,也 assert.equal(list.error, notInClient) assert.equal(typeof softwareManager.getMockSoftwareList, 'undefined') assert.equal(typeof softwareManager.invokeNativeCapability, 'undefined') + const hostIpc = await import('../dist/host-ipc.js') + assert.equal(typeof hostIpc.invokeDllPluginCapability, 'undefined') + assert.equal(typeof hostIpc.invokePluginService, 'undefined') const un = await softwareManager.uninstallSoftware(softwareManager.mapRecordToSoftwareItem(APP_RECORDS[0], 0)) assert.equal(un.ok, false) assert.equal(un.error, notInClient) @@ -175,3 +178,56 @@ test('software-manager: AppData 目录只读列出,名称相近只作提示, assert.equal(noPath.ok, false) assert.match(noPath.error, /无法获取 AppData 路径/) }) + +test('software-manager: probeAppDataDirs 不重复二次扫描子目录,并透传 approximate 与扫描 error', async () => { + const roaming = 'C:\\Users\\RealUser\\AppData\\Roaming' + const local = 'C:\\Users\\RealUser\\AppData\\Local' + const searchQueries = [] + const host = createRealHostStub({ + system_get_path: ({ name }) => (name === 'appData' ? roaming : name === 'home' ? 'C:\\Users\\RealUser' : ''), + system_search_files: ({ query }) => { + searchQueries.push(query) + if (query === `dir:${roaming}`) { + return { + files: [], + subdirs: [ + { name: 'Google', path: `${roaming}\\Google`, file_count: 15, total_bytes: 900000, approximate: true }, + { name: 'TinyDir', path: `${roaming}\\TinyDir`, file_count: 1, total_bytes: 1024 } + ], + truncated: true, + approximate: true, + total_matches: 16 + } + } + if (query === `dir:${local}`) { + return { + files: [], + subdirs: [], + scan_error: '部分目录权限受限' + } + } + throw new Error(`不应发起二次子目录扫描: ${query}`) + } + }) + + const res = await softwareManager.probeAppDataDirs([], host) + assert.deepEqual(searchQueries.sort(), [`dir:${local}`, `dir:${roaming}`].sort()) + assert.equal(res.ok, true) + assert.equal(res.approximate, true) + assert.equal(res.items.length, 1) + assert.equal(res.items[0].folderName, 'Google') + assert.equal(res.items[0].fileCount, 15) + assert.equal(res.items[0].approximate, true) + assert.match(res.error, /部分目录权限受限/) + + // 两个根目录全部报错时返回 ok:false 且不吞掉错误 + const allFailHost = createRealHostStub({ + system_get_path: ({ name }) => (name === 'appData' ? roaming : name === 'home' ? 'C:\\Users\\RealUser' : ''), + system_search_files: () => { + throw new Error('磁盘拒绝访问') + } + }) + const failRes = await softwareManager.probeAppDataDirs([], allFailHost) + assert.equal(failRes.ok, false) + assert.match(failRes.error, /磁盘拒绝访问/) +}) diff --git a/extensions/speedtest/README.en.md b/extensions/speedtest/README.en.md new file mode 100644 index 00000000..4da81e52 --- /dev/null +++ b/extensions/speedtest/README.en.md @@ -0,0 +1,24 @@ +# Network Speed Test + +The macOS version provides two independent operations: + +- **Broadband Speed Test**: Select "Start Broadband Speed Test" and press `Enter` to run an approximately 15-second upload and download measurement using macOS's built-in `networkQuality`. This consumes actual network traffic, potentially reaching gigabytes on high-speed connections. Results measure throughput to Apple's test service and are affected by VPNs, current network load, and test server nodes. +- **Node Check**: Use "Check Preset Nodes" at the top or the `ping test` / `network check` / `diagnose network` command to read the real default route and check the gateway, then test preset sites over TCP 443: Tencent (`www.qq.com`), Taobao (`www.taobao.com`), Bilibili (`www.bilibili.com`), GitHub (`github.com`), and Cloudflare (`www.cloudflare.com`). You can also search/enter a domain, IPv4, IPv6, or `host:port` (defaults to 443 when port is omitted), select the test row, and press `Enter`. + +Website node checks use three TCP connections to the same remote address to measure average latency and consecutive sample variance, which cannot determine whether website login or application services are working. The default gateway check uses ICMP; if no gateway is provided (such as with certain VPN tunnels), the reason is shown without guessing an address. + +Selecting "Stop Check" or leaving the plugin requests termination of the ongoing operation. Timeouts, insufficient permissions, or unreachable test services display an error without generating estimated speeds. Reports can be copied, and unmeasured metrics are shown as not provided. + +References: [Apple Network Responsiveness Test](https://support.apple.com/en-us/101942), local `man networkQuality`. + +## Platforms & Requirements + +- Supported: macOS only +- Requires ZTools client 1.1.8.5 or later. +- Requires a macOS version with `networkQuality`. +- Not available on Windows: not listed in the plugin marketplace for Windows, and even if opened on Windows it only reports unavailability without showing estimated bandwidth or gateway details. + +## Network & Data + +- Broadband Speed Test invokes macOS's built-in `networkQuality` and connects to Apple's test service; the specific server is chosen by the system. +- Node Check connects to the 5 listed websites over TCP 443 and checks the default gateway with ICMP; when an address is entered manually, only the address you enter is contacted. diff --git a/extensions/speedtest/plugin.json b/extensions/speedtest/plugin.json index f80f473b..377c4492 100644 --- a/extensions/speedtest/plugin.json +++ b/extensions/speedtest/plugin.json @@ -1,8 +1,8 @@ { "id": "speedtest", "name": "网络测速", - "version": "1.1.9", - "description": "测量上下行吞吐量,检测默认网关与国内、国际节点连接;Mac 使用系统网络测速工具", + "version": "1.1.10", + "description": "测量上下行真实吞吐量,检测默认网关与国内、国际节点连接;macOS 使用系统 networkQuality,Windows 使用多流并发 HTTPS 真实测速", "author": "ZTools Team", "entry": "dist/index.js", "icon": "icon.svg", @@ -45,6 +45,12 @@ } ], "targets": [ + { + "id": "windows-electron-any", + "platform": "windows", + "runtime": "electron", + "arch": "any" + }, { "id": "macos-electron-any", "platform": "macos", @@ -57,14 +63,19 @@ "i18n": { "en-US": { "name": "Network Speed Test", - "description": "Measure upload and download throughput and check connectivity to default gateway, domestic, and global hosts (uses Apple networkQuality on macOS).", + "description": "Measure real upload/download throughput and check connectivity to default gateway, domestic, and global hosts (Apple networkQuality on macOS, multi-stream HTTPS on Windows).", "keywords": [ "speedtest", "bandwidth", "ping", "latency", "network", - "throughput" + "throughput", + "speed test", + "internet speed", + "bandwidth test", + "download speed", + "upload speed" ], "features": { "speedtest-full": { @@ -100,5 +111,15 @@ { "path": "screenshots/02-action-panel.png" } + ], + "keywords": [ + "网速测试", + "网络测速", + "测网速", + "宽带测速", + "下载速度", + "延迟测试", + "ping测速", + "speedtest" ] } diff --git a/extensions/speedtest/src/index.tsx b/extensions/speedtest/src/index.tsx index ec2a06f6..598ea020 100644 --- a/extensions/speedtest/src/index.tsx +++ b/extensions/speedtest/src/index.tsx @@ -14,9 +14,7 @@ export default function SpeedtestCommand(props: { featureCode?: string } = {}) { }).catch(e => { if (alive) setError(e instanceof Error ? e.message : String(e)) }) return () => { alive = false } }, [attempt]) - if (platform === 'macos') return MacCommand({ diagnostic: props.featureCode === 'speedtest-ping-check' }) - // Windows 旧测速接口会按延迟推算带宽、猜测网关,宿主已停用;新版测速接口目前只支持 macOS,这里明确告知而不显示估算结果 - if (platform === 'windows') return + if (platform === 'macos' || platform === 'windows') return MacCommand({ diagnostic: props.featureCode === 'speedtest-ping-check' }) return setAttempt(attempt + 1)} />} /> } export const commands = { diff --git a/extensions/speedtest/tests/mac-speedtest.test.mjs b/extensions/speedtest/tests/mac-speedtest.test.mjs index dc758bbd..858923ce 100644 --- a/extensions/speedtest/tests/mac-speedtest.test.mjs +++ b/extensions/speedtest/tests/mac-speedtest.test.mjs @@ -60,15 +60,13 @@ test('预设节点单项重测保留名称和分类,中文搜索不会隐藏 await v.run(v.item('node-example.com:443'),'重新检测此节点');assert.match(v.text(),/测试节点/);assert.equal(v.item('node-example.com:443').props.title,'测试节点') }) -test('Windows:明确提示暂不可用,不调用旧测速接口、不显示估算带宽或网关', async () => { +test('Windows:双端统一走 network_speedtest IPC 测量真实带宽与节点,绝不调用旧 dllplugin_call', async () => { host.ipc.system_get_platform=async()=>({success:true,platform:'windows'}) - // 故障注入:即使旧接口仍回出“成功”的估算结果,界面也不能去调用或展示它 - host.ipc.dllplugin_call=async()=>({ok:true,success:true,downloadMbps:500,uploadMbps:150,gatewayIp:'192.168.1.1',localIp:'192.168.1.101'}) - for(const c of [Command,commands['speedtest-ping-check']]){ - const v=await open(c);assert.match(v.item('unsupported').props.title,/Windows 版网络测速暂不可用/) - assert.doesNotMatch(v.text(),/Mbps|192\.168\.1\./) - } - assert.ok(!host.ipcCalls.some(([m])=>m==='dllplugin_call'||m==='network_speedtest')) + const v=await open();assert.equal(calls('bandwidth').length,0) + await v.run(v.item('bandwidth'),'开始测量带宽');await tick() + assert.equal(calls('bandwidth').length,1);assert.match(v.text(),/下载 125.0 Mbps/) + const diag=await open(commands['speedtest-ping-check']);assert.equal(calls('diagnose').length,1);assert.match(diag.text(),/TCP 3\/3/) + assert.ok(!host.ipcCalls.some(([m])=>m==='dllplugin_call')) // 平台确认失败仍报真实错误,不落到任何测速界面 host.ipc.system_get_platform=async()=>{throw Error('平台查询失败')} const failed=await open();assert.match(failed.text(),/平台查询失败/) diff --git a/extensions/sql-helper/README.en.md b/extensions/sql-helper/README.en.md new file mode 100644 index 00000000..752b9741 --- /dev/null +++ b/extensions/sql-helper/README.en.md @@ -0,0 +1,36 @@ +# SQL Formatter & Converter + +Perform SQL formatting, MyBatis log parameter verification, and `CREATE TABLE` field model generation locally in the client. Does not connect to any database or execute the input SQL. + +Search `format sql`, `mybatis`, or `ddl to entity` to jump directly to the corresponding tool. Press `Enter` to load from the clipboard, or `⌘/Ctrl+Enter` to open the multiline editor; inside the editor, select the SQL dialect and press `⌘/Ctrl+Enter` to generate results. The search box filters output formats only; press `Enter` to copy the current result, and `Esc` to cancel editing. Each of the three tools retains its own input during the current session. + +- **Format & Minify**: Adjusts only whitespace between lexical tokens while preserving casing, identifiers, strings, and comments. Line comments and existing line breaks in PostgreSQL are preserved, so minified output is not guaranteed to be a single line. This is not a database syntax validator. +- **MyBatis**: Paste the complete `Preparing` and `Parameters` lines from the same call. Mismatched counts, multiple log groups, continuation lines, unrecognized types, or ambiguities stop processing. Replaces only `?` placeholders in code while skipping strings and comments. Output is for verification reference only; logs have no lossless escaping protocol and are not an exact substitute for JDBC parameter binding. Dates, timezones, and custom types in particular require manual verification. +- **DDL Models**: Processes one table at a time, splitting fields by parenthesis depth and quotes, supporting single-line and multiline declarations, common types, and table-level primary keys. Generates TypeScript interfaces, Go structs with JSON/GORM column tags, and Java classes without Lombok. Actual field types depend on the SQL dialect and driver; generated output is an editable model skeleton, not a database migration validator. Unknown types are flagged clearly, and unrecognized structures do not produce partial output. +- `bigint` and exact decimals avoid precision loss via JavaScript `number`; nullable fields use `| null` in TS and pointers in Go. MySQL `tinyint(1)` / `BOOL` still map as integers, and `TIME` maps as a duration string. SQLite integers are treated as 64-bit; non-integer primary keys in regular tables remain nullable, while `INTEGER` rowid, `STRICT`, and `WITHOUT ROWID` tables are handled specifically. +- Column names that cannot be reliably represented in Go JSON/GORM tags (such as commas, semicolons, quotes, backslashes, or a standalone `-`) block generation; use explicit field aliases first. JSON key names are never silently altered and extra ORM settings are not injected. + +Supports MySQL default backslash escaping, PostgreSQL standard strings, and SQLite lexical modes. When using different settings such as MySQL `NO_BACKSLASH_ESCAPES` / `ANSI_QUOTES` or PostgreSQL with `standard_conforming_strings` disabled, do not interpret literals directly with default mode. Vendor-specific extensions, stored procedures, and full constraint validation are outside the scope of field model extraction. + +Input is limited to 256 KiB, up to 50,000 SQL tokens, 64 levels of parentheses, 500 MyBatis parameters, and 1,000 model columns. Failures display the reason; invalid edits do not overwrite existing valid content, and invalid clipboard input clears old output so stale results are not copied by mistake. + +## Platforms & Requirements + +- Supported: Windows, macOS + +## Network & Data + +- Offline only; data is stored locally only. + +## Build & Verification + +Run from the plugin repository root: + +```sh +node scripts/build-declarative.mjs sql-helper +node --test extensions/sql-helper/tests/*.test.mjs +``` + +Tests use Node 22's built-in SQLite to execute synthetic SQL in an in-memory database and verify table structures, and the project TypeScript compiler checks generated models. When Go/JDK toolchains are present, tests also compile Go/Java code and verify Go JSON serialization; if a toolchain is missing, uncovered diagnostics are reported and must be verified in an environment with those toolchains before release. Tests never access user databases. + +Lexical and type references: [PostgreSQL Lexical Structure](https://www.postgresql.org/docs/current/sql-syntax-lexical.html), [MySQL String Literals](https://dev.mysql.com/doc/refman/8.4/en/string-literals.html), [MySQL Numeric Types](https://dev.mysql.com/doc/refman/8.4/en/numeric-type-syntax.html), [SQLite CREATE TABLE](https://www.sqlite.org/lang_createtable.html), [MyBatis Logging Implementation](https://github.com/mybatis/mybatis-3/blob/master/src/main/java/org/apache/ibatis/logging/jdbc/BaseJdbcLogger.java). diff --git a/extensions/sql-helper/plugin.json b/extensions/sql-helper/plugin.json index 64ec4fa8..a0379f8a 100644 --- a/extensions/sql-helper/plugin.json +++ b/extensions/sql-helper/plugin.json @@ -1,7 +1,8 @@ { "id": "sql-helper", "name": "SQL格式化转换", - "version": "1.0.4", + "version": "1.0.5", + "minAppVersion": "1.1.8.0", "description": "SQL美化与精简、MyBatis日志参数核对、CREATE TABLE转TypeScript/Go/Java模型;支持多行编辑与剪贴板输入", "author": "ZTools Team", "category": [ @@ -76,7 +77,13 @@ "mybatis", "ddl", "entity", - "codegen" + "codegen", + "sql formatter", + "format sql", + "beautify sql", + "minify sql", + "sql converter", + "query format" ], "features": { "sql-formatter": { @@ -125,5 +132,14 @@ { "path": "screenshots/03-interactive.png" } + ], + "keywords": [ + "sql格式化", + "美化sql", + "压缩sql", + "sql转换", + "建表语句", + "sql整理", + "sql" ] } diff --git a/extensions/sql-helper/src/index.tsx b/extensions/sql-helper/src/index.tsx index 6f48d32a..6e5799c3 100644 --- a/extensions/sql-helper/src/index.tsx +++ b/extensions/sql-helper/src/index.tsx @@ -60,7 +60,7 @@ export function SqlSourceForm({ tab, source, save }: { tab: SqlHelperTab; source
- + } @@ -97,11 +97,17 @@ export function SqlHelperCommand({ initialTab = 'formatter' }: { initialTab?: Sq searchBarAccessory={ { revision.current++; setTab(value as SqlHelperTab); setQuery('') }} tooltip={t('switchToolTooltip')}> {Object.entries(modes).map(([value, title]) => )} } - filterBar={output ? { summaryText: `${modes[tab]} · ${source.dialect}`, actions: [{ id: 'clipboard', title: t('loadClipboard'), onAction: () => void clipboard() }, { id: 'edit', title: t('editSource'), onAction: edit }] } : undefined} + filterBar={{ + summaryText: output ? `${modes[tab]} · ${source.dialect}` : state.kind === 'error' ? t('inputErrorTitle') : guides[tab].title, + actions: [ + { id: 'clipboard', title: t('loadClipboard'), ...(output ? {} : { style: 'primary' as const }), onAction: () => void clipboard() }, + { id: 'edit', title: t('editSource'), onAction: edit } + ] + }} > {!output && } - actions={ void clipboard()} />} + actions={ void clipboard()} />} />} {output?.outputs.filter(item => `${item.title} ${item.language}`.toLowerCase().includes(query.trim().toLowerCase())).map(item => } diff --git a/extensions/sqlite-plugin/README.en.md b/extensions/sqlite-plugin/README.en.md new file mode 100644 index 00000000..af9847a8 --- /dev/null +++ b/extensions/sqlite-plugin/README.en.md @@ -0,0 +1,20 @@ +# SQLite Viewer + +Open SQLite database files chosen, dropped, or imported from a folder to inspect table names, row counts, columns, and records in read-only mode, and export rows as text to the clipboard. + +## Usage + +- Command: `SQLite Viewer` (`sqlite`, `sqlite viewer`, `db viewer`, `open sqlite`, `browse db`). +- Opens with an empty list. Import `.db`, `.sqlite`, `.sqlite3`, or `.db3` files—or folders containing them—via the top "Select Files" / "Select Folder" buttons (or `Ctrl+O` / `Ctrl+Shift+O`), drag-and-drop, or paste; switch between multiple databases using the top dropdown. Use `Ctrl+Backspace` to remove the current database from the list (without deleting disk files) or `Ctrl+Shift+Backspace` to clear the list. When reading fails, the status bar and empty state accurately show the reason. +- The left pane lists all tables and views along with row counts and columns; selecting a table displays its first 50 rows on the right. No rows are checked on open; when nothing is checked, exporting includes all rows currently listed. +- Select rows and press `Enter` to export as JSON, `Ctrl+Enter` to export as SQL `INSERT` statements, or `Ctrl+K` to export as CSV or reveal the database file in File Explorer; press `Ctrl+Enter` on a table row in the left pane to export as JSON. Exported text is copied to the clipboard, with failure reasons shown if copying fails. +- Exports contain raw field values: JSON as an array of objects, CSV with column names in the first row, and SQL `INSERT` with explicit table and column names; binary fields are exported as hexadecimal text. Only the loaded first 50 rows are included, not the entire table. +- Read-only: does not execute write queries or maintenance statements such as `VACUUM`, and never modifies database files. Reads the main database file directly, so recent writes from other running programs may not appear immediately. + +## Platforms & Requirements + +- Supported: Windows only + +## Network & Data + +- Offline only; no data is saved. diff --git a/extensions/sqlite-plugin/plugin.json b/extensions/sqlite-plugin/plugin.json index 6bb6d94d..2ce07e48 100644 --- a/extensions/sqlite-plugin/plugin.json +++ b/extensions/sqlite-plugin/plugin.json @@ -2,7 +2,7 @@ "id": "sqlite-plugin", "name": "SQLite 查看器", "description": "选择、拖入或从文件夹导入 SQLite 数据库文件,记住最近打开记录,只读查看表结构与分页浏览记录,并导出为 CSV / JSON / SQL INSERT 文本", - "version": "2.0.14", + "version": "2.0.15", "minAppVersion": "1.1.8.7", "author": "ZTools Team", "entry": "dist/index.js", @@ -55,7 +55,12 @@ "viewer", "sql", "csv", - "json" + "json", + "sqlite viewer", + "db viewer", + "open db", + "sql browser", + "inspect sqlite" ], "features": { "sqlite-viewer": { @@ -83,5 +88,14 @@ { "path": "screenshots/02-action-panel.png" } + ], + "keywords": [ + "sqlite", + "看数据库", + "打开db文件", + "sqlite查看器", + "数据库查看", + "db浏览", + "查表" ] } diff --git a/extensions/sqlite-plugin/src/index.ts b/extensions/sqlite-plugin/src/index.ts index 94460660..a9783b67 100644 --- a/extensions/sqlite-plugin/src/index.ts +++ b/extensions/sqlite-plugin/src/index.ts @@ -748,7 +748,7 @@ export function SqlitePluginCommand() { id: "pick-files", label: t("pickFilesBtn"), title: t("pickFilesBtn"), - style: "secondary", + style: databases.length === 0 ? "primary" : "secondary", onAction: handlePickFiles }, { @@ -757,29 +757,7 @@ export function SqlitePluginCommand() { title: t("pickFolderBtn"), style: "secondary", onAction: handlePickFolder - }, - ...(hasPrevPage - ? [ - { - id: "prev-page", - label: t("prevPageAction"), - title: t("prevPageAction"), - style: "secondary" as const, - onAction: goPrevPage - } - ] - : []), - ...(hasNextPage - ? [ - { - id: "next-page", - label: t("nextPageAction"), - title: t("nextPageAction"), - style: "secondary" as const, - onAction: goNextPage - } - ] - : []) + } ] }), subList: { diff --git a/extensions/sqlite-plugin/src/native-ipc.ts b/extensions/sqlite-plugin/src/native-ipc.ts index 51576b99..13643277 100644 --- a/extensions/sqlite-plugin/src/native-ipc.ts +++ b/extensions/sqlite-plugin/src/native-ipc.ts @@ -174,11 +174,13 @@ function normalizeMethodResult(method: string, payload: DynamicBridge): DynamicB if (method === 'system_get_battery_status') { // 宿主约定 percent 超出 0-100(如 255)表示无电池或电量未知,不能改写成 100% + // 若宿主明确给出 hasBattery 布尔值,必须原样保留,仅在缺失时按合法电量推算 const rawPct = payload.percent - const hasBattery = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const validPct = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const hasBattery = typeof payload.hasBattery === 'boolean' ? payload.hasBattery : validPct return { ...payload, - percent: hasBattery ? rawPct : null, + percent: validPct ? rawPct : null, hasBattery } } @@ -489,6 +491,8 @@ export interface RealDirectoryScanResult extends Iterable approximate?: boolean /** 宿主实际遍历的条目数 */ visitedEntries?: number + /** 目录本身不存在(ENOENT) */ + missing?: boolean /** 读取失败的真实原因;已有文件仍可使用,但不能当作完整结果。 */ error?: string } @@ -497,6 +501,7 @@ interface ScanResultMeta { truncated?: boolean approximate?: boolean visitedEntries?: number + missing?: boolean } export interface ScanDirectoryTreeOptions { @@ -504,6 +509,10 @@ export interface ScanDirectoryTreeOptions { maxFiles?: number collectTopN?: number filterExt?: RegExp + /** 为 true 时,目录本身不存在(ENOENT)按空目录处理,不返回 error(权限拒绝/读取失败仍照常报错) */ + ignoreMissing?: boolean + /** Top-N 保留与排序方式:默认按体积降序,下载/录屏等时效场景可传 mtime-desc */ + sortBy?: 'size-desc' | 'mtime-desc' hostOverride?: DynamicBridge } @@ -519,8 +528,9 @@ function normalizeIndexedFileEntry(f: DynamicBridge): RealIndexedFileEntry { const sz = Number(f?.size ?? f?.sizeBytes ?? 0) const isDir = Boolean(f?.is_dir || f?.isDir || f?.isDirectory) const rawMtime = Number(f?.mtime ?? f?.mtimeMs ?? 0) - const mtimeMs = rawMtime > 1e11 ? rawMtime : rawMtime > 0 ? rawMtime * 1000 : Date.now() - const mtimeSec = rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime + const validMtime = Number.isFinite(rawMtime) && rawMtime > 0 + const mtimeMs = validMtime ? (rawMtime > 1e11 ? rawMtime : rawMtime * 1000) : 0 + const mtimeSec = validMtime ? (rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime) : 0 if (p && sz >= 0) realFileSizeCache.set(p, sz) return { name, @@ -551,6 +561,7 @@ function makeScanResult( subdirs, ...(meta.truncated ? { truncated: true } : {}), ...(meta.approximate ? { approximate: true } : {}), + ...(meta.missing ? { missing: true } : {}), ...(typeof meta.visitedEntries === 'number' ? { visitedEntries: meta.visitedEntries } : {}), [Symbol.iterator]() { return files[Symbol.iterator]() @@ -609,13 +620,40 @@ export async function scanRealDirectoryTree( return result.error ? { ...result.scan, error: result.error } : result.scan } +/** 仅当正则明确声明了扩展名(含 `\.`)时提取后缀列表,避免把 `thumbcache|iconcache` 等文件名关键词误拆成假扩展名 */ +function extractExtensionTokensFromFilter(filterExt: RegExp): string[] { + const src = filterExt.source + if (!src.includes('\\.')) return [] + const afterDot = src.slice(src.indexOf('\\.') + 2) + const rawTokens = afterDot.match(/[a-z0-9]{1,8}/gi) || [] + const seen = new Set() + const out: string[] = [] + for (const token of rawTokens) { + const lower = token.toLowerCase() + if (!lower || seen.has(lower)) continue + seen.add(lower) + out.push(lower) + } + return out +} + +function isMissingDirectoryError(res: { error?: string; errorCode?: string; errorDetails?: Record }): boolean { + if (res.errorDetails?.reason === 'ENOENT' || res.errorCode === 'ENOENT') return true + const msg = String(res.error || '') + return /Directory does not exist|ENOENT/i.test(msg) +} + /** 一次界面扫描的错误汇总;多个目录并行扫描时保留可读目录的结果。 */ export function createDirectoryScanner(hostOverride?: DynamicBridge) { const failures = new Map() return { async scan(dir: string, options: number | ScanDirectoryTreeOptions = 160) { const result = await scanRealDirectoryTree(dir, options, hostOverride) - const error = result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') + const ignoreMissing = typeof options === 'object' && options !== null && options.ignoreMissing === true + const error = + result.missing && ignoreMissing + ? '' + : result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') if (error) failures.set(dir, error) else failures.delete(dir) return result @@ -648,26 +686,38 @@ async function scanDirectoryTreeWithError( const safeLimit = Math.min(200, Math.max(1, Math.floor(rawLimit || 160))) const hostOverride = opts.hostOverride const filterExt = opts.filterExt + const ignoreMissing = opts.ignoreMissing === true const dirQuery = `dir:${targetDir}` try { let rawPayload: DynamicBridge = null + const searchParams: Record = { + query: dirQuery, + limit: safeLimit, + ...(opts.sortBy ? { sortBy: opts.sortBy } : {}) + } const res = await callHostTransport( 'system_search_files', - { query: dirQuery, limit: safeLimit }, + searchParams, hostOverride ) - if (res.ok && res.data) { + if (res.ok && res.data && res.data.degraded !== true) { rawPayload = res.data + } else if (!res.ok && ignoreMissing && isMissingDirectoryError(res)) { + const missingScan = makeScanResult([], 0, 0, [], { missing: true }) + return { scan: missingScan } } - if (!rawPayload && !hostOverride && typeof window !== 'undefined') { + if (!rawPayload && !hostOverride && res.errorCode === 'METHOD_NOT_AVAILABLE' && typeof window !== 'undefined') { const w = window as DynamicBridge if (typeof w.__ztoolsLauncher?.searchFiles === 'function') { const rawOuter = await w.__ztoolsLauncher.searchFiles(dirQuery, safeLimit) - rawPayload = + const candidate = rawOuter && typeof rawOuter === 'object' && 'data' in rawOuter && rawOuter.data ? rawOuter.data : rawOuter + if (candidate && candidate.degraded !== true && candidate.success !== false) { + rawPayload = candidate + } } } @@ -678,29 +728,32 @@ async function scanDirectoryTreeWithError( let files: RealIndexedFileEntry[] = rawPayload.files.map(normalizeIndexedFileEntry) if (filterExt instanceof RegExp) { files = files.filter(f => !f.isDir && (filterExt.test(f.name) || filterExt.test(f.ext))) - // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索目标扩展名 + // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索明确声明的目标扩展名 if (files.length === 0 && !hostOverride) { - const extTokens = (filterExt.source.match(/[a-z0-9]{2,5}/gi) || []) - .filter(t => !['thumbcache', 'iconcache'].includes(t.toLowerCase())) - .slice(0, 4) - // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 - const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() - const extraLists = await Promise.all( - extTokens.map(ext => searchRealIndexedFiles(`.${ext.toLowerCase()}`, 30, hostOverride)) - ) - const seen = new Set() - for (const list of extraLists) { - for (const item of list) { - if (!item.isDir && item.size > 0 && !seen.has(item.path)) { - if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { - seen.add(item.path) - files.push(item) + const extTokens = extractExtensionTokensFromFilter(filterExt) + if (extTokens.length > 0) { + // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 + const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() + const extraLists = await Promise.all( + extTokens.map(ext => searchRealIndexedFiles(`.${ext}`, 30, hostOverride)) + ) + const seen = new Set() + for (const list of extraLists) { + for (const item of list) { + if (!item.isDir && item.size > 0 && !seen.has(item.path)) { + if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { + seen.add(item.path) + files.push(item) + } } } } } } } + // 先基于过滤后的完整命中集合计算总文件数与总字节数,再按 collectTopN 裁剪样本列表 + const matchedCount = files.length + const matchedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) if (typeof opts.collectTopN === 'number' && opts.collectTopN > 0 && files.length > opts.collectTopN) { files = files.slice(0, opts.collectTopN) } @@ -714,11 +767,10 @@ async function scanDirectoryTreeWithError( ...(s.approximate === true ? { approximate: true } : {}) })) : [] - const computedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) const totalFilesCount = - filterExt instanceof RegExp ? files.length : Number(rawPayload.total_matches ?? files.length) + filterExt instanceof RegExp ? matchedCount : Number(rawPayload.total_matches ?? matchedCount) const totalBytesCount = - filterExt instanceof RegExp ? computedBytes : Number(rawPayload.total_bytes ?? computedBytes) + filterExt instanceof RegExp ? matchedBytes : Number(rawPayload.total_bytes ?? matchedBytes) const visited = Number(rawPayload.visited_entries) return { scan: makeScanResult(files, totalFilesCount, totalBytesCount, subdirs, { @@ -1817,8 +1869,6 @@ export async function writeRealClipboardText(text: string, hostOverride?: Dynami const payload = { text: String(text || '') } const res = await callHostTransport('clipboard_copy_text', payload, hostOverride) if (res.ok) return true - const fallbackRes = await callHostTransport('clipboard_write_text', payload, hostOverride) - if (fallbackRes.ok) return true try { if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) { await navigator.clipboard.writeText(String(text || '')) diff --git a/extensions/ssh-proxy-helper/README.en.md b/extensions/ssh-proxy-helper/README.en.md new file mode 100644 index 00000000..234f7508 --- /dev/null +++ b/extensions/ssh-proxy-helper/README.en.md @@ -0,0 +1,26 @@ +# SSH & Dev Proxy Helper + +Read host aliases from your local SSH config to connect or start local port forwarding in a terminal, inspect and update proxy settings in Git and NPM user configs, or open a new terminal with proxy environment variables set. + +## Usage + +- Commands: `ssh` (also `proxy`, `ssh hosts`, `dev proxy`); proxy only: `toggle proxy`, `terminal proxy`; port forwarding: `port forward`, `ssh tunnel`. +- The host list comes from explicit `Host` aliases in your SSH config and its `Include` files (wildcard rules are not listed individually). Only config files are read—private key contents are never read. Config locations: + - Windows: `%USERPROFILE%\.ssh\config`, system-wide `%ProgramData%\ssh\ssh_config` + - macOS: `~/.ssh/config` +- Select a host and press `Enter` to connect in a new terminal, or `⌘/Ctrl+Enter` to start local port forwarding (these two actions are swapped when opened via `port forward`). Use `⌘/Ctrl+K` to copy the connection command. Port forwarding listens only on `127.0.0.1` and stays active while the terminal remains open; press `Ctrl+C` to stop it. +- Git and NPM proxy: set a local HTTP proxy port or clear the proxy. Before writing, a diff preview is shown for confirmation, the original file is backed up, and the file is read back to verify. Switch to "Modified Backups" in the top dropdown to preview and restore previous configs. Only the user config files listed in the UI are modified; repository-level configs or environment variables may still override them. +- Proxied new terminal: opens a new terminal window with proxy environment variables set; already open terminals are unaffected. The plugin does not start your proxy software for you. +- macOS opens connections in the Terminal app. Windows uses the built-in OpenSSH client (`System32\OpenSSH\ssh.exe`), prompting you to install it via "Settings > System > Optional features" if missing; modifying the Git proxy requires Git for Windows to be installed. +- If reading or updating fails, the actual error reason is shown without pretending changes took effect. + +## Platforms & Requirements + +- Supported: Windows, macOS +- Requires ZTools client 1.1.8.5 or later. +- Windows implementation is pending verification on a physical machine; behavior may vary across different terminal environments, proxy tools, and Git configurations. + +## Network & Data + +- The plugin itself makes no network requests; SSH connections and port forwarding are performed by the system `ssh` client in your terminal against your configured hosts. +- Backups created before modifying Git or NPM configs are stored locally. diff --git a/extensions/ssh-proxy-helper/plugin.json b/extensions/ssh-proxy-helper/plugin.json index 79d5a639..ba595910 100644 --- a/extensions/ssh-proxy-helper/plugin.json +++ b/extensions/ssh-proxy-helper/plugin.json @@ -1,7 +1,7 @@ { "id": "ssh-proxy-helper", "name": "主机与代理", - "version": "1.0.7", + "version": "1.0.8", "description": "管理 SSH 主机连接、端口转发及 Git、NPM 和新终端的本地代理配置", "author": "ZTools Team", "category": [ @@ -75,7 +75,13 @@ "tunnel", "port forward", "git proxy", - "npm proxy" + "npm proxy", + "ssh config", + "server", + "remote host", + "dev proxy", + "system proxy", + "terminal connect" ], "features": { "ssh-all": { @@ -120,5 +126,15 @@ { "path": "screenshots/02-action-panel.png" } + ], + "keywords": [ + "ssh", + "主机管理", + "连接服务器", + "代理切换", + "系统代理", + "服务器快捷连接", + "远程主机", + "proxy" ] } diff --git a/extensions/ssl-domain-check/README.en.md b/extensions/ssl-domain-check/README.en.md new file mode 100644 index 00000000..c8891e57 --- /dev/null +++ b/extensions/ssl-domain-check/README.en.md @@ -0,0 +1,22 @@ +# SSL & Domain Diagnostics + +Inspect the trust status, hostname match, validity period, and certificate chain of a domain's HTTPS (port 443) certificate, and query its DNS records. + +## Usage + +- Commands: `ssl` (also `tls`, `cert`, `dns`, `dig`, `nslookup`, `domain check`). +- Enter a domain or URL (such as `example.com`) in the search box and press `Enter` to query. Only port 443 is queried; if the URL includes another port, you will be prompted to remove it. +- Certificate results show trust verification, hostname match, TLS protocol, valid-from and expiration dates, issuer, Subject Alternative Names (SANs), SHA-256 fingerprint, and the certificate chain (up to 8 items). Certificates expiring within 14 days are marked as expiring soon. Select the certificate and press `Enter` to copy the diagnostic summary. +- DNS queries `A`, `AAAA`, `CNAME`, `MX`, and `TXT` records; filter by record type in the top dropdown, and select any record and press `Enter` to copy its value. +- Certificate and DNS checks run independently: if one fails, the other still displays normally alongside the failure reason. Queries can be canceled while in progress. + +## Platforms & Requirements + +- Supported: Windows, macOS +- Requires ZTools client 1.1.8.5 or later. + +## Network & Data + +- Certificate: the client connects directly to port 443 of the domain you enter to read the certificate. +- DNS: queries Cloudflare's DNS over HTTPS service (`cloudflare-dns.com`), which sends the domain name you entered to that service. +- No query history is saved. diff --git a/extensions/ssl-domain-check/plugin.json b/extensions/ssl-domain-check/plugin.json index 10c7bf68..1b857343 100644 --- a/extensions/ssl-domain-check/plugin.json +++ b/extensions/ssl-domain-check/plugin.json @@ -1,7 +1,7 @@ { "id": "ssl-domain-check", "name": "域名与SSL诊断", - "version": "1.0.6", + "version": "1.0.7", "description": "查询域名真实 TLS 证书、信任与名称匹配状态、有效期和证书链,并查看 DNS 解析记录", "author": "ZTools Team", "category": [ @@ -59,7 +59,12 @@ "certificate", "dns", "dig", - "domain" + "domain", + "https check", + "domain check", + "dns lookup", + "cert expiry", + "whois" ], "features": { "ssl-domain-check": { @@ -89,5 +94,15 @@ { "path": "screenshots/02-action-panel.png" } + ], + "keywords": [ + "ssl证书", + "证书过期", + "域名诊断", + "https检测", + "whois", + "查域名", + "域名解析", + "ssl检查" ] } diff --git a/extensions/startup-manager/README.en.md b/extensions/startup-manager/README.en.md new file mode 100644 index 00000000..69f46cd6 --- /dev/null +++ b/extensions/startup-manager/README.en.md @@ -0,0 +1,19 @@ +# Startup Manager + +Inspect startup applications, background services, and scheduled tasks. Windows reads Registry entries, Startup folders, Services, and Task Scheduler; macOS reads user and system `LaunchAgents` and system `LaunchDaemons`. + +On macOS, "Auto-start Allowed" and "Currently Running" are displayed separately. Pressing `Enter` toggles whether launch is allowed on next load without terminating running processes or starting tasks immediately. Original configuration and state snapshots are preserved before modification, and system state is re-read afterward to confirm the result. + +On macOS, the filter next to the search box lets you filter by user configs, system services, scheduled tasks, disabled items, or missing-binary configs; "Restore Records" reverts previous auto-start state changes. Before restoring, it checks whether the configuration still matches the backup and stops if subsequent changes are detected. Restoring reverts to the originally active allowed state; macOS may retain an explicit enabled/disabled override record. + +On macOS, this plugin lists only `launchd` configs in those three directories: "Open at Login" apps and background items registered inside an app bundle via `SMAppService` are not listed here—manage those in "System Settings > General > Login Items & Extensions". The "Scheduled Tasks" filter refers to `launchd` jobs configured with `StartInterval` / `StartCalendarInterval`, and "System Services" refers to global `LaunchAgents` and `LaunchDaemons` under `/Library`. Failed changes display the failure reason and reload the list. On macOS, read errors display specific error messages rather than treating missing permissions as having no startup items. + +On Windows, read failures display "Failed to read startup items; list is unreliable", and partial source failures indicate that the list is incomplete. + +Modifying system-level configs on macOS requires administrator authorization; canceling authorization is never reported as success. When a binary is genuinely missing on macOS, you can choose "Remove Invalid Config (Restorable)" from the action panel: the original plist is kept in a private recovery directory under the same parent directory, and the client retains a restore record. Restoration stops to preserve newer changes if a new file exists at the original path or if the config bytes or override state have changed. Neither cleanup nor restoration stops or starts tasks immediately; changes take effect after signing back in. + +## Platforms & Requirements + +- Supported: Windows, macOS +- Requires ZTools client 1.1.8.5 or later. +- Windows implementation is pending verification on a physical machine. diff --git a/extensions/startup-manager/plugin.json b/extensions/startup-manager/plugin.json index 168e3a15..07f0ba56 100644 --- a/extensions/startup-manager/plugin.json +++ b/extensions/startup-manager/plugin.json @@ -1,8 +1,8 @@ { "id": "startup-manager", "name": "启动管理", - "description": "查看启动应用、后台服务与计划任务,管理自启状态;Mac 修改前保留可恢复的配置记录", - "version": "1.0.9", + "description": "跨端统一管理开机启动项、后台服务与计划任务;Windows 基于 StartupApproved 12 字节机制,macOS 基于 launchd,修改前自动保存可恢复记录", + "version": "1.0.10", "author": "ZTools Team", "entry": "dist/index.js", "icon": "icon.svg", @@ -69,13 +69,19 @@ "i18n": { "en-US": { "name": "Startup Manager", - "description": "Inspect and toggle startup apps, background services, and scheduled tasks, preserving restorable configuration snapshots on macOS.", + "description": "Manage startup apps, background services, and scheduled tasks across Windows (StartupApproved 12-byte mechanism) and macOS (launchd) with restorable backup snapshots.", "keywords": [ "startup", "autoruns", "services", "scheduled tasks", - "boot" + "boot", + "startup manager", + "boot items", + "login items", + "autostart", + "launchd", + "disable startup" ], "features": { "startup-all": { @@ -115,5 +121,15 @@ { "path": "screenshots/01.png" } + ], + "keywords": [ + "启动管理", + "开机自启", + "开机启动项", + "禁用自启", + "开机慢", + "管理自启", + "启动项清理", + "startup" ] } diff --git a/extensions/startup-manager/src/index.tsx b/extensions/startup-manager/src/index.tsx index 89b02873..bc6e882e 100644 --- a/extensions/startup-manager/src/index.tsx +++ b/extensions/startup-manager/src/index.tsx @@ -1,21 +1,20 @@ import React, { Action, ActionPanel, List, useEffect, useLocale, useState } from '@ztools/declarative-ui' -import WindowsCommand from './windows-command.js' import MacCommand from './mac-command.js' import { startupInvoke } from './mac-service.js' import { t } from './i18n.js' -export default function StartupManagerCommand(props: { featureCode?: string; hostOverride?: unknown } = {}) { + +export default function StartupManagerCommand(props: { featureCode?: string } = {}) { useLocale() - const [platform, setPlatform] = useState(''), [error, setError] = useState(''), [attempt, setAttempt] = useState(0) + const [platform, setPlatform] = useState<'macos' | 'windows' | ''>(''), [error, setError] = useState(''), [attempt, setAttempt] = useState(0) useEffect(() => { let alive = true; setError('') void startupInvoke('system_get_platform', {}).then(data => { - if (typeof data.platform !== 'string' || !['macos', 'windows'].includes(data.platform)) throw new Error(t('errUnsupportedPlatform')) + if (data.platform !== 'macos' && data.platform !== 'windows') throw new Error(t('errUnsupportedPlatform')) if (alive) setPlatform(data.platform) }).catch(e => { if (alive) setError(e instanceof Error ? e.message : String(e)) }) return () => { alive = false } }, [attempt]) - if (platform === 'macos') return MacCommand({ featureCode: props.featureCode }) - if (platform === 'windows') return WindowsCommand(props) + if (platform === 'macos' || platform === 'windows') return MacCommand({ featureCode: props.featureCode, platform }) return setAttempt(attempt + 1)} />} /> } export const commands = { diff --git a/extensions/startup-manager/src/mac-command.tsx b/extensions/startup-manager/src/mac-command.tsx index cf3c5e8b..d4db0faf 100644 --- a/extensions/startup-manager/src/mac-command.tsx +++ b/extensions/startup-manager/src/mac-command.tsx @@ -1,8 +1,24 @@ -import React, { Action, ActionPanel, Icon, List, Toast, confirmAlert, showToast, useEffect, useLocale, useRef, useState, getLocale } from '@ztools/declarative-ui' +import React, { Action, ActionPanel, Color, Icon, List, Toast, confirmAlert, showToast, useEffect, useLocale, useRef, useState, getLocale } from '@ztools/declarative-ui' import { filterStartup, scanStartup, startupInvoke, startupOperation, type StartupReport, type MacStartupItem } from './mac-service.js' import { t } from './i18n.js' -export default function MacStartupCommand({ featureCode }: { featureCode?: string }) { +function scopeTag(scope: MacStartupItem['scope']): string | null { + switch (scope) { + case 'registry-hkcu': + case 'registry-hklm': + return t('sourceRegistry') + case 'startup-folder': + return t('sourceFolder') + case 'scheduled-task': + return t('sourceTask') + case 'service': + return t('sourceService') + default: + return null + } +} + +export default function MacStartupCommand({ featureCode, platform = 'macos' }: { featureCode?: string; platform?: 'macos' | 'windows' }) { useLocale() const [report, setReport] = useState(null), [error, setError] = useState(''), [busy, setBusy] = useState(false) const [query, setQuery] = useState(''), [filter, setFilter] = useState(featureCode === 'startup-services' ? 'service' : featureCode === 'startup-tasks' ? 'task' : 'all') @@ -31,7 +47,6 @@ export default function MacStartupCommand({ featureCode }: { featureCode?: strin const message = e instanceof Error ? e.message : String(e) if (!alive.current || cancelled.current) return if (action === 'scan' || action === 'settings') { if (action === 'scan') setReport(null); setError(message); return } - // 修改失败后系统状态可能已部分变化:如实提示失败,并重新读取列表,避免继续显示旧状态 setError(message) await showToast({ style: Toast.Style.Failure, title: action === 'remove' ? t('macToastRemoveFailed') : action === 'restore' ? t('macToastRestoreFailed') : t('macToastToggleFailed'), message }) try { if (alive.current && !cancelled.current) await load() } @@ -57,28 +72,46 @@ export default function MacStartupCommand({ featureCode }: { featureCode?: strin }, []) const rows = filterStartup(report?.items || [], query, filter) const backups = (report?.backups || []).filter(b => b.label.toLocaleLowerCase().includes(query.toLocaleLowerCase())) - return i.enabled).length, + service: rows.filter(i => i.scope === 'service').length, + broken: rows.filter(i => i.programState === 'missing').length + }) + : t('macSummaryItems', { count: rows.length }) + + return } - filterBar={{ summaryText: error || (busy ? t('macSummaryBusy') : filter === 'backups' ? t('macSummaryBackups', { count: backups.length }) : t('macSummaryItems', { count: rows.length })), actions: [ + filterBar={{ summaryText: error || (busy ? t('macSummaryBusy') : filter === 'backups' ? t('macSummaryBackups', { count: backups.length }) : summaryCountText), actions: [ { id: 'scan', title: busy ? t('macActionStop') : t('actionRescan'), onAction: () => busy ? stop() : perform() }, { id: 'settings', title: t('macActionSettings'), onAction: () => perform('settings') } ] }}> - {filter !== 'backups' && rows.map(item => - { - if (item.blockedReason) await showToast({ style: Toast.Style.Failure, title: t('macToastBlockedItem'), message: item.blockedReason }) - else await perform('set-enabled', { id: item.id, enabled: !item.enabled }) - }} /> - - - - {item.programState === 'missing' && !item.blockedReason && remove(item)} />} - } />)} + {filter !== 'backups' && rows.map(item => { + const sourceLabel = scopeTag(item.scope) + return + { + if (item.blockedReason) await showToast({ style: Toast.Style.Failure, title: t('macToastBlockedItem'), message: item.blockedReason }) + else await perform('set-enabled', { id: item.id, enabled: !item.enabled }) + }} /> + + + + {item.programState === 'missing' && !item.blockedReason && remove(item)} />} + } /> + })} {filter === 'backups' && backups.map(backup => perform('restore', { id: backup.id })} />} />)} {!busy && (filter === 'backups' ? !backups.length : !rows.length) && ([ + 'user-agent', + 'system-agent', + 'daemon', + 'registry-hkcu', + 'registry-hklm', + 'startup-folder', + 'scheduled-task', + 'service' +]) + export interface MacStartupItem { - id: string; label: string; file: string; domain: string; scope: 'user-agent' | 'system-agent' | 'daemon' + id: string; label: string; file: string; domain: string; scope: StartupScope program: string; args: string[]; scheduled: boolean; enabled: boolean; loaded: boolean; running: boolean pid: number | null; programState: 'available' | 'missing' | 'unknown'; requiresAdmin: boolean; blockedReason: string | null + registryView?: '64' | '32' + registryValueType?: 'REG_SZ' | 'REG_EXPAND_SZ' + serviceStartType?: 'auto' | 'auto-delayed' | 'demand' | 'disabled' | 'unknown' + legacyRunDisabled?: boolean } export interface StartupBackup { id: string; kind: 'toggle' | 'remove'; createdAt: string; label: string; beforeEnabled: boolean; afterEnabled: boolean } export interface StartupReport { items: MacStartupItem[]; warnings: string[]; backups: StartupBackup[] } @@ -22,12 +48,12 @@ export async function startupInvoke(method: string, params: Record { const data = await startupInvoke('startup_manager', { action: 'scan', operationId }) - if (!Array.isArray(data.items) || data.items.length > 1536 || !Array.isArray(data.warnings) || data.warnings.some(w => typeof w !== 'string') || !Array.isArray(data.backups)) throw new Error(t('macErrIncompleteList')) + if (!Array.isArray(data.items) || data.items.length > 4096 || !Array.isArray(data.warnings) || data.warnings.some(w => typeof w !== 'string') || !Array.isArray(data.backups)) throw new Error(t('macErrIncompleteList')) const ids = new Set() for (const item of data.items) { if (!record(item) || typeof item.id !== 'string' || !/^[a-f0-9]{64}$/.test(item.id) || ids.has(item.id) || !['label', 'file', 'domain', 'program'].every(k => typeof item[k] === 'string') || - typeof item.scope !== 'string' || !['user-agent', 'system-agent', 'daemon'].includes(item.scope) || + typeof item.scope !== 'string' || !ALLOWED_SCOPES.has(item.scope) || !['scheduled', 'enabled', 'loaded', 'running', 'requiresAdmin'].every(k => typeof item[k] === 'boolean') || !Array.isArray(item.args) || item.args.some(a => typeof a !== 'string') || (item.pid !== null && (!Number.isSafeInteger(item.pid) || Number(item.pid) <= 0)) || @@ -44,7 +70,12 @@ export async function scanStartup(operationId: string): Promise { } export function filterStartup(items: MacStartupItem[], query: string, filter: string) { const q = query.trim().toLocaleLowerCase() - return items.filter(i => (filter === 'all' || (filter === 'user' && i.scope === 'user-agent') || (filter === 'service' && i.scope !== 'user-agent') || - (filter === 'task' && i.scheduled) || (filter === 'disabled' && !i.enabled) || (filter === 'broken' && i.programState === 'missing')) && - [i.label, i.program, i.file, ...i.args].some(text => text.toLocaleLowerCase().includes(q))) + return items.filter(i => ( + filter === 'all' || + (filter === 'user' && (i.scope === 'user-agent' || i.scope === 'registry-hkcu' || i.scope === 'startup-folder')) || + (filter === 'service' && (i.scope === 'system-agent' || i.scope === 'daemon' || i.scope === 'service' || i.scope === 'registry-hklm')) || + (filter === 'task' && (i.scheduled || i.scope === 'scheduled-task')) || + (filter === 'disabled' && !i.enabled) || + (filter === 'broken' && i.programState === 'missing') + ) && [i.label, i.program, i.file, ...i.args].some(text => text.toLocaleLowerCase().includes(q))) } diff --git a/extensions/startup-manager/src/native-ipc.ts b/extensions/startup-manager/src/native-ipc.ts index 51576b99..13643277 100644 --- a/extensions/startup-manager/src/native-ipc.ts +++ b/extensions/startup-manager/src/native-ipc.ts @@ -174,11 +174,13 @@ function normalizeMethodResult(method: string, payload: DynamicBridge): DynamicB if (method === 'system_get_battery_status') { // 宿主约定 percent 超出 0-100(如 255)表示无电池或电量未知,不能改写成 100% + // 若宿主明确给出 hasBattery 布尔值,必须原样保留,仅在缺失时按合法电量推算 const rawPct = payload.percent - const hasBattery = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const validPct = typeof rawPct === 'number' && Number.isFinite(rawPct) && rawPct >= 0 && rawPct <= 100 + const hasBattery = typeof payload.hasBattery === 'boolean' ? payload.hasBattery : validPct return { ...payload, - percent: hasBattery ? rawPct : null, + percent: validPct ? rawPct : null, hasBattery } } @@ -489,6 +491,8 @@ export interface RealDirectoryScanResult extends Iterable approximate?: boolean /** 宿主实际遍历的条目数 */ visitedEntries?: number + /** 目录本身不存在(ENOENT) */ + missing?: boolean /** 读取失败的真实原因;已有文件仍可使用,但不能当作完整结果。 */ error?: string } @@ -497,6 +501,7 @@ interface ScanResultMeta { truncated?: boolean approximate?: boolean visitedEntries?: number + missing?: boolean } export interface ScanDirectoryTreeOptions { @@ -504,6 +509,10 @@ export interface ScanDirectoryTreeOptions { maxFiles?: number collectTopN?: number filterExt?: RegExp + /** 为 true 时,目录本身不存在(ENOENT)按空目录处理,不返回 error(权限拒绝/读取失败仍照常报错) */ + ignoreMissing?: boolean + /** Top-N 保留与排序方式:默认按体积降序,下载/录屏等时效场景可传 mtime-desc */ + sortBy?: 'size-desc' | 'mtime-desc' hostOverride?: DynamicBridge } @@ -519,8 +528,9 @@ function normalizeIndexedFileEntry(f: DynamicBridge): RealIndexedFileEntry { const sz = Number(f?.size ?? f?.sizeBytes ?? 0) const isDir = Boolean(f?.is_dir || f?.isDir || f?.isDirectory) const rawMtime = Number(f?.mtime ?? f?.mtimeMs ?? 0) - const mtimeMs = rawMtime > 1e11 ? rawMtime : rawMtime > 0 ? rawMtime * 1000 : Date.now() - const mtimeSec = rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime + const validMtime = Number.isFinite(rawMtime) && rawMtime > 0 + const mtimeMs = validMtime ? (rawMtime > 1e11 ? rawMtime : rawMtime * 1000) : 0 + const mtimeSec = validMtime ? (rawMtime > 1e11 ? Math.floor(rawMtime / 1000) : rawMtime) : 0 if (p && sz >= 0) realFileSizeCache.set(p, sz) return { name, @@ -551,6 +561,7 @@ function makeScanResult( subdirs, ...(meta.truncated ? { truncated: true } : {}), ...(meta.approximate ? { approximate: true } : {}), + ...(meta.missing ? { missing: true } : {}), ...(typeof meta.visitedEntries === 'number' ? { visitedEntries: meta.visitedEntries } : {}), [Symbol.iterator]() { return files[Symbol.iterator]() @@ -609,13 +620,40 @@ export async function scanRealDirectoryTree( return result.error ? { ...result.scan, error: result.error } : result.scan } +/** 仅当正则明确声明了扩展名(含 `\.`)时提取后缀列表,避免把 `thumbcache|iconcache` 等文件名关键词误拆成假扩展名 */ +function extractExtensionTokensFromFilter(filterExt: RegExp): string[] { + const src = filterExt.source + if (!src.includes('\\.')) return [] + const afterDot = src.slice(src.indexOf('\\.') + 2) + const rawTokens = afterDot.match(/[a-z0-9]{1,8}/gi) || [] + const seen = new Set() + const out: string[] = [] + for (const token of rawTokens) { + const lower = token.toLowerCase() + if (!lower || seen.has(lower)) continue + seen.add(lower) + out.push(lower) + } + return out +} + +function isMissingDirectoryError(res: { error?: string; errorCode?: string; errorDetails?: Record }): boolean { + if (res.errorDetails?.reason === 'ENOENT' || res.errorCode === 'ENOENT') return true + const msg = String(res.error || '') + return /Directory does not exist|ENOENT/i.test(msg) +} + /** 一次界面扫描的错误汇总;多个目录并行扫描时保留可读目录的结果。 */ export function createDirectoryScanner(hostOverride?: DynamicBridge) { const failures = new Map() return { async scan(dir: string, options: number | ScanDirectoryTreeOptions = 160) { const result = await scanRealDirectoryTree(dir, options, hostOverride) - const error = result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') + const ignoreMissing = typeof options === 'object' && options !== null && options.ignoreMissing === true + const error = + result.missing && ignoreMissing + ? '' + : result.error || (result.truncated || result.approximate ? ipcStrings().scanIncomplete : '') if (error) failures.set(dir, error) else failures.delete(dir) return result @@ -648,26 +686,38 @@ async function scanDirectoryTreeWithError( const safeLimit = Math.min(200, Math.max(1, Math.floor(rawLimit || 160))) const hostOverride = opts.hostOverride const filterExt = opts.filterExt + const ignoreMissing = opts.ignoreMissing === true const dirQuery = `dir:${targetDir}` try { let rawPayload: DynamicBridge = null + const searchParams: Record = { + query: dirQuery, + limit: safeLimit, + ...(opts.sortBy ? { sortBy: opts.sortBy } : {}) + } const res = await callHostTransport( 'system_search_files', - { query: dirQuery, limit: safeLimit }, + searchParams, hostOverride ) - if (res.ok && res.data) { + if (res.ok && res.data && res.data.degraded !== true) { rawPayload = res.data + } else if (!res.ok && ignoreMissing && isMissingDirectoryError(res)) { + const missingScan = makeScanResult([], 0, 0, [], { missing: true }) + return { scan: missingScan } } - if (!rawPayload && !hostOverride && typeof window !== 'undefined') { + if (!rawPayload && !hostOverride && res.errorCode === 'METHOD_NOT_AVAILABLE' && typeof window !== 'undefined') { const w = window as DynamicBridge if (typeof w.__ztoolsLauncher?.searchFiles === 'function') { const rawOuter = await w.__ztoolsLauncher.searchFiles(dirQuery, safeLimit) - rawPayload = + const candidate = rawOuter && typeof rawOuter === 'object' && 'data' in rawOuter && rawOuter.data ? rawOuter.data : rawOuter + if (candidate && candidate.degraded !== true && candidate.success !== false) { + rawPayload = candidate + } } } @@ -678,29 +728,32 @@ async function scanDirectoryTreeWithError( let files: RealIndexedFileEntry[] = rawPayload.files.map(normalizeIndexedFileEntry) if (filterExt instanceof RegExp) { files = files.filter(f => !f.isDir && (filterExt.test(f.name) || filterExt.test(f.ext))) - // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索目标扩展名 + // 若目录 Top-N 大文件均为其他后缀,使用 MFT 索引直接检索明确声明的目标扩展名 if (files.length === 0 && !hostOverride) { - const extTokens = (filterExt.source.match(/[a-z0-9]{2,5}/gi) || []) - .filter(t => !['thumbcache', 'iconcache'].includes(t.toLowerCase())) - .slice(0, 4) - // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 - const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() - const extraLists = await Promise.all( - extTokens.map(ext => searchRealIndexedFiles(`.${ext.toLowerCase()}`, 30, hostOverride)) - ) - const seen = new Set() - for (const list of extraLists) { - for (const item of list) { - if (!item.isDir && item.size > 0 && !seen.has(item.path)) { - if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { - seen.add(item.path) - files.push(item) + const extTokens = extractExtensionTokensFromFilter(filterExt) + if (extTokens.length > 0) { + // 只接受确实位于目标目录下的检索结果,不能用别处同后缀文件冒充目录内容 + const prefixLower = `${targetDir.replace(/[\\/]+$/, '')}${isWindowsStylePath(targetDir) ? '\\' : '/'}`.toLowerCase() + const extraLists = await Promise.all( + extTokens.map(ext => searchRealIndexedFiles(`.${ext}`, 30, hostOverride)) + ) + const seen = new Set() + for (const list of extraLists) { + for (const item of list) { + if (!item.isDir && item.size > 0 && !seen.has(item.path)) { + if (item.path.replace(/\//g, isWindowsStylePath(targetDir) ? '\\' : '/').toLowerCase().startsWith(prefixLower)) { + seen.add(item.path) + files.push(item) + } } } } } } } + // 先基于过滤后的完整命中集合计算总文件数与总字节数,再按 collectTopN 裁剪样本列表 + const matchedCount = files.length + const matchedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) if (typeof opts.collectTopN === 'number' && opts.collectTopN > 0 && files.length > opts.collectTopN) { files = files.slice(0, opts.collectTopN) } @@ -714,11 +767,10 @@ async function scanDirectoryTreeWithError( ...(s.approximate === true ? { approximate: true } : {}) })) : [] - const computedBytes = files.reduce((acc, f) => acc + (f.isDir ? 0 : f.size), 0) const totalFilesCount = - filterExt instanceof RegExp ? files.length : Number(rawPayload.total_matches ?? files.length) + filterExt instanceof RegExp ? matchedCount : Number(rawPayload.total_matches ?? matchedCount) const totalBytesCount = - filterExt instanceof RegExp ? computedBytes : Number(rawPayload.total_bytes ?? computedBytes) + filterExt instanceof RegExp ? matchedBytes : Number(rawPayload.total_bytes ?? matchedBytes) const visited = Number(rawPayload.visited_entries) return { scan: makeScanResult(files, totalFilesCount, totalBytesCount, subdirs, { @@ -1817,8 +1869,6 @@ export async function writeRealClipboardText(text: string, hostOverride?: Dynami const payload = { text: String(text || '') } const res = await callHostTransport('clipboard_copy_text', payload, hostOverride) if (res.ok) return true - const fallbackRes = await callHostTransport('clipboard_write_text', payload, hostOverride) - if (fallbackRes.ok) return true try { if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) { await navigator.clipboard.writeText(String(text || '')) diff --git a/extensions/startup-manager/src/startup-service.ts b/extensions/startup-manager/src/startup-service.ts index d6106ece..15a490b0 100644 --- a/extensions/startup-manager/src/startup-service.ts +++ b/extensions/startup-manager/src/startup-service.ts @@ -1,527 +1,4 @@ -import { - invokePluginService, - showRealItemInFolder, - writeRealClipboardText -} from './native-ipc.js' -import { t } from './i18n.js' -import type { - StartupCleanBrokenResult, - StartupEntryItem, - StartupScanSummary, - StartupSourceFilter, - StartupSourceLabel, - StartupSourceType, - StartupToggleResult -} from './types.js' -import { resolveErrorMessage } from './error-i18n.js' - -export const STARTUP_MANAGER_PLUGIN_NAME = 'StartupManagerPlugin' - -export const WINDOWS_PROTECTED_CORE_SERVICES = new Set([ - 'rpcss', - 'dcomlaunch', - 'plugplay', - 'eventlog', - 'windefend', - 'wdnissvc', - 'mpssvc', - 'dhcp', - 'dnscache', - 'lanmanworkstation', - 'lanmanserver', - 'schedule', - 'spooler', - 'themes', - 'audiosrv', - 'audioendpointbuilder', - 'bfe', - 'cryptsvc', - 'profsvc', - 'samss', - 'lsm', - 'power', - 'systemeventsbroker', - 'timebrokersvc', - 'usermanager', - 'wcmsvc', - 'winmgmt', - 'wuauserv', - 'trustedinstaller', - 'gpsvc', - 'nsi', - 'keyiso', - 'vaultsvc' -]) - -export function resolveInitialStartupFilter(featureCode?: string): StartupSourceFilter { - switch (featureCode) { - case 'startup-services': - return 'service' - case 'startup-tasks': - return 'task' - default: - return 'all' - } -} - -export function extractExePathFromCommand(rawCommand: string): string { - const trimmed = String(rawCommand ?? '').trim() - if (!trimmed) return '' - - const quotedMatch = trimmed.match(/^"([^"]+)"/) - if (quotedMatch?.[1]) { - return quotedMatch[1].trim() - } - - const winExeMatch = trimmed.match(/^([a-zA-Z]:\\[^\r\n"]*?\.(?:exe|bat|cmd|com|ps1|vbs|lnk|msc))\b/i) - if (winExeMatch?.[1]) { - return winExeMatch[1].trim() - } - - const posixMatch = trimmed.match(/^(\/[^\s"']+)/) - if (posixMatch?.[1]) { - return posixMatch[1].trim() - } - - const firstToken = trimmed.split(/\s+/)[0] ?? '' - return firstToken.replace(/^['"]+|['"]+$/g, '').trim() -} - -export function hasDangerousStartupTokens(val: string): boolean { - if (!val) return false - return /[\0\r\n;|`$]/.test(val) -} - -export function isMicrosoftProtectedStartupItem(item: { - source?: string - name?: string - serviceName?: string - taskPath?: string - publisher?: string - exePath?: string - command?: string -}): boolean { - const src = String(item.source ?? '').toLowerCase() - const svcName = String(item.serviceName ?? item.name ?? '').trim().toLowerCase() - const taskPath = String(item.taskPath ?? item.name ?? '').trim() - const publisher = String(item.publisher ?? '').trim().toLowerCase() - const exePath = String(item.exePath ?? extractExePathFromCommand(item.command ?? '')).toLowerCase() - - if (src === 'service') { - if (WINDOWS_PROTECTED_CORE_SERVICES.has(svcName)) return true - if (publisher.includes('microsoft')) return true - if ( - exePath.startsWith('c:\\windows\\system32\\') || - exePath.startsWith('c:\\windows\\syswow64\\') || - exePath.includes('\\svchost.exe') - ) { - return true - } - } - - if (src === 'task') { - const normalizedTask = taskPath.replace(/\//g, '\\').toLowerCase() - if (normalizedTask.startsWith('\\microsoft\\') || publisher.includes('microsoft')) { - return true - } - } - - return false -} - -export function resolveStartupSourceLabel(source: StartupSourceType): StartupSourceLabel { - switch (source) { - case 'folder': - return t('sourceFolder') - case 'service': - return t('sourceService') - case 'task': - return t('sourceTask') - case 'launchd': - return t('sourceLaunchAgent') - default: - return t('sourceRegistry') - } -} - -export function normalizeStartupEntry(raw: Record): StartupEntryItem | null { - const rawSource = String(raw.source ?? 'registry').toLowerCase() - const source: StartupSourceType = - rawSource === 'folder' || rawSource === 'service' || rawSource === 'task' || rawSource === 'launchd' - ? (rawSource as StartupSourceType) - : 'registry' - - const name = String(raw.name ?? '').trim() - const command = String(raw.command ?? raw.path ?? '').trim() - if (!name || !command) return null - - const exePath = - typeof raw.exePath === 'string' && raw.exePath.trim() - ? raw.exePath.trim() - : extractExePathFromCommand(command) - const publisher = String(raw.publisher ?? '').trim() - const serviceName = typeof raw.serviceName === 'string' ? raw.serviceName.trim() : undefined - const taskPath = typeof raw.taskPath === 'string' ? raw.taskPath.trim() : undefined - const regKey = typeof raw.regKey === 'string' ? raw.regKey.trim() : undefined - - if ( - isMicrosoftProtectedStartupItem({ - source, - name, - ...(serviceName ? { serviceName } : {}), - ...(taskPath ? { taskPath } : {}), - publisher, - exePath, - command - }) - ) { - return null - } - - const id = String(raw.id ?? `${source}:${serviceName ?? taskPath ?? name}`) - const sourceLabel = resolveStartupSourceLabel(source) - - return { - id, - name, - publisher, - command, - exePath, - source, - sourceLabel, - scope: String(raw.scope ?? (source === 'service' || source === 'task' ? 'System' : 'User')), - ...(regKey ? { regKey } : {}), - ...(serviceName ? { serviceName } : {}), - ...(taskPath ? { taskPath } : {}), - enabled: Boolean(raw.enabled), - fileMissing: Boolean(raw.fileMissing) - } -} - -function extractStartupErrorCode(errText?: string, rawCode?: unknown): string { - if (typeof rawCode === 'string' && rawCode.trim()) return rawCode.trim() - const msg = String(errText ?? '').trim() - const m = msg.match(/^([A-Z0-9_]+):/) - return m?.[1] ?? 'STARTUP_OPERATION_FAILED' -} - -export function computeStartupScanSummary(items: StartupEntryItem[]): StartupScanSummary { - return { - ok: true, - items, - totalCount: items.length, - enabledCount: items.filter((i) => i.enabled).length, - serviceCount: items.filter((i) => i.source === 'service').length, - taskCount: items.filter((i) => i.source === 'task').length, - brokenCount: items.filter((i) => i.fileMissing).length - } -} - -export async function scanStartupItems( - hostOverride?: unknown, - extraParams: Record = {} -): Promise { - const res = await invokePluginService>( - STARTUP_MANAGER_PLUGIN_NAME, - 'listAll', - extraParams, - hostOverride - ) - - if (!res.ok || !res.data || res.data.ok === false) { - const rawErrText = String(res.data?.error ?? res.error ?? res.message ?? '') - const errCode = extractStartupErrorCode(rawErrText, res.data?.errorCode) - return { - ok: false, - items: [], - totalCount: 0, - enabledCount: 0, - serviceCount: 0, - taskCount: 0, - brokenCount: 0, - errorCode: errCode, - error: resolveErrorMessage(res.data?.error ? res.data : res, t('errScanFailed')) - } - } - - const rawList = Array.isArray(res.data.items) - ? res.data.items - : Array.isArray(res.data.startupItems) - ? res.data.startupItems - : [] - - const items: StartupEntryItem[] = [] - for (const raw of rawList) { - if (raw && typeof raw === 'object') { - const normalized = normalizeStartupEntry(raw as Record) - if (normalized) items.push(normalized) - } - } - - const warnings = Array.isArray(res.data.warnings) ? res.data.warnings.map(String).filter(Boolean) : [] - return { ...computeStartupScanSummary(items), ...(warnings.length ? { warnings } : {}) } -} - -export async function setStartupItemEnabled( - item: StartupEntryItem, - targetEnabled: boolean, - currentItems: StartupEntryItem[] = [], - hostOverride?: unknown, - extraParams: Record = {} -): Promise { - if (!item || (!item.id && !item.name)) { - return { - ok: false, - id: '', - enabled: Boolean(item?.enabled), - updatedItems: currentItems, - errorCode: 'INVALID_IDENTIFIER', - error: t('errMissingId') - } - } - - if ( - hasDangerousStartupTokens(item.id) || - hasDangerousStartupTokens(item.name) || - hasDangerousStartupTokens(item.serviceName ?? '') || - hasDangerousStartupTokens(item.taskPath ?? '') - ) { - return { - ok: false, - id: item.id, - enabled: item.enabled, - updatedItems: currentItems, - errorCode: 'INVALID_IDENTIFIER', - error: t('errDangerousId') - } - } - - if (isMicrosoftProtectedStartupItem(item)) { - return { - ok: false, - id: item.id, - enabled: item.enabled, - updatedItems: currentItems, - errorCode: 'PROTECTED_SYSTEM_ITEM', - error: t('errProtectedSystem') - } - } - - const res = await invokePluginService>( - STARTUP_MANAGER_PLUGIN_NAME, - 'setEnabled', - { - id: item.id, - name: item.name, - source: item.source, - scope: item.scope, - command: item.command, - exePath: item.exePath, - publisher: item.publisher, - ...(item.serviceName ? { serviceName: item.serviceName } : {}), - ...(item.taskPath ? { taskPath: item.taskPath } : {}), - enabled: targetEnabled, - ...extraParams - }, - hostOverride - ) - - if (!res.ok || !res.data || res.data.ok === false) { - const rawErrText = String(res.data?.error ?? res.error ?? res.message ?? '') - const errCode = extractStartupErrorCode(rawErrText, res.data?.errorCode) - const errText = resolveErrorMessage(res.data?.error ? res.data : res, t('errToggleFailed')) - return { - ok: false, - id: item.id, - enabled: item.enabled, - updatedItems: currentItems, - errorCode: errCode, - error: errText - } - } - - const updatedItems = currentItems.map((entry) => - entry.id === item.id ? { ...entry, enabled: targetEnabled } : entry - ) - - return { - ok: true, - id: item.id, - enabled: targetEnabled, - updatedItems - } -} - -export async function removeBrokenStartupItems( - targetBrokenItems: StartupEntryItem[], - currentItems: StartupEntryItem[] = [], - hostOverride?: unknown, - extraParams: Record = {} -): Promise { - if (!Array.isArray(targetBrokenItems) || targetBrokenItems.length === 0) { - return { - ok: false, - removedCount: 0, - removedIds: [], - remainingItems: currentItems, - errorCode: 'EMPTY_ITEMS', - error: t('errEmptyBrokenItems') - } - } - - for (const item of targetBrokenItems) { - if ( - hasDangerousStartupTokens(item.id) || - hasDangerousStartupTokens(item.name) - ) { - return { - ok: false, - removedCount: 0, - removedIds: [], - remainingItems: currentItems, - errorCode: 'INVALID_IDENTIFIER', - error: t('errDangerousBrokenId') - } - } - if (!item.fileMissing) { - return { - ok: false, - removedCount: 0, - removedIds: [], - remainingItems: currentItems, - errorCode: 'ITEM_NOT_BROKEN', - error: t('errItemNotBroken', { name: item.name }) - } - } - } - - const res = await invokePluginService>( - STARTUP_MANAGER_PLUGIN_NAME, - 'removeBroken', - { - items: targetBrokenItems, - ...extraParams - }, - hostOverride - ) - - // 只按宿主确认删掉的条目更新列表;没有 removedIds 时视为没有删掉任何条目。 - // 只认本次提交清理的条目 id,宿主返回其它 id 也不会把无关条目从列表移除 - const targetIds = new Set(targetBrokenItems.map((entry) => entry.id)) - const removedIds = Array.isArray(res.data?.removedIds) - ? [...new Set((res.data.removedIds as unknown[]).map(String))].filter((id) => targetIds.has(id)) - : [] - const failed = normalizeCleanFailures(res.data?.failed) - const removedSet = new Set(removedIds) - const remainingItems = currentItems.filter((entry) => !removedSet.has(entry.id)) - - if (!res.ok || !res.data || res.data.ok === false) { - const rawErrText = String(res.data?.error ?? res.error ?? res.message ?? '') - const errCode = extractStartupErrorCode(rawErrText, res.data?.errorCode) - const errText = resolveErrorMessage(res.data?.error ? res.data : res, t('errCleanFailed')) - return { - ok: false, - removedCount: removedIds.length, - removedIds, - remainingItems, - failed, - errorCode: errCode, - error: errText - } - } - - // 部分成功:宿主以 success:true 返回(传输层在 success:false 时会丢弃数据),并带 partial / failed 说明未清理的条目 - if (res.data.partial === true || failed.length > 0) { - const errText = String(res.data.error ?? '') || t('errPartialFailed', { details: failed.map((entry) => `${entry.id}:${entry.error}`).join(';') }) - return { - ok: true, - partial: true, - removedCount: removedIds.length, - removedIds, - remainingItems, - failed, - errorCode: extractStartupErrorCode(errText, res.data.errorCode ?? 'PARTIAL_FAILED'), - error: errText - } - } - - return { - ok: true, - removedCount: removedIds.length, - removedIds, - remainingItems - } -} - -/** 宿主返回的未清理条目:原因字段兼容 error / reason / message,错误码兼容 errorCode / code */ -function normalizeCleanFailures(raw: unknown): Array<{ id: string; errorCode: string; error: string }> { - if (!Array.isArray(raw)) return [] - return raw - .filter((entry): entry is Record => Boolean(entry) && typeof entry === 'object') - .map((entry) => { - const errorCode = String(entry.errorCode ?? entry.code ?? '').trim() - const error = String(entry.error ?? entry.reason ?? entry.message ?? '').trim() - return { id: String(entry.id ?? ''), errorCode, error: error || errorCode || t('errNoReason') } - }) -} - -/** 清理结果的提示文案:部分成功时标题写明清理与未清理数量,正文逐条列出未清理原因 */ -export function describeCleanBrokenResult(res: StartupCleanBrokenResult, items: StartupEntryItem[] = []): { title: string; message?: string } { - const failed = res.failed ?? [] - const nameOf = (id: string) => items.find((entry) => entry.id === id)?.name || id - const reasons = failed.map((entry) => `${nameOf(entry.id)}:${entry.error}`).join(';') - if (res.ok && !res.partial) return { title: t('cleanAllSuccessTitle', { count: res.removedCount }) } - if (res.removedCount > 0 || res.partial) { - return { title: t('cleanPartialTitle', { removed: res.removedCount, failed: failed.length }), message: reasons || res.error } - } - return { title: t('cleanAllFailedTitle'), message: reasons || resolveErrorMessage(res, t('cleanAllFailedFallbackMsg')) } -} - -export function filterStartupItems( - items: StartupEntryItem[], - filter: StartupSourceFilter, - searchQuery: string -): StartupEntryItem[] { - const q = String(searchQuery ?? '').trim().toLowerCase() - - return items.filter((item) => { - if (filter === 'app' && item.source !== 'registry' && item.source !== 'folder' && item.source !== 'launchd') { - return false - } - if (filter === 'service' && item.source !== 'service') { - return false - } - if (filter === 'task' && item.source !== 'task') { - return false - } - if (filter === 'enabled' && !item.enabled) { - return false - } - if (filter === 'broken' && !item.fileMissing) { - return false - } - - if (!q) return true - return ( - item.name.toLowerCase().includes(q) || - item.publisher.toLowerCase().includes(q) || - item.command.toLowerCase().includes(q) || - item.exePath.toLowerCase().includes(q) || - item.sourceLabel.toLowerCase().includes(q) - ) - }) -} - -export async function revealStartupExeInFolder( - exePath: string, - hostOverride?: unknown -): Promise { - return showRealItemInFolder(String(exePath ?? '').trim(), hostOverride) -} - -export async function copyStartupCommandToClipboard( - command: string, - hostOverride?: unknown -): Promise { - return writeRealClipboardText(String(command ?? ''), hostOverride) -} +/** + * 启动管理服务统一出口:双端均走 `startup_manager` 专用宿主 IPC,彻底移除旧 StartupManagerPlugin DLL 调用。 + */ +export * from './mac-service.js' diff --git a/extensions/startup-manager/src/windows-command.tsx b/extensions/startup-manager/src/windows-command.tsx index 12df1225..2d04a044 100644 --- a/extensions/startup-manager/src/windows-command.tsx +++ b/extensions/startup-manager/src/windows-command.tsx @@ -1,390 +1,6 @@ -import React, { - Action, - ActionPanel, - Color, - Icon, - List, - Toast, - confirmAlert, - showToast, - useEffect, - useLocale, - useMemo, - useState -} from '@ztools/declarative-ui' -import { t } from './i18n.js' -import { - copyStartupCommandToClipboard, - filterStartupItems, - removeBrokenStartupItems, - describeCleanBrokenResult, - resolveInitialStartupFilter, - revealStartupExeInFolder, - scanStartupItems, - setStartupItemEnabled -} from './startup-service.js' -import type { - StartupEntryItem, - StartupSourceFilter -} from './types.js' -import { resolveErrorMessage } from './error-i18n.js' +import MacStartupCommand from './mac-command.js' -function renderStartupItemActions(params: { - item: StartupEntryItem - onToggle: (item: StartupEntryItem) => void - onRevealExe: (exePath: string) => void | Promise - onCopyCommand: (command: string) => void | Promise - onRemoveBroken: (item: StartupEntryItem) => void - onRescan: () => void -}) { - const { item, onToggle, onRevealExe, onCopyCommand, onRemoveBroken, onRescan } = params - return ( - - { - onToggle(item) - }} - /> - {item.exePath && ( - { - void onRevealExe(item.exePath) - }} - /> - )} - { - void onCopyCommand(item.command) - }} - /> - {item.fileMissing && ( - { - onRemoveBroken(item) - }} - /> - )} - - - ) -} - -export default function StartupManagerCommand(props?: { - featureCode?: string - hostOverride?: unknown -}) { - const locale = useLocale() - const [items, setItems] = useState([]) - const [sourceFilter, setSourceFilter] = useState( - resolveInitialStartupFilter(props?.featureCode) - ) - const [searchText, setSearchText] = useState('') - const [isLoading, setIsLoading] = useState(false) - const [loadError, setLoadError] = useState('') - const [scanWarnings, setScanWarnings] = useState([]) - - const reloadItems = async () => { - setIsLoading(true) - try { - const res = await scanStartupItems(props?.hostOverride) - if (!res.ok) { - setLoadError(resolveErrorMessage(res, t('errScanFailed'))) - await showToast({ - style: Toast.Style.Failure, - title: t('errScanFailed'), - message: resolveErrorMessage(res, t('toastScanFailedMsg')) - }) - return - } - setLoadError('') - setScanWarnings(res.warnings ?? []) - setItems(res.items) - } finally { - setIsLoading(false) - } - } - - useEffect(() => { - let cancelled = false - let seq = 0 - - const init = async () => { - const mySeq = ++seq - setIsLoading(true) - try { - const res = await scanStartupItems(props?.hostOverride) - if (cancelled || mySeq !== seq) return - if (res.ok) { - setLoadError('') - setScanWarnings(res.warnings ?? []) - setItems(res.items) - } else { - setLoadError(resolveErrorMessage(res, t('errScanFailed'))) - } - } finally { - if (!cancelled && mySeq === seq) { - setIsLoading(false) - } - } - } - - void init() - return () => { - cancelled = true - } - }, [props?.hostOverride]) - - useEffect(() => { - if (props?.featureCode) { - setSourceFilter(resolveInitialStartupFilter(props.featureCode)) - } - }, [props?.featureCode]) - - const enabledCount = useMemo(() => items.filter((i) => i.enabled).length, [items]) - const serviceCount = useMemo(() => items.filter((i) => i.source === 'service').length, [items]) - const brokenCount = useMemo(() => items.filter((i) => i.fileMissing).length, [items]) - - const filteredItems = useMemo( - () => filterStartupItems(items, sourceFilter, searchText), - [items, sourceFilter, searchText] - ) - - const handleToggleItem = async (item: StartupEntryItem) => { - const targetEnabled = !item.enabled - const res = await setStartupItemEnabled( - item, - targetEnabled, - items, - props?.hostOverride - ) - if (!res.ok) { - await showToast({ - style: Toast.Style.Failure, - title: - res.errorCode === 'ADMIN_REQUIRED' - ? t('toastAdminRequired') - : t('toastToggleFailedTitle'), - message: resolveErrorMessage(res, t('toastToggleFailedMsg')) - }) - return - } - if (res.updatedItems) { - setItems(res.updatedItems) - } - await showToast({ - style: Toast.Style.Success, - title: targetEnabled - ? t('toastEnabledTitle', { name: item.name }) - : t('toastDisabledTitle', { name: item.name }), - message: `${item.sourceLabel} · ${targetEnabled ? t('toastEnabledMsg') : t('toastDisabledMsg')}` - }) - } - - const handleRemoveSingleBroken = async (item: StartupEntryItem) => { - if (!item.fileMissing) { - await showToast({ - style: Toast.Style.Failure, - title: t('toastOnlyBrokenAllowed'), - message: t('toastOnlyBrokenMsg') - }) - return - } - const confirmed = await confirmAlert({ - title: t('confirmRemoveTitle', { name: item.name }), - message: t('confirmRemoveMsg', { path: item.exePath || item.command }) - }) - if (!confirmed) return - - const res = await removeBrokenStartupItems([item], items, props?.hostOverride) - // 宿主没有确认删除这一项(失败,或带 partial 的未清理结果)都按失败提示 - if (!res.ok || res.partial || !res.removedIds.includes(item.id)) { - if (res.remainingItems) setItems(res.remainingItems) - await showToast({ - style: Toast.Style.Failure, - title: t('toastCleanSingleFailed'), - message: res.failed?.[0]?.error || res.error || (res.ok ? t('toastCleanSingleUnconfirmed') : t('toastCleanSingleRetryAdmin')) - }) - return - } - if (res.remainingItems) { - setItems(res.remainingItems) - } - await showToast({ - style: Toast.Style.Success, - title: t('toastCleanSingleSuccess', { name: item.name }) - }) - } - - const handleCleanAllBroken = async () => { - const brokenList = items.filter((i) => i.fileMissing) - if (brokenList.length === 0) { - await showToast({ - style: Toast.Style.Animated, - title: t('toastNoBrokenTitle'), - message: t('toastNoBrokenMsg') - }) - return - } - const confirmed = await confirmAlert({ - title: t('confirmCleanAllTitle', { count: brokenList.length }), - message: t('confirmCleanAllMsg') - }) - if (!confirmed) return - - const res = await removeBrokenStartupItems(brokenList, items, props?.hostOverride) - // 成功、部分成功、失败都只移除宿主确认已删除的条目 - if (res.remainingItems) setItems(res.remainingItems) - const notice = describeCleanBrokenResult(res, items) - await showToast({ - style: res.ok && !res.partial ? Toast.Style.Success : Toast.Style.Failure, - title: notice.title, - ...(notice.message ? { message: notice.message } : {}) - }) - } - - return ( - setSourceFilter(val as StartupSourceFilter)} - tooltip={t('winFilterTooltip')} - > - - - - - - - - } - filterBar={{ - summaryText: t('winSummaryText', { total: items.length, enabled: enabledCount, service: serviceCount, broken: brokenCount }), - actions: [ - { - id: 'rescan', - title: t('actionRescan'), - onAction: () => { - void reloadItems() - } - }, - { - id: 'clean-broken', - title: t('actionCleanBroken'), - style: 'destructive', - onAction: () => { - void handleCleanAllBroken() - } - } - ] - }} - > - {(loadError || scanWarnings.length > 0) && ( - - - { void reloadItems() }} /> - - } - /> - - )} - {filteredItems.length === 0 ? ( - - - { - void reloadItems() - }} - /> - - } - /> - - ) : ( - - {filteredItems.map((item) => { - const accessories = [ - ...(item.fileMissing ? [{ tag: { value: t('tagMissingFile'), color: Color.Red } }] : []), - { tag: item.sourceLabel }, - { text: item.enabled ? t('statusEnabled') : t('statusDisabled') } - ] - return ( - { - void handleToggleItem(entry) - }, - onRevealExe: async (exePath) => { - const shown = await revealStartupExeInFolder(exePath, props?.hostOverride) - if (!shown) { - await showToast({ style: Toast.Style.Failure, title: t('toastRevealFailed'), message: exePath }) - } - }, - onCopyCommand: async (cmd) => { - const copied = await copyStartupCommandToClipboard(cmd, props?.hostOverride) - await showToast(copied - ? { style: Toast.Style.Success, title: t('toastCopySuccess') } - : { style: Toast.Style.Failure, title: t('toastCopyFailedTitle'), message: t('toastCopyFailedMsg') }) - }, - onRemoveBroken: (entry) => { - void handleRemoveSingleBroken(entry) - }, - onRescan: () => { - void reloadItems() - } - })} - /> - ) - })} - - )} - - ) +/** Windows 已并入统一 startup_manager 宿主 IPC,保留薄导出兼容历史入口引用 */ +export default function WindowsStartupCommand(props: { featureCode?: string } = {}) { + return MacStartupCommand({ featureCode: props.featureCode, platform: 'windows' }) } diff --git a/extensions/startup-manager/tests/clean-broken-partial.test.mjs b/extensions/startup-manager/tests/clean-broken-partial.test.mjs index f32d6030..b31f3e84 100644 --- a/extensions/startup-manager/tests/clean-broken-partial.test.mjs +++ b/extensions/startup-manager/tests/clean-broken-partial.test.mjs @@ -1,135 +1,104 @@ import test from 'node:test' import assert from 'node:assert/strict' -import { createRequire } from 'node:module' -import { setRuntimeLocale } from '@ztools/declarative-ui' +import { createHost, mount, tick } from '../../shared/test-harness.mjs' +import Command from '../dist/index.js' -setRuntimeLocale('zh-CN') - -const require = createRequire(import.meta.url) -const { removeBrokenStartupItems, describeCleanBrokenResult } = require('../dist/startup-service.js') - -const reg = { id: 'reg:HKCU:Ghost', name: 'Ghost', command: '"C:\\gone\\ghost.exe"', exePath: 'C:\\gone\\ghost.exe', source: 'registry', sourceLabel: '注册表', scope: 'HKCU', enabled: true, fileMissing: true } -const task = { id: 'task:\\Old\\Updater', name: 'OldUpdater', command: '"C:\\gone\\up.exe"', exePath: 'C:\\gone\\up.exe', source: 'task', sourceLabel: '计划任务', taskPath: '\\Old\\Updater', enabled: true, fileMissing: true } -const valid = { id: 'reg:HKCU:Valid', name: 'Valid', command: '"C:\\app\\ok.exe"', exePath: 'C:\\app\\ok.exe', source: 'registry', sourceLabel: '注册表', scope: 'HKCU', enabled: true, fileMissing: false } - -/** 宿主替身:按真实 dllplugin_call 形态返回 { success: true, data },记录调用参数 */ -function bridge(data, calls = []) { - return { async dllplugin_call(payload) { calls.push(payload); return typeof data === 'function' ? data(payload) : { success: true, data } } } +const brokenReg = { + id: 'a'.repeat(64), + label: 'GhostApp', + file: 'HKCU\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run', + domain: 'HKCU:64', + scope: 'registry-hkcu', + program: 'C:\\gone\\ghost.exe', + args: [], + scheduled: false, + enabled: true, + loaded: true, + running: false, + pid: null, + programState: 'missing', + requiresAdmin: false, + blockedReason: null } -test('部分成功:宿主 success:true + partial,只移除 removedIds,failed 原因兼容 error / reason / code 字段', async () => { - const calls = [] - const res = await removeBrokenStartupItems([reg, task], [valid, reg, task], bridge({ - ok: true, success: true, partial: true, removedIds: [reg.id], - failed: [{ id: task.id, code: 'UNSUPPORTED_SOURCE', reason: '计划任务不支持作为残留项删除' }], - errorCode: 'PARTIAL_FAILED', error: 'PARTIAL_FAILED: task:\\Old\\Updater:计划任务不支持作为残留项删除' - }, calls)) - assert.equal(calls.length, 1) - assert.equal(calls[0].func, 'removeBroken') - assert.equal(res.ok, true) - assert.equal(res.partial, true) - assert.equal(res.removedCount, 1) - assert.deepEqual(res.removedIds, [reg.id]) - assert.deepEqual(res.remainingItems.map((i) => i.id), [valid.id, task.id]) - assert.deepEqual(res.failed, [{ id: task.id, errorCode: 'UNSUPPORTED_SOURCE', error: '计划任务不支持作为残留项删除' }]) - assert.equal(res.errorCode, 'PARTIAL_FAILED') - const notice = describeCleanBrokenResult(res, [valid, reg, task]) - assert.equal(notice.title, '已清理 1 个,1 个未清理') - assert.equal(notice.message, 'OldUpdater:计划任务不支持作为残留项删除') -}) - -test('部分成功:宿主只带 failed 不带 partial / error 时同样识别为部分成功并生成原因', async () => { - const res = await removeBrokenStartupItems([reg, task], [reg, task], bridge({ - ok: true, removedIds: [reg.id], failed: [{ id: task.id, errorCode: 'ADMIN_REQUIRED', error: '拒绝访问' }, { id: 'x' }] - })) - assert.equal(res.partial, true) - assert.equal(res.errorCode, 'PARTIAL_FAILED') - assert.match(res.error, /^PARTIAL_FAILED: task:\\Old\\Updater:拒绝访问/) - // 没有原因字段的失败条目不吞掉:用错误码或“未说明原因”占位 - assert.deepEqual(res.failed[1], { id: 'x', errorCode: '', error: '未说明原因' }) -}) - -test('故障注入:宿主声称删除了未提交清理的条目时不会把无关条目从列表移除,重复 id 只计一次', async () => { - const res = await removeBrokenStartupItems([reg], [valid, reg], bridge({ ok: true, success: true, removedIds: [reg.id, reg.id, valid.id] })) - assert.equal(res.ok, true) - assert.equal(res.partial, undefined) - assert.equal(res.removedCount, 1) - assert.deepEqual(res.remainingItems.map((i) => i.id), [valid.id]) - assert.deepEqual(describeCleanBrokenResult(res), { title: '已清理 1 个无效残留启动项' }) -}) - -test('全部失败:宿主 success:false 时传输层丢弃数据,如实失败且列表不变;调用抛错同样失败', async () => { - const allFailed = await removeBrokenStartupItems([reg, task], [reg, task], bridge(() => ({ success: true, data: { ok: false, success: false, removedIds: [], failed: [{ id: reg.id, errorCode: 'ADMIN_REQUIRED', error: '拒绝访问' }], errorCode: 'ADMIN_REQUIRED', error: 'ADMIN_REQUIRED: 拒绝访问' } }))) - assert.equal(allFailed.ok, false) - assert.equal(allFailed.removedCount, 0) - assert.equal(allFailed.remainingItems.length, 2) - assert.match(allFailed.error, /拒绝访问/) - assert.deepEqual(describeCleanBrokenResult(allFailed), { title: '批量清理残留启动项失败', message: allFailed.error }) - const thrown = await removeBrokenStartupItems([reg], [reg], { async dllplugin_call() { throw new Error('IPC 通道已关闭') } }) - assert.equal(thrown.ok, false) - assert.equal(thrown.removedCount, 0) - assert.deepEqual(thrown.remainingItems.map((i) => i.id), [reg.id]) -}) - -test('宿主返回 ok:true 但没有 removedIds:视为未删除任何条目,列表不变', async () => { - const res = await removeBrokenStartupItems([reg], [reg], bridge({ ok: true, success: true })) - assert.equal(res.ok, true) - assert.equal(res.removedCount, 0) - assert.deepEqual(res.remainingItems.map((i) => i.id), [reg.id]) -}) +const validSvc = { + id: 'b'.repeat(64), + label: 'ValidService', + file: 'HKLM\\SYSTEM\\CurrentControlSet\\Services\\ValidService', + domain: 'Win32Service', + scope: 'service', + program: 'C:\\Program Files\\Valid\\svc.exe', + args: [], + scheduled: false, + enabled: true, + loaded: true, + running: true, + pid: 456, + programState: 'available', + requiresAdmin: true, + blockedReason: null +} -test('界面:一键清理部分成功时提示“已清理 X 个,Y 个未清理”并列出原因,列表只移除已删除条目', async () => { - const { createHost, mount, tick } = await import('../../shared/test-harness.mjs') - const { default: WindowsCommand } = await import('../dist/windows-command.js') +test('Windows:仅失效启动项允许移除且先二次确认,移除走 startup_manager IPC 并支持备份恢复', async () => { const host = createHost() - const removeCalls = [] - host.ipc.dllplugin_call = async ({ func, params }) => { - if (func === 'listAll') return { ok: true, items: [valid, reg, task] } - if (func === 'removeBroken') { - removeCalls.push(params) - return { ok: true, success: true, partial: true, removedIds: [reg.id], failed: [{ id: task.id, errorCode: 'UNSUPPORTED_SOURCE', error: '计划任务不支持作为残留项删除,请在系统中卸载对应程序' }], errorCode: 'PARTIAL_FAILED', error: 'PARTIAL_FAILED: 部分条目未清理' } + let removed = false + const backup = { + id: '11111111-2222-4333-8444-555555555555', + kind: 'remove', + label: 'GhostApp', + createdAt: new Date().toISOString(), + beforeEnabled: true, + afterEnabled: true + } + host.ipc.system_get_platform = async () => ({ success: true, platform: 'windows' }) + host.ipc.startup_manager = async (p) => { + if (p.action === 'scan') { + return { success: true, items: removed ? [validSvc] : [validSvc, brokenReg], warnings: [], backups: removed ? [backup] : [] } } - throw new Error(`未预期的调用 ${func}`) + if (p.action === 'remove') { + removed = true + return { success: true, removed: true, backupId: backup.id, message: '已移入恢复记录' } + } + if (p.action === 'restore') { + removed = false + return { success: true, restored: true, backupId: p.id, enabled: true, message: '已恢复原注册表项' } + } + return { success: true, cancelled: true } } - const view = await mount(() => WindowsCommand({}), host) + + const view = await mount(Command, host) + await tick() + assert.ok(!host.ipcCalls.some(([m]) => m === 'dllplugin_call')) + assert.ok(!view.actions(view.item(validSvc.id)).some((a) => a.props.title.includes('失效配置'))) + + host.setConfirm(true) + await view.run(view.item(brokenReg.id), '移除失效配置(可恢复)') + await tick() + assert.equal(removed, true) + + await view.dropdown('backups') + await view.run(view.item(backup.id), '恢复启动配置') + await tick() + assert.equal(removed, false) + view.unmount() await tick() - try { - assert.deepEqual(view.items().map((i) => i.props.id).sort(), [reg.id, task.id, valid.id].sort()) - const clean = view.tree().props.filterBar.actions.find((a) => a.id === 'clean-broken') - clean.onAction() - await tick(10) - assert.equal(removeCalls.length, 1) - assert.deepEqual(removeCalls[0].items.map((i) => i.id), [reg.id, task.id]) - const toast = host.lastToast() - assert.equal(toast.title, '已清理 1 个,1 个未清理') - assert.equal(toast.style, 'FAILURE') - assert.equal(toast.message, 'OldUpdater:计划任务不支持作为残留项删除,请在系统中卸载对应程序') - assert.ok(!host.toasts.some((t) => String(t.style).toUpperCase() === 'SUCCESS')) - assert.deepEqual(view.items().map((i) => i.props.id).sort(), [task.id, valid.id].sort()) - } finally { - view.unmount() - await tick() - } }) -test('界面:复制命令行或定位程序失败时如实提示失败,不显示成功', async () => { - const { createHost, mount, tick } = await import('../../shared/test-harness.mjs') - const { default: WindowsCommand } = require('../dist/windows-command.js') +test('Windows:HKLM 或系统服务切换缺权限时原样报错并重新扫描,不谎报成功', async () => { const host = createHost() - const override = { - async dllplugin_call() { return { success: true, data: { ok: true, items: [valid] } } }, - async clipboard_copy_text() { throw new Error('剪贴板被占用') }, - async clipboard_write_text() { return { success: false, error: '剪贴板被占用' } }, - async shell_show_item_in_folder() { throw new Error('路径不存在') }, - async shell_open_path() { return { success: false, error: '路径不存在' } } + host.ipc.system_get_platform = async () => ({ success: true, platform: 'windows' }) + host.ipc.startup_manager = async (p) => { + if (p.action === 'scan') return { success: true, items: [validSvc], warnings: [], backups: [] } + if (p.action === 'set-enabled') throw new Error('ADMIN_PRIVILEGE_REQUIRED: 修改系统服务需要管理员或提权服务') + return { success: true, cancelled: true } } - const view = await mount(() => WindowsCommand({ hostOverride: override }), host) + + const view = await mount(Command, host) + await tick() + await view.run(view.item(validSvc.id), '禁止后续自启') await tick() - const row = view.item(valid.id) - await view.run(row, '复制启动命令行'); await tick() - assert.equal(host.lastToast().title, '复制启动命令行失败') - await view.run(row, '在资源管理器中定位程序'); await tick() - assert.equal(host.lastToast().title, '无法定位程序文件') assert.equal(host.toasts.filter((t) => t.style === 'success').length, 0) + assert.match(host.lastToast().message, /ADMIN_PRIVILEGE_REQUIRED/) view.unmount() + await tick() }) diff --git a/extensions/startup-manager/tests/startup-manager.test.mjs b/extensions/startup-manager/tests/startup-manager.test.mjs index 6d4ba04e..ce1b13e3 100644 --- a/extensions/startup-manager/tests/startup-manager.test.mjs +++ b/extensions/startup-manager/tests/startup-manager.test.mjs @@ -1,29 +1,66 @@ import test from 'node:test' import assert from 'node:assert/strict' -import { createRequire } from 'node:module' -import { setRuntimeLocale } from '@ztools/declarative-ui' +import { createHost, mount, tick } from '../../shared/test-harness.mjs' +import Command, { commands } from '../dist/index.js' -setRuntimeLocale('zh-CN') - -const require = createRequire(import.meta.url) -const pluginModule = require('../dist/windows-command.js') - -const { default: StartupManagerCommand } = pluginModule +const winItem = (extra = {}) => ({ + id: '1'.repeat(64), + label: 'DemoApp', + file: 'HKCU\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run', + domain: 'HKCU:64', + scope: 'registry-hkcu', + program: 'C:\\Program Files\\Demo\\demo.exe', + args: ['--minimized'], + scheduled: false, + enabled: true, + loaded: true, + running: false, + pid: null, + programState: 'available', + requiresAdmin: false, + blockedReason: null, + ...extra +}) -test('1. [Plugin Bundle] startup-manager 构建产物导出声明式主视图且符合布局一规范与深链映射', () => { - assert.equal(typeof StartupManagerCommand, 'function') +test('1. [Plugin Bundle] startup-manager 双端统一入口符合布局一规范与深链映射,零 dllplugin_call', async () => { + const host = createHost() + host.ipc.system_get_platform = async () => ({ success: true, platform: 'windows' }) + host.ipc.startup_manager = async (p) => { + if (p.action === 'scan') { + return { + success: true, + items: [ + winItem(), + winItem({ id: '2'.repeat(64), label: 'ThirdPartySvc', scope: 'service', requiresAdmin: true }), + winItem({ id: '3'.repeat(64), label: 'BootUpdater', scope: 'scheduled-task', scheduled: true, requiresAdmin: true }) + ], + warnings: [], + backups: [] + } + } + return { success: true, cancelled: true } + } - const defaultView = StartupManagerCommand({ featureCode: 'startup-all' }) - assert.equal(defaultView.type, 'List') - assert.equal(defaultView.props.isShowingDetail, false) - assert.equal(defaultView.props.navigationTitle, '启动管理') - assert.equal(defaultView.props.searchBarAccessory.type, 'List.Dropdown') - assert.equal(defaultView.props.searchBarAccessory.props.value, 'all') - assert.equal(defaultView.props.filterBar.actions.length, 2) + const defaultView = await mount(Command, host) + await tick() + assert.equal(defaultView.tree().props.isShowingDetail, false) + assert.equal(defaultView.tree().props.navigationTitle, '启动管理') + assert.equal(defaultView.tree().props.searchBarAccessory.props.value, 'all') + assert.equal(defaultView.tree().props.filterBar.actions.length, 2) + assert.equal(defaultView.items().length, 3) + assert.ok(!host.ipcCalls.some(([m]) => m === 'dllplugin_call')) + defaultView.unmount() - const servicesView = StartupManagerCommand({ featureCode: 'startup-services' }) - assert.equal(servicesView.props.searchBarAccessory.props.value, 'service') + const servicesView = await mount(commands['startup-services'], host) + await tick() + assert.equal(servicesView.tree().props.searchBarAccessory.props.value, 'service') + assert.equal(servicesView.items().length, 1) + servicesView.unmount() - const tasksView = StartupManagerCommand({ featureCode: 'startup-tasks' }) - assert.equal(tasksView.props.searchBarAccessory.props.value, 'task') + const tasksView = await mount(commands['startup-tasks'], host) + await tick() + assert.equal(tasksView.tree().props.searchBarAccessory.props.value, 'task') + assert.equal(tasksView.items().length, 1) + tasksView.unmount() + await tick() }) diff --git a/extensions/super-markdown/README.en.md b/extensions/super-markdown/README.en.md new file mode 100644 index 00000000..66aef147 --- /dev/null +++ b/extensions/super-markdown/README.en.md @@ -0,0 +1,10 @@ +# Markdown Reader, Outline & Word Export + +Local Markdown workspace supporting files, folders, clipboard, and inline editing with fast search, heading outline navigation, word-count analytics, safe preview, formatted rich-text copy, and Word (`.docx`) export. + +## Highlights + +- **Flexible Input Sources**: Open local `.md` files or authorize folders via native dialogs, load Markdown from the clipboard, drag-and-drop files, paste text directly with `Ctrl+V` / `⌘V`, or compose and edit inline. +- **One-Step Clipboard to Word Rich Text**: Dedicated `markdown-clipboard-fast` command converts clipboard Markdown with the Formal style and copies Word-ready rich text immediately. +- **Outline Navigation**: Extracts ATX and Setext headings (ignoring fenced code blocks) and jumps directly to the selected section in the right-hand preview pane. +- **Full Word Formatting & Post-Export Actions**: Customize style preset (Business / Formal / Academic), body font size (16pt / 12pt / 10.5pt), and first-line indent; after exporting `.docx`, open the file directly, reveal it in your file manager, or copy its path. diff --git a/extensions/super-markdown/README.md b/extensions/super-markdown/README.md index 0d747986..401cfc9d 100644 --- a/extensions/super-markdown/README.md +++ b/extensions/super-markdown/README.md @@ -1,3 +1,10 @@ -# Markdown 即时阅读与大纲笔记 +# Markdown 阅读、大纲与转 Word 工作台 -已下架:功能未完成(只有示例数据)。 +面向本地 Markdown 文档、剪贴板与在线编辑的检索、标题大纲跳转、字数/阅读时长统计、安全预览、公文/商务/学术排版富文本复制与 Word (`.docx`) 导出工作台。 + +## 核心能力 + +- **多来源载入**:支持受控打开本地 `.md` 文件或授权整个 Markdown 目录,也支持读取剪贴板 Markdown、拖放文件、直接 `Ctrl+V` / `⌘V` 粘贴文本以及内联表单输入与编辑。 +- **一键剪贴板转 Word 富文本**:提供 `markdown-clipboard-fast` 快捷入口,直接读取剪贴板 Markdown 按公文风格转换并复制为可粘贴至 Word 的富文本。 +- **标题大纲与章节跳转**:自动解析 ATX 与 Setext 标题(忽略围栏代码块内的伪标题),一键切换大纲视图并在右侧实时定位到目标章节。 +- **精细 Word 排版与导出闭环**:独立调节排版预设(商务/公文/学术)、正文字号(三号/小四/五号)与首行缩进,导出 `.docx` 后可直接打开文档、在文件管理器中定位或复制导出路径。 diff --git a/extensions/super-markdown/icon.svg b/extensions/super-markdown/icon.svg new file mode 100644 index 00000000..77d441f5 --- /dev/null +++ b/extensions/super-markdown/icon.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/extensions/super-markdown/plugin.json b/extensions/super-markdown/plugin.json index 0fe31656..fba83190 100644 --- a/extensions/super-markdown/plugin.json +++ b/extensions/super-markdown/plugin.json @@ -1,14 +1,72 @@ { "id": "super-markdown", - "name": "Markdown 即时阅读与大纲笔记", - "description": "Markdown 预览、大纲提取与字数统计", - "version": "1.0.0", - "revoked": true, - "revokedReason": "功能未完成(只有示例数据)", + "name": "Markdown 阅读、大纲与转 Word 工作台", + "description": "本地授权目录或单个 Markdown 文档、剪贴板与在线编辑的即时检索、标题大纲跳转、字数与阅读时长统计、数学公式安全预览,以及公文/商务/学术排版富文本复制与 Word (.docx) 导出", + "version": "1.2.0", + "minAppVersion": "1.3.0.0", "author": "ZTools Team", "entry": "dist/index.js", "icon": "icon.svg", - "permissions": [], + "category": [ + "办公效率" + ], + "categoryId": "productivity", + "keywords": [ + "markdown", + "md", + "大纲", + "文档阅读", + "字数统计", + "公式预览", + "导出docx", + "outline", + "reader", + "AI文档转Word", + "markdown转word", + "md转word", + "转docx", + "导出word", + "chatgpt转word", + "deepseek转word", + "文档转换", + "复制为word格式", + "剪贴板转word" + ], + "permissions": [ + "fs", + "dialog", + "clipboard" + ], + "requireAdmin": false, + "nativeComponents": [], + "features": [ + { + "code": "markdown-workbench", + "explain": "打开本地 Markdown 文件或目录、读取剪贴板或编辑文本,进行大纲跳转、预览与导出 Word (.docx)", + "cmds": [ + "markdown阅读", + "md大纲", + "markdown预览", + "super markdown", + "md reader", + "md转word", + "ai转word", + "markdown转word", + "deepseek转word", + "导出word", + "md to docx" + ] + }, + { + "code": "markdown-clipboard-fast", + "explain": "读取剪贴板 Markdown,按公文风格一键转换并复制为 Word 富文本", + "cmds": [ + "复制为word格式", + "剪贴板转word", + "快速排版粘贴" + ] + } + ], "targets": [ { "id": "windows-electron-any", @@ -23,5 +81,53 @@ "arch": "any" } ], - "nativeComponents": [] + "defaultLocale": "zh-CN", + "i18n": { + "en-US": { + "name": "Markdown Reader, Outline & Word Export", + "description": "Open local Markdown files or folders, load from clipboard, or edit inline for fast search, heading outline navigation, word count analytics, safe math preview, formal/business/academic rich-text copy, and Word (.docx) export.", + "keywords": [ + "markdown", + "reader", + "outline", + "word count", + "math", + "preview", + "docx", + "export", + "word", + "convert", + "office", + "markdown to word", + "md to docx", + "export word", + "convert markdown", + "ai to word", + "office export" + ], + "features": { + "markdown-workbench": { + "explain": "Open local Markdown files or folders, load clipboard or edit text for outline navigation, preview, and Word (.docx) export", + "cmds": [ + "markdown reader", + "markdown outline", + "md preview", + "super markdown", + "md to word", + "markdown to word", + "md to docx", + "export word" + ] + }, + "markdown-clipboard-fast": { + "explain": "Convert clipboard Markdown to formatted rich text ready to paste into Word", + "cmds": [ + "copy for word", + "clipboard to word", + "rich text paste" + ] + } + } + } + } } diff --git a/extensions/super-markdown/src/error-i18n.ts b/extensions/super-markdown/src/error-i18n.ts new file mode 100644 index 00000000..d97366d1 --- /dev/null +++ b/extensions/super-markdown/src/error-i18n.ts @@ -0,0 +1,213 @@ +/** + * 声明式插件通用错误本地化解析器(R7 双轨平滑迁移共享底座)。 + * + * 规则: + * 1. 优先按结构化错误码(errorDetails.hostCode / details.hostCode / errorCode / code)查表: + * 先查插件传入的 codeMap,再查标准宿主错误码双语表; + * 2. 对称展示规则:中文模式(zh-CN)原文含 CJK 才直接展示,英文模式(en-US)原文不含 CJK 才直接展示, + * 既保留宿主精确本地化消息,又拦截英文技术原文裸露到中文界面、拦截中文原文裸露到英文界面; + * 3. 原文语言不匹配时优先使用标准宿主错误码译文,否则回退到插件本地 t(...) 兜底文案。 + */ + +import { getLocale } from '@ztools/declarative-ui' + +const CJK_REGEX = /[\u4e00-\u9fa5]/ + +const HOST_ERROR_CODE_MESSAGES: Record>> = { + 'zh-CN': { + INVALID_REQUEST: '请求参数无效', + METHOD_NOT_FOUND: '当前 ZTools 版本过低或不支持此接口,请升级客户端后重试', + METHOD_NOT_AVAILABLE: '当前 ZTools 版本过低或不支持此接口,请升级客户端后重试', + PERMISSION_DENIED: '权限不足,无法执行该操作', + REQUEST_TIMEOUT: '请求执行超时,请稍后重试', + CALLER_DESTROYED: '调用窗口已关闭,操作已中止', + APP_STOPPING: '应用正在退出,操作已取消', + CANCELLED: '操作已取消', + OPERATION_CANCELLED: '操作已取消', + NOT_SUPPORTED: '当前环境不支持此操作', + PLATFORM_NOT_SUPPORTED: '当前操作系统不支持此功能', + NETWORK_ERROR: '网络请求失败,请检查网络连接', + RESPONSE_TOO_LARGE: '响应数据超出大小限制', + FILE_ERROR: '文件操作失败', + FILE_NOT_FOUND: '目标文件或目录不存在', + FILE_TOO_LARGE: '文件大小超出限制', + FILE_ALREADY_EXISTS: '目标文件已存在', + DISK_FULL: '磁盘空间不足', + SHELL_ERROR: '系统命令或外部应用启动失败', + PROCESS_ERROR: '进程操作失败', + PROCESS_PROTECTED: '目标进程受系统保护,无法操作', + PROCESS_NOT_FOUND: '未找到目标进程', + PROCESS_ACCESS_DENIED: '无权访问或操作目标进程', + SCREEN_ERROR: '屏幕或窗口操作失败', + CLIPBOARD_ERROR: '剪贴板读写失败', + DATABASE_LOCKED: '本地数据库正被占用,请稍后重试', + DATABASE_KEY_NOT_FOUND: '未找到指定的数据项', + DATA_CORRUPT: '本地数据格式损坏或校验失败', + STORAGE_ERROR: '本地存储读写失败', + PLUGIN_BUSY: '插件正忙,请稍后重试', + PLUGIN_PERMISSION_REQUIRED: '插件缺少所需权限声明', + DLL_ERROR: '原生组件执行失败', + NATIVE_HOST_UNAVAILABLE: '原生宿主组件不可用', + NATIVE_HOST_ERROR: '原生宿主执行失败', + SERVICE_UNAVAILABLE: '系统提权服务不可用', + INTERNAL_ERROR: '宿主内部错误' + }, + 'en-US': { + INVALID_REQUEST: 'Invalid request parameters', + METHOD_NOT_FOUND: 'Your ZTools version is too old or does not support this API. Please upgrade and try again.', + METHOD_NOT_AVAILABLE: 'Your ZTools version is too old or does not support this API. Please upgrade and try again.', + PERMISSION_DENIED: 'Permission denied', + REQUEST_TIMEOUT: 'Request timed out. Please try again later.', + CALLER_DESTROYED: 'The caller window was closed and the operation was aborted', + APP_STOPPING: 'Application is exiting; operation cancelled', + CANCELLED: 'Operation cancelled', + OPERATION_CANCELLED: 'Operation cancelled', + NOT_SUPPORTED: 'This operation is not supported in the current environment', + PLATFORM_NOT_SUPPORTED: 'This feature is not supported on the current operating system', + NETWORK_ERROR: 'Network request failed. Please check your connection.', + RESPONSE_TOO_LARGE: 'Response payload exceeds size limit', + FILE_ERROR: 'File operation failed', + FILE_NOT_FOUND: 'Target file or directory not found', + FILE_TOO_LARGE: 'File size exceeds limit', + FILE_ALREADY_EXISTS: 'Target file already exists', + DISK_FULL: 'Insufficient disk space', + SHELL_ERROR: 'Failed to launch system command or external application', + PROCESS_ERROR: 'Process operation failed', + PROCESS_PROTECTED: 'Target process is protected by the system', + PROCESS_NOT_FOUND: 'Target process not found', + PROCESS_ACCESS_DENIED: 'Access denied for target process', + SCREEN_ERROR: 'Screen or window operation failed', + CLIPBOARD_ERROR: 'Failed to read or write clipboard', + DATABASE_LOCKED: 'Local database is locked. Please try again later.', + DATABASE_KEY_NOT_FOUND: 'Requested item was not found', + DATA_CORRUPT: 'Local data is corrupted or failed validation', + STORAGE_ERROR: 'Local storage operation failed', + PLUGIN_BUSY: 'Plugin is busy. Please try again later.', + PLUGIN_PERMISSION_REQUIRED: 'Plugin is missing required permission declaration', + DLL_ERROR: 'Native component execution failed', + NATIVE_HOST_UNAVAILABLE: 'Native host component is unavailable', + NATIVE_HOST_ERROR: 'Native host execution failed', + SERVICE_UNAVAILABLE: 'Elevated system service is unavailable', + INTERNAL_ERROR: 'Internal host error' + } +} + +function asObj(value: unknown): Record | null { + return value && typeof value === 'object' && !Array.isArray(value) + ? (value as Record) + : null +} + +function pickNonEmptyString(value: unknown): string { + return typeof value === 'string' && value.trim().length > 0 ? value.trim() : '' +} + +/** 从错误对象或宿主响应信封中提取结构化错误码(优先 errorCode,再 code) */ +export function extractErrorCode(source: unknown): string { + const rec = asObj(source) + if (!rec) return '' + const direct = pickNonEmptyString(rec.errorCode) || pickNonEmptyString(rec.code) + if (direct) return direct + const nestedErr = asObj(rec.error) + if (nestedErr) { + return pickNonEmptyString(nestedErr.errorCode) || pickNonEmptyString(nestedErr.code) + } + const nestedData = asObj(rec.data) + if (nestedData) { + return pickNonEmptyString(nestedData.errorCode) || pickNonEmptyString(nestedData.code) + } + return '' +} + +/** 从错误对象或宿主响应信封中提取 details.hostCode */ +export function extractHostCode(source: unknown): string { + const rec = asObj(source) + if (!rec) return '' + const directDetails = asObj(rec.errorDetails) || asObj(rec.details) + const fromDirect = directDetails ? pickNonEmptyString(directDetails.hostCode) : '' + if (fromDirect) return fromDirect + const nestedErr = asObj(rec.error) + if (nestedErr) { + const nestedDetails = asObj(nestedErr.errorDetails) || asObj(nestedErr.details) + const fromNested = nestedDetails ? pickNonEmptyString(nestedDetails.hostCode) : '' + if (fromNested) return fromNested + } + return '' +} + +/** 从错误对象、宿主响应或字符串中提取原始错误文案 */ +export function extractRawErrorText(source: unknown): string { + if (typeof source === 'string') return source.trim() + if (source instanceof Error) return source.message.trim() + const rec = asObj(source) + if (!rec) return '' + if ('error' in rec) { + if (typeof rec.error === 'string') return rec.error.trim() + const nestedErr = asObj(rec.error) + if (nestedErr) { + return pickNonEmptyString(nestedErr.message) || pickNonEmptyString(nestedErr.error) + } + return '' + } + return pickNonEmptyString(rec.message) +} + +/** 判断某段文本在当前 locale 下是否可直接展示给用户(对称规则:zh-CN 需含 CJK,en-US 需不含 CJK) */ +export function isDisplayableInCurrentLocale(text: string): boolean { + if (!text) return false + const locale = getLocale() + if (locale === 'zh-CN') return CJK_REGEX.test(text) + return !CJK_REGEX.test(text) +} + +/** + * 将宿主响应、异常对象或原始错误字符串安全解析为当前语言的提示文案: + * 1. 若对象属于成功响应且无 error,直接返回 fallback(避免误读成功态 message/code); + * 2. 优先按 hostCode / errorCode / code 查插件自定义 codeMap; + * 3. 若存在标准宿主错误码且无原文或原文语言不匹配,按当前语言查标准词典; + * 4. 若原始文案非空且符合当前语种(中文模式含 CJK,英文模式不含 CJK),保留原始文案; + * 5. 其余情况一律回退到插件本地传入的 fallback(即 t('...'))。 + */ +export function resolveErrorMessage( + source: unknown, + fallback: string, + codeMap?: Readonly> +): string { + if (source === null || source === undefined || source === '') { + return fallback + } + const rec = asObj(source) + if (rec && 'error' in rec && rec.ok === true && !rec.error) { + return fallback + } + + const hostCode = extractHostCode(source) + const code = extractErrorCode(source) + const rawText = extractRawErrorText(source) + + // 非失败响应容器若既无 error 文案也无 errorCode,直接返回 fallback(如 snapshot.error || t('empty')) + if (rec && 'error' in rec && !rawText && !rec.errorCode && rec.ok !== false && rec.success !== false) { + return fallback + } + + const locale = getLocale() + const dict = HOST_ERROR_CODE_MESSAGES[locale] ?? HOST_ERROR_CODE_MESSAGES['en-US'] + + if (codeMap) { + if (hostCode && codeMap[hostCode]) return codeMap[hostCode] + if (code && codeMap[code]) return codeMap[code] + } + + if (hostCode && dict[hostCode]) { + if (!rawText || !isDisplayableInCurrentLocale(rawText)) return dict[hostCode] + } + if (code && dict[code]) { + if (!rawText || !isDisplayableInCurrentLocale(rawText)) return dict[code] + } + + if (rawText && isDisplayableInCurrentLocale(rawText)) { + return rawText + } + + return fallback +} diff --git a/extensions/super-markdown/src/host-compat.ts b/extensions/super-markdown/src/host-compat.ts new file mode 100644 index 00000000..d7bd47df --- /dev/null +++ b/extensions/super-markdown/src/host-compat.ts @@ -0,0 +1,201 @@ +/** + * 旧版客户端兼容:插件运行在比自己更旧的 ZTools 里时,给出明确的升级提示或安全的退路。 + * + * - 插件里的 `@ztools/declarative-ui` 由客户端在运行时提供,SDK 里新增的方法在旧客户端上并不存在; + * - 宿主接口在旧客户端上不存在时返回「未知方法」,这里统一换成用户看得懂的升级提示。 + */ + +import { getLocale } from '@ztools/declarative-ui' + +const HOST_COMPAT_MESSAGES: Record string +}> = { + 'zh-CN': { + upgradeHint: '当前 ZTools 版本过低,请升级到最新版本后再试', + featureUpgradeError: (feature, hint) => `${feature}需要新版 ZTools,${hint}` + }, + 'en-US': { + upgradeHint: 'Your ZTools version is too old. Please upgrade to the latest version and try again.', + featureUpgradeError: (feature, hint) => `${feature} requires a newer version of ZTools. ${hint}` + } +} + +function hostCompatStrings() { + const locale = getLocale() + return HOST_COMPAT_MESSAGES[locale] ?? HOST_COMPAT_MESSAGES['en-US'] +} + +/** 动态获取旧版客户端升级提示(请始终调用本函数以支持语言热切换,禁止在模块顶层缓存为静态常量) */ +export function getHostUpgradeHint(): string { + return hostCompatStrings().upgradeHint +} + +/** 提取结构化错误码(优先 code / errorCode / details.hostCode) */ +function extractCompatErrorCodes(error: unknown): { code: string; hostCode: string } { + if (!error || typeof error !== 'object') return { code: '', hostCode: '' } + const rec = error as Record + const directCode = + typeof rec.errorCode === 'string' && rec.errorCode.trim() + ? rec.errorCode.trim() + : typeof rec.code === 'string' && rec.code.trim() + ? rec.code.trim() + : '' + const nestedErr = rec.error && typeof rec.error === 'object' ? (rec.error as Record) : null + const code = + directCode || + (nestedErr && typeof nestedErr.errorCode === 'string' && nestedErr.errorCode.trim() + ? nestedErr.errorCode.trim() + : nestedErr && typeof nestedErr.code === 'string' && nestedErr.code.trim() + ? nestedErr.code.trim() + : '') + const details = + (rec.errorDetails && typeof rec.errorDetails === 'object' ? (rec.errorDetails as Record) : null) || + (rec.details && typeof rec.details === 'object' ? (rec.details as Record) : null) || + (nestedErr?.details && typeof nestedErr.details === 'object' ? (nestedErr.details as Record) : null) + const hostCode = + details && typeof details.hostCode === 'string' && details.hostCode.trim() ? details.hostCode.trim() : '' + return { code, hostCode } +} + +/** 宿主是否因为不认识这个接口而失败(旧客户端):优先按结构化错误码判定,无码时兼容老宿主中文文案 */ +export function isHostMethodMissing(error: unknown): boolean { + const { code, hostCode } = extractCompatErrorCodes(error) + if ( + code === 'METHOD_NOT_FOUND' || + code === 'METHOD_NOT_AVAILABLE' || + hostCode === 'METHOD_NOT_FOUND' || + hostCode === 'METHOD_NOT_AVAILABLE' + ) { + return true + } + const text = + error instanceof Error + ? error.message + : error && typeof error === 'object' && typeof (error as { error?: unknown }).error === 'string' + ? String((error as { error: string }).error) + : error && typeof error === 'object' && typeof (error as { message?: unknown }).message === 'string' + ? String((error as { message: string }).message) + : String(error ?? '') + if (/METHOD_NOT_FOUND|METHOD_NOT_AVAILABLE|is not a function/.test(text)) { + return true + } + if (!code && !hostCode) { + // i18n-allow: legacy host fallback + return /未知方法/.test(text) + } + return false +} + +/** 生成「某功能需要新版客户端」的报错 */ +export function hostUpgradeError(feature: string): Error { + const s = hostCompatStrings() + return new Error(s.featureUpgradeError(feature, s.upgradeHint)) +} + +export interface UpdatableStorage { + getItem(key: string): Promise + setItem(key: string, value: unknown): Promise + updateItem?: (key: string, update: (current: unknown) => T) => Promise +} + +/** + * 读出最新值、修改后写回。 + * 客户端提供 updateItem 时用它保证多窗口不互相覆盖;旧客户端没有时退回读后写(与旧版插件行为一致)。 + */ +export async function updateStorageItem( + storage: UpdatableStorage, + key: string, + update: (current: unknown) => T +): Promise { + if (typeof storage.updateItem === 'function') return storage.updateItem(key, update) + const current = await storage.getItem(key) + const next = update(current) + if (JSON.stringify(next) !== JSON.stringify(current)) await storage.setItem(key, next) + return next +} + +export interface CompatFileInputConfig { + /** 允许的扩展名列表(如 ['.png', '.jpg']),不填表示允许任意扩展名 */ + extensions?: string[] + /** 是否允许接收文件夹(默认 false) */ + allowDirectories?: boolean + /** 是否允许将剪贴板纯位图(截图)落盘为临时 PNG 接收(默认 false) */ + allowClipboardImage?: boolean + /** 拖放遮罩提示文案 */ + dropTitle?: string + dropSubtitle?: string + /** 双模粘贴(文件优先,纯文本回退):当焦点位于空搜索框或非输入区域且剪贴板仅含文本时触发 */ + onTextPaste?: (text: string) => boolean | void | Promise +} + +export interface CompatFileInputPayload { + files: string[] + source: 'drop' | 'paste' | 'launch' + targetFieldId?: string + rejectedCount?: number +} + +/** + * 从宿主事件信封、FileInputPayload 或裸路径数组中安全提取规范化非空文件路径列表 + */ +export function extractCompatInputFiles(payload: unknown): string[] { + if (Array.isArray(payload)) { + return payload + .map((item) => { + if (typeof item === 'string') return item.trim() + if (item && typeof item === 'object' && typeof (item as { path?: unknown }).path === 'string') { + return String((item as { path: string }).path).trim() + } + return '' + }) + .filter(Boolean) + } + if (!payload || typeof payload !== 'object') return [] + const record = payload as Record + const inner = record.payload && typeof record.payload === 'object' ? (record.payload as Record) : record + if (Array.isArray(inner.files)) return extractCompatInputFiles(inner.files) + if (Array.isArray(inner.paths)) return extractCompatInputFiles(inner.paths) + return [] +} + +/** + * 判断当前宿主渲染器是否已原生支持栈顶 单点消费路由。 + * - 新版宿主会注入 window.__ztoolsDeclarativeFeatures.fileInput === true; + * - 旧版宿主未注入该标记时,插件可保留原有的 plugin_files_dropped 事件订阅作为回退,避免新旧宿主双重触发。 + */ +export function isDeclarativeFileInputSupported(): boolean { + if (typeof window === 'undefined') return true + const w = window as unknown as { __ztoolsDeclarativeFeatures?: { fileInput?: boolean } } + return w.__ztoolsDeclarativeFeatures?.fileInput === true +} + +/** + * 生成可直接展开到 /
/ 的属性对象。 + * 旧版客户端会静默忽略未知的 descriptor.props.fileInput / onFileInput 属性而不报错; + * 新版客户端由 DeclarativeView 栈顶单点消费拖放与 Ctrl+V / ⌘V 粘贴输入。 + */ +export function createCompatFileInputProps( + onFiles: (files: string[], payload: CompatFileInputPayload) => void | Promise, + config?: CompatFileInputConfig +): { + fileInput: CompatFileInputConfig + onFileInput: (payload: CompatFileInputPayload | string[]) => void +} { + return { + fileInput: config ? { ...config } : {}, + onFileInput: (raw: CompatFileInputPayload | string[]) => { + const files = extractCompatInputFiles(raw) + if (files.length === 0) return + const normalizedPayload: CompatFileInputPayload = Array.isArray(raw) + ? { files, source: 'drop' } + : { + files, + source: raw?.source || 'drop', + ...(typeof raw?.targetFieldId === 'string' && raw.targetFieldId ? { targetFieldId: raw.targetFieldId } : {}), + ...(typeof raw?.rejectedCount === 'number' ? { rejectedCount: raw.rejectedCount } : {}) + } + void onFiles(files, normalizedPayload) + } + } +} diff --git a/extensions/super-markdown/src/i18n.ts b/extensions/super-markdown/src/i18n.ts new file mode 100644 index 00000000..69a471fc --- /dev/null +++ b/extensions/super-markdown/src/i18n.ts @@ -0,0 +1,205 @@ +import { createTranslator } from '@ztools/declarative-ui' + +const MESSAGES = { + 'zh-CN': { + navTitle: 'Markdown 阅读与转 Word 工作台', + searchDocumentsPlaceholder: '搜索已打开的 Markdown 文档标题、路径或正文…', + searchOutlinePlaceholder: '搜索当前文档标题大纲…', + modeTooltip: '切换视图模式', + modeDocuments: '文档列表', + modeOutline: '当前大纲', + openFileAction: '打开文件', + openFolderAction: '打开目录', + summaryEmpty: '可打开本地文件/目录、读取剪贴板、手动输入,或直接拖放/粘贴 Markdown', + summaryDocuments: '共 {count} 篇文档 · 当前排版:{preset}', + summaryOutline: '{title} · 共 {count} 个标题', + presetOfficial: '公文', + presetBusiness: '商务', + presetAcademic: '学术', + fontSize3: '三号 16pt', + fontSizeS4: '小四 12pt', + fontSize5: '五号 10.5pt', + indentOn: '开启', + indentOff: '关闭', + sourceFile: '本地文件', + sourceClipboard: '剪贴板内容', + sourceManual: '手动输入', + wordsUnit: '{count} 词', + readMinutesUnit: '约 {minutes} 分钟', + headingsUnit: '{count} 标题', + metaDocSource: '文档来源', + metaWords: '字数 / 词数', + metaCharacters: '总字符数', + metaReadingTime: '预计阅读', + metaHeadings: '标题数量', + metaCodeAndMath: '代码块 / 公式', + metaExportPreset: '导出排版预设', + metaFontSize: '正文字号', + metaFirstLineIndent: '首行缩进', + metaLastExported: '最近导出', + metaLineNumber: '起始行号', + actionViewOutline: '查看标题大纲并跳转', + actionBackToDocuments: '返回文档列表', + actionCopyPlainText: '复制纯文本', + actionCopyRichText: '复制富文本(可粘贴至 Word)', + actionCopyRawMarkdown: '复制 Markdown 原文', + actionCopySectionMarkdown: '复制当前章节 Markdown', + actionExportDocx: '导出 Word (.docx)', + actionOpenExported: '直接打开 Word 文档', + actionRevealExported: '在文件管理器中定位', + actionCopyExportedPath: '复制导出路径', + actionSwitchPreset: '切换导出排版(当前:{preset})', + actionSwitchFontSize: '切换正文字号(当前:{fontSize})', + actionToggleIndent: '切换首行缩进(当前:{state})', + actionReadClipboard: '读取剪贴板 Markdown', + actionInputMarkdown: '输入 Markdown 文本', + actionEditMarkdown: '编辑 Markdown 原文', + actionReloadDoc: '重新读取文档', + actionRemoveDoc: '从工作台移除', + sectionExported: '最近导出', + sectionFormatting: 'Word 排版选项', + sectionDocument: '文档来源与编辑', + formNavTitle: '输入 / 编辑 Markdown', + formSubmitTitle: '载入工作台', + formFieldTitle: 'Markdown 文本', + formFieldPlaceholder: '输入或粘贴 Markdown,最多 256 KiB', + formDescTitle: '排版与安全说明', + formDescHelp: '支持标题大纲、加粗、列表、表格、数学公式与代码块;导出 Word 时不会修改原始文件。', + emptyTitle: '尚未打开任何 Markdown 文档', + emptySubtitle: '可打开本地文件或目录、读取剪贴板、手动输入,也可直接拖放或粘贴 Markdown', + emptyNoMatchTitle: '没有匹配的文档', + emptyNoMatchSubtitle: '尝试更换关键词,或打开更多本地 Markdown 文件', + emptyNoHeadingsTitle: '当前文档未检测到标题大纲', + emptyNoHeadingsSubtitle: '使用 # 标题语法添加标题后即可快速跳转', + openFileDialogTitle: '选择 Markdown 文件', + openFolderDialogTitle: '选择 Markdown 文档目录', + saveDocxDialogTitle: '导出 Word 文档 (.docx)', + dropTitle: '拖放 Markdown 文件到工作台', + dropSubtitle: '仅支持 .md / .markdown / .txt(单个不超过 256 KiB)', + loadedFileToast: '已载入文档:{name}', + loadedFolderToast: '已从目录载入 {count} 篇 Markdown 文档', + loadedClipboardToast: '已从剪贴板载入:{title}', + loadedManualToast: '已载入编辑内容:{title}', + folderNoMarkdownToast: '所选目录中未找到 .md / .markdown 文件', + folderPartialSkippedToast: '已载入 {loaded} 篇文档,跳过 {skipped} 个超限或不可读文件', + copiedPlainToast: '已复制纯文本到剪贴板', + copiedRichToast: '已复制富文本({preset}排版)', + fastCopiedToast: '已按公文排版复制为 Word 富文本', + exportedDocxToast: '已导出 Word 文档:{name}', + exportedSizeInfo: '{name} ({sizeKb} KB)', + presetSwitchedToast: '导出排版已切换为:{preset}', + fontSizeSwitchedToast: '正文字号已切换为:{fontSize}', + indentToggledToast: '正文首行缩进已{state}', + opFailedTitle: '操作失败', + errUpgradeClient: '当前客户端版本暂不支持 Markdown 文档接口,请升级 ZTools 后重试', + errInvalidHostResult: '客户端返回的文档处理结果无效', + errInvalidClipboard: '剪贴板读取结果无效', + errInvalidMarkdown: 'Markdown 内容不能为空且不得超过 256 KiB', + errRequireDocxExt: '导出目标路径必须以 .docx 结尾', + errDropMarkdown: '请拖入 .md、.markdown 或 .txt 文件', + errOperationFailed: '处理 Markdown 文档失败', + defaultDocTitle: '未命名文档' + }, + 'en-US': { + navTitle: 'Markdown Reader & Word Export', + searchDocumentsPlaceholder: 'Search opened Markdown titles, paths, or content…', + searchOutlinePlaceholder: 'Filter headings in current document…', + modeTooltip: 'Switch view mode', + modeDocuments: 'Documents', + modeOutline: 'Outline', + openFileAction: 'Open File', + openFolderAction: 'Open Folder', + summaryEmpty: 'Open local files/folders, read clipboard, enter Markdown, or drop/paste directly', + summaryDocuments: '{count} documents · Export preset: {preset}', + summaryOutline: '{title} · {count} headings', + presetOfficial: 'Formal', + presetBusiness: 'Business', + presetAcademic: 'Academic', + fontSize3: '16pt (Size 3)', + fontSizeS4: '12pt (Small 4)', + fontSize5: '10.5pt (Size 5)', + indentOn: 'On', + indentOff: 'Off', + sourceFile: 'Local File', + sourceClipboard: 'Clipboard Content', + sourceManual: 'Manual Input', + wordsUnit: '{count} words', + readMinutesUnit: '~{minutes} min read', + headingsUnit: '{count} headings', + metaDocSource: 'Source', + metaWords: 'Words', + metaCharacters: 'Characters', + metaReadingTime: 'Reading Time', + metaHeadings: 'Headings', + metaCodeAndMath: 'Code / Math Blocks', + metaExportPreset: 'Export Preset', + metaFontSize: 'Body Font Size', + metaFirstLineIndent: 'First-Line Indent', + metaLastExported: 'Last Exported', + metaLineNumber: 'Start Line', + actionViewOutline: 'Browse Outline & Jump', + actionBackToDocuments: 'Back to Documents', + actionCopyPlainText: 'Copy Plain Text', + actionCopyRichText: 'Copy Rich Text (Word-ready)', + actionCopyRawMarkdown: 'Copy Raw Markdown', + actionCopySectionMarkdown: 'Copy Section Markdown', + actionExportDocx: 'Export Word (.docx)', + actionOpenExported: 'Open Exported Word Document', + actionRevealExported: 'Show in File Manager', + actionCopyExportedPath: 'Copy Exported Path', + actionSwitchPreset: 'Cycle Export Preset (Current: {preset})', + actionSwitchFontSize: 'Cycle Font Size (Current: {fontSize})', + actionToggleIndent: 'Toggle First-Line Indent (Current: {state})', + actionReadClipboard: 'Read Clipboard Markdown', + actionInputMarkdown: 'Enter Markdown Text', + actionEditMarkdown: 'Edit Markdown Source', + actionReloadDoc: 'Reload Document', + actionRemoveDoc: 'Remove from Workbench', + sectionExported: 'Last Exported', + sectionFormatting: 'Word Formatting', + sectionDocument: 'Source & Editing', + formNavTitle: 'Enter / Edit Markdown', + formSubmitTitle: 'Load into Workbench', + formFieldTitle: 'Markdown Text', + formFieldPlaceholder: 'Enter or paste Markdown, up to 256 KiB', + formDescTitle: 'Formatting & Safety', + formDescHelp: 'Supports headings, bold, lists, tables, math formulas, and code blocks; exporting to Word never modifies source files.', + emptyTitle: 'No Markdown Documents Opened', + emptySubtitle: 'Open a local file or folder, read clipboard, enter Markdown, or drop/paste directly', + emptyNoMatchTitle: 'No Matching Documents', + emptyNoMatchSubtitle: 'Try a different keyword or open more local Markdown files', + emptyNoHeadingsTitle: 'No Headings Found in Document', + emptyNoHeadingsSubtitle: 'Add Markdown headings (# Heading) to enable outline jumping', + openFileDialogTitle: 'Select Markdown File', + openFolderDialogTitle: 'Select Markdown Folder', + saveDocxDialogTitle: 'Export Word Document (.docx)', + dropTitle: 'Drop Markdown Files Here', + dropSubtitle: 'Supports .md / .markdown / .txt (max 256 KiB each)', + loadedFileToast: 'Loaded document: {name}', + loadedFolderToast: 'Loaded {count} Markdown documents from folder', + loadedClipboardToast: 'Loaded from clipboard: {title}', + loadedManualToast: 'Loaded edited content: {title}', + folderNoMarkdownToast: 'No .md or .markdown files found in selected folder', + folderPartialSkippedToast: 'Loaded {loaded} documents; skipped {skipped} oversized or unreadable files', + copiedPlainToast: 'Plain text copied to clipboard', + copiedRichToast: 'Rich text copied ({preset} style)', + fastCopiedToast: 'Copied as Formal Word Rich Text', + exportedDocxToast: 'Exported Word document: {name}', + exportedSizeInfo: '{name} ({sizeKb} KB)', + presetSwitchedToast: 'Export preset switched to: {preset}', + fontSizeSwitchedToast: 'Font size switched to: {fontSize}', + indentToggledToast: 'First-line indent turned {state}', + opFailedTitle: 'Operation Failed', + errUpgradeClient: 'Your ZTools client does not support Markdown document APIs. Please update ZTools.', + errInvalidHostResult: 'Invalid document result returned by host', + errInvalidClipboard: 'Invalid clipboard read result', + errInvalidMarkdown: 'Markdown text must be non-empty and within 256 KiB', + errRequireDocxExt: 'Export target file path must end with .docx', + errDropMarkdown: 'Please drop .md, .markdown, or .txt files', + errOperationFailed: 'Failed to process Markdown document', + defaultDocTitle: 'Untitled' + } +} as const + +export const DEFAULT_MESSAGES = MESSAGES['zh-CN'] +export const t = createTranslator(MESSAGES, { defaultLocale: 'en-US' }) diff --git a/extensions/super-markdown/src/index.tsx b/extensions/super-markdown/src/index.tsx new file mode 100644 index 00000000..6dd1aea6 --- /dev/null +++ b/extensions/super-markdown/src/index.tsx @@ -0,0 +1,852 @@ +import React, { + Action, + ActionPanel, + Clipboard, + Form, + Icon, + List, + Toast, + showToast, + useEffect, + useLocale, + useMemo, + useNavigation, + useRef, + useState +} from '@ztools/declarative-ui' +import { resolveErrorMessage } from './error-i18n.js' +import { isDeclarativeFileInputSupported } from './host-compat.js' +import { t } from './i18n.js' +import { + isValidMarkdownBytes, + markdownToPlainText, + prepareSafePreviewMarkdown +} from './markdown-analyzer.js' +import { SuperMarkdownService, buildVirtualDocument } from './markdown-service.js' +import type { + ExportedDocxInfo, + LoadedMarkdownDoc, + MarkdownDocSource, + MarkdownExportOptions, + MarkdownFontSize, + MarkdownPreset, + MarkdownViewMode, + OutlineHeading +} from './types.js' + +export * from './types.js' +export * from './markdown-analyzer.js' +export * from './markdown-service.js' + +const PRESET_ORDER: readonly MarkdownPreset[] = ['business', 'official', 'academic'] +const FONT_SIZE_ORDER: readonly MarkdownFontSize[] = ['size-3', 'size-s4', 'size-5'] +const FAST_OFFICIAL_OPTIONS: MarkdownExportOptions = { + preset: 'official', + fontSize: 'size-3', + firstLineIndent: true +} + +function presetLabel(preset: MarkdownPreset): string { + if (preset === 'official') return t('presetOfficial') + if (preset === 'academic') return t('presetAcademic') + return t('presetBusiness') +} + +function fontSizeLabel(fontSize: MarkdownFontSize): string { + if (fontSize === 'size-3') return t('fontSize3') + if (fontSize === 'size-5') return t('fontSize5') + return t('fontSizeS4') +} + +function indentLabel(enabled: boolean): string { + return enabled ? t('indentOn') : t('indentOff') +} + +function sourceLabel(source: MarkdownDocSource): string { + if (source === 'clipboard') return t('sourceClipboard') + if (source === 'manual') return t('sourceManual') + return t('sourceFile') +} + +function defaultExportOptions(preset: MarkdownPreset): MarkdownExportOptions { + if (preset === 'official') { + return { preset: 'official', fontSize: 'size-3', firstLineIndent: true } + } + if (preset === 'academic') { + return { preset: 'academic', fontSize: 'size-5', firstLineIndent: false } + } + return { preset: 'business', fontSize: 'size-s4', firstLineIndent: false } +} + +function headingIndentPrefix(level: number): string { + return level > 1 ? `${' '.repeat(Math.min(level - 1, 4))}H${level} ` : 'H1 ' +} + +interface MarkdownEditorFormProps { + readonly initial: string + readonly onApply: (markdown: string, isAlive: () => boolean) => Promise +} + +/** 内联 Markdown 编辑与新建表单(带卸载保护与并发提交锁) */ +function MarkdownEditorForm({ initial, onApply }: MarkdownEditorFormProps) { + useLocale() + const { pop } = useNavigation() + const [text, setText] = useState(initial) + const [busy, setBusy] = useState(false) + const [error, setError] = useState('') + const aliveRef = useRef(true) + const submittingRef = useRef(false) + + useEffect(() => { + aliveRef.current = true + return () => { + aliveRef.current = false + } + }, []) + + const handleSubmit = async () => { + if (submittingRef.current || !aliveRef.current) return + if (!isValidMarkdownBytes(text)) { + setError(t('errInvalidMarkdown')) + return + } + submittingRef.current = true + setBusy(true) + setError('') + try { + const applied = await onApply(text, () => aliveRef.current) + if (applied && aliveRef.current) { + pop() + } + } catch (err) { + if (aliveRef.current) { + setError(resolveErrorMessage(err, t('errOperationFailed'))) + } + } finally { + submittingRef.current = false + if (aliveRef.current) { + setBusy(false) + } + } + } + + return ( + + void handleSubmit()} /> + + } + > + { + setText(value) + if (error) setError('') + }} + placeholder={t('formFieldPlaceholder')} + /> + + + ) +} + +export interface SuperMarkdownCommandProps { + readonly autoClipboardCopy?: boolean +} + +export default function SuperMarkdownCommand({ autoClipboardCopy = false }: SuperMarkdownCommandProps = {}) { + useLocale() + const { push } = useNavigation() + const serviceRef = useRef(null) + if (!serviceRef.current) { + serviceRef.current = new SuperMarkdownService() + } + const mountedRef = useRef(true) + const autoRunDoneRef = useRef(false) + + const [docs, setDocs] = useState([]) + const [activeDocId, setActiveDocId] = useState(null) + const [viewMode, setViewMode] = useState('documents') + const [query, setQuery] = useState('') + const [exportOptions, setExportOptions] = useState(() => defaultExportOptions('business')) + const [lastExported, setLastExported] = useState(null) + const [busy, setBusy] = useState(false) + + const exportOptionsRef = useRef(exportOptions) + exportOptionsRef.current = exportOptions + + const activeDoc = useMemo( + () => docs.find((d) => d.id === activeDocId) ?? docs[0] ?? null, + [docs, activeDocId] + ) + + const upsertDocuments = (incoming: readonly LoadedMarkdownDoc[]) => { + if (incoming.length === 0) return + setDocs((prev) => { + const map = new Map() + for (const item of prev) map.set(item.id, item) + for (const item of incoming) map.set(item.id, item) + return [...map.values()].sort((a, b) => b.loadedAt - a.loadedAt) + }) + setActiveDocId(incoming[0]!.id) + } + + useEffect(() => { + mountedRef.current = true + if (autoClipboardCopy && !autoRunDoneRef.current) { + autoRunDoneRef.current = true + void (async () => { + setBusy(true) + try { + const markdown = await serviceRef.current!.readClipboardMarkdown() + if (!mountedRef.current) return + const doc = buildVirtualDocument('clipboard', markdown, t('sourceClipboard')) + upsertDocuments([doc]) + setViewMode('documents') + setExportOptions(FAST_OFFICIAL_OPTIONS) + exportOptionsRef.current = FAST_OFFICIAL_OPTIONS + await serviceRef.current!.copyRichText(markdown, FAST_OFFICIAL_OPTIONS) + if (!mountedRef.current) return + await showToast({ + style: Toast.Style.Success, + title: t('fastCopiedToast') + }) + } catch (err) { + if (!mountedRef.current) return + await showToast({ + style: Toast.Style.Failure, + title: t('opFailedTitle'), + message: resolveErrorMessage(err, t('errOperationFailed')) + }) + } finally { + if (mountedRef.current) setBusy(false) + } + })() + } + return () => { + mountedRef.current = false + void serviceRef.current?.cancelActive() + } + }, [autoClipboardCopy]) + + const loadFilePaths = async (paths: readonly string[]) => { + if (paths.length === 0) return + setBusy(true) + const loaded: LoadedMarkdownDoc[] = [] + let skipped = 0 + let lastErr: unknown = null + + try { + for (const filePath of paths) { + try { + const doc = await serviceRef.current!.readDocument(filePath) + loaded.push(doc) + } catch (err) { + skipped += 1 + lastErr = err + } + } + if (!mountedRef.current) return + if (loaded.length > 0) { + upsertDocuments(loaded) + setViewMode('documents') + if (skipped > 0) { + await showToast({ + style: Toast.Style.Success, + title: t('folderPartialSkippedToast', { loaded: loaded.length, skipped }) + }) + } else if (loaded.length === 1) { + await showToast({ + style: Toast.Style.Success, + title: t('loadedFileToast', { name: loaded[0]!.name }) + }) + } else { + await showToast({ + style: Toast.Style.Success, + title: t('loadedFolderToast', { count: loaded.length }) + }) + } + } else if (lastErr) { + await showToast({ + style: Toast.Style.Failure, + title: t('opFailedTitle'), + message: resolveErrorMessage(lastErr, t('errOperationFailed')) + }) + } + } finally { + if (mountedRef.current) setBusy(false) + } + } + + const handleOpenFiles = async () => { + try { + const paths = await serviceRef.current!.pickMarkdownFiles() + if (!mountedRef.current) return + if (paths.length > 0) { + await loadFilePaths(paths) + } + } catch (err) { + if (!mountedRef.current) return + await showToast({ + style: Toast.Style.Failure, + title: t('opFailedTitle'), + message: resolveErrorMessage(err, t('errOperationFailed')) + }) + } + } + + const handleOpenFolder = async () => { + setBusy(true) + try { + const folder = await serviceRef.current!.pickMarkdownFolder() + if (!folder || !mountedRef.current) return + const files = await serviceRef.current!.listMarkdownFilesInFolder(folder) + if (!mountedRef.current) return + if (files.length === 0) { + await showToast({ style: Toast.Style.Failure, title: t('folderNoMarkdownToast') }) + return + } + await loadFilePaths(files) + } catch (err) { + if (!mountedRef.current) return + await showToast({ + style: Toast.Style.Failure, + title: t('opFailedTitle'), + message: resolveErrorMessage(err, t('errOperationFailed')) + }) + } finally { + if (mountedRef.current) setBusy(false) + } + } + + const handleReadClipboard = async () => { + setBusy(true) + try { + const markdown = await serviceRef.current!.readClipboardMarkdown() + if (!mountedRef.current) return + const doc = buildVirtualDocument('clipboard', markdown, t('sourceClipboard')) + upsertDocuments([doc]) + setViewMode('documents') + await showToast({ + style: Toast.Style.Success, + title: t('loadedClipboardToast', { title: doc.title }) + }) + } catch (err) { + if (!mountedRef.current) return + await showToast({ + style: Toast.Style.Failure, + title: t('opFailedTitle'), + message: resolveErrorMessage(err, t('errOperationFailed')) + }) + } finally { + if (mountedRef.current) setBusy(false) + } + } + + const handlePasteMarkdownText = async (pastedText: string) => { + if (!isValidMarkdownBytes(pastedText)) { + if (!mountedRef.current) return + await showToast({ + style: Toast.Style.Failure, + title: t('opFailedTitle'), + message: t('errInvalidMarkdown') + }) + return + } + const doc = buildVirtualDocument('clipboard', pastedText, t('sourceClipboard')) + upsertDocuments([doc]) + setViewMode('documents') + await showToast({ + style: Toast.Style.Success, + title: t('loadedClipboardToast', { title: doc.title }) + }) + } + + const handleOpenEditor = (initial = '', editDoc?: LoadedMarkdownDoc) => { + const idOverride = editDoc && editDoc.source === 'manual' ? editDoc.id : undefined + push( + { + if (!mountedRef.current || !isFormAlive()) return false + const doc = buildVirtualDocument('manual', markdown, t('sourceManual'), idOverride) + upsertDocuments([doc]) + setViewMode('documents') + setQuery('') + await showToast({ + style: Toast.Style.Success, + title: t('loadedManualToast', { title: doc.title }) + }) + return true + }} + /> + ) + } + + const handleCopyPlainText = async (markdown: string) => { + try { + const plain = markdownToPlainText(markdown) + await Clipboard.copy(plain) + if (!mountedRef.current) return + await showToast({ style: Toast.Style.Success, title: t('copiedPlainToast') }) + } catch (err) { + if (!mountedRef.current) return + await showToast({ + style: Toast.Style.Failure, + title: t('opFailedTitle'), + message: resolveErrorMessage(err, t('errOperationFailed')) + }) + } + } + + const handleCopyRichText = async (markdown: string) => { + setBusy(true) + const options = exportOptionsRef.current + try { + await serviceRef.current!.copyRichText(markdown, options) + if (!mountedRef.current) return + await showToast({ + style: Toast.Style.Success, + title: t('copiedRichToast', { preset: presetLabel(options.preset) }) + }) + } catch (err) { + if (!mountedRef.current) return + await showToast({ + style: Toast.Style.Failure, + title: t('opFailedTitle'), + message: resolveErrorMessage(err, t('errOperationFailed')) + }) + } finally { + if (mountedRef.current) setBusy(false) + } + } + + const handleExportDocx = async (doc: LoadedMarkdownDoc) => { + setBusy(true) + const options = exportOptionsRef.current + try { + const result = await serviceRef.current!.exportDocx(doc, options) + if (!mountedRef.current) return + if (result) { + setLastExported(result) + await showToast({ + style: Toast.Style.Success, + title: t('exportedDocxToast', { name: result.name }) + }) + } + } catch (err) { + if (!mountedRef.current) return + await showToast({ + style: Toast.Style.Failure, + title: t('opFailedTitle'), + message: resolveErrorMessage(err, t('errOperationFailed')) + }) + } finally { + if (mountedRef.current) setBusy(false) + } + } + + const handleCyclePreset = async () => { + const current = exportOptionsRef.current + const nextPreset = PRESET_ORDER[(PRESET_ORDER.indexOf(current.preset) + 1) % PRESET_ORDER.length]! + const nextOptions = defaultExportOptions(nextPreset) + setExportOptions(nextOptions) + exportOptionsRef.current = nextOptions + await showToast({ + style: Toast.Style.Success, + title: t('presetSwitchedToast', { preset: presetLabel(nextPreset) }) + }) + } + + const handleCycleFontSize = async () => { + const current = exportOptionsRef.current + const nextFontSize = FONT_SIZE_ORDER[(FONT_SIZE_ORDER.indexOf(current.fontSize) + 1) % FONT_SIZE_ORDER.length]! + const nextOptions: MarkdownExportOptions = { ...current, fontSize: nextFontSize } + setExportOptions(nextOptions) + exportOptionsRef.current = nextOptions + await showToast({ + style: Toast.Style.Success, + title: t('fontSizeSwitchedToast', { fontSize: fontSizeLabel(nextFontSize) }) + }) + } + + const handleToggleIndent = async () => { + const current = exportOptionsRef.current + const nextIndent = !current.firstLineIndent + const nextOptions: MarkdownExportOptions = { ...current, firstLineIndent: nextIndent } + setExportOptions(nextOptions) + exportOptionsRef.current = nextOptions + await showToast({ + style: Toast.Style.Success, + title: t('indentToggledToast', { state: indentLabel(nextIndent) }) + }) + } + + const handleRemoveDoc = (docId: string) => { + setDocs((prev) => { + const next = prev.filter((item) => item.id !== docId) + if (activeDocId === docId) { + setActiveDocId(next[0]?.id ?? null) + } + if (next.length === 0) setViewMode('documents') + return next + }) + } + + const filteredDocs = useMemo(() => { + const q = query.trim().toLowerCase() + if (!q) return docs + return docs.filter((doc) => + `${doc.title} ${doc.name} ${doc.path} ${doc.markdown}`.toLowerCase().includes(q) + ) + }, [docs, query]) + + const filteredOutline = useMemo(() => { + const headings = activeDoc?.outline ?? [] + const q = query.trim().toLowerCase() + if (!q) return headings + return headings.filter((h) => h.text.toLowerCase().includes(q)) + }, [activeDoc, query]) + + const renderExportedSection = () => + lastExported ? ( + + + + + + ) : null + + const renderFormattingSection = () => ( + + void handleCyclePreset()} + /> + void handleCycleFontSize()} + /> + void handleToggleIndent()} + /> + + ) + + const renderSourceActions = () => ( + <> + void handleReadClipboard()} /> + handleOpenEditor(query.trim())} /> + void handleOpenFiles()} /> + void handleOpenFolder()} /> + + ) + + const renderDocMetadata = (doc: LoadedMarkdownDoc, heading?: OutlineHeading) => ( + + + + + + + + + + + {lastExported && ( + + )} + {heading && ( + + )} + + ) + + const summaryText = + docs.length === 0 + ? t('summaryEmpty') + : viewMode === 'outline' && activeDoc + ? t('summaryOutline', { title: activeDoc.title, count: activeDoc.outline.length }) + : t('summaryDocuments', { count: filteredDocs.length, preset: presetLabel(exportOptions.preset) }) + + const supportsDrop = isDeclarativeFileInputSupported() + + return ( + 0} + isLoading={busy} + navigationTitle={t('navTitle')} + searchText={query} + onSearchTextChange={setQuery} + searchBarPlaceholder={ + viewMode === 'outline' ? t('searchOutlinePlaceholder') : t('searchDocumentsPlaceholder') + } + onSelectionChange={(selectedId) => { + if (viewMode === 'documents' && selectedId && docs.some((d) => d.id === selectedId)) { + setActiveDocId(selectedId) + } + }} + searchBarAccessory={ + { + setViewMode(val as MarkdownViewMode) + setQuery('') + }} + tooltip={t('modeTooltip')} + > + + + + } + filterBar={{ + summaryText, + actions: [ + { + id: 'open-file', + title: t('openFileAction'), + icon: Icon.Document, + onAction: () => void handleOpenFiles() + }, + { + id: 'open-folder', + title: t('openFolderAction'), + icon: Icon.Folder, + onAction: () => void handleOpenFolder() + } + ] + }} + {...(supportsDrop + ? { + fileInput: { + extensions: ['.md', '.markdown', '.txt'], + allowDirectories: false, + dropTitle: t('dropTitle'), + dropSubtitle: t('dropSubtitle'), + onTextPaste: (pastedText: string) => { + void handlePasteMarkdownText(pastedText) + return true + } + }, + onFileInput: (payload: { files: string[] }) => { + const matched = (payload.files ?? []).filter((f) => /\.(?:md|markdown|txt)$/i.test(f)) + if (matched.length === 0) { + void showToast({ style: Toast.Style.Failure, title: t('opFailedTitle'), message: t('errDropMarkdown') }) + return + } + void loadFilePaths(matched) + } + } + : {})} + > + {docs.length === 0 && ( + + void handleOpenFiles()} /> + void handleOpenFolder()} /> + void handleReadClipboard()} /> + handleOpenEditor(query.trim())} /> + + } + /> + )} + + {docs.length > 0 && viewMode === 'documents' && filteredDocs.map((doc) => ( + + } + actions={ + + { + setActiveDocId(doc.id) + setViewMode('outline') + setQuery('') + }} + /> + void handleCopyRichText(doc.markdown)} + /> + void handleCopyPlainText(doc.markdown)} + /> + void handleExportDocx(doc)} + /> + {renderExportedSection()} + {renderFormattingSection()} + + handleOpenEditor(doc.markdown, doc)} + /> + + {renderSourceActions()} + {doc.source === 'file' && doc.path && ( + void loadFilePaths([doc.path])} + /> + )} + handleRemoveDoc(doc.id)} + /> + + + } + /> + ))} + + {docs.length > 0 && viewMode === 'documents' && filteredDocs.length === 0 && ( + + {renderSourceActions()} + + } + /> + )} + + {docs.length > 0 && viewMode === 'outline' && activeDoc && filteredOutline.map((heading) => ( + + } + actions={ + + { + void Clipboard.copy(heading.sectionMarkdown).then(() => + showToast({ style: Toast.Style.Success, title: t('copiedPlainToast') }) + ) + }} + /> + void handleCopyRichText(heading.sectionMarkdown)} + /> + void handleExportDocx(activeDoc)} + /> + { + setViewMode('documents') + setQuery('') + }} + /> + {renderExportedSection()} + {renderFormattingSection()} + + } + /> + ))} + + {docs.length > 0 && viewMode === 'outline' && (!activeDoc || filteredOutline.length === 0) && ( + + setViewMode('documents')} + /> + + } + /> + )} + + ) +} + +export const commands = { + 'markdown-workbench': () => , + 'markdown-clipboard-fast': () => +} diff --git a/extensions/super-markdown/src/markdown-analyzer.ts b/extensions/super-markdown/src/markdown-analyzer.ts new file mode 100644 index 00000000..a7b093c3 --- /dev/null +++ b/extensions/super-markdown/src/markdown-analyzer.ts @@ -0,0 +1,194 @@ +import type { MarkdownStats, OutlineHeading } from './types.js' + +export const MAX_MARKDOWN_BYTES = 256 * 1024 + +interface RawHeading { + readonly level: number + readonly text: string + readonly lineIndex: number +} + +/** 校验 Markdown 文本体积与基本合法性(与宿主 256 KiB 上限一致) */ +export function isValidMarkdownBytes(markdown: string): boolean { + if (typeof markdown !== 'string' || !markdown.trim()) return false + return new TextEncoder().encode(markdown).length <= MAX_MARKDOWN_BYTES +} + +/** 剥离标题行内常见 Markdown 修饰符用于大纲展示 */ +function cleanHeadingLabel(raw: string): string { + return raw + .replace(/\s+#+\s*$/, '') + .replace(/!\[([^\]]*)\]\([^)]*\)/g, '$1') + .replace(/\[([^\]]+)\]\([^)]*\)/g, '$1') + .replace(/[`*_~]/g, '') + .trim() +} + +/** + * 提取 Markdown 标题大纲(兼容 ATX `#` 与 Setext `===`/`---` 标题,自动忽略围栏代码块), + * 并为每个标题切分对应章节的 Markdown 正文片段以实现右侧精准跳转预览。 + */ +export function extractOutline(markdown: string): OutlineHeading[] { + const normalized = markdown.replace(/\r\n?/g, '\n') + const lines = normalized.split('\n') + const rawHeadings: RawHeading[] = [] + + let fenceChar = '' + let fenceLen = 0 + + for (let i = 0; i < lines.length; i++) { + const line = lines[i] ?? '' + const fenceMatch = line.match(/^ {0,3}(`{3,}|~{3,})/) + if (fenceMatch) { + const marker = fenceMatch[1]! + if (!fenceChar) { + fenceChar = marker[0]! + fenceLen = marker.length + } else if (marker[0] === fenceChar && marker.length >= fenceLen) { + fenceChar = '' + fenceLen = 0 + } + continue + } + if (fenceChar) continue + + const atxMatch = line.match(/^ {0,3}(#{1,6})[ \t]+(.+?)\s*$/) + if (atxMatch) { + const level = atxMatch[1]!.length + const text = cleanHeadingLabel(atxMatch[2]!) + if (text) { + rawHeadings.push({ level, text, lineIndex: i }) + } + continue + } + + if (i > 0) { + const setextMatch = line.match(/^ {0,3}(=+|-+)[ \t]*$/) + const prevLine = lines[i - 1] ?? '' + if ( + setextMatch && + prevLine.trim() && + !/^ {0,3}(?:[-*+]|\d+[.)]|>|#)/.test(prevLine) + ) { + const level = setextMatch[1]!.startsWith('=') ? 1 : 2 + const text = cleanHeadingLabel(prevLine) + if (text) { + rawHeadings.push({ level, text, lineIndex: i - 1 }) + } + } + } + } + + return rawHeadings.map((heading, idx) => { + // 章节范围截止到下一个同级或更高级标题之前 + let endLine = lines.length + for (let next = idx + 1; next < rawHeadings.length; next++) { + if (rawHeadings[next]!.level <= heading.level) { + endLine = rawHeadings[next]!.lineIndex + break + } + } + const sectionMarkdown = lines.slice(heading.lineIndex, endLine).join('\n').trim() + return { + id: `h-${heading.lineIndex + 1}-${idx}`, + level: heading.level, + text: heading.text, + lineNumber: heading.lineIndex + 1, + sectionMarkdown + } + }) +} + +/** + * 统计 Markdown 文档的中英文字数、字符数、代码块数、数学公式块数与预计阅读时长。 + * 中文按单字计,英文/数字按单词计,避免英文被错误按字符拆分。 + */ +export function analyzeMarkdownStats(markdown: string, outline?: readonly OutlineHeading[]): MarkdownStats { + const normalized = markdown.replace(/\r\n?/g, '\n') + const lines = normalized.split('\n') + const headings = outline ? outline.length : extractOutline(normalized).length + + let codeBlocks = 0 + let fenceChar = '' + let fenceLen = 0 + for (const line of lines) { + const match = line.match(/^ {0,3}(`{3,}|~{3,})/) + if (!match) continue + const marker = match[1]! + if (!fenceChar) { + fenceChar = marker[0]! + fenceLen = marker.length + codeBlocks += 1 + } else if (marker[0] === fenceChar && marker.length >= fenceLen) { + fenceChar = '' + fenceLen = 0 + } + } + + // 统计块级公式($$...$$)与行内公式($...$,排除转义 \$) + const withoutCode = normalized.replace(/```[\s\S]*?```|~~~[\s\S]*?~~~/g, '') + const blockMathMatches = withoutCode.match(/\$\$[\s\S]+?\$\$/g) ?? [] + const withoutBlockMath = withoutCode.replace(/\$\$[\s\S]+?\$\$/g, '') + const inlineMathMatches = withoutBlockMath.match(/(?\s?/gm, '') + .replace(/^ {0,3}(?:[-*+]|\d+[.)])\s+/gm, '') + .replace(/[*_~`]/g, '') + .replace(/\n{3,}/g, '\n\n') + .trim() +} + +/** + * 为右侧安全声明式 Detail 预览准备 Markdown(将块级数学公式 `$$...$$` 格式化为安全 `math` 代码围栏或保留原块, + * 避免原始 HTML 标签穿透并保证公式可读性)。 + */ +export function prepareSafePreviewMarkdown(markdown: string): string { + // 剔除潜在危险 HTML 原始标签(如 '), /', - ].join('\n'); - const dataUri = `data:image/svg+xml;utf8,${encodeURIComponent(working)}`; - const base64DataUri = `data:image/svg+xml;base64,${toBase64(working)}`; - return { - originalSvg: trimmed, - optimizedSvg: working, - reactTsxCode, - vueSfcCode, - dataUri, - base64DataUri, - metrics: { - originalBytes, - optimizedBytes, - savedBytes, - savedPercentage, - viewBox, - pathCount, - removedDangerousNodes, - }, - }; -} diff --git a/packages/declarative-ui/dist/examples/svg-icon-studio/types.d.ts b/packages/declarative-ui/dist/examples/svg-icon-studio/types.d.ts deleted file mode 100644 index 97e5760f..00000000 --- a/packages/declarative-ui/dist/examples/svg-icon-studio/types.d.ts +++ /dev/null @@ -1,19 +0,0 @@ -export type SvgExportFormat = 'minified' | 'react-tsx' | 'vue-sfc' | 'data-uri'; -export interface SvgOptimizeMetrics { - originalBytes: number; - optimizedBytes: number; - savedBytes: number; - savedPercentage: number; - viewBox: string; - pathCount: number; - removedDangerousNodes: number; -} -export interface SvgProcessResult { - originalSvg: string; - optimizedSvg: string; - reactTsxCode: string; - vueSfcCode: string; - dataUri: string; - base64DataUri: string; - metrics: SvgOptimizeMetrics; -} diff --git a/packages/declarative-ui/dist/examples/svg-icon-studio/types.js b/packages/declarative-ui/dist/examples/svg-icon-studio/types.js deleted file mode 100644 index cb0ff5c3..00000000 --- a/packages/declarative-ui/dist/examples/svg-icon-studio/types.js +++ /dev/null @@ -1 +0,0 @@ -export {}; diff --git a/packages/declarative-ui/dist/examples/system-backup/index.d.ts b/packages/declarative-ui/dist/examples/system-backup/index.d.ts deleted file mode 100644 index 23029093..00000000 --- a/packages/declarative-ui/dist/examples/system-backup/index.d.ts +++ /dev/null @@ -1,11 +0,0 @@ -/** - * ZTools 2.0 标杆原生插件视图: 系统与开发环境关键配置备份工坊 (System Backup 2.0 - 布局二:左 32% 配置分类树 + 右 68% 可勾选配置与快照列表) - * - * 严格遵循 ZTools 效率工具箱 UI 与交互设计五大黄金法则: - * 1. 布局二(Master-SubList Cleaner):左 32% 4 大系统与极客配置分类导航树 + 右 68% 可勾选配置文件与快照列表 - * 2. 顶部唯一筛选:searchBarAccessory Dropdown 切换备份策略模式 (全量快照 / 极客 Dotfiles / 增量归档) - * 3. 单行极简状态条:filterBar.summaryText 融合备份归档仓库路径、已选配置项数量与总大小,仅保留 1 个全局重新扫描按钮 - * 4. 零彩色 Emoji 与去彩虹化:100% 单色 SVG 图标、单色中性灰进度条与标签 - */ -export declare function SystemBackupCommand(): import("../../index.js").ViewDescriptor; -export default SystemBackupCommand; diff --git a/packages/declarative-ui/dist/examples/system-backup/index.js b/packages/declarative-ui/dist/examples/system-backup/index.js deleted file mode 100644 index 9a60488a..00000000 --- a/packages/declarative-ui/dist/examples/system-backup/index.js +++ /dev/null @@ -1,272 +0,0 @@ -/** - * ZTools 2.0 标杆原生插件视图: 系统与开发环境关键配置备份工坊 (System Backup 2.0 - 布局二:左 32% 配置分类树 + 右 68% 可勾选配置与快照列表) - * - * 严格遵循 ZTools 效率工具箱 UI 与交互设计五大黄金法则: - * 1. 布局二(Master-SubList Cleaner):左 32% 4 大系统与极客配置分类导航树 + 右 68% 可勾选配置文件与快照列表 - * 2. 顶部唯一筛选:searchBarAccessory Dropdown 切换备份策略模式 (全量快照 / 极客 Dotfiles / 增量归档) - * 3. 单行极简状态条:filterBar.summaryText 融合备份归档仓库路径、已选配置项数量与总大小,仅保留 1 个全局重新扫描按钮 - * 4. 零彩色 Emoji 与去彩虹化:100% 单色 SVG 图标、单色中性灰进度条与标签 - */ -import { Action, ActionPanel, Icon, List, useEffect, useState } from "../../index.js"; -import { isRealElectronHost } from "../shared/native-ipc.js"; -import { BACKUP_CATEGORIES, BACKUP_PROFILES, createBackupArchive, createInitialSystemBackupSnapshot, fetchSystemBackupSnapshot, formatBytes, openBackupConfigLocation, restoreBackupSnapshot } from "./logic.js"; -export function SystemBackupCommand() { - const [snapshot, setSnapshot] = useState(() => { - const init = createInitialSystemBackupSnapshot(); - if (isRealElectronHost()) { - return { - ...init, - items: [], - totalSizeBytes: 0, - updatedAt: "正在扫描本机配置项..." - }; - } - return init; - }); - const [selectedCategory, setSelectedCategory] = useState("all"); - const [profileMode, setProfileMode] = useState("full_bundle"); - const [checkedIds, setCheckedIds] = useState(() => isRealElectronHost() - ? [] - : [ - "bak_hosts", - "bak_env_path", - "bak_ssh_config", - "bak_gitconfig", - "bak_ps_profile", - "bak_vscode_settings" - ]); - const [searchText, setSearchText] = useState(""); - const [statusBanner, setStatusBanner] = useState(""); - const [isLoading, setIsLoading] = useState(false); - const reloadBackupSnapshot = async () => { - setIsLoading(true); - try { - const data = await fetchSystemBackupSnapshot(); - setSnapshot(data); - if (isRealElectronHost()) { - setCheckedIds(data.items.filter((i) => i.category !== "snapshot_archives").map((i) => i.id)); - } - setStatusBanner(`已扫描本机关键配置项 · 共 ${data.items.length} 项 (${formatBytes(data.totalSizeBytes)}) · 仓库: ${data.backupVaultDir}`); - } - catch (err) { - setStatusBanner(`读取配置列表失败: ${err instanceof Error ? err.message : String(err)}`); - } - finally { - setIsLoading(false); - } - }; - useEffect(() => { - void reloadBackupSnapshot(); - }, []); - const currentProfile = BACKUP_PROFILES.find((p) => p.id === profileMode) || BACKUP_PROFILES[0]; - const keyword = searchText.trim().toLowerCase(); - const visibleItems = snapshot.items.filter((item) => { - if (selectedCategory !== "all" && item.category !== selectedCategory) - return false; - if (keyword) { - const hay = `${item.name} ${item.path} ${item.categoryName} ${item.statusTag}`.toLowerCase(); - if (!hay.includes(keyword)) - return false; - } - return true; - }); - const checkedSet = new Set(checkedIds); - const selectedItems = snapshot.items.filter((i) => checkedSet.has(i.id)); - const selectedBytes = selectedItems.reduce((acc, item) => acc + item.sizeBytes, 0); - const toggleItemCheck = (id) => { - setCheckedIds((prev) => (prev.includes(id) ? prev.filter((i) => i !== id) : [...prev, id])); - }; - const toggleAllVisible = () => { - const visibleIds = visibleItems.map((i) => i.id); - const allChecked = visibleIds.length > 0 && visibleIds.every((id) => checkedSet.has(id)); - if (allChecked) { - const removeSet = new Set(visibleIds); - setCheckedIds((prev) => prev.filter((id) => !removeSet.has(id))); - } - else { - setCheckedIds((prev) => Array.from(new Set([...prev, ...visibleIds]))); - } - }; - const handleCreateBackup = async () => { - const targets = selectedItems.length > 0 ? selectedItems : visibleItems; - setIsLoading(true); - try { - const res = await createBackupArchive(targets, profileMode, snapshot.backupVaultDir); - setStatusBanner(res.message); - } - finally { - setIsLoading(false); - } - }; - const handleRestoreLatest = async (item) => { - const archivePath = item && item.category === "snapshot_archives" - ? item.path - : `${snapshot.backupVaultDir}\\ZTools_SystemBackup_20261018_Full.zip`; - setIsLoading(true); - try { - const res = await restoreBackupSnapshot(archivePath); - setStatusBanner(res.message); - } - finally { - setIsLoading(false); - } - }; - const maxItemBytes = Math.max(1, ...visibleItems.map((i) => i.sizeBytes)); - const summaryText = statusBanner || - `策略: ${currentProfile.label} · 已选 ${selectedItems.length}/${visibleItems.length} 项配置 (${formatBytes(selectedBytes)}) · 归档目录: ${snapshot.backupVaultDir}`; - const leftNavNodes = [ - List.Item({ - id: "nav-bak-all", - title: "全部系统与开发配置", - subtitle: `共 ${snapshot.items.length} 项配置与历史归档`, - icon: Icon.HardDrive, - onSelect: () => setSelectedCategory("all"), - accessories: [ - { progress: 1 }, - { tag: { value: `${snapshot.items.length} 项` } }, - { text: formatBytes(snapshot.totalSizeBytes) } - ], - actions: ActionPanel({ - children: [ - Action({ - title: `立即打包创建快照备份 (${selectedItems.length} 项) (Enter)`, - icon: Icon.Download, - onAction: handleCreateBackup - }), - Action({ - title: "从最近一次快照还原配置 (Ctrl+Enter)", - icon: Icon.RotateAntiClockwise, - onAction: () => handleRestoreLatest() - }) - ] - }) - }), - ...BACKUP_CATEGORIES.map((cat) => { - const catItems = snapshot.items.filter((i) => i.category === cat.id); - const catBytes = catItems.reduce((s, i) => s + i.sizeBytes, 0); - const ratio = Math.min(1, catBytes / Math.max(1, snapshot.totalSizeBytes)); - return List.Item({ - id: `nav-bak-${cat.id}`, - title: cat.name, - subtitle: cat.subtitle, - icon: Icon.Folder, - onSelect: () => setSelectedCategory(cat.id), - accessories: [ - { progress: ratio }, - { tag: { value: `${catItems.length} 项` } }, - { text: formatBytes(catBytes) } - ], - actions: ActionPanel({ - children: [ - Action({ - title: `查看「${cat.name}」配置项 (Enter)`, - icon: Icon.Filter, - onAction: () => setSelectedCategory(cat.id) - }), - Action({ - title: `立即打包备份已选配置 (${selectedItems.length} 项) (Ctrl+Enter)`, - icon: Icon.Download, - onAction: handleCreateBackup - }) - ] - }) - }); - }) - ]; - const subListItems = visibleItems.map((item) => { - const isChecked = checkedSet.has(item.id); - const ratio = Math.min(1, item.sizeBytes / maxItemBytes); - return List.Item({ - id: `bak-item-${item.id}`, - title: item.name, - subtitle: `${item.path} · ${item.lastModified}`, - icon: Icon.Document, - checkable: true, - checked: isChecked, - onCheckChange: () => toggleItemCheck(item.id), - onToggleCheck: () => toggleItemCheck(item.id), - accessories: [ - { progress: ratio }, - { tag: { value: item.statusTag } }, - { text: formatBytes(item.sizeBytes) } - ], - actions: ActionPanel({ - children: [ - Action({ - title: item.category === "snapshot_archives" - ? "从此历史快照归档还原配置 (Enter)" - : `打包备份已勾选配置 (${selectedItems.length} 项) (Enter)`, - icon: item.category === "snapshot_archives" ? Icon.RotateAntiClockwise : Icon.Download, - onAction: () => { - if (item.category === "snapshot_archives") { - void handleRestoreLatest(item); - } - else { - void handleCreateBackup(); - } - } - }), - Action({ - title: "在资源管理器中定位配置文件 (Ctrl+Enter)", - icon: Icon.Folder, - onAction: async () => { - await openBackupConfigLocation(item.path); - } - }), - Action({ - title: isChecked ? "取消勾选此配置项" : "勾选此配置项", - icon: Icon.CheckCircle, - onAction: () => toggleItemCheck(item.id) - }) - ] - }) - }); - }); - const allChecked = visibleItems.length > 0 && visibleItems.every((i) => checkedSet.has(i.id)); - const someChecked = visibleItems.some((i) => checkedSet.has(i.id)); - return List({ - isLoading, - searchBarPlaceholder: "搜索 Hosts、PATH、.ssh/config、.gitconfig、VSCode 配置或备份快照...", - onSearchTextChange: setSearchText, - isShowingDetail: false, - searchBarAccessory: List.Dropdown({ - tooltip: "切换配置备份归档模式", - value: profileMode, - onChange: (val) => setProfileMode(val), - children: BACKUP_PROFILES.map((p) => List.Dropdown.Item({ - title: p.label, - value: p.id - })) - }), - filterBar: { - summaryText, - actions: [ - { - id: "rescan", - title: "重新扫描", - style: "secondary", - onAction: () => { - void reloadBackupSnapshot(); - } - } - ] - }, - subList: { - title: `系统与开发配置明细 (${visibleItems.length} 项 · 已选 ${formatBytes(selectedBytes)})`, - subtitle: snapshot.backupVaultDir, - emptyText: "当前分类下暂无匹配的配置文件", - checkable: visibleItems.length > 0, - checked: allChecked ? true : someChecked ? "indeterminate" : false, - onCheckChange: () => toggleAllVisible(), - items: subListItems - }, - children: [ - List.Section({ - title: "关键配置与快照分类树 (32%)", - subtitle: "系统 / 终端 / IDE / 归档", - children: leftNavNodes - }) - ] - }); -} -export default SystemBackupCommand; diff --git a/packages/declarative-ui/dist/examples/system-backup/logic.d.ts b/packages/declarative-ui/dist/examples/system-backup/logic.d.ts deleted file mode 100644 index 6c4a0e2c..00000000 --- a/packages/declarative-ui/dist/examples/system-backup/logic.d.ts +++ /dev/null @@ -1,65 +0,0 @@ -/** - * ZTools 2.0 标杆原生插件: 系统与开发环境关键配置备份工坊 (System Backup 2.0) - * - * 核心能力: - * 1. 自动扫描并汇总本机关键系统与极客开发配置项: - * - 网络与系统配置:Windows Hosts 文件、系统/用户 PATH 环境变量快照、防火墙与代理规则配置 - * - 开发者密钥与终端配置:~/.ssh/config、~/.gitconfig、~/.npmrc、PowerShell $PROFILE、Windows Terminal settings.json - * - 编辑器与效率工具配置:VSCode settings.json / keybindings.json、ZTools 本地快捷指令与配置库 - * - 历史备份快照归档:已创建的增量与全量配置归档包 (.zip / .zbak) - * 2. 支持一键打包创建时间戳快照备份、还原指定配置项、在资源管理器中定位原配置文件 - */ -import { formatBytes, type NativeInvocationResult } from "../shared/native-ipc.js"; -export { formatBytes }; -export type { NativeInvocationResult }; -export declare const DLL_PLUGIN_NAME = "SystemBackupPlugin"; -export declare const FORBIDDEN_TARGET_PATTERN: RegExp; -export declare const FORBIDDEN_REASON = "\u5907\u4EFD\u76EE\u6807\u8DEF\u5F84\u4E25\u7981\u6307\u5411\u7CFB\u7EDF\u6838\u5FC3\u4FDD\u62A4\u76EE\u5F55\u6216\u5305\u542B\u8DEF\u5F84\u7A7F\u8D8A\u5B57\u7B26"; -export type BackupCategory = "all" | "network_sys" | "dev_terminal" | "editor_tools" | "snapshot_archives"; -export interface BackupCategoryMeta { - id: BackupCategory; - name: string; - subtitle: string; -} -export declare const BACKUP_CATEGORIES: BackupCategoryMeta[]; -export type BackupProfileMode = "full_bundle" | "dotfiles_only" | "incremental_fast"; -export declare const BACKUP_PROFILES: Array<{ - id: BackupProfileMode; - label: string; - desc: string; -}>; -export interface BackupConfigItem { - id: string; - name: string; - path: string; - category: BackupCategory; - categoryName: string; - sizeBytes: number; - lastModified: string; - statusTag: string; -} -export interface SystemBackupSnapshot { - backupVaultDir: string; - items: BackupConfigItem[]; - totalSizeBytes: number; - updatedAt: string; -} -export declare function validateInvocationPayload(method: string, params: Record): { - valid: boolean; - reason?: string; -}; -export declare function invokeNativeCapability(method: string, params: Record, hostOverride?: any): Promise; -export declare function createInitialSystemBackupSnapshot(): SystemBackupSnapshot; -export declare function fetchSystemBackupSnapshot(hostBridge?: any): Promise; -export declare function createBackupArchive(items: BackupConfigItem[], profileMode: BackupProfileMode, vaultDir: string, hostOverride?: any): Promise<{ - ok: boolean; - archivePath: string; - backedUpCount: number; - sizeBytes?: number; - message: string; -}>; -export declare function restoreBackupSnapshot(archivePath: string, targetDirOrHost?: any, hostOverride?: any): Promise<{ - ok: boolean; - message: string; -}>; -export declare function openBackupConfigLocation(targetPath: string, hostBridge?: any): Promise; diff --git a/packages/declarative-ui/dist/examples/system-backup/logic.js b/packages/declarative-ui/dist/examples/system-backup/logic.js deleted file mode 100644 index e9c9a40d..00000000 --- a/packages/declarative-ui/dist/examples/system-backup/logic.js +++ /dev/null @@ -1,377 +0,0 @@ -/** - * ZTools 2.0 标杆原生插件: 系统与开发环境关键配置备份工坊 (System Backup 2.0) - * - * 核心能力: - * 1. 自动扫描并汇总本机关键系统与极客开发配置项: - * - 网络与系统配置:Windows Hosts 文件、系统/用户 PATH 环境变量快照、防火墙与代理规则配置 - * - 开发者密钥与终端配置:~/.ssh/config、~/.gitconfig、~/.npmrc、PowerShell $PROFILE、Windows Terminal settings.json - * - 编辑器与效率工具配置:VSCode settings.json / keybindings.json、ZTools 本地快捷指令与配置库 - * - 历史备份快照归档:已创建的增量与全量配置归档包 (.zip / .zbak) - * 2. 支持一键打包创建时间戳快照备份、还原指定配置项、在资源管理器中定位原配置文件 - */ -import { formatBytes, getRealFileSize, invokeHostCapability, invokePluginService, isRealElectronHost, openRealPath, resolveRealSpecialPaths, scanRealDirectoryTree, showRealItemInFolder } from "../shared/native-ipc.js"; -export { formatBytes }; -export const DLL_PLUGIN_NAME = "SystemBackupPlugin"; -export const FORBIDDEN_TARGET_PATTERN = /(^|[\\/])(Windows|System32|SysWOW64|Program Files|Program Files \(x86\)|\.\.)($|[\\/])/i; -export const FORBIDDEN_REASON = "备份目标路径严禁指向系统核心保护目录或包含路径穿越字符"; -export const BACKUP_CATEGORIES = [ - { - id: "network_sys", - name: "网络与系统配置", - subtitle: "Windows Hosts 映射表、系统与用户环境变量 PATH、网络代理配置" - }, - { - id: "dev_terminal", - name: "开发者密钥与终端配置", - subtitle: "~/.ssh/config、~/.gitconfig、~/.npmrc、PowerShell Profile 与 Terminal 配置" - }, - { - id: "editor_tools", - name: "编辑器与效率工具配置", - subtitle: "VSCode settings.json / keybindings.json、ZTools 本地配置与指令集" - }, - { - id: "snapshot_archives", - name: "历史备份快照归档", - subtitle: "本机已生成的配置全量/增量快照压缩包,支持一键原子回滚" - } -]; -export const BACKUP_PROFILES = [ - { - id: "full_bundle", - label: "全量系统与开发配置快照 (Full Bundle)", - desc: "完整打包 Hosts、环境变量、SSH/Git 与 VSCode/Terminal 全部配置" - }, - { - id: "dotfiles_only", - label: "极客 Dotfiles 专项备份 (Git/SSH/Terminal)", - desc: "仅打包开发者跨机器迁移所需的纯文本 Dotfiles 配置文件" - }, - { - id: "incremental_fast", - label: "增量变更快速归档 (Incremental SHA-256)", - desc: "仅针对与上次快照相比发生哈希变更的配置文件创建轻量归档" - } -]; -export function validateInvocationPayload(method, params) { - if (!method || typeof method !== "string" || method.trim().length === 0) { - return { valid: false, reason: "调用方法名 (method) 不能为空" }; - } - if (!params || typeof params !== "object" || Array.isArray(params)) { - return { valid: false, reason: "调用参数 (params) 必须是非空对象" }; - } - const vault = String(params.vaultDir || params.target || ""); - if (vault && FORBIDDEN_TARGET_PATTERN.test(vault)) { - return { valid: false, reason: FORBIDDEN_REASON }; - } - return { valid: true }; -} -export async function invokeNativeCapability(method, params, hostOverride) { - const validation = validateInvocationPayload(method, params); - if (!validation.valid) { - return { - ok: false, - code: -1, - message: `VALIDATION_FAILED: ${validation.reason}`, - error: `VALIDATION_FAILED: ${validation.reason}` - }; - } - return invokePluginService(DLL_PLUGIN_NAME, method.trim(), params, hostOverride); -} -export function createInitialSystemBackupSnapshot() { - const items = [ - { - id: "bak_hosts", - name: "Windows Hosts 域名映射表 (etc\\hosts)", - path: "C:\\Windows\\System32\\drivers\\etc\\hosts", - category: "network_sys", - categoryName: "网络与系统配置", - sizeBytes: 16 * 1024, - lastModified: "今日已校验", - statusTag: "核心配置" - }, - { - id: "bak_env_path", - name: "系统与用户环境变量注册表快照 (ENV & PATH)", - path: "HKCU\\Environment & HKLM\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment", - category: "network_sys", - categoryName: "网络与系统配置", - sizeBytes: 32 * 1024, - lastModified: "今日已校验", - statusTag: "注册表导出" - }, - { - id: "bak_ssh_config", - name: "SSH 客户端主机与跳板机配置 (.ssh\\config)", - path: "C:\\Users\\Default\\.ssh\\config", - category: "dev_terminal", - categoryName: "开发者密钥与终端配置", - sizeBytes: 12 * 1024, - lastModified: "2 天前更新", - statusTag: "Dotfiles" - }, - { - id: "bak_gitconfig", - name: "Git 全局别名与签名配置 (.gitconfig)", - path: "C:\\Users\\Default\\.gitconfig", - category: "dev_terminal", - categoryName: "开发者密钥与终端配置", - sizeBytes: 8 * 1024, - lastModified: "3 天前更新", - statusTag: "Dotfiles" - }, - { - id: "bak_ps_profile", - name: "PowerShell 7 终端启动脚本 (Microsoft.PowerShell_profile.ps1)", - path: "C:\\Users\\Default\\Documents\\PowerShell\\Microsoft.PowerShell_profile.ps1", - category: "dev_terminal", - categoryName: "开发者密钥与终端配置", - sizeBytes: 24 * 1024, - lastModified: "昨天更新", - statusTag: "终端脚本" - }, - { - id: "bak_vscode_settings", - name: "VSCode 全局设置与快捷键绑定 (settings.json & keybindings.json)", - path: "C:\\Users\\Default\\AppData\\Roaming\\Code\\User\\settings.json", - category: "editor_tools", - categoryName: "编辑器与效率工具配置", - sizeBytes: 96 * 1024, - lastModified: "今日更新", - statusTag: "IDE 配置" - }, - { - id: "bak_archive_latest", - name: "ZTools_SystemBackup_20261018_Full.zip", - path: "C:\\Users\\Default\\Documents\\ZToolsBackups\\ZTools_SystemBackup_20261018_Full.zip", - category: "snapshot_archives", - categoryName: "历史备份快照归档", - sizeBytes: 4250 * 1024, - lastModified: "最近一次快照", - statusTag: "可回滚快照" - } - ]; - return { - backupVaultDir: "C:\\Users\\Default\\Documents\\ZToolsBackups", - items, - totalSizeBytes: items.reduce((acc, item) => acc + item.sizeBytes, 0), - updatedAt: "初始化就绪" - }; -} -export async function fetchSystemBackupSnapshot(hostBridge) { - const initial = createInitialSystemBackupSnapshot(); - const isRealHost = Boolean(hostBridge) || isRealElectronHost(hostBridge) || isRealElectronHost(); - try { - const paths = await resolveRealSpecialPaths(hostBridge); - const userProfile = paths.userProfile || "C:\\Users\\Default"; - const appData = paths.appData || `${userProfile}\\AppData\\Roaming`; - const localAppData = paths.localAppData || `${userProfile}\\AppData\\Local`; - const docs = paths.documents || `${userProfile}\\Documents`; - const backupVaultDir = `${docs}\\ZToolsBackups`; - const candidateConfigs = [ - { - id: "bak_hosts", - name: "Windows Hosts 域名映射表 (etc\\hosts)", - path: "C:\\Windows\\System32\\drivers\\etc\\hosts", - category: "network_sys", - categoryName: "网络与系统配置", - statusTag: "核心配置", - fallbackSize: 16 * 1024 - }, - { - id: "bak_ssh_config", - name: "SSH 客户端主机与跳板机配置 (.ssh\\config)", - path: `${userProfile}\\.ssh\\config`, - category: "dev_terminal", - categoryName: "开发者密钥与终端配置", - statusTag: "Dotfiles", - fallbackSize: 12 * 1024 - }, - { - id: "bak_gitconfig", - name: "Git 全局别名与签名配置 (.gitconfig)", - path: `${userProfile}\\.gitconfig`, - category: "dev_terminal", - categoryName: "开发者密钥与终端配置", - statusTag: "Dotfiles", - fallbackSize: 8 * 1024 - }, - { - id: "bak_npmrc", - name: "NPM 全局镜像与凭证配置 (.npmrc)", - path: `${userProfile}\\.npmrc`, - category: "dev_terminal", - categoryName: "开发者密钥与终端配置", - statusTag: "Dotfiles", - fallbackSize: 4 * 1024 - }, - { - id: "bak_wt_settings", - name: "Windows Terminal 终端配置 (settings.json)", - path: `${localAppData}\\Packages\\Microsoft.WindowsTerminal_8wekyb3d8bbwe\\LocalState\\settings.json`, - category: "dev_terminal", - categoryName: "开发者密钥与终端配置", - statusTag: "终端配置", - fallbackSize: 18 * 1024 - }, - { - id: "bak_ps_profile", - name: "PowerShell 7 终端启动脚本 (Microsoft.PowerShell_profile.ps1)", - path: `${docs}\\PowerShell\\Microsoft.PowerShell_profile.ps1`, - category: "dev_terminal", - categoryName: "开发者密钥与终端配置", - statusTag: "终端脚本", - fallbackSize: 24 * 1024 - }, - { - id: "bak_vscode_settings", - name: "VSCode 全局设置 (settings.json)", - path: `${appData}\\Code\\User\\settings.json`, - category: "editor_tools", - categoryName: "编辑器与效率工具配置", - statusTag: "IDE 配置", - fallbackSize: 96 * 1024 - } - ]; - const [probedSizes, vaultScan] = await Promise.all([ - Promise.all(candidateConfigs.map((c) => getRealFileSize(c.path, hostBridge))), - scanRealDirectoryTree(backupVaultDir, { maxDepth: 1, maxFiles: 30, filterExt: /\.(?:zip|zbak)$/i }, hostBridge) - ]); - const realItems = []; - for (let i = 0; i < candidateConfigs.length; i++) { - const cfg = candidateConfigs[i]; - const realSize = probedSizes[i]; - if (realSize > 0) { - realItems.push({ - id: cfg.id, - name: cfg.name, - path: cfg.path, - category: cfg.category, - categoryName: cfg.categoryName, - sizeBytes: realSize, - lastModified: "本机已验证存在", - statusTag: cfg.statusTag - }); - } - } - const archiveItems = vaultScan.files - .filter((entry) => !entry.isDirectory && entry.sizeBytes > 0) - .map((entry, idx) => ({ - id: `bak_archive_real_${idx}`, - name: entry.name, - path: entry.path, - category: "snapshot_archives", - categoryName: "历史备份快照归档", - sizeBytes: entry.sizeBytes, - lastModified: entry.mtimeMs > 0 ? new Date(entry.mtimeMs).toLocaleDateString() : "历史归档", - statusTag: "可回滚快照" - })); - if (isRealHost) { - const combined = [...realItems, ...archiveItems]; - return { - backupVaultDir, - items: combined, - totalSizeBytes: combined.reduce((acc, item) => acc + item.sizeBytes, 0), - updatedAt: new Date().toLocaleTimeString() - }; - } - const fallbackItems = realItems.length > 0 || archiveItems.length > 0 ? [...realItems, ...archiveItems] : initial.items; - return { - backupVaultDir, - items: fallbackItems, - totalSizeBytes: fallbackItems.reduce((acc, item) => acc + item.sizeBytes, 0), - updatedAt: new Date().toLocaleTimeString() - }; - } - catch { - if (isRealHost) { - return { - backupVaultDir: "C:\\Users\\Default\\Documents\\ZToolsBackups", - items: [], - totalSizeBytes: 0, - updatedAt: new Date().toLocaleTimeString() - }; - } - return initial; - } -} -export async function createBackupArchive(items, profileMode, vaultDir, hostOverride) { - if (!vaultDir || FORBIDDEN_TARGET_PATTERN.test(vaultDir)) { - return { ok: false, archivePath: "", backedUpCount: 0, sizeBytes: 0, message: FORBIDDEN_REASON }; - } - if (!items || items.length === 0) { - return { - ok: false, - archivePath: "", - backedUpCount: 0, - sizeBytes: 0, - message: "请先勾选至少一项待备份配置" - }; - } - const stamp = new Date().toISOString().slice(0, 10).replace(/-/g, ""); - const archivePath = `${vaultDir.replace(/[\\/]+$/, "")}\\ZTools_Backup_${profileMode}_${stamp}.zip`; - const validPaths = items.map((i) => i.path).filter(Boolean); - const res = await invokeHostCapability("backup.createSnapshotArchive", { - profileMode, - vaultDir, - backupDir: vaultDir, - archivePath, - paths: validPaths, - sourcePaths: validPaths, - compression: "zstd" - }, hostOverride); - if (!res.ok) { - return { - ok: false, - archivePath: "", - backedUpCount: 0, - sizeBytes: 0, - message: res.error || res.message || "创建配置备份归档失败" - }; - } - const resolvedArchivePath = String(res.data?.archivePath ?? res.data?.backupPath ?? archivePath); - const realArchiveSize = Number(res.data?.sizeBytes ?? res.data?.size ?? 0) || - (await getRealFileSize(resolvedArchivePath, hostOverride)) || - items.reduce((s, i) => s + i.sizeBytes, 0); - return { - ok: true, - archivePath: resolvedArchivePath, - backedUpCount: items.length, - sizeBytes: realArchiveSize, - message: `已成功打包 ${items.length} 项关键配置并生成快照归档: ${resolvedArchivePath} (${formatBytes(realArchiveSize)})` - }; -} -export async function restoreBackupSnapshot(archivePath, targetDirOrHost, hostOverride) { - const trimmed = String(archivePath || "").trim(); - const targetDir = typeof targetDirOrHost === "string" ? targetDirOrHost.trim() : undefined; - const resolvedHost = typeof targetDirOrHost === "string" ? hostOverride : (hostOverride ?? targetDirOrHost); - if (!trimmed || FORBIDDEN_TARGET_PATTERN.test(trimmed)) { - return { ok: false, message: FORBIDDEN_REASON }; - } - if (targetDir && FORBIDDEN_TARGET_PATTERN.test(targetDir)) { - return { ok: false, message: FORBIDDEN_REASON }; - } - const res = await invokeHostCapability("backup.restoreSnapshotArchive", { - archivePath: trimmed, - backupPath: trimmed, - ...(targetDir ? { targetDir } : {}) - }, resolvedHost); - if (!res.ok) { - return { - ok: false, - message: res.error || res.message || `从归档快照 ${trimmed} 还原配置失败` - }; - } - return { - ok: true, - message: `已从归档快照 ${trimmed} 原子还原所选配置文件` - }; -} -export async function openBackupConfigLocation(targetPath, hostBridge) { - if (!targetPath || targetPath.startsWith("HKCU")) - return false; - const shown = await showRealItemInFolder(targetPath, hostBridge); - if (shown) - return true; - return openRealPath(targetPath, hostBridge); -} diff --git a/packages/declarative-ui/dist/examples/system/index.d.ts b/packages/declarative-ui/dist/examples/system/index.d.ts deleted file mode 100644 index e6b56b48..00000000 --- a/packages/declarative-ui/dist/examples/system/index.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -export * from "./system-actions.js"; -export default function SystemCommand(): JSX.Element; diff --git a/packages/declarative-ui/dist/examples/system/index.js b/packages/declarative-ui/dist/examples/system/index.js deleted file mode 100644 index 8c5cac32..00000000 --- a/packages/declarative-ui/dist/examples/system/index.js +++ /dev/null @@ -1,66 +0,0 @@ -import React from "../../index.js"; -import { List, ActionPanel, Action, Icon, Color } from "../../index.js"; -import { useState, useMemo } from "../../runtime/hooks.js"; -import { filterSystemActions, executeSystemAction } from "./system-actions.js"; -export * from "./system-actions.js"; -function getCategoryTitle(category) { - switch (category) { - case "power": return "电源与会话 (Power & Session)"; - case "apps": return "进程与桌面治理 (Apps & Windows)"; - case "audio": return "音频与硬件控制 (Audio & Hardware)"; - case "maintenance": return "系统维护与通知 (Maintenance)"; - case "desktop": return "桌面环境治理 (Desktop)"; - case "process": return "进程治理急救 (Process)"; - default: return "全部系统指令 (All Actions)"; - } -} -export default function SystemCommand() { - const [searchText, setSearchText] = useState(""); - const [category, setCategory] = useState("all"); - const [isShowingDetail, setIsShowingDetail] = useState(false); - const [selectedId, setSelectedId] = useState(null); - const filtered = useMemo(() => { - return filterSystemActions(searchText, category); - }, [searchText, category]); - const handleExecute = async (item, options) => { - await executeSystemAction(item, options); - }; - const groupedSections = useMemo(() => { - if (category !== "all") { - return [{ title: `${getCategoryTitle(category)} (${filtered.length})`, items: filtered }]; - } - const categories = ["power", "apps", "audio", "maintenance"]; - return categories - .map(cat => { - const items = filtered.filter(item => { - if (item.category === cat) - return true; - if (cat === "apps" && item.category === "desktop") - return true; - return false; - }); - return { - title: `${getCategoryTitle(cat)} (${items.length})`, - items - }; - }) - .filter(section => section.items.length > 0); - }, [filtered, category]); - return (React.createElement(List, { isShowingDetail: isShowingDetail, searchBarPlaceholder: "\u641C\u7D22 macOS / Windows \u7CFB\u7EDF\u63A7\u5236\u6307\u4EE4 (\u5982 \u6DF1\u8272\u6A21\u5F0F, \u9690\u85CF\u6587\u4EF6, \u9632\u4F11\u7720, \u9501\u5C4F, \u6E05\u7A7A\u56DE\u6536\u7AD9)...", onSearchTextChange: setSearchText, onSelectionChange: setSelectedId, filterBar: { - summaryText: `系统原生控制指令共 ${filtered.length} 项 · 当前视图: ${getCategoryTitle(category)} · 支持回车直接触发` - }, searchBarAccessory: React.createElement(List.Dropdown, { tooltip: "\u6309\u7C7B\u522B\u7B5B\u9009", value: category, onChange: setCategory }, - React.createElement(List.Dropdown.Item, { title: "\u5168\u90E8\u52A8\u4F5C (All Actions)", value: "all", icon: Icon.List }), - React.createElement(List.Dropdown.Item, { title: "\u7535\u6E90\u4E0E\u9632\u4F11\u7720 (Power & Session)", value: "power", icon: Icon.Power }), - React.createElement(List.Dropdown.Item, { title: "\u684C\u9762\u4E0E\u5916\u89C2\u6CBB\u7406 (Apps & Desktop)", value: "apps", icon: Icon.AppWindow }), - React.createElement(List.Dropdown.Item, { title: "\u97F3\u9891\u4E0E\u84DD\u7259\u63A7\u5236 (Audio & Hardware)", value: "audio", icon: Icon.Play }), - React.createElement(List.Dropdown.Item, { title: "\u7CFB\u7EDF\u7EF4\u62A4\u4E0E\u5E9F\u7EB8\u7BD3 (Maintenance)", value: "maintenance", icon: Icon.Gear })) }, groupedSections.map((section, idx) => (React.createElement(List.Section, { key: `section-${idx}`, title: section.title }, section.items.map(item => (React.createElement(List.Item, { key: item.id, id: item.id, title: item.title, subtitle: `${item.description} · ${item.subtitle}`, icon: item.icon, accessories: [ - ...(item.destructive ? [{ tag: { value: "高危操作", color: Color.Red } }] : []), - { tag: { value: item.category.toUpperCase() } }, - ...(item.shortcut ? [{ text: item.shortcut }] : []) - ], detail: React.createElement(List.Item.Detail, { markdown: `### ${item.title}\n\n${item.description}\n\n> **底层调用契约**: \`${item.subtitle}\`\n\n${item.technicalDetails ? `**技术实现细节**:\n${item.technicalDetails}\n\n` : ''}${item.destructive ? '**破坏性操作警告**:该操作会重置系统运行状态或导致正在运行的未保存数据丢失,执行前请务必确认关键工作已妥善存储。' : '**安全运维指令**:该操作执行平稳无损,可在任意工作阶段直接调度。'}` }), actions: React.createElement(ActionPanel, { title: `系统动作: ${item.title}` }, - React.createElement(Action, { title: `立即执行: ${item.title}`, icon: item.destructive ? Icon.ExclamationMark : Icon.Checkmark, onAction: () => handleExecute(item) }), - item.destructive && (React.createElement(Action, { title: "\u5F3A\u5236\u76F4\u63A5\u6267\u884C (\u8DF3\u8FC7\u4E8C\u6B21\u786E\u8BA4)", icon: Icon.ExclamationMark, shortcut: { modifiers: ["ctrl"], key: "return" }, onAction: () => handleExecute(item, { force: true, confirmBypass: true }) })), - React.createElement(Action.CopyToClipboard, { title: "\u590D\u5236\u5E95\u5C42\u8C03\u7528\u5951\u7EA6", content: item.actionKey, shortcut: { modifiers: ["ctrl"], key: "c" } }), - item.technicalDetails && (React.createElement(Action.CopyToClipboard, { title: "\u590D\u5236\u6280\u672F\u5B9E\u73B0\u7EC6\u8282", content: item.technicalDetails, shortcut: { modifiers: ["ctrl", "shift"], key: "c" } })), - React.createElement(Action, { title: isShowingDetail ? "关闭双栏详情" : "展开双栏详情", icon: Icon.SidebarRight, shortcut: { modifiers: ["ctrl"], key: "b" }, onAction: () => setIsShowingDetail(!isShowingDetail) })) })))))))); -} diff --git a/packages/declarative-ui/dist/examples/system/system-actions.d.ts b/packages/declarative-ui/dist/examples/system/system-actions.d.ts deleted file mode 100644 index 2b09b81a..00000000 --- a/packages/declarative-ui/dist/examples/system/system-actions.d.ts +++ /dev/null @@ -1,39 +0,0 @@ -/** - * Windows 原生运维动作集合 (System Actions Definition) - * 参考常见启动器的系统命令集自研实现 - * 包含电源与会话、进程与桌面治理、音频与硬件控制、维护与通知 4 大分类 20+ 项指令 - */ -import { Icon } from "../../constants/icons.js"; -export type SystemCategory = 'power' | 'apps' | 'audio' | 'maintenance' | 'desktop' | 'process'; -export interface SystemActionItem { - id: string; - actionKey: string; - title: string; - subtitle: string; - description: string; - category: SystemCategory; - icon: Icon | string; - destructive?: boolean; - shortcut?: string; - keywords?: string[]; - requiresConfirmation?: boolean; - confirmationMessage?: string; - technicalDetails?: string; -} -export declare const SYSTEM_ACTIONS: readonly SystemActionItem[]; -/** - * 智能过滤系统运维指令 - */ -export declare function filterSystemActions(query: string, category?: string): SystemActionItem[]; -/** - * 执行系统原生运维调度 - */ -export declare function executeSystemAction(itemOrId: SystemActionItem | string, options?: { - force?: boolean; - confirmBypass?: boolean; - hostOverride?: any; -}): Promise<{ - success: boolean; - executed: boolean; - message: string; -}>; diff --git a/packages/declarative-ui/dist/examples/system/system-actions.js b/packages/declarative-ui/dist/examples/system/system-actions.js deleted file mode 100644 index 023d8d31..00000000 --- a/packages/declarative-ui/dist/examples/system/system-actions.js +++ /dev/null @@ -1,530 +0,0 @@ -/** - * Windows 原生运维动作集合 (System Actions Definition) - * 参考常见启动器的系统命令集自研实现 - * 包含电源与会话、进程与桌面治理、音频与硬件控制、维护与通知 4 大分类 20+ 项指令 - */ -import { Icon } from "../../constants/icons.js"; -import { getDeclarativeBridge } from "../../api/bridge.js"; -import { showToast, Toast } from "../../api/toast.js"; -import { callHostTransport, isRealElectronHost } from "../shared/native-ipc.js"; -export const SYSTEM_ACTIONS = Object.freeze([ - // ========================================================================= - // 1. 电源与会话 (Power & Session) - // ========================================================================= - { - id: "lock-screen", - actionKey: "lockScreen", - title: "锁定屏幕 (Lock Screen)", - subtitle: "pmset displaysleepnow / user32.dll LockWorkStation", - description: "立即锁定当前计算机屏幕并要求身份重新验证", - category: "power", - icon: Icon.Lock, - shortcut: "Cmd+Ctrl+Q / Win+L", - keywords: ["lock", "lockscreen", "锁屏", "锁定", "安全锁屏"], - technicalDetails: "macOS 调用 CGSession / System Events 锁屏;Windows 调用 Win32 user32.dll!LockWorkStation 立即挂起交互式会话。" - }, - { - id: "sleep", - actionKey: "sleep", - title: "睡眠待机 (Sleep)", - subtitle: "pmset sleepnow / powrprof.dll SetSuspendState(0,0,0)", - description: "使计算机转入内存保留低功耗睡眠待机状态", - category: "power", - icon: Icon.Power, - keywords: ["sleep", "suspend", "待机", "睡眠", "低功耗"], - technicalDetails: "macOS 执行 pmset sleepnow;Windows 调用 powrprof.dll!SetSuspendState(FALSE, FALSE, FALSE) 进入挂起状态。" - }, - { - id: "sleep-displays", - actionKey: "sleepDisplays", - title: "立即关闭显示器 (Sleep Displays)", - subtitle: "pmset displaysleepnow / SC_MONITORPOWER 2", - description: "不进入整机睡眠,立即熄灭并关闭所有连接的显示器屏幕", - category: "power", - icon: Icon.Monitor, - keywords: ["sleep displays", "display sleep", "screen off", "关闭显示器", "熄屏", "关屏幕"], - technicalDetails: "macOS 调用 pmset displaysleepnow 立即熄屏;Windows 下发 WM_SYSCOMMAND SC_MONITORPOWER 2。" - }, - { - id: "toggle-caffeinate", - actionKey: "toggleCaffeinate", - title: "开启 / 关闭防休眠咖啡因模式 (Prevent System from Sleeping / Caffeinate)", - subtitle: "/usr/bin/caffeinate -di / SetThreadExecutionState", - description: "阻止 Mac 或 Windows 自动进入睡眠或熄屏状态,适合长耗时编译、下载与演示", - category: "power", - icon: Icon.Bolt, - keywords: ["caffeinate", "keep awake", "prevent sleep", "coffee", "防休眠", "咖啡因", "保持唤醒", "常亮"], - technicalDetails: "macOS 后台托管 /usr/bin/caffeinate -di 守护进程;Windows 设置 ES_CONTINUOUS | ES_SYSTEM_REQUIRED | ES_DISPLAY_REQUIRED。" - }, - { - id: "restart", - actionKey: "restart", - title: "重新启动 (Restart)", - subtitle: "System Events restart / shutdown.exe /r /t 0", - description: "安全关闭全部应用程序并立即重新启动操作系统", - category: "power", - icon: Icon.RotateClockwise, - destructive: true, - requiresConfirmation: true, - confirmationMessage: "确认立即重新启动计算机?未保存的工作可能会丢失。", - keywords: ["restart", "reboot", "重启", "重启电脑", "重开机"], - technicalDetails: "macOS 通过 System Events 发送 restart 事件;Windows 执行 shutdown.exe /r /t 0。" - }, - { - id: "shut-down", - actionKey: "shutDown", - title: "关闭计算机 (Shut Down)", - subtitle: "System Events shut down / shutdown.exe /s /t 0", - description: "安全终结全部运行进程并切断计算机主电源", - category: "power", - icon: Icon.Power, - destructive: true, - requiresConfirmation: true, - confirmationMessage: "确认立即关闭计算机电源?请确保重要数据已全部保存。", - keywords: ["shutdown", "power off", "关机", "断电", "关机电脑"], - technicalDetails: "macOS 通过 System Events 发送 shut down 事件;Windows 执行 shutdown.exe /s /t 0。" - }, - { - id: "log-out", - actionKey: "logOut", - title: "注销用户会话 (Log Out)", - subtitle: "System Events log out / shutdown.exe /l", - description: "退出当前已登录的系统用户桌面会话", - category: "power", - icon: Icon.Circle, - destructive: true, - requiresConfirmation: true, - confirmationMessage: "确认注销当前用户会话?", - keywords: ["logout", "sign out", "注销", "登出", "注销登录"], - technicalDetails: "macOS 通过 System Events log out;Windows 执行 shutdown.exe /l 或 ExitWindowsEx(EWX_LOGOFF)。" - }, - { - id: "hibernate", - actionKey: "hibernate", - title: "深度休眠 (Hibernate)", - subtitle: "powrprof.dll SetSuspendState(1,0,0)", - description: "将内存数据完整转储至磁盘并彻底切断电源", - category: "power", - icon: Icon.Power, - keywords: ["hibernate", "休眠", "深度休眠", "hiberfil"], - technicalDetails: "调用 powrprof.dll!SetSuspendState(TRUE, FALSE, FALSE) 进入 S4 休眠。" - }, - // ========================================================================= - // 2. 进程与桌面治理 (Apps, Desktop & Appearance) - // ========================================================================= - { - id: "toggle-appearance", - actionKey: "toggleAppearance", - title: "切换深色 / 浅色模式 (Toggle System Appearance)", - subtitle: "System Events dark mode / AppsUseLightTheme", - description: "一键在系统深色模式 (Dark Mode) 与浅色模式 (Light Mode) 之间瞬时切换", - category: "desktop", - icon: Icon.Eye, - keywords: ["appearance", "dark mode", "light mode", "theme", "深色模式", "浅色模式", "暗黑模式", "切换主题", "外观"], - technicalDetails: "macOS 执行 tell application \"System Events\" to tell appearance preferences to set dark mode to not dark mode;Windows 切换 Personalize 注册表项。" - }, - { - id: "toggle-hidden-files", - actionKey: "toggleHiddenFiles", - title: "切换显示隐藏文件 (Toggle Hidden Files in Finder / Explorer)", - subtitle: "defaults write com.apple.finder AppleShowAllFiles / Explorer Hidden", - description: "在 macOS Finder 或 Windows Explorer 中一键显示或隐藏以点开头的隐藏文件与系统目录", - category: "desktop", - icon: Icon.Folder, - shortcut: "Cmd+Shift+.", - keywords: ["hidden files", "dotfiles", "show hidden", "finder", "隐藏文件", "显示隐藏文件", "点文件"], - technicalDetails: "macOS 切换 com.apple.finder AppleShowAllFiles 并重启 Finder;Windows 切换 HKCU Explorer Advanced Hidden 键值。" - }, - { - id: "toggle-desktop-icons", - actionKey: "toggleDesktopIcons", - title: "显示 / 隐藏桌面图标 (Toggle Desktop Icons)", - subtitle: "defaults write com.apple.finder CreateDesktop / HideIcons", - description: "一键隐藏或恢复桌面上的所有文件与快捷方式图标,适合录屏、演示与极简壁纸控", - category: "desktop", - icon: Icon.Desktop, - keywords: ["desktop icons", "hide desktop", "clean desktop", "桌面图标", "隐藏桌面图标", "显示桌面图标", "纯净桌面"], - technicalDetails: "macOS 切换 com.apple.finder CreateDesktop 并刷新 Finder;Windows 切换 Explorer Advanced HideIcons。" - }, - { - id: "hide-all-apps-except-frontmost", - actionKey: "hideAllAppsExceptFrontmost", - title: "隐藏除前台外所有应用 (Hide All Apps Except Frontmost)", - subtitle: "System Events visible=false / Win32 ShowWindow(SW_MINIMIZE)", - description: "保持当前最前台聚焦应用可见,将其余所有后台窗口一键隐藏或最小化", - category: "apps", - icon: Icon.EyeSlash, - shortcut: "Cmd+Opt+H", - keywords: ["hide all apps", "isolate", "focus", "专注模式", "隐藏后台", "最小化其他"], - technicalDetails: "macOS 将非 frontmost 进程设置 visible=false;Windows 遍历顶层 HWND 对非前台主窗口下发 SW_MINIMIZE。" - }, - { - id: "quit-all-applications", - actionKey: "quitAllApplications", - title: "退出所有运行应用 (Quit All Apps)", - subtitle: "System Events quit / WM_CLOSE broadcast", - description: "向当前会话中所有运行的应用窗口发送安全退出指令(自动排除 Finder 与 ZTools)", - category: "apps", - icon: Icon.XmarkCircle, - destructive: true, - requiresConfirmation: true, - confirmationMessage: "确认退出当前会话中的所有应用程序?", - keywords: ["quit all apps", "close all", "退出全部", "关闭所有应用"], - technicalDetails: "向用户层活动应用进程平缓发送 quit 事件或广播 WM_CLOSE 消息请求正常退出。" - }, - { - id: "quit-all-applications-except-frontmost", - actionKey: "quitAllApplicationsExceptFrontmost", - title: "退出除前台外所有应用 (Quit All Apps Except Frontmost)", - subtitle: "Quit background apps / WM_CLOSE to background processes", - description: "仅保留当前处于前台焦点的窗口,退出其余全部后台运行程序", - category: "apps", - icon: Icon.XmarkCircle, - destructive: true, - requiresConfirmation: true, - confirmationMessage: "确认退出除前台窗口外的所有后台应用?", - keywords: ["quit background apps", "退出后台应用", "清理后台进程"], - technicalDetails: "排查当前前台进程,向其余后台用户进程投递退出消息。" - }, - { - id: "quit-active-application", - actionKey: "quitActiveApplication", - title: "终结当前前台应用 (Quit Active App)", - subtitle: "Cmd+Q / Alt+F4 / WM_CLOSE", - description: "立即向当前处于最前台焦点的应用程序窗口发送退出指令", - category: "apps", - icon: Icon.XmarkCircle, - destructive: true, - keywords: ["quit active app", "alt+f4", "cmd+q", "close active", "关闭当前应用", "强退"], - technicalDetails: "获取当前最前台应用进程并向其投递退出指令。" - }, - { - id: "show-desktop", - actionKey: "showDesktop", - title: "显示物理桌面 (Show Desktop)", - subtitle: "Mission Control Show Desktop / Shell.Application ToggleDesktop", - description: "推开或最小化屏幕上全部活动窗口并瞬间切换至纯净物理桌面", - category: "desktop", - icon: Icon.Desktop, - shortcut: "F11 / Win+D", - keywords: ["desktop", "show desktop", "win+d", "桌面", "显示桌面", "最小化所有"], - technicalDetails: "macOS 触发 Show Desktop (CoreDock / key code 103);Windows 调用 IShellDispatch4::ToggleDesktop()。" - }, - // ========================================================================= - // 3. 音频与硬件控制 (Audio & Hardware) - // ========================================================================= - { - id: "toggle-mute-current-app", - actionKey: "toggleMuteCurrentApp", - title: "切换前台应用静音 (Toggle Active App Mute)", - subtitle: "ISimpleAudioVolume::SetMute", - description: "一键静音或恢复当前获得焦点的前台程序的音频流", - category: "audio", - icon: Icon.Play, - keywords: ["mute current app", "mute active app", "静音当前应用", "单个应用静音"], - technicalDetails: "定位前台窗口 PID 并通过音频会话控制切换 SetMute。" - }, - { - id: "turn-current-app-volume-up", - actionKey: "turnCurrentAppVolumeUp", - title: "提高前台应用音量 (Turn Active App Volume Up)", - subtitle: "WASAPI App Session +10%", - description: "按 10% 步长增加当前最前台活动应用的独立输出音量", - category: "audio", - icon: Icon.Plus, - keywords: ["active app volume up", "前台音量加", "调大当前程序音量"], - technicalDetails: "读取前台应用的音频会话音量并递增 10% (上限 100%)。" - }, - { - id: "turn-current-app-volume-down", - actionKey: "turnCurrentAppVolumeDown", - title: "降低前台应用音量 (Turn Active App Volume Down)", - subtitle: "WASAPI App Session -10%", - description: "按 10% 步长调小当前最前台活动应用的独立输出音量", - category: "audio", - icon: Icon.Minus, - keywords: ["active app volume down", "前台音量减", "调小当前程序音量"], - technicalDetails: "读取前台应用的音频会话音量并递减 10% (下限 0%)。" - }, - { - id: "volume-mixer", - actionKey: "volumeMixer", - title: "系统音量混音器 (Volume Mixer)", - subtitle: "Sound Settings / sndvol.exe", - description: "调出系统级音频混合器或声音偏好设置面板以独立精细调音", - category: "audio", - icon: Icon.Gear, - keywords: ["volume mixer", "audio mixer", "sndvol", "音量合成器", "混音器", "声音设置"], - technicalDetails: "macOS 打开系统声音设置面板;Windows 启动内置 sndvol.exe 混音控制台。" - }, - { - id: "toggle-mute", - actionKey: "toggleMute", - title: "系统主声道静音切换 (Toggle Mute)", - subtitle: "osascript set volume output muted / VK_VOLUME_MUTE", - description: "一键静音或恢复计算机主声卡默认输出端点", - category: "audio", - icon: Icon.Stop, - keywords: ["mute", "unmute", "主音量静音", "静音", "恢复声音"], - technicalDetails: "macOS 执行 set volume output muted not (output muted of (get volume settings));Windows 触发 IAudioEndpointVolume::SetMute。" - }, - { - id: "volume-up", - actionKey: "turnVolumeUp", - title: "调高音量 (+10%) / 提高系统主音量 (Turn Volume Up)", - subtitle: "osascript output volume +10% / VK_VOLUME_UP", - description: "按 10% 步长调高计算机全局扬声器输出主音量", - category: "audio", - icon: Icon.ArrowUp, - keywords: ["volume up", "调高音量", "系统音量加", "调大音量", "大声", "+10%"], - technicalDetails: "macOS 通过 osascript 读取当前音量并 +10%;Windows 触发系统全局音量递增事件。" - }, - { - id: "volume-down", - actionKey: "turnVolumeDown", - title: "调低音量 (-10%) / 降低系统主音量 (Turn Volume Down)", - subtitle: "osascript output volume -10% / VK_VOLUME_DOWN", - description: "按 10% 步长调低计算机全局扬声器输出主音量", - category: "audio", - icon: Icon.ArrowDown, - keywords: ["volume down", "调低音量", "系统音量减", "调小音量", "小声", "-10%"], - technicalDetails: "macOS 通过 osascript 读取当前音量并 -10%;Windows 触发系统全局音量递减事件。" - }, - { - id: "toggle-bluetooth", - actionKey: "toggleBluetooth", - title: "打开蓝牙设置 / 切换蓝牙 (Toggle Bluetooth)", - subtitle: "Bluetooth Settings / blueutil / ms-settings:bluetooth", - description: "快速切换系统蓝牙开关状态或直达系统蓝牙设备管理面板", - category: "audio", - icon: Icon.Wifi, - keywords: ["bluetooth", "toggle bluetooth", "airpods", "蓝牙", "切换蓝牙", "蓝牙设置", "打开蓝牙"], - technicalDetails: "macOS 调用 blueutil 或打开 x-apple.systempreferences:com.apple.BluetoothSettings;Windows 打开 ms-settings:bluetooth。" - }, - { - id: "turn-display-off", - actionKey: "turnDisplayOff", - title: "关闭显示器电源 (Turn Display Off / Sleep Displays)", - subtitle: "pmset displaysleepnow / SC_MONITORPOWER 2", - description: "下发节能信号使全部连接的物理显示器立即关闭熄屏", - category: "audio", - icon: Icon.Monitor, - keywords: ["sleep displays", "screen off", "display off", "熄屏", "关屏幕", "显示器休眠"], - technicalDetails: "macOS 执行 pmset displaysleepnow;Windows 广播 SendMessage(HWND_BROADCAST, WM_SYSCOMMAND, SC_MONITORPOWER, 2)。" - }, - { - id: "eject-all-disks", - actionKey: "ejectAllDisks", - title: "安全弹出所有磁盘 (Eject All Disks)", - subtitle: "Finder eject every disk / FSCTL_LOCK_VOLUME", - description: "卸载并安全弹出当前挂载的全部外接移动磁盘、U盘与 DMG 磁盘映像", - category: "audio", - icon: Icon.HardDrive, - destructive: true, - requiresConfirmation: true, - confirmationMessage: "确认安全卸载并弹出全部已挂载的移动磁盘?", - keywords: ["eject disks", "unmount", "弹出U盘", "安全删除硬件", "弹出所有磁盘", "推出磁盘"], - technicalDetails: "macOS 调用 Finder eject (every disk whose ejectable is true);Windows 发送 FSCTL_DISMOUNT_VOLUME 与 IOCTL_STORAGE_EJECT_MEDIA。" - }, - // ========================================================================= - // 4. 维护与通知 (Maintenance) - // ========================================================================= - { - id: "empty-trash", - actionKey: "emptyTrash", - title: "清空废纸篓 / 回收站 (Empty Trash / Empty Recycle Bin)", - subtitle: "Finder empty trash / SHEmptyRecycleBinW", - description: "永久清除 macOS 废纸篓或 Windows 回收站中的全部废弃文件并立即释放磁盘物理空间", - category: "maintenance", - icon: Icon.Trash, - destructive: true, - requiresConfirmation: true, - confirmationMessage: "确认永久清空废纸篓/回收站?清除后文件将无法直接还原。", - keywords: ["empty recycle bin", "empty trash", "clean trash", "清空回收站", "清空废纸篓", "清理垃圾桶", "清除临时文件"], - technicalDetails: "macOS 执行 tell application \"Finder\" to empty trash;Windows 调用 Shell32!SHEmptyRecycleBinW。" - }, - { - id: "open-trash", - actionKey: "openTrash", - title: "打开废纸篓 / 回收站 (Open Trash / Recycle Bin)", - subtitle: "open ~/.Trash / explorer.exe shell:RecycleBinFolder", - description: "在 Finder 或文件资源管理器中打开废纸篓/回收站视图以查看待清理文件", - category: "maintenance", - icon: Icon.Folder, - keywords: ["open recycle bin", "open trash", "打开回收站", "打开废纸篓", "查看回收站"], - technicalDetails: "macOS 打开 ~/.Trash 目录;Windows 通过 ShellExecute 启动 shell:RecycleBinFolder。" - }, - { - id: "dismiss-notifications", - actionKey: "dismissNotifications", - title: "清除所有系统通知 (Dismiss Notifications)", - subtitle: "NotificationCenter Dismiss / ActionCenter Dismiss", - description: "立即关闭屏幕上当前浮现的所有通知横幅与通知中心待办提醒", - category: "maintenance", - icon: Icon.Checkmark, - keywords: ["dismiss notifications", "clear alerts", "清除通知", "关闭提醒", "清空横幅"], - technicalDetails: "清理 macOS NotificationCenter 或 Windows ActionCenter 弹窗。" - } -]); -/** - * 智能过滤系统运维指令 - */ -export function filterSystemActions(query, category) { - let list = [...SYSTEM_ACTIONS]; - if (category && category !== "all") { - const c = category.toLowerCase(); - list = list.filter(item => { - if (item.category === c) - return true; - // 兼容历史分类映射 - if (c === "desktop" && (item.category === "apps" || item.category === "maintenance")) - return true; - if (c === "apps" && item.category === "desktop") - return true; - if (c === "process" && item.category === "apps") - return true; - return false; - }); - } - if (!query || !query.trim()) - return list; - const q = query.trim().toLowerCase(); - return list.filter(item => { - if (item.title.toLowerCase().includes(q)) - return true; - if (item.subtitle.toLowerCase().includes(q)) - return true; - if (item.description.toLowerCase().includes(q)) - return true; - if (item.actionKey.toLowerCase().includes(q)) - return true; - if (item.id.toLowerCase().includes(q)) - return true; - if (item.keywords?.some(k => k.toLowerCase().includes(q))) - return true; - return false; - }); -} -/** - * 执行系统原生运维调度 - */ -export async function executeSystemAction(itemOrId, options = {}) { - const item = typeof itemOrId === "string" - ? SYSTEM_ACTIONS.find(a => a.id === itemOrId || a.actionKey === itemOrId) - : itemOrId; - if (!item || typeof item !== "object" || (!item.id && !item.actionKey)) { - return { - success: false, - executed: false, - message: `未知或无效的系统指令: ${String(itemOrId || "")}` - }; - } - const bridge = getDeclarativeBridge(); - // 高危破坏性动作拦截确认 - if (item.destructive && !options.confirmBypass && !options.force) { - if (bridge?.confirmAlert) { - const confirmed = await bridge.confirmAlert({ - title: `系统高危操作: ${item.title}`, - message: item.confirmationMessage ?? `确定要执行 ${item.title} 吗?此操作具有不可逆影响。`, - primaryAction: { - title: "确认执行", - style: "destructive" - }, - dismissAction: { - title: "取消" - } - }); - if (!confirmed) { - await showToast(Toast.Style.Animated, "已取消操作", `未执行: ${item.title}`); - return { success: false, executed: false, message: "用户已取消执行" }; - } - } - } - // 1. 尝试通过 Bridge 调度 - try { - if (bridge?.system?.execute) { - const res = await bridge.system.execute(item.actionKey, options); - if (res && typeof res === "object" && (res.ok === false || res.success === false)) { - const errMsg = String(res.error || res.message || "执行失败"); - await showToast(Toast.Style.Failure, `调度失败: ${item.title}`, errMsg); - return { success: false, executed: false, message: errMsg }; - } - await showToast(Toast.Style.Success, `系统调度成功: ${item.title}`, item.technicalDetails); - return { success: true, executed: true, message: res?.message ?? "执行完成" }; - } - } - catch (err) { - await showToast(Toast.Style.Failure, `调度异常: ${item.title}`, err?.message); - return { success: false, executed: false, message: err?.message ?? "执行失败" }; - } - // 2. 优先调用宿主真实 IPC system_execute_action 及 SystemActionsPlugin - if (options.hostOverride || isRealElectronHost(options.hostOverride)) { - const ipcRes = await callHostTransport("system_execute_action", { - actionKey: item.actionKey, - action: item.id, - id: item.id, - params: options - }, options.hostOverride); - if (ipcRes.ok && ipcRes.data?.ok !== false && ipcRes.data?.success !== false) { - const msg = ipcRes.data?.message || `已执行系统操作: ${item.title}`; - await showToast(Toast.Style.Success, msg, item.technicalDetails); - return { success: true, executed: true, message: msg }; - } - const dllRes = await callHostTransport("dllplugin_call", { - plugin: "SystemActionsPlugin", - func: item.actionKey || item.id, - params: { id: item.id, actionKey: item.actionKey, ...options } - }, options.hostOverride); - if (dllRes.ok && dllRes.data?.ok !== false && dllRes.data?.success !== false) { - const msg = dllRes.data?.message || `已执行系统操作: ${item.title}`; - await showToast(Toast.Style.Success, msg, item.technicalDetails); - return { success: true, executed: true, message: msg }; - } - if (item.id === "lock-screen" || item.actionKey === "lockScreen") { - const lockRes = await callHostTransport("system_lock", {}, options.hostOverride); - if (lockRes.ok) { - await showToast(Toast.Style.Success, `已锁定屏幕: ${item.title}`); - return { success: true, executed: true, message: "屏幕已锁定" }; - } - } - else if (item.id === "sleep" || item.actionKey === "sleep") { - const sleepRes = await callHostTransport("system_sleep", {}, options.hostOverride); - if (sleepRes.ok) { - await showToast(Toast.Style.Success, `已进入睡眠状态: ${item.title}`); - return { success: true, executed: true, message: "系统已进入睡眠" }; - } - } - const errMsg = ipcRes.error || - dllRes.error || - String(ipcRes.data?.error || ipcRes.data?.message || `系统指令执行失败: ${item.title}`); - await showToast(Toast.Style.Failure, `系统操作失败: ${item.title}`, errMsg); - return { success: false, executed: false, message: errMsg }; - } - // 3. 尝试通过 window.ztools 宿主调度 - const ztools = globalThis.window?.ztools ?? globalThis.ztools; - if (typeof ztools?.systemAction === 'function') { - try { - await ztools.systemAction(item.actionKey, options); - await showToast(Toast.Style.Success, `已触发系统操作: ${item.title}`, item.technicalDetails); - return { success: true, executed: true, message: "原生服务已响应" }; - } - catch (err) { - await showToast(Toast.Style.Failure, `执行失败: ${item.title}`, err?.message); - return { success: false, executed: false, message: err?.message ?? "宿主执行错误" }; - } - } - if (typeof ztools?.system?.power === 'function' && item.category === 'power') { - try { - await ztools.system.power(item.actionKey, options); - await showToast(Toast.Style.Success, `电源指令已分发: ${item.title}`); - return { success: true, executed: true, message: "电源指令已发送" }; - } - catch (err) { - await showToast(Toast.Style.Failure, `电源调度失败`, err?.message); - return { success: false, executed: false, message: err?.message ?? "电源调度失败" }; - } - } - // 4. 仅在无真实宿主的纯离线环境下返回预览结果 - await showToast(item.destructive ? Toast.Style.Animated : Toast.Style.Success, `系统动作: ${item.title}`, item.technicalDetails ?? item.description); - return { success: true, executed: true, message: `已成功调度: ${item.title}` }; -} diff --git a/packages/declarative-ui/dist/examples/table-converter/index.d.ts b/packages/declarative-ui/dist/examples/table-converter/index.d.ts deleted file mode 100644 index 277382ac..00000000 --- a/packages/declarative-ui/dist/examples/table-converter/index.d.ts +++ /dev/null @@ -1,10 +0,0 @@ -export * from './types.js'; -export * from './table-service.js'; -export interface TableConverterCommandProps { - featureCode?: string; - initialRawText?: string; - initialHeaderMode?: 'first-row-header' | 'no-header'; - initialSqlTableName?: string; -} -export declare function TableConverterCommand(props?: TableConverterCommandProps): JSX.Element; -export default TableConverterCommand; diff --git a/packages/declarative-ui/dist/examples/table-converter/index.js b/packages/declarative-ui/dist/examples/table-converter/index.js deleted file mode 100644 index 321cbde5..00000000 --- a/packages/declarative-ui/dist/examples/table-converter/index.js +++ /dev/null @@ -1,78 +0,0 @@ -import React, { Action, ActionPanel, Clipboard, Icon, List, Toast, showToast, useEffect, useMemo, useState } from '../../index.js'; -import { buildAllConversionTargets, detectAndParse } from './table-service.js'; -export * from './types.js'; -export * from './table-service.js'; -const DEFAULT_SAMPLE_TSV = [ - '服务模块\tQPS峰值\tP99延迟(ms)\t核心状态', - 'ztools-indexer\t48500\t1.8\ttrue', - 'declarative-reconciler\t19200\t3.2\ttrue', - 'host-ipc-bridge\t12800\t2.4\ttrue' -].join('\n'); -export function TableConverterCommand(props = {}) { - const [rawText, setRawText] = useState(props.initialRawText ?? DEFAULT_SAMPLE_TSV); - const [headerMode, setHeaderMode] = useState(props.initialHeaderMode ?? 'first-row-header'); - const [sqlTableName] = useState(props.initialSqlTableName ?? 'my_table'); - const [searchText, setSearchText] = useState(''); - const [isConverting, setIsConverting] = useState(false); - const handleReadClipboard = async () => { - setIsConverting(true); - try { - const clipText = await Clipboard.readText(); - if (clipText && clipText.trim()) { - setRawText(clipText); - await showToast({ - style: Toast.Style.Success, - title: '已从剪贴板读取表格数据' - }); - } - } - catch { - // Keep current text if clipboard is empty or unavailable - } - finally { - setIsConverting(false); - } - }; - useEffect(() => { - if (props.initialRawText === undefined) { - void handleReadClipboard(); - } - }, [props.featureCode]); - const parsed = useMemo(() => detectAndParse(rawText, headerMode === 'first-row-header'), [rawText, headerMode]); - const conversionTargets = useMemo(() => { - const targets = buildAllConversionTargets(parsed.grid, sqlTableName); - const q = searchText.trim().toLowerCase(); - if (!q) - return targets; - return targets.filter((t) => t.title.toLowerCase().includes(q) || - t.subtitle.toLowerCase().includes(q) || - t.id.toLowerCase().includes(q)); - }, [parsed.grid, sqlTableName, searchText]); - const rowCount = parsed.grid.rows.length; - const colCount = parsed.grid.headers.length; - return (React.createElement(List, { navigationTitle: "\u8868\u683C\u4E92\u8F6C", isLoading: isConverting, isShowingDetail: true, searchText: searchText, onSearchTextChange: setSearchText, searchBarPlaceholder: "\u5207\u6362\u76EE\u6807\u8F6C\u6362\u683C\u5F0F\uFF08Markdown / JSON / SQL / HTML / CSV\uFF09...", searchBarAccessory: React.createElement(List.Dropdown, { value: headerMode, onChange: (val) => setHeaderMode(val), tooltip: "\u8868\u5934\u8BC6\u522B\u6A21\u5F0F" }, - React.createElement(List.Dropdown.Item, { title: "\u7B2C\u4E00\u884C\u4E3A\u5217\u6807\u9898\uFF08\u9996\u884C\u8868\u5934\uFF09", value: "first-row-header", icon: Icon.List }), - React.createElement(List.Dropdown.Item, { title: "\u7EAF\u6570\u636E\u65E0\u8868\u5934\uFF08\u81EA\u52A8\u5206\u914D col_1, col_2...\uFF09", value: "no-header", icon: Icon.Code })), filterBar: { - summaryText: parsed.format === 'empty' - ? '等待输入或从剪贴板粘贴表格数据' - : `识别源格式: ${parsed.format.toUpperCase()} · 共 ${rowCount} 行 × ${colCount} 列`, - actions: [ - { - id: 'read-clipboard', - title: '读取剪贴板', - onAction: () => { - void handleReadClipboard(); - } - } - ] - } }, conversionTargets.map((target) => (React.createElement(List.Item, { key: target.id, id: target.id, title: target.title, subtitle: target.subtitle, icon: target.id === 'markdown' ? Icon.Document : Icon.Code, accessories: [{ tag: target.badge }], detail: React.createElement(List.Item.Detail, { markdown: `\`\`\`${target.language}\n${target.previewText}\n\`\`\``, metadata: React.createElement(List.Item.Detail.Metadata, null, - React.createElement(List.Item.Detail.Metadata.Label, { title: "\u8F93\u51FA\u683C\u5F0F", text: target.title }), - React.createElement(List.Item.Detail.Metadata.Label, { title: "\u884C\u6570 / \u5217\u6570", text: `${rowCount} 行 × ${colCount} 列` }), - React.createElement(List.Item.Detail.Metadata.Label, { title: "\u8F93\u51FA\u5B57\u7B26\u6570", text: `${target.fullText.length} 字符` }), - React.createElement(List.Item.Detail.Metadata.Separator, null), - React.createElement(List.Item.Detail.Metadata.Label, { title: "\u63A8\u65AD\u5217\u7C7B\u578B", text: target.typeSummary })) }), actions: React.createElement(ActionPanel, null, - React.createElement(Action.CopyToClipboard, { title: "\u590D\u5236\u8F6C\u6362\u7ED3\u679C", content: target.fullText, icon: Icon.Clipboard }), - React.createElement(Action.Paste, { title: "\u76F4\u63A5\u4E0A\u5C4F\u7C98\u8D34", content: target.fullText, icon: Icon.Text, shortcut: { modifiers: ['cmd'], key: 'enter' } }), - React.createElement(Action, { title: "\u91CD\u65B0\u8BFB\u53D6\u526A\u8D34\u677F", icon: Icon.ArrowClockwise, shortcut: { modifiers: ['cmd'], key: 'r' }, onAction: handleReadClipboard })) }))))); -} -export default TableConverterCommand; diff --git a/packages/declarative-ui/dist/examples/table-converter/table-service.d.ts b/packages/declarative-ui/dist/examples/table-converter/table-service.d.ts deleted file mode 100644 index 67d244a7..00000000 --- a/packages/declarative-ui/dist/examples/table-converter/table-service.d.ts +++ /dev/null @@ -1,15 +0,0 @@ -import type { DetectedSourceFormat, TableConversionTarget, TableGrid } from './types.js'; -/** - * 符合 RFC 4180 规范的分隔符解析器(支持双引号包裹、内部含分隔符或真实换行 `\n`、双引号转义 `""`) - */ -export declare function parseDelimitedRows(rawText: string, delimiter: string): string[][]; -export declare function detectAndParse(rawText: string, hasHeader?: boolean): { - format: DetectedSourceFormat; - grid: TableGrid; -}; -export declare function gridToMarkdown(grid: TableGrid): string; -export declare function gridToJson(grid: TableGrid): string; -export declare function gridToSql(grid: TableGrid, tableName?: string): string; -export declare function gridToHtml(grid: TableGrid): string; -export declare function gridToCsv(grid: TableGrid): string; -export declare function buildAllConversionTargets(grid: TableGrid, sqlTableName?: string): TableConversionTarget[]; diff --git a/packages/declarative-ui/dist/examples/table-converter/table-service.js b/packages/declarative-ui/dist/examples/table-converter/table-service.js deleted file mode 100644 index 48b96bb5..00000000 --- a/packages/declarative-ui/dist/examples/table-converter/table-service.js +++ /dev/null @@ -1,351 +0,0 @@ -/** - * 符合 RFC 4180 规范的分隔符解析器(支持双引号包裹、内部含分隔符或真实换行 `\n`、双引号转义 `""`) - */ -export function parseDelimitedRows(rawText, delimiter) { - const rows = []; - let currentRow = []; - let currentCell = ''; - let inQuotes = false; - const text = String(rawText ?? '').replace(/\r\n/g, '\n'); - for (let i = 0; i < text.length; i++) { - const ch = text[i]; - const next = text[i + 1]; - if (inQuotes) { - if (ch === '"' && next === '"') { - currentCell += '"'; - i++; - } - else if (ch === '"') { - inQuotes = false; - } - else { - currentCell += ch; - } - continue; - } - if (ch === '"') { - inQuotes = true; - } - else if (ch === delimiter) { - currentRow.push(currentCell); - currentCell = ''; - } - else if (ch === '\n') { - currentRow.push(currentCell); - rows.push(currentRow); - currentRow = []; - currentCell = ''; - } - else { - currentCell += ch; - } - } - if (currentCell.length > 0 || currentRow.length > 0) { - currentRow.push(currentCell); - rows.push(currentRow); - } - return rows.filter((r) => !(r.length === 1 && r[0]?.trim() === '')); -} -function inferColumnTypes(headers, rows) { - return headers.map((_, colIdx) => { - const values = rows.map((r) => (r[colIdx] ?? '').trim()).filter((v) => v !== ''); - if (values.length === 0) - return 'null'; - if (values.every((v) => /^-?\d+(\.\d+)?$/.test(v))) - return 'number'; - if (values.every((v) => /^(true|false)$/i.test(v))) - return 'boolean'; - return 'string'; - }); -} -function normalizeMatrixToGrid(rawRows, hasHeader) { - if (rawRows.length === 0) { - return { headers: [], rows: [], inferredTypes: [] }; - } - const colCount = Math.max(...rawRows.map((r) => r.length), 1); - const paddedRows = rawRows.map((r) => { - const copy = [...r]; - while (copy.length < colCount) { - copy.push(''); - } - return copy; - }); - const headers = hasHeader - ? paddedRows[0].map((h, i) => h.trim() || `col_${i + 1}`) - : Array.from({ length: colCount }, (_, i) => `col_${i + 1}`); - const dataRows = hasHeader ? paddedRows.slice(1) : paddedRows; - return { - headers, - rows: dataRows, - inferredTypes: inferColumnTypes(headers, dataRows) - }; -} -export function detectAndParse(rawText, hasHeader = true) { - const trimmed = String(rawText ?? '').trim(); - if (!trimmed) { - return { - format: 'empty', - grid: { headers: [], rows: [], inferredTypes: [] } - }; - } - // 1. JSON Array - if (trimmed.startsWith('[')) { - try { - const parsed = JSON.parse(trimmed); - if (Array.isArray(parsed) && parsed.length > 0) { - if (Array.isArray(parsed[0])) { - const matrix = parsed.map((r) => r.map((c) => String(c ?? ''))); - return { format: 'json', grid: normalizeMatrixToGrid(matrix, hasHeader) }; - } - if (typeof parsed[0] === 'object' && parsed[0] !== null) { - const keySet = new Set(); - for (const item of parsed) { - if (item && typeof item === 'object') { - for (const k of Object.keys(item)) - keySet.add(k); - } - } - const headers = Array.from(keySet); - const rows = parsed.map((item) => { - const obj = (item || {}); - return headers.map((h) => (obj[h] === undefined || obj[h] === null ? '' : String(obj[h]))); - }); - return { - format: 'json', - grid: { - headers, - rows, - inferredTypes: inferColumnTypes(headers, rows) - } - }; - } - } - } - catch { - // Not valid JSON, continue - } - } - // 2. Markdown Table - const lines = trimmed.replace(/\r\n/g, '\n').split('\n'); - if (lines.length >= 2 && lines[0].trim().startsWith('|') && lines[0].trim().endsWith('|')) { - const mdRows = []; - for (const line of lines) { - const t = line.trim(); - if (!t.startsWith('|')) - continue; - const inner = t.replace(/^\|/, '').replace(/\|$/, ''); - const cells = inner.split(/(? c.replace(/\\\|/g, '|').trim()); - const isSep = cells.every((c) => /^:?-{2,}:?$/.test(c)); - if (!isSep) { - mdRows.push(cells); - } - } - if (mdRows.length > 0) { - return { format: 'markdown', grid: normalizeMatrixToGrid(mdRows, hasHeader) }; - } - } - // 3. HTML - if (/]/i.test(trimmed) && /]/i.test(trimmed)) { - const trMatches = trimmed.match(//gi) ?? []; - const htmlRows = []; - for (const tr of trMatches) { - const cellMatches = tr.match(/]*>([\s\S]*?)<\/t[hd]>/gi) ?? []; - if (cellMatches.length > 0) { - htmlRows.push(cellMatches.map((cell) => cell - .replace(/<[^>]+>/g, '') - .replace(/ /g, ' ') - .replace(/&/g, '&') - .trim())); - } - } - if (htmlRows.length > 0) { - return { format: 'html', grid: normalizeMatrixToGrid(htmlRows, hasHeader) }; - } - } - // 4. TSV vs CSV - const firstLine = lines[0] ?? ''; - const tabCount = (firstLine.match(/\t/g) ?? []).length; - if (tabCount > 0) { - const tsvRows = parseDelimitedRows(trimmed, '\t'); - return { format: 'tsv', grid: normalizeMatrixToGrid(tsvRows, hasHeader) }; - } - const csvRows = parseDelimitedRows(trimmed, ','); - return { format: 'csv', grid: normalizeMatrixToGrid(csvRows, hasHeader) }; -} -function sanitizeMarkdownCell(val) { - return String(val ?? '') - .replace(/\r\n/g, '\n') - .replace(/\n/g, '
') - .replace(/\|/g, '\\|') - .trim(); -} -export function gridToMarkdown(grid) { - if (grid.headers.length === 0) - return ''; - const escapedHeaders = grid.headers.map(sanitizeMarkdownCell); - const escapedRows = grid.rows.map((row) => grid.headers.map((_, cIdx) => sanitizeMarkdownCell(row[cIdx] ?? ''))); - const colWidths = escapedHeaders.map((h, cIdx) => { - const maxCell = Math.max(h.length, ...escapedRows.map((r) => (r[cIdx] ?? '').length), 3); - return maxCell; - }); - const formatRow = (cells) => '| ' + - cells.map((c, idx) => c.padEnd(colWidths[idx], ' ')).join(' | ') + - ' |'; - const sepRow = '| ' + - colWidths - .map((w, idx) => grid.inferredTypes[idx] === 'number' ? '-'.repeat(w - 1) + ':' : '-'.repeat(w)) - .join(' | ') + - ' |'; - return [formatRow(escapedHeaders), sepRow, ...escapedRows.map(formatRow)].join('\n'); -} -export function gridToJson(grid) { - if (grid.headers.length === 0) - return '[]'; - const objects = grid.rows.map((row) => { - const item = {}; - grid.headers.forEach((h, idx) => { - const raw = (row[idx] ?? '').trim(); - const colType = grid.inferredTypes[idx]; - if (raw === '') { - item[h] = null; - } - else if (colType === 'number' && /^-?\d+(\.\d+)?$/.test(raw)) { - item[h] = Number(raw); - } - else if (colType === 'boolean' && /^(true|false)$/i.test(raw)) { - item[h] = raw.toLowerCase() === 'true'; - } - else { - item[h] = row[idx] ?? ''; - } - }); - return item; - }); - return JSON.stringify(objects, null, 2); -} -export function gridToSql(grid, tableName = 'my_table') { - if (grid.headers.length === 0 || grid.rows.length === 0) - return ''; - const safeTable = tableName.replace(/[^a-zA-Z0-9_]/g, '_') || 'my_table'; - const colList = grid.headers - .map((h) => `\`${h.replace(/`/g, '')}\``) - .join(', '); - const valueTuples = grid.rows.map((row) => { - const vals = grid.headers.map((_, idx) => { - const raw = row[idx] ?? ''; - const trimmed = raw.trim(); - const colType = grid.inferredTypes[idx]; - if (trimmed === '') - return 'NULL'; - if (colType === 'number' && /^-?\d+(\.\d+)?$/.test(trimmed)) - return trimmed; - if (colType === 'boolean' && /^(true|false)$/i.test(trimmed)) { - return trimmed.toLowerCase() === 'true' ? 'TRUE' : 'FALSE'; - } - const escaped = raw.replace(/'/g, "''").replace(/\r\n/g, '\n'); - return `'${escaped}'`; - }); - return ` (${vals.join(', ')})`; - }); - return `INSERT INTO ${safeTable} (${colList})\nVALUES\n${valueTuples.join(',\n')};`; -} -function escapeHtml(str) { - return String(str ?? '') - .replace(/&/g, '&') - .replace(//g, '>') - .replace(/"/g, '"'); -} -export function gridToHtml(grid) { - if (grid.headers.length === 0) - return ''; - const thead = `
\n ${grid.headers.map((h) => ``).join('')}\n `; - const tbodyRows = grid.rows - .map((r) => ` ${grid.headers.map((_, idx) => ``).join('')}`) - .join('\n'); - return `
${escapeHtml(h)}
${escapeHtml(r[idx] ?? '')}
\n${thead}\n \n${tbodyRows}\n \n
`; -} -export function gridToCsv(grid) { - if (grid.headers.length === 0) - return ''; - const encodeCsvCell = (val) => { - const s = String(val ?? ''); - if (s.includes(',') || s.includes('"') || s.includes('\n')) { - return `"${s.replace(/"/g, '""')}"`; - } - return s; - }; - const lines = [ - grid.headers.map(encodeCsvCell).join(','), - ...grid.rows.map((r) => grid.headers.map((_, i) => encodeCsvCell(r[i] ?? '')).join(',')) - ]; - return lines.join('\n'); -} -export function buildAllConversionTargets(grid, sqlTableName = 'my_table') { - const typeSummary = grid.headers - .map((h, i) => `${h}: ${grid.inferredTypes[i]}`) - .join(' · '); - const mdFull = gridToMarkdown(grid); - const jsonFull = gridToJson(grid); - const sqlFull = gridToSql(grid, sqlTableName); - const htmlFull = gridToHtml(grid); - const csvFull = gridToCsv(grid); - const slicePreview = (text) => { - const lines = text.split('\n'); - if (lines.length <= 100) - return text; - return lines.slice(0, 100).join('\n') + `\n... (已截断预览,共 ${lines.length} 行)`; - }; - return [ - { - id: 'markdown', - title: 'Markdown 对齐表格', - subtitle: '自动计算等宽空格对齐 · 数值列右对齐 · 管道符与换行安全转义', - badge: '推荐文档格式', - language: 'markdown', - fullText: mdFull, - previewText: slicePreview(mdFull), - typeSummary - }, - { - id: 'json', - title: 'JSON 结构化对象数组', - subtitle: '首行自动映射为 Key · 智能推导 number / boolean / null 类型', - badge: 'API / 研发', - language: 'json', - fullText: jsonFull, - previewText: slicePreview(jsonFull), - typeSummary - }, - { - id: 'sql', - title: `SQL 批量 INSERT 语句 (${sqlTableName})`, - subtitle: '单引号自动防注入双写转义 · 空值映射 NULL', - badge: '数据库导入', - language: 'sql', - fullText: sqlFull, - previewText: slicePreview(sqlFull), - typeSummary - }, - { - id: 'html', - title: 'HTML 语义化结构', - subtitle: '标准 thead / tbody 标签封装', - badge: '网页内嵌', - language: 'html', - fullText: htmlFull, - previewText: slicePreview(htmlFull), - typeSummary - }, - { - id: 'csv', - title: 'RFC 4180 标准 CSV', - subtitle: '自动包裹含逗号或换行的复杂单元格', - badge: '通用交换', - language: 'csv', - fullText: csvFull, - previewText: slicePreview(csvFull), - typeSummary - } - ]; -} diff --git a/packages/declarative-ui/dist/examples/table-converter/types.d.ts b/packages/declarative-ui/dist/examples/table-converter/types.d.ts deleted file mode 100644 index d069612e..00000000 --- a/packages/declarative-ui/dist/examples/table-converter/types.d.ts +++ /dev/null @@ -1,17 +0,0 @@ -export type InferredColumnType = 'number' | 'boolean' | 'string' | 'null'; -export type DetectedSourceFormat = 'tsv' | 'csv' | 'json' | 'markdown' | 'html' | 'empty'; -export interface TableGrid { - headers: string[]; - rows: string[][]; - inferredTypes: InferredColumnType[]; -} -export interface TableConversionTarget { - id: 'markdown' | 'json' | 'sql' | 'html' | 'csv'; - title: string; - subtitle: string; - badge: string; - language: string; - fullText: string; - previewText: string; - typeSummary: string; -} diff --git a/packages/declarative-ui/dist/examples/table-converter/types.js b/packages/declarative-ui/dist/examples/table-converter/types.js deleted file mode 100644 index cb0ff5c3..00000000 --- a/packages/declarative-ui/dist/examples/table-converter/types.js +++ /dev/null @@ -1 +0,0 @@ -export {}; diff --git a/packages/declarative-ui/dist/examples/translator/engine.d.ts b/packages/declarative-ui/dist/examples/translator/engine.d.ts deleted file mode 100644 index 66a41ffd..00000000 --- a/packages/declarative-ui/dist/examples/translator/engine.d.ts +++ /dev/null @@ -1,54 +0,0 @@ -/** - * 极速离线与多语言翻译引擎 - * 对标 Raycast Translator 交互逻辑与反向对照规范 - */ -export interface ReverseTranslationItem { - readonly term: string; - readonly pos?: string; - readonly meaning: string; - readonly alternates?: readonly string[]; -} -export interface TranslationResult { - readonly sourceText: string; - readonly translatedText: string; - readonly sourceLanguage: string; - readonly targetLanguage: string; - readonly detectedLanguage: { - code: string; - label: string; - confidence: number; - }; - readonly phonetic?: string; - readonly reverseTranslations?: readonly ReverseTranslationItem[]; -} -export interface RecentTranslationRecord { - readonly id: string; - readonly sourceText: string; - readonly translatedText: string; - readonly sourceLang: string; - readonly targetLang: string; - readonly timestamp: number; -} -export declare function translateText(text: string, sourceLang?: string, targetLang?: string, hostOverride?: unknown): Promise; -/** - * 双向语言切换 (Swap Languages) - * 对标 Raycast: 如果源语言是 auto,则将目标语言对调为探测语言,源语言设为旧目标语言 - */ -export declare function swapLanguages(sourceLang: string, targetLang: string, detectedSourceLang?: string): { - newSource: string; - newTarget: string; -}; -/** - * 历史翻译记录读取与持久化 - */ -export declare function getRecentTranslations(): Promise; -export declare function saveRecentTranslation(sourceText: string, translatedText: string, sourceLang: string, targetLang: string): Promise; -export declare function clearRecentTranslations(): Promise; -/** - * 外部 Web 翻译器跳转 URL 生成器 - */ -export declare function getWebTranslatorUrls(text: string, sourceLang: string, targetLang: string): { - deepL: string; - googleTranslate: string; - baidu: string; -}; diff --git a/packages/declarative-ui/dist/examples/translator/engine.js b/packages/declarative-ui/dist/examples/translator/engine.js deleted file mode 100644 index fdf5a7ee..00000000 --- a/packages/declarative-ui/dist/examples/translator/engine.js +++ /dev/null @@ -1,243 +0,0 @@ -/** - * 极速离线与多语言翻译引擎 - * 对标 Raycast Translator 交互逻辑与反向对照规范 - */ -import { LocalStorage } from "../../api/storage.js"; -import { callHostTransport, isRealElectronHost } from "../shared/native-ipc.js"; -import { detectLanguage, getLanguageByCode } from "./languages.js"; -const RECENT_TRANSLATIONS_KEY = "ztools_translator_recents_v1"; -const MAX_RECENTS = 50; -/** - * 丰富的高频与科技互译词库 - */ -const DICT_TRANSLATIONS = { - // 英译中 / 多语 - "hello": { - "zh-Hans": { translated: "你好", phonetic: "nǐ hǎo", reverse: [{ term: "你好", pos: "int.", meaning: "hello; hi; how do you do", alternates: ["您好", "哈喽"] }] }, - "ja": { translated: "こんにちは", phonetic: "konnichiwa", reverse: [{ term: "こんにちは", pos: "int.", meaning: "hello; good afternoon" }] }, - "ko": { translated: "안녕하세요", phonetic: "annyeonghaseyo" }, - "fr": { translated: "Bonjour", phonetic: "/bɔ̃.ʒuʁ/" }, - "de": { translated: "Hallo", phonetic: "/ˈhaloː/" }, - "es": { translated: "Hola", phonetic: "/ˈo.la/" }, - "ru": { translated: "Здравствуйте", phonetic: "Zdravstvuyte" } - }, - "world": { - "zh-Hans": { translated: "世界", phonetic: "shì jiè", reverse: [{ term: "世界", pos: "n.", meaning: "world; earth; universe", alternates: ["天下", "世间"] }] }, - "ja": { translated: "世界", phonetic: "sekai" }, - "fr": { translated: "monde" }, - "de": { translated: "Welt" }, - "es": { translated: "mundo" } - }, - "hello world": { - "zh-Hans": { translated: "你好,世界", phonetic: "nǐ hǎo, shì jiè" }, - "ja": { translated: "こんにちは、世界" }, - "fr": { translated: "Bonjour le monde" }, - "de": { translated: "Hallo Welt" } - }, - "settings": { - "zh-Hans": { translated: "设置", phonetic: "shè zhì", reverse: [{ term: "设置", pos: "n./v.", meaning: "settings; preferences; setup; configuration", alternates: ["首选项", "偏好设置"] }] }, - "ja": { translated: "設定", phonetic: "settei" }, - "fr": { translated: "Paramètres" }, - "de": { translated: "Einstellungen" } - }, - "clipboard": { - "zh-Hans": { translated: "剪贴板", phonetic: "jiǎn tiē bǎn", reverse: [{ term: "剪贴板", pos: "n.", meaning: "clipboard; pasteboard", alternates: ["复制板"] }] }, - "ja": { translated: "クリップボード", phonetic: "kurippubōdo" } - }, - "architecture": { - "zh-Hans": { translated: "架构", phonetic: "jià gòu", reverse: [{ term: "架构", pos: "n.", meaning: "architecture; structural framework", alternates: ["体系结构", "体系"] }] } - }, - "algorithm": { - "zh-Hans": { translated: "算法", phonetic: "suàn fǎ", reverse: [{ term: "算法", pos: "n.", meaning: "algorithm; method of computation" }] } - }, - "resilience": { - "zh-Hans": { translated: "弹性与抗毁性", phonetic: "tán xìng yǔ kàng huǐ xìng", reverse: [{ term: "抗毁性", pos: "n.", meaning: "resilience; robustness; fault tolerance" }] } - }, - "sidecar": { - "zh-Hans": { translated: "边车与伴生进程", phonetic: "biān chē yǔ bàn shēng jìn chéng", reverse: [{ term: "伴生侧车", pos: "n.", meaning: "sidecar process" }] } - }, - // 中译英 - "你好": { - "en": { translated: "Hello", phonetic: "/həˈloʊ/", reverse: [{ term: "Hello", pos: "int.", meaning: "你好;喂;您好", alternates: ["Hi", "Greetings"] }] }, - "ja": { translated: "こんにちは" }, - "ko": { translated: "안녕하세요" } - }, - "世界": { - "en": { translated: "World", phonetic: "/wɜːrld/", reverse: [{ term: "World", pos: "n.", meaning: "世界;地球;领域", alternates: ["Earth", "Globe"] }] } - }, - "设置": { - "en": { translated: "Settings", phonetic: "/ˈsetɪŋz/", reverse: [{ term: "Settings", pos: "n.", meaning: "设置;偏好设置;配置", alternates: ["Preferences", "Configuration"] }] } - }, - "剪贴板": { - "en": { translated: "Clipboard", phonetic: "/ˈklɪpbɔːrd/", reverse: [{ term: "Clipboard", pos: "n.", meaning: "剪贴板;带夹写字板", alternates: ["Pasteboard"] }] } - }, - "架构": { - "en": { translated: "Architecture", phonetic: "/ˈɑːrkɪtektʃər/", reverse: [{ term: "Architecture", pos: "n.", meaning: "架构;建筑学;体系结构", alternates: ["Framework", "Structure"] }] } - }, - "算法": { - "en": { translated: "Algorithm", phonetic: "/ˈælɡərɪðəm/", reverse: [{ term: "Algorithm", pos: "n.", meaning: "算法;解题程序", alternates: ["Procedure", "Computation"] }] } - }, - "抗毁性": { - "en": { translated: "Resilience", phonetic: "/rɪˈzɪliəns/", reverse: [{ term: "Resilience", pos: "n.", meaning: "抗毁性;弹性;韧性", alternates: ["Robustness", "Fault-tolerance"] }] } - }, - "侧车": { - "en": { translated: "Sidecar", phonetic: "/ˈsaɪdkɑːr/", reverse: [{ term: "Sidecar", pos: "n.", meaning: "侧车;边车架构模式" }] } - } -}; -/** - * 执行多语言极速翻译(在真实 Electron 宿主中优先走 translator_translate IPC) - */ -let translationRecordSeq = 0; -export async function translateText(text, sourceLang = "auto", targetLang = "en", hostOverride) { - const trimmed = text.trim(); - if (!trimmed) { - return { - sourceText: "", - translatedText: "", - sourceLanguage: sourceLang, - targetLanguage: targetLang, - detectedLanguage: { code: "en", label: "English", confidence: 0 } - }; - } - // 1. 语言探测 - const detected = detectLanguage(trimmed); - const effectiveSource = sourceLang === "auto" ? detected.code : sourceLang; - // 2. 目标语言自动调整:如果源语言和目标语言一致,且源为中文,则目标自动变为英文,反之亦然 - let effectiveTarget = targetLang; - if (effectiveSource === effectiveTarget) { - effectiveTarget = effectiveSource === "zh-Hans" ? "en" : "zh-Hans"; - } - // 3. 在真实 Electron 宿主或提供 hostOverride 时优先调用主进程 translator_translate IPC - if (hostOverride || isRealElectronHost(hostOverride)) { - const ipcRes = await callHostTransport("translator_translate", { - text: trimmed, - sourceLanguage: sourceLang, - targetLanguage: effectiveTarget - }, hostOverride); - if (ipcRes.ok && ipcRes.data) { - const payload = ipcRes.data; - const translatedStr = String(payload.translatedText ?? payload.translation ?? payload.text ?? "").trim(); - if (translatedStr) { - return { - sourceText: text, - translatedText: translatedStr, - sourceLanguage: String(payload.sourceLanguage || effectiveSource), - targetLanguage: String(payload.targetLanguage || effectiveTarget), - detectedLanguage: payload.detectedLanguage || detected, - phonetic: typeof payload.phonetic === "string" ? payload.phonetic : undefined, - reverseTranslations: Array.isArray(payload.reverseTranslations) - ? payload.reverseTranslations - : undefined - }; - } - } - } - // 4. 查表匹配(忽略大小写) - const lower = trimmed.toLowerCase(); - const dictMatch = DICT_TRANSLATIONS[lower] || DICT_TRANSLATIONS[trimmed]; - if (dictMatch && dictMatch[effectiveTarget]) { - const entry = dictMatch[effectiveTarget]; - return { - sourceText: text, - translatedText: entry.translated, - sourceLanguage: effectiveSource, - targetLanguage: effectiveTarget, - detectedLanguage: detected, - phonetic: entry.phonetic, - reverseTranslations: entry.reverse - }; - } - // 5. 通用离线本地翻译回退 - let translatedText = ""; - let phonetic; - let reverse; - if (effectiveTarget === "zh-Hans") { - translatedText = `[译] ${text}`; - } - else if (effectiveTarget === "en") { - translatedText = `[Translated] ${text}`; - } - else { - const targetDef = getLanguageByCode(effectiveTarget); - translatedText = `[${targetDef.nativeName}] ${text}`; - } - return { - sourceText: text, - translatedText, - sourceLanguage: effectiveSource, - targetLanguage: effectiveTarget, - detectedLanguage: detected, - phonetic, - reverseTranslations: reverse - }; -} -/** - * 双向语言切换 (Swap Languages) - * 对标 Raycast: 如果源语言是 auto,则将目标语言对调为探测语言,源语言设为旧目标语言 - */ -export function swapLanguages(sourceLang, targetLang, detectedSourceLang = "zh-Hans") { - if (sourceLang === "auto") { - // 切换后:原目标变为源,原探测源变为新目标 - return { - newSource: targetLang, - newTarget: detectedSourceLang - }; - } - return { - newSource: targetLang, - newTarget: sourceLang - }; -} -/** - * 历史翻译记录读取与持久化 - */ -export async function getRecentTranslations() { - try { - const raw = await LocalStorage.getItem(RECENT_TRANSLATIONS_KEY); - if (!raw || typeof raw !== "string") - return []; - const parsed = JSON.parse(raw); - if (!Array.isArray(parsed)) - return []; - return parsed.filter(item => item && typeof item.sourceText === "string" && typeof item.translatedText === "string"); - } - catch (e) { - console.warn("[translator] getRecentTranslations failed:", e); - return []; - } -} -export async function saveRecentTranslation(sourceText, translatedText, sourceLang, targetLang) { - const cleanSource = sourceText.trim(); - const cleanTrans = translatedText.trim(); - if (!cleanSource || !cleanTrans) - return await getRecentTranslations(); - const current = await getRecentTranslations(); - const filtered = current.filter(r => r.sourceText !== cleanSource || r.targetLang !== targetLang); - const newRecord = { - id: `${Date.now()}-${++translationRecordSeq}`, - sourceText: cleanSource, - translatedText: cleanTrans, - sourceLang, - targetLang, - timestamp: Date.now() - }; - const updated = [newRecord, ...filtered].slice(0, MAX_RECENTS); - await LocalStorage.setItem(RECENT_TRANSLATIONS_KEY, JSON.stringify(updated)); - return updated; -} -export async function clearRecentTranslations() { - await LocalStorage.removeItem(RECENT_TRANSLATIONS_KEY); -} -/** - * 外部 Web 翻译器跳转 URL 生成器 - */ -export function getWebTranslatorUrls(text, sourceLang, targetLang) { - const enc = encodeURIComponent(text.trim()); - const s = sourceLang === "auto" ? "auto" : sourceLang; - const t = targetLang; - return { - deepL: `https://www.deepl.com/translator#${s}/${t}/${enc}`, - googleTranslate: `https://translate.google.com/?sl=${s}&tl=${t}&text=${enc}&op=translate`, - baidu: `https://fanyi.baidu.com/#${s === "auto" ? "auto" : s}/${t}/${enc}` - }; -} diff --git a/packages/declarative-ui/dist/examples/translator/index.d.ts b/packages/declarative-ui/dist/examples/translator/index.d.ts deleted file mode 100644 index 580cfd3a..00000000 --- a/packages/declarative-ui/dist/examples/translator/index.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -export * from "./languages.js"; -export * from "./engine.js"; -/** - * 多语言即时翻译主入口 - * 输入即译,支持自动识别源语言、语言对调与反向对照 - */ -export default function TranslatorCommand(): JSX.Element; diff --git a/packages/declarative-ui/dist/examples/translator/index.js b/packages/declarative-ui/dist/examples/translator/index.js deleted file mode 100644 index 78a71374..00000000 --- a/packages/declarative-ui/dist/examples/translator/index.js +++ /dev/null @@ -1,168 +0,0 @@ -import React from "../../index.js"; -import { List, ActionPanel, Action, Icon, showToast, Toast, Clipboard } from "../../index.js"; -import { useState, useMemo, useEffect } from "../../runtime/hooks.js"; -import { SUPPORTED_LANGUAGES, getLanguageByCode } from "./languages.js"; -import { translateText, swapLanguages, getRecentTranslations, saveRecentTranslation, clearRecentTranslations, getWebTranslatorUrls } from "./engine.js"; -export * from "./languages.js"; -export * from "./engine.js"; -/** - * 多语言即时翻译主入口 - * 输入即译,支持自动识别源语言、语言对调与反向对照 - */ -export default function TranslatorCommand() { - const [inputText, setInputText] = useState(""); - const [sourceLang, setSourceLang] = useState("auto"); - const [targetLang, setTargetLang] = useState("zh-Hans"); - const [translation, setTranslation] = useState(null); - const [recents, setRecents] = useState([]); - const [isLoading, setIsLoading] = useState(false); - // 初始化加载历史记录与选中文本 - useEffect(() => { - let mounted = true; - (async () => { - try { - const history = await getRecentTranslations(); - if (mounted) - setRecents(history); - } - catch (e) { - console.warn("[translator] load recent translations failed:", e); - } - })(); - return () => { mounted = false; }; - }, []); - // 响应输入变化执行翻译 - useEffect(() => { - let mounted = true; - const clean = inputText.trim(); - if (!clean) { - setTranslation(null); - return; - } - setIsLoading(true); - const timer = setTimeout(async () => { - try { - const res = await translateText(clean, sourceLang, targetLang); - if (mounted) { - setTranslation(res); - setIsLoading(false); - // 异步计入历史 - const updated = await saveRecentTranslation(clean, res.translatedText, res.sourceLanguage, res.targetLanguage); - if (mounted) - setRecents(updated); - } - } - catch (err) { - if (mounted) - setIsLoading(false); - } - }, 200); - return () => { - mounted = false; - clearTimeout(timer); - }; - }, [inputText, sourceLang, targetLang]); - // 语言对调 (Swap Languages) - const handleSwap = () => { - const detectedCode = translation?.detectedLanguage.code || "zh-Hans"; - const swapped = swapLanguages(sourceLang, targetLang, detectedCode); - setSourceLang(swapped.newSource); - setTargetLang(swapped.newTarget); - showToast(Toast.Style.Success, "已对调语言", `${swapped.newSource} ⇄ ${swapped.newTarget}`); - }; - const handleCopyTranslated = async (text) => { - if (!text) - return; - await Clipboard.copy(text); - await showToast(Toast.Style.Success, "已复制译文", text); - }; - const handlePasteTranslated = async (text) => { - if (!text) - return; - await Clipboard.paste(text); - await showToast(Toast.Style.Success, "已粘贴译文到活动窗口", text); - }; - const handleCopySource = async (text) => { - if (!text) - return; - await Clipboard.copy(text); - await showToast(Toast.Style.Success, "已复制原文", text); - }; - const handleSpeak = async (text, langCode) => { - if (!text) - return; - const { callHostTransport, isRealElectronHost } = await import("../shared/native-ipc.js"); - if (isRealElectronHost()) { - await callHostTransport("dictionary_speak", { word: text, lang: langCode }); - } - const langDef = getLanguageByCode(langCode); - await showToast(Toast.Style.Success, `朗读 (${langDef.nativeName})`, text); - }; - const handleClearHistory = async () => { - await clearRecentTranslations(); - setRecents([]); - await showToast(Toast.Style.Success, "翻译历史已清空"); - }; - const sourceLangDef = getLanguageByCode(sourceLang); - const targetLangDef = getLanguageByCode(targetLang); - const webUrls = inputText ? getWebTranslatorUrls(inputText, sourceLang, targetLang) : null; - // 构建翻译结果卡片的 Markdown - const detailMarkdown = useMemo(() => { - if (!translation || !inputText) { - return `### 极速多语言翻译中枢\n\n` + - `- **支持语言**: 中、英、日、韩、法、德、西、俄 等 30+ 常用语言\n` + - `- **极客特性**: 语言自动探测、双向热键对调 (\`Ctrl+S\`)、拼音/音标高保真注音、反向词条对照\n` + - `- **快速操作**: 回车粘贴到当前焦点窗口,或按 \`Ctrl+C\` 复制译文\n\n` + - `> 请在上方搜索框输入待翻译的内容开始体验。`; - } - const lines = [ - `# ${translation.translatedText}`, - translation.phonetic ? `*注音 / 音标:* \`${translation.phonetic}\`\n` : ``, - `---`, - `### 原文对照`, - `> ${translation.sourceText}`, - `**源语种**: \`${translation.detectedLanguage.label}\` (置信度: ${Math.round(translation.detectedLanguage.confidence * 100)}%)   |   **目标语种**: \`${targetLangDef.nativeName}\`\n` - ]; - if (translation.reverseTranslations && translation.reverseTranslations.length > 0) { - lines.push(`### 反向词条对照 (Reverse Translations)`); - translation.reverseTranslations.forEach(r => { - lines.push(`- **${r.term}** ${r.pos ? `\`${r.pos}\`` : ""} : ${r.meaning}`); - if (r.alternates && r.alternates.length > 0) { - lines.push(` *近义对照:* ` + r.alternates.map(a => `\`${a}\``).join(" • ")); - } - }); - } - return lines.filter(Boolean).join("\n\n"); - }, [translation, inputText, targetLangDef]); - return (React.createElement(List, { isLoading: isLoading, isShowingDetail: true, searchBarPlaceholder: `输入待翻译内容... (当前目标: ${targetLangDef.flag} ${targetLangDef.nativeName})`, onSearchTextChange: setInputText, searchBarAccessory: React.createElement(List.Dropdown, { tooltip: "\u9009\u62E9\u76EE\u6807\u8BED\u8A00", value: targetLang, onChange: (val) => setTargetLang(val) }, SUPPORTED_LANGUAGES.filter(l => l.code !== "auto").map(lang => (React.createElement(List.Dropdown.Item, { key: lang.code, value: lang.code, title: `${lang.flag} ${lang.nativeName} (${lang.label})` })))) }, - translation && inputText ? (React.createElement(List.Section, { title: "\u5B9E\u65F6\u7FFB\u8BD1\u7ED3\u679C (Live Translation)" }, - React.createElement(List.Item, { key: "current-translation", id: "current-translation", title: translation.translatedText, subtitle: `原文: ${translation.sourceText}`, icon: Icon.Globe, accessories: [ - { text: `${translation.detectedLanguage.code} → ${translation.targetLanguage}` }, - { icon: Icon.Checkmark } - ], detail: React.createElement(List.Item.Detail, { markdown: detailMarkdown, metadata: React.createElement(List.Item.Detail.Metadata, null, - React.createElement(List.Item.Detail.Metadata.Label, { title: "\u6E90\u8BED\u79CD", text: translation.detectedLanguage.label, icon: Icon.Globe }), - React.createElement(List.Item.Detail.Metadata.Label, { title: "\u76EE\u6807\u8BED\u79CD", text: targetLangDef.nativeName, icon: Icon.Text }), - translation.phonetic && (React.createElement(List.Item.Detail.Metadata.Label, { title: "\u6CE8\u97F3/\u97F3\u6807", text: translation.phonetic })), - React.createElement(List.Item.Detail.Metadata.Separator, null), - React.createElement(List.Item.Detail.Metadata.Label, { title: "\u63A2\u6D4B\u72B6\u6001", text: "\u5DF2\u81EA\u52A8\u8BC6\u522B", icon: Icon.Check })) }), actions: React.createElement(ActionPanel, null, - React.createElement(ActionPanel.Section, { title: "\u9996\u8981\u64CD\u4F5C" }, - React.createElement(Action, { title: "\u7C98\u8D34\u8BD1\u6587\u5230\u6D3B\u52A8\u7A97\u53E3 (\u56DE\u8F66\u9ED8\u8BA4)", icon: Icon.Clipboard, onAction: () => handlePasteTranslated(translation.translatedText) }), - React.createElement(Action, { title: "\u590D\u5236\u8BD1\u6587", icon: Icon.CopyClipboard, shortcut: { modifiers: ["ctrl"], key: "c" }, onAction: () => handleCopyTranslated(translation.translatedText) }), - React.createElement(Action, { title: "\u590D\u5236\u539F\u6587", icon: Icon.Text, shortcut: { modifiers: ["ctrl", "shift"], key: "c" }, onAction: () => handleCopySource(translation.sourceText) })), - React.createElement(ActionPanel.Section, { title: "\u7FFB\u8BD1\u63A7\u5236" }, - React.createElement(Action, { title: "\u5BF9\u8C03\u6E90\u4E0E\u76EE\u6807\u8BED\u8A00 (Swap)", icon: Icon.Repeat, shortcut: { modifiers: ["ctrl"], key: "s" }, onAction: handleSwap }), - React.createElement(Action, { title: "\u6717\u8BFB\u8BD1\u6587", icon: Icon.Play, shortcut: { modifiers: ["ctrl"], key: "p" }, onAction: () => handleSpeak(translation.translatedText, translation.targetLanguage) }), - React.createElement(Action, { title: "\u6717\u8BFB\u539F\u6587", icon: Icon.Play, onAction: () => handleSpeak(translation.sourceText, translation.sourceLanguage) })), - webUrls && (React.createElement(ActionPanel.Section, { title: "\u5916\u90E8\u7FFB\u8BD1\u5E73\u53F0" }, - React.createElement(Action.OpenInBrowser, { title: "\u5728 DeepL \u4E2D\u6253\u5F00", url: webUrls.deepL }), - React.createElement(Action.OpenInBrowser, { title: "\u5728 Google Translate \u4E2D\u6253\u5F00", url: webUrls.googleTranslate }), - React.createElement(Action.OpenInBrowser, { title: "\u5728 \u767E\u5EA6\u7FFB\u8BD1 \u4E2D\u6253\u5F00", url: webUrls.baidu })))) }))) : (React.createElement(List.Section, { title: "\u7B49\u5F85\u8F93\u5165\u5F85\u7FFB\u8BD1\u6587\u672C" }, - React.createElement(List.Item, { title: "\u7B49\u5F85\u8F93\u5165...", subtitle: "\u8F93\u5165\u82F1\u6587\u3001\u4E2D\u6587\u3001\u65E5\u6587\u3001\u97E9\u6587\u6216\u6B27\u6D32\u8BED\u8A00\u5373\u65F6\u5448\u73B0\u8BD1\u6587", icon: Icon.Text, detail: React.createElement(List.Item.Detail, { markdown: detailMarkdown }) }))), - recents.length > 0 && (React.createElement(List.Section, { title: `近期翻译历史 (${recents.length})` }, recents.map(r => (React.createElement(List.Item, { key: r.id, id: r.id, title: r.translatedText, subtitle: `原文: ${r.sourceText} (${r.sourceLang} → ${r.targetLang})`, icon: Icon.Clock, actions: React.createElement(ActionPanel, null, - React.createElement(Action, { title: "\u590D\u5236\u8BD1\u6587", icon: Icon.Clipboard, onAction: () => handleCopyTranslated(r.translatedText) }), - React.createElement(Action, { title: "\u91CD\u65B0\u8F7D\u5165\u67E5\u8BE2", icon: Icon.MagnifyingGlass, onAction: () => { - setInputText(r.sourceText); - setTargetLang(r.targetLang); - } }), - React.createElement(Action, { title: "\u6E05\u7A7A\u7FFB\u8BD1\u5386\u53F2", icon: Icon.Trash, shortcut: { modifiers: ["ctrl", "shift"], key: "delete" }, onAction: handleClearHistory })) }))))))); -} diff --git a/packages/declarative-ui/dist/examples/translator/languages.d.ts b/packages/declarative-ui/dist/examples/translator/languages.d.ts deleted file mode 100644 index eb7f4f3f..00000000 --- a/packages/declarative-ui/dist/examples/translator/languages.d.ts +++ /dev/null @@ -1,21 +0,0 @@ -/** - * 多语言语言定义与自动检测引擎 - * 对标 Raycast Translator 官方支持语言规范 - */ -export interface LanguageDefinition { - readonly code: string; - readonly label: string; - readonly nativeName: string; - readonly flag: string; - readonly phoneticsType?: "pinyin" | "ipa" | "romaji" | "hangul"; -} -export declare const SUPPORTED_LANGUAGES: readonly LanguageDefinition[]; -export declare function getLanguageByCode(code: string): LanguageDefinition; -/** - * 智能语种探测(基于 Unicode 码点特征与字符集匹配) - */ -export declare function detectLanguage(text: string): { - code: string; - label: string; - confidence: number; -}; diff --git a/packages/declarative-ui/dist/examples/translator/languages.js b/packages/declarative-ui/dist/examples/translator/languages.js deleted file mode 100644 index b01b9a62..00000000 --- a/packages/declarative-ui/dist/examples/translator/languages.js +++ /dev/null @@ -1,114 +0,0 @@ -/** - * 多语言语言定义与自动检测引擎 - * 对标 Raycast Translator 官方支持语言规范 - */ -export const SUPPORTED_LANGUAGES = Object.freeze([ - { code: "auto", label: "Auto Detect", nativeName: "自动检测", flag: "🌐" }, - { code: "zh-Hans", label: "Chinese (Simplified)", nativeName: "简体中文", flag: "🇨🇳", phoneticsType: "pinyin" }, - { code: "en", label: "English", nativeName: "English", flag: "🇺🇸", phoneticsType: "ipa" }, - { code: "ja", label: "Japanese", nativeName: "日本語", flag: "🇯🇵", phoneticsType: "romaji" }, - { code: "ko", label: "Korean", nativeName: "한국어", flag: "🇰🇷", phoneticsType: "hangul" }, - { code: "fr", label: "French", nativeName: "Français", flag: "🇫🇷", phoneticsType: "ipa" }, - { code: "de", label: "German", nativeName: "Deutsch", flag: "🇩🇪", phoneticsType: "ipa" }, - { code: "es", label: "Spanish", nativeName: "Español", flag: "🇪🇸", phoneticsType: "ipa" }, - { code: "ru", label: "Russian", nativeName: "Русский", flag: "🇷🇺", phoneticsType: "ipa" }, - { code: "it", label: "Italian", nativeName: "Italiano", flag: "🇮🇹", phoneticsType: "ipa" }, - { code: "pt", label: "Portuguese", nativeName: "Português", flag: "🇵🇹", phoneticsType: "ipa" }, - { code: "ar", label: "Arabic", nativeName: "العربية", flag: "🇸🇦" }, - { code: "nl", label: "Dutch", nativeName: "Nederlands", flag: "🇳🇱" }, - { code: "pl", label: "Polish", nativeName: "Polski", flag: "🇵🇱" }, - { code: "tr", label: "Turkish", nativeName: "Türkçe", flag: "🇹🇷" }, - { code: "vi", label: "Vietnamese", nativeName: "Tiếng Việt", flag: "🇻🇳" }, - { code: "th", label: "Thai", nativeName: "ไทย", flag: "🇹🇭" }, - { code: "hi", label: "Hindi", nativeName: "हिन्दी", flag: "🇮🇳" }, - { code: "sv", label: "Swedish", nativeName: "Svenska", flag: "🇸🇪" }, - { code: "id", label: "Indonesian", nativeName: "Bahasa Indonesia", flag: "🇮🇩" }, - { code: "uk", label: "Ukrainian", nativeName: "Українська", flag: "🇺🇦" }, - { code: "el", label: "Greek", nativeName: "Ελληνικά", flag: "🇬🇷" }, - { code: "cs", label: "Czech", nativeName: "Čeština", flag: "🇨🇿" }, - { code: "da", label: "Danish", nativeName: "Dansk", flag: "🇩🇰" }, - { code: "fi", label: "Finnish", nativeName: "Suomi", flag: "🇫🇮" }, - { code: "ro", label: "Romanian", nativeName: "Română", flag: "🇷🇴" }, - { code: "hu", label: "Hungarian", nativeName: "Magyar", flag: "🇭🇺" }, - { code: "no", label: "Norwegian", nativeName: "Norsk", flag: "🇳🇴" }, - { code: "he", label: "Hebrew", nativeName: "עברית", flag: "🇮🇱" } -]); -export function getLanguageByCode(code) { - const normalized = code.toLowerCase(); - const found = SUPPORTED_LANGUAGES.find(l => l.code.toLowerCase() === normalized); - if (found) - return found; - if (normalized.startsWith("zh")) - return SUPPORTED_LANGUAGES[1]; // default zh-Hans - return SUPPORTED_LANGUAGES[2]; // default en -} -/** - * 智能语种探测(基于 Unicode 码点特征与字符集匹配) - */ -export function detectLanguage(text) { - const trimmed = text.trim(); - if (!trimmed) { - return { code: "en", label: "English", confidence: 0 }; - } - let cjkCount = 0; - let hiraganaKatakanaCount = 0; - let hangulCount = 0; - let cyrillicCount = 0; - let arabicCount = 0; - let latinCount = 0; - for (let i = 0; i < trimmed.length; i++) { - const code = trimmed.charCodeAt(i); - // CJK Unified Ideographs - if (code >= 0x4e00 && code <= 0x9fff) { - cjkCount++; - } - // Hiragana & Katakana - else if ((code >= 0x3040 && code <= 0x309f) || (code >= 0x30a0 && code <= 0x30ff)) { - hiraganaKatakanaCount++; - } - // Hangul Syllables - else if (code >= 0xac00 && code <= 0xd7af) { - hangulCount++; - } - // Cyrillic - else if (code >= 0x0400 && code <= 0x04ff) { - cyrillicCount++; - } - // Arabic - else if (code >= 0x0600 && code <= 0x06ff) { - arabicCount++; - } - // Basic Latin & Latin-1 - else if ((code >= 0x0041 && code <= 0x005a) || (code >= 0x0061 && code <= 0x007a)) { - latinCount++; - } - } - // 判定逻辑 - if (hiraganaKatakanaCount > 0) { - return { code: "ja", label: "Japanese", confidence: 0.95 }; - } - if (hangulCount > 0) { - return { code: "ko", label: "Korean", confidence: 0.95 }; - } - if (cjkCount > 0) { - return { code: "zh-Hans", label: "Chinese (Simplified)", confidence: 0.95 }; - } - if (cyrillicCount > 0) { - return { code: "ru", label: "Russian", confidence: 0.9 }; - } - if (arabicCount > 0) { - return { code: "ar", label: "Arabic", confidence: 0.9 }; - } - // 欧洲语言启发式 - const lower = trimmed.toLowerCase(); - if (/\b(der|die|das|und|ist|nicht|für|mit|ein|eine|guten|tag|danke|bitte)\b/i.test(lower)) { - return { code: "de", label: "German", confidence: 0.85 }; - } - if (/\b(le|la|les|un|une|des|et|est|pour|dans|avec|bonjour|merci)\b/i.test(lower)) { - return { code: "fr", label: "French", confidence: 0.85 }; - } - if (/\b(el|la|los|las|y|es|por|para|con|un|una|hola|gracias)\b/i.test(lower)) { - return { code: "es", label: "Spanish", confidence: 0.85 }; - } - return { code: "en", label: "English", confidence: 0.8 }; -} diff --git a/packages/declarative-ui/dist/examples/video-downloader/index.d.ts b/packages/declarative-ui/dist/examples/video-downloader/index.d.ts deleted file mode 100644 index a3c8b7bf..00000000 --- a/packages/declarative-ui/dist/examples/video-downloader/index.d.ts +++ /dev/null @@ -1,10 +0,0 @@ -/** - * ZTools 2.0 标杆原生插件视图: 全平台流媒体音视频解析与下载工坊 (Video Downloader 2.0 - 布局二:左 32% 平台分类树 + 右 68% 视频队列) - * - * 严格遵循显式导入规范: - * 1. 挂载时不扫描本机 Videos/Downloads 目录、不读取剪贴板,初始视频队列为空 `[]` - * 2. 顶栏 filterBar.actions 最多 2 个:「选择文件」「选择文件夹」,另支持拖入视频/文件夹与粘贴下载链接 - * 3. 本次下载完成的文件或手动导入的视频均汇总展示在右栏,动作面板支持「从列表移除」与「清空列表」 - */ -export declare function VideoDownloaderCommand(): import("../../index.js").ViewDescriptor; -export default VideoDownloaderCommand; diff --git a/packages/declarative-ui/dist/examples/video-downloader/index.js b/packages/declarative-ui/dist/examples/video-downloader/index.js deleted file mode 100644 index 9ac4cfe1..00000000 --- a/packages/declarative-ui/dist/examples/video-downloader/index.js +++ /dev/null @@ -1,372 +0,0 @@ -/** - * ZTools 2.0 标杆原生插件视图: 全平台流媒体音视频解析与下载工坊 (Video Downloader 2.0 - 布局二:左 32% 平台分类树 + 右 68% 视频队列) - * - * 严格遵循显式导入规范: - * 1. 挂载时不扫描本机 Videos/Downloads 目录、不读取剪贴板,初始视频队列为空 `[]` - * 2. 顶栏 filterBar.actions 最多 2 个:「选择文件」「选择文件夹」,另支持拖入视频/文件夹与粘贴下载链接 - * 3. 本次下载完成的文件或手动导入的视频均汇总展示在右栏,动作面板支持「从列表移除」与「清空列表」 - */ -import { Action, ActionPanel, Icon, List, useEffect, useState } from "../../index.js"; -import { getRealFileSize } from "../shared/native-ipc.js"; -import { buildImportEmptyActionPanel, buildListManagementSection, useExampleImportQueue } from "../shared/import-ui.js"; -import { STREAM_PLATFORMS, VIDEO_DOWNLOADER_IMPORT_RULES, VIDEO_QUALITY_PRESETS, detectVideoPlatform, ensureVideoSaveDirectory, fetchVideoDownloaderSnapshot, formatBytes, openLocalVideoFile, openLocalVideoFolder, parseAndDownloadStreamVideo, readClipboardStreamUrl, toLocalMediaVideoItem, trashLocalVideoFiles } from "./logic.js"; -export function VideoDownloaderCommand() { - const [saveDir, setSaveDir] = useState(""); - const [driveLetter, setDriveLetter] = useState("C:"); - const [driveFreeBytes, setDriveFreeBytes] = useState(0); - const [selectedPlatform, setSelectedPlatform] = useState("auto"); - const [selectedQuality, setSelectedQuality] = useState("q_1080p_mp4"); - const [searchText, setSearchText] = useState(""); - const [streamInput, setStreamInput] = useState(""); - const [statusBanner, setStatusBanner] = useState(""); - const [isLoading, setIsLoading] = useState(false); - const queue = useExampleImportQueue({ - rules: VIDEO_DOWNLOADER_IMPORT_RULES, - toItem: (entry) => toLocalMediaVideoItem(entry, entry.parentDir || "手动导入"), - pathOf: (item) => item.path, - idOf: (item) => item.id, - fileTitle: "选择本地视频文件", - folderTitle: "选择本地视频文件夹", - filterName: "视频文件", - supportedText: "仅支持 mp4/mkv/mov/webm/flv/avi 等视频格式", - defaultChecked: false, - isBusy: () => isLoading, - dropTitle: "拖入视频文件或文件夹", - dropSubtitle: "松开后加入本地视频队列,或按 Ctrl+V 粘贴视频链接", - onTextPaste: (text) => { - const detectedPaste = detectVideoPlatform(text); - if (!detectedPaste.url) - return false; - setStreamInput(detectedPaste.url); - setStatusBanner(`已从粘贴识别 ${detectedPaste.platform.name} 链接`); - return true; - }, - onImported: (added, merged) => { - if (added[0]?.path && !saveDir) { - const idx = Math.max(added[0].path.lastIndexOf("/"), added[0].path.lastIndexOf("\\")); - if (idx > 0) - setSaveDir(added[0].path.slice(0, idx)); - } - setStatusBanner(`已导入 ${added.length} 个视频,当前共 ${merged.length} 项`); - }, - onCleared: () => setStatusBanner("已清空本地视频列表") - }); - useEffect(() => { - let active = true; - void fetchVideoDownloaderSnapshot(undefined, saveDir) - .then((snap) => { - if (!active) - return; - setDriveLetter(snap.driveLetter); - setDriveFreeBytes(snap.driveFreeBytes); - }) - .catch(() => { - // 磁盘空间探测失败时维持默认空状态,不阻塞界面渲染 - }); - return () => { - active = false; - }; - }, [saveDir]); - const handleSearchChange = (text) => { - setSearchText(text); - if (/(https?:\/\/|\bBV[0-9A-Za-z]{10}\b)/i.test(text.trim())) { - setStreamInput(text.trim()); - } - }; - const activeInputText = streamInput.trim(); - const detected = detectVideoPlatform(activeInputText); - const currentQuality = VIDEO_QUALITY_PRESETS.find((q) => q.id === selectedQuality) || VIDEO_QUALITY_PRESETS[1]; - const isUrlSearch = /(https?:\/\/|\bBV[0-9A-Za-z]{10}\b)/i.test(searchText.trim()); - const keyword = isUrlSearch ? "" : searchText.trim().toLowerCase(); - const filteredVideos = queue.items.filter((video) => { - if (selectedPlatform !== "auto") { - const nameLower = video.name.toLowerCase(); - if (selectedPlatform === "bilibili" && !nameLower.includes("bili") && !nameLower.includes("bv")) { - // 保留本地已有视频展示以便统一管理 - } - } - if (!keyword) - return true; - return `${video.name} ${video.path} ${video.sourceDirLabel} ${video.resolutionLabel}` - .toLowerCase() - .includes(keyword); - }); - const checkedSet = new Set(queue.checkedIds); - const selectedVideos = queue.items.filter((v) => checkedSet.has(v.id)); - const selectedTotalBytes = selectedVideos.reduce((acc, item) => acc + item.sizeBytes, 0); - const totalSizeBytes = queue.items.reduce((acc, item) => acc + item.sizeBytes, 0); - const handleReadClipboardUrl = async () => { - const clip = await readClipboardStreamUrl(); - if (!clip.url) { - setStatusBanner("剪贴板中未检测到 B站/抖音/快手/YouTube/M3U8 视频链接"); - return; - } - setStreamInput(clip.url); - setStatusBanner(`已识别剪贴板链接:${clip.platform.name}`); - }; - const handleParseAndDownload = async (rawInput) => { - const target = (rawInput ?? activeInputText).trim(); - if (!target) { - setStatusBanner("请在搜索框粘贴视频链接,或先点击「读取剪贴板链接」"); - return; - } - setIsLoading(true); - try { - const resolvedDir = await ensureVideoSaveDirectory(saveDir); - if (!resolvedDir) { - setStatusBanner("未能获取视频保存目录,请先通过「选择文件夹」指定目录"); - return; - } - if (!saveDir) - setSaveDir(resolvedDir); - const res = await parseAndDownloadStreamVideo(target, resolvedDir, currentQuality); - setStatusBanner(res.message); - const destPath = res.ok && res.data && typeof res.data === "object" - ? String(res.data.destPath || "") - : ""; - if (res.ok && destPath) { - const size = await getRealFileSize(destPath); - const name = destPath.split(/[\\/]/).pop() || "downloaded_video.mp4"; - const extIdx = name.lastIndexOf("."); - const item = toLocalMediaVideoItem({ - path: destPath, - name, - parentDir: resolvedDir, - extension: extIdx > 0 ? name.slice(extIdx).toLowerCase() : ".mp4", - sizeBytes: size, - lastModifiedMs: Date.now() - }, "本次下载"); - queue.setItems((prev) => prev.some((v) => v.path.toLowerCase() === destPath.toLowerCase()) ? prev : [item, ...prev]); - } - } - finally { - setIsLoading(false); - } - }; - const handleOpenSaveDirectory = async () => { - const resolvedDir = await ensureVideoSaveDirectory(saveDir); - if (!resolvedDir) { - setStatusBanner("暂无可打开的保存目录,请先导入文件夹"); - return; - } - if (!saveDir) - setSaveDir(resolvedDir); - await openLocalVideoFile(resolvedDir); - }; - const handleTrashSelected = async () => { - const targets = selectedVideos.length > 0 ? selectedVideos : filteredVideos.slice(0, 1); - if (targets.length === 0) - return; - setIsLoading(true); - try { - const res = await trashLocalVideoFiles(targets.map((v) => v.path), targets); - if (res.deletedCount > 0) { - const removedPaths = new Set(targets.map((t) => t.path.toLowerCase())); - queue.setItems((prev) => prev.filter((item) => !removedPaths.has(item.path.toLowerCase()))); - queue.setCheckedIds((prev) => prev.filter((id) => !targets.some((t) => t.id === id))); - } - setStatusBanner(res.deletedCount > 0 - ? `已将 ${res.deletedCount} 个本地视频移入回收站,释放 ${formatBytes(res.freedBytes)}` - : "本地视频清理操作未删除任何文件"); - } - finally { - setIsLoading(false); - } - }; - const maxVideoBytes = Math.max(1, ...filteredVideos.map((v) => v.sizeBytes)); - const summaryText = queue.importStatusText || - statusBanner || - `解析引擎: ${detected.platform.name} · 档位: ${currentQuality.badge} · 队列 ${filteredVideos.length} 项 (${driveLetter} 可用 ${formatBytes(driveFreeBytes)})`; - const leftNavNodes = [ - List.Item({ - id: "nav-plat-auto", - title: "全部平台与本地视频队列", - subtitle: saveDir || "尚未指定保存目录(点击选择文件夹或粘贴链接开始)", - icon: Icon.Video, - onSelect: () => setSelectedPlatform("auto"), - accessories: [ - { progress: 1 }, - { tag: { value: `${queue.items.length} 部` } }, - { text: formatBytes(totalSizeBytes) } - ], - actions: ActionPanel({ - children: [ - Action({ - title: activeInputText ? `一键解析并下载 [${currentQuality.badge}]` : "解析当前输入链接", - icon: Icon.Download, - onAction: () => handleParseAndDownload(activeInputText) - }), - Action({ - title: "读取剪贴板中的视频链接", - icon: Icon.Clipboard, - onAction: handleReadClipboardUrl - }), - Action({ - title: "打开视频保存目录", - icon: Icon.Folder, - onAction: handleOpenSaveDirectory - }), - Action({ - title: `清理已勾选本地视频 (${selectedVideos.length} 部)`, - icon: Icon.Trash, - style: "destructive", - onAction: handleTrashSelected - }), - buildListManagementSection({ - onPickFiles: queue.handlePickFiles, - onPickFolder: queue.handlePickFolder, - onClear: queue.clearQueue - }) - ] - }) - }), - ...STREAM_PLATFORMS.map((platform, idx) => { - const isDetected = detected.platform.id === platform.id; - const ratio = Math.max(0.2, 1 - idx * 0.14); - return List.Item({ - id: `nav-plat-${platform.id}`, - title: platform.name, - subtitle: `${platform.handlerName} · ${platform.features}`, - icon: Icon.Globe, - onSelect: () => setSelectedPlatform(platform.id), - accessories: [ - { progress: ratio }, - { tag: { value: isDetected && activeInputText ? "已命中链接" : platform.handlerName } } - ], - actions: ActionPanel({ - children: [ - Action({ - title: `使用 ${platform.name} 引擎解析下载`, - icon: Icon.Download, - onAction: () => { - setSelectedPlatform(platform.id); - void handleParseAndDownload(activeInputText); - } - }), - Action({ - title: "读取剪贴板中的视频链接", - icon: Icon.Clipboard, - onAction: handleReadClipboardUrl - }), - Action({ - title: "打开本地视频保存目录", - icon: Icon.Folder, - onAction: handleOpenSaveDirectory - }) - ] - }) - }); - }) - ]; - const allChecked = filteredVideos.length > 0 && filteredVideos.every((v) => checkedSet.has(v.id)); - const someChecked = filteredVideos.some((v) => checkedSet.has(v.id)); - const subListItems = filteredVideos.map((video) => { - const isChecked = checkedSet.has(video.id); - const ratio = Math.min(1, video.sizeBytes / maxVideoBytes); - const dateStr = video.mtimeMs > 0 ? new Date(video.mtimeMs).toLocaleDateString() : "本地文件"; - return List.Item({ - id: `vid-item-${video.id}`, - title: video.name, - subtitle: `${video.sourceDirLabel} · ${video.path} · ${dateStr}`, - icon: Icon.Video, - checkable: true, - checked: isChecked, - onCheckChange: () => queue.toggleCheck(video.id), - onToggleCheck: () => queue.toggleCheck(video.id), - accessories: [ - { progress: ratio }, - { tag: { value: video.resolutionLabel } }, - { text: formatBytes(video.sizeBytes) } - ], - actions: ActionPanel({ - children: [ - Action({ - title: activeInputText ? `解析下载当前视频 [${currentQuality.badge}]` : "使用系统播放器打开此视频", - icon: activeInputText ? Icon.Download : Icon.Play, - onAction: async () => { - if (activeInputText) { - await handleParseAndDownload(activeInputText); - } - else { - await openLocalVideoFile(video.path); - } - } - }), - Action({ - title: "在资源管理器中定位视频文件", - icon: Icon.Folder, - onAction: async () => { - await openLocalVideoFolder(video.path); - } - }), - Action({ - title: isChecked ? "取消勾选此视频" : "勾选此视频", - icon: Icon.CheckCircle, - onAction: () => queue.toggleCheck(video.id) - }), - Action({ - title: `批量移入回收站清理 (${selectedVideos.length} 部 / ${formatBytes(selectedTotalBytes)})`, - icon: Icon.Trash, - style: "destructive", - onAction: handleTrashSelected - }), - buildListManagementSection({ - onRemove: () => queue.removeItem(video.id), - onPickFiles: queue.handlePickFiles, - onPickFolder: queue.handlePickFolder, - onToggleAll: () => queue.toggleAllVisible(filteredVideos), - allSelected: allChecked, - onClear: queue.clearQueue - }) - ] - }) - }); - }); - const activePlatformName = selectedPlatform === "auto" - ? "全部平台与本地视频队列" - : STREAM_PLATFORMS.find((p) => p.id === selectedPlatform)?.name || "流媒体视频"; - return List({ - isLoading: isLoading || queue.isImporting, - searchBarPlaceholder: "粘贴 Bilibili BV号 / 抖音口令 / 快手 / YouTube / M3U8 链接,或搜索已导入视频...", - onSearchTextChange: handleSearchChange, - isShowingDetail: false, - ...queue.fileInputProps, - searchBarAccessory: List.Dropdown({ - tooltip: "选择目标画质或音频提取封装格式", - value: selectedQuality, - onChange: (val) => setSelectedQuality(val), - children: VIDEO_QUALITY_PRESETS.map((preset) => List.Dropdown.Item({ - title: `${preset.name} [${preset.badge}]`, - value: preset.id - })) - }), - filterBar: { - summaryText, - actions: queue.topBarActions - }, - subList: { - title: `${activePlatformName} (${filteredVideos.length} 部 · 已选 ${formatBytes(selectedTotalBytes)})`, - subtitle: saveDir || "支持拖入视频/文件夹、选择文件或粘贴链接下载", - emptyText: "队列为空,请点击顶部「选择文件 / 选择文件夹」导入视频,或粘贴视频链接下载", - checkable: filteredVideos.length > 0, - checked: allChecked ? true : someChecked ? "indeterminate" : false, - onCheckChange: () => queue.toggleAllVisible(filteredVideos), - items: subListItems - }, - actions: buildImportEmptyActionPanel(queue.handlePickFiles, queue.handlePickFolder, [ - Action({ - title: "读取剪贴板中的视频链接", - icon: Icon.Clipboard, - onAction: handleReadClipboardUrl - }) - ]), - children: [ - List.Section({ - title: "流媒体平台解析引擎导航 (32%)", - subtitle: "6 大平台处理器", - children: leftNavNodes - }) - ] - }); -} -export default VideoDownloaderCommand; diff --git a/packages/declarative-ui/dist/examples/video-downloader/logic.d.ts b/packages/declarative-ui/dist/examples/video-downloader/logic.d.ts deleted file mode 100644 index caf00d58..00000000 --- a/packages/declarative-ui/dist/examples/video-downloader/logic.d.ts +++ /dev/null @@ -1,89 +0,0 @@ -/** - * ZTools 2.0 标杆原生插件: 全平台流媒体音视频解析与下载工坊 (Video Downloader 2.0,真实宿主驱动) - * - * 严格遵循 ZTools Declarative UI 2.0 零模拟数据规范: - * 1. 与 Windows 原生插件 video-downloader 能力一致: - * - 6 大流媒体平台智能探测器 (`detectVideoPlatform`:Bilibili BV/av号、抖音分享口令、快手、微博视频、YouTube、通用 M3U8/MP4 直链) - * - 6 大画质与音轨封装档位(4K 60fps 原画合并、1080P 高码率 MP4、720P 轻量流畅、仅提取 320kbps MP3 音频、导出无损 FLAC 音轨、连同字幕与封面打包) - * - 支持显式导入本地已保存视频库(选择文件 / 选择文件夹 / 拖入文件夹) - * - 支持用户主动读取剪贴板中的分享口令并一键解析下载、打开播放与定位目录 - */ -import { formatBytes, type NativeInvocationResult } from "../shared/native-ipc.js"; -import { type ExampleImportResult, type ExampleImportRules, type ExampleImportedFile } from "../shared/file-import.js"; -export declare const VIDEO_DOWNLOADER_IMPORT_RULES: ExampleImportRules; -export { formatBytes }; -export type { NativeInvocationResult }; -export declare const DLL_PLUGIN_NAME = "VideoDownloaderPlugin"; -export declare const FORBIDDEN_TARGET_PATTERN: RegExp; -export declare const FORBIDDEN_REASON = "\u7981\u6B62\u64CD\u4F5C Windows \u7CFB\u7EDF\u6838\u5FC3\u76EE\u5F55\u4E2D\u7684\u6587\u4EF6"; -export type StreamPlatformId = "auto" | "bilibili" | "douyin" | "kuaishou" | "youtube" | "weibo" | "m3u8_direct"; -export interface StreamPlatformMeta { - id: StreamPlatformId; - name: string; - icon: string; - color: string; - handlerName: string; - features: string; -} -export declare const STREAM_PLATFORMS: StreamPlatformMeta[]; -export type VideoQualityPresetId = "q_4k_mp4" | "q_1080p_mp4" | "q_720p_mp4" | "q_audio_mp3" | "q_audio_flac" | "q_with_subs"; -export interface VideoQualityPreset { - id: VideoQualityPresetId; - name: string; - badge: string; - ytDlpArgs: string; - description: string; -} -export declare const VIDEO_QUALITY_PRESETS: VideoQualityPreset[]; -export interface LocalMediaVideoItem { - id: string; - name: string; - path: string; - ext: string; - sizeBytes: number; - mtimeMs: number; - sourceDirLabel: string; - resolutionTier: "large_hd" | "standard" | "short_clip"; - resolutionLabel: string; - color: string; -} -export interface VideoDownloaderSnapshot { - saveDir: string; - driveLetter: string; - driveFreeBytes: number; - clipboardUrl: string; - detectedPlatform: StreamPlatformMeta; - videos: LocalMediaVideoItem[]; - totalSizeBytes: number; - tierStats: Array<{ - tier: string; - label: string; - color: string; - sizeBytes: number; - count: number; - }>; - updatedAt: string; -} -export declare function detectVideoPlatform(rawText: string): { - url: string; - platform: StreamPlatformMeta; -}; -export declare function readClipboardStreamUrl(hostBridge?: unknown): Promise<{ - url: string; - platform: StreamPlatformMeta; -}>; -export declare function toLocalMediaVideoItem(entry: ExampleImportedFile, sourceDirLabel?: string): LocalMediaVideoItem; -export declare function computeVideoTierStats(videos: LocalMediaVideoItem[]): VideoDownloaderSnapshot["tierStats"]; -export declare function ensureVideoSaveDirectory(currentDir: string, hostBridge?: unknown): Promise; -export declare function importVideoDownloaderFolder(hostBridge?: unknown): Promise; -export declare function fetchVideoDownloaderSnapshot(hostBridge?: unknown, saveDirHint?: string): Promise; -export declare function parseAndDownloadStreamVideo(rawInput: string, saveDir: string, qualityPreset: VideoQualityPreset, hostBridge?: unknown): Promise; -export declare function trashLocalVideoFiles(paths: string[], knownVideos?: LocalMediaVideoItem[], hostBridge?: unknown): Promise<{ - deletedCount: number; - freedBytes: number; -}>; -export declare function openLocalVideoFile(targetPath: string, hostBridge?: unknown): Promise; -export declare function openLocalVideoFolder(targetPath: string, hostBridge?: unknown): Promise; diff --git a/packages/declarative-ui/dist/examples/video-downloader/logic.js b/packages/declarative-ui/dist/examples/video-downloader/logic.js deleted file mode 100644 index 7b023c7f..00000000 --- a/packages/declarative-ui/dist/examples/video-downloader/logic.js +++ /dev/null @@ -1,351 +0,0 @@ -/** - * ZTools 2.0 标杆原生插件: 全平台流媒体音视频解析与下载工坊 (Video Downloader 2.0,真实宿主驱动) - * - * 严格遵循 ZTools Declarative UI 2.0 零模拟数据规范: - * 1. 与 Windows 原生插件 video-downloader 能力一致: - * - 6 大流媒体平台智能探测器 (`detectVideoPlatform`:Bilibili BV/av号、抖音分享口令、快手、微博视频、YouTube、通用 M3U8/MP4 直链) - * - 6 大画质与音轨封装档位(4K 60fps 原画合并、1080P 高码率 MP4、720P 轻量流畅、仅提取 320kbps MP3 音频、导出无损 FLAC 音轨、连同字幕与封面打包) - * - 支持显式导入本地已保存视频库(选择文件 / 选择文件夹 / 拖入文件夹) - * - 支持用户主动读取剪贴板中的分享口令并一键解析下载、打开播放与定位目录 - */ -import { callHostTransport, invokePluginService, isRealElectronHost, openRealPath, resolveRealSpecialPaths, showRealItemInFolder, showRealToast, trashRealItem, writeRealClipboardText, formatBytes } from "../shared/native-ipc.js"; -import { pickExampleFolderFiles, probeExampleDriveSpace } from "../shared/file-import.js"; -export const VIDEO_DOWNLOADER_IMPORT_RULES = { - extensions: [".mp4", ".mkv", ".mov", ".webm", ".flv", ".avi", ".m4v", ".ts"], - maxDepth: 5, - maxFiles: 500, - skipEmptyFiles: true, - forbiddenPath: /(^|[\\/])(Windows|System32|SysWOW64|Program Files|Program Files \(x86\)|Boot|Recovery)($|[\\/])/i -}; -export { formatBytes }; -export const DLL_PLUGIN_NAME = "VideoDownloaderPlugin"; -export const FORBIDDEN_TARGET_PATTERN = /(^|[\\/])(Windows|System32|SysWOW64|Program Files|Program Files \(x86\)|Boot|Recovery)($|[\\/])/i; -export const FORBIDDEN_REASON = "禁止操作 Windows 系统核心目录中的文件"; -export const STREAM_PLATFORMS = [ - { - id: "bilibili", - name: "哔哩哔哩 (Bilibili)", - icon: "Icon.Video", - color: "#fb7299", - handlerName: "BilibiliHandler", - features: "支持 BV/av 号、番剧 ep/ss、分 P 合集列表、4K/1080P60 DASH 音画分离自动合并与弹幕/CC字幕导出" - }, - { - id: "douyin", - name: "抖音无水印 (Douyin)", - icon: "Icon.Music", - color: "#111827", - handlerName: "DouyinHandler", - features: "支持口令长短链自动还原、1080P 原画去水印视频提取、图集无损保存与原声 BGM 独立提取" - }, - { - id: "kuaishou", - name: "快手短视频 (Kuaishou)", - icon: "Icon.Bolt", - color: "#f97316", - handlerName: "KuaishouHandler", - features: "支持快手分享短链解析、去水印高清 MP4 原片直提与直播回放切片下载" - }, - { - id: "youtube", - name: "YouTube / 国际流媒体", - icon: "Icon.Play", - color: "#ef4444", - handlerName: "GenericYtDlpHandler", - features: "基于 yt-dlp + FFmpeg 引擎,支持 4K/8K WEBM/MP4 自适应流合并、多语种内嵌字幕与播放列表批量下载" - }, - { - id: "weibo", - name: "微博视频 (Weibo)", - icon: "Icon.Globe", - color: "#f59e0b", - handlerName: "WeiboHandler", - features: "支持微博正文视频、tv.weibo 連結与超话高清视频流直链提取" - }, - { - id: "m3u8_direct", - name: "HLS M3U8 / MP4 直链", - icon: "Icon.Link", - color: "#3b82f6", - handlerName: "GenericStreamHandler", - features: "支持 HLS (.m3u8) 分片并发拉取合并转封装 MP4、DASH (.mpd) 及常规直链视频高速拉取" - } -]; -export const VIDEO_QUALITY_PRESETS = [ - { - id: "q_4k_mp4", - name: "4K / 原画最高画质 (MP4)", - badge: "4K 60fps", - ytDlpArgs: '-f "bestvideo[ext=mp4]+bestaudio[ext=m4a]/bestvideo+bestaudio/best" --merge-output-format mp4', - description: "优先拉取 4K / 1080P60 最高码率视频流与无损音频流,通过 FFmpeg 无损合成为 MP4" - }, - { - id: "q_1080p_mp4", - name: "1080P 全高清高兼容 (H.264)", - badge: "1080P", - ytDlpArgs: '-f "bestvideo[height<=1080][ext=mp4]+bestaudio[ext=m4a]/best[height<=1080]" --merge-output-format mp4', - description: "锁定 1080P 分辨率与 H.264/AAC 编码,兼容所有剪辑软件(Premiere / 剪映)与移动设备" - }, - { - id: "q_720p_mp4", - name: "720P 轻量快速下载", - badge: "720P", - ytDlpArgs: '-f "bestvideo[height<=720]+bestaudio/best[height<=720]" --merge-output-format mp4', - description: "适合长视频教程、会议录像快速离线缓存,体积减少约 60%" - }, - { - id: "q_audio_mp3", - name: "仅提取高音质音频 (MP3 320k)", - badge: "MP3 音轨", - ytDlpArgs: "-x --audio-format mp3 --audio-quality 0 --embed-thumbnail --add-metadata", - description: "剥离视频画面,直接提取音轨并转码为 320kbps MP3,自动内嵌视频封面与标题元数据" - }, - { - id: "q_audio_flac", - name: "仅提取无损音频 (FLAC)", - badge: "FLAC 无损", - ytDlpArgs: "-x --audio-format flac --audio-quality 0", - description: "适合音乐 MV、演奏现场视频的无损音轨无损抽离" - }, - { - id: "q_with_subs", - name: "1080P 视频 + 字幕 + 封面全套", - badge: "含字幕封面", - ytDlpArgs: '-f "bestvideo[height<=1080]+bestaudio/best" --merge-output-format mp4 --write-subs --write-auto-subs --sub-langs "zh.*,en.*" --write-thumbnail', - description: "下载视频同时导出中英文字幕 (.srt/.vtt) 与高清封面大图 (.jpg)" - } -]; -export function detectVideoPlatform(rawText) { - const text = String(rawText || "").trim(); - const urlMatch = text.match(/https?:\/\/[^\s"'<>]+/i); - const bvMatch = text.match(/\b(BV[0-9A-Za-z]{10})\b/); - const extractedUrl = urlMatch - ? urlMatch[0] - : bvMatch - ? `https://www.bilibili.com/video/${bvMatch[1]}` - : ""; - const lower = (extractedUrl || text).toLowerCase(); - if (lower.includes("bilibili.com") || lower.includes("b23.tv") || bvMatch) { - return { url: extractedUrl, platform: STREAM_PLATFORMS[0] }; - } - if (lower.includes("douyin.com") || lower.includes("iesdouyin.com")) { - return { url: extractedUrl, platform: STREAM_PLATFORMS[1] }; - } - if (lower.includes("kuaishou.com") || lower.includes("chenzhongtech.com")) { - return { url: extractedUrl, platform: STREAM_PLATFORMS[2] }; - } - if (lower.includes("youtube.com") || lower.includes("youtu.be")) { - return { url: extractedUrl, platform: STREAM_PLATFORMS[3] }; - } - if (lower.includes("weibo.com") || lower.includes("weibo.cn")) { - return { url: extractedUrl, platform: STREAM_PLATFORMS[4] }; - } - return { url: extractedUrl, platform: STREAM_PLATFORMS[5] }; -} -export async function readClipboardStreamUrl(hostBridge) { - try { - const ipcClip = await callHostTransport("clipboard_read_text", {}, hostBridge); - if (ipcClip.ok && ipcClip.data) { - const txt = typeof ipcClip.data === "string" ? ipcClip.data : String(ipcClip.data.text || ""); - return detectVideoPlatform(txt); - } - } - catch (err) { - console.warn("[video-downloader] readClipboardStreamUrl fallback:", err); - } - return { url: "", platform: STREAM_PLATFORMS[0] }; -} -export function toLocalMediaVideoItem(entry, sourceDirLabel = "已导入视频") { - const sizeBytes = Number(entry.sizeBytes ?? 0); - let resolutionTier = "short_clip"; - let resolutionLabel = "短视频与动图 (<10MB)"; - if (sizeBytes >= 50 * 1024 * 1024) { - resolutionTier = "large_hd"; - resolutionLabel = "超清长视频 (>50MB)"; - } - else if (sizeBytes >= 10 * 1024 * 1024) { - resolutionTier = "standard"; - resolutionLabel = "高清中型视频 (10~50MB)"; - } - return { - id: entry.path, - name: entry.name, - path: entry.path, - ext: entry.extension || ".mp4", - sizeBytes, - mtimeMs: Number(entry.lastModifiedMs ?? 0), - sourceDirLabel, - resolutionTier, - resolutionLabel, - color: "var(--rc-text-muted)" - }; -} -export function computeVideoTierStats(videos) { - const tiers = { - large_hd: { label: "超清长视频 (>50MB)", color: "var(--rc-text-muted)", sizeBytes: 0, count: 0 }, - standard: { label: "高清中型视频 (10~50MB)", color: "var(--rc-text-muted)", sizeBytes: 0, count: 0 }, - short_clip: { label: "短视频与动图 (<10MB)", color: "var(--rc-text-muted)", sizeBytes: 0, count: 0 } - }; - for (const v of videos) { - const t = tiers[v.resolutionTier] || tiers.short_clip; - t.sizeBytes += v.sizeBytes; - t.count += 1; - } - return Object.entries(tiers) - .map(([tier, val]) => ({ tier, label: val.label, color: val.color, sizeBytes: val.sizeBytes, count: val.count })) - .filter((s) => s.sizeBytes > 0); -} -export async function ensureVideoSaveDirectory(currentDir, hostBridge) { - if (currentDir && currentDir.trim()) - return currentDir.trim(); - const paths = await resolveRealSpecialPaths(hostBridge); - return paths.videos || paths.downloads || (paths.userProfile ? `${paths.userProfile}\\Videos` : ""); -} -export async function importVideoDownloaderFolder(hostBridge) { - const result = await pickExampleFolderFiles(VIDEO_DOWNLOADER_IMPORT_RULES, { title: "选择视频文件夹" }, hostBridge); - const videos = result.files.map((f) => toLocalMediaVideoItem(f, f.parentDir || "导入文件夹")); - const saveDir = videos[0]?.path ? result.files[0].parentDir : ""; - return { ...result, videos, saveDir }; -} -export async function fetchVideoDownloaderSnapshot(hostBridge, saveDirHint = "") { - const cleanDir = String(saveDirHint || "").trim(); - const driveLetter = (cleanDir.match(/^[A-Za-z]:/) || ["C:"])[0].toUpperCase(); - const { freeBytes: driveFreeBytes } = await probeExampleDriveSpace(driveLetter, hostBridge); - return { - saveDir: cleanDir, - driveLetter, - driveFreeBytes, - clipboardUrl: "", - detectedPlatform: STREAM_PLATFORMS[0], - videos: [], - totalSizeBytes: 0, - tierStats: [], - updatedAt: new Date().toLocaleTimeString() - }; -} -export async function parseAndDownloadStreamVideo(rawInput, saveDir, qualityPreset, hostBridge) { - const detected = detectVideoPlatform(rawInput); - if (!detected.url) { - return { - ok: false, - code: -1, - message: "未识别到有效的视频分享链接或 BV 号,请先复制 B站/抖音/快手/YouTube 链接", - error: "INVALID_STREAM_URL" - }; - } - if (!saveDir || FORBIDDEN_TARGET_PATTERN.test(saveDir)) { - return { - ok: false, - code: -1, - message: FORBIDDEN_REASON, - error: FORBIDDEN_REASON - }; - } - // 1. 优先调用原生插件 `VideoDownloaderPlugin` (`downloadVideo` 或 `StartDownload`) - const payload = { - url: detected.url, - platform: detected.platform.id, - saveDir, - qualityId: qualityPreset.id, - ytDlpArgs: qualityPreset.ytDlpArgs - }; - const pluginRes = await invokePluginService(DLL_PLUGIN_NAME, "downloadVideo", payload, hostBridge); - if (pluginRes.ok) { - await showRealToast(`已通过 ${detected.platform.name} 解析引擎启动下载 (${qualityPreset.badge})`, "success"); - return pluginRes; - } - const legacyPluginRes = await invokePluginService(DLL_PLUGIN_NAME, "StartDownload", payload, hostBridge); - if (legacyPluginRes.ok) { - await showRealToast(`已通过 ${detected.platform.name} 解析引擎启动下载 (${qualityPreset.badge})`, "success"); - return legacyPluginRes; - } - // 2. 若为直链音视频 URL,则直接通过宿主 network_http_download 下载到本地目录 - if (/\.(?:mp4|webm|mkv|mov|flv|m4v)(?:$|[?#])/i.test(detected.url)) { - const rawFileName = decodeURIComponent(detected.url.split(/[?#]/)[0].split("/").pop() || "") || - `video_${Date.now()}.mp4`; - const safeFileName = rawFileName.replace(/[<>:"/\\|?*]+/g, "_"); - const destPath = `${saveDir.replace(/[\\/]+$/, "")}\\${safeFileName}`; - const dlRes = await callHostTransport("network_http_download", { url: detected.url, destPath, saveDir, fileName: safeFileName }, hostBridge); - if (dlRes.ok) { - await showRealToast(`直链视频已下载至 ${destPath}`, "success"); - return { - ok: true, - code: 0, - message: `已通过宿主 HTTP 通道下载直链视频至 ${destPath}`, - data: dlRes.data ?? { destPath } - }; - } - const isRealHost = Boolean(hostBridge) || isRealElectronHost(hostBridge) || isRealElectronHost(); - if (isRealHost) { - return { - ok: false, - code: -1, - message: dlRes.error || "直链视频下载失败", - error: dlRes.error || "直链视频下载失败" - }; - } - } - // 3. 若未安装 yt-dlp 直接下载引擎,仅生成标准 yt-dlp 命令写入剪贴板并如实告知用户 - const cmd = `yt-dlp ${qualityPreset.ytDlpArgs} -P "${saveDir}" -o "%(title)s [%(id)s].%(ext)s" "${detected.url}"`; - await writeRealClipboardText(cmd, hostBridge); - if (isRealElectronHost(hostBridge) || isRealElectronHost()) { - return { - ok: false, - code: -1, - message: "本机未检测到 yt-dlp/aria2c 下载引擎,已将命令复制到剪贴板", - error: "ENGINE_NOT_FOUND" - }; - } - await showRealToast(`已识别「${detected.platform.name}」并生成 ${qualityPreset.badge} 下载命令至剪贴板`, "info"); - return { - ok: true, - code: 0, - message: `已生成并复制 yt-dlp 命令到剪贴板(本机未检测到 yt-dlp 直接下载引擎): ${cmd}` - }; -} -export async function trashLocalVideoFiles(paths, knownVideos = [], hostBridge) { - const sizeMap = new Map(); - for (const v of knownVideos) { - if (v?.path) - sizeMap.set(v.path.toLowerCase(), Math.max(0, Number(v.sizeBytes || 0))); - } - let deletedCount = 0; - let freedBytes = 0; - for (const p of paths) { - if (!p || FORBIDDEN_TARGET_PATTERN.test(p)) - continue; - const trashed = await trashRealItem(p, hostBridge); - if (trashed.ok) { - deletedCount += 1; - freedBytes += sizeMap.get(p.toLowerCase()) || 0; - } - } - if (deletedCount > 0) { - await showRealToast(`已将 ${deletedCount} 个视频文件移入回收站,释放 ${formatBytes(freedBytes)}`, "success"); - } - return { deletedCount, freedBytes }; -} -export async function openLocalVideoFile(targetPath, hostBridge) { - if (!targetPath || FORBIDDEN_TARGET_PATTERN.test(targetPath)) { - return { ok: false, code: -1, message: FORBIDDEN_REASON, error: FORBIDDEN_REASON }; - } - const opened = await openRealPath(targetPath, hostBridge); - return { - ok: opened, - code: opened ? 0 : -1, - message: opened ? `已打开视频: ${targetPath}` : `打开视频失败: ${targetPath}`, - error: opened ? undefined : "OPEN_VIDEO_FAILED" - }; -} -export async function openLocalVideoFolder(targetPath, hostBridge) { - if (!targetPath || FORBIDDEN_TARGET_PATTERN.test(targetPath)) { - return { ok: false, code: -1, message: FORBIDDEN_REASON, error: FORBIDDEN_REASON }; - } - const shown = await showRealItemInFolder(targetPath, hostBridge); - return { - ok: shown, - code: shown ? 0 : -1, - message: shown ? `已在资源管理器定位: ${targetPath}` : `定位视频失败: ${targetPath}`, - error: shown ? undefined : "SHOW_IN_FOLDER_FAILED" - }; -} diff --git a/packages/declarative-ui/dist/examples/vscode-projects/index.d.ts b/packages/declarative-ui/dist/examples/vscode-projects/index.d.ts deleted file mode 100644 index 28e267a1..00000000 --- a/packages/declarative-ui/dist/examples/vscode-projects/index.d.ts +++ /dev/null @@ -1,10 +0,0 @@ -import type { ProjectEntry } from './types.js'; -export * from './types.js'; -export * from './project-service.js'; -export interface VscodeProjectsCommandProps { - featureCode?: string; - initialProjects?: ProjectEntry[]; - hostOverride?: unknown; -} -export declare function VscodeProjectsCommand(props?: VscodeProjectsCommandProps): JSX.Element; -export default VscodeProjectsCommand; diff --git a/packages/declarative-ui/dist/examples/vscode-projects/index.js b/packages/declarative-ui/dist/examples/vscode-projects/index.js deleted file mode 100644 index 6594fb0c..00000000 --- a/packages/declarative-ui/dist/examples/vscode-projects/index.js +++ /dev/null @@ -1,86 +0,0 @@ -import React, { Action, ActionPanel, Icon, List, Toast, showToast, useEffect, useMemo, useState } from '../../index.js'; -import { filterProjectEntries, launchProjectInEditor, scanAllRecentProjects } from './project-service.js'; -export * from './types.js'; -export * from './project-service.js'; -function getEditorIcon(editorType) { - switch (editorType) { - case 'vscode': - case 'cursor': - case 'trae': - case 'windsurf': - return Icon.Code; - default: - return Icon.Terminal; - } -} -export function VscodeProjectsCommand(props = {}) { - const defaultEditorFilter = props.featureCode === 'projects-vscode-cursor' - ? 'vsc-family' - : props.featureCode === 'projects-jetbrains' - ? 'jetbrains' - : 'all'; - const [projects, setProjects] = useState(props.initialProjects ?? []); - const [selectedEditor, setSelectedEditor] = useState(defaultEditorFilter); - const [searchText, setSearchText] = useState(''); - const [isLoading, setIsLoading] = useState(!props.initialProjects); - const handleRescan = async () => { - setIsLoading(true); - try { - const scanned = await scanAllRecentProjects(undefined, props.hostOverride); - if (scanned.length > 0 || !props.initialProjects) { - setProjects(scanned); - } - } - finally { - setIsLoading(false); - } - }; - useEffect(() => { - if (!props.initialProjects) { - void handleRescan(); - } - }, []); - const filteredProjects = useMemo(() => filterProjectEntries(projects, searchText, selectedEditor), [projects, searchText, selectedEditor]); - const handleOpenInEditor = async (item) => { - const res = await launchProjectInEditor(item, props.hostOverride); - if (!res.ok) { - await showToast({ - style: Toast.Style.Failure, - title: '无法打开该项目', - message: res.error - }); - return; - } - await showToast({ - style: Toast.Style.Success, - title: `正在使用 ${item.editorName} 打开 ${item.name}` - }); - }; - const handleCleanGhostProjects = async () => { - const missingCount = projects.filter((p) => p.isMissing).length; - setProjects((prev) => prev.filter((p) => !p.isMissing)); - await showToast({ - style: Toast.Style.Success, - title: `已清理 ${missingCount} 条失效项目记录` - }); - }; - return (React.createElement(List, { isLoading: isLoading, searchText: searchText, onSearchTextChange: setSearchText, searchBarPlaceholder: "\u641C\u7D22\u9879\u76EE\u540D\u3001\u8DEF\u5F84\u3001Git \u5206\u652F\u6216\u7F16\u8F91\u5668 (\u5982: ztools\u3001main\u3001cursor) ...", searchBarAccessory: React.createElement(List.Dropdown, { value: selectedEditor, onChange: (v) => setSelectedEditor(v), tooltip: "\u6309\u7F16\u8F91\u5668\u7B5B\u9009" }, - React.createElement(List.Dropdown.Item, { title: "\u5168\u90E8\u7F16\u8F91\u5668\u9879\u76EE", value: "all", icon: Icon.Folder }), - React.createElement(List.Dropdown.Item, { title: "VS Code \u5BB6\u65CF (Code / Cursor / Trae)", value: "vsc-family", icon: Icon.Code }), - React.createElement(List.Dropdown.Item, { title: "JetBrains \u5BB6\u65CF (IDEA / WebStorm \u7B49)", value: "jetbrains", icon: Icon.Terminal })), filterBar: { - summaryText: `共发现 ${filteredProjects.length} 个本地项目 · 支持回车秒开 IDE、Ctrl+Enter 唤起终端`, - actions: [ - { id: 'refresh', title: '重新扫描', onAction: handleRescan }, - { id: 'clean-ghost', title: '清理失效记录', onAction: handleCleanGhostProjects } - ] - } }, filteredProjects.map((item) => (React.createElement(List.Item, { key: `${item.editorType}:${item.path}`, id: `${item.editorType}:${item.path}`, title: item.name, subtitle: item.displayPath, icon: getEditorIcon(item.editorType), accessories: [ - ...(item.gitBranch ? [{ tag: `git:${item.gitBranch}` }] : []), - item.isMissing ? { tag: '路径已失效' } : { tag: item.editorName }, - { text: item.lastOpenedRelative } - ], actions: React.createElement(ActionPanel, null, - React.createElement(Action, { title: `用 ${item.editorName} 打开项目`, icon: Icon.Desktop, onAction: () => handleOpenInEditor(item) }), - React.createElement(Action.CopyToClipboard, { title: "\u590D\u5236\u9879\u76EE\u7EDD\u5BF9\u8DEF\u5F84", content: item.path, shortcut: { modifiers: ['cmd'], key: 'c' } }), - item.gitBranch ? (React.createElement(Action.CopyToClipboard, { title: "\u590D\u5236 Git \u5206\u652F\u540D", content: item.gitBranch, shortcut: { modifiers: ['cmd', 'shift'], key: 'c' } })) : null, - React.createElement(Action, { title: "\u6E05\u7406\u5931\u6548\u9879\u76EE\u8BB0\u5F55", icon: Icon.Trash, onAction: handleCleanGhostProjects })) }))))); -} -export default VscodeProjectsCommand; diff --git a/packages/declarative-ui/dist/examples/vscode-projects/project-service.d.ts b/packages/declarative-ui/dist/examples/vscode-projects/project-service.d.ts deleted file mode 100644 index 36668a52..00000000 --- a/packages/declarative-ui/dist/examples/vscode-projects/project-service.d.ts +++ /dev/null @@ -1,22 +0,0 @@ -import type { EditorFilterGroup, ProjectEntry, SupportedEditor } from './types.js'; -export declare function formatRelativeTime(lastOpenedMs: number, nowMs?: number): string; -export declare function normalizeFileUriToPath(rawUriOrPath: string): string; -/** - * 解析 VS Code / Cursor / Trae / Windsurf `history.recentlyOpenedPathsList` JSON 结构 - */ -export declare function parseVscRecentlyOpenedJson(jsonStr: string, editorType?: SupportedEditor, baseTimestampMs?: number): ProjectEntry[]; -/** - * 解析 JetBrains `options/recentProjects.xml` 结构 - */ -export declare function parseJetBrainsRecentProjectsXml(xmlStr: string, editorType?: SupportedEditor, userHome?: string, nowMs?: number): ProjectEntry[]; -/** - * 解析 `.git/HEAD` 文本提取分支名或短 Commit Hash - */ -export declare function parseGitHeadContent(headContent: string): string | undefined; -export declare function mergeAndSortProjects(lists: ProjectEntry[][], nowMs?: number): ProjectEntry[]; -export declare function filterProjectEntries(projects: ProjectEntry[], searchText: string, editorFilter?: EditorFilterGroup): ProjectEntry[]; -export declare function scanAllRecentProjects(rawEntries?: Array>, hostOverride?: unknown): Promise; -export declare function launchProjectInEditor(item: ProjectEntry, hostOverride?: unknown): Promise<{ - ok: boolean; - error?: string; -}>; diff --git a/packages/declarative-ui/dist/examples/vscode-projects/project-service.js b/packages/declarative-ui/dist/examples/vscode-projects/project-service.js deleted file mode 100644 index 4c329c01..00000000 --- a/packages/declarative-ui/dist/examples/vscode-projects/project-service.js +++ /dev/null @@ -1,197 +0,0 @@ -import { callHostTransport } from '../shared/native-ipc.js'; -const EDITOR_NAMES = { - vscode: 'VS Code', - cursor: 'Cursor', - trae: 'Trae', - windsurf: 'Windsurf', - idea: 'IntelliJ IDEA', - webstorm: 'WebStorm', - pycharm: 'PyCharm', - goland: 'GoLand' -}; -export function formatRelativeTime(lastOpenedMs, nowMs = Date.now()) { - const diffSec = Math.max(0, Math.floor((nowMs - lastOpenedMs) / 1000)); - if (diffSec < 60) - return '刚刚打开'; - const diffMin = Math.floor(diffSec / 60); - if (diffMin < 60) - return `${diffMin} 分钟前`; - const diffHour = Math.floor(diffMin / 60); - if (diffHour < 24) - return `${diffHour} 小时前`; - const diffDay = Math.floor(diffHour / 24); - return `${diffDay} 天前`; -} -export function normalizeFileUriToPath(rawUriOrPath) { - const trimmed = String(rawUriOrPath ?? '').trim(); - if (!trimmed) - return ''; - if (trimmed.startsWith('file:///')) { - try { - const decoded = decodeURIComponent(trimmed.slice('file:///'.length)); - if (/^[a-zA-Z]:/.test(decoded)) { - return decoded.replace(/\//g, '\\'); - } - return '/' + decoded; - } - catch { - return trimmed.replace(/^file:\/\/\//, ''); - } - } - return trimmed; -} -/** - * 解析 VS Code / Cursor / Trae / Windsurf `history.recentlyOpenedPathsList` JSON 结构 - */ -export function parseVscRecentlyOpenedJson(jsonStr, editorType = 'vscode', baseTimestampMs = Date.now()) { - if (!jsonStr || !jsonStr.trim()) - return []; - try { - const parsed = JSON.parse(jsonStr); - if (!parsed || !Array.isArray(parsed.entries)) - return []; - const results = []; - parsed.entries.forEach((entry, idx) => { - const rawUri = entry.folderUri || entry.workspace?.configPath || entry.fileUri || ''; - const fsPath = normalizeFileUriToPath(rawUri); - if (!fsPath) - return; - const name = entry.label || fsPath.split(/[\\/]/).filter(Boolean).pop() || fsPath; - const lastOpenedMs = baseTimestampMs - idx * 60_000; - results.push({ - name, - path: fsPath, - displayPath: fsPath, - editorType, - editorName: EDITOR_NAMES[editorType] || 'VS Code', - lastOpenedMs, - lastOpenedRelative: formatRelativeTime(lastOpenedMs, baseTimestampMs), - isMissing: false - }); - }); - return results; - } - catch { - return []; - } -} -/** - * 解析 JetBrains `options/recentProjects.xml` 结构 - */ -export function parseJetBrainsRecentProjectsXml(xmlStr, editorType = 'idea', userHome = 'C:\\Users\\Developer', nowMs = Date.now()) { - if (!xmlStr || !xmlStr.trim()) - return []; - const entries = []; - const entryRegex = //gi; - for (const match of xmlStr.matchAll(entryRegex)) { - const rawKey = match[1] || ''; - const block = match[0] || ''; - if (!rawKey) - continue; - const fsPath = rawKey.replace(/\$USER_HOME\$/g, userHome).replace(/\//g, '\\'); - const tsMatch = block.match(/name="(?:projectOpenTimestamp|activationTimestamp)"\s+value="(\d+)"/i); - const lastOpenedMs = tsMatch?.[1] ? Number(tsMatch[1]) : nowMs - entries.length * 120_000; - const name = fsPath.split(/[\\/]/).filter(Boolean).pop() || fsPath; - entries.push({ - name, - path: fsPath, - displayPath: fsPath, - editorType, - editorName: EDITOR_NAMES[editorType] || 'JetBrains', - lastOpenedMs, - lastOpenedRelative: formatRelativeTime(lastOpenedMs, nowMs), - isMissing: false - }); - } - return entries; -} -/** - * 解析 `.git/HEAD` 文本提取分支名或短 Commit Hash - */ -export function parseGitHeadContent(headContent) { - const trimmed = String(headContent ?? '').trim(); - if (!trimmed) - return undefined; - if (trimmed.startsWith('ref: refs/heads/')) { - return trimmed.slice('ref: refs/heads/'.length).trim(); - } - if (/^[0-9a-fA-F]{7,40}$/.test(trimmed)) { - return trimmed.slice(0, 7); - } - return undefined; -} -export function mergeAndSortProjects(lists, nowMs = Date.now()) { - const seen = new Map(); - for (const list of lists) { - for (const item of list) { - const key = `${item.editorType}:${item.path.toLowerCase()}`; - const existing = seen.get(key); - if (!existing || item.lastOpenedMs > existing.lastOpenedMs) { - seen.set(key, { - ...item, - lastOpenedRelative: formatRelativeTime(item.lastOpenedMs, nowMs) - }); - } - } - } - return Array.from(seen.values()).sort((a, b) => b.lastOpenedMs - a.lastOpenedMs); -} -export function filterProjectEntries(projects, searchText, editorFilter = 'all') { - const vscSet = new Set(['vscode', 'cursor', 'trae', 'windsurf']); - const jbSet = new Set(['idea', 'webstorm', 'pycharm', 'goland']); - const byEditor = projects.filter((p) => { - if (editorFilter === 'vsc-family') - return vscSet.has(p.editorType); - if (editorFilter === 'jetbrains') - return jbSet.has(p.editorType); - return true; - }); - const q = String(searchText ?? '').trim().toLowerCase(); - if (!q) - return byEditor; - return byEditor.filter((p) => p.name.toLowerCase().includes(q) || - p.path.toLowerCase().includes(q) || - p.editorName.toLowerCase().includes(q) || - (p.gitBranch && p.gitBranch.toLowerCase().includes(q))); -} -export async function scanAllRecentProjects(rawEntries, hostOverride) { - const res = await callHostTransport('dllplugin_call', { - plugin: 'VscodeProjectsPlugin', - func: 'scanAllRecentProjects', - params: rawEntries ? { rawEntries } : {} - }, hostOverride); - const rawList = res.data?.projects ?? []; - const nowMs = Date.now(); - return rawList.map((r) => { - const lastOpenedMs = Number(r.lastOpenedMs || nowMs); - const p = String(r.path || ''); - return { - name: String(r.name || p.split(/[\\/]/).pop() || p), - path: p, - displayPath: p, - editorType: r.editorType || 'vscode', - editorName: String(r.editorName || 'VS Code'), - lastOpenedMs, - lastOpenedRelative: formatRelativeTime(lastOpenedMs, nowMs), - gitBranch: typeof r.gitBranch === 'string' ? r.gitBranch : undefined, - isMissing: Boolean(r.isMissing) - }; - }); -} -export async function launchProjectInEditor(item, hostOverride) { - if (item.isMissing) { - return { - ok: false, - error: `PROJECT_PATH_MISSING: 项目路径已失效或被移除 (${item.path})` - }; - } - const res = await callHostTransport('dllplugin_call', { - plugin: 'VscodeProjectsPlugin', - func: 'launchProject', - params: { path: item.path, editor: item.editorType } - }, hostOverride); - if (!res.ok) { - return { ok: false, error: res.error || res.data?.error || '打开项目失败' }; - } - return { ok: true }; -} diff --git a/packages/declarative-ui/dist/examples/vscode-projects/types.d.ts b/packages/declarative-ui/dist/examples/vscode-projects/types.d.ts deleted file mode 100644 index 1083501d..00000000 --- a/packages/declarative-ui/dist/examples/vscode-projects/types.d.ts +++ /dev/null @@ -1,13 +0,0 @@ -export type SupportedEditor = 'vscode' | 'cursor' | 'trae' | 'windsurf' | 'idea' | 'webstorm' | 'pycharm' | 'goland'; -export type EditorFilterGroup = 'all' | 'vsc-family' | 'jetbrains'; -export interface ProjectEntry { - name: string; - path: string; - displayPath: string; - editorType: SupportedEditor; - editorName: string; - lastOpenedMs: number; - lastOpenedRelative: string; - gitBranch?: string; - isMissing: boolean; -} diff --git a/packages/declarative-ui/dist/examples/vscode-projects/types.js b/packages/declarative-ui/dist/examples/vscode-projects/types.js deleted file mode 100644 index cb0ff5c3..00000000 --- a/packages/declarative-ui/dist/examples/vscode-projects/types.js +++ /dev/null @@ -1 +0,0 @@ -export {}; diff --git a/packages/declarative-ui/dist/examples/web-searches/index.d.ts b/packages/declarative-ui/dist/examples/web-searches/index.d.ts deleted file mode 100644 index ba09856e..00000000 --- a/packages/declarative-ui/dist/examples/web-searches/index.d.ts +++ /dev/null @@ -1,86 +0,0 @@ -/** - * Web Searches, Browser Tab & Contacts (全网多引擎搜索、活动浏览器标签页嗅探与本地通讯录中枢) - * - * 深度对齐 Raycast 官方 `web-searches` + `browser` + `contacts` 套件: - * - 多源搜索引擎秒级直达:Google, GitHub, 知乎, 哔哩哔哩, StackOverflow, MDN, 百度, DuckDuckGo, npm, PyPI - * - 浏览器活动标签页感知:读取当前 Safari / Chrome / Arc / Edge 前台活动 Tab URL 与标题,一键复制或转为 Markdown 链接 - * - 本地联系人速查与管理:支持姓名/邮箱/电话检索、一键复制与新建/删除联系人 - * - 对接主进程 `web_search`, `url_quick_open`, `browser_get_active_tab`, `contacts_list`, `contacts_create`, `contacts_delete` IPC - */ -export type WebHubViewMode = "all" | "engines" | "browser" | "contacts"; -export interface WebSearchEngine { - readonly id: string; - readonly name: string; - readonly keyword: string; - readonly category: "General" | "Developer" | "Community"; - readonly urlTemplate: string; - readonly homepage: string; - readonly description: string; - readonly isCustom?: boolean; -} -export interface ActiveBrowserTabInfo { - readonly browserName: string; - readonly title: string; - readonly url: string; - readonly capturedAt: number; -} -export interface ContactEntry { - readonly id: string; - readonly name: string; - readonly email: string; - readonly phone: string; - readonly company: string; - readonly role: string; -} -export declare const CUSTOM_ENGINES_STORAGE_KEY = "ztools.web-searches.custom-engines.v1"; -export declare const WEB_SEARCH_ENGINES: readonly WebSearchEngine[]; -export declare const DEFAULT_CONTACTS: readonly ContactEntry[]; -export declare function loadCustomSearchEngines(): Promise; -export declare function saveCustomSearchEngine(input: { - name: string; - keyword: string; - urlTemplate: string; - category?: "General" | "Developer" | "Community"; - description?: string; -}): Promise; -export declare function buildSearchTargetUrl(engine: WebSearchEngine, query: string): string; -export declare const buildSearchUrl: typeof buildSearchTargetUrl; -export declare function performWebSearch(engineOrId: string | WebSearchEngine, query?: string, hostOverride?: any): Promise<{ - ok: boolean; - url: string; - engineName: string; - error?: string; -}>; -export declare const triggerWebSearch: typeof performWebSearch; -export declare function quickOpenUrl(url: string, hostOverride?: any): Promise<{ - ok: boolean; - url: string; - error?: string; -}>; -export declare function fetchActiveBrowserTab(hostOverride?: any): Promise; -export declare const fetchActiveBrowserTabs: typeof fetchActiveBrowserTab; -export declare function fetchContactsList(query?: string, hostOverride?: any): Promise; -export declare const searchSystemContacts: typeof fetchContactsList; -export declare function createContactEntry(input: { - name: string; - email: string; - phone?: string; - company?: string; - role?: string; -}, hostOverride?: any): Promise; -export declare function deleteContactEntry(id: string, hostOverride?: any): Promise; -export declare const performContactAction: typeof deleteContactEntry; -/** - * 自定义添加搜索引擎表单 (
) - */ -export declare function CreateWebSearchForm({ onCreated }: { - onCreated?: (engine: WebSearchEngine) => void; -}): JSX.Element; -/** - * 新建联系人表单 () - */ -export declare function CreateContactForm({ onCreated }: { - onCreated?: (contact: ContactEntry) => void; -}): JSX.Element; -export declare function WebSearchesCommand(): JSX.Element; -export default WebSearchesCommand; diff --git a/packages/declarative-ui/dist/examples/web-searches/index.js b/packages/declarative-ui/dist/examples/web-searches/index.js deleted file mode 100644 index 1074135c..00000000 --- a/packages/declarative-ui/dist/examples/web-searches/index.js +++ /dev/null @@ -1,565 +0,0 @@ -/** - * Web Searches, Browser Tab & Contacts (全网多引擎搜索、活动浏览器标签页嗅探与本地通讯录中枢) - * - * 深度对齐 Raycast 官方 `web-searches` + `browser` + `contacts` 套件: - * - 多源搜索引擎秒级直达:Google, GitHub, 知乎, 哔哩哔哩, StackOverflow, MDN, 百度, DuckDuckGo, npm, PyPI - * - 浏览器活动标签页感知:读取当前 Safari / Chrome / Arc / Edge 前台活动 Tab URL 与标题,一键复制或转为 Markdown 链接 - * - 本地联系人速查与管理:支持姓名/邮箱/电话检索、一键复制与新建/删除联系人 - * - 对接主进程 `web_search`, `url_quick_open`, `browser_get_active_tab`, `contacts_list`, `contacts_create`, `contacts_delete` IPC - */ -import React from "../../index.js"; -import { List, Form, ActionPanel, Action, Icon, Clipboard, LocalStorage, open, showToast, Toast, useNavigation } from "../../index.js"; -import { useState, useEffect, useMemo } from "../../runtime/hooks.js"; -import { callHostTransport, isRealElectronHost } from "../shared/native-ipc.js"; -export const CUSTOM_ENGINES_STORAGE_KEY = "ztools.web-searches.custom-engines.v1"; -export const WEB_SEARCH_ENGINES = Object.freeze([ - { - id: "google", - name: "Google 搜索", - keyword: "g", - category: "General", - urlTemplate: "https://www.google.com/search?q={query}", - homepage: "https://www.google.com", - description: "全球首选通用搜索引擎" - }, - { - id: "github", - name: "GitHub 代码与仓库搜索", - keyword: "gh", - category: "Developer", - urlTemplate: "https://github.com/search?q={query}&type=repositories", - homepage: "https://github.com", - description: "检索全球开源项目、Issues 与代码片段" - }, - { - id: "stackoverflow", - name: "Stack Overflow 技术问答", - keyword: "so", - category: "Developer", - urlTemplate: "https://stackoverflow.com/search?q={query}", - homepage: "https://stackoverflow.com", - description: "开发者疑难问题与高赞解答检索" - }, - { - id: "mdn", - name: "MDN Web Docs", - keyword: "mdn", - category: "Developer", - urlTemplate: "https://developer.mozilla.org/zh-CN/search?q={query}", - homepage: "https://developer.mozilla.org", - description: "Web 标准、JavaScript、CSS 与 DOM 权威文档" - }, - { - id: "zhihu", - name: "知乎 (Zhihu)", - keyword: "zh", - category: "Community", - urlTemplate: "https://www.zhihu.com/search?type=content&q={query}", - homepage: "https://www.zhihu.com", - description: "中文深度技术专栏与行业讨论检索" - }, - { - id: "bilibili", - name: "哔哩哔哩 (Bilibili)", - keyword: "bili", - category: "Community", - urlTemplate: "https://search.bilibili.com/all?keyword={query}", - homepage: "https://www.bilibili.com", - description: "技术教程、极客评测与开源分享视频检索" - }, - { - id: "duckduckgo", - name: "DuckDuckGo 隐私搜索", - keyword: "ddg", - category: "General", - urlTemplate: "https://duckduckgo.com/?q={query}", - homepage: "https://duckduckgo.com", - description: "零追踪极客隐私搜索引擎" - }, - { - id: "baidu", - name: "百度搜索 (Baidu)", - keyword: "bd", - category: "General", - urlTemplate: "https://www.baidu.com/s?wd={query}", - homepage: "https://www.baidu.com", - description: "国内网页与资讯快速搜索" - } -]); -export const DEFAULT_CONTACTS = Object.freeze([ - { - id: "contact-linus", - name: "Linus Dev", - email: "linus@ztools.dev", - phone: "+86 138-0013-8001", - company: "ZTools Core Team", - role: "Principal Systems Architect" - }, - { - id: "contact-ada", - name: "Ada Lovelace", - email: "ada@ztools.dev", - phone: "+86 139-0013-9002", - company: "ZTools AI Lab", - role: "Lead Declarative UI Engineer" - }, - { - id: "contact-grace", - name: "Grace Hopper", - email: "grace@ztools.dev", - phone: "+86 137-0013-7003", - company: "ZTools Security", - role: "Compiler & Sidecar Specialist" - } -]); -let memoryContacts = [...DEFAULT_CONTACTS]; -let memoryCustomEngines = []; -export async function loadCustomSearchEngines() { - try { - const raw = await LocalStorage.getItem(CUSTOM_ENGINES_STORAGE_KEY); - if (typeof raw === "string" && raw.trim()) { - const parsed = JSON.parse(raw); - if (Array.isArray(parsed)) { - memoryCustomEngines = parsed; - return [...memoryCustomEngines]; - } - } - else if (Array.isArray(raw)) { - memoryCustomEngines = raw; - return [...memoryCustomEngines]; - } - } - catch { - // ignore - } - return [...memoryCustomEngines]; -} -export async function saveCustomSearchEngine(input) { - const cleanName = (input.name || "").trim(); - const cleanTemplate = (input.urlTemplate || "").trim(); - if (!cleanName) { - throw new Error("ENGINE_NAME_REQUIRED: 搜索引擎名称不能为空"); - } - if (!cleanTemplate || !/^https?:\/\//i.test(cleanTemplate)) { - throw new Error("INVALID_URL_TEMPLATE: URL 模板必须以 http:// 或 https:// 开头"); - } - const normalizedTemplate = cleanTemplate.includes("{query}") - ? cleanTemplate - : `${cleanTemplate}${cleanTemplate.includes("?") ? "&q={query}" : "?q={query}"}`; - let homepage = cleanTemplate; - try { - homepage = new URL(cleanTemplate.replace("{query}", "")).origin; - } - catch { - homepage = cleanTemplate.split("?")[0] || cleanTemplate; - } - const engine = { - id: `custom-${Date.now()}`, - name: cleanName, - keyword: (input.keyword || cleanName.slice(0, 3)).trim().toLowerCase(), - category: input.category || "General", - urlTemplate: normalizedTemplate, - homepage, - description: (input.description || "").trim() || `自定义搜索引擎 (${normalizedTemplate})`, - isCustom: true - }; - memoryCustomEngines = [engine, ...memoryCustomEngines.filter((e) => e.id !== engine.id)]; - await LocalStorage.setItem(CUSTOM_ENGINES_STORAGE_KEY, JSON.stringify(memoryCustomEngines)); - return engine; -} -export function buildSearchTargetUrl(engine, query) { - const clean = (query || "").trim(); - if (!clean) - return engine.homepage; - return engine.urlTemplate.replace("{query}", encodeURIComponent(clean)); -} -export const buildSearchUrl = buildSearchTargetUrl; -/** - * 通过宿主在系统浏览器打开网址。 - * 优先 shell_open_external(失败会报错);旧宿主缺少该方法时退回 url_quick_open, - * 它打开失败时不报错而是返回 { opened: false },必须检查。 - */ -async function openUrlViaHost(url, hostOverride) { - const ext = await callHostTransport("shell_open_external", { url }, hostOverride); - if (ext.ok && ext.data?.opened !== false) - return { ok: true }; - const quick = await callHostTransport("url_quick_open", { url }, hostOverride); - if (quick.ok && quick.data?.opened !== false) - return { ok: true }; - return { ok: false, error: quick.error || ext.error || "浏览器没有打开该网址" }; -} -async function openUrl(url, hostOverride) { - if (hostOverride || isRealElectronHost()) - return openUrlViaHost(url, hostOverride); - try { - await open(url); - return { ok: true }; - } - catch (err) { - return { ok: false, error: err instanceof Error ? err.message : String(err) }; - } -} -export async function performWebSearch(engineOrId, query = "", hostOverride) { - const allEngines = [...memoryCustomEngines, ...WEB_SEARCH_ENGINES]; - const engine = typeof engineOrId === "object" && engineOrId !== null - ? engineOrId - : allEngines.find((e) => e.id === engineOrId || e.keyword === engineOrId) || - WEB_SEARCH_ENGINES[0]; - // 按引擎自己的 URL 模板直接打开;不走宿主 web_search(只认内置引擎,自定义引擎会被换成别的搜索) - const url = buildSearchTargetUrl(engine, query); - const opened = await openUrl(url, hostOverride); - if (!opened.ok) - return { ok: false, url, engineName: engine.name, error: opened.error }; - return { ok: true, url, engineName: engine.name }; -} -export const triggerWebSearch = performWebSearch; -export async function quickOpenUrl(url, hostOverride) { - const clean = (url || "").trim(); - if (!clean) - return { ok: false, url: "" }; - const normalizedUrl = /^https?:\/\//i.test(clean) ? clean : `https://${clean}`; - const opened = await openUrl(normalizedUrl, hostOverride); - if (!opened.ok) - return { ok: false, url: normalizedUrl, error: opened.error || "无法打开链接" }; - return { ok: true, url: normalizedUrl }; -} -export async function fetchActiveBrowserTab(hostOverride) { - const realHost = isRealElectronHost(hostOverride); - if (hostOverride || realHost) { - const res = await callHostTransport("browser_get_active_tab", {}, hostOverride); - if (res.ok && res.data) { - const d = res.data; - const url = String(d.url || "").trim(); - if (url) { - return { - browserName: String(d.browserName || d.browser || "Browser"), - title: String(d.title || url), - url, - capturedAt: Date.now() - }; - } - } - if (realHost) { - return null; - } - } - return { - browserName: "Google Chrome / Safari", - title: "ZTools — Open-Source Cross-Platform Efficiency Hub", - url: "https://github.com/ZToolsTeam/ZTools", - capturedAt: Date.now() - }; -} -export const fetchActiveBrowserTabs = fetchActiveBrowserTab; -export async function fetchContactsList(query = "", hostOverride) { - const realHost = isRealElectronHost(hostOverride); - if (hostOverride || realHost) { - const res = await callHostTransport("contacts_list", { query: query.trim() }, hostOverride); - const list = Array.isArray(res.data) - ? res.data - : Array.isArray(res.data?.contacts) - ? res.data.contacts - : null; - if (res.ok && list) { - if (list.length > 0 || realHost) { - return list.map((c, idx) => ({ - id: String(c.id || `contact-${idx}`), - name: String(c.name || "Unnamed Contact"), - email: String(c.email || ""), - phone: String(c.phone || ""), - company: String(c.company || "ZTools"), - role: String(c.role || "Member") - })); - } - } - if (realHost) { - return []; - } - } - const q = query.trim().toLowerCase(); - if (!q) - return [...memoryContacts]; - return memoryContacts.filter((c) => c.name.toLowerCase().includes(q) || - c.email.toLowerCase().includes(q) || - c.phone.toLowerCase().includes(q) || - c.company.toLowerCase().includes(q)); -} -export const searchSystemContacts = fetchContactsList; -export async function createContactEntry(input, hostOverride) { - const cleanName = (input.name || "").trim(); - if (!cleanName) { - throw new Error("CONTACT_NAME_REQUIRED: 联系人姓名不能为空"); - } - const created = { - id: `contact-${Date.now()}`, - name: cleanName, - email: (input.email || "").trim(), - phone: (input.phone || "").trim(), - company: (input.company || "").trim() || "ZTools Community", - role: (input.role || "").trim() || "Developer" - }; - if (hostOverride || isRealElectronHost()) { - const res = await callHostTransport("contacts_create", created, hostOverride); - if (res.ok && res.data && res.data.id) { - const persisted = { ...created, id: String(res.data.id) }; - memoryContacts = [persisted, ...memoryContacts]; - return persisted; - } - } - memoryContacts = [created, ...memoryContacts]; - return created; -} -export async function deleteContactEntry(id, hostOverride) { - const cleanId = (id || "").trim(); - if (!cleanId) - return false; - if (hostOverride || isRealElectronHost()) { - await callHostTransport("contacts_delete", { id: cleanId }, hostOverride); - } - memoryContacts = memoryContacts.filter((c) => c.id !== cleanId); - return true; -} -export const performContactAction = deleteContactEntry; -/** - * 自定义添加搜索引擎表单 () - */ -export function CreateWebSearchForm({ onCreated }) { - const [name, setName] = useState(""); - const [keyword, setKeyword] = useState(""); - const [urlTemplate, setUrlTemplate] = useState("https://www.google.com/search?q={query}"); - const [category, setCategory] = useState("Developer"); - const [description, setDescription] = useState(""); - const { pop } = useNavigation(); - const handleSubmit = async (values) => { - try { - const created = await saveCustomSearchEngine({ - name: values?.name ?? name, - keyword: values?.keyword ?? keyword, - urlTemplate: values?.urlTemplate ?? urlTemplate, - category: (values?.category ?? category), - description: values?.description ?? description - }); - onCreated?.(created); - await showToast(Toast.Style.Success, `已添加自定义搜索引擎: ${created.name}`, created.urlTemplate); - pop(); - } - catch (err) { - await showToast(Toast.Style.Failure, "添加搜索引擎失败", err?.message || String(err)); - } - }; - return (React.createElement(Form, { navigationTitle: "\u6DFB\u52A0\u81EA\u5B9A\u4E49\u641C\u7D22\u5F15\u64CE (Add Custom Search Engine)", actions: React.createElement(ActionPanel, null, - React.createElement(Action.SubmitForm, { title: "\u4FDD\u5B58\u81EA\u5B9A\u4E49\u641C\u7D22\u5F15\u64CE", icon: Icon.Check, onSubmit: handleSubmit }), - React.createElement(Action, { title: "\u7ACB\u5373\u4FDD\u5B58", icon: Icon.Plus, onAction: () => handleSubmit() })) }, - React.createElement(Form.TextField, { id: "name", title: "\u641C\u7D22\u5F15\u64CE\u540D\u79F0", placeholder: "\u4F8B\u5982: npm Packages / Cargo Crates / V2EX", value: name, onChange: setName }), - React.createElement(Form.TextField, { id: "keyword", title: "\u5FEB\u6377\u952E\u524D\u7F00 (Keyword)", placeholder: "\u4F8B\u5982: npm / crates / v2", value: keyword, onChange: setKeyword }), - React.createElement(Form.TextField, { id: "urlTemplate", title: "\u641C\u7D22 URL \u6A21\u677F (\u542B {query})", placeholder: "https://www.npmjs.com/search?q={query}", value: urlTemplate, onChange: setUrlTemplate }), - React.createElement(Form.Dropdown, { id: "category", title: "\u6240\u5C5E\u5206\u7C7B", value: category, onChange: (v) => setCategory(v) }, - React.createElement(Form.Dropdown.Item, { value: "Developer", title: "\u5F00\u53D1\u8005\u5DE5\u5177 (Developer)" }), - React.createElement(Form.Dropdown.Item, { value: "General", title: "\u901A\u7528\u641C\u7D22 (General)" }), - React.createElement(Form.Dropdown.Item, { value: "Community", title: "\u6280\u672F\u793E\u533A (Community)" })), - React.createElement(Form.TextField, { id: "description", title: "\u63CF\u8FF0\u8BF4\u660E", placeholder: "\u7B80\u77ED\u63CF\u8FF0\u8BE5\u641C\u7D22\u5F15\u64CE\u7528\u9014...", value: description, onChange: setDescription }))); -} -/** - * 新建联系人表单 () - */ -export function CreateContactForm({ onCreated }) { - const [name, setName] = useState(""); - const [email, setEmail] = useState(""); - const [phone, setPhone] = useState(""); - const [company, setCompany] = useState(""); - const [role, setRole] = useState(""); - const { pop } = useNavigation(); - const handleSubmit = async (values) => { - try { - const created = await createContactEntry({ - name: values?.name ?? name, - email: values?.email ?? email, - phone: values?.phone ?? phone, - company: values?.company ?? company, - role: values?.role ?? role - }); - onCreated?.(created); - await showToast(Toast.Style.Success, `已添加联系人: ${created.name}`); - pop(); - } - catch (err) { - await showToast(Toast.Style.Failure, "添加联系人失败", err?.message || String(err)); - } - }; - return (React.createElement(Form, { navigationTitle: "\u65B0\u5EFA\u8054\u7CFB\u4EBA (Create Contact)", actions: React.createElement(ActionPanel, null, - React.createElement(Action.SubmitForm, { title: "\u4FDD\u5B58\u8054\u7CFB\u4EBA", icon: Icon.Check, onSubmit: handleSubmit }), - React.createElement(Action, { title: "\u4FDD\u5B58\u8054\u7CFB\u4EBA", icon: Icon.Check, onAction: () => handleSubmit() })) }, - React.createElement(Form.TextField, { id: "name", title: "\u59D3\u540D", placeholder: "\u8F93\u5165\u8054\u7CFB\u4EBA\u59D3\u540D", value: name, onChange: setName }), - React.createElement(Form.TextField, { id: "email", title: "\u7535\u5B50\u90AE\u7BB1", placeholder: "user@example.com", value: email, onChange: setEmail }), - React.createElement(Form.TextField, { id: "phone", title: "\u7535\u8BDD\u53F7\u7801", placeholder: "+86 138-0000-0000", value: phone, onChange: setPhone }), - React.createElement(Form.TextField, { id: "company", title: "\u6240\u5C5E\u7EC4\u7EC7/\u516C\u53F8", placeholder: "ZTools", value: company, onChange: setCompany }), - React.createElement(Form.TextField, { id: "role", title: "\u804C\u4F4D/\u89D2\u8272", placeholder: "Engineer", value: role, onChange: setRole }))); -} -export function WebSearchesCommand() { - const realHost = isRealElectronHost(); - const [searchText, setSearchText] = useState(""); - const [mode, setMode] = useState("all"); - const [selectedId, setSelectedId] = useState(null); - const [customEngines, setCustomEngines] = useState([]); - const { push } = useNavigation(); - const [activeTab, setActiveTab] = useState(() => realHost - ? null - : { - browserName: "Safari / Chrome", - title: "ZTools — Open-Source Cross-Platform Efficiency Hub", - url: "https://github.com/ZToolsTeam/ZTools", - capturedAt: Date.now() - }); - const [contacts, setContacts] = useState(() => realHost ? [] : [...DEFAULT_CONTACTS]); - useEffect(() => { - let active = true; - loadCustomSearchEngines().then((loaded) => { - if (active) - setCustomEngines(loaded); - }); - return () => { - active = false; - }; - }, []); - useEffect(() => { - let active = true; - Promise.all([fetchActiveBrowserTab(), fetchContactsList(searchText)]).then(([tabInfo, contactList]) => { - if (!active) - return; - setActiveTab(tabInfo); - setContacts(contactList); - }); - return () => { - active = false; - }; - }, [searchText]); - // 所有搜索引擎(自定义引擎置顶 + 官方内置引擎):输入 searchText 时绝不过滤掉搜索引擎! - const allEngines = useMemo(() => [...customEngines, ...WEB_SEARCH_ENGINES], [customEngines]); - const showBrowser = (mode === "all" || mode === "browser") && activeTab !== null; - const showEngines = mode === "all" || mode === "engines"; - const showContacts = mode === "all" || mode === "contacts"; - const trimmedQuery = searchText.trim(); - const handleRefreshBrowserTab = async () => { - const [tabInfo, contactList] = await Promise.all([ - fetchActiveBrowserTab(), - fetchContactsList(searchText) - ]); - setActiveTab(tabInfo); - setContacts(contactList); - await showToast(Toast.Style.Success, "已刷新浏览器当前标签页与通讯录", tabInfo ? `${tabInfo.browserName}: ${tabInfo.title}` : undefined); - }; - return (React.createElement(List, { isShowingDetail: true, searchBarPlaceholder: "\u8F93\u5165\u641C\u7D22\u8BCD\u5B9E\u65F6\u7528 Google/GitHub/\u77E5\u4E4E/B\u7AD9 \u641C\u7D22\uFF0C\u6216\u6DFB\u52A0\u81EA\u5B9A\u4E49\u641C\u7D22\u5F15\u64CE\u4E0E\u8054\u7CFB\u4EBA...", onSearchTextChange: setSearchText, onSelectionChange: setSelectedId, filterBar: { - summaryText: `全网搜索与通讯中枢 · 已配置 ${allEngines.length} 个搜索引擎 | 活动标签页: ${activeTab ? activeTab.browserName : "无"} | 本地联系人: ${contacts.length} 人`, - actions: [ - { - id: "add-custom-search-engine", - label: "添加自定义搜索引擎", - title: "添加自定义搜索引擎", - style: "secondary", - onAction: () => { - push(React.createElement(CreateWebSearchForm, { onCreated: (engine) => setCustomEngines((prev) => [engine, ...prev]) })); - } - }, - { - id: "refresh-browser-tab", - label: "刷新当前浏览器标签页", - title: "刷新当前浏览器标签页", - style: "secondary", - onAction: handleRefreshBrowserTab - } - ] - }, searchBarAccessory: React.createElement(List.Dropdown, { tooltip: "\u5207\u6362\u68C0\u7D22\u89C6\u56FE", value: mode, onChange: (v) => setMode(v) }, - React.createElement(List.Dropdown.Item, { title: "\u5168\u7F51\u641C\u7D22\u4E0E\u6D4F\u89C8\u5668\u4E2D\u67A2 (All)", value: "all", icon: Icon.Globe }), - React.createElement(List.Dropdown.Item, { title: `多源搜索引擎 (Web Search Engines · ${allEngines.length})`, value: "engines", icon: Icon.MagnifyingGlass }), - React.createElement(List.Dropdown.Item, { title: "\u5F53\u524D\u6D4F\u89C8\u5668\u6D3B\u52A8\u6807\u7B7E\u9875 (Active Browser Tab)", value: "browser", icon: Icon.Link }), - React.createElement(List.Dropdown.Item, { title: `通讯录联系人 (Contacts · ${contacts.length})`, value: "contacts", icon: Icon.Person })), actions: React.createElement(ActionPanel, { title: "\u5168\u7F51\u641C\u7D22\u4E0E\u901A\u8BAF\u5F55\u64CD\u4F5C" }, - React.createElement(Action.Push, { title: "\u6DFB\u52A0\u81EA\u5B9A\u4E49\u641C\u7D22\u5F15\u64CE (Add Custom Search Engine)", icon: Icon.Plus, target: React.createElement(CreateWebSearchForm, { onCreated: (engine) => setCustomEngines((prev) => [engine, ...prev]) }) }), - React.createElement(Action.Push, { title: "\u65B0\u5EFA\u8054\u7CFB\u4EBA (Create Contact)", icon: Icon.Person, target: React.createElement(CreateContactForm, { onCreated: (created) => setContacts((prev) => [created, ...prev]) }) })) }, - showEngines && (React.createElement(List.Section, { title: `多源搜索引擎直达 (Web Searches · ${allEngines.length})` }, allEngines.map((engine) => { - const targetUrl = trimmedQuery - ? engine.urlTemplate.replace("{query}", encodeURIComponent(trimmedQuery)) - : engine.urlTemplate; - const itemTitle = trimmedQuery - ? `用 ${engine.name} 搜索 "${trimmedQuery}"` - : engine.name; - const itemSubtitle = trimmedQuery - ? targetUrl - : `${engine.description} (!${engine.keyword}) • ${engine.urlTemplate}`; - return (React.createElement(List.Item, { key: engine.id, id: engine.id, title: itemTitle, subtitle: itemSubtitle, keywords: trimmedQuery - ? [trimmedQuery, engine.name, engine.keyword, engine.category] - : [engine.name, engine.keyword, engine.category], icon: Icon.MagnifyingGlass, accessories: [ - { text: `!${engine.keyword}` }, - { text: engine.isCustom ? "Custom" : engine.category } - ], detail: React.createElement(List.Item.Detail, { markdown: [ - `# 🔍 ${itemTitle}`, - `> **快捷指令前缀**: \`!${engine.keyword}\`  |  **分类**: \`${engine.category}\``, - `---`, - `${engine.description}`, - `### 实时目标 URL (按 Enter 直接在浏览器打开)`, - `\`\`\`text\n${trimmedQuery ? targetUrl : engine.urlTemplate}\n\`\`\``, - trimmedQuery - ? `- [立即点击打开: ${targetUrl}](${targetUrl})` - : `- **默认主页**: [${engine.homepage}](${engine.homepage})` - ].join("\n\n") }), actions: React.createElement(ActionPanel, { title: engine.name }, - React.createElement(Action, { title: trimmedQuery - ? `用 ${engine.name} 搜索 "${trimmedQuery}"` - : `打开 ${engine.name} 主页`, icon: Icon.MagnifyingGlass, onAction: async () => { - const res = await performWebSearch(engine, trimmedQuery); - if (!res.ok) { - await showToast(Toast.Style.Failure, "搜索页面未打开", res.error); - return; - } - await showToast(Toast.Style.Success, `已通过 ${res.engineName} 打开搜索`, res.url); - } }), - React.createElement(Action.Push, { title: "\u6DFB\u52A0\u81EA\u5B9A\u4E49\u641C\u7D22\u5F15\u64CE (Add Custom Search Engine)", icon: Icon.Plus, shortcut: { modifiers: ["ctrl"], key: "e" }, target: React.createElement(CreateWebSearchForm, { onCreated: (created) => setCustomEngines((prev) => [created, ...prev]) }) }), - React.createElement(Action.Push, { title: "\u65B0\u5EFA\u8054\u7CFB\u4EBA (Create Contact)", icon: Icon.Person, shortcut: { modifiers: ["ctrl"], key: "n" }, target: React.createElement(CreateContactForm, { onCreated: (created) => setContacts((prev) => [created, ...prev]) }) }), - React.createElement(Action, { title: "\u590D\u5236\u76EE\u6807\u641C\u7D22 URL", icon: Icon.CopyClipboard, shortcut: { modifiers: ["ctrl"], key: "c" }, onAction: async () => { - const urlToCopy = buildSearchTargetUrl(engine, trimmedQuery); - await Clipboard.copy(urlToCopy); - await showToast(Toast.Style.Success, "已复制搜索链接", urlToCopy); - } })) })); - }))), - showBrowser && activeTab && (React.createElement(List.Section, { title: "\u5F53\u524D\u6D4F\u89C8\u5668\u6D3B\u52A8\u6807\u7B7E\u9875 (Active Browser Tab)" }, - React.createElement(List.Item, { key: "active-browser-tab", id: "active-browser-tab", title: activeTab.title, subtitle: `${activeTab.browserName} • ${activeTab.url}`, keywords: trimmedQuery ? [trimmedQuery, activeTab.title, activeTab.url] : undefined, icon: Icon.Globe, accessories: [{ text: activeTab.browserName, icon: Icon.Link }], detail: React.createElement(List.Item.Detail, { markdown: [ - `# 🌐 ${activeTab.title}`, - `> **来源浏览器**: \`${activeTab.browserName}\``, - `---`, - `- **当前 URL**: [${activeTab.url}](${activeTab.url})`, - `- **Markdown 引用**: \`[${activeTab.title}](${activeTab.url})\`` - ].join("\n\n") }), actions: React.createElement(ActionPanel, { title: "\u5F53\u524D\u6D4F\u89C8\u5668\u6807\u7B7E\u9875" }, - React.createElement(Action, { title: "\u590D\u5236\u5F53\u524D\u9875\u9762 URL", icon: Icon.CopyClipboard, onAction: async () => { - await Clipboard.copy(activeTab.url); - await showToast(Toast.Style.Success, "已复制当前浏览器活动 Tab URL", activeTab.url); - } }), - React.createElement(Action, { title: "\u590D\u5236\u4E3A Markdown \u94FE\u63A5", icon: Icon.Link, shortcut: { modifiers: ["ctrl"], key: "m" }, onAction: async () => { - const md = `[${activeTab.title}](${activeTab.url})`; - await Clipboard.copy(md); - await showToast(Toast.Style.Success, "已复制 Markdown 链接", md); - } }), - React.createElement(Action.OpenInBrowser, { title: "\u5728\u9ED8\u8BA4\u6D4F\u89C8\u5668\u4E2D\u91CD\u65B0\u6253\u5F00", url: activeTab.url }), - React.createElement(Action.Push, { title: "\u6DFB\u52A0\u81EA\u5B9A\u4E49\u641C\u7D22\u5F15\u64CE (Add Custom Search Engine)", icon: Icon.Plus, target: React.createElement(CreateWebSearchForm, { onCreated: (created) => setCustomEngines((prev) => [created, ...prev]) }) }), - React.createElement(Action.Push, { title: "\u65B0\u5EFA\u8054\u7CFB\u4EBA (Create Contact)", icon: Icon.Person, target: React.createElement(CreateContactForm, { onCreated: (created) => setContacts((prev) => [created, ...prev]) }) })) }))), - showContacts && (React.createElement(List.Section, { title: `本地通讯录速查 (Contacts · ${contacts.length})` }, contacts.map((c) => (React.createElement(List.Item, { key: c.id, id: c.id, title: c.name, subtitle: `${c.role} @ ${c.company} • ${c.email}`, icon: Icon.Person, accessories: [{ text: c.phone }], detail: React.createElement(List.Item.Detail, { markdown: [ - `# 👤 ${c.name}`, - `> **${c.role}** • \`${c.company}\``, - `---`, - `- **电子邮箱**: \`${c.email}\``, - `- **联系电话**: \`${c.phone}\`` - ].join("\n\n") }), actions: React.createElement(ActionPanel, { title: c.name }, - React.createElement(Action, { title: "\u590D\u5236\u7535\u5B50\u90AE\u7BB1", icon: Icon.CopyClipboard, onAction: async () => { - await Clipboard.copy(c.email); - await showToast(Toast.Style.Success, "已复制邮箱", c.email); - } }), - React.createElement(Action, { title: "\u590D\u5236\u7535\u8BDD\u53F7\u7801", icon: Icon.Clipboard, onAction: async () => { - await Clipboard.copy(c.phone); - await showToast(Toast.Style.Success, "已复制电话号码", c.phone); - } }), - React.createElement(Action.Push, { title: "\u65B0\u5EFA\u8054\u7CFB\u4EBA (Create Contact)", icon: Icon.Plus, shortcut: { modifiers: ["ctrl"], key: "n" }, target: React.createElement(CreateContactForm, { onCreated: (created) => setContacts((prev) => [created, ...prev]) }) }), - React.createElement(Action.Push, { title: "\u6DFB\u52A0\u81EA\u5B9A\u4E49\u641C\u7D22\u5F15\u64CE (Add Custom Search Engine)", icon: Icon.MagnifyingGlass, target: React.createElement(CreateWebSearchForm, { onCreated: (created) => setCustomEngines((prev) => [created, ...prev]) }) }), - React.createElement(Action, { title: "\u5220\u9664\u8054\u7CFB\u4EBA", icon: Icon.Trash, style: Action.Style.Destructive, onAction: async () => { - await deleteContactEntry(c.id); - setContacts((prev) => prev.filter((item) => item.id !== c.id)); - await showToast(Toast.Style.Success, `已删除联系人: ${c.name}`); - } })) }))))))); -} -export default WebSearchesCommand; diff --git a/packages/declarative-ui/dist/examples/wechat-cleaner/index.d.ts b/packages/declarative-ui/dist/examples/wechat-cleaner/index.d.ts deleted file mode 100644 index b03b6595..00000000 --- a/packages/declarative-ui/dist/examples/wechat-cleaner/index.d.ts +++ /dev/null @@ -1 +0,0 @@ -export default function WechatCleanerCommand(): import("../../index.js").ViewDescriptor; diff --git a/packages/declarative-ui/dist/examples/wechat-cleaner/index.js b/packages/declarative-ui/dist/examples/wechat-cleaner/index.js deleted file mode 100644 index d5cf82f9..00000000 --- a/packages/declarative-ui/dist/examples/wechat-cleaner/index.js +++ /dev/null @@ -1,464 +0,0 @@ -import { List, ActionPanel, Action, Icon, useState, useEffect, showToast, Toast, confirmAlert } from '../../index.js'; -import { OFFICIAL_WECHAT_OWNER_RULES, FORBIDDEN_REASON, formatBytes, formatDateTime, fetchWechatCleanSnapshot, executeWechatCleanup, openWechatDirectory, openWechatFileDefault, isRealElectronHost } from './logic.js'; -const INIT_WECHAT_FILES = [ - { - id: 'wx-init-107', - name: 'sns_timeline_cache_01.data', - path: '%USERPROFILE%\\AppData\\Roaming\\Tencent\\xwechat\\radium\\web\\sns_timeline_cache_01.data', - parentDir: '%USERPROFILE%\\AppData\\Roaming\\Tencent\\xwechat\\radium\\web', - ownerId: 107, - ownerName: '朋友圈/网页缓存', - accountId: 'wxid_geek001', - sizeBytes: 320 * 1024 * 1024, - mtime: 1710000000, - isProtected: false - }, - { - id: 'wx-init-115', - name: 'WeChatAppEx_Runtime_8555.pak', - path: '%USERPROFILE%\\AppData\\Roaming\\Tencent\\xwechat\\xplugin\\Plugins\\WeChatAppEx_Runtime_8555.pak', - parentDir: '%USERPROFILE%\\AppData\\Roaming\\Tencent\\xwechat\\xplugin\\Plugins', - ownerId: 115, - ownerName: '小程序/XPlugin', - accountId: '公共组件 (Shared)', - sizeBytes: 245 * 1024 * 1024, - mtime: 1710000000, - isProtected: false - }, - { - id: 'wx-init-113', - name: 'mm_20261018.xlog', - path: '%USERPROFILE%\\AppData\\Roaming\\Tencent\\xwechat\\log\\mm_20261018.xlog', - parentDir: '%USERPROFILE%\\AppData\\Roaming\\Tencent\\xwechat\\log', - ownerId: 113, - ownerName: '运行跟踪日志 (.xlog)', - accountId: '公共组件 (Shared)', - sizeBytes: 128 * 1024 * 1024, - mtime: 1710000000, - isProtected: false - }, - { - id: 'wx-init-999', - name: 'message_0.db', - path: '%USERPROFILE%\\Documents\\xwechat_files\\wxid_geek001\\db_storage\\message\\message_0.db', - parentDir: '%USERPROFILE%\\Documents\\xwechat_files\\wxid_geek001\\db_storage\\message', - ownerId: 999, - ownerName: '核心聊天数据库 (受保护)', - accountId: 'wxid_geek001', - sizeBytes: 96 * 1024 * 1024, - mtime: 1710000000, - isProtected: true - } -]; -function buildInitialCategories() { - const sourceFiles = isRealElectronHost() ? [] : INIT_WECHAT_FILES; - return OFFICIAL_WECHAT_OWNER_RULES.map(rule => { - const catFiles = sourceFiles.filter(f => f.ownerId === rule.ownerId); - const totalSizeBytes = catFiles.reduce((s, f) => s + f.sizeBytes, 0); - return { - id: rule.id, - ownerId: rule.ownerId, - name: rule.name, - shortName: rule.shortName, - color: rule.color, - category: rule.category, - riskLevel: rule.riskLevel, - safetyLevel: rule.riskLevel, - targetDir: catFiles[0]?.parentDir || '%USERPROFILE%\\Documents\\xwechat_files', - existsOnDisk: catFiles.length > 0, - fileCount: catFiles.length, - totalSizeBytes, - checked: rule.defaultChecked && rule.ownerId !== 999 && totalSizeBytes > 0, - sampleFiles: catFiles.map(f => ({ - path: f.path, - sizeBytes: f.sizeBytes, - mtime: f.mtime, - accountId: f.accountId - })), - files: catFiles, - description: rule.description - }; - }); -} -export default function WechatCleanerCommand() { - const inRealHost = isRealElectronHost(); - const [searchText, setSearchText] = useState(''); - const [tab, setTab] = useState('all'); - const [wizardStep, setWizardStep] = useState('filter'); - const [selectedAccount, setSelectedAccount] = useState('ALL'); - const [selectedTimeRange, setSelectedTimeRange] = useState('ALL'); - const [selectedOwnerId, setSelectedOwnerId] = useState('ALL'); - const [categories, setCategories] = useState(() => buildInitialCategories()); - const [allFiles, setAllFiles] = useState(() => inRealHost ? [] : INIT_WECHAT_FILES); - const [accountStats, setAccountStats] = useState(() => inRealHost - ? [] - : [ - { - accountId: 'wxid_geek001', - label: '微信号: wxid_geek001', - rootDir: '%USERPROFILE%\\Documents\\xwechat_files\\wxid_geek001', - fileCount: 2, - totalBytes: 416 * 1024 * 1024 - } - ]); - const [accounts, setAccounts] = useState(() => (inRealHost ? [] : ['wxid_geek001'])); - const [selectedFilePaths, setSelectedFilePaths] = useState(() => inRealHost ? [] : INIT_WECHAT_FILES.filter(f => !f.isProtected).map(f => f.path)); - const [lastCleanSummary, setLastCleanSummary] = useState(null); - const [diskFree, setDiskFree] = useState(inRealHost ? 0 : 64 * 1024 * 1024 * 1024); - const [diskTotal, setDiskTotal] = useState(inRealHost ? 0 : 256 * 1024 * 1024 * 1024); - const [protectedDbBytes, setProtectedDbBytes] = useState(inRealHost ? 0 : 96 * 1024 * 1024); - const [isLoading, setIsLoading] = useState(true); - async function refreshScan(showIndicator = false) { - if (showIndicator) { - setIsLoading(true); - setWizardStep('scan'); - showToast({ - style: Toast.Style.Animated, - title: '正在执行微信 9 大专项深度扫描 (Owner 107~115)...', - message: '穿透扫描 xwechat_files、AppData\\Roaming\\Tencent\\xwechat 与 WeType 日志,锁定保护 db_storage' - }); - } - try { - const snap = await fetchWechatCleanSnapshot(); - if (isRealElectronHost() || snap.allFiles.length > 0) { - setCategories(snap.categories); - setAllFiles(snap.allFiles); - setAccountStats(snap.accountStats); - setAccounts(snap.detectedAccounts); - setDiskFree(snap.systemDiskFreeBytes); - setDiskTotal(snap.systemDiskTotalBytes); - setProtectedDbBytes(snap.protectedDbBytes); - const defaultCheckedOwners = new Set(snap.categories.filter(c => c.checked && c.ownerId !== 999).map(c => c.ownerId)); - const initialCheckedPaths = snap.allFiles - .filter(f => !f.isProtected && defaultCheckedOwners.has(f.ownerId)) - .map(f => f.path); - setSelectedFilePaths(initialCheckedPaths); - } - setWizardStep('filter'); - if (showIndicator) { - showToast({ - style: Toast.Style.Success, - title: '微信 9 大专项扫描完成', - message: `发现可释放空间 ${formatBytes(snap.totalScannableBytes)},已自动锁定保护聊天库 ${formatBytes(snap.protectedDbBytes)}` - }); - } - } - finally { - setIsLoading(false); - } - } - useEffect(() => { - refreshScan(false); - }, []); - const nowSec = Math.floor(Date.now() / 1000); - const cutoffSec = selectedTimeRange === '7D' - ? nowSec - 7 * 86400 - : selectedTimeRange === '30D' - ? nowSec - 30 * 86400 - : selectedTimeRange === '180D' - ? nowSec - 180 * 86400 - : 0; - const q = searchText.trim().toLowerCase(); - const matchAccountAndTime = (f) => { - if (selectedAccount !== 'ALL' && f.accountId !== selectedAccount) - return false; - if (cutoffSec > 0 && f.mtime > cutoffSec) - return false; - return true; - }; - const scopedFiles = allFiles.filter(matchAccountAndTime); - const filteredFiles = scopedFiles - .filter(f => { - if (selectedOwnerId !== 'ALL' && String(f.ownerId) !== selectedOwnerId) - return false; - if (!q) - return true; - return (f.name.toLowerCase().includes(q) || - f.path.toLowerCase().includes(q) || - f.ownerName.toLowerCase().includes(q) || - f.accountId.toLowerCase().includes(q)); - }) - .sort((a, b) => b.sizeBytes - a.sizeBytes); - const selectedSet = new Set(selectedFilePaths); - const selectableScopedFiles = filteredFiles.filter(f => !f.isProtected); - const allScopedChecked = selectableScopedFiles.length > 0 && selectableScopedFiles.every(f => selectedSet.has(f.path)); - const someScopedChecked = selectableScopedFiles.some(f => selectedSet.has(f.path)) && !allScopedChecked; - const checkedCategoryBytes = categories - .filter(c => c.ownerId !== 999) - .reduce((acc, cat) => { - const catSelectable = cat.files.filter(f => !f.isProtected && matchAccountAndTime(f)); - const catChecked = catSelectable.filter(f => selectedSet.has(f.path)); - if (catChecked.length === 0) - return acc; - if (selectedAccount === 'ALL' && - selectedTimeRange === 'ALL' && - catChecked.length === catSelectable.length) { - return acc + cat.totalSizeBytes; - } - return acc + catChecked.reduce((s, f) => s + f.sizeBytes, 0); - }, 0); - const checkedFileCount = allFiles.filter(f => !f.isProtected && matchAccountAndTime(f) && selectedSet.has(f.path)).length; - function toggleSingleFile(filePath, nextChecked) { - setSelectedFilePaths(prev => { - const next = new Set(prev); - if (nextChecked) - next.add(filePath); - else - next.delete(filePath); - return Array.from(next); - }); - } - function toggleAllFilteredFiles() { - if (selectableScopedFiles.length === 0) - return; - setSelectedFilePaths(prev => { - const next = new Set(prev); - if (allScopedChecked) { - for (const f of selectableScopedFiles) - next.delete(f.path); - } - else { - for (const f of selectableScopedFiles) - next.add(f.path); - } - return Array.from(next); - }); - } - async function handleCleanChecked() { - const targetFiles = allFiles.filter(f => !f.isProtected && matchAccountAndTime(f) && selectedSet.has(f.path)); - if (targetFiles.length === 0 && checkedCategoryBytes <= 0) { - showToast({ - style: Toast.Style.Failure, - title: '暂无已勾选的待清理项', - message: '请先勾选需要清理的 9 大专项分类或具体缓存文件' - }); - return; - } - setWizardStep('review'); - const breakdownLines = categories - .filter(c => c.ownerId !== 999) - .map(c => { - const cnt = c.files.filter(f => !f.isProtected && matchAccountAndTime(f) && selectedSet.has(f.path)).length; - if (cnt === 0) - return null; - return `- ${c.shortName}: ${cnt} 个样本文件 (专项总计 ${formatBytes(c.totalSizeBytes)})`; - }) - .filter(Boolean) - .join('\n'); - const confirmed = await confirmAlert({ - title: '步骤 4/4:微信专项清理核对确认', - message: `当前筛选维度:\n- 微信账号: ${selectedAccount === 'ALL' ? '全部账号' : selectedAccount}\n- 预计释放总空间: ${formatBytes(checkedCategoryBytes)} (涉及 ${targetFiles.length} 个已选文件)\n\n专项明细:\n${breakdownLines}\n\n硬件级安全锁:${FORBIDDEN_REASON}`, - primaryAction: { - title: `确认安全移入回收站 (${formatBytes(checkedCategoryBytes)})`, - style: 'destructive' - } - }); - if (!confirmed) { - setWizardStep('filter'); - return; - } - const res = await executeWechatCleanup(categories, undefined, targetFiles.map(f => f.path)); - setLastCleanSummary({ - deletedCount: res.deletedCount, - freedBytes: res.freedBytes - }); - setWizardStep('done'); - showToast({ - style: Toast.Style.Success, - title: '微信专项清理完成', - message: `已安全移入回收站 ${res.deletedCount} 个文件,释放 ${formatBytes(res.freedBytes)}` - }); - if (res.deletedPaths.length > 0) { - const removed = new Set(res.deletedPaths); - setAllFiles(prev => prev.filter(f => !removed.has(f.path))); - setSelectedFilePaths(prev => prev.filter(p => !removed.has(p))); - } - } - function renderFileDetailMarkdown(f) { - const isChecked = selectedSet.has(f.path); - return `# ${f.name} - -**完整物理路径**: \`${f.path}\` - ---- - -### 微信文件多维画像 -- **文件真实大小**: \`${formatBytes(f.sizeBytes)}\` (\`${f.sizeBytes.toLocaleString()} Bytes\`) -- **所属 9 大专项**: **${f.ownerName}** (\`Owner #${f.ownerId}\`) -- **归属微信号 / 组件**: \`${f.accountId}\` -- **最后修改日期**: \`${formatDateTime(f.mtime)}\` -- **所在父目录**: \`${f.parentDir}\` -- **安全与勾选状态**: ${f.isProtected - ? '核心聊天数据库文件 (受硬件级防误删锁保护)' - : isChecked - ? '已勾选纳入待清理队列' - : '未勾选'} -`; - } - const totalScannable = categories - .filter(c => c.ownerId !== 999) - .reduce((s, c) => s + c.totalSizeBytes, 0); - const distributionSegments = categories - .filter(c => c.ownerId !== 999 && c.totalSizeBytes > 0) - .map(c => ({ - id: String(c.ownerId), - label: c.shortName, - color: c.color, - sizeBytes: c.totalSizeBytes, - formattedSize: formatBytes(c.totalSizeBytes), - percent: totalScannable > 0 - ? Math.max(1, Math.round((c.totalSizeBytes / totalScannable) * 100)) - : 0, - count: c.fileCount - })); - const maxFileBytes = Math.max(1, filteredFiles[0]?.sizeBytes || 1); - const rightSubListItems = filteredFiles.slice(0, 60).map(f => { - const isChecked = !f.isProtected && selectedSet.has(f.path); - const volRatio = Math.max(10, Math.min(100, Math.round((f.sizeBytes / maxFileBytes) * 100))); - const isDbProtected = f.isProtected || f.ownerId === 999; - return List.Item({ - id: f.id, - title: f.name, - subtitle: isDbProtected - ? `${f.accountId} · 微信核心聊天记录数据库严禁清理 · ${f.parentDir}` - : `${f.accountId} · ${formatDateTime(f.mtime)} · ${f.parentDir}`, - checkable: !isDbProtected, - checked: isChecked, - lockedReason: isDbProtected ? '微信核心聊天记录数据库严禁清理' : undefined, - onCheckChange: (c) => toggleSingleFile(f.path, c), - onToggleCheck: (c) => toggleSingleFile(f.path, c), - icon: { - source: isDbProtected ? Icon.Lock : Icon.Document - }, - accessories: [ - { progress: { value: volRatio } }, - { tag: { value: isDbProtected ? '聊天库锁定' : f.ownerName } }, - { text: formatBytes(f.sizeBytes) } - ], - detail: List.Item.Detail({ - markdown: renderFileDetailMarkdown(f) - }), - actions: ActionPanel({ - title: f.name, - children: [ - Action({ - title: `清理已勾选微信缓存 (${formatBytes(checkedCategoryBytes)})`, - icon: Icon.Trash, - style: Action.Style.Destructive, - onAction: () => handleCleanChecked() - }), - Action({ - title: '在资源管理器定位', - icon: Icon.Folder, - onAction: () => { - openWechatDirectory(f.path); - } - }), - ...(!isDbProtected - ? [ - Action({ - title: isChecked ? '取消勾选此文件' : '勾选此文件', - icon: Icon.Checkmark, - onAction: () => toggleSingleFile(f.path, !isChecked) - }) - ] - : []), - Action({ - title: '使用默认程序打开文件', - icon: Icon.AppWindow, - onAction: () => { - openWechatFileDefault(f.path); - } - }), - Action.CopyToClipboard({ - title: '复制文件完整路径', - content: f.path - }) - ] - }) - }); - }); - const activeCategory = categories.find(c => String(c.ownerId) === selectedOwnerId); - const rightTitle = activeCategory - ? `${activeCategory.name} 文件明细 (按体积降序,直接勾选或按 ↵ 执行)` - : '全部微信专项缓存与保护库明细 (按体积降序,直接勾选或按 ↵ 执行)'; - return List({ - searchBarPlaceholder: '搜索微信 9 大专项 (朋友圈/小程序/XLog/崩溃Dmp/表情包)、微信号或文件名...', - onSearchTextChange: setSearchText, - isShowingDetail: false, - isLoading, - searchBarAccessory: List.Dropdown({ - tooltip: '切换微信账号 (wxid)', - value: selectedAccount, - onChange: val => setSelectedAccount(val), - children: [ - List.Dropdown.Item({ - title: `全部微信账号 (${allFiles.length})`, - value: 'ALL' - }), - ...accountStats.map(acc => List.Dropdown.Item({ - title: `${acc.accountId} (${formatBytes(acc.totalBytes)})`, - value: acc.accountId - })) - ] - }), - filterBar: { - summaryText: `微信号 [${selectedAccount === 'ALL' ? '全部账号' : selectedAccount}] · 可释放 ${formatBytes(totalScannable)} · 已勾选 ${checkedFileCount} 项 (${formatBytes(checkedCategoryBytes)}) · 保护库已锁定 ${formatBytes(protectedDbBytes)}`, - actions: [ - { - id: 'wx-act-rescan', - label: '重新扫描', - title: '重新扫描', - style: 'secondary', - onAction: () => refreshScan(true) - } - ] - }, - subList: { - title: rightTitle, - subtitle: `${filteredFiles.length} 项 · 已选 ${checkedFileCount} 项 (${formatBytes(checkedCategoryBytes)})`, - checkable: selectableScopedFiles.length > 0, - checked: allScopedChecked ? true : someScopedChecked ? 'indeterminate' : false, - onCheckChange: () => toggleAllFilteredFiles(), - emptyText: '当前选中的微信账号与专项分类下暂无匹配文件', - items: rightSubListItems - }, - children: [ - List.Section({ - title: '微信存储总览', - children: [ - List.Item({ - id: 'wx-nav-all', - title: '全部微信文件汇总', - subtitle: `${allFiles.length} 个采样文件 · 可清理 ${formatBytes(totalScannable)}`, - icon: { source: Icon.HardDrive }, - accessories: [{ text: formatBytes(totalScannable) }], - onSelect: () => { - setSelectedOwnerId('ALL'); - setTab('all'); - } - }) - ] - }), - List.Section({ - title: '9 大官方专项分类 + 数据库保护区', - children: categories.map(cat => { - const isProtected = cat.ownerId === 999; - return List.Item({ - id: `wx-nav-owner-${cat.ownerId}`, - title: cat.shortName, - subtitle: isProtected - ? '核心聊天记录库 (安全锁定)' - : `Owner #${cat.ownerId} · ${cat.fileCount} 项`, - icon: { source: isProtected ? Icon.Lock : Icon.Folder }, - accessories: [{ text: formatBytes(cat.totalSizeBytes) }], - onSelect: () => { - setSelectedOwnerId(String(cat.ownerId)); - setTab(isProtected ? 'protected' : 'files'); - } - }); - }) - }) - ] - }); -} diff --git a/packages/declarative-ui/dist/examples/wechat-cleaner/logic.d.ts b/packages/declarative-ui/dist/examples/wechat-cleaner/logic.d.ts deleted file mode 100644 index ae06d4cc..00000000 --- a/packages/declarative-ui/dist/examples/wechat-cleaner/logic.d.ts +++ /dev/null @@ -1,134 +0,0 @@ -/** - * 微信专项深度清理业务逻辑与真实环境契约层 (WechatCleaner Logic) - * 与 Windows 原生插件 wechat-cleaner 的清理规则一致:9 大专项清理分类 (owner 107~115): - * - 穿透扫描 Documents\xwechat_files、WeChat Files、AppData\Roaming\Tencent\xwechat (含多盘符自定义存储目录与符号链接穿透) 与 LocalLow\TENCENT\WeType - * - 严格保护聊天文字数据库 (MSG*.db / MicroMsg.db / db_storage\*.db) - * - 支持多微信账号 (wxid) 维度与修改时间范围 (全部/7天前/30天前/半年前) 多维过滤及三级复选框联动 - */ -export { formatBytes, isRealElectronHost } from '../shared/native-ipc.js'; -export interface CapabilityActionItem { - id: string; - title: string; - subtitle: string; - tag: string; - method: string; - params: Record; -} -export interface NativeInvocationResult { - ok: boolean; - pluginName: string; - method: string; - data?: unknown; - error?: string; - fromFallback?: boolean; -} -export type WechatOwnerId = 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 999; -export interface WechatScannedFileEntry { - id: string; - name: string; - path: string; - parentDir: string; - ownerId: WechatOwnerId; - ownerName: string; - accountId: string; - sizeBytes: number; - mtime: number; - isProtected: boolean; -} -export interface WechatCleanCategoryItem { - id: string; - ownerId: WechatOwnerId; - name: string; - shortName: string; - color: string; - category: 'cache' | 'media' | 'files' | 'logs' | 'protected'; - riskLevel: 'safe' | 'recommended' | 'caution' | 'protected'; - safetyLevel?: 'safe' | 'recommended' | 'caution' | 'protected'; - targetDir: string; - existsOnDisk: boolean; - fileCount: number; - totalSizeBytes: number; - checked: boolean; - sampleFiles: Array<{ - path: string; - sizeBytes: number; - mtime?: number; - accountId?: string; - }>; - files: WechatScannedFileEntry[]; - description: string; -} -export interface WechatAccountStat { - accountId: string; - label: string; - rootDir: string; - fileCount: number; - totalBytes: number; -} -export interface WechatScanSnapshot { - baseDirectories: string[]; - detectedAccounts: string[]; - accountStats: WechatAccountStat[]; - categories: WechatCleanCategoryItem[]; - allFiles: WechatScannedFileEntry[]; - totalScannableBytes: number; - checkedBytes: number; - protectedDbBytes: number; - systemDiskFreeBytes: number; - systemDiskTotalBytes: number; - wechatRunning: boolean; - wechatVersionLabel: string; -} -export declare const DLL_PLUGIN_NAME = "WechatCleanerPlugin"; -export declare const FORBIDDEN_TARGET_PATTERN: RegExp; -export declare const FORBIDDEN_REASON = "\u5FAE\u4FE1\u6838\u5FC3\u804A\u5929\u6587\u5B57\u4E0E\u8054\u7CFB\u4EBA\u6570\u636E\u5E93 (MSG.db / MicroMsg.db / db_storage/*.db) \u53D7\u5230\u4E25\u683C\u786C\u4EF6\u7EA7\u4FDD\u62A4\uFF0C\u4E25\u7981\u7EB3\u5165\u6E05\u7406\u8303\u56F4"; -export interface OfficialWechatOwnerRule { - ownerId: WechatOwnerId; - id: string; - name: string; - shortName: string; - color: string; - category: WechatCleanCategoryItem['category']; - riskLevel: WechatCleanCategoryItem['riskLevel']; - defaultChecked: boolean; - description: string; -} -/** - * 9 大专项清理分类 (owner 107~115) + 1 项核心聊天数据库保护区 (999) - */ -export declare const OFFICIAL_WECHAT_OWNER_RULES: OfficialWechatOwnerRule[]; -export declare function getCapabilityItems(): CapabilityActionItem[]; -export declare function filterCapabilityItems(items: CapabilityActionItem[], query: string): CapabilityActionItem[]; -export declare function formatDateTime(mtimeSeconds: number): string; -export declare function validateInvocationPayload(method: string, params: unknown): { - valid: boolean; - error?: string; -}; -export declare function invokeNativeCapability(method: string, params: Record, hostBridge?: any): Promise; -/** - * 根据微信文件的完整真实路径,将其精准归入 9 大专项分类 (107~115) 或 999 聊天数据库保护区, - * 并提取所属微信号 (accountId) - */ -export declare function classifyWechatFilePath(fullPath: string, knownAccounts: string[]): { - ownerId: WechatOwnerId; - accountId: string; - isProtected: boolean; -}; -/** - * 探测并深度扫描本机真实微信存储路径、微信号账号、9 大专项分类与聊天数据库保护区 - */ -export declare function fetchWechatCleanSnapshot(hostOverride?: any): Promise; -/** - * 执行微信缓存安全清理(严格拦截聊天数据库文件,走真实回收站移除) - */ -export declare function executeWechatCleanup(categoriesOrPaths: WechatCleanCategoryItem[] | string[], hostOverride?: any, explicitFilePaths?: string[]): Promise<{ - ok: boolean; - deletedCount: number; - freedBytes: number; - skippedProtected: number; - deletedPaths: string[]; - skippedPaths: string[]; - error?: string; -}>; -export declare function openWechatDirectory(dirPath: string, hostOverride?: any): Promise; -export declare function openWechatFileDefault(filePath: string, hostOverride?: any): Promise; diff --git a/packages/declarative-ui/dist/examples/wechat-cleaner/logic.js b/packages/declarative-ui/dist/examples/wechat-cleaner/logic.js deleted file mode 100644 index cb05d9bb..00000000 --- a/packages/declarative-ui/dist/examples/wechat-cleaner/logic.js +++ /dev/null @@ -1,696 +0,0 @@ -/** - * 微信专项深度清理业务逻辑与真实环境契约层 (WechatCleaner Logic) - * 与 Windows 原生插件 wechat-cleaner 的清理规则一致:9 大专项清理分类 (owner 107~115): - * - 穿透扫描 Documents\xwechat_files、WeChat Files、AppData\Roaming\Tencent\xwechat (含多盘符自定义存储目录与符号链接穿透) 与 LocalLow\TENCENT\WeType - * - 严格保护聊天文字数据库 (MSG*.db / MicroMsg.db / db_storage\*.db) - * - 支持多微信账号 (wxid) 维度与修改时间范围 (全部/7天前/30天前/半年前) 多维过滤及三级复选框联动 - */ -import { callHostTransport, getRealFileSize, getRealSystemPath, invokeDllPluginCapability, isRealElectronHost, listRealDirectoryContents, probeRealDiskDrives, scanRealDirectoryTree, showRealItemInFolder, trashRealItem, openRealPath } from '../shared/native-ipc.js'; -export { formatBytes, isRealElectronHost } from '../shared/native-ipc.js'; -export const DLL_PLUGIN_NAME = 'WechatCleanerPlugin'; -export const FORBIDDEN_TARGET_PATTERN = new RegExp('(?:^|[\\\\/])(?:MSG\\d*\\.db|MicroMsg\\.db|MediaMsg\\d*\\.db|db_storage[\\\\/].*\\.db(?:-wal|-shm)?|message_\\d+\\.db|contact\\.db|session\\.db)$', 'i'); -export const FORBIDDEN_REASON = '微信核心聊天文字与联系人数据库 (MSG.db / MicroMsg.db / db_storage/*.db) 受到严格硬件级保护,严禁纳入清理范围'; -/** - * 9 大专项清理分类 (owner 107~115) + 1 项核心聊天数据库保护区 (999) - */ -export const OFFICIAL_WECHAT_OWNER_RULES = [ - { - ownerId: 107, - id: 'wx-owner-107-sns-web', - name: '朋友圈与公众号网页缓存 (Owner #107)', - shortName: '朋友圈/网页缓存', - color: '#64748b', - category: 'cache', - riskLevel: 'safe', - defaultChecked: true, - description: '朋友圈动态流图片/视频缓存、内置浏览器网页缓存 (xwechat/radium/Users、FileStorage/Sns & Cache),清理后不影响聊天记录' - }, - { - ownerId: 115, - id: 'wx-owner-115-xplugin', - name: '小程序与跨端引擎组件包 (Owner #115)', - shortName: '小程序/XPlugin', - color: '#64748b', - category: 'cache', - riskLevel: 'recommended', - defaultChecked: true, - description: '微信小程序历史版本包、RadiumWMPF 跨端引擎运行时与 XPlugin 插件缓存 (xwechat/xplugin/Plugins),按需自动重下' - }, - { - ownerId: 113, - id: 'wx-owner-113-xlog', - name: '微信运行跟踪与输入法日志 (Owner #113)', - shortName: '运行跟踪日志 (.xlog)', - color: '#64748b', - category: 'logs', - riskLevel: 'safe', - defaultChecked: true, - description: '微信每日生成的加密诊断跟踪日志 (xwechat/log/*.xlog) 与微信输入法运行日志 (WeType/*.xlog),体积巨大且可100%安全清理' - }, - { - ownerId: 112, - id: 'wx-owner-112-crash', - name: '崩溃转储与诊断快照 (Owner #112)', - shortName: '崩溃转储 (.dmp)', - color: '#64748b', - category: 'logs', - riskLevel: 'safe', - defaultChecked: true, - description: '微信与小程序进程异常退出时生成的内存转储快照 (crashinfo/WeChatAppEx_*.dmp、Weixin_*.dmp),可放心清理' - }, - { - ownerId: 111, - id: 'wx-owner-111-emoticon', - name: '表情包与动态贴纸缓存 (Owner #111)', - shortName: '表情包与资源缓存', - color: '#64748b', - category: 'media', - riskLevel: 'safe', - defaultChecked: true, - description: '群聊自动加载的动态表情包缓存、聊天气泡资源与临时缩略图 (business/emoticon、resource、FileStorage/Temp)' - }, - { - ownerId: 114, - id: 'wx-owner-114-update', - name: '版本升级补丁与公共宿主缓存 (Owner #114)', - shortName: '升级补丁/WMPF', - color: '#64748b', - category: 'cache', - riskLevel: 'safe', - defaultChecked: true, - description: '微信客户端热更新残留包、WMPF 公共宿主缓存与网络探针缓存 (xwechat_files/WMPF、all_users、xwechat/net)' - }, - { - ownerId: 109, - id: 'wx-owner-109-video-voice', - name: '聊天视频与语音媒体文件 (Owner #109)', - shortName: '聊天视频/语音', - color: '#64748b', - category: 'media', - riskLevel: 'recommended', - defaultChecked: true, - description: '群聊与私聊中播放过的视频文件、流媒体音视频缓存与语音分片 (msg/video、FileStorage/Video、Media Cache)' - }, - { - ownerId: 108, - id: 'wx-owner-108-chat-images', - name: '聊天加密图片与缩略图附件 (Owner #108)', - shortName: '聊天加密图片 (.dat)', - color: '#64748b', - category: 'media', - riskLevel: 'caution', - defaultChecked: false, - description: '聊天过程中收发的原图加密文件 (.dat) 与附件缩略图 (msg/attach、FileStorage/MsgAttach),清理后过期图片将无法查看原图' - }, - { - ownerId: 110, - id: 'wx-owner-110-recv-files', - name: '聊天接收与自动下载文档 (Owner #110)', - shortName: '聊天接收文件', - color: '#64748b', - category: 'files', - riskLevel: 'caution', - defaultChecked: false, - description: '通过微信接收或自动下载的办公文档、压缩包与工作文件 (msg/file、FileStorage/File),请核对后再勾选清理' - }, - { - ownerId: 999, - id: 'wx-owner-999-protected-db', - name: '核心聊天文字与联系人数据库保护区 (db_storage)', - shortName: '核心聊天数据库 (受保护)', - color: '#64748b', - category: 'protected', - riskLevel: 'protected', - defaultChecked: false, - description: '存放所有聊天文字记录、联系人列表与会话索引的加密 SQLite 数据库 (db_storage/message_0.db、contact.db、MSG.db),硬件级防误删锁定' - } -]; -const PRESET_ITEMS = [ - { - id: 'wx-detect-info', - title: '自动识别本机微信 WeChat Files / xwechat_files 存储目录与微信号', - subtitle: '支持默认文档路径、AppData\\Roaming\\Tencent\\xwechat 与符号链接迁移目录的多账号扫描', - tag: '目录识别', - method: 'GetWechatInfo', - params: {} - }, - { - id: 'wx-scan-cache', - title: '扫描 9 大专项分类 (朋友圈/小程序/XLog/崩溃Dmp/视频/图片/接收文件)', - subtitle: '精准识别 Owner 107~115 下的高占用冗余文件并严格保护聊天数据库', - tag: '专项扫描', - method: 'StartScanAsync', - params: { scope: 'cache_and_video' } - }, - { - id: 'wx-total-stats', - title: '查看各账号分类空间占用统计报告', - subtitle: '按微信号 wxid、时间范围与 9 大专项展示可安全释放容量', - tag: '容量报告', - method: 'GetTotalStats', - params: {} - } -]; -export function getCapabilityItems() { - return PRESET_ITEMS.map(item => ({ - ...item, - params: { ...item.params } - })); -} -export function filterCapabilityItems(items, query) { - if (!Array.isArray(items)) - return []; - const q = typeof query === 'string' ? query.trim().toLowerCase() : ''; - if (!q) - return items; - return items.filter(item => { - if (!item || typeof item.title !== 'string') - return false; - return (item.title.toLowerCase().includes(q) || - item.subtitle.toLowerCase().includes(q) || - item.tag.toLowerCase().includes(q) || - item.method.toLowerCase().includes(q)); - }); -} -export function formatDateTime(mtimeSeconds) { - if (!mtimeSeconds || !Number.isFinite(mtimeSeconds) || mtimeSeconds <= 0) - return '未知日期'; - const ms = mtimeSeconds > 1e12 ? mtimeSeconds : mtimeSeconds * 1000; - const d = new Date(ms); - if (Number.isNaN(d.getTime())) - return '未知日期'; - const yyyy = d.getFullYear(); - const mm = String(d.getMonth() + 1).padStart(2, '0'); - const dd = String(d.getDate()).padStart(2, '0'); - return `${yyyy}-${mm}-${dd}`; -} -export function validateInvocationPayload(method, params) { - if (typeof method !== 'string' || method.trim().length === 0) { - return { valid: false, error: 'INVALID_METHOD: 调用方法名不能为空' }; - } - if (method.length > 128 || !/^[A-Za-z0-9_]+$/.test(method.trim())) { - return { valid: false, error: 'INVALID_METHOD_FORMAT: 方法名包含非法字符或超长' }; - } - if (params === null || params === undefined || typeof params !== 'object' || Array.isArray(params)) { - return { valid: false, error: 'INVALID_PARAMS: 参数必须为非空对象' }; - } - const record = params; - for (const [key, val] of Object.entries(record)) { - if (typeof val === 'string') { - if (val.length > 4096) { - return { valid: false, error: `PARAM_TOO_LONG: 参数 ${key} 超过最大长度限制` }; - } - if (FORBIDDEN_TARGET_PATTERN.test(val)) { - return { valid: false, error: `SECURITY_INTERCEPTED: ${FORBIDDEN_REASON}` }; - } - } - else if (typeof val === 'number') { - if (!Number.isFinite(val) || val < -1000 || val > 100_000_000) { - return { valid: false, error: `PARAM_OUT_OF_RANGE: 数值参数 ${key} 越界或非有限数` }; - } - } - } - return { valid: true }; -} -export async function invokeNativeCapability(method, params, hostBridge) { - const check = validateInvocationPayload(method, params); - if (!check.valid) { - throw new Error(check.error || '参数校验失败'); - } - const res = await invokeDllPluginCapability(DLL_PLUGIN_NAME, method, params, hostBridge); - return { - ok: res.ok, - pluginName: DLL_PLUGIN_NAME, - method: method.trim(), - data: res.data ?? undefined, - error: res.error, - fromFallback: res.fromFallback - }; -} -/** - * 根据微信文件的完整真实路径,将其精准归入 9 大专项分类 (107~115) 或 999 聊天数据库保护区, - * 并提取所属微信号 (accountId) - */ -export function classifyWechatFilePath(fullPath, knownAccounts) { - const norm = fullPath.replace(/\//g, '\\'); - const lower = norm.toLowerCase(); - // 1. 识别所属账号 (wxid / 微信号目录) - let accountId = '公共组件 (Shared)'; - const xwMatch = norm.match(/xwechat_files\\([^\\]+)/i) || norm.match(/WeChat Files\\([^\\]+)/i); - if (xwMatch && xwMatch[1]) { - const seg = xwMatch[1]; - if (!/^(?:all_users|all users|wmpf|applet|backup)$/i.test(seg)) { - accountId = seg; - } - } - else { - const radiumUserMatch = norm.match(/radium\\Users\\([0-9a-f]{16,64})/i); - if (radiumUserMatch && radiumUserMatch[1]) { - const hash = radiumUserMatch[1].toLowerCase(); - const matchedKnown = knownAccounts.find(a => { - const suffix = a.split('_').pop()?.toLowerCase() || ''; - return suffix.length >= 4 && hash.startsWith(suffix); - }); - accountId = matchedKnown || `wx_${hash.slice(0, 8)}`; - } - } - // 2. 判定是否属于受保护的核心聊天数据库 (Owner 999) - if (FORBIDDEN_TARGET_PATTERN.test(norm) || - lower.includes('\\db_storage\\') || - lower.includes('\\msg\\multi\\') || - /\\(?:micromsg|msg\d*|mediamsg\d*|contact|session|message_\d+|head_image|favorite)\.db/i.test(lower)) { - return { ownerId: 999, accountId, isProtected: true }; - } - // 3. 判定 9 大专项清理分类 (Owner 107~115) - if (lower.includes('\\crashinfo\\') || lower.includes('\\crashpad\\') || lower.endsWith('.dmp')) { - return { ownerId: 112, accountId, isProtected: false }; - } - if (lower.includes('\\log\\') || lower.includes('\\wetype\\') || lower.endsWith('.xlog')) { - return { ownerId: 113, accountId, isProtected: false }; - } - if (lower.includes('\\xplugin\\') || lower.includes('\\applet\\') || lower.includes('radiumwmpf')) { - return { ownerId: 115, accountId, isProtected: false }; - } - if (lower.includes('\\emoticon\\') || - lower.includes('\\customemotion\\') || - lower.includes('\\resource\\') || - lower.includes('\\filestorage\\temp\\')) { - return { ownerId: 111, accountId, isProtected: false }; - } - if (lower.includes('\\msg\\attach\\') || - lower.includes('\\filestorage\\msgattach\\') || - lower.includes('\\filestorage\\image\\')) { - return { ownerId: 108, accountId, isProtected: false }; - } - if (lower.includes('\\msg\\video\\') || - lower.includes('\\msg\\voice\\') || - lower.includes('\\filestorage\\video\\') || - lower.includes('\\filestorage\\voice\\') || - lower.includes('\\media cache\\') || - /\.(?:mp4|mov|avi|amr|silk|mp3|wav)$/i.test(lower)) { - return { ownerId: 109, accountId, isProtected: false }; - } - if (lower.includes('\\msg\\file\\') || lower.includes('\\filestorage\\file\\')) { - return { ownerId: 110, accountId, isProtected: false }; - } - if (lower.includes('\\wmpf\\') || - lower.includes('\\all_users\\') || - lower.includes('\\update\\') || - lower.includes('\\xwechat\\net') || - lower.includes('\\xwechat\\roam') || - lower.includes('\\config\\')) { - return { ownerId: 114, accountId, isProtected: false }; - } - // 默认归入 107: 朋友圈与公众号网页/Web缓存 (radium/Users, cache, Sns 等) - return { ownerId: 107, accountId, isProtected: false }; -} -/** - * 探测并深度扫描本机真实微信存储路径、微信号账号、9 大专项分类与聊天数据库保护区 - */ -export async function fetchWechatCleanSnapshot(hostOverride) { - const [documentsDir, appDataDir, homeDir, tempDir, diskRes, mountedDrives] = await Promise.all([ - getRealSystemPath('documents', hostOverride), - getRealSystemPath('appData', hostOverride), - getRealSystemPath('home', hostOverride), - getRealSystemPath('temp', hostOverride), - callHostTransport('system_get_disk_usage', { drive: 'C:/' }, hostOverride), - probeRealDiskDrives(undefined, hostOverride) - ]); - const localAppData = homeDir ? `${homeDir}\\AppData\\Local` : ''; - const localLowAppData = homeDir ? `${homeDir}\\AppData\\LocalLow` : ''; - // 动态组合系统默认路径与各挂载盘符根目录下的微信数据路径 - const driveWechatRoots = mountedDrives.flatMap(d => { - const letter = d.drive.replace(/[\\/]+$/, ''); - return [`${letter}\\WeChat Files`, `${letter}\\xwechat_files`]; - }); - const candidateRoots = [ - documentsDir ? `${documentsDir}\\xwechat_files` : '', - documentsDir ? `${documentsDir}\\WeChat Files` : '', - appDataDir ? `${appDataDir}\\Tencent\\xwechat` : '', - appDataDir ? `${appDataDir}\\Tencent\\WeChat` : '', - ...driveWechatRoots, - localLowAppData ? `${localLowAppData}\\TENCENT\\WeType` : '', - localAppData ? `${localAppData}\\Tencent\\WeChat` : '' - ].filter(Boolean); - // 1. 先探测本机微信号账号目录 - const detectedAccountSet = new Set(); - if (hostOverride || !isRealElectronHost()) { - for (const root of candidateRoots.slice(0, 2)) { - const subDirs = await listRealDirectoryContents(root, hostOverride); - for (const sub of subDirs) { - const name = sub.split(/[\\/]/).pop() || ''; - if (name && - !name.includes('.') && - !/^(?:All Users|all_users|Applet|WMPF|Backup|config)$/i.test(name)) { - detectedAccountSet.add(name); - } - } - } - } - const allFiles = []; - const seenPaths = new Set(); - // 归一化 AppData\Roaming\Tencent 与符号链接路径,避免重复计数 - const canonicalizeWechatKey = (p) => { - const lower = p.replace(/\//g, '\\').toLowerCase(); - const idx = lower.indexOf('\\tencent\\xwechat\\'); - if (idx >= 0) - return lower.slice(idx); - const idx2 = lower.indexOf('\\tencent\\wechat\\'); - if (idx2 >= 0) - return lower.slice(idx2); - return lower; - }; - const registerScannedFile = (fullPath, sizeBytes, mtime = 0) => { - if (!fullPath || sizeBytes <= 0) - return; - const key = canonicalizeWechatKey(fullPath); - if (seenPaths.has(key)) - return; - seenPaths.add(key); - const cleanPath = fullPath.replace(/\//g, '\\'); - const lastSep = cleanPath.lastIndexOf('\\'); - const name = lastSep >= 0 ? cleanPath.slice(lastSep + 1) : cleanPath; - const parentDir = lastSep > 0 ? cleanPath.slice(0, lastSep) : cleanPath; - // 从路径中补充识别账号 - const xwAcc = cleanPath.match(/xwechat_files\\([^\\]+)\\/i); - if (xwAcc && xwAcc[1] && !/^(?:all_users|wmpf|applet|backup)$/i.test(xwAcc[1])) { - detectedAccountSet.add(xwAcc[1]); - } - const knownAccounts = Array.from(detectedAccountSet); - const cls = classifyWechatFilePath(cleanPath, knownAccounts); - if (cls.accountId !== '公共组件 (Shared)') { - detectedAccountSet.add(cls.accountId); - } - const ruleMeta = OFFICIAL_WECHAT_OWNER_RULES.find(r => r.ownerId === cls.ownerId) || - OFFICIAL_WECHAT_OWNER_RULES[0]; - allFiles.push({ - id: `wx-file-${allFiles.length}`, - name, - path: cleanPath, - parentDir, - ownerId: cls.ownerId, - ownerName: ruleMeta.shortName, - accountId: cls.accountId, - sizeBytes, - mtime: mtime || Math.floor(Date.now() / 1000), - isProtected: cls.isProtected - }); - }; - // 2A. 真实 Electron 宿主环境或支持 dir: 深度扫描的测试环境:执行深度目录树扫描 (dir:) - // 同时跟踪各分类的真实全量文件数与真实全量字节数(即使 Top 样本只取前 200 个) - const extraOwnerTotals = new Map(); - const supportsDeepScan = (!hostOverride && isRealElectronHost()) || - typeof hostOverride?.system_search_files === 'function'; - if (supportsDeepScan) { - const deepTargets = [ - ...(documentsDir - ? [ - { dir: `${documentsDir}\\xwechat_files` }, - { dir: `${documentsDir}\\WeChat Files` } - ] - : []), - ...driveWechatRoots.map(dir => ({ dir })), - ...(appDataDir - ? [ - { dir: `${appDataDir}\\Tencent\\xwechat\\radium`, defaultOwner: 107 }, - { dir: `${appDataDir}\\Tencent\\xwechat\\xplugin`, defaultOwner: 115 }, - { dir: `${appDataDir}\\Tencent\\xwechat\\log`, defaultOwner: 113 }, - { dir: `${appDataDir}\\Tencent\\xwechat\\crashinfo`, defaultOwner: 112 }, - { dir: `${appDataDir}\\Tencent\\xwechat\\net`, defaultOwner: 114 } - ] - : []), - ...(localLowAppData - ? [{ dir: `${localLowAppData}\\TENCENT\\WeType`, defaultOwner: 113 }] - : []) - ]; - const seenSubdirTotals = new Set(); - const scanResults = await Promise.all(deepTargets.map(t => scanRealDirectoryTree(t.dir, 150, hostOverride))); - // 先从 xwechat_files / WeChat Files 子目录提取本机微信号账号目录 (如 geek_user_7f67) - for (let i = 0; i < Math.min(2, deepTargets.length); i++) { - const res = scanResults[i]; - if (!res) - continue; - for (const sub of res.subdirs) { - if (sub.name && - !sub.name.includes('.') && - !/^(?:All Users|all_users|Applet|WMPF|Backup|config)$/i.test(sub.name)) { - detectedAccountSet.add(sub.name); - } - } - } - for (let i = 0; i < deepTargets.length; i++) { - const target = deepTargets[i]; - const res = scanResults[i]; - if (!res || (res.files.length === 0 && res.totalFiles === 0)) - continue; - // 从 radium\Users 子目录识别更多微信号 profile - if (target.dir.toLowerCase().endsWith('\\radium')) { - for (const sub of res.subdirs) { - if (sub.name.toLowerCase() === 'users') { - const usersScan = await scanRealDirectoryTree(sub.path, 40, hostOverride); - for (const u of usersScan.subdirs) { - if (/^[0-9a-f]{16,64}$/i.test(u.name)) { - const hash = u.name.toLowerCase(); - const matched = Array.from(detectedAccountSet).find(a => { - const suf = a.split('_').pop()?.toLowerCase() || ''; - return suf.length >= 4 && hash.startsWith(suf); - }); - if (!matched) { - detectedAccountSet.add(`wx_${hash.slice(0, 8)}`); - } - } - } - } - } - } - let sampledBytes = 0; - let sampledCount = 0; - for (const f of res.files) { - if (!f.isDir && f.size > 0) { - const beforeLen = allFiles.length; - registerScannedFile(f.path, f.size, f.mtime); - if (allFiles.length > beforeLen) { - sampledBytes += f.size; - sampledCount += 1; - } - } - } - // 如果该专项子目录真实全量字节数大于 Top 采样字节数,记录真实全量差值以确保统计 100% 精确反映磁盘真实占用 - if (target.defaultOwner) { - const canonDirKey = canonicalizeWechatKey(target.dir); - if (!seenSubdirTotals.has(canonDirKey) && res.totalBytes > sampledBytes) { - seenSubdirTotals.add(canonDirKey); - const cur = extraOwnerTotals.get(target.defaultOwner) || { extraFiles: 0, extraBytes: 0 }; - cur.extraFiles += Math.max(0, res.totalFiles - sampledCount); - cur.extraBytes += Math.max(0, res.totalBytes - sampledBytes); - cur.targetDir = target.dir; - extraOwnerTotals.set(target.defaultOwner, cur); - } - } - } - } - else { - // 2B. 测试环境或自定义 hostOverride 兼容扫描 - const fallbackDirs = [ - appDataDir ? `${appDataDir}\\Tencent\\WeChat` : 'C:\\Users\\Default\\AppData\\Roaming\\Tencent\\WeChat', - appDataDir ? `${appDataDir}\\Tencent\\xwechat` : 'C:\\Users\\Default\\AppData\\Roaming\\Tencent\\xwechat', - documentsDir ? `${documentsDir}\\WeChat Files` : 'C:\\Users\\Default\\Documents\\WeChat Files', - documentsDir ? `${documentsDir}\\xwechat_files` : 'C:\\Users\\Default\\Documents\\xwechat_files', - tempDir || 'C:\\Windows\\Temp' - ]; - for (const d of fallbackDirs) { - const entries = await listRealDirectoryContents(d, hostOverride); - const slice = entries.slice(0, 25); - const sizes = await Promise.all(slice.map(p => getRealFileSize(p, hostOverride))); - for (let i = 0; i < slice.length; i++) { - registerScannedFile(slice[i], sizes[i] || 0); - } - } - } - allFiles.sort((a, b) => b.sizeBytes - a.sizeBytes); - // 3. 构建 9 大官方专项分类 + 1 个核心数据库保护区 - const categories = OFFICIAL_WECHAT_OWNER_RULES.map(rule => { - const catFiles = allFiles.filter(f => f.ownerId === rule.ownerId); - const extra = extraOwnerTotals.get(rule.ownerId); - const sampledBytes = catFiles.reduce((acc, f) => acc + f.sizeBytes, 0); - const totalSizeBytes = sampledBytes + (extra?.extraBytes || 0); - const fileCount = catFiles.length + (extra?.extraFiles || 0); - const defaultDir = catFiles[0]?.parentDir || - extra?.targetDir || - (rule.ownerId === 107 || rule.ownerId === 115 || rule.ownerId === 112 || rule.ownerId === 113 - ? appDataDir - ? `${appDataDir}\\Tencent\\xwechat` - : 'C:\\Users\\Default\\AppData\\Roaming\\Tencent\\xwechat' - : documentsDir - ? `${documentsDir}\\xwechat_files` - : 'C:\\Users\\Default\\Documents\\xwechat_files'); - return { - id: rule.id, - ownerId: rule.ownerId, - name: rule.name, - shortName: rule.shortName, - color: rule.color, - category: rule.category, - riskLevel: rule.riskLevel, - safetyLevel: rule.riskLevel, - targetDir: defaultDir, - existsOnDisk: fileCount > 0, - fileCount, - totalSizeBytes, - checked: rule.defaultChecked && rule.ownerId !== 999 && totalSizeBytes > 0, - sampleFiles: catFiles.slice(0, 12).map(f => ({ - path: f.path, - sizeBytes: f.sizeBytes, - mtime: f.mtime, - accountId: f.accountId - })), - files: catFiles, - description: rule.description - }; - }); - // 按实际体积降序排列(但保持 999 保护区在最后以便清晰核对) - categories.sort((a, b) => { - if (a.ownerId === 999) - return 1; - if (b.ownerId === 999) - return -1; - return b.totalSizeBytes - a.totalSizeBytes; - }); - // 4. 汇总各微信账号统计 - const accountMap = new Map(); - for (const acc of detectedAccountSet) { - accountMap.set(acc, { - fileCount: 0, - totalBytes: 0, - rootDir: documentsDir ? `${documentsDir}\\xwechat_files\\${acc}` : acc - }); - } - for (const f of allFiles) { - const cur = accountMap.get(f.accountId) || { - fileCount: 0, - totalBytes: 0, - rootDir: f.parentDir - }; - cur.fileCount += 1; - cur.totalBytes += f.sizeBytes; - accountMap.set(f.accountId, cur); - } - const accountStats = Array.from(accountMap.entries()) - .map(([accountId, stat]) => ({ - accountId, - label: accountId === '公共组件 (Shared)' - ? '微信公共引擎与跨端缓存 (xplugin/log/WMPF)' - : `微信号: ${accountId}`, - rootDir: stat.rootDir, - fileCount: stat.fileCount, - totalBytes: stat.totalBytes - })) - .sort((a, b) => b.totalBytes - a.totalBytes); - const detectedAccounts = Array.from(detectedAccountSet); - const scannableCategories = categories.filter(c => c.ownerId !== 999); - const totalScannableBytes = scannableCategories.reduce((s, c) => s + c.totalSizeBytes, 0); - const checkedBytes = scannableCategories - .filter(c => c.checked) - .reduce((s, c) => s + c.totalSizeBytes, 0); - const protectedDbBytes = categories.find(c => c.ownerId === 999)?.totalSizeBytes || 0; - return { - baseDirectories: candidateRoots, - detectedAccounts, - accountStats, - categories, - allFiles, - totalScannableBytes, - checkedBytes, - protectedDbBytes, - systemDiskFreeBytes: diskRes.ok && diskRes.data?.available ? diskRes.data.available : 0, - systemDiskTotalBytes: diskRes.ok && diskRes.data?.total ? diskRes.data.total : 0, - wechatRunning: false, - wechatVersionLabel: 'WeChat 4.0 (xwechat + RadiumWMPF)' - }; -} -/** - * 执行微信缓存安全清理(严格拦截聊天数据库文件,走真实回收站移除) - */ -export async function executeWechatCleanup(categoriesOrPaths, hostOverride, explicitFilePaths) { - let deletedCount = 0; - let freedBytes = 0; - let skippedProtected = 0; - const deletedPaths = []; - const skippedPaths = []; - const directStringPaths = Array.isArray(categoriesOrPaths) && categoriesOrPaths.length > 0 && typeof categoriesOrPaths[0] === 'string' - ? categoriesOrPaths - : explicitFilePaths; - const categories = Array.isArray(categoriesOrPaths) && (categoriesOrPaths.length === 0 || typeof categoriesOrPaths[0] !== 'string') - ? categoriesOrPaths - : []; - if (Array.isArray(directStringPaths) && directStringPaths.length > 0) { - const fileSizeLookup = new Map(); - for (const cat of categories) { - for (const f of cat.files || []) { - fileSizeLookup.set(f.path, f.sizeBytes); - } - for (const s of cat.sampleFiles || []) { - if (!fileSizeLookup.has(s.path)) - fileSizeLookup.set(s.path, s.sizeBytes); - } - } - for (const targetPath of directStringPaths) { - if (FORBIDDEN_TARGET_PATTERN.test(targetPath) || targetPath.toLowerCase().includes('\\db_storage\\')) { - skippedProtected += 1; - skippedPaths.push(targetPath); - continue; - } - const res = await trashRealItem(targetPath, hostOverride); - if (res.ok) { - deletedCount += 1; - freedBytes += fileSizeLookup.get(targetPath) || 0; - deletedPaths.push(targetPath); - } - } - return { - ok: true, - deletedCount, - freedBytes, - skippedProtected, - deletedPaths, - skippedPaths - }; - } - const selected = categories.filter(c => c.checked && c.ownerId !== 999 && c.sampleFiles.length > 0); - if (selected.length === 0) { - return { ok: true, deletedCount: 0, freedBytes: 0, skippedProtected: 0, deletedPaths: [], skippedPaths: [] }; - } - for (const cat of selected) { - for (const sample of cat.sampleFiles) { - if (FORBIDDEN_TARGET_PATTERN.test(sample.path) || sample.path.toLowerCase().includes('\\db_storage\\')) { - skippedProtected += 1; - skippedPaths.push(sample.path); - continue; - } - const res = await trashRealItem(sample.path, hostOverride); - if (res.ok) { - deletedCount += 1; - freedBytes += sample.sizeBytes; - deletedPaths.push(sample.path); - } - } - } - return { - ok: true, - deletedCount, - freedBytes, - skippedProtected, - deletedPaths, - skippedPaths - }; -} -export async function openWechatDirectory(dirPath, hostOverride) { - if (!dirPath) - return false; - return showRealItemInFolder(dirPath, hostOverride); -} -export async function openWechatFileDefault(filePath, hostOverride) { - if (!filePath) - return false; - return openRealPath(filePath, hostOverride); -} diff --git a/packages/declarative-ui/dist/examples/wechat-multi/index.d.ts b/packages/declarative-ui/dist/examples/wechat-multi/index.d.ts deleted file mode 100644 index 1748308d..00000000 --- a/packages/declarative-ui/dist/examples/wechat-multi/index.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -export * from './logic.js'; -export declare function WechatMultiCommand(): import("../../index.js").ViewDescriptor; -export default WechatMultiCommand; diff --git a/packages/declarative-ui/dist/examples/wechat-multi/index.js b/packages/declarative-ui/dist/examples/wechat-multi/index.js deleted file mode 100644 index beb25798..00000000 --- a/packages/declarative-ui/dist/examples/wechat-multi/index.js +++ /dev/null @@ -1,216 +0,0 @@ -import { List, ActionPanel, Action, Icon, Clipboard, useState, useEffect, showToast, Toast } from '../../index.js'; -import { formatBytes, fetchWechatInstances, launchNewWechatInstance, terminateWechatInstance, openWechatInstallLocation, filterWechatInstances } from './logic.js'; -export * from './logic.js'; -export function WechatMultiCommand() { - const [searchText, setSearchText] = useState(''); - const [filterMode, setFilterMode] = useState('all'); - const [items, setItems] = useState([]); - const [mainCount, setMainCount] = useState(2); - const [appletCount, setAppletCount] = useState(2); - const [totalMemBytes, setTotalMemBytes] = useState(0); - const [isLoading, setIsLoading] = useState(true); - async function refreshInstances(showNotice = false) { - if (showNotice) - setIsLoading(true); - try { - const snap = await fetchWechatInstances(); - setItems(snap.items); - setMainCount(snap.mainInstanceCount); - setAppletCount(snap.appletCount); - setTotalMemBytes(snap.totalMemoryBytes); - if (showNotice) { - showToast({ - style: Toast.Style.Success, - title: '微信运行实例已刷新', - message: `主进程 ${snap.mainInstanceCount} 个 · 小程序容器 ${snap.appletCount} 个` - }); - } - } - finally { - setIsLoading(false); - } - } - useEffect(() => { - void refreshInstances(false); - }, []); - async function handleLaunchNew() { - const res = await launchNewWechatInstance(1); - if (res.ok) { - await refreshInstances(false); - showToast({ - style: Toast.Style.Success, - title: res.message, - message: res.pid ? `新实例 PID: ${res.pid}` : res.executablePath - }); - } - else { - showToast({ - style: Toast.Style.Failure, - title: '启动微信实例失败', - message: res.message - }); - } - } - async function handleTerminate(item) { - if (item.isActionRow) { - await handleLaunchNew(); - return; - } - const res = await terminateWechatInstance(item.pid); - if (res.ok) { - setItems((prev) => prev.filter((cur) => cur.pid !== item.pid)); - if (item.role === 'main') - setMainCount((c) => Math.max(0, c - 1)); - else - setAppletCount((c) => Math.max(0, c - 1)); - setTotalMemBytes((m) => Math.max(0, m - item.memoryBytes)); - showToast({ - style: Toast.Style.Success, - title: res.message, - message: item.name - }); - } - else { - showToast({ - style: Toast.Style.Failure, - title: '结束微信实例失败', - message: res.message - }); - } - } - const filtered = filterWechatInstances(items, searchText, filterMode); - const maxMem = Math.max(500 * 1024 * 1024, ...items.map((i) => i.memoryBytes || 0)); - return List({ - navigationTitle: '微信多开与实例管理', - searchBarPlaceholder: '搜索微信实例 PID、路径、小程序容器或回车直接启动新微信实例...', - onSearchTextChange: setSearchText, - isShowingDetail: false, - isLoading, - searchBarAccessory: List.Dropdown({ - tooltip: '筛选微信进程类型', - value: filterMode, - onChange: (val) => setFilterMode(val), - children: [ - List.Dropdown.Item({ title: '全部实例与操作 (All Instances)', value: 'all' }), - List.Dropdown.Item({ title: '正在运行的微信主进程 (WeChat Main)', value: 'main' }), - List.Dropdown.Item({ title: '小程序容器进程 (WeChatAppEx)', value: 'applet' }) - ] - }), - filterBar: { - summaryText: `运行中微信主实例 ${mainCount} 个 · 小程序/媒体容器 ${appletCount} 个 · 物理内存合计 ${formatBytes(totalMemBytes)}`, - actions: [ - { - id: 'launch-wx', - label: '一键多开新微信', - title: '一键多开新微信', - style: 'secondary', - onAction: () => void handleLaunchNew() - }, - { - id: 'refresh-wx', - label: '刷新实例状态', - title: '刷新实例状态', - style: 'secondary', - onAction: () => void refreshInstances(true) - } - ] - }, - children: [ - List.Section({ - title: `微信多开与活动进程列表 (${filtered.length})`, - children: filtered.map((item) => { - if (item.isActionRow) { - return List.Item({ - id: item.id, - title: item.name, - subtitle: `${item.executablePath} · ${item.mutexStatus}`, - icon: Icon.Plus, - accessories: [ - { tag: { value: item.roleLabel } }, - { text: '回车立即启动' } - ], - actions: ActionPanel({ - title: item.name, - children: [ - Action({ - title: '立即启动新微信实例 (突破单实例锁)', - icon: Icon.Plus, - onAction: () => handleLaunchNew() - }), - Action({ - title: '定位微信安装目录', - icon: Icon.Folder, - shortcut: { modifiers: ['ctrl'], key: 'return' }, - onAction: () => { - void openWechatInstallLocation(item.executablePath); - } - }), - Action({ - title: '刷新实例状态', - icon: Icon.ArrowClockwise, - shortcut: { modifiers: ['ctrl'], key: 'r' }, - onAction: () => refreshInstances(true) - }) - ] - }) - }); - } - const memRatio = Math.min(100, Math.max(6, Math.round((item.memoryBytes / maxMem) * 100))); - return List.Item({ - id: item.id, - title: `${item.name} [PID: ${item.pid}]`, - subtitle: `${item.uptimeText} · ${item.mutexStatus} · ${item.executablePath}`, - icon: item.role === 'main' ? Icon.AppWindow : Icon.Terminal, - accessories: [ - { progress: { value: memRatio } }, - { tag: { value: item.roleLabel } }, - { text: `CPU ${item.cpuPercent.toFixed(1)}%` }, - { text: formatBytes(item.memoryBytes) } - ], - actions: ActionPanel({ - title: `${item.name} (PID: ${item.pid})`, - children: [ - Action({ - title: '一键多开新微信实例', - icon: Icon.Plus, - onAction: () => handleLaunchNew() - }), - Action({ - title: `结束该${item.roleLabel} (PID: ${item.pid})`, - icon: Icon.XMarkCircle, - style: 'destructive', - shortcut: { modifiers: ['ctrl'], key: 'return' }, - onAction: () => handleTerminate(item) - }), - Action({ - title: '在资源管理器中定位安装路径', - icon: Icon.Folder, - shortcut: { modifiers: ['ctrl'], key: 'o' }, - onAction: () => { - void openWechatInstallLocation(item.executablePath); - } - }), - Action({ - title: '复制进程 PID', - icon: Icon.Key, - shortcut: { modifiers: ['ctrl'], key: 'c' }, - onAction: async () => { - await Clipboard.copy(String(item.pid)); - showToast({ style: Toast.Style.Success, title: '已复制 PID', message: String(item.pid) }); - } - }), - Action({ - title: '刷新实例状态', - icon: Icon.ArrowClockwise, - shortcut: { modifiers: ['ctrl'], key: 'r' }, - onAction: () => refreshInstances(true) - }) - ] - }) - }); - }) - }) - ] - }); -} -export default WechatMultiCommand; diff --git a/packages/declarative-ui/dist/examples/wechat-multi/logic.d.ts b/packages/declarative-ui/dist/examples/wechat-multi/logic.d.ts deleted file mode 100644 index ed75c1c2..00000000 --- a/packages/declarative-ui/dist/examples/wechat-multi/logic.d.ts +++ /dev/null @@ -1,74 +0,0 @@ -/** - * 微信多开与运行实例管理中枢 (WechatMulti 2.0 Logic) - * 真实探测本机微信安装路径与运行中的 WeChat.exe / Weixin.exe / WeChatAppEx.exe 实例,支持拉起真实客户端进程 - */ -import { formatBytes } from '../shared/native-ipc.js'; -export { formatBytes }; -export interface CapabilityActionItem { - id: string; - title: string; - subtitle: string; - tag: string; - method: string; - params: Record; -} -export interface NativeInvocationResult { - ok: boolean; - pluginName: string; - method: string; - data?: unknown; - error?: string; - fromFallback?: boolean; -} -export type WechatProcessRole = 'launcher' | 'main' | 'applet' | 'helper'; -export type WechatFilterMode = 'all' | 'main' | 'applet'; -export interface WechatInstanceItem { - id: string; - pid: number; - name: string; - role: WechatProcessRole; - roleLabel: string; - executablePath: string; - dataDir: string; - memoryBytes: number; - cpuPercent: number; - uptimeText: string; - mutexStatus: string; - isActionRow?: boolean; -} -export interface WechatMultiSnapshot { - items: WechatInstanceItem[]; - mainInstanceCount: number; - appletCount: number; - totalMemoryBytes: number; - installPath: string; - dataRootPath: string; - installed?: boolean; -} -export declare const DLL_PLUGIN_NAME = "WeChatMultiPlugin"; -export declare const FORBIDDEN_TARGET_PATTERN: RegExp; -export declare const FORBIDDEN_REASON = "\u4E25\u7981\u4FEE\u6539\u6216\u6CE8\u5165 WeChatWin.dll \u6587\u4EF6\u4EE5\u514D\u89E6\u53D1\u8D26\u53F7\u5B89\u5168\u5C01\u7981\uFF0C\u4EC5\u5141\u8BB8\u6807\u51C6\u8FDB\u7A0B\u53E5\u67C4\u4E92\u65A5\u9501\u91CA\u653E\u4E0E\u591A\u8FDB\u7A0B\u542F\u52A8"; -export declare const WECHAT_MUTEX_NAME = "_WeChat_App_Instance_Identity_Mutex_Name"; -export declare function getCapabilityItems(): CapabilityActionItem[]; -export declare function filterCapabilityItems(items: CapabilityActionItem[], query: string): CapabilityActionItem[]; -export declare function validateInvocationPayload(method: string, params: unknown): { - valid: boolean; - error?: string; -}; -export declare function invokeNativeCapability(method: string, params: Record, hostBridge?: any): Promise; -export declare function fetchWechatInstances(hostOverride?: any): Promise; -export declare const fetchWeChatMultiSnapshot: typeof fetchWechatInstances; -export declare function launchNewWechatInstance(countOrExePath?: number | string, hostOverride?: any): Promise<{ - ok: boolean; - launchedCount: number; - pid?: number; - executablePath: string; - message: string; -}>; -export declare const launchNewWeChatInstance: typeof launchNewWechatInstance; -export declare function terminateWechatInstance(pid: number, hostOverride?: any): Promise<{ - ok: boolean; - message: string; -}>; -export declare function openWechatInstallLocation(filePath: string, hostOverride?: any): Promise; -export declare function filterWechatInstances(items: WechatInstanceItem[], query: string, mode?: WechatFilterMode | string): WechatInstanceItem[]; diff --git a/packages/declarative-ui/dist/examples/wechat-multi/logic.js b/packages/declarative-ui/dist/examples/wechat-multi/logic.js deleted file mode 100644 index a136d3dc..00000000 --- a/packages/declarative-ui/dist/examples/wechat-multi/logic.js +++ /dev/null @@ -1,326 +0,0 @@ -/** - * 微信多开与运行实例管理中枢 (WechatMulti 2.0 Logic) - * 真实探测本机微信安装路径与运行中的 WeChat.exe / Weixin.exe / WeChatAppEx.exe 实例,支持拉起真实客户端进程 - */ -import { callHostTransport, invokePluginService, isRealElectronHost, showRealItemInFolder, formatBytes, invokeDllPluginCapability } from '../shared/native-ipc.js'; -export { formatBytes }; -export const DLL_PLUGIN_NAME = 'WeChatMultiPlugin'; -export const FORBIDDEN_TARGET_PATTERN = new RegExp('^(?:INJECT_MEMORY_HOOK_UNSAFE|MODIFY_WECHAT_WIN_DLL)$', 'i'); -export const FORBIDDEN_REASON = '严禁修改或注入 WeChatWin.dll 文件以免触发账号安全封禁,仅允许标准进程句柄互斥锁释放与多进程启动'; -export const WECHAT_MUTEX_NAME = '_WeChat_App_Instance_Identity_Mutex_Name'; -const DEFAULT_WECHAT_PATH = 'C:\\Program Files\\Tencent\\WeChat\\WeChat.exe'; -const DEFAULT_WECHAT_DATA_DIR = 'C:\\Users\\User\\Documents\\WeChat Files'; -const FALLBACK_WECHAT_INSTANCES = [ - { - id: 'wx-action-launch-new', - pid: 0, - name: '启动全新微信多开实例 (突破单实例互斥锁)', - role: 'launcher', - roleLabel: '一键多开', - executablePath: DEFAULT_WECHAT_PATH, - dataDir: DEFAULT_WECHAT_DATA_DIR, - memoryBytes: 0, - cpuPercent: 0, - uptimeText: '瞬时拉起', - mutexStatus: '自动释放 _WeChat_App_Instance_Identity_Mutex_Name', - isActionRow: true - }, - { - id: 'wx-main-18420', - pid: 18420, - name: 'WeChat.exe (主账号实例 #1)', - role: 'main', - roleLabel: '微信主进程', - executablePath: DEFAULT_WECHAT_PATH, - dataDir: `${DEFAULT_WECHAT_DATA_DIR}\\wechat_profile_default`, - memoryBytes: 428 * 1024 * 1024, - cpuPercent: 1.4, - uptimeText: '已运行 04:18:22', - mutexStatus: '互斥锁已剥离' - }, - { - id: 'wx-main-23916', - pid: 23916, - name: 'WeChat.exe (工作号实例 #2)', - role: 'main', - roleLabel: '微信主进程', - executablePath: DEFAULT_WECHAT_PATH, - dataDir: `${DEFAULT_WECHAT_DATA_DIR}\\wxid_work_studio`, - memoryBytes: 362 * 1024 * 1024, - cpuPercent: 0.8, - uptimeText: '已运行 02:05:10', - mutexStatus: '互斥锁已剥离' - }, - { - id: 'wx-applet-26104', - pid: 26104, - name: 'WeChatAppEx.exe (小程序渲染容器)', - role: 'applet', - roleLabel: '小程序容器', - executablePath: 'C:\\Users\\User\\AppData\\Roaming\\Tencent\\WeChat\\XPlugin\\Plugins\\RadiumWMPF\\WeChatAppEx.exe', - dataDir: DEFAULT_WECHAT_DATA_DIR, - memoryBytes: 294 * 1024 * 1024, - cpuPercent: 2.1, - uptimeText: '已运行 01:12:45', - mutexStatus: 'Chromium 子进程' - }, - { - id: 'wx-applet-27880', - pid: 27880, - name: 'WeChatPlayer.exe (视频号与内置播放器)', - role: 'applet', - roleLabel: '媒体容器', - executablePath: DEFAULT_WECHAT_PATH, - dataDir: DEFAULT_WECHAT_DATA_DIR, - memoryBytes: 118 * 1024 * 1024, - cpuPercent: 0.3, - uptimeText: '已运行 00:48:19', - mutexStatus: '独立解码容器' - } -]; -export function getCapabilityItems() { - return [ - { - id: 'wx-cap-launch', - title: '突破单实例互斥锁并启动新微信客户端', - subtitle: `释放 ${WECHAT_MUTEX_NAME} 句柄并拉起独立 WeChat.exe 进程`, - tag: '微信多开', - method: 'LaunchMultipleWeChat', - params: { count: 1 } - }, - { - id: 'wx-cap-scan', - title: '扫描本机运行中的全部微信主进程与小程序容器', - subtitle: '枚举 WeChat.exe / Weixin.exe / WeChatAppEx.exe 工作集内存与 PID', - tag: '实例监控', - method: 'GetWeChatInstances', - params: {} - } - ]; -} -export function filterCapabilityItems(items, query) { - if (!Array.isArray(items)) - return []; - const q = typeof query === 'string' ? query.trim().toLowerCase() : ''; - if (!q) - return items; - return items.filter((item) => item.title.toLowerCase().includes(q) || - item.subtitle.toLowerCase().includes(q) || - item.tag.toLowerCase().includes(q)); -} -export function validateInvocationPayload(method, params) { - if (typeof method !== 'string' || !method.trim()) { - return { valid: false, error: 'INVALID_METHOD: 调用方法名不能为空' }; - } - if (params === null || params === undefined || typeof params !== 'object' || Array.isArray(params)) { - return { valid: false, error: 'INVALID_PARAMS: 参数必须为非空对象' }; - } - for (const [k, v] of Object.entries(params)) { - if (typeof v === 'string' && FORBIDDEN_TARGET_PATTERN.test(v.trim())) { - return { valid: false, error: `SECURITY_INTERCEPTED (${k}): ${FORBIDDEN_REASON}` }; - } - } - return { valid: true }; -} -export async function invokeNativeCapability(method, params, hostBridge) { - const check = validateInvocationPayload(method, params); - if (!check.valid) { - throw new Error(check.error || '参数校验失败'); - } - return invokeDllPluginCapability(DLL_PLUGIN_NAME, method.trim(), params, hostBridge); -} -function mapProcessToWechatItem(p, mainIdxRef, defaultInstallPath, dataRootPath) { - const pid = Number(p.pid || 0); - const rawName = String(p.name || 'WeChat.exe'); - const isMain = p.role === 'main' || /^(?:wechat|weixin)(?:\.exe)?$/i.test(rawName); - const pathStr = String(p.executablePath || p.path || defaultInstallPath); - const memBytes = Number(p.workingSetBytes ?? - p.memoryBytes ?? - p.memoryUsage ?? - (typeof p.memoryMB === 'number' ? Math.round(p.memoryMB * 1024 * 1024) : 0)); - const cpuPercent = Number(p.cpuPercent ?? p.cpuUsage ?? 0); - return { - id: String(p.id || `wx-proc-${pid}`), - pid, - name: isMain ? `${rawName} (主实例 #${mainIdxRef.count++})` : `${rawName}`, - role: isMain ? 'main' : 'applet', - roleLabel: isMain ? '微信主进程' : '小程序容器', - executablePath: pathStr, - dataDir: String(p.dataDir || dataRootPath), - memoryBytes: memBytes, - cpuPercent, - uptimeText: String(p.uptimeText || '实时运行中'), - mutexStatus: String(p.mutexStatus || (isMain ? '进程运行中' : '子进程容器')) - }; -} -export async function fetchWechatInstances(hostOverride) { - const realHost = isRealElectronHost(hostOverride) || Boolean(hostOverride); - const detected = []; - let installPath = DEFAULT_WECHAT_PATH; - let dataRootPath = DEFAULT_WECHAT_DATA_DIR; - let installed = true; - let hostResponded = false; - if (realHost) { - // 1. 优先尝试 WeChatMultiPlugin.getStatus - const svcRes = await invokePluginService(DLL_PLUGIN_NAME, 'getStatus', {}, hostOverride); - if (svcRes.ok && svcRes.data) { - hostResponded = true; - const resolvedInstallPath = svcRes.data.installPath ?? svcRes.data.wechatPath; - if (typeof resolvedInstallPath === 'string' && resolvedInstallPath.trim()) { - installPath = resolvedInstallPath; - } - if (typeof svcRes.data.dataRootPath === 'string' && svcRes.data.dataRootPath) { - dataRootPath = svcRes.data.dataRootPath; - } - if (typeof svcRes.data.installed === 'boolean') { - installed = svcRes.data.installed; - } - const rawInstances = Array.isArray(svcRes.data.instances) - ? svcRes.data.instances - : Array.isArray(svcRes.data.items) - ? svcRes.data.items - : []; - const mainIdxRef = { count: 1 }; - for (const p of rawInstances) { - if (p?.isActionRow) - continue; - detected.push(mapProcessToWechatItem(p, mainIdxRef, installPath, dataRootPath)); - } - } - else { - // 2. 回退使用 process_list 过滤真实进程 - const procRes = await callHostTransport('process_list', {}, hostOverride); - if (procRes.ok && Array.isArray(procRes.data)) { - hostResponded = true; - const wxProcs = procRes.data.filter((p) => /^(?:wechat|weixin|wechatappex|wechatplayer|wechatutility)(?:\.exe)?$/i.test(String(p?.name || ''))); - const mainIdxRef = { count: 1 }; - for (const p of wxProcs) { - const item = mapProcessToWechatItem(p, mainIdxRef, installPath, dataRootPath); - if (item.role === 'main' && item.executablePath) { - installPath = item.executablePath; - } - detected.push(item); - } - } - } - } - const launcherAction = { - ...FALLBACK_WECHAT_INSTANCES[0], - executablePath: installPath || DEFAULT_WECHAT_PATH, - dataDir: dataRootPath - }; - // 在真实宿主或显式传入 hostOverride 时,严禁混入虚构的 wxid_geek_primary 等假实例 - const items = hostResponded || isRealElectronHost(hostOverride) - ? [launcherAction, ...detected] - : FALLBACK_WECHAT_INSTANCES.map((i) => ({ ...i })); - const mainInstanceCount = items.filter((i) => i.role === 'main').length; - const appletCount = items.filter((i) => i.role === 'applet').length; - const totalMemoryBytes = items.reduce((acc, cur) => acc + (cur.memoryBytes || 0), 0); - return { - items, - mainInstanceCount, - appletCount, - totalMemoryBytes, - installPath, - dataRootPath, - installed - }; -} -export const fetchWeChatMultiSnapshot = fetchWechatInstances; -export async function launchNewWechatInstance(countOrExePath = 1, hostOverride) { - const customExePath = typeof countOrExePath === 'string' ? countOrExePath.trim() : ''; - const count = typeof countOrExePath === 'number' ? countOrExePath : 1; - const safeCount = Math.min(5, Math.max(1, Math.floor(count || 1))); - const targetExe = customExePath || DEFAULT_WECHAT_PATH; - if (hostOverride || isRealElectronHost(hostOverride)) { - const svcRes = await invokePluginService(DLL_PLUGIN_NAME, 'launchInstance', { executablePath: customExePath, count: safeCount }, hostOverride); - if (svcRes.ok && svcRes.data?.ok !== false) { - const exePath = String(svcRes.data?.executablePath || svcRes.data?.wechatPath || targetExe); - const pid = Number(svcRes.data?.pid || 0); - return { - ok: true, - launchedCount: Number(svcRes.data?.launchedCount ?? safeCount), - ...(pid > 0 ? { pid } : {}), - executablePath: exePath, - message: String(svcRes.data?.message || `已启动 ${safeCount} 个新微信客户端实例`) - }; - } - if (svcRes.data?.ok === false) { - return { - ok: false, - launchedCount: 0, - executablePath: '', - message: String(svcRes.data.error || svcRes.data.message || '启动新微信客户端实例失败') - }; - } - const startRes = await callHostTransport('process_start', { command: targetExe, args: [] }, hostOverride); - if (startRes.ok) { - const pid = Number(startRes.data?.pid || 0); - return { - ok: true, - launchedCount: safeCount, - ...(pid > 0 ? { pid } : {}), - executablePath: targetExe, - message: `已拉起 ${safeCount} 个新微信客户端实例` - }; - } - const openRes = await callHostTransport('shell_open_path', { fullPath: targetExe }, hostOverride); - if (openRes.ok) { - return { - ok: true, - launchedCount: safeCount, - executablePath: targetExe, - message: `已通过系统 Shell 拉起微信客户端实例` - }; - } - return { - ok: false, - launchedCount: 0, - executablePath: '', - message: svcRes.error || startRes.error || openRes.error || '未检测到本机安装的微信客户端 (WeChat.exe / Weixin.exe) 或启动失败' - }; - } - return { - ok: true, - launchedCount: safeCount, - executablePath: targetExe, - message: `已突破单实例互斥锁并拉起 ${safeCount} 个新微信客户端实例` - }; -} -export const launchNewWeChatInstance = launchNewWechatInstance; -export async function terminateWechatInstance(pid, hostOverride) { - if (!Number.isInteger(pid) || pid <= 0) { - return { ok: false, message: '无效的微信进程 PID' }; - } - if (hostOverride || isRealElectronHost(hostOverride)) { - const res = await callHostTransport('process_kill', { pid, force: true }, hostOverride); - if (!res.ok) { - return { ok: false, message: res.error || `结束微信实例 (PID: ${pid}) 失败` }; - } - } - return { - ok: true, - message: `已安全结束微信进程实例 (PID: ${pid})` - }; -} -export async function openWechatInstallLocation(filePath, hostOverride) { - return showRealItemInFolder(filePath || DEFAULT_WECHAT_PATH, hostOverride); -} -export function filterWechatInstances(items, query, mode = 'all') { - if (!Array.isArray(items)) - return []; - let list = items; - if (mode === 'main') { - list = list.filter((i) => i.role === 'main' || i.isActionRow); - } - else if (mode === 'applet') { - list = list.filter((i) => i.role === 'applet'); - } - const q = typeof query === 'string' ? query.trim().toLowerCase() : ''; - if (!q) - return list; - return list.filter((i) => i.name.toLowerCase().includes(q) || - String(i.pid).includes(q) || - i.executablePath.toLowerCase().includes(q) || - i.roleLabel.toLowerCase().includes(q)); -} diff --git a/packages/declarative-ui/dist/examples/wifi-password-reveal/index.d.ts b/packages/declarative-ui/dist/examples/wifi-password-reveal/index.d.ts deleted file mode 100644 index d14b4e28..00000000 --- a/packages/declarative-ui/dist/examples/wifi-password-reveal/index.d.ts +++ /dev/null @@ -1,12 +0,0 @@ -import type { WifiProfileInfo } from './types.js'; -export * from './types.js'; -export * from './wifi-service.js'; -export declare function WifiDetailView({ profile, hostOverride }: { - profile: WifiProfileInfo; - hostOverride?: unknown; -}): JSX.Element; -export declare function WifiPasswordRevealCommand(props?: { - featureCode?: string; - hostOverride?: unknown; -}): JSX.Element; -export default WifiPasswordRevealCommand; diff --git a/packages/declarative-ui/dist/examples/wifi-password-reveal/index.js b/packages/declarative-ui/dist/examples/wifi-password-reveal/index.js deleted file mode 100644 index 42934580..00000000 --- a/packages/declarative-ui/dist/examples/wifi-password-reveal/index.js +++ /dev/null @@ -1,197 +0,0 @@ -import React, { Action, ActionPanel, Clipboard, Detail, Icon, List, Toast, showToast, useEffect, useMemo, useState } from '../../index.js'; -import { isRealElectronHost } from '../shared/native-ipc.js'; -import { SAMPLE_WIFI_PROFILES, fetchSavedWifiProfiles, filterAndSortWifiProfiles, generateWifiQrString, generateWifiQrSvgDataUrl, revealWifiPasswordFromHost } from './wifi-service.js'; -export * from './types.js'; -export * from './wifi-service.js'; -export function WifiDetailView({ profile, hostOverride }) { - const [resolvedPassword, setResolvedPassword] = useState(profile.password); - useEffect(() => { - let active = true; - setResolvedPassword(profile.password); - if (!profile.password && - !profile.isOpenNetwork && - !profile.isEnterprise && - (hostOverride || isRealElectronHost())) { - void revealWifiPasswordFromHost(profile.ssid, hostOverride).then((pwd) => { - if (active && pwd) { - setResolvedPassword(pwd); - } - }); - } - return () => { - active = false; - }; - }, [profile.ssid, profile.password, profile.isOpenNetwork, profile.isEnterprise, hostOverride]); - const effectiveProfile = useMemo(() => ({ ...profile, password: resolvedPassword }), [profile, resolvedPassword]); - const qrString = useMemo(() => generateWifiQrString(effectiveProfile.ssid, effectiveProfile.password, effectiveProfile.authType), [effectiveProfile.ssid, effectiveProfile.password, effectiveProfile.authType]); - const qrSvgUrl = useMemo(() => generateWifiQrSvgDataUrl(effectiveProfile), [effectiveProfile]); - const displayPassword = effectiveProfile.isOpenNetwork - ? '(开放网络 — 无需密码)' - : effectiveProfile.isEnterprise - ? '(802.1X 企业证书认证 — 无预共享明文密码)' - : effectiveProfile.password || '(未读取到密码)'; - const markdown = ` -# ${effectiveProfile.ssid} - -${effectiveProfile.isConnected ? '> **当前已连接此无线网络**\n' : ''} -${effectiveProfile.notes ? `> ${effectiveProfile.notes}\n` : ''} - ---- - -### 明文密码 (Key Content) -\`\`\`text -${displayPassword} -\`\`\` - -### 手机扫码一键连网协议串 -\`\`\`text -${qrString} -\`\`\` - -![Wi-Fi QR Preview](${qrSvgUrl}) -`; - return (React.createElement(Detail, { navigationTitle: `Wi-Fi 详情: ${effectiveProfile.ssid}`, markdown: markdown, metadata: React.createElement(Detail.Metadata, null, - React.createElement(Detail.Metadata.Label, { title: "\u52A0\u5BC6\u7B97\u6CD5 (Cipher)", text: effectiveProfile.cipher || 'CCMP (AES)', icon: Icon.Lock }), - React.createElement(Detail.Metadata.Label, { title: "\u65E0\u7EBF\u9891\u6BB5 (Band)", text: effectiveProfile.band || 'Dual-Band', icon: Icon.Signal3 }), - React.createElement(Detail.Metadata.Separator, null), - React.createElement(Detail.Metadata.Label, { title: "\u4FE1\u53F7\u5F3A\u5EA6", text: `${effectiveProfile.signalPercent ?? 85}%`, icon: Icon.BarChart }), - React.createElement(Detail.Metadata.Label, { title: "\u6700\u8FD1\u8FDE\u63A5", text: effectiveProfile.lastConnected || '已保存', icon: Icon.Clock })), actions: React.createElement(ActionPanel, null, - !effectiveProfile.isOpenNetwork && !effectiveProfile.isEnterprise && (React.createElement(Action, { title: "\u590D\u5236 Wi-Fi \u5BC6\u7801", icon: Icon.CopyClipboard, onAction: async () => { - let pwd = effectiveProfile.password; - if (!pwd && (hostOverride || isRealElectronHost())) { - pwd = await revealWifiPasswordFromHost(effectiveProfile.ssid, hostOverride); - if (pwd) - setResolvedPassword(pwd); - } - if (pwd) { - await Clipboard.copy(pwd); - await showToast(Toast.Style.Success, `已复制 "${effectiveProfile.ssid}" 的密码`); - } - else { - await showToast(Toast.Style.Failure, `未能读取 "${effectiveProfile.ssid}" 的明文密码`); - } - } })), - React.createElement(Action, { title: "\u590D\u5236\u626B\u7801\u8FDE\u7F51\u534F\u8BAE\u4E32 (WIFI:)", icon: Icon.QrCode, shortcut: { modifiers: ['ctrl'], key: 'q' }, onAction: async () => { - await Clipboard.copy(qrString); - await showToast(Toast.Style.Success, '已复制 WIFI: 标准二维码连网串'); - } }), - React.createElement(Action, { title: "\u590D\u5236\u7F51\u7EDC\u540D\u79F0 (SSID)", icon: Icon.Text, shortcut: { modifiers: ['ctrl', 'shift'], key: 'c' }, onAction: async () => { - await Clipboard.copy(effectiveProfile.ssid); - await showToast(Toast.Style.Success, `已复制 SSID: ${effectiveProfile.ssid}`); - } })) })); -} -export function WifiPasswordRevealCommand(props) { - const [allProfiles, setAllProfiles] = useState(() => props?.hostOverride || isRealElectronHost() ? [] : SAMPLE_WIFI_PROFILES); - const [searchText, setSearchText] = useState(''); - const [securityFilter, setSecurityFilter] = useState('all'); - const [revealInList, setRevealInList] = useState(false); - const [isLoading, setIsLoading] = useState(() => Boolean(props?.hostOverride) || isRealElectronHost()); - const reloadWifiProfiles = async () => { - setIsLoading(true); - try { - const loaded = await fetchSavedWifiProfiles({ hostOverride: props?.hostOverride }); - setAllProfiles(loaded); - await showToast(Toast.Style.Success, `已刷新无线网络配置 (${loaded.length} 个)`); - } - finally { - setIsLoading(false); - } - }; - useEffect(() => { - let active = true; - setIsLoading(true); - void fetchSavedWifiProfiles({ hostOverride: props?.hostOverride }) - .then((loaded) => { - if (active && (loaded.length > 0 || props?.hostOverride || isRealElectronHost())) { - setAllProfiles(loaded); - } - }) - .finally(() => { - if (active) - setIsLoading(false); - }); - return () => { - active = false; - }; - }, [props?.hostOverride]); - const profiles = useMemo(() => filterAndSortWifiProfiles(allProfiles, { - query: searchText, - securityFilter, - sortBy: 'connected' - }), [allProfiles, searchText, securityFilter]); - const connectedProfile = useMemo(() => profiles.find((p) => p.isConnected), [profiles]); - return (React.createElement(List, { isLoading: isLoading, isShowingDetail: true, navigationTitle: "Wi-Fi \u5BC6\u7801\u67E5\u770B", searchBarPlaceholder: "\u641C\u7D22\u5DF2\u4FDD\u5B58\u7684 Wi-Fi \u540D\u79F0\u3001\u62FC\u97F3\u6216\u9891\u6BB5...", onSearchTextChange: setSearchText, filterBar: { - summaryText: `已保存 ${profiles.length} 个 Wi-Fi 网络 | 当前连接:${connectedProfile ? connectedProfile.ssid : '未连接'}`, - actions: [ - { - id: 'toggle-reveal', - title: revealInList ? '隐藏列表明文密码' : '显示列表明文密码', - style: 'primary', - onAction: () => { - setRevealInList((prev) => !prev); - } - }, - { - id: 'refresh-wifi', - title: '刷新网络配置', - style: 'secondary', - onAction: () => { - void reloadWifiProfiles(); - } - } - ] - }, searchBarAccessory: React.createElement(List.Dropdown, { tooltip: "\u6309\u52A0\u5BC6\u7C7B\u578B\u8FC7\u6EE4", value: securityFilter, onChange: (val) => setSecurityFilter(val) }, - React.createElement(List.Dropdown.Item, { title: "\u5168\u90E8\u5DF2\u4FDD\u5B58\u7F51\u7EDC", value: "all" }), - React.createElement(List.Dropdown.Item, { title: "\u4EC5\u5F53\u524D\u8FDE\u63A5", value: "connected" }), - React.createElement(List.Dropdown.Item, { title: "WPA3 \u4E2A\u4EBA\u52A0\u5BC6", value: "wpa3" }), - React.createElement(List.Dropdown.Item, { title: "WPA2 \u4E2A\u4EBA\u52A0\u5BC6", value: "wpa2" }), - React.createElement(List.Dropdown.Item, { title: "\u5F00\u653E\u65E0\u5BC6\u7801\u7F51\u7EDC", value: "open" }), - React.createElement(List.Dropdown.Item, { title: "802.1X \u4F01\u4E1A\u7F51\u7EDC", value: "enterprise" })) }, profiles.length === 0 ? (React.createElement(List.Section, { title: "\u68C0\u6D4B\u7ED3\u679C" }, - React.createElement(List.Item, { id: "empty-wifi", icon: Icon.Wifi, title: "\u672A\u68C0\u6D4B\u5230\u5DF2\u4FDD\u5B58\u7684\u65E0\u7EBF\u7F51\u7EDC\u914D\u7F6E", subtitle: "\u8BF7\u786E\u8BA4\u5F53\u524D\u8BBE\u5907\u5DF2\u542F\u7528\u65E0\u7EBF\u7F51\u5361\uFF08WLAN\uFF09\uFF0C\u6216\u5207\u6362\u53F3\u4E0A\u89D2\u7B5B\u9009\u6761\u4EF6\u91CD\u8BD5" }))) : (React.createElement(List.Section, { title: "\u5DF2\u4FDD\u5B58\u7684\u65E0\u7EBF\u7F51\u7EDC\u914D\u7F6E\u6587\u4EF6", subtitle: `共 ${profiles.length} 个网络` }, profiles.map((item) => { - const maskedPwd = item.password - ? revealInList - ? item.password - : '••••••••' - : item.isOpenNetwork - ? '开放网络(无密码)' - : item.isEnterprise - ? '802.1X 证书认证' - : '回车复制或查看明文密码'; - const qrString = generateWifiQrString(item.ssid, item.password, item.authType); - const qrSvgUrl = generateWifiQrSvgDataUrl(item); - const detailMarkdown = `### 手机扫码一键连网\n\n![Wi-Fi QR Code](${qrSvgUrl})\n\n### 明文密码\n\`\`\`text\n${item.isOpenNetwork ? '(开放网络 — 无需密码)' : item.isEnterprise ? '(802.1X 企业认证 — 无预共享密码)' : item.password || '(按回车提取密码)'}\n\`\`\`\n\n### 二维码连网协议串\n\`${qrString}\``; - return (React.createElement(List.Item, { key: item.id, id: item.id, icon: Icon.Wifi, title: item.ssid, subtitle: `${item.authType} · ${maskedPwd}`, accessories: [ - item.isConnected ? { tag: '已连接' } : { text: item.lastConnected || '已保存' } - ], detail: React.createElement(List.Item.Detail, { markdown: detailMarkdown, metadata: React.createElement(List.Item.Detail.Metadata, null, - React.createElement(List.Item.Detail.Metadata.Label, { title: "\u52A0\u5BC6\u7B97\u6CD5 (Cipher)", text: item.cipher || 'CCMP (AES)' }), - React.createElement(List.Item.Detail.Metadata.Label, { title: "\u65E0\u7EBF\u9891\u6BB5 (Band)", text: item.band || 'Dual-Band' }), - React.createElement(List.Item.Detail.Metadata.Label, { title: "\u7F51\u5361\u63A5\u53E3", text: item.interfaceName || 'WLAN' })) }), actions: React.createElement(ActionPanel, null, - !item.isOpenNetwork && !item.isEnterprise && (React.createElement(Action, { title: "\u590D\u5236 Wi-Fi \u5BC6\u7801", icon: Icon.CopyClipboard, onAction: async () => { - let pwd = item.password; - if (!pwd && (props?.hostOverride || isRealElectronHost())) { - pwd = await revealWifiPasswordFromHost(item.ssid, props?.hostOverride); - if (pwd) { - setAllProfiles((prev) => prev.map((p) => (p.id === item.id ? { ...p, password: pwd } : p))); - } - } - if (pwd) { - await Clipboard.copy(pwd); - await showToast(Toast.Style.Success, `已复制 "${item.ssid}" 的密码`); - } - else { - await showToast(Toast.Style.Failure, `未能提取 "${item.ssid}" 的明文密码`); - } - } })), - React.createElement(Action.Push, { title: "\u5168\u5C4F\u67E5\u770B\u5BC6\u7801\u4E0E\u8FDE\u7F51\u4E8C\u7EF4\u7801", icon: Icon.Eye, shortcut: { modifiers: ['ctrl'], key: 'enter' }, target: React.createElement(WifiDetailView, { profile: item, hostOverride: props?.hostOverride }) }), - React.createElement(Action, { title: revealInList ? '隐藏列表明文密码' : '显示列表明文密码', icon: revealInList ? Icon.EyeDisabled : Icon.Eye, shortcut: { modifiers: ['ctrl'], key: 'h' }, onAction: () => setRevealInList(!revealInList) }), - React.createElement(Action, { title: "\u590D\u5236\u626B\u7801\u8FDE\u7F51\u534F\u8BAE\u4E32 (WIFI:)", icon: Icon.QrCode, shortcut: { modifiers: ['ctrl'], key: 'q' }, onAction: async () => { - await Clipboard.copy(qrString); - await showToast(Toast.Style.Success, '已复制 WIFI: 标准二维码连网串'); - } }), - React.createElement(Action, { title: "\u590D\u5236\u7F51\u7EDC\u540D\u79F0 (SSID)", icon: Icon.Text, shortcut: { modifiers: ['ctrl', 'shift'], key: 'c' }, onAction: async () => { - await Clipboard.copy(item.ssid); - await showToast(Toast.Style.Success, `已复制 SSID: ${item.ssid}`); - } })) })); - }))))); -} -export default WifiPasswordRevealCommand; diff --git a/packages/declarative-ui/dist/examples/wifi-password-reveal/types.d.ts b/packages/declarative-ui/dist/examples/wifi-password-reveal/types.d.ts deleted file mode 100644 index 562740b9..00000000 --- a/packages/declarative-ui/dist/examples/wifi-password-reveal/types.d.ts +++ /dev/null @@ -1,47 +0,0 @@ -export type WifiSecurityType = 'WPA3-Personal' | 'WPA2-Personal' | 'WPA/WPA2-Personal' | 'WPA2-Enterprise' | 'WPA3-Enterprise' | 'WEP' | 'Open' | 'Unknown'; -export type WifiBand = '2.4 GHz' | '5 GHz' | '6 GHz' | 'Dual-Band (2.4/5 GHz)' | 'Unknown'; -export type WifiSortBy = 'connected' | 'signal' | 'ssid' | 'security'; -export type WifiSecurityFilter = 'all' | 'wpa3' | 'wpa2' | 'open' | 'enterprise' | 'connected'; -export interface WifiProfileInfo { - id: string; - ssid: string; - password: string; - authType: WifiSecurityType; - cipher?: string; - band?: WifiBand; - isConnected?: boolean; - isOpenNetwork?: boolean; - isEnterprise?: boolean; - signalPercent?: number; - interfaceName?: string; - lastConnected?: string; - pinyin?: string; - notes?: string; -} -export type WifiErrorCode = 'ProfileNotFound' | 'PermissionDenied' | 'EnterpriseNetwork' | 'InvalidInput' | 'ExecutionFailed' | 'Unknown'; -export interface WifiParseError { - code: WifiErrorCode; - message: string; -} -export interface WifiParseDetailResult { - ssid: string; - password: string; - authType: WifiSecurityType; - cipher: string; - isOpenNetwork: boolean; - isEnterprise: boolean; - error?: WifiParseError; -} -export interface CommandExecOutput { - stdout: string; - stderr?: string; - exitCode?: number; -} -export type WifiCommandExecutor = (command: string, args?: string[]) => Promise; -export interface FetchWifiProfilesOptions { - platform?: 'win32' | 'darwin' | 'linux'; - executor?: WifiCommandExecutor; - fallbackToSample?: boolean; - interfaceName?: string; - hostOverride?: unknown; -} diff --git a/packages/declarative-ui/dist/examples/wifi-password-reveal/types.js b/packages/declarative-ui/dist/examples/wifi-password-reveal/types.js deleted file mode 100644 index cb0ff5c3..00000000 --- a/packages/declarative-ui/dist/examples/wifi-password-reveal/types.js +++ /dev/null @@ -1 +0,0 @@ -export {}; diff --git a/packages/declarative-ui/dist/examples/wifi-password-reveal/wifi-service.d.ts b/packages/declarative-ui/dist/examples/wifi-password-reveal/wifi-service.d.ts deleted file mode 100644 index e955775b..00000000 --- a/packages/declarative-ui/dist/examples/wifi-password-reveal/wifi-service.d.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { FetchWifiProfilesOptions, WifiParseDetailResult, WifiProfileInfo, WifiSecurityFilter, WifiSecurityType, WifiSortBy } from './types.js'; -export declare const SAMPLE_WIFI_PROFILES: readonly WifiProfileInfo[]; -export declare function parseNetshWlanProfiles(output: string): string[]; -export declare const parseWindowsWlanProfiles: typeof parseNetshWlanProfiles; -export declare function normalizeSecurityType(rawAuth: string): WifiSecurityType; -export declare function parseWindowsWlanProfileDetail(ssidInput: string, output: string): WifiParseDetailResult; -export declare function parseWifiInterface(output: string): string; -export declare function escapeWifiQrField(value: string): string; -export declare function generateWifiQrString(ssid: string, password?: string, authType?: WifiSecurityType): string; -export declare function generateWifiQrSvgDataUrl(profile: WifiProfileInfo): string; -export declare function filterAndSortWifiProfiles(profiles: readonly WifiProfileInfo[], options?: { - query?: string; - securityFilter?: WifiSecurityFilter; - sortBy?: WifiSortBy; -}): WifiProfileInfo[]; -export declare function revealWifiPasswordFromHost(ssid: string, hostOverride?: unknown): Promise; -export declare function fetchSavedWifiProfiles(options?: FetchWifiProfilesOptions): Promise; diff --git a/packages/declarative-ui/dist/examples/wifi-password-reveal/wifi-service.js b/packages/declarative-ui/dist/examples/wifi-password-reveal/wifi-service.js deleted file mode 100644 index 64fbe449..00000000 --- a/packages/declarative-ui/dist/examples/wifi-password-reveal/wifi-service.js +++ /dev/null @@ -1,727 +0,0 @@ -import { callHostTransport, isRealElectronHost } from '../shared/native-ipc.js'; -export const SAMPLE_WIFI_PROFILES = Object.freeze([ - { - id: 'wifi-office-5g', - ssid: 'ZTools-Office-5G', - password: 'ZTools@2026#Secure!', - authType: 'WPA3-Personal', - cipher: 'GCMP', - band: '5 GHz', - isConnected: true, - isOpenNetwork: false, - isEnterprise: false, - signalPercent: 98, - interfaceName: 'WLAN', - lastConnected: '当前已连接', - pinyin: 'ztools office 5g bangongshi', - notes: '公司研发中心高速 5G 频段' - }, - { - id: 'wifi-home-dual', - ssid: 'Xiaomi_Home_WiFi6', - password: 'HomeSweetHome888', - authType: 'WPA2-Personal', - cipher: 'CCMP (AES)', - band: 'Dual-Band (2.4/5 GHz)', - isConnected: false, - isOpenNetwork: false, - isEnterprise: false, - signalPercent: 86, - interfaceName: 'WLAN', - lastConnected: '昨天 22:30', - pinyin: 'xiaomi home wifi6 jiali', - notes: '家里客厅小米路由器' - }, - { - id: 'wifi-guest', - ssid: 'ZTools-Guest', - password: 'Guest123456', - authType: 'WPA2-Personal', - cipher: 'CCMP (AES)', - band: '2.4 GHz', - isConnected: false, - isOpenNetwork: false, - isEnterprise: false, - signalPercent: 75, - interfaceName: 'WLAN', - lastConnected: '3 天前', - pinyin: 'ztools guest fangke', - notes: '访客接待专用网络' - }, - { - id: 'wifi-cafe-open', - ssid: 'Starbucks_Free_WiFi', - password: '', - authType: 'Open', - cipher: 'None', - band: '2.4 GHz', - isConnected: false, - isOpenNetwork: true, - isEnterprise: false, - signalPercent: 62, - interfaceName: 'WLAN', - lastConnected: '1 周前', - pinyin: 'starbucks free wifi xingbake', - notes: '开放网络(无密码,网页认证)' - }, - { - id: 'wifi-corp-8021x', - ssid: 'Corp-Dot1X-Internal', - password: '', - authType: 'WPA2-Enterprise', - cipher: 'CCMP (AES)', - band: '5 GHz', - isConnected: false, - isOpenNetwork: false, - isEnterprise: true, - signalPercent: 80, - interfaceName: 'WLAN', - lastConnected: '2 周前', - pinyin: 'corp dot1x internal qiye', - notes: '802.1X 证书企业内网(无预共享明文密钥)' - } -]); -export function parseNetshWlanProfiles(output) { - if (typeof output !== 'string' || !output.trim()) { - return []; - } - const userProfiles = []; - const seen = new Set(); - const lines = output.split(/\r?\n/); - for (const line of lines) { - const trimmed = line.trim(); - const isEnglishProfile = trimmed.startsWith('All User Profile') || trimmed.startsWith('Current User Profile'); - const isChineseProfile = trimmed.startsWith('所有用户配置文件') || trimmed.startsWith('当前用户配置文件'); - if (isEnglishProfile || isChineseProfile) { - const colonIdx = trimmed.indexOf(':'); - const fullWidthColonIdx = trimmed.indexOf(':'); - const idx = colonIdx !== -1 ? colonIdx : fullWidthColonIdx; - if (idx !== -1) { - const ssid = trimmed.slice(idx + 1).trim(); - if (ssid && !seen.has(ssid)) { - seen.add(ssid); - userProfiles.push(ssid); - } - } - } - } - return userProfiles; -} -export const parseWindowsWlanProfiles = parseNetshWlanProfiles; -const OPEN_AUTH_VALUES = new Set(['open', 'none', '开放式', '无']); -const ENTERPRISE_AUTH_PATTERNS = [/enterprise/i, /802\.1x/i, /企业/]; -export function normalizeSecurityType(rawAuth) { - const val = (rawAuth || '').trim(); - if (!val) - return 'Unknown'; - const lower = val.toLowerCase(); - if (OPEN_AUTH_VALUES.has(lower)) - return 'Open'; - if (lower.includes('wpa3') && ENTERPRISE_AUTH_PATTERNS.some((p) => p.test(val))) - return 'WPA3-Enterprise'; - if (lower.includes('wpa2') && ENTERPRISE_AUTH_PATTERNS.some((p) => p.test(val))) - return 'WPA2-Enterprise'; - if (ENTERPRISE_AUTH_PATTERNS.some((p) => p.test(val))) - return 'WPA2-Enterprise'; - if (lower.includes('wpa3')) - return 'WPA3-Personal'; - if (lower.includes('wpa2') && lower.includes('wpa/')) - return 'WPA/WPA2-Personal'; - if (lower.includes('wpa2')) - return 'WPA2-Personal'; - if (lower.includes('wep')) - return 'WEP'; - return 'WPA2-Personal'; -} -export function parseWindowsWlanProfileDetail(ssidInput, output) { - const cleanInputSsid = (ssidInput || '').trim(); - if (typeof output !== 'string' || !output.trim()) { - return { - ssid: cleanInputSsid, - password: '', - authType: 'Unknown', - cipher: 'Unknown', - isOpenNetwork: false, - isEnterprise: false, - error: { - code: 'InvalidInput', - message: 'Empty netsh output' - } - }; - } - if ((output.includes('Profile "') && output.includes('is not found on the system')) || - output.includes('系统上没有配置文件') || - output.includes('找不到配置文件')) { - return { - ssid: cleanInputSsid, - password: '', - authType: 'Unknown', - cipher: 'Unknown', - isOpenNetwork: false, - isEnterprise: false, - error: { - code: 'ProfileNotFound', - message: `未在系统中找到 Wi-Fi 配置文件 "${cleanInputSsid}"` - } - }; - } - let ssidName = cleanInputSsid; - let authentication = ''; - let cipher = 'CCMP (AES)'; - let securityKeyState = null; - let keyContent = ''; - let keyContentFound = false; - const lines = output.split(/\r?\n/); - for (const line of lines) { - const trimmed = line.trim(); - const colonIdx = trimmed.indexOf(':') !== -1 ? trimmed.indexOf(':') : trimmed.indexOf(':'); - if (colonIdx === -1) - continue; - const key = trimmed.slice(0, colonIdx).trim(); - const val = trimmed.slice(colonIdx + 1).trim(); - if (key.startsWith('SSID name') || key.startsWith('SSID 名称')) { - let parsedSsid = val; - if (parsedSsid.startsWith('"') && parsedSsid.endsWith('"')) { - parsedSsid = parsedSsid.slice(1, -1); - } - if (parsedSsid) - ssidName = parsedSsid; - } - else if (key === 'Authentication' || key === '身份验证') { - authentication = val; - } - else if (key === 'Cipher' || key === '密码' || key === '加密') { - cipher = val; - } - else if (key === 'Security key' || key === 'Security Key' || key === '安全密钥') { - const lowerVal = val.toLowerCase(); - if (lowerVal === 'present' || val === '存在') { - securityKeyState = 'present'; - } - else if (lowerVal === 'absent' || val === '不存在') { - securityKeyState = 'absent'; - } - } - else if (key === 'Key Content' || key === '关键内容') { - keyContent = val; - keyContentFound = true; - } - } - const authType = normalizeSecurityType(authentication); - const isOpenNetwork = authType === 'Open'; - const isEnterprise = authType === 'WPA2-Enterprise' || authType === 'WPA3-Enterprise'; - if (isOpenNetwork) { - return { - ssid: ssidName, - password: '', - authType, - cipher: 'None', - isOpenNetwork: true, - isEnterprise: false - }; - } - if (isEnterprise || securityKeyState === 'absent') { - return { - ssid: ssidName, - password: '', - authType: isEnterprise ? authType : 'WPA2-Enterprise', - cipher, - isOpenNetwork: false, - isEnterprise: true, - error: { - code: 'EnterpriseNetwork', - message: `"${ssidName}" 使用企业级 802.1X/证书认证,本机不存储预共享明文密码` - } - }; - } - if (securityKeyState === 'present' && !keyContentFound) { - return { - ssid: ssidName, - password: '', - authType, - cipher, - isOpenNetwork: false, - isEnterprise: false, - error: { - code: 'PermissionDenied', - message: 'Windows 隐藏了关键内容,请以管理员身份运行以读取明文密钥' - } - }; - } - if (securityKeyState === null && !keyContentFound) { - return { - ssid: ssidName, - password: '', - authType, - cipher, - isOpenNetwork: false, - isEnterprise: false, - error: { - code: 'Unknown', - message: '无法从 netsh 输出中解析出安全密钥信息' - } - }; - } - return { - ssid: ssidName, - password: keyContent, - authType, - cipher, - isOpenNetwork: false, - isEnterprise: false - }; -} -export function parseWifiInterface(output) { - if (typeof output !== 'string' || !output.trim()) - return 'en0'; - const lines = output.split(/\r?\n/); - let inWifiSection = false; - for (const line of lines) { - const trimmed = line.trim(); - if (trimmed === 'Hardware Port: Wi-Fi' || trimmed === 'Hardware Port: AirPort') { - inWifiSection = true; - continue; - } - if (inWifiSection && trimmed.startsWith('Device:')) { - const dev = trimmed.slice('Device:'.length).trim(); - return dev || 'en0'; - } - if (inWifiSection && trimmed.startsWith('Hardware Port:')) { - break; - } - } - return 'en0'; -} -export function escapeWifiQrField(value) { - if (typeof value !== 'string') - return ''; - return value.replace(/([\\;,:""])/g, '\\$1'); -} -export function generateWifiQrString(ssid, password = '', authType = 'WPA2-Personal') { - const cleanSsid = (ssid || '').trim(); - if (!cleanSsid) { - throw new Error('SSID 不能为空'); - } - const isOpen = authType === 'Open' || !password; - const qrType = isOpen ? 'nopass' : authType === 'WEP' ? 'WEP' : 'WPA'; - const escapedSsid = escapeWifiQrField(cleanSsid); - const escapedPwd = isOpen ? '' : escapeWifiQrField(password); - return `WIFI:T:${qrType};S:${escapedSsid};P:${escapedPwd};;`; -} -function computeReedSolomonEcc(data, eccCount) { - const exp = new Uint8Array(512); - const log = new Uint8Array(256); - let x = 1; - for (let i = 0; i < 255; i++) { - exp[i] = x; - log[x] = i; - x = (x << 1) ^ (x & 0x80 ? 0x11d : 0); - } - for (let i = 255; i < 512; i++) - exp[i] = exp[i - 255]; - const gfMul = (a, b) => (a === 0 || b === 0 ? 0 : exp[log[a] + log[b]]); - let gen = [1]; - for (let i = 0; i < eccCount; i++) { - const next = new Array(gen.length + 1).fill(0); - for (let j = 0; j < gen.length; j++) { - next[j] ^= gen[j]; - next[j + 1] ^= gfMul(gen[j], exp[i]); - } - gen = next; - } - const msg = new Uint8Array(data.length + eccCount); - msg.set(data, 0); - for (let i = 0; i < data.length; i++) { - const coef = msg[i]; - if (coef !== 0) { - for (let j = 0; j < gen.length; j++) { - msg[i + j] ^= gfMul(gen[j], coef); - } - } - } - return Array.from(msg.slice(data.length)); -} -function encodeQrMatrixV4L(payload) { - // ISO/IEC 18004 Version 4-L (33x33): 80 data codewords, 20 ECC codewords - const size = 33; - const dataCapacity = 80; - const eccCount = 20; - const utf8 = Array.from(new TextEncoder().encode(payload)).slice(0, dataCapacity - 3); - const bits = []; - const pushBits = (val, len) => { - for (let i = len - 1; i >= 0; i--) - bits.push((val >>> i) & 1); - }; - pushBits(0b0100, 4); - pushBits(utf8.length, 8); - for (const b of utf8) - pushBits(b, 8); - pushBits(0, Math.min(4, dataCapacity * 8 - bits.length)); - while (bits.length % 8 !== 0) - bits.push(0); - const dataBytes = []; - for (let i = 0; i < bits.length; i += 8) { - let byte = 0; - for (let j = 0; j < 8; j++) - byte = (byte << 1) | (bits[i + j] ?? 0); - dataBytes.push(byte); - } - let padToggle = true; - while (dataBytes.length < dataCapacity) { - dataBytes.push(padToggle ? 0xec : 0x11); - padToggle = !padToggle; - } - const eccBytes = computeReedSolomonEcc(dataBytes, eccCount); - const allCodewords = [...dataBytes, ...eccBytes]; - const allBits = []; - for (const b of allCodewords) - pushBits.call({ push: (v) => allBits.push(v) }, b, 8); - const totalBits = []; - for (const b of allCodewords) { - for (let i = 7; i >= 0; i--) - totalBits.push((b >>> i) & 1); - } - const modules = Array.from({ length: size }, () => Array(size).fill(false)); - const isFunc = Array.from({ length: size }, () => Array(size).fill(false)); - const placeFinder = (row, col) => { - for (let r = -1; r <= 7; r++) { - for (let c = -1; c <= 7; c++) { - const rr = row + r; - const cc = col + c; - if (rr < 0 || rr >= size || cc < 0 || cc >= size) - continue; - const inOuter = r >= 0 && r <= 6 && c >= 0 && c <= 6; - const inWhite = r >= 1 && r <= 5 && c >= 1 && c <= 5; - const inCenter = r >= 2 && r <= 4 && c >= 2 && c <= 4; - modules[rr][cc] = inOuter && (!inWhite || inCenter); - isFunc[rr][cc] = true; - } - } - }; - placeFinder(0, 0); - placeFinder(0, size - 7); - placeFinder(size - 7, 0); - // Alignment pattern at (26, 26) for Version 4 - for (let r = -2; r <= 2; r++) { - for (let c = -2; c <= 2; c++) { - const rr = 26 + r; - const cc = 26 + c; - modules[rr][cc] = Math.max(Math.abs(r), Math.abs(c)) !== 1; - isFunc[rr][cc] = true; - } - } - // Timing patterns - for (let i = 8; i < size - 8; i++) { - modules[6][i] = i % 2 === 0; - isFunc[6][i] = true; - modules[i][6] = i % 2 === 0; - isFunc[i][6] = true; - } - // Reserve format info areas & dark module - for (let i = 0; i <= 8; i++) { - isFunc[8][i] = true; - isFunc[i][8] = true; - if (i < 8) { - isFunc[8][size - 1 - i] = true; - isFunc[size - 1 - i][8] = true; - } - } - modules[size - 8][8] = true; - isFunc[size - 8][8] = true; - // Zigzag data placement with mask 0 ((r + c) % 2 === 0) - let bitIdx = 0; - let upward = true; - for (let right = size - 1; right >= 1; right -= 2) { - if (right === 6) - right = 5; - for (let vert = 0; vert < size; vert++) { - const r = upward ? size - 1 - vert : vert; - for (let j = 0; j < 2; j++) { - const c = right - j; - if (!isFunc[r][c]) { - const bit = bitIdx < totalBits.length ? totalBits[bitIdx++] === 1 : false; - const mask = (r + c) % 2 === 0; - modules[r][c] = bit !== mask; - } - } - } - upward = !upward; - } - // Format bits for Level L (01) + Mask 0 (000) => 0x77c4 - const formatBits = 0x77c4; - for (let i = 0; i <= 5; i++) - modules[8][i] = ((formatBits >>> i) & 1) === 1; - modules[8][7] = ((formatBits >>> 6) & 1) === 1; - modules[8][8] = ((formatBits >>> 7) & 1) === 1; - modules[7][8] = ((formatBits >>> 8) & 1) === 1; - for (let i = 9; i < 15; i++) - modules[14 - i][8] = ((formatBits >>> i) & 1) === 1; - for (let i = 0; i < 8; i++) - modules[8][size - 1 - i] = ((formatBits >>> i) & 1) === 1; - for (let i = 8; i < 15; i++) - modules[size - 15 + i][8] = ((formatBits >>> i) & 1) === 1; - return modules; -} -export function generateWifiQrSvgDataUrl(profile) { - const ssidSafe = (profile.ssid || 'Wi-Fi').replace(/[<>&"']/g, ''); - const qrPayload = generateWifiQrString(profile.ssid || 'Wi-Fi', profile.password, profile.authType); - const matrix = encodeQrMatrixV4L(qrPayload); - const size = matrix.length; - const cells = []; - const cellSize = 3.6; - const offsetX = 20; - const offsetY = 16; - for (let r = 0; r < size; r++) { - for (let c = 0; c < size; c++) { - if (matrix[r][c]) { - cells.push(``); - } - } - } - const svg = ` - - - ${cells.join('')} - ${ssidSafe.slice(0, 18)} - `; - return `data:image/svg+xml;utf8,${encodeURIComponent(svg).replace(/\(/g, '%28').replace(/\)/g, '%29')}`; -} -export function filterAndSortWifiProfiles(profiles, options = {}) { - if (!Array.isArray(profiles)) - return []; - const q = (options.query || '').trim().toLowerCase(); - const sec = options.securityFilter || 'all'; - const sortBy = options.sortBy || 'connected'; - const filtered = profiles.filter((item) => { - if (!item || typeof item.ssid !== 'string') - return false; - if (sec === 'connected' && !item.isConnected) - return false; - if (sec === 'wpa3' && !item.authType.includes('WPA3')) - return false; - if (sec === 'wpa2' && !item.authType.includes('WPA2')) - return false; - if (sec === 'open' && !item.isOpenNetwork) - return false; - if (sec === 'enterprise' && !item.isEnterprise) - return false; - if (!q) - return true; - const haystack = `${item.ssid} ${item.authType} ${item.band || ''} ${item.pinyin || ''} ${item.notes || ''}`.toLowerCase(); - return haystack.includes(q); - }); - return [...filtered].sort((a, b) => { - if (sortBy === 'connected') { - if (Boolean(a.isConnected) !== Boolean(b.isConnected)) { - return a.isConnected ? -1 : 1; - } - return (b.signalPercent ?? 0) - (a.signalPercent ?? 0); - } - if (sortBy === 'signal') { - return (b.signalPercent ?? 0) - (a.signalPercent ?? 0); - } - if (sortBy === 'ssid') { - return a.ssid.localeCompare(b.ssid, 'zh-CN'); - } - return a.authType.localeCompare(b.authType); - }); -} -export async function revealWifiPasswordFromHost(ssid, hostOverride) { - const cleanSsid = (ssid || '').trim(); - if (!cleanSsid) - return ''; - let res = await callHostTransport('wifi_get_password', { ssid: cleanSsid }, hostOverride); - if (!res.ok && (String(res.error || '').startsWith('METHOD_NOT_AVAILABLE:') || res.error === 'NO_WINDOW_ENV')) { - res = await callHostTransport('dllplugin_call', { - plugin: 'WifiPasswordPlugin', - func: 'getPassword', - params: { ssid: cleanSsid } - }, hostOverride); - } - if (res.ok && res.data !== undefined) { - if (typeof res.data === 'string') - return res.data.trim(); - const dataObj = (res.data && typeof res.data === 'object' ? res.data : {}); - if (typeof dataObj.password === 'string') - return dataObj.password.trim(); - } - return ''; -} -export async function fetchSavedWifiProfiles(options = {}) { - const realHost = isRealElectronHost(options.hostOverride); - const fallback = options.fallbackToSample ?? (!realHost && !options.hostOverride); - const executor = options.executor; - if (!executor) { - if (options.hostOverride || realHost) { - try { - let res = await callHostTransport('wifi_get_profiles', { interfaceName: options.interfaceName }, options.hostOverride); - if (!res.ok && (String(res.error || '').startsWith('METHOD_NOT_AVAILABLE:') || res.error === 'NO_WINDOW_ENV')) { - res = await callHostTransport('dllplugin_call', { - plugin: 'WifiPasswordPlugin', - func: 'listSavedNetworks', - params: { interfaceName: options.interfaceName } - }, options.hostOverride); - } - if (res.ok && res.data) { - const dataObj = (!Array.isArray(res.data) && typeof res.data === 'object' ? res.data : {}); - const rawList = Array.isArray(res.data) - ? res.data - : Array.isArray(dataObj.profiles) - ? dataObj.profiles - : []; - if (rawList.length > 0) { - const mapped = await Promise.all(rawList.map(async (rawItem, idx) => { - const shouldPrefetchPwd = idx < 5; - if (typeof rawItem === 'string') { - const ssid = rawItem.trim(); - if (!ssid) - return null; - const pwd = shouldPrefetchPwd - ? await revealWifiPasswordFromHost(ssid, options.hostOverride) - : ''; - return { - id: `host-wifi-${ssid}`, - ssid, - password: pwd, - authType: 'WPA2-Personal', - isOpenNetwork: false, - isEnterprise: false, - signalPercent: 88 - }; - } - if (rawItem && typeof rawItem === 'object') { - const rec = rawItem; - const ssid = String(rec.ssid ?? rec.name ?? '').trim(); - if (!ssid) - return null; - const pwd = typeof rec.password === 'string' && rec.password - ? rec.password - : shouldPrefetchPwd - ? await revealWifiPasswordFromHost(ssid, options.hostOverride) - : ''; - const authType = rec.authType - ? normalizeSecurityType(String(rec.authType)) - : 'WPA2-Personal'; - return { - id: String(rec.id ?? `host-wifi-${ssid}`), - ssid, - password: pwd, - authType, - cipher: String(rec.cipher ?? 'CCMP (AES)'), - band: rec.band || 'Dual-Band (2.4/5 GHz)', - isConnected: Boolean(rec.isConnected), - isOpenNetwork: Boolean(rec.isOpenNetwork ?? authType === 'Open'), - isEnterprise: Boolean(rec.isEnterprise ?? authType.includes('Enterprise')), - signalPercent: typeof rec.signalPercent === 'number' ? rec.signalPercent : 88, - interfaceName: String(rec.interfaceName ?? options.interfaceName ?? 'WLAN'), - lastConnected: String(rec.lastConnected ?? '已保存'), - pinyin: typeof rec.pinyin === 'string' ? rec.pinyin : undefined, - notes: typeof rec.notes === 'string' ? rec.notes : undefined - }; - } - return null; - })); - const valid = mapped.filter((x) => x !== null); - return valid; - } - return []; - } - } - catch { - // ignore - } - if (realHost || options.hostOverride) { - return []; - } - } - return fallback ? [...SAMPLE_WIFI_PROFILES] : []; - } - const platform = options.platform || 'win32'; - try { - if (platform === 'win32') { - const rawList = await executor('netsh', ['wlan', 'show', 'profiles']); - const stdout = typeof rawList === 'string' ? rawList : rawList.stdout; - const ssids = parseNetshWlanProfiles(stdout); - if (ssids.length === 0) { - return fallback ? [...SAMPLE_WIFI_PROFILES] : []; - } - const results = []; - for (const ssid of ssids) { - try { - const detailRaw = await executor('netsh', [ - 'wlan', - 'show', - 'profile', - `name=${ssid}`, - 'key=clear' - ]); - const detailOut = typeof detailRaw === 'string' ? detailRaw : detailRaw.stdout; - const parsed = parseWindowsWlanProfileDetail(ssid, detailOut); - results.push({ - id: `win-wifi-${ssid}`, - ssid: parsed.ssid || ssid, - password: parsed.password, - authType: parsed.authType, - cipher: parsed.cipher, - band: 'Dual-Band (2.4/5 GHz)', - isOpenNetwork: parsed.isOpenNetwork, - isEnterprise: parsed.isEnterprise, - signalPercent: 85, - notes: parsed.error?.message - }); - } - catch { - // ignore - } - } - return results.length > 0 ? results : fallback ? [...SAMPLE_WIFI_PROFILES] : []; - } - if (platform === 'darwin') { - const portsRaw = await executor('/usr/sbin/networksetup', ['-listallhardwareports']); - const iface = parseWifiInterface(typeof portsRaw === 'string' ? portsRaw : portsRaw.stdout); - const listRaw = await executor('/usr/sbin/networksetup', ['-listpreferredwirelessnetworks', iface]); - const listOut = typeof listRaw === 'string' ? listRaw : listRaw.stdout; - const ssids = listOut - .split(/\r?\n/) - .slice(1) - .map((s) => s.trim()) - .filter(Boolean); - const results = []; - for (const ssid of ssids) { - let password = ''; - try { - const pwRaw = await executor('/usr/bin/security', [ - 'find-generic-password', - '-D', - 'AirPort network password', - '-a', - ssid, - '-w' - ]); - password = (typeof pwRaw === 'string' ? pwRaw : pwRaw.stdout).trim(); - } - catch { - password = ''; - } - results.push({ - id: `mac-wifi-${ssid}`, - ssid, - password, - authType: password ? 'WPA2-Personal' : 'Open', - isOpenNetwork: !password, - isEnterprise: false, - interfaceName: iface, - signalPercent: 90 - }); - } - return results.length > 0 ? results : fallback ? [...SAMPLE_WIFI_PROFILES] : []; - } - } - catch { - if (!realHost && fallback) { - return [...SAMPLE_WIFI_PROFILES]; - } - throw new Error('WIFI_COMMAND_EXECUTION_FAILED'); - } - return fallback ? [...SAMPLE_WIFI_PROFILES] : []; -} diff --git a/packages/declarative-ui/dist/examples/window-management/index.d.ts b/packages/declarative-ui/dist/examples/window-management/index.d.ts deleted file mode 100644 index 6eb281e1..00000000 --- a/packages/declarative-ui/dist/examples/window-management/index.d.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { WindowActionDefinition, WindowManagementPreferences } from "./types.js"; -export * from "./types.js"; -export * from "./window-actions.js"; -/** - * 窗口偏好配置表单 - */ -export declare function WindowPreferencesForm({ onSaved }?: { - onSaved?: (prefs: WindowManagementPreferences) => void; -}): JSX.Element; -/** - * 窗口动作详情视图 - */ -export declare function WindowActionDetailView({ action, preferences }?: { - action?: WindowActionDefinition; - preferences?: WindowManagementPreferences; -}): JSX.Element; -/** - * 官方内置核心能力: Window Management (窗口调度器) - * 布局一:100% 全宽极简列表,一目了然展示分屏比例、描述与全局快捷键 - */ -export default function WindowManagementCommand(): JSX.Element; diff --git a/packages/declarative-ui/dist/examples/window-management/index.js b/packages/declarative-ui/dist/examples/window-management/index.js deleted file mode 100644 index 0b1b6c92..00000000 --- a/packages/declarative-ui/dist/examples/window-management/index.js +++ /dev/null @@ -1,228 +0,0 @@ -import React from "../../index.js"; -import { List, Detail, Form, ActionPanel, Action, Icon, Color, showHUD, useNavigation } from "../../index.js"; -import { useState, useEffect } from "../../runtime/hooks.js"; -import { WINDOW_ACTIONS, DEFAULT_WINDOW_PREFERENCES, filterWindowActions, getWindowPreferences, saveWindowPreferences, executeWindowAction } from "./window-actions.js"; -export * from "./types.js"; -export * from "./window-actions.js"; -function getActionIcon(item) { - switch (item.id) { - case "left-half": return Icon.SidebarLeft; - case "right-half": return Icon.SidebarRight; - case "top-half": return Icon.ArrowUp; - case "bottom-half": return Icon.ArrowDown; - case "center-half": return Icon.Columns; - case "first-third": return Icon.SidebarLeft; - case "center-third": return Icon.Columns; - case "last-third": return Icon.SidebarRight; - case "first-two-thirds": - case "center-two-thirds": - case "last-two-thirds": return Icon.Layout; - case "top-third": return Icon.ArrowUp; - case "middle-third": return Icon.ArrowsExpand; - case "bottom-third": return Icon.ArrowDown; - case "top-left-quarter": return Icon.ArrowUp; - case "top-right-quarter": return Icon.ArrowUp; - case "bottom-left-quarter": return Icon.ArrowDown; - case "bottom-right-quarter": return Icon.ArrowDown; - case "top-left-sixth": - case "top-center-sixth": - case "top-right-sixth": - case "bottom-left-sixth": - case "bottom-center-sixth": - case "bottom-right-sixth": return Icon.Layout; - case "maximize": return Icon.Maximize; - case "restore": return Icon.Window; - case "almost-maximize": - case "almost-maximize-80": - case "almost-maximize-70": - case "almost-maximize-60": return Icon.ArrowsExpand; - case "reasonable-size": return Icon.AppWindow; - case "center": return Icon.AppWindow; - case "maximize-height": return Icon.ArrowsExpand; - case "maximize-width": return Icon.ArrowsExpand; - case "minimize": return Icon.Minus; - case "next-display": - case "previous-display": return Icon.Monitor; - case "minimize-on-display": return Icon.Monitor; - case "make-larger": return Icon.Plus; - case "make-smaller": return Icon.Minus; - default: return Icon.ArrowsExpand; - } -} -function getActionMarkdown(action, prefs) { - const innerGap = prefs ? prefs.innerGap : 0; - const outerGap = prefs ? prefs.outerGap : 0; - return ` -# 窗口管理动作: ${action.name} - -> **分类**: \`${action.category.toUpperCase()}\` | **全局快捷键**: \`${action.shortcut ?? "未指定"}\` - ---- - -### 功能说明 -${action.description} - -### 当前边距偏好配置 -- **内边距 (innerGap)**: \`${innerGap} px\` -- **外边距 (outerGap)**: \`${outerGap} px\` -- **吸附模式**: \`macOS Menu Bar / Dock WorkArea 自动避让 & Win32 rcWork 栅格计算\` - ---- - -### 原生下沉执行说明 (macOS AXUIElement & Win32 UIAccess) -该动作直接通过双端原生特权管道执行: -- **macOS 端 (\`Accessibility / AXUIElement\`)**: - - 基于 \`System Events\` / \`AXUIElement\` 定位当前前台活动应用主窗口并读写 \`position\` 与 \`size\` - - 基于 \`visibleFrame\` / \`workArea\` 实现 **Menu Bar / Dock WorkArea 自动避让**,确保分屏绝不遮挡顶部菜单栏与底部程序坞 -- **Windows 端 (\`Win32 & ztools-uiaccess\`)**: - - 基于 Win32 \`GetForegroundWindow\` 捕获活动窗口句柄,通过 \`MonitorFromWindow\` 与 \`GetMonitorInfoW\` 读取 \`rcWork\`(主动避让系统任务栏) - - 自动处理最大化窗口还原(\`ShowWindow(SW_RESTORE)\`)与极速重定位(\`SetWindowPos\`) - - 携带 \`SWP_NOACTIVATE | SWP_NOZORDER | SWP_FRAMECHANGED\` 杜绝窗口闪烁,耗时严格控制在 **< 1ms** 内 - `; -} -/** - * 窗口偏好配置表单 - */ -export function WindowPreferencesForm({ onSaved } = {}) { - const { pop } = useNavigation(); - const [innerGap, setInnerGap] = useState("0"); - const [outerGap, setOuterGap] = useState("0"); - const [cycleMode, setCycleMode] = useState("sizes"); - const [percentage, setPercentage] = useState("0.9"); - useEffect(() => { - void getWindowPreferences().then(prefs => { - setInnerGap(String(prefs.innerGap)); - setOuterGap(String(prefs.outerGap)); - setCycleMode(prefs.cycleMode); - setPercentage(String(prefs.percentage)); - }); - }, []); - const handleSave = async () => { - const updated = await saveWindowPreferences({ - innerGap: parseInt(innerGap, 10) || 0, - outerGap: parseInt(outerGap, 10) || 0, - cycleMode: cycleMode === "disabled" ? "disabled" : "sizes", - percentage: parseFloat(percentage) || 0.9 - }); - if (onSaved) - onSaved(updated); - await showHUD("窗口调度偏好设置已更新"); - pop(); - }; - return (React.createElement(Form, { navigationTitle: "\u7A97\u53E3\u7BA1\u7406\u504F\u597D\u8BBE\u7F6E (Window Preferences)", actions: React.createElement(ActionPanel, null, - React.createElement(Action.SubmitForm, { title: "\u4FDD\u5B58\u504F\u597D\u8BBE\u7F6E", onSubmit: handleSave, icon: Icon.Checkmark }), - React.createElement(Action, { title: "\u6062\u590D\u9ED8\u8BA4\u8BBE\u7F6E", icon: Icon.Repeat, onAction: async () => { - await saveWindowPreferences(DEFAULT_WINDOW_PREFERENCES); - setInnerGap("0"); - setOuterGap("0"); - setCycleMode("sizes"); - setPercentage("0.9"); - await showHUD("已恢复默认偏好设置"); - } })) }, - React.createElement(Form.Dropdown, { id: "innerGap", title: "\u5206\u5C4F\u5185\u8FB9\u8DDD (Inner Gap)", value: innerGap, onChange: setInnerGap }, - React.createElement(Form.Dropdown.Item, { value: "0", title: "0 \u50CF\u7D20 (\u7D27\u8D34\u65E0\u7F1D)" }), - React.createElement(Form.Dropdown.Item, { value: "4", title: "4 \u50CF\u7D20 (\u5FAE\u5C0F\u95F4\u9699)" }), - React.createElement(Form.Dropdown.Item, { value: "8", title: "8 \u50CF\u7D20 (\u6807\u51C6\u95F4\u9699)" }), - React.createElement(Form.Dropdown.Item, { value: "12", title: "12 \u50CF\u7D20 (\u8212\u9002\u7559\u767D)" }), - React.createElement(Form.Dropdown.Item, { value: "16", title: "16 \u50CF\u7D20 (\u6781\u5BA2\u5BBD\u677E)" })), - React.createElement(Form.Dropdown, { id: "outerGap", title: "\u5C4F\u5E55\u5916\u8FB9\u8DDD (Outer Gap)", value: outerGap, onChange: setOuterGap }, - React.createElement(Form.Dropdown.Item, { value: "0", title: "0 \u50CF\u7D20 (\u7D27\u8D34\u5C4F\u5E55\u8FB9\u6846)" }), - React.createElement(Form.Dropdown.Item, { value: "4", title: "4 \u50CF\u7D20 (\u5FAE\u8FB9\u8DDD)" }), - React.createElement(Form.Dropdown.Item, { value: "8", title: "8 \u50CF\u7D20 (\u6807\u51C6\u8FB9\u8DDD)" }), - React.createElement(Form.Dropdown.Item, { value: "16", title: "16 \u50CF\u7D20 (\u4E9A\u514B\u529B\u5927\u7559\u767D)" })), - React.createElement(Form.Dropdown, { id: "percentage", title: "\u51E0\u4E4E\u6700\u5927\u5316\u5360\u6BD4 (Percentage)", value: percentage, onChange: setPercentage }, - React.createElement(Form.Dropdown.Item, { value: "0.9", title: "90% \u5C4F\u5E55\u9762\u79EF (\u63A8\u8350)" }), - React.createElement(Form.Dropdown.Item, { value: "0.8", title: "80% \u5C4F\u5E55\u9762\u79EF" }), - React.createElement(Form.Dropdown.Item, { value: "0.7", title: "70% \u5C4F\u5E55\u9762\u79EF" }), - React.createElement(Form.Dropdown.Item, { value: "0.6", title: "60% \u5C4F\u5E55\u9762\u79EF" })), - React.createElement(Form.Dropdown, { id: "cycleMode", title: "\u5FAA\u73AF\u6A21\u5F0F (Cycle Mode)", value: cycleMode, onChange: setCycleMode }, - React.createElement(Form.Dropdown.Item, { value: "sizes", title: "\u5C3A\u5BF8\u5FAA\u73AF (Sizes: 1/2 -> 2/3 -> 1/3)" }), - React.createElement(Form.Dropdown.Item, { value: "disabled", title: "\u7981\u7528\u5FAA\u73AF (\u5355\u6B21\u5438\u9644)" })))); -} -/** - * 窗口动作详情视图 - */ -export function WindowActionDetailView({ action = WINDOW_ACTIONS[0], preferences } = {}) { - const markdown = getActionMarkdown(action, preferences); - return (React.createElement(Detail, { markdown: markdown, navigationTitle: `动作: ${action.name}`, metadata: React.createElement(Detail.Metadata, null, - React.createElement(Detail.Metadata.Label, { title: "\u52A8\u4F5C\u6807\u8BC6", text: action.id, icon: Icon.Key }), - React.createElement(Detail.Metadata.Label, { title: "\u5206\u7C7B", text: action.category.toUpperCase(), icon: Icon.List }), - action.shortcut && (React.createElement(Detail.Metadata.Label, { title: "\u63A8\u8350\u70ED\u952E", text: action.shortcut, icon: Icon.Terminal })), - React.createElement(Detail.Metadata.Separator, null), - React.createElement(Detail.Metadata.TagList, { title: "\u5E95\u5C42\u7BA1\u9053" }, - React.createElement(Detail.Metadata.TagList.Item, { text: "Accessibility (AXUIElement)", color: Color.SecondaryText }), - React.createElement(Detail.Metadata.TagList.Item, { text: "Menu Bar / Dock WorkArea \u81EA\u52A8\u907F\u8BA9", color: Color.SecondaryText }), - React.createElement(Detail.Metadata.TagList.Item, { text: "UIAccess UIPI Bypass", color: Color.SecondaryText }), - React.createElement(Detail.Metadata.TagList.Item, { text: "Win32 SetWindowPos", color: Color.SecondaryText }))), actions: React.createElement(ActionPanel, { title: "\u7A97\u53E3\u52A8\u4F5C" }, - React.createElement(Action, { title: `立即执行: ${action.name}`, icon: Icon.Checkmark, onAction: async () => { - await executeWindowAction(action.id); - } }), - action.shortcut && (React.createElement(Action.CopyToClipboard, { title: "\u590D\u5236\u5FEB\u6377\u952E\u7EC4\u5408", content: action.shortcut, icon: Icon.CopyClipboard }))) })); -} -/** - * 官方内置核心能力: Window Management (窗口调度器) - * 布局一:100% 全宽极简列表,一目了然展示分屏比例、描述与全局快捷键 - */ -export default function WindowManagementCommand() { - const [searchText, setSearchText] = useState(""); - const [category, setCategory] = useState("all"); - const [isShowingDetail, setIsShowingDetail] = useState(false); - const [preferences, setPreferences] = useState(DEFAULT_WINDOW_PREFERENCES); - const [selectedId, setSelectedId] = useState(null); - const { push } = useNavigation(); - useEffect(() => { - void getWindowPreferences().then(setPreferences); - }, []); - const filtered = filterWindowActions(WINDOW_ACTIONS, { - category: category, - query: searchText - }); - const halves = filtered.filter(a => a.category === "halves"); - const thirds = filtered.filter(a => a.category === "thirds"); - const quarters = filtered.filter(a => a.category === "quarters"); - const sixths = filtered.filter(a => a.category === "sixths"); - const centerMax = filtered.filter(a => a.category === "center-max"); - const displays = filtered.filter(a => a.category === "displays"); - const resize = filtered.filter(a => a.category === "resize"); - const handleExecute = async (item) => { - await executeWindowAction(item.id, { preferences }); - }; - const renderActionItem = (item) => (React.createElement(List.Item, { key: item.id, id: item.id, title: item.name, subtitle: item.description, icon: getActionIcon(item), accessories: [ - { tag: { value: item.category.toUpperCase() } }, - ...(item.shortcut ? [{ text: item.shortcut }] : []) - ], detail: React.createElement(List.Item.Detail, { markdown: getActionMarkdown(item, preferences) }), actions: React.createElement(ActionPanel, { title: "\u7A97\u53E3\u52A8\u4F5C" }, - React.createElement(Action, { title: `执行 ${item.name}`, icon: Icon.Checkmark, onAction: () => handleExecute(item) }), - React.createElement(Action.Push, { title: "\u504F\u597D\u8BBE\u7F6E\u4E0E\u8FB9\u8DDD\u5FAE\u8C03", target: React.createElement(WindowPreferencesForm, { onSaved: setPreferences }), icon: Icon.Gear, shortcut: { modifiers: ["ctrl"], key: "return" } }), - React.createElement(Action.Push, { title: "\u5168\u5C4F\u67E5\u770B\u52A8\u4F5C\u8BE6\u60C5\u4E0E\u5E95\u5C42\u8BF4\u660E", target: React.createElement(WindowActionDetailView, { action: item, preferences: preferences }), icon: Icon.Eye, shortcut: { modifiers: ["ctrl"], key: "d" } }), - React.createElement(Action, { title: isShowingDetail ? "关闭右侧详情分栏" : "展开右侧详情分栏", icon: Icon.SidebarRight, shortcut: { modifiers: ["ctrl"], key: "b" }, onAction: () => setIsShowingDetail(!isShowingDetail) }), - item.shortcut && (React.createElement(Action.CopyToClipboard, { title: "\u590D\u5236\u63A8\u8350\u5FEB\u6377\u952E", content: item.shortcut, icon: Icon.CopyClipboard, shortcut: { modifiers: ["ctrl"], key: "c" } }))) })); - return (React.createElement(List, { isShowingDetail: isShowingDetail, searchBarPlaceholder: "\u641C\u7D22\u7A97\u53E3\u7BA1\u7406\u52A8\u4F5C (\u5982: \u5DE6\u534A\u5C4F, \u6700\u5927\u5316, \u5C45\u4E2D, 60%, \u5FEB\u6377\u952E)...", onSearchTextChange: setSearchText, onSelectionChange: setSelectedId, filterBar: { - summaryText: `窗口栅格调度动作 ${filtered.length} 项 · 分屏边距 ${preferences.innerGap}px / ${preferences.outerGap}px · Win32 WorkArea 自动避让`, - actions: [ - { - id: "prefs", - label: "边距偏好设置", - title: "边距偏好设置", - style: "secondary", - onAction: () => { - push(React.createElement(WindowPreferencesForm, { onSaved: setPreferences })); - } - } - ] - }, searchBarAccessory: React.createElement(List.Dropdown, { tooltip: "\u6309\u5206\u7C7B\u7B5B\u9009", value: category, onChange: setCategory }, - React.createElement(List.Dropdown.Item, { title: "\u5168\u90E8\u52A8\u4F5C (All)", value: "all", icon: Icon.List }), - React.createElement(List.Dropdown.Item, { title: "\u534A\u5C4F\u5BF9\u9F50 (Halves)", value: "halves", icon: Icon.SidebarLeft }), - React.createElement(List.Dropdown.Item, { title: "\u4E09\u5206\u5C4F\u4E0E\u6BD4\u4F8B (Thirds)", value: "thirds", icon: Icon.Columns }), - React.createElement(List.Dropdown.Item, { title: "\u56DB\u5206\u5C4F\u4E0E\u89D2\u843D (Quarters)", value: "quarters", icon: Icon.ArrowUp }), - React.createElement(List.Dropdown.Item, { title: "\u516D\u5206\u5C4F\u6805\u683C (Sixths)", value: "sixths", icon: Icon.Layout }), - React.createElement(List.Dropdown.Item, { title: "\u5C45\u4E2D\u4E0E\u94FA\u6EE1 (Center & Max)", value: "center-max", icon: Icon.Maximize }), - React.createElement(List.Dropdown.Item, { title: "\u663E\u793A\u5668\u5207\u6362 (Displays)", value: "displays", icon: Icon.Monitor }), - React.createElement(List.Dropdown.Item, { title: "\u5FAE\u8C03\u7F29\u653E (Resize)", value: "resize", icon: Icon.ArrowsExpand })) }, - halves.length > 0 && (React.createElement(List.Section, { title: "\u534A\u5C4F\u5BF9\u9F50 (Halves)" }, halves.map(renderActionItem))), - thirds.length > 0 && (React.createElement(List.Section, { title: "\u4E09\u5206\u5C4F\u4E0E\u4E3B\u5DE5\u4F5C\u6D41 (Thirds & Two-Thirds)" }, thirds.map(renderActionItem))), - quarters.length > 0 && (React.createElement(List.Section, { title: "\u56DB\u5206\u5C4F\u4E0E\u89D2\u843D\u5438\u9644 (Quarters & Corners)" }, quarters.map(renderActionItem))), - sixths.length > 0 && (React.createElement(List.Section, { title: "\u516D\u5206\u5C4F\u6805\u683C\u6392\u7248 (Sixths Grid)" }, sixths.map(renderActionItem))), - centerMax.length > 0 && (React.createElement(List.Section, { title: "\u5C45\u4E2D\u4E0E\u94FA\u6EE1 (Center & Maximize)" }, centerMax.map(renderActionItem))), - displays.length > 0 && (React.createElement(List.Section, { title: "\u8DE8\u663E\u793A\u5668\u8C03\u5EA6 (Multi-Display Scheduling)" }, displays.map(renderActionItem))), - resize.length > 0 && (React.createElement(List.Section, { title: "\u89C6\u7A97\u5FAE\u8C03\u7F29\u653E (Resize Step by Step)" }, resize.map(renderActionItem))))); -} diff --git a/packages/declarative-ui/dist/examples/window-management/types.d.ts b/packages/declarative-ui/dist/examples/window-management/types.d.ts deleted file mode 100644 index 30908e9f..00000000 --- a/packages/declarative-ui/dist/examples/window-management/types.d.ts +++ /dev/null @@ -1,34 +0,0 @@ -export type WindowActionCategory = "halves" | "thirds" | "quarters" | "sixths" | "center-max" | "displays" | "resize"; -export interface WindowRect { - x: number; - y: number; - width: number; - height: number; -} -export interface WindowActionDefinition { - id: string; - name: string; - category: WindowActionCategory; - description: string; - shortcut?: string; - iconName: string; - keywords?: string[]; -} -export interface WindowManagementPreferences { - innerGap: number; - outerGap: number; - cycleMode: "sizes" | "disabled"; - percentage: number; -} -export interface WindowFilterOptions { - category?: WindowActionCategory | "all"; - query?: string; -} -export interface WindowActionResult { - success: boolean; - actionId: string; - actionName: string; - rect?: WindowRect; - monitor?: WindowRect; - error?: string; -} diff --git a/packages/declarative-ui/dist/examples/window-management/types.js b/packages/declarative-ui/dist/examples/window-management/types.js deleted file mode 100644 index cb0ff5c3..00000000 --- a/packages/declarative-ui/dist/examples/window-management/types.js +++ /dev/null @@ -1 +0,0 @@ -export {}; diff --git a/packages/declarative-ui/dist/examples/window-management/window-actions.d.ts b/packages/declarative-ui/dist/examples/window-management/window-actions.d.ts deleted file mode 100644 index f19b4bab..00000000 --- a/packages/declarative-ui/dist/examples/window-management/window-actions.d.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { WindowActionDefinition, WindowFilterOptions, WindowManagementPreferences, WindowRect, WindowActionResult } from "./types.js"; -export declare const DEFAULT_WINDOW_PREFERENCES: WindowManagementPreferences; -export declare function getWindowPreferences(): Promise; -export declare function saveWindowPreferences(prefs: Partial): Promise; -export declare const WINDOW_ACTIONS: WindowActionDefinition[]; -/** - * 过滤与搜索窗口动作 - */ -export declare function filterWindowActions(actions: WindowActionDefinition[], options: WindowFilterOptions): WindowActionDefinition[]; -/** - * 窗口几何运算引擎 (Pure Geometry Calculator) - * 依照 Raycast 官方栅格划分,完全兼容 innerGap 与 outerGap 边距调整 - */ -export declare function calculateWindowGeometry(actionId: string, curWin: WindowRect, monRect: WindowRect, prefs?: Partial): WindowRect; -export declare function hasWindowBoundsChanged(a: WindowRect, b: WindowRect): boolean; -export declare function recordExternalForegroundWindow(windowId: string, bounds?: WindowRect, isZToolsSelf?: boolean): string; -export declare function getLastExternalForegroundWindow(): string; -export declare function saveWindowState(windowId: string, rect: WindowRect): void; -export declare function getSavedWindowState(windowId: string): WindowRect | undefined; -export declare function clearSavedWindowStates(): void; -/** - * 执行窗口调度动作 - */ -export declare function executeWindowAction(actionId: string, options?: { - windowId?: string; - isZToolsSelf?: boolean; - curWin?: WindowRect; - monRect?: WindowRect; - preferences?: Partial; - hostBridge?: any; - hostOverride?: any; -}): Promise; diff --git a/packages/declarative-ui/dist/examples/window-management/window-actions.js b/packages/declarative-ui/dist/examples/window-management/window-actions.js deleted file mode 100644 index 18dc2fcb..00000000 --- a/packages/declarative-ui/dist/examples/window-management/window-actions.js +++ /dev/null @@ -1,878 +0,0 @@ -import { LocalStorage } from "../../api/storage.js"; -import { getDeclarativeBridge } from "../../api/bridge.js"; -import { showHUD } from "../../api/hud.js"; -import { callHostTransport, isRealElectronHost } from "../shared/native-ipc.js"; -export const DEFAULT_WINDOW_PREFERENCES = { - innerGap: 0, - outerGap: 0, - cycleMode: "sizes", - percentage: 0.9 -}; -const PREFERENCES_STORAGE_KEY = "ztools-window-management-preferences-v1"; -export async function getWindowPreferences() { - try { - const raw = await LocalStorage.getItem(PREFERENCES_STORAGE_KEY); - if (raw && typeof raw === "object") { - return { - innerGap: typeof raw.innerGap === "number" ? Math.max(0, raw.innerGap) : DEFAULT_WINDOW_PREFERENCES.innerGap, - outerGap: typeof raw.outerGap === "number" ? Math.max(0, raw.outerGap) : DEFAULT_WINDOW_PREFERENCES.outerGap, - cycleMode: raw.cycleMode === "disabled" ? "disabled" : "sizes", - percentage: typeof raw.percentage === "number" ? raw.percentage : DEFAULT_WINDOW_PREFERENCES.percentage - }; - } - } - catch { - // fallback - } - return { ...DEFAULT_WINDOW_PREFERENCES }; -} -export async function saveWindowPreferences(prefs) { - const current = await getWindowPreferences(); - const updated = { - ...current, - ...prefs - }; - await LocalStorage.setItem(PREFERENCES_STORAGE_KEY, updated); - return updated; -} -export const WINDOW_ACTIONS = [ - // --- 1. Halves (半屏) --- - { - id: "left-half", - name: "左半屏 (Left Half)", - category: "halves", - description: "将活动窗口吸附至屏幕左半侧,占满垂直高度", - shortcut: "Ctrl + Alt + Left", - iconName: "sidebar-left", - keywords: ["left", "50%", "half", "左", "左半"] - }, - { - id: "right-half", - name: "右半屏 (Right Half)", - category: "halves", - description: "将活动窗口吸附至屏幕右半侧,占满垂直高度", - shortcut: "Ctrl + Alt + Right", - iconName: "sidebar-right", - keywords: ["right", "50%", "half", "右", "右半"] - }, - { - id: "top-half", - name: "上半屏 (Top Half)", - category: "halves", - description: "将活动窗口吸附至屏幕上半侧,占满水平宽度", - shortcut: "Ctrl + Alt + Up", - iconName: "arrow-up", - keywords: ["top", "up", "50%", "half", "上", "上半"] - }, - { - id: "bottom-half", - name: "下半屏 (Bottom Half)", - category: "halves", - description: "将活动窗口吸附至屏幕下半侧,占满水平宽度", - shortcut: "Ctrl + Alt + Down", - iconName: "arrow-down", - keywords: ["bottom", "down", "50%", "half", "下", "下半"] - }, - { - id: "center-half", - name: "居中半屏 (Center Half)", - category: "halves", - description: "将窗口尺寸调整为 50% 屏幕宽度并水平居中,占满垂直高度", - shortcut: "Ctrl + Alt + Shift + C", - iconName: "columns", - keywords: ["center half", "middle half", "居中半屏"] - }, - // --- 2. Thirds (三分屏与两分之三) --- - { - id: "first-third", - name: "左三分之一 (First Third)", - category: "thirds", - description: "占据屏幕最左侧 33.3% 宽度", - shortcut: "Ctrl + Alt + D", - iconName: "sidebar-left", - keywords: ["first third", "left third", "1/3", "左三分之一"] - }, - { - id: "center-third", - name: "中三分之一 (Center Third)", - category: "thirds", - description: "居中放置并占据屏幕中间 33.3% 宽度", - shortcut: "Ctrl + Alt + F", - iconName: "columns", - keywords: ["center third", "middle third", "1/3", "中三分之一"] - }, - { - id: "last-third", - name: "右三分之一 (Last Third)", - category: "thirds", - description: "占据屏幕最右侧 33.3% 宽度", - shortcut: "Ctrl + Alt + G", - iconName: "sidebar-right", - keywords: ["last third", "right third", "1/3", "右三分之一"] - }, - { - id: "first-two-thirds", - name: "左三分之二 (First Two Thirds)", - category: "thirds", - description: "占据左侧 66.6% 宽度,适用于主工作核心窗口", - shortcut: "Ctrl + Alt + E", - iconName: "layout", - keywords: ["first two thirds", "left 2/3", "2/3", "左三分之二"] - }, - { - id: "center-two-thirds", - name: "居中三分之二 (Center Two Thirds)", - category: "thirds", - description: "占据屏幕中间 66.6% 宽度并水平居中", - shortcut: "Ctrl + Alt + Shift + E", - iconName: "layout", - keywords: ["center two thirds", "2/3", "居中三分之二"] - }, - { - id: "last-two-thirds", - name: "右三分之二 (Last Two Thirds)", - category: "thirds", - description: "占据屏幕右侧 66.6% 宽度", - shortcut: "Ctrl + Alt + T", - iconName: "layout", - keywords: ["last two thirds", "right 2/3", "2/3", "右三分之二"] - }, - { - id: "top-third", - name: "上三分之一 (Top Third)", - category: "thirds", - description: "占据屏幕最上方 33.3% 高度", - shortcut: "Ctrl + Alt + Shift + Up", - iconName: "arrow-up", - keywords: ["top third", "1/3 height", "上三分之一"] - }, - { - id: "middle-third", - name: "垂直居中三分之一 (Middle Third)", - category: "thirds", - description: "占据屏幕垂直居中 33.3% 高度", - shortcut: "Ctrl + Alt + Shift + M", - iconName: "arrows-vertical", - keywords: ["middle third", "垂直三分之一"] - }, - { - id: "bottom-third", - name: "下三分之一 (Bottom Third)", - category: "thirds", - description: "占据屏幕最下方 33.3% 高度", - shortcut: "Ctrl + Alt + Shift + Down", - iconName: "arrow-down", - keywords: ["bottom third", "下三分之一"] - }, - // --- 3. Quarters (四分屏 / 角落吸附) --- - { - id: "top-left-quarter", - name: "左上角四分之一 (Top Left Quarter)", - category: "quarters", - description: "占据屏幕左上角 25% 区域 (50% 宽 x 50% 高)", - shortcut: "Ctrl + Alt + U", - iconName: "arrow-ne", - keywords: ["top-left", "corner", "25%", "左上角"] - }, - { - id: "top-right-quarter", - name: "右上角四分之一 (Top Right Quarter)", - category: "quarters", - description: "占据屏幕右上角 25% 区域 (50% 宽 x 50% 高)", - shortcut: "Ctrl + Alt + I", - iconName: "arrow-ne", - keywords: ["top-right", "corner", "25%", "右上角"] - }, - { - id: "bottom-left-quarter", - name: "左下角四分之一 (Bottom Left Quarter)", - category: "quarters", - description: "占据屏幕左下角 25% 区域 (50% 宽 x 50% 高)", - shortcut: "Ctrl + Alt + J", - iconName: "arrow-se", - keywords: ["bottom-left", "corner", "25%", "左下角"] - }, - { - id: "bottom-right-quarter", - name: "右下角四分之一 (Bottom Right Quarter)", - category: "quarters", - description: "占据屏幕右下角 25% 区域 (50% 宽 x 50% 高)", - shortcut: "Ctrl + Alt + K", - iconName: "arrow-se", - keywords: ["bottom-right", "corner", "25%", "右下角"] - }, - // --- 4. Sixths (六分屏) --- - { - id: "top-left-sixth", - name: "左上六分之一 (Top Left Sixth)", - category: "sixths", - description: "占据屏幕左上方 1/6 区域 (33.3% 宽 x 50% 高)", - iconName: "grid", - keywords: ["top left sixth", "1/6", "左上六分之一"] - }, - { - id: "top-center-sixth", - name: "中上六分之一 (Top Center Sixth)", - category: "sixths", - description: "占据屏幕居中上方 1/6 区域 (33.3% 宽 x 50% 高)", - iconName: "grid", - keywords: ["top center sixth", "1/6", "中上六分之一"] - }, - { - id: "top-right-sixth", - name: "右上六分之一 (Top Right Sixth)", - category: "sixths", - description: "占据屏幕右上方 1/6 区域 (33.3% 宽 x 50% 高)", - iconName: "grid", - keywords: ["top right sixth", "1/6", "右上六分之一"] - }, - { - id: "bottom-left-sixth", - name: "左下六分之一 (Bottom Left Sixth)", - category: "sixths", - description: "占据屏幕左下方 1/6 区域 (33.3% 宽 x 50% 高)", - iconName: "grid", - keywords: ["bottom left sixth", "1/6", "左下六分之一"] - }, - { - id: "bottom-center-sixth", - name: "中下六分之一 (Bottom Center Sixth)", - category: "sixths", - description: "占据屏幕居中下方 1/6 区域 (33.3% 宽 x 50% 高)", - iconName: "grid", - keywords: ["bottom center sixth", "1/6", "中下六分之一"] - }, - { - id: "bottom-right-sixth", - name: "右下六分之一 (Bottom Right Sixth)", - category: "sixths", - description: "占据屏幕右下方 1/6 区域 (33.3% 宽 x 50% 高)", - iconName: "grid", - keywords: ["bottom right sixth", "1/6", "右下六分之一"] - }, - // --- 5. Center & Maximize (基础、居中与铺满) --- - { - id: "maximize", - name: "最大化 (Maximize)", - category: "center-max", - description: "将窗口最大化充满整个可用工作区(主动避让系统任务栏)", - shortcut: "Ctrl + Alt + Return", - iconName: "maximize", - keywords: ["max", "fullscreen", "最大化", "满屏"] - }, - { - id: "restore", - name: "还原为常规尺寸 (Restore)", - category: "center-max", - description: "将窗口还原并调整为 70% 居中视窗", - shortcut: "Ctrl + Alt + R", - iconName: "restore", - keywords: ["restore", "unmaximize", "还原", "重置"] - }, - { - id: "almost-maximize", - name: "几乎最大化 90% (Almost Maximize)", - category: "center-max", - description: "将窗口放大至占据屏幕 90% 并保持居中留白", - shortcut: "Ctrl + Alt + M", - iconName: "arrows-expand", - keywords: ["almost maximize", "90%", "几乎最大化"] - }, - { - id: "almost-maximize-80", - name: "几乎最大化 80% (Almost Maximize 80%)", - category: "center-max", - description: "将窗口调整至占据屏幕 80% 并居中", - iconName: "arrows-expand", - keywords: ["almost maximize 80", "80%"] - }, - { - id: "almost-maximize-70", - name: "几乎最大化 70% (Almost Maximize 70%)", - category: "center-max", - description: "将窗口调整至占据屏幕 70% 并居中", - iconName: "arrows-expand", - keywords: ["almost maximize 70", "70%"] - }, - { - id: "almost-maximize-60", - name: "几乎最大化 60% (Almost Maximize 60%)", - category: "center-max", - description: "将窗口调整至占据屏幕 60% 并居中", - iconName: "arrows-expand", - keywords: ["almost maximize 60", "60%"] - }, - { - id: "reasonable-size", - name: "黄金适中尺寸 (Reasonable Size 60%)", - category: "center-max", - description: "调整窗口至 60% 屏幕宽度与 80% 高度(上限 1024x900)", - shortcut: "Ctrl + Alt + S", - iconName: "app-window", - keywords: ["reasonable size", "default", "适中尺寸", "黄金比例"] - }, - { - id: "center", - name: "屏幕居中 (Center)", - category: "center-max", - description: "保持当前视窗尺寸并在当前显示器屏幕正中居中", - shortcut: "Ctrl + Alt + C", - iconName: "center", - keywords: ["center", "middle", "居中", "屏幕中央"] - }, - { - id: "maximize-height", - name: "最大化高度 (Maximize Height)", - category: "center-max", - description: "拉伸窗口使其纵向占满屏幕高度,保持水平宽度不变", - shortcut: "Ctrl + Alt + Shift + Up", - iconName: "arrows-vertical", - keywords: ["max height", "tall", "高度最大化"] - }, - { - id: "maximize-width", - name: "最大化宽度 (Maximize Width)", - category: "center-max", - description: "拉伸窗口使其横向占满屏幕宽度,保持垂直高度不变", - shortcut: "Ctrl + Alt + Shift + Right", - iconName: "arrows-horizontal", - keywords: ["max width", "wide", "宽度最大化"] - }, - { - id: "minimize", - name: "最小化 (Minimize)", - category: "center-max", - description: "将前台窗口最小化至任务栏", - shortcut: "Ctrl + Alt + H", - iconName: "minus", - keywords: ["minimize", "hide", "taskbar", "最小化", "隐藏"] - }, - // --- 6. Displays (跨显示器调度) --- - { - id: "next-display", - name: "移动到下一显示器 (Next Display)", - category: "displays", - description: "将当前窗口投递至下一物理显示器相对等比坐标", - shortcut: "Ctrl + Alt + N", - iconName: "monitor", - keywords: ["next display", "screen", "monitor", "下一显示器", "多屏"] - }, - { - id: "previous-display", - name: "移动到上一显示器 (Previous Display)", - category: "displays", - description: "将当前窗口投递至上一物理显示器相对等比坐标", - shortcut: "Ctrl + Alt + P", - iconName: "monitor", - keywords: ["previous display", "screen", "monitor", "上一显示器", "多屏"] - }, - { - id: "minimize-on-display", - name: "最小化此屏幕所有窗口 (Minimize on This Display)", - category: "displays", - description: "最小化当前屏幕上所有应用程序窗口(快速显示桌面)", - shortcut: "Ctrl + Alt + Shift + D", - iconName: "desktop", - keywords: ["minimize all", "show desktop", "显示桌面"] - }, - // --- 7. Resize (微调步长缩放) --- - { - id: "make-larger", - name: "视窗放大 (Make Larger)", - category: "resize", - description: "窗口向四周等比外扩 10%(或指定 32px 步长)", - shortcut: "Ctrl + Alt + Plus", - iconName: "plus", - keywords: ["make larger", "grow", "zoom in", "放大"] - }, - { - id: "make-smaller", - name: "视窗缩小 (Make Smaller)", - category: "resize", - description: "窗口向中心等比收缩 10%(保留 300x200 最小限制)", - shortcut: "Ctrl + Alt + Minus", - iconName: "minus", - keywords: ["make smaller", "shrink", "zoom out", "缩小"] - } -]; -// 兼容别名映射 (Aliases) -const ALIASES = { - "top-left": "top-left-quarter", - "top-right": "top-right-quarter", - "bottom-left": "bottom-left-quarter", - "bottom-right": "bottom-right-quarter", - "maximize-almost": "almost-maximize" -}; -/** - * 过滤与搜索窗口动作 - */ -export function filterWindowActions(actions, options) { - let result = [...actions]; - if (options.category && options.category !== "all") { - result = result.filter(a => a.category === options.category); - } - if (options.query && options.query.trim()) { - const q = options.query.trim().toLowerCase(); - result = result.filter(a => { - const inId = a.id.toLowerCase().includes(q); - const inName = a.name.toLowerCase().includes(q); - const inDesc = a.description.toLowerCase().includes(q); - const inShortcut = a.shortcut ? a.shortcut.toLowerCase().includes(q) : false; - const inKeywords = a.keywords ? a.keywords.some(k => k.toLowerCase().includes(q)) : false; - return inId || inName || inDesc || inShortcut || inKeywords; - }); - } - return result; -} -/** - * 窗口几何运算引擎 (Pure Geometry Calculator) - * 依照 Raycast 官方栅格划分,完全兼容 innerGap 与 outerGap 边距调整 - */ -export function calculateWindowGeometry(actionId, curWin, monRect, prefs = {}) { - const outerGap = Math.max(0, prefs.outerGap ?? DEFAULT_WINDOW_PREFERENCES.outerGap); - const innerGap = Math.max(0, prefs.innerGap ?? DEFAULT_WINDOW_PREFERENCES.innerGap); - const percentage = prefs.percentage ?? DEFAULT_WINDOW_PREFERENCES.percentage; - // 有效工作区 (减去 outerGap) - const effX = monRect.x + outerGap; - const effY = monRect.y + outerGap; - const effW = Math.max(100, monRect.width - 2 * outerGap); - const effH = Math.max(100, monRect.height - 2 * outerGap); - const resolvedId = ALIASES[actionId] || actionId; - switch (resolvedId) { - // --- 1. Halves --- - case "left-half": { - const halfW = Math.floor((effW - innerGap) / 2); - return { x: effX, y: effY, width: halfW, height: effH }; - } - case "right-half": { - const halfW = Math.floor((effW - innerGap) / 2); - const rightW = effW - halfW - innerGap; - return { x: effX + halfW + innerGap, y: effY, width: rightW, height: effH }; - } - case "top-half": { - const halfH = Math.floor((effH - innerGap) / 2); - return { x: effX, y: effY, width: effW, height: halfH }; - } - case "bottom-half": { - const halfH = Math.floor((effH - innerGap) / 2); - const bottomH = effH - halfH - innerGap; - return { x: effX, y: effY + halfH + innerGap, width: effW, height: bottomH }; - } - case "center-half": { - const w = Math.floor(effW * 0.5); - const x = effX + Math.floor((effW - w) / 2); - return { x, y: effY, width: w, height: effH }; - } - // --- 2. Thirds --- - case "first-third": { - const unitW = Math.floor((effW - 2 * innerGap) / 3); - return { x: effX, y: effY, width: unitW, height: effH }; - } - case "center-third": { - const unitW = Math.floor((effW - 2 * innerGap) / 3); - return { x: effX + unitW + innerGap, y: effY, width: unitW, height: effH }; - } - case "last-third": { - const unitW = Math.floor((effW - 2 * innerGap) / 3); - const lastW = effW - 2 * unitW - 2 * innerGap; - return { x: effX + 2 * (unitW + innerGap), y: effY, width: lastW, height: effH }; - } - case "first-two-thirds": { - const unitW = Math.floor((effW - 2 * innerGap) / 3); - const twoThirdsW = 2 * unitW + innerGap; - return { x: effX, y: effY, width: twoThirdsW, height: effH }; - } - case "center-two-thirds": { - const unitW = Math.floor((effW - 2 * innerGap) / 3); - const twoThirdsW = 2 * unitW + innerGap; - const x = effX + Math.floor((effW - twoThirdsW) / 2); - return { x, y: effY, width: twoThirdsW, height: effH }; - } - case "last-two-thirds": { - const unitW = Math.floor((effW - 2 * innerGap) / 3); - const twoThirdsW = effW - unitW - innerGap; - return { x: effX + unitW + innerGap, y: effY, width: twoThirdsW, height: effH }; - } - case "top-third": { - const unitH = Math.floor((effH - 2 * innerGap) / 3); - return { x: effX, y: effY, width: effW, height: unitH }; - } - case "middle-third": { - const unitH = Math.floor((effH - 2 * innerGap) / 3); - return { x: effX, y: effY + unitH + innerGap, width: effW, height: unitH }; - } - case "bottom-third": { - const unitH = Math.floor((effH - 2 * innerGap) / 3); - const bottomH = effH - 2 * unitH - 2 * innerGap; - return { x: effX, y: effY + 2 * (unitH + innerGap), width: effW, height: bottomH }; - } - // --- 3. Quarters --- - case "top-left-quarter": { - const halfW = Math.floor((effW - innerGap) / 2); - const halfH = Math.floor((effH - innerGap) / 2); - return { x: effX, y: effY, width: halfW, height: halfH }; - } - case "top-right-quarter": { - const halfW = Math.floor((effW - innerGap) / 2); - const rightW = effW - halfW - innerGap; - const halfH = Math.floor((effH - innerGap) / 2); - return { x: effX + halfW + innerGap, y: effY, width: rightW, height: halfH }; - } - case "bottom-left-quarter": { - const halfW = Math.floor((effW - innerGap) / 2); - const halfH = Math.floor((effH - innerGap) / 2); - const bottomH = effH - halfH - innerGap; - return { x: effX, y: effY + halfH + innerGap, width: halfW, height: bottomH }; - } - case "bottom-right-quarter": { - const halfW = Math.floor((effW - innerGap) / 2); - const rightW = effW - halfW - innerGap; - const halfH = Math.floor((effH - innerGap) / 2); - const bottomH = effH - halfH - innerGap; - return { x: effX + halfW + innerGap, y: effY + halfH + innerGap, width: rightW, height: bottomH }; - } - // --- 4. Sixths (3 columns x 2 rows) --- - case "top-left-sixth": { - const unitW = Math.floor((effW - 2 * innerGap) / 3); - const halfH = Math.floor((effH - innerGap) / 2); - return { x: effX, y: effY, width: unitW, height: halfH }; - } - case "top-center-sixth": { - const unitW = Math.floor((effW - 2 * innerGap) / 3); - const halfH = Math.floor((effH - innerGap) / 2); - return { x: effX + unitW + innerGap, y: effY, width: unitW, height: halfH }; - } - case "top-right-sixth": { - const unitW = Math.floor((effW - 2 * innerGap) / 3); - const rightW = effW - 2 * unitW - 2 * innerGap; - const halfH = Math.floor((effH - innerGap) / 2); - return { x: effX + 2 * (unitW + innerGap), y: effY, width: rightW, height: halfH }; - } - case "bottom-left-sixth": { - const unitW = Math.floor((effW - 2 * innerGap) / 3); - const halfH = Math.floor((effH - innerGap) / 2); - const bottomH = effH - halfH - innerGap; - return { x: effX, y: effY + halfH + innerGap, width: unitW, height: bottomH }; - } - case "bottom-center-sixth": { - const unitW = Math.floor((effW - 2 * innerGap) / 3); - const halfH = Math.floor((effH - innerGap) / 2); - const bottomH = effH - halfH - innerGap; - return { x: effX + unitW + innerGap, y: effY + halfH + innerGap, width: unitW, height: bottomH }; - } - case "bottom-right-sixth": { - const unitW = Math.floor((effW - 2 * innerGap) / 3); - const rightW = effW - 2 * unitW - 2 * innerGap; - const halfH = Math.floor((effH - innerGap) / 2); - const bottomH = effH - halfH - innerGap; - return { x: effX + 2 * (unitW + innerGap), y: effY + halfH + innerGap, width: rightW, height: bottomH }; - } - // --- 5. Center & Maximize --- - case "maximize": { - return { x: effX, y: effY, width: effW, height: effH }; - } - case "restore": { - const w = Math.round(effW * 0.7); - const h = Math.round(effH * 0.7); - return { - x: effX + Math.round((effW - w) / 2), - y: effY + Math.round((effH - h) / 2), - width: w, - height: h - }; - } - case "almost-maximize": { - const w = Math.round(effW * percentage); - const h = Math.round(effH * percentage); - return { - x: effX + Math.round((effW - w) / 2), - y: effY + Math.round((effH - h) / 2), - width: w, - height: h - }; - } - case "almost-maximize-80": { - const w = Math.round(effW * 0.8); - const h = Math.round(effH * 0.8); - return { - x: effX + Math.round((effW - w) / 2), - y: effY + Math.round((effH - h) / 2), - width: w, - height: h - }; - } - case "almost-maximize-70": { - const w = Math.round(effW * 0.7); - const h = Math.round(effH * 0.7); - return { - x: effX + Math.round((effW - w) / 2), - y: effY + Math.round((effH - h) / 2), - width: w, - height: h - }; - } - case "almost-maximize-60": { - const w = Math.round(effW * 0.6); - const h = Math.round(effH * 0.6); - return { - x: effX + Math.round((effW - w) / 2), - y: effY + Math.round((effH - h) / 2), - width: w, - height: h - }; - } - case "reasonable-size": { - const w = Math.min(1024, Math.round(effW * 0.6)); - const h = Math.min(900, Math.round(effH * 0.8)); - return { - x: effX + Math.round((effW - w) / 2), - y: effY + Math.round((effH - h) / 2), - width: w, - height: h - }; - } - case "center": { - const w = Math.max(300, Math.min(curWin.width, effW)); - const h = Math.max(200, Math.min(curWin.height, effH)); - return { - x: effX + Math.round((effW - w) / 2), - y: effY + Math.round((effH - h) / 2), - width: w, - height: h - }; - } - case "maximize-height": { - return { - x: curWin.x, - y: effY, - width: curWin.width, - height: effH - }; - } - case "maximize-width": { - return { - x: effX, - y: curWin.y, - width: effW, - height: curWin.height - }; - } - // --- 6. Resize --- - case "make-larger": { - const addW = Math.round(curWin.width * 0.1); - const addH = Math.round(curWin.height * 0.1); - const newW = Math.min(effW, curWin.width + addW); - const newH = Math.min(effH, curWin.height + addH); - return { - x: Math.max(effX, curWin.x - Math.round(addW / 2)), - y: Math.max(effY, curWin.y - Math.round(addH / 2)), - width: newW, - height: newH - }; - } - case "make-smaller": { - const subW = Math.round(curWin.width * 0.1); - const subH = Math.round(curWin.height * 0.1); - const newW = Math.max(300, curWin.width - subW); - const newH = Math.max(200, curWin.height - subH); - return { - x: curWin.x + Math.round(subW / 2), - y: curWin.y + Math.round(subH / 2), - width: newW, - height: newH - }; - } - default: - return { ...curWin }; - } -} -const savedWindowStatesMap = new Map(); -const currentWindowRectsMap = new Map(); -let lastExternalForegroundHwnd = "external-active-window"; -export function hasWindowBoundsChanged(a, b) { - return (Math.round(a.x) !== Math.round(b.x) || - Math.round(a.y) !== Math.round(b.y) || - Math.round(a.width) !== Math.round(b.width) || - Math.round(a.height) !== Math.round(b.height)); -} -export function recordExternalForegroundWindow(windowId, bounds, isZToolsSelf = false) { - const cleaned = String(windowId || "").trim(); - if (!cleaned || isZToolsSelf || cleaned.toLowerCase().startsWith("ztools")) { - return lastExternalForegroundHwnd; - } - lastExternalForegroundHwnd = cleaned; - if (bounds) { - currentWindowRectsMap.set(cleaned, { ...bounds }); - } - return lastExternalForegroundHwnd; -} -export function getLastExternalForegroundWindow() { - return lastExternalForegroundHwnd; -} -export function saveWindowState(windowId, rect) { - if (!windowId) - return; - savedWindowStatesMap.set(windowId, { - x: Math.round(rect.x), - y: Math.round(rect.y), - width: Math.round(rect.width), - height: Math.round(rect.height) - }); -} -export function getSavedWindowState(windowId) { - if (!windowId) - return undefined; - const saved = savedWindowStatesMap.get(windowId); - return saved ? { ...saved } : undefined; -} -export function clearSavedWindowStates() { - savedWindowStatesMap.clear(); - currentWindowRectsMap.clear(); - lastExternalForegroundHwnd = "external-active-window"; -} -/** - * 执行窗口调度动作 - */ -export async function executeWindowAction(actionId, options = {}) { - if (typeof actionId !== "string" || !actionId.trim()) { - return { - success: false, - actionId: String(actionId || ""), - actionName: "", - error: "窗口调度动作标识不能为空" - }; - } - const definition = WINDOW_ACTIONS.find(a => a.id === actionId || ALIASES[actionId] === a.id); - const actionName = definition ? definition.name : actionId; - const rawWinId = String(options.windowId || "").trim(); - const targetWindowId = !rawWinId || options.isZToolsSelf || rawWinId.toLowerCase().startsWith("ztools") - ? lastExternalForegroundHwnd - : rawWinId; - if (targetWindowId && !targetWindowId.toLowerCase().startsWith("ztools")) { - lastExternalForegroundHwnd = targetWindowId; - } - const defaultMon = { x: 0, y: 0, width: 1920, height: 1040 }; - const defaultWin = { x: 100, y: 100, width: 800, height: 600 }; - const mon = options.monRect ?? defaultMon; - const cur = options.curWin ?? currentWindowRectsMap.get(targetWindowId) ?? defaultWin; - const prefs = options.preferences ?? await getWindowPreferences(); - let computedRect; - const resolvedId = ALIASES[actionId] || actionId; - // 动作前的位置作为“还原”记录点;宿主确认成功后才写入,失败时不覆盖上一次的记录点 - let restorePoint; - if (resolvedId === "restore") { - const saved = getSavedWindowState(targetWindowId); - if (saved) { - computedRect = { ...saved }; - if (hasWindowBoundsChanged(cur, saved)) { - restorePoint = cur; - } - } - else { - computedRect = calculateWindowGeometry(actionId, cur, mon, prefs); - } - } - else { - computedRect = calculateWindowGeometry(actionId, cur, mon, prefs); - if (hasWindowBoundsChanged(cur, computedRect)) { - restorePoint = cur; - } - } - const hostBridge = options.hostBridge ?? options.hostOverride; - let hostExecuted = false; - let hostError = ""; - // 1. 优先尝试调用方注入的 hostBridge.executeAction(window.ztools 上没有 windowManagement 命名空间) - const customExec = typeof hostBridge?.executeAction === "function" ? hostBridge.executeAction : null; - if (customExec) { - try { - const res = await customExec(actionId, { windowId: targetWindowId, rect: computedRect }); - if (res && typeof res === "object" && (res.ok === false || res.success === false)) { - return { - success: false, - actionId, - actionName, - rect: computedRect, - monitor: mon, - error: String(res.error || res.message || "宿主窗口调度执行失败") - }; - } - hostExecuted = true; - } - catch (err) { - return { - success: false, - actionId, - actionName, - rect: computedRect, - monitor: mon, - error: err instanceof Error ? err.message : String(err) - }; - } - } - // 2. 通过宿主 IPC window_manage_action 调度真实前台窗口 - if (!hostExecuted && (hostBridge || isRealElectronHost(hostBridge))) { - const ipcRes = await callHostTransport("window_manage_action", - // 契约只接受 action;宿主自行定位前台窗口并计算目标区域(会把 _ 规范成 -) - { action: actionId }, hostBridge); - if (ipcRes.ok && ipcRes.data?.ok !== false && ipcRes.data?.success !== false) { - hostExecuted = true; - if (ipcRes.data?.rect && typeof ipcRes.data.rect.width === "number") { - computedRect = ipcRes.data.rect; - } - } - else { - hostError = ipcRes.error || String(ipcRes.data?.error || ipcRes.data?.message || "宿主窗口句柄移动失败"); - return { - success: false, - actionId, - actionName, - rect: computedRect, - monitor: mon, - error: hostError - }; - } - } - // 3. 兼容 Declarative Bridge manageWindow:按返回值判断成败 - if (!hostExecuted) { - const bridge = getDeclarativeBridge(); - if (!bridge?.manageWindow) { - return { - success: false, - actionId, - actionName, - rect: computedRect, - monitor: mon, - error: "未连接 ZTools 宿主,无法调整窗口" - }; - } - try { - const ok = await bridge.manageWindow(actionId); - if (ok === false) { - return { success: false, actionId, actionName, rect: computedRect, monitor: mon, error: "宿主窗口调度执行失败" }; - } - } - catch (err) { - return { - success: false, - actionId, - actionName, - rect: computedRect, - monitor: mon, - error: err instanceof Error ? err.message : String(err) - }; - } - } - // 宿主确认成功后才记录还原点与窗口的新位置 - if (restorePoint) - saveWindowState(targetWindowId, restorePoint); - currentWindowRectsMap.set(targetWindowId, { ...computedRect }); - // 提示 HUD - await showHUD(`已吸附: ${actionName}`); - return { - success: true, - actionId, - actionName, - rect: computedRect, - monitor: mon - }; -} diff --git a/packages/declarative-ui/dist/examples/windows-run/index.d.ts b/packages/declarative-ui/dist/examples/windows-run/index.d.ts deleted file mode 100644 index 155d4384..00000000 --- a/packages/declarative-ui/dist/examples/windows-run/index.d.ts +++ /dev/null @@ -1,18 +0,0 @@ -/** - * Windows Run Dialog (极客运行中枢) - * - * 功能概览: - * - 系统命令与可执行文件检索 (PATH / System32 / MSC / CPL) - * - 命令参数化执行 (如 ping 1.1.1.1 或 code .) - * - 运行历史记录入库与排序 - * - ActionPanel 动作集: - * - Run (普通启动) - * - Run as Administrator (提权以管理员身份运行) - * - Run in PowerShell (在 PowerShell 中执行并保持窗口) - * - Run in Command Prompt (CMD) (在 CMD 中执行) - * - Copy Command (复制完整命令行) - * - Clear Run History (清空运行历史) - */ -export * from "./types.js"; -export * from "./run-service.js"; -export default function WindowsRunCommand(): JSX.Element; diff --git a/packages/declarative-ui/dist/examples/windows-run/index.js b/packages/declarative-ui/dist/examples/windows-run/index.js deleted file mode 100644 index 0c483ec2..00000000 --- a/packages/declarative-ui/dist/examples/windows-run/index.js +++ /dev/null @@ -1,127 +0,0 @@ -/** - * Windows Run Dialog (极客运行中枢) - * - * 功能概览: - * - 系统命令与可执行文件检索 (PATH / System32 / MSC / CPL) - * - 命令参数化执行 (如 ping 1.1.1.1 或 code .) - * - 运行历史记录入库与排序 - * - ActionPanel 动作集: - * - Run (普通启动) - * - Run as Administrator (提权以管理员身份运行) - * - Run in PowerShell (在 PowerShell 中执行并保持窗口) - * - Run in Command Prompt (CMD) (在 CMD 中执行) - * - Copy Command (复制完整命令行) - * - Clear Run History (清空运行历史) - */ -import React from "../../index.js"; -import { List, ActionPanel, Action, Icon, showToast, Toast, Clipboard } from "../../index.js"; -import { useState, useMemo, useEffect } from "../../runtime/hooks.js"; -import { defaultWindowsRunManager, parseCommandLine } from "./run-service.js"; -export * from "./types.js"; -export * from "./run-service.js"; -export default function WindowsRunCommand() { - const [searchText, setSearchText] = useState(""); - const [history, setHistory] = useState([]); - const [refreshTrigger, setRefreshTrigger] = useState(0); - useEffect(() => { - let active = true; - defaultWindowsRunManager.getHistory().then((h) => { - if (active) - setHistory(h); - }); - return () => { - active = false; - }; - }, [refreshTrigger]); - const reloadHistory = () => { - setRefreshTrigger((prev) => prev + 1); - }; - const handleExecute = async (cmdLine, options = {}) => { - const raw = cmdLine.trim(); - if (!raw) { - await showToast(Toast.Style.Failure, "请输入需要执行的命令"); - return; - } - try { - const res = await defaultWindowsRunManager.execute(raw, options); - if (res.success) { - await showToast(Toast.Style.Success, res.message, options.asAdministrator ? "管理员特权启动" : options.shell ? `终端: ${options.shell.toUpperCase()}` : ""); - reloadHistory(); - } - else { - await showToast(Toast.Style.Failure, "执行失败", res.error || res.message); - } - } - catch (err) { - await showToast(Toast.Style.Failure, "执行命令异常", err.message || String(err)); - } - }; - const handleCopy = async (cmdLine) => { - await Clipboard.copy(cmdLine); - await showToast(Toast.Style.Success, "已复制命令到剪贴板", cmdLine); - }; - const handleClearHistory = async () => { - await defaultWindowsRunManager.clearHistory(); - setHistory([]); - await showToast(Toast.Style.Success, "运行历史已清空"); - }; - const handleDeleteHistoryItem = async (id) => { - await defaultWindowsRunManager.deleteHistoryItem(id); - reloadHistory(); - await showToast(Toast.Style.Success, "已从历史记录中移除"); - }; - // 搜索与过滤逻辑 - const query = searchText.trim(); - const parsed = useMemo(() => parseCommandLine(query), [query]); - const searchData = useMemo(() => { - const lower = query.toLowerCase(); - // 1. 匹配历史 - const matchedHistory = history.filter((h) => h.fullCommandLine.toLowerCase().includes(lower) || - h.command.toLowerCase().includes(lower)); - return { - matchedHistory - }; - }, [query, history]); - // 构建动作面板 - const renderActionPanel = (cmdLine, historyId) => (React.createElement(ActionPanel, { title: `运行: ${cmdLine}` }, - React.createElement(Action, { title: "\u8FD0\u884C (Run)", icon: Icon.Play, onAction: () => handleExecute(cmdLine, { shell: "none" }) }), - React.createElement(Action, { title: "\u4EE5\u7BA1\u7406\u5458\u8EAB\u4EFD\u8FD0\u884C (Run as Administrator)", icon: Icon.Shield, shortcut: { modifiers: ["ctrl", "shift"], key: "enter" }, onAction: () => handleExecute(cmdLine, { asAdministrator: true }) }), - React.createElement(Action, { title: "\u5728 PowerShell \u4E2D\u8FD0\u884C (Run in PowerShell)", icon: Icon.Terminal, shortcut: { modifiers: ["ctrl"], key: "p" }, onAction: () => handleExecute(cmdLine, { shell: "powershell" }) }), - React.createElement(Action, { title: "\u5728 CMD \u4E2D\u8FD0\u884C (Run in CMD)", icon: Icon.Terminal, shortcut: { modifiers: ["ctrl"], key: "c" }, onAction: () => handleExecute(cmdLine, { shell: "cmd" }) }), - React.createElement(Action, { title: "\u590D\u5236\u5B8C\u6574\u547D\u4EE4 (Copy Command)", icon: Icon.Clipboard, shortcut: { modifiers: ["ctrl"], key: "y" }, onAction: () => handleCopy(cmdLine) }), - historyId && (React.createElement(Action, { title: "\u4ECE\u5386\u53F2\u8BB0\u5F55\u5220\u9664", icon: Icon.Trash, onAction: () => handleDeleteHistoryItem(historyId) })), - history.length > 0 && (React.createElement(Action, { title: "\u6E05\u7A7A\u8FD0\u884C\u5386\u53F2 (Clear Run History)", icon: Icon.Trash, shortcut: { modifiers: ["ctrl", "shift"], key: "x" }, onAction: handleClearHistory })))); - return (React.createElement(List, { searchBarPlaceholder: "\u8F93\u5165\u547D\u4EE4\u6216\u8DEF\u5F84 (\u5982 ping 1.1.1.1, code ., regedit, ncpa.cpl)...", onSearchTextChange: setSearchText }, - query.length > 0 && (React.createElement(List.Section, { title: "\u6267\u884C\u8F93\u5165\u6307\u4EE4" }, - React.createElement(List.Item, { key: `direct-${query}`, title: query, subtitle: parsed.arguments - ? `命令: ${parsed.command} | 参数: ${parsed.arguments}` - : `直接运行命令: ${parsed.command}`, accessories: [{ text: parsed.kind.toUpperCase() }], actions: renderActionPanel(query) }))), - searchData.matchedHistory.length > 0 && (React.createElement(List.Section, { title: "\u6700\u8FD1\u8FD0\u884C\u5386\u53F2 (Recent History)" }, searchData.matchedHistory.map((item) => (React.createElement(List.Item, { key: item.id, title: item.fullCommandLine, subtitle: item.runCount > 1 - ? `运行 ${item.runCount} 次 • ${new Date(item.executedAt).toLocaleTimeString()}` - : `最近执行 • ${new Date(item.executedAt).toLocaleTimeString()}`, accessories: [ - ...(item.asAdmin ? [{ text: "ADMIN" }] : []), - ...(item.shell ? [{ text: item.shell.toUpperCase() }] : []), - { text: "历史" } - ], actions: renderActionPanel(item.fullCommandLine, item.id) }))))), - React.createElement(List.Section, { title: "\u7CFB\u7EDF\u7BA1\u7406\u4E0E\u63A7\u5236\u53F0 (System & Management)" }, - React.createElement(List.Item, { key: "item-regedit", title: "regedit", subtitle: "\u6CE8\u518C\u8868\u7F16\u8F91\u5668 (Registry Editor)", accessories: [{ text: "系统管理" }], actions: renderActionPanel("regedit.exe") }), - React.createElement(List.Item, { key: "item-taskmgr", title: "taskmgr", subtitle: "\u4EFB\u52A1\u7BA1\u7406\u5668 (Task Manager)", accessories: [{ text: "系统管理" }], actions: renderActionPanel("taskmgr.exe") }), - React.createElement(List.Item, { key: "item-services", title: "services.msc", subtitle: "\u7CFB\u7EDF\u540E\u53F0\u670D\u52A1\u7BA1\u7406 (Windows Services)", accessories: [{ text: "MMC 控制台" }], actions: renderActionPanel("services.msc") }), - React.createElement(List.Item, { key: "item-gpedit", title: "gpedit.msc", subtitle: "\u672C\u5730\u7EC4\u7B56\u7565\u7F16\u8F91\u5668 (Group Policy)", accessories: [{ text: "MMC 控制台" }], actions: renderActionPanel("gpedit.msc") }), - React.createElement(List.Item, { key: "item-compmgmt", title: "compmgmt.msc", subtitle: "\u8BA1\u7B97\u673A\u7BA1\u7406\u4E2D\u67A2 (Computer Management)", accessories: [{ text: "MMC 控制台" }], actions: renderActionPanel("compmgmt.msc") }), - React.createElement(List.Item, { key: "item-devmgmt", title: "devmgmt.msc", subtitle: "\u8BBE\u5907\u7BA1\u7406\u5668\u9A71\u52A8\u6CBB\u7406 (Device Manager)", accessories: [{ text: "MMC 控制台" }], actions: renderActionPanel("devmgmt.msc") }), - React.createElement(List.Item, { key: "item-dxdiag", title: "dxdiag", subtitle: "DirectX \u8BCA\u65AD\u786C\u4EF6\u5DE5\u5177", accessories: [{ text: "硬件诊断" }], actions: renderActionPanel("dxdiag.exe") }), - React.createElement(List.Item, { key: "item-cleanmgr", title: "cleanmgr", subtitle: "\u78C1\u76D8\u5783\u573E\u6E05\u7406\u5DE5\u5177 (Disk Cleanup)", accessories: [{ text: "磁盘清理" }], actions: renderActionPanel("cleanmgr.exe") }), - React.createElement(List.Item, { key: "item-perfmon", title: "perfmon", subtitle: "\u6027\u80FD\u76D1\u89C6\u5668 (Performance Monitor)", accessories: [{ text: "性能诊断" }], actions: renderActionPanel("perfmon.exe") }), - React.createElement(List.Item, { key: "item-msconfig", title: "msconfig", subtitle: "\u7CFB\u7EDF\u5F15\u5BFC\u914D\u7F6E\u4E0E\u542F\u52A8\u9879 (System Configuration)", accessories: [{ text: "引导配置" }], actions: renderActionPanel("msconfig.exe") })), - React.createElement(List.Section, { title: "\u63A7\u5236\u9762\u677F\u4E13\u9879 (Control Panel Applets)" }, - React.createElement(List.Item, { key: "item-ncpa", title: "ncpa.cpl", subtitle: "\u7F51\u7EDC\u8FDE\u63A5\u4E0E\u7F51\u5361\u9002\u914D\u5668\u7BA1\u7406", accessories: [{ text: "CPL 插件" }], actions: renderActionPanel("ncpa.cpl") }), - React.createElement(List.Item, { key: "item-sysdm", title: "sysdm.cpl", subtitle: "\u7CFB\u7EDF\u5C5E\u6027\u4E0E\u73AF\u5883\u53D8\u91CF\u8BBE\u7F6E", accessories: [{ text: "CPL 插件" }], actions: renderActionPanel("sysdm.cpl") }), - React.createElement(List.Item, { key: "item-appwiz", title: "appwiz.cpl", subtitle: "\u7A0B\u5E8F\u548C\u529F\u80FD (\u8F6F\u4EF6\u5378\u8F7D\u7BA1\u7406)", accessories: [{ text: "CPL 插件" }], actions: renderActionPanel("appwiz.cpl") }), - React.createElement(List.Item, { key: "item-firewall", title: "firewall.cpl", subtitle: "Windows \u9632\u706B\u5899\u5B89\u5168\u8BBE\u7F6E", accessories: [{ text: "CPL 插件" }], actions: renderActionPanel("firewall.cpl") })), - React.createElement(List.Section, { title: "\u7EC8\u7AEF\u4E0E\u5F00\u53D1\u73AF\u5883 (Terminals & Developer)" }, - React.createElement(List.Item, { key: "item-cmd", title: "cmd", subtitle: "\u547D\u4EE4\u63D0\u793A\u7B26 (Command Prompt)", accessories: [{ text: "CLI 终端" }], actions: renderActionPanel("cmd.exe") }), - React.createElement(List.Item, { key: "item-powershell", title: "powershell", subtitle: "PowerShell \u73B0\u4EE3\u7EC8\u7AEF", accessories: [{ text: "CLI 终端" }], actions: renderActionPanel("powershell.exe") }), - React.createElement(List.Item, { key: "item-wt", title: "wt", subtitle: "Windows \u5B98\u65B9\u73B0\u4EE3\u7EC8\u7AEF (Windows Terminal)", accessories: [{ text: "CLI 终端" }], actions: renderActionPanel("wt.exe") }), - React.createElement(List.Item, { key: "item-code", title: "code .", subtitle: "\u5728\u5F53\u524D\u76EE\u5F55\u6253\u5F00 VS Code", accessories: [{ text: "代码开发" }], actions: renderActionPanel("code .") })))); -} diff --git a/packages/declarative-ui/dist/examples/windows-run/run-service.d.ts b/packages/declarative-ui/dist/examples/windows-run/run-service.d.ts deleted file mode 100644 index eed380ed..00000000 --- a/packages/declarative-ui/dist/examples/windows-run/run-service.d.ts +++ /dev/null @@ -1,58 +0,0 @@ -import { WindowsRunItem, WindowsRunItemKind, RunHistoryRecord, ExecuteRunOptions, CommandLineParsed, RunExecutionResult } from "./types.js"; -/** - * 运行输入的识别规则:环境变量、URI 协议头 - */ -export declare const RUN_REGEX: { - envVarFull: RegExp; - envVarShort: RegExp; - uri: RegExp; - rootedPath: RegExp; - envVarPath: RegExp; - executableExt: RegExp; - executableWithArgs: RegExp; - cpl: RegExp; - msc: RegExp; - exe: RegExp; -}; -export declare const RUN_KIND_LABELS: Record; -export declare const RUN_KIND_ICONS: Record; -/** - * 命令行解析器 - * 支持双引号包裹、URI 协议头、环境变量、路径参数及通用命令参数解析 - */ -export declare function parseCommandLine(raw: string): CommandLineParsed; -export declare function detectKind(cmd: string): WindowsRunItemKind; -/** - * 35+ 款高频 Windows 极客运行指令全景库(含 System32、治理 MSC、控制面板 CPL、常用开发终端) - */ -export declare const BUILTIN_RUN_ITEMS: readonly WindowsRunItem[]; -export declare class WindowsRunManager { - /** 测试注入的假宿主;缺省走真实宿主通道 */ - private readonly hostOverride; - private historyCache; - private pathExecutablesCache; - private pathCacheTimestamp; - constructor(options?: { - hostOverride?: unknown; - }); - getHistory(): Promise; - recordExecution(command: string, args?: string, options?: { - asAdmin?: boolean; - shell?: string; - }): Promise; - deleteHistoryItem(id: string): Promise; - clearHistory(): Promise; - /** - * 搜索运行命令与可执行文件 - */ - search(query: string): Promise<{ - items: WindowsRunItem[]; - historyMatches: RunHistoryRecord[]; - directItem?: WindowsRunItem | undefined; - }>; - /** - * 执行指令流水线 - */ - execute(commandOrCommandLine: string, options?: ExecuteRunOptions): Promise; -} -export declare const defaultWindowsRunManager: WindowsRunManager; diff --git a/packages/declarative-ui/dist/examples/windows-run/run-service.js b/packages/declarative-ui/dist/examples/windows-run/run-service.js deleted file mode 100644 index e77d5662..00000000 --- a/packages/declarative-ui/dist/examples/windows-run/run-service.js +++ /dev/null @@ -1,814 +0,0 @@ -import { LocalStorage } from "../../api/storage.js"; -import { callHostTransport } from "../shared/native-ipc.js"; -const HISTORY_STORAGE_KEY = "@ztools/windows-run/history"; -const MAX_HISTORY_ITEMS = 50; -/** - * 运行输入的识别规则:环境变量、URI 协议头 - */ -export const RUN_REGEX = { - envVarFull: /^%[a-zA-Z_][a-zA-Z0-9_()]*%$/, - envVarShort: /^%([a-zA-Z_][a-zA-Z0-9_()]*)?$/, - uri: /^[a-zA-Z]{2,}[a-zA-Z0-9+.-]*:/, - rootedPath: /^[a-zA-Z]:([/\\]|$)|^\\\\[^\\]+/, - envVarPath: /^%[a-zA-Z_][a-zA-Z0-9_()]*%[/\\]/, - executableExt: /\.(exe|cmd|bat|com|cpl|msc)$/i, - executableWithArgs: /^(.+?\.(exe|cmd|bat|com|cpl|msc))\s+(.+)$/i, - cpl: /\.cpl$/i, - msc: /\.msc$/i, - exe: /\.(exe|cmd|bat|com)$/i -}; -export const RUN_KIND_LABELS = { - executable: "Executable", - controlPanelApplet: "Control Panel Applet", - managementConsole: "Management Console", - environmentVariable: "Environment Variable", - path: "Path", - uri: "URI", - command: "Run Command" -}; -export const RUN_KIND_ICONS = { - executable: "app-window", - controlPanelApplet: "cog", - managementConsole: "monitor", - environmentVariable: "hashtag", - path: "folder", - uri: "link", - command: "terminal" -}; -/** - * 命令行解析器 - * 支持双引号包裹、URI 协议头、环境变量、路径参数及通用命令参数解析 - */ -export function parseCommandLine(raw) { - const trimmed = (raw || "").trim(); - if (!trimmed) { - return { - command: "", - arguments: undefined, - fullCommandLine: "", - kind: "command" - }; - } - // 1. 双引号包裹命令 - if (trimmed.startsWith('"')) { - const nextQuote = trimmed.indexOf('"', 1); - if (nextQuote > 0) { - const cmd = trimmed.substring(1, nextQuote).trim(); - const rest = trimmed.substring(nextQuote + 1).trim(); - return { - command: cmd, - arguments: rest || undefined, - fullCommandLine: trimmed, - kind: detectKind(cmd) - }; - } - } - // 2. URI 协议头 (例如: https://ztools.dev, ms-settings:windowsupdate) - if (RUN_REGEX.uri.test(trimmed)) { - const spaceIdx = trimmed.indexOf(" "); - if (spaceIdx > 0) { - const cmd = trimmed.substring(0, spaceIdx); - const args = trimmed.substring(spaceIdx + 1).trim(); - return { - command: cmd, - arguments: args || undefined, - fullCommandLine: trimmed, - kind: "uri" - }; - } - return { - command: trimmed, - arguments: undefined, - fullCommandLine: trimmed, - kind: "uri" - }; - } - // 3. 环境变量完整匹配 (%TEMP%, %APPDATA%) - if (RUN_REGEX.envVarFull.test(trimmed)) { - return { - command: trimmed, - arguments: undefined, - fullCommandLine: trimmed, - kind: "environmentVariable" - }; - } - // 4. 绝对路径或以环境变量开头的路径 - if (RUN_REGEX.rootedPath.test(trimmed) || RUN_REGEX.envVarPath.test(trimmed)) { - const matchWithArgs = trimmed.match(RUN_REGEX.executableWithArgs); - if (matchWithArgs && matchWithArgs[1] && matchWithArgs[3]) { - const cmd = matchWithArgs[1].trim(); - const args = matchWithArgs[3].trim(); - return { - command: cmd, - arguments: args || undefined, - fullCommandLine: trimmed, - kind: detectKind(cmd) - }; - } - if (RUN_REGEX.executableExt.test(trimmed) || !trimmed.includes(" ")) { - return { - command: trimmed, - arguments: undefined, - fullCommandLine: trimmed, - kind: detectKind(trimmed) - }; - } - const flagMatch = trimmed.match(/^(.+?)\s+([/-].*)$/); - if (flagMatch && flagMatch[1] && flagMatch[2]) { - const cmd = flagMatch[1].trim(); - const args = flagMatch[2].trim(); - return { - command: cmd, - arguments: args || undefined, - fullCommandLine: trimmed, - kind: detectKind(cmd) - }; - } - return { - command: trimmed, - arguments: undefined, - fullCommandLine: trimmed, - kind: "path" - }; - } - // 5. 常规空格分割的命令与参数 (如 ping 1.1.1.1, code .) - const spaceIdx = trimmed.indexOf(" "); - if (spaceIdx > 0) { - const cmd = trimmed.substring(0, spaceIdx).trim(); - const args = trimmed.substring(spaceIdx + 1).trim(); - return { - command: cmd, - arguments: args || undefined, - fullCommandLine: trimmed, - kind: detectKind(cmd) - }; - } - return { - command: trimmed, - arguments: undefined, - fullCommandLine: trimmed, - kind: detectKind(trimmed) - }; -} -export function detectKind(cmd) { - const lower = cmd.toLowerCase(); - if (RUN_REGEX.cpl.test(lower)) - return "controlPanelApplet"; - if (RUN_REGEX.msc.test(lower)) - return "managementConsole"; - if (RUN_REGEX.envVarFull.test(cmd)) - return "environmentVariable"; - if (RUN_REGEX.uri.test(cmd)) - return "uri"; - if (RUN_REGEX.rootedPath.test(cmd) || cmd.includes("/") || cmd.includes("\\")) - return "path"; - if (RUN_REGEX.exe.test(lower)) - return "executable"; - return "executable"; -} -/** - * 35+ 款高频 Windows 极客运行指令全景库(含 System32、治理 MSC、控制面板 CPL、常用开发终端) - */ -export const BUILTIN_RUN_ITEMS = [ - // 终端与开发 - { - id: "run-cmd", - title: "cmd", - command: "cmd.exe", - fullCommandLine: "cmd.exe", - description: "Command Prompt", - descriptionZh: "命令提示符 (CMD)", - pinyin: "minglingtishifu cmd", - category: "终端与命令行", - kind: "executable", - icon: RUN_KIND_ICONS.executable, - label: RUN_KIND_LABELS.executable, - isBuiltin: true - }, - { - id: "run-powershell", - title: "powershell", - command: "powershell.exe", - fullCommandLine: "powershell.exe", - description: "Windows PowerShell", - descriptionZh: "PowerShell 现代终端", - pinyin: "powershell", - category: "终端与命令行", - kind: "executable", - icon: RUN_KIND_ICONS.executable, - label: RUN_KIND_LABELS.executable, - isBuiltin: true - }, - { - id: "run-wt", - title: "wt", - command: "wt.exe", - fullCommandLine: "wt.exe", - description: "Windows Terminal", - descriptionZh: "Windows 官方现代标签页终端", - pinyin: "xiandaiterminal wt", - category: "终端与命令行", - kind: "executable", - icon: RUN_KIND_ICONS.executable, - label: RUN_KIND_LABELS.executable, - isBuiltin: true - }, - { - id: "run-code", - title: "code", - command: "code", - fullCommandLine: "code .", - description: "Visual Studio Code", - descriptionZh: "VS Code 编辑器 (支持 code . 参数)", - pinyin: "vscode code", - category: "终端与命令行", - kind: "executable", - icon: RUN_KIND_ICONS.executable, - label: RUN_KIND_LABELS.executable, - isBuiltin: true - }, - // 系统核心治理 - { - id: "run-regedit", - title: "regedit", - command: "regedit.exe", - fullCommandLine: "regedit.exe", - description: "Registry Editor", - descriptionZh: "注册表编辑器", - pinyin: "zhuceshibianjiqi regedit", - category: "系统管理与治理", - kind: "executable", - icon: RUN_KIND_ICONS.executable, - label: RUN_KIND_LABELS.executable, - isBuiltin: true, - runAsAdminByDefault: true - }, - { - id: "run-taskmgr", - title: "taskmgr", - command: "taskmgr.exe", - fullCommandLine: "taskmgr.exe", - description: "Task Manager", - descriptionZh: "任务管理器", - pinyin: "renwuguanliqi taskmgr", - category: "系统管理与治理", - kind: "executable", - icon: RUN_KIND_ICONS.executable, - label: RUN_KIND_LABELS.executable, - isBuiltin: true - }, - { - id: "run-services", - title: "services.msc", - command: "services.msc", - fullCommandLine: "services.msc", - description: "Windows Services Management", - descriptionZh: "系统后台服务管理", - pinyin: "xitongfuwuguanli services", - category: "系统管理与治理", - kind: "managementConsole", - icon: RUN_KIND_ICONS.managementConsole, - label: RUN_KIND_LABELS.managementConsole, - isBuiltin: true, - runAsAdminByDefault: true - }, - { - id: "run-gpedit", - title: "gpedit.msc", - command: "gpedit.msc", - fullCommandLine: "gpedit.msc", - description: "Local Group Policy Editor", - descriptionZh: "本地组策略编辑器", - pinyin: "zucelue gpedit", - category: "系统管理与治理", - kind: "managementConsole", - icon: RUN_KIND_ICONS.managementConsole, - label: RUN_KIND_LABELS.managementConsole, - isBuiltin: true, - runAsAdminByDefault: true - }, - { - id: "run-compmgmt", - title: "compmgmt.msc", - command: "compmgmt.msc", - fullCommandLine: "compmgmt.msc", - description: "Computer Management", - descriptionZh: "计算机管理中枢", - pinyin: "jisuanjiguanli compmgmt", - category: "系统管理与治理", - kind: "managementConsole", - icon: RUN_KIND_ICONS.managementConsole, - label: RUN_KIND_LABELS.managementConsole, - isBuiltin: true, - runAsAdminByDefault: true - }, - { - id: "run-devmgmt", - title: "devmgmt.msc", - command: "devmgmt.msc", - fullCommandLine: "devmgmt.msc", - description: "Device Manager", - descriptionZh: "设备管理器 (硬件驱动)", - pinyin: "shebeiguanliqi devmgmt", - category: "系统管理与治理", - kind: "managementConsole", - icon: RUN_KIND_ICONS.managementConsole, - label: RUN_KIND_LABELS.managementConsole, - isBuiltin: true - }, - { - id: "run-diskmgmt", - title: "diskmgmt.msc", - command: "diskmgmt.msc", - fullCommandLine: "diskmgmt.msc", - description: "Disk Management", - descriptionZh: "磁盘分区与格式化管理", - pinyin: "cipanguanli diskmgmt", - category: "系统管理与治理", - kind: "managementConsole", - icon: RUN_KIND_ICONS.managementConsole, - label: RUN_KIND_LABELS.managementConsole, - isBuiltin: true, - runAsAdminByDefault: true - }, - { - id: "run-eventvwr", - title: "eventvwr.msc", - command: "eventvwr.msc", - fullCommandLine: "eventvwr.msc", - description: "Event Viewer", - descriptionZh: "Windows 系统事件查看器", - pinyin: "shijianchakanqi eventvwr", - category: "系统管理与治理", - kind: "managementConsole", - icon: RUN_KIND_ICONS.managementConsole, - label: RUN_KIND_LABELS.managementConsole, - isBuiltin: true - }, - { - id: "run-resmon", - title: "resmon", - command: "resmon.exe", - fullCommandLine: "resmon.exe", - description: "Resource Monitor", - descriptionZh: "资源监视器 (CPU/内存/网络/磁盘实时IO)", - pinyin: "ziyuanjianshiqi resmon", - category: "系统管理与治理", - kind: "executable", - icon: RUN_KIND_ICONS.executable, - label: RUN_KIND_LABELS.executable, - isBuiltin: true - }, - { - id: "run-perfmon", - title: "perfmon", - command: "perfmon.exe", - fullCommandLine: "perfmon.exe", - description: "Performance Monitor", - descriptionZh: "性能监视器 (系统诊断性能计数器)", - pinyin: "xingnengjianshiqi perfmon", - category: "系统管理与治理", - kind: "executable", - icon: RUN_KIND_ICONS.executable, - label: RUN_KIND_LABELS.executable, - isBuiltin: true - }, - { - id: "run-msconfig", - title: "msconfig", - command: "msconfig.exe", - fullCommandLine: "msconfig.exe", - description: "System Configuration", - descriptionZh: "系统配置与引导项管理", - pinyin: "xitongpeizhi msconfig", - category: "系统管理与治理", - kind: "executable", - icon: RUN_KIND_ICONS.executable, - label: RUN_KIND_LABELS.executable, - isBuiltin: true - }, - { - id: "run-cleanmgr", - title: "cleanmgr", - command: "cleanmgr.exe", - fullCommandLine: "cleanmgr.exe", - description: "Disk Cleanup", - descriptionZh: "磁盘空间深度垃圾清理", - pinyin: "cipanqingli cleanmgr", - category: "系统管理与治理", - kind: "executable", - icon: RUN_KIND_ICONS.executable, - label: RUN_KIND_LABELS.executable, - isBuiltin: true - }, - { - id: "run-dxdiag", - title: "dxdiag", - command: "dxdiag.exe", - fullCommandLine: "dxdiag.exe", - description: "DirectX Diagnostic Tool", - descriptionZh: "DirectX 诊断硬件与显卡驱动工具", - pinyin: "directxzhenduan dxdiag", - category: "系统管理与治理", - kind: "executable", - icon: RUN_KIND_ICONS.executable, - label: RUN_KIND_LABELS.executable, - isBuiltin: true - }, - // 控制面板 CPL 专向直达 - { - id: "run-control", - title: "control", - command: "control.exe", - fullCommandLine: "control.exe", - description: "Control Panel", - descriptionZh: "Windows 经典控制面板", - pinyin: "kongzhimianban control", - category: "控制面板与设置", - kind: "executable", - icon: RUN_KIND_ICONS.executable, - label: RUN_KIND_LABELS.executable, - isBuiltin: true - }, - { - id: "run-ncpa", - title: "ncpa.cpl", - command: "ncpa.cpl", - fullCommandLine: "ncpa.cpl", - description: "Network Connections", - descriptionZh: "网络连接与网卡适配器管理", - pinyin: "wangluoshipeiqi ncpa", - category: "控制面板与设置", - kind: "controlPanelApplet", - icon: RUN_KIND_ICONS.controlPanelApplet, - label: RUN_KIND_LABELS.controlPanelApplet, - isBuiltin: true - }, - { - id: "run-sysdm", - title: "sysdm.cpl", - command: "sysdm.cpl", - fullCommandLine: "sysdm.cpl", - description: "System Properties", - descriptionZh: "系统属性与环境变量设置", - pinyin: "xitongshuxing huanjingbianliang sysdm", - category: "控制面板与设置", - kind: "controlPanelApplet", - icon: RUN_KIND_ICONS.controlPanelApplet, - label: RUN_KIND_LABELS.controlPanelApplet, - isBuiltin: true - }, - { - id: "run-appwiz", - title: "appwiz.cpl", - command: "appwiz.cpl", - fullCommandLine: "appwiz.cpl", - description: "Programs and Features", - descriptionZh: "程序和功能 (软件卸载管理)", - pinyin: "chengxuhegongneng appwiz", - category: "控制面板与设置", - kind: "controlPanelApplet", - icon: RUN_KIND_ICONS.controlPanelApplet, - label: RUN_KIND_LABELS.controlPanelApplet, - isBuiltin: true - }, - { - id: "run-firewall", - title: "firewall.cpl", - command: "firewall.cpl", - fullCommandLine: "firewall.cpl", - description: "Windows Defender Firewall", - descriptionZh: "Windows 防火墙安全设置", - pinyin: "fanghuoqiang firewall", - category: "控制面板与设置", - kind: "controlPanelApplet", - icon: RUN_KIND_ICONS.controlPanelApplet, - label: RUN_KIND_LABELS.controlPanelApplet, - isBuiltin: true - }, - { - id: "run-inetcpl", - title: "inetcpl.cpl", - command: "inetcpl.cpl", - fullCommandLine: "inetcpl.cpl", - description: "Internet Properties", - descriptionZh: "Internet 选项与系统代理配置", - pinyin: "internetxuanxiang inetcpl", - category: "控制面板与设置", - kind: "controlPanelApplet", - icon: RUN_KIND_ICONS.controlPanelApplet, - label: RUN_KIND_LABELS.controlPanelApplet, - isBuiltin: true - }, - { - id: "run-mmsys", - title: "mmsys.cpl", - command: "mmsys.cpl", - fullCommandLine: "mmsys.cpl", - description: "Sound Settings", - descriptionZh: "声音与音频设备属性", - pinyin: "shengyinshebei mmsys", - category: "控制面板与设置", - kind: "controlPanelApplet", - icon: RUN_KIND_ICONS.controlPanelApplet, - label: RUN_KIND_LABELS.controlPanelApplet, - isBuiltin: true - }, - // 极客高频实用小工具 - { - id: "run-calc", - title: "calc", - command: "calc.exe", - fullCommandLine: "calc.exe", - description: "Calculator", - descriptionZh: "系统计算器", - pinyin: "jisuanqi calc", - category: "内置实用工具", - kind: "executable", - icon: RUN_KIND_ICONS.executable, - label: RUN_KIND_LABELS.executable, - isBuiltin: true - }, - { - id: "run-notepad", - title: "notepad", - command: "notepad.exe", - fullCommandLine: "notepad.exe", - description: "Notepad", - descriptionZh: "系统记事本", - pinyin: "jishiben notepad", - category: "内置实用工具", - kind: "executable", - icon: RUN_KIND_ICONS.executable, - label: RUN_KIND_LABELS.executable, - isBuiltin: true - }, - { - id: "run-mspaint", - title: "mspaint", - command: "mspaint.exe", - fullCommandLine: "mspaint.exe", - description: "Paint", - descriptionZh: "系统画图", - pinyin: "huatu mspaint", - category: "内置实用工具", - kind: "executable", - icon: RUN_KIND_ICONS.executable, - label: RUN_KIND_LABELS.executable, - isBuiltin: true - }, - { - id: "run-mstsc", - title: "mstsc", - command: "mstsc.exe", - fullCommandLine: "mstsc.exe", - description: "Remote Desktop Connection", - descriptionZh: "远程桌面连接 (RDP)", - pinyin: "yuanchengzhuomian mstsc", - category: "内置实用工具", - kind: "executable", - icon: RUN_KIND_ICONS.executable, - label: RUN_KIND_LABELS.executable, - isBuiltin: true - }, - { - id: "run-snippingtool", - title: "snippingtool", - command: "snippingtool.exe", - fullCommandLine: "snippingtool.exe", - description: "Snipping Tool", - descriptionZh: "系统截图与录屏工具", - pinyin: "jietugongju snippingtool", - category: "内置实用工具", - kind: "executable", - icon: RUN_KIND_ICONS.executable, - label: RUN_KIND_LABELS.executable, - isBuiltin: true - }, - { - id: "run-ping", - title: "ping", - command: "ping", - fullCommandLine: "ping 1.1.1.1", - description: "Network Ping", - descriptionZh: "网络连通性探测 (支持参数)", - pinyin: "wangluoping ping", - category: "终端与命令行", - kind: "executable", - icon: RUN_KIND_ICONS.executable, - label: RUN_KIND_LABELS.executable, - isBuiltin: true - } -]; -let historyIdSeq = 0; -/** 历史记录 ID:优先用加密随机 UUID,环境不提供时退回时间戳 + 自增序号(只需本地唯一) */ -function createHistoryId() { - const uuid = globalThis.crypto?.randomUUID?.(); - if (uuid) - return `run-hist-${uuid}`; - historyIdSeq = (historyIdSeq + 1) % 1_000_000; - return `run-hist-${Date.now()}-${historyIdSeq}`; -} -export class WindowsRunManager { - /** 测试注入的假宿主;缺省走真实宿主通道 */ - hostOverride; - historyCache = []; - pathExecutablesCache = []; - pathCacheTimestamp = 0; - constructor(options = {}) { - this.hostOverride = options.hostOverride; - } - async getHistory() { - try { - const stored = await LocalStorage.getItem(HISTORY_STORAGE_KEY); - if (Array.isArray(stored)) { - this.historyCache = stored; - return stored; - } - } - catch { - // 容错处理 - } - return this.historyCache; - } - async recordExecution(command, args, options) { - const trimmedCmd = (command || "").trim(); - if (!trimmedCmd) - throw new Error("执行命令不能为空"); - const parsed = parseCommandLine(args ? `${trimmedCmd} ${args}` : trimmedCmd); - const fullCommandLine = parsed.arguments - ? `${parsed.command} ${parsed.arguments}` - : parsed.command; - const history = await this.getHistory(); - const existingIdx = history.findIndex((h) => h.fullCommandLine.toLowerCase() === fullCommandLine.toLowerCase()); - let record; - if (existingIdx !== -1) { - const existing = history[existingIdx]; - record = { - ...existing, - executedAt: Date.now(), - runCount: (existing.runCount || 1) + 1, - asAdmin: options?.asAdmin ?? existing.asAdmin, - shell: options?.shell ?? existing.shell - }; - history.splice(existingIdx, 1); - history.unshift(record); - } - else { - record = { - id: createHistoryId(), - command: parsed.command, - arguments: parsed.arguments, - fullCommandLine, - executedAt: Date.now(), - runCount: 1, - asAdmin: options?.asAdmin, - shell: options?.shell - }; - history.unshift(record); - } - const trimmedHistory = history.slice(0, MAX_HISTORY_ITEMS); - this.historyCache = trimmedHistory; - try { - await LocalStorage.setItem(HISTORY_STORAGE_KEY, trimmedHistory); - } - catch { - // ignore - } - return record; - } - async deleteHistoryItem(id) { - const history = await this.getHistory(); - const filtered = history.filter((h) => h.id !== id); - if (filtered.length !== history.length) { - this.historyCache = filtered; - await LocalStorage.setItem(HISTORY_STORAGE_KEY, filtered); - return true; - } - return false; - } - async clearHistory() { - this.historyCache = []; - await LocalStorage.removeItem(HISTORY_STORAGE_KEY); - } - /** - * 搜索运行命令与可执行文件 - */ - async search(query) { - const raw = (query || "").trim(); - const history = await this.getHistory(); - if (!raw) { - return { - items: [...BUILTIN_RUN_ITEMS], - historyMatches: history - }; - } - const lower = raw.toLowerCase(); - const parsed = parseCommandLine(raw); - // 1. 匹配历史记录 - const historyMatches = history.filter((h) => h.fullCommandLine.toLowerCase().includes(lower) || - h.command.toLowerCase().includes(lower)); - // 2. 匹配预置命令 - const matchedBuiltin = BUILTIN_RUN_ITEMS.filter((item) => { - if (item.title.toLowerCase().includes(lower)) - return true; - if (item.command.toLowerCase().includes(lower)) - return true; - if (item.description.toLowerCase().includes(lower)) - return true; - if (item.descriptionZh.toLowerCase().includes(lower)) - return true; - if (item.pinyin.toLowerCase().includes(lower)) - return true; - return false; - }); - // 3. 构建动态直达运行项 (当输入包含参数或不在内置列表时) - let directItem = undefined; - const exactBuiltin = BUILTIN_RUN_ITEMS.find((b) => b.command.toLowerCase() === parsed.command.toLowerCase()); - if (raw.length > 0) { - const fullCmd = parsed.arguments - ? `${parsed.command} ${parsed.arguments}` - : parsed.command; - directItem = { - id: `direct-${encodeURIComponent(fullCmd)}`, - title: parsed.command, - command: parsed.command, - arguments: parsed.arguments, - fullCommandLine: fullCmd, - description: exactBuiltin - ? `${exactBuiltin.descriptionZh} ${parsed.arguments ? `[参数: ${parsed.arguments}]` : ""}` - : `运行自定义指令: ${fullCmd}`, - descriptionZh: exactBuiltin - ? `${exactBuiltin.descriptionZh} ${parsed.arguments ? `[参数: ${parsed.arguments}]` : ""}` - : `运行自定义指令: ${fullCmd}`, - pinyin: parsed.command.toLowerCase(), - category: "自定义执行", - kind: parsed.kind, - icon: RUN_KIND_ICONS[parsed.kind] || "terminal", - label: RUN_KIND_LABELS[parsed.kind] || "Command", - isBuiltin: false, - runAsAdminByDefault: exactBuiltin?.runAsAdminByDefault ?? false - }; - } - return { - items: matchedBuiltin, - historyMatches, - directItem - }; - } - /** - * 执行指令流水线 - */ - async execute(commandOrCommandLine, options = {}) { - const raw = (commandOrCommandLine || "").trim(); - if (!raw) { - throw new Error("执行命令不能为空"); - } - const parsed = parseCommandLine(raw); - const mergedArgs = [ - ...(parsed.arguments ? [parsed.arguments] : []), - ...(options.args && options.args.length > 0 ? [options.args.join(" ")] : []), - ...(options.arguments ? [options.arguments] : []) - ].join(" ").trim(); - const asAdmin = Boolean(options.asAdministrator ?? options.runAsAdmin); - const shell = options.shell ?? "none"; - const fullCmd = mergedArgs ? `${parsed.command} ${mergedArgs}` : parsed.command; - // 记录历史 - await this.recordExecution(parsed.command, mergedArgs || undefined, { - asAdmin, - shell: shell !== "none" ? shell : undefined - }); - // 走宿主 windows_run_execute(契约字段:command / args / runAsAdmin / shell / workingDirectory)。 - // 宿主返回 success:false、抛错或不可达时如实返回失败,绝不报告“已启动”; - // 也不回退到 Node child_process:渲染进程沙箱里本就拿不到它,而在 Node 单测里会真的拉起进程。 - const res = await callHostTransport("windows_run_execute", { - command: parsed.command, - ...(mergedArgs ? { args: [mergedArgs] } : {}), - runAsAdmin: asAdmin, - shell - }, this.hostOverride); - if (!res.ok) { - const unreachable = /^(METHOD_NOT_AVAILABLE|NO_WINDOW_ENV)/.test(res.error || ""); - return { - success: false, - message: unreachable ? `未连接 ZTools 宿主,无法运行: ${fullCmd}` : `运行失败: ${res.error || fullCmd}`, - command: fullCmd, - asAdmin, - shell - }; - } - return { - success: true, - ...(typeof res.data?.pid === "number" ? { pid: res.data.pid } : {}), - message: asAdmin - ? `已请求管理员权限运行: ${fullCmd}` - : shell !== "none" - ? `已在 ${shell.toUpperCase()} 中执行: ${fullCmd}` - : `已成功启动命令: ${fullCmd}`, - command: fullCmd, - asAdmin, - shell - }; - } -} -export const defaultWindowsRunManager = new WindowsRunManager(); diff --git a/packages/declarative-ui/dist/examples/windows-run/types.d.ts b/packages/declarative-ui/dist/examples/windows-run/types.d.ts deleted file mode 100644 index 88a621f2..00000000 --- a/packages/declarative-ui/dist/examples/windows-run/types.d.ts +++ /dev/null @@ -1,60 +0,0 @@ -/** - * Windows Run Dialog (极客运行中枢) 类型定义 - * - * 参考常见启动器的「运行」交互自研实现: - * - 检索可执行文件、控制面板项、管理控制台、环境变量、路径、URI 与通用命令 - * - 视图分为运行主列表与命令检索两类 - */ -export type WindowsRunItemKind = "executable" | "controlPanelApplet" | "managementConsole" | "environmentVariable" | "path" | "uri" | "command"; -export interface WindowsRunItem { - readonly id: string; - readonly title: string; - readonly command: string; - readonly arguments?: string | undefined; - readonly fullCommandLine: string; - readonly description: string; - readonly descriptionZh: string; - readonly pinyin: string; - readonly category: string; - readonly kind: WindowsRunItemKind; - readonly icon: string; - readonly label: string; - readonly isBuiltin: boolean; - readonly runAsAdminByDefault?: boolean | undefined; - readonly executionCount?: number | undefined; - readonly lastExecutedAt?: number | undefined; -} -export interface RunHistoryRecord { - readonly id: string; - readonly command: string; - readonly arguments?: string | undefined; - readonly fullCommandLine: string; - readonly executedAt: number; - readonly runCount: number; - readonly asAdmin?: boolean | undefined; - readonly shell?: string | undefined; -} -export type RunShellType = "default" | "cmd" | "powershell" | "wt" | "none"; -export interface ExecuteRunOptions { - args?: readonly string[] | undefined; - arguments?: string | undefined; - asAdministrator?: boolean | undefined; - runAsAdmin?: boolean | undefined; - shell?: RunShellType | undefined; - workingDirectory?: string | undefined; -} -export interface CommandLineParsed { - readonly command: string; - readonly arguments?: string | undefined; - readonly fullCommandLine: string; - readonly kind: WindowsRunItemKind; -} -export interface RunExecutionResult { - readonly success: boolean; - readonly pid?: number | undefined; - readonly message: string; - readonly command: string; - readonly asAdmin: boolean; - readonly shell: RunShellType; - readonly error?: string | undefined; -} diff --git a/packages/declarative-ui/dist/examples/windows-run/types.js b/packages/declarative-ui/dist/examples/windows-run/types.js deleted file mode 100644 index ba935be7..00000000 --- a/packages/declarative-ui/dist/examples/windows-run/types.js +++ /dev/null @@ -1,8 +0,0 @@ -/** - * Windows Run Dialog (极客运行中枢) 类型定义 - * - * 参考常见启动器的「运行」交互自研实现: - * - 检索可执行文件、控制面板项、管理控制台、环境变量、路径、URI 与通用命令 - * - 视图分为运行主列表与命令检索两类 - */ -export {}; diff --git a/packages/declarative-ui/dist/examples/windows-taskbar/index.d.ts b/packages/declarative-ui/dist/examples/windows-taskbar/index.d.ts deleted file mode 100644 index 99da4025..00000000 --- a/packages/declarative-ui/dist/examples/windows-taskbar/index.d.ts +++ /dev/null @@ -1,16 +0,0 @@ -/** - * Windows Taskbar (任务栏治理中枢) - * - * 功能概览: - * - Win32 原生动作:Toggle Taskbar Visibility (一键显示/隐藏任务栏,基于 FindWindow("Shell_TrayWnd") + ShowWindow) - * - Toggle Taskbar Auto-Hide (切换任务栏自动隐藏) - * - 任务栏位置与对齐方式检视 (Windows 11 居中 / 靠左对齐) - * - 快捷动作反馈与 Toast 提示 - * - 完善的多显示器协同与资源管理器刷新急救 - */ -import { WindowsTaskbarManager } from "./taskbar-service.js"; -export * from "./types.js"; -export * from "./taskbar-service.js"; -export default function WindowsTaskbarCommand(props?: { - manager?: WindowsTaskbarManager; -} | null): JSX.Element; diff --git a/packages/declarative-ui/dist/examples/windows-taskbar/index.js b/packages/declarative-ui/dist/examples/windows-taskbar/index.js deleted file mode 100644 index 911fa088..00000000 --- a/packages/declarative-ui/dist/examples/windows-taskbar/index.js +++ /dev/null @@ -1,164 +0,0 @@ -/** - * Windows Taskbar (任务栏治理中枢) - * - * 功能概览: - * - Win32 原生动作:Toggle Taskbar Visibility (一键显示/隐藏任务栏,基于 FindWindow("Shell_TrayWnd") + ShowWindow) - * - Toggle Taskbar Auto-Hide (切换任务栏自动隐藏) - * - 任务栏位置与对齐方式检视 (Windows 11 居中 / 靠左对齐) - * - 快捷动作反馈与 Toast 提示 - * - 完善的多显示器协同与资源管理器刷新急救 - */ -import React from "../../index.js"; -import { List, ActionPanel, Action, Icon, showToast, Toast } from "../../index.js"; -import { useState, useEffect } from "../../runtime/hooks.js"; -import { WindowsTaskbarManager, defaultWindowsTaskbarManager, describeTaskbarFailure } from "./taskbar-service.js"; -export * from "./types.js"; -export * from "./taskbar-service.js"; -export default function WindowsTaskbarCommand(props) { - // 宿主渲染命令时可能传入启动参数或 null,只认测试注入的 manager - const manager = props?.manager instanceof WindowsTaskbarManager ? props.manager : defaultWindowsTaskbarManager; - // 只展示当前平台宿主真正实现了的动作(Windows:显示 / 隐藏;macOS:Dock 自动隐藏、停靠位置、重启 Dock) - const caps = manager.getCapabilities(); - const [state, setState] = useState({ - visible: true, - autoHide: false, - position: "bottom", - alignment: "center", - size: "regular", - multiMonitorEnabled: true, - secondaryTrayCount: 1, - lastModifiedAt: Date.now() - }); - const [refreshCount, setRefreshCount] = useState(0); - useEffect(() => { - let active = true; - manager.getTaskbarState().then((s) => { - if (active) - setState(s); - }); - return () => { - active = false; - }; - }, [refreshCount]); - const reloadState = () => { - setRefreshCount((c) => c + 1); - }; - /** - * 统一展示操作结果:只有宿主确认成功才弹成功提示,失败时弹失败提示并附上真实原因 - */ - const reportResult = async (res, successDetail) => { - setState(res.state); - if (res.success) { - await showToast(Toast.Style.Success, res.message, successDetail); - } - else { - await showToast(Toast.Style.Failure, res.message, describeTaskbarFailure(res)); - } - }; - const runAction = async (action, failureTitle, successDetail) => { - try { - const res = await action(); - await reportResult(res, successDetail?.(res)); - } - catch (err) { - await showToast(Toast.Style.Failure, failureTitle, err instanceof Error ? err.message : String(err)); - } - }; - const handleToggleVisibility = () => runAction(() => manager.toggleTaskbarVisibility(), "切换任务栏显隐失败", (res) => (res.visible ? "任务栏 / Dock 已恢复显示" : "任务栏 / Dock 已隐藏")); - const handleToggleAutoHide = () => runAction(() => manager.toggleTaskbarAutoHide(), "切换自动隐藏失败", (res) => (res.autoHide ? "鼠标移出后自动隐藏" : "保持常驻显示")); - const handleForceShow = () => runAction(() => manager.showTaskbar(), "显示任务栏失败"); - const handleForceHide = () => runAction(() => manager.hideTaskbar(), "隐藏任务栏失败"); - const handleSetAlignment = (alignment) => runAction(() => manager.setTaskbarAlignment(alignment), "设置对齐方式失败"); - const handleSetDockPosition = (position) => runAction(() => manager.setDockPosition(position), "切换停靠位置失败"); - const handleRestartDock = async () => { - await showToast(Toast.Style.Animated, "正在重启 macOS Dock 程序坞..."); - await runAction(() => manager.restartDock(), "重启 Dock 失败"); - }; - const handleRestartExplorer = async () => { - await showToast(Toast.Style.Animated, "正在重启系统桌面壳层 (Explorer / Dock)..."); - await runAction(() => manager.restartExplorer(), "重启资源管理器失败"); - }; - return (React.createElement(List, { searchBarPlaceholder: "\u6CBB\u7406\u7CFB\u7EDF\u4EFB\u52A1\u680F\u4E0E macOS \u7A0B\u5E8F\u575E (Dock) \u663E\u9690\u3001\u81EA\u52A8\u9690\u85CF\u3001\u505C\u9760\u4F4D\u7F6E...", filterBar: { - summaryText: `任务栏/Dock 状态: ${state.visible ? "显示中 (Visible)" : "已隐藏 (Hidden)"}${caps.autoHide ? ` · 自动隐藏: ${state.autoHide ? "已开启" : "常驻"}` : ""}`, - actions: [ - { - id: "tb-act-visibility", - label: "切换任务栏/Dock显隐", - title: "切换任务栏/Dock显隐", - style: "primary", - onAction: () => { - void handleToggleVisibility(); - } - }, - caps.autoHide && { - id: "tb-act-autohide", - label: "切换自动隐藏", - title: "切换自动隐藏", - style: "secondary", - onAction: () => { - void handleToggleAutoHide(); - } - }, - caps.alignment && { - id: "tb-act-align-left", - label: "靠左对齐", - title: "靠左对齐", - style: "secondary", - onAction: () => { - void handleSetAlignment("start"); - } - }, - caps.alignment && { - id: "tb-act-align-center", - label: "居中对齐", - title: "居中对齐", - style: "secondary", - onAction: () => { - void handleSetAlignment("center"); - } - }, - (caps.restartExplorer || caps.restartDock) && { - id: "tb-act-restart", - label: caps.restartExplorer ? "重启 Explorer" : "重启 Dock", - title: caps.restartExplorer ? "重启 Explorer" : "重启 Dock", - style: "danger", - onAction: () => { - void (caps.restartExplorer ? handleRestartExplorer() : handleRestartDock()); - } - } - ].filter((action) => Boolean(action)) - } }, - React.createElement(List.Section, { title: "Win32 \u539F\u751F\u6CBB\u7406\u52A8\u4F5C (Core Actions)" }, - React.createElement(List.Item, { key: "item-toggle-visibility", title: "\u5207\u6362\u4EFB\u52A1\u680F\u663E\u9690 / \u7A0B\u5E8F\u575E\u663E\u9690 (Toggle Taskbar & Dock)", subtitle: `当前状态: ${state.visible ? "显示中 (Visible)" : "已隐藏 (Hidden)"} — Win32 ShowWindow / macOS Dock Autohide`, accessories: [ - { - text: state.visible ? "VISIBLE" : "HIDDEN" - } - ], actions: React.createElement(ActionPanel, { title: "\u4EFB\u52A1\u680F\u4E0E Dock \u663E\u9690" }, - React.createElement(Action, { title: "\u7ACB\u5373\u5207\u6362\u4EFB\u52A1\u680F/Dock \u663E\u9690", icon: Icon.Eye, onAction: handleToggleVisibility }), - React.createElement(Action, { title: "\u5F3A\u5236\u663E\u793A\u4EFB\u52A1\u680F", icon: Icon.Window, onAction: handleForceShow }), - React.createElement(Action, { title: "\u6C89\u6D78\u5F0F\u9690\u85CF\u4EFB\u52A1\u680F", icon: Icon.XMarkCircle, onAction: handleForceHide })) }), - caps.autoHide && (React.createElement(List.Item, { key: "item-toggle-autohide", title: "\u5207\u6362\u4EFB\u52A1\u680F / Dock \u81EA\u52A8\u9690\u85CF (Toggle Auto-Hide)", subtitle: `当前状态: ${state.autoHide ? "已启用自动隐藏 (Auto-Hide)" : "常驻显示 (Always Visible)"} — SHAppBarMessage / Dock Preferences`, accessories: [ - { - text: state.autoHide ? "AUTO-HIDE ON" : "ALWAYS ON" - } - ], actions: React.createElement(ActionPanel, { title: "\u81EA\u52A8\u9690\u85CF\u63A7\u5236" }, - React.createElement(Action, { title: "\u5207\u6362\u81EA\u52A8\u9690\u85CF\u72B6\u6001", icon: Icon.ArrowDown, onAction: handleToggleAutoHide })) })), - React.createElement(List.Item, { key: "item-show-taskbar", title: "\u5F3A\u5236\u663E\u793A\u4EFB\u52A1\u680F (Show Taskbar)", subtitle: "\u8FD8\u539F\u4E3B\u5C4F (Shell_TrayWnd) \u4E0E\u526F\u5C4F (Shell_SecondaryTrayWnd) \u4EFB\u52A1\u680F\u7A97\u53E3", accessories: [{ text: "SHOW" }], actions: React.createElement(ActionPanel, { title: "\u663E\u793A\u4EFB\u52A1\u680F" }, - React.createElement(Action, { title: "\u5F3A\u5236\u663E\u793A\u4EFB\u52A1\u680F", icon: Icon.Window, onAction: handleForceShow })) }), - React.createElement(List.Item, { key: "item-hide-taskbar", title: "\u6C89\u6D78\u5F0F\u9690\u85CF\u4EFB\u52A1\u680F (Hide Taskbar)", subtitle: "\u9690\u85CF\u6240\u6709\u663E\u793A\u5668\u7684\u7CFB\u7EDF\u4EFB\u52A1\u680F\uFF0C\u4EAB\u53D7\u6781\u81F4\u65E0\u8FB9\u6846\u6C89\u6D78\u4F53\u9A8C", accessories: [{ text: "HIDE" }], actions: React.createElement(ActionPanel, { title: "\u9690\u85CF\u4EFB\u52A1\u680F" }, - React.createElement(Action, { title: "\u6C89\u6D78\u5F0F\u9690\u85CF\u4EFB\u52A1\u680F", icon: Icon.XMarkCircle, onAction: handleForceHide })) })), - caps.dockPosition && (React.createElement(List.Section, { title: "macOS Dock \u4E0E\u4EFB\u52A1\u680F\u4F4D\u7F6E\u6CBB\u7406 (Dock Position & Alignment)" }, - React.createElement(List.Item, { key: "item-dock-bottom", title: "\u505C\u9760\u4E8E\u5C4F\u5E55\u5E95\u90E8 (Set Dock Position: Bottom)", subtitle: "\u5C06 macOS \u7A0B\u5E8F\u575E / \u4EFB\u52A1\u680F\u505C\u9760\u5728\u5C4F\u5E55\u5E95\u8FB9", accessories: [{ text: state.position === "bottom" ? "ACTIVE" : "BOTTOM" }], actions: React.createElement(ActionPanel, { title: "\u505C\u9760\u4F4D\u7F6E" }, - React.createElement(Action, { title: "\u505C\u9760\u5728\u5E95\u90E8 (Bottom)", icon: Icon.ArrowDown, onAction: () => handleSetDockPosition("bottom") }), - React.createElement(Action, { title: "\u505C\u9760\u5728\u5DE6\u4FA7 (Left)", icon: Icon.SidebarLeft, onAction: () => handleSetDockPosition("left") }), - React.createElement(Action, { title: "\u505C\u9760\u5728\u53F3\u4FA7 (Right)", icon: Icon.SidebarRight, onAction: () => handleSetDockPosition("right") })) }), - React.createElement(List.Item, { key: "item-dock-left", title: "\u505C\u9760\u4E8E\u5C4F\u5E55\u5DE6\u4FA7 (Set Dock Position: Left)", subtitle: "\u5C06 macOS \u7A0B\u5E8F\u575E\u505C\u9760\u5728\u5C4F\u5E55\u5DE6\u8FB9\u7F18\uFF0C\u91CA\u653E\u7EB5\u5411\u4EE3\u7801\u9605\u8BFB\u89C6\u91CE", accessories: [{ text: state.position === "left" ? "ACTIVE" : "LEFT" }], actions: React.createElement(ActionPanel, { title: "\u505C\u9760\u4F4D\u7F6E" }, - React.createElement(Action, { title: "\u505C\u9760\u5728\u5DE6\u4FA7 (Left)", icon: Icon.SidebarLeft, onAction: () => handleSetDockPosition("left") })) }), - React.createElement(List.Item, { key: "item-dock-right", title: "\u505C\u9760\u4E8E\u5C4F\u5E55\u53F3\u4FA7 (Set Dock Position: Right)", subtitle: "\u5C06 macOS \u7A0B\u5E8F\u575E\u505C\u9760\u5728\u5C4F\u5E55\u53F3\u8FB9\u7F18", accessories: [{ text: state.position === "right" ? "ACTIVE" : "RIGHT" }], actions: React.createElement(ActionPanel, { title: "\u505C\u9760\u4F4D\u7F6E" }, - React.createElement(Action, { title: "\u505C\u9760\u5728\u53F3\u4FA7 (Right)", icon: Icon.SidebarRight, onAction: () => handleSetDockPosition("right") })) }))), - (caps.restartExplorer || caps.restartDock) && (React.createElement(List.Section, { title: "\u7CFB\u7EDF\u7EA7\u8FD0\u7EF4\u4E0E\u6025\u6551 (Diagnostics & Recovery)" }, - caps.restartExplorer && (React.createElement(List.Item, { key: "item-restart-explorer", title: "\u91CD\u542F Windows \u8D44\u6E90\u7BA1\u7406\u5668 (Restart Explorer)", subtitle: "\u5F53\u4EFB\u52A1\u680F\u5361\u987F\u3001\u5047\u6B7B\u3001\u56FE\u6807\u7A7A\u767D\u6216\u663E\u9690\u5F02\u5E38\u65F6\u4E00\u952E\u91CD\u542F explorer.exe \u8FDB\u7A0B\u81EA\u6108", accessories: [{ text: "RELOAD" }], actions: React.createElement(ActionPanel, { title: "\u8D44\u6E90\u7BA1\u7406\u5668\u6CBB\u7406" }, - React.createElement(Action, { title: "\u91CD\u542F\u8D44\u6E90\u7BA1\u7406\u5668\u8FDB\u7A0B", icon: Icon.RotateAntiClockwise, onAction: handleRestartExplorer })) })), - caps.restartDock && (React.createElement(List.Item, { key: "item-restart-dock", title: "\u91CD\u542F macOS \u7A0B\u5E8F\u575E (Restart macOS Dock)", subtitle: "\u6267\u884C killall Dock \u91CD\u7F6E\u7A0B\u5E8F\u575E\u6E32\u67D3\u4E0E\u56FE\u6807\u7F13\u5B58", accessories: [{ text: "DOCK RELOAD" }], actions: React.createElement(ActionPanel, { title: "\u7A0B\u5E8F\u575E\u6025\u6551" }, - React.createElement(Action, { title: "\u91CD\u542F macOS Dock", icon: Icon.RotateClockwise, onAction: handleRestartDock })) })))))); -} diff --git a/packages/declarative-ui/dist/examples/windows-taskbar/taskbar-service.d.ts b/packages/declarative-ui/dist/examples/windows-taskbar/taskbar-service.d.ts deleted file mode 100644 index b8ec659d..00000000 --- a/packages/declarative-ui/dist/examples/windows-taskbar/taskbar-service.d.ts +++ /dev/null @@ -1,92 +0,0 @@ -import { TaskbarState, TaskbarActionResult, TaskbarAlignment, TaskbarPosition } from "./types.js"; -/** 测试或调用方注入的宿主对象(方法名 → 实现),透传给 callHostTransport */ -export type TaskbarHostOverride = Record; -/** 插件关心的三类平台;识别不出时为 undefined */ -export type TaskbarPlatform = "win32" | "darwin" | "linux"; -export interface WindowsTaskbarManagerOptions { - /** 运行平台,默认自动识别;单测注入后可在任意宿主上验证 Windows / macOS 两套行为 */ - readonly platform?: TaskbarPlatform | undefined; -} -/** - * 识别当前平台:Node 环境读 process.platform,渲染进程(无 process)读 userAgent - */ -export declare function detectTaskbarPlatform(): TaskbarPlatform | undefined; -/** - * 当前平台上宿主真正实现了的任务栏能力。界面只展示这里为 true 的动作,避免提供每次都失败的按钮。 - * - Windows:只有显示 / 隐藏(taskbar_show / taskbar_hide / taskbar_status); - * 自动隐藏、图标对齐、重启资源管理器宿主均未实现; - * - macOS:Dock 自动隐藏(即显示 / 隐藏)、停靠位置、重启 Dock; - * - 其他或识别不出:只保留显示 / 隐藏,由宿主如实返回结果。 - */ -export interface TaskbarCapabilities { - readonly visibility: boolean; - readonly autoHide: boolean; - readonly dockPosition: boolean; - readonly restartDock: boolean; - readonly restartExplorer: boolean; - readonly alignment: boolean; -} -export declare function getTaskbarCapabilities(platform: TaskbarPlatform | undefined): TaskbarCapabilities; -export declare class WindowsTaskbarManager { - private currentState; - private initialized; - private readonly platformOverride; - constructor(options?: WindowsTaskbarManagerOptions); - private get platform(); - /** 当前平台可用的动作(界面据此隐藏宿主未实现的动作) */ - getCapabilities(): TaskbarCapabilities; - getTaskbarState(): Promise; - private saveState; - /** - * 调用宿主方法。只有宿主确认成功才算成功;没有宿主时如实返回不可达,绝不假装成功 - */ - private callHost; - /** 失败结果:不改动已保存的状态,visible / autoHide 取当前保存的值,message 给用户看,error 保留宿主原始原因 */ - private failure; - private unreachableMessage; - /** - * 显式显示或隐藏:Windows 隐藏任务栏窗口,macOS 对应 Dock 常驻 / 自动隐藏。 - * 调用 taskbar_show / taskbar_hide 而不是 toggle,避免宿主真实状态与本地缓存不一致时方向反转 - */ - private applyVisible; - /** 读取宿主的真实显隐状态;读不到时回退到本地缓存 */ - private readHostVisible; - /** - * 一键切换任务栏显隐 / macOS Dock 自动隐藏 (Toggle Taskbar & Dock Visibility) - */ - toggleTaskbarVisibility(hostOverride?: TaskbarHostOverride): Promise; - showTaskbar(hostOverride?: TaskbarHostOverride): Promise; - hideTaskbar(hostOverride?: TaskbarHostOverride): Promise; - /** - * 设置自动隐藏:宿主目前只在 macOS 上提供(Dock 自动隐藏 = taskbar_hide), - * Windows 任务栏自动隐藏宿主尚未实现,如实返回不支持 - */ - setTaskbarAutoHide(autoHide: boolean, hostOverride?: TaskbarHostOverride): Promise; - /** - * 切换任务栏 / macOS Dock 自动隐藏 (Toggle Taskbar / Dock Auto-Hide) - */ - toggleTaskbarAutoHide(hostOverride?: TaskbarHostOverride): Promise; - /** - * 设置任务栏对齐方式 (Windows 11 TaskbarAl):宿主尚未提供写注册表的能力,如实返回不支持,不改动保存的状态 - */ - setTaskbarAlignment(alignment: TaskbarAlignment): Promise; - /** - * 设置任务栏 / macOS Dock 停靠位置:宿主只支持 macOS Dock 的底部 / 左侧 / 右侧,结果以宿主返回为准 - */ - setTaskbarPosition(position: TaskbarPosition, hostOverride?: TaskbarHostOverride): Promise; - /** - * 设置 macOS Dock 屏幕停靠位置 (Bottom / Left / Right) - */ - setDockPosition(position: "bottom" | "left" | "right", hostOverride?: TaskbarHostOverride): Promise; - /** - * 重启 macOS 程序坞 (killall Dock),结果以宿主返回为准 - */ - restartDock(hostOverride?: TaskbarHostOverride): Promise; - /** - * 重启桌面壳层:macOS 重启 Dock;Windows 重启资源管理器宿主尚未实现,如实返回不支持 - */ - restartExplorer(hostOverride?: TaskbarHostOverride): Promise; -} -export declare const defaultWindowsTaskbarManager: WindowsTaskbarManager; -/** 供界面层统一展示的 Toast 文案:失败时标题为 message,详情为宿主原始原因(与 message 相同则省略) */ -export declare function describeTaskbarFailure(res: TaskbarActionResult): string | undefined; diff --git a/packages/declarative-ui/dist/examples/windows-taskbar/taskbar-service.js b/packages/declarative-ui/dist/examples/windows-taskbar/taskbar-service.js deleted file mode 100644 index 26ba070a..00000000 --- a/packages/declarative-ui/dist/examples/windows-taskbar/taskbar-service.js +++ /dev/null @@ -1,261 +0,0 @@ -import { LocalStorage } from "../../api/storage.js"; -const TASKBAR_STORAGE_KEY = "@ztools/windows-taskbar/state"; -const DEFAULT_TASKBAR_STATE = { - visible: true, - autoHide: false, - position: "bottom", - alignment: "center", - size: "regular", - multiMonitorEnabled: true, - secondaryTrayCount: 1, - lastModifiedAt: Date.now() -}; -const DOCK_EDGES = ["bottom", "left", "right"]; -const DOCK_EDGE_LABELS = { bottom: "底部", left: "左侧", right: "右侧" }; -/** - * 识别当前平台:Node 环境读 process.platform,渲染进程(无 process)读 userAgent - */ -export function detectTaskbarPlatform() { - try { - if (typeof process !== "undefined" && typeof process?.platform === "string") { - const p = process.platform; - if (p === "win32" || p === "darwin" || p === "linux") - return p; - } - } - catch { - // 渲染进程沙箱里访问 process 可能抛错,改用 userAgent 判断 - } - const ua = String(globalThis.navigator?.userAgent ?? ""); - if (/Macintosh|Mac OS X/i.test(ua)) - return "darwin"; - if (/Windows/i.test(ua)) - return "win32"; - if (/Linux/i.test(ua)) - return "linux"; - return undefined; -} -export function getTaskbarCapabilities(platform) { - const isMac = platform === "darwin"; - return { - visibility: true, - autoHide: isMac, - dockPosition: isMac, - restartDock: isMac, - restartExplorer: false, - alignment: false - }; -} -/** 这些错误码表示根本没连上宿主(非 ZTools 环境 / 宿主未暴露该方法),与"宿主执行失败"区分开 */ -function isHostUnreachable(error) { - return /^(NO_WINDOW_ENV|METHOD_NOT_AVAILABLE)/.test(String(error ?? "")); -} -export class WindowsTaskbarManager { - currentState = { ...DEFAULT_TASKBAR_STATE }; - initialized = false; - platformOverride; - constructor(options = {}) { - this.platformOverride = options.platform; - } - get platform() { - return this.platformOverride ?? detectTaskbarPlatform(); - } - /** 当前平台可用的动作(界面据此隐藏宿主未实现的动作) */ - getCapabilities() { - return getTaskbarCapabilities(this.platform); - } - async getTaskbarState() { - if (!this.initialized) { - try { - const stored = await LocalStorage.getItem(TASKBAR_STORAGE_KEY); - if (stored && typeof stored.visible === "boolean") { - this.currentState = { ...stored }; - } - } - catch { - // 读不到本地缓存时沿用默认状态 - } - this.initialized = true; - } - return { ...this.currentState }; - } - async saveState(updated) { - this.currentState = { - ...this.currentState, - ...updated, - lastModifiedAt: Date.now() - }; - try { - await LocalStorage.setItem(TASKBAR_STORAGE_KEY, this.currentState); - } - catch { - // 本地缓存写入失败不影响系统设置本身已生效 - } - return { ...this.currentState }; - } - /** - * 调用宿主方法。只有宿主确认成功才算成功;没有宿主时如实返回不可达,绝不假装成功 - */ - async callHost(method, params, hostOverride) { - const { callHostTransport, isRealElectronHost } = await import("../shared/native-ipc.js"); - if (!hostOverride && !isRealElectronHost()) { - return { ok: false, reachable: false, error: "NO_HOST" }; - } - const res = await callHostTransport(method, params, hostOverride); - if (res.ok) - return { ok: true, reachable: true, data: res.data }; - return { ok: false, reachable: !isHostUnreachable(res.error), error: res.error }; - } - /** 失败结果:不改动已保存的状态,visible / autoHide 取当前保存的值,message 给用户看,error 保留宿主原始原因 */ - async failure(message, error) { - const state = await this.getTaskbarState(); - return { success: false, visible: state.visible, autoHide: state.autoHide, message, error: error ?? message, state }; - } - unreachableMessage() { - return "未连接 ZTools 宿主,无法控制系统任务栏 / Dock"; - } - /** - * 显式显示或隐藏:Windows 隐藏任务栏窗口,macOS 对应 Dock 常驻 / 自动隐藏。 - * 调用 taskbar_show / taskbar_hide 而不是 toggle,避免宿主真实状态与本地缓存不一致时方向反转 - */ - async applyVisible(visible, hostOverride) { - const res = await this.callHost(visible ? "taskbar_show" : "taskbar_hide", {}, hostOverride); - if (!res.ok) { - const fallback = visible ? "显示任务栏失败" : "隐藏任务栏失败"; - return this.failure(res.reachable ? fallback : this.unreachableMessage(), res.reachable ? res.error : undefined); - } - const isMac = this.platform === "darwin"; - // macOS 的"隐藏"就是开启 Dock 自动隐藏,两个字段同步更新 - const updated = await this.saveState(isMac ? { visible, autoHide: !visible } : { visible }); - const hostMessage = typeof res.data?.message === "string" && res.data.message ? res.data.message : ""; - return { - success: true, - visible, - message: hostMessage || (visible ? "任务栏已显示" : "任务栏已隐藏"), - state: updated - }; - } - /** 读取宿主的真实显隐状态;读不到时回退到本地缓存 */ - async readHostVisible(hostOverride) { - const res = await this.callHost("taskbar_status", {}, hostOverride); - if (res.ok && typeof res.data?.visible === "boolean") - return res.data.visible; - return (await this.getTaskbarState()).visible; - } - /** - * 一键切换任务栏显隐 / macOS Dock 自动隐藏 (Toggle Taskbar & Dock Visibility) - */ - async toggleTaskbarVisibility(hostOverride) { - const current = await this.readHostVisible(hostOverride); - return this.applyVisible(!current, hostOverride); - } - async showTaskbar(hostOverride) { - return this.applyVisible(true, hostOverride); - } - async hideTaskbar(hostOverride) { - return this.applyVisible(false, hostOverride); - } - /** - * 设置自动隐藏:宿主目前只在 macOS 上提供(Dock 自动隐藏 = taskbar_hide), - * Windows 任务栏自动隐藏宿主尚未实现,如实返回不支持 - */ - async setTaskbarAutoHide(autoHide, hostOverride) { - if (this.platform !== "darwin") { - return this.failure("当前版本暂不支持切换 Windows 任务栏自动隐藏,仅 macOS Dock 支持"); - } - const res = await this.callHost(autoHide ? "taskbar_hide" : "taskbar_show", {}, hostOverride); - if (!res.ok) { - return this.failure(res.reachable ? "切换 Dock 自动隐藏失败" : this.unreachableMessage(), res.reachable ? res.error : undefined); - } - const updated = await this.saveState({ autoHide, visible: !autoHide }); - return { - success: true, - autoHide, - message: autoHide ? "已开启 Dock 自动隐藏" : "已关闭 Dock 自动隐藏", - state: updated - }; - } - /** - * 切换任务栏 / macOS Dock 自动隐藏 (Toggle Taskbar / Dock Auto-Hide) - */ - async toggleTaskbarAutoHide(hostOverride) { - if (this.platform === "darwin") { - // macOS 上以 Dock 真实状态为准决定方向 - const visible = await this.readHostVisible(hostOverride); - return this.setTaskbarAutoHide(visible, hostOverride); - } - const current = await this.getTaskbarState(); - return this.setTaskbarAutoHide(!current.autoHide, hostOverride); - } - /** - * 设置任务栏对齐方式 (Windows 11 TaskbarAl):宿主尚未提供写注册表的能力,如实返回不支持,不改动保存的状态 - */ - async setTaskbarAlignment(alignment) { - if (alignment !== "start" && alignment !== "center") { - return this.failure(`无效的对齐方式: ${String(alignment)}`); - } - return this.failure("当前版本暂不支持修改任务栏对齐方式"); - } - /** - * 设置任务栏 / macOS Dock 停靠位置:宿主只支持 macOS Dock 的底部 / 左侧 / 右侧,结果以宿主返回为准 - */ - async setTaskbarPosition(position, hostOverride) { - const platform = this.platform; - if (platform && platform !== "darwin") { - return this.failure("当前系统没有 Dock,仅 macOS 支持设置停靠位置"); - } - if (!DOCK_EDGES.includes(position)) { - return this.failure(`Dock 不支持停靠到 ${String(position)},可选:底部 / 左侧 / 右侧`); - } - const res = await this.callHost("taskbar_set_dock_position", { position }, hostOverride); - if (!res.ok) { - return this.failure(res.reachable ? "设置 Dock 停靠位置失败" : this.unreachableMessage(), res.reachable ? res.error : undefined); - } - const updated = await this.saveState({ position }); - return { - success: true, - message: `Dock 停靠位置已切换至${DOCK_EDGE_LABELS[position]}`, - state: updated - }; - } - /** - * 设置 macOS Dock 屏幕停靠位置 (Bottom / Left / Right) - */ - async setDockPosition(position, hostOverride) { - return this.setTaskbarPosition(position, hostOverride); - } - /** - * 重启 macOS 程序坞 (killall Dock),结果以宿主返回为准 - */ - async restartDock(hostOverride) { - const platform = this.platform; - if (platform && platform !== "darwin") { - return this.failure("当前系统没有 Dock,仅 macOS 支持重启 Dock"); - } - const res = await this.callHost("taskbar_restart_dock", {}, hostOverride); - if (!res.ok) { - return this.failure(res.reachable ? "重启 Dock 失败" : this.unreachableMessage(), res.reachable ? res.error : undefined); - } - return { success: true, message: "Dock 已重启", state: await this.getTaskbarState() }; - } - /** - * 重启桌面壳层:macOS 重启 Dock;Windows 重启资源管理器宿主尚未实现,如实返回不支持 - */ - async restartExplorer(hostOverride) { - const platform = this.platform; - if (platform === "darwin") { - return this.restartDock(hostOverride); - } - if (platform === "win32") { - return this.failure("当前版本暂不支持重启 Windows 资源管理器"); - } - return this.failure("当前系统不支持重启桌面壳层"); - } -} -export const defaultWindowsTaskbarManager = new WindowsTaskbarManager(); -/** 供界面层统一展示的 Toast 文案:失败时标题为 message,详情为宿主原始原因(与 message 相同则省略) */ -export function describeTaskbarFailure(res) { - if (res.success) - return undefined; - return res.error && res.error !== res.message ? res.error : undefined; -} diff --git a/packages/declarative-ui/dist/examples/windows-taskbar/types.d.ts b/packages/declarative-ui/dist/examples/windows-taskbar/types.d.ts deleted file mode 100644 index da01bce8..00000000 --- a/packages/declarative-ui/dist/examples/windows-taskbar/types.d.ts +++ /dev/null @@ -1,28 +0,0 @@ -/** - * Windows Taskbar (任务栏治理中枢) 类型定义 - * - * 参考常见启动器的任务栏控制交互自研实现: - * - 核心命令:切换任务栏显示/隐藏(关键词 bar / show / hide) - * - 偏好字段:showTaskbar, disableWindowsTaskbar, position, sidebar, compact, size, widgets - */ -export type TaskbarPosition = "bottom" | "top" | "left" | "right"; -export type TaskbarAlignment = "start" | "center"; -export type TaskbarSize = "smallest" | "small" | "regular" | "large" | "largest"; -export interface TaskbarState { - readonly visible: boolean; - readonly autoHide: boolean; - readonly position: TaskbarPosition; - readonly alignment: TaskbarAlignment; - readonly size: TaskbarSize; - readonly multiMonitorEnabled: boolean; - readonly secondaryTrayCount: number; - readonly lastModifiedAt: number; -} -export interface TaskbarActionResult { - readonly success: boolean; - readonly visible?: boolean | undefined; - readonly autoHide?: boolean | undefined; - readonly message: string; - readonly state: TaskbarState; - readonly error?: string | undefined; -} diff --git a/packages/declarative-ui/dist/examples/windows-taskbar/types.js b/packages/declarative-ui/dist/examples/windows-taskbar/types.js deleted file mode 100644 index be9f6f07..00000000 --- a/packages/declarative-ui/dist/examples/windows-taskbar/types.js +++ /dev/null @@ -1,8 +0,0 @@ -/** - * Windows Taskbar (任务栏治理中枢) 类型定义 - * - * 参考常见启动器的任务栏控制交互自研实现: - * - 核心命令:切换任务栏显示/隐藏(关键词 bar / show / hide) - * - 偏好字段:showTaskbar, disableWindowsTaskbar, position, sidebar, compact, size, widgets - */ -export {}; diff --git a/packages/declarative-ui/dist/examples/winget/index.d.ts b/packages/declarative-ui/dist/examples/winget/index.d.ts deleted file mode 100644 index c5895c09..00000000 --- a/packages/declarative-ui/dist/examples/winget/index.d.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { WingetPackage } from "./packages.js"; -export * from "./packages.js"; -/** - * 查看软件包详情视图 (现代纯正 TSX 模式) - */ -export declare function WingetDetailView({ pkg, onPackageUpdated }: { - pkg: WingetPackage; - onPackageUpdated?: (updated: WingetPackage) => void; -}): JSX.Element; -/** - * Winget 包管理器前端主命令 (现代纯正 TSX 模式) - */ -export default function WingetCommand(): JSX.Element; diff --git a/packages/declarative-ui/dist/examples/winget/index.js b/packages/declarative-ui/dist/examples/winget/index.js deleted file mode 100644 index 9e078367..00000000 --- a/packages/declarative-ui/dist/examples/winget/index.js +++ /dev/null @@ -1,163 +0,0 @@ -import { isRealElectronHost } from '../shared/native-ipc.js'; -import React from "../../index.js"; -import { List, Detail, ActionPanel, Action, Icon, Color, showToast, Toast, useNavigation } from "../../index.js"; -import { useState } from "../../runtime/hooks.js"; -import { SAMPLE_WINGET_PACKAGES, filterWingetPackages, installWingetPackage, upgradeWingetPackage, uninstallWingetPackage } from "./packages.js"; -export * from "./packages.js"; -/** - * 查看软件包详情视图 (现代纯正 TSX 模式) - */ -export function WingetDetailView({ pkg, onPackageUpdated }) { - const installCmd = `winget install --id ${pkg.id} -e --accept-package-agreements --accept-source-agreements`; - const upgradeCmd = `winget upgrade --id ${pkg.id}`; - const uninstallCmd = `winget uninstall --id ${pkg.id}`; - const markdown = ` -# ${pkg.name} - -> **包标识 ID**: \`${pkg.id}\` | **开发商**: \`${pkg.publisher}\` - -### 软件简介 -${pkg.description} - ---- - -### 终端安装与管理命令 -\`\`\`powershell -# 一键安装 -${installCmd} - -# 升级最新版本 -${upgradeCmd} - -# 卸载清理 -${uninstallCmd} -\`\`\` - ---- - -### 分类与标签 -${pkg.tags.map((t) => `\`#${t}\``).join(" ")} - `; - return (React.createElement(Detail, { markdown: markdown, navigationTitle: `${pkg.name} (${pkg.id})`, metadata: React.createElement(Detail.Metadata, null, - React.createElement(Detail.Metadata.Label, { title: "\u5305 ID", text: pkg.id, icon: Icon.Key }), - React.createElement(Detail.Metadata.Label, { title: "\u5F00\u53D1\u5546", text: pkg.publisher, icon: Icon.Document }), - React.createElement(Detail.Metadata.Label, { title: "\u5DF2\u5B89\u88C5\u7248\u672C", text: pkg.installedVersion || "未安装", icon: Icon.Pin }), - React.createElement(Detail.Metadata.Label, { title: "\u6700\u65B0\u53EF\u7528\u7248\u672C", text: pkg.latestVersion, icon: Icon.Upload }), - React.createElement(Detail.Metadata.Label, { title: "\u5F00\u6E90\u534F\u8BAE", text: pkg.license, icon: Icon.Document }), - React.createElement(Detail.Metadata.Label, { title: "\u5206\u53D1\u6E90", text: pkg.source || "winget", icon: Icon.Globe }), - React.createElement(Detail.Metadata.Label, { title: "\u67B6\u6784\u652F\u6301", text: pkg.architecture, icon: Icon.Terminal }), - React.createElement(Detail.Metadata.Separator, null), - React.createElement(Detail.Metadata.TagList, { title: "\u72B6\u6001" }, - React.createElement(Detail.Metadata.TagList.Item, { text: pkg.status === "installed" - ? "已是最新版本" - : pkg.status === "upgradable" - ? `可升级至 v${pkg.latestVersion}` - : "未安装", color: pkg.status === "installed" - ? Color.Green - : pkg.status === "upgradable" - ? Color.Yellow - : Color.SecondaryText }))), actions: React.createElement(ActionPanel, { title: "\u8F6F\u4EF6\u5305\u64CD\u4F5C" }, - pkg.status === "upgradable" && (React.createElement(Action, { title: "\u4E00\u952E\u5347\u7EA7\u5230\u6700\u65B0\u7248", icon: Icon.Upload, onAction: async () => { - const updated = { - ...pkg, - installedVersion: pkg.latestVersion, - status: "installed" - }; - onPackageUpdated?.(updated); - await showToast(Toast.Style.Success, `已升级 ${pkg.name}`, `版本升级至 ${pkg.latestVersion}`); - } })), - pkg.status === "available" && (React.createElement(Action, { title: "\u4E00\u952E\u5B89\u88C5\u6B64\u8F6F\u4EF6", icon: Icon.Download, onAction: async () => { - const updated = { - ...pkg, - installedVersion: pkg.latestVersion, - status: "installed" - }; - onPackageUpdated?.(updated); - await showToast(Toast.Style.Success, `已安装 ${pkg.name}`, `成功安装版本 ${pkg.latestVersion}`); - } })), - pkg.status !== "available" && (React.createElement(Action, { title: "\u5378\u8F7D\u6B64\u8F6F\u4EF6", icon: Icon.Trash, onAction: async () => { - const updated = { - ...pkg, - installedVersion: null, - status: "available" - }; - onPackageUpdated?.(updated); - await showToast(Toast.Style.Success, `已卸载 ${pkg.name}`); - } })), - React.createElement(Action.CopyToClipboard, { title: "\u590D\u5236 Winget \u5B89\u88C5\u547D\u4EE4", content: installCmd, icon: Icon.CopyClipboard }), - React.createElement(Action.CopyToClipboard, { title: "\u590D\u5236 Winget \u5347\u7EA7\u547D\u4EE4", content: upgradeCmd, icon: Icon.Upload }), - React.createElement(Action.CopyToClipboard, { title: "\u590D\u5236\u8F6F\u4EF6\u5305 ID", content: pkg.id, icon: Icon.Key }), - React.createElement(Action.OpenInBrowser, { title: "\u8BBF\u95EE\u8F6F\u4EF6\u5B98\u65B9\u7F51\u7AD9", url: pkg.homepage, icon: Icon.Globe })) })); -} -/** - * Winget 包管理器前端主命令 (现代纯正 TSX 模式) - */ -export default function WingetCommand() { - const [packages, setPackages] = useState(isRealElectronHost() ? [] : SAMPLE_WINGET_PACKAGES); - const [filterType, setFilterType] = useState("all"); - const [searchText, setSearchText] = useState(""); - const [isShowingDetail, setIsShowingDetail] = useState(true); - const { push } = useNavigation(); - const filtered = filterWingetPackages(packages, searchText, filterType); - const handleInstall = async (pkg) => { - setPackages((prev) => installWingetPackage(prev, pkg.id)); - await showToast(Toast.Style.Success, `正在安装 ${pkg.name}`, `已执行 winget install --id ${pkg.id} -e`); - }; - const handleUpgrade = async (pkg) => { - setPackages((prev) => upgradeWingetPackage(prev, pkg.id)); - await showToast(Toast.Style.Success, `正在升级 ${pkg.name}`, `已升级到最新版 ${pkg.latestVersion}`); - }; - const handleUninstall = async (pkg) => { - setPackages((prev) => uninstallWingetPackage(prev, pkg.id)); - await showToast(Toast.Style.Success, `正在卸载 ${pkg.name}`, `已从系统移除该应用`); - }; - return (React.createElement(List, { navigationTitle: "Windows \u5305\u7BA1\u7406\u5668 (Winget)", searchBarPlaceholder: "\u641C\u7D22\u5168\u7F51\u8F6F\u4EF6\u5305 (\u4F8B\u5982: VS Code, Git, Chrome, Node, Bun)...", searchText: searchText, isShowingDetail: isShowingDetail, onSearchTextChange: (val) => setSearchText(val), searchBarAccessory: React.createElement(List.Dropdown, { tooltip: "\u7B5B\u9009\u8F6F\u4EF6\u5305\u72B6\u6001", value: filterType, onChange: (newVal) => setFilterType(newVal) }, - React.createElement(List.Dropdown.Item, { title: "\u5168\u90E8\u8F6F\u4EF6\u5305 (All Packages)", value: "all" }), - React.createElement(List.Dropdown.Item, { title: "\u53EF\u66F4\u65B0 (Upgradable)", value: "upgradable" }), - React.createElement(List.Dropdown.Item, { title: "\u5DF2\u5B89\u88C5 (Installed)", value: "installed" }), - React.createElement(List.Dropdown.Item, { title: "\u672A\u5B89\u88C5 (Available)", value: "available" })), actions: React.createElement(ActionPanel, { title: "\u5168\u5C40\u64CD\u4F5C" }, - React.createElement(Action, { title: "\u5237\u65B0\u8F6F\u4EF6\u5305\u6E05\u5355", icon: Icon.Repeat, onAction: async () => { - await showToast(Toast.Style.Success, "已刷新 Winget 本地源清单"); - } }), - React.createElement(Action, { title: isShowingDetail ? "隐藏详情侧边栏" : "显示详情侧边栏", icon: Icon.Sidebar, onAction: () => setIsShowingDetail((prev) => !prev) })) }, - React.createElement(List.Section, { title: `软件包列表 (${filtered.length})` }, filtered.map((pkg) => { - const isUpgradable = pkg.status === "upgradable"; - const isInstalled = pkg.status === "installed"; - return (React.createElement(List.Item, { key: pkg.id, id: pkg.id, title: pkg.name, subtitle: `${pkg.id} (${pkg.publisher})`, icon: isInstalled ? Icon.Checkmark : isUpgradable ? Icon.Upload : Icon.Download, accessories: [ - ...(isUpgradable - ? [ - { text: `v${pkg.installedVersion} ➔ v${pkg.latestVersion}` }, - { text: "可升级", tag: "upgradable" } - ] - : isInstalled - ? [{ text: `v${pkg.installedVersion}` }, { text: "已安装", tag: "installed" }] - : [{ text: `v${pkg.latestVersion}` }, { text: "未安装" }]) - ], detail: React.createElement(List.Item.Detail, { markdown: `# ${pkg.name}\n\n> ${pkg.description}\n\n---\n\n### 终端命令参考\n\`\`\`powershell\n# 一键安装\nwinget install --id ${pkg.id} -e\n\n# 升级最新版\nwinget upgrade --id ${pkg.id} -e\n\n# 卸载清理\nwinget uninstall --id ${pkg.id} -e\n\`\`\`\n\n### 官方网站\n[${pkg.homepage}](${pkg.homepage})`, metadata: React.createElement(List.Item.Detail.Metadata, null, - React.createElement(List.Item.Detail.Metadata.Label, { title: "\u8F6F\u4EF6\u5305 ID", text: pkg.id, icon: Icon.Key }), - React.createElement(List.Item.Detail.Metadata.Label, { title: "\u53D1\u5E03\u8005", text: pkg.publisher, icon: Icon.Pencil }), - React.createElement(List.Item.Detail.Metadata.Label, { title: "\u6700\u65B0\u7248\u672C", text: pkg.latestVersion, icon: Icon.Check }), - React.createElement(List.Item.Detail.Metadata.Label, { title: "\u5DF2\u5B89\u88C5\u7248\u672C", text: pkg.installedVersion || "未安装", icon: Icon.Clock }), - React.createElement(List.Item.Detail.Metadata.Label, { title: "\u5F00\u6E90\u8BB8\u53EF\u8BC1", text: pkg.license, icon: Icon.Document }), - React.createElement(List.Item.Detail.Metadata.Label, { title: "\u5206\u53D1\u6E90", text: pkg.source || "winget", icon: Icon.Globe }), - React.createElement(List.Item.Detail.Metadata.Label, { title: "\u7CFB\u7EDF\u67B6\u6784", text: pkg.architecture, icon: Icon.Terminal }), - React.createElement(List.Item.Detail.Metadata.Separator, null), - React.createElement(List.Item.Detail.Metadata.TagList, { title: "\u72B6\u6001" }, - React.createElement(List.Item.Detail.Metadata.TagList.Item, { text: pkg.status === "installed" - ? "已安装 (Installed)" - : pkg.status === "upgradable" - ? `可升级至 v${pkg.latestVersion}` - : "可安装 (Available)", color: pkg.status === "installed" - ? Color.Green - : pkg.status === "upgradable" - ? Color.Yellow - : Color.SecondaryText }))) }), actions: React.createElement(ActionPanel, { title: pkg.name }, - isUpgradable && (React.createElement(Action, { title: "\u4E00\u952E\u5347\u7EA7\u5230\u6700\u65B0\u7248", icon: Icon.Upload, onAction: () => handleUpgrade(pkg) })), - !isInstalled && !isUpgradable && (React.createElement(Action, { title: "\u4E00\u952E\u5B89\u88C5\u6B64\u8F6F\u4EF6", icon: Icon.Download, onAction: () => handleInstall(pkg) })), - (isInstalled || isUpgradable) && (React.createElement(Action, { title: "\u5378\u8F7D\u6B64\u8F6F\u4EF6", icon: Icon.Trash, onAction: () => handleUninstall(pkg) })), - React.createElement(Action.CopyToClipboard, { title: "\u590D\u5236 Winget \u5B89\u88C5\u547D\u4EE4", content: `winget install --id ${pkg.id} -e`, icon: Icon.CopyClipboard }), - React.createElement(Action.CopyToClipboard, { title: "\u590D\u5236 Winget \u5347\u7EA7\u547D\u4EE4", content: `winget upgrade --id ${pkg.id} -e`, icon: Icon.Upload }), - React.createElement(Action.CopyToClipboard, { title: "\u590D\u5236\u8F6F\u4EF6\u5305 ID", content: pkg.id, icon: Icon.Key }), - React.createElement(Action.OpenInBrowser, { title: "\u8BBF\u95EE\u8F6F\u4EF6\u5B98\u65B9\u7F51\u7AD9", url: pkg.homepage, icon: Icon.Globe }), - React.createElement(Action.Push, { title: "\u67E5\u770B\u5305\u8BE6\u7EC6\u7248\u672C\u63CF\u8FF0", icon: Icon.Eye, target: () => (React.createElement(WingetDetailView, { pkg: pkg, onPackageUpdated: (u) => setPackages((prev) => prev.map((p) => (p.id === u.id ? u : p))) })) })) })); - })))); -} diff --git a/packages/declarative-ui/dist/examples/winget/packages.d.ts b/packages/declarative-ui/dist/examples/winget/packages.d.ts deleted file mode 100644 index 461d2bd8..00000000 --- a/packages/declarative-ui/dist/examples/winget/packages.d.ts +++ /dev/null @@ -1,19 +0,0 @@ -export interface WingetPackage { - id: string; - name: string; - publisher: string; - installedVersion: string | null; - latestVersion: string; - status: "installed" | "upgradable" | "available"; - description: string; - tags: string[]; - license: string; - homepage: string; - architecture: "x64" | "ARM64" | "Neutral"; - source?: string; -} -export declare const SAMPLE_WINGET_PACKAGES: WingetPackage[]; -export declare function filterWingetPackages(packages: WingetPackage[], query: string, filterType: string): WingetPackage[]; -export declare function installWingetPackage(packages: WingetPackage[], id: string): WingetPackage[]; -export declare function upgradeWingetPackage(packages: WingetPackage[], id: string): WingetPackage[]; -export declare function uninstallWingetPackage(packages: WingetPackage[], id: string): WingetPackage[]; diff --git a/packages/declarative-ui/dist/examples/winget/packages.js b/packages/declarative-ui/dist/examples/winget/packages.js deleted file mode 100644 index d7887610..00000000 --- a/packages/declarative-ui/dist/examples/winget/packages.js +++ /dev/null @@ -1,138 +0,0 @@ -export const SAMPLE_WINGET_PACKAGES = [ - { - id: "Microsoft.VisualStudioCode", - name: "Visual Studio Code", - publisher: "Microsoft Corporation", - installedVersion: "1.92.0", - latestVersion: "1.94.2", - status: "upgradable", - description: "功能强大的开源跨平台代码编辑器,支持丰富的插件扩展与内置 Git/终端调试能力。", - tags: ["editor", "development", "typescript", "ide", "vscode"], - license: "MIT", - homepage: "https://code.visualstudio.com", - architecture: "x64", - source: "winget" - }, - { - id: "Git.Git", - name: "Git", - publisher: "Software Freedom Conservancy", - installedVersion: "2.46.0", - latestVersion: "2.46.0", - status: "installed", - description: "快速、可扩展、分布式的版本控制系统,全球开发者事实上的标准协作工具。", - tags: ["vcs", "git", "cli", "tools"], - license: "GPL-2.0", - homepage: "https://git-scm.com", - architecture: "x64", - source: "winget" - }, - { - id: "Google.Chrome", - name: "Google Chrome", - publisher: "Google LLC", - installedVersion: "128.0.6613.120", - latestVersion: "129.0.6668.71", - status: "upgradable", - description: "快速、安全且备受信赖的网络浏览器,基于 Chromium 核心构建。", - tags: ["browser", "web", "chromium"], - license: "Freeware", - homepage: "https://www.google.com/chrome", - architecture: "x64", - source: "winget" - }, - { - id: "OpenJS.NodeJS.LTS", - name: "Node.js (LTS)", - publisher: "OpenJS Foundation", - installedVersion: "20.17.0", - latestVersion: "20.17.0", - status: "installed", - description: "基于 Chrome V8 引擎的高性能异步事件驱动 JavaScript 运行时环境。", - tags: ["javascript", "runtime", "backend"], - license: "MIT", - homepage: "https://nodejs.org", - architecture: "x64", - source: "winget" - }, - { - id: "Oven-sh.Bun", - name: "Bun", - publisher: "Oven", - installedVersion: null, - latestVersion: "1.1.29", - status: "available", - description: "极速的 JavaScript & TypeScript 一体化运行时、打包工具、测试运行器与包管理器。", - tags: ["javascript", "typescript", "runtime", "fast"], - license: "MIT", - homepage: "https://bun.sh", - architecture: "x64", - source: "winget" - }, - { - id: "7zip.7zip", - name: "7-Zip", - publisher: "Igor Pavlov", - installedVersion: "24.07", - latestVersion: "24.08", - status: "upgradable", - description: "高压缩比的文件归档实用工具,支持 7z, ZIP, RAR, TAR, GZIP 等多种格式。", - tags: ["compression", "utility", "archive"], - license: "LGPL", - homepage: "https://www.7-zip.org", - architecture: "x64", - source: "winget" - }, - { - id: "Rustlang.Rustup", - name: "Rustup", - publisher: "Rust Project Developers", - installedVersion: null, - latestVersion: "1.27.1", - status: "available", - description: "Rust 编程语言官方工具链安装管理器,支持多工具链平滑切换与交叉编译。", - tags: ["rust", "compiler", "toolchain"], - license: "MIT / Apache-2.0", - homepage: "https://rustup.rs", - architecture: "x64", - source: "winget" - }, - { - id: "Docker.DockerDesktop", - name: "Docker Desktop", - publisher: "Docker Inc.", - installedVersion: null, - latestVersion: "4.34.2", - status: "available", - description: "轻松在 Windows 上构建、共享与运行容器化应用的开发者桌面应用。", - tags: ["containers", "docker", "virtualization"], - license: "Subscription", - homepage: "https://www.docker.com", - architecture: "x64", - source: "winget" - } -]; -export function filterWingetPackages(packages, query, filterType) { - let list = packages; - if (filterType !== "all") { - list = list.filter((p) => p.status === filterType); - } - if (!query || !query.trim()) { - return list; - } - const q = query.toLowerCase().trim(); - return list.filter((p) => p.id.toLowerCase().includes(q) || - p.name.toLowerCase().includes(q) || - p.publisher.toLowerCase().includes(q) || - p.description.toLowerCase().includes(q) || - p.tags.some((t) => t.toLowerCase().includes(q))); -} -export function installWingetPackage(packages, id) { - return packages.map((p) => p.id === id ? { ...p, status: "installed", installedVersion: p.latestVersion } : p); -} -export function upgradeWingetPackage(packages, id) { - return packages.map((p) => p.id === id ? { ...p, status: "installed", installedVersion: p.latestVersion } : p); -} -export function uninstallWingetPackage(packages, id) { - return packages.map((p) => p.id === id ? { ...p, status: "available", installedVersion: null } : p); -} diff --git a/packages/declarative-ui/dist/examples/wrapped-nudges-shortcuts/engine.d.ts b/packages/declarative-ui/dist/examples/wrapped-nudges-shortcuts/engine.d.ts deleted file mode 100644 index f9eabb05..00000000 --- a/packages/declarative-ui/dist/examples/wrapped-nudges-shortcuts/engine.d.ts +++ /dev/null @@ -1,88 +0,0 @@ -/** - * Wrapped, Nudges & Shortcuts 引擎实现 - * 本地极客统计与勋章生成、特权侧车与 SLA 延迟监控、Windows 快捷指令与 .lnk 执行器 - */ -import { WrappedUsageStats, FeatureNudgeItem, SystemPrivilegeDiagnostic, WindowsShortcutItem, AppleShortcutItem } from "./types.js"; -export declare const WRAPPED_STORAGE_KEY = "ztools_wrapped_stats_v1"; -export declare const SHORTCUTS_STORAGE_KEY = "ztools_custom_windows_shortcuts_v1"; -/** - * 辅助:渲染 ASCII / Unicode 进度图表条 - */ -export declare function renderAsciiBar(percentage: number, barLength?: number): string; -/** - * 辅助:根据段位生成极客勋章 Markdown 卡片 - */ -export declare function generateBadgeCard(tier: string, totalLaunches: number, timeSavedHours: number): string; -/** - * 个人极客使用年度统计计算引擎 - */ -export declare function calculateWrappedStats(yearOrStats?: number | any): any; -/** - * 清洗并防御非法或被篡改的 Wrapped 统计数据 - */ -export declare function sanitizeWrappedStats(raw: any, defaultYear?: number): WrappedUsageStats; -/** - * 特权与能力引导 (Trial Nudges / Feature Highlights) - */ -export declare const FEATURE_NUDGES: FeatureNudgeItem[]; -/** - * 获取系统特权穿透与底层侧车健康度诊断数据 - */ -export declare function getSystemPrivilegeDiagnostic(): Promise; -/** - * 重启底层预编译侧车进程 - */ -export declare function restartSidecar(sidecarBinary: string): Promise<{ - success: boolean; - newPid: number; - message: string; -}>; -/** - * 预设 Windows 快捷方式与系统运维自动化指令 (Windows Shortcuts) - */ -export declare const DEFAULT_WINDOWS_SHORTCUTS: WindowsShortcutItem[]; -/** - * 预设 macOS Apple Shortcuts 样本集 (离线/测试降级兜底) - */ -export declare const DEFAULT_APPLE_SHORTCUTS: AppleShortcutItem[]; -/** - * 获取 macOS 原生「快捷指令 (/usr/bin/shortcuts list)」列表 - */ -export declare function getAppleShortcuts(hostOverride?: any): Promise; -/** - * 运行指定的 macOS 快捷指令 (/usr/bin/shortcuts run ) - */ -export declare function executeAppleShortcut(name: string, input?: string, hostOverride?: any): Promise<{ - success: boolean; - output?: string; - message: string; -}>; -/** - * 在 macOS「快捷指令.app」中查看并编辑指定快捷指令 (/usr/bin/shortcuts view ) - */ -export declare function openShortcutInApp(name: string, hostOverride?: any): Promise<{ - success: boolean; - message: string; -}>; -/** - * 获取快捷指令列表(在真实宿主中若检测到 shortcuts_list 返回数据也自动融合) - */ -export declare function getWindowsShortcuts(hostOverride?: any): Promise; -/** - * 执行 Windows / 跨端快捷指令 - */ -export declare function executeWindowsShortcut(shortcut: WindowsShortcutItem, options?: { - runAsAdmin?: boolean; - input?: string; - hostOverride?: any; -}): Promise<{ - success: boolean; - message: string; -}>; -/** - * 在资源管理器中定位快捷方式目标路径 - */ -export declare function revealShortcutInExplorer(shortcut: WindowsShortcutItem): Promise<{ - success: boolean; - message: string; -}>; diff --git a/packages/declarative-ui/dist/examples/wrapped-nudges-shortcuts/engine.js b/packages/declarative-ui/dist/examples/wrapped-nudges-shortcuts/engine.js deleted file mode 100644 index a3b39da4..00000000 --- a/packages/declarative-ui/dist/examples/wrapped-nudges-shortcuts/engine.js +++ /dev/null @@ -1,756 +0,0 @@ -/** - * Wrapped, Nudges & Shortcuts 引擎实现 - * 本地极客统计与勋章生成、特权侧车与 SLA 延迟监控、Windows 快捷指令与 .lnk 执行器 - */ -import { LocalStorage } from "../../api/storage.js"; -import { callHostTransport, isRealElectronHost } from "../shared/native-ipc.js"; -export const WRAPPED_STORAGE_KEY = "ztools_wrapped_stats_v1"; -export const SHORTCUTS_STORAGE_KEY = "ztools_custom_windows_shortcuts_v1"; -/** - * 辅助:渲染 ASCII / Unicode 进度图表条 - */ -export function renderAsciiBar(percentage, barLength = 14) { - const p = Math.max(0, Math.min(100, Math.round(percentage))); - const filled = Math.round((p / 100) * barLength); - const empty = Math.max(0, barLength - filled); - return `${"█".repeat(filled)}${"░".repeat(empty)} ${p}%`; -} -/** - * 辅助:根据段位生成极客勋章 Markdown 卡片 - */ -export function generateBadgeCard(tier, totalLaunches, timeSavedHours) { - return `\`\`\` -┌────────────────────────────────────────────────────────┐ -│ ★ ZTOOLS GEEK EXCELLENCE BADGE · 极客卓越成就勋章 │ -├────────────────────────────────────────────────────────┤ -│ 称号: ${tier.toUpperCase().padEnd(20, " ")} 认证等级: ★★★★★ │ -│ 年累计唤醒: ${String(totalLaunches).padStart(6, " ")} 次 净节省时间: ${String(timeSavedHours).padStart(4, " ")} 小时 │ -│ 加密校验: Ed25519-Signed 隐私规范: 100% Local-First│ -└────────────────────────────────────────────────────────┘ -\`\`\``; -} -/** - * 个人极客使用年度统计计算引擎 - */ -export function calculateWrappedStats(yearOrStats = 2026) { - if (typeof yearOrStats === "object" && yearOrStats !== null) { - const rawTotal = Number(yearOrStats.totalLaunches); - const totalLaunches = !Number.isNaN(rawTotal) ? Math.max(0, Math.floor(rawTotal)) : 0; - const rawMinutes = Number(yearOrStats.timeSavedMinutes); - const timeSavedMinutes = !Number.isNaN(rawMinutes) ? Math.max(0, Math.floor(rawMinutes)) : Math.round(totalLaunches * 0.75); - const timeSavedHours = Math.round(timeSavedMinutes / 60); - const totalKeystrokesSaved = Number(yearOrStats.totalKeystrokesSaved) || totalLaunches * 38; - const manualHoursEstimate = Number(yearOrStats.manualHoursEstimate) || parseFloat(((totalLaunches * 1.25) / 60).toFixed(1)); - const ztoolsHoursSpent = Number(yearOrStats.ztoolsHoursSpent) || parseFloat(((totalLaunches * 0.1) / 60).toFixed(1)); - const netHoursSaved = Number(yearOrStats.netHoursSaved) || parseFloat((manualHoursEstimate - ztoolsHoursSpent).toFixed(1)); - const efficiencyRatio = yearOrStats.efficiencyRatio || `${(manualHoursEstimate / Math.max(0.1, ztoolsHoursSpent)).toFixed(1)}x`; - const rawTokens = Number(yearOrStats.tokensUsed ?? yearOrStats.aiTokenCount); - const tokensUsed = !Number.isNaN(rawTokens) ? Math.max(0, Math.floor(rawTokens)) : 0; - const rawExtensions = Array.isArray(yearOrStats.topExtensions) ? yearOrStats.topExtensions : []; - const topExtensions = rawExtensions.map((ext) => { - const count = Number(ext.count) || 0; - const pct = totalLaunches > 0 ? Math.round((count / totalLaunches) * 100) : 20; - return { - name: ext.name || "极客扩展", - id: ext.id || "ext", - count, - percentage: pct, - barChart: ext.barChart || renderAsciiBar(pct), - category: ext.category || "常用工具" - }; - }); - let rankLevel = "极客新星"; - let geekMasteryTier = "Master"; - if (totalLaunches >= 10000 && timeSavedHours >= 50) { - rankLevel = "王者极客"; - geekMasteryTier = "Grandmaster"; - } - else if (totalLaunches >= 3000) { - rankLevel = "黄金极客"; - geekMasteryTier = "Master"; - } - const res = { - year: Number(yearOrStats.year) || 2026, - totalLaunches, - totalKeystrokesSaved, - timeSavedMinutes, - timeSavedHours, - manualHoursEstimate, - ztoolsHoursSpent, - netHoursSaved, - efficiencyRatio, - tokensUsed, - aiTokenCount: tokensUsed, - topExtensions, - topShortcuts: Array.isArray(yearOrStats.topShortcuts) ? yearOrStats.topShortcuts : [], - rankLevel, - geekMasteryTier, - badgeTitle: `★ ${rankLevel} · ${geekMasteryTier} 勋章`, - badgeCardMarkdown: generateBadgeCard(geekMasteryTier, totalLaunches, timeSavedHours), - isLocalFirst: true, - generatedAt: Date.now() - }; - const target = { ...res }; - target.then = function (onFulfilled, onRejected) { - try { - const cleanCopy = { ...res }; - delete cleanCopy.then; - const result = typeof onFulfilled === "function" ? onFulfilled(cleanCopy) : cleanCopy; - return Promise.resolve(result); - } - catch (err) { - if (typeof onRejected === "function") { - return Promise.resolve(onRejected(err)); - } - return Promise.reject(err); - } - }; - return target; - } - // 读取本地持久化统计或使用动态基准 - const year = typeof yearOrStats === "number" ? yearOrStats : 2026; - const totalLaunches = 3840; - const timeSavedMinutes = Math.round(totalLaunches * 0.75); // 2880 分钟 (48 小时) - const timeSavedHours = Math.round(timeSavedMinutes / 60); - const totalKeystrokesSaved = totalLaunches * 38; // 145,920 次按键节省 - const manualHoursEstimate = parseFloat(((totalLaunches * 1.25) / 60).toFixed(1)); // 80 小时 - const ztoolsHoursSpent = parseFloat(((totalLaunches * 0.1) / 60).toFixed(1)); // 6.4 小时 - const netHoursSaved = parseFloat((manualHoursEstimate - ztoolsHoursSpent).toFixed(1)); // 73.6 小时 - const efficiencyRatio = `${(manualHoursEstimate / ztoolsHoursSpent).toFixed(1)}x`; - const topExtensions = [ - { - name: "剪贴板历史与流水粘贴", - id: "clipboard-history", - count: 1240, - percentage: 32, - barChart: renderAsciiBar(32), - category: "办公效率" - }, - { - name: "Everything 文件秒搜", - id: "everything-file-search", - count: 890, - percentage: 23, - barChart: renderAsciiBar(23), - category: "系统工具" - }, - { - name: "窗口极速调度 (Win32)", - id: "window-management", - count: 620, - percentage: 16, - barChart: renderAsciiBar(16), - category: "系统工具" - }, - { - name: "综合计算器与色彩速查", - id: "calculator", - count: 480, - percentage: 13, - barChart: renderAsciiBar(13), - category: "办公效率" - }, - { - name: "快捷短语与宏展开", - id: "snippets", - count: 350, - percentage: 9, - barChart: renderAsciiBar(9), - category: "办公效率" - } - ]; - const defaultStats = { - year, - totalLaunches, - totalKeystrokesSaved, - timeSavedMinutes, - timeSavedHours, - manualHoursEstimate, - ztoolsHoursSpent, - netHoursSaved, - efficiencyRatio, - topExtensions, - topShortcuts: [ - { key: "Alt+Space", name: "全局唤醒搜索", count: 3840 }, - { key: "Alt+V", name: "剪贴板历史", count: 1240 }, - { key: "Ctrl+K", name: "操作面板", count: 910 }, - { key: "Alt+C", name: "计算器", count: 480 } - ], - aiTokenCount: 158200, - tokensUsed: 158200, - rankLevel: "黄金极客", - geekMasteryTier: "Grandmaster", - badgeTitle: "★ 效率领航者 · Grandmaster 宗师勋章", - badgeCardMarkdown: generateBadgeCard("Grandmaster", totalLaunches, timeSavedHours), - isLocalFirst: true, - generatedAt: Date.now() - }; - const targetDefault = { ...defaultStats }; - targetDefault.then = function (onFulfilled, onRejected) { - return LocalStorage.getItem(`${WRAPPED_STORAGE_KEY}_${year}`) - .then((raw) => { - if (raw) { - try { - const parsed = JSON.parse(raw); - if (parsed && typeof parsed === "object") { - return sanitizeWrappedStats(parsed, year); - } - } - catch { /* ignore malformed cached stats */ } - } - const cleanCopy = { ...defaultStats }; - delete cleanCopy.then; - return cleanCopy; - }) - .then(onFulfilled, onRejected); - }; - return targetDefault; -} -/** - * 清洗并防御非法或被篡改的 Wrapped 统计数据 - */ -export function sanitizeWrappedStats(raw, defaultYear = 2026) { - const rawTotal = Number(raw.totalLaunches); - const total = !Number.isNaN(rawTotal) && rawTotal > 0 ? Math.floor(rawTotal) : 100; - const rawMinutes = Number(raw.timeSavedMinutes); - const timeSavedMinutes = !Number.isNaN(rawMinutes) && rawMinutes >= 0 ? Math.floor(rawMinutes) : Math.round(total * 0.75); - const timeSavedHours = Math.round(timeSavedMinutes / 60); - const rawTokens = Number(raw.aiTokenCount ?? raw.tokensUsed); - const aiTokenCount = !Number.isNaN(rawTokens) && rawTokens >= 0 ? Math.floor(rawTokens) : 0; - const totalKeystrokesSaved = Number(raw.totalKeystrokesSaved) || total * 38; - const manualHoursEstimate = Number(raw.manualHoursEstimate) || parseFloat(((total * 1.25) / 60).toFixed(1)); - const ztoolsHoursSpent = Number(raw.ztoolsHoursSpent) || parseFloat(((total * 0.1) / 60).toFixed(1)); - const netHoursSaved = Number(raw.netHoursSaved) || parseFloat((manualHoursEstimate - ztoolsHoursSpent).toFixed(1)); - const efficiencyRatio = raw.efficiencyRatio || `${(manualHoursEstimate / Math.max(0.1, ztoolsHoursSpent)).toFixed(1)}x`; - let rankLevel = "黄金极客"; - if (total >= 10000 && timeSavedHours >= 50) { - rankLevel = "王者极客"; - } - else if (total < 1000) { - rankLevel = "极客新星"; - } - const validTiers = ["Apprentice", "Specialist", "Master", "Grandmaster", "Legendary"]; - const geekMasteryTier = validTiers.includes(raw.geekMasteryTier) ? raw.geekMasteryTier : "Master"; - const rawExtensions = Array.isArray(raw.topExtensions) ? raw.topExtensions : []; - const topExtensions = rawExtensions.slice(0, 5).map((ext) => { - const count = Number(ext.count) || 0; - const pct = total > 0 ? Math.round((count / total) * 100) : 20; - return { - name: ext.name || "未知扩展", - id: ext.id || "ext", - count, - percentage: pct, - barChart: ext.barChart || renderAsciiBar(pct), - category: ext.category || "常用工具" - }; - }); - return { - year: Number(raw.year) > 2000 ? Math.floor(Number(raw.year)) : defaultYear, - totalLaunches: total, - totalKeystrokesSaved, - timeSavedMinutes, - timeSavedHours, - manualHoursEstimate, - ztoolsHoursSpent, - netHoursSaved, - efficiencyRatio, - tokensUsed: aiTokenCount, - topExtensions, - topShortcuts: Array.isArray(raw.topShortcuts) ? raw.topShortcuts : [], - aiTokenCount, - rankLevel, - geekMasteryTier, - badgeTitle: `★ ${rankLevel} · ${geekMasteryTier} 勋章`, - badgeCardMarkdown: generateBadgeCard(geekMasteryTier, total, timeSavedHours), - isLocalFirst: true, - generatedAt: Date.now() - }; -} -/** - * 特权与能力引导 (Trial Nudges / Feature Highlights) - */ -export const FEATURE_NUDGES = [ - { - id: "nudge_indexer", - featureKey: "mft_indexer", - title: "NTFS MFT 硬件级极速索引", - subtitle: "0.035ms 平均召回延迟,毫秒追踪全盘变动", - description: "自研 Rust 预编译侧车直接读取磁盘主文件表 (MFT) 与 USN 日志,突破普通文件枚举性能瓶颈。", - iconName: "magnifying-glass", - badge: "Native 硬件加速", - benefits: [ - "百万级文件索引内存占用 < 80MB", - "全量拼音模糊匹配与文件类型智能过滤", - "后台实时感知文件增删改,零等待" - ] - }, - { - id: "nudge_uiaccess", - featureKey: "uiaccess_penetration", - title: "UIAccess UIPI 特权穿透 Worker", - subtitle: "穿透 Windows 权限边界,跨应用极速取词", - description: "基于 Win32 UIAccess 特权架构,突破管理员窗口与浏览器沙盒隔离,实现划词翻译与上下文感知。", - iconName: "shield", - badge: "系统特权穿透", - benefits: [ - "跨权限选中文本读取与热键监听", - "活跃浏览器 Tab URL 与窗口句柄毫秒提取", - "沙盒进程隔离,主进程杜绝崩溃扩散" - ] - }, - { - id: "nudge_e2ee", - featureKey: "e2ee_cloud_sync", - title: "去中心化 E2EE 端到端加密", - subtitle: "Argon2id + AES-256-GCM 本地加密", - description: "拒绝隐私搜集与云端数据绑架,配置、短语与笔记全部经由主密码本地加密后同步至 WebDAV 或 Gist。", - iconName: "lock", - badge: "Local-First 隐私", - benefits: [ - "服务端仅可见高熵不可逆密文", - "WebDAV 412 ETag 乐观锁并发防覆盖", - "零中继服务器,完全掌控自己的数据" - ] - }, - { - id: "nudge_byok", - featureKey: "byok_local_ai", - title: "BYOK 自由接入与离线模型自动嗅探", - subtitle: "支持 DeepSeek R1 思考流与本地 Ollama", - description: "支持自带 API Key 与一键探测本地 Ollama (11434) / LM Studio (1234),完全零充值门槛。", - iconName: "brain", - badge: "极客自由", - benefits: [ - "原生支持 DeepSeek-R1 思考过程流式呈现", - "离线环境无网断网依然可用", - "MCP 协议反向暴露系统能力为 AI Tools" - ] - } -]; -/** - * 获取系统特权穿透与底层侧车健康度诊断数据 - */ -export async function getSystemPrivilegeDiagnostic() { - const nowStr = new Date().toISOString().replace("T", " ").substring(0, 19); - return { - uiaccess: { - status: "active", - uipiBypassVerified: true, - activeTabUrlCapture: true, - elevatedWindowTextCapture: true, - latencyMs: 0.8 - }, - mftIndexer: { - status: "healthy", - indexedFilesCount: 1285400, - indexedDrives: ["C:\\", "D:\\"], - avgRecallLatencyMs: 0.035, - usnJournalActive: true, - memoryMb: 62.4 - }, - sidecars: [ - { - name: "NTFS MFT 硬件极速索引侧车", - binary: "ztools-indexer.exe", - pid: 14208, - status: "healthy", - latencyMs: 0.035, - slaTargetMs: 10, - memoryMb: 62.4, - features: [ - "NTFS 裸盘 MFT 解析", - "USN Journal 毫秒变动实时追踪", - "百万文件多拼音索引" - ] - }, - { - name: "UIAccess UIPI 特权穿透 Worker", - binary: "ztools-uiaccess.exe", - pid: 16824, - status: "healthy", - latencyMs: 0.12, - slaTargetMs: 10, - memoryMb: 18.2, - features: [ - "UIPI 权限穿透", - "活跃浏览器 Tab URL 实时抓取", - "管理员窗口划词读取" - ] - } - ], - overallSlaMet: true, - diagnosedAt: nowStr - }; -} -/** - * 重启底层预编译侧车进程 - */ -export async function restartSidecar(sidecarBinary) { - if (isRealElectronHost()) { - const res = await callHostTransport("sidecar_restart", { binary: sidecarBinary }); - if (!res.ok || typeof res.data?.pid !== "number") { - return { - success: false, - newPid: 0, - message: res.error || `底层侧车 ${sidecarBinary} 重启失败` - }; - } - return { - success: true, - newPid: res.data.pid, - message: `底层侧车 ${sidecarBinary} 已重启成功 (新 PID: ${res.data.pid}),SLA 响应恢复至 <0.05ms` - }; - } - const newPid = 10000 + sidecarBinary.length; - return { - success: true, - newPid, - message: `底层侧车 ${sidecarBinary} 已重启成功 (新 PID: ${newPid}),SLA 响应恢复至 <0.05ms` - }; -} -/** - * 预设 Windows 快捷方式与系统运维自动化指令 (Windows Shortcuts) - */ -export const DEFAULT_WINDOWS_SHORTCUTS = [ - { - id: "ws_lnk_terminal", - name: "Windows Terminal 现代化终端", - description: "启动 Windows 官方现代化终端,集成 PowerShell、CMD 与 WSL", - targetPath: "wt.exe", - commandType: "lnk", - commandScript: "wt.exe", - category: "productivity", - iconName: "terminal" - }, - { - id: "ws_lnk_vscode", - name: "Visual Studio Code 代码编辑器", - description: "极速启动 VS Code 工作区与项目开发环境", - targetPath: "C:\\Program Files\\Microsoft VS Code\\Code.exe", - commandType: "lnk", - commandScript: "code .", - category: "dev", - iconName: "code" - }, - { - id: "ws_lnk_taskmgr", - name: "Windows 任务管理器 (Task Manager)", - description: "一键启动任务管理器,排查系统负载与进程句柄", - targetPath: "taskmgr.exe", - commandType: "lnk", - commandScript: "taskmgr.exe", - category: "system", - iconName: "desktop" - }, - { - id: "ws_lnk_regedit", - name: "注册表编辑器 (Registry Editor)", - description: "以管理员权限打开 Windows 系统注册表配置", - targetPath: "regedit.exe", - commandType: "lnk", - commandScript: "regedit.exe", - category: "system", - iconName: "gear", - requiresAdmin: true - }, - { - id: "ws_flush_dns", - name: "清理系统 DNS 缓存 (Flush DNS)", - description: "刷新本地 DNS 解析缓存,解决网络域名访问与网页证书刷新异常", - targetPath: "ipconfig.exe", - commandType: "powershell", - commandScript: "Clear-DnsClientCache; ipconfig /flushdns", - category: "network", - iconName: "globe" - }, - { - id: "ws_restart_explorer", - name: "一键重启 Windows 资源管理器", - description: "优雅重启 Explorer.exe 进程,快速解决任务栏卡死或桌面无响应", - targetPath: "explorer.exe", - commandType: "powershell", - commandScript: "Stop-Process -ProcessName explorer -Force; Start-Process explorer", - category: "system", - iconName: "arrow-clockwise", - destructive: true - }, - { - id: "ws_system_report", - name: "生成系统性能与电池报告", - description: "利用 Windows 原生诊断工具在桌面生成全面的硬件健康度报告", - targetPath: "powercfg.exe", - commandType: "cmd", - commandScript: "powercfg /batteryreport /output %USERPROFILE%\\Desktop\\battery-report.html", - category: "system", - iconName: "document" - }, - { - id: "ws_toggle_dark_theme", - name: "切换 Windows 系统深色/浅色模式", - description: "修改注册表键值即时切换 Windows 系统与应用的深浅外观", - targetPath: "powershell.exe", - commandType: "powershell", - commandScript: "$path = 'HKCU:\\Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize'; $val = (Get-ItemProperty -Path $path).AppsUseLightTheme; Set-ItemProperty -Path $path -Name AppsUseLightTheme -Value (1 - $val)", - category: "productivity", - iconName: "moon" - }, - { - id: "ws_wsl_terminal", - name: "极速启动 WSL2 Linux 极客终端", - description: "在当前工作区直接呼出 WSL 交互式终端会话", - targetPath: "wsl.exe", - commandType: "powershell", - commandScript: "wsl.exe ~", - category: "dev", - iconName: "terminal" - } -]; -/** - * 预设 macOS Apple Shortcuts 样本集 (离线/测试降级兜底) - */ -export const DEFAULT_APPLE_SHORTCUTS = [ - { - id: "as_focus_work", - name: "开启深度工作专注模式 (Deep Work Focus)", - folder: "效率办公", - description: "一键开启勿扰模式、启动 VS Code 与播放白噪音", - category: "productivity", - iconName: "star", - acceptsInput: false - }, - { - id: "as_summarize_clipboard", - name: "提炼剪贴板文本摘要 (Summarize Text)", - folder: "AI 助手", - description: "接收输入文本并通过快捷指令生成结构化要点摘要", - category: "productivity", - iconName: "document", - acceptsInput: true - }, - { - id: "as_clean_desktop", - name: "整理桌面截图与归档 (Clean Desktop)", - folder: "系统工具", - description: "将桌面零散截图按月份归档至 ~/Pictures/Screenshots", - category: "system", - iconName: "folder", - acceptsInput: false - }, - { - id: "as_network_diag", - name: "刷新 macOS DNS 与网络诊断 (Flush DNS)", - folder: "网络工具", - description: "执行 dscacheutil -flushcache 并检测网关延迟", - category: "network", - iconName: "globe", - acceptsInput: false - } -]; -/** - * 获取 macOS 原生「快捷指令 (/usr/bin/shortcuts list)」列表 - */ -export async function getAppleShortcuts(hostOverride) { - if (hostOverride || isRealElectronHost()) { - const res = await callHostTransport("shortcuts_list", {}, hostOverride); - if (!res.ok) - throw new Error(res.error || "无法读取系统快捷指令"); - if (res.data !== undefined) { - const rawList = Array.isArray(res.data) - ? res.data - : Array.isArray(res.data?.items) - ? res.data.items - : Array.isArray(res.data?.shortcuts) - ? res.data.shortcuts - : typeof res.data === "string" - ? res.data.split(/\r?\n/).map(s => s.trim()).filter(Boolean) - : []; - if (rawList.length === 0) - return []; - if (rawList.length > 0) { - return rawList.map((item, idx) => { - if (typeof item === "string") { - return { - id: `apple_sc_${idx}_${item}`, - name: item, - folder: "我的快捷指令", - description: `macOS 系统快捷指令: /usr/bin/shortcuts run "${item}"`, - category: "productivity", - iconName: "bolt", - acceptsInput: true - }; - } - const name = String(item?.name || item?.title || `Shortcut #${idx + 1}`); - return { - id: String(item?.id || `apple_sc_${idx}_${name}`), - name, - folder: item?.folder || "我的快捷指令", - description: item?.description || `macOS 系统快捷指令: /usr/bin/shortcuts run "${name}"`, - category: item?.category || "productivity", - iconName: item?.iconName || "bolt", - acceptsInput: item?.acceptsInput ?? true - }; - }); - } - } - throw new Error("快捷指令列表响应无效"); - } - return []; -} -/** - * 运行指定的 macOS 快捷指令 (/usr/bin/shortcuts run ) - */ -export async function executeAppleShortcut(name, input, hostOverride) { - const cleanName = (name || "").trim(); - if (!cleanName) { - return { success: false, message: "快捷指令名称不能为空" }; - } - if (hostOverride || isRealElectronHost()) { - const res = await callHostTransport("shortcuts_run", { name: cleanName, input: input !== undefined ? String(input) : undefined }, hostOverride); - if (res.ok) { - const out = typeof res.data === "string" ? res.data : res.data?.output || res.data?.stdout || ""; - return { - success: true, - output: out, - message: out - ? `快捷指令「${cleanName}」运行完成: ${String(out).slice(0, 80)}` - : `快捷指令「${cleanName}」已成功运行` - }; - } - return { - success: false, - message: res.error || `运行快捷指令「${cleanName}」失败` - }; - } - const inputSuffix = input ? ` (传入参数: "${input}")` : ""; - return { - success: true, - output: `Executed ${cleanName}${inputSuffix}`, - message: `已执行 macOS 快捷指令「${cleanName}」${inputSuffix}` - }; -} -/** - * 在 macOS「快捷指令.app」中查看并编辑指定快捷指令 (/usr/bin/shortcuts view ) - */ -export async function openShortcutInApp(name, hostOverride) { - const cleanName = (name || "").trim(); - if (!cleanName) { - return { success: false, message: "快捷指令名称不能为空" }; - } - if (hostOverride || isRealElectronHost()) { - const res = await callHostTransport("shortcuts_view", { name: cleanName }, hostOverride); - if (res.ok) { - return { - success: true, - message: `已在「快捷指令」应用中打开: ${cleanName}` - }; - } - return { - success: false, - message: res.error || `无法在「快捷指令」应用中打开: ${cleanName}` - }; - } - return { - success: true, - message: `已在「快捷指令」应用中打开编辑: ${cleanName}` - }; -} -/** - * 获取快捷指令列表(在真实宿主中若检测到 shortcuts_list 返回数据也自动融合) - */ -export async function getWindowsShortcuts(hostOverride) { - let baseList = [...DEFAULT_WINDOWS_SHORTCUTS]; - try { - const raw = await LocalStorage.getItem(SHORTCUTS_STORAGE_KEY); - if (raw) { - const parsed = JSON.parse(raw); - if (Array.isArray(parsed) && parsed.length > 0) { - baseList = parsed; - } - } - } - catch { - // 降级使用预设 - } - if (hostOverride || isRealElectronHost()) { - try { - const res = await callHostTransport("shortcuts_list", {}, hostOverride); - if (res.ok && res.data !== undefined) { - const rawList = Array.isArray(res.data) - ? res.data - : Array.isArray(res.data?.items) - ? res.data.items - : Array.isArray(res.data?.shortcuts) - ? res.data.shortcuts - : typeof res.data === "string" - ? res.data.split(/\r?\n/).map((s) => s.trim()).filter(Boolean) - : []; - if (rawList.length > 0) { - const appleMapped = rawList.map((item, idx) => { - const name = typeof item === "string" ? item : String(item?.name || item?.title || `Shortcut #${idx + 1}`); - return { - id: `mac_sc_${idx}_${name}`, - name, - description: `macOS 快捷指令 (/usr/bin/shortcuts): ${name}`, - targetPath: "/usr/bin/shortcuts", - commandType: "apple_shortcut", - commandScript: `shortcuts run "${name}"`, - category: "productivity", - iconName: "bolt", - folder: typeof item === "object" ? item?.folder : "Apple Shortcuts" - }; - }); - return [...appleMapped, ...baseList]; - } - } - } - catch { - // ignore - } - } - return baseList; -} -/** - * 执行 Windows / 跨端快捷指令 - */ -export async function executeWindowsShortcut(shortcut, options) { - if (!shortcut || (!shortcut.commandScript && !shortcut.targetPath)) { - return { success: false, message: "指令脚本或目标路径为空" }; - } - if (shortcut.commandType === "apple_shortcut") { - return executeAppleShortcut(shortcut.name, options?.input, options?.hostOverride); - } - const runAdmin = options?.runAsAdmin || shortcut.requiresAdmin; - // 1. 若宿主提供原生执行 IPC - if (typeof globalThis.window?.ztools?.execCommand === "function") { - try { - const res = await globalThis.window.ztools.execCommand({ - type: shortcut.commandType, - script: shortcut.commandScript, - targetPath: shortcut.targetPath, - runAsAdmin: runAdmin - }); - return { success: true, message: res?.output || `指令「${shortcut.name}」已${runAdmin ? "以管理员身份" : ""}成功执行` }; - } - catch (err) { - return { success: false, message: `执行异常: ${err.message}` }; - } - } - const adminPrefix = runAdmin ? "[以管理员身份] " : ""; - const targetDesc = shortcut.targetPath || shortcut.commandScript; - return { - success: true, - message: `${adminPrefix}已调度执行 ${shortcut.commandType.toUpperCase()} 指令: ${shortcut.name} (${targetDesc})` - }; -} -/** - * 在资源管理器中定位快捷方式目标路径 - */ -export async function revealShortcutInExplorer(shortcut) { - if (!shortcut || !shortcut.targetPath) { - return { success: false, message: "目标路径为空" }; - } - return { - success: true, - message: `已在资源管理器中定位: ${shortcut.targetPath}` - }; -} diff --git a/packages/declarative-ui/dist/examples/wrapped-nudges-shortcuts/index.d.ts b/packages/declarative-ui/dist/examples/wrapped-nudges-shortcuts/index.d.ts deleted file mode 100644 index 1df436ed..00000000 --- a/packages/declarative-ui/dist/examples/wrapped-nudges-shortcuts/index.d.ts +++ /dev/null @@ -1,25 +0,0 @@ -export * from "./types.js"; -export * from "./engine.js"; -/** - * Raycast Wrapped 年度极客报告主入口 - */ -export default function RaycastWrappedCommand(): JSX.Element; -/** - * Trial Nudges 核心特权与技术方案诊断中枢 - */ -export declare function TrialNudgesCommand(): JSX.Element; -/** - * Windows 快捷指令与自动化调度管理器 (Shortcuts) - */ -export declare function WindowsShortcutsCommand(): JSX.Element; -/** - * 带参数运行 macOS 快捷指令表单 () - */ -export declare function RunShortcutWithInputForm({ shortcutName, onCompleted }: { - shortcutName: string; - onCompleted?: (output?: string) => void; -}): JSX.Element; -/** - * P1-6: macOS 原生「快捷指令 (Apple Shortcuts)」直连主视图 - */ -export declare function AppleShortcutsCommand(): JSX.Element; diff --git a/packages/declarative-ui/dist/examples/wrapped-nudges-shortcuts/index.js b/packages/declarative-ui/dist/examples/wrapped-nudges-shortcuts/index.js deleted file mode 100644 index 6d85f4cb..00000000 --- a/packages/declarative-ui/dist/examples/wrapped-nudges-shortcuts/index.js +++ /dev/null @@ -1,400 +0,0 @@ -import React from "../../index.js"; -import { List, Detail, Form, ActionPanel, Action, Icon, Color, showToast, Toast, Clipboard, useNavigation } from "../../index.js"; -import { useState, useEffect, useMemo } from "../../runtime/hooks.js"; -import { calculateWrappedStats, FEATURE_NUDGES, getSystemPrivilegeDiagnostic, restartSidecar, getWindowsShortcuts, executeWindowsShortcut, revealShortcutInExplorer, getAppleShortcuts, executeAppleShortcut, openShortcutInApp } from "./engine.js"; -export * from "./types.js"; -export * from "./engine.js"; -/** - * Raycast Wrapped 年度极客报告主入口 - */ -export default function RaycastWrappedCommand() { - const [stats, setStats] = useState(() => calculateWrappedStats(2026)); - const [isLoading, setIsLoading] = useState(false); - useEffect(() => { - let isMounted = true; - (async () => { - try { - const res = await calculateWrappedStats(2026); - if (isMounted) { - setStats(res); - setIsLoading(false); - } - } - catch { - if (isMounted) - setIsLoading(false); - } - })(); - return () => { - isMounted = false; - }; - }, []); - const markdown = useMemo(() => { - if (!stats) - return "正在加载极客数据大盘与年度战报..."; - return `# 🏆 ZTools ${stats.year} 年度极客报告 - -> **极客段位评估**: \`${stats.badgeTitle}\` -> *基于本地 SQLite 行为日志分析,100% 本地运算,零隐私上报 (Local-First)* - ---- - -### ⏱️ 效率总耗时对比 (Time Investment vs Manual Baseline) -| 评估维度 | 统计数值 | 说明 | -| :--- | :--- | :--- | -| **传统鼠标与层级菜单预计耗时** | **${stats.manualHoursEstimate} 小时** | 估算每次手工寻址/点击平均耗时 1.25 分钟 | -| **ZTools 极客键盘流实际消耗时间** | **${stats.ztoolsHoursSpent} 小时** | 呼出后秒级命中,平均耗时仅 6 秒 | -| **累计净节省时间 (Net Saved)** | **${stats.netHoursSaved} 小时** | 折合约 **${stats.timeSavedMinutes}** 分钟 | -| **综合效率倍率提升** | **⚡ ${stats.efficiencyRatio}** | 键盘优先流带来的质变效率倍率 | -| **年累计呼出与唤醒** | **${stats.totalLaunches.toLocaleString()} 次** | 全天候即时响应 | -| **累计节省按键与点击次数** | **⌨️ ${stats.totalKeystrokesSaved.toLocaleString()} 次** | 显著缓解手指腕管疲劳 | -| **AI 交互 Token 规模** | **${(stats.tokensUsed || stats.aiTokenCount).toLocaleString()} Tokens** | BYOK 自由接入无绑架 | - ---- - -### 📊 最常调用的前 5 款插件统计图表 (Top 5 Extensions Chart) -${stats.topExtensions - .map((ext, i) => `${i + 1}. **${ext.name}** (\`${ext.id}\`): 唤醒 **${ext.count}** 次 (${ext.category})\n \`${ext.barChart}\``) - .join("\n\n")} - ---- - -### ⌨️ 高频快捷键习惯 (Top Shortcuts) -${stats.topShortcuts - .map((sc, i) => `- **${sc.name}** (\`${sc.key}\`): 触发 **${sc.count}** 次`) - .join("\n")} - ---- - -### 🎖️ 极客卓越成就勋章 (Geek Excellence Badge) -${stats.badgeCardMarkdown} - ---- -*愿每一位极客在键盘与纯粹中探索无限可能,感谢与 ZTools 共同前行!*`; - }, [stats]); - return (React.createElement(Detail, { isLoading: isLoading, markdown: markdown, metadata: stats ? (React.createElement(Detail.Metadata, null, - React.createElement(Detail.Metadata.Label, { title: "\u7EDF\u8BA1\u5E74\u4EFD", text: `${stats.year} 年度`, icon: Icon.Calendar }), - React.createElement(Detail.Metadata.Label, { title: "\u603B\u5524\u9192", text: `${stats.totalLaunches} 次`, icon: Icon.ArrowsExpand }), - React.createElement(Detail.Metadata.Label, { title: "\u51C0\u8282\u7701\u65F6\u95F4", text: `${stats.netHoursSaved} 小时`, icon: Icon.Clock }), - React.createElement(Detail.Metadata.Label, { title: "\u8282\u7701\u6309\u952E", text: `${stats.totalKeystrokesSaved} 次`, icon: Icon.Terminal }), - React.createElement(Detail.Metadata.Label, { title: "\u6548\u7387\u500D\u7387", text: stats.efficiencyRatio, icon: Icon.Star }), - React.createElement(Detail.Metadata.Separator, null), - React.createElement(Detail.Metadata.TagList, { title: "\u6781\u5BA2\u8BC4\u7EA7" }, - React.createElement(Detail.Metadata.TagList.Item, { text: stats.geekMasteryTier, color: Color.Green }), - React.createElement(Detail.Metadata.TagList.Item, { text: "100% Local-First", color: Color.Blue })))) : undefined, actions: React.createElement(ActionPanel, null, - React.createElement(Action, { title: "\u590D\u5236\u5E74\u5EA6\u6781\u5BA2\u6218\u62A5", icon: Icon.Clipboard, onAction: async () => { - await Clipboard.copy(markdown); - await showToast(Toast.Style.Success, "年度极客战报已复制到剪贴板"); - } }), - stats?.badgeCardMarkdown && (React.createElement(Action, { title: "\u590D\u5236\u6781\u5BA2\u52CB\u7AE0\u5361\u7247", icon: Icon.Star, onAction: async () => { - await Clipboard.copy(stats.badgeCardMarkdown); - await showToast(Toast.Style.Success, "极客成就勋章卡片已复制"); - } })), - React.createElement(Action, { title: "\u91CD\u65B0\u8BA1\u7B97\u5E74\u5EA6\u7EDF\u8BA1", icon: Icon.Repeat, onAction: async () => { - const res = await calculateWrappedStats(2026); - setStats(res); - await showToast(Toast.Style.Success, "年度统计数据已重新聚合刷新"); - } })) })); -} -/** - * Trial Nudges 核心特权与技术方案诊断中枢 - */ -export function TrialNudgesCommand() { - const [nudges] = useState(FEATURE_NUDGES); - const [diagnostic, setDiagnostic] = useState(null); - const [isLoading, setIsLoading] = useState(true); - useEffect(() => { - let isMounted = true; - (async () => { - try { - const diag = await getSystemPrivilegeDiagnostic(); - if (isMounted) { - setDiagnostic(diag); - setIsLoading(false); - } - } - catch { - if (isMounted) - setIsLoading(false); - } - })(); - return () => { - isMounted = false; - }; - }, []); - const handleRestartSidecar = async (binary) => { - await showToast(Toast.Style.Animated, `正在重启底层侧车 ${binary}...`); - const res = await restartSidecar(binary); - await showToast(Toast.Style.Success, res.message); - }; - const handleRunSelfTest = async () => { - await showToast(Toast.Style.Animated, "正在运行全系统特权穿透自检..."); - const diag = await getSystemPrivilegeDiagnostic(); - setDiagnostic(diag); - await showToast(Toast.Style.Success, "特权自检完成", "UIAccess、MFT 与 Sidecars 全部正常运行"); - }; - return (React.createElement(List, { isLoading: isLoading, isShowingDetail: true, searchBarPlaceholder: "\u6D4F\u89C8 ZTools \u6838\u5FC3\u7279\u6743\u3001Rust \u4FA7\u8F66\u76D1\u63A7\u4E0E\u6280\u672F\u65B9\u6848\u8BCA\u65AD..." }, - diagnostic && (React.createElement(List.Section, { title: `底层预编译侧车与 SLA 延迟监控 (${diagnostic.sidecars.length})` }, diagnostic.sidecars.map((sc) => (React.createElement(List.Item, { key: sc.binary, id: sc.binary, title: sc.name, subtitle: `二进制: ${sc.binary} • 响应延迟: ${sc.latencyMs}ms (SLA < ${sc.slaTargetMs}ms)`, icon: sc.status === "healthy" ? Icon.Checkmark : Icon.ExclamationMark, accessories: [ - { text: `PID: ${sc.pid}` }, - { text: `${sc.memoryMb} MB` }, - { text: sc.status.toUpperCase() } - ], detail: React.createElement(List.Item.Detail, { markdown: `### ⚙️ ${sc.name} (\`${sc.binary}\`)\n\n- **进程标识 (PID)**: \`${sc.pid}\`\n- **实时响应延迟**: \`${sc.latencyMs}ms\` (严格符合 SLA < 10ms 纪律)\n- **常驻内存占用**: \`${sc.memoryMb} MB\` (严苛资源纪律,待机释放显存)\n- **运行健康度**: 🟢 \`${sc.status.toUpperCase()}\`\n\n#### 核心技术特性\n${sc.features.map((f) => `- ${f}`).join("\n")}\n\n> **侧车解耦架构**: 采用独立 Rust 预编译侧车承载密集计算,通过标准管道与主进程通信,坚决避免把多语言硬性缝合,杜绝崩溃连锁反应。`, metadata: React.createElement(List.Item.Detail.Metadata, null, - React.createElement(List.Item.Detail.Metadata.Label, { title: "\u4E8C\u8FDB\u5236\u540D\u79F0", text: sc.binary, icon: Icon.Terminal }), - React.createElement(List.Item.Detail.Metadata.Label, { title: "\u8FDB\u7A0B PID", text: String(sc.pid), icon: Icon.Key }), - React.createElement(List.Item.Detail.Metadata.Label, { title: "SLA \u5EF6\u8FDF", text: `${sc.latencyMs}ms`, icon: Icon.Clock }), - React.createElement(List.Item.Detail.Metadata.Label, { title: "\u5185\u5B58\u5360\u7528", text: `${sc.memoryMb} MB`, icon: Icon.HardDrive }), - React.createElement(List.Item.Detail.Metadata.Separator, null), - React.createElement(List.Item.Detail.Metadata.TagList, { title: "\u8FD0\u884C\u72B6\u6001" }, - React.createElement(List.Item.Detail.Metadata.TagList.Item, { text: "SLA \u8FBE\u6807", color: Color.Green }), - React.createElement(List.Item.Detail.Metadata.TagList.Item, { text: "Rust \u9884\u7F16\u8BD1", color: Color.Blue }))) }), actions: React.createElement(ActionPanel, null, - React.createElement(Action, { title: `重启底层侧车 (${sc.binary})`, icon: Icon.Repeat, onAction: () => handleRestartSidecar(sc.binary) }), - React.createElement(Action, { title: "\u91CD\u65B0\u8FD0\u884C\u5168\u7CFB\u7EDF\u7279\u6743\u81EA\u68C0", icon: Icon.Play, onAction: handleRunSelfTest })) }))))), - React.createElement(List.Section, { title: `核心特权穿透与技术方案 (${nudges.length})` }, nudges.map((item) => (React.createElement(List.Item, { key: item.id, id: item.id, title: item.title, subtitle: item.subtitle, icon: Icon.Star, accessories: [{ text: item.badge }], detail: React.createElement(List.Item.Detail, { markdown: `### 🌟 ${item.title}\n\n${item.description}\n\n#### 🎯 核心技术收益\n${item.benefits.map((b) => `- ${b}`).join("\n")}\n\n> **ZTools 商业哲学**:核心能力永久免费、零广告。充分尊重极客,支持自带 Key 与离线模型,杜绝强制绑定。` }), actions: React.createElement(ActionPanel, null, - React.createElement(Action, { title: "\u8FD0\u884C\u7279\u6743\u6DF1\u5EA6\u8BCA\u65AD", icon: Icon.QuestionMark, onAction: async () => { - await showToast(Toast.Style.Success, `特权特性已诊断就绪: ${item.title}`); - } }), - React.createElement(Action, { title: "\u91CD\u65B0\u8FD0\u884C\u7279\u6743\u81EA\u68C0", icon: Icon.Repeat, onAction: handleRunSelfTest })) })))))); -} -/** - * Windows 快捷指令与自动化调度管理器 (Shortcuts) - */ -export function WindowsShortcutsCommand() { - const [shortcuts, setShortcuts] = useState([]); - const [isLoading, setIsLoading] = useState(true); - const [filterCategory, setFilterCategory] = useState("all"); - const [selectedId, setSelectedId] = useState(null); - const { push } = useNavigation(); - const reloadWindowsShortcuts = async () => { - setIsLoading(true); - try { - const loaded = await getWindowsShortcuts(); - setShortcuts(loaded); - } - finally { - setIsLoading(false); - } - }; - useEffect(() => { - let isMounted = true; - (async () => { - try { - const loaded = await getWindowsShortcuts(); - if (isMounted) { - setShortcuts(loaded); - setIsLoading(false); - } - } - catch { - if (isMounted) - setIsLoading(false); - } - })(); - return () => { - isMounted = false; - }; - }, []); - const handleRun = async (sc, runAsAdmin = false) => { - await showToast(Toast.Style.Animated, `正在${runAsAdmin ? "以管理员身份" : ""}调度执行: ${sc.name}...`); - const res = await executeWindowsShortcut(sc, { runAsAdmin }); - if (res.success) { - await showToast(Toast.Style.Success, res.message); - } - else { - await showToast(Toast.Style.Failure, res.message); - } - }; - const handleReveal = async (sc) => { - const res = await revealShortcutInExplorer(sc); - await showToast(Toast.Style.Success, res.message); - }; - const filteredShortcuts = useMemo(() => { - if (filterCategory === "all") - return shortcuts; - return shortcuts.filter((s) => s.category === filterCategory); - }, [shortcuts, filterCategory]); - const activeWinShortcut = useMemo(() => { - return filteredShortcuts.find((s) => s.id === selectedId) || filteredShortcuts[0]; - }, [filteredShortcuts, selectedId]); - return (React.createElement(List, { isLoading: isLoading, isShowingDetail: true, searchBarPlaceholder: "\u641C\u7D22 Windows \u5FEB\u6377\u65B9\u5F0F (.lnk) \u4E0E\u81EA\u52A8\u5316\u8FD0\u7EF4\u6307\u4EE4...", onSelectionChange: setSelectedId, filterBar: { - summaryText: `已加载 ${filteredShortcuts.length} 个自动化快捷指令`, - actions: [ - { - id: "refresh-list", - label: "刷新列表", - title: "刷新列表", - style: "secondary", - onAction: () => { - void reloadWindowsShortcuts(); - } - } - ] - }, searchBarAccessory: React.createElement(List.Dropdown, { tooltip: "\u7B5B\u9009\u5206\u7C7B", value: filterCategory, onChange: setFilterCategory }, - React.createElement(List.Dropdown.Item, { title: "\u5168\u90E8\u5FEB\u6377\u6307\u4EE4 (All)", value: "all", icon: Icon.List }), - React.createElement(List.Dropdown.Item, { title: "\u5E38\u7528\u5E94\u7528\u7A0B\u5E8F (.lnk)", value: "apps", icon: Icon.AppWindow }), - React.createElement(List.Dropdown.Item, { title: "\u5F00\u53D1\u8C03\u8BD5\u6307\u4EE4 (Dev)", value: "dev", icon: Icon.Code }), - React.createElement(List.Dropdown.Item, { title: "\u7CFB\u7EDF\u8FD0\u7EF4\u6025\u6551 (System)", value: "system", icon: Icon.Gear }), - React.createElement(List.Dropdown.Item, { title: "\u7F51\u7EDC\u8BCA\u65AD\u5DE5\u5177 (Network)", value: "network", icon: Icon.Globe }), - React.createElement(List.Dropdown.Item, { title: "\u529E\u516C\u6548\u80FD\u52A0\u901F (Productivity)", value: "productivity", icon: Icon.Star })) }, - React.createElement(List.Section, { title: `Windows 自动化快捷指令 (${filteredShortcuts.length})` }, filteredShortcuts.map((sc) => (React.createElement(List.Item, { key: sc.id, id: sc.id, title: sc.name, subtitle: sc.description, icon: sc.destructive - ? Icon.ExclamationMark - : sc.requiresAdmin - ? Icon.Shield - : sc.commandType === "lnk" - ? Icon.AppWindow - : Icon.Terminal, accessories: [ - ...(sc.requiresAdmin ? [{ text: "管理员权限", icon: Icon.Shield }] : []), - { text: sc.commandType.toUpperCase() }, - { text: sc.category.toUpperCase() } - ], detail: React.createElement(List.Item.Detail, { markdown: `### ⚡ ${sc.name}\n\n${sc.description}\n\n- **目标路径**: \`${sc.targetPath}\`\n- **执行引擎**: \`${sc.commandType.toUpperCase()}\`\n- **分类**: \`${sc.category.toUpperCase()}\`\n- **权限等级**: ${sc.requiresAdmin ? "🛡️ 需管理员特权 (UAC / RunAs)" : "🟢 普通用户权限"}\n\n\`\`\`${sc.commandType}\n${sc.commandScript || sc.targetPath}\n\`\`\`${sc.destructive ? "\n\n⚠️ **注意**: 该操作可能导致未保存的桌面状态或系统进程重启。" : ""}`, metadata: React.createElement(List.Item.Detail.Metadata, null, - React.createElement(List.Item.Detail.Metadata.Label, { title: "\u6307\u4EE4\u540D\u79F0", text: sc.name, icon: Icon.Terminal }), - React.createElement(List.Item.Detail.Metadata.Label, { title: "\u7C7B\u578B", text: sc.commandType.toUpperCase(), icon: Icon.Key }), - React.createElement(List.Item.Detail.Metadata.Label, { title: "\u8DEF\u5F84", text: sc.targetPath, icon: Icon.Folder }), - React.createElement(List.Item.Detail.Metadata.Separator, null), - React.createElement(List.Item.Detail.Metadata.TagList, { title: "\u5B89\u5168\u7279\u6743" }, - React.createElement(List.Item.Detail.Metadata.TagList.Item, { text: sc.requiresAdmin ? "管理员权限" : "标准用户", color: sc.requiresAdmin ? Color.Orange : Color.Green }))) }), actions: React.createElement(ActionPanel, null, - React.createElement(Action, { title: "\u7ACB\u5373\u8FD0\u884C\u6B64\u6307\u4EE4", icon: Icon.Play, onAction: () => handleRun(sc, false) }), - React.createElement(Action, { title: "\u4EE5\u7BA1\u7406\u5458\u8EAB\u4EFD\u8FD0\u884C", icon: Icon.Shield, shortcut: { modifiers: ["ctrl"], key: "return" }, onAction: () => handleRun(sc, true) }), - React.createElement(Action, { title: "\u590D\u5236\u76EE\u6807\u8DEF\u5F84", icon: Icon.Clipboard, onAction: async () => { - await Clipboard.copy(sc.targetPath); - await showToast(Toast.Style.Success, `路径已复制: ${sc.targetPath}`); - } }), - React.createElement(Action, { title: "\u5728\u8D44\u6E90\u7BA1\u7406\u5668\u4E2D\u5B9A\u4F4D", icon: Icon.Folder, onAction: () => handleReveal(sc) }), - React.createElement(Action, { title: "\u590D\u5236\u5B8C\u6574\u811A\u672C\u4EE3\u7801", icon: Icon.Code, onAction: async () => { - await Clipboard.copy(sc.commandScript || sc.targetPath); - await showToast(Toast.Style.Success, "脚本内容已复制到剪贴板"); - } })) })))))); -} -/** - * 带参数运行 macOS 快捷指令表单 () - */ -export function RunShortcutWithInputForm({ shortcutName, onCompleted }) { - const { pop } = useNavigation(); - const [inputValue, setInputValue] = useState(""); - return (React.createElement(Form, { navigationTitle: `带参数运行: ${shortcutName}`, actions: React.createElement(ActionPanel, null, - React.createElement(Action.SubmitForm, { title: "\u8FD0\u884C\u5FEB\u6377\u6307\u4EE4 (Run Shortcut)", icon: Icon.Play, onSubmit: async (values) => { - const finalInput = values?.input !== undefined ? String(values.input) : inputValue; - await showToast(Toast.Style.Animated, `正在运行快捷指令: ${shortcutName}...`); - const res = await executeAppleShortcut(shortcutName, finalInput); - if (res.success) { - if (res.output) { - await Clipboard.copy(res.output); - } - await showToast(Toast.Style.Success, res.message); - onCompleted?.(res.output); - pop(); - } - else { - await showToast(Toast.Style.Failure, res.message); - } - } })) }, - React.createElement(Form.TextArea, { id: "input", title: "\u8F93\u5165\u6587\u672C\u53C2\u6570 (Shortcut Input)", placeholder: "\u8F93\u5165\u4F20\u9012\u7ED9 /usr/bin/shortcuts run \u7684\u6587\u672C\u3001URL \u6216 JSON \u5185\u5BB9...", value: inputValue, onChange: setInputValue }))); -} -/** - * P1-6: macOS 原生「快捷指令 (Apple Shortcuts)」直连主视图 - */ -export function AppleShortcutsCommand() { - const [shortcuts, setShortcuts] = useState([]); - const [searchText, setSearchText] = useState(""); - const [isLoading, setIsLoading] = useState(true); - const [lastOutputMap, setLastOutputMap] = useState({}); - const [selectedId, setSelectedId] = useState(null); - const { push } = useNavigation(); - const reloadAppleShortcuts = async () => { - setIsLoading(true); - try { - const list = await getAppleShortcuts(); - setShortcuts(list); - } - catch (error) { - await showToast(Toast.Style.Failure, "读取快捷指令失败", error instanceof Error ? error.message : String(error)); - } - finally { - setIsLoading(false); - } - }; - useEffect(() => { - let isMounted = true; - (async () => { - try { - const list = await getAppleShortcuts(); - if (isMounted) { - setShortcuts(list); - setIsLoading(false); - } - } - catch (error) { - if (isMounted) { - setIsLoading(false); - await showToast(Toast.Style.Failure, "读取快捷指令失败", error instanceof Error ? error.message : String(error)); - } - } - })(); - return () => { - isMounted = false; - }; - }, []); - const filtered = useMemo(() => { - const q = searchText.trim().toLowerCase(); - if (!q) - return shortcuts; - return shortcuts.filter((item) => item.name.toLowerCase().includes(q) || - item.description.toLowerCase().includes(q) || - (item.folder && item.folder.toLowerCase().includes(q))); - }, [shortcuts, searchText]); - const activeAppleShortcut = useMemo(() => { - return filtered.find((item) => item.id === selectedId) || filtered[0]; - }, [filtered, selectedId]); - const handleRun = async (item) => { - await showToast(Toast.Style.Animated, `正在运行快捷指令: ${item.name}...`); - const res = await executeAppleShortcut(item.name); - if (res.success) { - if (res.output) { - setLastOutputMap((prev) => ({ ...prev, [item.id]: res.output })); - await Clipboard.copy(res.output); - } - await showToast(Toast.Style.Success, res.message); - } - else { - await showToast(Toast.Style.Failure, res.message); - } - }; - const handleOpenInApp = async (item) => { - const res = await openShortcutInApp(item.name); - await showToast(res.success ? Toast.Style.Success : Toast.Style.Failure, res.message); - }; - return (React.createElement(List, { isLoading: isLoading, isShowingDetail: true, searchBarPlaceholder: "\u641C\u7D22 macOS \u5FEB\u6377\u6307\u4EE4 (Search Apple Shortcuts)...", onSearchTextChange: setSearchText, onSelectionChange: setSelectedId, filterBar: { - summaryText: `已加载 ${filtered.length} 个自动化快捷指令`, - actions: [ - { - id: "refresh-list", - label: "刷新列表", - title: "刷新列表", - style: "secondary", - onAction: () => { - void reloadAppleShortcuts(); - } - } - ] - } }, - React.createElement(List.Section, { title: `macOS 快捷指令 (${filtered.length})` }, filtered.map((item) => { - const lastOut = lastOutputMap[item.id]; - return (React.createElement(List.Item, { key: item.id, id: item.id, title: item.name, subtitle: item.folder || "Shortcuts", icon: Icon.Bolt, accessories: [ - ...(item.folder ? [{ text: item.folder }] : []), - { text: "Apple Shortcuts" } - ], detail: React.createElement(List.Item.Detail, { markdown: `# ⚡ ${item.name}\n\n${item.description}\n\n- **所属文件夹**: \`${item.folder || "默认"}\`\n- **底层 CLI**: \`/usr/bin/shortcuts run "${item.name}"\`\n${lastOut ? `\n### 最近执行输出\n\`\`\`text\n${lastOut}\n\`\`\`\n` : ""}`, metadata: React.createElement(List.Item.Detail.Metadata, null, - React.createElement(List.Item.Detail.Metadata.Label, { title: "\u5FEB\u6377\u6307\u4EE4\u540D\u79F0", text: item.name, icon: Icon.Bolt }), - React.createElement(List.Item.Detail.Metadata.Label, { title: "\u6587\u4EF6\u5939", text: item.folder || "默认", icon: Icon.Folder }), - React.createElement(List.Item.Detail.Metadata.Label, { title: "\u6267\u884C\u5F15\u64CE", text: "/usr/bin/shortcuts", icon: Icon.Terminal }), - React.createElement(List.Item.Detail.Metadata.Separator, null), - React.createElement(List.Item.Detail.Metadata.TagList, { title: "\u652F\u6301\u80FD\u529B" }, - React.createElement(List.Item.Detail.Metadata.TagList.Item, { text: "macOS Native CLI", color: Color.Green }), - item.acceptsInput && (React.createElement(List.Item.Detail.Metadata.TagList.Item, { text: "\u652F\u6301\u53C2\u6570\u8F93\u5165", color: Color.Blue })))) }), actions: React.createElement(ActionPanel, { title: item.name }, - React.createElement(Action, { title: "\u8FD0\u884C\u5FEB\u6377\u6307\u4EE4 (Run Shortcut)", icon: Icon.Play, onAction: () => handleRun(item) }), - React.createElement(Action.Push, { title: "\u5E26\u53C2\u6570\u8FD0\u884C\u5FEB\u6377\u6307\u4EE4 (Run with Input...)", icon: Icon.Terminal, shortcut: { modifiers: ["cmd"], key: "return" }, target: React.createElement(RunShortcutWithInputForm, { shortcutName: item.name, onCompleted: (out) => { - if (out) - setLastOutputMap((prev) => ({ ...prev, [item.id]: out })); - } }) }), - React.createElement(Action, { title: "\u5728\u300C\u5FEB\u6377\u6307\u4EE4\u300D\u5E94\u7528\u4E2D\u6253\u5F00\u7F16\u8F91 (Open in Shortcuts App)", icon: Icon.AppWindow, shortcut: { modifiers: ["cmd"], key: "o" }, onAction: () => handleOpenInApp(item) }), - React.createElement(Action.CopyToClipboard, { title: "\u590D\u5236\u5FEB\u6377\u6307\u4EE4\u540D\u79F0 (Copy Name)", content: item.name, icon: Icon.CopyClipboard, shortcut: { modifiers: ["cmd"], key: "c" } })) })); - })))); -} diff --git a/packages/declarative-ui/dist/examples/wrapped-nudges-shortcuts/types.d.ts b/packages/declarative-ui/dist/examples/wrapped-nudges-shortcuts/types.d.ts deleted file mode 100644 index 2e20495b..00000000 --- a/packages/declarative-ui/dist/examples/wrapped-nudges-shortcuts/types.d.ts +++ /dev/null @@ -1,99 +0,0 @@ -/** - * Raycast Wrapped, Trial Nudges & Shortcuts 类型契约 - * 对标 Raycast 年度战报、技术特权引导与系统快捷指令管理器 - */ -export interface WrappedUsageStats { - year: number; - totalLaunches: number; - totalKeystrokesSaved: number; - timeSavedMinutes: number; - timeSavedHours: number; - manualHoursEstimate: number; - ztoolsHoursSpent: number; - netHoursSaved: number; - efficiencyRatio: string; - topExtensions: Array<{ - name: string; - id: string; - count: number; - percentage: number; - barChart: string; - category?: string; - }>; - topShortcuts: Array<{ - key: string; - name: string; - count: number; - }>; - aiTokenCount: number; - tokensUsed?: number; - geekMasteryTier: "Apprentice" | "Specialist" | "Master" | "Grandmaster" | "Legendary"; - rankLevel?: string; - badgeTitle: string; - badgeCardMarkdown: string; - isLocalFirst?: boolean; - generatedAt?: number; -} -export interface FeatureNudgeItem { - id: string; - featureKey: string; - title: string; - subtitle: string; - description: string; - iconName: string; - badge: string; - benefits: string[]; -} -export interface NativeSidecarHealth { - name: string; - binary: string; - pid: number; - status: "running" | "healthy" | "degraded" | "stopped"; - latencyMs: number; - slaTargetMs: number; - memoryMb: number; - features: string[]; -} -export interface SystemPrivilegeDiagnostic { - uiaccess: { - status: "active" | "inactive" | "restricted"; - uipiBypassVerified: boolean; - activeTabUrlCapture: boolean; - elevatedWindowTextCapture: boolean; - latencyMs: number; - }; - mftIndexer: { - status: "healthy" | "indexing" | "unsupported"; - indexedFilesCount: number; - indexedDrives: string[]; - avgRecallLatencyMs: number; - usnJournalActive: boolean; - memoryMb: number; - }; - sidecars: NativeSidecarHealth[]; - overallSlaMet: boolean; - diagnosedAt: string; -} -export interface WindowsShortcutItem { - id: string; - name: string; - description: string; - targetPath: string; - arguments?: string; - commandType: "lnk" | "powershell" | "cmd" | "task_scheduler" | "uri" | "apple_shortcut"; - commandScript: string; - category: "apps" | "system" | "network" | "dev" | "productivity"; - iconName: string; - requiresAdmin?: boolean; - destructive?: boolean; - folder?: string; -} -export interface AppleShortcutItem { - id: string; - name: string; - folder?: string; - description: string; - category: "apps" | "system" | "network" | "dev" | "productivity"; - iconName: string; - acceptsInput?: boolean; -} diff --git a/packages/declarative-ui/dist/examples/wrapped-nudges-shortcuts/types.js b/packages/declarative-ui/dist/examples/wrapped-nudges-shortcuts/types.js deleted file mode 100644 index 21ffaf6f..00000000 --- a/packages/declarative-ui/dist/examples/wrapped-nudges-shortcuts/types.js +++ /dev/null @@ -1,5 +0,0 @@ -/** - * Raycast Wrapped, Trial Nudges & Shortcuts 类型契约 - * 对标 Raycast 年度战报、技术特权引导与系统快捷指令管理器 - */ -export {}; diff --git a/packages/ztools-plugins-spec/official-ids.json b/packages/ztools-plugins-spec/official-ids.json index 3f2f249c..217c1f13 100644 --- a/packages/ztools-plugins-spec/official-ids.json +++ b/packages/ztools-plugins-spec/official-ids.json @@ -11,13 +11,11 @@ "batch-rename", "batch-text-convert", "batch-video", - "boost", "browser-bookmarks", "browser-history", "caffeine", "calculator", "calendar", - "chinese-number-converter", "chmod-cidr-calc", "clean-keyboard", "cleaner", @@ -53,11 +51,9 @@ "invoice-assistant", "json-format", "jwt-url-codec", - "kill-process", "lan-scanner", "lan-share", "linux-http-dict", - "md-to-office", "media-metadata", "memo", "mock-data", @@ -83,7 +79,6 @@ "screen-color-picker", "screenshot", "shredder", - "shutdown-timer", "snippets", "software-manager", "speedtest", @@ -101,7 +96,6 @@ "timestamp", "todo", "translator", - "unit-converter", "uuid-generator", "video-downloader", "vscode-projects", diff --git a/packages/ztools-plugins-spec/plugin.schema.json b/packages/ztools-plugins-spec/plugin.schema.json index ded45c19..793201d3 100644 --- a/packages/ztools-plugins-spec/plugin.schema.json +++ b/packages/ztools-plugins-spec/plugin.schema.json @@ -81,6 +81,8 @@ "crypto", "audio", "video", + "media.read", + "media.process", "process" ] }, @@ -181,6 +183,29 @@ "pattern": "^\\d+(\\.\\d+){1,3}$", "description": "运行插件所需的最低客户端版本(如 1.1.8.3);发布时还会按插件用到的宿主接口自动提高" }, + "requiredCapabilities": { + "type": "array", + "uniqueItems": true, + "items": { + "type": "string", + "enum": [ + "media.probe", + "media.transcode", + "media.capture", + "download.stream", + "download.transfer", + "archive.list", + "archive.extract", + "archive.create", + "document.pdf.inspect", + "document.pdf.transform", + "document.pdf.render", + "image.inspect", + "image.process" + ] + }, + "description": "插件依赖的宿主平台无关薄原语能力列表(由宿主按平台异构驱动或按需拉取 CommonLibs 签名工具池承接)" + }, "requireAdmin": { "type": "boolean", "default": false, diff --git a/packages/ztools-plugins-spec/src/host-requirements.js b/packages/ztools-plugins-spec/src/host-requirements.js index f14a0cea..24a08f9e 100644 --- a/packages/ztools-plugins-spec/src/host-requirements.js +++ b/packages/ztools-plugins-spec/src/host-requirements.js @@ -35,7 +35,17 @@ export const HOST_API_REQUIREMENTS = Object.freeze([ { api: 'ssh_proxy', minAppVersion: '1.1.8.5', pattern: /\bssh_proxy\b/ }, { api: 'startup_manager', minAppVersion: '1.1.8.5', pattern: /\bstartup_manager\b/ }, { api: 'tls_inspect', minAppVersion: '1.1.8.5', pattern: /\btls_inspect\b/ }, - { api: 'image_ocr', minAppVersion: '1.1.8.9', pattern: /\bimage_ocr\b/ } + { api: 'image_ocr', minAppVersion: '1.1.8.9', pattern: /\bimage_ocr\b/ }, + { api: 'tool_runtime', minAppVersion: '1.3.0.0', pattern: /\btool_(?:runtime_(?:capabilities|ensure)|task_cancel)\b/ }, + { api: 'tool_media', minAppVersion: '1.3.0.0', pattern: /\btool_media_(?:probe|transcode_run)\b/ }, + { api: 'tool_download', minAppVersion: '1.3.0.0', pattern: /\btool_download_(?:stream_(?:probe|run)|transfer_(?:add|pause|resume|cancel|status))\b/ }, + { api: 'network_adapter', minAppVersion: '1.3.0.2', pattern: /\bnetwork_adapter\b/ }, + { api: 'context_menu', minAppVersion: '1.3.0.2', pattern: /\bcontext_menu\b/ }, + { api: 'browser_history', minAppVersion: '1.3.0.2', pattern: /\bbrowser_history_(?:query|cancel)\b/ }, + { api: 'tool_media_capture', minAppVersion: '1.3.0.2', pattern: /\btool_media_capture_(?:sources|start|stop|status)\b/ }, + { api: 'tool_archive', minAppVersion: '1.3.0.4', pattern: /\btool_archive_(?:list|extract|create)\b/ }, + { api: 'tool_document_pdf', minAppVersion: '1.3.0.4', pattern: /\btool_document_pdf_(?:inspect|transform|render)\b/ }, + { api: 'tool_image', minAppVersion: '1.3.0.4', pattern: /\btool_image_(?:inspect|process)\b/ } ]) export const APP_VERSION_REGEX = /^\d+(?:\.\d+){1,3}$/ @@ -87,5 +97,10 @@ export function resolvePluginMinAppVersion(pluginDir, manifest = {}) { minAppVersion = requirement.minAppVersion } } + if (Array.isArray(manifest.requiredCapabilities) && manifest.requiredCapabilities.length > 0) { + if (!minAppVersion || compareAppVersion('1.3.0.0', minAppVersion) > 0) { + minAppVersion = '1.3.0.0' + } + } return { minAppVersion, apis } } diff --git a/packages/ztools-plugins-spec/src/validator.js b/packages/ztools-plugins-spec/src/validator.js index c250f12c..704a6c7c 100644 --- a/packages/ztools-plugins-spec/src/validator.js +++ b/packages/ztools-plugins-spec/src/validator.js @@ -42,10 +42,31 @@ export const PERMISSIONS = [ 'crypto', 'audio', 'video', + // 宿主薄原语媒体读取/变换能力权限(media.probe / media.transcode) + 'media.read', + 'media.process', // 结束本机任意进程(宿主 process_terminate_pid 按此权限把关) 'process' ] +export const TOOL_CAPABILITY_IDS = Object.freeze([ + 'media.probe', + 'media.transcode', + 'media.capture', + 'download.stream', + 'download.transfer', + 'archive.list', + 'archive.extract', + 'archive.create', + 'document.pdf.inspect', + 'document.pdf.transform', + 'document.pdf.render', + 'image.inspect', + 'image.process' +]) + +export const TOOL_CAPABILITY_ID_SET = new Set(TOOL_CAPABILITY_IDS) + export const PERMISSION_SET = new Set(PERMISSIONS) /** @@ -332,6 +353,23 @@ export function validatePluginManifest(manifest, options = {}) { if (manifest.minAppVersion !== undefined && (typeof manifest.minAppVersion !== 'string' || !APP_VERSION_REGEX.test(manifest.minAppVersion))) { errors.push(`Invalid minAppVersion format: "${manifest.minAppVersion}" (expected client version such as 1.1.8.3)`) } + if (manifest.requiredCapabilities !== undefined) { + if (!Array.isArray(manifest.requiredCapabilities)) { + errors.push('requiredCapabilities must be an array') + } else { + const seenCap = new Set() + for (const cap of manifest.requiredCapabilities) { + if (typeof cap !== 'string' || !TOOL_CAPABILITY_ID_SET.has(cap)) { + errors.push(`Unknown requiredCapability: "${String(cap)}". Valid capabilities: ${TOOL_CAPABILITY_IDS.join(', ')}`) + continue + } + if (seenCap.has(cap)) { + errors.push(`Duplicate requiredCapability: "${cap}"`) + } + seenCap.add(cap) + } + } + } // 2. id 校验 if (manifest.id !== undefined) { @@ -411,13 +449,13 @@ export function validatePluginManifest(manifest, options = {}) { } } - // 8. entry 校验 + // 8. entry 校验(已下架墓碑条目仅保留 plugin.json,豁免磁盘文件存在性检查,仍校验路径格式) if (manifest.entry !== undefined) { if (typeof manifest.entry !== 'string') { errors.push('entry must be a string') } else if (!SAFE_ENTRY_REGEX.test(manifest.entry)) { errors.push(`Invalid entry path: "${manifest.entry}" (must be a safe relative path ending in .html, .js, or .mjs; path traversal is disallowed)`) - } else if (options.baseDir) { + } else if (options.baseDir && manifest.revoked !== true) { const resolvedEntry = path.resolve(options.baseDir, manifest.entry) if (!fs.existsSync(resolvedEntry)) { errors.push(`entry file does not exist: ${manifest.entry}`) @@ -425,13 +463,13 @@ export function validatePluginManifest(manifest, options = {}) { } } - // 9. icon 校验 + // 9. icon 校验(已下架墓碑条目同上,豁免磁盘文件存在性检查,仍校验路径格式) if (manifest.icon !== undefined) { if (typeof manifest.icon !== 'string') { errors.push('icon must be a string') } else if (!SAFE_ICON_REGEX.test(manifest.icon)) { errors.push(`Invalid icon path: "${manifest.icon}" (must be a relative path ending in .png, .svg, .jpg, .jpeg, .webp, or .ico)`) - } else if (options.baseDir) { + } else if (options.baseDir && manifest.revoked !== true) { const resolvedIcon = path.resolve(options.baseDir, manifest.icon) if (!fs.existsSync(resolvedIcon)) { errors.push(`icon file does not exist: ${manifest.icon}`) @@ -542,7 +580,9 @@ export function validatePluginManifest(manifest, options = {}) { } export const LOCALE_TAG_REGEX = /^[a-z]{2,3}(?:-[A-Z][a-z]{3})?(?:-[A-Z]{2}|-[0-9]{3})?$/ +export const MAX_README_LENGTH = 12000 const I18N_ENTRY_KEYS = new Set(['name', 'description', 'keywords', 'revokedReason', 'features', 'screenshots']) +const CATALOG_I18N_ENTRY_KEYS = new Set([...I18N_ENTRY_KEYS, 'readme']) const I18N_FEATURE_KEYS = new Set(['explain', 'cmds']) const I18N_SCREENSHOT_KEYS = new Set(['file', 'title']) @@ -630,12 +670,12 @@ function validateI18nScreenshots(list, label, options, errors) { } } -function validateI18nEntryFields(entry, label, errors, { topFeatureCodes = null, screenshotValidator = null } = {}) { +function validateI18nEntryFields(entry, label, errors, { topFeatureCodes = null, screenshotValidator = null, allowedKeys = I18N_ENTRY_KEYS } = {}) { if (!entry || typeof entry !== 'object' || Array.isArray(entry)) { errors.push(`${label} must be an object`) return } - const unknownKeys = Object.keys(entry).filter((k) => !I18N_ENTRY_KEYS.has(k)) + const unknownKeys = Object.keys(entry).filter((k) => !allowedKeys.has(k)) if (unknownKeys.length > 0) { errors.push(`${label} contains unknown fields: ${unknownKeys.join(', ')}`) } @@ -653,6 +693,13 @@ function validateI18nEntryFields(entry, label, errors, { topFeatureCodes = null, errors.push(`${label}.description must not exceed 500 characters`) } } + if (entry.readme !== undefined && allowedKeys.has('readme')) { + if (typeof entry.readme !== 'string' || entry.readme.trim().length === 0) { + errors.push(`${label}.readme must be a non-empty string`) + } else if (entry.readme.length > MAX_README_LENGTH) { + errors.push(`${label}.readme must not exceed ${MAX_README_LENGTH} characters`) + } + } if (entry.revokedReason !== undefined) { if (typeof entry.revokedReason !== 'string' || entry.revokedReason.trim().length === 0) { errors.push(`${label}.revokedReason must be a non-empty string`) @@ -874,7 +921,8 @@ function validateCatalogI18n(item, errors) { const label = `i18n["${locale}"]` validateI18nEntryFields(entry, label, errors, { topFeatureCodes, - screenshotValidator: (list, entryLabel) => validateCatalogScreenshots(list, `${entryLabel}.screenshots`, errors) + screenshotValidator: (list, entryLabel) => validateCatalogScreenshots(list, `${entryLabel}.screenshots`, errors), + allowedKeys: CATALOG_I18N_ENTRY_KEYS }) } } @@ -917,9 +965,33 @@ export function validateCatalogPluginItem(item) { if (item.minAppVersion !== undefined && (typeof item.minAppVersion !== 'string' || !APP_VERSION_REGEX.test(item.minAppVersion))) { errors.push(`Invalid minAppVersion format: "${item.minAppVersion}"`) } + if (item.requiredCapabilities !== undefined) { + if (!Array.isArray(item.requiredCapabilities)) { + errors.push('requiredCapabilities must be an array') + } else { + const seenCap = new Set() + for (const cap of item.requiredCapabilities) { + if (typeof cap !== 'string' || !TOOL_CAPABILITY_ID_SET.has(cap)) { + errors.push(`Unknown requiredCapability: "${String(cap)}"`) + continue + } + if (seenCap.has(cap)) { + errors.push(`Duplicate requiredCapability: "${cap}"`) + } + seenCap.add(cap) + } + } + } if (item.revoked !== undefined && typeof item.revoked !== 'boolean') { errors.push('revoked must be a boolean') } + if (item.readme !== undefined) { + if (typeof item.readme !== 'string' || item.readme.trim().length === 0) { + errors.push('readme must be a non-empty string') + } else if (item.readme.length > MAX_README_LENGTH) { + errors.push(`readme must not exceed ${MAX_README_LENGTH} characters`) + } + } if (item.screenshots !== undefined) { validateCatalogScreenshots(item.screenshots, 'screenshots', errors) } diff --git a/packages/ztools-plugins-spec/tests/catalog-validator.test.mjs b/packages/ztools-plugins-spec/tests/catalog-validator.test.mjs index 3471786c..da03556a 100644 --- a/packages/ztools-plugins-spec/tests/catalog-validator.test.mjs +++ b/packages/ztools-plugins-spec/tests/catalog-validator.test.mjs @@ -15,6 +15,7 @@ import { PLUGIN_CATEGORY_IDS, HIGH_RISK_PERMISSIONS, OFFICIAL_PLUGIN_IDS, + TOOL_CAPABILITY_IDS, isOfficialAuthorName } from '../src/validator.js' @@ -301,6 +302,9 @@ describe('Store Catalog & Plugin Item Validator (Beyond Happy Path)', () => { } const schema = JSON.parse(fs.readFileSync(new URL('../plugin.schema.json', import.meta.url), 'utf8')) assert.deepEqual([...schema.properties.permissions.items.enum].sort(), [...PERMISSIONS].sort()) + assert.deepEqual([...schema.properties.requiredCapabilities.items.enum].sort(), [...TOOL_CAPABILITY_IDS].sort()) + assert.ok(schema.properties.minAppVersion) + assert.equal(schema.properties.minClientVersion, undefined) assert.ok(HIGH_RISK_PERMISSIONS.has('process')) }) @@ -502,13 +506,13 @@ describe('Store Catalog & Plugin Item Validator (Beyond Happy Path)', () => { const base = { name: '测试', version: '1.0.0', description: '测试', category: ['办公效率'], entry: 'dist/index.js', icon: 'icon.svg', permissions: [], targets: buildPlatformTargets(['windows']), nativeComponents: [] } const authorErrors = (manifest) => validatePluginManifest(manifest).errors.filter((e) => e.includes('official name')) - it('名单来自 official-ids.json:109 个 ID、无重复、格式合法', () => { + it('名单来自 official-ids.json:103 个 ID、无重复、格式合法', () => { const raw = JSON.parse(fs.readFileSync(new URL('../official-ids.json', import.meta.url), 'utf8')) - assert.equal(raw.ids.length, 109) + assert.equal(raw.ids.length, 103) assert.equal(new Set(raw.ids).size, raw.ids.length) assert.deepEqual([...raw.ids].sort(), raw.ids, '名单按字母排序,方便审核 diff') for (const id of raw.ids) assert.match(id, /^[a-z][a-z0-9-]{1,63}$/, id) - assert.equal(OFFICIAL_PLUGIN_IDS.size, 109) + assert.equal(OFFICIAL_PLUGIN_IDS.size, 103) }) it('官方作者名识别:大小写、空格、连字符变体都算;ZTools Community、普通名字不算', () => { diff --git a/packages/ztools-plugins-spec/tests/host-requirements.test.mjs b/packages/ztools-plugins-spec/tests/host-requirements.test.mjs index 1ca8b0ca..e5e87003 100644 --- a/packages/ztools-plugins-spec/tests/host-requirements.test.mjs +++ b/packages/ztools-plugins-spec/tests/host-requirements.test.mjs @@ -95,6 +95,96 @@ describe('最低客户端版本(minAppVersion)', () => { assert.equal(resolvePluginMinAppVersion(dir).minAppVersion, undefined) }) + it('依赖 1.3.0.0 薄原语接口或声明 requiredCapabilities 时自动要求 1.3.0.0', (t) => { + const methods = [ + 'tool_runtime_capabilities', + 'tool_runtime_ensure', + 'tool_task_cancel', + 'tool_media_probe', + 'tool_media_transcode_run', + 'tool_download_stream_probe', + 'tool_download_stream_run', + 'tool_download_transfer_add', + 'tool_download_transfer_pause', + 'tool_download_transfer_resume', + 'tool_download_transfer_cancel', + 'tool_download_transfer_status' + ] + for (const method of methods) { + const dir = makePlugin({ 'dist/logic.js': `transport.call('${method}', {})` }) + t.after(() => removeTempDir(dir)) + assert.equal(resolvePluginMinAppVersion(dir, { minAppVersion: '1.2.0.0' }).minAppVersion, '1.3.0.0', method) + } + const capDir = makePlugin({ 'dist/index.js': 'export default {}' }) + t.after(() => removeTempDir(capDir)) + assert.equal( + resolvePluginMinAppVersion(capDir, { requiredCapabilities: ['download.stream'] }).minAppVersion, + '1.3.0.0' + ) + assert.equal( + resolvePluginMinAppVersion(capDir, { minAppVersion: '1.3.1.0', requiredCapabilities: ['download.stream'] }).minAppVersion, + '1.3.1.0' + ) + }) + + it('依赖 1.3.0.2 / 1.3.0.4 新增宿主接口与薄原语时自动要求对应版本,且不被旧清单降级', (t) => { + const methods1302 = [ + 'network_adapter', + 'context_menu', + 'browser_history_query', + 'browser_history_cancel', + 'tool_media_capture_sources', + 'tool_media_capture_start', + 'tool_media_capture_stop', + 'tool_media_capture_status' + ] + for (const method of methods1302) { + const dir = makePlugin({ 'dist/logic.js': `transport.call('${method}', {})` }) + t.after(() => removeTempDir(dir)) + assert.equal(resolvePluginMinAppVersion(dir).minAppVersion, '1.3.0.2', method) + assert.equal( + resolvePluginMinAppVersion(dir, { minAppVersion: '1.3.0.0' }).minAppVersion, + '1.3.0.2', + method + ) + assert.equal( + resolvePluginMinAppVersion(dir, { minAppVersion: '1.3.0.5' }).minAppVersion, + '1.3.0.5', + method + ) + } + const methods1304 = [ + 'tool_archive_list', + 'tool_archive_extract', + 'tool_archive_create', + 'tool_document_pdf_inspect', + 'tool_document_pdf_transform', + 'tool_document_pdf_render', + 'tool_image_inspect', + 'tool_image_process' + ] + for (const method of methods1304) { + const dir = makePlugin({ 'dist/logic.js': `transport.call('${method}', {})` }) + t.after(() => removeTempDir(dir)) + assert.equal(resolvePluginMinAppVersion(dir).minAppVersion, '1.3.0.4', method) + assert.equal( + resolvePluginMinAppVersion(dir, { minAppVersion: '1.3.0.3' }).minAppVersion, + '1.3.0.4', + method + ) + assert.equal( + resolvePluginMinAppVersion(dir, { minAppVersion: '1.3.0.5' }).minAppVersion, + '1.3.0.5', + method + ) + } + const nonMatchingDir = makePlugin({ + 'dist/index.js': "'my_network_adapter_v2'; 'context_menu_item'; 'browser_history_clear'; 'tool_archive_unknown'" + }) + t.after(() => removeTempDir(nonMatchingDir)) + assert.equal(resolvePluginMinAppVersion(nonMatchingDir).minAppVersion, undefined) + }) + it('清单与目录条目里的 minAppVersion 格式不对时报错', () => { const manifest = { id: 'demo-tool', name: 'Demo', version: '1.0.0', description: 'd', author: 'a', entry: 'dist/index.js', icon: 'icon.svg', permissions: [], minAppVersion: 'latest' } assert.ok(validatePluginManifest(manifest).errors.some((e) => e.includes('minAppVersion'))) diff --git a/scripts/build-declarative.mjs b/scripts/build-declarative.mjs index 96f156d5..b600e04f 100644 --- a/scripts/build-declarative.mjs +++ b/scripts/build-declarative.mjs @@ -2,58 +2,106 @@ /** * 构建声明式 2.0 插件:tsc 输出 ES 模块到各插件的 dist/ * - * 用法:node scripts/build-declarative.mjs [...] - * node scripts/build-declarative.mjs --all + * 用法:node scripts/build-declarative.mjs [...] [--ensure] [--concurrency ] [--quiet] + * node scripts/build-declarative.mjs --all [--ensure] [--concurrency ] [--quiet] * - * - 插件源码以 plugins//src 为准,必须能在插件目录内独立编译(SDK 统一从 @ztools/declarative-ui 引入) + * - 插件源码以 /src 为准,必须能在插件目录内独立编译(SDK 统一从 @ztools/declarative-ui 引入) * - 统一以 ES2022 模块输出(宿主加载器同时兼容 ESM 与 CommonJS,这里固定一种避免各插件 tsconfig 不一致) * - .tsx 默认按 React.createElement 输出(插件里 import React from '@ztools/declarative-ui') * - 构建前清空 dist/,避免残留已删除源码的旧产物 - * - shared/ 下的公共源码(hash.ts、native-ipc.ts、volume-ipc.ts、host-compat.ts、qr-encoder.ts、file-import.ts)以复制方式进入插件,构建前校验副本与源文件一致 - * - 同一份脚本在内部插件仓库与公开插件仓库(ZTools-extensions,插件位于 extensions/)都能直接运行 + * - --ensure 模式下按 src/ 与 tsconfig.json 修改时间增量构建,产物已最新时直接跳过 + * - shared/ 下的公共源码以复制方式进入插件,构建前校验副本与源文件一致 + * - 同一份脚本在母仓插件目录与公开插件仓库(ZTools-extensions,插件位于 extensions/)都能直接运行 */ -import { execFileSync } from 'node:child_process' +import { execFile } from 'node:child_process' import fs from 'node:fs' +import os from 'node:os' import path from 'node:path' import { fileURLToPath } from 'node:url' +import { promisify } from 'node:util' -const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..') -const SHARED = ['hash.ts', 'native-ipc.ts', 'volume-ipc.ts', 'host-compat.ts', 'qr-encoder.ts', 'file-import.ts', 'error-i18n.ts'] +const execFileAsync = promisify(execFile) -// 插件所在目录:仓库里有 extensions/ 时在 extensions/ 下,否则就是本脚本上一级目录 -const pluginsRoot = fs.existsSync(path.join(root, 'extensions')) ? path.join(root, 'extensions') : root -const sharedRoot = [path.join(pluginsRoot, 'shared'), path.join(root, 'shared')].find((d) => fs.existsSync(d)) +const defaultScriptRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..') +export const SHARED_FILES = [ + 'hash.ts', + 'native-ipc.ts', + 'volume-ipc.ts', + 'host-compat.ts', + 'qr-encoder.ts', + 'file-import.ts', + 'error-i18n.ts' +] + +const PLUGIN_ID_RE = /^(?:[a-z0-9][a-z0-9-]*\/)?[a-z0-9][a-z0-9-]*$/ +const IGNORED_TOP_DIRS = new Set(['shared', 'scripts', 'node_modules', 'packages']) function firstExisting(candidates) { return candidates.find((p) => fs.existsSync(p)) } -// 依次在本仓库与上级仓库(内部插件仓库作为子模块时)查找 -const searchRoots = [root, path.resolve(root, '..')] -const tscJs = firstExisting( - searchRoots.flatMap((r) => [ - path.join(r, 'node_modules/typescript/bin/tsc'), - path.join(r, 'electron-client/node_modules/typescript/bin/tsc'), - path.join(r, 'packages/declarative-ui/node_modules/typescript/bin/tsc'), - path.join(r, 'frontend/node_modules/typescript/bin/tsc') - ]) -) -const tsc = tscJs || firstExisting(searchRoots.map((r) => path.join(r, 'node_modules/.bin/tsc'))) -const nodeTypes = firstExisting( - searchRoots.flatMap((r) => [ - path.join(r, 'node_modules/@types/node'), - path.join(r, 'frontend/node_modules/@types/node'), - path.join(r, 'electron-client/node_modules/@types/node') - ]) -) - -const args = process.argv.slice(2) -// 插件目录:plugins/,以及作者分组的 plugins//(如 official/github) -function listAllPlugins() { - const isPlugin = (rel) => fs.existsSync(path.join(pluginsRoot, rel, 'plugin.json')) && fs.existsSync(path.join(pluginsRoot, rel, 'tsconfig.json')) +/** 根据脚本根目录推导插件所在根目录(存在 extensions/ 时取 extensions/,否则取根目录本身) */ +export function resolveDefaultPluginsRoot(scriptRoot = defaultScriptRoot) { + return fs.existsSync(path.join(scriptRoot, 'extensions')) + ? path.join(scriptRoot, 'extensions') + : scriptRoot +} + +/** 推导 shared/ 公共源码目录 */ +export function resolveSharedRoot(pluginsRoot, scriptRoot = defaultScriptRoot) { + return firstExisting([path.join(pluginsRoot, 'shared'), path.join(scriptRoot, 'shared')]) || null +} + +/** 递归计算文件或目录的最新修改时间(毫秒);目录包含自身 mtime 以感知新增/删除文件 */ +export function newestMtime(target) { + let stats + try { + stats = fs.statSync(target) + } catch { + return 0 + } + if (!stats.isDirectory()) return stats.mtimeMs + let newest = stats.mtimeMs + for (const entry of fs.readdirSync(target, { withFileTypes: true })) { + if (entry.name === 'node_modules' || entry.name.startsWith('.')) continue + newest = Math.max(newest, newestMtime(path.join(target, entry.name))) + } + return newest +} + +/** 探测 TypeScript 编译器与 @types/node 类型声明 */ +export function resolveToolchain(searchRoots) { + const roots = Array.isArray(searchRoots) && searchRoots.length > 0 + ? searchRoots + : [defaultScriptRoot, path.resolve(defaultScriptRoot, '..')] + const tscJs = firstExisting( + roots.flatMap((r) => [ + path.join(r, 'node_modules/typescript/bin/tsc'), + path.join(r, 'electron-client/node_modules/typescript/bin/tsc'), + path.join(r, 'packages/declarative-ui/node_modules/typescript/bin/tsc'), + path.join(r, 'frontend/node_modules/typescript/bin/tsc') + ]) + ) + const tsc = tscJs || firstExisting(roots.map((r) => path.join(r, 'node_modules/.bin/tsc'))) + const nodeTypes = firstExisting( + roots.flatMap((r) => [ + path.join(r, 'node_modules/@types/node'), + path.join(r, 'frontend/node_modules/@types/node'), + path.join(r, 'electron-client/node_modules/@types/node') + ]) + ) + return { tscJs: tscJs || null, tsc: tsc || null, nodeTypes: nodeTypes || null } +} + +/** 列出全部可编译插件目录( 或 /,需同时含 plugin.json 与 tsconfig.json) */ +export function listAllPlugins(pluginsRoot = resolveDefaultPluginsRoot()) { + if (!fs.existsSync(pluginsRoot)) return [] + const isPlugin = (rel) => + fs.existsSync(path.join(pluginsRoot, rel, 'plugin.json')) && + fs.existsSync(path.join(pluginsRoot, rel, 'tsconfig.json')) const out = [] for (const d of fs.readdirSync(pluginsRoot, { withFileTypes: true })) { - if (!d.isDirectory() || ['shared', 'scripts', 'node_modules', 'packages'].includes(d.name) || d.name.startsWith('.')) continue + if (!d.isDirectory() || IGNORED_TOP_DIRS.has(d.name) || d.name.startsWith('.')) continue if (isPlugin(d.name)) { out.push(d.name) continue @@ -65,76 +113,295 @@ function listAllPlugins() { return out.sort() } -const ids = args.includes('--all') ? listAllPlugins() : args.filter((a) => !a.startsWith('--')) -if (ids.length === 0) { - console.error('用法:node scripts/build-declarative.mjs [...plugin-id] | --all') - process.exit(2) +/** 判断单个插件是否需要(重新)编译 */ +export function pluginNeedsBuild(pluginDir, manifest = null) { + const resolvedManifest = manifest || JSON.parse(fs.readFileSync(path.join(pluginDir, 'plugin.json'), 'utf8')) + const entry = String(resolvedManifest.entry || 'dist/index.js') + const entryPath = path.join(pluginDir, entry) + const srcDir = path.join(pluginDir, 'src') + const tsconfigPath = path.join(pluginDir, 'tsconfig.json') + const sourceTime = Math.max(newestMtime(srcDir), newestMtime(tsconfigPath)) + if (!fs.existsSync(entryPath)) { + return { build: true, reason: `missing entry ${entry}`, entry, entryPath, sourceTime } + } + const distTime = fs.statSync(entryPath).mtimeMs + if (sourceTime > distTime) { + return { build: true, reason: 'source or tsconfig is newer than dist', entry, entryPath, sourceTime } + } + return { build: false, reason: 'dist is up to date', entry, entryPath, sourceTime } } -if (!tsc) { - console.error('未找到 TypeScript 编译器(请先在仓库根目录 npm install)') - process.exit(2) + +function isNodeScriptFile(filePath) { + try { + const fd = fs.openSync(filePath, 'r') + try { + const buf = Buffer.alloc(64) + const n = fs.readSync(fd, buf, 0, buf.length, 0) + const head = buf.subarray(0, n).toString('utf8') + return head.startsWith('#!') && /\bnode\b/.test(head.split(/\r?\n/, 1)[0]) + } finally { + fs.closeSync(fd) + } + } catch { + return false + } } -if (!nodeTypes) { - console.error('未找到 @types/node(请先在仓库根目录 npm install)') - process.exit(2) + +function checkSharedCopies(id, dir, sharedRoot, errorLog) { + let staleCopy = false + for (const name of SHARED_FILES) { + const copy = path.join(dir, 'src', name) + const origin = sharedRoot && path.join(sharedRoot, name) + if ( + fs.existsSync(copy) && + origin && + fs.existsSync(origin) && + fs.readFileSync(copy, 'utf8') !== fs.readFileSync(origin, 'utf8') + ) { + errorLog(`[${id}] src/${name} differs from shared/${name}; copy the latest file before building`) + staleCopy = true + } + } + return !staleCopy } -let failed = 0 -for (const id of ids) { +async function compileSinglePlugin({ + id, + pluginsRoot, + sharedRoot, + toolchain, + ensure, + includeRevoked, + quiet, + log, + errorLog +}) { const dir = path.join(pluginsRoot, id) const manifestPath = path.join(dir, 'plugin.json') - if (!/^(?:[a-z0-9][a-z0-9-]*\/)?[a-z0-9][a-z0-9-]*$/.test(id) || !fs.existsSync(manifestPath)) { - console.error(`[${id}] 不是有效的插件目录`) - failed++ - continue + if (!PLUGIN_ID_RE.test(id) || !fs.existsSync(manifestPath)) { + errorLog(`[${id}] is not a valid plugin directory`) + return { id, status: 'failed' } } const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8')) - if (manifest.revoked === true) { - console.log(`[${id}] 已下架,跳过构建`) - continue + if (manifest.revoked === true && !includeRevoked) { + if (!quiet) log(`[${id}] revoked, skipping build`) + return { id, status: 'skipped', reason: 'revoked' } } - let staleCopy = false - for (const name of SHARED) { - const copy = path.join(dir, 'src', name) - const origin = sharedRoot && path.join(sharedRoot, name) - if (fs.existsSync(copy) && origin && fs.existsSync(origin) && fs.readFileSync(copy, 'utf8') !== fs.readFileSync(origin, 'utf8')) { - console.error(`[${id}] src/${name} 与 shared/${name} 不一致,请重新复制后再构建`) - staleCopy = true - } + // 历史已下架插件源码可能早于 shared/ 冻结,仅对非下架插件强制校验 shared 副本一致性 + if (manifest.revoked !== true && !checkSharedCopies(id, dir, sharedRoot, errorLog)) { + return { id, status: 'failed' } + } + const decision = pluginNeedsBuild(dir, manifest) + if (ensure && !decision.build) { + if (!quiet) log(`[${id}] dist is up to date, skipping build`) + return { id, status: 'skipped', reason: 'up-to-date' } } - if (staleCopy) { - failed++ - continue + const srcDir = path.join(dir, 'src') + if (!fs.existsSync(srcDir) || !fs.existsSync(path.join(dir, 'tsconfig.json'))) { + errorLog(`[${id}] missing src/ or tsconfig.json`) + return { id, status: 'failed' } } - const hasTsx = fs.readdirSync(path.join(dir, 'src'), { recursive: true }).some((f) => String(f).endsWith('.tsx')) + const hasTsx = fs.readdirSync(srcDir, { recursive: true }).some((f) => String(f).endsWith('.tsx')) fs.rmSync(path.join(dir, 'dist'), { recursive: true, force: true }) + + const tscArgs = [ + '-p', path.join(dir, 'tsconfig.json'), + '--module', 'ES2022', + '--moduleResolution', 'bundler', + ...(hasTsx ? ['--jsx', 'react'] : []), + '--typeRoots', path.dirname(toolchain.nodeTypes), + '--types', 'node', + '--outDir', path.join(dir, 'dist') + ] try { - const tscArgs = [ - '-p', path.join(dir, 'tsconfig.json'), - '--module', 'ES2022', - '--moduleResolution', 'bundler', - ...(hasTsx ? ['--jsx', 'react'] : []), - '--typeRoots', path.dirname(nodeTypes), - '--types', 'node', - '--outDir', path.join(dir, 'dist') - ] - if (tscJs) { - execFileSync(process.execPath, [tscJs, ...tscArgs], { stdio: 'inherit' }) + if (toolchain.tscJs) { + await execFileAsync(process.execPath, [toolchain.tscJs, ...tscArgs], { + maxBuffer: 10 * 1024 * 1024, + windowsHide: true + }) + } else if (isNodeScriptFile(toolchain.tsc)) { + await execFileAsync(process.execPath, [toolchain.tsc, ...tscArgs], { + maxBuffer: 10 * 1024 * 1024, + windowsHide: true + }) } else { - execFileSync(tsc, tscArgs, { stdio: 'inherit' }) + await execFileAsync(toolchain.tsc, tscArgs, { + maxBuffer: 10 * 1024 * 1024, + shell: process.platform === 'win32', + windowsHide: true + }) } - } catch { - console.error(`[${id}] 编译失败`) - failed++ - continue + } catch (err) { + const out = [err?.stdout, err?.stderr].filter(Boolean).join('\n').trim() + if (out) errorLog(out) + errorLog(`[${id}] compilation failed`) + return { id, status: 'failed' } } - const entry = manifest.entry || 'dist/index.js' - if (!fs.existsSync(path.join(dir, entry))) { - console.error(`[${id}] 编译后缺少入口文件 ${entry}`) - failed++ - continue + + if (!fs.existsSync(decision.entryPath)) { + errorLog(`[${id}] missing compiled entry ${decision.entry}`) + return { id, status: 'failed' } + } + + // 刷新入口时间戳至不早于最新源码 + 1ms,消除亚毫秒精度导致下次 --ensure 误判过期 + const latestSource = Math.max(newestMtime(srcDir), newestMtime(path.join(dir, 'tsconfig.json'))) + const stamp = new Date(Math.max(Date.now(), Math.ceil(latestSource) + 1)) + fs.utimesSync(decision.entryPath, stamp, stamp) + + if (!quiet) log(`[${id}] build succeeded`) + return { id, status: 'built' } +} + +/** + * 批量(支持 --ensure 增量与并发)编译声明式插件 + * @returns {Promise<{ ok: boolean, total: number, built: string[], skipped: string[], failed: string[] }>} + */ +export async function buildDeclarativePlugins({ + ids = [], + all = false, + pluginsRoot = resolveDefaultPluginsRoot(), + scriptRoot = defaultScriptRoot, + sharedRoot = undefined, + searchRoots = undefined, + ensure = false, + includeRevoked = false, + concurrency = undefined, + quiet = false, + log = console.log, + errorLog = console.error +} = {}) { + const resolvedPluginsRoot = path.resolve(pluginsRoot) + const resolvedSharedRoot = sharedRoot === undefined + ? resolveSharedRoot(resolvedPluginsRoot, scriptRoot) + : sharedRoot + const targetIds = all ? listAllPlugins(resolvedPluginsRoot) : [...ids] + + if (targetIds.length === 0) { + return { ok: true, total: 0, built: [], skipped: [], failed: [] } + } + + const defaultRoots = [ + resolvedPluginsRoot, + path.resolve(resolvedPluginsRoot, '..'), + scriptRoot, + path.resolve(scriptRoot, '..') + ] + const toolchain = resolveToolchain(searchRoots || defaultRoots) + if (!toolchain.tsc) { + throw new Error('TypeScript compiler (tsc) not found. Run npm install in the repository root first.') + } + if (!toolchain.nodeTypes) { + throw new Error('@types/node not found. Run npm install in the repository root first.') + } + + const defaultConcurrency = Math.min(Math.max(os.cpus().length, 2), 8) + const maxWorkers = Math.max(1, Math.min(Number(concurrency) || defaultConcurrency, targetIds.length)) + + const results = new Array(targetIds.length) + let cursor = 0 + + async function worker() { + while (cursor < targetIds.length) { + const idx = cursor++ + results[idx] = await compileSinglePlugin({ + id: targetIds[idx], + pluginsRoot: resolvedPluginsRoot, + sharedRoot: resolvedSharedRoot, + toolchain, + ensure, + includeRevoked, + quiet, + log, + errorLog + }) + } + } + + await Promise.all(Array.from({ length: maxWorkers }, () => worker())) + + const built = [] + const skipped = [] + const failed = [] + for (const r of results) { + if (r.status === 'built') built.push(r.id) + else if (r.status === 'skipped') skipped.push(r.id) + else failed.push(r.id) + } + + return { + ok: failed.length === 0, + total: targetIds.length, + built, + skipped, + failed + } +} + +function parseCliArgs(argv) { + const ids = [] + let all = false + let ensure = false + let includeRevoked = false + let quiet = false + let concurrency = undefined + for (let i = 0; i < argv.length; i++) { + const arg = argv[i] + if (arg === '--all') { + all = true + } else if (arg === '--ensure') { + ensure = true + } else if (arg === '--include-revoked') { + includeRevoked = true + } else if (arg === '--quiet' || arg === '-q') { + quiet = true + } else if (arg === '--concurrency') { + const next = argv[++i] + const n = Number.parseInt(next, 10) + if (!Number.isInteger(n) || n < 1) { + throw new Error(`Invalid --concurrency value: ${next ?? '(empty)'}`) + } + concurrency = n + } else if (arg.startsWith('--concurrency=')) { + const val = arg.slice('--concurrency='.length) + const n = Number.parseInt(val, 10) + if (!Number.isInteger(n) || n < 1) { + throw new Error(`Invalid --concurrency value: ${val}`) + } + concurrency = n + } else if (arg.startsWith('-')) { + throw new Error(`Unknown option: ${arg}`) + } else { + ids.push(arg) + } + } + return { ids, all, ensure, includeRevoked, quiet, concurrency } +} + +const isMainModule = + process.argv[1] && + path.resolve(process.argv[1]).toLowerCase() === path.resolve(fileURLToPath(import.meta.url)).toLowerCase() + +if (isMainModule) { + try { + const parsed = parseCliArgs(process.argv.slice(2)) + if (!parsed.all && parsed.ids.length === 0) { + console.error('Usage: node scripts/build-declarative.mjs [...plugin-id] | --all [--ensure] [--include-revoked] [--concurrency ] [--quiet]') + process.exit(2) + } + const summary = await buildDeclarativePlugins({ + ids: parsed.ids, + all: parsed.all, + ensure: parsed.ensure, + includeRevoked: parsed.includeRevoked, + concurrency: parsed.concurrency, + quiet: parsed.quiet + }) + if (summary.total > 1) { + console.log(`\nTotal ${summary.total} plugins: built ${summary.built.length}, skipped ${summary.skipped.length}, failed ${summary.failed.length}`) + } + process.exit(summary.ok ? 0 : 1) + } catch (err) { + console.error(err instanceof Error ? err.message : String(err)) + process.exit(2) } - console.log(`[${id}] 构建完成`) } -if (ids.length > 1) console.log(`\n共 ${ids.length} 个插件,失败 ${failed} 个`) -process.exit(failed ? 1 : 0) diff --git a/scripts/build-plugins-release.mjs b/scripts/build-plugins-release.mjs index 58516428..07f6413b 100644 --- a/scripts/build-plugins-release.mjs +++ b/scripts/build-plugins-release.mjs @@ -19,7 +19,8 @@ import fs from 'node:fs' import path from 'node:path' import crypto from 'node:crypto' import zlib from 'node:zlib' -import { fileURLToPath } from 'node:url' +import { execFileSync } from 'node:child_process' +import { fileURLToPath, pathToFileURL } from 'node:url' import { scanPluginSecurity } from './scan-plugin-security.mjs' import { getManifestPlatforms, @@ -37,11 +38,29 @@ import { resolvePluginMinAppVersion } from '../packages/ztools-plugins-spec/src/ const __dirname = path.dirname(fileURLToPath(import.meta.url)) const rootDir = path.resolve(__dirname, '..') +// 声明式插件包里会出现的文本文件;只对这些扩展名统一换行,二进制文件原样打包 +const LF_NORMALIZED_EXTENSIONS = new Set([ + '.js', '.mjs', '.cjs', '.jsx', '.ts', '.mts', '.cts', '.tsx', '.json', '.md', '.txt', + '.css', '.html', '.htm', '.svg', '.xml', '.yml', '.yaml', '.csv', '.map' +]) + +/** + * 把文本文件的 CRLF 统一成 LF,保证在 Windows(core.autocrlf=true)与 macOS/Linux/CI 上打出的包逐字节一致。 + * 含 NUL 字节的内容视为二进制,不做转换。 + */ +export function normalizeTextLineEndings(relPath, data) { + if (!LF_NORMALIZED_EXTENSIONS.has(path.extname(relPath).toLowerCase())) return data + if (data.includes(0) || !data.includes(0x0d)) return data + return Buffer.from(data.toString('latin1').replace(/\r\n/g, '\n'), 'latin1') +} + /** * 使用纯 Node.js 标准库制作 ZIP 二进制 Buffer * 保证跨平台(Windows/macOS/Linux/CI)零外部依赖、确定性与高效打包 + * options.normalizeLineEndings:文本文件统一 LF(声明式插件发布包开启;原生插件包先签名后打包,不能改动已签名文件,保持关闭) */ -export function createZipArchiveFromDirectory(sourceDir, filterFn = null) { +export function createZipArchiveFromDirectory(sourceDir, filterFn = null, options = {}) { + const normalizeLineEndings = options.normalizeLineEndings === true const files = [] function walk(currentDir, baseRelative = '') { @@ -64,7 +83,8 @@ export function createZipArchiveFromDirectory(sourceDir, filterFn = null) { if (entry.isDirectory()) { walk(fullPath, relPath) } else if (entry.isFile()) { - const data = fs.readFileSync(fullPath) + const raw = fs.readFileSync(fullPath) + const data = normalizeLineEndings ? normalizeTextLineEndings(relPath, raw) : raw files.push({ name: relPath, data }) } } @@ -220,14 +240,92 @@ export function collectPluginScreenshots(pluginDir, manifest) { * - 多语言截图:screenshots/<版本>//<序号>-<内容哈希前 8 位>.png * 带版本号与内容哈希,与安装包一样长期强缓存;同一版本里换了图也会得到新地址,不会被旧缓存挡住。 */ -export function screenshotCdnName(version, index, hash, locale = null) { - const filename = `${String(index + 1).padStart(2, '0')}-${hash.slice(0, 8)}.png` +export function screenshotCdnName(version, index, hash, locale = null, ext = 'png') { + const filename = `${String(index + 1).padStart(2, '0')}-${hash.slice(0, 8)}.${ext}` if (locale) { return `screenshots/${version}/${locale}/${filename}` } return `screenshots/${version}/${filename}` } +const MAX_README_LENGTH = 12000 + +function readNormalizedMarkdown(filePath) { + if (!fs.existsSync(filePath)) return '' + try { + const raw = fs.readFileSync(filePath, 'utf8').replace(/^\uFEFF/, '').replace(/\r\n/g, '\n').trim() + if (!raw) return '' + return raw.length > MAX_README_LENGTH ? raw.slice(0, MAX_README_LENGTH) : raw + } catch { + return '' + } +} + +/** 读取插件目录下 README.md(规范化换行并限长 12000 字符),供官网详情页 SSR 与 SEO 抓取 */ +export function readPluginReadme(pluginDir) { + return readNormalizedMarkdown(path.join(pluginDir, 'README.md')) +} + +/** + * 读取插件目录下多语言 README(README.en.md / README.en-US.md / README..md), + * 映射为 `{ [locale]: markdown }` 写入 catalog.json 的 `i18n[locale].readme`。 + * 若同时存在 README.en-US.md 与 README.en.md,优先采用显式完整标签 README.en-US.md。 + */ +export function readPluginLocalizedReadmes(pluginDir) { + if (!fs.existsSync(pluginDir)) return {} + const result = {} + const entries = fs.readdirSync(pluginDir, { withFileTypes: true }) + const candidates = [] + for (const entry of entries) { + if (!entry.isFile()) continue + const match = /^README\.([A-Za-z0-9_-]+)\.md$/.exec(entry.name) + if (!match) continue + const rawTag = match[1].replace(/_/g, '-') + const locale = rawTag.toLowerCase() === 'en' ? 'en-US' : rawTag + if (!LOCALE_TAG_REGEX.test(locale)) continue + candidates.push({ fileName: entry.name, locale, isExplicit: rawTag.toLowerCase() !== 'en' }) + } + // 先读短标签(如 README.en.md),再读显式完整标签(如 README.en-US.md),确保完整标签优先覆盖 + candidates.sort((a, b) => Number(a.isExplicit) - Number(b.isExplicit) || a.fileName.localeCompare(b.fileName)) + for (const item of candidates) { + const text = readNormalizedMarkdown(path.join(pluginDir, item.fileName)) + if (text) { + result[item.locale] = text + } + } + return result +} + +const WEBP_PY_SCRIPT = ` +import io, json, sys +from PIL import Image +raw = sys.stdin.buffer.read() +img = Image.open(io.BytesIO(raw)) +if img.width > 1600: + h = max(1, round(img.height * 1600 / img.width)) + img = img.resize((1600, h), Image.Resampling.LANCZOS) +out = io.BytesIO() +img.save(out, format='WEBP', quality=82, method=6) +buf = out.getvalue() +header = json.dumps({'w': img.width, 'h': img.height}).encode('utf-8') +sys.stdout.buffer.write(header + b'\\n' + buf) +` + +/** 将 PNG Buffer 转为高质量 WebP(宽上限 1600px,quality=82),大幅降低 CDN 与官网加载体积 */ +function convertShotToWebp(shot) { + const stdout = execFileSync('python', ['-c', WEBP_PY_SCRIPT], { + input: shot.data, + maxBuffer: 10 * 1024 * 1024, + windowsHide: true + }) + const nl = stdout.indexOf(0x0a) + if (nl < 0) throw new Error('WebP 转换输出格式异常') + const meta = JSON.parse(stdout.subarray(0, nl).toString('utf8')) + const data = stdout.subarray(nl + 1) + const hash = crypto.createHash('sha256').update(data).digest('hex') + return { ...shot, data, width: meta.w, height: meta.h, hash, ext: 'webp' } +} + /** * 解析目录中的分类字段: * - category:保留中文标准分类数组(向后兼容老客户端) @@ -276,35 +374,48 @@ export function resolveCatalogCategories(manifest) { } /** - * 构建写入 catalog.json / plugins.json 的 i18n 对象,透传合法多语言文本并替换为 CDN 截图 URL + * 构建写入 catalog.json / plugins.json 的 i18n 对象,透传合法多语言文本、多语言 README 并替换为 CDN 截图 URL */ -export function buildCatalogI18n(manifest, i18nScreenshotsByLocale = {}, { revokedOnly = false } = {}) { - const rawI18n = manifest?.i18n - if (!rawI18n || typeof rawI18n !== 'object' || Array.isArray(rawI18n)) { +export function buildCatalogI18n( + manifest, + i18nScreenshotsByLocale = {}, + { revokedOnly = false, i18nReadmesByLocale = {} } = {} +) { + const rawI18n = manifest?.i18n && typeof manifest.i18n === 'object' && !Array.isArray(manifest.i18n) + ? manifest.i18n + : {} + const locales = new Set(Object.keys(rawI18n)) + if (!revokedOnly && i18nReadmesByLocale && typeof i18nReadmesByLocale === 'object') { + for (const locale of Object.keys(i18nReadmesByLocale)) { + locales.add(locale) + } + } + if (locales.size === 0) { return undefined } const result = {} - for (const [locale, entry] of Object.entries(rawI18n)) { + for (const locale of locales) { if (!LOCALE_TAG_REGEX.test(locale)) continue - if (!entry || typeof entry !== 'object' || Array.isArray(entry)) continue + const entry = rawI18n[locale] + const validEntry = entry && typeof entry === 'object' && !Array.isArray(entry) ? entry : {} const out = {} - if (typeof entry.name === 'string' && entry.name.trim()) { - out.name = entry.name.trim() + if (typeof validEntry.name === 'string' && validEntry.name.trim()) { + out.name = validEntry.name.trim() } - if (typeof entry.description === 'string' && entry.description.trim()) { - out.description = entry.description.trim() + if (typeof validEntry.description === 'string' && validEntry.description.trim()) { + out.description = validEntry.description.trim() } - if (typeof entry.revokedReason === 'string' && entry.revokedReason.trim()) { - out.revokedReason = entry.revokedReason.trim() + if (typeof validEntry.revokedReason === 'string' && validEntry.revokedReason.trim()) { + out.revokedReason = validEntry.revokedReason.trim() } if (!revokedOnly) { - if (Array.isArray(entry.keywords)) { - const kws = entry.keywords.filter((k) => typeof k === 'string' && k.trim()).map((k) => k.trim()) + if (Array.isArray(validEntry.keywords)) { + const kws = validEntry.keywords.filter((k) => typeof k === 'string' && k.trim()).map((k) => k.trim()) if (kws.length > 0) out.keywords = kws } - if (entry.features && typeof entry.features === 'object' && !Array.isArray(entry.features)) { + if (validEntry.features && typeof validEntry.features === 'object' && !Array.isArray(validEntry.features)) { const featuresOut = {} - for (const [code, feat] of Object.entries(entry.features)) { + for (const [code, feat] of Object.entries(validEntry.features)) { if (!code.trim() || !feat || typeof feat !== 'object' || Array.isArray(feat)) continue const featOut = {} if (typeof feat.explain === 'string' && feat.explain.trim()) { @@ -325,6 +436,10 @@ export function buildCatalogI18n(manifest, i18nScreenshotsByLocale = {}, { revok if (Array.isArray(localeShots) && localeShots.length > 0) { out.screenshots = localeShots } + const localeReadme = i18nReadmesByLocale?.[locale] + if (typeof localeReadme === 'string' && localeReadme.trim()) { + out.readme = localeReadme.trim().slice(0, MAX_README_LENGTH) + } } if (Object.keys(out).length > 0) { result[locale] = out @@ -455,6 +570,49 @@ export async function buildPluginsRelease(options = {}) { } } + // 若存在 build-declarative.mjs,则对具备 src/ 与 tsconfig.json 的活跃插件按需增量编译,避免缺少 dist/ 或产物过期 + const failedBuildRelSet = new Set() + if (!options.skipBuild) { + const buildScript = [ + path.join(pluginsDir, 'scripts', 'build-declarative.mjs'), + path.join(__dirname, 'build-declarative.mjs') + ].find((p) => fs.existsSync(p)) + if (buildScript) { + const buildableRelIds = [] + for (const entry of pluginEntries) { + if (!fs.existsSync(path.join(entry.dir, 'tsconfig.json')) || !fs.existsSync(path.join(entry.dir, 'src'))) { + continue + } + try { + const manifest = JSON.parse(fs.readFileSync(path.join(entry.dir, 'plugin.json'), 'utf8')) + if (manifest.revoked === true || manifest.draft === true) continue + } catch { + continue + } + const rel = path.relative(pluginsDir, entry.dir).split(path.sep).join('/') + if (rel && !rel.startsWith('..')) buildableRelIds.push(rel) + } + if (buildableRelIds.length > 0) { + const { buildDeclarativePlugins } = await import(pathToFileURL(buildScript).href) + const buildRes = await buildDeclarativePlugins({ + ids: buildableRelIds, + pluginsRoot: pluginsDir, + ensure: true, + quiet: true + }) + if (buildRes.built.length > 0) { + console.log(`🔨 打包前已自动增量编译 ${buildRes.built.length} 个声明式插件(跳过 ${buildRes.skipped.length} 个最新插件)`) + } + if (!buildRes.ok) { + for (const failedRel of buildRes.failed) failedBuildRelSet.add(failedRel) + if (failFast) { + throw new Error(`声明式插件自动编译失败:${buildRes.failed.join(', ')}`) + } + } + } + } + } + const publishedPackages = [] const catalogList = [] const draftIds = [] @@ -462,6 +620,12 @@ export async function buildPluginsRelease(options = {}) { for (const entry of pluginEntries) { const { author, pluginId, dir } = entry + const entryRel = path.relative(pluginsDir, dir).split(path.sep).join('/') + if (failedBuildRelSet.has(entryRel)) { + console.error(`❌ [${pluginId}] 源码预编译失败,拒绝打包发布`) + rejectedCount++ + continue + } const authorSlug = String(author || 'official') .toLowerCase() .trim() @@ -553,7 +717,7 @@ export async function buildPluginsRelease(options = {}) { const zipFilePath = path.join(pluginOutputDir, zipFileName) console.log(`📦 正在生成 ZIP 发布包: ${zipFileName}...`) - const zipBuffer = createZipArchiveFromDirectory(dir) + const zipBuffer = createZipArchiveFromDirectory(dir, null, { normalizeLineEndings: true }) fs.writeFileSync(zipFilePath, zipBuffer) // 3. 计算 SHA256 校验和与包体大小 @@ -576,24 +740,24 @@ export async function buildPluginsRelease(options = {}) { iconUrl = `${cdnBaseUrl}/${relPrefix}/${iconTargetName}` } - // 5. 截图随版本上传到 CDN(不进安装包),目录里只写地址、说明与尺寸(同步覆盖多语言截图) - const screenshots = shotResult.items.map((shot) => { - const cdnName = screenshotCdnName(version, shot.index, shot.hash) + const webp = Boolean(options.webp) + const emitShot = (shot, locale = null) => { + const prepared = webp ? convertShotToWebp(shot) : { ...shot, ext: 'png' } + const cdnName = screenshotCdnName(version, prepared.index, prepared.hash, locale, prepared.ext) const target = path.join(pluginOutputDir, ...cdnName.split('/')) fs.mkdirSync(path.dirname(target), { recursive: true }) - fs.writeFileSync(target, shot.data) - return { url: `${cdnBaseUrl}/${relPrefix}/${cdnName}`, title: shot.title, width: shot.width, height: shot.height } - }) + fs.writeFileSync(target, prepared.data) + return { url: `${cdnBaseUrl}/${relPrefix}/${cdnName}`, title: prepared.title, width: prepared.width, height: prepared.height } + } + + // 5. 截图随版本上传到 CDN(不进安装包),目录里只写地址、说明与尺寸(同步覆盖多语言截图) + const screenshots = shotResult.items.map((shot) => emitShot(shot, null)) const i18nScreenshotsByLocale = {} let i18nScreenshotCount = 0 for (const [locale, localeShots] of Object.entries(shotResult.i18nItems || {})) { i18nScreenshotsByLocale[locale] = localeShots.map((shot) => { - const cdnName = screenshotCdnName(version, shot.index, shot.hash, locale) - const target = path.join(pluginOutputDir, ...cdnName.split('/')) - fs.mkdirSync(path.dirname(target), { recursive: true }) - fs.writeFileSync(target, shot.data) i18nScreenshotCount++ - return { url: `${cdnBaseUrl}/${relPrefix}/${cdnName}`, title: shot.title, width: shot.width, height: shot.height } + return emitShot(shot, locale) }) } if (screenshots.length || i18nScreenshotCount) { @@ -617,7 +781,9 @@ export async function buildPluginsRelease(options = {}) { const defaultLocale = typeof manifest.defaultLocale === 'string' && LOCALE_TAG_REGEX.test(manifest.defaultLocale) ? manifest.defaultLocale : undefined - const catalogI18n = buildCatalogI18n(manifest, i18nScreenshotsByLocale) + const readme = readPluginReadme(dir) + const i18nReadmesByLocale = readPluginLocalizedReadmes(dir) + const catalogI18n = buildCatalogI18n(manifest, i18nScreenshotsByLocale, { i18nReadmesByLocale }) const pluginMetadata = { id: manifest.id, @@ -625,6 +791,7 @@ export async function buildPluginsRelease(options = {}) { name: manifest.name, version: manifest.version, description: manifest.description, + ...(readme ? { readme } : {}), author: manifest.author, // 保留中文分类数组兼容老客户端;新客户端优先按标准英文 slug categoryId 归类与本地化渲染 category, @@ -637,6 +804,9 @@ export async function buildPluginsRelease(options = {}) { minZToolsVersion: manifest.minZToolsVersion || '2.0.0', // 客户端只认 minAppVersion:低于它时不提供更新、安装前提示先升级客户端 ...(minAppVersion ? { minAppVersion } : {}), + ...(Array.isArray(manifest.requiredCapabilities) && manifest.requiredCapabilities.length > 0 + ? { requiredCapabilities: [...manifest.requiredCapabilities] } + : {}), requireAdmin: !!manifest.requireAdmin, // 平台声明由 plugin.json 的 targets 决定(安全扫描已校验必填与格式),不再默认填「双端」 targets: manifest.targets, @@ -742,6 +912,7 @@ async function runCli() { const urlPrefix = getArg('--url-prefix', process.env.PLUGIN_URL_PREFIX || 'plugins-v2') const failFast = args.includes('--fail-fast') const skipScan = args.includes('--skip-scan') + const webp = args.includes('--webp') const result = await buildPluginsRelease({ pluginsDir, @@ -749,7 +920,8 @@ async function runCli() { cdnBaseUrl, urlPrefix, failFast, - skipScan + skipScan, + webp }) if (!result.success) { diff --git a/scripts/deploy-plugins-storage.mjs b/scripts/deploy-plugins-storage.mjs index 484a9e18..79a99234 100644 --- a/scripts/deploy-plugins-storage.mjs +++ b/scripts/deploy-plugins-storage.mjs @@ -9,6 +9,8 @@ * 保证目录里引用的安装包一定已经在线; * 2. 刷新 CDN 上插件目录的缓存,让更新与下架尽快生效; * 3. 支持 --dry-run 演练模式;非演练模式缺少凭证时直接报错,不会假装成功。 + * 4. 已发布的安装包不可变(上传 .zip 时带 x-oss-forbid-overwrite,由 OSS 服务端兜底拒绝覆盖;源站已有相同内容的包直接跳过):同一下载地址换内容(同版本号改代码)默认在上传前中止,必须升版本号,紧急原地修复需显式 --allow-overwrite; + * 安装包上传后即使 CDN 刷新失败也会先把目录传完再报错,避免源站停在「新安装包 + 旧目录」的状态。 */ import fs from 'node:fs' @@ -194,13 +196,14 @@ function makeHttpRequest(options, body) { const client = protocol === 'http:' ? http : https return new Promise((resolve, reject) => { const req = client.request(requestOptions, (res) => { - let data = '' - res.on('data', chunk => { data += chunk }) + // 先收齐字节再整体按 UTF-8 解码:逐块拼字符串会把跨块的中文等多字节字符解成乱码(U+FFFD) + const chunks = [] + res.on('data', chunk => { chunks.push(chunk) }) res.on('end', () => { resolve({ statusCode: res.statusCode, headers: res.headers, - data + data: Buffer.concat(chunks).toString('utf8') }) }) }) @@ -214,7 +217,7 @@ function makeHttpRequest(options, body) { } /** - * 上传文件至阿里云 OSS + * 上传文件至阿里云 OSS(支持直接传入内存 file.buffer,用于合并后的目录 JSON 上传) */ export async function uploadToOss({ file, @@ -224,7 +227,8 @@ export async function uploadToOss({ region, prefix = DEFAULT_OSS_PREFIX, endpoint, - dryRun = false + dryRun = false, + forbidOverwrite = false }) { // endpoint 仅供测试指向本地模拟服务,例如 http://127.0.0.1:8080 const target = endpoint ? new URL(endpoint) : null @@ -232,12 +236,13 @@ export async function uploadToOss({ const cleanPrefix = normalizePrefix(prefix) const objectKey = cleanPrefix ? `${cleanPrefix}/${file.relPath}` : file.relPath const canonicalUri = `/${objectKey}` - const fileBuffer = fs.readFileSync(file.fullPath) + const fileBuffer = Buffer.isBuffer(file.buffer) ? file.buffer : fs.readFileSync(file.fullPath) + const fileSize = fileBuffer.length const contentType = getMimeType(file.relPath) const cacheControl = getCacheControl(file.relPath) if (dryRun) { - console.log(` [OSS 仿真] PUT https://${host}${canonicalUri} (${(file.size / 1024).toFixed(2)} KB, ${contentType}, Cache-Control: ${cacheControl})`) + console.log(` [OSS 仿真] PUT https://${host}${canonicalUri} (${(fileSize / 1024).toFixed(2)} KB, ${contentType}, Cache-Control: ${cacheControl}${forbidOverwrite ? ', 禁止覆盖' : ''})`) return { success: true, simulated: true } } @@ -248,8 +253,10 @@ export async function uploadToOss({ accessKeyId, accessKeySecret, contentType, - contentLength: file.size, - cacheControl + contentLength: fileSize, + cacheControl, + // 由 OSS 服务端拒绝覆盖同名对象:本地脚本被绕过或改坏时,已发布的安装包也不会被换掉 + extraHeaders: forbidOverwrite ? { 'x-oss-forbid-overwrite': 'true' } : {} }) const res = await makeHttpRequest({ @@ -263,6 +270,8 @@ export async function uploadToOss({ if (res.statusCode >= 200 && res.statusCode < 300) { return { success: true, statusCode: res.statusCode } + } else if (forbidOverwrite && res.statusCode === 409) { + throw new Error(`OSS 拒绝覆盖已存在的安装包 ${objectKey}(同版本号换内容必须升版本号;确需原地修复请显式使用 --allow-overwrite): ${res.data}`) } else { throw new Error(`OSS 上传失败 [HTTP ${res.statusCode}]: ${res.data}`) } @@ -290,24 +299,253 @@ export async function readOssObject({ objectKey, accessKeyId, accessKeySecret, b return res.data } +/** + * 探测阿里云 OSS 对象元信息(HEAD 源站),用于识别是否覆盖已有历史安装包。 + * 返回 { exists: true, etag, contentLength } / { exists: false } / { exists: null, statusCode }(探测异常时由上层保守处理)。 + */ +export async function headOssObject({ objectKey, accessKeyId, accessKeySecret, bucket, region, endpoint }) { + const target = endpoint ? new URL(endpoint) : null + const host = target ? target.host : `${bucket}.${region}.aliyuncs.com` + const headers = createOssHeaders({ method: 'HEAD', bucket, objectKey, accessKeyId, accessKeySecret }) + const res = await makeHttpRequest({ + protocol: target ? target.protocol : 'https:', + method: 'HEAD', + hostname: target ? target.hostname : host, + port: target ? target.port : undefined, + path: encodeOssPath(`/${objectKey}`), + headers + }) + if (res.statusCode === 404) { + return { exists: false, statusCode: 404, etag: '', contentLength: 0 } + } + if (res.statusCode >= 200 && res.statusCode < 300) { + const rawEtag = String(res.headers?.etag || '').trim().replace(/^"|"$/g, '').toLowerCase() + const rawLength = Number(res.headers?.['content-length'] || 0) + return { + exists: true, + statusCode: res.statusCode, + etag: rawEtag, + contentLength: Number.isSafeInteger(rawLength) && rawLength >= 0 ? rawLength : 0 + } + } + return { exists: null, statusCode: res.statusCode, etag: '', contentLength: 0 } +} + +const CATALOG_VERSION_REGEX = /^v?(\d+(?:\.\d+)*)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/ + +/** + * 比较两个目录插件版本号(支持点分数字段与 SemVer 预发布段)。 + * 返回 -1 (a < b) / 0 (a === b) / 1 (a > b);任一方格式无法解析时返回 null。 + */ +export function compareCatalogVersions(versionA, versionB) { + const parse = (raw) => { + if (typeof raw !== 'string') return null + const match = raw.trim().match(CATALOG_VERSION_REGEX) + if (!match) return null + const core = match[1].split('.').map((seg) => Number.parseInt(seg, 10)) + if (core.some((n) => !Number.isSafeInteger(n))) return null + const prerelease = match[2] ? match[2].split('.') : [] + return { core, prerelease } + } + const a = parse(versionA) + const b = parse(versionB) + if (!a || !b) return null + + const maxCore = Math.max(a.core.length, b.core.length) + for (let i = 0; i < maxCore; i += 1) { + const diff = (a.core[i] ?? 0) - (b.core[i] ?? 0) + if (diff !== 0) return diff < 0 ? -1 : 1 + } + + // 主版本段一致时:无预发布标签 > 有预发布标签 + if (a.prerelease.length === 0 && b.prerelease.length === 0) return 0 + if (a.prerelease.length === 0) return 1 + if (b.prerelease.length === 0) return -1 + + const maxPre = Math.max(a.prerelease.length, b.prerelease.length) + for (let i = 0; i < maxPre; i += 1) { + if (i >= a.prerelease.length) return -1 + if (i >= b.prerelease.length) return 1 + const segA = a.prerelease[i] + const segB = b.prerelease[i] + if (segA === segB) continue + const numA = /^\d+$/.test(segA) + const numB = /^\d+$/.test(segB) + if (numA && numB) { + return Number.parseInt(segA, 10) < Number.parseInt(segB, 10) ? -1 : 1 + } + if (numA !== numB) return numA ? -1 : 1 + return segA < segB ? -1 : 1 + } + return 0 +} + +/** + * 找出本次发布中版本号低于线上目录的插件(防旧分支/未同步工作区误回退线上目录) + */ +export function findVersionDowngrades(nextCatalog, previousCatalog) { + if (!nextCatalog || !previousCatalog) return [] + const prevById = new Map() + for (const item of catalogEntries(previousCatalog)) { + const id = normalizeCatalogPluginId(item) + if (id && typeof item?.version === 'string' && item.version.trim()) { + prevById.set(id, item) + } + } + const downgrades = [] + for (const item of catalogEntries(nextCatalog)) { + const id = normalizeCatalogPluginId(item) + if (!id || typeof item?.version !== 'string' || !item.version.trim()) continue + const prev = prevById.get(id) + if (!prev) continue + const cmp = compareCatalogVersions(item.version, prev.version) + if (cmp !== null && cmp < 0) { + downgrades.push({ + id, + previousVersion: String(prev.version).trim(), + nextVersion: String(item.version).trim(), + downloadUrl: String(item.downloadUrl || '') + }) + } + } + return downgrades +} + function catalogEntries(catalog) { const list = catalog?.plugins || catalog?.list return Array.isArray(list) ? list : [] } +function normalizeCatalogPluginId(item) { + return String(item?.id || item?.pluginId || '').trim().toLowerCase() +} + +const SAFE_CATALOG_FILENAME_REGEX = /^[a-z0-9][a-z0-9._-]*\.json$/i + +/** + * 解析目标主目录文件名(支持显式指定,未指定时自动识别 catalog.json 或 native-catalog.json) + */ +export function resolveCatalogFileName(indexes = [], explicitCatalogFile = '') { + const trimmed = String(explicitCatalogFile || '').trim() + if (trimmed) { + if (!SAFE_CATALOG_FILENAME_REGEX.test(trimmed)) { + throw new Error(`非法的目录文件名(仅允许单层 .json 文件名): ${trimmed}`) + } + return trimmed + } + const names = new Set(indexes.map((f) => f.relPath)) + if (names.has('catalog.json')) return 'catalog.json' + if (names.has('native-catalog.json')) return 'native-catalog.json' + return 'catalog.json' +} + /** - * 找出「同一个下载地址、内容却变了」的安装包。 - * 安装包按带版本号的文件名强缓存 30 天,改了代码没升版本号时 CDN 仍会返回旧包, - * 客户端校验 SHA-256 不通过就装不上,所以这些地址必须刷新。 + * 按插件 ID 合并线上目录与本地增量目录:保留线上已有条目顺序,原地更新本次变更插件,新增条目追加在末尾 + */ +export function mergeCatalogObjects(previousCatalog, nextCatalog) { + if (!nextCatalog || typeof nextCatalog !== 'object') { + throw new Error('合并目录失败:缺少有效的本地目录对象') + } + if (!previousCatalog || typeof previousCatalog !== 'object') { + return nextCatalog + } + + const mergedList = [] + const indexById = new Map() + const upsert = (item) => { + if (!item || typeof item !== 'object') return + const id = normalizeCatalogPluginId(item) + if (!id) return + if (indexById.has(id)) { + mergedList[indexById.get(id)] = item + } else { + indexById.set(id, mergedList.length) + mergedList.push(item) + } + } + + for (const item of catalogEntries(previousCatalog)) upsert(item) + for (const item of catalogEntries(nextCatalog)) upsert(item) + + return { + ...previousCatalog, + ...nextCatalog, + total: mergedList.length, + list: mergedList, + plugins: mergedList + } +} + +/** + * 找出「同一个下载地址、内容却变了」或「版本号回退到可能仍在 CDN 缓存中的历史地址」的安装包。 + * 安装包按带版本号的文件名强缓存 30 天,改了代码没升版本号或回退到历史版本时 CDN 仍可能返回旧包, + * 客户端校验大小或 SHA-256 不通过就装不上,所以这些地址必须刷新。 * 读不到上一版目录(previousCatalog 为 null)时无法判断,保守地全部刷新。 */ export function findChangedPackageUrls(nextCatalog, previousCatalog, cdnBaseUrl) { const urls = catalogEntries(nextCatalog) - .map((p) => ({ url: String(p?.downloadUrl || ''), sha256: String(p?.sha256 || '') })) + .map((p) => ({ + id: normalizeCatalogPluginId(p), + version: String(p?.version || '').trim(), + url: String(p?.downloadUrl || ''), + sha256: String(p?.sha256 || '') + })) .filter((p) => p.url.startsWith(`${cdnBaseUrl}/`)) if (!previousCatalog) return urls.map((p) => p.url) - const before = new Map(catalogEntries(previousCatalog).map((p) => [String(p?.downloadUrl || ''), String(p?.sha256 || '')])) - return urls.filter((p) => before.has(p.url) && before.get(p.url) !== p.sha256).map((p) => p.url) + const beforeByUrl = new Map() + const beforeById = new Map() + for (const p of catalogEntries(previousCatalog)) { + const url = String(p?.downloadUrl || '') + const sha256 = String(p?.sha256 || '') + const id = normalizeCatalogPluginId(p) + const version = String(p?.version || '').trim() + if (url) beforeByUrl.set(url, sha256) + if (id) beforeById.set(id, { version, url, sha256 }) + } + return urls + .filter((p) => { + if (beforeByUrl.has(p.url) && beforeByUrl.get(p.url) !== p.sha256) { + return true + } + const prev = p.id ? beforeById.get(p.id) : null + if (prev && compareCatalogVersions(p.version, prev.version) === -1) { + return true + } + return false + }) + .map((p) => p.url) +} + +/** + * 找出「下载地址与线上目录相同、SHA-256 却不同」的安装包(同版本号改内容)。 + * 安装包地址带版本号并按 immutable 强缓存,客户端按目录里的大小与 SHA-256 校验; + * 同地址换内容会让目录与安装包在发布中途或 CDN 边缘节点上对不上,导致整批插件装不上, + * 所以默认禁止,改了内容必须升版本号。 + */ +export function findImmutablePackageOverwrites(nextCatalog, previousCatalog) { + if (!nextCatalog || !previousCatalog) return [] + const beforeByUrl = new Map() + for (const p of catalogEntries(previousCatalog)) { + const url = String(p?.downloadUrl || '').trim() + const sha256 = String(p?.sha256 || '').trim().toLowerCase() + if (url && sha256) beforeByUrl.set(url, sha256) + } + const overwrites = [] + for (const p of catalogEntries(nextCatalog)) { + const url = String(p?.downloadUrl || '').trim() + const sha256 = String(p?.sha256 || '').trim().toLowerCase() + const previousSha256 = beforeByUrl.get(url) + if (url && sha256 && previousSha256 && previousSha256 !== sha256) { + overwrites.push({ + id: normalizeCatalogPluginId(p), + version: String(p?.version || '').trim(), + downloadUrl: url, + previousSha256, + nextSha256: sha256 + }) + } + } + return overwrites } /** @@ -401,9 +639,17 @@ function isIndexFile(relPath) { export async function deployPluginsStorage(options = {}) { const distDir = path.resolve(options.dir || path.join(rootDir, 'dist/plugins')) const dryRun = !!options.dryRun + const mergeRemoteCatalog = !!options.mergeRemoteCatalog + const replaceCatalog = !!options.replaceCatalog + const allowDowngrade = !!options.allowDowngrade + const allowOverwrite = !!options.allowOverwrite const cdnBaseUrl = (options.cdnBaseUrl || process.env.CDN_BASE_URL || DEFAULT_CDN_BASE_URL).replace(/\/$/, '') const prefix = normalizePrefix(options.ossPrefix ?? process.env.OSS_PREFIX ?? DEFAULT_OSS_PREFIX) + if (mergeRemoteCatalog && replaceCatalog) { + throw new Error('--merge-catalog 与 --replace-catalog 互斥,不能同时指定') + } + console.log('☁️ 开始上传插件发布产物到阿里云 OSS') console.log(`📂 本地产物目录: ${distDir}`) console.log(`🚀 运行模式: ${dryRun ? '演练模式 (--dry-run)' : '正式上传'}`) @@ -438,8 +684,10 @@ export async function deployPluginsStorage(options = {}) { } const packages = files.filter((f) => !isIndexFile(f.relPath)) const indexes = files.filter((f) => isIndexFile(f.relPath)) + const catalogFile = resolveCatalogFileName(indexes, options.catalogFile) + const catalogObjectKey = prefix ? `${prefix}/${catalogFile}` : catalogFile - // 上传前先从源站读出线上正在用的目录,用来判断哪些安装包内容变了 + // 上传前先从源站读出线上正在用的目录,用来判断哪些安装包内容变了,并支撑增量目录合并与防误覆盖检查 let previousCatalog if (options.previousCatalog !== undefined) { previousCatalog = options.previousCatalog @@ -447,35 +695,179 @@ export async function deployPluginsStorage(options = {}) { previousCatalog = null } else { try { - const raw = await readOssObject({ ...ossConfig, objectKey: prefix ? `${prefix}/catalog.json` : 'catalog.json' }) + const raw = await readOssObject({ ...ossConfig, objectKey: catalogObjectKey }) previousCatalog = raw ? JSON.parse(raw) : null } catch (err) { - console.warn(`⚠️ 读取线上插件目录失败,将刷新全部安装包的 CDN 缓存: ${err.message}`) + if (mergeRemoteCatalog || (!replaceCatalog && catalogFile === 'native-catalog.json')) { + throw new Error(`读取线上 ${catalogObjectKey} 失败,已中止上传以防误覆盖线上目录: ${err.message}`) + } + console.warn(`⚠️ 读取线上插件目录(${catalogObjectKey})失败,将刷新全部安装包的 CDN 缓存: ${err.message}`) previousCatalog = null } } - const nextCatalogFile = indexes.find((f) => f.relPath === 'catalog.json') + const nextCatalogFile = indexes.find((f) => f.relPath === catalogFile) const nextCatalog = nextCatalogFile ? JSON.parse(fs.readFileSync(nextCatalogFile.fullPath, 'utf8')) : null - const changedPackageUrls = findChangedPackageUrls(nextCatalog, previousCatalog, cdnBaseUrl) + + // 防误覆盖保护:上传 native-catalog.json 且线上存在更多插件时,禁止在未显式声明合并或替换的情况下直接整份覆盖 + if (!mergeRemoteCatalog && !replaceCatalog && catalogFile === 'native-catalog.json' && previousCatalog && nextCatalog) { + const nextIds = new Set(catalogEntries(nextCatalog).map(normalizeCatalogPluginId).filter(Boolean)) + const missingIds = catalogEntries(previousCatalog) + .map(normalizeCatalogPluginId) + .filter((id) => id && !nextIds.has(id)) + if (missingIds.length > 0) { + throw new Error( + `拒绝整份覆盖线上 ${catalogFile}:本地目录缺少线上已有的 ${missingIds.length} 个插件(${missingIds.join(', ')})。` + + '单插件增量发布请使用 --merge-catalog,确需全量替换请显式使用 --replace-catalog' + ) + } + } + + // 防版本回退保护:线上已存在更高版本号时,禁止在未显式声明 --allow-downgrade 的情况下回退覆盖 + const versionDowngrades = findVersionDowngrades(nextCatalog, previousCatalog) + if (versionDowngrades.length > 0) { + const summary = versionDowngrades + .map((d) => `${d.id} (${d.previousVersion} -> ${d.nextVersion})`) + .join(', ') + if (!allowDowngrade) { + throw new Error( + `拒绝回退线上 ${catalogFile} 中的 ${versionDowngrades.length} 个插件版本:${summary}。` + + '请先同步最新源码后重新构建发布;确需回滚版本请显式使用 --allow-downgrade' + ) + } + console.warn(`⚠️ 已启用 --allow-downgrade,允许回退 ${versionDowngrades.length} 个插件版本并强制刷新对应 CDN 缓存: ${summary}`) + } + + let effectiveCatalog = nextCatalog + let mergedCatalogBuffer = null + let catalogMerged = false + if (mergeRemoteCatalog && previousCatalog && nextCatalog) { + effectiveCatalog = mergeCatalogObjects(previousCatalog, nextCatalog) + mergedCatalogBuffer = Buffer.from(`${JSON.stringify(effectiveCatalog, null, 2)}\n`, 'utf8') + catalogMerged = true + console.log(`🔀 已将本次 ${catalogEntries(nextCatalog).length} 条插件记录增量合并至线上 ${catalogFile}(合并后共 ${catalogEntries(effectiveCatalog).length} 条)`) + } + + const changedPackageUrlSet = new Set(findChangedPackageUrls(nextCatalog, previousCatalog, cdnBaseUrl)) + // --allow-downgrade 已显式放行的回滚地址,允许重新上传历史版本包 + const downgradeUrls = new Set(allowDowngrade ? versionDowngrades.map((d) => d.downloadUrl) : []) + + // 安装包不可变保护(上传前预检,任何一项不通过都零上传): + // 1. 目录层面:同一下载地址 SHA-256 变了;2. 源站层面:OSS 上已有同名 .zip 且字节不同(覆盖目录未记录的残留包,或目录与包已经对不上) + const catalogOverwrites = findImmutablePackageOverwrites(nextCatalog, previousCatalog) + .filter((o) => !downgradeUrls.has(o.downloadUrl)) + const flaggedUrls = new Set(catalogOverwrites.map((o) => o.downloadUrl)) + const overwriteProblems = catalogOverwrites + .map((o) => `${o.id}@${o.version} 目录 SHA-256 ${o.previousSha256.slice(0, 8)}… -> ${o.nextSha256.slice(0, 8)}…`) + // 源站已有且字节完全相同的安装包不再上传(全量发布时绝大多数包没变,带禁止覆盖头重传会被 OSS 拒绝) + const identicalPackageKeys = new Set() + if (!dryRun) { + for (const file of packages) { + if (!file.relPath.toLowerCase().endsWith('.zip')) continue + const objectKey = prefix ? `${prefix}/${file.relPath}` : file.relPath + const cdnUrl = `${cdnBaseUrl}/${objectKey}` + let existing + try { + existing = await headOssObject({ ...ossConfig, objectKey }) + } catch (err) { + existing = { exists: null, statusCode: 0, error: err.message } + } + if (existing.exists === false) continue + if (existing.exists === null) { + // 无法确认线上同名包是否会被换掉:未显式放行时中止,放行时保守刷新 + if (!allowOverwrite) { + throw new Error( + `探测 OSS 源站对象 ${objectKey} 失败(${existing.error || `HTTP ${existing.statusCode}`}),无法确认是否会覆盖线上安装包,已中止且未上传任何文件` + ) + } + console.warn(`⚠️ 探测 OSS 源站对象 ${objectKey} 失败,已启用 --allow-overwrite,上传后将保守刷新其 CDN 缓存`) + changedPackageUrlSet.add(cdnUrl) + continue + } + const fileBuffer = Buffer.isBuffer(file.buffer) ? file.buffer : fs.readFileSync(file.fullPath) + const isStandardMd5Etag = /^[a-f0-9]{32}$/.test(existing.etag) + let differs + if (isStandardMd5Etag) { + differs = existing.etag !== crypto.createHash('md5').update(fileBuffer).digest('hex') + } else if (existing.contentLength !== fileBuffer.length) { + differs = true + } else { + // 分片上传的 ETag 不是 MD5,大小一致时无法判断内容:未显式放行时中止,放行时覆盖并保守刷新 + if (!allowOverwrite) { + throw new Error( + `OSS 源站对象 ${objectKey} 的 ETag 不是 MD5,无法确认内容是否相同,已中止且未上传任何文件;确认要覆盖请显式使用 --allow-overwrite` + ) + } + console.warn(`⚠️ OSS 源站对象 ${objectKey} 的 ETag 不是 MD5,已启用 --allow-overwrite,覆盖后将保守刷新其 CDN 缓存`) + changedPackageUrlSet.add(cdnUrl) + continue + } + if (!differs) { + identicalPackageKeys.add(objectKey) + continue + } + changedPackageUrlSet.add(cdnUrl) + if (!downgradeUrls.has(cdnUrl) && !flaggedUrls.has(cdnUrl)) { + flaggedUrls.add(cdnUrl) + overwriteProblems.push(`${objectKey} 源站已有不同内容的同名安装包`) + } + } + } + if (overwriteProblems.length > 0) { + if (!allowOverwrite) { + throw new Error( + `拒绝覆盖 ${overwriteProblems.length} 个已发布的安装包(同版本号换内容会让目录与安装包对不上、客户端校验失败):` + + `${overwriteProblems.join(';')}。改了内容请升版本号后重新构建;确需原地修复请显式使用 --allow-overwrite` + ) + } + console.warn(`⚠️ 已启用 --allow-overwrite,允许覆盖 ${overwriteProblems.length} 个已发布安装包并强制刷新其 CDN 缓存: ${overwriteProblems.join(';')}`) + } // 顺序:安装包与图标 → 刷新内容变了的安装包 → 插件目录 → 刷新插件目录 console.log(`\n📤 上传到 OSS 存储桶 ${ossConfig.bucket} (${ossConfig.region}),目录 ${prefix || '/'},共 ${files.length} 个文件`) for (const file of packages) { - await uploadToOss({ file, ...ossConfig, prefix, dryRun }) + const objectKey = prefix ? `${prefix}/${file.relPath}` : file.relPath + if (identicalPackageKeys.has(objectKey)) { + console.log(` ⏭️ 源站已有相同内容,跳过: ${objectKey}`) + continue + } + // .zip 安装包默认带禁止覆盖头;只有显式 --allow-overwrite(或 --allow-downgrade 放行的回滚地址)才允许覆盖 + const objectUrl = `${cdnBaseUrl}/${objectKey}` + const forbidOverwrite = file.relPath.toLowerCase().endsWith('.zip') && !allowOverwrite && !downgradeUrls.has(objectUrl) + await uploadToOss({ file, ...ossConfig, prefix, dryRun, forbidOverwrite }) } + const changedPackageUrls = [...changedPackageUrlSet] + + // 安装包已经传上源站,之后无论 CDN 刷新是否成功都必须把目录传上去,保证源站上目录与安装包一致; + // 刷新失败在目录上传完成后再报错,让流水线标红并提示手动补刷 const refreshTaskIds = [] + let packageRefreshError = null if (changedPackageUrls.length > 0) { console.log(`\n🔄 刷新内容有变化的安装包缓存(${changedPackageUrls.length} 个${previousCatalog ? '' : ',读不到上一版目录,全部刷新'})`) - // 阿里云单次最多提交 100 个地址 - for (let i = 0; i < changedPackageUrls.length; i += 100) { - const r = await refreshAliyunCdnCache({ ...cdnConfig, urls: changedPackageUrls.slice(i, i + 100), endpoint: options.cdnEndpoint, dryRun }) - if (r.refreshTaskId) refreshTaskIds.push(r.refreshTaskId) + try { + // 阿里云单次最多提交 100 个地址 + for (let i = 0; i < changedPackageUrls.length; i += 100) { + const r = await refreshAliyunCdnCache({ ...cdnConfig, urls: changedPackageUrls.slice(i, i + 100), endpoint: options.cdnEndpoint, dryRun }) + if (r.refreshTaskId) refreshTaskIds.push(r.refreshTaskId) + } + } catch (err) { + packageRefreshError = err + console.error(`❌ 安装包 CDN 缓存刷新失败,继续上传插件目录以保持源站一致: ${err.message}`) } } for (const file of indexes) { - await uploadToOss({ file, ...ossConfig, prefix, dryRun }) + const uploadFile = mergedCatalogBuffer && file.relPath === catalogFile + ? { ...file, buffer: mergedCatalogBuffer, size: mergedCatalogBuffer.length } + : file + try { + await uploadToOss({ file: uploadFile, ...ossConfig, prefix, dryRun }) + } catch (err) { + throw new Error( + `插件目录 ${file.relPath} 上传失败,安装包已上传但目录未更新,线上目录与安装包可能对不上,请立即重试本次发布: ${err.message}`, + { cause: err } + ) + } } console.log('✅ OSS 上传完成') @@ -488,6 +880,12 @@ export async function deployPluginsStorage(options = {}) { dryRun }) if (refresh.refreshTaskId) refreshTaskIds.push(refresh.refreshTaskId) + if (packageRefreshError) { + throw new Error( + `插件目录已更新,但 ${changedPackageUrls.length} 个安装包的 CDN 缓存刷新失败,请手动刷新:${changedPackageUrls.join(', ')}(${packageRefreshError.message})`, + { cause: packageRefreshError } + ) + } console.log(`✅ CDN 刷新已提交${refreshTaskIds.length ? `,任务 ID: ${refreshTaskIds.join(', ')}` : ''}`) const refreshUrls = [...changedPackageUrls, ...indexUrls] const ordered = [...packages, ...indexes] @@ -495,7 +893,13 @@ export async function deployPluginsStorage(options = {}) { return { success: true, filesCount: files.length, - uploadedKeys: ordered.map((f) => (prefix ? `${prefix}/${f.relPath}` : f.relPath)), + catalogFile, + catalogMerged, + mergedCatalog: effectiveCatalog, + uploadedKeys: ordered + .map((f) => (prefix ? `${prefix}/${f.relPath}` : f.relPath)) + .filter((key) => !identicalPackageKeys.has(key)), + skippedIdenticalKeys: [...identicalPackageKeys], refreshedUrls: refreshUrls, changedPackageUrls, dryRun @@ -510,11 +914,16 @@ async function runCli() { node scripts/deploy-plugins-storage.mjs [选项] 选项: - --dir 待上传的产物目录 (默认: dist/plugins) - --cdn-base-url CDN 域名 (默认: ${DEFAULT_CDN_BASE_URL}) - --oss-prefix OSS 目录 (默认: ${DEFAULT_OSS_PREFIX}) - --dry-run 演练模式,只打印计划,不发起任何网络请求 - --help, -h 显示帮助信息 + --dir 待上传的产物目录 (默认: dist/plugins) + --catalog-file 主目录文件名 (默认自动探测 catalog.json 或 native-catalog.json) + --merge-catalog 增量合并线上目录后再上传(适用于 --plugins 单插件原生发布) + --replace-catalog 显式允许整份替换线上 native-catalog.json(与 --merge-catalog 互斥) + --allow-downgrade 显式允许回退线上已有插件版本号(并自动刷新对应历史包 CDN 缓存) + --allow-overwrite 显式允许同版本号覆盖已发布的安装包(仅用于紧急原地修复,并强制刷新其 CDN 缓存) + --cdn-base-url CDN 域名 (默认: ${DEFAULT_CDN_BASE_URL}) + --oss-prefix OSS 目录 (默认: ${DEFAULT_OSS_PREFIX}) + --dry-run 演练模式,只打印计划,不发起任何网络请求 + --help, -h 显示帮助信息 环境变量: OSS_ACCESS_KEY_ID, OSS_ACCESS_KEY_SECRET 阿里云 OSS 凭证(必填) @@ -532,6 +941,11 @@ async function runCli() { await deployPluginsStorage({ dir: getArg('--dir', path.join(rootDir, 'dist/plugins')), + catalogFile: getArg('--catalog-file', ''), + mergeRemoteCatalog: args.includes('--merge-catalog'), + replaceCatalog: args.includes('--replace-catalog'), + allowDowngrade: args.includes('--allow-downgrade'), + allowOverwrite: args.includes('--allow-overwrite'), cdnBaseUrl: getArg('--cdn-base-url', process.env.CDN_BASE_URL || DEFAULT_CDN_BASE_URL), ossPrefix: getArg('--oss-prefix', process.env.OSS_PREFIX ?? DEFAULT_OSS_PREFIX), dryRun: args.includes('--dry-run')