Quellcode durchsuchen

添加文件/文件夹的标签/备注功能

soease vor 2 Wochen
Ursprung
Commit
8448558eed
48 geänderte Dateien mit 4178 neuen und 726 gelöschten Zeilen
  1. 2 0
      .gitignore
  2. 20 10
      README.md
  3. 21 0
      apiserver.go
  4. 7 7
      build/config.yml
  5. 4 4
      build/darwin/Info.dev.plist
  6. 4 4
      build/darwin/Info.plist
  7. 8 8
      build/windows/info.json
  8. 6 6
      build/windows/msix/app_manifest.xml
  9. 7 7
      build/windows/msix/template.xml
  10. 5 5
      build/windows/nsis/project.nsi
  11. 1 1
      build/windows/wails.exe.manifest
  12. 544 0
      contextmenu_windows.go
  13. 238 0
      explorerservice.go
  14. 23 0
      explorerservice_other.go
  15. 772 0
      explorerservice_windows.go
  16. 45 0
      frontend/bindings/TengTuToolbox/explorerservice.js
  17. 3 0
      frontend/bindings/TengTuToolbox/index.js
  18. 130 40
      frontend/bindings/TengTuToolbox/models.js
  19. 59 34
      frontend/bindings/TengTuToolbox/settingsservice.js
  20. 78 0
      frontend/bindings/TengTuToolbox/tagservice.js
  21. 63 16
      frontend/index.html
  22. BIN
      frontend/public/Inter-Medium.ttf
  23. BIN
      frontend/public/bg-desktop.jpg
  24. BIN
      frontend/public/bg-mobile.jpg
  25. 0 1
      frontend/public/javascript.svg
  26. 81 15
      frontend/public/style.css
  27. 345 41
      frontend/src/main.js
  28. 125 0
      generate-manifest.ps1
  29. 1 1
      go.mod
  30. 86 11
      main.go
  31. 5 0
      mousealert_other.go
  32. 239 67
      mousealert_windows.go
  33. 3 1
      proxyservice.go
  34. 60 18
      settings.go
  35. 28 3
      settingsservice.go
  36. 87 0
      tagcmd.go
  37. 331 0
      tageditor_windows.go
  38. 35 0
      tagmenu_dev.go
  39. 38 0
      tagmenu_other.go
  40. 128 0
      tagmenu_prod.go
  41. 142 0
      tagmenu_windows.go
  42. 177 0
      tagservice.go
  43. 28 0
      tagservice_other.go
  44. 47 0
      tagservice_windows.go
  45. 40 0
      tagtoggle.go
  46. 0 391
      update.md
  47. 62 25
      updater.go
  48. 50 10
      webservice.go

+ 2 - 0
.gitignore

@@ -9,6 +9,8 @@ build/bin/
 build/appicon.icon/
 *.syso
 TengTuToolbox.exe
+# Wails CLI 本地构建产物(工具本体,非应用,不进版本库)
+out/
 
 # --- Android 构建(Wails 生成的移动端工程,整目录为产物) ---
 build/android/

+ 20 - 10
README.md

@@ -57,7 +57,7 @@ footer 显示的水平滚动随机古诗,数据来源为 [古诗词网接口](
 
 ### 设置项
 
-- 系统:界面样式(暗色/亮色)、系统启动时运行、窗口置顶、启动时缩小(直接收拢为圆点)、呼出窗口热键、全局字号偏移(+-3px)、指定浏览器 exe 路径(空=系统默认);主窗口尺寸随调整自动保存并在下次启动时恢复(收拢为圆点的尺寸不记录)
+- 系统:界面样式(暗色/亮色)、系统启动时运行、窗口置顶、启动时缩小(直接收拢为圆点)、呼出窗口热键、全局字号偏移(+-3px)、指定浏览器 exe 路径(空=系统默认)、**启用标签功能**(关闭后删除资源管理器右键菜单、停止监听悬停,默认启用)、**标签数据库路径**(资源管理器右键「标签」写入的 SQLite 数据库);主窗口尺寸随调整自动保存并在下次启动时恢复(收拢为圆点的尺寸不记录)
 - 各 Tab 对应设置:Tab 显示顺序(逗号分隔,名称用 `[]` 包裹的项折叠到标签栏末尾的三条横线菜单中,鼠标悬停展开选择,「设置」固定为该菜单最后一项)、股票代码与涨跌颜色、股市刷新间隔与休市刷新间隔、新闻关键词、新闻刷新间隔与显示条数、Github 项目(地址/说明/本地版本)与刷新间隔、记录数据库路径、待办文件路径、B 站关注动态 cookie(未配置或过期时自动回退热门视频,并在新闻页顶部提示更新)、自定义 Tab 列表(名字 + 网址 + 备注)
 - API 服务:内置 API 监听地址、随应用自动启动开关
 - 文件上传:上传/下载接口密码(空=不启用)、保存目录、单文件大小上限
@@ -203,6 +203,15 @@ sc delete TengTuToolboxService
 
 通过内置 API 触发系统级鼠标提醒:平时鼠标为正常样式;触发后鼠标图标闪烁(白↔红,约 250ms 周期),光标下方浮出半透明提示文字,可覆盖任意窗口(系统级),默认 8 秒自动消退。文字默认带黑色描边(可在设置中调整描边颜色与宽度,0 关闭),避免在亮/暗不同背景下看不清。详见 [mousealert_windows.go](mousealert_windows.go)。
 
+### 标签(资源管理器文件/文件夹)
+
+给资源管理器中的文件/文件夹打上「标签」与「备注」,鼠标悬停时在光标上方显示。
+
+- **添加/编辑**:在资源管理器中**右键**文件或文件夹,菜单中点击「**标签**」,弹出编辑窗口,填写标签(可空)与备注(可空)后「保存」。标签与备注存入 SQLite 数据库(路径在「设置 → 系统 → 标签数据库」配置,默认 `D:\My\腾图\标签.db`),按文件完整路径(不区分大小写)唯一保存。
+- **查看**:鼠标悬停在文件/文件夹上约 0.3 秒,若该文件已有标签/备注,光标上方会浮出气泡显示(复用系统级鼠标提醒,置顶覆盖任意窗口),约 2 秒自动消退;鼠标移开(不指向任何文件)后气泡立即隐藏。
+- **启用开关**:默认启用。可在「设置 → 系统 → **启用标签功能**」关闭:关闭后立即删除资源管理器右键菜单、停止后台监听悬停,鼠标悬停不再读取/提示标签;重新打开即恢复。删除/写入右键菜单需管理员权限,关闭时若普通权限删除失败会弹出 UAC 提权确认。
+- **实现**:后台服务 `explorerservice.go` 以 60ms 周期轮询前台资源管理器窗口,用 COM 命中测试读取鼠标所指文件;`contextmenu_windows.go` 安装 `WH_MOUSE_LL` 钩子注入右键菜单;`tagservice.go` 负责 SQLite 读写与路径规范化。详见 [tagmenu_windows.go](tagmenu_windows.go)、[tageditor_windows.go](tageditor_windows.go)、[mousealert_windows.go](mousealert_windows.go)。
+
 ### 拖动手柄
 
 Tab 栏最左侧的圆点手柄区域用于拖动窗口。双击手柄可在「全尺寸」与「仅手柄大小」(收拢后窗口只剩一个可拖动、可双击的正圆点,窗口背景全透明、四边不可见)之间切换,再双击还原。也可在设置中开启「启动时缩小」,应用启动即收拢为圆点。收拢时禁止拖动调整窗口大小;圆点为立体球体(镜面高光 + 暗部渐深 + 投影),默认以 6 秒周期「呼吸」(透明度 0.5 ↔ 1.0)缓慢明暗变化。
@@ -252,6 +261,16 @@ Tab 栏最左侧的圆点手柄区域用于拖动窗口。双击手柄可在「
 - `todoremind.go`:待办提醒调度(解析待办文件中的 `@ 时间` 标记,到点广播事件)
 - `mousealert_windows.go`:系统级鼠标提醒(Windows,WH_MOUSE_LL 全局钩子 + 置顶透明覆盖层 + GDI 绘制)
 - `mousealert_other.go`:鼠标提醒非 Windows 空实现
+- `tagservice.go`:标签功能 SQLite 读写(按文件路径规范化,tagDBPath 每次从磁盘读配置)
+- `tagservice_windows.go` / `tagservice_other.go`:标签功能平台实现(Windows 为空/非 Windows 空桩)
+- `tagcmd.go`:`-tag <路径>` 命令行参数解析(右键菜单调用,检测已运行实例并转发到 API 打开标签编辑窗口)
+- `tagmenu_windows.go`:资源管理器右键菜单注册表读写(`*` 与 `Directory` 下的 `shell\标签`)
+- `tagmenu_prod.go` / `tagmenu_dev.go` / `tagmenu_other.go`:右键菜单写入/删除的构建门控(production 写注册表、dev 跳过、非 Windows 空实现)
+- `tagtoggle.go`:按「启用标签功能」开关启停标签功能(启动/停止悬停监听、装/卸右键钩子、写/删注册表菜单)
+- `tageditor_windows.go`:标签编辑窗口(Windows 原生 Win32 窗口,DPI 缩放)
+- `explorerservice.go`:资源管理器悬停监听服务(后台轮询前台资源管理器选中项,供标签气泡读取)
+- `explorerservice_windows.go` / `explorerservice_other.go`:悬停监听平台实现(Windows 用 COM 命中测试读取鼠标所指文件,其他平台空实现)
+- `contextmenu_windows.go`:资源管理器右键菜单「标签」注入(WH_MOUSE_LL 全局钩子)
 - `frontend/`:前端代码(HTML、CSS、JavaScript)
 - `frontend/src/main.js`:前端逻辑,负责调用后端服务、监听后端事件(含 Tab 管理、工具页折叠、待办提醒弹窗、记录柱状图、Croc/视频下载/Memos 等工具交互、窗口收拢与还原圆点动画等)
 - `frontend/src/ticker.js`:滚动条逻辑
@@ -265,12 +284,3 @@ Tab 栏最左侧的圆点手柄区域用于拖动窗口。双击手柄可在「
 - 生产构建:`wails3 build`,输出 `bin/腾图工具箱.exe`(UPX 压缩)
 - 后端单独编译:`go build .`
 - 前端单独构建:`cd frontend && npm run build`
-
-## 备注
-
-1. `wails3 task windows:build BIN_DIR=Z:/` 可编译到指定目录并 UPX 压缩(见 `build/windows/taskfile.yml`)
-2. `wails3 dev` 会根据 `bin/config.yaml` 的配置决定输出目录
-3. 先 `npm run build` 完成后再单独 `go build`(后端需要读取构建后的前端 dist 清单,并行会导致 embed 失败)
-4. 修改 Go 结构体/事件后需运行 `wails3 generate bindings` 重新生成前端绑定
-5. 修改/新增前端页面后需 `cd frontend && npm run build`,再 `wails3 build` 才能打入产物
-6. 自定义 Tab 的内嵌网页属于跨站 iframe:需要登录态的资源(例如 Memos 的附件图片 `/file/attachments/...`,匿名访问返回 401)可能因第三方 Cookie / SameSite 限制而无法显示,网页主体本身仍正常。图片等资源依赖 `Authorization` 头时 `<img>` 也无法携带。需要完整登录态时,请在「设置」中配置指定浏览器后直接打开该网址,或改用不依赖会话 Cookie 的公开链接。

+ 21 - 0
apiserver.go

@@ -218,6 +218,7 @@ func runAPIServer(addr string) {
 	api.POST("/window/show", handleShowWindow)       // 显示主窗口
 	api.POST("/window/compact", handleWindowCompact) // 窗口收拢/还原(与双击手柄等效)
 	api.POST("/mouse/alert", handleMouseAlert)       // 触发系统级鼠标提醒(闪烁光标+提示文字)
+	api.POST("/tag/open", handleTagOpen)             // 打开标签编辑窗口(注册表右键菜单转发)
 	api.POST("/handle/flash", handleHandleFlash)     // 触发拖动手柄圆点闪烁(颜色+大小变化)
 	api.GET("/settings", handleGetSettings)          // 读取配置
 	api.POST("/settings", handleSaveSettings)        // 保存配置
@@ -321,6 +322,26 @@ func handleMouseAlert(c *gin.Context) {
 	c.JSON(http.StatusOK, gin.H{"ok": true})
 }
 
+// handleTagOpen 打开标签编辑窗口,例如:POST /api/tag/open {"path":"C:\\xx\\yy.txt"}
+// 由注册表右键菜单「标签」调用本程序时,若已有实例在运行则转发到此接口;
+// 运行中的实例收到后弹出标签编辑窗口(openTagEditor)供用户输入标签/备注。
+func handleTagOpen(c *gin.Context) {
+	var req struct {
+		Path string `json:"path"`
+	}
+	if err := c.ShouldBindJSON(&req); err != nil {
+		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
+		return
+	}
+	path := strings.TrimSpace(req.Path)
+	if path == "" {
+		c.JSON(http.StatusBadRequest, gin.H{"error": "path 不能为空"})
+		return
+	}
+	openTagEditor(path) // 弹出标签编辑窗口(单实例,已有窗口则切换路径并聚焦)
+	c.JSON(http.StatusOK, gin.H{"ok": true})
+}
+
 // handleHandleFlash 触发拖动手柄圆点闪烁,例如:POST /api/handle/flash {"count":3}
 // count 为闪烁次数(可选,默认 3);前端收到 handleFlash 事件后播放颜色+大小变化动画。
 func handleHandleFlash(c *gin.Context) {

+ 7 - 7
build/config.yml

@@ -5,13 +5,13 @@ version: '3'
 
 # This information is used to generate the build assets.
 info:
-  companyName: "My Company" # The name of the company
-  productName: "My Product" # The name of the application
-  productIdentifier: "com.mycompany.myproduct" # The unique product identifier
-  description: "A program that does X" # The application description
-  copyright: "(c) 2025, My Company" # Copyright text
-  comments: "Some Product Comments" # Comments
-  version: "0.0.1" # The application version
+  companyName: "TengTu Studio" # The name of the company
+  productName: "TengTuToolbox" # The name of the application
+  productIdentifier: "net.scwy.tttbox" # The unique product identifier
+  description: "腾图工作室工具箱" # The application description
+  copyright: "(c) 2026, TengTu Studio" # Copyright text
+  comments: "腾图工作室工具箱" # Comments
+  version: "0.1.7" # The application version
   # cfBundleIconName: "appicon" # The macOS icon name in Assets.car icon bundles (optional)
   #                               # Should match the name of your .icon file without the extension
   #                               # If not set and Assets.car exists, defaults to "appicon"

+ 4 - 4
build/darwin/Info.dev.plist

@@ -13,13 +13,13 @@
 		<key>CFBundleIdentifier</key>
 		<string>com.mycompany.myproduct</string>
 		<key>CFBundleName</key>
-		<string>My Product</string>
+		<string>腾图工具箱</string>
 		<key>CFBundlePackageType</key>
 		<string>APPL</string>
 		<key>CFBundleShortVersionString</key>
-		<string>0.0.1</string>
+		<string>0.1.7</string>
 		<key>CFBundleVersion</key>
-		<string>0.0.1</string>
+		<string>0.1.7</string>
 		<key>LSMinimumSystemVersion</key>
 		<string>12.0.0</string>
 		<key>NSAppTransportSecurity</key>
@@ -30,6 +30,6 @@
 		<key>NSHighResolutionCapable</key>
 		<string>true</string>
 		<key>NSHumanReadableCopyright</key>
-		<string>(c) 2025, My Company</string>
+		<string>(c) 2026, TengTu Studio</string>
 	</dict>
 </plist>

+ 4 - 4
build/darwin/Info.plist

@@ -13,18 +13,18 @@
 		<key>CFBundleIdentifier</key>
 		<string>com.mycompany.myproduct</string>
 		<key>CFBundleName</key>
-		<string>My Product</string>
+		<string>腾图工具箱</string>
 		<key>CFBundlePackageType</key>
 		<string>APPL</string>
 		<key>CFBundleShortVersionString</key>
-		<string>0.0.1</string>
+		<string>0.1.7</string>
 		<key>CFBundleVersion</key>
-		<string>0.0.1</string>
+		<string>0.1.7</string>
 		<key>LSMinimumSystemVersion</key>
 		<string>12.0.0</string>
 		<key>NSHighResolutionCapable</key>
 		<string>true</string>
 		<key>NSHumanReadableCopyright</key>
-		<string>(c) 2025, My Company</string>
+		<string>(c) 2026, TengTu Studio</string>
 	</dict>
 </plist>

+ 8 - 8
build/windows/info.json

@@ -1,15 +1,15 @@
 {
 	"fixed": {
-		"file_version": "0.0.1"
+		"file_version": "0.1.8.0"
 	},
 	"info": {
 		"0409": {
-			"ProductVersion": "0.0.1",
-			"CompanyName": "My Company",
-			"FileDescription": "A program that does X",
-			"LegalCopyright": "(c) 2025, My Company",
-			"ProductName": "My Product",
-			"Comments": "Some Product Comments"
+			"ProductVersion": "0.1.8.0",
+			"CompanyName": "TengTu Studio",
+			"FileDescription": "腾图多用途工具箱",
+			"LegalCopyright": "(c) 2026, TengTu Studio",
+			"ProductName": "腾图工具箱",
+			"Comments": "腾图多用途工具箱"
 		}
 	}
-}
+}

+ 6 - 6
build/windows/msix/app_manifest.xml

@@ -8,15 +8,15 @@
   IgnorableNamespaces="uap3">
   
   <Identity 
-    Name="net.scwy.myapp"
-    Publisher="CN=TengTu Studio"
-    Version="0.1.0.0" 
+    Name="net.scwy.tttbox"
+    Publisher="CNTengTu Studio"
+    Version="0.1.8.0" 
     ProcessorArchitecture="x64" />
   
   <Properties>
-    <DisplayName>My Product</DisplayName>
+    <DisplayName>腾图工具箱</DisplayName>
     <PublisherDisplayName>TengTu Studio</PublisherDisplayName>
-    <Description>A myapp application</Description>
+    <Description>腾图工具箱</Description>
     <Logo>Assets\StoreLogo.png</Logo>
   </Properties>
   
@@ -31,7 +31,7 @@
   <Applications>
     <Application Id="net.scwy.myapp" Executable="myapp.exe" EntryPoint="Windows.FullTrustApplication">
       <uap:VisualElements
-        DisplayName="My Product"
+        DisplayName="腾图工具箱"
         Description="A myapp application"
         BackgroundColor="transparent"
         Square150x150Logo="Assets\Square150x150Logo.png"

+ 7 - 7
build/windows/msix/template.xml

@@ -10,11 +10,11 @@
     <Installer
         Path="myapp.exe"
         Arguments=""
-        InstallLocation="C:\Program Files\TengTu Studio\My Product">
+        InstallLocation="C:\Program Files\TengTu Studio\Toolbox">
     </Installer>
     <PackageInformation
-        PackageName="My Product"
-        PackageDisplayName="My Product"
+        PackageName="TengTuToolbox"
+        PackageDisplayName="腾图工具箱"
         PublisherName="CN=TengTu Studio"
         PublisherDisplayName="TengTu Studio"
         Version="0.1.0.0"
@@ -26,8 +26,8 @@
         <Applications>
             <Application
                 Id="net.scwy.myapp"
-                Description="A myapp application"
-                DisplayName="My Product"
+                Description="腾图工具箱"
+                DisplayName="腾图工具箱"
                 ExecutableName="myapp.exe"
                 EntryPoint="Windows.FullTrustApplication">
                 
@@ -41,9 +41,9 @@
         </Dependencies>
         <Properties>
             <Framework>false</Framework>
-            <DisplayName>My Product</DisplayName>
+            <DisplayName>腾图工具箱</DisplayName>
             <PublisherDisplayName>TengTu Studio</PublisherDisplayName>
-            <Description>A myapp application</Description>
+            <Description>腾图工具箱</Description>
             <Logo>Assets\AppIcon.png</Logo>
         </Properties>
     </PackageInformation>

+ 5 - 5
build/windows/nsis/project.nsi

@@ -19,11 +19,11 @@ Unicode true
 ####
 ## The following information is taken from the wails_tools.nsh file, but they can be overwritten here.
 ####
-## !define INFO_PROJECTNAME    "my-project" # Default "myapp"
-## !define INFO_COMPANYNAME    "My Company" # Default "TengTu Studio"
-## !define INFO_PRODUCTNAME    "My Product Name" # Default "My Product"
-## !define INFO_PRODUCTVERSION "1.0.0"     # Default "0.1.0"
-## !define INFO_COPYRIGHT      "(c) Now, My Company" # Default "© 2026, TengTu Studio"
+!define INFO_PROJECTNAME    "TengTu Toolbox"
+!define INFO_COMPANYNAME    "TengTu Studio"
+!define INFO_PRODUCTNAME    "TengTu Toolbox"
+!define INFO_PRODUCTVERSION "0.1.8.0"
+!define INFO_COPYRIGHT      "(c) 2026, TengTu Studio"
 ###
 ## !define PRODUCT_EXECUTABLE  "Application.exe"      # Default "${INFO_PROJECTNAME}.exe"
 ## !define UNINST_KEY_NAME     "UninstKeyInRegistry"  # Default "${INFO_COMPANYNAME}${INFO_PRODUCTNAME}"

+ 1 - 1
build/windows/wails.exe.manifest

@@ -1,6 +1,6 @@
 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
 <assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1" xmlns:asmv3="urn:schemas-microsoft-com:asm.v3">
-    <assemblyIdentity type="win32" name="com.mycompany.myproduct" version="0.0.1" processorArchitecture="*"/>
+    <assemblyIdentity type="win32" name="net.scwy.tttbox" version="0.1.8.0" processorArchitecture="*"/>
     <dependency>
         <dependentAssembly>
             <assemblyIdentity type="win32" name="Microsoft.Windows.Common-Controls" version="6.0.0.0" processorArchitecture="*" publicKeyToken="6595b64144ccf1df" language="*"/>

+ 544 - 0
contextmenu_windows.go

@@ -0,0 +1,544 @@
+//go:build windows
+
+// ============================================================================
+// contextmenu_windows.go — 资源管理器右键菜单注入「标签」功能
+//
+// 方案:全局鼠标钩子 WH_MOUSE_LL 监听右键事件。
+//   1. WM_RBUTTONDOWN 在资源管理器文件项上时「吞掉」该事件,阻止 explorer
+//      收到后发 WM_CONTEXTMENU 弹默认菜单(否则会与我们的菜单双重弹出)。
+//   2. WM_RBUTTONUP 时用 IContextMenu 重建系统右键菜单(QueryContextMenu),
+//      并在末尾插入「标签(&T)」项,然后 TrackPopupMenu 弹出。
+//   3. 用户选「标签」→ 弹标签编辑窗口写库;选其他项 → InvokeCommand 转发给
+//      explorer 执行默认动作(复制/删除/属性等)。
+//
+// 重要:安装钩子前先探测本机能否取到文件项的 IContextMenu。
+//   Win11 新版资源管理器(WebView2/XAML 视图)已不再经 COM 暴露它
+//   (SHBindToParent → E_NOINTERFACE,SHCreateShellItem → E_INVALIDARG),
+//   此时无法重建系统右键菜单,于是**不吞掉右键**、完全放行给 explorer,
+//   由系统自己弹原生右键菜单(注入的「标签」项在这种机器上不可用)。
+//   若不加这个探测,吞掉右键又不弹菜单 = 用户右键彻底失效。
+//
+// 钩子线程安全(规避历史崩溃根因):钩子回调由系统投递到「安装钩子的线程」
+// 执行,因此必须 runtime.LockOSThread + 在该线程运行 GetMessage 消息循环,
+// 回调才能同步进入 Go runtime(安全)。v1 因未锁线程 + 无消息循环而崩溃。
+// ============================================================================
+package main
+
+import (
+	"log"
+	"os"
+	"runtime"
+	"sync"
+	"syscall"
+	"time"
+	"unsafe"
+
+	ole "github.com/go-ole/go-ole"
+)
+
+// ------------------------------------------------------------------------
+// 钩子过程 / 常量
+// ------------------------------------------------------------------------
+
+const (
+	whMouseLL    = 14     // WH_MOUSE_LL:低层鼠标钩子(全局,无需 DLL)
+	wmRButtonDown = 0x0204 // WM_RBUTTONDOWN
+	wmRButtonUp   = 0x0205 // WM_RBUTTONUP
+
+	// IContextMenu 命令 ID 范围:系统默认菜单用 [cmdFirst, cmdFirst+0x100)。
+	// 我们把「标签」放在其后 0x4000,避开系统范围,且远低于资源管理器自己的命令。
+	cmdFirst   = 0x4000
+	ourTagCmd  = cmdFirst // 「标签(&T)」菜单项命令 ID
+	cmdCount   = 0x100    // 系统项数量上限(与 IContextMenu::QueryContextMenu 约定一致)
+
+	// CMF_NORMAL:QueryContextMenu 的标准 flags
+	cmfNormal = 0x00000000
+
+	// MF_BYPOSITION:InsertMenuW 按位置插入(MF_STRING 常量已在 quickservice_windows.go 定义)
+	mfByPosition = 0x00000400
+
+	// TPM_LEFTALIGN | TPM_NONOTIFY(TPM_RIGHTBUTTON/TPM_RETURNCMD 已在 quickservice_windows.go 定义)
+	tpmLeftAlign = 0x0000
+	tpmNoNotify  = 0x0080
+
+	// IID_IContextMenu
+	iidIContextMenu = "{000214E4-0000-0000-C000-000000000046}"
+)
+
+// tagHook 全局钩子状态(包级,供回调与安装线程共享)。
+var tagHook struct {
+	mu      sync.Mutex
+	hook    uintptr // SetWindowsHookExW 返回的钩子句柄
+	started bool
+	cb      uintptr // syscall.NewCallback 返回的地址,须保持引用防 GC
+	// comMenuOK:安装钩子时探测一次「本机能否取到文件的 IContextMenu」。
+	// Win11 新版资源管理器返回 E_NOINTERFACE,取不到;此时必须放行右键,
+	// 否则会被我们吞掉导致「右键完全失效」。
+	comMenuOK bool
+	// 最近一次右键定位到的目标文件完整路径(WM_RBUTTONDOWN 时缓存,UP 时使用)
+	lastPath string
+	// cachedPath/cachedTime:由 explorerService 后台轮询维护的「当前悬停项路径」缓存。
+	// 右键钩子回调优先用它(零 COM 开销),避免在低层钩子里做重 COM 而被系统丢弃。
+	cachedPath string
+	cachedTime time.Time
+
+	// hookThreadID:安装钩子的那个线程的 TID。右键弹菜单必须在该线程执行
+	// (IContextMenu 是 STA COM 对象,跨线程调用会 RPC_E_WRONG_THREAD;
+	// 且该线程有 GetMessage 消息循环,TrackPopupMenu 才能正常跑模态循环)。
+	hookThreadID uintptr
+	// pendingMenu*:WM_RBUTTONUP 时暂存的路径与坐标,由钩子线程消息循环取出后弹菜单。
+	pendingPath string
+	pendingX    int32
+	pendingY    int32
+
+	// startMu 保护安装/卸载的串行化,避免 start/stop 并发导致重复装钩子。
+	startMu sync.Mutex
+}
+
+// setTagHookCachedPath 由悬停轮询调用,更新右键钩子可直接使用的路径缓存。
+// 该调用发生在轮询线程,与钩子线程通过 mutex 共享。
+func setTagHookCachedPath(path string) {
+	tagHook.mu.Lock()
+	tagHook.cachedPath = path
+	tagHook.cachedTime = time.Now()
+	tagHook.mu.Unlock()
+}
+
+// tagHookCachedPath 返回钩子缓存的当前悬停项路径(无锁开销的只读快照)。
+// 仅当缓存时间在 tagHookCacheValid(1 秒)内才视为可用。
+func tagHookCachedPath() string {
+	tagHook.mu.Lock()
+	defer tagHook.mu.Unlock()
+	if tagHook.cachedPath == "" || time.Since(tagHook.cachedTime) > tagHookCacheValid {
+		return ""
+	}
+	return tagHook.cachedPath
+}
+
+// tagHookCacheValid 右键钩子路径缓存的有效期。轮询间隔 60ms,1 秒足以覆盖
+// 「鼠标已稳定停在该项上」的场景;超期则回退到完整 COM 解析。
+const tagHookCacheValid = time.Second
+
+// wmTagMenu:自定义消息 ID(WM_APP+偏移),由钩子回调 PostThreadMessage 给钩子线程,
+// 触发在「钩子线程」上执行弹菜单。为何必须在本线程:IContextMenu 是 STA COM 对象,
+// 在其它线程(如普通 goroutine)调用 QueryContextMenu/InvokeCommand 会返回
+// RPC_E_WRONG_THREAD;且本线程有 GetMessage 消息循环,TrackPopupMenu 的模态循环才正常。
+const wmTagMenu = 0x0400 + 0xB001
+
+// startTagContextHook 安装 WH_MOUSE_LL 全局钩子(Windows 专用,非 Windows 为空实现)。
+// 在独立 goroutine 中 LockOSThread + 消息循环,保证钩子回调线程安全。
+// 可重复调用:已在运行(started)时无操作;Stop 后重新调用可再次安装。
+func startTagContextHook() {
+	tagHook.startMu.Lock()
+	tagHook.mu.Lock()
+	if tagHook.started {
+		tagHook.mu.Unlock()
+		tagHook.startMu.Unlock()
+		return // 钩子已在运行,不重复安装
+	}
+	tagHook.mu.Unlock()
+	tagHook.startMu.Unlock()
+
+	go func() {
+		runtime.LockOSThread()
+		defer runtime.UnlockOSThread()
+
+		// 钩子线程需要 STA COM(IContextMenu 是 STA 对象)。
+		if err := initComThread(); err != nil {
+			log.Printf("[tag] 钩子线程 COM 初始化失败: %v", err)
+			return
+		}
+
+		// 安装前探测一次「本机能否取到文件项的 IContextMenu」。
+		// Win11 新版资源管理器返回 E_NOINTERFACE,此时绝不能吞掉右键事件,
+		// 否则用户在文件上的右键将彻底失效(我们已无法重建系统菜单)。
+		// 注意:comMenuOK 零值是 false,探测成功后必须显式置 true。
+		comOK := probeComContextMenu()
+		tagHook.mu.Lock()
+		tagHook.comMenuOK = comOK
+		tagHook.mu.Unlock()
+		if comOK {
+			log.Printf("[tag] 本机可获取 IContextMenu,启用「标签」菜单注入")
+		} else {
+			log.Printf("[tag] 本机无法获取 IContextMenu(新版资源管理器):不拦截右键,交由 explorer 弹原生菜单")
+		}
+
+		tagHook.cb = syscall.NewCallback(mouseHookCallback)
+		h, _, _ := procSetWindowsHookExW.Call(
+			uintptr(whMouseLL),
+			tagHook.cb,
+			0, // hMod:WH_MOUSE_LL 可传 0(回调在当前进程)
+			0,
+		)
+		// 记录本线程 TID:钩子回调里 PostThreadMessage 要用它投递 wmTagMenu。
+		hookTID, _, _ := procGetCurrentThreadId.Call()
+
+		tagHook.mu.Lock()
+		tagHook.hook = h
+		tagHook.started = (h != 0)
+		tagHook.hookThreadID = hookTID
+		tagHook.mu.Unlock()
+		if h == 0 {
+			log.Printf("[tag] SetWindowsHookExW(WH_MOUSE_LL) 失败")
+			return
+		}
+		log.Printf("[tag] WH_MOUSE_LL 右键钩子已安装(线程TID=%d)", hookTID)
+
+		// 消息循环:钩子回调在 GetMessage 内部被调用,必须在此线程。
+		// 循环除常规消息分发外,还要处理我们投递的 wmTagMenu——
+		// 取暂存的路径/坐标,在本线程弹注入菜单(COM 调用必须在本线程)。
+		var m msg
+		for {
+			ret, _, _ := procGetMessage.Call(uintptr(unsafe.Pointer(&m)), 0, 0, 0)
+			if ret == 0 { // WM_QUIT
+				break
+			}
+			procTranslateMessage.Call(uintptr(unsafe.Pointer(&m)))
+			procDispatchMessage.Call(uintptr(unsafe.Pointer(&m)))
+
+			// 取出待弹菜单请求(由钩子回调 PostThreadMessage 触发,非阻塞)。
+			// showTagContextMenu 含 IContextMenu 等 STA COM 调用,必须在本线程执行。
+			tagHook.mu.Lock()
+			path := tagHook.pendingPath
+			x, y := tagHook.pendingX, tagHook.pendingY
+			tagHook.pendingPath = ""
+			tagHook.mu.Unlock()
+			if path != "" {
+				showTagContextMenu(path, x, y)
+			}
+		}
+		procUnhookWindowsHookEx.Call(h)
+		tagHook.mu.Lock()
+		tagHook.hook = 0
+		tagHook.started = false
+		tagHook.mu.Unlock()
+	}()
+}
+
+// stopTagContextHook 卸载钩子(关闭标签功能或应用退出时调用;正常进程退出由 OS 清理)。
+func stopTagContextHook() {
+	tagHook.startMu.Lock()
+	defer tagHook.startMu.Unlock()
+	tagHook.mu.Lock()
+	defer tagHook.mu.Unlock()
+	if tagHook.hook != 0 {
+		procUnhookWindowsHookEx.Call(tagHook.hook)
+		tagHook.hook = 0
+		tagHook.started = false
+	}
+}
+
+// msllhookstruct 对应 MSLLHOOKSTRUCT(WH_MOUSE_LL 回调的 lParam)。
+type msllhookstruct struct {
+	Pt          point
+	MouseData   uint32
+	Flags       uint32
+	Time        uint32
+	DwExtraInfo uintptr
+}
+
+// mouseHookCallback WH_MOUSE_LL 回调(在钩子线程执行,安全)。
+// 返回非 0 表示吞掉该事件(不再传递给系统)。
+func mouseHookCallback(nCode int, wParam uintptr, lParam uintptr) uintptr {
+	next := func() uintptr {
+		r, _, _ := procCallNextHookEx.Call(0, uintptr(nCode), wParam, lParam)
+		return r
+	}
+	if nCode < 0 { // 钩子链:必须放行
+		return next()
+	}
+	if wParam != wmRButtonDown && wParam != wmRButtonUp {
+		return next()
+	}
+
+	m := (*msllhookstruct)(unsafe.Pointer(lParam))
+	if m == nil {
+		return next()
+	}
+
+	// 仅处理资源管理器前台窗口上的文件项。
+	if !isForegroundExplorer() {
+		return next()
+	}
+
+	// 诊断日志:确认钩子已收到右键事件(右键时打印一次,便于定位不弹菜单的原因)。
+	if wParam == wmRButtonDown || wParam == wmRButtonUp {
+		log.Printf("[tag] 钩子收到 0x%04X (%d,%d)", wParam, m.Pt.X, m.Pt.Y)
+	}
+
+	tagHook.mu.Lock()
+	comOK := tagHook.comMenuOK
+	tagHook.mu.Unlock()
+
+	if wParam == wmRButtonDown {
+		// 右键按下:先解析出悬停项路径(DOWN 时确认,UP 时复用,避免误标到别的项)。
+		path, ok := filePathAtCursorCached(m.Pt.X, m.Pt.Y)
+		if ok {
+			tagHook.mu.Lock()
+			tagHook.lastPath = path
+			tagHook.mu.Unlock()
+		}
+		// 仅当能取到系统菜单对象时才「吞掉」事件阻止 explorer 发 WM_CONTEXTMENU
+		// (否则默认菜单会先弹出,我们再弹就双重)。
+		// COM 不可用(Win11 新版资源管理器)时必须放行,否则右键彻底失效。
+		if comOK && ok {
+			return 1 // 吞掉:阻止默认菜单
+		}
+		return next()
+	}
+
+	// WM_RBUTTONUP:COM 不可用时直接放行,让 explorer 弹它的原生右键菜单
+	// (我们无法重建系统菜单,此时任何拦截都会让用户「右键失效」)。
+	if !comOK {
+		return next()
+	}
+
+	// WM_RBUTTONUP:弹注入菜单。
+	// 关键:绝不能在钩子回调里直接弹菜单——
+	//   1) TrackPopupMenu 是模态阻塞调用,会卡住低层钩子回调(系统超时后丢弃钩子);
+	//   2) IContextMenu 是 STA COM 对象,只能在「安装了 COM 的钩子线程」上调用,
+	//      在普通 goroutine 里调用会 RPC_E_WRONG_THREAD(表现为菜单静默不弹)。
+	// 因此这里只暂存路径+坐标,再用 PostThreadMessage 给钩子线程投递 wmTagMenu,
+	// 由钩子线程的 GetMessage 循环取出后在本线程执行 showTagContextMenu。
+	tagHook.mu.Lock()
+	path := tagHook.lastPath // 仅使用 DOWN 时确认命中的路径,避免误标到别的项
+	tid := tagHook.hookThreadID
+	tagHook.mu.Unlock()
+	if path != "" && tid != 0 {
+		tagHook.mu.Lock()
+		tagHook.pendingPath = path
+		tagHook.pendingX = m.Pt.X
+		tagHook.pendingY = m.Pt.Y
+		tagHook.mu.Unlock()
+		// 投递到钩子线程,由 GetMessage 循环在本线程弹菜单。
+		procPostThreadMessage.Call(tid, wmTagMenu, 0, 0)
+		return 1 // 吞掉 UP:我们不希望 explorer 处理(已由我们的菜单接管)
+	}
+	return next()
+}
+
+// filePathAtCursorCached 只读「悬停轮询」缓存的路径(零 COM、零开销)。
+//
+// 这是 WH_MOUSE_LL 回调里的唯一入口:钩子回调必须在极短时间内返回,
+// 否则系统会判定钩子卡死并将其静默丢弃(LowLevelHooksTimeout 默认约 300ms,
+// 表现同样是「右键没有标签项」)。explorerService 的后台轮询每 60ms 更新
+// 当前悬停项路径,而用户要先悬停住才能右键,故缓存几乎总是可用。
+//
+// 重要:这里刻意**不做** COM 回退(不调 readHoveredExplorerItem)。
+// 缓存为空说明轮询尚未覆盖该位置,此时直接放行给 explorer 默认菜单更安全——
+// 宁可不弹「标签」项,也不能在钩子里做重 COM 而被系统丢弃。
+// 参数 (x,y) 保留以便日后接入按坐标的纯内存命中判断。
+func filePathAtCursorCached(x, y int32) (string, bool) {
+	if p := tagHookCachedPath(); p != "" {
+		return p, true
+	}
+	return "", false
+}
+
+// filePathAtCursor 仅供非钩子上下文(如后台线程、诊断)使用的完整解析入口。
+// 含重 COM,严禁在钩子回调里调用。
+func filePathAtCursor(x, y int32) (string, bool) {
+	path, ok := readHoveredExplorerItem()
+	if !ok || path == "" {
+		return "", false
+	}
+	log.Printf("[tag] 解析命中文件: %q (坐标 %d,%d)", path, x, y)
+	return path, true
+}
+
+// showTagContextMenu 在 (x,y) 弹出系统右键菜单,末尾注入「标签(&T)」项。
+// 由钩子回调异步调用(TrackPopupMenu 阻塞,不能放钩子线程)。
+func showTagContextMenu(path string, x, y int32) {
+	if path == "" {
+		return
+	}
+	log.Printf("[tag] 弹出右键菜单: path=%q (%d,%d)", path, x, y)
+
+	pcm, err := getIContextMenu(path)
+	if err != nil || pcm == nil {
+		log.Printf("[tag] IContextMenu 获取失败: %v", err)
+		// Win11 新版资源管理器已不再经 COM 暴露文件项的 IContextMenu
+		// (SHBindToParent → E_NOINTERFACE/E_NOTIMPL,SHCreateShellItem → E_INVALIDARG,
+		//  已用独立探针验证:连 notepad.exe 都取不到)。
+		// 此时系统菜单无法重建,只能放行给 explorer 弹原生菜单。
+		return
+	}
+	defer pcm.Release()
+
+	// 构建系统默认菜单。
+	hmenu, _, _ := procCreatePopupMenu.Call()
+	if hmenu == 0 {
+		return
+	}
+	defer procDestroyMenu.Call(hmenu)
+
+	vtable := pcm.VTable()
+	// IContextMenu vtable:IUnknown(0-2) + QueryContextMenu@3。
+	qcmPtr := *(*uintptr)(unsafe.Pointer(uintptr(unsafe.Pointer(vtable)) + 3*unsafe.Sizeof(uintptr(0))))
+	r0, _, _ := syscall.SyscallN(qcmPtr,
+		uintptr(unsafe.Pointer(pcm)),
+		hmenu,
+		0,          // indexMenu
+		uintptr(cmdFirst),
+		uintptr(cmdFirst+cmdCount),
+		uintptr(cmfNormal),
+	)
+	if r0 != 0 {
+		log.Printf("[tag] IContextMenu::QueryContextMenu 失败: hr=%#x", r0)
+		return
+	}
+
+	// 注入「标签(&T)」到菜单末尾(位置 -1 = 追加)。
+	procInsertMenuW.Call(
+		hmenu,
+		^uintptr(0), // -1:追加到末尾(MF_BYPOSITION)
+		uintptr(mfByPosition|mfString),
+		uintptr(ourTagCmd),
+		strPtr("标签(&T)"),
+	)
+
+	// 允许菜单接收键盘输入(TrackPopupMenu 需要前台窗口)。
+	procSetForegroundWindow.Call(0)
+
+	selected, _, _ := procTrackPopupMenu.Call(
+		hmenu,
+		uintptr(tpmLeftAlign|tpmRightButto|tpmReturnCmd|tpmNoNotify),
+		uintptr(x),
+		uintptr(y),
+		0, // hWnd:无所有者窗口
+		0,
+		0,
+	)
+
+	switch {
+	case selected == 0:
+		// 用户取消或菜单关闭:什么都不做。
+		return
+	case selected == ourTagCmd:
+		// 用户点「标签」:弹标签编辑窗口(异步,写库后关闭)。
+		go openTagEditor(path)
+		return
+	default:
+		// 其他项:转发给 explorer 的 IContextMenu::InvokeCommand 执行默认动作。
+		if selected >= cmdFirst && selected < cmdFirst+cmdCount {
+			invokeIContextMenu(pcm, uint32(selected-cmdFirst))
+		}
+	}
+}
+
+// getIContextMenu 用 SHParseDisplayName + SHBindToParent 拿到目标文件的
+// IContextMenu COM 接口。调用方负责 Release。
+func getIContextMenu(path string) (*ole.IUnknown, error) {
+	var pidl uintptr
+	// SHParseDisplayName(pszName, pbc, &pidl, sfgao, pattr)
+	r0, _, _ := procSHParseDisplayName.Call(
+		strPtr(path),
+		0,
+		uintptr(unsafe.Pointer(&pidl)),
+		0,
+		0,
+	)
+	if r0 != 0 || pidl == 0 {
+		return nil, ole.NewError(r0)
+	}
+	defer procCoTaskMemFree.Call(pidl) // 释放 PIDL
+
+	// SHBindToParent(pidl, riid, ppv, ppidlLast) → IContextMenu
+	var pcm *ole.IUnknown
+	childPidl := uintptr(0)
+	r0, _, _ = procSHBindToParent.Call(
+		pidl,
+		uintptr(unsafe.Pointer(ole.NewGUID(iidIContextMenu))),
+		uintptr(unsafe.Pointer(&pcm)),
+		uintptr(unsafe.Pointer(&childPidl)),
+	)
+	if r0 != 0 || pcm == nil {
+		return nil, ole.NewError(r0)
+	}
+	return pcm, nil
+}
+
+// invokeIContextMenu 调用 IContextMenu::InvokeCommand,把选中的系统项命令
+// 转发给 explorer 执行(复制/删除/属性等)。lpVerb 用 MAKEINTRESOURCE。
+func invokeIContextMenu(pcm *ole.IUnknown, cmdOffset uint32) {
+	// CMINVOKECOMMANDINFO 结构(足够大以兼容后续扩展)
+	type cminvokecommandinfo struct {
+		CbSize        uint32
+		FMask         uint32
+		HWnd          uintptr
+		LpVerb        uintptr
+		LpParameters  uintptr
+		LpDirectory   uintptr
+		NAShow        int32
+		DwHotKey      uint32
+		HIcon         uintptr
+	}
+	cmii := cminvokecommandinfo{
+		CbSize: uint32(unsafe.Sizeof(cminvokecommandinfo{})),
+		NAShow: 1, // SW_SHOWNORMAL
+	}
+	// lpVerb = MAKEINTRESOURCE(cmdOffset):把命令偏移当作指针传入(低位值)。
+	cmii.LpVerb = uintptr(cmdOffset)
+
+	vtable := pcm.VTable()
+	// InvokeCommand@4
+	invPtr := *(*uintptr)(unsafe.Pointer(uintptr(unsafe.Pointer(vtable)) + 4*unsafe.Sizeof(uintptr(0))))
+	syscall.SyscallN(invPtr,
+		uintptr(unsafe.Pointer(pcm)),
+		uintptr(unsafe.Pointer(&cmii)),
+	)
+}
+
+// ------------------------------------------------------------------------
+// 进程变量(本文件专用,避免与其它文件重名)
+// 注:procCreatePopupMenu/procTrackPopupMenu/procDestroyMenu/procSetForegroundWindow
+// 已在 quickservice_windows.go 定义,此处不复用,避免重复声明。
+// ------------------------------------------------------------------------
+var (
+	procSetWindowsHookExW   = user32.NewProc("SetWindowsHookExW")
+	procUnhookWindowsHookEx = user32.NewProc("UnhookWindowsHookEx")
+	procCallNextHookEx      = user32.NewProc("CallNextHookEx")
+	procInsertMenuW         = user32.NewProc("InsertMenuW")
+	// PostThreadMessageW:把 wmTagMenu 投递到钩子线程队列,使弹菜单(含模态
+	// TrackPopupMenu)在本线程的 GetMessage 循环里执行,而非阻塞钩子回调。
+	procPostThreadMessage = user32.NewProc("PostThreadMessageW")
+	// GetCurrentThreadId:获取钩子线程 TID,供 PostThreadMessage 定位目标线程。
+	// 注意:此函数在 kernel32.dll(不是 user32),放错 DLL 会 panic「找不到过程」。
+	procGetCurrentThreadId = kernel32.NewProc("GetCurrentThreadId")
+	procSHParseDisplayName = shell32DLL.NewProc("SHParseDisplayName")
+	procSHBindToParent   = shell32DLL.NewProc("SHBindToParent")
+)
+
+// probeComContextMenu 在安装钩子前探测一次「本机能否取到文件项的 IContextMenu」。
+//
+// Win11 新版资源管理器(WebView2/XAML 视图)已不再经 COM 暴露文件项的
+// IContextMenu:SHBindToParent → E_NOINTERFACE / E_NOTIMPL,
+// SHCreateShellItem + SHCreateContextMenuFromShellItem → E_INVALIDARG。
+// 此时我们无法重建系统右键菜单,因此**绝不能**吞掉右键事件——
+// 一旦吞掉,explorer 收不到右键,用户就再也右键不了了(本次「右键失效」的根因)。
+//
+// 返回 true 表示可用(老版 shell),可照旧注入菜单项;返回 false 表示放行右键。
+// 只需探测一次:结果是系统级的(同一台机器、同一个 shell 版本)。
+func probeComContextMenu() bool {
+	// 必须用「真实存在」的路径探测,否则 SHParseDisplayName 会直接失败,
+	// 无法区分「API 不支持」与「路径不存在」。
+	var candidates []string
+	if exe, err := os.Executable(); err == nil {
+		candidates = append(candidates, exe)
+	}
+	candidates = append(candidates,
+		`C:\Windows\System32\notepad.exe`,
+		`C:\Windows\explorer.exe`,
+	)
+	for _, p := range candidates {
+		if p == "" {
+			continue
+		}
+		pcm, err := getIContextMenu(p)
+		if err == nil && pcm != nil {
+			pcm.Release()
+			return true
+		}
+	}
+	return false
+}

+ 238 - 0
explorerservice.go

@@ -0,0 +1,238 @@
+package main
+
+import (
+	"log"
+	"runtime"
+	"strings"
+	"sync"
+	"time"
+)
+
+// tagHoverDelay 鼠标悬停在文件/文件夹上多久后才查询标签库并弹出「标签」提示。
+// 300ms:用户实测反馈 1 秒太长——鼠标在文件上停留不足 1 秒时(快速扫过或
+// 犹豫),查询从未触发、提示不出现。300ms 让正常停留(约半秒)也能触发,
+// 同时仍能过滤掉「一闪而过的快速移动」(<300ms)。
+const tagHoverDelay = 300 * time.Millisecond
+
+// explorerService 缓存最近一次从资源管理器读到的鼠标悬停项(完整路径)。
+// 后台轮询:当前台窗口是资源管理器且有鼠标悬停项时更新缓存。
+// 当检测到悬停项发生变化(与上次缓存不同)时,在鼠标旁弹出临时提示
+// 显示完整路径(复用系统级 mousealert 置顶气泡,无需切换到 Wails 窗口)。
+//
+// 可启停:Start/Stop 可反复调用(「配置→系统」关闭标签功能时 Stop 停止轮询,
+// 重新启用时 Start 再启动)。Stop 关闭 stopCh 令 pollLoop 退出;Start 重建
+// stopCh 并启动新 pollLoop。
+type explorerService struct {
+	mu      sync.RWMutex
+	lastSel string // 保持字段名 lastSel(绑定哈希只依赖方法名,字段名可自由改)
+	lastTime time.Time
+	stopCh   chan struct{}
+	runMu    sync.Mutex // 保护 running 与 stopCh 的启停切换
+	running  bool
+}
+
+func newExplorerService() *explorerService {
+	return &explorerService{stopCh: make(chan struct{})}
+}
+
+// Start 启动后台轮询 goroutine。若已在运行则无操作;Stop 后再次调用可重新启动。
+func (s *explorerService) Start() {
+	s.runMu.Lock()
+	defer s.runMu.Unlock()
+	if s.running {
+		return // 已在轮询,不重复启动
+	}
+	s.stopCh = make(chan struct{})
+	s.running = true
+	go s.pollLoop()
+}
+
+// Stop 停止后台轮询。若已停止则无操作。
+func (s *explorerService) Stop() {
+	s.runMu.Lock()
+	defer s.runMu.Unlock()
+	if !s.running {
+		return
+	}
+	s.running = false
+	close(s.stopCh) // 令 pollLoop 的 select 收到 stopCh 后退出
+}
+
+// LastSelection 返回最近一次读到的悬停项完整路径,无则 ""。
+// 注意:方法名保留 LastSelection 以匹配 Wails 绑定(绑定 ID 哈希只依赖方法全名,
+// 改方法名会导致前端绑定失效)。语义已从「选中项列表」变为「悬停项单个路径」。
+func (s *explorerService) LastSelection() string {
+	s.mu.RLock()
+	defer s.mu.RUnlock()
+	return s.lastSel
+}
+
+// pollLoop 轮询前台资源管理器鼠标悬停项。
+// 关键改进:不再 300ms 高频轮询 COM(那会干扰 explorer 的 shell view,
+// 导致资源管理器不停闪烁、悬停项被反复清空 → 永远读不到 → 无气泡)。
+// 改为「事件驱动」:检测到鼠标移动后,延迟 120ms 查询一次悬停项,
+// 其余时间完全不做 COM 调用,让 explorer 恢复常态。
+func (s *explorerService) pollLoop() {
+	// 锁定 OS 线程:COM 的 STA 模型要求同一线程执行所有 COM 调用。
+	// Go 的 goroutine 默认可在线程间迁移,必须 LockOSThread 固定,
+	// 否则跨线程访问 Explorer 的 COM 对象会破坏其单元状态(导致闪烁/卡死)。
+	runtime.LockOSThread()
+	defer runtime.UnlockOSThread()
+
+	// 整个 pollLoop 生命周期内 COM 只初始化一次,且从不 CoUninitialize。
+	// 之前的 bug:每次 readHoveredExplorerItem 都 CoInitializeEx + CoUninitialize,
+	// 且 S_FALSE(1)(线程已被他人初始化)时仍无条件 CoUninitialize,
+	// 误释放了 Wails 主线程的 COM → 资源管理器闪烁、无法点击。
+	if err := initComThread(); err != nil {
+		log.Printf("[explorer] COM 初始化失败: %v", err)
+		return
+	}
+
+	ticker := time.NewTicker(60 * time.Millisecond) // 每 60ms 检查一次鼠标位置
+	defer ticker.Stop()
+
+	// 状态机:
+	//   stateWaiting   — 等待鼠标移动
+	//   stateDebounce  — 已检测到移动,等待 120ms 让 explorer 稳定后再查询
+	//   stateHoverHold — 悬停项已稳定,再等 tagHoverDelay(1.0s)后查询标签库。
+	//                    若该路径有标签/备注则弹出「标签」气泡(鼠标正上方),
+	//                    无标签则不弹任何气泡(取消原「显示完整路径」提示)。
+	const (
+		stateWaiting = iota
+		stateDebounce
+		stateHoverHold
+	)
+	state := stateWaiting
+	debounceUntil := time.Time{}
+	holdUntil := time.Time{}
+	lastX, lastY := int32(0), int32(0)
+	haveLast := false
+	// shownAlertPath 记录当前正显示标签气泡的那条路径。
+	// 悬停项一变(鼠标移到别的文件、或移出列表导致读到空路径),就立即隐藏气泡,
+	// 而不是等它的显示时长走完——否则鼠标早已离开,气泡还挂在原地跟随鼠标。
+	shownAlertPath := ""
+	// emptyStreak 连续读到「空/非文件项」的次数。readHoveredExplorerItem 在鼠标
+	// 停在文件上时可能间歇返回空(COM 命中测试偶发落到列头/空白区),
+	// 若每次都立即隐藏气泡,气泡会刚出现就被关掉(用户几乎看不到)。
+	// 连续 emptyHideThreshold 次空返回才真正隐藏,过滤掉这种抖动。
+	emptyStreak := 0
+	const emptyHideThreshold = 3
+
+	// readOnce 只在「当前台是资源管理器」时查询一次悬停项,
+	// 其余时间不做 COM 调用,避免干扰 explorer。
+	// 悬停项变化时不再立即弹「完整路径」气泡,而是进入 stateHoverHold,
+	// 延迟 tagHoverDelay 后查询标签数据库(见 stateHoverHold 分支)。
+	readOnce := func() {
+		if !isForegroundExplorer() {
+			// 前台已不是资源管理器(鼠标移到了别的程序上):标签提示没有意义,
+			// 若还有气泡在显示则立即隐藏。
+			if shownAlertPath != "" {
+				shownAlertPath = ""
+				stopTagAlert()
+			}
+			return
+		}
+		path, ok := readHoveredExplorerItem()
+		if !ok || path == "" {
+			setTagHookCachedPath("") // 无悬停项时清空右键钩子缓存
+			// 连续多次读到空/非文件项,才认为鼠标确实移出文件列表并隐藏气泡。
+			// 单次空返回可能是 COM 命中测试抖动(鼠标仍停在文件上),
+			// 立即隐藏会让气泡刚出现就被关掉。
+			emptyStreak++
+			if emptyStreak >= emptyHideThreshold && shownAlertPath != "" {
+				shownAlertPath = ""
+				stopTagAlert()
+			}
+			return
+		}
+		emptyStreak = 0 // 读到有效文件项:清空空返回计数
+		s.mu.Lock()
+		// 用规范化路径比较(统一小写/分隔符),避免 COM 命中测试间歇返回
+		// 同一文件的大小写/分隔符变体(如 Z:\A.exe 与 z:\a.exe)被误判为
+		// 「悬停项变化」,导致气泡被误隐藏、stateHoverHold 被反复重置。
+		changed := normalizeTagPath(s.lastSel) != normalizeTagPath(path)
+		if changed {
+			s.lastSel = path
+			s.lastTime = time.Now()
+		}
+		s.mu.Unlock()
+
+		// 同步给右键菜单钩子作缓存:WH_MOUSE_LL 回调里有系统级超时
+		// (约 300ms),在那里做 COM 解析会被静默丢弃;钩子优先用此缓存。
+		setTagHookCachedPath(path)
+
+		if changed {
+			if shownAlertPath != "" {
+				// 悬停项切换到别的文件:旧文件的标签气泡不再适用,立即隐藏
+				shownAlertPath = ""
+				stopTagAlert()
+			}
+			state = stateHoverHold
+			// tagHoverDelay:鼠标停留该时长后才查库并弹提示,避免鼠标快速
+			// 扫过文件时频繁读写 SQLite。此常量固定写在程序中,可调优。
+			holdUntil = time.Now().Add(tagHoverDelay)
+		}
+	}
+
+	// queryTagAndAlert 查询标签库中是否记录了悬停项路径的标签/备注;
+	// 有则弹出「标签」气泡(鼠标正上方,avoidExplorerAlert=true 走 aboveMode),
+	// 无则静默(不弹任何气泡)。同时记录当前路径,供后续重复悬停去重。
+	queryTagAndAlert := func(path string) {
+		if path == "" {
+			return
+		}
+		tag, found, err := getTagSvc().GetTag(path)
+		if err != nil {
+			logTagErr("查询悬停标签", err)
+			return
+		}
+		// 有标签或备注才提示;两者皆空视为未打标签,不打扰。
+		if !found || (strings.TrimSpace(tag.Tag) == "" && strings.TrimSpace(tag.Note) == "") {
+			return
+		}
+		text := strings.TrimSpace(tag.Tag)
+		if note := strings.TrimSpace(tag.Note); note != "" {
+			if text != "" {
+				text += "  " // 标签与备注之间空两格分隔
+			}
+			text += note
+		}
+		triggerMouseAlertAbove(text)
+		shownAlertPath = path // 记录当前气泡对应的路径,便于悬停项变化时及时隐藏
+	}
+
+	for {
+		select {
+		case <-s.stopCh:
+			return
+		case now := <-ticker.C:
+			x, y, ok := cursorPos()
+			moved := ok && (!haveLast || x != lastX || y != lastY)
+			if moved {
+				haveLast = true
+				lastX, lastY = x, y
+			}
+
+			switch state {
+			case stateWaiting:
+				if moved {
+					state = stateDebounce
+					// 120ms:给 explorer 足够时间响应鼠标悬停,避免命中测试尚未就绪。
+					debounceUntil = now.Add(120 * time.Millisecond)
+				}
+			case stateDebounce:
+				if now.After(debounceUntil) {
+					readOnce()
+					if state == stateDebounce {
+						state = stateWaiting
+					}
+				}
+			case stateHoverHold:
+				if now.After(holdUntil) {
+					queryTagAndAlert(s.lastSel)
+					state = stateWaiting
+				}
+			}
+		}
+	}
+}

+ 23 - 0
explorerservice_other.go

@@ -0,0 +1,23 @@
+//go:build !windows
+
+package main
+
+// isForegroundExplorer 非 Windows 平台不支持,恒返回 false。
+func isForegroundExplorer() bool {
+	return false
+}
+
+// readHoveredExplorerItem 非 Windows 平台不支持。
+func readHoveredExplorerItem() (string, bool) {
+	return "", false
+}
+
+// initComThread 非 Windows 平台不需要初始化 COM。
+func initComThread() error {
+	return nil
+}
+
+// cursorPos 非 Windows 平台无鼠标坐标,恒返回 false。
+func cursorPos() (int32, int32, bool) {
+	return 0, 0, false
+}

+ 772 - 0
explorerservice_windows.go

@@ -0,0 +1,772 @@
+//go:build windows
+
+package main
+
+import (
+	"log"
+	"path/filepath"
+	"syscall"
+	"unsafe"
+
+	ole "github.com/go-ole/go-ole"
+)
+
+// ========== 前台进程 / 窗口查询 ==========
+
+var (
+	modKernel32 = syscall.NewLazyDLL("kernel32.dll")
+	modUser32   = syscall.NewLazyDLL("user32.dll")
+
+	procCreateToolhelp32Snapshot = modKernel32.NewProc("CreateToolhelp32Snapshot")
+	procProcess32FirstW          = modKernel32.NewProc("Process32FirstW")
+	procProcess32NextW           = modKernel32.NewProc("Process32NextW")
+	procGetForegroundWindow      = modUser32.NewProc("GetForegroundWindow")
+	procGetWindowThreadProcessId = modUser32.NewProc("GetWindowThreadProcessId")
+	procGetAncestor              = modUser32.NewProc("GetAncestor")
+	// 注意:procGetCursorPos 已在 mousealert_windows.go 中声明,此处不再重复。
+
+	// gaRoot:GA_ROOT = 返回指定窗口的根所有者窗口(顶层窗口)。
+	gaRoot = 2
+
+	// GetFileAttributesW 在 kernel32.dll(fileExists 检查路径真实存在)。
+	modKernel32B          = syscall.NewLazyDLL("kernel32.dll")
+	procGetFileAttributesW = modKernel32B.NewProc("GetFileAttributesW")
+
+	modOle32           = syscall.NewLazyDLL("ole32.dll")
+	procCoInit         = modOle32.NewProc("CoInitializeEx")
+	procCoTaskMemFree  = modOle32.NewProc("CoTaskMemFree")
+	procCoCreateInst   = modOle32.NewProc("CoCreateInstance")
+
+	// SysFreeString 在 oleaut32.dll(释放 BSTR)。
+	modOleaut32      = syscall.NewLazyDLL("oleaut32.dll")
+	procSysFreeString = modOleaut32.NewProc("SysFreeString")
+
+	// AccessibleObjectFromPoint / AccessibleObjectFromWindow 在 oleacc.dll。
+	// 鼠标悬停命中测试用前者(拿到鼠标下项的 IAccessible),
+	// 再经其 QueryInterface(IShellItem) 取完整路径。
+	modOleacc                     = syscall.NewLazyDLL("oleacc.dll")
+	procAccessibleObjectFromPoint = modOleacc.NewProc("AccessibleObjectFromPoint")
+)
+
+const (
+	th32csSnapProcess = 0x00000002
+	maxPath           = 260
+
+	// IID_IShellItem:鼠标命中项经 QI 取 IShellItem 后,
+	// 用 GetDisplayName(SIGDN_FILESYSPATH) 拿完整路径。
+	iidIShellItem = "{43826D1E-E718-42EE-BC55-A1E261C37BFE}"
+
+	// IID_IShellItemArray:DefView 的 IAccessible 可能实现此接口(含命中项),
+	// QI(IShellItem) 失败时回退用它取第一项。
+	iidIShellItemArray = "{B63EA76D-1F85-456F-A19C-48159EFA858B}"
+
+	// SIGDN_FILESYSPATH:IShellItem::GetDisplayName 请求的文件系统路径。
+	sigdnFileSysPath = 0x80058000
+
+	// CHILDID_SELF:IAccessible 代表自身(accHitTest 返回的叶子项常为自身)。
+	childIdSelf = 0
+
+	// VARIANT 类型标记
+	vtI4 = 3 // VT_I4
+
+	// ========== UI Automation 常量 ==========
+	// Win10/11 资源管理器文件项的 UIA ItemStatus 属性直接返回完整路径,
+	// 非文件项(任务栏/列头/浏览器)返回空字符串——天然过滤。
+	// 这是「悬停拿完整路径」最可靠的方案(MSAA 的 AccessibleObjectFromPoint
+	// 在 Win11 XAML 视图下不落到具体文件项,已实测确诊)。
+	clsidCuiAutomation = "{FF48DBA4-60EF-4201-AA87-54103EEF594E}" // CLSID_CUIAutomation
+	iidIUIAutomation   = "{30CBE57D-D9D0-452A-AB13-7AC5AC4825EE}" // IID_IUIAutomation
+	iidIUIAutomationElement = "{D22108AA-85C5-49DC-9F0A-0A42EE9420C3}" // IID_IUIAutomationElement
+
+	uiaItemStatusPropertyId = 30119 // UIA_ItemStatusPropertyId:文件完整路径
+	uiaControlTypePropertyId = 30003 // UIA_ControlTypePropertyId:判断是否文件项
+
+	// ControlType(用于过滤,可选)
+	uiaControlTypeListItem = 50008 // UIA_ListItemControlTypeId(文件项)
+	uiaControlTypeDataItem = 50024 // UIA_DataItemControlTypeId(数据网格项)
+)
+
+// processEntry32 对应 PROCESSENTRY32W。
+type processEntry32 struct {
+	Size            uint32
+	CntUsage        uint32
+	ProcessID       uint32
+	DefaultHeapID   uintptr
+	ModuleID        uint32
+	CntThreads      uint32
+	ParentProcessID uint32
+	PriClassBase    int32
+	Flags           uint32
+	ExeFile         [maxPath]uint16
+}
+
+// processName 返回 pid 对应进程名(小写,不含路径),找不到返回 ""。
+func processName(pid uint32) string {
+	snapshot, _, _ := procCreateToolhelp32Snapshot.Call(th32csSnapProcess, 0)
+	if snapshot == uintptr(syscall.InvalidHandle) {
+		return ""
+	}
+	defer syscall.CloseHandle(syscall.Handle(snapshot))
+
+	var entry processEntry32
+	entry.Size = uint32(unsafe.Sizeof(entry))
+	ret, _, _ := procProcess32FirstW.Call(snapshot, uintptr(unsafe.Pointer(&entry)))
+	for ret != 0 {
+		if entry.ProcessID == pid {
+			return syscall.UTF16ToString(entry.ExeFile[:])
+		}
+		ret, _, _ = procProcess32NextW.Call(snapshot, uintptr(unsafe.Pointer(&entry)))
+	}
+	return ""
+}
+
+// foregroundPid 返回前台窗口所属进程 PID。
+func foregroundPid() uint32 {
+	hwnd, _, _ := procGetForegroundWindow.Call()
+	if hwnd == 0 {
+		return 0
+	}
+	var pid uint32
+	procGetWindowThreadProcessId.Call(hwnd, uintptr(unsafe.Pointer(&pid)))
+	return pid
+}
+
+// isForegroundExplorer 前台窗口是否属于 explorer.exe。
+func isForegroundExplorer() bool {
+	pid := foregroundPid()
+	if pid == 0 {
+		return false
+	}
+	return processName(pid) == "explorer.exe"
+}
+
+// ========== COM 读取资源管理器选中项 ==========
+
+// initComThread 在 pollLoop 专用 goroutine 上一次性初始化 COM(STA)。
+// 必须在 runtime.LockOSThread 之后调用,且整个进程生命周期内不 CoUninitialize,
+// 避免跨线程 COM 调用和误释放他人初始化的单元。
+func initComThread() error {
+	hr, _, _ := procCoInit.Call(0, uintptr(ole.COINIT_APARTMENTTHREADED))
+	// S_OK(0) 与 S_FALSE(1)(该线程已初始化)都可接受,仅负 HRESULT 失败。
+	if int32(hr) < 0 {
+		return ole.NewError(hr)
+	}
+	return nil
+}
+
+// cursorPos 获取当前鼠标屏幕坐标。
+func cursorPos() (int32, int32, bool) {
+	var pt struct{ X, Y int32 }
+	r0, _, _ := procGetCursorPos.Call(uintptr(unsafe.Pointer(&pt)))
+	return pt.X, pt.Y, r0 != 0
+}
+
+// readHoveredExplorerItem 读取鼠标当前悬停的资源管理器项完整路径。
+//
+// 方案(复刻已验证的 AutoHotkey 实现):
+//  1. AccessibleObjectFromPoint(鼠标坐标) → IAccessible(MSAA 命中测试)
+//  2. 经 accHitTest/get_accChild 落到具体文件项
+//  3. get_accValue(vtable 11) → 文件名(AHK 的 oAcc.value)
+//  4. Shell.Application 当前窗口的 Document.Folder.Self.Path → 当前文件夹
+//  5. 拼接 fullPath = 文件夹 + "\" + 文件名,FileExist 验证真实存在
+//
+// 为什么读 accValue 而非 accName:实测确诊 accName 返回的是非文件项名称
+// (任务栏按钮/项目视图/列头「名称」),而 AHK 用 oAcc.value(= get_accValue)
+// 能拿到真实文件名,这是已被 AHK 验证可行的路径。
+//
+// 前置条件:pollLoop 已用 isForegroundExplorer() 确认前台是 explorer.exe。
+// 返回 (路径, true) 表示命中一个真实存在的文件系统项;否则 ("", false)。
+func readHoveredExplorerItem() (string, bool) {
+	x, y, ok := cursorPos()
+	if !ok {
+		return "", false
+	}
+
+	// 先确认鼠标在资源管理器窗口上(避免解析到桌面/其他程序)。
+	fg, _, _ := procGetForegroundWindow.Call()
+	if fg == 0 || !isForegroundExplorer() {
+		return "", false
+	}
+
+	// 1+2:MSAA 命中测试,落到具体文件项 IAccessible。
+	// AHK 的 Acc.ElementFromPoint 关键:AccessibleObjectFromPoint 拿到的常是
+	// 容器(childID=0),此时必须再对它调用 accHitTest(x,y) 精确命中文件项,
+	// 否则 get_accValue 读的是容器的 value(空),永远拿不到文件名。
+	acc, childID, err := accessibleObjectAtPoint(x, y)
+	if err != nil || acc == nil {
+		log.Printf("[explorer] AccessibleObjectFromPoint(%d,%d) 失败: %v acc=%v", x, y, err, acc == nil)
+		return "", false
+	}
+	log.Printf("[explorer] 命中: childID=%d name=%q", childID, accNameOfSafe(acc))
+	if childID == 0 {
+		// 容器自身:用 accHitTest 在鼠标坐标处精确命中子项。
+		if hitChild, err := accHitTest(acc, x, y); err == nil {
+			childID = hitChild
+			log.Printf("[explorer] accHitTest(%d,%d) → childID=%d", x, y, childID)
+		} else {
+			log.Printf("[explorer] accHitTest(%d,%d) 失败: %v", x, y, err)
+		}
+	}
+	target := acc
+	if childID != 0 {
+		childAcc, err := resolveChildAccessible(acc, childID)
+		if err != nil {
+			log.Printf("[explorer] get_accChild(childID=%d) 失败: %v", childID, err)
+			acc.Release()
+			return "", false
+		}
+		target = childAcc
+		acc.Release()
+	}
+	defer target.Release()
+
+	// 3:读 get_accValue = 文件名。
+	fileName, err := accValueOf(target)
+	if err != nil || fileName == "" {
+		log.Printf("[explorer] get_accValue 失败/空: err=%v name=%q", err, accNameOfSafe(target))
+		return "", false
+	}
+	log.Printf("[explorer] 文件名=%q", fileName)
+
+	// 4:当前资源管理器窗口的文件夹路径。
+	folderPath := currentExplorerFolderPath(fg)
+	if folderPath == "" {
+		log.Printf("[explorer] 当前文件夹路径为空(前台HWND=%d,Shell.Windows 遍历未找到有效 Document.Folder.Self.Path)", fg)
+		return "", false
+	}
+	log.Printf("[explorer] 文件夹=%q", folderPath)
+
+	// 5:拼接 + 存在性验证。
+	fullPath := filepath.Join(folderPath, fileName)
+	if !pathExists(fullPath) {
+		log.Printf("[explorer] 路径不存在: %q", fullPath)
+		return "", false
+	}
+	return fullPath, true
+}
+
+// accNameOfSafe 读取命中项的 accName(用于诊断日志,失败返回 "")。
+func accNameOfSafe(acc *ole.IUnknown) string {
+	name, err := accNameOf(acc)
+	if err != nil {
+		return ""
+	}
+	return name
+}
+
+// accValueOf 调用 IAccessible::get_accValue(vtable 11),返回命中项 value(文件名)。
+// 签名:HRESULT get_accValue(VARIANT varChild, BSTR *pszValue);varChild 按引用传。
+func accValueOf(acc *ole.IUnknown) (string, error) {
+	vtable := acc.VTable()
+	methodPtr := *(*uintptr)(unsafe.Pointer(uintptr(unsafe.Pointer(vtable)) + 11*unsafe.Sizeof(uintptr(0))))
+	var varChild struct {
+		vt        uint16
+		r1, r2, r3 uint16
+		lVal      int32
+		_         [12]byte
+	}
+	varChild.vt = vtI4
+	varChild.lVal = childIdSelf
+	var value *uint16
+	r0, _, _ := syscall.SyscallN(methodPtr,
+		uintptr(unsafe.Pointer(acc)),
+		uintptr(unsafe.Pointer(&varChild)),
+		uintptr(unsafe.Pointer(&value)))
+	if r0 != 0 || value == nil {
+		return "", ole.NewError(r0)
+	}
+	defer procSysFreeString.Call(uintptr(unsafe.Pointer(value)))
+	// BSTR 是标准布局:value 直接指向 WCHAR 数据开头,结尾有 null。
+	// 不用读「前 4 字节长度」(value-4 才是长度,且易受平台/封装差异影响),
+	// 改为逐字符扫描到 null——与 accNameOf 完全一致,已实测可靠。
+	var chars []uint16
+	for p := value; *p != 0; p = (*uint16)(unsafe.Pointer(uintptr(unsafe.Pointer(p)) + 2)) {
+		chars = append(chars, *p)
+	}
+	return syscall.UTF16ToString(chars), nil
+}
+
+// currentExplorerFolderPath 用 Shell.Application COM 获取前台资源管理器窗口
+// 当前标签页的文件夹路径(复刻 AHK GetActiveExplorerPath)。
+// 路径:Shell.Application → Windows → 匹配 HWND → Document → Folder → Self.Path。
+func currentExplorerFolderPath(hwnd uintptr) string {
+	// CoCreateInstance(CLSID_Shell="{13709620-C279-11CE-A49E-444553540000}", IID_IDispatch)
+	shellUnk, err := coCreateInstance("{13709620-C279-11CE-A49E-444553540000}", ole.IID_IDispatch.String())
+	if err != nil || shellUnk == nil {
+		log.Printf("[explorer] CoCreateInstance(Shell.Application) 失败: err=%v", err)
+		return ""
+	}
+	defer shellUnk.Release()
+
+	// *ole.IUnknown → *ole.IDispatch(go-ole 属性调用需要 IDispatch)。
+	shell, err := shellUnk.QueryInterface(ole.IID_IDispatch)
+	if err != nil || shell == nil {
+		log.Printf("[explorer] QI(IDispatch) 失败: err=%v", err)
+		return ""
+	}
+	defer shell.Release()
+
+	// 诊断:验证 Windows 成员是否可识别(区分「对象不是 Shell.Application」
+	// 与「Invoke 失败」)。CLSCTX_LOCAL_SERVER 若生效,这里应返回 dispid。
+	if dispid, err := shell.GetSingleIDOfName("Windows"); err != nil {
+		log.Printf("[explorer] 诊断: GetIDsOfNames(\"Windows\") 失败: err=%v(对象可能非 explorer.exe 的 Shell.Application)", err)
+	} else {
+		log.Printf("[explorer] 诊断: GetIDsOfNames(\"Windows\") → dispid=%d", dispid)
+	}
+
+	// windows := shell.Windows
+	// 关键:Shell.Application.Windows 是「方法」(DISPATCH_METHOD)而非属性。
+	// go-ole 的 GetProperty("Windows") 用 DISPATCH_PROPERTYGET 调用,
+	// 对仅方法的成员会返回 DISP_E_MEMBERNOTFOUND(「找不到成员」)——这是之前
+	// shell.Windows 失败的根因。AHK 的 obj.Windows 会自动在属性失败后回退到方法,
+	// 故 AHK 能工作。这里用 shellGetMember(先属性后方法回退)复刻 AHK 行为。
+	windows, err := shellGetMember(shell, "Windows")
+	if err != nil || windows == nil {
+		log.Printf("[explorer] shell.Windows 失败: err=%v win=%v", err, windows == nil)
+		return ""
+	}
+	defer windows.Release()
+
+	// count := windows.Count
+	count, err := shellGetInt(windows, "Count")
+	if err != nil || count <= 0 {
+		log.Printf("[explorer] windows.Count 失败: err=%v count=%d", err, count)
+		return ""
+	}
+	log.Printf("[explorer] Shell.Windows 窗口数=%d(前台HWND=%d)", count, hwnd)
+
+	// 前台 explorer 窗口必在 Windows 列表。直接遍历,取第一个能读出非空
+	// 文件夹路径的窗口即可(isForegroundExplorer 已确认前台是 explorer,
+	// 无需 HWND 精确比对——GetForegroundWindow 可能返回焦点子窗口,
+	// 与 Shell.Windows.Item(i).HWND 顶层窗口不匹配,这是之前失败的根因)。
+	for i := 0; i < int(count); i++ {
+		// win := windows.Item(i)
+		win, err := shellGetItem(windows, i)
+		if err != nil || win == nil {
+			log.Printf("[explorer] Windows.Item(%d) 失败: err=%v win=%v", i, err, win == nil)
+			continue
+		}
+		// doc := win.Document
+		doc, err := shellGetProperty(win, "Document")
+		if err != nil || doc == nil {
+			log.Printf("[explorer] Windows[%d].Document 失败: err=%v doc=%v", i, err, doc == nil)
+			win.Release()
+			continue
+		}
+		// folder := doc.Folder
+		folder, err := shellGetProperty(doc, "Folder")
+		doc.Release()
+		if err != nil || folder == nil {
+			log.Printf("[explorer] Windows[%d].Document.Folder 失败: err=%v folder=%v", i, err, folder == nil)
+			win.Release()
+			continue
+		}
+		// self := folder.Self
+		self, err := shellGetProperty(folder, "Self")
+		folder.Release()
+		if err != nil || self == nil {
+			log.Printf("[explorer] Windows[%d].Folder.Self 失败: err=%v self=%v", i, err, self == nil)
+			win.Release()
+			continue
+		}
+		// path := self.Path
+		path, err := shellGetString(self, "Path")
+		self.Release()
+		win.Release()
+		if err != nil {
+			log.Printf("[explorer] Windows[%d].Self.Path 读取失败: err=%v", i, err)
+			continue
+		}
+		if path != "" {
+			log.Printf("[explorer] 文件夹路径=%q(Windows[%d])", path, i)
+			return path
+		}
+		log.Printf("[explorer] Windows[%d].Self.Path 为空", i)
+	}
+	return ""
+}
+
+// coCreateInstance 创建 COM 类实例,返回指定接口的 *ole.IUnknown。
+func coCreateInstance(clsid, iid string) (*ole.IUnknown, error) {
+	var out *ole.IUnknown
+	r0, _, _ := procCoCreateInst.Call(
+		uintptr(unsafe.Pointer(ole.NewGUID(clsid))),
+		0,  // pUnkOuter = nil
+		1,  // CLSCTX_INPROC_SERVER:Shell.Application 只有 InprocServer32(shell32.dll),
+		// 无 LocalServer32(CLSCTX_LOCAL_SERVER(4) 会报 REGDB_E_CLASSNOTREG「没有注册类」)。
+		// AHK 的 ComObject("Shell.Application") 用 CLSCTX_ALL 也只能 fallback 到 Inproc,
+		// 说明 shell32.dll 的 CShellApplication 有 Windows 属性——go-ole GetIDsOfNames
+		// 对它不兼容的问题另行定位。
+		uintptr(unsafe.Pointer(ole.NewGUID(iid))),
+		uintptr(unsafe.Pointer(&out)))
+	if r0 != 0 || out == nil {
+		return nil, ole.NewError(r0)
+	}
+	return out, nil
+}
+
+// pathExists 检查路径是否存在(文件或文件夹,FileExist 等效)。
+// 注意:不能复用 webservice.go 的 fileExists(它排除目录),悬停文件夹也要显示路径。
+func pathExists(path string) bool {
+	p, _ := syscall.UTF16PtrFromString(path)
+	if p == nil {
+		return false
+	}
+	r0, _, _ := procGetFileAttributesW.Call(uintptr(unsafe.Pointer(p)))
+	return r0 != ^uintptr(0) // INVALID_FILE_ATTRIBUTES = -1
+}
+
+// shellGetProperty 读取 COM 对象的属性,返回 IDispatch 值(如 Document/Folder/Self)。
+//
+// 关键:go-ole 的 ToIDispatch() 只是裸指针转换,不 AddRef;而 VARIANT 持有该
+// 对象的一个引用,defer v.Clear()(VariantClear)会 Release 它。若不 AddRef,
+// 返回的 IDispatch 在函数返回时已被释放,调用方后续使用报 RPC_E_DISCONNECTED
+// (「对象没有连接到服务器」)——这是之前 windows.Count 失败的根因。
+// 故返回前 AddRef(),让 Clear 释放的只是额外引用,返回对象保持有效。
+func shellGetProperty(obj *ole.IDispatch, name string) (*ole.IDispatch, error) {
+	v, err := obj.GetProperty(name)
+	if err != nil || v == nil {
+		return nil, err
+	}
+	defer v.Clear()
+	if v.Value() == nil {
+		return nil, nil
+	}
+	disp := v.ToIDispatch()
+	if disp == nil {
+		return nil, nil
+	}
+	disp.AddRef()
+	return disp, nil
+}
+
+// shellGetInt 读取 COM 对象的整型属性(如 Count/HWND)。
+func shellGetInt(obj *ole.IDispatch, name string) (int64, error) {
+	v, err := obj.GetProperty(name)
+	if err != nil || v == nil {
+		return 0, err
+	}
+	defer v.Clear()
+	if v.Value() == nil {
+		return 0, nil
+	}
+	switch n := v.Value().(type) {
+	case int:
+		return int64(n), nil
+	case int32:
+		return int64(n), nil
+	case int64:
+		return n, nil
+	case float64:
+		return int64(n), nil
+	default:
+		return 0, nil
+	}
+}
+
+// shellGetString 读取 COM 对象的字符串属性(如 Path)。
+func shellGetString(obj *ole.IDispatch, name string) (string, error) {
+	v, err := obj.GetProperty(name)
+	if err != nil || v == nil {
+		return "", err
+	}
+	defer v.Clear()
+	if v.Value() == nil {
+		return "", nil
+	}
+	return v.ToString(), nil
+}
+
+// shellGetItem 调用 COM 集合的 Item(index) 方法(DISPATCH_METHOD),返回 IDispatch。
+// 注意:Item 是方法不是属性,必须用 CallMethod,用 GetProperty 会失败。
+// 返回前 AddRef()(见 shellGetProperty 的说明,防 VariantClear 提前释放对象)。
+func shellGetItem(obj *ole.IDispatch, index int) (*ole.IDispatch, error) {
+	v, err := obj.CallMethod("Item", index)
+	if err != nil || v == nil {
+		return nil, err
+	}
+	defer v.Clear()
+	if v.Value() == nil {
+		return nil, nil
+	}
+	disp := v.ToIDispatch()
+	if disp == nil {
+		return nil, nil
+	}
+	disp.AddRef()
+	return disp, nil
+}
+
+// shellGetMember 读取 COM 成员并返回 IDispatch 值,兼容属性与无参方法。
+//
+// 背景:Shell.Application.Windows 在类型库中是「方法」(Windows()),
+// 而 Document/Folder/Self/Path 是属性。go-ole 的 GetProperty 对仅方法的成员
+// 调用 DISPATCH_PROPERTYGET 会返回 DISP_E_MEMBERNOTFOUND,导致之前
+// shell.Windows 一直失败。AHK 的 obj.Windows 会自动在属性失败后回退到方法调用
+// (DISPATCH_METHOD),故 AHK 能工作。此函数复刻该回退行为:
+//  1. 先按属性读(DISPATCH_PROPERTYGET)——多数成员是属性,一步到位;
+//  2. 属性读失败则按无参方法调用(DISPATCH_METHOD)——覆盖 Windows 这种方法。
+func shellGetMember(obj *ole.IDispatch, name string) (*ole.IDispatch, error) {
+	// 1) 属性读(多数成员是属性)。
+	v, err := obj.GetProperty(name)
+	if err != nil {
+		// 属性读失败(如 Shell.Windows 是方法而非属性)→ 释放并回退到方法。
+		// 注意:go-ole 的 Invoke 失败时也可能返回非 nil 的 VARIANT,须 Clear。
+		if v != nil {
+			v.Clear()
+		}
+	} else {
+		defer v.Clear()
+		if v.Value() == nil {
+			return nil, nil
+		}
+		disp := v.ToIDispatch()
+		if disp == nil {
+			return nil, nil
+		}
+		disp.AddRef() // 防 VariantClear 提前释放对象(见 shellGetProperty 说明)
+		return disp, nil
+	}
+	// 2) 回退:无参方法调用(如 Shell.Windows())。
+	v, err = obj.CallMethod(name)
+	if err != nil || v == nil {
+		return nil, err
+	}
+	defer v.Clear()
+	if v.Value() == nil {
+		return nil, nil
+	}
+	disp := v.ToIDispatch()
+	if disp == nil {
+		return nil, nil
+	}
+	disp.AddRef()
+	return disp, nil
+}
+
+// accessibleObjectAtPoint 调用 AccessibleObjectFromPoint,返回命中项的 IAccessible
+// 及其 childID。accChild 参数是 [in/out]:传 CHILDID_SELF,命中叶子项时回填实际 childID。
+// AccessibleObjectFromPoint 是 COM 方法,返回的是 IAccessible*(作为 *ole.IUnknown 接收)。
+func accessibleObjectAtPoint(x, y int32) (*ole.IUnknown, int32, error) {
+	// POINT {x, y}
+	var pt struct{ X, Y int32 }
+	pt.X = x
+	pt.Y = y
+
+	// VARIANT varChild:输入 VT_I4 + lVal=CHILDID_SELF,输出回填命中子项 ID。
+	var varChild struct {
+		vt        uint16
+		r1, r2, r3 uint16
+		lVal      int32
+		_         [12]byte
+	}
+	varChild.vt = vtI4
+	varChild.lVal = childIdSelf
+
+	var acc *ole.IUnknown
+	// AccessibleObjectFromPoint(POINT, IAccessible**, VARIANT*)
+	// 签名:HRESULT AccessibleObjectFromPoint(POINT ptScreen, IAccessible** ppacc, VARIANT* pvarChild)
+	//
+	// 关键:x64 Windows 调用约定下,8 字节结构体(POINT)按值通过单个整数
+	// 寄存器传递——低 32 位放 x,高 32 位放 y。绝不能传 &pt(那会变成「把
+	// 地址当作坐标」,导致命中坐标完全错误)。故把 POINT 打包进一个 uintptr。
+	ptVal := uintptr(uint32(pt.X)) | (uintptr(uint32(pt.Y)) << 32)
+	r0, _, _ := procAccessibleObjectFromPoint.Call(
+		ptVal,
+		uintptr(unsafe.Pointer(&acc)),
+		uintptr(unsafe.Pointer(&varChild)))
+	if r0 != 0 || acc == nil {
+		return nil, 0, ole.NewError(r0)
+	}
+	return acc, varChild.lVal, nil
+}
+
+// resolveChildAccessible 若命中的是容器(childID>0),调用 get_accChild 取出真正的
+// 子项 IAccessible。childID=0 表示 acc 本身即命中项(资源管理器单个文件项常如此)。
+//
+// get_accChild 是 IAccessible 方法,vtable 索引 9(不是 6!):
+//   IAccessible 继承 IDispatch:IUnknown(0-2) + IDispatch(3-6: GetTypeInfoCount@3,
+//   GetTypeInfo@4, GetIDsOfNames@5, Invoke@6) + IAccessible 自有(get_accParent@7,
+//   get_accChildCount@8, get_accChild@9, ...)。
+// 之前误用 6(那是 IDispatch::Invoke),会调用到错误函数指针导致子项解析失败。
+//
+// 签名:HRESULT get_accChild(VARIANT varChild, IDispatch **ppdispChild);
+// VARIANT 是 24 字节结构体,x64 下 >8 字节结构体必须按引用传递(传 &varChild),
+// 不能按值打包。之前按值打包成 8 字节同样错误。
+func resolveChildAccessible(acc *ole.IUnknown, childID int32) (*ole.IUnknown, error) {
+	if childID == 0 {
+		return acc, nil // acc 自身即命中项
+	}
+	vtable := acc.VTable()
+	methodPtr := *(*uintptr)(unsafe.Pointer(uintptr(unsafe.Pointer(vtable)) + 9*unsafe.Sizeof(uintptr(0))))
+
+	// VARIANT:vt=VT_I4(3),union.lVal=childID。24 字节:
+	// header 8 字节(vt@0 + 保留 6 字节),union 16 字节从 offset 8 开始,
+	// lVal 是 union 第一个成员(offset 8)。
+	var varChild struct {
+		vt        uint16
+		r1, r2, r3 uint16
+		lVal      int32
+		_         [12]byte
+	}
+	varChild.vt = vtI4
+	varChild.lVal = childID
+
+	var childDisp *ole.IDispatch
+	r0, _, _ := syscall.SyscallN(methodPtr,
+		uintptr(unsafe.Pointer(acc)),
+		uintptr(unsafe.Pointer(&varChild)), // VARIANT 按引用传递(24字节 > 8字节)
+		uintptr(unsafe.Pointer(&childDisp)))
+	if r0 != 0 || childDisp == nil {
+		return nil, ole.NewError(r0)
+	}
+	return (*ole.IUnknown)(unsafe.Pointer(childDisp)), nil
+}
+
+// accHitTest 调用 IAccessible::accHitTest(vtable 24),在容器上按坐标精确命中子项,
+// 返回命中子项的 childID。这是 AHK Acc.ElementFromPoint 的关键步骤:
+// AccessibleObjectFromPoint 拿到的常是容器(childID=0),需 accHitTest 落到文件项。
+//
+// IAccessible vtable(IUnknown 0-2 + IDispatch 3-6 + 自有):
+//   get_accParent@7, get_accChildCount@8, get_accChild@9, get_accName@10,
+//   get_accValue@11, ..., accSelect@21, accLocation@22, accNavigate@23,
+//   accHitTest@24, accDoDefaultAction@25。
+//
+// 签名:HRESULT accHitTest(long xLeft, long yTop, VARIANT *pvarChild);
+func accHitTest(acc *ole.IUnknown, x, y int32) (int32, error) {
+	vtable := acc.VTable()
+	methodPtr := *(*uintptr)(unsafe.Pointer(uintptr(unsafe.Pointer(vtable)) + 24*unsafe.Sizeof(uintptr(0))))
+	var varChild struct {
+		vt        uint16
+		r1, r2, r3 uint16
+		lVal      int32
+		_         [12]byte
+	}
+	varChild.vt = vtI4
+	varChild.lVal = childIdSelf
+	r0, _, _ := syscall.SyscallN(methodPtr,
+		uintptr(unsafe.Pointer(acc)),
+		uintptr(x),
+		uintptr(y),
+		uintptr(unsafe.Pointer(&varChild)))
+	if r0 != 0 {
+		return 0, ole.NewError(r0)
+	}
+	return varChild.lVal, nil
+}
+
+// shellItemPathFromAccessible 从命中项 IAccessible 提取完整文件系统路径。
+// 路径:IAccessible → QI(IShellItem) → GetDisplayName(SIGDN_FILESYSPATH)。
+// 若 QI 失败(非文件系统项,如工具栏/空白),返回 ("", false)。
+func shellItemPathFromAccessible(acc *ole.IUnknown) (string, bool) {
+	// 诊断:打印命中项的名称,判断 MSAA 是否到了文件项。
+	name, _ := accNameOf(acc)
+
+	// 路径 1:直接 QI(IShellItem)。
+	// 对资源管理器的文件项,IAccessible 对象同时实现 IShellItem。
+	if item, err := acc.QueryInterface(ole.NewGUID(iidIShellItem)); err == nil && item != nil {
+		defer item.Release()
+		// QueryInterface 返回 *ole.IDispatch,但其底层对象是 IShellItem;
+		// 转成 *ole.IUnknown 后按 IShellItem vtable 调用 GetDisplayName。
+		itemUnk := (*ole.IUnknown)(unsafe.Pointer(item))
+		if path, ok := shellItemDisplayName(itemUnk, sigdnFileSysPath); ok {
+			return path, true
+		}
+		log.Printf("[explorer] QI(IShellItem) 成功但 GetDisplayName 失败: name=%q", name)
+	} else {
+		log.Printf("[explorer] QI(IShellItem) 失败(err=%v): name=%q", err, name)
+	}
+
+	// 路径 2:回退 QI(IShellItemArray),取第一项。
+	// 某些视图(DefView 容器)的 IAccessible 实现 IShellItemArray,项 0 即命中项。
+	if arr, err := acc.QueryInterface(ole.NewGUID(iidIShellItemArray)); err == nil && arr != nil {
+		defer arr.Release()
+		arrUnk := (*ole.IUnknown)(unsafe.Pointer(arr))
+		if item := shellItemArrayAt(arrUnk, 0); item != nil {
+			defer item.Release()
+			if path, ok := shellItemDisplayName(item, sigdnFileSysPath); ok {
+				return path, true
+			}
+		}
+		log.Printf("[explorer] QI(IShellItemArray) 成功但取项/显示名失败: name=%q", name)
+	} else {
+		log.Printf("[explorer] QI(IShellItemArray) 也失败(err=%v): name=%q", err, name)
+	}
+
+	return "", false
+}
+
+// accNameOf 调用 IAccessible::get_accName(vtable 10),返回命中项显示名(诊断用)。
+// 签名:HRESULT get_accName(VARIANT varChild, BSTR *pszName);varChild 按引用传。
+func accNameOf(acc *ole.IUnknown) (string, error) {
+	vtable := acc.VTable()
+	methodPtr := *(*uintptr)(unsafe.Pointer(uintptr(unsafe.Pointer(vtable)) + 10*unsafe.Sizeof(uintptr(0))))
+	var varChild struct {
+		vt        uint16
+		r1, r2, r3 uint16
+		lVal      int32
+		_         [12]byte
+	}
+	varChild.vt = vtI4
+	varChild.lVal = childIdSelf
+	var name *uint16
+	r0, _, _ := syscall.SyscallN(methodPtr,
+		uintptr(unsafe.Pointer(acc)),
+		uintptr(unsafe.Pointer(&varChild)),
+		uintptr(unsafe.Pointer(&name)))
+	if r0 != 0 || name == nil {
+		return "", ole.NewError(r0)
+	}
+	defer procSysFreeString.Call(uintptr(unsafe.Pointer(name)))
+	var chars []uint16
+	for p := name; *p != 0; p = (*uint16)(unsafe.Pointer(uintptr(unsafe.Pointer(p)) + 2)) {
+		chars = append(chars, *p)
+	}
+	return syscall.UTF16ToString(chars), nil
+}
+
+// shellItemArrayAt 从 IShellItemArray 取第 index 项。
+// IShellItemArray vtable:IUnknown(3) + GetType@3 + GetCount@4 + GetItemAt@5 +
+// EnumItems@6 + ...。故 GetItemAt 在 vtable 索引 5。
+// GetItemAt(DWORD dwIndex, IShellItem **ppsi)。
+func shellItemArrayAt(arr *ole.IUnknown, index uint32) *ole.IUnknown {
+	vtable := arr.VTable()
+	methodPtr := *(*uintptr)(unsafe.Pointer(uintptr(unsafe.Pointer(vtable)) + 5*unsafe.Sizeof(uintptr(0))))
+	var item *ole.IUnknown
+	r0, _, _ := syscall.SyscallN(methodPtr,
+		uintptr(unsafe.Pointer(arr)),
+		uintptr(index),
+		uintptr(unsafe.Pointer(&item)))
+	if r0 != 0 || item == nil {
+		return nil
+	}
+	return item
+}
+
+// shellItemDisplayName 调用 IShellItem::GetDisplayName(SIGDN_FILESYSPATH)。
+// IShellItem vtable:IUnknown(3) + BindToHandler@3 + GetParent@4 + GetDisplayName@5 +
+// GetAttributes@6 + Compare@7。故 GetDisplayName 在 vtable 索引 5。
+// GetDisplayName(SIGDN, LPWSTR** ppszName),返回的字符串用 CoTaskMemFree 释放。
+func shellItemDisplayName(item *ole.IUnknown, sigdn uint32) (string, bool) {
+	vtable := item.VTable()
+	methodPtr := *(*uintptr)(unsafe.Pointer(uintptr(unsafe.Pointer(vtable)) + 5*unsafe.Sizeof(uintptr(0))))
+	var psz *uint16
+	r0, _, _ := syscall.SyscallN(methodPtr,
+		uintptr(unsafe.Pointer(item)),
+		uintptr(sigdn),
+		uintptr(unsafe.Pointer(&psz)))
+	if r0 != 0 || psz == nil {
+		return "", false
+	}
+	defer procCoTaskMemFree.Call(uintptr(unsafe.Pointer(psz)))
+
+	// 手动扫描到 null 确定字符串长度,再转 string。
+	// 不直接用 unsafe.Slice(psz, 固定上限):GetDisplayName 返回的缓冲区实际
+	// 长度不可预知,固定上限可能越界;扫描到 null 是安全做法。
+	var chars []uint16
+	for p := psz; *p != 0; p = (*uint16)(unsafe.Pointer(uintptr(unsafe.Pointer(p)) + 2)) {
+		chars = append(chars, *p)
+	}
+	return syscall.UTF16ToString(chars), true
+}
+

+ 45 - 0
frontend/bindings/TengTuToolbox/explorerservice.js

@@ -0,0 +1,45 @@
+// @ts-check
+// Cynhyrchwyd y ffeil hon yn awtomatig. PEIDIWCH Â MODIWL
+// This file is automatically generated. DO NOT EDIT
+
+/**
+ * explorerService 缓存最近一次从资源管理器读到的鼠标悬停项(完整路径)。
+ * 后台轮询:当前台窗口是资源管理器且有鼠标悬停项时更新缓存。
+ * 当检测到悬停项发生变化(与上次缓存不同)时,在鼠标旁弹出临时提示
+ * 显示完整路径(复用系统级 mousealert 置顶气泡,无需切换到 Wails 窗口)。
+ * 
+ * 可启停:Start/Stop 可反复调用(「配置→系统」关闭标签功能时 Stop 停止轮询,
+ * 重新启用时 Start 再启动)。Stop 关闭 stopCh 令 pollLoop 退出;Start 重建
+ * stopCh 并启动新 pollLoop。
+ * @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";
+
+/**
+ * LastSelection 返回最近一次读到的悬停项完整路径,无则 ""。
+ * 注意:方法名保留 LastSelection 以匹配 Wails 绑定(绑定 ID 哈希只依赖方法全名,
+ * 改方法名会导致前端绑定失效)。语义已从「选中项列表」变为「悬停项单个路径」。
+ * @returns {$CancellablePromise<string>}
+ */
+export function LastSelection() {
+    return $Call.ByID(869620300);
+}
+
+/**
+ * Start 启动后台轮询 goroutine。若已在运行则无操作;Stop 后再次调用可重新启动。
+ * @returns {$CancellablePromise<void>}
+ */
+export function Start() {
+    return $Call.ByID(1659257734);
+}
+
+/**
+ * Stop 停止后台轮询。若已停止则无操作。
+ * @returns {$CancellablePromise<void>}
+ */
+export function Stop() {
+    return $Call.ByID(19212526);
+}

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

@@ -11,6 +11,7 @@ import * as MemosService from "./memosservice.js";
 import * as ProxyService from "./proxyservice.js";
 import * as QuickService from "./quickservice.js";
 import * as SettingsService from "./settingsservice.js";
+import * as TagService from "./tagservice.js";
 import * as UDPService from "./udpservice.js";
 import * as YTDLPService from "./ytdlpservice.js";
 export {
@@ -23,6 +24,7 @@ export {
     ProxyService,
     QuickService,
     SettingsService,
+    TagService,
     UDPService,
     YTDLPService
 };
@@ -62,6 +64,7 @@ export {
     RepoItem,
     ServiceModeStatus,
     StockQuote,
+    TagInfo,
     TickerConfig,
     TranslateResult,
     TrendingRepo,

+ 130 - 40
frontend/bindings/TengTuToolbox/models.js

@@ -183,6 +183,14 @@ export class AppSettings {
              */
             this["biliCookie"] = "";
         }
+        if (!("biliPopularEnabled" in $$source)) {
+            /**
+             * 新闻页是否显示 B站热门视频区块(默认开启)
+             * @member
+             * @type {boolean}
+             */
+            this["biliPopularEnabled"] = false;
+        }
         if (!("githubRepos" in $$source)) {
             /**
              * 关注的 GitHub 仓库列表
@@ -303,6 +311,22 @@ export class AppSettings {
              */
             this["recordDBPath"] = "";
         }
+        if (!("tagDBPath" in $$source)) {
+            /**
+             * 文件标签数据库路径:SQLite3(资源管理器右键「标签」与悬停标签提示使用)
+             * @member
+             * @type {string}
+             */
+            this["tagDBPath"] = "";
+        }
+        if (!("tagMenuEnabled" in $$source)) {
+            /**
+             * 资源管理器右键「标签」功能开关:false=关闭右键菜单+停止监听悬停(默认启用)
+             * @member
+             * @type {boolean}
+             */
+            this["tagMenuEnabled"] = false;
+        }
         if (!("backupDir" in $$source)) {
             /**
              * 文本文件备份目录(文件类自定义 Tab「备份」按钮使用)
@@ -508,23 +532,23 @@ export class AppSettings {
         const $$createField9_0 = $$createType0;
         const $$createField10_0 = $$createType0;
         const $$createField11_0 = $$createType2;
-        const $$createField14_0 = $$createType4;
-        const $$createField15_0 = $$createType6;
-        const $$createField16_0 = $$createType8;
-        const $$createField17_0 = $$createType10;
-        const $$createField18_0 = $$createType12;
-        const $$createField30_0 = $$createType13;
-        const $$createField31_0 = $$createType13;
-        const $$createField32_0 = $$createType14;
-        const $$createField33_0 = $$createType15;
-        const $$createField44_0 = $$createType16;
-        const $$createField45_0 = $$createType17;
-        const $$createField46_0 = $$createType18;
-        const $$createField47_0 = $$createType19;
-        const $$createField48_0 = $$createType20;
-        const $$createField49_0 = $$createType0;
-        const $$createField50_0 = $$createType21;
-        const $$createField52_0 = $$createType22;
+        const $$createField15_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;
         let $$parsedSource = typeof $$source === 'string' ? JSON.parse($$source) : $$source;
         if ("tabOrder" in $$parsedSource) {
             $$parsedSource["tabOrder"] = $$createField9_0($$parsedSource["tabOrder"]);
@@ -536,55 +560,55 @@ export class AppSettings {
             $$parsedSource["links"] = $$createField11_0($$parsedSource["links"]);
         }
         if ("githubRepos" in $$parsedSource) {
-            $$parsedSource["githubRepos"] = $$createField14_0($$parsedSource["githubRepos"]);
+            $$parsedSource["githubRepos"] = $$createField15_0($$parsedSource["githubRepos"]);
         }
         if ("customTabs" in $$parsedSource) {
-            $$parsedSource["customTabs"] = $$createField15_0($$parsedSource["customTabs"]);
+            $$parsedSource["customTabs"] = $$createField16_0($$parsedSource["customTabs"]);
         }
         if ("localTools" in $$parsedSource) {
-            $$parsedSource["localTools"] = $$createField16_0($$parsedSource["localTools"]);
+            $$parsedSource["localTools"] = $$createField17_0($$parsedSource["localTools"]);
         }
         if ("quickGroups" in $$parsedSource) {
-            $$parsedSource["quickGroups"] = $$createField17_0($$parsedSource["quickGroups"]);
+            $$parsedSource["quickGroups"] = $$createField18_0($$parsedSource["quickGroups"]);
         }
         if ("controlKeys" in $$parsedSource) {
-            $$parsedSource["controlKeys"] = $$createField18_0($$parsedSource["controlKeys"]);
+            $$parsedSource["controlKeys"] = $$createField19_0($$parsedSource["controlKeys"]);
         }
         if ("stockTicker" in $$parsedSource) {
-            $$parsedSource["stockTicker"] = $$createField30_0($$parsedSource["stockTicker"]);
+            $$parsedSource["stockTicker"] = $$createField33_0($$parsedSource["stockTicker"]);
         }
         if ("newsTicker" in $$parsedSource) {
-            $$parsedSource["newsTicker"] = $$createField31_0($$parsedSource["newsTicker"]);
+            $$parsedSource["newsTicker"] = $$createField34_0($$parsedSource["newsTicker"]);
         }
         if ("poem" in $$parsedSource) {
-            $$parsedSource["poem"] = $$createField32_0($$parsedSource["poem"]);
+            $$parsedSource["poem"] = $$createField35_0($$parsedSource["poem"]);
         }
         if ("mouseAlert" in $$parsedSource) {
-            $$parsedSource["mouseAlert"] = $$createField33_0($$parsedSource["mouseAlert"]);
+            $$parsedSource["mouseAlert"] = $$createField36_0($$parsedSource["mouseAlert"]);
         }
         if ("localSend" in $$parsedSource) {
-            $$parsedSource["localSend"] = $$createField44_0($$parsedSource["localSend"]);
+            $$parsedSource["localSend"] = $$createField47_0($$parsedSource["localSend"]);
         }
         if ("croc" in $$parsedSource) {
-            $$parsedSource["croc"] = $$createField45_0($$parsedSource["croc"]);
+            $$parsedSource["croc"] = $$createField48_0($$parsedSource["croc"]);
         }
         if ("ytdlp" in $$parsedSource) {
-            $$parsedSource["ytdlp"] = $$createField46_0($$parsedSource["ytdlp"]);
+            $$parsedSource["ytdlp"] = $$createField49_0($$parsedSource["ytdlp"]);
         }
         if ("memos" in $$parsedSource) {
-            $$parsedSource["memos"] = $$createField47_0($$parsedSource["memos"]);
+            $$parsedSource["memos"] = $$createField50_0($$parsedSource["memos"]);
         }
         if ("brightness" in $$parsedSource) {
-            $$parsedSource["brightness"] = $$createField48_0($$parsedSource["brightness"]);
+            $$parsedSource["brightness"] = $$createField51_0($$parsedSource["brightness"]);
         }
         if ("toolOrder" in $$parsedSource) {
-            $$parsedSource["toolOrder"] = $$createField49_0($$parsedSource["toolOrder"]);
+            $$parsedSource["toolOrder"] = $$createField52_0($$parsedSource["toolOrder"]);
         }
         if ("gitLab" in $$parsedSource) {
-            $$parsedSource["gitLab"] = $$createField50_0($$parsedSource["gitLab"]);
+            $$parsedSource["gitLab"] = $$createField53_0($$parsedSource["gitLab"]);
         }
         if ("proxy" in $$parsedSource) {
-            $$parsedSource["proxy"] = $$createField52_0($$parsedSource["proxy"]);
+            $$parsedSource["proxy"] = $$createField55_0($$parsedSource["proxy"]);
         }
         return new AppSettings(/** @type {Partial<AppSettings>} */($$parsedSource));
     }
@@ -957,8 +981,9 @@ export class CustomTab {
 }
 
 /**
- * GitLabConfig 私有 GitLab(git.scwy.net)自动升级配置。
- * PrivateToken 为空时也可从 gitlab-cred.json 读取,避免令牌明文进设置文件。
+ * GitLabConfig 自动升级配置(静态更新站方案)。
+ * BaseURL 为静态站目录地址,清单固定放在 {BaseURL}/manifest.json,无需鉴权。
+ * ProjectPath / PrivateToken / Branch 为旧私有仓库方案遗留字段,不再参与,保留以兼容旧配置。
  */
 export class GitLabConfig {
     /**
@@ -968,7 +993,7 @@ export class GitLabConfig {
     constructor($$source = {}) {
         if (!("baseUrl" in $$source)) {
             /**
-             * GitLab 根地址,如 https://git.scwy.net
+             * 静态更新站目录地址,如 https://i.scwy.net/down/toolsbox
              * @member
              * @type {string}
              */
@@ -976,7 +1001,7 @@ export class GitLabConfig {
         }
         if (!("projectPath" in $$source)) {
             /**
-             * 项目路径,如 ease/toolbox
+             * (旧字段,不再使用)
              * @member
              * @type {string}
              */
@@ -984,7 +1009,7 @@ export class GitLabConfig {
         }
         if (!("privateToken" in $$source)) {
             /**
-             * 私有访问令牌(PRIVATE_TOKEN)
+             * (旧字段,不再使用)
              * @member
              * @type {string}
              */
@@ -992,7 +1017,7 @@ export class GitLabConfig {
         }
         if (!("branch" in $$source)) {
             /**
-             * 版本清单所在分支或 Tag,默认 main
+             * (旧字段,不再使用)
              * @member
              * @type {string}
              */
@@ -2445,6 +2470,63 @@ export class StockQuote {
     }
 }
 
+/**
+ * TagInfo 一条文件标签:完整路径 + 标签 + 备注 + 更新时间。
+ * 供前端设置页/标签管理 UI 与后端悬停提示使用。
+ */
+export class TagInfo {
+    /**
+     * Creates a new TagInfo instance.
+     * @param {Partial<TagInfo>} [$$source = {}] - The source object to create the TagInfo.
+     */
+    constructor($$source = {}) {
+        if (!("path" in $$source)) {
+            /**
+             * 完整路径(已规范化:小写 + Clean)
+             * @member
+             * @type {string}
+             */
+            this["path"] = "";
+        }
+        if (!("tag" in $$source)) {
+            /**
+             * 标签(可空)
+             * @member
+             * @type {string}
+             */
+            this["tag"] = "";
+        }
+        if (!("note" in $$source)) {
+            /**
+             * 备注(可空)
+             * @member
+             * @type {string}
+             */
+            this["note"] = "";
+        }
+        if (!("updatedAt" in $$source)) {
+            /**
+             * 最近更新时间 YYYY-MM-DD HH:MM:SS
+             * @member
+             * @type {string}
+             */
+            this["updatedAt"] = "";
+        }
+
+        Object.assign(this, $$source);
+    }
+
+    /**
+     * Creates a new TagInfo instance from a string or object.
+     * @param {any} [$$source = {}]
+     * @returns {TagInfo}
+     */
+    static createFrom($$source = {}) {
+        let $$parsedSource = typeof $$source === 'string' ? JSON.parse($$source) : $$source;
+        return new TagInfo(/** @type {Partial<TagInfo>} */($$parsedSource));
+    }
+}
+
 /**
  * TickerConfig 置顶滚动条(股票 / 新闻)的显示配置
  */
@@ -2790,6 +2872,14 @@ export class WebServiceInfo {
              */
             this["url"] = "";
         }
+        if (!("port" in $$source)) {
+            /**
+             * 监听端口
+             * @member
+             * @type {number}
+             */
+            this["port"] = 0;
+        }
         if (!("indexName" in $$source)) {
             /**
              * 实际用作默认页的文件(index.html / readme.md / 空)

+ 59 - 34
frontend/bindings/TengTuToolbox/settingsservice.js

@@ -54,6 +54,18 @@ export function CaptureScreen(display) {
     return $Call.ByID(2784207426, display);
 }
 
+/**
+ * CheckUpdateDialog 设置页「检查更新」按钮:手动检查一次,发现新版本直接弹原生对话框
+ * (立即升级 / 暂时跳过 / 此版不再提示)。已最新时返回 upToDate=true 供前端提示;
+ * 检查失败返回 message 供前端显示错误。
+ * @returns {$CancellablePromise<{ [_ in string]?: any }>}
+ */
+export function CheckUpdateDialog() {
+    return $Call.ByID(3461986409).then(/** @type {($result: any) => any} */(($result) => {
+        return $$createType0($result);
+    }));
+}
+
 /**
  * CheckUpdateManual 手动检查新版本(「更新」Tab 的「检查更新」按钮调用)。
  * 检查结果经 wails:updater:* 事件推送给前端,这里返回检查后的状态快照。
@@ -134,6 +146,17 @@ export function GetGithubFeeds() {
     }));
 }
 
+/**
+ * GetHotkeyStatus 返回三个热键的注册状态(空字符串=已生效;非空=占用/失败原因),
+ * 供设置页在热键输入框旁显示冲突提示,例如默认组合键被其他程序占用时。
+ * @returns {$CancellablePromise<{ [_ in string]?: string }>}
+ */
+export function GetHotkeyStatus() {
+    return $Call.ByID(2857242844).then(/** @type {($result: any) => any} */(($result) => {
+        return $$createType6($result);
+    }));
+}
+
 /**
  * GetKLine 拉取指定股票的日 K 数据,count 为交易日数量
  * @param {string} code
@@ -142,7 +165,7 @@ export function GetGithubFeeds() {
  */
 export function GetKLine(code, count) {
     return $Call.ByID(1009336803, code, count).then(/** @type {($result: any) => any} */(($result) => {
-        return $$createType7($result);
+        return $$createType8($result);
     }));
 }
 
@@ -177,7 +200,7 @@ export function GetLEDText() {
  */
 export function GetMinuteChart(code) {
     return $Call.ByID(1171130824, code).then(/** @type {($result: any) => any} */(($result) => {
-        return $$createType8($result);
+        return $$createType9($result);
     }));
 }
 
@@ -187,7 +210,7 @@ export function GetMinuteChart(code) {
  */
 export function GetNews() {
     return $Call.ByID(1306230863).then(/** @type {($result: any) => any} */(($result) => {
-        return $$createType10($result);
+        return $$createType11($result);
     }));
 }
 
@@ -225,7 +248,7 @@ export function GetNtfyTopics() {
  */
 export function GetPCStatus() {
     return $Call.ByID(4166939475).then(/** @type {($result: any) => any} */(($result) => {
-        return $$createType11($result);
+        return $$createType12($result);
     }));
 }
 
@@ -235,7 +258,7 @@ export function GetPCStatus() {
  */
 export function GetRandomPoem() {
     return $Call.ByID(3860766604).then(/** @type {($result: any) => any} */(($result) => {
-        return $$createType12($result);
+        return $$createType13($result);
     }));
 }
 
@@ -265,7 +288,7 @@ export function GetRecordNames() {
  */
 export function GetServiceModeStatus() {
     return $Call.ByID(3531437326).then(/** @type {($result: any) => any} */(($result) => {
-        return $$createType13($result);
+        return $$createType14($result);
     }));
 }
 
@@ -275,7 +298,7 @@ export function GetServiceModeStatus() {
  */
 export function GetSettings() {
     return $Call.ByID(3034808949).then(/** @type {($result: any) => any} */(($result) => {
-        return $$createType14($result);
+        return $$createType15($result);
     }));
 }
 
@@ -285,7 +308,7 @@ export function GetSettings() {
  */
 export function GetStocks() {
     return $Call.ByID(3187718815).then(/** @type {($result: any) => any} */(($result) => {
-        return $$createType16($result);
+        return $$createType17($result);
     }));
 }
 
@@ -295,7 +318,7 @@ export function GetStocks() {
  */
 export function GetTrendingRepos() {
     return $Call.ByID(4191072422).then(/** @type {($result: any) => any} */(($result) => {
-        return $$createType18($result);
+        return $$createType19($result);
     }));
 }
 
@@ -426,7 +449,7 @@ export function PrepareUpdate(version) {
  */
 export function ReadRecords() {
     return $Call.ByID(2989114738).then(/** @type {($result: any) => any} */(($result) => {
-        return $$createType20($result);
+        return $$createType21($result);
     }));
 }
 
@@ -491,7 +514,7 @@ export function SHA256Hash(text) {
  */
 export function SaveSettings(settings) {
     return $Call.ByID(2662658340, settings).then(/** @type {($result: any) => any} */(($result) => {
-        return $$createType14($result);
+        return $$createType15($result);
     }));
 }
 
@@ -625,13 +648,14 @@ export function StartServiceMode() {
 }
 
 /**
- * StartWebService 启动静态文件服务(默认页 index.html 或 readme.md)。
+ * StartWebService 启动静态文件服务(默认页 index.html 或 readme.md),监听指定端口。
  * @param {string} dir
+ * @param {number} port
  * @returns {$CancellablePromise<$models.WebServiceInfo>}
  */
-export function StartWebService(dir) {
-    return $Call.ByID(3007036157, dir).then(/** @type {($result: any) => any} */(($result) => {
-        return $$createType21($result);
+export function StartWebService(dir, port) {
+    return $Call.ByID(3007036157, dir, port).then(/** @type {($result: any) => any} */(($result) => {
+        return $$createType22($result);
     }));
 }
 
@@ -696,7 +720,7 @@ export function ToggleWindowCompact() {
  */
 export function Translate(text) {
     return $Call.ByID(3284480866, text).then(/** @type {($result: any) => any} */(($result) => {
-        return $$createType22($result);
+        return $$createType23($result);
     }));
 }
 
@@ -727,7 +751,7 @@ export function UploadFile(diskPath) {
  */
 export function WebServiceStatus() {
     return $Call.ByID(1311352355).then(/** @type {($result: any) => any} */(($result) => {
-        return $$createType21($result);
+        return $$createType22($result);
     }));
 }
 
@@ -768,20 +792,21 @@ const $$createType2 = $models.APIStatus.createFrom;
 const $$createType3 = $models.BiliFeedResult.createFrom;
 const $$createType4 = $models.RepoFeed.createFrom;
 const $$createType5 = $Create.Array($$createType4);
-const $$createType6 = $models.KLineBar.createFrom;
-const $$createType7 = $Create.Array($$createType6);
-const $$createType8 = $models.MinuteChart.createFrom;
-const $$createType9 = $models.NewsItem.createFrom;
-const $$createType10 = $Create.Array($$createType9);
-const $$createType11 = $models.PCStatus.createFrom;
-const $$createType12 = $models.PoemData.createFrom;
-const $$createType13 = $models.ServiceModeStatus.createFrom;
-const $$createType14 = $models.AppSettings.createFrom;
-const $$createType15 = $models.StockQuote.createFrom;
-const $$createType16 = $Create.Array($$createType15);
-const $$createType17 = $models.TrendingRepo.createFrom;
-const $$createType18 = $Create.Array($$createType17);
-const $$createType19 = $models.RecordItem.createFrom;
-const $$createType20 = $Create.Array($$createType19);
-const $$createType21 = $models.WebServiceInfo.createFrom;
-const $$createType22 = $models.TranslateResult.createFrom;
+const $$createType6 = $Create.Map($Create.Any, $Create.Any);
+const $$createType7 = $models.KLineBar.createFrom;
+const $$createType8 = $Create.Array($$createType7);
+const $$createType9 = $models.MinuteChart.createFrom;
+const $$createType10 = $models.NewsItem.createFrom;
+const $$createType11 = $Create.Array($$createType10);
+const $$createType12 = $models.PCStatus.createFrom;
+const $$createType13 = $models.PoemData.createFrom;
+const $$createType14 = $models.ServiceModeStatus.createFrom;
+const $$createType15 = $models.AppSettings.createFrom;
+const $$createType16 = $models.StockQuote.createFrom;
+const $$createType17 = $Create.Array($$createType16);
+const $$createType18 = $models.TrendingRepo.createFrom;
+const $$createType19 = $Create.Array($$createType18);
+const $$createType20 = $models.RecordItem.createFrom;
+const $$createType21 = $Create.Array($$createType20);
+const $$createType22 = $models.WebServiceInfo.createFrom;
+const $$createType23 = $models.TranslateResult.createFrom;

+ 78 - 0
frontend/bindings/TengTuToolbox/tagservice.js

@@ -0,0 +1,78 @@
+// @ts-check
+// Cynhyrchwyd y ffeil hon yn awtomatig. PEIDIWCH Â MODIWL
+// This file is automatically generated. DO NOT EDIT
+
+/**
+ * TagService 文件标签服务(Wails 绑定)。
+ * 
+ * Wails 会把公开方法(GetTag/SaveTag/DeleteTag/ListTags/SetTagDBPath)
+ * 暴露给前端 bindings/TengTuToolbox/index.js。内部读写通过包级 openTagDB/
+ * 数据库辅助函数完成,与右键菜单/悬停提示共用。
+ * @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 $models from "./models.js";
+
+/**
+ * DeleteTag 删除指定路径的标签记录(不存在时静默成功)。
+ * @param {string} path
+ * @returns {$CancellablePromise<void>}
+ */
+export function DeleteTag(path) {
+    return $Call.ByID(3335691034, path);
+}
+
+/**
+ * GetTag 查询指定路径的标签记录。
+ * 返回 (记录, 是否存在, 错误):存在=false 表示数据库中无该路径记录(未打标签),
+ * 供悬停提示区分「无标签(不弹气泡)」与「有标签(弹气泡)」。
+ * @param {string} path
+ * @returns {$CancellablePromise<[$models.TagInfo, boolean]>}
+ */
+export function GetTag(path) {
+    return $Call.ByID(2526599461, path).then(/** @type {($result: any) => any} */(($result) => {
+        $result[0] = $$createType0($result[0]);
+        return $result;
+    }));
+}
+
+/**
+ * ListTags 返回全部标签记录(按最近更新倒序),供设置页/标签管理查看。
+ * @returns {$CancellablePromise<$models.TagInfo[]>}
+ */
+export function ListTags() {
+    return $Call.ByID(3196819316).then(/** @type {($result: any) => any} */(($result) => {
+        return $$createType1($result);
+    }));
+}
+
+/**
+ * SaveTag 保存(UPSERT)指定路径的标签与备注。路径规范化后写入。
+ * @param {string} path
+ * @param {string} tag
+ * @param {string} note
+ * @returns {$CancellablePromise<void>}
+ */
+export function SaveTag(path, tag, note) {
+    return $Call.ByID(2991007632, path, tag, note);
+}
+
+/**
+ * SetTagDBPath 设置标签数据库路径并持久化到设置(供前端设置页调用,
+ * 也可在保存设置时直接改 AppSettings.TagDBPath 走 SaveSettings)。
+ * @param {string} path
+ * @returns {$CancellablePromise<void>}
+ */
+export function SetTagDBPath(path) {
+    return $Call.ByID(4279149704, path);
+}
+
+// Private type creation functions
+const $$createType0 = $models.TagInfo.createFrom;
+const $$createType1 = $Create.Array($$createType0);

+ 63 - 16
frontend/index.html

@@ -184,13 +184,15 @@
                             <input class="input tool-dir" id="websvc-dir" type="text" placeholder="未选择目录" readonly>
                             <button class="btn-ghost" id="websvc-pick">选择目录</button>
                         </div>
-                        <div class="tool-row tool-actions">
+                        <div class="tool-row">
+                            <input class="input" id="websvc-port" type="number" min="1" max="65535" placeholder="8080" title="监听端口">
                             <button class="btn-primary" id="websvc-toggle">开启浏览服务</button>
-                            <span class="tool-hint" id="websvc-hint"></span>
                         </div>
-                        <div class="websvc-preview" id="websvc-preview" hidden>
-                            <iframe id="websvc-frame" title="Web 服务预览"></iframe>
+                        <div class="tool-row tool-actions">
+                            <button class="btn-ghost" id="websvc-clear">清空日志</button>
+                            <span class="tool-hint" id="websvc-hint"></span>
                         </div>
+                        <pre class="croc-log" id="websvc-log" hidden></pre>
                     </div>
                 </div>
 
@@ -333,7 +335,6 @@
                         <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">
-                        <p class="tool-desc">点击截屏后自动隐藏本程序窗口,截取整个屏幕(全部显示器),完成后重新显示并预览。截到的画面不含本程序自身。</p>
                         <div class="tool-row tool-actions">
                             <button class="btn-primary" id="shot-capture">截屏</button>
                             <span class="tool-hint" id="shot-hint"></span>
@@ -356,7 +357,6 @@
                         <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">
-                        <p class="tool-desc">输入多少分钟后关机,确认后交给系统倒计时(即使本程序退出仍会执行),也可随时取消。</p>
                         <div class="tool-row">
                             <input class="input" id="sd-minutes" type="number" min="1" max="1440" step="1" placeholder="分钟数" style="width:120px">
                             <button class="btn-primary" id="sd-go">延时关机</button>
@@ -374,7 +374,6 @@
                         <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">
-                        <p class="tool-desc">输入任意字符串,计算其 32 位小写十六进制 MD5 摘要。常用于文件/字符串校验,注意 MD5 已不适合密码存储。</p>
                         <textarea class="input tr-input" id="md5-input" rows="3" placeholder="输入要计算 MD5 的字符串……"></textarea>
                         <div class="tool-row tool-actions">
                             <button class="btn-primary" id="md5-go">计算 MD5</button>
@@ -392,7 +391,6 @@
                         <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">
-                        <p class="tool-desc">输入任意字符串,计算其 64 位小写十六进制 SHA256 摘要。适用于校验、签名与安全存储。</p>
                         <textarea class="input tr-input" id="sha-input" rows="3" placeholder="输入要计算 SHA256 的字符串……"></textarea>
                         <div class="tool-row tool-actions">
                             <button class="btn-primary" id="sha-go">计算 SHA256</button>
@@ -436,10 +434,12 @@
                         <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">
-                        <p class="tool-desc">输入提醒信息与间隔分钟数,每 xx 分钟弹出一次提醒,直到手动取消。适合定时喝水、休息、吃药等。</p>
-                        <input class="input" id="remind-message" type="text" placeholder="提醒信息,如:该喝水了">
-                        <div class="tool-row tool-actions">
-                            <input class="input" id="remind-minutes" type="number" min="1" max="1440" step="1" placeholder="间隔(分钟)" style="width:120px">
+                        <div class="tool-row tool-actions remind-row">
+                            <input class="input remind-message" id="remind-message" type="text" placeholder="提醒信息,如:该喝水了">
+                            <label class="num-group" title="每隔多少分钟提醒一次">
+                                <input class="input input-num" id="remind-minutes" type="number" min="1" max="440" step="1" placeholder="30">
+                                <span class="num-unit">分钟</span>
+                            </label>
                             <button class="btn-primary" id="remind-go">开始提醒</button>
                             <button class="btn-ghost" id="remind-stop">取消提醒</button>
                             <span class="tool-hint" id="remind-hint"></span>
@@ -493,7 +493,7 @@
                     </div>
                     <div class="tool-card-body">
                         <div class="tool-row tool-actions">
-                            <label class="ytdlp-select-all"><input type="checkbox" id="ytdlp-select-all">全选</label>
+                            <label class="ytdlp-select-all" title="点击循环切换:全选所有 → 全选未下载 → 全选已下载 → 取消全选(无已下载项时跳过「全选未下载」)"><input type="checkbox" id="ytdlp-select-all"><span id="ytdlp-select-all-label">全选</span></label>
                             <button class="btn-primary" id="ytdlp-batch-download" type="button" disabled>批量下载</button>
                             <button class="btn-ghost" id="ytdlp-batch-mp3" type="button" style="display:none" disabled>批量转 mp3</button>
                             <button class="btn-ghost" id="ytdlp-clear" type="button" title="清空列表(正在下载会先停止)" disabled>清除</button>
@@ -734,6 +734,7 @@
                         <div class="setting-info">
                             <div class="setting-title">呼出窗口热键</div>
                             <div class="setting-hint">点击输入框后按下组合键,例如 Ctrl+Shift+G</div>
+                            <div class="setting-hint hotkey-status is-error" id="hotkey-status" hidden></div>
                         </div>
                         <input class="input hotkey-input" id="hotkey" readonly placeholder="按下组合键">
                     </div>
@@ -743,6 +744,7 @@
                         <div class="setting-info">
                             <div class="setting-title">快捷菜单热键</div>
                             <div class="setting-hint">按下后在鼠标位置弹出「快捷」启动菜单,例如 Ctrl+Shift+H</div>
+                            <div class="setting-hint hotkey-status is-error" id="quickhotkey-status" hidden></div>
                         </div>
                         <input class="input hotkey-input" id="quickhotkey" readonly placeholder="按下组合键">
                     </div>
@@ -764,16 +766,37 @@
                     <div class="setting-row" data-tab-group="system">
                         <div class="setting-info">
                             <div class="setting-title">Tab 显示顺序</div>
-                            <div class="setting-hint">用逗号分隔 Tab 名称,从左到右依次显示;未列出的追加到末尾。名称用 [] 包裹(如 [工具])则折叠到标签栏末尾的三条横线菜单中,鼠标移到该处展开选择;「设置」固定在该菜单的最后一项</div>
+                            <div class="setting-hint">用逗号分隔 Tab 名称,从左到右依次显示;未列出的追加到末尾。名称用 [] 包裹则折叠到标签栏末尾的三条横线菜单中</div>
                         </div>
                         <input class="input" id="tab-order" type="text" placeholder="网址, 新闻, Github, 股市, 待办, 工具, 服务, [记录]">
                     </div>
 
+                    <!-- 启用标签功能(归入「系统」组):关闭后删除资源管理器右键菜单、停止监听悬停 -->
+                    <div class="setting-row" data-tab-group="system">
+                        <div class="setting-info">
+                            <div class="setting-title">启用标签功能</div>
+                            <div class="setting-hint">为文件/文件夹添加右键「标签」菜单,鼠标悬停约 0.3 秒后读取标签与备注并显示在光标上方;关闭后删除右键菜单并停止后台监听,默认启用</div>
+                        </div>
+                        <label class="switch">
+                            <input type="checkbox" id="tag-menu-enabled" checked>
+                            <span class="switch-track"></span>
+                        </label>
+                    </div>
+
+                    <!-- 标签数据库路径(归入「系统」组) -->
+                    <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>
+                        <input class="input" id="tag-db-path" type="text" placeholder="D:\My\腾图\标签.db">
+                    </div>
+
                     <!-- 自定义 Tab 页面(归入「系统」组) -->
                     <div class="setting-row setting-row-col" data-tab-group="system">
                         <div class="setting-info">
                             <div class="setting-title">自定义 Tab 页面</div>
-                            <div class="setting-hint">每行一条,格式:页面名称|地址|备注(备注可空)。地址以 http:// 或 https:// 开头则内嵌网页;否则按本地文件路径读取,Markdown 自动渲染。名称用于 Tab 显示顺序,备注显示为 Tab 说明</div>
+                            <div class="setting-hint">每行一条,格式:页面名称|地址|备注(备注可空)。<br/>地址以 http:// 或 https:// 开头则内嵌网页;否则按本地文件路径读取,Markdown 自动渲染。名称用于 Tab 显示顺序,备注显示为 Tab 说明</div>
                         </div>
                         <textarea class="input textarea" id="custom-tabs" rows="3" placeholder="文档|D:\My\notes\readme.md|个人笔记&#10;示例|https://example.com"></textarea>
                     </div>
@@ -891,6 +914,18 @@
                         <input class="input" id="bili-cookie" type="text" placeholder="SESSDATA=xxxxxxxx; bili_jct=xxxx" spellcheck="false">
                     </div>
 
+                    <!-- B站热门视频区块开关 -->
+                    <div class="setting-row" data-tab-group="news">
+                        <div class="setting-info">
+                            <div class="setting-title">B站热门视频</div>
+                            <div class="setting-hint">在「新闻」页显示 B站热门视频区块。关闭后隐藏该区块,不抓取 B站数据。</div>
+                        </div>
+                        <label class="switch">
+                            <input type="checkbox" id="bili-popular-enabled">
+                            <span class="slider"></span>
+                        </label>
+                    </div>
+
                     <!-- 新闻刷新间隔 -->
                     <div class="setting-row" data-tab-group="news">
                         <div class="setting-info">
@@ -998,6 +1033,7 @@
                         <div class="setting-info">
                             <div class="setting-title">代理开关热键</div>
                             <div class="setting-hint">点击输入框后按下组合键,全局切换系统网络代理;留空则不设热键(默认 Ctrl+Shift+J)</div>
+                            <div class="setting-hint hotkey-status is-error" id="proxyhotkey-status" hidden></div>
                         </div>
                         <input class="input hotkey-input" id="proxyhotkey" readonly placeholder="留空=不设热键">
                     </div>
@@ -1197,7 +1233,7 @@
                     <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">
@@ -1215,6 +1251,7 @@
                 <div class="save-bar">
                     <button class="btn-primary" id="save-settings">保存设置</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>
                 </div>
             </div>
@@ -1299,6 +1336,16 @@
 <!-- 「更多」Tab 下拉菜单:挂在 body 下,避免被标签栏的 backdrop-filter/overflow 裁剪或压层 -->
 <div class="tab-more-menu" id="tab-more-menu" role="menu"></div>
 
+<!-- 升级过程浮层:显示下载进度 / 安装 / 重启提示(默认隐藏) -->
+<div class="update-overlay" id="update-overlay" hidden>
+    <div class="update-card">
+        <div class="update-title" id="update-title">正在检查更新…</div>
+        <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>
+</div>
+
 <script type="module" src="/src/main.js"></script>
 </body>
 </html>

BIN
frontend/public/Inter-Medium.ttf


BIN
frontend/public/bg-desktop.jpg


BIN
frontend/public/bg-mobile.jpg


+ 0 - 1
frontend/public/javascript.svg

@@ -1 +0,0 @@
-<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="32" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path fill="#F7DF1E" d="M0 0h256v256H0V0Z"></path><path d="m67.312 213.932l19.59-11.856c3.78 6.701 7.218 12.371 15.465 12.371c7.905 0 12.89-3.092 12.89-15.12v-81.798h24.057v82.138c0 24.917-14.606 36.259-35.916 36.259c-19.245 0-30.416-9.967-36.087-21.996m85.07-2.576l19.588-11.341c5.157 8.421 11.859 14.607 23.715 14.607c9.969 0 16.325-4.984 16.325-11.858c0-8.248-6.53-11.17-17.528-15.98l-6.013-2.58c-17.357-7.387-28.87-16.667-28.87-36.257c0-18.044 13.747-31.792 35.228-31.792c15.294 0 26.292 5.328 34.196 19.247l-18.732 12.03c-4.125-7.389-8.591-10.31-15.465-10.31c-7.046 0-11.514 4.468-11.514 10.31c0 7.217 4.468 10.14 14.778 14.608l6.014 2.577c20.45 8.765 31.963 17.7 31.963 37.804c0 21.654-17.012 33.51-39.867 33.51c-22.339 0-36.774-10.654-43.819-24.574"></path></svg>

+ 81 - 15
frontend/public/style.css

@@ -320,8 +320,8 @@ body.window-compact #compact-restore span {
     flex-shrink: 0;
     border-radius: 8px;
     cursor: grab;
-    --wails-draggable: no-drag;                 /* 句柄需接收右键菜单,设为不可拖动;
-                                                   窗口拖动仍由父级 .tab-buttons 承担 */
+    --wails-draggable: drag;                    /* 左键拖动窗口;右键不触发拖动(Wails 仅左键 arm 拖动),
+                                                   故右键快捷菜单仍可正常弹出 */
     transition: background 0.18s ease;
 }
 .tab-drag-handle:hover {
@@ -979,6 +979,16 @@ body.window-compact #compact-restore span {
     cursor: pointer;
 }
 
+/* 热键占用提示:组合键被其他程序占用时在输入框旁显示 */
+.hotkey-status {
+    margin-top: 5px;
+    font-size: calc(13px + var(--font-delta));
+    line-height: 1.4;
+}
+.hotkey-status.is-error {
+    color: var(--up); /* 使用主题红色突出占用告警 */
+}
+
 /* 保存栏 */
 .save-bar {
     display: flex;
@@ -1341,6 +1351,69 @@ body.window-compact #compact-restore span {
     margin-left: auto; /* 靠右,与「保存设置」同行最右 */
 }
 
+/* 「检查更新」与「意见/建议」紧贴成一组靠右:前者承担 auto 推右,后者去掉 auto 紧随其后 */
+.save-bar #check-update {
+    margin-left: auto;
+}
+.save-bar #feedback-open {
+    margin-left: 0; /* 紧贴「检查更新」,两者形成一组 */
+}
+
+/* --- 升级过程浮层 --- */
+.update-overlay {
+    position: fixed;
+    inset: 0;
+    z-index: 200;
+    display: flex;
+    align-items: center;
+    justify-content: center;
+    background: rgba(0, 0, 0, 0.45);
+    backdrop-filter: blur(2px);
+}
+/* 覆盖 display:flex,确保 hidden 属性生效 —— 浮层默认隐藏,仅在更新时显示 */
+.update-overlay[hidden] {
+    display: none;
+}
+.update-card {
+    width: 360px;
+    max-width: 86vw;
+    padding: 22px 24px;
+    border-radius: 14px;
+    background: var(--panel, #fff);
+    box-shadow: 0 12px 40px rgba(0, 0, 0, 0.3);
+}
+.update-title {
+    font-size: calc(16px + var(--font-delta));
+    font-weight: 600;
+    color: var(--text, #222);
+    margin-bottom: 6px;
+}
+.update-sub {
+    font-size: calc(13px + var(--font-delta));
+    color: var(--muted, #888);
+    margin-bottom: 14px;
+    white-space: pre-wrap;
+    word-break: break-all;
+}
+.update-bar {
+    height: 8px;
+    border-radius: 6px;
+    background: rgba(0, 0, 0, 0.1);
+    overflow: hidden;
+}
+.update-bar-fill {
+    height: 100%;
+    border-radius: 6px;
+    background: var(--grad, #2f8fff);
+    transition: width 0.15s ease;
+}
+.update-pct {
+    margin-top: 6px;
+    text-align: right;
+    font-size: calc(12px + var(--font-delta));
+    color: var(--muted, #888);
+}
+
 /* --- 意见/建议弹窗 --- */
 .feedback-modal {
     position: fixed;
@@ -3000,6 +3073,12 @@ a.ver-muted:hover {
     color: var(--muted);
     font-size: calc(13.5px + var(--font-delta));
 }
+
+/* 定时提醒:提醒信息输入框占满卡片宽度,便于长文案输入 */
+.remind-message {
+    width: 70%;
+    margin-bottom: 12px;
+}
 /* 颜色选择器:色块 + 标签,用于 LED 点阵颜色等 */
 .color-field {
     display: inline-flex;
@@ -3054,19 +3133,6 @@ a.ver-muted:hover {
 .speed-field input[type="number"]:focus {
     border-color: var(--accent);
 }
-.websvc-preview {
-    margin-top: 14px;
-    height: 320px;
-    border: 1px solid var(--glass-border);
-    border-radius: var(--radius);
-    overflow: hidden;
-    background: rgba(0, 0, 0, 0.25);
-}
-.websvc-preview iframe {
-    width: 100%;
-    height: 100%;
-    border: none;
-}
 
 /* LocalSend 文件互传 */
 .localsend-config {

+ 345 - 41
frontend/src/main.js

@@ -45,6 +45,7 @@ const FALLBACK_SETTINGS = {
     links: [{name: '煎蛋', url: 'https://jandan.net/'}],
     newsKeywords: '',
     biliCookie: '',                    // B站登录 cookie(含 SESSDATA),用于抓取「关注的人最新动态」
+    biliPopularEnabled: true,          // 新闻页是否显示 B站热门视频区块(默认开启)
     githubRepos: [{url: 'https://github.com/wailsapp/wails', desc: 'Wails 框架'}],
     customTabs: [],                   // 用户自定义 Tab 页面(名字 + 地址;http/https 为网页,其余为本地文件)
     localTools: [],                   // 「本地」页资源(标题 + 启动命令 + 说明)
@@ -55,6 +56,8 @@ const FALLBACK_SETTINGS = {
     todoPath: '', // 待办路径:无默认值,空值提示用户到设置页配置
     recordPath: '', // 记录路径:无默认值,空值提示用户到设置页配置(保留兼容,记录 Tab 实际使用数据库)
     recordDBPath: '', // 记录数据库路径:无默认值,空值提示用户到设置页配置
+    tagDBPath: '', // 标签数据库路径:无默认值,空值提示用户到设置页配置
+    tagMenuEnabled: true, // 资源管理器右键「标签」功能开关(默认启用)
     backupDir: '', // 备份目录:无默认值,空值提示用户到设置页配置
     stockUpColor: '#ff5a5a',      // 股票上涨颜色(红涨)
     stockDownColor: '#4d8dff',    // 股票下跌颜色(蓝跌)
@@ -65,7 +68,7 @@ const FALLBACK_SETTINGS = {
     githubRefreshMinutes: 120,    // Github 自动刷新间隔(分钟)
     fontDelta: 0,                 // 全局字号偏移(px),+-3,默认 0(基准字号已含 +2)
     toolOrder: ['websvc', 'udp', 'translate', 'qrcode', 'ntfy', 'chat', 'poem', 'screenshot', 'shutdown', 'md5', 'sha256', 'led', 'reminder', 'localsend', 'croc', 'ytdlp', 'memos', 'brightness', 'proxy'], // 工具页卡片默认顺序
-    gitLab: {baseUrl: 'https://git.scwy.net', projectPath: 'ease/toolbox', privateToken: '', branch: 'main'}, // 私有 GitLab 自动升级
+    gitLab: {baseUrl: 'https://i.scwy.net/down/toolsbox', projectPath: 'ease/toolbox', privateToken: '', branch: 'main'}, // 静态更新站:清单固定放在 {baseUrl}/manifest.json
     croc: {password: '', dir: ''}, // Croc 传送:发送/接收共用密码、接收保存目录
     ytdlp: {dir: '', mp3Quality: '0'}, // 视频下载:yt-dlp 下载保存目录 + mp3 转换质量
     memos: {url: 'https://m.scwy.net', token: ''}, // Memos 速记:实例地址/访问令牌
@@ -747,6 +750,7 @@ const stockCodesInput = document.getElementById('stock-codes');     // 股票代
 const linksText = document.getElementById('links-text');            // 常用网址(每行 名称|网址)
 const newsKeywordsInput = document.getElementById('news-keywords'); // 新闻关键词
 const biliCookieInput = document.getElementById('bili-cookie');      // B站登录 cookie
+const biliPopularEnabledInput = document.getElementById('bili-popular-enabled'); // B站热门视频区块开关
 const githubReposText = document.getElementById('github-repos');    // Github 项目(每行 地址|说明)
 const apiAddrInput = document.getElementById('api-addr');           // API 监听地址
 const serviceAddrInput = document.getElementById('service-addr');     // 服务模式 API 监听地址
@@ -756,6 +760,8 @@ const uploadDirInput = document.getElementById('upload-dir');         // 上传
 const uploadMaxSizeInput = document.getElementById('upload-max-size'); // 上传大小上限(MB)
 const todoPathInput = document.getElementById('todo-path');         // 待办(TODO)文件路径
 const recordDBPathInput = document.getElementById('record-db-path'); // 记录(Record)数据库路径
+const tagDBPathInput = document.getElementById('tag-db-path');       // 文件标签数据库路径(资源管理器右键「标签」)
+const tagMenuEnabledToggle = document.getElementById('tag-menu-enabled'); // 启用标签功能开关(关闭后删右键菜单+停止监听)
 const backupDirInput = document.getElementById('backup-dir');       // 文本备份目录(文件类自定义 Tab「备份」按钮使用)
 const browserPathInput = document.getElementById('browser-path');   // 指定浏览器 exe 路径(空=系统默认)
 const browserPickBtn = document.getElementById('browser-pick');     // 选择浏览器按钮
@@ -893,6 +899,7 @@ async function syncForm(settings) {
     linksText.value = (settings.links || []).map(l => `${l.name}|${l.url}`).join('\n');
     newsKeywordsInput.value = settings.newsKeywords || '';
     biliCookieInput.value = settings.biliCookie || '';
+    biliPopularEnabledInput.checked = settings.biliPopularEnabled !== false; // 默认开启
     githubReposText.value = (settings.githubRepos || []).map(r => `${r.url}|${r.desc}|${r.version || ''}`).join('\n');
     customTabsText.value = (settings.customTabs || []).map(t => `${t.name}|${t.url}${t.desc ? '|' + t.desc : ''}`).join('\n');
     localToolsText.value = (settings.localTools || []).map(t => `${t.title}|${t.cmd}${t.desc ? '|' + t.desc : ''}`).join('\n');
@@ -916,6 +923,8 @@ async function syncForm(settings) {
     uploadMaxSizeInput.value = settings.uploadMaxSize || '';      // 上传大小上限(MB)
     todoPathInput.value = settings.todoPath;
     recordDBPathInput.value = settings.recordDBPath;
+    tagDBPathInput.value = settings.tagDBPath;
+    if (tagMenuEnabledToggle) tagMenuEnabledToggle.checked = settings.tagMenuEnabled !== false; // 默认启用(兼容旧配置无该字段)
     backupDirInput.value = settings.backupDir;
     browserPathInput.value = settings.browserPath || '';
     stockUpColorInput.value = settings.stockUpColor || FALLBACK_SETTINGS.stockUpColor;
@@ -1041,6 +1050,39 @@ bindHotkeyInput(hotkeyInput);
 bindHotkeyInput(quickHotkeyInput);
 bindHotkeyInput(proxyHotkeyInput);
 
+// ------------------------------------------------------------------------
+// 热键注册状态:组合键被其他程序占用时,在输入框旁显示提示
+// ------------------------------------------------------------------------
+// statusKey 对应后端 hotkeyStatus 的 key:hotkey / quickHotkey / proxyHotkey
+const HOTKEY_STATUS_EL = {
+    hotkey: document.getElementById('hotkey-status'),
+    quickHotkey: document.getElementById('quickhotkey-status'),
+    proxyHotkey: document.getElementById('proxyhotkey-status'),
+};
+
+// 拉取后端热键注册状态并渲染到各输入框旁(空=已生效隐藏提示;非空=显示占用原因)
+async function renderHotkeyStatus() {
+    if (typeof SettingsService?.GetHotkeyStatus !== 'function') return;
+    try {
+        const status = await SettingsService.GetHotkeyStatus() || {};
+        for (const [key, el] of Object.entries(HOTKEY_STATUS_EL)) {
+            if (!el) continue;
+            const msg = (status[key] || '').trim();
+            if (msg) {
+                el.textContent = msg;
+                el.hidden = false;
+            } else {
+                el.textContent = '';
+                el.hidden = true;
+            }
+        }
+    } catch (err) {
+        console.warn('读取热键状态失败:', err);
+    }
+}
+
+renderHotkeyStatus();
+
 // 指定浏览器:选择按钮弹出文件选择框,清除按钮恢复系统默认
 browserPickBtn.addEventListener('click', async () => {
     try {
@@ -1097,6 +1139,7 @@ async function loadSettings() {
     renderLinks(currentSettings.links || []);
     initFooterPoem(currentSettings.poem);  // footer 古诗按配置显示并加载
     restartAutoTimers(); // 按真实设置的间隔重建自动刷新定时器
+    renderHotkeyStatus(); // 显示各热键注册状态(组合键被占用时提示)
 }
 
 // 解析「每行 键|值」格式的文本域为对象数组
@@ -1439,6 +1482,7 @@ function collectForm() {
         links: parsePipeLines(fallbackArr(linksText, 'links'), 'name', 'url').filter(l => l.name && l.url),
         newsKeywords: newsKeywordsInput.value.trim(),
         biliCookie: biliCookieInput.value.trim(),
+        biliPopularEnabled: biliPopularEnabledInput.checked,
         githubRepos: parsePipeLines3(fallbackArr(githubReposText, 'githubRepos'), 'url', 'desc', 'version').filter(r => r.url),
         customTabs: parsePipeLines3(fallbackArr(customTabsText, 'customTabs'), 'name', 'url', 'desc').filter(t => t.name && t.url),
         localTools: parsePipeLines3(fallbackArr(localToolsText, 'localTools'), 'title', 'cmd', 'desc').filter(t => t.title && t.cmd),
@@ -1478,6 +1522,8 @@ function collectForm() {
         uploadMaxSize: parseInt(uploadMaxSizeInput.value, 10) || 512, // 上传大小上限(MB,默认 512)
         todoPath: todoPathInput.value.trim(),
         recordDBPath: recordDBPathInput.value.trim(),
+        tagDBPath: tagDBPathInput.value.trim(),
+        tagMenuEnabled: tagMenuEnabledToggle ? tagMenuEnabledToggle.checked : true, // 启用标签功能(默认启用)
         backupDir: backupDirInput.value.trim(),
         browserPath: browserPathInput.value.trim(), // 指定浏览器 exe 路径(空=系统默认)
         gitLab: currentSettings.gitLab || {}, // 升级源配置仅存于配置文件(设置界面已移除该行),此处透传保留,需修改时手动编辑 settings.json
@@ -1730,7 +1776,7 @@ function renderProxyStatus(st) {
         proxyServerInput.value = st.server;
     }
     if (proxyStatusEl) {
-        proxyStatusEl.textContent = st.enabled ? '已启用' : (st.configured ? '已禁用' : '未配置');
+        proxyStatusEl.textContent = st.enabled ? '已启用' : (st.configured ? '未启用' : '未配置');
         proxyStatusEl.className = 'tool-status' + (st.enabled ? ' is-on' : '');
     }
     if (proxyToggleBtn) {
@@ -2129,6 +2175,7 @@ async function saveSettings() {
     saveStatus.classList.remove('is-error', 'is-ok');
 
     try {
+        const biliWasEnabled = currentSettings.biliPopularEnabled !== false; // 保存前 B站开关状态
         const saved = await SettingsService.SaveSettings(new AppSettings(collectForm()));
         currentSettings = saved;
         await syncForm(saved);
@@ -2138,6 +2185,11 @@ async function saveSettings() {
         loadStocks(); // 代码变化后立即刷新行情
         restartAutoTimers(); // 按新设置的间隔重建各面板定时器
 
+        // B站开关变化:立即刷新新闻页,让「显示/隐藏 B站热门视频区块」即时生效
+        if ((saved.biliPopularEnabled !== false) !== biliWasEnabled) {
+            loadNews();
+        }
+
         // 把 LocalSend 配置同步到后端服务(运行中则即时生效,未运行则下次启动生效)
         try {
             const ls = saved.localSend || {};
@@ -2148,6 +2200,7 @@ async function saveSettings() {
         isDirty = false; // 保存成功,清除未保存标记
         saveStatus.textContent = '已保存并生效';
         saveStatus.classList.add('is-ok');
+        renderHotkeyStatus(); // 热键可能变化,刷新占用提示
     } catch (err) {
         saveStatus.textContent = '保存失败:' + (err?.message || err);
         saveStatus.classList.add('is-error');
@@ -2178,6 +2231,7 @@ const feedbackCancelBtn = document.getElementById('feedback-cancel');
 const feedbackCloseBtn = document.getElementById('feedback-close');
 const feedbackMask = document.getElementById('feedback-mask');
 const feedbackOpenBtn = document.getElementById('feedback-open');
+const checkUpdateBtn = document.getElementById('check-update'); // 设置页「检查更新」按钮
 
 function openFeedback() {
     if (!feedbackModal) return;
@@ -2223,6 +2277,91 @@ feedbackCancelBtn?.addEventListener('click', closeFeedback);
 feedbackCloseBtn?.addEventListener('click', closeFeedback);
 feedbackMask?.addEventListener('click', closeFeedback);
 
+// 设置页「检查更新」:调用后端手动检查一次,发现新版本会弹原生对话框(升级/暂时跳过/此版不再提示)。
+// 已最新 → 显示「当前已是最新版本」;检查失败 → 显示错误信息。
+checkUpdateBtn?.addEventListener('click', async () => {
+    if (!checkUpdateBtn) return;
+    checkUpdateBtn.disabled = true;
+    const original = checkUpdateBtn.textContent;
+    checkUpdateBtn.textContent = '检查中…';
+    const saveStatusEl = document.getElementById('save-status');
+    const showStatus = (text, ok) => {
+        if (!saveStatusEl) return;
+        saveStatusEl.textContent = text;
+        saveStatusEl.className = 'save-status ' + (ok ? 'is-ok' : 'is-error');
+    };
+    try {
+        const st = await SettingsService.CheckUpdateDialog();
+        if (st && st.upToDate) {
+            // 已是最新版本:给用户明确反馈
+            showStatus('当前已是最新版本 ✓', true);
+        } else if (st && st.message) {
+            showStatus(st.message, false);
+        }
+    } catch (err) {
+        showStatus('检查更新失败:' + (err?.message || err), false);
+    } finally {
+        checkUpdateBtn.disabled = false;
+        checkUpdateBtn.textContent = original;
+    }
+});
+
+// ---- 升级过程反馈:订阅 Wails 内置 Updater 事件,驱动进度浮层 ----
+const updateOverlayEl = document.getElementById('update-overlay');
+const updateTitleEl = document.getElementById('update-title');
+const updateSubEl = document.getElementById('update-sub');
+const updateBarFillEl = document.getElementById('update-bar-fill');
+const updatePctEl = document.getElementById('update-pct');
+
+function showUpdateOverlay(title, sub, pct) {
+    if (!updateOverlayEl) return;
+    updateOverlayEl.hidden = false;
+    updateTitleEl.textContent = title;
+    updateSubEl.textContent = sub || '';
+    const p = Math.max(0, Math.min(100, pct || 0));
+    updateBarFillEl.style.width = p + '%';
+    updatePctEl.textContent = p.toFixed(1) + '%'; // 进度百分比保留一位小数
+}
+function hideUpdateOverlay() {
+    if (updateOverlayEl) updateOverlayEl.hidden = true;
+}
+// 事件订阅失败或错误时提示
+function updateError(msg) {
+    showUpdateOverlay('升级失败', String(msg || '未知错误'), 0);
+    setTimeout(hideUpdateOverlay, 5000);
+}
+
+if (updateOverlayEl) {
+    Events.On('wails:updater:download-started', () => {
+        showUpdateOverlay('正在下载更新…', '请勿关闭应用', 0);
+    });
+    Events.On('wails:updater:download-progress', (evt) => {
+        const d = evt?.data || evt || {};
+        const total = Number(d.total) || 0;
+        const written = Number(d.written) || 0;
+        const pct = total > 0 ? (written / total) * 100 : 0;
+        const rate = Number(d.rate) || 0;
+        const sub = rate > 0 ? `下载速度:${(rate / 1024 / 1024).toFixed(1)} MB/s` : '';
+        showUpdateOverlay('正在下载更新…', sub, pct);
+    });
+    Events.On('wails:updater:download-complete', () => {
+        showUpdateOverlay('下载完成,正在校验…', '', 100);
+    });
+    Events.On('wails:updater:verifying', () => {
+        showUpdateOverlay('正在校验下载文件…', '', 100);
+    });
+    Events.On('wails:updater:installing', () => {
+        showUpdateOverlay('正在安装更新…', '请勿关闭应用', 100);
+    });
+    Events.On('wails:updater:update-ready', () => {
+        showUpdateOverlay('升级完成,正在重启应用…', '应用即将自动重启', 100);
+    });
+    Events.On('wails:updater:error', (evt) => {
+        const d = evt?.data || evt || {};
+        updateError(d.message || '未知错误');
+    });
+}
+
 feedbackSendBtn?.addEventListener('click', async () => {
     const text = (feedbackInput?.value || '').trim();
     if (!text) {
@@ -2424,9 +2563,13 @@ async function loadNews() {
     const runId = ++newsRunSeq; // 抓取批次编号:只有最新一批才允许写列表
     try {
         // 并行抓取:普通新闻 + B站动态(后者失败不阻断新闻展示,单独显示提示)
+        // B站热门视频区块开关关闭时不抓取 B站数据(避免浪费请求)。
+        const biliEnabled = currentSettings.biliPopularEnabled !== false;
         const [news, bili] = await Promise.all([
             SettingsService.GetNews(),
-            SettingsService.GetBiliDynamic().catch(err => ({ __error: err?.message || String(err) })),
+            biliEnabled
+                ? SettingsService.GetBiliDynamic().catch(err => ({ __error: err?.message || String(err) }))
+                : Promise.resolve(null),
         ]);
         newsStreaming = false; // 后端返回即代表所有来源已完成
 
@@ -2438,22 +2581,25 @@ async function loadNews() {
             </a>`;
 
         // B站动态区块(放在新闻列表上方,独立分组)
+        // 开关关闭时不渲染 B站区块(即使后端返回了数据也隐藏)。
         let biliHtml = '';
-        const biliItems = Array.isArray(bili) ? bili : (bili?.items || []); // 兼容旧绑定返回数组
-        const biliNotice = (!bili || bili.__error) ? '' : (bili.notice || '');
-        if (bili && bili.__error) {
-            biliHtml = `<div class="news-group-label"><span class="news-group-dot"></span>B站动态</div>
-                <div class="news-bili-hint">${escapeHtml(bili.__error)}</div>`;
-        } else if (biliItems.length) {
-            const biliShown = biliItems.slice(0, 8); // B站动态最多显示 8 条,避免喧宾夺主
-            // cookie 未配置/过期时后端回退热门视频,标题与提示同步说明,避免误认为关注动态
-            const biliLabel = biliNotice ? 'B站热门视频' : 'B站关注动态';
-            biliHtml = `<div class="news-group-label"><span class="news-group-dot"></span>${biliLabel}(${biliShown.length})</div>`;
-            if (biliNotice) {
-                biliHtml += `<div class="news-bili-hint news-bili-warn">${escapeHtml(biliNotice)}</div>`;
+        if (biliEnabled) {
+            const biliItems = Array.isArray(bili) ? bili : (bili?.items || []); // 兼容旧绑定返回数组
+            const biliNotice = (!bili || bili.__error) ? '' : (bili.notice || '');
+            if (bili && bili.__error) {
+                biliHtml = `<div class="news-group-label"><span class="news-group-dot"></span>B站动态</div>
+                    <div class="news-bili-hint">${escapeHtml(bili.__error)}</div>`;
+            } else if (biliItems.length) {
+                const biliShown = biliItems.slice(0, 8); // B站动态最多显示 8 条,避免喧宾夺主
+                // cookie 未配置/过期时后端回退热门视频,标题与提示同步说明,避免误认为关注动态
+                const biliLabel = biliNotice ? 'B站热门视频' : 'B站关注动态';
+                biliHtml = `<div class="news-group-label"><span class="news-group-dot"></span>${biliLabel}(${biliShown.length})</div>`;
+                if (biliNotice) {
+                    biliHtml += `<div class="news-bili-hint news-bili-warn">${escapeHtml(biliNotice)}</div>`;
+                }
+                biliHtml += biliShown.map(rowHtml).join('');
+                biliHtml += `<div class="news-divider"></div>`;
             }
-            biliHtml += biliShown.map(rowHtml).join('');
-            biliHtml += `<div class="news-divider"></div>`;
         }
         newsBiliHtml = biliHtml;
 
@@ -2606,7 +2752,7 @@ async function loadGithub() {
                     const badgeText = `发现新版本 ${escapeHtml(feed.latest)}`;
                     versionBadge = `<a class="ver-badge ver-update" href="${escapeHtml(feed.releaseURL || feed.url)}" target="_blank" data-wml-openURL="${escapeHtml(feed.releaseURL || feed.url)}" title="点击前往下载${latestTip}">● ${badgeText}</a>`;
                     if (feed.version) versionBadge += `<a class="ver-local" href="${escapeHtml(releasesURL)}" target="_blank" data-wml-openURL="${escapeHtml(releasesURL)}" title="查看版本列表${versionTipFull}">本地 ${escapeHtml(feed.version)}</a>`;
-                    versionBadge += `<button class="btn-ghost repo-check-btn" data-url="${escapeHtml(feed.url)}" data-latest="${escapeHtml(feed.latest)}">检视</button>`;
+                    versionBadge += `<button class="btn-ghost repo-check-btn" data-url="${escapeHtml(feed.url)}" data-latest="${escapeHtml(feed.latest)}" data-releases="${escapeHtml(releasesURL)}" data-latesttime="${escapeHtml(feed.latestTime)}">检视</button>`;
                 } else if (feed.version) {
                     // 本地已是最新版本:勾选本地版本号,不再显示「最新 xxx」标签
                     versionBadge = `<a class="ver-badge ver-ok" href="${escapeHtml(releasesURL)}" target="_blank" data-wml-openURL="${escapeHtml(releasesURL)}" title="查看版本列表${latestTip}${versionTipFull}">✓ 本地 ${escapeHtml(feed.version)}</a>`;
@@ -2642,14 +2788,39 @@ async function loadGithub() {
         }).join('');
         WML.Reload();
 
-        // 「检视」按钮:标记已检查,把本地版本更新为最新版,消除更新提示
+        // 「检视」按钮:标记已检查,把本地版本更新为最新版,消除更新提示。
+        // 只局部更新该仓库徽标为「✓ 本地 xxx」,不重新拉取全量 GitHub API(避免等待 15 秒级请求)。
         repoList.querySelectorAll('.repo-check-btn').forEach(btn => {
             btn.addEventListener('click', async () => {
                 btn.disabled = true; // 防止重复点击
                 btn.textContent = '处理中…';
                 try {
-                    await SettingsService.MarkGithubRepoChecked(btn.dataset.url, btn.dataset.latest);
-                    await loadGithub(); // 重新拉取,更新徽标状态
+                    const latest = btn.dataset.latest || '';
+                    await SettingsService.MarkGithubRepoChecked(btn.dataset.url, latest);
+                    // 局部替换:把「发现新版本」徽标 + 「本地 xxx」 + 「检视」按钮
+                    // 换成「✓ 本地 xxx」徽标(已检视 = 本地已是最新)。
+                    const card = btn.closest('.repo-card');
+                    if (card) {
+                        const head = card.querySelector('.repo-head');
+                        const releasesURL = btn.dataset.releases || btn.dataset.url || '#';
+                        const latestTip = btn.dataset.latesttime ? `(发布时间 ${escapeHtml(btn.dataset.latesttime)})` : '';
+                        const okBadge = document.createElement('a');
+                        okBadge.className = 'ver-badge ver-ok';
+                        okBadge.href = releasesURL;
+                        okBadge.target = '_blank';
+                        okBadge.dataset.wmlOpenURL = releasesURL;
+                        okBadge.title = `查看版本列表${latestTip}`;
+                        okBadge.textContent = `✓ 本地 ${latest}`;
+                        // 移除旧的版本徽标区(含「发现新版本」「本地 xxx」链接与「检视」按钮)
+                        const oldBadges = head.querySelectorAll('.ver-update, .ver-local, .repo-check-btn');
+                        oldBadges.forEach(el => el.remove());
+                        // 重新挂上「✓ 本地 xxx」徽标(插在 desc 之后 / 行尾)
+                        head.appendChild(okBadge);
+                        WML.Reload();
+                    } else {
+                        // 找不到卡片时回退到全量刷新,保证状态一致
+                        await loadGithub();
+                    }
                 } catch (err) {
                     console.warn('标记检视失败:', err);
                     btn.disabled = false;
@@ -4201,6 +4372,7 @@ const ytdlpStatusEl = document.getElementById('ytdlp-status'); // 状态徽标
 const ytdlpListEl = document.getElementById('ytdlp-list');     // B 站链接列表
 const ytdlpLogEl = document.getElementById('ytdlp-log');       // 下载日志
 const ytdlpSelectAll = document.getElementById('ytdlp-select-all');       // 全选
+const ytdlpSelectAllLabel = document.getElementById('ytdlp-select-all-label'); // 全选文案(随循环态变化)
 const ytdlpBatchBtn = document.getElementById('ytdlp-batch-download');    // 批量下载
 const ytdlpBatchMp3Btn = document.getElementById('ytdlp-batch-mp3');      // 批量转 mp3(ffmpeg 可用时显示)
 const ytdlpClearBtn = document.getElementById('ytdlp-clear');             // 清空列表
@@ -4217,7 +4389,14 @@ let ytdlpBatchQueue = [];     // 批量下载待处理链接队列
 let ytdlpBatchTotal = 0;      // 批量下载总数
 let ytdlpBatchDone = 0;       // 批量下载已完成数
 const ytdlpSeen = new Set();  // 已加入列表的链接,避免剪贴板反复读取导致重复
-const YTDLP_MAX_ITEMS = 20;   // 列表最多保留的链接条数
+const YTDLP_MAX_ITEMS = 100;  // 列表最多保留的链接条数
+
+// 「全选」循环态:0=全选所有 1=全选未下载 2=全选已下载 3=取消全选(下次点击回到全选所有)
+const YTDLP_SELECT_MODE_ALL = 0;
+const YTDLP_SELECT_MODE_PENDING = 1;
+const YTDLP_SELECT_MODE_DONE = 2;
+const YTDLP_SELECT_MODE_OFF = 3;
+let ytdlpSelectMode = YTDLP_SELECT_MODE_ALL;
 
 // 从任意文本中提取第一个 B 站链接(支持 bilibili.com 与 b23.tv 短链)
 function extractBilibiliUrl(text) {
@@ -4248,8 +4427,8 @@ function ytdlpUpdateBatchCount() {
     const total = ytdlpListEl.querySelectorAll('.ytdlp-item').length;
     const selected = ytdlpSelectedUrls().length;
     if (ytdlpSelectAll) {
-        ytdlpSelectAll.checked = total > 0 && selected === total;
-        ytdlpSelectAll.indeterminate = selected > 0 && selected < total;
+        // 三态循环下复选框外观由 syncSelectAllMode 按当前态设置,
+        // 这里只处理「列表为空」的禁用态,避免覆盖循环态的显示。
         ytdlpSelectAll.disabled = total === 0;
     }
     if (ytdlpBatchBtn) {
@@ -4263,6 +4442,70 @@ function ytdlpUpdateBatchCount() {
     if (ytdlpClearBtn) ytdlpClearBtn.disabled = total === 0;
 }
 
+// 按「全选」循环态设置列表行的勾选状态:
+// ALL=勾选所有行;PENDING=只勾未下载行;DONE=只勾已下载行;OFF=全部取消勾选。
+// 返回实际勾选的行数。
+function ytdlpApplySelectMode() {
+    if (!ytdlpListEl) return 0;
+    const items = Array.from(ytdlpListEl.querySelectorAll('.ytdlp-item'));
+    let selected = 0;
+    items.forEach(item => {
+        const done = item.classList.contains('is-done');
+        let on = false;
+        if (ytdlpSelectMode === YTDLP_SELECT_MODE_ALL) on = true;
+        else if (ytdlpSelectMode === YTDLP_SELECT_MODE_PENDING) on = !done;
+        else if (ytdlpSelectMode === YTDLP_SELECT_MODE_DONE) on = done;
+        else on = false;
+        const cb = item.querySelector('.ytdlp-check');
+        if (cb) cb.checked = on;
+        if (on) selected++;
+    });
+    return selected;
+}
+
+// 把当前循环态同步到复选框外观与文案,让用户能看出现在处于哪种「全选」。
+function ytdlpSyncSelectAllUI() {
+    if (!ytdlpListEl) return;
+    const total = ytdlpListEl.querySelectorAll('.ytdlp-item').length;
+    const selected = ytdlpSelectedUrls().length;
+    if (ytdlpSelectAllLabel) {
+        const text = {
+            [YTDLP_SELECT_MODE_ALL]: '全选所有',
+            [YTDLP_SELECT_MODE_PENDING]: '全选未下载',
+            [YTDLP_SELECT_MODE_DONE]: '全选已下载',
+            [YTDLP_SELECT_MODE_OFF]: '全选',
+        }[ytdlpSelectMode] || '全选';
+        ytdlpSelectAllLabel.textContent = total === 0 ? '全选' : text;
+        ytdlpSelectAllLabel.dataset.mode = String(ytdlpSelectMode);
+    }
+    if (ytdlpSelectAll) {
+        // 取消全选态显示未勾选;其余态只要有勾选就显示勾选,
+        // 半选(部分行匹配)用 indeterminate 区分。
+        ytdlpSelectAll.checked = selected > 0;
+        ytdlpSelectAll.indeterminate =
+            ytdlpSelectMode !== YTDLP_SELECT_MODE_ALL && selected > 0 && selected < total;
+    }
+}
+
+// 是否存在已下载(is-done)的列表行
+function ytdlpHasDone() {
+    if (!ytdlpListEl) return false;
+    return Array.from(ytdlpListEl.querySelectorAll('.ytdlp-item'))
+        .some(item => item.classList.contains('is-done'));
+}
+
+// 「全选」按钮的循环切换:全选所有 → 全选未下载 → 全选已下载 → 取消全选 → 循环。
+// 没有已下载内容时跳过「全选未下载」——此时它与「全选所有」效果相同,留着只是多余一步。
+function ytdlpCycleSelectAll() {
+    ytdlpSelectMode = (ytdlpSelectMode + 1) % 4;
+    if (ytdlpSelectMode === YTDLP_SELECT_MODE_PENDING && !ytdlpHasDone()) {
+        ytdlpSelectMode = (ytdlpSelectMode + 1) % 4;
+    }
+    ytdlpApplySelectMode();
+    ytdlpSyncSelectAllUI();
+    ytdlpUpdateBatchCount();
+}
+
 // 按链接查找列表行
 function ytdlpItemByUrl(url) {
     return Array.from(ytdlpListEl?.children || []).find(el => el.dataset.url === url) || null;
@@ -4277,8 +4520,10 @@ function ytdlpStartBatch(audioOnly) {
     ytdlpBatching = true;
     ytdlpBatchAudio = !!audioOnly;
     ytdlpBatchQueue = urls.slice();
-    // 点击后自动取消选中
+    // 点击后自动取消选中,并把循环态复位到「全选所有」
     ytdlpListEl?.querySelectorAll('.ytdlp-check').forEach(c => { c.checked = false; });
+    ytdlpSelectMode = YTDLP_SELECT_MODE_ALL;
+    ytdlpSyncSelectAllUI();
     ytdlpUpdateBatchCount();
     ytdlpBatchTotal = urls.length;
     ytdlpBatchDone = 0;
@@ -4338,7 +4583,8 @@ function addYTDLPItem(url) {
     check.type = 'checkbox';
     check.className = 'ytdlp-check';
     check.title = '勾选后可批量下载';
-    check.addEventListener('change', ytdlpUpdateBatchCount);
+    // 单行勾选变化后同步「全选」复选框的外观与半选态
+    check.addEventListener('change', () => { ytdlpUpdateBatchCount(); ytdlpSyncSelectAllUI(); });
 
     // 标题 + 链接:标题异步用 yt-dlp 解析,解析失败时回退显示链接
     const meta = document.createElement('div');
@@ -4400,7 +4646,17 @@ function addYTDLPItem(url) {
         ytdlpSeen.delete(last.dataset.url || '');
         last.remove();
     }
-    ytdlpUpdateBatchCount(); // 新链接默认不勾选,刷新全选/批量按钮状态
+    // 新链接按当前「全选」循环态决定是否勾选:
+    // 处于「全选所有」或「全选未下载」时新链接(未下载)自动勾选,
+    // 「全选已下载」与「取消全选」态下不勾选。
+    const newCheck = item.querySelector('.ytdlp-check');
+    if (newCheck) {
+        newCheck.checked =
+            ytdlpSelectMode === YTDLP_SELECT_MODE_ALL ||
+            ytdlpSelectMode === YTDLP_SELECT_MODE_PENDING;
+    }
+    ytdlpSyncSelectAllUI(); // 刷新全选框外观与文案
+    ytdlpUpdateBatchCount(); // 刷新批量按钮计数
     return true;
 }
 
@@ -4422,6 +4678,8 @@ async function ytdlpClearList() {
     }
     ytdlpSeen.clear();          // 清空后允许重新收录相同链接
     ytdlpListEl.innerHTML = '';
+    ytdlpSelectMode = YTDLP_SELECT_MODE_ALL; // 清空后「全选」复位到初始态
+    ytdlpSyncSelectAllUI();
     ytdlpActiveBtn = null;
     ytdlpActiveHint = null;
     ytdlpActiveLabel = '';
@@ -4455,6 +4713,10 @@ function ytdlpFinishDownload(ok) {
     ytdlpActiveLabel = '';
     document.querySelectorAll('#ytdlp-list button').forEach(b => { b.disabled = false; });
     ytdlpSetStatus(ok ? '已就绪' : '已停止', false);
+    // 下载状态变化后按当前「全选」循环态重新套用勾选:
+    // 处于「全选未下载」时刚完成的行自动取消勾选,处于「全选已下载」时自动勾上。
+    ytdlpApplySelectMode();
+    ytdlpSyncSelectAllUI();
     ytdlpUpdateBatchCount();
     if (ytdlpBatching) setTimeout(ytdlpProcessBatch, 300); // 批量流程:继续下一条
 }
@@ -4556,12 +4818,12 @@ function hideYTDLPSettings() {
     }
 })();
 
-// 全选 / 批量下载按钮
+// 「全选」:点击循环切换四种态(全选所有 → 全选未下载 → 全选已下载 → 取消全选)。
+// 用 click 而非 change:复选框的勾选状态由 ytdlpSyncSelectAllUI 统一控制,
+// 用 change 会与程序化设置 checked 产生冲突。
 if (ytdlpSelectAll) {
-    ytdlpSelectAll.addEventListener('change', () => {
-        const on = ytdlpSelectAll.checked;
-        ytdlpListEl?.querySelectorAll('.ytdlp-check').forEach(c => { c.checked = on; });
-        ytdlpUpdateBatchCount();
+    ytdlpSelectAll.addEventListener('click', () => {
+        ytdlpCycleSelectAll();
     });
 }
 if (ytdlpBatchBtn) ytdlpBatchBtn.addEventListener('click', () => ytdlpStartBatch(false));
@@ -5087,14 +5349,32 @@ refreshToolOrderBtns();
 const websvcStatusEl = document.getElementById('websvc-status');  // 运行状态徽标
 const websvcDirInput = document.getElementById('websvc-dir');     // 目录输入框
 const websvcPickBtn = document.getElementById('websvc-pick');     // 选择目录按钮
+const websvcPortInput = document.getElementById('websvc-port');   // 监听端口输入
 const websvcToggleBtn = document.getElementById('websvc-toggle'); // 开启/停止乒乓按钮
+const websvcClearBtn = document.getElementById('websvc-clear');   // 清空日志按钮
 let websvcRunning = false; // 当前 Web 服务是否运行(乒乓按钮状态)
 const websvcHintEl = document.getElementById('websvc-hint');      // 提示文字
-const websvcPreview = document.getElementById('websvc-preview');  // 预览容器
-const websvcFrame = document.getElementById('websvc-frame');      // 预览 iframe
+const websvcLogEl = document.getElementById('websvc-log');        // 请求日志框
 
 let websvcDir = ''; // 当前选中的目录(持久化于 localStorage)
 
+// 追加一行到 Web 服务日志框
+function websvcAppendLog(kind, line) {
+    if (!websvcLogEl) return;
+    websvcLogEl.hidden = false;
+    const prefix = kind === 'req' ? '[请求] ' : '[信息] ';
+    websvcLogEl.textContent += prefix + line + '\n';
+    websvcLogEl.scrollTop = websvcLogEl.scrollHeight; // 滚动到最新一行
+}
+
+// 订阅 Web 服务日志事件(后端 webservice.go 通过 app.Event.Emit 推送)
+if (typeof Events?.On === 'function') {
+    Events.On('websvc:log', (e) => {
+        const d = e?.data || {};
+        websvcAppendLog(d.kind, d.line || '');
+    });
+}
+
 // 渲染 Web 服务状态(运行中 / 未运行)
 function renderWebSvc(info) {
     if (info && info.running) {
@@ -5105,16 +5385,13 @@ function renderWebSvc(info) {
         websvcHintEl.textContent = info.indexName
             ? `默认页 ${info.indexName}|${info.connections} 次请求`
             : `未发现 index.html 或 readme.md,显示目录列表|${info.connections} 次请求`;
-        // 预览:加载服务首页
-        websvcPreview.hidden = false;
-        websvcFrame.src = info.url;
+        if (websvcPortInput) websvcPortInput.disabled = true; // 运行中禁用端口输入
     } else {
         websvcRunning = false;
         websvcStatusEl.textContent = '未运行';
         websvcStatusEl.className = 'tool-status';
         websvcHintEl.textContent = websvcDir ? '' : '请先选择目录';
-        websvcPreview.hidden = true;
-        websvcFrame.src = 'about:blank';
+        if (websvcPortInput) websvcPortInput.disabled = false;
     }
     // 乒乓按钮:运行中显示「停止服务」(红),未运行显示「开启浏览服务」(主色)
     websvcToggleBtn.textContent = websvcRunning ? '停止服务' : '开启浏览服务';
@@ -5127,6 +5404,9 @@ function renderWebSvc(info) {
 async function loadToolsPanel() {
     websvcDir = localStorage.getItem('tengtu-websvc-dir') || '';
     if (websvcDir) websvcDirInput.value = websvcDir;
+    const savedPort = localStorage.getItem('tengtu-websvc-port');
+    if (savedPort && websvcPortInput && !websvcPortInput.value) websvcPortInput.value = savedPort;
+    if (websvcPortInput && !websvcPortInput.value) websvcPortInput.value = '8080'; // 默认端口
     try {
         const info = await SettingsService.WebServiceStatus();
         if (info && info.running && info.dir) {
@@ -5179,10 +5459,17 @@ websvcToggleBtn.addEventListener('click', async () => {
             websvcHintEl.textContent = '请先选择目录';
             return;
         }
+        const port = parseInt(websvcPortInput?.value, 10);
+        if (isNaN(port) || port < 1 || port > 65535) {
+            websvcHintEl.textContent = '端口无效:请输入 1-65535';
+            return;
+        }
         websvcToggleBtn.classList.add('loading');
         websvcToggleBtn.disabled = true;
         try {
-            const info = await SettingsService.StartWebService(websvcDir);
+            const info = await SettingsService.StartWebService(websvcDir, port);
+            localStorage.setItem('tengtu-websvc-port', String(port));
+            websvcAppendLog('info', `端口 ${port} 已开启,浏览服务运行中`); // 打开日志框
             renderWebSvc(info);
         } catch (err) {
             console.warn('开启服务失败:', err);
@@ -5194,6 +5481,14 @@ websvcToggleBtn.addEventListener('click', async () => {
     }
 });
 
+// 清空日志框
+if (websvcClearBtn) websvcClearBtn.addEventListener('click', () => {
+    if (websvcLogEl) {
+        websvcLogEl.textContent = '';
+        websvcLogEl.hidden = true;
+    }
+});
+
 // ------------------------------------------------------------------------
 // 工具页:UDP 键值服务——启动 UDP 服务器,存储/查询键值,来往数据显示在信息框
 // ------------------------------------------------------------------------
@@ -5298,7 +5593,7 @@ if (udpToggleBtn) udpToggleBtn.addEventListener('click', async () => {
 });
 
 // 手动发送键值/查询到指定远端
-if (udpSendBtn) udpSendBtn.addEventListener('click', async () => {
+async function udpSendNow() {
     const target = udpTargetInput.value.trim();
     const msg = udpMsgInput.value;
     if (!target) {
@@ -5316,6 +5611,15 @@ if (udpSendBtn) udpSendBtn.addEventListener('click', async () => {
     } finally {
         udpSendBtn.disabled = false;
     }
+}
+if (udpSendBtn) udpSendBtn.addEventListener('click', udpSendNow);
+
+// 键=值 输入框:按回车键即发送(等效点击「发送」按钮)
+if (udpMsgInput) udpMsgInput.addEventListener('keydown', (e) => {
+    if (e.key === 'Enter') {
+        e.preventDefault();
+        udpSendNow();
+    }
 });
 
 // 清空信息框

+ 125 - 0
generate-manifest.ps1

@@ -0,0 +1,125 @@
+<#
+.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/"

+ 1 - 1
go.mod

@@ -5,6 +5,7 @@ go 1.27.3
 require (
 	github.com/gen2brain/beeep v0.11.3
 	github.com/gin-gonic/gin v1.12.0
+	github.com/go-ole/go-ole v1.3.0
 	github.com/gomarkdown/markdown v0.0.0-20261026184151-79e163b7b632
 	github.com/kbinani/screenshot v0.0.0-20250624051815-089614a94018
 	github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e
@@ -27,7 +28,6 @@ require (
 	github.com/gabriel-vasile/mimetype v1.4.12 // indirect
 	github.com/gen2brain/shm v0.1.0 // indirect
 	github.com/gin-contrib/sse v1.1.0 // indirect
-	github.com/go-ole/go-ole v1.3.0 // indirect
 	github.com/go-playground/locales v0.14.1 // indirect
 	github.com/go-playground/universal-translator v0.18.1 // indirect
 	github.com/go-playground/validator/v10 v10.30.1 // indirect

+ 86 - 11
main.go

@@ -7,10 +7,10 @@
 package main
 
 import (
-	"bytes"   // 托盘菜单图标:PNG 编码缓冲区
-	"embed"   // Go 内嵌资源包:将前端静态文件打包进可执行文件
-	"fmt"     // 格式化 I/O:用于控制台打印调试信息
-	"image"   // 托盘菜单图标:RGBA 画布
+	"bytes" // 托盘菜单图标:PNG 编码缓冲区
+	"embed" // Go 内嵌资源包:将前端静态文件打包进可执行文件
+	"fmt"   // 格式化 I/O:用于控制台打印调试信息
+	"image" // 托盘菜单图标:RGBA 画布
 	"image/color"
 	"image/png" // 托盘菜单图标:将 RGBA 编码为 PNG 字节
 	"log"       // 日志:记录并输出错误
@@ -51,6 +51,10 @@ var (
 	// 窗口隐藏前的位置,恢复显示时还原
 	savedX, savedY int
 	hasSavedPos    bool
+
+	// explorerSvc 资源管理器悬停监听服务(全局引用,供「配置→系统」启停标签功能)。
+	// 在 main 中创建并 Start;SaveSettings 切换 TagMenuEnabled 时启停。
+	explorerSvc *explorerService
 )
 
 // showMainWindow 统一显示入口:先还原位置,再显示并聚焦。
@@ -106,6 +110,7 @@ func showQuickMenuAtCursor() {
 
 // toggleProxyByHotkey 「网络代理」开关全局热键回调:切换系统代理启用/禁用,
 // 并向前端发射 proxyChanged 事件刷新工具页「网络代理」卡片状态。
+// 同时在鼠标位置弹出提示文字:网络代理已启动/关闭。
 func toggleProxyByHotkey() {
 	if app == nil {
 		return
@@ -120,6 +125,12 @@ func toggleProxyByHotkey() {
 		"server":     st.Server,
 		"configured": st.Configured,
 	})
+	// 鼠标光标下方提示:网络代理已启动/已关闭
+	if st.Enabled {
+		triggerMouseAlert("网络代理已启动")
+	} else {
+		triggerMouseAlert("网络代理已关闭")
+	}
 }
 
 var (
@@ -159,7 +170,7 @@ func init() {
 	application.RegisterEvent[string]("ntfyChat")     // ntfy 聊天室:订阅主题后收到消息广播给前端
 	application.RegisterEvent[int]("handleFlash")     // 拖动手柄圆点闪烁:API 触发,前端播放颜色+大小动画
 	application.RegisterEvent[bool]("windowCompact")  // 后端呼出窗口时同步圆点收拢/还原状态
-	application.RegisterEvent[string]("switchTab") // 托盘菜单点击 Tab:前端切换到对应页面
+	application.RegisterEvent[string]("switchTab")    // 托盘菜单点击 Tab:前端切换到对应页面
 	// 升级状态由 Wails 内置升级框架自行推给前端(wails:updater:* 系列事件),无需在此注册
 }
 
@@ -461,6 +472,26 @@ func main() {
 		return
 	}
 
+	// 注册表右键菜单「标签」:本程序 -tag <路径>。
+	// 若已有实例在运行,把路径转发给其实例的 /api/tag/open 接口后本进程退出
+	// (保持原程序运行);无运行实例则本进程作为主实例继续启动并弹窗。
+	if handleTagCommandIfNeeded() {
+		return // 已转发给运行中的实例,本进程直接退出
+	}
+
+	// 提权写入注册表右键菜单:`-install-tagmenu` 由 maybeWriteTagMenu 检测到
+	// 权限不足时用 runas 提权启动的本进程(子进程),完成写入后立即退出,
+	// 不再初始化应用界面。放在 handleTagCommandIfNeeded 之后,二者互斥。
+	if handleInstallTagMenu() {
+		return
+	}
+
+	// 提权删除注册表右键菜单:`-remove-tagmenu` 由 maybeRemoveTagMenu 检测到
+	// 权限不足时用 runas 提权启动的本进程(子进程),完成删除后立即退出。
+	if handleRemoveTagMenu() {
+		return
+	}
+
 	// 创建 dock service 实例,自定义 badge 选项
 	dockService := dock.NewWithOptions(dock.BadgeOptions{
 		TextColour:       color.RGBA{255, 255, 255, 255}, // 白色文字
@@ -470,6 +501,29 @@ func main() {
 		SmallFontSize:    14,                             // 多字符字号
 	})
 
+	// ------------------------------------------------------------------------
+	// 读取配置(提前到创建 explorerService 之前:决定是否启动标签功能监听)。
+	// ------------------------------------------------------------------------
+	ensureSettingsFile()       // 首次运行:自动生成默认配置文件(已存在则不覆盖)
+	settings := loadSettings() // 读取用户配置,首次运行返回默认值(开机启动默认开启)
+
+	// 创建 explorerService:后台轮询前台资源管理器的选中项并缓存,
+	// 供 Wails 窗口获得焦点时把最近一次选中的文件/文件夹显示到鼠标提示。
+	// 是否启动由「配置→系统→启用标签功能」开关决定:
+	//   启用(默认)→ 启动后台监听,鼠标悬停文件/文件夹时读取标签并提示;
+	//   关闭       → 不启动(也避免不必要的 COM 轮询干扰资源管理器)。
+	explorerSvc = newExplorerService()
+	if settings.TagMenuEnabled {
+		explorerSvc.Start()
+	}
+
+	// 安装资源管理器右键菜单「标签」钩子(Windows 专用;非 Windows 为空实现)。
+	// 钩子在独立线程监听右键点击,向系统右键菜单注入「标签(&T)」项。
+	// 同样受「启用标签功能」开关控制:关闭时不安装钩子(右键不注入菜单)。
+	if settings.TagMenuEnabled {
+		startTagContextHook()
+	}
+
 	// ------------------------------------------------------------------------
 	// 第 1 步:创建 Wails 应用实例
 	// ------------------------------------------------------------------------
@@ -489,6 +543,8 @@ func main() {
 			application.NewService(NewUDPService()),        // 注册 UDPService,供工具页 UDP 键值服务器启停/发送
 			application.NewService(NewProxyService()),      // 注册 ProxyService,供工具页「网络代理」设置/启用/禁用系统代理
 			application.NewService(dockService),            // 注册 dockService,前端可通过 bindings 直接调用其 SetBadge 方法
+			application.NewService(explorerSvc),            // 注册 explorerService,供前端读取资源管理器选中项
+			application.NewService(&TagService{}),          // 注册 TagService,供资源管理器右键「标签」/悬停标签提示读写文件标签
 		},
 		Assets: application.AssetOptions{
 			Handler: application.AssetFileServerFS(assets), // 使用嵌入的前端文件作为资源服务器处理器
@@ -499,11 +555,8 @@ func main() {
 	})
 
 	// ------------------------------------------------------------------------
-	// 第 2 步:读取配置并创建主窗口(使用上次保存的窗口尺寸)
+	// 第 2 步:创建主窗口(使用上次保存的窗口尺寸)
 	// ------------------------------------------------------------------------
-	ensureSettingsFile()       // 首次运行:自动生成默认配置文件(已存在则不覆盖)
-	settings := loadSettings() // 读取用户配置,首次运行返回默认值(开机启动默认开启)
-
 	win := app.Window.NewWithOptions(application.WebviewWindowOptions{
 		Title:  "腾图工具箱", // 窗口标题
 		Width:  settings.WindowWidth,
@@ -544,6 +597,14 @@ func main() {
 	applySettings(settings) // 注册热键、设置置顶、同步开机启动
 	startUIRegistration()   // 向服务模式登记界面 API 地址(服务转发未实现接口时使用)
 
+	// 写入(或修复)资源管理器右键菜单「标签」:文件与文件夹均添加,
+	// 命令为本程序 -tag "%1",由 -tag 命令行逻辑弹出标签编辑窗口。
+	// 仅发布构建(production 标签)写入,dev 构建跳过以免覆盖正式版菜单。
+	// 受「启用标签功能」开关控制:关闭时不写入(也不弹 UAC 提权)。
+	if settings.TagMenuEnabled {
+		maybeWriteTagMenu()
+	}
+
 	if settings.Brightness.RestoreOnStart {
 		restoreBrightness(settings.Brightness.Levels) // 启动时恢复上次各显示器亮度
 	}
@@ -554,8 +615,10 @@ func main() {
 		log.Printf("内置升级框架初始化失败:%v", err)
 	} else {
 		go func() {
-			time.Sleep(2 * time.Second) // 等窗口与前端就绪,避免事件早于订阅
-			if err := checkUpdateNow(); err != nil {
+			time.Sleep(2 * time.Second) // 等窗口与前端就绪
+			// 启动时检查一次更新:发现新版本则弹原生对话框(升级/暂时跳过/此版不再提示),
+			// 已最新或检查失败则静默不打扰。
+			if _, err := PromptUpdateIfAvailable(); err != nil {
 				log.Printf("启动检查新版本失败:%v", err)
 			}
 		}()
@@ -584,6 +647,10 @@ func main() {
 	// 第 5 步:注册窗口事件处理
 	// ------------------------------------------------------------------------
 
+	// 资源管理器选中项提示已改为:后台轮询检测选中项变化时,由 explorerService
+	// 直接调用系统级 mousealert 置顶气泡显示(无需窗口焦点/前端事件)。
+	// 故不再监听 WindowFocus 发 explorerSelection 事件。
+
 	// 监听「文件拖放完成」事件,打印拖放目标详情与所有被拖入的文件
 	win.OnWindowEvent(events.Common.WindowFilesDropped, func(event *application.WindowEvent) {
 		files := event.Context().DroppedFiles()        // 获取拖入的文件路径列表
@@ -648,6 +715,14 @@ func main() {
 	// 放在后台协程,即使窗口隐藏/最小化也能触发。
 	go startTodoReminderLoop()
 
+	// 本进程作为主实例且带 -tag 参数:界面已就绪,打开标签编辑窗口。
+	// (转发给运行实例的情况已在 handleTagCommandIfNeeded 中返回退出。)
+	if pendingTagPath != "" {
+		path := pendingTagPath
+		pendingTagPath = ""
+		go openTagEditor(path)
+	}
+
 	// 运行应用(阻塞,直到退出)
 	if err := app.Run(); err != nil {
 		log.Fatal(err) // 运行过程中发生错误则记录日志并退出进程

+ 5 - 0
mousealert_other.go

@@ -17,3 +17,8 @@ func triggerMouseAlert(text string) {
 func stopMouseAlert() {
 	// 无操作
 }
+
+// stopTagAlert 非 Windows 平台为空实现。
+func stopTagAlert() {
+	// 无操作
+}

+ 239 - 67
mousealert_windows.go

@@ -43,15 +43,15 @@ const (
 	wmPaint     = 0x000F
 	wmRefresh   = 0x8001 // 自定义:立即刷新(trigger 唤醒窗口线程)
 
-	wndExLayered   = 0x00080000 // WS_EX_LAYERED 分层窗口(支持透明)
-	wndExTool      = 0x00000080 // WS_EX_TOOLWINDOW 不占任务栏
-	wndExTopMost   = 0x00000008 // WS_EX_TOPMOST 置顶
+	wndExLayered    = 0x00080000 // WS_EX_LAYERED 分层窗口(支持透明)
+	wndExTool       = 0x00000080 // WS_EX_TOOLWINDOW 不占任务栏
+	wndExTopMost    = 0x00000008 // WS_EX_TOPMOST 置顶
 	wndExNoActivate = 0x08000000 // WS_EX_NOACTIVATE 不抢焦点
 
 	swpNoActivate = 0x0010 // SWP_NOACTIVATE
 	swpShowWindow = 0x0040 // SWP_SHOWWINDOW
 
-	lwaAlpha   = 0x2 // LWA_ALPHA:SetLayeredWindowAttributes 设置整体 alpha
+	lwaAlpha    = 0x2 // LWA_ALPHA:SetLayeredWindowAttributes 设置整体 alpha
 	lwaColorKey = 0x1 // LWA_COLORKEY:把指定颜色像素抠成透明(背景透明)
 
 	timerFollow = 1 // 位置跟随 + 闪烁定时器 ID
@@ -59,8 +59,13 @@ const (
 	overlayWidth  = 200
 	overlayHeight = 54
 
-	alertDuration   = 8 * time.Second
+	alertDuration    = 8 * time.Second
 	followIntervalMs = 60 // 跟随/闪烁轮询间隔 60ms
+
+	// tagAlertDuration 资源管理器「标签」气泡的显示时长(固定,不取用户「鼠标提醒」
+	// 时长,也不做超长文字延长)。标签提示是顺带一瞥的信息,停得太久会一直挂在
+	// 鼠标旁很干扰;鼠标离开悬停项时还会被立即隐藏(见 stopTagAlert)。
+	tagAlertDuration = 2 * time.Second
 )
 
 // hwndTopMost HWND_TOPMOST = (HWND)-1
@@ -131,12 +136,12 @@ type rect struct {
 }
 
 type msg struct {
-	HWND    uintptr
-	Message uint32
-	WParam  uintptr
-	LParam  uintptr
-	Time    uint32
-	Pt      point
+	HWND     uintptr
+	Message  uint32
+	WParam   uintptr
+	LParam   uintptr
+	Time     uint32
+	Pt       point
 	LPrivate uint32
 }
 
@@ -177,43 +182,99 @@ var (
 	gdi32    = syscall.NewLazyDLL("gdi32.dll")
 	kernel32 = syscall.NewLazyDLL("kernel32.dll")
 
-	procGetMessage          = user32.NewProc("GetMessageW")
-	procTranslateMessage    = user32.NewProc("TranslateMessage")
-	procDispatchMessage     = user32.NewProc("DispatchMessageW")
-	procRegisterClassEx     = user32.NewProc("RegisterClassExW")
-	procCreateWindowEx      = user32.NewProc("CreateWindowExW")
-	procDefWindowProc       = user32.NewProc("DefWindowProcW")
-	procDestroyWindow       = user32.NewProc("DestroyWindow")
-	procSetTimer            = user32.NewProc("SetTimer")
-	procKillTimer           = user32.NewProc("KillTimer")
-	procShowWindow          = user32.NewProc("ShowWindow")
-	procSetWindowPos        = user32.NewProc("SetWindowPos")
-	procGetCursorPos        = user32.NewProc("GetCursorPos")
-	procPostMessage         = user32.NewProc("PostMessageW")
+	procGetMessage           = user32.NewProc("GetMessageW")
+	procTranslateMessage     = user32.NewProc("TranslateMessage")
+	procDispatchMessage      = user32.NewProc("DispatchMessageW")
+	procRegisterClassEx      = user32.NewProc("RegisterClassExW")
+	procCreateWindowEx       = user32.NewProc("CreateWindowExW")
+	procDefWindowProc        = user32.NewProc("DefWindowProcW")
+	procDestroyWindow        = user32.NewProc("DestroyWindow")
+	procSetTimer             = user32.NewProc("SetTimer")
+	procKillTimer            = user32.NewProc("KillTimer")
+	procShowWindow           = user32.NewProc("ShowWindow")
+	procSetWindowPos         = user32.NewProc("SetWindowPos")
+	procGetCursorPos         = user32.NewProc("GetCursorPos")
+	procPostMessage          = user32.NewProc("PostMessageW")
 	procSetLayeredWindowAttr = user32.NewProc("SetLayeredWindowAttributes")
-	procBeginPaint          = user32.NewProc("BeginPaint")
-	procEndPaint            = user32.NewProc("EndPaint")
-	procInvalidateRect      = user32.NewProc("InvalidateRect")
-	procFillRect            = user32.NewProc("FillRect") // 注意:FillRect 在 user32.dll,不在 gdi32.dll
-	procDrawTextW           = user32.NewProc("DrawTextW")
-
-	procCreateSolidBrush = gdi32.NewProc("CreateSolidBrush")
-	procDeleteObject     = gdi32.NewProc("DeleteObject")
-	procSetBkMode        = gdi32.NewProc("SetBkMode")
-	procSetTextColor     = gdi32.NewProc("SetTextColor")
-	procGetStockObject   = gdi32.NewProc("GetStockObject")
-	procSelectObject     = gdi32.NewProc("SelectObject")
-	procCreateFontW      = gdi32.NewProc("CreateFontW")
-	procTextOutW         = gdi32.NewProc("TextOutW")                            // 单行文字输出(超长滚动用)
-	procGetTextExtentPoint32W = gdi32.NewProc("GetTextExtentPoint32W")          // 测量文字宽度(判断是否超长)
-	procCreateCompatibleDC     = gdi32.NewProc("CreateCompatibleDC")            // 双缓冲:创建内存 DC
-	procCreateCompatibleBitmap = gdi32.NewProc("CreateCompatibleBitmap")        // 双缓冲:创建兼容位图
-	procBitBlt                 = gdi32.NewProc("BitBlt")                        // 双缓冲:整块拷贝上屏
-	procDeleteDC               = gdi32.NewProc("DeleteDC")                      // 双缓冲:删除内存 DC
+	procBeginPaint           = user32.NewProc("BeginPaint")
+	procEndPaint             = user32.NewProc("EndPaint")
+	procInvalidateRect       = user32.NewProc("InvalidateRect")
+	procFillRect             = user32.NewProc("FillRect") // 注意:FillRect 在 user32.dll,不在 gdi32.dll
+	procDrawTextW            = user32.NewProc("DrawTextW")
+
+	procCreateSolidBrush       = gdi32.NewProc("CreateSolidBrush")
+	procDeleteObject           = gdi32.NewProc("DeleteObject")
+	procSetBkMode              = gdi32.NewProc("SetBkMode")
+	procSetTextColor           = gdi32.NewProc("SetTextColor")
+	procGetStockObject         = gdi32.NewProc("GetStockObject")
+	procSelectObject           = gdi32.NewProc("SelectObject")
+	procCreateFontW            = gdi32.NewProc("CreateFontW")
+	procTextOutW               = gdi32.NewProc("TextOutW")               // 单行文字输出(超长滚动用)
+	procGetTextExtentPoint32W  = gdi32.NewProc("GetTextExtentPoint32W")  // 测量文字宽度(判断是否超长)
+	procCreateCompatibleDC     = gdi32.NewProc("CreateCompatibleDC")     // 双缓冲:创建内存 DC
+	procCreateCompatibleBitmap = gdi32.NewProc("CreateCompatibleBitmap") // 双缓冲:创建兼容位图
+	procBitBlt                 = gdi32.NewProc("BitBlt")                 // 双缓冲:整块拷贝上屏
+	procDeleteDC               = gdi32.NewProc("DeleteDC")               // 双缓冲:删除内存 DC
 
 	procGetModuleHandleW = kernel32.NewProc("GetModuleHandleW")
+	procGetDpiForWindow  = user32.NewProc("GetDpiForWindow") // Win10 1607+,返回窗口 DPI
+	procGetDpiForSystem  = user32.NewProc("GetDpiForSystem") // Win10 1607+,返回系统 DPI
+	procGetDC            = user32.NewProc("GetDC")
+	procReleaseDC        = user32.NewProc("ReleaseDC")
+	procGetDeviceCaps    = gdi32.NewProc("GetDeviceCaps")
 )
 
+// ------------------------------------------------------------------------
+// DPI 缩放辅助:高 DPI 屏幕(125%/150%/200%)下窗口与控件按物理像素创建会显得
+// 过小。manifest 声明 permonitorv2 只让进程「感知」DPI,不会自动放大窗口尺寸,
+// 必须手动把逻辑尺寸乘上缩放系数。scaleForDpi 返回 1.0~2.0 的缩放因子。
+// ------------------------------------------------------------------------
+
+// dpiScale 返回当前 DPI 缩放因子(96 基准)。失败/非 Windows 返回 1.0。
+func dpiScale() float64 {
+	dpi := systemDpi()
+	if dpi <= 0 {
+		return 1.0
+	}
+	return float64(dpi) / 96.0
+}
+
+// scaleInt 按 DPI 缩放整数尺寸(最小保留 1)。
+func scaleInt(v int, scale float64) int {
+	if scale <= 0 {
+		scale = 1
+	}
+	r := int(float64(v) * scale)
+	if r < 1 {
+		r = 1
+	}
+	return r
+}
+
+// systemDpi 返回系统 DPI(96 基准)。GetDpiForSystem 可能受 OS 版本限制,
+// 失败时用 GetDeviceCaps(LOGPIXELSX) 兜底。
+func systemDpi() uint32 {
+	// GetDpiForSystem(Win10 1607+)
+	if procGetDpiForSystem.Find() == nil {
+		r, _, _ := procGetDpiForSystem.Call()
+		if r != 0 {
+			return uint32(r)
+		}
+	}
+	// 兜底:GetDeviceCaps(LOGPIXELSX=88)
+	if procGetDeviceCaps.Find() == nil {
+		hdc, _, _ := procGetDC.Call(0)
+		if hdc != 0 {
+			r, _, _ := procGetDeviceCaps.Call(hdc, 88)
+			procReleaseDC.Call(0, hdc)
+			if r != 0 {
+				return uint32(r)
+			}
+		}
+	}
+	return 96
+}
+
 // ------------------------------------------------------------------------
 // 鼠标提醒运行时状态
 // ------------------------------------------------------------------------
@@ -222,30 +283,35 @@ var (
 type mouseAlertState struct {
 	mu sync.Mutex
 
-	started    bool   // 工作线程是否已启动(持久化,仅启动一次)
-	overlayWnd uintptr
-	active     bool
-	text       string
-	flashOn    bool
+	started      bool // 工作线程是否已启动(持久化,仅启动一次)
+	overlayWnd   uintptr
+	active       bool
+	text         string
+	flashOn      bool
 	lastX, lastY int32
-	stopTime   time.Time
-	wndProc    uintptr
-	classOK    bool
-	bgBrush    uintptr
-	scrollX    int32  // 超长文字水平滚动偏移(px),定时器推进
-	textWidth  int32  // 当前文字像素宽度(>可用宽度时滚动)
-	textGap    int32  // 头尾相联间隔(两个空格宽度 px),滚动周期 = 文字宽 + 间隔
+	stopTime     time.Time
+	wndProc      uintptr
+	classOK      bool
+	bgBrush      uintptr
+	scrollX      int32 // 超长文字水平滚动偏移(px),定时器推进
+	textWidth    int32 // 当前文字像素宽度(>可用宽度时滚动)
+	textGap      int32 // 头尾相联间隔(两个空格宽度 px),滚动周期 = 文字宽 + 间隔
 
 	// 运行时配置(triggerMouseAlert 时从设置加载)
-	cfgWidth     int32         // 气泡窗口宽度(px)
-	cfgHeight    int32         // 气泡窗口高度(px,按字号自适应)
-	cfgFontSize  int32         // 字号(px)
-	cfgSpeed     int           // 超长文字滚动速度(px/s)
-	cfgDuration  time.Duration // 显示时长
-	cfgTextColor uintptr       // 文字颜色(COLORREF)
-	cfgBgColor   uintptr       // 气泡背景色(COLORKEY 抠透明)
-	cfgOutlineColor uintptr    // 文字描边颜色(COLORREF),形成反差
-	cfgOutlineWidth int32      // 文字描边宽度(px),0 关闭
+	cfgWidth        int32         // 气泡窗口宽度(px)
+	cfgHeight       int32         // 气泡窗口高度(px,按字号自适应)
+	cfgFontSize     int32         // 字号(px)
+	cfgSpeed        int           // 超长文字滚动速度(px/s)
+	cfgDuration     time.Duration // 显示时长
+	cfgTextColor    uintptr       // 文字颜色(COLORREF)
+	cfgBgColor      uintptr       // 气泡背景色(COLORKEY 抠透明)
+	cfgOutlineColor uintptr       // 文字描边颜色(COLORREF),形成反差
+	cfgOutlineWidth int32         // 文字描边宽度(px),0 关闭
+
+	// aboveMode 提示定位模式:true 时气泡显示在鼠标正上方(用于资源管理器
+	// 悬停标签提示,避免遮挡光标且不与系统原有的右下信息提示重叠);
+	// false 时气泡显示在鼠标右下偏移(默认,见 positionAndDraw)。
+	aboveMode bool
 }
 
 var mouseAlert = &mouseAlertState{}
@@ -290,6 +356,81 @@ func triggerMouseAlert(text string) {
 	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()
+
+	// 首次触发:启动常驻工作线程(幂等),建窗后由线程主动定位并重绘
+	if !started {
+		go mouseAlertLoop()
+		return
+	}
+	// 已启动:唤醒窗口线程立即刷新(窗口线程负责 SetWindowPos/绘制)
+	if overlay != 0 {
+		procPostMessage.Call(overlay, wmRefresh, 0, 0)
+	}
+}
+
+// triggerMouseAlertAbove 触发鼠标提醒,并强制把气泡定位到鼠标正上方。
+// 用于资源管理器悬停文件/文件夹显示「标签」提示:与默认的右下偏移不同,
+// 正上方模式能避开光标本身,也不会与资源管理器原有的信息提示(多位于
+// 光标右下方)重叠,满足用户「提示注意显示位置」的要求。
+// 除定位模式外,其余行为与 triggerMouseAlert 完全一致。
+func triggerMouseAlertAbove(text string) {
+	if text == "" {
+		return
+	}
+
+	// 从设置加载鼠标提醒配置(字号/宽度/速度/颜色/时长)
+	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
+	}
+	// 固定显示 tagAlertDuration(2 秒),不取用户「鼠标提醒」时长、也不因文字超长
+	// 智能延长:标签提示只在鼠标停留该文件期间显示,鼠标移开即被 stopTagAlert 隐藏。
+	// 若沿用 8 秒 + 超长延长,长备注的气泡会长时间挂在鼠标旁(用户反馈的问题)。
+	totalDur := tagAlertDuration
+
+	mouseAlert.mu.Lock()
+	mouseAlert.text = text
+	mouseAlert.active = true
+	mouseAlert.flashOn = true
+	mouseAlert.aboveMode = true // 关键:气泡定位到鼠标正上方
 	mouseAlert.stopTime = time.Now().Add(totalDur)
 	mouseAlert.scrollX = 0   // 新消息从头开始滚动
 	mouseAlert.textWidth = 0 // 强制重新测量
@@ -339,6 +480,23 @@ func stopMouseAlert() {
 	}
 }
 
+// stopTagAlert 立即隐藏资源管理器「标签」气泡(鼠标离开悬停项时调用)。
+// 与 stopMouseAlert 的区别:只在当前处于标签提示模式(aboveMode)时才停止,
+// 避免误关掉用户主动触发的普通鼠标提醒。
+func stopTagAlert() {
+	mouseAlert.mu.Lock()
+	if !mouseAlert.aboveMode {
+		mouseAlert.mu.Unlock()
+		return
+	}
+	mouseAlert.active = false
+	overlay := mouseAlert.overlayWnd
+	mouseAlert.mu.Unlock()
+	if overlay != 0 {
+		procShowWindow.Call(overlay, 0) // SW_HIDE
+	}
+}
+
 // mouseAlertLoop 常驻工作线程:注册窗口类、创建半透明置顶气泡窗口、
 // 启动跟随/闪烁定时器,进入消息循环。
 func mouseAlertLoop() {
@@ -589,11 +747,25 @@ func (s *mouseAlertState) positionAndDraw(overlay uintptr, x, y int32) {
 	if h <= 0 {
 		h = overlayHeight
 	}
+	above := s.aboveMode
 	s.mu.Unlock()
 
-	// 气泡左上角位于鼠标右下偏移,避免遮挡光标
-	left := x + 20
-	top := y + 24
+	var left, top int32
+	if above {
+		// 正上方模式(资源管理器悬停标签提示):气泡水平居中于鼠标、置于光标正上方,
+		// 留 8px 间隙,既不遮挡光标,也不与资源管理器原有的信息提示(光标右下方)重叠。
+		left = x - w/2
+		top = y - h - 8
+		// 顶部越界(鼠标太靠近屏幕顶)时,回退到光标下方显示,保证可见
+		if top < 0 {
+			left = x + 20
+			top = y + 24
+		}
+	} else {
+		// 默认:气泡左上角位于鼠标右下偏移,避免遮挡光标
+		left = x + 20
+		top = y + 24
+	}
 
 	// 背景透明(LWA_COLORKEY)只在创建窗口时设置一次,避免每帧重复设置导致闪烁。
 

+ 3 - 1
proxyservice.go

@@ -73,11 +73,13 @@ func (s *ProxyService) GetProxyStatus() ProxyStatus {
 		}
 	}
 	cfg := loadSettings().Proxy
-	st.Configured = strings.TrimSpace(cfg.Server) != ""
 	// 系统里没有地址但配置里有:用配置值回填,便于展示
 	if st.Server == "" {
 		st.Server = strings.TrimSpace(cfg.Server)
 	}
+	// 只要存在有效代理地址(系统注册表或配置任一来源)即视为「已配置」,
+	// 前端据此区分「未配置」(无地址)与「未启用」(有地址但代理未开启)。
+	st.Configured = strings.TrimSpace(st.Server) != ""
 	return st
 }
 

+ 60 - 18
settings.go

@@ -35,7 +35,7 @@ const (
 	DefaultNewsRefreshMinutes     = 120                 // 新闻自动刷新间隔(分钟)
 	DefaultNewsCount              = 30                  // 新闻页显示条数
 	DefaultGithubRefreshMinutes   = 120                 // Github 自动刷新间隔(分钟)
-	AppVersion                    = "0.1.7"             // 应用自身版本(与 build/windows/info.json 的 ProductVersion 一致),用于仓库更新提示
+	AppVersion                    = "0.1.8"             // 应用自身版本(与 build/windows/info.json 的 ProductVersion 一致),用于仓库更新提示
 
 	// 鼠标提醒默认配置
 	DefaultMouseAlertFontSize     = 20        // 字号(px)
@@ -97,13 +97,14 @@ type MouseAlertConfig struct {
 	OutlineWidth int    `json:"outlineWidth"` // 文字描边宽度(px),0 表示关闭描边
 }
 
-// GitLabConfig 私有 GitLab(git.scwy.net)自动升级配置。
-// PrivateToken 为空时也可从 gitlab-cred.json 读取,避免令牌明文进设置文件。
+// GitLabConfig 自动升级配置(静态更新站方案)。
+// BaseURL 为静态站目录地址,清单固定放在 {BaseURL}/manifest.json,无需鉴权。
+// ProjectPath / PrivateToken / Branch 为旧私有仓库方案遗留字段,不再参与,保留以兼容旧配置。
 type GitLabConfig struct {
-	BaseURL      string `json:"baseUrl"`      // GitLab 根地址,如 https://git.scwy.net
-	ProjectPath  string `json:"projectPath"`  // 项目路径,如 ease/toolbox
-	PrivateToken string `json:"privateToken"` // 私有访问令牌(PRIVATE_TOKEN)
-	Branch       string `json:"branch"`       // 版本清单所在分支或 Tag,默认 main
+	BaseURL      string `json:"baseUrl"`      // 静态更新站目录地址,如 https://i.scwy.net/down/toolsbox
+	ProjectPath  string `json:"projectPath"`  // (旧字段,不再使用)
+	PrivateToken string `json:"privateToken"` // (旧字段,不再使用)
+	Branch       string `json:"branch"`       // (旧字段,不再使用)
 }
 
 // ProxyConfig 网络代理配置(工具页「网络代理」卡片)。
@@ -144,6 +145,7 @@ type AppSettings struct {
 	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"`        // 「本地」页资源(标题|启动命令|说明,在设置中维护)
@@ -159,6 +161,8 @@ type AppSettings struct {
 	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"`        // 新闻滚动条配置
@@ -193,6 +197,14 @@ var (
 	activeHotkey      string
 	activeQuickHotkey string
 	activeProxyHotkey string
+	// hotkeyStatus 记录各热键最近的注册结果,供设置页提示:
+	// key 为 hotkey / quickHotkey / proxyHotkey,value 为失败原因(空=已生效)。
+	// 典型失败:该组合键已被其他程序占用(Register 返回冲突错误)。
+	hotkeyStatus = map[string]string{
+		"hotkey":      "",
+		"quickHotkey": "",
+		"proxyHotkey": "",
+	}
 )
 
 // defaultSettings 返回默认配置:开机启动默认开启,热键与页面地址使用内置值
@@ -215,6 +227,7 @@ func defaultSettings() AppSettings {
 			{Name: "GitHub", URL: "https://github.com/"},
 		},
 		NewsKeywords: "",
+		BiliPopularEnabled: true, // 新闻页默认显示 B站热门视频区块
 		GithubRepos: []RepoItem{
 			{URL: "https://github.com/wailsapp/wails", Desc: "Wails:Go + Web 桌面应用框架"},
 		},
@@ -229,6 +242,8 @@ func defaultSettings() AppSettings {
 		TodoPath:          "",                   // 待办路径:无默认值,用户须在设置中配置(空值时强制进入设置)
 		RecordPath:        "",                   // 记录路径:无默认值,用户须在设置中配置(空值时强制进入设置)
 		RecordDBPath:      "",                   // 记录数据库路径:无默认值,用户须在设置中配置(空值时强制进入设置)
+		TagDBPath:         "",                   // 文件标签数据库路径:无默认值,用户须在设置中配置(空值时标签功能不生效)
+		TagMenuEnabled:    true,                 // 资源管理器右键「标签」功能默认启用
 		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},
@@ -253,9 +268,9 @@ func defaultSettings() AppSettings {
 			Levels:         map[string]int{}, // 显示器名称 -> 亮度百分比
 		},
 		GitLab: GitLabConfig{
-			BaseURL:     "https://git.scwy.net", // 私有 GitLab 根地址
-			ProjectPath: "ease/toolbox",         // 版本清单所在项目
-			Branch:      "main",                 // 版本清单所在分支或 Tag
+			BaseURL:     "https://i.scwy.net/down/toolsbox", // 静态更新站:清单固定放在 {baseUrl}/manifest.json
+			ProjectPath: "ease/toolbox",                     // 保留字段,静态站方案不再参与
+			Branch:      "main",                             // 保留字段,静态站方案不再参与
 		},
 		Proxy: ProxyConfig{
 			Server: "", // 代理地址默认空,由用户在工具页填写
@@ -439,21 +454,15 @@ func normalizeSettings(settings AppSettings) AppSettings {
 		settings.ControlRepeatSecs = 1.0
 	}
 
-	// 自动升级(私有 GitLab)配置清洗:地址去尾部斜杠、补默认值;令牌仅 trim,允许空
+	// 自动升级(静态更新站)配置清洗:地址去尾部斜杠、补默认值;project/branch 保留但不再参与
 	settings.GitLab.BaseURL = strings.TrimRight(strings.TrimSpace(settings.GitLab.BaseURL), "/")
 	if settings.GitLab.BaseURL == "" {
-		settings.GitLab.BaseURL = "https://git.scwy.net"
+		settings.GitLab.BaseURL = "https://i.scwy.net/down/toolsbox"
 	}
 	settings.GitLab.ProjectPath = strings.TrimSpace(settings.GitLab.ProjectPath)
 	settings.GitLab.ProjectPath = strings.Trim(settings.GitLab.ProjectPath, "/")
-	if settings.GitLab.ProjectPath == "" {
-		settings.GitLab.ProjectPath = "ease/toolbox"
-	}
 	settings.GitLab.PrivateToken = strings.TrimSpace(settings.GitLab.PrivateToken)
 	settings.GitLab.Branch = strings.TrimSpace(settings.GitLab.Branch)
-	if settings.GitLab.Branch == "" {
-		settings.GitLab.Branch = "main"
-	}
 	settings.SkippedUpdateVersion = strings.TrimSpace(settings.SkippedUpdateVersion)
 
 	// Tab 顺序:只保留已存在的 tabId(内置 + 自定义 custom-N),去重;未列出的追加到末尾,保证全部 Tab 都能显示
@@ -756,6 +765,32 @@ func mergeRuntimeState(settings AppSettings) AppSettings {
 	return settings
 }
 
+// hotkeyConflictMessage 把热键注册失败原因整理为设置页可展示的中文提示。
+// 最常见原因:组合键已被其他程序占用(Register 返回冲突错误),
+// 此时引导用户换一个组合键;其余错误原样保留供排查。
+func hotkeyConflictMessage(hotkey string, err error) string {
+	if err == nil {
+		return ""
+	}
+	msg := strings.ToLower(err.Error())
+	if strings.Contains(msg, "already registered") || strings.Contains(msg, "already in use") {
+		return "该组合键已被其他程序占用,请换一个组合键"
+	}
+	return "注册失败:" + err.Error()
+}
+
+// GetHotkeyStatus 返回三个热键的注册状态(空字符串=已生效;非空=失败原因),
+// 供设置页在热键输入框旁显示冲突提示。key:hotkey / quickHotkey / proxyHotkey。
+func GetHotkeyStatus() map[string]string {
+	hotkeyMu.Lock()
+	defer hotkeyMu.Unlock()
+	out := make(map[string]string, len(hotkeyStatus))
+	for k, v := range hotkeyStatus {
+		out[k] = v
+	}
+	return out
+}
+
 // applySettings 把配置应用到运行时:重新注册热键、设置窗口置顶、同步开机启动
 func applySettings(settings AppSettings) {
 	hotkeyMu.Lock()
@@ -765,8 +800,10 @@ func applySettings(settings AppSettings) {
 		}
 		if err := app.GlobalShortcut.Register(settings.Hotkey, showMainWindow); err != nil {
 			log.Printf("register hotkey %q failed: %v", settings.Hotkey, err)
+			hotkeyStatus["hotkey"] = hotkeyConflictMessage(settings.Hotkey, err) // 记录失败原因,设置页提示
 		} else {
 			activeHotkey = settings.Hotkey // 记录当前生效的热键
+			hotkeyStatus["hotkey"] = ""    // 注册成功,清除提示
 		}
 	}
 	// 「快捷」菜单热键:独立注册,触发时在鼠标位置弹出快捷启动菜单
@@ -776,8 +813,10 @@ func applySettings(settings AppSettings) {
 		}
 		if err := app.GlobalShortcut.Register(settings.QuickHotkey, showQuickMenuAtCursor); err != nil {
 			log.Printf("register quick hotkey %q failed: %v", settings.QuickHotkey, err)
+			hotkeyStatus["quickHotkey"] = hotkeyConflictMessage(settings.QuickHotkey, err)
 		} else {
 			activeQuickHotkey = settings.QuickHotkey
+			hotkeyStatus["quickHotkey"] = "" // 注册成功,清除提示
 		}
 	}
 	// 「网络代理」开关热键:留空则不设热键(注销旧热键并跳过注册)
@@ -787,11 +826,14 @@ func applySettings(settings AppSettings) {
 		}
 		if strings.TrimSpace(settings.ProxyHotkey) == "" {
 			activeProxyHotkey = "" // 用户清空热键:不注册,仅记录空值
+			hotkeyStatus["proxyHotkey"] = ""
 		} else if err := app.GlobalShortcut.Register(settings.ProxyHotkey, toggleProxyByHotkey); err != nil {
 			log.Printf("register proxy hotkey %q failed: %v", settings.ProxyHotkey, err)
 			activeProxyHotkey = "" // 注册失败:视为未设,避免下次比较时误判
+			hotkeyStatus["proxyHotkey"] = hotkeyConflictMessage(settings.ProxyHotkey, err)
 		} else {
 			activeProxyHotkey = settings.ProxyHotkey
+			hotkeyStatus["proxyHotkey"] = "" // 注册成功,清除提示
 		}
 	}
 	hotkeyMu.Unlock()

+ 28 - 3
settingsservice.go

@@ -44,6 +44,23 @@ func (s *SettingsService) CheckUpdateManual() map[string]interface{} {
 	return CheckUpdateState()
 }
 
+// CheckUpdateDialog 设置页「检查更新」按钮:手动检查一次,发现新版本直接弹原生对话框
+// (立即升级 / 暂时跳过 / 此版不再提示)。已最新时返回 upToDate=true 供前端提示;
+// 检查失败返回 message 供前端显示错误。
+func (s *SettingsService) CheckUpdateDialog() map[string]interface{} {
+	found, err := PromptUpdateIfAvailable()
+	if err != nil {
+		state := CheckUpdateState()
+		state["message"] = err.Error()
+		return state
+	}
+	state := CheckUpdateState()
+	if !found {
+		state["upToDate"] = true // 已是最新版本,前端据此给出反馈提示
+	}
+	return state
+}
+
 // PrepareUpdate 下载并安装可用升级(需先 Check 出待升级版本),随后程序自动重启。
 // version 参数仅作记录用途,实际安装的版本由内置升级框架决定。
 func (s *SettingsService) PrepareUpdate(version string) error {
@@ -94,6 +111,12 @@ func (s *SettingsService) GetSettings() AppSettings {
 	return loadSettings()
 }
 
+// GetHotkeyStatus 返回三个热键的注册状态(空字符串=已生效;非空=占用/失败原因),
+// 供设置页在热键输入框旁显示冲突提示,例如默认组合键被其他程序占用时。
+func (s *SettingsService) GetHotkeyStatus() map[string]string {
+	return GetHotkeyStatus()
+}
+
 // SetMobileMode 前端在窗口尺寸变化时调用:移动端(窄屏)隐藏主机 Tab 并禁止滚动条
 func (s *SettingsService) SetMobileMode(mobile bool) {
 	SetMobileMode(mobile)
@@ -101,12 +124,14 @@ func (s *SettingsService) SetMobileMode(mobile bool) {
 
 // SaveSettings 保存配置并立即生效:热键、窗口置顶、开机启动、页面地址、股票代码等
 func (s *SettingsService) SaveSettings(settings AppSettings) (AppSettings, error) {
+	prev := loadSettings() // 旧配置:用于检测「标签功能」开关翻转
 	settings = normalizeSettings(settings) // 校正空值与代码格式
 	settings = mergeRuntimeState(settings) // 保留自动保存的窗口尺寸与滚动条位置
 	if err := saveSettings(settings); err != nil {
 		return settings, err
 	}
 	applySettings(settings) // 应用到运行时
+	applyTagMenuToggle(prev, settings) // 按开关翻转启停标签功能
 	return settings, nil
 }
 
@@ -126,9 +151,9 @@ func (s *SettingsService) PickWebDir() (string, error) {
 	return pickWebDir()
 }
 
-// StartWebService 启动静态文件服务(默认页 index.html 或 readme.md)。
-func (s *SettingsService) StartWebService(dir string) (WebServiceInfo, error) {
-	return StartWebService(dir)
+// StartWebService 启动静态文件服务(默认页 index.html 或 readme.md),监听指定端口。
+func (s *SettingsService) StartWebService(dir string, port int) (WebServiceInfo, error) {
+	return StartWebService(dir, port)
 }
 
 // StopWebService 停止静态文件服务。

+ 87 - 0
tagcmd.go

@@ -0,0 +1,87 @@
+// ============================================================================
+// tagcmd.go — 「-tag <路径>」命令行处理(跨平台)
+//
+// 注册表右键菜单「标签」调用本程序:`本程序 -tag "<文件/文件夹完整路径>"`。
+// 流程:
+//  1. 解析 os.Args 中的 -tag 参数;
+//  2. 若已有实例在运行(其内置 API 可探测),把路径 POST 到该实例的
+//     /api/tag/open 接口,让运行中的实例弹出标签编辑窗口,本进程随即退出
+//     (保持原有程序运行);
+//  3. 若探测不到运行中的实例,本进程作为主实例继续完整启动,并在界面就绪后
+//     打开标签编辑窗口(pendingTagPath 记录待处理路径)。
+//
+// ============================================================================
+package main
+
+import (
+	"bytes"
+	"encoding/json"
+	"net/http"
+	"os"
+	"strings"
+	"time"
+)
+
+// pendingTagPath 主实例自身携带的待打开标签编辑窗口的路径(-tag 参数解析后,
+// 未能转发给其他实例时记录,待界面就绪后由 main 调用 openTagEditor)。
+var pendingTagPath string
+
+// tagPathFromArgs 从命令行解析 -tag 后的路径参数;未提供返回 ""。
+func tagPathFromArgs() string {
+	args := os.Args[1:]
+	for i := 0; i < len(args); i++ {
+		if args[i] == "-tag" && i+1 < len(args) {
+			return strings.TrimSpace(args[i+1])
+		}
+	}
+	return ""
+}
+
+// handleTagCommandIfNeeded 处理 -tag 命令行。
+// 返回 true 表示已成功转发给运行中的实例,调用方应立即退出本进程;
+// 返回 false 表示本进程应作为主实例继续启动(若带 -tag,路径已记入 pendingTagPath)。
+func handleTagCommandIfNeeded() bool {
+	path := tagPathFromArgs()
+	if path == "" {
+		return false
+	}
+	if forwardTagToRunning(path) {
+		return true // 已有实例接管,本进程退出
+	}
+	pendingTagPath = path // 无运行实例:本进程负责弹窗
+	return false
+}
+
+// tagAPIAddr 返回本程序内置 API 的监听地址(读取配置,空则用默认)。
+func tagAPIAddr() string {
+	addr := strings.TrimSpace(loadSettings().APIAddr)
+	if addr == "" {
+		addr = DefaultAPIAddr
+	}
+	return addr
+}
+
+// forwardTagToRunning 探测运行中的实例并把「打开标签编辑」请求转发过去。
+// 成功返回 true(调用方应退出);多次重试以应对主实例启动早期 API 尚未就绪。
+func forwardTagToRunning(path string) bool {
+	client := &http.Client{Timeout: 2 * time.Second}
+	body, err := json.Marshal(map[string]string{"path": path})
+	if err != nil {
+		return false
+	}
+	url := "http://" + tagAPIAddr() + "/api/tag/open"
+	for i := 0; i < 3; i++ { // 主实例启动早期可能还没监听,重试 3 次
+		req, err := http.NewRequest(http.MethodPost, url, bytes.NewReader(body))
+		if err != nil {
+			return false
+		}
+		req.Header.Set("Content-Type", "application/json")
+		resp, err := client.Do(req)
+		if err == nil {
+			resp.Body.Close()
+			return resp.StatusCode == http.StatusOK
+		}
+		time.Sleep(300 * time.Millisecond)
+	}
+	return false
+}

+ 331 - 0
tageditor_windows.go

@@ -0,0 +1,331 @@
+//go:build windows
+
+// ============================================================================
+// tageditor_windows.go — 标签编辑输入窗口(难点2)
+//
+// 右键菜单点「标签(&T)」后弹出的小窗口:输入「标签」和「备注」两栏,
+// 确定时写入标签数据库(SaveTag),取消/关闭则不写。
+//
+// 实现:仿 mouseAlertLoop 的窗口线程模式(runtime.LockOSThread + RegisterClassExW
+// + CreateWindowExW + GetMessage 消息循环 + 自有 WndProc)。不用 Wails 前端模态
+// 是因为右键场景前台是 explorer,切到 Wails 窗口体验割裂且需新增前端 UI+事件通道。
+// ============================================================================
+package main
+
+import (
+	"fmt"
+	"os"
+	"runtime"
+	"sync"
+	"syscall"
+	"unsafe"
+)
+
+// 标签编辑窗口控件 ID
+const (
+	tagEditID       = 1001 // 标签 EDIT
+	noteEditID      = 1002 // 备注 EDIT(多行)
+	btnOKID         = 1003 // 确定
+	btnCancelID     = 1004 // 取消
+	tagEditorWidth  = 400  // 逻辑宽度(px @96DPI),创建时按 DPI 缩放
+	tagEditorHeight = 260  // 逻辑高度(px @96DPI),创建时按 DPI 缩放
+)
+
+// 标准控件样式
+const (
+	wsChild         = 0x40000000
+	wsVisible       = 0x10000000
+	wsTabStop       = 0x00010000
+	wsGroup         = 0x00020000
+	wsBorder        = 0x00800000
+	wsCaption       = 0x00C00000
+	wsSysMenu       = 0x00080000
+	wsThickFrame    = 0x00040000
+	wsOverlapped    = 0x00000000
+	wsExDlgModal    = 0x00000001
+	wsExTopMost     = 0x00000008
+	wsExAppWindow   = 0x00040000
+	esMultiLine     = 0x0004
+	esAutoHScroll   = 0x0080
+	esAutoVScroll   = 0x0040
+	bsDefPushButton = 0x0001
+)
+
+// 本文件用到的 user32 过程(procCreateWindowEx/procGetMessage/procRegisterClassEx/
+// procDefWindowProc/procDestroyWindow/procShowWindow/procSetForegroundWindow/
+// procGetSystemMetrics/procGetModuleHandleW 等已在其它文件定义,此处不复用)。
+var (
+	procGetWindowTextW       = user32.NewProc("GetWindowTextW")
+	procSetWindowTextW       = user32.NewProc("SetWindowTextW")
+	procGetDlgItem           = user32.NewProc("GetDlgItem")
+	procGetWindowTextLengthW = user32.NewProc("GetWindowTextLengthW")
+	procSetFocus             = user32.NewProc("SetFocus")
+	procPostQuitMessage      = user32.NewProc("PostQuitMessage")
+	procGetClientRect        = user32.NewProc("GetClientRect")
+)
+
+// tagEditor 标签编辑窗口状态(单实例,包级)。
+var tagEditor struct {
+	mu      sync.Mutex
+	hwnd    uintptr
+	path    string
+	cb      uintptr // WndProc 回调地址(保持引用防 GC)
+	classOK bool
+	started bool
+}
+
+// openTagEditor 弹出标签编辑窗口(由右键菜单回调异步调用)。
+// 会启动一个 LockOSThread 的窗口线程。path 为规范化前的完整路径(显示用原始,
+// 写入库时由 SaveTag 再规范化)。
+func openTagEditor(path string) {
+	if path == "" {
+		return
+	}
+	tagEditor.mu.Lock()
+	if tagEditor.started {
+		// 已有一个编辑窗口:把新路径切过去(复用窗口,避免多实例)。
+		hwnd := tagEditor.hwnd
+		tagEditor.path = path
+		tagEditor.mu.Unlock()
+		if hwnd != 0 {
+			procSetForegroundWindow.Call(hwnd)
+		}
+		return
+	}
+	tagEditor.started = true
+	tagEditor.path = path
+	tagEditor.mu.Unlock()
+
+	go tagEditorLoop()
+}
+
+// tagEditorLoop 标签编辑窗口线程。
+func tagEditorLoop() {
+	runtime.LockOSThread()
+	defer runtime.UnlockOSThread()
+
+	hInst, _, _ := procGetModuleHandleW.Call(0)
+	className, _ := syscall.UTF16PtrFromString("TengTuTagEditor")
+
+	// 注册窗口类(WndProc 是 Go 回调,须保持地址)。
+	tagEditor.mu.Lock()
+	tagEditor.cb = syscall.NewCallback(tagEditorWndProc)
+	wc := wndclassex{
+		CbSize:        uint32(unsafe.Sizeof(wndclassex{})),
+		LpfnWndProc:   tagEditor.cb,
+		HInstance:     hInst,
+		LpszClassName: className,
+		HCursor:       0,
+	}
+	atom, _, _ := procRegisterClassEx.Call(uintptr(unsafe.Pointer(&wc)))
+	if atom == 0 {
+		tagEditor.classOK = false
+		tagEditor.mu.Unlock()
+		fmt.Fprintf(os.Stderr, "[tageditor] RegisterClassEx failed\n")
+		return
+	}
+	tagEditor.classOK = true
+	tagEditor.mu.Unlock()
+
+	// 按 DPI 缩放窗口尺寸:manifest permonitorv2 下窗口按物理像素创建,
+	// 高 DPI 屏幕(125%/150%/200%)上 380x220 物理像素显得过小(用户反馈
+	// 「窗口小,看不到按钮/输入框」)。这里把逻辑尺寸乘上缩放因子。
+	scale := dpiScale()
+	winW := scaleInt(tagEditorWidth, scale)
+	winH := scaleInt(tagEditorHeight, scale)
+
+	// 屏幕中心定位
+	sw, _, _ := procGetSystemMetrics.Call(0) // SM_CXSCREEN
+	sh, _, _ := procGetSystemMetrics.Call(1) // SM_CYSCREEN
+	x := int(sw)/2 - winW/2
+	y := int(sh)/2 - winH/2
+
+	// 创建主窗口(带标题栏、系统菜单;模态于 explorer 之上)
+	hwnd, _, _ := procCreateWindowEx.Call(
+		uintptr(wsExTopMost|wsExAppWindow), // 置顶 + 应用窗口
+		uintptr(unsafe.Pointer(className)),
+		strPtr("添加标签 / 备注"),
+		uintptr(wsOverlapped|wsCaption|wsSysMenu|wsThickFrame),
+		uintptr(x), uintptr(y),
+		uintptr(winW), uintptr(winH),
+		0, 0, hInst, 0,
+	)
+	if hwnd == 0 {
+		fmt.Fprintf(os.Stderr, "[tageditor] CreateWindowEx failed\n")
+		tagEditor.mu.Lock()
+		tagEditor.started = false
+		tagEditor.mu.Unlock()
+		return
+	}
+	tagEditor.mu.Lock()
+	tagEditor.hwnd = hwnd
+	tagEditor.mu.Unlock()
+
+	// 创建控件:标签标签+输入框、备注标签+多行输入框、确定/取消按钮
+	createTagEditorControls(hwnd, hInst)
+
+	procShowWindow.Call(hwnd, 1) // SW_SHOWNORMAL
+	procSetForegroundWindow.Call(hwnd)
+	// procGetDlgItem.Call 返回 (hwnd, r2, err);Go 不允许对多返回值直接下标,
+	// 先取第一值(控件句柄)再 SetFocus。
+	tagEditCtrl, _, _ := procGetDlgItem.Call(hwnd, tagEditID)
+	procSetFocus.Call(tagEditCtrl)
+
+	// 消息循环(直到 WM_QUIT)
+	var m msg
+	for {
+		ret, _, _ := procGetMessage.Call(uintptr(unsafe.Pointer(&m)), 0, 0, 0)
+		if ret == 0 {
+			break
+		}
+		procTranslateMessage.Call(uintptr(unsafe.Pointer(&m)))
+		procDispatchMessage.Call(uintptr(unsafe.Pointer(&m)))
+	}
+
+	// 清理
+	if hwnd != 0 {
+		procDestroyWindow.Call(hwnd)
+	}
+	tagEditor.mu.Lock()
+	tagEditor.hwnd = 0
+	tagEditor.started = false
+	tagEditor.mu.Unlock()
+}
+
+// createTagEditorControls 创建标签编辑窗口内的控件。
+func createTagEditorControls(hwnd, hInst uintptr) {
+	// mk 创建静态标签文本控件(class="STATIC",text 为显示文字)。
+	// procCreateWindowEx.Call 返回 (hwnd, r2, err),此处只关心句柄,故取 [0]。
+	// 坐标/尺寸用 int(DPI 缩放后计算),内部转 uintptr。
+	mk := func(text string, x, y, w, h int) {
+		ts, _ := syscall.UTF16PtrFromString(text)
+		procCreateWindowEx.Call(0,
+			uintptr(unsafe.Pointer(utf16("STATIC"))),
+			uintptr(unsafe.Pointer(ts)),
+			uintptr(wsChild|wsVisible|wsGroup),
+			uintptr(x), uintptr(y), uintptr(w), uintptr(h), hwnd, 0, hInst, 0)
+	}
+	// 按 DPI 缩放控件尺寸与坐标(与窗口同比例),否则高 DPI 屏上输入框/按钮
+	// 仍按物理像素创建而显得过小、且放不进被放大的窗口。
+	scale := dpiScale()
+	pad := scaleInt(12, scale)
+	labelH := scaleInt(18, scale)
+	inputH := scaleInt(26, scale)
+	btnW := scaleInt(80, scale)
+	btnH := scaleInt(30, scale)
+	gap := scaleInt(12, scale) // 行间距
+	labelX := pad
+	labelW := scaleInt(64, scale)
+	inputX := pad + labelW
+	noteH := scaleInt(80, scale) // 备注输入框高度(多行)
+
+	// 客户区实际尺寸:外层窗口含标题栏+边框,CreateWindowEx 传入的是外层宽高,
+	// 若按外层高度布局按钮会超出客户区被裁切(用户反馈「按钮/输入框显示不全」)。
+	// 这里用 GetClientRect 取真实客户区,按钮贴客户区底边、备注框贴按钮上方。
+	var cr rect
+	procGetClientRect.Call(hwnd, uintptr(unsafe.Pointer(&cr)))
+	clientW := int(cr.Right - cr.Left)
+	clientH := int(cr.Bottom - cr.Top)
+	if clientW <= 0 || clientH <= 0 { // 兜底:取外层尺寸(几乎不会发生)
+		clientW = scaleInt(tagEditorWidth, scale)
+		clientH = scaleInt(tagEditorHeight, scale)
+	}
+
+	btnY := clientH - pad - btnH            // 按钮底边贴客户区底边(留 pad)
+	editW := clientW - inputX - pad         // 输入框右缘贴客户区右边(留 pad)
+	noteY := pad + inputH + gap             // 备注框在标签输入框下方 gap
+	// 备注框高度:按钮上方到备注框顶部之间全部利用(若剩余空间不足则用 noteH)
+	if btnY-noteY-gap < noteH {
+		noteH = btnY - noteY - gap
+		if noteH < scaleInt(40, scale) {
+			noteH = scaleInt(40, scale) // 保底 40px,避免极端情况挤压
+		}
+	}
+
+	// 标签
+	mk("标签:", labelX, pad, labelW, labelH)
+	procCreateWindowEx.Call(0,
+		uintptr(unsafe.Pointer(utf16("EDIT"))),
+		0,
+		uintptr(wsChild|wsVisible|wsTabStop|wsBorder),
+		uintptr(inputX), uintptr(pad-scaleInt(1, scale)), uintptr(editW), uintptr(inputH), hwnd,
+		tagEditID, hInst, 0)
+	// 备注
+	mk("备注:", labelX, noteY, labelW, labelH)
+	procCreateWindowEx.Call(0,
+		uintptr(unsafe.Pointer(utf16("EDIT"))),
+		0,
+		uintptr(wsChild|wsVisible|wsTabStop|wsBorder|esMultiLine|esAutoVScroll|esAutoHScroll),
+		uintptr(inputX), uintptr(noteY-scaleInt(1, scale)), uintptr(editW), uintptr(noteH), hwnd,
+		noteEditID, hInst, 0)
+	// 按钮:取消(左)、确定(右),底边贴客户区底边
+	procCreateWindowEx.Call(0,
+		uintptr(unsafe.Pointer(utf16("BUTTON"))),
+		uintptr(unsafe.Pointer(utf16("取消"))),
+		uintptr(wsChild|wsVisible|wsTabStop),
+		uintptr(clientW-btnW*2-pad*2), uintptr(btnY), uintptr(btnW), uintptr(btnH), hwnd,
+		btnCancelID, hInst, 0)
+	procCreateWindowEx.Call(0,
+		uintptr(unsafe.Pointer(utf16("BUTTON"))),
+		uintptr(unsafe.Pointer(utf16("确定"))),
+		uintptr(wsChild|wsVisible|wsTabStop|bsDefPushButton),
+		uintptr(clientW-btnW-pad), uintptr(btnY), uintptr(btnW), uintptr(btnH), hwnd,
+		btnOKID, hInst, 0)
+}
+
+// utf16 快捷转 UTF16 指针(临时,须立即使用)。
+func utf16(s string) *uint16 {
+	p, _ := syscall.UTF16PtrFromString(s)
+	return p
+}
+
+// tagEditorWndProc 标签编辑窗口消息处理。
+func tagEditorWndProc(hwnd uintptr, msgID uint32, wParam uintptr, lParam uintptr) uintptr {
+	switch msgID {
+	case 0x0111: // WM_COMMAND:控件通知
+		id := uint32(wParam & 0xffff)
+		switch id {
+		case btnOKID:
+			// 读控件文本 → 写库 → 关闭
+			tagEditor.mu.Lock()
+			path := tagEditor.path
+			tagEditor.mu.Unlock()
+			tagText := getControlText(hwnd, tagEditID)
+			noteText := getControlText(hwnd, noteEditID)
+			if err := getTagSvc().SaveTag(path, tagText, noteText); err != nil {
+				logTagErr("SaveTag", err)
+				// 写库失败:提示并保持窗口打开(先取确定按钮句柄)
+				okBtn, _, _ := procGetDlgItem.Call(hwnd, btnOKID)
+				procSetWindowTextW.Call(okBtn, uintptr(unsafe.Pointer(utf16("确定(失败)"))))
+			} else {
+				procPostQuitMessage.Call(0)
+			}
+		case btnCancelID:
+			procPostQuitMessage.Call(0)
+		}
+	case 0x0010: // WM_CLOSE:用户点标题栏关闭 → 视为取消
+		procPostQuitMessage.Call(0)
+	case 0x0002: // WM_DESTROY
+		procPostQuitMessage.Call(0)
+	}
+	// msgID 是 uint32,转 uintptr 传入 DefWindowProc;
+	// procDefWindowProc.Call 返回 (ret, r2, err),只需取第一值。
+	ret, _, _ := procDefWindowProc.Call(hwnd, uintptr(msgID), wParam, lParam)
+	return ret
+}
+
+// getControlText 读取 EDIT 控件文本。
+func getControlText(parent, id uintptr) string {
+	edit, _, _ := procGetDlgItem.Call(parent, id)
+	if edit == 0 {
+		return ""
+	}
+	// 先查长度,再读
+	n, _, _ := procGetWindowTextLengthW.Call(edit)
+	if n == 0 {
+		return ""
+	}
+	buf := make([]uint16, n+1)
+	procGetWindowTextW.Call(edit, uintptr(unsafe.Pointer(&buf[0])), n+1)
+	return syscall.UTF16ToString(buf)
+}

+ 35 - 0
tagmenu_dev.go

@@ -0,0 +1,35 @@
+//go:build !production
+
+// ============================================================================
+// tagmenu_dev.go — 开发构建(wails3 dev)跳过注册表写入
+//
+// wails3 dev 把代码编译为 bin/腾图工具箱.exe 并直接运行,无 production 标签。
+// 若此时写入注册表,会把「标签」右键菜单命令误指向 dev 版 exe,
+// 导致用户从资源管理器右键启动的是开发版而非已安装的正式版。
+// 故开发构建一律跳过注册表写入(不修改已有正式版菜单)。
+// ============================================================================
+package main
+
+import "log"
+
+// maybeWriteTagMenu 开发构建:跳过注册表写入,避免覆盖正式版菜单命令。
+// 返回 true 表示已处理(dev 构建一律跳过,无需写入)。
+func maybeWriteTagMenu() bool {
+	log.Printf("[tagmenu] 开发构建(无 production 标签),跳过注册表右键菜单写入")
+	return true
+}
+
+// handleInstallTagMenu 开发构建:不处理 -install-tagmenu(dev 不写注册表)。
+func handleInstallTagMenu() bool {
+	return false
+}
+
+// maybeRemoveTagMenu 开发构建:跳过注册表删除(dev 不写注册表,无需删除)。
+func maybeRemoveTagMenu() bool {
+	return true
+}
+
+// handleRemoveTagMenu 开发构建:不处理 -remove-tagmenu。
+func handleRemoveTagMenu() bool {
+	return false
+}

+ 38 - 0
tagmenu_other.go

@@ -0,0 +1,38 @@
+//go:build !windows
+
+// ============================================================================
+// tagmenu_other.go — 资源管理器右键菜单「标签」(非 Windows 桩)
+//
+// 右键菜单与标签编辑窗口仅 Windows 使用(依赖注册表与 Win32 窗口)。
+// 非 Windows 平台提供空实现保证编译通过:不写入注册表、不弹窗、
+// 不处理提权子命令。
+// ============================================================================
+package main
+
+import "log"
+
+// maybeWriteTagMenu 非 Windows 平台为空实现(无注册表右键菜单)。
+func maybeWriteTagMenu() bool {
+	return true
+}
+
+// handleInstallTagMenu 非 Windows 平台为空实现(无提权写入)。
+func handleInstallTagMenu() bool {
+	return false
+}
+
+// maybeRemoveTagMenu 非 Windows 平台为空实现(无注册表右键菜单)。
+func maybeRemoveTagMenu() bool {
+	return true
+}
+
+// handleRemoveTagMenu 非 Windows 平台为空实现。
+func handleRemoveTagMenu() bool {
+	return false
+}
+
+// openTagEditor 非 Windows 平台为空实现(无 Win32 弹窗能力)。
+func openTagEditor(path string) {
+	_ = path
+	log.Printf("[tagmenu] 标签编辑窗口仅支持 Windows")
+}

+ 128 - 0
tagmenu_prod.go

@@ -0,0 +1,128 @@
+//go:build production
+
+// ============================================================================
+// tagmenu_prod.go — 发布构建时写入右键菜单注册表
+//
+// 仅当编译带 `production` 标签(wails3 build / 安装包构建)时,才把
+// 「标签」右键菜单写入系统注册表,命令指向当前发布版 exe。
+// `wails3 dev`(无 production 标签)运行的是 dev 版 bin/腾图工具箱.exe,
+// 若写入注册表会把命令误指到 dev 版,故 dev 构建通过 tagmenu_dev.go 跳过。
+//
+// 写入 HKEY_CLASSES_ROOT 需要管理员权限。策略:
+//   - 日常启动:先探测是否需要写入(键缺失或命令不一致才需要)。
+//     普通权限能读 HKCR,探测无副作用、不弹 UAC。
+//   - 普通权限写入失败(访问被拒绝):用 runas 提权运行自身
+//     `-install-tagmenu`,让提权后的子进程完成写入,本进程不等待。
+//
+// ============================================================================
+package main
+
+import (
+	"log"
+	"os"
+
+	"golang.org/x/sys/windows"
+)
+
+// maybeWriteTagMenu 发布构建:写入(或修复)资源管理器右键菜单「标签」。
+// 返回 true 表示本次已处理(含已提权子进程接管),false 表示无需写入。
+func maybeWriteTagMenu() bool {
+	if !tagMenuNeedsWrite() {
+		return true // 已就绪且命令一致,无需写入
+	}
+	if err := ensureTagMenuRegistry(); err != nil {
+		// 普通权限写入失败(常见:HKCR 需要管理员)。提权运行自身完成写入。
+		log.Printf("[tagmenu] 写入注册表失败(可能无管理员权限),尝试提权: %v", err)
+		requestElevatedTagMenuWrite()
+		return true
+	}
+	log.Printf("[tagmenu] 注册表右键菜单「标签」已写入")
+	return true
+}
+
+// requestElevatedTagMenuWrite 用 runas verb 触发 UAC 提权运行自身 `-install-tagmenu`。
+// 子进程以管理员完成注册表写入;本进程不等待(子进程独立完成任务后退出)。
+// 注意:必须用 ShellExecute + runas,不能 exec.Command —— exec.Command 用
+// CreateProcess 以同权限启动子进程,不会触发 UAC 提权弹窗。
+func requestElevatedTagMenuWrite() {
+	exe, err := os.Executable()
+	if err != nil {
+		log.Printf("[tagmenu] 提权写入失败(获取自身路径): %v", err)
+		return
+	}
+	verb, _ := windows.UTF16PtrFromString("runas")
+	file, _ := windows.UTF16PtrFromString(exe)
+	args, _ := windows.UTF16PtrFromString("-install-tagmenu")
+	// SW_HIDE:提权子进程是纯命令行写入,不显示窗口。
+	if err := windows.ShellExecute(0, verb, file, args, nil, windows.SW_HIDE); err != nil {
+		log.Printf("[tagmenu] 触发 UAC 提权失败(可能被取消): %v", err)
+		return
+	}
+	log.Printf("[tagmenu] 已请求管理员提权写入注册表(UAC 弹窗,请确认)")
+}
+
+// handleInstallTagMenu 处理 `-install-tagmenu` 子命令(提权子进程)。
+// 返回 true 表示本进程是提权写入进程,应立即退出。
+func handleInstallTagMenu() bool {
+	for _, a := range os.Args[1:] {
+		if a == "-install-tagmenu" {
+			if err := ensureTagMenuRegistry(); err != nil {
+				log.Printf("[tagmenu] 提权写入注册表失败: %v", err)
+				return true
+			}
+			log.Printf("[tagmenu] 提权写入注册表成功")
+			return true
+		}
+	}
+	return false
+}
+
+// maybeRemoveTagMenu 关闭「标签」功能:删除注册表右键菜单。
+// 返回 true 表示已处理(含已提权子进程接管),false 表示无需删除。
+func maybeRemoveTagMenu() bool {
+	if !tagMenuExists() {
+		return true // 键不存在,无需删除
+	}
+	if err := removeTagMenuRegistry(); err != nil {
+		// 普通权限删除失败(常见:HKCR 需要管理员)。提权运行自身完成删除。
+		log.Printf("[tagmenu] 删除注册表失败(可能无管理员权限),尝试提权: %v", err)
+		requestElevatedTagMenuRemove()
+		return true
+	}
+	log.Printf("[tagmenu] 注册表右键菜单「标签」已删除")
+	return true
+}
+
+// requestElevatedTagMenuRemove 用 runas verb 触发 UAC 提权运行自身 `-remove-tagmenu`。
+// 子进程以管理员完成注册表删除;本进程不等待。
+func requestElevatedTagMenuRemove() {
+	exe, err := os.Executable()
+	if err != nil {
+		log.Printf("[tagmenu] 提权删除失败(获取自身路径): %v", err)
+		return
+	}
+	verb, _ := windows.UTF16PtrFromString("runas")
+	file, _ := windows.UTF16PtrFromString(exe)
+	args, _ := windows.UTF16PtrFromString("-remove-tagmenu")
+	if err := windows.ShellExecute(0, verb, file, args, nil, windows.SW_HIDE); err != nil {
+		log.Printf("[tagmenu] 触发 UAC 提权删除失败(可能被取消): %v", err)
+		return
+	}
+	log.Printf("[tagmenu] 已请求管理员提权删除注册表(UAC 弹窗,请确认)")
+}
+
+// handleRemoveTagMenu 处理 `-remove-tagmenu` 子命令(提权子进程)。
+// 返回 true 表示本进程是提权删除进程,应立即退出。
+func handleRemoveTagMenu() bool {
+	for _, a := range os.Args[1:] {
+		if a == "-remove-tagmenu" {
+			if err := removeTagMenuRegistry(); err != nil {
+				log.Printf("[tagmenu] 提权删除注册表失败: %v", err)
+				return true
+			}
+			log.Printf("[tagmenu] 提权删除注册表成功")
+			return true
+		}
+	}
+	return false
+}

+ 142 - 0
tagmenu_windows.go

@@ -0,0 +1,142 @@
+//go:build windows
+
+// ============================================================================
+// tagmenu_windows.go — 资源管理器右键菜单「标签」注册表写入(Windows 实现)
+//
+// 向系统注册表添加两个右键菜单项:
+//   - HKEY_CLASSES_ROOT\*\shell\标签        —— 所有文件
+//   - HKEY_CLASSES_ROOT\Directory\shell\标签 —— 所有文件夹
+//
+// 命令调用:本程序 -tag "%1"("%1" 由资源管理器替换为选中项的完整路径)。
+// 右键点击「标签」即调用本程序,由 -tag 命令行逻辑转发给运行中的实例或本实例弹窗。
+//
+// 写入 HKEY_CLASSES_ROOT(实际落 HKLM\Software\Classes)需要管理员权限。
+// 普通权限下 CreateKey 返回「访问被拒绝」;调用方(maybeWriteTagMenu)检测到
+// 写入失败后用 runas 提权运行自身(-install-tagmenu)完成写入。
+// ============================================================================
+package main
+
+import (
+	"errors"
+	"fmt"
+	"os"
+	"syscall"
+
+	"golang.org/x/sys/windows/registry"
+)
+
+// tagMenuName 右键菜单显示名
+const tagMenuName = "标签"
+
+// tagMenuRoots 写入的注册表父键:* 为所有文件,Directory 为所有文件夹。
+var tagMenuRoots = []string{"*", "Directory"}
+
+// tagMenuCommand 返回右键菜单命令:本程序 -tag "%1"(路径与 %1 各加引号,兼容空格)。
+func tagMenuCommand() string {
+	exe, err := os.Executable()
+	if err != nil {
+		return ""
+	}
+	return `"` + exe + `" -tag "%1"`
+}
+
+// ensureTagMenuRegistry 写入(或修复)资源管理器右键菜单注册表项。
+// 幂等:已存在则覆盖更新(命令路径变化时自动刷新),可安全重复调用。
+// 返回错误(如权限不足),由调用方决定是否提权重试;不中断应用启动。
+func ensureTagMenuRegistry() error {
+	command := tagMenuCommand()
+	if command == "" {
+		return fmt.Errorf("获取本程序路径失败")
+	}
+	for _, root := range tagMenuRoots {
+		if err := writeTagMenuKey(root, command); err != nil {
+			return err
+		}
+	}
+	return nil
+}
+
+// writeTagMenuKey 写入单个右键菜单键(root 为 "*" 或 "Directory")。
+func writeTagMenuKey(root, command string) error {
+	keyPath := root + `\shell\` + tagMenuName
+	k, _, err := registry.CreateKey(registry.CLASSES_ROOT, keyPath, registry.SET_VALUE)
+	if err != nil {
+		return fmt.Errorf("创建右键菜单键 %s 失败: %w", keyPath, err)
+	}
+	defer k.Close()
+
+	// 菜单显示名与图标(图标用本程序自身,便于用户识别)
+	if err := k.SetStringValue("", tagMenuName); err != nil {
+		return fmt.Errorf("设置菜单名 %s 失败: %w", keyPath, err)
+	}
+	if exe, _ := os.Executable(); exe != "" {
+		_ = k.SetStringValue("Icon", exe)
+	}
+
+	// command 子键:默认值即实际执行的命令行
+	cmdK, _, err := registry.CreateKey(k, "command", registry.SET_VALUE)
+	if err != nil {
+		return fmt.Errorf("创建 command 子键 %s 失败: %w", keyPath, err)
+	}
+	defer cmdK.Close()
+	if err := cmdK.SetStringValue("", command); err != nil {
+		return fmt.Errorf("写入命令 %s 失败: %w", keyPath, err)
+	}
+	return nil
+}
+
+// tagMenuNeedsWrite 判断是否需要写入注册表右键菜单。
+// 读取 HKEY_CLASSES_ROOT 不需要管理员权限,可安全探测:
+//   - 键不存在 → 需要写入(true)
+//   - 键存在但命令与当前 exe 不一致 → 需要覆盖(true,程序被移动/升级后刷新)
+//   - 键存在且命令一致 → 无需写入(false),避免每次启动都触发写/提权
+func tagMenuNeedsWrite() bool {
+	command := tagMenuCommand()
+	if command == "" {
+		return true
+	}
+	for _, root := range tagMenuRoots {
+		keyPath := root + `\shell\` + tagMenuName + `\command`
+		k, err := registry.OpenKey(registry.CLASSES_ROOT, keyPath, registry.QUERY_VALUE)
+		if err != nil {
+			return true // 键不存在
+		}
+		val, _, err := k.GetStringValue("")
+		k.Close()
+		if err != nil || val != command {
+			return true // 命令不一致或读取失败
+		}
+	}
+	return false
+}
+
+// tagMenuExists 判断注册表右键菜单「标签」键是否已存在(任一 root 下)。
+// 只读探测,不需要管理员权限;供关闭功能时判断是否需要删除/提权。
+func tagMenuExists() bool {
+	for _, root := range tagMenuRoots {
+		keyPath := root + `\shell\` + tagMenuName
+		k, err := registry.OpenKey(registry.CLASSES_ROOT, keyPath, registry.QUERY_VALUE)
+		if err == nil {
+			k.Close()
+			return true
+		}
+	}
+	return false
+}
+
+// removeTagMenuRegistry 删除资源管理器右键菜单「标签」注册表项(* 与 Directory)。
+// 与写入类似,删除 HKCR 下的键需要管理员权限;普通权限下 DeleteKey 返回
+// 「访问被拒绝」,由调用方(maybeRemoveTagMenu)检测后提权重试。
+func removeTagMenuRegistry() error {
+	var firstErr error
+	for _, root := range tagMenuRoots {
+		// 先删 command 子键,再删父键(registry.DeleteKey 只能删空键)
+		_ = registry.DeleteKey(registry.CLASSES_ROOT, root+`\shell\`+tagMenuName+`\command`)
+		if err := registry.DeleteKey(registry.CLASSES_ROOT, root+`\shell\`+tagMenuName); err != nil {
+			if !errors.Is(err, syscall.ERROR_FILE_NOT_FOUND) && firstErr == nil {
+				firstErr = fmt.Errorf("删除右键菜单键 %s 失败: %w", root+`\shell\`+tagMenuName, err)
+			}
+		}
+	}
+	return firstErr
+}

+ 177 - 0
tagservice.go

@@ -0,0 +1,177 @@
+// ============================================================================
+// tagservice.go — 文件标签(Tag)SQLite 存储(全平台:结构体 + Wails 绑定)
+//
+// 资源管理器文件/文件夹的「标签 + 备注」持久化:右键菜单注入「标签」项,
+// 弹输入窗口写入;鼠标悬停 1.0s 后查询并气泡显示。数据库路径由设置页
+// 「系统 → 标签数据库」配置(AppSettings.TagDBPath)。
+//
+// 数据库用 modernc.org/sqlite(纯 Go 驱动,无 CGO),实现细节在
+// tagservice_windows.go(Windows)与 tagservice_other.go(非 Windows 桩)。
+// ============================================================================
+package main
+
+import (
+	"database/sql"
+	"errors"
+	"log"
+	"path/filepath"
+	"strings"
+	"sync"
+	"time"
+)
+
+// TagInfo 一条文件标签:完整路径 + 标签 + 备注 + 更新时间。
+// 供前端设置页/标签管理 UI 与后端悬停提示使用。
+type TagInfo struct {
+	Path      string `json:"path"`      // 完整路径(已规范化:小写 + Clean)
+	Tag       string `json:"tag"`       // 标签(可空)
+	Note      string `json:"note"`      // 备注(可空)
+	UpdatedAt string `json:"updatedAt"` // 最近更新时间 YYYY-MM-DD HH:MM:SS
+}
+
+// tagService 包级单例:供右键菜单(contextmenu_windows.go)与悬停轮询
+// (explorerservice.go 的 pollLoop)访问,避免重复建连接。
+// 注意:Wails 绑定的 TagService 与内部逻辑解耦——各业务入口直接调包级函数,
+// 保证任何调用方(含非 Wails 线程)都能用。
+var (
+	tagSvc     *TagService
+	tagSvcOnce sync.Once
+)
+
+// getTagSvc 返回包级 TagService 单例(懒初始化,线程安全)。
+func getTagSvc() *TagService {
+	tagSvcOnce.Do(func() {
+		tagSvc = &TagService{}
+	})
+	return tagSvc
+}
+
+// TagService 文件标签服务(Wails 绑定)。
+//
+// Wails 会把公开方法(GetTag/SaveTag/DeleteTag/ListTags/SetTagDBPath)
+// 暴露给前端 bindings/TengTuToolbox/index.js。内部读写通过包级 openTagDB/
+// 数据库辅助函数完成,与右键菜单/悬停提示共用。
+type TagService struct{}
+
+// GetTag 查询指定路径的标签记录。
+// 返回 (记录, 是否存在, 错误):存在=false 表示数据库中无该路径记录(未打标签),
+// 供悬停提示区分「无标签(不弹气泡)」与「有标签(弹气泡)」。
+func (s *TagService) GetTag(path string) (TagInfo, bool, error) {
+	key := normalizeTagPath(path)
+	if key == "" {
+		return TagInfo{}, false, errors.New("路径为空")
+	}
+	db, err := openTagDB(tagDBPath())
+	if err != nil {
+		return TagInfo{}, false, err
+	}
+	defer db.Close()
+	var t TagInfo
+	t.Path = key
+	err = db.QueryRow(`SELECT tag, note, updated_at FROM file_tags WHERE path = ?`, key).
+		Scan(&t.Tag, &t.Note, &t.UpdatedAt)
+	if errors.Is(err, sql.ErrNoRows) {
+		return TagInfo{}, false, nil // 无记录:未打标签
+	}
+	if err != nil {
+		return TagInfo{}, false, err
+	}
+	return t, true, nil
+}
+
+// SaveTag 保存(UPSERT)指定路径的标签与备注。路径规范化后写入。
+func (s *TagService) SaveTag(path, tag, note string) error {
+	key := normalizeTagPath(path)
+	if key == "" {
+		return errors.New("路径为空")
+	}
+	db, err := openTagDB(tagDBPath())
+	if err != nil {
+		return err
+	}
+	defer db.Close()
+	now := time.Now().Format("2006-01-02 15:04:05")
+	_, err = db.Exec(`INSERT INTO file_tags (path, tag, note, updated_at) VALUES (?, ?, ?, ?)
+		ON CONFLICT(path) DO UPDATE SET tag = excluded.tag, note = excluded.note, updated_at = excluded.updated_at`,
+		key, strings.TrimSpace(tag), strings.TrimSpace(note), now)
+	return err
+}
+
+// DeleteTag 删除指定路径的标签记录(不存在时静默成功)。
+func (s *TagService) DeleteTag(path string) error {
+	key := normalizeTagPath(path)
+	if key == "" {
+		return nil
+	}
+	db, err := openTagDB(tagDBPath())
+	if err != nil {
+		return err
+	}
+	defer db.Close()
+	_, err = db.Exec(`DELETE FROM file_tags WHERE path = ?`, key)
+	return err
+}
+
+// ListTags 返回全部标签记录(按最近更新倒序),供设置页/标签管理查看。
+func (s *TagService) ListTags() ([]TagInfo, error) {
+	db, err := openTagDB(tagDBPath())
+	if err != nil {
+		return nil, err
+	}
+	defer db.Close()
+	rows, err := db.Query(`SELECT path, tag, note, updated_at FROM file_tags ORDER BY updated_at DESC`)
+	if err != nil {
+		return nil, err
+	}
+	defer rows.Close()
+	items := make([]TagInfo, 0, 32)
+	for rows.Next() {
+		var t TagInfo
+		if err := rows.Scan(&t.Path, &t.Tag, &t.Note, &t.UpdatedAt); err != nil {
+			return nil, err
+		}
+		items = append(items, t)
+	}
+	return items, rows.Err()
+}
+
+// SetTagDBPath 设置标签数据库路径并持久化到设置(供前端设置页调用,
+// 也可在保存设置时直接改 AppSettings.TagDBPath 走 SaveSettings)。
+func (s *TagService) SetTagDBPath(path string) error {
+	st := loadSettings()
+	st.TagDBPath = strings.TrimSpace(path)
+	return saveSettings(st)
+}
+
+// tagDBPath 返回当前设置的标签数据库路径(去空格)。
+func tagDBPath() string {
+	return strings.TrimSpace(loadSettings().TagDBPath)
+}
+
+// normalizeTagPath 规范化路径键:Windows 路径大小写不敏感,统一小写 + Clean,
+// 保证写入与查询命中一致(如 C:\A\b.txt 与 c:\a\B.TXT 视为同一条)。
+func normalizeTagPath(p string) string {
+	p = strings.TrimSpace(p)
+	if p == "" {
+		return ""
+	}
+	// 去掉可能的引号包裹(从资源管理器复制路径可能带引号)
+	p = strings.Trim(p, `"`)
+	p = filepath.Clean(p)
+	// 统一分隔符为反斜杠,避免 mixed separator
+	p = strings.ReplaceAll(p, "/", `\`)
+	// 盘符 + 路径整体小写(Windows 不区分大小写)
+	p = strings.ToLower(p)
+	// 去除尾部反斜杠(根目录除外)
+	for len(p) > 3 && strings.HasSuffix(p, `\`) {
+		p = strings.TrimSuffix(p, `\`)
+	}
+	return p
+}
+
+// logTagErr 统一日志标签相关错误(右键/悬停路径),避免各处重复 log 噪音。
+func logTagErr(op string, err error) {
+	if err != nil {
+		log.Printf("[tag] %s 失败: %v", op, err)
+	}
+}

+ 28 - 0
tagservice_other.go

@@ -0,0 +1,28 @@
+//go:build !windows
+
+// ============================================================================
+// tagservice_other.go — 文件标签存储(非 Windows 桩)
+//
+// 文件标签功能仅 Windows 使用(资源管理器右键菜单 + MSAA 悬停)。非 Windows
+// 平台提供空实现保证编译通过:openTagDB 返回错误,startTagContextHook 为空。
+// ============================================================================
+package main
+
+import (
+	"database/sql"
+	"errors"
+)
+
+// openTagDB 非 Windows 平台不可用,返回错误(功能仅限 Windows)。
+func openTagDB(dbPath string) (*sql.DB, error) {
+	return nil, errors.New("文件标签功能仅支持 Windows")
+}
+
+// startTagContextHook 非 Windows 平台为空实现。
+func startTagContextHook() {}
+
+// stopTagContextHook 非 Windows 平台为空实现。
+func stopTagContextHook() {}
+
+// setTagHookCachedPath 非 Windows 平台为空实现。
+func setTagHookCachedPath(path string) {}

+ 47 - 0
tagservice_windows.go

@@ -0,0 +1,47 @@
+//go:build windows
+
+// ============================================================================
+// tagservice_windows.go — 文件标签 SQLite 存储(Windows 实现)
+//
+// openTagDB 仿 recordservice.go 的 openRecordDB:纯 Go 驱动 modernc.org/sqlite,
+// 每次操作临时 Open+Close(不做连接池常驻),靠 WAL + busy_timeout 应对并发。
+// ============================================================================
+package main
+
+import (
+	"database/sql"
+	"errors"
+	"os"
+	"path/filepath"
+	"strings"
+
+	_ "modernc.org/sqlite" // 纯 Go SQLite 驱动(无需 CGO)
+)
+
+// openTagDB 打开(或创建)标签数据库并确保表结构存在。
+// dbPath 为空时返回错误,提示用户到设置页配置「系统→标签数据库路径」。
+func openTagDB(dbPath string) (*sql.DB, error) {
+	dbPath = strings.TrimSpace(dbPath)
+	if dbPath == "" {
+		return nil, errors.New("未设置「标签数据库路径」,请到设置页配置后再使用")
+	}
+	if err := os.MkdirAll(filepath.Dir(dbPath), 0o755); err != nil {
+		return nil, err
+	}
+	// DSN 加 _pragma 参数:WAL 提升并发读;foreign_keys 开启;busy_timeout 让写锁等待
+	dsn := "file:" + filepath.ToSlash(dbPath) + "?_pragma=journal_mode(WAL)&_pragma=foreign_keys(ON)&_pragma=busy_timeout(5000)"
+	db, err := sql.Open("sqlite", dsn)
+	if err != nil {
+		return nil, err
+	}
+	if _, err := db.Exec(`CREATE TABLE IF NOT EXISTS file_tags (
+		path       TEXT PRIMARY KEY,                                     -- 完整路径(规范化小写)
+		tag        TEXT NOT NULL DEFAULT '',                             -- 标签(可空)
+		note       TEXT NOT NULL DEFAULT '',                             -- 备注(可空)
+		updated_at TEXT NOT NULL DEFAULT (datetime('now','localtime'))   -- 最近更新
+	)`); err != nil {
+		db.Close()
+		return nil, err
+	}
+	return db, nil
+}

+ 40 - 0
tagtoggle.go

@@ -0,0 +1,40 @@
+// ============================================================================
+// tagtoggle.go — 按「启用标签功能」开关启停资源管理器标签功能(跨平台)
+//
+// 用户在「配置→系统」切换「启用标签功能」开关时,SaveSettings 保存后调用
+// applyTagMenuToggle:检测开关是否翻转,是则:
+//   启用:启动悬停监听、安装右键菜单钩子、写入(或修复)注册表右键菜单;
+//   关闭:停止悬停监听、卸载右键菜单钩子、删除注册表右键菜单(提权)。
+//
+// 各底层操作均已在各自平台文件实现(Windows / 非 Windows 桩),本文件只做
+// 状态编排,不依赖具体平台 API,保证跨平台编译。
+// ============================================================================
+package main
+
+import "log"
+
+// applyTagMenuToggle 按「启用标签功能」开关翻转启停标签功能。
+// prev 为保存前的旧配置,cur 为新配置;两者开关相同时不做任何操作。
+func applyTagMenuToggle(prev, cur AppSettings) {
+	if prev.TagMenuEnabled == cur.TagMenuEnabled {
+		return // 未翻转,无需处理
+	}
+	if cur.TagMenuEnabled {
+		// 重新启用:启动悬停监听、安装右键钩子、写入(或修复)注册表菜单
+		log.Printf("[tag] 启用标签功能")
+		if explorerSvc != nil {
+			explorerSvc.Start()
+		}
+		startTagContextHook()
+		maybeWriteTagMenu()
+	} else {
+		// 关闭:立即隐藏悬停标签气泡、停止悬停监听、卸载右键钩子、删除注册表菜单
+		log.Printf("[tag] 关闭标签功能")
+		stopTagAlert() // 若正显示标签气泡则立即关闭
+		if explorerSvc != nil {
+			explorerSvc.Stop()
+		}
+		stopTagContextHook()
+		maybeRemoveTagMenu()
+	}
+}

+ 0 - 391
update.md

@@ -1,391 +0,0 @@
-# 自动升级与回滚说明
-
-本项目基于 **Wails v3 内置升级框架**(`app.Updater`)实现自动升级,不自研下载 / 校验 / 替换管线。
-界面不使用内置升级弹窗,也不在主窗口里提供「更新」Tab;启动时自动检查新版本,
-结果只记日志,不弹任何提示。升级源配置仍在设置页「升级」分组中。
-
-代码位置:
-
-| 文件 | 职责 |
-|---|---|
-| `updater.go` | 初始化 `app.Updater`、换算更新源与鉴权头、升级状态记录与回滚 |
-| `main.go` | 启动时检查一次新版本;`--rollback` 子进程角色;自动回滚判定 |
-| `settingsservice.go` | 暴露给前端的绑定方法(检查 / 升级 / 跳过 / 回滚) |
-| `settings.go` | `GitLabConfig` 更新源配置、`SkippedUpdateVersion` |
-| `frontend/src/main.js` | 设置页分组标题(「升级」组) |
-| `frontend/index.html` | 设置页升级源四行(仓库地址 / 项目路径 / 令牌 / 分支) |
-
----
-
-## 1. 总体流程
-
-```
-启动 → initAppUpdater() 初始化内置 Updater(WindowNone,不弹内置窗口、无「更新」Tab)
-     → 2 秒后 checkUpdateNow() 调 app.Updater.Check(ctx)
-     → 有新版则自动下载并安装;结果只写日志,不弹任何提示
-
-新版本就绪
-  → PerformUpdate()
-  → markUpgradePending(exe)                # 先备份当前版本,记录待确认状态
-  → app.Updater.DownloadAndInstall(ctx)   # 下载 + 摘要/签名校验 + 暂存
-  → app.Updater.Restart(ctx)              # 派生内置 helper,替换二进制并重启
-
-重启后
-  → 新版本正常 → 启动存活宽限期到后 MarkUpdateOK() 清除待确认标记
-  → 新版本反复启动失败 → maybeAutoRollback() 达阈值自动回滚到备份
-```
-
-### 决策记录
-
-- **检查频率**:仅在启动时检查一次(`main.go` 启动协程),不做定时轮询,因此
-  `updater.Config.CheckInterval` 保持零值。
-- **界面**:无内置升级窗口、无「更新」Tab(已按用户要求取消),
-  `updater.Config.Window = updater.WindowNone`;升级由启动检查自动触发,界面不干预。
-- **回滚**:自动(新版本反复异常时自动回退上一版本),为本项目自研。
-
----
-
-## 2. 设置
-
-在应用「设置」页填写以下四项(对应 `settings.go` 的 `GitLabConfig`,持久化到
-`<用户配置目录>/TengTuToolbox/settings.json`):
-
-| 设置项 | 示例 | 说明 |
-|---|---|---|
-| 仓库地址 | `https://git.scwy.net` | 私有仓库根地址 |
-| 项目路径 | `ease/toolbox` | `owner/repo` 形式 |
-| 访问令牌 | `…` | Gogs 走 Basic 认证,GitLab 走 `PRIVATE-TOKEN` |
-| 版本清单分支 | `main` | 存放 `release/manifest.json` 的分支或 Tag |
-
-清单地址由 `resolveUpdateSource()` 换算为 Gogs / Gitea 的 raw 文件地址:
-
-```
-{base}/{owner}/{repo}/raw/{branch}/release/manifest.json
-
-# 例:
-https://git.scwy.net/ease/toolbox/raw/main/release/manifest.json
-```
-
-未填仓库地址或项目路径时,`initAppUpdater()` 直接返回「未配置更新源」错误,
-记录到日志,不弹任何提示。
-
----
-
-## 3. 发布新版本
-
-### 3.1 生成签名密钥(每个应用只需一次)
-
-```bash
-wails3 updater genkey
-# updater.key     私钥,务必保密(放 CI 密钥库),用于给每个版本签名
-# updater.key.pub 公钥,供客户端验签
-```
-
-私钥为 PKCS#8 PEM,公钥为 PKIX PEM。
-
-客户端加载公钥的查找顺序(`loadUpdaterPublicKey()`):
-
-1. `<用户配置目录>/TengTuToolbox/updater.key.pub`
-2. 可执行文件同目录的 `updater.key.pub`
-
-两个位置都不存在时不配公钥(仅做摘要校验)。
-
-### 3.2 生成清单
-
-```bash
-# 对每个版本执行:计算摘要 + 签名 + 生成清单,一次完成
-wails3 updater manifest -version 2.1.0 -channel stable \
-    -key updater.key -notes-file notes.md \
-    -url-prefix "https://git.scwy.net/ease/toolbox/raw/main/release" \
-    bin/updates/
-```
-
-- 产物为 `manifest.json`,连同打包好的发布文件一起提交到仓库的 `release/` 目录
-  (与设置页配置的 `release/manifest.json` 路径一致)。
-- `manifest` 接受文件或目录,自动跳过密钥、`.json`、校验和、notes 等旁挂文件。
-- 逐个文件流式计算 SHA-512;给了 `-key` 时用 Ed25519ph 对摘要签名。
-- 从文件名推断平台与架构(如 `MyApp-2.1.0-windows-amd64.zip`),识别 `macos` /
-  `win64` / `x86_64` / `aarch64` 等常见别名;推断不出的会打印警告,并按「匹配所有
-  平台」处理。
-- 省略 `-url-prefix` 时输出相对 URL,把清单和发布文件放在同一目录即可。
-
-### 3.3 发布前校验
-
-```bash
-wails3 updater verify -manifest manifest.json -publickey updater.key.pub
-```
-
-与客户端的校验逻辑一致,任一文件不匹配即退出非零,适合作为「构建 → 发布」之间的
-CI 门禁。
-
-服务端自行拼装清单时可用:
-
-```bash
-wails3 updater sign -key updater.key <files...>
-# 输出每个文件的 digest / signature 字段(JSON),便于合并进自己的清单文档
-```
-
-### 3.4 清单格式
-
-```json
-{
-  "schemaVersion": 1,
-  "version": "2.1.0",
-  "channel": "stable",
-  "name": "Summer Release",
-  "notes": "## 本次升级\n\n- 更快的启动速度\n- 新主题",
-  "publishedAt": "2026-07-03T10:00:00Z",
-  "artifacts": [
-    {
-      "url": "MyApp-2.1.0-windows-amd64.zip",
-      "platform": "windows",
-      "arch": "amd64",
-      "filetype": "zip",
-      "size": 9437184,
-      "digestAlgo": "sha512",
-      "digest": "base64 编码的摘要字节",
-      "signatureAlgo": "ed25519ph",
-      "signature": "base64 编码的签名字节"
-    }
-  ]
-}
-```
-
-顶层字段:
-
-| 字段 | 类型 | 必填 | 说明 |
-|---|---|---|---|
-| `schemaVersion` | int | 否 | 协议版本,省略视为 `1`;客户端拒绝高于自己理解的版本 |
-| `version` | string | **是** | SemVer 2.0.0,带不带 `v` 前缀均可 |
-| `channel` | string | 否 | 仅供参考;客户端配置了不同 channel 时视为无更新 |
-| `name` | string | 否 | 版本标题 |
-| `notes` | string | 否 | 升级内容,Markdown,在「更新」Tab 中渲染 |
-| `publishedAt` | string | 否 | RFC 3339 时间戳 |
-| `artifacts` | array | **是** | 每个可下载产物一条,顺序即发布方优先级 |
-| `metadata` | object | 否 | 自由键值,原样透传给应用 |
-
-产物字段:
-
-| 字段 | 类型 | 必填 | 说明 |
-|---|---|---|---|
-| `url` | string | **是** | 绝对地址,或相对清单 URL;仅支持 `http(s)` |
-| `platform` | string | 否 | Go `GOOS` 值(`macos`/`win` 等别名可识别);留空匹配所有平台 |
-| `arch` | string | 否 | Go `GOARCH` 值(`x86_64`/`aarch64` 等别名可识别);留空匹配所有架构 |
-| `filename` | string | 否 | 默认取 `url` 最后一段路径 |
-| `filetype` | string | 否 | 默认取文件名扩展名 |
-| `size` | int | 否 | 字节数,用于下载进度显示 |
-| `digestAlgo` / `digest` | string / base64 | 否 | `sha256` 或 `sha512` |
-| `signatureAlgo` / `signature` | string / base64 | 否 | `ed25519` / `ed25519ph` / `ecdsa-p256`;有 `signature` 就必须给 `signatureAlgo` |
-
-客户端按 `platform` + `arch` 取**第一条**匹配的产物。base64 有无 padding 均可接受。
-未知字段被忽略,服务端可自由扩展,扩展内容建议放进 `metadata`。
-
-### 3.5 升级判定与验签算法
-
-**版本比较**:一律由客户端按 SemVer 2.0.0 判定,清单 `version` 必须严格高于已安装版本
-才算升级。这让静态托管天然正确(清单永远描述最新版,旧客户端无事可做)。
-
-**签名算法**(`Config.PublicKey` 是唯一信任根,发布源无法自行替换密钥):
-
-| 算法 | 签名内容 | 备注 |
-|---|---|---|
-| `ed25519` | 产物的 SHA-256 摘要 | Sparkle EdDSA 使用 |
-| `ed25519ph` | 完整产物,经 Ed25519ph 预哈希(内部 SHA-512) | keygen.sh 使用 |
-| `ecdsa-p256` | 产物的 SHA-256 摘要 | raw `r∥s` 与 DER 签名都接受 |
-
-另有仅摘要模式(`DigestAlgo`:`sha256` / `sha512`)。
-
-**验签是「失败即关闭」的,务必注意**:
-
-- 配置了公钥 → 签名强制。产物若不带签名(只有摘要块,或完全没有 `Verification`)会被拒绝;
-  带了 `Signature` 却没配置公钥也会被拒绝。
-- 未配置公钥 → 只有摘要的产物可以安装;但**带签名的产物会被拒绝**。
-
-因此「是否放公钥」与「清单是否带签名」必须匹配,否则升级必然失败。摘要校验只防损坏,
-防篡改请用签名。
-
-### 3.6 产物格式
-
-| 格式 | 处理 | 说明 |
-|---|---|---|
-| 单个二进制(如 `myapp-linux-amd64`) | 直接使用 | Linux 常见 |
-| `.zip` | 原地解压 | **压缩包内必须恰好一个顶层条目**(单个二进制或 macOS `.app`) |
-| `.tar.gz` / `.tgz` | 原地解压 | 同样要求单一顶层条目 |
-
-顶层条目多于一个的压缩包会被拒绝。`.dmg` / `.pkg`(macOS)与 `.msi`(Windows)
-v1 不支持,macOS 请分发 `.app` 的 `.zip`。
-解压带 zip-slip 防护,拒绝逃逸根目录的符号链接,且限制总解压体积(2 GiB)与条目数(50000)。
-
----
-
-## 4. 内置框架事件与状态
-
-### 4.1 状态机(`updater.State`)
-
-| 状态 | 含义 |
-|---|---|
-| `unconfigured` | `Init` 之前 |
-| `idle` | `Init` 之后、任何检查之前 |
-| `checking` | 检查进行中 |
-| `up-to-date` | 已是最新 |
-| `available` | 发现新版本,尚未下载 |
-| `downloading` | 正在流式下载 |
-| `verifying` | 下载完成,正在校验摘要 / 签名 |
-| `installing` | 已校验的字节正被解压并写入暂存目录 |
-| `ready` | 已就绪,调用 `Restart` 生效 |
-| `error` | 前序某步失败 |
-
-### 4.2 事件
-
-Go 常量(`pkg/updater/events.go`)与前端订阅的事件名:
-
-| 常量 | 事件名 | 载荷 |
-|---|---|---|
-| `EventCheckStarted` | `wails:updater:check-started` | 无 |
-| `EventUpdateAvailable` | `wails:updater:update-available` | `*Release` |
-| `EventNoUpdate` | `wails:updater:no-update` | 无 |
-| `EventDownloadStarted` | `wails:updater:download-started` | 无 |
-| `EventDownloadProgress` | `wails:updater:download-progress` | `Progress`(`written` / `total` / `rate` / `provider`) |
-| `EventDownloadComplete` | `wails:updater:download-complete` | 无 |
-| `EventVerifying` | `wails:updater:verifying` | 无 |
-| `EventInstalling` | `wails:updater:installing` | 无 |
-| `EventUpdateReady` | `wails:updater:update-ready` | 无 |
-| `EventError` | `wails:updater:error` | `ErrorInfo`(`stage` / `message` / `provider`) |
-| `EventMeta` | `wails:updater:meta` | `Meta`(`currentVersion` / `skippedVersion`) |
-
-`update-available` 载荷中的 `Release` 字段即清单顶层字段:`version`、`notes`、
-`publishedAt` 等;本项目中该事件仅用于触发自动下载安装,不渲染界面。
-
-### 4.3 用户动作事件
-
-内置窗口 / 自定义界面通过下列事件回传用户意图:
-
-```
-wails:updater:user:install   安装
-wails:updater:user:skip      跳过此版本
-wails:updater:user:remind    稍后提醒
-wails:updater:user:cancel    取消
-wails:updater:user:restart   重启生效
-```
-
-本项目界面在 `WindowNone` 模式下无「更新」Tab,升级由启动检查自动触发、
-不依赖 `user:*` 事件;这些监听器在 `WindowNone` 下仍会被注册,供需要时复用。
-
-### 4.4 关于 `WindowNone`
-
-`updater.Config.Window = updater.WindowNone` 时:
-
-- 不打开任何内置窗口;
-- 用户动作监听器仍会注册;
-- **但 `meta` 状态重放不会自动发生**(重放依赖内置窗口的 `wails:updater:window:ready`,
-  而该窗口不存在)。本项目无「更新」Tab,不消费事件、也不做状态重放,因此不受影响。
-
----
-
-## 5. 自动回滚(自研)
-
-内置框架只负责替换与重启,不提供回滚。回滚由本项目实现,逻辑在 `updater.go`:
-
-| 函数 | 作用 |
-|---|---|
-| `markUpgradePending(exe)` | 升级重启前,把当前可执行文件**复制**到配置目录,并记录待确认状态 |
-| `MarkUpdateOK()` | 新版本确认可用后清除待确认标记 |
-| `maybeAutoRollback() bool` | 启动时判定是否达到自动回滚阈值 |
-| `rollbackNow()` | 派生回滚子进程完成替换 |
-| `runRollbackRole()` | 子进程角色:替换二进制并重启旧版 |
-| `RollbackUpdate()` | 手动回滚(日志触发;无「更新」Tab 按钮,供 CLI / 后续界面复用) |
-
-### 5.1 为什么备份要另存一份
-
-内置 helper 在成功替换并启动新版本后会 `os.RemoveAll(exe + ".bak")` 删除它自建的备份。
-因此回滚备份不依赖 `.bak`,而是由 `markUpgradePending()` 提前复制到用户配置目录:
-
-```
-<用户配置目录>/TengTuToolbox/prev-version.exe
-```
-
-该路径内置 helper 无法触及,可长期保留。备份查找顺序(`resolveBackup()`):
-
-1. 升级状态记录的 `PrevExe`
-2. `<用户配置目录>/TengTuToolbox/prev-version.exe`
-3. `exe + ".bak"`(内置 helper 自建的,可能已被删除)
-
-### 5.2 自动回滚策略
-
-状态文件 `<用户配置目录>/TengTuToolbox/update-state.json`:
-
-```json
-{
-  "currentVer": "1.0.0",
-  "prevExe": "C:\\Users\\...\\TengTuToolbox\\prev-version.exe",
-  "failCount": 2,
-  "pending": true,
-  "pendingSince": "2026-11-14T10:00:00+08:00"
-}
-```
-
-策略(`maybeAutoRollback()`,在 `main.go` 于初始化应用之前调用):
-
-- 每次启动,若处于「待确认」状态,则异常计数 +1;
-- 计数达到 `updateRollbackMax`(**3 次**)即自动回滚到备份版本并重启;
-- 仅在 `updateRollbackGrace`(**10 分钟**)宽限期内累计的异常启动才触发自动回滚;
-  宽限期过后只清除标记,保留备份供手动回滚。
-
-「正常」的判定:窗口创建成功后延迟调用一次 `MarkUpdateOK()`(`main.go` L379 附近),
-即进程存活到窗口就绪、未被判定为启动异常,就视为新版本可正常使用。
-
-因此「进程在启动后到窗口就绪前退出(崩溃 / 白屏循环)」才会累计异常计数。
-
-### 5.3 Windows 文件锁的处理
-
-Windows 上正在运行的 `.exe` 被系统文件锁占用,`os.Rename` 原地替换必失败。
-本项目采用与内置 helper 相同的「派生子进程自举」思路:
-
-1. `rollbackNow()` 把备份内容写入主程序同目录的 `exe + ".restore"`;
-2. 派生**当前程序**的回滚子进程:`exe --rollback <备份副本> <主程序路径>`
-   (派生当前版本而非旧版副本,因为旧版二进制不认识 `--rollback` 参数);
-   使用 `syscall.SysProcAttr{HideWindow: true}` 隐藏控制台窗口;
-3. 主程序立即 `os.Exit(0)`,让出文件锁;
-4. 子进程(`runRollbackRole()`)等待 1.5 秒后删除主程序并写回备份内容,再启动旧版,
-   最后清理暂存文件。
-
-`main.go` 在初始化应用之前先判断 `--rollback`:命中则进入 `runRollbackRole()` 并直接返回,
-不再启动应用。
-
----
-
-## 6. 认证头的注意事项
-
-`endpoint` provider 的 `Headers` 会用于清单请求;**产物下载请求只在以下情况下复用这些头**:
-
-- 产物 URL 与清单同主机,且
-- 没有发生 `https` → `http` 降级。
-
-任何跨域或降级跳转都会剥离 `Authorization` 头(避免凭据泄露到 CDN 或对象存储,
-也不会以明文传输)。因此产物 URL 建议与清单同源、同为 `https`,否则私有仓库的
-产物下载会因 401 失败。
-
-本项目按仓库类型选择认证头(`resolveUpdateSource()`):
-
-- 地址含 `gitlab` → `PRIVATE-TOKEN: <令牌>`
-- 其它(Gogs / Gitea)→ `Authorization: Basic base64(<令牌>:)`(令牌置于用户名位,密码留空)
-
----
-
-## 7. 待办与遗留风险
-
-- **无法本地编译验证**:本轮改动未经 `go build` / `wails3 build` 验证,请先构建确认。
-- **`app.Updater` 实例化**:`initAppUpdater()` 与 `checkUpdateNow()` 均有 `app.Updater == nil`
-  判空,若框架未提供则返回错误而非 panic;升级功能此时整体不可用,需留意日志
-  「内置升级框架初始化失败」。
-- **`PublicKey` 与清单签名必须匹配**:见 3.5,配错会「失败即关闭」导致升级永远不成功。
-- **备份完整性**:回滚只校验文件可读写,不对备份做签名校验;备份目录被篡改时会自动
-  回滚到被篡改的版本。如需要,可为 `prev-version.exe` 补摘要校验。
-- **宽限期 10 分钟内累计 3 次异常即回滚**:若用户在此期间反复手动重启新版本,
-  可能被误判为异常并触发回滚。可按需调大 `updateRollbackMax` 或 `updateRollbackGrace`。
-- **「升级」设置项在「系统」分组之后**:设置页的升级源四行(仓库地址 / 项目路径 /
-  令牌 / 分支)被归入独立的「升级」组,位于「系统」组之后;若未显式配置,
-  `initAppUpdater()` 会记「未配置更新源」日志。
-- **`MarkUpdateOK()` 是「启动即视为正常」的近似判定**:窗口就绪后即清除待确认标记,
-  若新版本在窗口创建之后才崩溃(如异步初始化失败)则不会被判定为异常。可按需把
-  该调用移到「窗口创建 + 若干秒存活」之后再执行。

+ 62 - 25
updater.go

@@ -11,11 +11,9 @@ package main
 
 import (
 	"context"
-	"encoding/base64"
 	"encoding/json"
 	"fmt"
 	"log"
-	"net/url"
 	"os"
 	"os/exec"
 	"path/filepath"
@@ -31,7 +29,6 @@ import (
 const (
 	updateKeyFile       = "updater.key.pub"  // 发布方公钥(可选,配了才做签名验签)
 	updateStateFile     = "update-state.json" // 升级状态(回滚依据)
-	updateManifestPath  = "release/manifest.json"
 	updateRollbackMax   = 3                    // 新版本异常启动次数达到该值即自动回滚
 	updateRollbackGrace = 10 * time.Minute     // 回滚宽限期:仅在该时间内累计的异常启动会触发自动回滚
 )
@@ -334,33 +331,21 @@ func maybeAutoRollback() bool {
 // ---------------------------------------------------------------------------
 
 // resolveUpdateSource 按设置换算更新清单地址与鉴权头。
-// 兼容两种私有仓库:GitLab(PRIVATE-TOKEN 头)与 Gogs / Gitea(Basic 头,令牌放用户名位)。
+// 静态站方案:清单固定放在 {baseUrl}/manifest.json,无需鉴权。
+// baseUrl 复用 GitLabConfig.BaseURL(如 https://i.scwy.net/down/toolsbox),
+// project / branch / token 字段不再参与,保留以兼容旧配置。
 func resolveUpdateSource() (manifestURL, header, value string) {
-	cfg := loadSettings().GitLab
-	base := strings.TrimRight(strings.TrimSpace(cfg.BaseURL), "/")
-	project := strings.Trim(strings.TrimSpace(cfg.ProjectPath), "/")
-	branch := strings.TrimSpace(cfg.Branch)
-	if branch == "" {
-		branch = "main"
-	}
-	token := strings.TrimSpace(cfg.PrivateToken)
-	if base == "" || project == "" {
+	base := strings.TrimRight(strings.TrimSpace(loadSettings().GitLab.BaseURL), "/")
+	if base == "" {
 		return "", "", ""
 	}
-	// Gogs / Gitea 的 raw 文件地址:{base}/{owner}/{repo}/raw/{branch}/{path}
-	manifestURL = fmt.Sprintf("%s/%s/raw/%s/%s", base, project, url.PathEscape(branch), updateManifestPath)
-	if token == "" {
-		return manifestURL, "", ""
-	}
-	// Gogs 认 Basic 头(令牌置于用户名,密码留空);GitLab 认 PRIVATE-TOKEN
-	if strings.Contains(strings.ToLower(base), "gitlab") {
-		return manifestURL, "PRIVATE-TOKEN", token
-	}
-	return manifestURL, "Authorization", "Basic " + base64.StdEncoding.EncodeToString([]byte(token+":"))
+	manifestURL = base + "/manifest.json"
+	return manifestURL, "", ""
 }
 
 // loadUpdaterPublicKey 读取发布方公钥(可选)。
-// 放在用户配置目录或可执行文件旁;不存在时仅校验摘要,不做签名验签。
+// 依次查找:用户配置目录、可执行文件旁、当前工作目录(兼容 go run / wails dev 开发场景)。
+// 不存在时仅校验摘要,不做签名验签。
 func loadUpdaterPublicKey() []byte {
 	candidates := []string{
 		filepath.Join(userConfigDir(), updateKeyFile),
@@ -368,6 +353,9 @@ func loadUpdaterPublicKey() []byte {
 	if exe, err := currentExePath(); err == nil {
 		candidates = append(candidates, filepath.Join(filepath.Dir(exe), updateKeyFile))
 	}
+	if cwd, err := os.Getwd(); err == nil {
+		candidates = append(candidates, filepath.Join(cwd, updateKeyFile))
+	}
 	for _, p := range candidates {
 		if data, err := os.ReadFile(p); err == nil && len(strings.TrimSpace(string(data))) > 0 {
 			log.Printf("升级签名公钥已加载:%s", p)
@@ -403,7 +391,7 @@ func initAppUpdater() error {
 	}
 	manifest, header, value := resolveUpdateSource()
 	if manifest == "" {
-		return fmt.Errorf("未配置更新源:请到设置页填写仓库地址与项目路径")
+		return fmt.Errorf("未配置更新站地址:请在配置文件 settings.json 的 gitLab.baseUrl 填写(如 https://i.scwy.net/down/toolsbox)")
 	}
 	var headers map[string]string
 	if header != "" {
@@ -440,6 +428,55 @@ func checkUpdateNow() error {
 	return err
 }
 
+// PromptUpdateIfAvailable 启动时检查一次更新;若发现新版本,弹出原生对话框
+// 提供三个选择:立即升级 / 暂时跳过(下次启动再提醒)/ 此版不再提示(持久化跳过)。
+// 返回 found=true 表示发现新版本(已弹窗并等待用户选择);已最新返回 (false, nil)。
+func PromptUpdateIfAvailable() (found bool, err error) {
+	if app == nil || app.Updater == nil {
+		return false, fmt.Errorf("升级框架未就绪")
+	}
+	ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
+	defer cancel()
+	rel, err := app.Updater.Check(ctx)
+	if err != nil {
+		return false, err
+	}
+	if rel == nil {
+		return false, nil // 已是最新,不打扰
+	}
+	version := rel.Version
+
+	msg := fmt.Sprintf("发现新版本 v%s,当前为 v%s。", version, AppVersion)
+	if rel.Notes != "" {
+		msg += "\n\n更新说明:\n" + rel.Notes
+	}
+
+	dlg := app.Dialog.Question().
+		SetTitle("发现新版本").
+		SetMessage(msg).
+		AttachToWindow(mainWindow)
+
+	upgrade := dlg.AddButton("立即升级").SetAsDefault()
+	dlg.AddButton("暂时跳过") // 仅关闭对话框,下次启动重新检查提醒
+	skip := dlg.AddButton("此版不再提示")
+
+	upgrade.OnClick(func() {
+		go func() {
+			if err := PerformUpdate(); err != nil {
+				log.Printf("升级失败:%v", err)
+			}
+		}()
+	})
+	skip.OnClick(func() {
+		// 持久化跳过该版本,之后启动视为无更新,直到用户手动清除
+		if err := SkipUpdate(version); err != nil {
+			log.Printf("记录跳过版本失败:%v", err)
+		}
+	})
+	dlg.Show()
+	return true, nil
+}
+
 // CheckUpdateState 返回内置 Updater 当前状态,供「更新」Tab 展示
 func CheckUpdateState() map[string]interface{} {
 	st := updater.StateUpToDate

+ 50 - 10
webservice.go

@@ -27,6 +27,7 @@ type WebServiceInfo struct {
 	Running     bool   `json:"running"`     // 是否运行中
 	Dir         string `json:"dir"`         // 服务目录
 	URL         string `json:"url"`         // 访问地址 http://127.0.0.1:port/
+	Port        int    `json:"port"`        // 监听端口
 	IndexName   string `json:"indexName"`   // 实际用作默认页的文件(index.html / readme.md / 空)
 	StartedAt   string `json:"startedAt"`   // 启动时间
 	Error       string `json:"error"`       // 最近一次错误
@@ -39,6 +40,7 @@ type webService struct {
 	server  *http.Server
 	dir     string
 	url     string
+	port    int // 监听端口
 	index   string // 默认页文件名
 	started time.Time
 	conns   int64
@@ -46,6 +48,14 @@ type webService struct {
 
 var webSrv = &webService{}
 
+// websvcEmit 推送一条日志给前端信息框。kind: req / info。
+func websvcEmit(kind, line string) {
+	if app == nil {
+		return
+	}
+	app.Event.Emit("websvc:log", map[string]string{"kind": kind, "line": line})
+}
+
 // pickWebDir 弹出目录选择对话框,返回用户选中的目录(取消则返回空串)。
 // 使用 Wails 全局 app 的 Dialog(绑定到主窗口)。
 func pickWebDir() (string, error) {
@@ -103,12 +113,15 @@ func webHandler(dir, indexName string) http.Handler {
 	return http.FileServer(http.Dir(dir))
 }
 
-// StartWebService 启动静态文件服务,监听 127.0.0.1:0 随机端口。
+// StartWebService 启动静态文件服务,监听 127.0.0.1:port(port 可指定,0 表示随机端口)。
 // 若已运行则先停止旧实例。indexName 为空时自动探测默认页。
-func StartWebService(dir string) (WebServiceInfo, error) {
+func StartWebService(dir string, port int) (WebServiceInfo, error) {
 	if strings.TrimSpace(dir) == "" {
 		return WebServiceInfo{}, errors.New("目录不能为空")
 	}
+	if port < 0 || port > 65535 {
+		return WebServiceInfo{}, fmt.Errorf("端口无效: %d(范围 1-65535)", port)
+	}
 	st, err := os.Stat(dir)
 	if err != nil || !st.IsDir() {
 		return WebServiceInfo{}, fmt.Errorf("目录不存在或不是文件夹: %s", dir)
@@ -118,19 +131,25 @@ func StartWebService(dir string) (WebServiceInfo, error) {
 	// 先停止已有实例(幂等)
 	stopWebService()
 
-	ln, err := net.Listen("tcp", "127.0.0.1:0")
+	addr := fmt.Sprintf("127.0.0.1:%d", port)
+	ln, err := net.Listen("tcp", addr)
 	if err != nil {
-		return WebServiceInfo{}, fmt.Errorf("监听端口失败: %w", err)
+		return WebServiceInfo{}, fmt.Errorf("监听端口 %d 失败(可能被占用): %w", port, err)
 	}
-	port := ln.Addr().(*net.TCPAddr).Port
+	actualPort := ln.Addr().(*net.TCPAddr).Port
 
 	mux := http.NewServeMux()
 	handler := webHandler(dir, indexName)
 	mux.Handle("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		start := time.Now()
+		sw := &statusWriter{ResponseWriter: w, status: http.StatusOK}
+		handler.ServeHTTP(sw, r)
 		webSrv.mu.Lock()
 		webSrv.conns++
 		webSrv.mu.Unlock()
-		handler.ServeHTTP(w, r)
+		websvcEmit("req", fmt.Sprintf("%s %s %s %s %s %d %s",
+			time.Now().Format("15:04:05"),
+			r.Method, r.URL.Path, r.RemoteAddr, r.Proto, sw.status, time.Since(start).Round(time.Millisecond)))
 	}))
 
 	srv := &http.Server{Handler: mux}
@@ -138,7 +157,8 @@ func StartWebService(dir string) (WebServiceInfo, error) {
 	webSrv.mu.Lock()
 	webSrv.server = srv
 	webSrv.dir = dir
-	webSrv.url = fmt.Sprintf("http://127.0.0.1:%d/", port)
+	webSrv.port = actualPort
+	webSrv.url = fmt.Sprintf("http://127.0.0.1:%d/", actualPort)
 	webSrv.index = indexName
 	webSrv.started = time.Now()
 	webSrv.conns = 0
@@ -148,12 +168,27 @@ func StartWebService(dir string) (WebServiceInfo, error) {
 		_ = srv.Serve(ln) // 阻塞直到 Shutdown;返回 http.ErrServerClosed 属正常
 	}()
 
+	websvcEmit("info", fmt.Sprintf("%s Web 服务已启动: http://127.0.0.1:%d/ (目录: %s)",
+		time.Now().Format("15:04:05"), actualPort, dir))
+
 	return WebServiceInfo{
-		Running: true, Dir: dir, URL: webSrv.url, IndexName: indexName,
+		Running: true, Dir: dir, URL: webSrv.url, Port: actualPort, IndexName: indexName,
 		StartedAt: webSrv.started.Format("2006-01-02 15:04:05"),
 	}, nil
 }
 
+// statusWriter 包装 ResponseWriter 以捕获响应状态码(用于请求日志)。
+type statusWriter struct {
+	http.ResponseWriter
+	status int
+}
+
+// WriteHeader 记录写入的状态码。
+func (w *statusWriter) WriteHeader(code int) {
+	w.status = code
+	w.ResponseWriter.WriteHeader(code)
+}
+
 // StopWebService 停止当前静态文件服务(未运行则无副作用)。
 func StopWebService() {
 	stopWebService()
@@ -161,7 +196,7 @@ func StopWebService() {
 
 func stopWebService() {
 	webSrv.mu.Lock()
-	defer webSrv.mu.Unlock()
+	wasRunning := webSrv.server != nil
 	if webSrv.server != nil {
 		ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
 		_ = webSrv.server.Shutdown(ctx)
@@ -170,6 +205,11 @@ func stopWebService() {
 		webSrv.url = ""
 		webSrv.dir = ""
 		webSrv.index = ""
+		webSrv.port = 0
+	}
+	webSrv.mu.Unlock()
+	if wasRunning {
+		websvcEmit("info", fmt.Sprintf("%s Web 服务已停止", time.Now().Format("15:04:05")))
 	}
 }
 
@@ -179,7 +219,7 @@ func WebServiceStatus() WebServiceInfo {
 	defer webSrv.mu.Unlock()
 	info := WebServiceInfo{
 		Running: webSrv.server != nil, Dir: webSrv.dir, URL: webSrv.url,
-		IndexName: webSrv.index, Connections: webSrv.conns,
+		Port: webSrv.port, IndexName: webSrv.index, Connections: webSrv.conns,
 	}
 	if !webSrv.started.IsZero() {
 		info.StartedAt = webSrv.started.Format("2006-01-02 15:04:05")