Parcourir la source

1. 新增AI重命名功能
2. 新增AI重命名设置页面
3. 准备拆分main.js

soease il y a 1 semaine
Parent
commit
c38b3f12c0

+ 3 - 0
.gitignore

@@ -41,6 +41,9 @@ build/windows/nsis/MicrosoftEdgeWebview2Setup.exe
 build/ios/xcode/overlay.json
 build/ios/xcode/gen/
 
+# --- 可执行文件:所有 .exe 结尾的文件一律不纳入版本库 ---
+*.exe
+
 # --- 系统文件 ---
 Thumbs.db
 .DS_Store

+ 1 - 1
Taskfile.yml

@@ -4,7 +4,7 @@ vars:
   APP_NAME: "腾图工具箱"
   BIN_DIR: "bin"
   PACKAGE_MANAGER: '{{.PACKAGE_MANAGER | default "npm"}}'
-  VITE_PORT: '{{.WAILS_VITE_PORT | default 9245}}'
+  VITE_PORT: '{{.WAILS_VITE_PORT | default 9350}}'
   # Target OS for build/package/run. Defaults to the host OS, and is overridden
   # by `wails3 build GOOS=...` (or the GOOS env var) for cross-compilation. The
   # tasks below dispatch to the matching platform Taskfile via this variable.

+ 9 - 7
apiserver.go

@@ -38,6 +38,11 @@ type notifyRequest struct {
 // mouseAlertRequest 鼠标提醒接口的请求体
 type mouseAlertRequest struct {
 	Text string `json:"text"` // 提示文字,为空时使用默认文案
+	// Width 气泡宽度(px),>0 时覆盖设置中的默认宽度,否则用设置配置
+	Width int `json:"width"`
+	// Scroll 是否滚动显示超长文字;null(缺省)用设置默认(Speed>0 即滚动),
+	// true=超长时水平滚动跑马灯,false=超长部分右侧裁剪不滚动
+	Scroll *bool `json:"scroll"`
 }
 
 // ------------------------------------------------------------------------
@@ -318,7 +323,8 @@ func handleMouseAlert(c *gin.Context) {
 		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
 		return
 	}
-	triggerMouseAlert(req.Text) // 触发鼠标闪烁 + 光标下方透明文字
+	// 触发鼠标闪烁 + 光标下方透明文字;width>0 覆盖宽度、scroll 非 nil 覆盖滚动行为
+	triggerMouseAlertWithOptions(req.Text, req.Width, req.Scroll)
 	c.JSON(http.StatusOK, gin.H{"ok": true})
 }
 
@@ -436,17 +442,13 @@ func handleScreenshot(c *gin.Context) {
 // 下载:GET /api/download/:filename?password=xxx  校验密码后返回文件内容。
 // ------------------------------------------------------------------------
 
-// uploadDirPath 返回上传保存目录:配置为空时回退到用户配置目录下 uploads/。
+// uploadDirPath 返回上传保存目录:配置为空时回退到程序所在目录下的 上传 文件夹。
 func uploadDirPath() string {
 	dir := strings.TrimSpace(loadSettings().UploadDir)
 	if dir != "" {
 		return dir
 	}
-	cfg, err := os.UserConfigDir()
-	if err != nil {
-		return "." // 兜底:当前目录
-	}
-	return filepath.Join(cfg, "TengTuToolbox", "uploads")
+	return filepath.Join(appDir(), "上传")
 }
 
 // checkUploadPassword 校验上传密码(常数时间比较,防时序侧信道)。

BIN
doc/github.png


BIN
doc/个人.png


+ 246 - 0
doc/使用说明.html

@@ -0,0 +1,246 @@
+<!DOCTYPE html>
+<html lang="zh-CN">
+<head>
+<meta charset="UTF-8">
+<meta name="viewport" content="width=device-width, initial-scale=1.0">
+<title>腾图工具箱 · 使用说明</title>
+<style>
+  :root{
+    --bg:#f5f6f8; --card:#ffffff; --text:#1f2430; --muted:#6b7280;
+    --accent:#3b82f6; --accent2:#8b5cf6; --border:#e5e7eb;
+    --code:#f3f4f6; --head:#111827;
+  }
+  *{box-sizing:border-box;margin:0;padding:0}
+  html{scroll-behavior:smooth}
+  body{background:var(--bg);color:var(--text);font-family:"Microsoft YaHei","PingFang SC","Segoe UI",system-ui,sans-serif;line-height:1.7;padding:32px 16px}
+  .wrap{max-width:960px;margin:0 auto}
+  header{text-align:center;padding:28px 0 12px}
+  header h1{font-size:30px;font-weight:700;background:linear-gradient(90deg,var(--accent),var(--accent2));-webkit-background-clip:text;background-clip:text;color:transparent}
+  header p{color:var(--muted);margin-top:6px;font-size:14px}
+  .toc{background:var(--card);border:1px solid var(--border);border-radius:12px;padding:18px 22px;margin:20px 0}
+  .toc h2{font-size:16px;color:var(--head);margin-bottom:10px}
+  .toc ul{list-style:none;display:flex;flex-wrap:wrap;gap:8px 18px}
+  .toc a{color:var(--accent);text-decoration:none;font-size:14px}
+  .toc a:hover{text-decoration:underline}
+  .toc-top{display:inline-block;margin-top:12px;font-size:13px;padding:2px 12px;border:1px solid var(--border);border-radius:14px}
+  section{background:var(--card);border:1px solid var(--border);border-radius:12px;padding:24px 28px;margin:18px 0;scroll-margin-top:20px}
+  section h2{font-size:20px;color:var(--head);margin-bottom:14px;padding-bottom:10px;border-bottom:2px solid var(--border);display:flex;align-items:center;gap:8px}
+  section h3{font-size:16px;color:var(--accent);margin:18px 0 8px}
+  section p{margin:8px 0}
+  section ul,section ol{margin:8px 0 8px 22px}
+  section li{margin:5px 0}
+  code{background:var(--code);padding:2px 6px;border-radius:4px;font-size:13px;font-family:Consolas,monospace}
+  pre{background:var(--code);border:1px solid var(--border);border-radius:8px;padding:12px 14px;margin:10px 0;overflow-x:auto;font-size:13px;line-height:1.6}
+  pre code{background:none;padding:0;font-size:13px}
+  a.xref{color:var(--accent);text-decoration:none;border-bottom:1px dotted var(--accent)}
+  a.xref:hover{border-bottom-style:solid}
+  .imgbox{margin:16px 0;text-align:center}
+  .imgbox img{max-width:100%;border:1px solid var(--border);border-radius:8px;box-shadow:0 4px 14px rgba(0,0,0,.08)}
+  .imgbox figcaption{font-size:13px;color:var(--muted);margin-top:8px}
+  .note{background:#fef9e7;border-left:4px solid #f0c040;padding:10px 14px;border-radius:6px;margin:12px 0;font-size:14px}
+  .tip{background:#eef6ff;border-left:4px solid var(--accent);padding:10px 14px;border-radius:6px;margin:12px 0;font-size:14px}
+  .grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(280px,1fr));gap:12px;margin:12px 0}
+  .card{background:#f9fafb;border:1px solid var(--border);border-radius:8px;padding:14px;font-size:14px;line-height:1.6}
+  .card b{color:var(--head);display:block;margin-bottom:4px;font-size:14.5px}
+  .card .path{display:block;color:var(--muted);font-family:Consolas,monospace;font-size:12.5px;margin-top:2px}
+  .backtop{color:var(--muted);text-decoration:none;font-size:12.5px;border:1px solid var(--border);border-radius:12px;padding:1px 10px;margin-left:auto;font-weight:400}
+  .backtop:hover{color:var(--accent);border-color:var(--accent)}
+  footer{text-align:center;color:var(--muted);font-size:13px;padding:24px 0}
+  @media print{body{background:#fff;padding:0}section{break-inside:avoid}.backtop,.toc-top{display:none}}
+</style>
+</head>
+<body>
+<div class="wrap">
+
+<header id="toc-top">
+  <h1>腾图工具箱 · 使用说明</h1>
+  <p>腾图个人工具箱</p>
+</header>
+
+<nav class="toc" id="toc">
+  <h2>目录</h2>
+  <ul>
+    <li><a href="#source">来源</a></li>
+    <li><a href="#links">网址</a></li>
+    <li><a href="#news">新闻</a></li>
+    <li><a href="#github">Github</a></li>
+    <li><a href="#stock">股市</a></li>
+    <li><a href="#todo">待办</a></li>
+    <li><a href="#record">记录</a></li>
+    <li><a href="#note">笔记</a></li>
+    <li><a href="#tools">工具</a></li>
+    <li><a href="#locals">本地</a></li>
+    <li><a href="#control">控制</a></li>
+    <li><a href="#me">个人</a></li>
+    <li><a href="#service">服务</a></li>
+    <li><a href="#menu">右键快捷菜单</a></li>
+    <li><a href="#settings">设置</a></li>
+    <li><a href="#tag">标签功能</a></li>
+    <li><a href="#diy">自定义页</a></li>
+  </ul>
+</nav>
+
+<section id="source">
+  <h2><a href="#toc-top" class="backtop">顶部</a>来源</h2>
+  <p><b>腾图工具箱</b>最初源于一个很简单的念头:把日常散落在浏览器书签、记事本、桌面快捷方式里的零碎工具,收进一个常驻任务栏、随手可点的窗口里;尽可能减少一些软件驻留。</p>
+  <p>作者平时要频繁打开各类网页(新闻、行情、Github 仓库)、偶尔使用的记录数据,还要在本地电脑上运行一些小工具。这些操作原本要在十几个应用之间切换,时间久了既费时又容易忘。</p>
+  <p>于是就有了这个工具箱——把<b>高频</b>的做成一个个 Tab 面板,把<b>低频</b>的小工具折叠在工具页;把<b>本机应用快捷启动</b>放进托盘菜单中,再加一个<b>内置 API 服务</b>统一对外提供电源、日志、鼠标提醒等接口。整个窗口紧凑常驻,不占地方,想用什么点一下就到。</p>
+  <p>技术上基于 <b>Wails v3</b>(Go 后端 + WebView2 前端),单文件分发、无需安装运行时;数据用 SQLite 本地保存。开发过程中还陆续加入了资源管理器<b>文件/文件夹标签</b>(见<a class="xref" href="#tag">标签功能</a>)、系统级<b>鼠标提醒</b>(见<a class="xref" href="#mouse">鼠标提醒</a>)、句柄<b>右键快捷菜单</b>(见<a class="xref" href="#menu">右键快捷菜单</a>)等功能,让它从一个「自己的小工具」逐渐长成日常顺手的工作台。</p>
+  <p>工具以自用为主,注重<b>简洁</b>、易用、可定制、资源占用少、<b>绿色</b>,每一个文件都清清楚楚。会随着需求变化而迭代。</p>
+</section>
+
+<section id="links">
+  <h2><a href="#toc-top" class="backtop">顶部</a>网址</h2>
+  <p>功能:常用网址卡片,点击卡片在浏览器打开。卡片列表在「<a class="xref" href="#settings">设置 → 网址</a>」中维护(名称 + 地址)。</p>
+  <figure class="imgbox"><img src="网址.png" alt="网址页截图"><figcaption>网址页</figcaption></figure>
+  <ul>
+    <li><b>一键打开</b>:勾选框可全选 / 取消全选,也可自选部分卡片,点「一键打开」批量在浏览器打开;未勾选任何卡片时打开全部。</li>
+    <li><b>层级分组</b>:在「<a class="xref" href="#settings">设置 → 网址</a>」中按缩进层级定义不同类型的网址——顶层无缩进行为分组名,其下缩进的 <code>名称|网址</code> 归入该组;无缩进的条目归为未分组(与「设置 → 快捷」的写法一致)。</li>
+  </ul>
+</section>
+
+<section id="news">
+  <h2><a href="#toc-top" class="backtop">顶部</a>新闻</h2>
+  <p>聚合煎蛋、腾讯、Solidot、财联社与今日热榜(澎湃/知乎/微信/今日头条优先),每条标题标注平台名。</p>
+  <ul>
+    <li>命中「关注关键词」的条目置顶高亮,命中越多排序越靠前、背景色越深。</li>
+    <li>已查看的标题灰显;B 站关注动态 cookie 未配置时回退热门视频并提示。</li>
+    <li>「阅读」按钮朗读未点击过的新闻标题。</li>
+  </ul>
+  <p>关注关键词、刷新间隔、显示条数与 B 站 cookie 在「<a class="xref" href="#settings">设置 → 新闻</a>」配置。</p>
+  <figure class="imgbox"><img src="新闻.png" alt="新闻页截图"><figcaption>新闻页</figcaption></figure>
+</section>
+
+<section id="github">
+  <h2><a href="#toc-top" class="backtop">顶部</a>Github</h2>
+  <p>监听配置仓库的最新提交与 release,本地版本低于最新版时提示更新;下方另显示 GitHub Trending 热门仓库。</p>
+  <figure class="imgbox"><img src="github.png" alt="Github 仓库监控截图"><figcaption>Github 仓库监控</figcaption></figure>
+</section>
+
+<section id="stock">
+  <h2><a href="#toc-top" class="backtop">顶部</a>股市</h2>
+  <p>自选股实时行情,点击行查看分时 / 日K。点击名称可以进入股吧。</p>
+  <p>股票代码、涨/跌颜色与刷新间隔在「<a class="xref" href="#settings">设置 → 股市</a>」配置,休市时自动延长刷新间隔。</p>
+  <figure class="imgbox"><img src="股市.png" alt="股市页截图"><figcaption>股市页</figcaption></figure>
+</section>
+
+<section id="todo">
+  <h2><a href="#toc-top" class="backtop">顶部</a>待办</h2>
+  <p>每行一个待办任务,可勾选完成、编辑、删除。每条可设置提醒时间(<code>@ 时间</code>),到点自动弹出置顶消息窗提醒,即使窗口隐藏也会触发。</p>
+  <div class="tip">文件保存在「<a class="xref" href="#settings">设置 → 待办</a>」的「待办文件路径」,留空时默认为<b>程序所在目录\待办.txt</b>。</div>
+  <figure class="imgbox"><img src="待办.png" alt="待办页截图"><figcaption>待办页</figcaption></figure>
+</section>
+
+<section id="record">
+  <h2><a href="#toc-top" class="backtop">顶部</a>记录</h2>
+  <p>通用的个人信息记录功能。可以记录身高、心率、消费支出等。</p>
+  <div class="tip">数据写入「<a class="xref" href="#settings">设置 → 记录</a>」的「记录数据库路径」SQLite 库,留空时默认为<b>程序所在目录\记录.db</b>;姓名 / 名称输入自动补全历史值。</div>
+  <figure class="imgbox"><img src="记录.png" alt="记录页柱状图截图"><figcaption>记录页柱状图</figcaption></figure>
+</section>
+
+<section id="note">
+  <h2><a href="#toc-top" class="backtop">顶部</a>笔记</h2>
+  <p>这是一个自定义页面,用户可以通过<a href="#settings">设置</a>随意定义网址(这里的页面内容只是一个示例,它是我的个人笔记)。</p>
+  <figure class="imgbox"><img src="笔记.png" alt="笔记页截图"><figcaption>笔记</figcaption></figure>
+</section>
+  
+<section id="tools">
+  <h2><a href="#toc-top" class="backtop">顶部</a>工具</h2>
+  <p>开发/运维辅助工具集,各功能默认折叠,点击标题展开:</p>
+  <ul>
+    <li><b>Web 服务</b>:选择目录开启本地静态文件浏览服务。</li>
+    <li><b>翻译</b>:中英互译</li>
+    <li><b>二维码</b>:任意字符串即时生成 PNG 二维码,可下载。</li>
+    <li><b>ntfy 消息 / 聊天室</b>:推送与订阅 ntfy 主题,跨设备通知/聊天。</li>
+    <li><b>古诗词</b>:查看 footer 随机古诗,手动刷新。</li>
+    <li><b>屏幕截图</b>:自动隐藏窗口截取整个屏幕(不含本程序),完成后预览。</li>
+    <li><b>延时关机</b>:1~1440 分钟后系统关机,可取消。</li>
+    <li><b>MD5 / SHA256</b>:字符串哈希编码。</li>
+    <li><b>LED 滚动文字</b>:中文点阵滚动,独立置顶透明窗口,可调色/速度。</li>
+    <li><b>定时提醒</b>:每隔 xx 分钟弹窗提醒,直到取消。</li>
+    <li><b>LocalSend</b>:局域网互传文件,与官方 v2.3 互通。</li>
+    <li><b>Croc 传送</b>:命令行加密传输(如 PATH 有 croc)。</li>
+    <li><b>视频下载</b>:监视剪贴板 B 站链接,yt-dlp 下载/转 mp3(如 PATH 有 yt-dlp和ffmpeg)。</li>
+    <li><b>Memos 速记</b>:调用 Memos REST API 创建私有备忘。</li>
+    <li><b>显示器设置</b>:逐屏亮度(DDC/CI 优先、Gamma 兜底)、一键息屏。</li>
+  </ul>
+  <figure class="imgbox"><img src="工具.png" alt="工具页截图"><figcaption>工具页</figcaption></figure>
+</section>
+
+<section id="locals">
+  <h2><a href="#toc-top" class="backtop">顶部</a>本地</h2>
+  <p>快捷启动在设置中配置的本机资源/工具:每行「标题|启动程序|说明」。支持可执行文件、脚本(.bat/.cmd/.ps1/.vbs)、PATH 命令,可带参数与 %VAR% 环境变量,分离启动无黑框。</p>
+  <div class="tip">入口在「<a class="xref" href="#settings">设置 → 本地</a>」,与「<a class="xref" href="#menu">右键快捷菜单</a>」使用同一套缩进层级写法:顶层无缩进行为分组名,其下缩进行为条目。</div>
+  <figure class="imgbox"><img src="本地.png" alt="本地页截图"><figcaption>本地页</figcaption></figure>
+</section>
+
+<section id="control">
+  <h2><a href="#toc-top" class="backtop">顶部</a>控制</h2>
+  <p>通过按钮调用接口(它原本用于控制wifi小车,再次思考中)</p>
+  <p>按键可在「<a class="xref" href="#settings">设置 → 控制</a>」配置为自定义命令 URL。</p>
+</section>
+
+<section id="me">
+  <h2><a href="#toc-top" class="backtop">顶部</a>个人</h2>
+  <p>通过设置添加的个人记录文本,可以随手记录杂七杂八的信息。</p>
+  <figure class="imgbox"><img src="个人.png" alt="个人截图"><figcaption>个人</figcaption></figure>
+</section>
+  
+<section id="service">
+  <h2><a href="#toc-top" class="backtop">顶部</a>服务</h2>
+  <p>内置 API 服务状态。配合第三方完成本机的关机等操作。例如通过网络实现一键关机。</p>
+  <div class="tip">程序支持以 Windows 服务方式后台常驻(<code>--service</code>),无需登录即可响应电源类 API,与界面进程共用同一份指令信箱。</div>
+  <figure class="imgbox"><img src="服务.png" alt="服务页截图"><figcaption>服务页</figcaption></figure>
+</section>
+
+<section id="menu">
+  <h2><a href="#toc-top" class="backtop">顶部</a>右键快捷菜单</h2>
+  <p>右键窗口拖动手柄或收拢圆点,弹出快捷启动菜单,可在「<a class="xref" href="#settings">设置 → 快捷</a>」实时构建分组与条目。</p>
+  <figure class="imgbox"><img src="右键快捷菜单.png" alt="右键快捷菜单截图"><figcaption>右键快捷菜单</figcaption></figure>
+</section>
+
+<section id="settings">
+  <h2><a href="#toc-top" class="backtop">顶部</a>设置</h2>
+  <p>入口在标签栏末尾 ☰ 汉堡菜单的最后一项。按「系统 + 各 Tab」分组展示配置项,保存后立即生效,焦点离开输入框自动保存。</p>
+  <ul>
+    <li><b>系统</b>:界面样式(暗/亮)、开机自启、窗口置顶、启动时缩小、呼出窗口热键、全局字号偏移、指定浏览器、<b>启用标签功能</b>、标签数据库路径。</li>
+    <li><b>各 Tab</b>:Tab 显示顺序(<code>[]</code> 折叠进 ☰)、股票代码/刷新、新闻关键词/刷新、Github 仓库、记录库路径、待办路径、B 站 cookie、自定义 Tab 列表。</li>
+    <li><b>滚动文字 / 古诗 / 鼠标提醒 / LED / LocalSend / Croc / 视频下载 / Memos / 显示器 / 服务模式</b>:对应功能参数。</li>
+  </ul>
+  <h3>层级写法</h3>
+  <p>「网址」「本地 / 快捷」三处使用同一套缩进层级格式:顶层无缩进行为分组名,其下缩进(两个及以上空格)的行为该组条目;无缩进的 <code>名称|路径</code> 归入未分组。示例:</p>
+  <pre><code>开发
+  仓库地址|https://github.com/xxx/yyy
+运维
+  Grafana|http://127.0.0.1:3000
+  未分组条目|https://example.com/</code></pre>
+  <figure class="imgbox"><img src="设置.png" alt="设置页截图"><figcaption>设置页</figcaption></figure>
+</section>
+
+<section id="tag">
+  <h2><a href="#toc-top" class="backtop">顶部</a>标签(资源管理器文件/文件夹)</h2>
+  <p>给资源管理器中的文件/文件夹打「标签」与「备注」,鼠标悬停时在光标上方显示。</p>
+  <ul>
+    <li><b>添加/编辑</b>:在资源管理器右键文件或文件夹 → 菜单「标签」→ 弹出编辑窗口,填标签(可空)与备注(可空)→ 保存。存入 SQLite(路径在「<a class="xref" href="#settings">设置 → 系统 → 标签数据库</a>」),按文件完整路径唯一保存。</li>
+    <li><b>查看</b>:鼠标悬停,若已有标签/备注,光标上方浮出气泡,约 2 秒自动消退,移开立即隐藏。</li>
+    <li><b>启用开关</b>:默认启用。设置→系统→「启用标签功能」关闭后删除右键菜单、停止监听悬停;重新打开恢复。</li>
+  </ul>
+</section>
+
+<section id="diy">
+  <h2><a href="#toc-top" class="backtop">顶部</a>自定义页面</h2>
+  <p>通过设置-系统-自定义Tab页面,可以添加自己常用的网站</p>
+  <p>这里是我的一个内容监控页面</p>
+  <figure class="imgbox"><img src="监控.png" alt="设置页截图"><figcaption>自定义页面</figcaption></figure>
+</section>
+
+<figure class="imgbox"><img src="https://i.scwy.net/other/pay_good.jpg" alt="设置页截图"><figcaption>有用你就支持一下</figcaption></figure>
+
+
+<footer>腾图工具箱 · 使用说明 · 生成于 2026-11-19 · <a href="#toc-top">回到顶部</a></footer>
+
+</div>
+</body>
+</html>
+
+

BIN
doc/右键快捷菜单.png


BIN
doc/工具.png


BIN
doc/待办.png


BIN
doc/新闻.png


BIN
doc/服务.png


BIN
doc/本地.png


BIN
doc/监控.png


BIN
doc/笔记.png


BIN
doc/网址.png


BIN
doc/股市.png


BIN
doc/记录.png


BIN
doc/设置.png


+ 80 - 1
explorerservice_windows.go

@@ -23,10 +23,16 @@ var (
 	procGetForegroundWindow      = modUser32.NewProc("GetForegroundWindow")
 	procGetWindowThreadProcessId = modUser32.NewProc("GetWindowThreadProcessId")
 	procGetAncestor              = modUser32.NewProc("GetAncestor")
+	// WindowFromPoint / GetClassNameW:确认鼠标下的窗口是否属于资源管理器窗口
+	// (进程判断不够——任务栏 Shell_TrayWnd 也是 explorer.exe 的窗口)。
+	// 注意:procGetDC/procReleaseDC 已在 mousealert_windows.go 中声明,此处不再重复。
+	procWindowFromPoint = modUser32.NewProc("WindowFromPoint")
+	procGetClassNameW   = modUser32.NewProc("GetClassNameW")
 	// 注意:procGetCursorPos 已在 mousealert_windows.go 中声明,此处不再重复。
 
 	// gaRoot:GA_ROOT = 返回指定窗口的根所有者窗口(顶层窗口)。
-	gaRoot = 2
+	gaRoot   = 2
+	gaParent = 3
 
 	// GetFileAttributesW 在 kernel32.dll(fileExists 检查路径真实存在)。
 	modKernel32B          = syscall.NewLazyDLL("kernel32.dll")
@@ -140,6 +146,71 @@ func isForegroundExplorer() bool {
 	return processName(pid) == "explorer.exe"
 }
 
+// isExplorerFileWindowAt 判断 (x,y) 处的窗口是否位于「资源管理器文件窗口」内。
+//
+// 不能只按前台进程名判断(isForegroundExplorer):explorer.exe 同时拥有任务栏
+// (Shell_TrayWnd / Win11 的 DesktopWindowXamlSource)、桌面(Progman)等窗口,
+// 鼠标停在任务栏上时前台进程名同样是 explorer.exe,于是 COM 命中测试持续执行
+// 却永远拿不到文件项,只会刷出「accHitTest 失败 / get_accValue 失败」日志。
+//
+// 判断两点,缺一不可:
+//  1. 鼠标下窗口的顶层进程必须是 explorer.exe —— 排除 Firefox 等其他程序
+//     (前台检查与 COM 命中之间存在竞态,会误判);
+//  2. 从命中窗口到顶层的祖先链上,任一类名都在「非文件窗口」名单内则拒绝
+//     —— 排除任务栏 / 桌面 / 托盘(它们也是 explorer.exe 的窗口)。
+func isExplorerFileWindowAt(x, y int32) bool {
+	var pt struct{ X, Y int32 }
+	pt.X, pt.Y = x, y
+	hwnd, _, _ := procWindowFromPoint.Call(uintptr(unsafe.Pointer(&pt)))
+	if hwnd == 0 {
+		return false
+	}
+	// 文件列表(FolderView / DirectUIHWND)是深层子窗口,其顶层窗口才是资源管理器
+	// 窗口;任务栏窗口本身即顶层。统一归到顶层判断所属进程。
+	root, _, _ := procGetAncestor.Call(hwnd, uintptr(gaRoot))
+	if root == 0 {
+		root = hwnd
+	}
+	var pid uint32
+	procGetWindowThreadProcessId.Call(root, uintptr(unsafe.Pointer(&pid)))
+	if pid == 0 || processName(pid) != "explorer.exe" {
+		return false
+	}
+	// 沿祖先链检查类名:任务栏子窗口(DesktopWindowXamlSource 等)的 GA_ROOT
+	// 未必是 Shell_TrayWnd,故逐级判定更稳妥。
+	for h := hwnd; h != 0; {
+		if explorerNonFileWindowClasses[windowClassName(h)] {
+			return false
+		}
+		next, _, _ := procGetAncestor.Call(h, uintptr(gaParent))
+		if next == 0 || next == h {
+			break
+		}
+		h = next
+	}
+	return true
+}
+
+// explorerNonFileWindowClasses:explorer.exe 拥有的非文件浏览窗口类名。
+// 这些窗口的进程名同样是 explorer.exe,必须按类名额外排除。
+var explorerNonFileWindowClasses = map[string]bool{
+	"Shell_TrayWnd":              true, // 任务栏主体
+	"DesktopWindowXamlSource":    true, // Win11 任务栏 XAML 实现
+	"Progman":                    true, // 桌面
+	"NotificationAreaWindow":     true, // 通知区域 / 系统托盘
+	"Windows.UI.Core.CoreWindow": true, // Win11 任务栏 / 快捷栏 UWP 宿主
+}
+
+// windowClassName 读取窗口类名(失败返回 "")。
+func windowClassName(hwnd uintptr) string {
+	buf := make([]uint16, maxPath)
+	n, _, _ := procGetClassNameW.Call(hwnd, uintptr(unsafe.Pointer(&buf[0])), maxPath)
+	if n <= 0 {
+		return ""
+	}
+	return syscall.UTF16ToString(buf)
+}
+
 // ========== COM 读取资源管理器选中项 ==========
 
 // initComThread 在 pollLoop 专用 goroutine 上一次性初始化 COM(STA)。
@@ -188,6 +259,14 @@ func readHoveredExplorerItem() (string, bool) {
 		return "", false
 	}
 
+	// 进程判断不够:explorer.exe 同时拥有任务栏(Shell_TrayWnd /
+	// Win11 的 DesktopWindowXamlSource)、桌面(Progman)等窗口,鼠标停在
+	// 任务栏上时前台进程名同样是 explorer.exe,会持续跑无意义的 COM 命中测试。
+	// 这里按窗口类名确认鼠标下的窗口确实是资源管理器文件窗口。
+	if !isExplorerFileWindowAt(x, y) {
+		return "", false
+	}
+
 	// 1+2:MSAA 命中测试,落到具体文件项 IAccessible。
 	// AHK 的 Acc.ElementFromPoint 关键:AccessibleObjectFromPoint 拿到的常是
 	// 容器(childID=0),此时必须再对它调用 accHitTest(x,y) 精确命中文件项,

+ 3 - 0
frontend/bindings/TengTuToolbox/index.js

@@ -10,6 +10,7 @@ import * as LocalService from "./localservice.js";
 import * as MemosService from "./memosservice.js";
 import * as ProxyService from "./proxyservice.js";
 import * as QuickService from "./quickservice.js";
+import * as RenamerService from "./renamerservice.js";
 import * as SettingsService from "./settingsservice.js";
 import * as TagService from "./tagservice.js";
 import * as UDPService from "./udpservice.js";
@@ -23,6 +24,7 @@ export {
     MemosService,
     ProxyService,
     QuickService,
+    RenamerService,
     SettingsService,
     TagService,
     UDPService,
@@ -42,6 +44,7 @@ export {
     CustomTab,
     GitLabConfig,
     KLineBar,
+    LinkGroup,
     LinkItem,
     LocalSendConfig,
     LocalTool,

+ 13 - 0
frontend/bindings/TengTuToolbox/internal/renamer/index.js

@@ -0,0 +1,13 @@
+// @ts-check
+// Cynhyrchwyd y ffeil hon yn awtomatig. PEIDIWCH Â MODIWL
+// This file is automatically generated. DO NOT EDIT
+
+export {
+    Config,
+    FileEntry,
+    History,
+    HistoryItem,
+    Pair,
+    PreviewEntry,
+    ScanResult
+} from "./models.js";

+ 358 - 0
frontend/bindings/TengTuToolbox/internal/renamer/models.js

@@ -0,0 +1,358 @@
+// @ts-check
+// Cynhyrchwyd y ffeil hon yn awtomatig. PEIDIWCH Â MODIWL
+// This file is automatically generated. DO NOT EDIT
+
+// eslint-disable-next-line @typescript-eslint/ban-ts-comment
+// @ts-ignore: Unused imports
+import { Create as $Create } from "@wailsio/runtime";
+
+/**
+ * Config AI 接入商配置(单行存储)。
+ */
+export class Config {
+    /**
+     * Creates a new Config instance.
+     * @param {Partial<Config>} [$$source = {}] - The source object to create the Config.
+     */
+    constructor($$source = {}) {
+        if (!("provider" in $$source)) {
+            /**
+             * openai | ollama
+             * @member
+             * @type {string}
+             */
+            this["provider"] = "";
+        }
+        if (!("baseURL" in $$source)) {
+            /**
+             * @member
+             * @type {string}
+             */
+            this["baseURL"] = "";
+        }
+        if (!("apiKey" in $$source)) {
+            /**
+             * @member
+             * @type {string}
+             */
+            this["apiKey"] = "";
+        }
+        if (!("model" in $$source)) {
+            /**
+             * @member
+             * @type {string}
+             */
+            this["model"] = "";
+        }
+
+        Object.assign(this, $$source);
+    }
+
+    /**
+     * Creates a new Config instance from a string or object.
+     * @param {any} [$$source = {}]
+     * @returns {Config}
+     */
+    static createFrom($$source = {}) {
+        let $$parsedSource = typeof $$source === 'string' ? JSON.parse($$source) : $$source;
+        return new Config(/** @type {Partial<Config>} */($$parsedSource));
+    }
+}
+
+/**
+ * FileEntry 目录扫描结果中的单个文件。
+ */
+export class FileEntry {
+    /**
+     * Creates a new FileEntry instance.
+     * @param {Partial<FileEntry>} [$$source = {}] - The source object to create the FileEntry.
+     */
+    constructor($$source = {}) {
+        if (!("name" in $$source)) {
+            /**
+             * 相对路径(递归时 ToSlash)
+             * @member
+             * @type {string}
+             */
+            this["name"] = "";
+        }
+        if (!("size" in $$source)) {
+            /**
+             * 字节数
+             * @member
+             * @type {number}
+             */
+            this["size"] = 0;
+        }
+        if (!("modTime" in $$source)) {
+            /**
+             * 修改时间 "2006-01-02 15:04"
+             * @member
+             * @type {string}
+             */
+            this["modTime"] = "";
+        }
+
+        Object.assign(this, $$source);
+    }
+
+    /**
+     * Creates a new FileEntry instance from a string or object.
+     * @param {any} [$$source = {}]
+     * @returns {FileEntry}
+     */
+    static createFrom($$source = {}) {
+        let $$parsedSource = typeof $$source === 'string' ? JSON.parse($$source) : $$source;
+        return new FileEntry(/** @type {Partial<FileEntry>} */($$parsedSource));
+    }
+}
+
+/**
+ * History 一次批量重命名的历史记录。
+ */
+export class History {
+    /**
+     * Creates a new History instance.
+     * @param {Partial<History>} [$$source = {}] - The source object to create the History.
+     */
+    constructor($$source = {}) {
+        if (!("id" in $$source)) {
+            /**
+             * @member
+             * @type {number}
+             */
+            this["id"] = 0;
+        }
+        if (!("createdAt" in $$source)) {
+            /**
+             * @member
+             * @type {string}
+             */
+            this["createdAt"] = "";
+        }
+        if (!("dir" in $$source)) {
+            /**
+             * @member
+             * @type {string}
+             */
+            this["dir"] = "";
+        }
+        if (!("count" in $$source)) {
+            /**
+             * @member
+             * @type {number}
+             */
+            this["count"] = 0;
+        }
+        if (!("undone" in $$source)) {
+            /**
+             * 该批次是否已撤回
+             * @member
+             * @type {boolean}
+             */
+            this["undone"] = false;
+        }
+        if (!("details" in $$source)) {
+            /**
+             * @member
+             * @type {HistoryItem[]}
+             */
+            this["details"] = [];
+        }
+
+        Object.assign(this, $$source);
+    }
+
+    /**
+     * Creates a new History instance from a string or object.
+     * @param {any} [$$source = {}]
+     * @returns {History}
+     */
+    static createFrom($$source = {}) {
+        const $$createField5_0 = $$createType1;
+        let $$parsedSource = typeof $$source === 'string' ? JSON.parse($$source) : $$source;
+        if ("details" in $$parsedSource) {
+            $$parsedSource["details"] = $$createField5_0($$parsedSource["details"]);
+        }
+        return new History(/** @type {Partial<History>} */($$parsedSource));
+    }
+}
+
+/**
+ * HistoryItem 单个文件的重命名记录。
+ */
+export class HistoryItem {
+    /**
+     * Creates a new HistoryItem instance.
+     * @param {Partial<HistoryItem>} [$$source = {}] - The source object to create the HistoryItem.
+     */
+    constructor($$source = {}) {
+        if (!("from" in $$source)) {
+            /**
+             * @member
+             * @type {string}
+             */
+            this["from"] = "";
+        }
+        if (!("to" in $$source)) {
+            /**
+             * @member
+             * @type {string}
+             */
+            this["to"] = "";
+        }
+
+        Object.assign(this, $$source);
+    }
+
+    /**
+     * Creates a new HistoryItem instance from a string or object.
+     * @param {any} [$$source = {}]
+     * @returns {HistoryItem}
+     */
+    static createFrom($$source = {}) {
+        let $$parsedSource = typeof $$source === 'string' ? JSON.parse($$source) : $$source;
+        return new HistoryItem(/** @type {Partial<HistoryItem>} */($$parsedSource));
+    }
+}
+
+/**
+ * Pair 一对「旧文件名 → 新文件名」。
+ */
+export class Pair {
+    /**
+     * Creates a new Pair instance.
+     * @param {Partial<Pair>} [$$source = {}] - The source object to create the Pair.
+     */
+    constructor($$source = {}) {
+        if (!("from" in $$source)) {
+            /**
+             * @member
+             * @type {string}
+             */
+            this["from"] = "";
+        }
+        if (!("to" in $$source)) {
+            /**
+             * @member
+             * @type {string}
+             */
+            this["to"] = "";
+        }
+
+        Object.assign(this, $$source);
+    }
+
+    /**
+     * Creates a new Pair instance from a string or object.
+     * @param {any} [$$source = {}]
+     * @returns {Pair}
+     */
+    static createFrom($$source = {}) {
+        let $$parsedSource = typeof $$source === 'string' ? JSON.parse($$source) : $$source;
+        return new Pair(/** @type {Partial<Pair>} */($$parsedSource));
+    }
+}
+
+/**
+ * PreviewEntry AI 预览结果行。
+ */
+export class PreviewEntry {
+    /**
+     * Creates a new PreviewEntry instance.
+     * @param {Partial<PreviewEntry>} [$$source = {}] - The source object to create the PreviewEntry.
+     */
+    constructor($$source = {}) {
+        if (!("from" in $$source)) {
+            /**
+             * @member
+             * @type {string}
+             */
+            this["from"] = "";
+        }
+        if (!("to" in $$source)) {
+            /**
+             * @member
+             * @type {string}
+             */
+            this["to"] = "";
+        }
+        if (!("status" in $$source)) {
+            /**
+             * ok | same | error
+             * @member
+             * @type {string}
+             */
+            this["status"] = "";
+        }
+        if (/** @type {any} */(false)) {
+            /**
+             * @member
+             * @type {string | undefined}
+             */
+            this["reason"] = undefined;
+        }
+
+        Object.assign(this, $$source);
+    }
+
+    /**
+     * Creates a new PreviewEntry instance from a string or object.
+     * @param {any} [$$source = {}]
+     * @returns {PreviewEntry}
+     */
+    static createFrom($$source = {}) {
+        let $$parsedSource = typeof $$source === 'string' ? JSON.parse($$source) : $$source;
+        return new PreviewEntry(/** @type {Partial<PreviewEntry>} */($$parsedSource));
+    }
+}
+
+/**
+ * ScanResult 目录扫描结果。
+ */
+export class ScanResult {
+    /**
+     * Creates a new ScanResult instance.
+     * @param {Partial<ScanResult>} [$$source = {}] - The source object to create the ScanResult.
+     */
+    constructor($$source = {}) {
+        if (!("dir" in $$source)) {
+            /**
+             * 绝对目录路径
+             * @member
+             * @type {string}
+             */
+            this["dir"] = "";
+        }
+        if (!("files" in $$source)) {
+            /**
+             * 文件列表(按名称排序)
+             * @member
+             * @type {FileEntry[]}
+             */
+            this["files"] = [];
+        }
+
+        Object.assign(this, $$source);
+    }
+
+    /**
+     * Creates a new ScanResult instance from a string or object.
+     * @param {any} [$$source = {}]
+     * @returns {ScanResult}
+     */
+    static createFrom($$source = {}) {
+        const $$createField1_0 = $$createType3;
+        let $$parsedSource = typeof $$source === 'string' ? JSON.parse($$source) : $$source;
+        if ("files" in $$parsedSource) {
+            $$parsedSource["files"] = $$createField1_0($$parsedSource["files"]);
+        }
+        return new ScanResult(/** @type {Partial<ScanResult>} */($$parsedSource));
+    }
+}
+
+// Private type creation functions
+const $$createType0 = HistoryItem.createFrom;
+const $$createType1 = $Create.Array($$createType0);
+const $$createType2 = FileEntry.createFrom;
+const $$createType3 = $Create.Array($$createType2);

+ 145 - 61
frontend/bindings/TengTuToolbox/models.js

@@ -161,12 +161,20 @@ export class AppSettings {
         }
         if (!("links" in $$source)) {
             /**
-             * 常用网址列表
+             * 常用网址列表(扁平,未分组;分组请用 LinkGroups)
              * @member
              * @type {LinkItem[]}
              */
             this["links"] = [];
         }
+        if (!("linkGroups" in $$source)) {
+            /**
+             * 「网址」页分组(缩进层级定义,空 Name 表示未分组)
+             * @member
+             * @type {LinkGroup[]}
+             */
+            this["linkGroups"] = [];
+        }
         if (!("newsKeywords" in $$source)) {
             /**
              * 新闻关注关键词,逗号分隔
@@ -273,7 +281,7 @@ export class AppSettings {
         }
         if (!("uploadDir" in $$source)) {
             /**
-             * 文件上传保存目录(空=用户配置目录/uploads)
+             * 文件上传保存目录(空=程序所在目录/上传)
              * @member
              * @type {string}
              */
@@ -487,6 +495,22 @@ export class AppSettings {
              */
             this["brightness"] = (new BrightnessConfig());
         }
+        if (!("footerDocsLabel" in $$source)) {
+            /**
+             * 页面右下角「官方文档」显示的标题文字
+             * @member
+             * @type {string}
+             */
+            this["footerDocsLabel"] = "";
+        }
+        if (!("footerDocsURL" in $$source)) {
+            /**
+             * 页面右下角标题文字点击打开的网址
+             * @member
+             * @type {string}
+             */
+            this["footerDocsURL"] = "";
+        }
         if (!("toolOrder" in $$source)) {
             /**
              * 工具页卡片显示顺序(工具 id 列表,未列出的追加到末尾)
@@ -532,23 +556,24 @@ export class AppSettings {
         const $$createField9_0 = $$createType0;
         const $$createField10_0 = $$createType0;
         const $$createField11_0 = $$createType2;
-        const $$createField15_0 = $$createType4;
+        const $$createField12_0 = $$createType4;
         const $$createField16_0 = $$createType6;
         const $$createField17_0 = $$createType8;
         const $$createField18_0 = $$createType10;
         const $$createField19_0 = $$createType12;
-        const $$createField33_0 = $$createType13;
-        const $$createField34_0 = $$createType13;
-        const $$createField35_0 = $$createType14;
-        const $$createField36_0 = $$createType15;
-        const $$createField47_0 = $$createType16;
-        const $$createField48_0 = $$createType17;
-        const $$createField49_0 = $$createType18;
-        const $$createField50_0 = $$createType19;
-        const $$createField51_0 = $$createType20;
-        const $$createField52_0 = $$createType0;
-        const $$createField53_0 = $$createType21;
-        const $$createField55_0 = $$createType22;
+        const $$createField20_0 = $$createType14;
+        const $$createField34_0 = $$createType15;
+        const $$createField35_0 = $$createType15;
+        const $$createField36_0 = $$createType16;
+        const $$createField37_0 = $$createType17;
+        const $$createField48_0 = $$createType18;
+        const $$createField49_0 = $$createType19;
+        const $$createField50_0 = $$createType20;
+        const $$createField51_0 = $$createType21;
+        const $$createField52_0 = $$createType22;
+        const $$createField55_0 = $$createType0;
+        const $$createField56_0 = $$createType23;
+        const $$createField58_0 = $$createType24;
         let $$parsedSource = typeof $$source === 'string' ? JSON.parse($$source) : $$source;
         if ("tabOrder" in $$parsedSource) {
             $$parsedSource["tabOrder"] = $$createField9_0($$parsedSource["tabOrder"]);
@@ -559,56 +584,59 @@ export class AppSettings {
         if ("links" in $$parsedSource) {
             $$parsedSource["links"] = $$createField11_0($$parsedSource["links"]);
         }
+        if ("linkGroups" in $$parsedSource) {
+            $$parsedSource["linkGroups"] = $$createField12_0($$parsedSource["linkGroups"]);
+        }
         if ("githubRepos" in $$parsedSource) {
-            $$parsedSource["githubRepos"] = $$createField15_0($$parsedSource["githubRepos"]);
+            $$parsedSource["githubRepos"] = $$createField16_0($$parsedSource["githubRepos"]);
         }
         if ("customTabs" in $$parsedSource) {
-            $$parsedSource["customTabs"] = $$createField16_0($$parsedSource["customTabs"]);
+            $$parsedSource["customTabs"] = $$createField17_0($$parsedSource["customTabs"]);
         }
         if ("localTools" in $$parsedSource) {
-            $$parsedSource["localTools"] = $$createField17_0($$parsedSource["localTools"]);
+            $$parsedSource["localTools"] = $$createField18_0($$parsedSource["localTools"]);
         }
         if ("quickGroups" in $$parsedSource) {
-            $$parsedSource["quickGroups"] = $$createField18_0($$parsedSource["quickGroups"]);
+            $$parsedSource["quickGroups"] = $$createField19_0($$parsedSource["quickGroups"]);
         }
         if ("controlKeys" in $$parsedSource) {
-            $$parsedSource["controlKeys"] = $$createField19_0($$parsedSource["controlKeys"]);
+            $$parsedSource["controlKeys"] = $$createField20_0($$parsedSource["controlKeys"]);
         }
         if ("stockTicker" in $$parsedSource) {
-            $$parsedSource["stockTicker"] = $$createField33_0($$parsedSource["stockTicker"]);
+            $$parsedSource["stockTicker"] = $$createField34_0($$parsedSource["stockTicker"]);
         }
         if ("newsTicker" in $$parsedSource) {
-            $$parsedSource["newsTicker"] = $$createField34_0($$parsedSource["newsTicker"]);
+            $$parsedSource["newsTicker"] = $$createField35_0($$parsedSource["newsTicker"]);
         }
         if ("poem" in $$parsedSource) {
-            $$parsedSource["poem"] = $$createField35_0($$parsedSource["poem"]);
+            $$parsedSource["poem"] = $$createField36_0($$parsedSource["poem"]);
         }
         if ("mouseAlert" in $$parsedSource) {
-            $$parsedSource["mouseAlert"] = $$createField36_0($$parsedSource["mouseAlert"]);
+            $$parsedSource["mouseAlert"] = $$createField37_0($$parsedSource["mouseAlert"]);
         }
         if ("localSend" in $$parsedSource) {
-            $$parsedSource["localSend"] = $$createField47_0($$parsedSource["localSend"]);
+            $$parsedSource["localSend"] = $$createField48_0($$parsedSource["localSend"]);
         }
         if ("croc" in $$parsedSource) {
-            $$parsedSource["croc"] = $$createField48_0($$parsedSource["croc"]);
+            $$parsedSource["croc"] = $$createField49_0($$parsedSource["croc"]);
         }
         if ("ytdlp" in $$parsedSource) {
-            $$parsedSource["ytdlp"] = $$createField49_0($$parsedSource["ytdlp"]);
+            $$parsedSource["ytdlp"] = $$createField50_0($$parsedSource["ytdlp"]);
         }
         if ("memos" in $$parsedSource) {
-            $$parsedSource["memos"] = $$createField50_0($$parsedSource["memos"]);
+            $$parsedSource["memos"] = $$createField51_0($$parsedSource["memos"]);
         }
         if ("brightness" in $$parsedSource) {
-            $$parsedSource["brightness"] = $$createField51_0($$parsedSource["brightness"]);
+            $$parsedSource["brightness"] = $$createField52_0($$parsedSource["brightness"]);
         }
         if ("toolOrder" in $$parsedSource) {
-            $$parsedSource["toolOrder"] = $$createField52_0($$parsedSource["toolOrder"]);
+            $$parsedSource["toolOrder"] = $$createField55_0($$parsedSource["toolOrder"]);
         }
         if ("gitLab" in $$parsedSource) {
-            $$parsedSource["gitLab"] = $$createField53_0($$parsedSource["gitLab"]);
+            $$parsedSource["gitLab"] = $$createField56_0($$parsedSource["gitLab"]);
         }
         if ("proxy" in $$parsedSource) {
-            $$parsedSource["proxy"] = $$createField55_0($$parsedSource["proxy"]);
+            $$parsedSource["proxy"] = $$createField58_0($$parsedSource["proxy"]);
         }
         return new AppSettings(/** @type {Partial<AppSettings>} */($$parsedSource));
     }
@@ -703,7 +731,7 @@ export class BiliFeedResult {
      * @returns {BiliFeedResult}
      */
     static createFrom($$source = {}) {
-        const $$createField0_0 = $$createType24;
+        const $$createField0_0 = $$createType26;
         let $$parsedSource = typeof $$source === 'string' ? JSON.parse($$source) : $$source;
         if ("items" in $$parsedSource) {
             $$parsedSource["items"] = $$createField0_0($$parsedSource["items"]);
@@ -747,7 +775,7 @@ export class BrightnessConfig {
      * @returns {BrightnessConfig}
      */
     static createFrom($$source = {}) {
-        const $$createField1_0 = $$createType25;
+        const $$createField1_0 = $$createType27;
         let $$parsedSource = typeof $$source === 'string' ? JSON.parse($$source) : $$source;
         if ("levels" in $$parsedSource) {
             $$parsedSource["levels"] = $$createField1_0($$parsedSource["levels"]);
@@ -1110,6 +1138,51 @@ export class KLineBar {
     }
 }
 
+/**
+ * LinkGroup 「网址」页分组(设置中以缩进层级定义,类似快捷启动)
+ * 未分组的条目放在 LinkGroups 的第一个 Name 为空分组的 Items 中(前端解析时统一按组渲染)
+ */
+export class LinkGroup {
+    /**
+     * Creates a new LinkGroup instance.
+     * @param {Partial<LinkGroup>} [$$source = {}] - The source object to create the LinkGroup.
+     */
+    constructor($$source = {}) {
+        if (!("name" in $$source)) {
+            /**
+             * 分组名(空表示未分组)
+             * @member
+             * @type {string}
+             */
+            this["name"] = "";
+        }
+        if (!("items" in $$source)) {
+            /**
+             * 组内网址
+             * @member
+             * @type {LinkItem[]}
+             */
+            this["items"] = [];
+        }
+
+        Object.assign(this, $$source);
+    }
+
+    /**
+     * Creates a new LinkGroup instance from a string or object.
+     * @param {any} [$$source = {}]
+     * @returns {LinkGroup}
+     */
+    static createFrom($$source = {}) {
+        const $$createField1_0 = $$createType2;
+        let $$parsedSource = typeof $$source === 'string' ? JSON.parse($$source) : $$source;
+        if ("items" in $$parsedSource) {
+            $$parsedSource["items"] = $$createField1_0($$parsedSource["items"]);
+        }
+        return new LinkGroup(/** @type {Partial<LinkGroup>} */($$parsedSource));
+    }
+}
+
 /**
  * LinkItem 常用网址条目
  */
@@ -1353,7 +1426,7 @@ export class MinuteChart {
      * @returns {MinuteChart}
      */
     static createFrom($$source = {}) {
-        const $$createField2_0 = $$createType27;
+        const $$createField2_0 = $$createType29;
         let $$parsedSource = typeof $$source === 'string' ? JSON.parse($$source) : $$source;
         if ("points" in $$parsedSource) {
             $$parsedSource["points"] = $$createField2_0($$parsedSource["points"]);
@@ -1539,6 +1612,15 @@ export class MouseAlertConfig {
              */
             this["outlineWidth"] = 0;
         }
+        if (!("scroll" in $$source)) {
+            /**
+             * Scroll 是否滚动显示超长文字:nil 表示未设置(兼容旧配置,用 Speed>0 决定);
+             * true=超长时水平滚动跑马灯,false=超长部分右侧裁剪不滚动。
+             * @member
+             * @type {boolean | null}
+             */
+            this["scroll"] = null;
+        }
 
         Object.assign(this, $$source);
     }
@@ -1956,7 +2038,7 @@ export class QuickGroup {
      * @returns {QuickGroup}
      */
     static createFrom($$source = {}) {
-        const $$createField1_0 = $$createType29;
+        const $$createField1_0 = $$createType31;
         let $$parsedSource = typeof $$source === 'string' ? JSON.parse($$source) : $$source;
         if ("items" in $$parsedSource) {
             $$parsedSource["items"] = $$createField1_0($$parsedSource["items"]);
@@ -2265,8 +2347,8 @@ export class RepoFeed {
      * @returns {RepoFeed}
      */
     static createFrom($$source = {}) {
-        const $$createField9_0 = $$createType31;
-        const $$createField10_0 = $$createType33;
+        const $$createField9_0 = $$createType33;
+        const $$createField10_0 = $$createType35;
         let $$parsedSource = typeof $$source === 'string' ? JSON.parse($$source) : $$source;
         if ("newer" in $$parsedSource) {
             $$parsedSource["newer"] = $$createField9_0($$parsedSource["newer"]);
@@ -3027,34 +3109,36 @@ export class YTDLPInfo {
 const $$createType0 = $Create.Array($Create.Any);
 const $$createType1 = LinkItem.createFrom;
 const $$createType2 = $Create.Array($$createType1);
-const $$createType3 = RepoItem.createFrom;
+const $$createType3 = LinkGroup.createFrom;
 const $$createType4 = $Create.Array($$createType3);
-const $$createType5 = CustomTab.createFrom;
+const $$createType5 = RepoItem.createFrom;
 const $$createType6 = $Create.Array($$createType5);
-const $$createType7 = LocalTool.createFrom;
+const $$createType7 = CustomTab.createFrom;
 const $$createType8 = $Create.Array($$createType7);
-const $$createType9 = QuickGroup.createFrom;
+const $$createType9 = LocalTool.createFrom;
 const $$createType10 = $Create.Array($$createType9);
-const $$createType11 = ControlKeyConfig.createFrom;
+const $$createType11 = QuickGroup.createFrom;
 const $$createType12 = $Create.Array($$createType11);
-const $$createType13 = TickerConfig.createFrom;
-const $$createType14 = PoemConfig.createFrom;
-const $$createType15 = MouseAlertConfig.createFrom;
-const $$createType16 = LocalSendConfig.createFrom;
-const $$createType17 = CrocConfig.createFrom;
-const $$createType18 = YTDLPConfig.createFrom;
-const $$createType19 = MemosConfig.createFrom;
-const $$createType20 = BrightnessConfig.createFrom;
-const $$createType21 = GitLabConfig.createFrom;
-const $$createType22 = ProxyConfig.createFrom;
-const $$createType23 = BiliDynamicItem.createFrom;
-const $$createType24 = $Create.Array($$createType23);
-const $$createType25 = $Create.Map($Create.Any, $Create.Any);
-const $$createType26 = MinutePoint.createFrom;
-const $$createType27 = $Create.Array($$createType26);
-const $$createType28 = QuickItem.createFrom;
+const $$createType13 = ControlKeyConfig.createFrom;
+const $$createType14 = $Create.Array($$createType13);
+const $$createType15 = TickerConfig.createFrom;
+const $$createType16 = PoemConfig.createFrom;
+const $$createType17 = MouseAlertConfig.createFrom;
+const $$createType18 = LocalSendConfig.createFrom;
+const $$createType19 = CrocConfig.createFrom;
+const $$createType20 = YTDLPConfig.createFrom;
+const $$createType21 = MemosConfig.createFrom;
+const $$createType22 = BrightnessConfig.createFrom;
+const $$createType23 = GitLabConfig.createFrom;
+const $$createType24 = ProxyConfig.createFrom;
+const $$createType25 = BiliDynamicItem.createFrom;
+const $$createType26 = $Create.Array($$createType25);
+const $$createType27 = $Create.Map($Create.Any, $Create.Any);
+const $$createType28 = MinutePoint.createFrom;
 const $$createType29 = $Create.Array($$createType28);
-const $$createType30 = ReleaseItem.createFrom;
+const $$createType30 = QuickItem.createFrom;
 const $$createType31 = $Create.Array($$createType30);
-const $$createType32 = CommitItem.createFrom;
+const $$createType32 = ReleaseItem.createFrom;
 const $$createType33 = $Create.Array($$createType32);
+const $$createType34 = CommitItem.createFrom;
+const $$createType35 = $Create.Array($$createType34);

+ 122 - 0
frontend/bindings/TengTuToolbox/renamerservice.js

@@ -0,0 +1,122 @@
+// @ts-check
+// Cynhyrchwyd y ffeil hon yn awtomatig. PEIDIWCH Â MODIWL
+// This file is automatically generated. DO NOT EDIT
+
+/**
+ * RenamerService 智能重命名服务:扫描目录、AI 预览、执行重命名、历史撤回与 AI 配置。
+ * @module
+ */
+
+// eslint-disable-next-line @typescript-eslint/ban-ts-comment
+// @ts-ignore: Unused imports
+import { Call as $Call, CancellablePromise as $CancellablePromise, Create as $Create } from "@wailsio/runtime";
+
+// eslint-disable-next-line @typescript-eslint/ban-ts-comment
+// @ts-ignore: Unused imports
+import * as renamer$0 from "./internal/renamer/models.js";
+
+/**
+ * ExecuteRename 按预览结果执行真实重命名(逐条校验,失败不影响其他文件)。
+ * @param {string} dir
+ * @param {renamer$0.Pair[]} renames
+ * @returns {$CancellablePromise<{ [_ in string]?: any }>}
+ */
+export function ExecuteRename(dir, renames) {
+    return $Call.ByID(4065469410, dir, renames).then(/** @type {($result: any) => any} */(($result) => {
+        return $$createType0($result);
+    }));
+}
+
+/**
+ * GetAIConfig 读取 AI 接入商配置。
+ * @returns {$CancellablePromise<renamer$0.Config>}
+ */
+export function GetAIConfig() {
+    return $Call.ByID(1934670571).then(/** @type {($result: any) => any} */(($result) => {
+        return $$createType1($result);
+    }));
+}
+
+/**
+ * ListDrives 返回当前主机可用的驱动器/挂载点列表(供前端快速选择目录)。
+ * @returns {$CancellablePromise<string[]>}
+ */
+export function ListDrives() {
+    return $Call.ByID(1303979928).then(/** @type {($result: any) => any} */(($result) => {
+        return $$createType2($result);
+    }));
+}
+
+/**
+ * ListHistory 列出重命名历史(最多 100 条,时间倒序)。
+ * @returns {$CancellablePromise<renamer$0.History[]>}
+ */
+export function ListHistory() {
+    return $Call.ByID(1271448283).then(/** @type {($result: any) => any} */(($result) => {
+        return $$createType4($result);
+    }));
+}
+
+/**
+ * SaveAIConfig 保存 AI 接入商配置。
+ * @param {renamer$0.Config} cfg
+ * @returns {$CancellablePromise<void>}
+ */
+export function SaveAIConfig(cfg) {
+    return $Call.ByID(504549448, cfg);
+}
+
+/**
+ * ScanDir 扫描指定目录下的所有文件(默认只扫当前层,recursive 时递归子目录)。
+ * @param {string} dir
+ * @param {boolean} recursive
+ * @returns {$CancellablePromise<renamer$0.ScanResult>}
+ */
+export function ScanDir(dir, recursive) {
+    return $Call.ByID(2178886743, dir, recursive).then(/** @type {($result: any) => any} */(($result) => {
+        return $$createType5($result);
+    }));
+}
+
+/**
+ * SuggestPreview 用户给出至少 3 个示例,AI 推断规则并返回全部文件的新名称(仅预览,不落盘)。
+ * @param {string} dir
+ * @param {string[]} files
+ * @param {renamer$0.Pair[]} examples
+ * @returns {$CancellablePromise<renamer$0.PreviewEntry[]>}
+ */
+export function SuggestPreview(dir, files, examples) {
+    return $Call.ByID(3935779791, dir, files, examples).then(/** @type {($result: any) => any} */(($result) => {
+        return $$createType7($result);
+    }));
+}
+
+/**
+ * TestAIConfig 测试 AI 服务连通性(不保存配置)。
+ * @param {renamer$0.Config} cfg
+ * @returns {$CancellablePromise<string>}
+ */
+export function TestAIConfig(cfg) {
+    return $Call.ByID(2278522101, cfg);
+}
+
+/**
+ * UndoHistory 撤回一次批量重命名:把该批次中的文件从「新文件名」改回「旧文件名」。
+ * @param {number} id
+ * @returns {$CancellablePromise<{ [_ in string]?: any }>}
+ */
+export function UndoHistory(id) {
+    return $Call.ByID(3026050761, id).then(/** @type {($result: any) => any} */(($result) => {
+        return $$createType0($result);
+    }));
+}
+
+// Private type creation functions
+const $$createType0 = $Create.Map($Create.Any, $Create.Any);
+const $$createType1 = renamer$0.Config.createFrom;
+const $$createType2 = $Create.Array($Create.Any);
+const $$createType3 = renamer$0.History.createFrom;
+const $$createType4 = $Create.Array($$createType3);
+const $$createType5 = renamer$0.ScanResult.createFrom;
+const $$createType6 = renamer$0.PreviewEntry.createFrom;
+const $$createType7 = $Create.Array($$createType6);

+ 172 - 29
frontend/index.html

@@ -43,9 +43,15 @@
 
         <!-- 内容面板 -->
         <div class="tab-content">
-            <!-- 常用网址:设置中配置,点击卡片在浏览器打开 -->
+            <!-- 常用网址:设置中配置(支持分组),点击卡片在浏览器打开;可勾选后一键打开 -->
             <div class="tab-panel active" id="tab-links">
-                <div class="card-grid" id="links-grid"></div>
+                <div class="panel-head links-head">
+                    <div class="panel-head-actions">
+                        <button class="btn-ghost" id="links-select-all" title="全选 / 取消全选所有网址">全选</button>
+                        <button class="btn-primary" id="links-open-selected" title="一键打开已勾选的网址">一键打开</button>
+                    </div>
+                </div>
+                <div class="links-body" id="links-grid"></div>
             </div>
 
             <!-- 新闻:煎蛋 + 热榜(澎湃/知乎/微信/今日头条优先),命中关键词的排在前面并高亮 -->
@@ -57,7 +63,7 @@
                     <div class="panel-head-actions">
                         <span class="github-refresh-time" id="news-refresh-time" title="最后一次成功刷新的时间"></span>
                         <button class="btn-ghost" id="news-read" title="朗读未点击过的新闻标题">阅读</button>
-                        <button class="btn-ghost" id="news-refresh">刷新</button>
+                        <button class="btn-ghost" id="news-refresh"><svg class="btn-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="23 4 23 10 17 10"/><polyline points="1 20 1 14 7 14"/><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"/></svg>刷新</button>
                     </div>
                 </div>
                 <div class="news-list" id="news-list">
@@ -74,7 +80,7 @@
                 <div class="panel-head">
                     <div class="panel-head-actions">
                         <span class="github-refresh-time" id="github-refresh-time" title="最后一次成功刷新的时间"></span>
-                        <button class="btn-ghost" id="github-refresh">刷新</button>
+                        <button class="btn-ghost" id="github-refresh"><svg class="btn-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="23 4 23 10 17 10"/><polyline points="1 20 1 14 7 14"/><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"/></svg>刷新</button>
                     </div>
                 </div>
                 <div class="repo-list" id="repo-list">
@@ -88,7 +94,7 @@
                     <div class="trending-head">
                         <h3 class="trending-title">热门仓库 <span class="trending-sub">GitHub Trending</span></h3>
                         <span class="github-refresh-time" id="trending-refresh-time" title="最后一次成功刷新的时间"></span>
-                        <button class="btn-ghost" id="trending-refresh">刷新</button>
+                        <button class="btn-ghost" id="trending-refresh"><svg class="btn-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="23 4 23 10 17 10"/><polyline points="1 20 1 14 7 14"/><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"/></svg>刷新</button>
                     </div>
                     <div class="trending-list" id="trending-list">
                         <div class="empty-state">
@@ -106,7 +112,7 @@
                     <div class="panel-head-actions">
                         <span class="market-status" id="market-status"><span class="dot"></span>加载中…</span>
                         <span class="github-refresh-time" id="stock-refresh-time" title="最后一次成功刷新的时间"></span>
-                        <button class="btn-ghost" id="stock-refresh">刷新</button>
+                        <button class="btn-ghost" id="stock-refresh"><svg class="btn-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="23 4 23 10 17 10"/><polyline points="1 20 1 14 7 14"/><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"/></svg>刷新</button>
                     </div>
                 </div>
                 <div class="stock-list" id="stock-list">
@@ -158,10 +164,8 @@
                     <div class="record-chart-tooltip" id="record-chart-tooltip" hidden></div>
                     <div class="record-chart-empty" id="record-chart-empty">请先选择姓名,才显示柱状图(可选名称进一步筛选)</div>
                 </div>
-                <!-- 自动补全候选:姓名/名称输入框通过 list 属性引用;随数据库历史值刷新。
-                     必须放在 record-list 容器之外,避免 loadRecords() 的 innerHTML='' 把它们清空 -->
-                <datalist id="record-names-dl"></datalist>
-                <datalist id="record-items-dl"></datalist>
+                <!-- 自动补全候选改为自定义下拉(record-ac,由 JS 动态创建挂到 body),
+                     不再用原生 datalist:与自定义下拉叠加会弹出两套候选(名称出现两个列表提示) -->
                 <div class="record-list" id="record-list"></div>
                 <div class="record-actions">
                     <button class="btn-ghost" id="record-add">添加记录</button>
@@ -315,7 +319,7 @@
                     <div class="tool-card-body">
                         <p class="tool-desc">显示主窗口 footer 最近获取到的古诗词内容,可手动刷新获取新的一首。数据来自古诗词网随机接口。</p>
                         <div class="tool-row tool-actions">
-                            <button class="btn-primary" id="poem-tool-refresh">刷新获取</button>
+                            <button class="btn-primary" id="poem-tool-refresh"><svg class="btn-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="23 4 23 10 17 10"/><polyline points="1 20 1 14 7 14"/><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"/></svg>刷新获取</button>
                             <button class="btn-ghost" id="poem-tool-read">朗读</button>
                             <span class="tool-hint" id="poem-tool-hint"></span>
                         </div>
@@ -532,7 +536,7 @@
                             <span class="tool-hint">正在读取显示器…</span>
                         </div>
                         <div class="tool-row tool-actions">
-                            <button class="btn-ghost" id="brightness-refresh" type="button" title="重新读取各显示器当前亮度">刷新</button>
+                            <button class="btn-ghost" id="brightness-refresh" type="button" title="重新读取各显示器当前亮度"><svg class="btn-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="23 4 23 10 17 10"/><polyline points="1 20 1 14 7 14"/><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"/></svg>刷新</button>
                             <button class="btn-ghost" id="brightness-off" type="button" title="立即关闭所有显示器(移动鼠标或按键即唤醒)">息屏</button>
                             <span class="tool-hint" id="brightness-hint"></span>
                         </div>
@@ -553,6 +557,54 @@
                         </div>
                     </div>
                 </div>
+
+                <!-- 工具:智能重命名——扫描目录,AI 推断命名规律,批量重命名文件 -->
+                <div class="tool-card is-collapsed" data-tool="renamer">
+                    <div class="tool-card-head" role="button" tabindex="0" aria-expanded="false">
+                        <span class="tool-card-title" title="选择目录扫描文件,填至少 3 个「旧名→新名」示例,AI 推断命名规律并预览全部新名称,确认后一键批量重命名;可随时从历史撤回。"><span class="tool-arrow">▸</span><span class="dot"></span>智能重命名</span>
+                        <span class="tool-status" id="renamer-status"></span>
+                        <span class="tool-order-btns"><button class="tool-order-btn tool-up" type="button" title="上移">↑</button><button class="tool-order-btn tool-down" type="button" title="下移">↓</button></span>
+                    </div>
+                    <div class="tool-card-body">
+                        <!-- 目录选择 -->
+                        <div class="tool-row">
+                            <input class="input" id="renamer-dir" type="text" placeholder="要重命名的目录,如 D:\图片" title="选择要扫描的目录">
+                            <button class="btn-ghost" id="renamer-browse" type="button">浏览…</button>
+                            <label class="tool-check"><input type="checkbox" id="renamer-recursive">含子目录</label>
+                            <button class="btn-primary" id="renamer-scan">扫描</button>
+                        </div>
+                        <div class="tool-row" id="renamer-filelist-row" hidden>
+                            <span class="tool-hint" id="renamer-filelist"></span>
+                        </div>
+                        <!-- 文件表格:原文件名(可双击复制到新名)| 新文件名(直接修改,≥3 个作为示例)| 状态 -->
+                        <div class="renamer-table-wrap" id="renamer-table-wrap" hidden>
+                            <table class="renamer-table" id="renamer-table">
+                                <thead>
+                                    <tr>
+                                        <th class="rt-name-head" id="renamer-th-name" title="点击排序:升序 → 降序 → 恢复原始顺序">原文件名 <span class="rt-sort-ind" id="renamer-sort-ind"></span></th>
+                                        <th style="width:40%">新文件名</th>
+                                        <th style="width:150px">状态</th>
+                                    </tr>
+                                </thead>
+                                <tbody id="renamer-table-body"></tbody>
+                            </table>
+                        </div>
+                        <!-- 操作栏:示例计数 + AI 推断 + 执行重命名(按钮紧跟在 AI 推断后面) -->
+                        <div class="tool-row renamer-actions" id="renamer-actions" hidden>
+                            <span class="tool-hint" id="renamer-example-count"></span>
+                            <button class="btn-ghost" id="renamer-reset" type="button" hidden>清空修改</button>
+                            <button class="btn-primary" id="renamer-preview" type="button">✨ AI 推断</button>
+                            <button class="btn-danger" id="renamer-execute" type="button" disabled>执行重命名</button>
+                            <span class="tool-hint" id="renamer-summary"></span>
+                            <span class="tool-hint" id="renamer-preview-status"></span>
+                        </div>
+                        <!-- 历史 -->
+                        <details class="tool-details">
+                            <summary class="tool-summary">历史记录(可撤回)</summary>
+                            <div id="renamer-history"></div>
+                        </details>
+                    </div>
+                </div>
             </div>
 
             <!-- 本地:设置中配置的本地资源/工具,点击卡片启动 -->
@@ -596,7 +648,7 @@
                         <div class="card-title-row">
                             <span class="card-title"><span class="dot"></span>服务模式</span>
                             <button class="btn-ghost" id="service-mode-toggle" type="button" title="启动/停止 Windows 服务(会弹出 UAC 提权确认);运行后未登录也能调用电源 API">启动服务模式</button>
-                            <button class="btn-ghost" id="service-mode-refresh">刷新</button>
+                            <button class="btn-ghost" id="service-mode-refresh"><svg class="btn-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="23 4 23 10 17 10"/><polyline points="1 20 1 14 7 14"/><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"/></svg>刷新</button>
                         </div>
                         <p id="service-mode-status">检查中…</p>
                     </div>
@@ -762,6 +814,15 @@
                         </div>
                     </div>
 
+                    <!-- 右下角标题文字与网址(归入「系统」组):格式「标题|链接」 -->
+                    <div class="setting-row" data-tab-group="system">
+                        <div class="setting-info">
+                            <div class="setting-title">右下角文字</div>
+                            <div class="setting-hint">格式:标题|链接 —— 竖线左侧是右下角显示的文字,右侧是点击打开的网址(默认「官方文档|https://v3.wails.io」);标题留空则隐藏该链接</div>
+                        </div>
+                        <input class="input" id="footer-docs-text" type="text" placeholder="官方文档|https://v3.wails.io" spellcheck="false">
+                    </div>
+
                     <!-- Tab 显示顺序(归入「系统」组) -->
                     <div class="setting-row" data-tab-group="system">
                         <div class="setting-info">
@@ -787,9 +848,9 @@
                     <div class="setting-row" data-tab-group="system">
                         <div class="setting-info">
                             <div class="setting-title">标签数据库</div>
-                            <div class="setting-hint">资源管理器文件/文件夹右键「标签」写入的 SQLite 数据库路径;鼠标悬停文件约 0.3 秒后读取其中的标签与备注并显示在光标上方</div>
+                            <div class="setting-hint">资源管理器文件/文件夹右键「标签」写入的 SQLite 数据库路径;鼠标悬停文件约 0.3 秒后读取其中的标签与备注并显示在光标上方;默认程序所在目录</div>
                         </div>
-                        <input class="input" id="tag-db-path" type="text" placeholder="D:\My\腾图\标签.db">
+                        <input class="input" id="tag-db-path" type="text" placeholder="默认:程序目录\标签.db">
                     </div>
 
                     <!-- 自定义 Tab 页面(归入「系统」组) -->
@@ -891,9 +952,9 @@
                     <div class="setting-row setting-row-col" data-tab-group="links">
                         <div class="setting-info">
                             <div class="setting-title">常用网址</div>
-                            <div class="setting-hint">每行一条,格式:名称|网址,例如 煎蛋|https://jandan.net/</div>
+                            <div class="setting-hint">顶层写分组名,缩进写「名称|网址」;无缩进的「名称|网址」为未分组</div>
                         </div>
-                        <textarea class="input textarea" id="links-text" rows="4" placeholder="名称|网址,每行一条"></textarea>
+                        <textarea class="input textarea" id="links-text" rows="5" placeholder="分组名&#10;  名称|网址&#10;名称|网址"></textarea>
                     </div>
 
                     <!-- 新闻关键词 -->
@@ -1014,9 +1075,9 @@
                     <div class="setting-row" data-tab-group="host">
                         <div class="setting-info">
                             <div class="setting-title">上传保存目录</div>
-                            <div class="setting-hint">上传文件的保存目录,留空则保存到用户配置目录/uploads</div>
+                            <div class="setting-hint">上传文件的保存目录,留空则保存到程序所在目录\上传</div>
                         </div>
-                        <input class="input" id="upload-dir" type="text" placeholder="D:\My\腾图\上传">
+                        <input class="input" id="upload-dir" type="text" placeholder="默认:程序目录\上传">
                     </div>
 
                     <!-- 上传大小上限 -->
@@ -1038,6 +1099,9 @@
                         <input class="input hotkey-input" id="proxyhotkey" readonly placeholder="留空=不设热键">
                     </div>
 
+                    <!-- LocalSend 相关设置(同类归为一个子框) -->
+                    <div class="setting-subgroup" data-tab-group="tools" data-subgroup="localsend">
+                        <div class="setting-subgroup-title">LocalSend 相关</div>
                     <!-- LocalSend 本机名称 -->
                     <div class="setting-row" data-tab-group="tools">
                         <div class="setting-info">
@@ -1068,7 +1132,11 @@
                             <button class="btn-ghost" id="localsend-pickdir" type="button" title="选择接收目录">选择目录</button>
                         </div>
                     </div>
+                    </div><!-- /setting-subgroup localsend -->
 
+                    <!-- Croc 相关设置(同类归为一个子框) -->
+                    <div class="setting-subgroup" data-tab-group="tools" data-subgroup="croc">
+                        <div class="setting-subgroup-title">Croc 相关</div>
                     <!-- Croc 传送密码(发送/接收共用) -->
                     <div class="setting-row croc-setting-row" data-tab-group="tools">
                         <div class="setting-info">
@@ -1089,6 +1157,58 @@
                             <button class="btn-ghost" id="croc-pickdir" type="button" title="选择接收目录">选择目录</button>
                         </div>
                     </div>
+                    </div><!-- /setting-subgroup croc -->
+
+                    <!-- 智能重命名 AI 设置(同类归为一个子框) -->
+                    <div class="setting-subgroup" data-tab-group="tools" data-subgroup="ai">
+                        <div class="setting-subgroup-title">AI重命名</div>
+                    <!-- 接入商类型 -->
+                    <div class="setting-row" data-tab-group="tools">
+                        <div class="setting-info">
+                            <div class="setting-title">接入商类型</div>
+                            <div class="setting-hint">Ollama 本地:无需鉴权,接口地址如 http://localhost:11434;OpenAI 兼容:需 API Key,接口地址如 https://xxx/v1</div>
+                        </div>
+                        <select class="input" id="renamer-provider" style="max-width:200px">
+                            <option value="ollama">Ollama(本地)</option>
+                            <option value="openai">OpenAI 兼容接入商</option>
+                        </select>
+                    </div>
+                    <!-- 接口地址 -->
+                    <div class="setting-row" data-tab-group="tools">
+                        <div class="setting-info">
+                            <div class="setting-title">接口地址</div>
+                            <div class="setting-hint">OpenAI 兼容 Chat Completions 接口地址</div>
+                        </div>
+                        <input class="input" id="renamer-baseurl" type="text" placeholder="http://localhost:11434 或 https://xxx/v1" spellcheck="false">
+                    </div>
+                    <!-- API Key -->
+                    <div class="setting-row" data-tab-group="tools">
+                        <div class="setting-info">
+                            <div class="setting-title">API Key</div>
+                            <div class="setting-hint">本地 Ollama 可空;OpenAI 兼容必填</div>
+                        </div>
+                        <input class="input" id="renamer-apikey" type="password" placeholder="本地 Ollama 可空" autocomplete="new-password" spellcheck="false">
+                    </div>
+                    <!-- 模型名称 -->
+                    <div class="setting-row" data-tab-group="tools">
+                        <div class="setting-info">
+                            <div class="setting-title">模型名称</div>
+                            <div class="setting-hint">用于推断命名规律,如 qwen2.5:7b</div>
+                        </div>
+                        <input class="input" id="renamer-model" type="text" placeholder="qwen2.5:7b" spellcheck="false">
+                    </div>
+                    <!-- 测试连接 -->
+                    <div class="setting-row" data-tab-group="tools">
+                        <div class="setting-info">
+                            <div class="setting-title">测试连接</div>
+                            <div class="setting-hint">验证接入商配置是否可连通(需已保存)</div>
+                        </div>
+                        <div class="browser-path-group">
+                            <button class="btn-ghost" id="renamer-aitest" type="button">测试连接</button>
+                            <span class="tool-hint" id="renamer-aitest-result"></span>
+                        </div>
+                    </div>
+                    </div><!-- /setting-subgroup ai -->
 
                     <!-- 视频下载保存目录 -->
                     <div class="setting-row ytdlp-setting-row" data-tab-group="tools">
@@ -1150,18 +1270,18 @@
                     <div class="setting-row" data-tab-group="todo">
                         <div class="setting-info">
                             <div class="setting-title">待办文件路径</div>
-                            <div class="setting-hint">「待办」标签每行一个任务,保存到该文本文件</div>
+                            <div class="setting-hint">「待办」标签每行一个任务,保存到该文本文件;默认程序所在目录</div>
                         </div>
-                        <input class="input" id="todo-path" type="text" placeholder="D:\My\腾图\待办.txt">
+                        <input class="input" id="todo-path" type="text" placeholder="默认:程序目录\待办.txt">
                     </div>
 
                     <!-- 记录数据库路径 -->
                     <div class="setting-row" data-tab-group="record">
                         <div class="setting-info">
                             <div class="setting-title">记录数据库路径</div>
-                            <div class="setting-hint">「记录」标签全部「姓名|名称|值」保存到该 SQLite 数据库文件;姓名/名称输入自动补全历史值,选择姓名与名称后按值绘柱状图</div>
+                            <div class="setting-hint">「记录」标签全部「姓名|名称|值」保存到该 SQLite 数据库文件;姓名/名称输入自动补全历史值,选择姓名与名称后按值绘柱状图;默认程序所在目录</div>
                         </div>
-                        <input class="input" id="record-db-path" type="text" placeholder="D:\My\腾图\记录.db">
+                        <input class="input" id="record-db-path" type="text" placeholder="默认:程序目录\记录.db">
                     </div>
 
                     <!-- 文本备份目录 -->
@@ -1170,7 +1290,7 @@
                             <div class="setting-title">文本备份目录</div>
                             <div class="setting-hint">文件类自定义 Tab 的「备份」按钮按当前时间备份文件到该目录,文件名带时间戳</div>
                         </div>
-                        <input class="input" id="backup-dir" type="text" placeholder="D:\My\腾图\备份">
+                        <input class="input" id="backup-dir" type="text" placeholder="默认:程序目录\备份">
                     </div>
 
                     <!-- 股票滚动条 -->
@@ -1233,12 +1353,13 @@
                     <div class="setting-row" data-tab-group="host">
                         <div class="setting-info">
                             <div class="setting-title">鼠标提醒</div>
-                            <div class="setting-hint">触发提醒时在鼠标旁浮出透明气泡文字,可调字号、宽度、滚动速度、颜色与描边</div>
+                            <div class="setting-hint">触发提醒时在鼠标旁浮出透明气泡文字,可调字号、宽度、滚动速度、颜色与描边;「滚动显示」控制超长文字水平滚动(关闭时超长部分右侧裁剪)</div>
                         </div>
                         <div class="ticker-controls">
                             <input class="input input-num" id="mouse-alert-size" type="number" min="10" max="48" title="字号 px">
                             <input class="input input-num" id="mouse-alert-width" type="number" min="120" max="1200" title="窗口宽度 px">
                             <input class="input input-num" id="mouse-alert-speed" type="number" min="5" max="300" title="滚动速度 px/s">
+                            <label class="switch" title="滚动显示超长文字(关闭=裁剪)"><input type="checkbox" id="mouse-alert-scroll" checked><span class="switch-track"></span></label>
                             <input class="input-color" id="mouse-alert-color" type="color" title="文字颜色">
                             <input class="input input-num" id="mouse-alert-outline-width" type="number" min="0" max="6" title="文字描边宽度 px(0 关闭)">
                             <input class="input-color" id="mouse-alert-outline-color" type="color" title="文字描边颜色(与文字形成反差)">
@@ -1249,10 +1370,22 @@
 
                 <!-- 保存栏 -->
                 <div class="save-bar">
-                    <button class="btn-primary" id="save-settings">保存设置</button>
+                    <button class="btn-primary" id="save-settings">
+                        <svg class="btn-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"/><polyline points="17 21 17 13 7 13 7 21"/><polyline points="7 3 7 8 15 8"/></svg>
+                        保存设置
+                    </button>
                     <span class="save-status" id="save-status"></span>
-                    <button class="btn-ghost save-bar-extra" id="check-update" type="button">检查更新</button>
-                    <button class="btn-ghost save-bar-extra" id="feedback-open" type="button">意见/建议</button>
+                    <button class="btn-ghost save-bar-extra" id="check-update" type="button">
+                        <svg class="btn-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="23 4 23 10 17 10"/><polyline points="1 20 1 14 7 14"/><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"/></svg>
+                        检查更新
+                    </button>
+                    <!--
+                    <a class="btn-ghost save-bar-extra" id="doc-open" href="https://i.scwy.net/down/toolsbox" data-wml-openURL="https://i.scwy.net/down/toolsbox" target="_blank" rel="noopener">使用说明</a>
+                    -->
+                    <button class="btn-ghost save-bar-extra" id="feedback-open" type="button">
+                        <svg class="btn-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"/></svg>
+                        意见/建议
+                    </button>
                 </div>
             </div>
         </div>
@@ -1327,10 +1460,11 @@
         <span class="footer-version"><span class="dot"></span>腾图工具箱 <span id="footer-version-text"></span></span>
         <div class="footer-desc" id="footer-desc">
             <span class="footer-marquee" id="footer-marquee"></span>
+            <span class="renamer-footer-status" id="renamer-footer-status" hidden></span>
             <button class="poem-read" id="poem-read" title="朗读古诗" hidden>🔊</button>
         </div>
         <span class="footer-time" id="time">--:--:--</span>
-        <a class="footer-docs" data-wml-openURL="https://v3.wails.io" aria-label="Wails documentation">官方文档</a>
+        <a class="footer-docs" id="footer-docs" data-wml-openURL="https://v3.wails.io" aria-label="官方文档">官方文档</a>
     </footer>
 
 <!-- 「更多」Tab 下拉菜单:挂在 body 下,避免被标签栏的 backdrop-filter/overflow 裁剪或压层 -->
@@ -1343,6 +1477,15 @@
         <div class="update-sub" id="update-sub"></div>
         <div class="update-bar"><div class="update-bar-fill" id="update-bar-fill" style="width:0%"></div></div>
         <div class="update-pct" id="update-pct">0%</div>
+        <div class="update-tip-img">
+            <img src="https://i.scwy.net/other/pay_good.jpg" alt="扫码打赏" loading="lazy">
+            <div class="update-tip-text">如果对你有帮助,欢迎扫码打赏</div>
+        </div>
+        <div class="update-poem" id="update-poem" hidden>
+            <div class="update-poem-title"></div>
+            <div class="update-poem-author"></div>           
+            <div class="update-poem-content"></div>
+        </div>
     </div>
 </div>
 

+ 434 - 2
frontend/public/style.css

@@ -589,6 +589,22 @@ body.window-compact #compact-restore span {
     word-break: break-all;
 }
 
+/* 非文本文档只读展示:等宽字体、可滚动、弱化底色 */
+.custom-file-readonly {
+    flex: 1;
+    min-height: 0;
+    overflow: auto;
+    padding: 14px 16px;
+    border: 1px solid var(--glass-border);
+    border-radius: var(--radius);
+    background: var(--glass);
+    color: var(--ink);
+    font-size: calc(15px + var(--font-delta));
+    font-family: "Consolas", "Courier New", monospace;
+    white-space: pre-wrap;
+    word-break: break-word;
+}
+
 @keyframes tabFadeIn {
     from { opacity: 0; transform: translateY(8px); }
     to   { opacity: 1; transform: translateY(0); }
@@ -785,6 +801,27 @@ body.window-compact #compact-restore span {
     margin-top: 0;
 }
 
+/* 工具子组框:把同类工具的若干设置行包进一个带边框的小容器(如 LocalSend、Croc) */
+.setting-subgroup {
+    display: flex;
+    flex-direction: column;
+    gap: 8px;
+    padding: 8px 10px 10px;
+    border: 1px dashed var(--glass-border);
+    border-radius: calc(var(--radius) + 2px);
+    background: rgba(200, 200, 200, 0.4);
+}
+
+/* 子组框标题:小号弱化文字,说明该框聚合的工具名 */
+.setting-subgroup-title {
+    padding: 10px 2px;
+    color: var(--muted);
+    font-size: calc(12.5px + var(--font-delta));
+    font-weight: 600;
+    letter-spacing: 0.4px;
+    user-select: none;
+}
+
 .setting-row {
     display: flex;
     align-items: center;
@@ -998,6 +1035,9 @@ body.window-compact #compact-restore span {
 }
 
 .btn-primary {
+    display: inline-flex;            /* 让内联 SVG 图标与文字横向排列 */
+    align-items: center;
+    gap: 6px;
     height: 34px;
     padding: 0 20px;
     border: none;
@@ -1044,6 +1084,9 @@ body.window-compact #compact-restore span {
 }
 
 .btn-ghost {
+    display: inline-flex;            /* 让内联 SVG 图标与文字横向排列 */
+    align-items: center;
+    gap: 6px;
     height: 30px;
     padding: 0 14px;
     border: 1px solid var(--glass-border);
@@ -1060,6 +1103,14 @@ body.window-compact #compact-restore span {
     border-color: rgba(255, 77, 77, 0.35);
 }
 
+/* 按钮内联图标:currentColor 自动继承按钮文字色(悬停变色时图标同步) */
+.btn-icon {
+    width: 16px;
+    height: 16px;
+    flex-shrink: 0;
+    pointer-events: none;            /* 不拦截按钮点击 */
+}
+
 /* 保存状态提示 */
 .save-status {
     color: var(--muted);
@@ -1355,8 +1406,16 @@ body.window-compact #compact-restore span {
 .save-bar #check-update {
     margin-left: auto;
 }
+.save-bar #doc-open {
+    margin-left: 0; /* 紧贴「检查更新」 */
+    display: inline-flex;
+    align-items: center;
+    justify-content: center;
+    text-decoration: none;
+    line-height: 1;
+}
 .save-bar #feedback-open {
-    margin-left: 0; /* 紧贴「检查更新」,两者形成一组 */
+    margin-left: 0; /* 紧贴「使用说明」,三者形成一组 */
 }
 
 /* --- 升级过程浮层 --- */
@@ -1375,7 +1434,7 @@ body.window-compact #compact-restore span {
     display: none;
 }
 .update-card {
-    width: 360px;
+    width: 420px; /* 加宽:给五言绝句单行显示留足空间 */
     max-width: 86vw;
     padding: 22px 24px;
     border-radius: 14px;
@@ -1413,6 +1472,54 @@ body.window-compact #compact-restore span {
     font-size: calc(12px + var(--font-delta));
     color: var(--muted, #888);
 }
+/* 升级浮层底部的扫码打赏提示:二维码 + 文案 */
+.update-tip-img {
+    margin-top: 16px;
+    text-align: center;
+}
+.update-tip-img img {
+    width: 200px;
+    height: 200px;
+    border-radius: 8px;
+    border: 1px solid rgba(0, 0, 0, 0.1);
+    object-fit: cover;
+}
+.update-tip-text {
+    margin-top: 6px;
+    font-size: calc(12px + var(--font-delta));
+    color: var(--muted, #888);
+}
+/* 升级浮层底部的五言绝句展示 */
+.update-poem {
+    margin-top: 14px;
+    padding: 12px 4px 0;
+    border-top: 1px dashed rgba(0, 0, 0, 0.12);
+    text-align: center;
+    white-space: nowrap;      /* 单行显示,不换行 */
+    overflow: hidden;         /* 超出容器时裁剪,避免文字贴到卡片边缘 */
+}
+.update-poem-title,
+.update-poem-content,
+.update-poem-author {
+    overflow: hidden;
+    text-overflow: clip;      /* 超长时直接裁剪,不出现省略号,保证内容完整可读 */
+}
+.update-poem-title {
+    font-size: calc(14px + var(--font-delta));
+    font-weight: 600;
+    color: var(--text, #222);
+    margin-bottom: 4px;
+}
+.update-poem-content {
+    font-size: calc(13px + var(--font-delta));
+    color: var(--text, #222);
+    line-height: 1.8;
+    margin-bottom: 4px;
+}
+.update-poem-author {
+    font-size: calc(12px + var(--font-delta));
+    color: var(--muted, #888);
+}
 
 /* --- 意见/建议弹窗 --- */
 .feedback-modal {
@@ -1648,6 +1755,22 @@ body.window-compact #compact-restore span {
     display: none;
 }
 
+/* 重命名提示:footer 说明区右侧,与滚动文字并排,不参与滚动 */
+.renamer-footer-status {
+    flex-shrink: 0;
+    max-width: 46%;
+    overflow: hidden;
+    white-space: nowrap;
+    text-overflow: ellipsis;
+    color: var(--muted);
+    opacity: 0.85;
+    margin-left: 10px;
+    --wails-draggable: no-drag;
+}
+.renamer-footer-status[hidden] {
+    display: none;
+}
+
 .footer-version {
     justify-self: start;
     display: inline-flex;
@@ -1681,6 +1804,9 @@ body.window-compact #compact-restore span {
 .footer-docs:hover {
     color: var(--accent);                   /* 悬停变主题红 */
 }
+.footer-docs[hidden] {
+    display: none;                          /* 右下角标题文字留空时隐藏(覆盖上方 inline-flex) */
+}
 
 /* ---------- 常用网址卡片 ---------- */
 .link-card {
@@ -1693,6 +1819,115 @@ body.window-compact #compact-restore span {
     color: var(--accent);
 }
 
+/* 「网址」页:工具条 + 分组容器 */
+.links-head {
+    min-height: auto;
+}
+.links-body {
+    display: flex;
+    flex-direction: column;
+    gap: 14px;
+}
+
+/* 网址分组:组头(组名 + 选择本组按钮)+ 组内卡片网格 */
+.link-group {
+    display: flex;
+    flex-direction: column;
+    gap: 8px;
+}
+.link-group-head {
+    display: flex;
+    align-items: center;
+    justify-content: space-between;
+    gap: 10px;
+}
+.link-group-name {
+    font-size: 13px;
+    font-weight: 600;
+    color: var(--muted);
+    letter-spacing: 0.4px;
+    padding-left: 2px;
+}
+.link-group-name::before {
+    content: '▸ ';
+    color: var(--accent);
+}
+.link-group-name.link-group-unnamed {
+    color: var(--muted);
+    opacity: 0.8;
+}
+.link-group-unnamed::before {
+    content: '◇ ';
+    color: var(--muted);
+}
+.link-group-select {
+    font-size: 12px;
+    padding: 2px 10px;
+    border: 1px solid var(--glass-border);
+    border-radius: 12px;
+    background: var(--glass);
+    color: var(--text);
+    cursor: pointer;
+    transition: background 0.15s ease, border-color 0.15s ease, color 0.15s ease;
+    white-space: nowrap;
+}
+.link-group-select:hover {
+    border-color: var(--accent);
+    color: var(--accent);
+}
+
+/* 卡片勾选框:自定义方框,避免原生样式在暗色下突兀 */
+.link-card {
+    position: relative;
+}
+.link-check {
+    position: absolute;
+    top: 8px;
+    right: 10px;
+    z-index: 1;
+    display: inline-flex;
+    width: 15px;
+    height: 15px;
+    cursor: pointer;
+}
+.link-check input {
+    position: absolute;
+    inset: 0;
+    margin: 0;
+    opacity: 0;
+    cursor: pointer;
+}
+.link-check .box {
+    width: 100%;
+    height: 100%;
+    border: 1px solid var(--glass-border);
+    border-radius: 4px;
+    background: var(--glass);
+    transition: background 0.15s ease, border-color 0.15s ease;
+}
+.link-card.is-checked .link-check .box {
+    background: var(--accent);
+    border-color: var(--accent);
+}
+.link-card.is-checked .link-check .box::after {
+    content: '✓';
+    position: absolute;
+    inset: 0;
+    display: flex;
+    align-items: center;
+    justify-content: center;
+    font-size: 11px;
+    line-height: 1;
+    color: #fff;
+}
+.link-card.is-checked {
+    border-color: var(--accent);
+    background: var(--glass-strong);
+}
+.link-card.is-checked .card-title {
+    color: var(--accent);
+}
+
 /* ---------- 新闻列表 ---------- */
 .news-list {
     display: flex;
@@ -3153,6 +3388,203 @@ a.ver-muted:hover {
     font-size: calc(13.5px + var(--font-delta));
     color: var(--muted);
 }
+/* 智能重命名:AI 设置/历史 折叠区 */
+.tool-details {
+    margin: 10px 0;
+    border: 1px solid var(--border);
+    border-radius: 8px;
+    background: rgba(255, 255, 255, 0.03);
+}
+.tool-summary {
+    padding: 8px 12px;
+    color: var(--accent);
+    font-size: calc(14px + var(--font-delta));
+    font-weight: 600;
+    cursor: pointer;
+    user-select: none;
+    list-style: none;
+}
+.tool-summary::-webkit-details-marker {
+    display: none;
+}
+.tool-summary::before {
+    content: '▸';
+    display: inline-block;
+    margin-right: 8px;
+    color: var(--muted);
+    transition: transform 0.2s;
+}
+.tool-details[open] > .tool-summary::before {
+    transform: rotate(90deg);
+}
+.tool-details > .tool-row {
+    margin: 4px 12px 12px;
+}
+.tool-details > #renamer-history {
+    margin: 4px 12px 12px;
+}
+/* 智能重命名:复选行与示例行 */
+.tool-check {
+    display: inline-flex;
+    align-items: center;
+    gap: 5px;
+    font-size: calc(13.5px + var(--font-delta));
+    color: var(--text);
+    cursor: pointer;
+    white-space: nowrap;
+}
+.tool-check input[type="checkbox"] {
+    accent-color: var(--accent);
+    cursor: pointer;
+}
+.renamer-example-row {
+    display: flex;
+    align-items: center;
+    gap: 6px;
+    margin-bottom: 8px;
+}
+.renamer-example-row .input {
+    flex: 1;
+    min-width: 0;
+}
+.renamer-example-del {
+    flex: none;
+    padding: 2px 8px;
+    font-size: calc(13px + var(--font-delta));
+    color: var(--muted);
+    background: transparent;
+    border: none;
+    cursor: pointer;
+}
+.renamer-example-del:hover {
+    color: var(--danger, #ff4d4f);
+}
+/* 智能重命名:文件表格(扫描后列出所有文件,直接改「新文件名」列) */
+.renamer-table-wrap {
+    max-height: 360px;
+    overflow: auto;
+    border: 1px solid var(--border);
+    border-radius: 8px;
+    margin-bottom: 10px;
+}
+.renamer-table {
+    width: 100%;
+    border-collapse: collapse;
+    font-size: calc(13px + var(--font-delta));
+}
+.renamer-table thead th {
+    position: sticky;
+    top: 0;
+    z-index: 1;
+    padding: 8px 12px;
+    text-align: left;
+    font-weight: 700;
+    color: var(--muted);
+    background: rgba(0, 0, 0, 0.2);
+    border-bottom: 1px solid var(--border);
+    white-space: nowrap;
+}
+.renamer-table .rt-name-head {
+    cursor: pointer;
+    user-select: none;
+}
+.renamer-table .rt-name-head:hover {
+    color: var(--text);
+}
+.rt-sort-ind {
+    display: inline-block;
+    width: 14px;
+    color: var(--text);
+}
+.renamer-table td {
+    padding: 5px 12px;
+    border-bottom: 1px solid var(--border);
+    vertical-align: middle;
+}
+.renamer-table tbody tr:last-child td {
+    border-bottom: none;
+}
+.renamer-row .rn-from {
+    display: block;
+    overflow: hidden;
+    text-overflow: ellipsis;
+    white-space: nowrap;
+    color: var(--muted);
+    max-width: 100%;
+}
+.renamer-row .rn-to {
+    width: 100%;
+    padding: 4px 8px;
+    font-size: calc(13px + var(--font-delta));
+}
+.renamer-row .rn-to:focus {
+    border-color: var(--accent);
+    outline: none;
+}
+.renamer-row.rn-ok .rn-to {
+    border-color: rgba(61, 220, 132, 0.5);
+}
+.renamer-row.rn-error .rn-to {
+    border-color: rgba(255, 77, 79, 0.6);
+}
+.renamer-row .rn-status {
+    display: inline-block;
+    padding: 1px 8px;
+    border-radius: 10px;
+    font-size: calc(12px + var(--font-delta));
+    font-weight: 600;
+}
+.renamer-row .rn-status.st-ok { color: #3ddc84; background: rgba(61, 220, 132, 0.12); }
+.renamer-row .rn-status.st-same { color: var(--muted); background: rgba(128, 128, 128, 0.15); }
+.renamer-row .rn-status.st-error { color: var(--danger, #ff4d4f); background: rgba(255, 77, 79, 0.12); }
+.renamer-row .rn-status.st-pending { color: var(--muted); background: rgba(128, 128, 128, 0.1); }
+.renamer-row .rn-reason {
+    margin-top: 3px;
+    font-size: calc(12px + var(--font-delta));
+    color: var(--danger, #ff4d4f);
+}
+.renamer-actions {
+    flex-wrap: wrap;
+    gap: 10px;
+}
+.renamer-execute-bar {
+    gap: 10px;
+}
+/* 智能重命名:历史记录 */
+.renamer-history-item {
+    margin-bottom: 8px;
+    padding: 8px 12px;
+    border: 1px solid var(--border);
+    border-radius: 8px;
+    background: rgba(255, 255, 255, 0.03);
+}
+.renamer-history-item .rh-meta {
+    display: flex;
+    align-items: center;
+    gap: 8px;
+    font-size: calc(13px + var(--font-delta));
+    color: var(--text);
+}
+.renamer-history-item .rh-dir {
+    flex: 1;
+    overflow: hidden;
+    text-overflow: ellipsis;
+    white-space: nowrap;
+    color: var(--muted);
+    font-size: calc(12px + var(--font-delta));
+}
+.renamer-history-item .rh-undo {
+    flex: none;
+}
+.renamer-history-item .rh-detail {
+    margin-top: 4px;
+    font-size: calc(12px + var(--font-delta));
+    color: var(--muted);
+}
+.renamer-history-empty {
+    font-size: calc(13px + var(--font-delta));
+    color: var(--muted);
+}
 .localsend-config .input {
     flex: 1;
     min-width: 0;

Fichier diff supprimé car celui-ci est trop grand
+ 799 - 46
frontend/src/main.js


+ 1 - 1
frontend/vite.config.js

@@ -5,7 +5,7 @@ import wails from "@wailsio/runtime/plugins/vite";
 export default defineConfig({
   server: {
     host: "127.0.0.1",
-    port: Number(process.env.WAILS_VITE_PORT) || 9245,
+    port: Number(process.env.WAILS_VITE_PORT) || 9350,
     strictPort: true,
   },
   build: {

+ 0 - 125
generate-manifest.ps1

@@ -1,125 +0,0 @@
-<#
-.SYNOPSIS
-    Generate bin/manifest.json - the update manifest for the Wails built-in updater (static-site scheme).
-
-.DESCRIPTION
-    Reads the release package under bin, computes file size and version, and writes the
-    upgrade manifest manifest.json. Upload both the package and manifest to the update site
-    https://i.scwy.net/down/toolsbox/. The manifest must be named manifest.json; the artifact
-    url is just the file name (same directory).
-
-.PARAMETER Exe
-    The release package to generate the manifest for (absolute or relative path).
-    Default: bin\TengTuToolbox-windows-amd64.exe, falling back to bin\TengTuToolbox.exe.
-
-.PARAMETER Version
-    Manifest version. Default: read from AppVersion in settings.go, else the exe version info.
-
-.PARAMETER Notes
-    Release notes (multi-line, use backtick n for newline). Default empty.
-
-.PARAMETER PublishedAt
-    Publish time (ISO 8601 or parseable). Default: now.
-
-.PARAMETER OutFile
-    Output manifest path. Default: bin\manifest.json.
-
-.EXAMPLE
-    .\generate-manifest.ps1
-
-.EXAMPLE
-    .\generate-manifest.ps1 -Version 0.2.0 -Notes "`n- Feature A.`n- Fix B."
-#>
-[CmdletBinding()]
-param(
-    [string]$Exe = "",
-    [string]$Version = "",
-    [string]$Notes = "",
-    [string]$PublishedAt = "",
-    [string]$OutFile = ""
-)
-
-$ErrorActionPreference = 'Stop'
-
-$root = Split-Path -Parent $MyInvocation.MyCommand.Path
-$binDir = Join-Path $root 'bin'
-
-# 1) Resolve the release package
-if (-not $Exe) {
-    $candidate = Join-Path $binDir 'TengTuToolbox-windows-amd64.exe'
-    if (-not (Test-Path $candidate)) {
-        $candidate = Join-Path $binDir 'TengTuToolbox.exe'
-    }
-    if (-not (Test-Path $candidate)) {
-        throw 'Release package not found. Put the installer under bin or pass -Exe.'
-    }
-    $Exe = $candidate
-}
-$exePath = if ([System.IO.Path]::IsPathRooted($Exe)) { $Exe } else { Join-Path (Get-Location) $Exe }
-if (-not (Test-Path $exePath)) {
-    throw "Release package not found: $exePath"
-}
-
-# 2) File name (artifact url = file name, uploaded alongside the manifest)
-$fileName = [System.IO.Path]::GetFileName($exePath)
-$fileSize = (Get-Item $exePath).Length
-
-# 3) Version: -Version first, then AppVersion in settings.go, then exe version info
-if (-not $Version) {
-    $settingsPath = Join-Path $root 'settings.go'
-    if (Test-Path $settingsPath) {
-        $m = Select-String -Path $settingsPath -Pattern 'AppVersion\s*=\s*"([^"]+)"'
-        if ($m) { $Version = $m.Matches[0].Groups[1].Value }
-    }
-}
-if (-not $Version) {
-    $ver = (Get-Item $exePath).VersionInfo
-    $Version = if ($ver.ProductVersion) { $ver.ProductVersion } else { $ver.FileVersion }
-}
-if (-not $Version) { $Version = '0.0.0' }
-
-# 4) Publish time
-if (-not $PublishedAt) {
-    $PublishedAt = (Get-Date).ToString('yyyy-MM-ddTHH:mm:sszzz')
-} else {
-    try { $PublishedAt = ([datetime]$PublishedAt).ToString('yyyy-MM-ddTHH:mm:sszzz') }
-    catch { }
-}
-
-# 5) (Manifest object no longer needed; JSON is built by hand below for stable indentation.)
-
-# 6) Write output
-if (-not $OutFile) { $OutFile = Join-Path $binDir 'manifest.json' }
-
-# Build the JSON by hand for stable 2-space indentation (ConvertTo-Json spacing varies by PS version).
-# Use ConvertTo-Json only to escape individual string values safely.
-function Esc([string]$s) { ($s | ConvertTo-Json -Compress) }
-
-$json = @(
-    '{'
-    '  "schemaVersion": 1,'
-    '  "version": ' + (Esc $Version) + ','
-    '  "name": ' + (Esc 'TengTu Toolbox') + ','
-    '  "notes": ' + (Esc $Notes) + ','
-    '  "publishedAt": ' + (Esc $PublishedAt) + ','
-    '  "artifacts": ['
-    '    {'
-    '      "url": ' + (Esc $fileName) + ','
-    '      "filename": ' + (Esc $fileName) + ','
-    '      "platform": "windows",'
-    '      "arch": "amd64",'
-    '      "size": ' + $fileSize
-    '    }'
-    '  ]'
-    '}'
-) -join "`r`n"
-
-# Write without BOM (Go's json.Unmarshal rejects a UTF-8 BOM). PS5.1's Out-File -Encoding utf8 adds BOM.
-[System.IO.File]::WriteAllText($OutFile, $json, (New-Object System.Text.UTF8Encoding($false)))
-
-Write-Host "Generated update manifest: $OutFile"
-Write-Host "  Package    : $fileName ($fileSize bytes)"
-Write-Host "  Version    : $Version"
-Write-Host "  PublishedAt: $PublishedAt"
-Write-Host ""
-Write-Host "Upload $fileName and manifest.json to https://i.scwy.net/down/toolsbox/"

+ 286 - 0
internal/ai/ai.go

@@ -0,0 +1,286 @@
+// Package ai 封装 AI 调用:兼容 OpenAI Chat Completions 协议的自定义接入商与本地 Ollama。
+// 本包为纯逻辑(无框架 / 数据库依赖),从原「文件重命名」项目移植,供智能重命名服务复用。
+package ai
+
+import (
+	"bytes"
+	"context"
+	"encoding/json"
+	"errors"
+	"fmt"
+	"io"
+	"log"
+	"net/http"
+	"os"
+	"regexp"
+	"strings"
+	"time"
+
+	"TengTuToolbox/internal/renamer"
+)
+
+// Pair 一对「旧文件名 → 新文件名」。
+type Pair = renamer.Pair
+
+const systemPrompt = `你是一个文件批量重命名助手。用户会给出某个目录下的文件列表,以及其中若干个"旧文件名 → 新文件名"的重命名示例。请推断示例背后的命名规律,为列表中的文件生成新文件名。
+
+必须严格遵守以下规则:
+1. 只输出一个 JSON 对象,不要输出任何解释文字,也不要使用 markdown 代码块标记。
+   格式:{"原文件名":"新文件名","另一个原文件名":"另一个新文件名"}
+2. 键必须从文件列表中原样复制,一字不差;值是对应文件的新文件名。
+3. 只输出命名会发生变化的文件;名字保持不变的文件不要出现在结果中。
+4. 严禁修改文件的扩展名(文件名最后一个点之后的部分必须保持原样)。
+5. 新文件名中不得出现 \ / : * ? " < > | 等字符,也不能以空格或点结尾。`
+
+// batchSize 单次请求发给模型的文件数上限。批次过大会导致小模型输出中途「重新数数」造成
+// 文件名错位,实测 50 个就会漂移,缩小到 20 并配合按文件名作键的输出可从结构上避免错位。
+const batchSize = 20
+
+// versionSuffixRe 匹配以版本号或 openai 兼容段结尾的 Base URL,
+// 如 https://xxx/v1、https://open.bigmodel.cn/api/paas/v4、Gemini 的 .../v1beta/openai
+var versionSuffixRe = regexp.MustCompile(`/v\d+\w*$|/openai$`)
+
+// endpoint 将用户填写的 Base URL 规范化为完整的 chat/completions 地址。
+// 兼容:http://localhost:11434(Ollama)、https://xxx/v1、https://open.bigmodel.cn/api/paas/v4 等。
+func endpoint(baseURL string) string {
+	u := strings.TrimRight(strings.TrimSpace(baseURL), "/")
+	if u == "" {
+		u = "http://localhost:11434"
+	}
+	switch {
+	case strings.HasSuffix(u, "/chat/completions"):
+		return u
+	case strings.HasSuffix(u, "/v1") || versionSuffixRe.MatchString(u):
+		return u + "/chat/completions"
+	default:
+		return u + "/v1/chat/completions"
+	}
+}
+
+type chatMessage struct {
+	Role    string `json:"role"`
+	Content string `json:"content"`
+}
+
+type chatRequest struct {
+	Model       string        `json:"model"`
+	Messages    []chatMessage `json:"messages"`
+	Temperature float64       `json:"temperature"`
+	MaxTokens   int           `json:"max_tokens"` // 显式放宽输出上限,防止长列表被默认值截断
+	Stream      bool          `json:"stream"`
+}
+
+type chatResponse struct {
+	Choices []struct {
+		Message struct {
+			Content string `json:"content"`
+		} `json:"message"`
+	} `json:"choices"`
+	Error *struct {
+		Message string `json:"message"`
+	} `json:"error"`
+}
+
+func chat(ctx context.Context, cfg renamer.Config, userPrompt string) (string, error) {
+	if strings.TrimSpace(cfg.BaseURL) == "" || strings.TrimSpace(cfg.Model) == "" {
+		return "", errors.New("尚未配置 AI 接入商,请先点击「AI 设置」完成配置")
+	}
+	payload, _ := json.Marshal(chatRequest{
+		Model: cfg.Model,
+		Messages: []chatMessage{
+			{Role: "system", Content: systemPrompt},
+			{Role: "user", Content: userPrompt},
+		},
+		Temperature: 0.1,
+		MaxTokens:   4095, // glm-4-flash 等模型的最大输出上限,各主流接入商均可接受
+	})
+	url := endpoint(cfg.BaseURL)
+	req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(payload))
+	if err != nil {
+		return "", err
+	}
+	req.Header.Set("Content-Type", "application/json")
+	if cfg.APIKey != "" {
+		req.Header.Set("Authorization", "Bearer "+cfg.APIKey)
+	}
+	// 本地模型(尤其 CPU 推理)可能很慢,放宽超时到 10 分钟
+	client := &http.Client{Timeout: 10 * time.Minute}
+	resp, err := client.Do(req)
+	if err != nil {
+		if errors.Is(err, context.DeadlineExceeded) || os.IsTimeout(err) {
+			return "", errors.New("AI 服务响应超时(已等待 10 分钟)。建议:换用更小的模型、减少单次处理的文件数量,或确认模型服务是否正常")
+		}
+		return "", fmt.Errorf("无法连接 AI 服务(%s): %w", url, err)
+	}
+	defer resp.Body.Close()
+	data, err := io.ReadAll(io.LimitReader(resp.Body, 8<<20))
+	if err != nil {
+		return "", fmt.Errorf("读取 AI 服务响应失败: %w", err)
+	}
+	var cr chatResponse
+	if json.Unmarshal(data, &cr) == nil && cr.Error != nil && cr.Error.Message != "" {
+		return "", fmt.Errorf("AI 服务返回错误: %s", cr.Error.Message)
+	}
+	if resp.StatusCode != http.StatusOK {
+		return "", fmt.Errorf("AI 服务返回 HTTP %d: %s", resp.StatusCode, truncate(string(data), 300))
+	}
+	if err := json.Unmarshal(data, &cr); err != nil {
+		return "", fmt.Errorf("AI 服务响应解析失败: %s", truncate(string(data), 300))
+	}
+	if len(cr.Choices) == 0 || strings.TrimSpace(cr.Choices[0].Message.Content) == "" {
+		return "", errors.New("AI 未返回任何内容")
+	}
+	return cr.Choices[0].Message.Content, nil
+}
+
+// Test 测试 AI 服务连通性。
+func Test(ctx context.Context, cfg renamer.Config) (string, error) {
+	if _, err := chat(ctx, cfg, "这是一次连通性测试,请只回复两个字母:OK"); err != nil {
+		return "", err
+	}
+	return fmt.Sprintf("连接成功,模型 %s 已正常响应", cfg.Model), nil
+}
+
+// Suggest 根据重命名示例推断命名规律,为全部文件生成新名称。
+// 文件数超过 batchSize 时自动分批请求,避免模型输出被 max_tokens 截断。
+func Suggest(ctx context.Context, cfg renamer.Config, examples []Pair, files []string) ([]Pair, error) {
+	out := make([]Pair, 0, len(files))
+	for start := 0; start < len(files); start += batchSize {
+		end := start + batchSize
+		if end > len(files) {
+			end = len(files)
+		}
+		names, err := suggestBatch(ctx, cfg, examples, files[start:end])
+		if err != nil {
+			return nil, err
+		}
+		for i, to := range names {
+			out = append(out, Pair{From: files[start+i], To: to})
+		}
+	}
+	// 二次确认:长列表会稀释模型注意力,个别文件被漏报或误判为「保持原名」。
+	// 把这些文件单独组成小批量再问一次(批量小、注意力集中,漏报率极低):
+	// 若模型这次给出新名则采纳,仍保持原名则视为命名规律确实不适用。
+	var rest []int
+	for i := range out {
+		if out[i].To == out[i].From {
+			rest = append(rest, i)
+		}
+	}
+	if len(rest) > 0 && len(rest) < len(files) {
+		batch := make([]string, len(rest))
+		for i, idx := range rest {
+			batch[i] = out[idx].From
+		}
+		if names, err := suggestBatch(ctx, cfg, examples, batch); err != nil {
+			log.Printf("AI 二次确认失败(保留首轮结果): %v", err)
+		} else {
+			recovered := 0
+			for i, idx := range rest {
+				if names[i] != out[idx].From {
+					recovered++
+				}
+				out[idx].To = names[i]
+			}
+			if recovered > 0 {
+				log.Printf("AI 二次确认补回 %d 个漏报文件", recovered)
+			}
+		}
+	}
+	return out, nil
+}
+
+// suggestBatch 对一批文件发起单次 AI 请求,返回与该批文件一一对应的新文件名。
+// 模型按「原文件名 → 新文件名」作键输出,未出现的文件视为保持原名;
+// 键不在本批文件列表中说明模型漂移(复述错文件名),自动重试一次后仍失败则报错。
+func suggestBatch(ctx context.Context, cfg renamer.Config, examples []Pair, batch []string) ([]string, error) {
+	var b strings.Builder
+	b.WriteString("重命名示例(旧文件名 → 新文件名):\n")
+	for _, p := range examples {
+		fmt.Fprintf(&b, "%s → %s\n", p.From, p.To)
+	}
+	fmt.Fprintf(&b, "\n目录中的全部文件(共 %d 个):\n", len(batch))
+	for _, f := range batch {
+		fmt.Fprintf(&b, "- %s\n", f)
+	}
+	var lastErr error
+	for attempt := 0; attempt < 2; attempt++ { // 漂移/解析失败自动重试一次
+		content, err := chat(ctx, cfg, b.String())
+		if err != nil {
+			return nil, err
+		}
+		m, err := parseNameMap(content)
+		if err != nil {
+			lastErr = err
+			continue
+		}
+		// 键校验:以「原文件名」为锚,输出键必须能对上本批文件(容忍首尾空白差异)。
+		// 模型偶尔会把示例里的文件名回显进结果——这些键不在本批,直接丢弃即可(安全:
+		// 结果按文件名对齐,丢弃只影响该文件保持原名,绝不会错改其它文件)。
+		// 仅当绝大多数键都无效(模型严重混乱)时才重试。
+		inBatch := make(map[string]bool, len(batch))
+		for _, f := range batch {
+			inBatch[f] = true
+		}
+		kept := make(map[string]string, len(m))
+		foreign := 0
+		for k, v := range m {
+			ck := strings.TrimSpace(k)
+			if inBatch[k] {
+				kept[k] = v
+			} else if inBatch[ck] {
+				kept[ck] = v
+			} else {
+				foreign++
+			}
+		}
+		if len(kept) == 0 || foreign > len(kept) {
+			lastErr = fmt.Errorf("AI 输出与文件列表严重不匹配(模型漂移),%d 个键中 %d 个无效,已自动重试仍失败,请再试一次", len(m), foreign)
+			continue
+		}
+		if foreign > 0 {
+			log.Printf("AI 输出包含 %d 个无效键(多为示例文件回显),已忽略", foreign)
+		}
+		// 按原文件名对齐:结果中缺失的文件保持原名
+		names := make([]string, len(batch))
+		for i, orig := range batch {
+			if v, ok := kept[orig]; ok && strings.TrimSpace(v) != "" {
+				names[i] = v
+			} else {
+				names[i] = orig
+			}
+		}
+		return names, nil
+	}
+	return nil, lastErr
+}
+
+// parseNameMap 从模型输出中提取「原文件名 → 新文件名」的 JSON 对象(容忍 markdown 代码块等噪声)。
+func parseNameMap(content string) (map[string]string, error) {
+	s := strings.TrimSpace(content)
+	s = strings.TrimPrefix(s, "```json")
+	s = strings.TrimPrefix(s, "```")
+	s = strings.TrimSuffix(s, "```")
+	s = strings.TrimSpace(s)
+	start := strings.Index(s, "{")
+	end := strings.LastIndex(s, "}")
+	if start < 0 || end <= start {
+		return nil, fmt.Errorf("AI 返回的内容无法解析:%s", truncate(content, 300))
+	}
+	var m map[string]string
+	if err := json.Unmarshal([]byte(s[start:end+1]), &m); err != nil {
+		return nil, fmt.Errorf("AI 返回的 JSON 格式有误: %w", err)
+	}
+	if len(m) == 0 {
+		return nil, errors.New("AI 返回了空结果,请重试")
+	}
+	return m, nil
+}
+
+func truncate(s string, n int) string {
+	r := []rune(s)
+	if len(r) <= n {
+		return s
+	}
+	return string(r[:n]) + "…"
+}

+ 64 - 0
internal/renamer/renamer.go

@@ -0,0 +1,64 @@
+// Package renamer 提供「智能重命名」共享导出类型。
+// 该包只定义纯数据类型(无数据库 / 框架依赖),供 internal/ai 纯逻辑与
+// renamerstore.go / renamerservice.go 的持久化与 Wails 服务共同引用,
+// 避免 AI 包与 store 之间重复定义结构体。
+package renamer
+
+// Pair 一对「旧文件名 → 新文件名」。
+type Pair struct {
+	From string `json:"from"`
+	To   string `json:"to"`
+}
+
+// Config AI 接入商配置(单行存储)。
+type Config struct {
+	Provider string `json:"provider"` // openai | ollama
+	BaseURL  string `json:"baseURL"`
+	APIKey   string `json:"apiKey"`
+	Model    string `json:"model"`
+}
+
+// FileEntry 目录扫描结果中的单个文件。
+type FileEntry struct {
+	Name    string `json:"name"`    // 相对路径(递归时 ToSlash)
+	Size    int64  `json:"size"`    // 字节数
+	ModTime string `json:"modTime"` // 修改时间 "2006-01-02 15:04"
+}
+
+// ScanResult 目录扫描结果。
+type ScanResult struct {
+	Dir   string      `json:"dir"`   // 绝对目录路径
+	Files []FileEntry `json:"files"` // 文件列表(按名称排序)
+}
+
+// PreviewEntry AI 预览结果行。
+type PreviewEntry struct {
+	From   string `json:"from"`
+	To     string `json:"to"`
+	Status string `json:"status"` // ok | same | error
+	Reason string `json:"reason,omitempty"`
+}
+
+// RenameResult 单文件重命名执行结果。
+type RenameResult struct {
+	From  string `json:"from"`
+	To    string `json:"to"`
+	OK    bool   `json:"ok"`
+	Error string `json:"error,omitempty"`
+}
+
+// HistoryItem 单个文件的重命名记录。
+type HistoryItem struct {
+	From string `json:"from"`
+	To   string `json:"to"`
+}
+
+// History 一次批量重命名的历史记录。
+type History struct {
+	ID        int64         `json:"id"`
+	CreatedAt string        `json:"createdAt"`
+	Dir       string        `json:"dir"`
+	Count     int           `json:"count"`
+	Undone    bool          `json:"undone"` // 该批次是否已撤回
+	Details   []HistoryItem `json:"details"`
+}

+ 2 - 1
main.go

@@ -545,6 +545,7 @@ func main() {
 			application.NewService(dockService),            // 注册 dockService,前端可通过 bindings 直接调用其 SetBadge 方法
 			application.NewService(explorerSvc),            // 注册 explorerService,供前端读取资源管理器选中项
 			application.NewService(&TagService{}),          // 注册 TagService,供资源管理器右键「标签」/悬停标签提示读写文件标签
+			application.NewService(NewRenamerService()),    // 注册 RenamerService,供工具页「智能重命名」调用
 		},
 		Assets: application.AssetOptions{
 			Handler: application.AssetFileServerFS(assets), // 使用嵌入的前端文件作为资源服务器处理器
@@ -576,7 +577,7 @@ func main() {
 		DefaultContextMenuDisabled: true,  // 禁用默认上下文菜单,防止右键点击打开菜单
 		UseApplicationMenu:         true,  // 启用应用菜单
 		EnableFileDrop:             true,  // 启用文件拖拽,需在 HTML 中添加 data-file-drop-target 标签
-		ContentProtectionEnabled:   true,  // 启用内容保护,防止截取窗口内容
+		ContentProtectionEnabled:   false, // 关闭内容保护,允许截取窗口内容(否则整个屏幕截图看不到本窗口)
 
 		Permissions: map[application.PermissionType]application.Permission{
 			application.PermissionMicrophone:    application.PermissionAllow,

+ 7 - 0
mousealert_other.go

@@ -13,6 +13,13 @@ func triggerMouseAlert(text string) {
 	_ = text // 忽略
 }
 
+// triggerMouseAlertWithOptions 非 Windows 平台为空实现。
+func triggerMouseAlertWithOptions(text string, width int, scroll *bool) {
+	_ = text
+	_ = width
+	_ = scroll
+}
+
 // stopMouseAlert 非 Windows 平台为空实现。
 func stopMouseAlert() {
 	// 无操作

+ 68 - 80
mousealert_windows.go

@@ -82,6 +82,16 @@ func cfgDurationOrDefault(sec int) time.Duration {
 	return time.Duration(sec) * time.Second
 }
 
+// mouseAlertScrollDefault 判断是否滚动显示超长文字:
+//   - cfg.Scroll 非 nil → 用显式配置(true=滚动,false=裁剪不滚动);
+//   - cfg.Scroll 为 nil(旧配置无该字段)→ 用 Speed>0 判断(旧行为:速度为 0 不滚动)。
+func mouseAlertScrollDefault(cfg MouseAlertConfig) bool {
+	if cfg.Scroll != nil {
+		return *cfg.Scroll
+	}
+	return cfg.Speed > 0
+}
+
 // estimateTextWidth 估算文字像素宽度(微软雅黑:全角/中文≈字号,半角/ASCII≈0.55*字号)。
 // 用于在触发时预判文字是否超长,从而智能延长显示时长。
 func estimateTextWidth(text string, fontSize int32) int32 {
@@ -302,6 +312,7 @@ type mouseAlertState struct {
 	cfgHeight       int32         // 气泡窗口高度(px,按字号自适应)
 	cfgFontSize     int32         // 字号(px)
 	cfgSpeed        int           // 超长文字滚动速度(px/s)
+	cfgScroll       bool          // 是否滚动显示超长文字(false=超出部分右侧裁剪,不滚动)
 	cfgDuration     time.Duration // 显示时长
 	cfgTextColor    uintptr       // 文字颜色(COLORREF)
 	cfgBgColor      uintptr       // 气泡背景色(COLORKEY 抠透明)
@@ -322,77 +333,14 @@ var mouseAlert = &mouseAlertState{}
 // 定位策略:窗口线程的定时器主动用 GetCursorPos 读取当前鼠标位置并跟随,
 // 不依赖任何全局钩子回调(钩子回调在系统线程执行,曾导致进程退出)。
 func triggerMouseAlert(text string) {
-	if text == "" {
-		text = "有新消息提醒"
-	}
-
-	// 从设置加载鼠标提醒配置(字号/宽度/速度/颜色/时长)
-	cfg := loadSettings().MouseAlert
-
-	var pt point
-	curRet, _, _ := procGetCursorPos.Call(uintptr(unsafe.Pointer(&pt)))
-	hasCursor := curRet != 0
-
-	// 智能延长显示时长:文字超长(需滚动)时,追加滚动一圈所需时间,保证能看完
-	cfgWidth := int32(cfg.Width)
-	if cfgWidth <= 0 {
-		cfgWidth = overlayWidth
-	}
-	cfgFontSize := int32(cfg.FontSize)
-	if cfgFontSize <= 0 {
-		cfgFontSize = DefaultMouseAlertFontSize
-	}
-	estW := estimateTextWidth(text, cfgFontSize)
-	baseDur := cfgDurationOrDefault(cfg.Duration)
-	totalDur := baseDur
-	if estW > cfgWidth-24 && cfg.Speed > 0 {
-		// 超出可用宽度的部分需滚动,所需时间 = 超出像素 / 速度
-		extra := estW - (cfgWidth - 24)
-		need := time.Duration(float64(extra) / float64(cfg.Speed) * float64(time.Second))
-		totalDur = baseDur + need
-	}
-
-	mouseAlert.mu.Lock()
-	mouseAlert.text = text
-	mouseAlert.active = true
-	mouseAlert.flashOn = true
-	mouseAlert.aboveMode = false // 默认:气泡位于鼠标右下偏移
-	mouseAlert.stopTime = time.Now().Add(totalDur)
-	mouseAlert.scrollX = 0   // 新消息从头开始滚动
-	mouseAlert.textWidth = 0 // 强制重新测量
-	// 缓存本次提醒的显示配置
-	mouseAlert.cfgWidth = cfgWidth
-	mouseAlert.cfgFontSize = cfgFontSize
-	mouseAlert.cfgSpeed = cfg.Speed
-	mouseAlert.cfgDuration = totalDur
-	mouseAlert.cfgTextColor = hexColorToRef(cfg.Color, 0x00FFFFFF) // 默认白字
-	mouseAlert.cfgBgColor = bgColorRef
-	mouseAlert.cfgOutlineColor = hexColorToRef(cfg.OutlineColor, 0x00000000) // 默认黑边
-	mouseAlert.cfgOutlineWidth = int32(cfg.OutlineWidth)
-	// 头尾相联间隔 = 两个空格宽度(约 0.3*字号 每个),提前缓存供滚动周期使用
-	mouseAlert.textGap = int32(float32(cfgFontSize) * 0.3 * 2)
-	if mouseAlert.textGap < 4 {
-		mouseAlert.textGap = 4
-	}
-	// 气泡高度按字号自适应:字号 + 上下留白 + 内边距
-	mouseAlert.cfgHeight = mouseAlert.cfgFontSize + 34
-	if hasCursor {
-		mouseAlert.lastX, mouseAlert.lastY = pt.X, pt.Y
-	}
-	started := mouseAlert.started
-	mouseAlert.started = true
-	overlay := mouseAlert.overlayWnd
-	mouseAlert.mu.Unlock()
+	triggerMouseAlertEx(text, 0, nil, false)
+}
 
-	// 首次触发:启动常驻工作线程(幂等),建窗后由线程主动定位并重绘
-	if !started {
-		go mouseAlertLoop()
-		return
-	}
-	// 已启动:唤醒窗口线程立即刷新(窗口线程负责 SetWindowPos/绘制)
-	if overlay != 0 {
-		procPostMessage.Call(overlay, wmRefresh, 0, 0)
-	}
+// triggerMouseAlertWithOptions 触发鼠标提醒,并允许通过参数覆盖气泡宽度与滚动行为。
+// 用于 API 触发场景:调用方可指定 width(px,>0 生效)与 scroll(是否滚动显示超长文字)。
+// 传入 nil scroll 时使用设置默认(Speed>0 则滚动)。
+func triggerMouseAlertWithOptions(text string, width int, scroll *bool) {
+	triggerMouseAlertEx(text, width, scroll, false)
 }
 
 // triggerMouseAlertAbove 触发鼠标提醒,并强制把气泡定位到鼠标正上方。
@@ -401,8 +349,17 @@ func triggerMouseAlert(text string) {
 // 光标右下方)重叠,满足用户「提示注意显示位置」的要求。
 // 除定位模式外,其余行为与 triggerMouseAlert 完全一致。
 func triggerMouseAlertAbove(text string) {
+	triggerMouseAlertEx(text, 0, nil, true)
+}
+
+// triggerMouseAlertEx 鼠标提醒核心:按参数触发气泡显示。
+//   - widthOverride > 0 时覆盖气泡宽度(px),否则用设置配置;
+//   - scrollOverride 非 nil 时覆盖「是否滚动显示超长文字」,否则用设置默认
+//     (Speed>0 即滚动);
+//   - above 为 true 时气泡定位到鼠标正上方(标签提示),否则右下偏移。
+func triggerMouseAlertEx(text string, widthOverride int, scrollOverride *bool, above bool) {
 	if text == "" {
-		return
+		text = "有新消息提醒"
 	}
 
 	// 从设置加载鼠标提醒配置(字号/宽度/速度/颜色/时长)
@@ -412,8 +369,11 @@ func triggerMouseAlertAbove(text string) {
 	curRet, _, _ := procGetCursorPos.Call(uintptr(unsafe.Pointer(&pt)))
 	hasCursor := curRet != 0
 
-	// 智能延长显示时长:文字超长(需滚动)时,追加滚动一圈所需时间,保证能看完
+	// 宽度:参数覆盖 > 设置值 > 默认
 	cfgWidth := int32(cfg.Width)
+	if widthOverride > 0 {
+		cfgWidth = int32(widthOverride)
+	}
 	if cfgWidth <= 0 {
 		cfgWidth = overlayWidth
 	}
@@ -421,16 +381,36 @@ func triggerMouseAlertAbove(text string) {
 	if cfgFontSize <= 0 {
 		cfgFontSize = DefaultMouseAlertFontSize
 	}
-	// 固定显示 tagAlertDuration(2 秒),不取用户「鼠标提醒」时长、也不因文字超长
-	// 智能延长:标签提示只在鼠标停留该文件期间显示,鼠标移开即被 stopTagAlert 隐藏。
-	// 若沿用 8 秒 + 超长延长,长备注的气泡会长时间挂在鼠标旁(用户反馈的问题)。
-	totalDur := tagAlertDuration
+	// 滚动开关:参数覆盖 > 设置配置(cfg.Scroll 非 nil)> 设置默认(Speed>0 即滚动)
+	scroll := mouseAlertScrollDefault(cfg)
+	if scrollOverride != nil {
+		scroll = *scrollOverride
+	}
+
+	// 智能延长显示时长:仅当「会滚动」且文字超长(需滚动)时,追加滚动一圈所需
+	// 时间,保证能看完。不滚动时超长部分右侧裁剪,不延长。
+	// 标签提示(above=true)固定 tagAlertDuration(2 秒):只在鼠标停留该文件期间
+	// 显示,鼠标移开即被 stopTagAlert 隐藏,不取用户「鼠标提醒」时长、也不因超长延长。
+	estW := estimateTextWidth(text, cfgFontSize)
+	var totalDur time.Duration
+	if above {
+		totalDur = tagAlertDuration
+	} else {
+		baseDur := cfgDurationOrDefault(cfg.Duration)
+		totalDur = baseDur
+		if scroll && estW > cfgWidth-24 && cfg.Speed > 0 {
+			// 超出可用宽度的部分需滚动,所需时间 = 超出像素 / 速度
+			extra := estW - (cfgWidth - 24)
+			need := time.Duration(float64(extra) / float64(cfg.Speed) * float64(time.Second))
+			totalDur = baseDur + need
+		}
+	}
 
 	mouseAlert.mu.Lock()
 	mouseAlert.text = text
 	mouseAlert.active = true
 	mouseAlert.flashOn = true
-	mouseAlert.aboveMode = true // 关键:气泡定位到鼠标正上方
+	mouseAlert.aboveMode = above // 定位模式:true=鼠标正上方(标签提示),false=右下偏移
 	mouseAlert.stopTime = time.Now().Add(totalDur)
 	mouseAlert.scrollX = 0   // 新消息从头开始滚动
 	mouseAlert.textWidth = 0 // 强制重新测量
@@ -438,6 +418,7 @@ func triggerMouseAlertAbove(text string) {
 	mouseAlert.cfgWidth = cfgWidth
 	mouseAlert.cfgFontSize = cfgFontSize
 	mouseAlert.cfgSpeed = cfg.Speed
+	mouseAlert.cfgScroll = scroll
 	mouseAlert.cfgDuration = totalDur
 	mouseAlert.cfgTextColor = hexColorToRef(cfg.Color, 0x00FFFFFF) // 默认白字
 	mouseAlert.cfgBgColor = bgColorRef
@@ -646,12 +627,13 @@ func (s *mouseAlertState) wndProcCallback(hwnd uintptr, msg uint32, wParam uintp
 				return 0
 			}
 			s.flashOn = !s.flashOn
-			// 超长文字滚动:文字宽度超过可用区时,按配置速度推进偏移,循环滚动
+			// 超长文字滚动:仅当「允许滚动」且文字宽度超过可用区时,按配置速度
+			// 推进偏移循环滚动;否则保持静止,超出部分右侧裁剪(不滚动)。
 			w := s.cfgWidth
 			if w <= 0 {
 				w = overlayWidth
 			}
-			if s.textWidth > w-24 {
+			if s.cfgScroll && s.textWidth > w-24 {
 				step := int32(s.cfgSpeed * 60 / 1000) // 每 60ms 帧推进(px)
 				if step < 1 {
 					step = 1
@@ -855,7 +837,10 @@ func (s *mouseAlertState) paintText(hdc uintptr) {
 	// 正文色在中心画一遍(fill),构成带色边的文字,形成颜色反差。
 	textLen := uintptr(len([]rune(text)))
 	leftX := int32(12) - scrollX
-	if textW > availW {
+	s.mu.Lock()
+	scroll := s.cfgScroll
+	s.mu.Unlock()
+	if textW > availW && scroll {
 		// 头尾相联:第二份从「文字头 + 文字宽 + 间隔」开始画,间隔为两个空格
 		s.mu.Lock()
 		gap := s.textGap
@@ -867,6 +852,9 @@ func (s *mouseAlertState) paintText(hdc uintptr) {
 		s.drawOutlinedText(hdc, textPtr, textLen, leftX, baseY, outlineColor, outlineWidth, textColor)
 		// 第二遍:文字头 + 文字宽 + 间隔,实现头尾相联无缝循环
 		s.drawOutlinedText(hdc, textPtr, textLen, leftX+textW+gap, baseY, outlineColor, outlineWidth, textColor)
+	} else if textW > availW {
+		// 不滚动:超长部分右侧裁剪(TextOutW 超出窗口区域自然被裁),只画一份
+		s.drawOutlinedText(hdc, textPtr, textLen, 12, baseY, outlineColor, outlineWidth, textColor)
 	} else {
 		// 未超长:左对齐单行
 		s.drawOutlinedText(hdc, textPtr, textLen, 12, baseY, outlineColor, outlineWidth, textColor)

+ 1 - 1
recordservice.go

@@ -71,7 +71,7 @@ func (s *SettingsService) ReadRecords() ([]RecordItem, error) {
 		return nil, err
 	}
 	defer db.Close()
-	rows, err := db.Query(`SELECT name, item, value, remark, created_at FROM records ORDER BY id ASC`)
+	rows, err := db.Query(`SELECT name, item, value, remark, created_at FROM records ORDER BY id DESC`)
 	if err != nil {
 		return nil, err
 	}

+ 421 - 0
renamerservice.go

@@ -0,0 +1,421 @@
+// ============================================================================
+// renamerservice.go — 「智能重命名」Wails 服务
+//
+// 从原「文件重命名」项目移植纯逻辑(目录扫描 / 校验 / 预览构建 / 执行重命名 /
+// 撤回),去掉 Gin 依赖,封装为 Wails 绑定方法供前端工具页调用。
+// 核心 AI 推断逻辑在 internal/ai(纯函数),持久化在 renamerstore.go。
+// ============================================================================
+package main
+
+import (
+	"context"
+	"database/sql"
+	"fmt"
+	"os"
+	"path/filepath"
+	"regexp"
+	"runtime"
+	"sort"
+	"strings"
+	"sync"
+	"time"
+
+	"TengTuToolbox/internal/ai"
+	"TengTuToolbox/internal/renamer"
+)
+
+// Windows 文件名非法字符(含控制字符)
+var renamerInvalidNameRe = regexp.MustCompile(`[\\/:*?"<>|\x00-\x1f]`)
+
+// 单次交给 AI 处理的文件数上限,避免超出上下文
+const renamerMaxFiles = 800
+
+// RenamerService 智能重命名服务:扫描目录、AI 预览、执行重命名、历史撤回与 AI 配置。
+type RenamerService struct {
+	dbOnce sync.Once // 惰性打开数据库(进程内一次)
+	db     *sql.DB
+	dbErr  error
+}
+
+// NewRenamerService 创建智能重命名服务。
+func NewRenamerService() *RenamerService {
+	return &RenamerService{}
+}
+
+// ---------- 纯逻辑(移植自原 api.go,非 Wails 绑定方法) ----------
+
+// scanDir 列出目录下文件(recursive 时递归子目录),返回相对路径(ToSlash)。
+func (s *RenamerService) scanDir(dir string, recursive bool) ([]renamer.FileEntry, error) {
+	var files []renamer.FileEntry
+	if !recursive {
+		entries, err := os.ReadDir(dir)
+		if err != nil {
+			return nil, err
+		}
+		for _, e := range entries {
+			if e.IsDir() {
+				continue
+			}
+			info, err := e.Info()
+			if err != nil {
+				continue
+			}
+			files = append(files, toFileEntry(e.Name(), info))
+		}
+		return files, nil
+	}
+	err := filepath.WalkDir(dir, func(path string, d os.DirEntry, err error) error {
+		if err != nil || d.IsDir() {
+			return nil // 跳过无法访问的项与目录本身
+		}
+		info, err := d.Info()
+		if err != nil {
+			return nil
+		}
+		rel, err := filepath.Rel(dir, path)
+		if err != nil {
+			return nil
+		}
+		files = append(files, toFileEntry(filepath.ToSlash(rel), info))
+		return nil
+	})
+	return files, err
+}
+
+func toFileEntry(name string, info os.FileInfo) renamer.FileEntry {
+	return renamer.FileEntry{
+		Name:    name,
+		Size:    info.Size(),
+		ModTime: info.ModTime().Format("2006-01-02 15:04"),
+	}
+}
+
+// validateNewName 校验新文件名,返回错误原因(空串表示合法)。
+func (s *RenamerService) validateNewName(name string) string {
+	switch {
+	case strings.TrimSpace(name) == "":
+		return "新文件名不能为空"
+	case renamerInvalidNameRe.MatchString(name):
+		return `新文件名包含非法字符 \ / : * ? " < > |`
+	case strings.HasSuffix(name, " ") || strings.HasSuffix(name, "."):
+		return "新文件名不能以空格或点结尾"
+	}
+	return ""
+}
+
+// sameExt 判断两个文件名的扩展名是否相同(不区分大小写)。
+func (s *RenamerService) sameExt(a, b string) bool {
+	return strings.EqualFold(filepath.Ext(a), filepath.Ext(b))
+}
+
+// buildEntries 合并 AI 建议与校验,生成带状态的预览结果。
+func (s *RenamerService) buildEntries(files []string, pairs []renamer.Pair) []renamer.PreviewEntry {
+	sugg := make(map[string]string, len(pairs)) // 小写旧名 -> 新名
+	for _, p := range pairs {
+		from := strings.TrimSpace(p.From)
+		if from == "" {
+			continue
+		}
+		sugg[strings.ToLower(from)] = strings.TrimSpace(p.To)
+	}
+	entries := make([]renamer.PreviewEntry, 0, len(files))
+	used := make(map[string]bool, len(files)) // 小写新名,检测重名冲突
+	for _, f := range files {
+		to := f
+		if t, ok := sugg[strings.ToLower(f)]; ok && t != "" {
+			to = t
+		}
+		e := renamer.PreviewEntry{From: f, To: to}
+		switch {
+		case to == f:
+			e.Status = "same"
+		case s.validateNewName(to) != "":
+			e.Status, e.Reason = "error", s.validateNewName(to)
+		case !s.sameExt(f, to):
+			e.Status, e.Reason = "error", "不允许修改文件扩展名"
+		default:
+			if key := strings.ToLower(to); used[key] {
+				e.Status, e.Reason = "error", "多个文件被重命名为同一个名称"
+			} else {
+				e.Status = "ok"
+				used[key] = true
+			}
+		}
+		entries = append(entries, e)
+	}
+	return entries
+}
+
+// targetExists 判断路径是否存在。
+func (s *RenamerService) targetExists(path string) bool {
+	_, err := os.Stat(path)
+	return err == nil
+}
+
+// listDrives Windows 枚举 C:\ 到 Z:\ 已存在的盘符;Linux/macOS 解析 /proc/mounts。
+func (s *RenamerService) listDrives() []string {
+	if runtime.GOOS == "windows" {
+		var drives []string
+		for ch := 'C'; ch <= 'Z'; ch++ {
+			root := string(ch) + `:\`
+			if info, err := os.Stat(root); err == nil && info.IsDir() {
+				drives = append(drives, root)
+			}
+		}
+		return drives
+	}
+	return listMounts()
+}
+
+// listMounts 解析 /proc/mounts(仅 Linux),只保留真实块设备挂载点,过滤虚拟文件系统。
+func listMounts() []string {
+	seen := map[string]bool{}
+	var out []string
+	if data, err := os.ReadFile("/proc/mounts"); err == nil {
+		for _, line := range strings.Split(string(data), "\n") {
+			fields := strings.Fields(line)
+			if len(fields) < 3 || !strings.HasPrefix(fields[0], "/dev/") {
+				continue
+			}
+			mp := strings.ReplaceAll(fields[1], "\\040", " ")
+			if !seen[mp] {
+				seen[mp] = true
+				out = append(out, mp)
+			}
+		}
+	}
+	if len(out) == 0 {
+		out = append(out, "/")
+	}
+	sort.Strings(out)
+	return out
+}
+
+// ---------- Wails 绑定方法 ----------
+
+// ListDrives 返回当前主机可用的驱动器/挂载点列表(供前端快速选择目录)。
+func (s *RenamerService) ListDrives() []string {
+	return s.listDrives()
+}
+
+// ScanDir 扫描指定目录下的所有文件(默认只扫当前层,recursive 时递归子目录)。
+func (s *RenamerService) ScanDir(dir string, recursive bool) (renamer.ScanResult, error) {
+	dir = strings.TrimSpace(dir)
+	if dir == "" {
+		return renamer.ScanResult{}, fmt.Errorf("请填写目录路径")
+	}
+	abs, err := filepath.Abs(dir)
+	if err != nil {
+		return renamer.ScanResult{}, fmt.Errorf("目录路径无效")
+	}
+	if info, err := os.Stat(abs); err != nil || !info.IsDir() {
+		return renamer.ScanResult{}, fmt.Errorf("目录不存在或不可访问:" + abs)
+	}
+	files, err := s.scanDir(abs, recursive)
+	if err != nil {
+		return renamer.ScanResult{}, fmt.Errorf("扫描目录失败: %w", err)
+	}
+	sort.Slice(files, func(i, j int) bool { return files[i].Name < files[j].Name })
+	return renamer.ScanResult{Dir: abs, Files: files}, nil
+}
+
+// SuggestPreview 用户给出至少 3 个示例,AI 推断规则并返回全部文件的新名称(仅预览,不落盘)。
+func (s *RenamerService) SuggestPreview(dir string, files []string, examples []renamer.Pair) ([]renamer.PreviewEntry, error) {
+	dir = strings.TrimSpace(dir)
+	if info, err := os.Stat(dir); err != nil || !info.IsDir() {
+		return nil, fmt.Errorf("目录不存在:" + dir)
+	}
+	if len(files) == 0 {
+		return nil, fmt.Errorf("文件列表为空,请先扫描目录")
+	}
+	if len(files) > renamerMaxFiles {
+		return nil, fmt.Errorf("文件数量(%d)超过单次上限 %d,请分批处理", len(files), renamerMaxFiles)
+	}
+	if len(examples) < 3 {
+		return nil, fmt.Errorf("至少需要 3 个重命名示例,AI 才能推断命名规律")
+	}
+	// 校验示例的合法性
+	actual := make(map[string]string, len(files)) // 小写文件名 -> 实际文件名
+	for _, f := range files {
+		actual[strings.ToLower(f)] = f
+	}
+	seen := make(map[string]bool, len(examples))
+	for i, ex := range examples {
+		real, ok := actual[strings.ToLower(strings.TrimSpace(ex.From))]
+		if !ok {
+			return nil, fmt.Errorf("示例 %d:文件 %q 不在当前列表中", i+1, ex.From)
+		}
+		if reason := s.validateNewName(ex.To); reason != "" {
+			return nil, fmt.Errorf("示例 %d:%s", i+1, reason)
+		}
+		if !s.sameExt(real, ex.To) {
+			return nil, fmt.Errorf("示例 %d:不允许修改文件扩展名(%s)", i+1, real)
+		}
+		key := strings.ToLower(real)
+		if seen[key] {
+			return nil, fmt.Errorf("文件 %s 在示例中重复出现", real)
+		}
+		seen[key] = true
+	}
+	cfg, err := s.getAIConfig()
+	if err != nil {
+		return nil, fmt.Errorf("读取 AI 配置失败: %w", err)
+	}
+	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
+	defer cancel()
+	pairs, err := ai.Suggest(ctx, cfg, examples, files)
+	if err != nil {
+		return nil, err
+	}
+	// 用户手动填写的示例优先于 AI 结果:AI 若把示例文件判为「保持原名」或遗漏,
+	// 仍以用户填写的新名为准(示例在前面已通过合法性与扩展名校验)
+	exMap := make(map[string]string, len(examples)) // 小写实际文件名 -> 用户新名
+	for _, ex := range examples {
+		if real, ok := actual[strings.ToLower(strings.TrimSpace(ex.From))]; ok {
+			exMap[strings.ToLower(real)] = strings.TrimSpace(ex.To)
+		}
+	}
+	for i := range pairs {
+		if to, ok := exMap[strings.ToLower(pairs[i].From)]; ok {
+			pairs[i].To = to
+			delete(exMap, strings.ToLower(pairs[i].From))
+		}
+	}
+	for from, to := range exMap { // AI 完全遗漏的示例文件直接补上
+		pairs = append(pairs, renamer.Pair{From: from, To: to})
+	}
+	return s.buildEntries(files, pairs), nil
+}
+
+// ExecuteRename 按预览结果执行真实重命名(逐条校验,失败不影响其他文件)。
+func (s *RenamerService) ExecuteRename(dir string, renames []renamer.Pair) (map[string]any, error) {
+	dir = strings.TrimSpace(dir)
+	if dir == "" {
+		return nil, fmt.Errorf("请求参数有误")
+	}
+	if info, err := os.Stat(dir); err != nil || !info.IsDir() {
+		return nil, fmt.Errorf("目录不存在:" + dir)
+	}
+	results := make([]renamer.RenameResult, 0, len(renames))
+	var succeeded []renamer.HistoryItem
+	for _, r := range renames {
+		if strings.TrimSpace(r.To) == "" || r.To == r.From {
+			continue // 无需修改
+		}
+		res := renamer.RenameResult{From: r.From, To: r.To}
+		switch {
+		case s.validateNewName(r.To) != "":
+			res.Error = s.validateNewName(r.To)
+		case !s.sameExt(r.From, r.To):
+			res.Error = "不允许修改文件扩展名"
+		default:
+			// Windows 文件系统大小写不敏感:仅大小写变化的合法改名放行
+			if s.targetExists(filepath.Join(dir, r.To)) && !strings.EqualFold(r.From, r.To) {
+				res.Error = "目标文件名已存在"
+			} else if err := os.Rename(filepath.Join(dir, r.From), filepath.Join(dir, r.To)); err != nil {
+				res.Error = "重命名失败: " + err.Error()
+			}
+		}
+		if res.Error == "" {
+			res.OK = true
+			succeeded = append(succeeded, renamer.HistoryItem{From: r.From, To: r.To})
+		}
+		results = append(results, res)
+	}
+	if len(succeeded) > 0 {
+		// 历史记录失败不影响重命名结果
+		_ = s.addHistory(dir, succeeded)
+	}
+	return map[string]any{
+		"results": results,
+		"success": len(succeeded),
+		"failed":  len(results) - len(succeeded),
+	}, nil
+}
+
+// GetAIConfig 读取 AI 接入商配置。
+func (s *RenamerService) GetAIConfig() (renamer.Config, error) {
+	return s.getAIConfig()
+}
+
+// SaveAIConfig 保存 AI 接入商配置。
+func (s *RenamerService) SaveAIConfig(cfg renamer.Config) error {
+	if cfg.Provider != "openai" && cfg.Provider != "ollama" {
+		return fmt.Errorf("接入商类型无效")
+	}
+	if strings.TrimSpace(cfg.BaseURL) == "" || strings.TrimSpace(cfg.Model) == "" {
+		return fmt.Errorf("接口地址与模型名称不能为空")
+	}
+	return s.saveAIConfig(cfg)
+}
+
+// TestAIConfig 测试 AI 服务连通性(不保存配置)。
+func (s *RenamerService) TestAIConfig(cfg renamer.Config) (string, error) {
+	ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
+	defer cancel()
+	return ai.Test(ctx, cfg)
+}
+
+// ListHistory 列出重命名历史(最多 100 条,时间倒序)。
+func (s *RenamerService) ListHistory() ([]renamer.History, error) {
+	return s.listHistory(100)
+}
+
+// UndoHistory 撤回一次批量重命名:把该批次中的文件从「新文件名」改回「旧文件名」。
+func (s *RenamerService) UndoHistory(id int64) (map[string]any, error) {
+	hist, err := s.getHistory(id)
+	if err != nil {
+		return nil, fmt.Errorf("历史记录不存在")
+	}
+	if hist.Undone {
+		return nil, fmt.Errorf("该批次已撤回过,不能重复撤回")
+	}
+	if info, err := os.Stat(hist.Dir); err != nil || !info.IsDir() {
+		return nil, fmt.Errorf("原目录不存在:" + hist.Dir)
+	}
+	// 从批次末尾往前撤回,减小中途失败导致的连锁冲突
+	type undoResult struct {
+		From    string `json:"from"`
+		To      string `json:"to"`
+		OK      bool   `json:"ok,omitempty"`
+		Skipped bool   `json:"skipped,omitempty"`
+		Error   string `json:"error,omitempty"`
+	}
+	results := make([]undoResult, 0, len(hist.Details))
+	success, skipped, failed := 0, 0, 0
+	for i := len(hist.Details) - 1; i >= 0; i-- {
+		d := hist.Details[i]
+		toPath := filepath.Join(hist.Dir, d.To)
+		fromPath := filepath.Join(hist.Dir, d.From)
+		r := undoResult{From: d.From, To: d.To}
+		switch {
+		case !s.targetExists(toPath):
+			// 新文件名已不存在:可能已被手动改回,视为跳过
+			r.Skipped = true
+			skipped++
+		case s.targetExists(fromPath) && !strings.EqualFold(d.From, d.To):
+			// 原文件名位置已被其他文件占用,拒绝覆盖
+			r.Error = "原文件名已存在,无法撤回"
+			failed++
+		default:
+			if err := os.Rename(toPath, fromPath); err != nil {
+				r.Error = "撤回失败: " + err.Error()
+				failed++
+			} else {
+				r.OK = true
+				success++
+			}
+		}
+		results = append(results, r)
+	}
+	if success > 0 || skipped == len(hist.Details) {
+		// 全部跳过也标记为已撤回,避免用户反复点击
+		_ = s.markHistoryUndone(id)
+	}
+	return map[string]any{
+		"results": results,
+		"success": success,
+		"skipped": skipped,
+		"failed":  failed,
+	}, nil
+}

+ 179 - 0
renamerstore.go

@@ -0,0 +1,179 @@
+// ============================================================================
+// renamerstore.go — 「智能重命名」SQLite 持久化
+//
+// 复用本项目 recordservice.go 的 modernc.org/sqlite(纯 Go 驱动,无 CGO)范式。
+// 数据库放程序目录 renamer.db,sync.Once 惰性初始化(进程内只 Open 一次,
+// 避免重复打开导致句柄泄漏)。包含 AI 接入商配置(config 单行)与重命名历史(history)。
+// ============================================================================
+package main
+
+import (
+	"database/sql"
+	"encoding/json"
+	"os"
+	"path/filepath"
+	"time"
+
+	_ "modernc.org/sqlite" // 纯 Go SQLite 驱动(无需 CGO)
+
+	"TengTuToolbox/internal/renamer"
+)
+
+// renamerDBPath 返回智能重命名数据库路径(程序目录下 renamer.db)。
+func renamerDBPath() string {
+	return filepath.Join(appDir(), "renamer.db")
+}
+
+// getDB 惰性打开智能重命名数据库并初始化表结构(进程内只执行一次)。
+// sync.Once 保证 runAPIServer / 多次调用不重复 Open 导致句柄泄漏。
+func (s *RenamerService) getDB() (*sql.DB, error) {
+	s.dbOnce.Do(func() {
+		path := renamerDBPath()
+		if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
+			s.dbErr = err
+			return
+		}
+		// DSN 加 _pragma:WAL 提升并发读;foreign_keys 开启;busy_timeout 让写锁等待而非立即报错
+		dsn := "file:" + filepath.ToSlash(path) +
+			"?_pragma=journal_mode(WAL)&_pragma=foreign_keys(ON)&_pragma=busy_timeout(5000)"
+		db, err := sql.Open("sqlite", dsn)
+		if err != nil {
+			s.dbErr = err
+			return
+		}
+		// SQLite 单写者,限制单连接避免锁冲突
+		db.SetMaxOpenConns(1)
+		if err := s.initDB(db); err != nil {
+			db.Close()
+			s.dbErr = err
+			return
+		}
+		s.db = db
+	})
+	return s.db, s.dbErr
+}
+
+func (s *RenamerService) initDB(db *sql.DB) error {
+	for _, q := range []string{
+		`CREATE TABLE IF NOT EXISTS config (
+			id       INTEGER PRIMARY KEY CHECK (id = 1),
+			provider TEXT NOT NULL DEFAULT 'ollama',
+			base_url TEXT NOT NULL DEFAULT '',
+			api_key  TEXT NOT NULL DEFAULT '',
+			model    TEXT NOT NULL DEFAULT ''
+		)`,
+		`INSERT OR IGNORE INTO config (id) VALUES (1)`,
+		`CREATE TABLE IF NOT EXISTS history (
+			id         INTEGER PRIMARY KEY AUTOINCREMENT,
+			created_at TEXT NOT NULL,
+			dir        TEXT NOT NULL,
+			details    TEXT NOT NULL
+		)`,
+	} {
+		if _, err := db.Exec(q); err != nil {
+			return err
+		}
+	}
+	// 增量迁移:为旧库补充 undone 列(已存在则忽略报错)
+	_, _ = db.Exec(`ALTER TABLE history ADD COLUMN undone INTEGER NOT NULL DEFAULT 0`)
+	return nil
+}
+
+// getAIConfig 读取 AI 接入商配置(单行 id=1)。
+func (s *RenamerService) getAIConfig() (renamer.Config, error) {
+	db, err := s.getDB()
+	if err != nil {
+		return renamer.Config{}, err
+	}
+	var c renamer.Config
+	err = db.QueryRow(`SELECT provider, base_url, api_key, model FROM config WHERE id = 1`).
+		Scan(&c.Provider, &c.BaseURL, &c.APIKey, &c.Model)
+	return c, err
+}
+
+// saveAIConfig 保存 AI 接入商配置。
+func (s *RenamerService) saveAIConfig(c renamer.Config) error {
+	db, err := s.getDB()
+	if err != nil {
+		return err
+	}
+	_, err = db.Exec(`UPDATE config SET provider = ?, base_url = ?, api_key = ?, model = ? WHERE id = 1`,
+		c.Provider, c.BaseURL, c.APIKey, c.Model)
+	return err
+}
+
+// addHistory 记录一次成功的批量重命名。
+func (s *RenamerService) addHistory(dir string, items []renamer.HistoryItem) error {
+	db, err := s.getDB()
+	if err != nil {
+		return err
+	}
+	details, err := json.Marshal(items)
+	if err != nil {
+		return err
+	}
+	_, err = db.Exec(`INSERT INTO history (created_at, dir, details) VALUES (?, ?, ?)`,
+		time.Now().Format("2006-01-02 15:04:05"), dir, string(details))
+	return err
+}
+
+// listHistory 按时间倒序列出历史记录(最多 limit 条)。
+func (s *RenamerService) listHistory(limit int) ([]renamer.History, error) {
+	db, err := s.getDB()
+	if err != nil {
+		return nil, err
+	}
+	rows, err := db.Query(`SELECT id, created_at, dir, undone, details FROM history ORDER BY id DESC LIMIT ?`, limit)
+	if err != nil {
+		return nil, err
+	}
+	defer rows.Close()
+	var list []renamer.History
+	for rows.Next() {
+		var h renamer.History
+		var details string
+		var undone int
+		if err := rows.Scan(&h.ID, &h.CreatedAt, &h.Dir, &undone, &details); err != nil {
+			return nil, err
+		}
+		h.Undone = undone != 0
+		if err := json.Unmarshal([]byte(details), &h.Details); err != nil {
+			h.Details = nil
+		}
+		h.Count = len(h.Details)
+		list = append(list, h)
+	}
+	return list, rows.Err()
+}
+
+// getHistory 按 ID 读取单条历史记录(撤回时使用)。
+func (s *RenamerService) getHistory(id int64) (*renamer.History, error) {
+	db, err := s.getDB()
+	if err != nil {
+		return nil, err
+	}
+	var h renamer.History
+	var details string
+	var undone int
+	err = db.QueryRow(`SELECT id, created_at, dir, undone, details FROM history WHERE id = ?`, id).
+		Scan(&h.ID, &h.CreatedAt, &h.Dir, &undone, &details)
+	if err != nil {
+		return nil, err
+	}
+	h.Undone = undone != 0
+	if err := json.Unmarshal([]byte(details), &h.Details); err != nil {
+		h.Details = nil
+	}
+	h.Count = len(h.Details)
+	return &h, nil
+}
+
+// markHistoryUndone 将历史批次标记为已撤回。
+func (s *RenamerService) markHistoryUndone(id int64) error {
+	db, err := s.getDB()
+	if err != nil {
+		return err
+	}
+	_, err = db.Exec(`UPDATE history SET undone = 1 WHERE id = ?`, id)
+	return err
+}

+ 123 - 49
settings.go

@@ -35,7 +35,7 @@ const (
 	DefaultNewsRefreshMinutes     = 120                 // 新闻自动刷新间隔(分钟)
 	DefaultNewsCount              = 30                  // 新闻页显示条数
 	DefaultGithubRefreshMinutes   = 120                 // Github 自动刷新间隔(分钟)
-	AppVersion                    = "0.1.8"             // 应用自身版本(与 build/windows/info.json 的 ProductVersion 一致),用于仓库更新提示
+	AppVersion                    = "0.1.10"            // 应用自身版本(与 build/windows/info.json 的 ProductVersion 一致),用于仓库更新提示
 
 	// 鼠标提醒默认配置
 	DefaultMouseAlertFontSize     = 20        // 字号(px)
@@ -53,6 +53,13 @@ type LinkItem struct {
 	URL  string `json:"url"`  // 网站地址
 }
 
+// LinkGroup 「网址」页分组(设置中以缩进层级定义,类似快捷启动)
+// 未分组的条目放在 LinkGroups 的第一个 Name 为空分组的 Items 中(前端解析时统一按组渲染)
+type LinkGroup struct {
+	Name  string     `json:"name"`  // 分组名(空表示未分组)
+	Items []LinkItem `json:"items"` // 组内网址
+}
+
 // CustomTab 用户自定义 Tab 页面
 type CustomTab struct {
 	Name string `json:"name"` // 页面名称(Tab 按钮显示文字)
@@ -95,6 +102,9 @@ type MouseAlertConfig struct {
 	Duration     int    `json:"duration"`     // 显示时长(秒)
 	OutlineColor string `json:"outlineColor"` // 文字描边颜色(白边/黑边,与文字形成反差)
 	OutlineWidth int    `json:"outlineWidth"` // 文字描边宽度(px),0 表示关闭描边
+	// Scroll 是否滚动显示超长文字:nil 表示未设置(兼容旧配置,用 Speed>0 决定);
+	// true=超长时水平滚动跑马灯,false=超长部分右侧裁剪不滚动。
+	Scroll *bool `json:"scroll"`
 }
 
 // GitLabConfig 自动升级配置(静态更新站方案)。
@@ -131,45 +141,46 @@ type QuickGroup struct {
 
 // AppSettings 保存全部可自定义配置,序列化为 JSON 存于用户配置目录
 type AppSettings struct {
-	Theme             string             `json:"theme"`             // 界面主题:dark / light
-	Autostart         bool               `json:"autostart"`         // 系统启动时运行
-	AlwaysOnTop       bool               `json:"alwaysOnTop"`       // 窗口置顶
-	StartCompact      bool               `json:"startCompact"`      // 启动时自动收拢为圆点(窗口缩小)
-	WindowWidth       int                `json:"windowWidth"`       // 主窗口宽度(px),随窗口调整自动保存
-	WindowHeight      int                `json:"windowHeight"`      // 主窗口高度(px),随窗口调整自动保存
-	Hotkey            string             `json:"hotkey"`            // 呼出(显示)窗口的全局热键
-	QuickHotkey       string             `json:"quickHotkey"`       // 在鼠标位置弹出「快捷」菜单的全局热键
-	ProxyHotkey       string             `json:"proxyHotkey"`       // 开关「网络代理」的全局热键(空=不设热键)
-	TabOrder          []string           `json:"tabOrder"`          // Tab 显示顺序(tabId 列表,未列出的追加到末尾)
-	StockCodes        []string           `json:"stockCodes"`        // 股市页展示的股票代码列表
-	Links             []LinkItem         `json:"links"`             // 常用网址列表
-	NewsKeywords      string             `json:"newsKeywords"`      // 新闻关注关键词,逗号分隔
-	BiliCookie        string             `json:"biliCookie"`        // B站登录 cookie(含 SESSDATA),用于抓取「关注的人最新动态」
-	BiliPopularEnabled bool              `json:"biliPopularEnabled"` // 新闻页是否显示 B站热门视频区块(默认开启)
-	GithubRepos       []RepoItem         `json:"githubRepos"`       // 关注的 GitHub 仓库列表
-	CustomTabs        []CustomTab        `json:"customTabs"`        // 用户自定义 Tab 页面(名字 + 网址)
-	LocalTools        []LocalTool        `json:"localTools"`        // 「本地」页资源(标题|启动命令|说明,在设置中维护)
-	QuickGroups       []QuickGroup       `json:"quickGroups"`       // 「快捷」页分组(缩进分层,名称|路径|说明 条目)
-	ControlKeys       []ControlKeyConfig `json:"controlKeys"`       // 控制页按键配置(前 5 键固定 上/下/左/右/休眠,第 6 键起为额外按键)
-	ControlRepeatSecs float64            `json:"controlRepeatSecs"` // 控制页长按连发频率(秒,0.0-10.0,默认 1.0)
-	APIAddr           string             `json:"apiAddr"`           // 内置 API 服务监听地址
-	ServiceAddr       string             `json:"serviceAddr"`       // Windows 服务模式(--service)监听地址,仅电源类接口
-	APIAutoStart      bool               `json:"apiAutoStart"`      // 应用启动时自动启动内置 API 服务(默认开启)
-	UploadPassword    string             `json:"uploadPassword"`    // 文件上传密码(空=不启用上传/下载接口)
-	UploadDir         string             `json:"uploadDir"`         // 文件上传保存目录(空=用户配置目录/uploads)
-	UploadMaxSize     int                `json:"uploadMaxSize"`     // 单个上传文件大小上限(MB),<=0 用默认 512
-	TodoPath          string             `json:"todoPath"`          // 待办(TODO)文件路径
-	RecordPath        string             `json:"recordPath"`        // 记录(Record)文件路径:每行「姓名|名称|值」(保留兼容)
-	RecordDBPath      string             `json:"recordDBPath"`      // 记录数据库路径:SQLite3 数据库文件(记录 Tab 实际存储)
-	TagDBPath         string             `json:"tagDBPath"`         // 文件标签数据库路径:SQLite3(资源管理器右键「标签」与悬停标签提示使用)
-	TagMenuEnabled    bool               `json:"tagMenuEnabled"`    // 资源管理器右键「标签」功能开关:false=关闭右键菜单+停止监听悬停(默认启用)
-	BackupDir         string             `json:"backupDir"`         // 文本文件备份目录(文件类自定义 Tab「备份」按钮使用)
-	StockTicker       TickerConfig       `json:"stockTicker"`       // 股票滚动条配置
-	NewsTicker        TickerConfig       `json:"newsTicker"`        // 新闻滚动条配置
-	Poem              PoemConfig         `json:"poem"`              // 随机古诗显示配置
-	MouseAlert        MouseAlertConfig   `json:"mouseAlert"`        // 系统级鼠标提醒气泡配置
-	BrowserPath       string             `json:"browserPath"`       // 指定浏览器 exe 路径(空=系统默认浏览器)
-	LEDColor          string             `json:"ledColor"`          // LED 滚动文字点阵颜色(如 #ff4d4d)
+	Theme              string             `json:"theme"`              // 界面主题:dark / light
+	Autostart          bool               `json:"autostart"`          // 系统启动时运行
+	AlwaysOnTop        bool               `json:"alwaysOnTop"`        // 窗口置顶
+	StartCompact       bool               `json:"startCompact"`       // 启动时自动收拢为圆点(窗口缩小)
+	WindowWidth        int                `json:"windowWidth"`        // 主窗口宽度(px),随窗口调整自动保存
+	WindowHeight       int                `json:"windowHeight"`       // 主窗口高度(px),随窗口调整自动保存
+	Hotkey             string             `json:"hotkey"`             // 呼出(显示)窗口的全局热键
+	QuickHotkey        string             `json:"quickHotkey"`        // 在鼠标位置弹出「快捷」菜单的全局热键
+	ProxyHotkey        string             `json:"proxyHotkey"`        // 开关「网络代理」的全局热键(空=不设热键)
+	TabOrder           []string           `json:"tabOrder"`           // Tab 显示顺序(tabId 列表,未列出的追加到末尾)
+	StockCodes         []string           `json:"stockCodes"`         // 股市页展示的股票代码列表
+	Links              []LinkItem         `json:"links"`              // 常用网址列表(扁平,未分组;分组请用 LinkGroups)
+	LinkGroups         []LinkGroup        `json:"linkGroups"`         // 「网址」页分组(缩进层级定义,空 Name 表示未分组)
+	NewsKeywords       string             `json:"newsKeywords"`       // 新闻关注关键词,逗号分隔
+	BiliCookie         string             `json:"biliCookie"`         // B站登录 cookie(含 SESSDATA),用于抓取「关注的人最新动态」
+	BiliPopularEnabled bool               `json:"biliPopularEnabled"` // 新闻页是否显示 B站热门视频区块(默认开启)
+	GithubRepos        []RepoItem         `json:"githubRepos"`        // 关注的 GitHub 仓库列表
+	CustomTabs         []CustomTab        `json:"customTabs"`         // 用户自定义 Tab 页面(名字 + 网址)
+	LocalTools         []LocalTool        `json:"localTools"`         // 「本地」页资源(标题|启动命令|说明,在设置中维护)
+	QuickGroups        []QuickGroup       `json:"quickGroups"`        // 「快捷」页分组(缩进分层,名称|路径|说明 条目)
+	ControlKeys        []ControlKeyConfig `json:"controlKeys"`        // 控制页按键配置(前 5 键固定 上/下/左/右/休眠,第 6 键起为额外按键)
+	ControlRepeatSecs  float64            `json:"controlRepeatSecs"`  // 控制页长按连发频率(秒,0.0-10.0,默认 1.0)
+	APIAddr            string             `json:"apiAddr"`            // 内置 API 服务监听地址
+	ServiceAddr        string             `json:"serviceAddr"`        // Windows 服务模式(--service)监听地址,仅电源类接口
+	APIAutoStart       bool               `json:"apiAutoStart"`       // 应用启动时自动启动内置 API 服务(默认开启)
+	UploadPassword     string             `json:"uploadPassword"`     // 文件上传密码(空=不启用上传/下载接口)
+	UploadDir          string             `json:"uploadDir"`          // 文件上传保存目录(空=程序所在目录/上传)
+	UploadMaxSize      int                `json:"uploadMaxSize"`      // 单个上传文件大小上限(MB),<=0 用默认 512
+	TodoPath           string             `json:"todoPath"`           // 待办(TODO)文件路径
+	RecordPath         string             `json:"recordPath"`         // 记录(Record)文件路径:每行「姓名|名称|值」(保留兼容)
+	RecordDBPath       string             `json:"recordDBPath"`       // 记录数据库路径:SQLite3 数据库文件(记录 Tab 实际存储)
+	TagDBPath          string             `json:"tagDBPath"`          // 文件标签数据库路径:SQLite3(资源管理器右键「标签」与悬停标签提示使用)
+	TagMenuEnabled     bool               `json:"tagMenuEnabled"`     // 资源管理器右键「标签」功能开关:false=关闭右键菜单+停止监听悬停(默认启用)
+	BackupDir          string             `json:"backupDir"`          // 文本文件备份目录(文件类自定义 Tab「备份」按钮使用)
+	StockTicker        TickerConfig       `json:"stockTicker"`        // 股票滚动条配置
+	NewsTicker         TickerConfig       `json:"newsTicker"`         // 新闻滚动条配置
+	Poem               PoemConfig         `json:"poem"`               // 随机古诗显示配置
+	MouseAlert         MouseAlertConfig   `json:"mouseAlert"`         // 系统级鼠标提醒气泡配置
+	BrowserPath        string             `json:"browserPath"`        // 指定浏览器 exe 路径(空=系统默认浏览器)
+	LEDColor           string             `json:"ledColor"`           // LED 滚动文字点阵颜色(如 #ff4d4d)
 
 	StockUpColor           string `json:"stockUpColor"`           // 股票上涨颜色
 	StockDownColor         string `json:"stockDownColor"`         // 股票下跌颜色
@@ -185,6 +196,8 @@ type AppSettings struct {
 	YTDLP                YTDLPConfig      `json:"ytdlp"`                // 视频下载配置(yt-dlp 保存目录)
 	Memos                MemosConfig      `json:"memos"`                // Memos 速记配置(地址/访问令牌)
 	Brightness           BrightnessConfig `json:"brightness"`           // 显示器亮度配置(记住亮度、启动恢复)
+	FooterDocsLabel      string           `json:"footerDocsLabel"`      // 页面右下角「官方文档」显示的标题文字
+	FooterDocsURL        string           `json:"footerDocsURL"`      // 页面右下角标题文字点击打开的网址
 	ToolOrder            []string         `json:"toolOrder"`            // 工具页卡片显示顺序(工具 id 列表,未列出的追加到末尾)
 	GitLab               GitLabConfig     `json:"gitLab"`               // 私有 GitLab 自动升级配置
 	SkippedUpdateVersion string           `json:"skippedUpdateVersion"` // 已跳过的版本(启动检查时视为无更新)
@@ -226,7 +239,7 @@ func defaultSettings() AppSettings {
 			{Name: "头条", URL: "https://www.toutiao.com/"},
 			{Name: "GitHub", URL: "https://github.com/"},
 		},
-		NewsKeywords: "",
+		NewsKeywords:       "",
 		BiliPopularEnabled: true, // 新闻页默认显示 B站热门视频区块
 		GithubRepos: []RepoItem{
 			{URL: "https://github.com/wailsapp/wails", Desc: "Wails:Go + Web 桌面应用框架"},
@@ -235,16 +248,16 @@ func defaultSettings() AppSettings {
 		ServiceAddr:       DefaultServiceAddr,
 		APIAutoStart:      true,                 // 内置 API 服务随应用启动(默认开启)
 		UploadPassword:    "",                   // 上传密码:默认空(不启用上传/下载)
-		UploadDir:         "",                   // 上传保存目录:默认空(回退到用户配置目录/uploads)
+		UploadDir:         "",                   // 上传保存目录:默认空(回退到程序所在目录/上传)
 		UploadMaxSize:     512,                  // 上传大小上限:默认 512MB
 		ControlKeys:       DefaultControlKeys(), // 控制页 5 键默认配置(图标↑↓←→休眠,命令空回退指令信箱)
 		ControlRepeatSecs: 1.0,                  // 长按连发频率默认 1 秒
-		TodoPath:          "",                   // 待办路径:无默认值,用户须在设置中配置(空值时强制进入设置)
-		RecordPath:        "",                   // 记录路径:无默认值,用户须在设置中配置(空值时强制进入设置)
-		RecordDBPath:      "",                   // 记录数据库路径:无默认值,用户须在设置中配置(空值时强制进入设置)
-		TagDBPath:         "",                   // 文件标签数据库路径:无默认值,用户须在设置中配置(空值时标签功能不生效)
+		TodoPath:          "",                   // 待办路径:默认空(回退到程序所在目录/待办.txt)
+		RecordPath:        "",                   // 记录路径:默认空(回退到程序所在目录/记录.txt)
+		RecordDBPath:      "",                   // 记录数据库路径:默认空(回退到程序所在目录/记录.db)
+		TagDBPath:         "",                   // 文件标签数据库路径:默认空(回退到程序所在目录/标签.db)
 		TagMenuEnabled:    true,                 // 资源管理器右键「标签」功能默认启用
-		BackupDir:         "",                   // 备份目录:无默认值,用户须在设置中配置(空值时强制进入设置)
+		BackupDir:         "",                   // 备份目录:默认空(回退到程序所在目录/备份)
 		StockTicker:       TickerConfig{Enabled: false, Width: 1400, FontSize: 14, Color: "#ff4d4d", Speed: 80, Transparent: true, X: -1, Y: -1},
 		NewsTicker:        TickerConfig{Enabled: false, Width: 1400, FontSize: 14, Color: "#3ddc84", Speed: 60, Transparent: true, X: -1, Y: -1},
 		Poem:              PoemConfig{Enabled: false, Color: DefaultPoemColor, FontSize: DefaultPoemFontSize, TTS: false, Interval: DefaultPoemInterval, Speed: DefaultPoemSpeed},
@@ -260,6 +273,8 @@ func defaultSettings() AppSettings {
 		NewsCount:              DefaultNewsCount,
 		GithubRefreshMinutes:   DefaultGithubRefreshMinutes,
 		FontDelta:              0, // 全局字号偏移默认 0
+		FooterDocsLabel:      "官方文档", // 右下角标题文字默认「官方文档」
+		FooterDocsURL:        "https://v3.wails.io", // 右下角标题文字默认打开的网址
 		Memos: MemosConfig{
 			URL: "https://m.scwy.net", // 默认 Memos 实例
 		},
@@ -300,6 +315,7 @@ func DefaultToolOrder() []string {
 		"memos",      // Memos 速记
 		"brightness", // 显示器设置(DDC/CI 优先,失败回退 Gamma;含一键息屏)
 		"proxy",      // 网络代理(设置并启用/禁用 Windows 系统代理)
+		"renamer",    // 智能重命名(AI 推断命名规律,批量重命名文件)
 	}
 }
 
@@ -314,6 +330,17 @@ func DefaultControlKeys() []ControlKeyConfig {
 	return keys
 }
 
+// appDir 返回程序所在目录(可执行文件所在文件夹),取不到时回退到当前工作目录
+func appDir() string {
+	if exe, err := os.Executable(); err == nil && exe != "" {
+		return filepath.Dir(exe)
+	}
+	if wd, err := os.Getwd(); err == nil && wd != "" {
+		return wd
+	}
+	return "."
+}
+
 // settingsFilePath 返回配置文件路径:<用户配置目录>/TengTuToolbox/settings.json
 func settingsFilePath() (string, error) {
 	dir, err := os.UserConfigDir() // 例如 C:\Users\<用户名>\AppData\Roaming
@@ -400,6 +427,12 @@ func normalizeSettings(settings AppSettings) AppSettings {
 	if settings.WindowHeight <= 0 {
 		settings.WindowHeight = DefaultWindowHeight
 	}
+	if strings.TrimSpace(settings.FooterDocsLabel) == "" {
+		settings.FooterDocsLabel = "官方文档" // 右下角标题文字为空时回退默认
+	}
+	if strings.TrimSpace(settings.FooterDocsURL) == "" {
+		settings.FooterDocsURL = "https://v3.wails.io" // 右下角标题网址为空时回退默认
+	}
 	// 先清洗自定义 Tab(生成 custom-N id 白名单供下方 Tab 顺序校验使用)
 	tabs := make([]CustomTab, 0, len(settings.CustomTabs))
 	for _, tab := range settings.CustomTabs {
@@ -534,8 +567,27 @@ func normalizeSettings(settings AppSettings) AppSettings {
 		settings.ServiceAddr = DefaultServiceAddr
 	}
 	settings.UploadPassword = strings.TrimSpace(settings.UploadPassword) // 上传密码:空表示不启用
-	settings.UploadDir = strings.TrimSpace(settings.UploadDir)           // 上传目录:空回退到默认目录
-	// TodoPath / RecordPath / RecordDBPath / BackupDir 无默认值:空值保留,前端据此强制用户进入设置配置(不做硬编码回填)
+	settings.UploadDir = strings.TrimSpace(settings.UploadDir)           // 上传目录
+	// 数据类路径默认值:未填写时统一取程序所在目录(exe 所在文件夹),避免用户每次都要手动配置
+	appDir := appDir()
+	if strings.TrimSpace(settings.TodoPath) == "" {
+		settings.TodoPath = filepath.Join(appDir, "待办.txt")
+	}
+	if strings.TrimSpace(settings.RecordPath) == "" {
+		settings.RecordPath = filepath.Join(appDir, "记录.txt")
+	}
+	if strings.TrimSpace(settings.RecordDBPath) == "" {
+		settings.RecordDBPath = filepath.Join(appDir, "记录.db")
+	}
+	if strings.TrimSpace(settings.TagDBPath) == "" {
+		settings.TagDBPath = filepath.Join(appDir, "标签.db")
+	}
+	if strings.TrimSpace(settings.BackupDir) == "" {
+		settings.BackupDir = filepath.Join(appDir, "备份")
+	}
+	if strings.TrimSpace(settings.UploadDir) == "" {
+		settings.UploadDir = filepath.Join(appDir, "上传")
+	}
 	settings.StockTicker = normalizeTicker(settings.StockTicker, "#ff4d4d", 80) // 股票条默认红字
 	settings.NewsTicker = normalizeTicker(settings.NewsTicker, "#3ddc84", 60)   // 新闻条默认绿字
 	settings.Poem = normalizePoemConfig(settings.Poem)                          // 古诗显示配置校正
@@ -623,6 +675,28 @@ func normalizeSettings(settings AppSettings) AppSettings {
 	}
 	settings.Links = links
 
+	// 网址分组归一:清理空白;若未配置分组,则把扁平 Links 归为一个未分组(Name 为空)
+	linkGroups := make([]LinkGroup, 0, len(settings.LinkGroups))
+	for _, g := range settings.LinkGroups {
+		g.Name = strings.TrimSpace(g.Name)
+		items := make([]LinkItem, 0, len(g.Items))
+		for _, link := range g.Items {
+			link.Name = strings.TrimSpace(link.Name)
+			link.URL = strings.TrimSpace(link.URL)
+			if link.Name != "" && link.URL != "" {
+				items = append(items, link)
+			}
+		}
+		if len(items) > 0 {
+			g.Items = items
+			linkGroups = append(linkGroups, g)
+		}
+	}
+	if len(linkGroups) == 0 {
+		linkGroups = append(linkGroups, LinkGroup{Name: "", Items: links})
+	}
+	settings.LinkGroups = linkGroups
+
 	repos := make([]RepoItem, 0, len(settings.GithubRepos))
 	for _, repo := range settings.GithubRepos {
 		repo.URL = strings.TrimSpace(repo.URL)

+ 101 - 11
tageditor_windows.go

@@ -15,7 +15,9 @@ package main
 import (
 	"fmt"
 	"os"
+	"path/filepath"
 	"runtime"
+	"strings"
 	"sync"
 	"syscall"
 	"unsafe"
@@ -31,6 +33,12 @@ const (
 	tagEditorHeight = 260  // 逻辑高度(px @96DPI),创建时按 DPI 缩放
 )
 
+// wmAppRefreshTagEditor:自定义窗口消息,取 WM_APP(0x8000 私有范围)的值,
+// 请求「窗口线程」刷新输入框(回填新路径的标签/备注)。
+// 用于复用分支:菜单线程不能直接 SetWindowText(跨线程操作控件),
+// 改为投递消息,由本窗口消息循环处理,天然串行安全。
+const wmAppRefreshTagEditor = 0x8000
+
 // 标准控件样式
 const (
 	wsChild         = 0x40000000
@@ -56,9 +64,9 @@ const (
 // procGetSystemMetrics/procGetModuleHandleW 等已在其它文件定义,此处不复用)。
 var (
 	procGetWindowTextW       = user32.NewProc("GetWindowTextW")
+	procGetWindowTextLengthW = user32.NewProc("GetWindowTextLengthW")
 	procSetWindowTextW       = user32.NewProc("SetWindowTextW")
 	procGetDlgItem           = user32.NewProc("GetDlgItem")
-	procGetWindowTextLengthW = user32.NewProc("GetWindowTextLengthW")
 	procSetFocus             = user32.NewProc("SetFocus")
 	procPostQuitMessage      = user32.NewProc("PostQuitMessage")
 	procGetClientRect        = user32.NewProc("GetClientRect")
@@ -74,6 +82,42 @@ var tagEditor struct {
 	started bool
 }
 
+// loadTagForEdit 读取 path 当前已保存的标签与备注,用于编辑窗口回填输入框。
+// 未找到(尚未打过标签)时返回两个空串,用户可重新填写。
+// 出错(数据库占用等)仅记日志并返回空串,不阻塞窗口打开。
+func loadTagForEdit(path string) (tag, note string) {
+	if path == "" {
+		return "", ""
+	}
+	t, found, err := getTagSvc().GetTag(path) // GetTag 内部会规范化路径键
+	if err != nil {
+		logTagErr("读取已有标签", err)
+		return "", ""
+	}
+	if !found {
+		return "", ""
+	}
+	return strings.TrimSpace(t.Tag), strings.TrimSpace(t.Note)
+}
+
+// refreshTagEditorTexts 用 path 已有的标签/备注刷新编辑窗口的两个输入框,
+// 并在窗口标题后附文件名(连续为不同文件打标签时可辨识)。
+// 只在编辑窗口的窗口线程内调用(首次创建后 / 切换路径时)。
+func refreshTagEditorTexts(hwnd uintptr, path string) {
+	if hwnd == 0 {
+		return
+	}
+	tag, note := loadTagForEdit(path)
+	if ctrl, _, _ := procGetDlgItem.Call(hwnd, tagEditID); ctrl != 0 {
+		procSetWindowTextW.Call(ctrl, uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(tag))))
+	}
+	if ctrl, _, _ := procGetDlgItem.Call(hwnd, noteEditID); ctrl != 0 {
+		procSetWindowTextW.Call(ctrl, uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(note))))
+	}
+	// 窗口标题:「标签:文件名」,便于区分当前正在为哪个文件打标签
+	procSetWindowTextW.Call(hwnd, uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr("标签 / 备注 - "+filepath.Base(filepath.Clean(path))))))
+}
+
 // openTagEditor 弹出标签编辑窗口(由右键菜单回调异步调用)。
 // 会启动一个 LockOSThread 的窗口线程。path 为规范化前的完整路径(显示用原始,
 // 写入库时由 SaveTag 再规范化)。
@@ -83,12 +127,16 @@ func openTagEditor(path string) {
 	}
 	tagEditor.mu.Lock()
 	if tagEditor.started {
-		// 已有一个编辑窗口:把新路径切过去(复用窗口,避免多实例)。
+		// 已有一个编辑窗口:把新路径切过去(复用窗口,避免多实例),
+		// 并请求窗口线程把该路径已有的标签/备注回填到输入框,供用户在其上修改。
+		// 菜单线程不能直接 SetWindowText(跨线程操作控件),改为投递自定义消息,
+		// 由本窗口的消息循环处理,天然串行安全。
 		hwnd := tagEditor.hwnd
 		tagEditor.path = path
 		tagEditor.mu.Unlock()
 		if hwnd != 0 {
 			procSetForegroundWindow.Call(hwnd)
+			procPostMessage.Call(hwnd, wmAppRefreshTagEditor, 0, 0)
 		}
 		return
 	}
@@ -96,11 +144,12 @@ func openTagEditor(path string) {
 	tagEditor.path = path
 	tagEditor.mu.Unlock()
 
-	go tagEditorLoop()
+	go tagEditorLoop(path)
 }
 
-// tagEditorLoop 标签编辑窗口线程。
-func tagEditorLoop() {
+// tagEditorLoop 标签编辑窗口线程。path 为本次要编辑的文件/文件夹路径,
+// 供创建窗口后回填已有标签/备注使用(避免与复用分支的并发写产生数据竞争)。
+func tagEditorLoop(path string) {
 	runtime.LockOSThread()
 	defer runtime.UnlockOSThread()
 
@@ -117,12 +166,26 @@ func tagEditorLoop() {
 		LpszClassName: className,
 		HCursor:       0,
 	}
-	atom, _, _ := procRegisterClassEx.Call(uintptr(unsafe.Pointer(&wc)))
+	atom, _, callErr := procRegisterClassEx.Call(uintptr(unsafe.Pointer(&wc)))
 	if atom == 0 {
-		tagEditor.classOK = false
-		tagEditor.mu.Unlock()
-		fmt.Fprintf(os.Stderr, "[tageditor] RegisterClassEx failed\n")
-		return
+		// RegisterClassEx 返回 0 可能是「类已注册」(ERROR_CLASS_ALREADY_EXISTS=1410),
+		// 此时窗口类定义仍有效,可继续创建窗口。第一次正常关闭后,窗口虽销毁但类定义
+		// 保留在系统里;再次点击「标签」时若仍把 0 当失败提前 return,会导致 started
+		// 卡在 true、后续永远无法弹窗。
+		// 注意:必须用 Call 的第三个返回值(syscall.Errno,API 调用后立即捕获)判断,
+		// 不能单独再调 GetLastError——Go 运行时在两次 syscall 间会改写线程 last-error,
+		// 导致读到 0(日志曾出现 "RegisterClassEx failed: 0"),从而误判为真失败。
+		errno, _ := callErr.(syscall.Errno)
+		if errno != 1410 { // ERROR_CLASS_ALREADY_EXISTS
+			fmt.Fprintf(os.Stderr, "[tageditor] RegisterClassEx failed: %d\n", errno)
+			tagEditor.classOK = false
+			tagEditor.mu.Unlock()
+			tagEditor.mu.Lock()
+			tagEditor.started = false
+			tagEditor.mu.Unlock()
+			return
+		}
+		// 类已存在:视为注册成功,继续创建窗口
 	}
 	tagEditor.classOK = true
 	tagEditor.mu.Unlock()
@@ -166,6 +229,9 @@ func tagEditorLoop() {
 
 	procShowWindow.Call(hwnd, 1) // SW_SHOWNORMAL
 	procSetForegroundWindow.Call(hwnd)
+	// 回填该路径已有的标签/备注(再次为同一文件打标签时,输入框显示上次内容供修改)。
+	// 用局部参数 path(不读 tagEditor.path,避免与复用分支的并发写产生数据竞争)。
+	refreshTagEditorTexts(hwnd, path)
 	// procGetDlgItem.Call 返回 (hwnd, r2, err);Go 不允许对多返回值直接下标,
 	// 先取第一值(控件句柄)再 SetFocus。
 	tagEditCtrl, _, _ := procGetDlgItem.Call(hwnd, tagEditID)
@@ -292,6 +358,18 @@ func tagEditorWndProc(hwnd uintptr, msgID uint32, wParam uintptr, lParam uintptr
 			tagEditor.mu.Unlock()
 			tagText := getControlText(hwnd, tagEditID)
 			noteText := getControlText(hwnd, noteEditID)
+			// 两个输入框都清空:视为取消打标签,删除该记录(否则留空记录,
+			// 悬停提示与右键「标签」都会把它当成有标签)。
+			if strings.TrimSpace(tagText) == "" && strings.TrimSpace(noteText) == "" {
+				if err := getTagSvc().DeleteTag(path); err != nil {
+					logTagErr("DeleteTag", err)
+					okBtn, _, _ := procGetDlgItem.Call(hwnd, btnOKID)
+					procSetWindowTextW.Call(okBtn, uintptr(unsafe.Pointer(utf16("确定(失败)"))))
+				} else {
+					procPostQuitMessage.Call(0)
+				}
+				break
+			}
 			if err := getTagSvc().SaveTag(path, tagText, noteText); err != nil {
 				logTagErr("SaveTag", err)
 				// 写库失败:提示并保持窗口打开(先取确定按钮句柄)
@@ -305,7 +383,19 @@ func tagEditorWndProc(hwnd uintptr, msgID uint32, wParam uintptr, lParam uintptr
 		}
 	case 0x0010: // WM_CLOSE:用户点标题栏关闭 → 视为取消
 		procPostQuitMessage.Call(0)
-	case 0x0002: // WM_DESTROY
+	case wmAppRefreshTagEditor: // 复用窗口切换到新路径:回填该路径已有的标签/备注
+		tagEditor.mu.Lock()
+		path := tagEditor.path
+		tagEditor.mu.Unlock()
+		refreshTagEditorTexts(hwnd, path)
+	case 0x0002: // WM_DESTROY:窗口已销毁
+		// 立即复位单实例状态,避免竞态:窗口销毁后、消息循环线程清理前,
+		// 用户再次点击「标签」时 started 仍为 true 且 hwnd=0,走复用分支
+		// SetForegroundWindow(0) 无效,窗口永远不弹(用户反馈「第二次无法弹出」)。
+		tagEditor.mu.Lock()
+		tagEditor.hwnd = 0
+		tagEditor.started = false
+		tagEditor.mu.Unlock()
 		procPostQuitMessage.Call(0)
 	}
 	// msgID 是 uint32,转 uintptr 传入 DefWindowProc;

+ 5 - 3
trending.go

@@ -79,9 +79,11 @@ var trendingLangRe = regexp.MustCompile(`itemprop="programmingLanguage"[^>]*>([^
 // 今日星数:如 "1,140 stars today"
 var trendingTodayRe = regexp.MustCompile(`([\d,]+)\s*stars\s*today`)
 
-// 总星数链接 / fork 数链接(数字可能嵌套在 span 内,允许中间任意标签)
-var trendingStarsRe = regexp.MustCompile(`href="[^"]*stargazers"[^>]*>(?:<[^>]+>)*\s*([\d,]+)`)
-var trendingForksRe = regexp.MustCompile(`href="[^"]*forks"[^>]*>(?:<[^>]+>)*\s*([\d,]+)`)
+// 总星数 / fork 数:链接内先是 octicon 图标(多层嵌套 SVG),数字在 </svg> 之后。
+// 原正则 (?:<[^>]+>)*\s*([\d,]+) 无法跨过多层嵌套标签(SVG path 等),导致
+// stars/forks 一直为空。改为锚定 </svg>((?s) 允许跨换行):数字紧跟图标闭合之后。
+var trendingStarsRe = regexp.MustCompile(`(?s)href="[^"]*stargazers"[^>]*>.*?</svg>\s*([\d,]+)`)
+var trendingForksRe = regexp.MustCompile(`(?s)href="[^"]*forks"[^>]*>.*?</svg>\s*([\d,]+)`)
 
 var htmlTagRe2 = regexp.MustCompile(`<[^>]+>`) // 剥掉内联标签残留
 

+ 280 - 0
update.ps1

@@ -0,0 +1,280 @@
+<#
+.SYNOPSIS
+    生成 bin/manifest.json —— Wails 内置升级器的更新清单(静态站点方案)。
+
+.DESCRIPTION
+    先用 `wails3 build -tags production` 编译应用,把编译产物 bin\腾图工具箱.exe
+    复制为 bin\TengTuToolbox-windows-amd64.exe(升级器期望的发布包名),
+    再读取 bin 下的发布包,计算文件大小与版本,写入升级清单 manifest.json。
+    将发布包与清单一起上传到更新站点 https://i.scwy.net/down/toolsbox/。
+    清单必须命名为 manifest.json;制品 url 即文件名(同一目录)。
+
+.PARAMETER Exe
+    用于生成清单的发布包(绝对或相对路径)。
+    默认 bin\TengTuToolbox-windows-amd64.exe,回退到 bin\TengTuToolbox.exe。
+
+.PARAMETER Version
+    清单版本。默认从 settings.go 的 AppVersion 读取,否则取 exe 版本信息。
+
+.PARAMETER Notes
+    更新说明(多行,用反引号 n 换行)。默认为空。
+
+.PARAMETER PublishedAt
+    发布时间(ISO 8601 或可解析格式)。默认为当前时间。
+
+.PARAMETER OutFile
+    输出清单路径。默认 bin\manifest.json。
+
+.PARAMETER Up
+    若设置,生成清单后用 scp 把发布包与清单上传到更新服务器,远端目录用 -UpTarget。
+
+.PARAMETER UpTarget
+    scp 远端目标目录。默认:
+    ease@192.168.100.22:/home/ease/server/blog/down/toolsbox
+
+.PARAMETER Build
+    若设置,先用 `wails3 build -tags production` 编译应用,再把编译产物
+    bin\腾图工具箱.exe 复制为发布包名。不设置时直接使用 bin 下已有的发布包。
+
+.EXAMPLE
+    .\update.ps1 -Build
+
+.EXAMPLE
+    .\update.ps1 -Build -Version 0.2.0 -Notes "`n- 新增功能 A.`n- 修复 B."
+
+.EXAMPLE
+    .\update.ps1 -Build -Up
+#>
+[CmdletBinding()]
+param(
+    [string]$Exe = "",
+    [string]$Version = "",
+    [string]$Notes = "",
+    [string]$PublishedAt = "",
+    [string]$OutFile = "",
+    [switch]$Up,
+    [string]$UpTarget = "ease@192.168.100.22:/home/ease/server/blog/down/toolsbox",
+    [switch]$Build
+)
+
+$ErrorActionPreference = 'Stop'
+
+$root = Split-Path -Parent $MyInvocation.MyCommand.Path
+$binDir = Join-Path $root 'bin'
+
+# 第 0 步:可选编译 —— 仅当 -Build 时用 `wails3 build -tags production` 编译应用
+# (production 标签:注册右键菜单「标签」注册表项),再把编译产物复制为升级器
+# 期望的发布包名。不设置 -Build 时直接用 bin 下已有的发布包。
+if ($Build) {
+    Write-Host '==> 正在用 wails3 build -tags production 编译 ...'
+    Push-Location $root
+    try {
+        wails3 build -tags production
+        if ($LASTEXITCODE -ne 0) {
+            throw "wails3 build 失败,退出码 $LASTEXITCODE"
+        }
+    } finally {
+        Pop-Location
+    }
+
+    # 定位刚编译出的可执行文件。不要在脚本里硬编码中文产品名「腾图工具箱.exe」:
+    # PowerShell 5.1 按系统 ANSI 代码页读取 .ps1,无 BOM 的 UTF-8 中文字面量会变乱码,
+    # 导致 Test-Path 失败。改为取 bin 下最新写入、且非发布/安装制品的 .exe,
+    # 编译总是把应用 exe 写得最新。
+    $excluded = @(
+        'TengTuToolbox-windows-amd64.exe'
+        'TengTu Toolbox-amd64-installer.exe'
+        'TengTuToolbox.exe'
+    )
+    $builtExe = Get-ChildItem -Path $binDir -Filter '*.exe' |
+        Where-Object { $excluded -notcontains $_.Name } |
+        Sort-Object LastWriteTime -Descending |
+        Select-Object -First 1
+    if (-not $builtExe) {
+        throw 'bin 下未找到编译产物,请检查 wails3 build 输出。'
+    }
+    $builtExe = $builtExe.FullName
+    $releaseExe = Join-Path $binDir 'TengTuToolbox-windows-amd64.exe'
+    Copy-Item -Path $builtExe -Destination $releaseExe -Force
+    Write-Host "==> 已复制编译产物到 $releaseExe"
+}
+
+# 第 1 步:解析发布包
+if (-not $Exe) {
+    $candidate = Join-Path $binDir 'TengTuToolbox-windows-amd64.exe'
+    if (-not (Test-Path $candidate)) {
+        $candidate = Join-Path $binDir 'TengTuToolbox.exe'
+    }
+    if (-not (Test-Path $candidate)) {
+        throw '未找到发布包,请把安装包放入 bin 或传入 -Exe。'
+    }
+    $Exe = $candidate
+}
+$exePath = if ([System.IO.Path]::IsPathRooted($Exe)) { $Exe } else { Join-Path (Get-Location) $Exe }
+if (-not (Test-Path $exePath)) {
+    throw "未找到发布包:$exePath"
+}
+
+# 第 2 步:文件名(制品 url = 文件名,与清单一起上传)
+$fileName = [System.IO.Path]::GetFileName($exePath)
+$fileSize = (Get-Item $exePath).Length
+
+# 第 3 步:版本 —— 优先 -Version,其次 settings.go 的 AppVersion,最后 exe 版本信息
+if (-not $Version) {
+    $settingsPath = Join-Path $root 'settings.go'
+    if (Test-Path $settingsPath) {
+        $m = Select-String -Path $settingsPath -Pattern 'AppVersion\s*=\s*"([^"]+)"'
+        if ($m) { $Version = $m.Matches[0].Groups[1].Value }
+    }
+}
+if (-not $Version) {
+    $ver = (Get-Item $exePath).VersionInfo
+    $Version = if ($ver.ProductVersion) { $ver.ProductVersion } else { $ver.FileVersion }
+}
+if (-not $Version) { $Version = '0.0.0' }
+
+# 第 4 步:发布时间
+if (-not $PublishedAt) {
+    $PublishedAt = (Get-Date).ToString('yyyy-MM-ddTHH:mm:sszzz')
+} else {
+    try { $PublishedAt = ([datetime]$PublishedAt).ToString('yyyy-MM-ddTHH:mm:sszzz') }
+    catch { }
+}
+
+# 第 5 步:规范化更新说明里的换行 —— 把用户传入的字面 \n(反斜杠+n)替换为真实换行。
+# PowerShell 的原生换行转义是反引号 n(`n),但命令行里常见反斜杠写法 \n。
+# 若用户已用 `n 得到真实换行,则不受影响;仅替换字面的反斜杠+n。
+$Notes = $Notes -replace '\\n', "`n"
+
+# 第 6 步:计算摘要与 Ed25519 签名 —— 升级器配置了 updater.key.pub 公钥后,
+# 要求每个 release 必须带签名(fail-closed)。签名方案:对发布包的 SHA-256
+# 摘要用 updater.key(PKCS#8 Ed25519 私钥)签名。
+# 若 updater.key 不存在,则只写摘要、不写签名(兼容未配公钥的旧版升级流程)。
+# 用 Go 临时程序计算,避免 PowerShell 5.1 的编码/字节处理问题。
+$digestAlgo = ''
+$digestB64 = ''
+$signatureAlgo = ''
+$signatureB64 = ''
+$keyPath = Join-Path $root 'updater.key'
+if (Test-Path $keyPath) {
+    $tmpGo = Join-Path $env:TEMP ('tengtu-sign-' + [guid]::NewGuid().ToString('N') + '.go')
+    $goSrc = @'
+package main
+
+import (
+	"crypto/ed25519"
+	"crypto/sha256"
+	"crypto/x509"
+	"encoding/base64"
+	"encoding/pem"
+	"fmt"
+	"os"
+)
+
+func main() {
+	if len(os.Args) != 3 {
+		fmt.Fprintln(os.Stderr, "usage: sign <keyfile> <exe>")
+		os.Exit(2)
+	}
+	keyRaw, err := os.ReadFile(os.Args[1])
+	if err != nil {
+		fmt.Fprintln(os.Stderr, "read key:", err)
+		os.Exit(1)
+	}
+	block, _ := pem.Decode(keyRaw)
+	if block == nil {
+		fmt.Fprintln(os.Stderr, "pem decode failed")
+		os.Exit(1)
+	}
+	privAny, err := x509.ParsePKCS8PrivateKey(block.Bytes)
+	if err != nil {
+		fmt.Fprintln(os.Stderr, "parse pkcs8:", err)
+		os.Exit(1)
+	}
+	priv, ok := privAny.(ed25519.PrivateKey)
+	if !ok {
+		fmt.Fprintln(os.Stderr, "not ed25519 private key")
+		os.Exit(1)
+	}
+	data, err := os.ReadFile(os.Args[2])
+	if err != nil {
+		fmt.Fprintln(os.Stderr, "read exe:", err)
+		os.Exit(1)
+	}
+	h := sha256.Sum256(data)
+	sig := ed25519.Sign(priv, h[:])
+	fmt.Println(base64.StdEncoding.EncodeToString(h[:]))
+	fmt.Println(base64.StdEncoding.EncodeToString(sig))
+}
+'@
+    [System.IO.File]::WriteAllText($tmpGo, $goSrc, (New-Object System.Text.UTF8Encoding($false)))
+    try {
+        $out = go run $tmpGo $keyPath $exePath 2>&1
+        if ($LASTEXITCODE -ne 0) {
+            throw "签名失败:$out"
+        }
+        $lines = @($out | ForEach-Object { $_.ToString() } | Where-Object { $_ -match '\S' })
+        if ($lines.Count -lt 2) {
+            throw "签名输出异常:$out"
+        }
+        $digestAlgo = 'sha256'
+        $digestB64 = $lines[0].Trim()
+        $signatureAlgo = 'ed25519'
+        $signatureB64 = $lines[1].Trim()
+        Write-Host "==> 已生成摘要与签名(Ed25519/SHA-256)"
+    } finally {
+        if (Test-Path $tmpGo) { Remove-Item $tmpGo -Force -ErrorAction SilentlyContinue }
+    }
+} else {
+    Write-Host '==> 未找到 updater.key,仅写摘要校验(无签名)'
+}
+
+# 第 7 步:写入输出
+if (-not $OutFile) { $OutFile = Join-Path $binDir 'manifest.json' }
+
+# 手工拼接 JSON,保持稳定的 2 空格缩进(不同 PS 版本的 ConvertTo-Json 缩进不一致)。
+# 只用 ConvertTo-Json 安全转义单个字符串值。
+function Esc([string]$s) { ($s | ConvertTo-Json -Compress) }
+
+$json = @(
+    '{'
+    '  "schemaVersion": 1,'
+    '  "version": ' + (Esc $Version) + ','
+    '  "name": ' + (Esc 'TengTu Toolbox') + ','
+    '  "notes": ' + (Esc $Notes) + ','
+    '  "publishedAt": ' + (Esc $PublishedAt) + ','
+    '  "artifacts": ['
+    '    {'
+    '      "url": ' + (Esc $fileName) + ','
+    '      "filename": ' + (Esc $fileName) + ','
+    '      "platform": "windows",'
+    '      "arch": "amd64",'
+    '      "size": ' + $fileSize + ','
+    '      "digestAlgo": ' + (Esc $digestAlgo) + ','
+    '      "digest": ' + (Esc $digestB64) + ','
+    '      "signatureAlgo": ' + (Esc $signatureAlgo) + ','
+    '      "signature": ' + (Esc $signatureB64)
+    '    }'
+    '  ]'
+    '}'
+) -join "`r`n"
+
+# 无 BOM 写入(Go 的 json.Unmarshal 会拒绝 UTF-8 BOM;PS5.1 的 Out-File -Encoding utf8 会加 BOM)。
+[System.IO.File]::WriteAllText($OutFile, $json, (New-Object System.Text.UTF8Encoding($false)))
+
+Write-Host "已生成更新清单:$OutFile"
+Write-Host "  发布包    : $fileName ($fileSize 字节)"
+Write-Host "  版本      : $Version"
+Write-Host "  发布时间  : $PublishedAt"
+Write-Host ""
+Write-Host "请把 $fileName 与 manifest.json 上传到 https://i.scwy.net/down/toolsbox/"
+
+# 第 7 步:可选 —— 用 scp 上传发布包与清单到更新服务器
+if ($Up) {
+    Write-Host "==> 正在通过 scp 上传到 $UpTarget ..."
+    scp $exePath $OutFile "$UpTarget"
+    if ($LASTEXITCODE -ne 0) {
+        throw "scp 上传失败,退出码 $LASTEXITCODE"
+    }
+    Write-Host "==> 上传完成。"
+}

Certains fichiers n'ont pas été affichés car il y a eu trop de fichiers modifiés dans ce diff