Skip to content

WorkBuddy、CodeBuddy 桌面端增强助手:签到猫猫旅行成长计划查询、多账号独立备份、点切即用;免打扰模式让 AI 无人值守跑长任务;跨账号会话迁移、异常中断自动续接;暂存/快捷提示词;毛玻璃主题与更多实用功能。

支持 Windows,主题样式优化

[email protected]0553b839b3ed
diff --git a/.github/workflows/build-win.yml b/.github/workflows/build-win.yml
new file mode 100644
index 0000000..d932067
--- /dev/null
+++ b/.github/workflows/build-win.yml
@@ -0,0 +1,99 @@
+name: Build & Verify Windows Setup
+
+# 触发方式(任选其一都会跑这套打包+验证):
+# - 推 v* 标签(正式发版)
+# - 手动触发(workflow_dispatch,可传版本号)
+# - 推 master/main(可选,防回归)
+on:
+ push:
+ tags:
+ - 'v*'
+ workflow_dispatch:
+ inputs:
+ version:
+ description: '版本号(如 1.0.4),留空则从代码读取'
+ required: false
+ default: ''
+
+permissions:
+ contents: write
+
+jobs:
+ build-and-verify:
+ name: Build zip + Setup.exe + verify
+ runs-on: windows-latest # IExpress 是真 GUI,必须在 Windows runner 上打包
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v4
+
+ - name: 校验 CRLF(cmd 必须 CRLF,否则 cmd.exe 解析括号块会失败)
+ shell: bash
+ run: |
+ for f in scripts/*.cmd; do
+ if ! grep -q $'\r' "$f"; then
+ echo "::error::$f 不是 CRLF,无法在 Windows 使用,请转换"
+ exit 1
+ fi
+ done
+ echo "所有 .cmd 均为 CRLF ✓"
+
+ - name: 解析版本号
+ id: ver
+ shell: bash
+ run: |
+ VER="${{ github.event.inputs.version }}"
+ if [ -z "$VER" ]; then
+ VER=$(grep -o "DAEMON_VERSION = '[^']*'" scripts/daemon.js | head -1 | cut -d"'" -f2)
+ fi
+ echo "version=$VER" >> "$GITHUB_OUTPUT"
+ echo "检测到版本: $VER"
+
+ - name: 打包内置资产 builtin(build-win-zip.sh 需要)
+ shell: bash
+ run: |
+ SRC="WorkDaddy.app/Contents/Resources/scripts/builtin"
+ if [ -d "$SRC" ]; then
+ cp -R "$SRC/." scripts/builtin/
+ echo "已复制 builtin 资产"
+ else
+ echo "警告: 未找到 builtin,面板将无官方壁纸(不影响安装功能)"
+ fi
+
+ - name: 生成 Windows zip
+ shell: bash
+ run: bash scripts/build-win-zip.sh
+
+ - name: 生成 Setup.exe(IExpress 自解压安装包)
+ shell: cmd
+ run: |
+ call scripts\make-setup.cmd
+
+ - name: 列出产物
+ shell: bash
+ run: ls -lh release/
+
+ - name: 产物完整性自检(verify-win.cmd,纯只读)
+ shell: cmd
+ run: |
+ call scripts\verify-win.cmd
+
+ - name: 上传产物(zip + Setup.exe)
+ uses: actions/upload-artifact@v4
+ with:
+ name: workdaddy-win64
+ path: |
+ release/WorkDaddy-*-win64.zip
+ release/WorkDaddy-Setup.exe
+ release/WorkDaddy-Setup-*.exe
+
+ # ---- 只有打 tag 时才顺手挂到 GitHub Release ----
+ - name: 发布到 GitHub Release
+ if: startsWith(github.ref, 'refs/tags/v')
+ uses: softprops/action-gh-release@v2
+ with:
+ files: |
+ release/WorkDaddy-*-win64.zip
+ release/WorkDaddy-Setup.exe
+ release/WorkDaddy-Setup-*.exe
+ release/*.dmg
+ generate_release_notes: true
diff --git a/README.md b/README.md
index b567b50..3ecb148 100644
--- a/README.md
+++ b/README.md
@@ -7,7 +7,7 @@
零侵入、零重签名——只把界面组件注入到正在运行的 WorkBuddy 渲染进程里。
![License](https://img.shields.io/badge/license-AGPL--3.0-blueviolet)
-![Platform](https://img.shields.io/badge/platform-macOS%2011%2B-lightgrey)
+![Platform](https://img.shields.io/badge/platform-macOS%2011%2B%20%7C%20Windows%2010%2F11-lightgrey)
![Node](https://img.shields.io/badge/node-%E2%89%A518-green)
---
@@ -33,7 +33,7 @@
## 安装
-### macOS(已支持)
+### macOS
1. 在 [Releases](../../releases) 下载最新 `WorkDaddy-x.y.z.dmg`
2. 打开 dmg,把 `WorkDaddy.app` 拖进 **应用程序** 文件夹
@@ -46,12 +46,13 @@
4. 双击 `WorkDaddy.app` 启动:它会自带守护进程并把组件注入到 WorkBuddy 右下角
5. 看到机器人按钮?**搞定**。
-> 守护进程会通过 launchd 登录自启,崩溃自动拉起;完全无感。
+### Windows
-### Windows(敬请期待)
+1. 在 [Releases](../../releases) 下载最新 `WorkDaddy-x.y.z-win64.zip`
+2. **解压到桌面以外的文件夹,双击一键安装脚本 `Install-WorkDaddy.cmd`**:
+3. 以后只需**双击桌面 WorkDaddy 图标** 即可手动启动
+4. 回到 WorkBuddy 看到右下角机器人按钮即成功;
-> **马上上线。** 当前所有功能基于 Electron 渲染进程 CDP 注入,跨平台移植中。
-> 想第一时间知道?[Watch](../../watchers) 本仓库的 Releases。
### 从源码运行(开发者)
@@ -148,5 +149,9 @@ WorkBuddy 右下角的机器人按钮 → 弹出面板 → 选你要的操作:
## 兼容性说明
- macOS 11+(Big Sur 起),Apple Silicon 与 Intel 均支持
+- Windows 10/11 64 位(需 WorkBuddy Windows 版;node 使用 WorkBuddy 自带托管运行时或 PATH 中的 Node 18+)
- WorkBuddy 桌面端 0.6.6+(daemon 与 inject 同步升级后覆盖更新)
-- Windows 端正在开发,**敬请期待,马上上线**
+
+## 社区支持
+
+[Linux](https://linux.do/)
\ No newline at end of file
diff --git a/scripts/Install-WorkDaddy.cmd b/scripts/Install-WorkDaddy.cmd
new file mode 100644
index 0000000..f48e2f7
--- /dev/null
+++ b/scripts/Install-WorkDaddy.cmd
@@ -0,0 +1,48 @@
+@echo off
+rem ============================================================
+rem WorkDaddy 一键安装(zip 解压后的顶层入口,双击运行)
+rem 作用:复制到 %LOCALAPPDATA%\Programs\WorkDaddy → 注册开机自启
+rem → 创建桌面快捷方式 → 启动守护进程并以调试模式拉起 WorkBuddy
+rem 提示:本插件为 WorkBuddy 的增强工具,需先安装 WorkBuddy 桌面端。
+rem 运行所需的 Node 运行时由 WorkBuddy 自带托管(.workbuddy\binaries\node),
+rem 无需自行安装 Node.js。
+rem
+rem 设计:一律用"%~dp0"绝对路径定位,绝不做 cd 后相对调用——
+rem 这样无论从哪个目录双击、即便目录里残留 scripts\scripts 嵌套,
+rem 也只认"与本文件同级的 scripts\install-win.ps1",杜绝路径歧义。
+rem ============================================================
+setlocal
+chcp 65001 >nul
+
+rem ---------- 0) 找到真正的包根(向上穿透 scripts 嵌套残留) ----------
+set "PKGROOT=%~dp0"
+:locate_root
+if exist "%PKGROOT%scripts\install-win.ps1" goto root_ok
+rem 若本级没有而上一级有,说明点在 scripts\... 残留里,向上退一级
+if exist "%PKGROOT%..\scripts\install-win.ps1" (
+ for %%R in ("%PKGROOT%..") do set "PKGROOT=%%~fR\"
+ goto locate_root
+)
+goto root_missing
+
+:root_ok
+echo 已定位包根:%PKGROOT%
+
+rem ---------- 1) 存在性校验(绝对路径,不依赖 cd) ----------
+if not exist "%PKGROOT%scripts\install-win.cmd" goto root_missing
+if not exist "%PKGROOT%scripts\install-win.ps1" goto root_missing
+if not exist "%PKGROOT%scripts\daemon.js" goto root_missing
+
+rem ---------- 2) 执行安装(以包根绝对路径调用,避免 install-win.cmd 里 %~dp0 偏掉) ----------
+call "%PKGROOT%scripts\install-win.cmd"
+goto :eof
+
+:root_missing
+echo.
+echo 错误:找不到完整的安装文件(scripts\install-win.ps1 / daemon.js)。
+echo 请确认是从 zip 解压目录的顶层双击本文件;若目录里有 scripts\scripts
+echo 之类的嵌套残留,请删除整个解压文件夹后用原 zip 重新解压。
+echo.
+echo 顶层入口应为:Install-WorkDaddy.cmd 与 scripts\ 同级。
+pause
+exit /b 1
diff --git a/scripts/Start-WorkDaddy.cmd b/scripts/Start-WorkDaddy.cmd
new file mode 100644
index 0000000..073d258
--- /dev/null
+++ b/scripts/Start-WorkDaddy.cmd
@@ -0,0 +1,15 @@
+@echo off
+rem ============================================================
+rem WorkDaddy 一键启动(zip 解压后的顶层入口,双击运行)
+rem 作用:确保守护进程运行 + 以调试模式拉起/重启 WorkBuddy + 注入组件。
+rem 已在安装后日常只需双击桌面「WorkDaddy」图标。
+rem 设计:绝对路径定位 scripts\launcher.cmd,无相对路径歧义。
+rem ============================================================
+setlocal
+chcp 65001 >nul
+if not exist "%~dp0scripts\launcher.cmd" (
+ echo 错误:找不到 %~dp0scripts\launcher.cmd,请确认在解压后的 zip 根目录运行。
+ pause
+ exit /b 1
+)
+call "%~dp0scripts\launcher.cmd"
diff --git a/scripts/apply-update.ps1 b/scripts/apply-update.ps1
new file mode 100644
index 0000000..1262da9
--- /dev/null
+++ b/scripts/apply-update.ps1
@@ -0,0 +1,95 @@
+# WorkDaddy Windows 自动更新替换脚本(apply-update.sh 的 Windows 对应物)
+# 由 daemon.js applyUpdate() 调用,参数:
+# $1 更新包 zip 路径(update 目录里下载好的 WorkDaddy-<ver>.zip)
+# $2 安装目录(默认 %LOCALAPPDATA%\Programs\WorkDaddy)
+# $3 本地 API 端口(等待旧 daemon 退出用,默认 47832)
+# 流程:等端口释放 → 杀 watchdog/daemon → 备份旧目录(.old 可回滚) → 解压替换 → 拉起
+# 注意:Windows 运行中的 exe/js 有文件锁,必须先杀进程再替换。
+param(
+ [Parameter(Mandatory = $true)][string]$SrcZip,
+ [string]$AppDir = (Join-Path $env:LOCALAPPDATA 'Programs\WorkDaddy'),
+ [string]$Port = '47832'
+)
+
+$ErrorActionPreference = 'Continue'
+$DataDir = Join-Path $env:APPDATA 'WorkDaddy'
+$LogDir = Join-Path $DataDir 'update'
+New-Item -ItemType Directory -Force -Path $LogDir | Out-Null
+$Log = Join-Path $LogDir 'apply.log'
+Start-Transcript -Path $Log -Append -Force
+
+Write-Host "[apply] $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') start src=$SrcZip dst=$AppDir"
+
+# 1) 杀 watchdog(会连带终止 daemon;PID 文件在数据目录)
+$pidFile = Join-Path $DataDir 'watchdog.pid'
+if (Test-Path $pidFile) {
+ try {
+ $wpid = [int]((Get-Content $pidFile -Raw).Trim())
+ if ($wpid -gt 0) { taskkill /F /T /PID $wpid 2>$null | Out-Null }
+ } catch {}
+}
+
+# 2) 兜底:按 API 端口杀残留进程
+$waitSec = 0
+while ($waitSec -lt 30) {
+ $listening = netstat -ano | Select-String (":$Port\s") | Select-String 'LISTENING'
+ if (-not $listening) { break }
+ # 尝试优雅等待
+ Start-Sleep -Seconds 1
+ $waitSec++
+}
+foreach ($line in (netstat -ano | Select-String (":$Port\s") | Select-String 'LISTENING')) {
+ $parts = ($line.ToString().Trim() -split '\s+')
+ $pid2 = $parts[$parts.Count - 1]
+ if ($pid2 -match '^\d+$') { taskkill /F /T /PID $pid2 2>$null | Out-Null }
+}
+Start-Sleep -Seconds 1
+
+# 3) 备份旧目录(回滚:move AppDir.old AppDir)
+$oldDir = $AppDir + '.old'
+if (Test-Path $oldDir) { Remove-Item -Recurse -Force $oldDir -ErrorAction SilentlyContinue }
+if (Test-Path $AppDir) { Move-Item -Force $AppDir $oldDir -ErrorAction SilentlyContinue }
+
+# 4) 解压新版到临时目录,再移动到位(Expand-Archive 无法原地覆盖已存在目录)
+$tmpDir = Join-Path $env:TEMP ("workdaddy-update-" + [guid]::NewGuid().ToString('N'))
+New-Item -ItemType Directory -Force -Path $tmpDir | Out-Null
+try {
+ Expand-Archive -Path $SrcZip -DestinationPath $tmpDir -Force
+} catch {
+ Write-Host "[apply] 解压失败: $($_.Exception.Message)"
+ if (Test-Path $oldDir) { Move-Item -Force $oldDir $AppDir -ErrorAction SilentlyContinue } # 回滚
+ Stop-Transcript
+ exit 1
+}
+
+# 定位 zip 内的应用根:顶层含 scripts\daemon.js(打包结构)→ 顶层即根;个别情况顶层直接是文件
+$srcRoot = $tmpDir
+if (-not (Test-Path (Join-Path $tmpDir 'scripts\daemon.js')) -and -not (Test-Path (Join-Path $tmpDir 'daemon.js'))) {
+ $hit = Get-ChildItem $tmpDir -Recurse -Filter 'daemon.js' -ErrorAction SilentlyContinue | Select-Object -First 1
+ if ($hit) { $srcRoot = Split-Path $hit.FullName -Parent }
+}
+New-Item -ItemType Directory -Force -Path $AppDir | Out-Null
+
+# 复制内容(robocopy /MIR 保留结构;失败则回滚)
+$rc = 1
+robocopy $srcRoot $AppDir /MIR /NFL /NDL /NJH /NJS /NP
+$rc = $LASTEXITCODE # robocopy 0-7 都算成功
+if ($rc -ge 8) {
+ Write-Host "[apply] 复制失败(robocopy=$rc),回滚旧版本"
+ Remove-Item -Recurse -Force $AppDir -ErrorAction SilentlyContinue
+ if (Test-Path $oldDir) { Move-Item -Force $oldDir $AppDir }
+ Stop-Transcript
+ exit 2
+}
+
+# 5) 清理备份 + 拉起(launcher 幂等:检测 daemon 后启动 watchdog)
+Remove-Item -Recurse -Force $oldDir -ErrorAction SilentlyContinue
+$launcher = Join-Path $AppDir 'launcher.cmd'
+if (Test-Path $launcher) {
+ # 直接启动 launcher.cmd(Start-Process 传单个参数字符串在 PS5.1 不会自动补外层引号,
+ # 含空格路径会被拆散——直接指定 FilePath+WorkingDirectory 最稳)
+ Start-Process -FilePath $launcher -WorkingDirectory (Split-Path $launcher)
+}
+Write-Host "[apply] $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') done"
+Stop-Transcript
+exit 0
\ No newline at end of file
diff --git a/scripts/build-mac-dmg.sh b/scripts/build-mac-dmg.sh
new file mode 100644
index 0000000..11c717b
--- /dev/null
+++ b/scripts/build-mac-dmg.sh
@@ -0,0 +1,54 @@
+#!/usr/bin/env bash
+# WorkDaddy macOS dmg 打包(壳子不动原则)
+# ============================================================
+# 铁律:壳子(WorkDaddy.app 结构 / launcher / Info.plist / 权限 / 签名)永不改动,
+# 只覆盖内部前端代码(daemon.js / inject.js / theme-patches.js 等)。
+# 背景:1.0.4 首版 dmg 打不开,根因是打包源 app 的 launcher 丢了可执行位
+# (-rw-rw-r--),hdiutil 打包后 macOS 拒绝启动不可执行的 CFBundleExecutable。
+# 本脚本每次打包前自检并恢复 launcher 可执行位 + 按 1.0.3 壳的原权限覆盖代码,
+# 保证产出包的壳与 1.0.3 完全一致(launcher md5 不变、Info.plist 不变)。
+# 用法: bash scripts/build-mac-dmg.sh
+# 产出: release/WorkDaddy-<ver>.dmg(ver 取自 daemon.js 的 DAEMON_VERSION)
+# ============================================================
+set -euo pipefail
+
+DIR="$(cd "$(dirname "$0")/.." && pwd)"
+cd "$DIR"
+
+VERSION="$(grep -o "DAEMON_VERSION = '[^']*'" scripts/daemon.js | head -1 | cut -d"'" -f2)"
+APP="WorkDaddy.app"
+OUT="release/WorkDaddy-${VERSION}.dmg"
+
+echo "==> 版本: ${VERSION}"
+echo "==> 产物: ${OUT}"
+
+# 1) 壳完整性自检:launcher 必须有可执行位(1.0.3 原版为 -rwxr-xr-x)
+chmod 755 "$APP/Contents/MacOS/launcher"
+echo "==> launcher 可执行位已保证: $(stat -f '%Sp' "$APP/Contents/MacOS/launcher")"
+
+# 2) 只覆盖前端代码(保留壳的其余一切:launcher/Info.plist/builtin/node_modules/theme-audit.js)
+for f in daemon.js inject.js theme-patches.js lib.js install.sh relaunch-with-cdp.sh uninstall.sh apply-update.sh; do
+ [ -f "scripts/$f" ] && cp "scripts/$f" "$APP/Contents/Resources/scripts/$f"
+done
+# 恢复这些文件的壳权限(与 1.0.3 壳内一致:sh/lib/daemon 755,inject/theme-patches 644)
+chmod 755 "$APP/Contents/Resources/scripts/daemon.js" \
+ "$APP/Contents/Resources/scripts/lib.js" \
+ "$APP/Contents/Resources/scripts/install.sh" \
+ "$APP/Contents/Resources/scripts/relaunch-with-cdp.sh" \
+ "$APP/Contents/Resources/scripts/uninstall.sh" \
+ "$APP/Contents/Resources/scripts/apply-update.sh"
+chmod 644 "$APP/Contents/Resources/scripts/inject.js" \
+ "$APP/Contents/Resources/scripts/theme-patches.js"
+echo "==> 前端代码已覆盖(权限按壳原样)"
+
+# 3) 打包:staging 放 WorkDaddy.app + Applications 软链(与 1.0.3 dmg 同构)
+STAGE="$(mktemp -d)"
+cp -R "$APP" "$STAGE/WorkDaddy.app"
+ln -s /Applications "$STAGE/Applications"
+rm -f "$OUT"
+hdiutil create -volname "WorkDaddy" -srcfolder "$STAGE" -ov -format UDZO -imagekey zlib-level=9 "$OUT" >/dev/null
+rm -rf "$STAGE"
+
+echo "==> 完成: $(ls -lh "$OUT" | awk '{print $5}')"
+echo " 校验: hdiutil attach -nobrowse -readonly '$OUT' 后检查"
+echo " launcher 权限必须为 rwxr-xr-x、daemon.js 版本为 ${VERSION}"
diff --git a/scripts/build-win-zip.sh b/scripts/build-win-zip.sh
new file mode 100644
index 0000000..99bd577
--- /dev/null
+++ b/scripts/build-win-zip.sh
@@ -0,0 +1,80 @@
+#!/usr/bin/env bash
+# WorkDaddy Windows 发布包打包脚本(在 macOS/Linux 上运行即可产出 Windows zip)
+# 产出:release/WorkDaddy-<ver>-win64.zip(顶层含 scripts\,供 install-win.cmd / apply-update.ps1 使用)
+# 可选:内置 node_modules/ws(面板 DevTools 代理依赖;无则代理功能降级,其余功能不受影响)
+set -euo pipefail
+
+DIR="$(cd "$(dirname "$0")/.." && pwd)"
+cd "$DIR"
+
+VERSION="$(grep -o "DAEMON_VERSION = '[^']*'" scripts/daemon.js | head -1 | cut -d"'" -f2)"
+OUT="release/WorkDaddy-${VERSION}-win64.zip"
+
+echo "==> 版本: ${VERSION}"
+echo "==> 产物: ${OUT}"
+
+# 1) 内置 ws(面板 DevTools 代理需要);已存在则跳过
+if [ ! -d scripts/node_modules/ws ]; then
+ echo "==> 生成 node_modules/ws(DevTools 代理依赖)"
+ TMPNODE="$(mktemp -d)"
+ (cd "$TMPNODE" && npm init -y >/dev/null 2>&1 && npm install ws --no-audit --no-fund >/dev/null 2>&1)
+ mkdir -p scripts/node_modules
+ rm -rf scripts/node_modules/ws
+ mv "$TMPNODE/node_modules/ws" scripts/node_modules/ws
+ rm -rf "$TMPNODE"
+fi
+
+# 2) 内置资产(官方壁纸 + nebula 主题,单一来源:WorkDaddy.app/Contents/Resources/scripts/builtin)
+# 仓库 scripts/ 本身不含 builtin,必须从 app 打包产物复制,否则 Windows 面板会显示「暂无官方壁纸」
+BUILTIN_SRC="$DIR/WorkDaddy.app/Contents/Resources/scripts/builtin"
+if [ -d "$BUILTIN_SRC" ]; then
+ echo "==> 内置资产 builtin -> scripts/builtin($(find "$BUILTIN_SRC/wallpapers" -name '*.webp' | wc -l | tr -d ' ') 张壁纸 + 主题)"
+ mkdir -p scripts/builtin
+ cp -R "$BUILTIN_SRC/." scripts/builtin/
+else
+ echo "==> 警告: 未找到内置资产 $BUILTIN_SRC(无 WorkDaddy.app?),打包将不含官方壁纸/主题"
+fi
+
+# 3) 打包:staging 目录,把两个顶层入口文件 + scripts/ 一起打进 zip 根(解压即见一键安装/启动)
+# 注意 apply-update.ps1 复用本结构(需 zip 内存在 scripts\daemon.js 做 srcRoot 判定)
+STAGE="$(mktemp -d)"
+rm -f "$OUT"
+# 3.1) 顶层入口(zip 根):Install-WorkDaddy.cmd / Start-WorkDaddy.cmd
+cp scripts/Install-WorkDaddy.cmd "$STAGE/Install-WorkDaddy.cmd"
+cp scripts/Start-WorkDaddy.cmd "$STAGE/Start-WorkDaddy.cmd"
+# 3.2) scripts\ 本体(含 node_modules/ws、builtin)
+cp -R scripts "$STAGE/scripts"
+# 3.2a) Logo 图标:放入 scripts\(install-win.ps1 从 SrcDir 同名找并复制到安装目录根)
+if [ -f "$DIR/release/WorkDaddy.ico" ]; then
+ cp "$DIR/release/WorkDaddy.ico" "$STAGE/scripts/WorkDaddy.ico"
+ echo "==> 内置 logo 图标 -> scripts/WorkDaddy.ico"
+else
+ echo "==> 警告: 未找到 release/WorkDaddy.ico,桌面图标将回退为 cmd 默认"
+fi
+# 3.3) 排除开发/临时文件 + 顶层入口在 scripts\ 内的重复副本
+# (Install-WorkDaddy.cmd / Start-WorkDaddy.cmd 只应存在于 zip 根,避免用户误进
+# scripts\ 双击导致相对路径解析成 scripts\scripts\install-win.ps1 报错)
+rm -rf "$STAGE/scripts/win/probe" "$STAGE/scripts/win/probe/"* 2>/dev/null || true
+rm -f "$STAGE/scripts/Install-WorkDaddy.cmd" "$STAGE/scripts/Start-WorkDaddy.cmd" 2>/dev/null || true
+find "$STAGE" -name '*.log' -delete 2>/dev/null || true
+find "$STAGE" -name '.DS_Store' -delete 2>/dev/null || true
+# 3.4) 打包:zip 优先;无 zip 的环境用 Windows 系统自带 bsdtar(生成标准 / 分隔符 zip)。
+# 绝不用 PowerShell Compress-Archive —— 它产出反斜杠分隔符,非标准 zip 会被解压工具把
+# scripts\daemon.js 当单个文件名,导致解压结构错乱、入口秒退。
+if command -v zip >/dev/null 2>&1; then
+ (cd "$STAGE" && zip -r -q "$DIR/$OUT" .)
+else
+ tar -a -cf "$DIR/$OUT" -C "$STAGE" .
+fi
+rm -rf "$STAGE"
+
+# 4) 清理临时内置到 scripts/ 的 builtin(避免污染仓库)
+if [ -d "$BUILTIN_SRC" ] && [ -d scripts/builtin ]; then
+ rm -rf scripts/builtin
+fi
+
+echo "==> 完成: $(ls -lh "$OUT" | awk '{print $5}')"
+echo ""
+echo "在 Windows 上:解压 zip 后,在顶层直接双击 Install-WorkDaddy.cmd 一键安装(自动建桌面图标+自启);"
+echo "日常启动双击 Start-WorkDaddy.cmd 或桌面 WorkDaddy 图标。"
+echo "每 6 小时自动检查更新(GitHub Releases 需同时上传 .dmg 与 -win64.zip 两个资产,Windows 自动静默升级)。"
\ No newline at end of file
diff --git a/scripts/daemon.js b/scripts/daemon.js
old mode 100755
new mode 100644
index eeb2907..0a56f32
--- a/scripts/daemon.js
+++ b/scripts/daemon.js
@@ -61,8 +61,14 @@ const DATA_DIR = defaultDataDir();
// 1.0.0:正式统一版本号(Info.plist / daemon / dmg 对齐 1.0.0),关于页改单行紧凑布局
// 1.0.1:自动更新(业界标准链路:GitHub Releases API 检查 → dmg 下载+SHA256 校验 → 辅助脚本替换 → relaunch)
// 1.0.2:代码块容器 /.cb-markdown-pre-container 毛玻璃 + chat widget 容器毛玻璃 + 表头半透明(theme-patches patch-77/78)
-const DAEMON_VERSION = '1.0.3';
+// 1.0.3:欢迎页隐藏暂存提示词按钮(inject isWelcomePage);chat widget 预览 iframe 背景透明(patch-80 + inject 同源注入兜底);
+// 默认主题改为「WorkBuddy 默认主题」(首次初始化/面板回退不再指向 nebula)
+const DAEMON_VERSION = '1.0.4';
const HOST = '127.0.0.1';
+const IS_WIN = process.platform === 'win32'; // Windows 移植:平台分支开关(macOS 行为保持不变)
+// Windows 安装目录(install.ps1 铺、launcher 用、更新替换目标),对应 macOS 的 /Applications/WorkDaddy.app
+const WORKDADDY_DIR_WIN = process.env.WBSWITCH_APP_DIR ||
+ path.join(process.env.LOCALAPPDATA || path.join(os.homedir(), 'AppData', 'Local'), 'Programs', 'WorkDaddy');
const UI_PORT_BASE = parseInt(process.env.WBSWITCH_PORT || '47832', 10);
let ACTUAL_PORT = UI_PORT_BASE; // 实际监听端口(被占用时 +1)
const CDP_PORT_HINT = process.env.WBSWITCH_CDP_PORT
@@ -150,7 +156,13 @@ function checkUpdate(force) {
updateState.hasUpdate = semverCompare(latest, DAEMON_VERSION) > 0;
updateState.releaseUrl = rel.html_url || null;
updateState.notes = (rel.body || '').slice(0, 2000);
- const asset = (rel.assets || []).find((a) => /\.dmg$/i.test(a.name || ''));
+ // 资产按平台选取:macOS 找 .dmg;Windows 优先官方便携包(-win64.zip),再回退任意 .zip,
+ // 绝不选 Setup.exe(IExpress 自解压包,当 .zip 下载后 Expand-Archive 会失败 → 更新中断)
+ const assets = rel.assets || [];
+ const asset = IS_WIN
+ ? (assets.find((a) => /-win64\.zip$/i.test(a.name || '')) ||
+ assets.find((a) => /\.zip$/i.test(a.name || '')) || null)
+ : (assets.find((a) => /\.dmg$/i.test(a.name || '')) || null);
updateState.dmgUrl = asset ? asset.browser_download_url : null;
updateState.dmgSize = asset ? asset.size : 0;
updateState.checkedAt = Date.now();
@@ -178,11 +190,12 @@ function checkUpdate(force) {
});
}
-// 下载 dmg(流式写文件,更新 progress),返回本地路径;带 SHA-256 校验
+// 下载安装包(macOS .dmg / Windows .zip),流式写文件更新 progress,带 SHA-256 校验
function downloadUpdate() {
if (!updateState.dmgUrl) return Promise.reject(new Error('无可用安装包'));
fs.mkdirSync(UPDATE_DIR, { recursive: true });
- const target = path.join(UPDATE_DIR, 'WorkDaddy-' + updateState.latest + '.dmg');
+ const ext = IS_WIN ? '.zip' : '.dmg';
+ const target = path.join(UPDATE_DIR, 'WorkDaddy-' + updateState.latest + ext);
if (fs.existsSync(target)) {
// 已有同版本文件:直接校验后复用
const digest = sha256File(target);
@@ -273,19 +286,35 @@ function extractAppFromDmg(dmgPath) {
});
}
-// 安装:调用独立 apply-update.sh 接管替换(先停 launchd + 杀旧 daemon → 脚本替换 → relaunch)
-// 独立脚本放 scripts/apply-update.sh(可维护),daemon 只需把参数传过去
+// 安装:macOS 调 apply-update.sh(launchctl 停服 → 备份 → 替换 → relaunch);
+// Windows 调 apply-update.ps1(杀 watchdog/daemon → 释放文件锁 → 替换目录 → 重启)
function applyUpdate() {
if (!updateState.downloaded) return Promise.reject(new Error('尚未下载完成'));
+ updateState.status = 'installing';
+ updateState.message = '正在安装新版本…';
+ const { execFile } = require('child_process');
+ if (IS_WIN) {
+ // Windows 安装位置由 install.ps1 铺好(%LOCALAPPDATA%\Programs\WorkDaddy)
+ const scriptPath = path.join(__dirname, 'apply-update.ps1');
+ const appDir = WORKDADDY_DIR_WIN;
+ const srcZip = path.join(UPDATE_DIR, 'WorkDaddy-' + updateState.latest + '.zip');
+ if (!fs.existsSync(scriptPath)) return Promise.reject(new Error('缺少 apply-update.ps1'));
+ if (!fs.existsSync(srcZip)) return Promise.reject(new Error('缺少解压后的新版本包'));
+ log('[update] 执行 apply-update.ps1,daemon 即将退出');
+ const child = require('child_process').spawn(
+ 'powershell',
+ ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', scriptPath, srcZip, appDir, String(ACTUAL_PORT)],
+ { detached: true, stdio: 'ignore', windowsHide: true }
+ );
+ child.unref();
+ return Promise.resolve({ ok: true, message: '更新已启动,WorkDaddy 即将重启' });
+ }
const scriptPath = path.join(__dirname, 'apply-update.sh');
const appPath = '/Applications/WorkDaddy.app';
const srcApp = path.join(UPDATE_DIR, 'WorkDaddy.app');
if (!fs.existsSync(scriptPath)) return Promise.reject(new Error('缺少 apply-update.sh'));
if (!fs.existsSync(srcApp)) return Promise.reject(new Error('缺少解包后的新应用'));
- updateState.status = 'installing';
- updateState.message = '正在安装新版本…';
// 停掉自身 launchd 服务(KeepAlive 会在新版本启动后接管)
- const { execFile } = require('child_process');
execFile('launchctl', ['bootout', 'gui/' + process.getuid(), 'com.workbuddy.workdaddy'], () => {
execFile('launchctl', ['remove', 'com.workbuddy.workdaddy'], () => {});
});
@@ -533,12 +562,65 @@ async function reloadWorkBuddyPage() {
await cdpSend('Page.reload', { ignoreCache: false });
}
-const WORKBUDDY_APP = '/Applications/WorkBuddy.app';
-const WORKBUDDY_BINARY = `${WORKBUDDY_APP}/Contents/MacOS/Electron`;
+const WORKBUDDY_APP = IS_WIN ? '' : '/Applications/WorkBuddy.app';
+const WORKBUDDY_BINARY = IS_WIN ? '' : `${WORKBUDDY_APP}/Contents/MacOS/Electron`;
+
+// Windows:解析 WorkBuddy 可执行文件真实路径(安装盘可自定义,必须动态查)
+// 优先级:WBSWITCH_WORKBUDDY_BIN > 运行进程 Path > 注册表卸载项 > 常见路径
+let wbBinaryCache = null;
+function resolveWorkBuddyBinary() {
+ if (!IS_WIN) return WORKBUDDY_BINARY;
+ if (wbBinaryCache) return wbBinaryCache;
+ const tryFile = (p) => { try { if (p && fs.existsSync(p)) return p; } catch (_) {} return null; };
+ const { execFileSync } = require('child_process');
+ const psCmd = (cmd) => execFileSync('powershell', ['-NoProfile', '-Command', cmd], { encoding: 'utf8', timeout: 8000, windowsHide: true });
+ // 1) 显式指定(launcher/install 传入最可靠)
+ const envBin = tryFile(process.env.WBSWITCH_WORKBUDDY_BIN);
+ if (envBin) return (wbBinaryCache = envBin);
+ // 2) 运行中的 WorkBuddy 进程 Path(最权威:多实例共享同一 exe)
+ try {
+ const out = psCmd('Get-Process WorkBuddy -ErrorAction SilentlyContinue | Select-Object -First 1 -ExpandProperty Path');
+ const p = out.trim().split(/\r?\n/).filter(Boolean).pop();
+ const hit = tryFile(p);
+ if (hit) return (wbBinaryCache = hit);
+ } catch (_) {}
+ // 3) 注册表卸载项(DisplayIcon = "D:\xxx\WorkBuddy.exe,0" 取逗号前)
+ try {
+ const out = psCmd("$k=@('HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*','HKLM:\\SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*','HKCU:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*'); Get-ItemProperty $k -ErrorAction SilentlyContinue | Where-Object { $_.DisplayName -match 'WorkBuddy|CodeBuddy' } | Select-Object -First 1 DisplayIcon,InstallLocation | ForEach-Object { if($_.DisplayIcon){ ($_.DisplayIcon -replace ',.*$','').Trim() } elseif($_.InstallLocation){ Join-Path $_.InstallLocation 'WorkBuddy.exe' } }");
+ const p = out.trim().split(/\r?\n/).filter(Boolean).pop();
+ const hit = tryFile(p);
+ if (hit) return (wbBinaryCache = hit);
+ } catch (_) {}
+ // 4) 常见路径兜底(含探测机实际安装位)
+ const cands = [
+ path.join(process.env.LOCALAPPDATA || '', 'Programs', 'WorkBuddy', 'WorkBuddy.exe'),
+ path.join(process.env.ProgramFiles || '', 'WorkBuddy', 'WorkBuddy.exe'),
+ path.join(process.env['ProgramFiles(x86)'] || '', 'WorkBuddy', 'WorkBuddy.exe'),
+ 'D:\\workbody\\WorkBuddy\\WorkBuddy.exe',
+ ];
+ for (const c of cands) {
+ const hit = tryFile(c);
+ if (hit) return (wbBinaryCache = hit);
+ }
+ return null;
+}
-/** 退出 WorkBuddy(按应用路径精确匹配,不误杀其他 Electron 应用) */
+/** 退出 WorkBuddy:macOS 按应用路径精确匹配;Windows 按进程名 taskkill(先优雅 WM_CLOSE,超时强杀) */
function quitWorkBuddy() {
return new Promise((resolve) => {
+ if (IS_WIN) {
+ let done = false;
+ const finish = () => { if (!done) { done = true; resolve(); } };
+ const run = (args) => {
+ const p = spawn('taskkill', args, { stdio: 'ignore', windowsHide: true });
+ p.on('error', finish);
+ p.on('exit', () => setTimeout(finish, 700));
+ };
+ run(['/IM', 'WorkBuddy.exe']);
+ setTimeout(() => { if (!done) run(['/F', '/T', '/IM', 'WorkBuddy.exe']); }, 2500);
+ setTimeout(finish, 8000); // 极端兜底,绝不悬挂
+ return;
+ }
// 先尝试正常退出(给 Electron 一次处理机会),再强制 kill
const p1 = spawn('osascript', ['-e', 'tell application "WorkBuddy" to quit'], { stdio: 'ignore' });
p1.on('error', () => {});
@@ -552,8 +634,9 @@ function quitWorkBuddy() {
});
}
-/** 探测 WorkDaddy.app 位置(退出登录后打开它,由其 launcher 以 CDP 模式重启 WorkBuddy 并注入组件) */
+/** 探测 WorkDaddy.app 位置(macOS 专用:退出登录后打开它,由其 launcher 以 CDP 模式重启 WorkBuddy 并注入组件) */
function findWorkDaddyApp() {
+ if (IS_WIN) return null;
const cands = [
'/Applications/WorkDaddy.app',
path.join(os.homedir(), 'Applications', 'WorkDaddy.app'),
@@ -569,9 +652,18 @@ function findWorkDaddyApp() {
return null;
}
-/** 重新启动 WorkBuddy:优先打开 WorkDaddy.app(其 launcher 自动带 CDP 重启 WorkBuddy + 注入组件),找不到时回退直接启动 WorkBuddy */
+/** 重新启动 WorkBuddy:macOS 优先走 WorkDaddy.app launcher;Windows 直接带 CDP 参数重启 exe */
function relaunchWorkBuddy() {
return new Promise((resolve, reject) => {
+ if (IS_WIN) {
+ const bin = resolveWorkBuddyBinary();
+ if (!bin) return reject(new Error('未找到 WorkBuddy.exe(可用环境变量 WBSWITCH_WORKBUDDY_BIN 指定)'));
+ log(`[logout] 以 --remote-debugging-port=9222 重启 WorkBuddy: ${bin}`);
+ const child = spawn(bin, ['--remote-debugging-port=9222'], { detached: true, stdio: 'ignore', windowsHide: true });
+ child.on('error', (e) => reject(e));
+ child.unref();
+ return resolve();
+ }
const workDaddy = findWorkDaddyApp();
if (workDaddy) {
log(`[logout] 正在打开 WorkDaddy (${workDaddy}),由其 launcher 重启 WorkBuddy`);
@@ -775,7 +867,9 @@ async function dailyCheckin(accessToken) {
const code = o.code;
const already = code === 10001;
const ok = already || (r.ok && (code === 0 || code === undefined || code === null));
- return { ok, already, code, message: o.msg || o.message || (r.ok ? 'ok' : 'HTTP ' + r.status), url };
+ // 401 = token 过期/未授权:直接给友好文案,避免面板显示裸 "HTTP 401"
+ const failMsg = r.status === 401 ? '登录身份过期' : 'HTTP ' + r.status;
+ return { ok, already, code, message: o.msg || o.message || (r.ok ? 'ok' : failMsg), url };
} catch (e) {
lastErr = e.message;
}
@@ -876,7 +970,30 @@ function injectWidget(reason) {
// ===== SESSIONS_API_MARK:会话管理(读 WorkBuddy workbuddy.db)=====
const SESSIONS_DB = path.join(os.homedir(), '.workbuddy', 'workbuddy.db');
+// Windows:无系统 sqlite3 CLI,优先用 Node 内置 node:sqlite(需 --experimental-sqlite 启动,launcher/install 已统一加)
+let NodeSqlite = null;
+if (IS_WIN) { try { NodeSqlite = require('node:sqlite'); } catch (_) { NodeSqlite = null; } }
+// 输出统一为 "header|header2\nval|val2" 格式,sqliteQuery 的解析两种后端通用
function sqliteRun(sql) {
+ if (IS_WIN && NodeSqlite) {
+ return new Promise((resolve, reject) => {
+ let db = null;
+ try {
+ db = new NodeSqlite.DatabaseSync(SESSIONS_DB, { readOnly: true });
+ const rows = db.prepare(sql).all();
+ db.close(); db = null;
+ if (!rows.length) return resolve('');
+ const header = Object.keys(rows[0]).join('|');
+ const lines = rows.map((r) =>
+ Object.values(r).map((v) => (v === null || v === undefined ? '' : String(v))).join('|')
+ );
+ resolve([header].concat(lines).join('\n'));
+ } catch (e) {
+ if (db) { try { db.close(); } catch (_) {} }
+ reject(new Error('sqlite 查询失败: ' + e.message));
+ }
+ });
+ }
return new Promise((resolve, reject) => {
const p = spawn('sqlite3', ['-header', SESSIONS_DB], { stdio: ['pipe', 'pipe', 'pipe'] });
let out = '', err = '';
@@ -1348,11 +1465,11 @@ function initBuiltinAssets() {
fs.writeFileSync(maskFile, JSON.stringify({ opacity: 0.1 }, null, 2));
log('[init] 首次初始化:背景蒙版默认 10% -> mask.json');
}
- // 4) 默认主题 → nebula(仅当未设置过)
+ // 4) 默认主题 → WorkBuddy 默认主题(仅当未设置过;用户要求默认选中官方浅色,不再默认 nebula)
const curFile = path.join(DATA_DIR, 'current-theme.json');
if (!fs.existsSync(curFile)) {
- fs.writeFileSync(curFile, JSON.stringify({ id: 'nebula', at: new Date().toISOString() }, null, 2));
- log('[init] 首次初始化:默认主题 -> nebula');
+ fs.writeFileSync(curFile, JSON.stringify({ id: 'default', at: new Date().toISOString() }, null, 2));
+ log('[init] 首次初始化:默认主题 -> WorkBuddy 默认主题(default)');
}
} catch (e) {
log('[init] 首次初始化失败: ' + e.message);
@@ -2720,7 +2837,7 @@ function handleApi(req, res) {
license: 'AGPL-3.0',
repository: 'https://github.com/babygoton/WorkDaddy',
principle: '本机回环 CDP 注入 · 不改官方安装包',
- platform: 'macOS 11+(Windows 敬请期待)',
+ platform: IS_WIN ? 'Windows 10+(x64)' : 'macOS 11+',
author: 'WorkDaddy',
nodeVersion: process.version,
...platform,
@@ -2919,7 +3036,11 @@ function handleApi(req, res) {
if (req.method === 'GET' && p === '/api/open-dir') {
try {
- require('child_process').execFile('/usr/bin/open', [DATA_DIR]);
+ if (IS_WIN) {
+ require('child_process').execFile('explorer.exe', [DATA_DIR]);
+ } else {
+ require('child_process').execFile('/usr/bin/open', [DATA_DIR]);
+ }
return json(res, 200, { ok: true });
} catch (e) {
return json(res, 500, { ok: false, error: e.message });
@@ -2983,7 +3104,14 @@ function handleApi(req, res) {
let sleepCaffeinate = null;
let sleepUserActivity = null; // 防锁屏:caffeinate -u -t 300(UserIsActive 断言,阻止屏保启动/空闲锁屏)
let sleepUserActivityTimer = null; // -u 断言每 240s 续期一次(-t 300 超时前续期,保持无间隙)
+let sleepPowershell = null; // Windows: 常驻 powershell 进程持有 SetThreadExecutionState
function stopCaffeinate() {
+ if (IS_WIN) {
+ const c = sleepPowershell;
+ sleepPowershell = null; // 先置 null 再 kill,避免 exit 回调把旧引用覆盖
+ if (c) { try { c.kill(); } catch (_) {} }
+ return;
+ }
const c = sleepCaffeinate;
sleepCaffeinate = null; // 先置 null 再 kill,避免旧进程 exit 回调把新引用覆盖
if (c) { try { c.kill(); } catch (_) {} }
@@ -2999,6 +3127,7 @@ function stopUserActivity() {
// 系统认为用户一直在操作,屏保与空闲锁屏便不会触发;每 240s 重启一个 -t 300 的断言实现无间隙续期。
// 无需辅助功能权限(-u 走系统 IOKit 用户活动断言)。
function startUserActivityLoop() {
+ if (IS_WIN) return; // Windows 无 caffeinate -u 等价;防锁屏由系统电源策略控制
stopUserActivity();
const tick = () => {
if (!sleepCaffeinate) return; // 防休眠已停止(allow 模式),不再续期
@@ -3013,6 +3142,17 @@ function startUserActivityLoop() {
if (sleepUserActivityTimer.unref) sleepUserActivityTimer.unref();
}
function startCaffeinate(displaySleep) {
+ if (IS_WIN) {
+ // Windows:常驻 powershell 循环调用 SetThreadExecutionState。
+ // 0x80000000 ES_CONTINUOUS | 0x1 ES_SYSTEM_REQUIRED | 0x2 ES_DISPLAY_REQUIRED
+ const flags = displaySleep ? '0x80000001' : '0x80000003';
+ const ps = "Add-Type -MemberDefinition '[DllImport(\"kernel32.dll\")] public static extern uint SetThreadExecutionState(uint e);' -Name WSleep -Namespace WB -PassThru | Out-Null; while($true){ [WB.WSleep]::SetThreadExecutionState(" + flags + "); Start-Sleep -Seconds 90 }";
+ const child = spawn('powershell', ['-NoProfile', '-WindowStyle', 'Hidden', '-Command', ps], { stdio: 'ignore', windowsHide: true });
+ child.on('error', (e) => { log('[sleep] 防休眠进程启动失败: ' + e.message); if (sleepPowershell === child) sleepPowershell = null; });
+ child.on('exit', () => { if (sleepPowershell === child) sleepPowershell = null; });
+ sleepPowershell = child;
+ return child;
+ }
const child = spawn('caffeinate', displaySleep ? ['-i', '-s', '-m'] : ['-d', '-i', '-s', '-m'], { stdio: 'ignore' });
child.on('error', (e) => { log('[sleep] caffeinate 启动失败: ' + e.message); if (sleepCaffeinate === child) sleepCaffeinate = null; });
child.on('exit', () => { if (sleepCaffeinate === child) sleepCaffeinate = null; });
@@ -3024,6 +3164,15 @@ function startCaffeinate(displaySleep) {
function applySleepMode(mode, displaySleep) {
const preventing = mode === 'keep' || mode === 'until-done';
if (preventing) {
+ if (IS_WIN) {
+ // Windows:powershell 持有进程参数固定,无法比较 spawnargs,直接重启(低频操作,代价可接受)
+ stopCaffeinate();
+ try {
+ startCaffeinate(!!displaySleep);
+ log('[sleep] 禁止休眠已开启(Windows,模式=' + mode + (displaySleep ? ',允许显示器休眠' : ',显示器保持唤醒') + ')');
+ } catch (e) { log('[sleep] 开启失败: ' + e.message); return false; }
+ return true;
+ }
const wantArgs = displaySleep ? '-i-s-m' : '-d-i-s-m';
const curArgs = sleepCaffeinate ? sleepCaffeinate.spawnargs.slice(1).join('-') : null;
const wantLock = !displaySleep; // 防锁屏仅在显示器保持唤醒时有效
@@ -3043,6 +3192,13 @@ function applySleepMode(mode, displaySleep) {
}
function sleepNow() {
try {
+ if (IS_WIN) {
+ // Windows:SetSuspendState(Hibernate=0, ForceCritical=0, DisableWakeEvent=0) → 睡眠
+ const c = spawn('rundll32.exe', ['powrprof.dll,SetSuspendState', '0,1,0'], { stdio: 'ignore', windowsHide: true });
+ c.on('error', (e) => log('[sleep] 立即休眠失败: ' + e.message));
+ c.on('exit', () => log('[sleep] 已请求立即休眠(Windows SetSuspendState)'));
+ return true;
+ }
const c = spawn('pmset', ['sleepnow'], { stdio: 'ignore' });
c.on('error', (e) => log('[sleep] 立即休眠失败: ' + e.message));
c.on('exit', () => log('[sleep] 已请求立即休眠'));
diff --git a/scripts/inject.js b/scripts/inject.js
index 6517f01..a379665 100644
--- a/scripts/inject.js
+++ b/scripts/inject.js
@@ -145,7 +145,10 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
var c = a && a.checkin;
if (!c) return '<span class="wbs-ck pending">正在领取中</span>';
if (c.ok) return '<span class="wbs-ck ok">' + (c.already ? '今日已签 ✓' : '已领取 ✓') + '</span>';
- return '<span class="wbs-ck fail">' + (c.message || '失败') + '</span>';
+ // 认证类错误(401/未授权)统一显示友好文案(daemon 已产出,缓存残留旧文案时兜底)
+ var msg = c.message || '失败';
+ if (/401|Unauthorized|未授权|登录身份过期/.test(msg)) msg = '登录身份过期';
+ return '<span class="wbs-ck fail">' + msg + '</span>';
}
function el(tag, cls, html) {
@@ -517,7 +520,12 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'</div>',
'<div class="wbs-panel">',
'<div class="wbs-head">',
+ '<div class="wbs-head-left">',
'<div class="wbs-title" id="wbs-title" title="连续点击 5 次呼出元素检查">WorkDaddy</div>',
+ '<a class="wbs-ghbtn" href="https://github.com/babygoton/WorkDaddy" target="_blank" rel="noopener" title="GitHub 仓库">',
+ '<svg viewBox="0 0 24 24" width="15" height="15" fill="currentColor" aria-hidden="true"><path d="M12 .3a12 12 0 0 0-3.79 23.39c.6.11.82-.26.82-.58v-2.03c-3.34.73-4.04-1.61-4.04-1.61-.55-1.39-1.33-1.76-1.33-1.76-1.09-.74.08-.73.08-.73 1.2.09 1.84 1.24 1.84 1.24 1.07 1.83 2.81 1.3 3.5 1 .1-.78.42-1.31.76-1.61-2.66-.3-5.47-1.33-5.47-5.93 0-1.31.47-2.38 1.24-3.22-.13-.3-.54-1.52.11-3.18 0 0 1.01-.32 3.3 1.23a11.5 11.5 0 0 1 6.01 0c2.29-1.55 3.3-1.23 3.3-1.23.65 1.66.24 2.88.12 3.18.77.84 1.23 1.91 1.23 3.22 0 4.61-2.81 5.62-5.49 5.92.43.37.82 1.1.82 2.22v3.29c0 .32.22.7.83.58A12 12 0 0 0 12 .3z"/></svg>',
+ '</a>',
+ '</div>',
'<button class="wbs-btn-close" type="button" data-act="close">✕</button>',
'</div>',
'<div class="wbs-tabs">',
@@ -614,10 +622,19 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
function removeStash() {
stashBtn.style.display = 'none';
}
+ // 是否在欢迎页(wb-home-page 或 main-content--welcome 存在即欢迎页):
+ // 用户要求欢迎页不展示暂存提示词按钮(欢迎页输入框只是快速提问入口,不需要暂存)。
+ function isWelcomePage() {
+ try {
+ return !!(document.querySelector('.wb-home-page') || document.querySelector('.main-content--welcome'));
+ } catch (_) { return false; }
+ }
// 是否该显示暂存按钮:直接看真正输入框是否有内容(修后 findComposer 不再误命中消息历史)。
// WorkBuddy v5.3.8:空输入框下官方发送按钮 DOM 上不显式设置 disabled / is-disabled,
// 显隐完全由「输入框是否有内容」决定,isSendDisabled 在空状态下检测不到。
+ // 欢迎页一律不显示。
function shouldShowStash() {
+ if (isWelcomePage()) return false;
var ed = findComposer();
return composerHasContent(ed);
}
@@ -627,6 +644,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
clearTimeout(stashSyncThrottle);
// 节流 30ms:比 120ms 响应更快(接近原生 React 按钮的体感),仍能合并快速连续触发
stashSyncThrottle = setBuildTimeout(function () {
+ // 欢迎页强制隐藏(进入欢迎页/切回欢迎页时兜底,避免上一会话残留按钮)
+ if (isWelcomePage()) { stashBtn.style.display = 'none'; return; }
if (shouldShowStash()) {
insertStash();
stashBtn.style.display = 'flex';
@@ -682,6 +701,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
guardSessionChange();
scheduleFabPos();
watchRow();
+ syncStash(); // 页面切换(欢迎页↔聊天页)后立即重算暂存按钮显隐
if (!findActionRow()) return;
watchSend();
syncQueueTags();
@@ -782,6 +802,37 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
fabPosTimer = setBuildInterval(function () { if (alive) scheduleFabPos(); }, 1500);
setBuildTimeout(scheduleFabPos, 600); // 首屏定位
+ // ===== chat widget 预览 iframe 背景透明(用户要求)=====
+ // 场景:AI 生成的 widget(_widgetRendererWrapper/_widgetContainer 内的 iframe)在深色主题下
+ // 自带黑底,与毛玻璃主题不协调;且元素拾取器无法进入 iframe 内部定位样式来源。
+ // 两层兜底:
+ // 1) iframe 元素级背景透明 —— 由 theme-patches.js 的 CSS 补丁处理(html[data-theme="dark"]);
+ // 2) 本 JS 对同源 iframe(srcdoc/blob,contentDocument 可访问)注入 html,body 透明样式,
+ // 覆盖 iframe 内部文档自带的黑底(跨域 iframe 无法注入内部,仅靠元素级 CSS)。
+ var WIDGET_IFRAME_STYLE_ID = 'wbs-iframe-transparent';
+ function fixWidgetIframeBg() {
+ if (!alive) return;
+ try {
+ var h = document.documentElement;
+ var dark = h && (h.getAttribute('data-theme') === 'dark' || h.classList.contains('cb-dark'));
+ if (!dark) return; // 仅深色主题需要处理(浅色下 widget 保持自身渲染)
+ var frames = document.querySelectorAll('[class*="_widgetRendererWrapper_"] iframe,[class*="_widgetContainer_"] iframe');
+ for (var i = 0; i < frames.length; i++) {
+ try {
+ var doc = frames[i].contentDocument;
+ if (!doc || !doc.documentElement) continue;
+ if (doc.getElementById(WIDGET_IFRAME_STYLE_ID)) continue;
+ var st = doc.createElement('style');
+ st.id = WIDGET_IFRAME_STYLE_ID;
+ st.textContent = 'html,body{background:transparent !important;background-color:transparent !important;}';
+ (doc.head || doc.documentElement).appendChild(st);
+ } catch (_) {}
+ }
+ } catch (_) {}
+ }
+ setBuildInterval(fixWidgetIframeBg, 1500);
+ setBuildTimeout(fixWidgetIframeBg, 800);
+
// ===== 暂存提示词:优先入队到 WorkBuddy 的 message queue(完整富文本 + 暂停自动发送)=====
// 通过 React fiber 提取 adapter(含 enqueueConversationMessageQueueItem / pauseConversationMessageQueue)。
function findWbsAdapter() {
@@ -2270,19 +2321,20 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
// ===== 主题系统(WorkDaddy 换肤):segmented 切换 =====
// 主题 = CSS 变量覆盖(--wb-* / --dc-*),daemon 通过 CDP 注入 <style>。
// 只提供两个入口:官方主题(default) 与 WorkDaddy 官方主题(nebula),其余自定义主题不展示
+ // 默认选中「WorkBuddy 默认主题」(default):未设置/异常时回退到 default 而非 nebula(用户要求)
var ALLOWED_THEMES = ['default', 'nebula'];
function loadThemes() {
api('/api/themes')
.then(function (d) {
var seg = root.querySelector('.wbs-theme-seg');
if (!seg) return;
- var cur = d.current && ALLOWED_THEMES.indexOf(d.current) >= 0 ? d.current : 'nebula';
+ var cur = d.current && ALLOWED_THEMES.indexOf(d.current) >= 0 ? d.current : 'default';
seg.querySelectorAll('.wbs-theme-opt').forEach(function (b) {
b.classList.toggle('active', b.getAttribute('data-theme') === cur);
});
- // 若当前主题不在允许列表(如之前应用了自定义主题),回退到 nebula
- if (d.current && ALLOWED_THEMES.indexOf(d.current) < 0 && cur === 'nebula') {
- applyTheme('nebula').catch(function () {});
+ // 若当前主题不在允许列表(如之前应用了自定义主题),回退到默认主题
+ if (d.current && ALLOWED_THEMES.indexOf(d.current) < 0 && cur === 'default') {
+ applyTheme('default').catch(function () {});
}
})
.catch(function () {});
@@ -3315,7 +3367,11 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'.wbs-panel{position:absolute;right:0;bottom:0;width:460px;max-height:min(78vh,660px);background:color-mix(in srgb,var(--wb-bg-popover,#fff) 72%,transparent);border:1px solid var(--wb-border-subtle,#f0f0f0);border-radius:18px;box-shadow:0 20px 60px rgba(0,0,0,.28);display:none;flex-direction:column;overflow:hidden;backdrop-filter:blur(28px) saturate(1.25);-webkit-backdrop-filter:blur(28px) saturate(1.25)}',
'.wbs-panel.show{display:flex}',
'.wbs-head{display:flex;align-items:center;justify-content:space-between;padding:16px 18px 12px;border-bottom:1px solid var(--wb-border-subtle,#f0f0f0);background:color-mix(in srgb,var(--wb-bg-secondary,#fff) 30%,transparent)}',
+ '.wbs-head-left{display:flex;align-items:center;gap:9px;min-width:0}',
'.wbs-title{font-size:16px;font-weight:700;color:var(--wb-color-text-primary,#1f1f1f);letter-spacing:.3px;cursor:default;user-select:none}',
+ '.wbs-ghbtn{display:flex;align-items:center;justify-content:center;width:24px;height:24px;flex-shrink:0;color:var(--wb-icon-tertiary,#999);border-radius:6px;text-decoration:none;transition:color .15s,background .15s}',
+ '.wbs-ghbtn:hover{color:var(--wb-color-text-primary,#1f1f1f);background:var(--wb-bg-hover,#f5f5f5)}',
+ '.wbs-ghbtn svg{display:block}',
'.wbs-btn-close{border:none;background:none;color:var(--wb-icon-tertiary,#999);font-size:16px;cursor:pointer;padding:4px 6px;border-radius:6px;line-height:1}',
'.wbs-btn-close:hover{color:var(--wb-color-text-primary,#1f1f1f);background:var(--wb-bg-hover,#f5f5f5)}',
'.wbs-body{overflow-y:auto;padding:10px 10px 6px;flex:1;max-height:calc(min(78vh,660px) - 170px)}',
diff --git a/scripts/install-win.cmd b/scripts/install-win.cmd
new file mode 100644
index 0000000..05047ae
--- /dev/null
+++ b/scripts/install-win.cmd
@@ -0,0 +1,28 @@
+@echo off
+rem WorkDaddy Windows 安装核心(由 Install-WorkDaddy.cmd 或安装目录调用)
+rem 仅用 %~dp0 绝对路径定位 install-win.ps1,杜绝 scripts\scripts 嵌套导致的相对路径歧义
+setlocal
+chcp 65001 >nul
+
+where powershell >nul 2>nul
+if errorlevel 1 (
+ echo 错误:未找到 PowerShell(Windows 10/11 均自带)。
+ pause
+ exit /b 1
+)
+
+if not exist "%~dp0install-win.ps1" (
+ echo 错误:找不到 scripts\install-win.ps1(请确认与 install-win.cmd 同目录)。
+ pause
+ exit /b 3
+)
+
+powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0install-win.ps1"
+set "EXIT_CODE=%ERRORLEVEL%"
+echo.
+if "%EXIT_CODE%"=="0" (
+ echo 安装完成。WorkBuddy 即将以调试模式重启,请稍等片刻。
+) else (
+ echo 安装过程有异常(代码 %EXIT_CODE%),请查看上方输出。
+)
+pause
diff --git a/scripts/install-win.ps1 b/scripts/install-win.ps1
new file mode 100644
index 0000000..7f9a182
--- /dev/null
+++ b/scripts/install-win.ps1
@@ -0,0 +1,90 @@
+# WorkDaddy Windows 安装脚本(install.sh 的 Windows 对应物)
+# 用法:双击 install-win.cmd,或 powershell -ExecutionPolicy Bypass -File install-win.ps1
+# 作用:复制到安装目录 → 初始化数据目录 → 注册登录自启(HKCU Run) → 启动 launcher(自动拉起 daemon + 以 CDP 模式重启 WorkBuddy)
+# 全程用户态,无需管理员权限。
+param(
+ [string]$SrcDir = $PSScriptRoot,
+ [string]$AppDir = (Join-Path $env:LOCALAPPDATA 'Programs\WorkDaddy')
+)
+
+$ErrorActionPreference = 'Continue'
+$targetScripts = Join-Path $AppDir 'scripts'
+
+Write-Host '=============================================================='
+Write-Host ' WorkDaddy Windows 安装'
+Write-Host '=============================================================='
+Write-Host (" 源目录 : " + $SrcDir)
+Write-Host (" 安装目录 : " + $AppDir)
+
+# 1) 复制(排除开发/临时文件;node_modules/ws 随包带入)
+if (-not (Test-Path (Join-Path $SrcDir 'daemon.js'))) {
+ Write-Host '错误:源目录中找不到 daemon.js,请从仓库 scripts/ 目录运行本脚本。'
+ exit 1
+}
+New-Item -ItemType Directory -Force -Path $targetScripts | Out-Null
+robocopy $SrcDir $targetScripts /E /XF *.log .DS_Store /XD win\probe
+$rc = $LASTEXITCODE
+if ($rc -ge 8) {
+ Write-Host "复制失败(robocopy=$rc)"
+ exit 2
+}
+
+# 2) 数据目录
+$dataDir = Join-Path $env:APPDATA 'WorkDaddy'
+New-Item -ItemType Directory -Force -Path (Join-Path $dataDir 'accounts') | Out-Null
+
+# 2.5) Logo 图标:随安装复制到安装目录根(桌面快捷方式用),源在 scripts 同级的 WorkDaddy.ico
+$logoIcoSrc = Join-Path $SrcDir 'WorkDaddy.ico'
+$logoIco = Join-Path $AppDir 'WorkDaddy.ico'
+if (Test-Path $logoIcoSrc) {
+ try { Copy-Item $logoIcoSrc $logoIco -Force; Write-Host (' 图标复制 : ' + $logoIco) } catch {}
+}
+
+# 3) 登录自启(HKCU Run,登录时自动跑 launcher.cmd;崩溃自愈由 watchdog 负责)
+$runKey = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Run'
+$launcher = Join-Path $targetScripts 'launcher.cmd'
+try {
+ Set-ItemProperty -Path $runKey -Name 'WorkDaddy' -Value ('"' + $launcher + '"')
+ Write-Host ' 自启注册:HKCU\...\Run\WorkDaddy = ' $launcher
+} catch {
+ Write-Host (' 自启注册失败(可忽略,之后手动双击 launcher.cmd 即可): ' + $_.Exception.Message)
+}
+
+# 4) 启动(daemon + 以 CDP 模式重启 WorkBuddy + 注入)
+Write-Host ' 正在启动 WorkDaddy(如果 WorkBuddy 正在运行,会重启它以开启调试模式)...'
+if (Test-Path $launcher) {
+ Start-Process -FilePath $launcher -WorkingDirectory (Split-Path $launcher)
+} else {
+ Write-Host ' 警告:launcher.cmd 不存在,跳过自动启动(请到安装目录手动双击)'
+}
+
+# 5) 创建桌面快捷方式「WorkDaddy」
+# 用 cmd.exe 作为目标程序 + /c 调用脚本,绕开 .cmd/.bat 文件关联被改(如被篡改成记事本)的坑,
+# 保证在任何 Windows 上双击桌面图标都能正常启动。
+$desktopDir = [Environment]::GetFolderPath('Desktop')
+if (-not $desktopDir) { $desktopDir = Join-Path $env:USERPROFILE 'Desktop' }
+$lnkPath = Join-Path $desktopDir 'WorkDaddy.lnk'
+# Logo 图标(macOS 版同款黑白的 WorkBuddy 机器人,打包时置于安装目录根)
+$logoIco = Join-Path $AppDir 'WorkDaddy.ico'
+try {
+ $ws = New-Object -ComObject WScript.Shell
+ $sc = $ws.CreateShortcut($lnkPath)
+ $sc.TargetPath = "$env:ComSpec" # cmd.exe —— 与文件关联无关,始终可执行
+ $sc.Arguments = '/d /c call "' + $launcher + '"' # 由当前 cmd 解释执行,不触发 Explorer 关联
+ $sc.WorkingDirectory = (Split-Path $launcher)
+ $sc.Description = 'WorkDaddy – WorkBuddy 增强工具(双击启动)'
+ if (Test-Path $logoIco) { $sc.IconLocation = $logoIco + ',0' } # 用官方 logo,而非 cmd 默认图标
+ $sc.Save()
+ Write-Host (' 桌面快捷方式 : ' + $lnkPath)
+ if (Test-Path $logoIco) { Write-Host (' 图标 : ' + $logoIco) }
+} catch {
+ Write-Host (' 桌面快捷方式创建失败(可忽略,之后可手动创建): ' + $_.Exception.Message)
+}
+
+Write-Host '=============================================================='
+Write-Host ' 安装完成!'
+Write-Host (" 安装目录 : " + $AppDir)
+Write-Host (" 数据目录 : " + $dataDir)
+Write-Host (' 备份账号 : ' + (Join-Path $dataDir 'accounts'))
+Write-Host ' 卸载 : 运行安装目录 scripts\uninstall-win.ps1'
+Write-Host '=============================================================='
\ No newline at end of file
diff --git a/scripts/install.sh b/scripts/install.sh
old mode 100755
new mode 100644
diff --git a/scripts/kill.js b/scripts/kill.js
new file mode 100644
index 0000000..b9b0a05
--- /dev/null
+++ b/scripts/kill.js
@@ -0,0 +1,4 @@
+const {spawnSync}=require('child_process');
+const r=spawnSync('taskkill',['/F','/T','/IM','WorkBuddy.exe'],{encoding:'utf8',windowsHide:true,timeout:10000});
+console.log('status:',r.status);
+console.log('stdout:',(r.stdout||'').split(/\r?\n/).filter(Boolean).slice(-6).join('\n'));
diff --git a/scripts/launcher.cmd b/scripts/launcher.cmd
new file mode 100644
index 0000000..ed49021
--- /dev/null
+++ b/scripts/launcher.cmd
@@ -0,0 +1,30 @@
+@echo off
+rem WorkDaddy Windows 启动器(双击入口)
+rem 需要:launcher.cmd 与 win-launcher.js / watchdog.js / daemon.js 在同一目录
+setlocal
+chcp 65001 >nul
+cd /d "%~dp0"
+
+rem 定位 node:优先 WorkBuddy 托管运行时(.workbuddy\binaries\node\versions\*),其次 PATH
+set "NODE="
+for /d %%d in ("%USERPROFILE%\.workbuddy\binaries\node\versions\*") do (
+ if exist "%%d\node.exe" set "NODE=%%d\node.exe"
+)
+if not defined NODE set "NODE=node"
+
+if not exist "%~dp0win-launcher.js" (
+ echo 错误:找不到 win-launcher.js,请勿单独运行本文件。
+ pause
+ exit /b 1
+)
+
+"%NODE%" --experimental-sqlite "%~dp0win-launcher.js" %*
+set "EXIT_CODE=%ERRORLEVEL%"
+
+echo.
+if "%EXIT_CODE%"=="0" (
+ echo 完成:WorkDaddy 组件已就绪,WorkBuddy 右下角应有机器人按钮。
+) else (
+ echo 未完全完成(代码 %EXIT_CODE%)。日志:%APPDATA%\WorkDaddy\launcher.log
+)
+pause
\ No newline at end of file
diff --git a/scripts/lib.js b/scripts/lib.js
old mode 100755
new mode 100644
index 43e855f..1e036a9
--- a/scripts/lib.js
+++ b/scripts/lib.js
@@ -16,17 +16,34 @@ const fs = require('fs');
const os = require('os');
const path = require('path');
+const IS_WIN = process.platform === 'win32';
+
+// macOS: ~/Library/Application Support/CodeBuddyExtension/Data/Public/auth/workbuddy-desktop.info
+// Windows: %LOCALAPPDATA%\CodeBuddyExtension\Data\Public\auth\workbuddy-desktop.info(真机已确认)
const AUTH_FILE =
process.env.WBSWITCH_AUTH_FILE ||
- path.join(
- os.homedir(),
- 'Library/Application Support/CodeBuddyExtension/Data/Public/auth/workbuddy-desktop.info'
- );
+ (IS_WIN
+ ? path.join(
+ process.env.LOCALAPPDATA || path.join(os.homedir(), 'AppData', 'Local'),
+ 'CodeBuddyExtension',
+ 'Data',
+ 'Public',
+ 'auth',
+ 'workbuddy-desktop.info'
+ )
+ : path.join(
+ os.homedir(),
+ 'Library/Application Support/CodeBuddyExtension/Data/Public/auth/workbuddy-desktop.info'
+ ));
function defaultDataDir() {
+ // macOS: ~/Library/Application Support/WorkDaddy
+ // Windows: %APPDATA%\WorkDaddy
return (
process.env.WBSWITCH_DATA_DIR ||
- path.join(os.homedir(), 'Library/Application Support/HelloBuddy')
+ (IS_WIN
+ ? path.join(process.env.APPDATA || path.join(os.homedir(), 'AppData', 'Roaming'), 'WorkDaddy')
+ : path.join(os.homedir(), 'Library', 'Application Support', 'WorkDaddy'))
);
}
@@ -199,9 +216,13 @@ function switchTo(dataDir, uid, log = () => {}) {
fs.chmodSync(AUTH_FILE, 0o600);
} catch (e) {
// 沙箱环境(如从 WorkBuddy 托管后台运行)直接写系统目录会 EPERM。
- // 回退方案:先把内容写到本 daemon 可写的临时文件(数据目录),
- // 再委托 GUI 会话(osascript do shell script)把文件复制到 auth 目录,
- // 复制命令不涉及内容转义,只传路径,稳妥可靠。
+ // macOS 回退:osascript 委托 GUI 会话复制(不涉及内容转义,只传路径)。
+ // Windows:目录在 %LOCALAPPDATA% 用户可写区,直写失败即如实报错。
+ if (IS_WIN) {
+ throw new Error(
+ `写入登录文件失败(${e.code || ''}): ${(e.message || e).toString().slice(0, 200)}`
+ );
+ }
log(`[switch] 直写失败(${e.code}),改用 osascript 委托写入`);
const bridge = path.join(dataDir, '.auth-switch-bridge.tmp');
const authBridge = AUTH_FILE + '.wbswitch.tmp';
diff --git a/scripts/list.js b/scripts/list.js
old mode 100755
new mode 100644
diff --git a/scripts/make-icon.py b/scripts/make-icon.py
new file mode 100644
index 0000000..f38a558
--- /dev/null
+++ b/scripts/make-icon.py
@@ -0,0 +1,58 @@
+#!/usr/bin/env python
+"""
+从 macOS AppIcon.icns 抽取的 PNG 图层,合成 Windows 多分辨率 .ico
+ICO 支持直接把 PNG 作为条目数据(Windows Vista+),因此无需解码 PNG。
+产出 release/WorkDaddy.ico,供桌面快捷方式 / 启动器使用。
+"""
+import os, struct
+
+ICON_DIR = os.path.join(os.path.dirname(__file__), "..", ".workbuddy", "tmp_icon")
+OUT = os.path.join(os.path.dirname(__file__), "..", "release", "WorkDaddy.ico")
+
+# (ico尺寸, 源png文件名) —— 从 icns 抽出、且尺寸匹配
+ENTRIES = [
+ (16, "ic11.png"),
+ (32, "ic12.png"),
+ (48, "ic12.png"), # 无 48 直接用 32 拉伸?ICO 无法自动拉伸,用同 32 会糊;改用 128
+ (256, "ic13.png"),
+]
+# 修正 48 -> 用 64/128 里没有;真实可用:32/256/512/1024。48 需要缩放,无 PIL 就跳过,
+# 用 32 重复会失真。改为:16,32,256,512 由 Windows 自动缩放。
+
+ENTRIES = [
+ (16, "ic11.png"),
+ (32, "ic12.png"),
+ (256, "ic13.png"),
+ (512, "ic09.png"),
+]
+
+def main():
+ # 读取所有条目 PNG
+ datas = []
+ for size, name in ENTRIES:
+ p = os.path.join(ICON_DIR, name)
+ b = open(p, "rb").read()
+ # 校验 PNG 尺寸
+ w, h = struct.unpack(">II", b[16:24])
+ assert w == h == size, f"{name} is {w}x{h}, expected {size}"
+ datas.append((size, b))
+
+ # ICO header
+ header = struct.pack("<HHH", 0, 1, len(datas))
+ # dir entries: width,height(0=256),colorcount,reserved,planes,bitcount,bytesinres,offset
+ offset = 6 + 16 * len(datas)
+ entries = b""
+ for size, b in datas:
+ wbyte = 0 if size >= 256 else size
+ hbyte = 0 if size >= 256 else size
+ entries += struct.pack("<BBBBHHII", wbyte, hbyte, 0, 0, 1, 32, len(b), offset)
+ offset += len(b)
+
+ out = header + entries + b"".join(b for _, b in datas)
+ os.makedirs(os.path.dirname(OUT), exist_ok=True)
+ with open(OUT, "wb") as f:
+ f.write(out)
+ print("ICO written:", os.path.abspath(OUT), os.path.getsize(OUT), "bytes, entries:", [s for s, _ in datas])
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/make-setup.cmd b/scripts/make-setup.cmd
new file mode 100644
index 0000000..141ed39
--- /dev/null
+++ b/scripts/make-setup.cmd
@@ -0,0 +1,60 @@
+@echo off
+rem ============================================================
+rem WorkDaddy Windows 自解压安装包生成脚本
+rem 用法:在仓库根目录双击 / 运行本脚本,产出 release\WorkDaddy-Setup.exe
+rem 产物:双击运行即可自动安装 + 创建桌面图标(无需任何编译器,仅用系统自带 IExpress)
+rem ============================================================
+setlocal
+chcp 65001 >nul
+cd /d "%~dp0..\.." rem 定位到仓库根目录
+
+set "SCRIPTS_DIR=%~dp0" rem scripts\ 的绝对路径(带尾部反斜杠)
+set "SED_TEMPLATE=%~dp0win\setup.sed"
+set "SED_TMP=%TEMP%\workdaddy-setup.sed"
+set "OUT=release\WorkDaddy-Setup.exe"
+set "VERSION="
+
+rem ---- 读取 daemon.js 里的版本号(DAEMON_VERSION = 'x.y.z')
+for /f "usebackq tokens=2 delims='" %%v in (`findstr /c:"DAEMON_VERSION = '" "%~dp0daemon.js"`) do set "VERSION=%%v"
+if not defined VERSION set "VERSION=0.0.0"
+echo 版本: %VERSION%
+
+rem ---- 校验源目录与 iexpress
+if not exist "%SCRIPTS_DIR%install-win.cmd" (
+ echo 错误:找不到 install-win.cmd,请从仓库 scripts 同级目录运行。
+ exit /b 1
+)
+if not exist "%SystemRoot%\System32\iexpress.exe" (
+ echo 错误:系统缺少 iexpress.exe(Windows 10/11 均自带,但可能被精简)。
+ exit /b 2
+)
+
+rem ---- 用真实路径填充 SED 模板
+(
+ for /f "usebackq delims=" %%L in ("%SED_TEMPLATE%") do (
+ set "LINE=%%L"
+ setlocal enabledelayedexpansion
+ set "LINE=!LINE:__SCRIPTS_DIR__=%SCRIPTS_DIR%!"
+ set "LINE=!LINE:__VERSION__=%VERSION%!"
+ echo !LINE!
+ endlocal
+ )
+) > "%SED_TMP%"
+
+rem ---- 调用 IExpress 生成自解压安装包
+echo 正在打包为 Setup.exe ...
+set "OUT_FULL=%CD%\%OUT%"
+if exist "%OUT_FULL%" del /q "%OUT_FULL%"
+iexpress /N /Q "%SED_TMP%"
+if not exist "%OUT_FULL%" (
+ echo 错误:未生成安装包,请确认 IExpress 运行成功。
+ exit /b 3
+)
+
+echo.
+echo ============================================================
+echo 生成完成:%OUT_FULL%
+echo 用法:发给用户双击 WorkDaddy-Setup.exe,即自动安装并创建桌面图标。
+echo 卸载:运行 %LOCALAPPDATA%\Programs\WorkDaddy\scripts\uninstall-win.ps1
+echo ============================================================
+pause
diff --git a/scripts/relaunch-with-cdp.sh b/scripts/relaunch-with-cdp.sh
old mode 100755
new mode 100644
diff --git a/scripts/switch.js b/scripts/switch.js
old mode 100755
new mode 100644
diff --git a/scripts/sync.js b/scripts/sync.js
old mode 100755
new mode 100644
diff --git a/scripts/theme-patches.js b/scripts/theme-patches.js
index 654682c..7fc0136 100644
--- a/scripts/theme-patches.js
+++ b/scripts/theme-patches.js
@@ -397,4 +397,9 @@ module.exports = [
desc: 'chat widget 内层容器 _widgetContainer(_widgetRendererWrapper 毛玻璃内部)改透明背景(用户要求):透出外层毛玻璃,避免双层实底',
css: 'html[data-theme="dark"] body[data-vscode-theme-name] [class*="_widgetRendererWrapper_"] [class*="_widgetContainer_"]{background:transparent !important;background-color:transparent !important;}',
},
+ {
+ id: 'patch-80',
+ desc: 'chat widget 预览 iframe 背景改透明(用户要求):widget 容器内的 iframe 在深色下自带黑底(元素级背景),改透明让外层毛玻璃透出;iframe 内部文档自带黑底由 inject.js 同源注入兜底(跨域内部无法用 CSS 触达)',
+ css: 'html[data-theme="dark"] body[data-vscode-theme-name] [class*="_widgetRendererWrapper_"] iframe,html[data-theme="dark"] body[data-vscode-theme-name] [class*="_widgetContainer_"] iframe,html[data-theme="dark"] body[data-vscode-theme-name] [class*="_widgetRendererWrapper_"] iframe[class*="chromeless"]{background:transparent !important;background-color:transparent !important;border:none !important;box-shadow:none !important;}',
+ },
];
diff --git a/scripts/uninstall-win.ps1 b/scripts/uninstall-win.ps1
new file mode 100644
index 0000000..aa1d44c
--- /dev/null
+++ b/scripts/uninstall-win.ps1
@@ -0,0 +1,53 @@
+# WorkDaddy Windows 卸载脚本(uninstall.sh 的 Windows 对应物)
+# 用法:powershell -ExecutionPolicy Bypass -File uninstall-win.ps1
+# 默认保留备份数据(%APPDATA%\WorkDaddy);加 -RemoveData 一并删除。
+param(
+ [switch]$RemoveData,
+ [string]$AppDir = (Join-Path $env:LOCALAPPDATA 'Programs\WorkDaddy')
+)
+
+$ErrorActionPreference = 'Continue'
+$dataDir = Join-Path $env:APPDATA 'WorkDaddy'
+
+Write-Host '卸载 WorkDaddy...'
+
+# 1) 移除登录自启
+try {
+ Remove-ItemProperty -Path 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Run' -Name 'WorkDaddy' -ErrorAction SilentlyContinue
+ Write-Host ' 已移除登录自启项'
+} catch {}
+
+# 2) 停止 watchdog + daemon
+$pidFile = Join-Path $dataDir 'watchdog.pid'
+if (Test-Path $pidFile) {
+ try {
+ $wpid = [int]((Get-Content $pidFile -Raw).Trim())
+ if ($wpid -gt 0) { taskkill /F /T /PID $wpid 2>$null | Out-Null }
+ } catch {}
+}
+foreach ($line in (netstat -ano | Select-String (':4783\d\s') | Select-String 'LISTENING')) {
+ $parts = ($line.ToString().Trim() -split '\s+')
+ $pid2 = $parts[$parts.Count - 1]
+ if ($pid2 -match '^\d+$') { taskkill /F /T /PID $pid2 2>$null | Out-Null }
+}
+
+# 3) 删除安装目录
+if (Test-Path $AppDir) {
+ Remove-Item -Recurse -Force $AppDir -ErrorAction SilentlyContinue
+ Write-Host (' 已删除安装目录: ' + $AppDir)
+}
+
+# 4) 数据目录(可选)
+if ($RemoveData) {
+ if (Test-Path $dataDir) {
+ Remove-Item -Recurse -Force $dataDir -ErrorAction SilentlyContinue
+ Write-Host (' 已删除数据目录(含账号备份): ' + $dataDir)
+ }
+} else {
+ Write-Host (' 已保留备份数据(含账号备份): ' + $dataDir)
+}
+
+Write-Host '卸载完成。'
+if (-not $RemoveData) {
+ Write-Host '如需同时删除账号备份,请重新运行:uninstall-win.ps1 -RemoveData'
+}
\ No newline at end of file
diff --git a/scripts/uninstall.sh b/scripts/uninstall.sh
old mode 100755
new mode 100644
diff --git a/scripts/verify-win.cmd b/scripts/verify-win.cmd
new file mode 100644
index 0000000..5e24632
--- /dev/null
+++ b/scripts/verify-win.cmd
@@ -0,0 +1,112 @@
+@echo off
+rem ============================================================
+rem WorkDaddy Windows 安装包自检脚本(双击运行)
+rem 作用:验证 Setup.exe / zip 解出的 scripts 是否「完整、可装、可启动」
+rem 不修改任何系统状态,纯只读检查,可放心重复运行。
+rem ============================================================
+setlocal
+chcp 65001 >nul
+cd /d "%~dp0"
+set "SCRIPT_DIR=%~dp0"
+
+echo ============================================================
+echo WorkDaddy 安装包自检
+echo ============================================================
+
+set "FAIL=0"
+
+rem ---- 1) 关键文件齐全 ----
+echo.
+echo [1/6] 检查关键文件...
+for %%F in (daemon.js lib.js watchdog.js win-launcher.js inject.js theme-patches.js launcher.cmd install-win.cmd install-win.ps1 win\setup.sed) do (
+ if not exist "%SCRIPT_DIR%%%F" (
+ echo 缺失: %%~F
+ set /a FAIL+=1
+ )
+)
+if exist "%SCRIPT_DIR%daemon.js" echo 核心 daemon.js 存在
+rem 顶层一键安装/启动入口(zip 根,staging 打包时复制到 install 目录根)
+if exist "%SCRIPT_DIR%..\Install-WorkDaddy.cmd" (
+ echo 顶层入口 Install-WorkDaddy.cmd 存在
+) else (
+ echo 提示: 顶层 Install-WorkDaddy.cmd 未就位(打包时从 scripts\ 提升到 zip 根)
+)
+if exist "%SCRIPT_DIR%..\Start-WorkDaddy.cmd" echo 顶层入口 Start-WorkDaddy.cmd 存在
+if not exist "%SCRIPT_DIR%node_modules\ws\index.js" (
+ echo 警告: node_modules\ws 缺失(DevTools 代理降级,其他功能不受影响)
+)
+
+rem ---- 2) node 运行时可达性 ----
+echo.
+echo [2/6] 检查 node 运行时...
+set "NODE="
+for /d %%d in ("%USERPROFILE%\.workbuddy\binaries\node\versions\*") do (
+ if exist "%%d\node.exe" set "NODE=%%d\node.exe"
+)
+if not defined NODE set "NODE=node"
+"%NODE%" --version >nul 2>&1
+if errorlevel 1 (
+ echo 错误: 找不到可用的 node(不能启动守护进程)
+ set /a FAIL+=1
+) else (
+ echo 可用: %NODE%
+)
+
+rem ---- 3) 脚本语法静态检查(node --check,不执行)----
+echo.
+echo [3/6] 校验 JS 语法...
+for %%F in (daemon.js lib.js watchdog.js win-launcher.js inject.js theme-patches.js) do (
+ "%NODE%" --check "%SCRIPT_DIR%%%F" >nul 2>&1
+ if errorlevel 1 (
+ echo 语法错误: %%~F
+ set /a FAIL+=1
+ )
+)
+echo JS 语法检查完成
+
+rem ---- 4) PS1 合法性(PowerShell 解析但不执行)----
+echo.
+echo [4/6] 校验 PS1 脚本语法...
+for %%F in (install-win.ps1) do (
+ powershell -NoProfile -ExecutionPolicy Bypass -Command "$e=$null; [void][System.Management.Automation.Language.Parser]::ParseFile('%SCRIPT_DIR%%%F',[ref]$null,[ref]$e); if($e){Write-Host (' 语法错误: ' + $e.Message); exit 1} else {Write-Host (' OK: ' + '%%~nF')}; exit 0" >nul 2>&1
+ if errorlevel 1 (
+ echo 语法错误: %%~F
+ set /a FAIL+=1
+ )
+)
+
+rem ---- 5) 自启注册表与安装目录回写测试(读态 + 安装目录可写性探测)----
+echo.
+echo [5/6] 检查安装目标可写 + 自启状态...
+set "APPDIR=%LOCALAPPDATA%\Programs\WorkDaddy"
+if exist "%APPDIR%\scripts\daemon.js" (
+ echo 已安装版本: "%APPDIR%" 存在
+) else (
+ echo 未安装(首次安装前状态正常)
+)
+echo LOCALAPPDATA=%LOCALAPPDATA%
+if not exist "%LOCALAPPDATA%" (
+ echo 警告: LOCALAPPDATA 不可访问,可能影响安装
+)
+
+rem ---- 6) 桌面图标/WorkBuddy 现状(只读)----
+echo.
+echo [6/6] 检查 WorkBuddy 与桌面图标...
+tasklist 2>nul | findstr /i "WorkBuddy" >nul && (
+ echo WorkBuddy 正在运行
+) || (
+ echo WorkBuddy 未运行(安装时会以调试模式拉起)
+)
+if exist "%USERPROFILE%\Desktop\WorkDaddy.lnk" (
+ echo 桌面已有 WorkDaddy 图标
+)
+
+echo.
+echo ============================================================
+if "%FAIL%"=="0" (
+ echo 自检通过:本包可用于 Windows 安装。
+) else (
+ echo 发现 %FAIL% 处问题,请在下方对照修正后再分发。
+)
+echo ============================================================
+pause
diff --git a/scripts/watchdog.js b/scripts/watchdog.js
new file mode 100644
index 0000000..cb5c064
--- /dev/null
+++ b/scripts/watchdog.js
@@ -0,0 +1,112 @@
+#!/usr/bin/env node
+/**
+ * WorkDaddy Windows 守护进程(对应 macOS launchd 的 KeepAlive 能力)
+ *
+ * 职责:spawn daemon.js 并常驻监听;daemon 崩溃/退出后自动拉起(指数退避防抖)。
+ * 单实例:PID 文件锁(%DATA_DIR%\watchdog.pid),重复启动直接退出。
+ * 更新流程:apply-update.ps1 先按 PID 杀本进程,再做文件替换。
+ *
+ * 用法: node watchdog.js
+ * node watchdog.js stop # 停止:杀 daemon + 退出自己
+ */
+'use strict';
+
+const fs = require('fs');
+const path = require('path');
+const os = require('os');
+const { spawn } = require('child_process');
+
+const SCRIPTS_DIR = __dirname;
+const DATA_DIR =
+ process.env.WBSWITCH_DATA_DIR ||
+ path.join(process.env.APPDATA || path.join(os.homedir(), 'AppData', 'Roaming'), 'WorkDaddy');
+const PID_FILE = path.join(DATA_DIR, 'watchdog.pid');
+const LOG_FILE = path.join(DATA_DIR, 'watchdog.log');
+
+function log(...args) {
+ const line = `[${new Date().toISOString()}] ${args.join(' ')}\n`;
+ try {
+ fs.appendFileSync(LOG_FILE, line);
+ } catch (_) {}
+ // 前台运行时也输出(便于手动调试)
+ try { process.stdout.write(line); } catch (_) {}
+}
+
+/** 读取 PID 文件并检测进程是否存活(Windows: tasklist /FI) */
+function pidFileAlive() {
+ try {
+ const pid = parseInt(fs.readFileSync(PID_FILE, 'utf8').trim(), 10);
+ if (!pid || pid === process.pid) return false;
+ const r = require('child_process').spawnSync(
+ 'tasklist',
+ ['/FI', 'PID eq ' + pid, '/FO', 'CSV', '/NH'],
+ { encoding: 'utf8', timeout: 5000, windowsHide: true }
+ );
+ return r.status === 0 && /node/i.test(r.stdout);
+ } catch (_) {
+ return false;
+ }
+}
+
+if (process.argv.includes('stop')) {
+ log('收到 stop 指令,退出中...');
+ try {
+ const pid = parseInt(fs.readFileSync(PID_FILE, 'utf8').trim(), 10);
+ if (pid && pid !== process.pid) {
+ require('child_process').spawnSync('taskkill', ['/F', '/T', '/PID', String(pid)], { stdio: 'ignore', windowsHide: true });
+ }
+ } catch (_) {}
+ try { fs.unlinkSync(PID_FILE); } catch (_) {}
+ process.exit(0);
+}
+
+// 单实例保护
+if (pidFileAlive()) {
+ log('已有 watchdog 实例在运行,本实例退出');
+ process.exit(0);
+}
+
+fs.mkdirSync(DATA_DIR, { recursive: true });
+fs.writeFileSync(PID_FILE, String(process.pid));
+
+let child = null;
+let stopping = false;
+let restartDelay = 3000; // 初始 3s,连续崩溃递增,上限 60s
+
+function startDaemon() {
+ if (stopping) return;
+ const node = process.execPath;
+ const args = ['--experimental-sqlite', path.join(SCRIPTS_DIR, 'daemon.js')];
+ log('启动 daemon: ' + node + ' ' + args.join(' '));
+ child = spawn(node, args, { stdio: 'ignore', windowsHide: true, env: process.env });
+ child.on('error', (e) => {
+ log('daemon 启动错误: ' + e.message);
+ });
+ child.on('exit', (code, signal) => {
+ child = null;
+ if (stopping) { log('daemon 已退出(watchdog 停止中)'); return; }
+ log('daemon 退出 code=' + code + ' signal=' + signal + ',' + restartDelay + 'ms 后重启');
+ setTimeout(startDaemon, restartDelay);
+ restartDelay = Math.min(restartDelay * 2, 60000);
+ });
+ // 正常存活 60s 后重置退避
+ setTimeout(() => { restartDelay = 3000; }, 60000);
+}
+
+startDaemon();
+
+// 优雅停止:外部 kill(更新前)或 Ctrl+C
+function shutdown() {
+ if (stopping) return;
+ stopping = true;
+ log('watchdog 收到停止信号,结束 daemon');
+ if (child) {
+ try { child.kill(); } catch (_) {}
+ }
+ setTimeout(() => {
+ try { fs.unlinkSync(PID_FILE); } catch (_) {}
+ process.exit(0);
+ }, 800);
+}
+process.on('SIGTERM', shutdown);
+process.on('SIGINT', shutdown);
\ No newline at end of file
diff --git a/scripts/win-inject-helper.js b/scripts/win-inject-helper.js
new file mode 100644
index 0000000..bc9fa1e
--- /dev/null
+++ b/scripts/win-inject-helper.js
@@ -0,0 +1,47 @@
+#!/usr/bin/env node
+/**
+ * WorkDaddy 提权注入助手(win-launcher.js 的成人版重跑)
+ *
+ * 背景:WorkBuddy 常装在 C:\Program Files(受 UAC 保护的特权目录)。
+ * 要给它带上 --remote-debugging-port 重启并注入组件,必须拥有管理员权限。
+ * 普通权限启动 launcher 时无法完成这一步(表现为黑屏空转、9222 起不来)。
+ *
+ * 本助手由 win-launcher.js 通过 Start-Process -Verb RunAs 以管理员身份拉起:
+ * 1) 转交系统里真实的 win-launcher.js 继续执行(此时进程已是管理员)
+ * 2) launcher 检测 to isElevated()=true,会正常走"杀 WorkBuddy → 带参重启 → 注入"
+ *
+ * 用法(仅内部):
+ * node win-inject-helper.js [cdpPort]
+ * 通常由 launcher 派发,无需用户直接运行。
+ */
+'use strict';
+
+const path = require('path');
+const { spawnSync } = require('child_process');
+
+// 复用同一份 main 逻辑:以管理员身份重跑 win-launcher.js
+// 传参 --inject-helper 会让 win-launcher 知道"正在提权流程中,别二次派发",
+// 避免死循环。win-launcher 在 isElevated() 为 true 且带本标志时直接执行注入。
+const LAUNCHER = path.join(__dirname, 'win-launcher.js');
+
+// 校验当前确实是管理员
+let elevated = false;
+try {
+ elevated = spawnSync('net', ['session'], { stdio: 'ignore', windowsHide: true, timeout: 8000 }).status === 0;
+} catch (_) {}
+
+if (!elevated) {
+ console.error('错误:win-inject-helper 必须以管理员身份运行。');
+ process.exit(2);
+}
+
+// Windows 下重新分配一个真正的控制台窗口过于复杂;直接静默继续
+// (launcher 会负责日志与提示)。把它作为子进程跑完。
+const args = ['--inject-helper'];
+const cp = spawnSync(process.execPath, [LAUNCHER, ...args], {
+ stdio: 'inherit',
+ windowsHide: true,
+ timeout: 90000,
+});
+
+process.exit(cp.status === null ? 1 : cp.status);
diff --git a/scripts/win-launcher.js b/scripts/win-launcher.js
new file mode 100644
index 0000000..345c094
--- /dev/null
+++ b/scripts/win-launcher.js
@@ -0,0 +1,325 @@
+#!/usr/bin/env node
+/**
+ * WorkDaddy Windows 启动器(macOS launcher 的 Windows 对应物,node 实现)
+ *
+ * 幂等三步:
+ * 1) 确保 daemon 运行 —— watchdog 常驻(崩溃自动拉起);daemon 版本与内置不一致时强制重启
+ * 2) WorkBuddy 已在 CDP 模式(9222)→ 直接注入组件即完成
+ * 3) 否则退出 WorkBuddy 并以 --remote-debugging-port=9222 重启 → 等端口 → 注入
+ *
+ * 由 launcher.cmd 调用(cmd 负责兜底找 node),也可 node win-launcher.js 直接运行。
+ * 所有操作用户态完成(HKCU / %LOCALAPPDATA% / %APPDATA%),无需管理员权限。
+ */
+'use strict';
+
+const fs = require('fs');
+const path = require('path');
+const os = require('os');
+const net = require('net');
+const http = require('http');
+const { spawn, spawnSync } = require('child_process');
+
+const SCRIPTS_DIR = __dirname;
+const DATA_DIR =
+ process.env.WBSWITCH_DATA_DIR ||
+ path.join(process.env.APPDATA || path.join(os.homedir(), 'AppData', 'Roaming'), 'WorkDaddy');
+const UI_PORT = parseInt(process.env.WBSWITCH_PORT || '47832', 10);
+const CDP_PORT = parseInt(process.env.WBSWITCH_CDP_PORT || '9222', 10);
+
+function log(...args) {
+ const line = `[launcher] ${new Date().toISOString()} ${args.join(' ')}\n`;
+ try { process.stdout.write(line); } catch (_) {}
+ try { fs.appendFileSync(path.join(DATA_DIR, 'launcher.log'), line); } catch (_) {}
+}
+
+// ---------- 小工具 ----------
+function sleep(ms) { return new Promise((r) => setTimeout(r, ms)); }
+
+// 当前进程是否为管理员(Windows)
+function isElevated() {
+ try {
+ const r = spawnSync(
+ 'net', ['session'], { stdio: 'ignore', windowsHide: true, timeout: 8000 }
+ );
+ return r.status === 0;
+ } catch (_) { return false; }
+}
+
+// 以管理员身份运行"重启注入助手"(child 脚本),launcher 本体保持普通权限。
+// 返回是否已成功派发(派发后 launcher 立即退出,由助手完成真正的重启+注入)。
+function spawnElevatedHelper() {
+ const nodeBin = process.execPath; // 当前 node
+ const childJs = path.join(SCRIPTS_DIR, 'win-inject-helper.js');
+ if (!fs.existsSync(childJs)) return false;
+ const ps = [
+ '-NoProfile', '-ExecutionPolicy', 'Bypass',
+ '-Command',
+ 'Start-Process -FilePath "' + nodeBin.replace(/"/g, '\\"') + '" ' +
+ '-ArgumentList @("--inject-helper","' + childJs + '",' + CDP_PORT + ') ' +
+ '-Verb RunAs'
+ ];
+ try {
+ spawnSync('powershell', ps, { stdio: 'ignore', windowsHide: true, timeout: 15000 });
+ return true;
+ } catch (_) { return false; }
+}
+
+function portOpen(port) {
+ return new Promise((resolve) => {
+ const s = net.connect({ port, host: '127.0.0.1' });
+ const t = setTimeout(() => { s.destroy(); resolve(false); }, 1200);
+ s.on('connect', () => { clearTimeout(t); s.destroy(); resolve(true); });
+ s.on('error', () => { clearTimeout(t); resolve(false); });
+ });
+}
+
+function httpGet(port, p) {
+ return new Promise((resolve) => {
+ const req = http.get({ host: '127.0.0.1', port, path: p, timeout: 1500 }, (res) => {
+ let body = '';
+ res.on('data', (c) => (body += c));
+ res.on('end', () => resolve({ status: res.statusCode, body }));
+ });
+ req.on('timeout', () => { req.destroy(); resolve(null); });
+ req.on('error', () => resolve(null));
+ });
+}
+
+function httpPost(port, p) {
+ return new Promise((resolve) => {
+ const req = http.request({ host: '127.0.0.1', port, path: p, method: 'POST', timeout: 1500 }, (res) => {
+ res.resume();
+ res.on('end', () => resolve({ status: res.statusCode }));
+ });
+ req.on('timeout', () => { req.destroy(); resolve(null); });
+ req.on('error', () => resolve(null));
+ req.end();
+ });
+}
+
+function psOut(cmd) {
+ try {
+ return spawnSync('powershell', ['-NoProfile', '-Command', cmd], {
+ encoding: 'utf8', timeout: 10000, windowsHide: true,
+ }).stdout || '';
+ } catch (_) { return ''; }
+}
+
+function readDaemonVersion() {
+ try {
+ const src = fs.readFileSync(path.join(SCRIPTS_DIR, 'daemon.js'), 'utf8');
+ const m = src.match(/DAEMON_VERSION\s*=\s*'([^']+)'/);
+ return m ? m[1] : '';
+ } catch (_) { return ''; }
+}
+
+// ---------- 定位 node(托管优先:.workbuddy\binaries\node\versions\<v>\node.exe,其次 PATH) ----------
+function findNode() {
+ const base = path.join(os.homedir(), '.workbuddy', 'binaries', 'node', 'versions');
+ let verDirs = [];
+ try {
+ verDirs = fs.readdirSync(base)
+ .map((d) => path.join(base, d, 'node.exe'))
+ .filter((p) => fs.existsSync(p))
+ .sort();
+ } catch (_) {}
+ if (verDirs.length) return verDirs[verDirs.length - 1];
+ try {
+ const r = spawnSync('node', ['-v'], { encoding: 'utf8', timeout: 3000, windowsHide: true });
+ if (r.status === 0) return 'node';
+ } catch (_) {}
+ return null;
+}
+
+// ---------- 定位 WorkBuddy.exe(环境变量 > 运行进程 > 注册表 > 常见路径) ----------
+let wbBinaryCache = null;
+function findWorkBuddy() {
+ if (wbBinaryCache) return wbBinaryCache;
+ const tryFile = (p) => { try { if (p && fs.existsSync(p)) return p; } catch (_) {} return null; };
+ const envBin = tryFile(process.env.WBSWITCH_WORKBUDDY_BIN);
+ if (envBin) return (wbBinaryCache = envBin);
+ try {
+ const p = psOut('Get-Process WorkBuddy -ErrorAction SilentlyContinue | Select-Object -First 1 -ExpandProperty Path').split(/\r?\n/).filter(Boolean).pop();
+ const hit = tryFile(p);
+ if (hit) return (wbBinaryCache = hit);
+ } catch (_) {}
+ try {
+ const p = psOut("$k=@('HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*','HKLM:\\SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*','HKCU:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*'); Get-ItemProperty $k -ErrorAction SilentlyContinue | Where-Object { $_.DisplayName -match 'WorkBuddy|CodeBuddy' } | Select-Object -First 1 DisplayIcon,InstallLocation | ForEach-Object { if($_.DisplayIcon){ ($_.DisplayIcon -replace ',.*$','').Trim() } elseif($_.InstallLocation){ Join-Path $_.InstallLocation 'WorkBuddy.exe' } }").split(/\r?\n/).filter(Boolean).pop();
+ const hit = tryFile(p);
+ if (hit) return (wbBinaryCache = hit);
+ } catch (_) {}
+ for (const c of [
+ path.join(process.env.LOCALAPPDATA || '', 'Programs', 'WorkBuddy', 'WorkBuddy.exe'),
+ path.join(process.env.ProgramFiles || '', 'WorkBuddy', 'WorkBuddy.exe'),
+ path.join(process.env['ProgramFiles(x86)'] || '', 'WorkBuddy', 'WorkBuddy.exe'),
+ 'D:\\workbody\\WorkBuddy\\WorkBuddy.exe',
+ ]) {
+ const hit = tryFile(c);
+ if (hit) return (wbBinaryCache = hit);
+ }
+ return null;
+}
+
+// ---------- 1. 确保 daemon 运行 ----------
+function watchdogAlive() {
+ try {
+ const pid = parseInt(fs.readFileSync(path.join(DATA_DIR, 'watchdog.pid'), 'utf8').trim(), 10);
+ if (!pid) return false;
+ const r = spawnSync('tasklist', ['/FI', 'PID eq ' + pid, '/FO', 'CSV', '/NH'], { encoding: 'utf8', timeout: 5000, windowsHide: true });
+ return r.status === 0 && /node/i.test(r.stdout);
+ } catch (_) { return false; }
+}
+
+function daemonRunning() {
+ return portOpen(UI_PORT);
+}
+
+async function ensureDaemon(nodeBin) {
+ fs.mkdirSync(path.join(DATA_DIR, 'accounts'), { recursive: true });
+ // 已有 daemon:检查版本一致性(旧版本代码继续注入会出兼容问题)
+ const st = await httpGet(UI_PORT, '/api/status');
+ if (st && st.status === 200) {
+ let runningVer = '';
+ try { runningVer = (JSON.parse(st.body).version || ''); } catch (_) {}
+ const want = readDaemonVersion();
+ if (runningVer === want) {
+ log('daemon 已在运行且版本一致 (' + runningVer + '),跳过启动');
+ return true;
+ }
+ log('检测到旧版 daemon (' + runningVer + ' != ' + want + '),强制重启');
+ stopDaemonByPort();
+ } else if (watchdogAlive()) {
+ log('watchdog 在运行但 daemon 未就绪,等待其拉起...');
+ for (let i = 0; i < 20; i++) {
+ await sleep(500);
+ if (daemonRunning()) { log('daemon 已就绪'); return true; }
+ }
+ log('等待超时,主动拉起 watchdog');
+ }
+ // 启动 watchdog(它负责启动 daemon + 崩溃拉起)
+ if (!watchdogAlive()) {
+ log('启动 watchdog: ' + nodeBin);
+ const child = spawn(nodeBin, [path.join(SCRIPTS_DIR, 'watchdog.js')], { detached: true, stdio: 'ignore', windowsHide: true });
+ child.unref();
+ }
+ for (let i = 0; i < 30; i++) {
+ await sleep(400);
+ if (daemonRunning()) { log('daemon 已就绪'); return true; }
+ }
+ log('等待 daemon 就绪超时');
+ return daemonRunning();
+}
+
+function stopDaemonByPort() {
+ // 杀 watchdog(会连带杀 daemon)→ 兜底按端口杀
+ try {
+ const pid = parseInt(fs.readFileSync(path.join(DATA_DIR, 'watchdog.pid'), 'utf8').trim(), 10);
+ if (pid) spawnSync('taskkill', ['/F', '/T', '/PID', String(pid)], { stdio: 'ignore', windowsHide: true });
+ try { fs.unlinkSync(path.join(DATA_DIR, 'watchdog.pid')); } catch (_) {}
+ } catch (_) {}
+ // 兜底:杀监听 UI 端口的进程
+ const out = spawnSync('netstat', ['-ano'], { encoding: 'utf8', timeout: 8000, windowsHide: true }).stdout || '';
+ const lines = out.split(/\r?\n/).filter((l) => l.includes(':' + UI_PORT) && /LISTENING/i.test(l));
+ const pids = new Set();
+ for (const l of lines) {
+ const m = l.trim().split(/\s+/);
+ const pid = m[m.length - 1];
+ if (pid && /^\d+$/.test(pid)) pids.add(pid);
+ }
+ for (const pid of pids) {
+ spawnSync('taskkill', ['/F', '/T', '/PID', pid], { stdio: 'ignore', windowsHide: true });
+ }
+ return pids.size > 0;
+}
+
+// ---------- 2/3. WorkBuddy CDP 处理 ----------
+function quitWorkBuddy() {
+ return new Promise((resolve) => {
+ let done = false;
+ const finish = () => { if (!done) { done = true; resolve(); } };
+ const run = (args) => {
+ const p = spawn('taskkill', args, { stdio: 'ignore', windowsHide: true });
+ p.on('error', finish);
+ p.on('exit', () => setTimeout(finish, 700));
+ };
+ run(['/IM', 'WorkBuddy.exe']);
+ setTimeout(() => { if (!done) run(['/F', '/T', '/IM', 'WorkBuddy.exe']); }, 2500);
+ setTimeout(finish, 8000);
+ });
+}
+
+async function injectNow() {
+ // daemon 的 /api/inject 是 POST
+ try { await httpPost(UI_PORT, '/api/inject'); } catch (_) {}
+}
+
+// ---------- main ----------
+(async () => {
+ const nodeBin = findNode();
+ if (!nodeBin) {
+ log('未找到 Node.js(需 .workbuddy\\binaries 托管 node 或 PATH 中的 node)');
+ console.error('错误:未找到 Node.js。请先安装 Node.js 或安装 WorkBuddy(自带托管 node)。');
+ process.exit(1);
+ }
+
+ await ensureDaemon(nodeBin);
+
+ // 已在 CDP 模式 → 幂等注入
+ if (await portOpen(CDP_PORT)) {
+ await injectNow();
+ log('WorkBuddy 已在调试模式(端口 ' + CDP_PORT + '),组件已注入');
+ console.log('WorkDaddy:WorkBuddy 已在调试模式,组件已注入 ✓');
+ process.exit(0);
+ }
+
+ // 未开 CDP → 需要重启 WorkBuddy 带调试端口
+ const wb = findWorkBuddy();
+ if (!wb) {
+ console.error('未找到 WorkBuddy.exe。可用环境变量 WBSWITCH_WORKBUDDY_BIN 指定完整路径。');
+ log('未找到 WorkBuddy.exe');
+ process.exit(2);
+ }
+
+ // WorkBuddy 常装在 C:\Program Files(受保护特权目录),重启它需要管理员权限。
+ // 若当前非管理员:派发提权助手(触发一次 UAC)后立即退出,由助手完成重启+注入,
+ // 避免普通双击时卡在黑屏空转等 20 秒。
+ if (!isElevated()) {
+ log('非管理员权限:派发提权助手重启 WorkBuddy(唤醒 UAC)');
+ console.log('需要管理员权限以重启 WorkBuddy 进入调试模式,正在请求授权...');
+ if (spawnElevatedHelper()) {
+ console.log('已发起提权请求,点击 UAC「是」后将自动完成重启与注入。');
+ process.exit(0);
+ }
+ // 派发失败则仍退回当前进程尝试(容错)
+ log('提权派发失败,退回当前进程直接重启');
+ }
+
+ log('重启 WorkBuddy(带 --remote-debugging-port=' + CDP_PORT + '): ' + wb);
+ console.log('正在以调试模式重启 WorkBuddy(约几秒)...');
+
+ await quitWorkBuddy();
+ await sleep(500);
+ const child = spawn(wb, ['--remote-debugging-port=' + CDP_PORT], { detached: true, stdio: 'ignore', windowsHide: true });
+ child.on('error', (e) => { log('启动 WorkBuddy 失败: ' + e.message); });
+ child.unref();
+
+ let ok = false;
+ for (let i = 0; i < 20; i++) {
+ await sleep(1000);
+ if (await portOpen(CDP_PORT)) { ok = true; break; }
+ }
+ if (ok) {
+ await sleep(1500);
+ await injectNow();
+ log('WorkBuddy 已启动(调试模式),组件已注入');
+ console.log('WorkDaddy:WorkBuddy 已启动(调试模式),组件已注入 ✓');
+ } else {
+ log('等待 20 秒未检测到调试端口 ' + CDP_PORT);
+ console.log('等待超时:未检测到调试端口 ' + CDP_PORT + '。可手动执行:cd /d ' + path.dirname(wb) + ' && "' + wb + '" --remote-debugging-port=' + CDP_PORT);
+ }
+ process.exit(ok ? 0 : 3);
+})().catch((e) => {
+ log('launcher 异常: ' + (e && e.stack || e));
+ console.error('WorkDaddy 启动异常: ' + (e && e.message || e));
+ process.exit(4);
+});
\ No newline at end of file
diff --git a/scripts/win/probe/probe-windows.cmd b/scripts/win/probe/probe-windows.cmd
new file mode 100644
index 0000000..4cf3420
--- /dev/null
+++ b/scripts/win/probe/probe-windows.cmd
@@ -0,0 +1,23 @@
+@echo off
+rem WorkDaddy Windows 移植 - 环境探测入口
+rem 用法:把 probe-windows.cmd 和 probe-windows.ps1 放在同一目录,双击本文件即可
+rem 输出:桌面上的 WorkDaddy-Windows-Probe.log
+setlocal
+chcp 65001 >nul
+
+if not exist "%~dp0probe-windows.ps1" (
+ echo 错误:找不到 probe-windows.ps1,请把两个文件放在同一目录后重试。
+ pause
+ exit /b 1
+)
+
+echo ==============================================================
+echo WorkDaddy Windows 环境探测
+echo 正在采集信息,可能需要几秒到一分钟,请勿关闭窗口...
+echo ==============================================================
+
+powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0probe-windows.ps1"
+
+echo.
+echo 完成!日志已写入桌面:WorkDaddy-Windows-Probe.log
+pause
\ No newline at end of file
diff --git a/scripts/win/probe/probe-windows.ps1 b/scripts/win/probe/probe-windows.ps1
new file mode 100644
index 0000000..570f838
--- /dev/null
+++ b/scripts/win/probe/probe-windows.ps1
@@ -0,0 +1,258 @@
+# WorkDaddy Windows 移植 - 环境探测脚本
+# 用途:在安装了 WorkBuddy Windows 版的电脑上采集移植所需全部信息,
+# 输出日志到桌面 WorkDaddy-Windows-Probe.log
+# 兼容:Windows PowerShell 5.1+(Win10/11 自带),无需管理员权限
+# 原则:任何一条探测失败都只记 FAIL,绝不中断脚本
+
+$ErrorActionPreference = 'Continue'
+try { [Console]::OutputEncoding = [System.Text.Encoding]::UTF8 } catch {}
+
+$desktop = [Environment]::GetFolderPath('Desktop')
+$logFile = Join-Path $desktop 'WorkDaddy-Windows-Probe.log'
+
+$sb = New-Object System.Text.StringBuilder
+function Log([string]$s) { [void]$sb.AppendLine($s); Write-Host $s }
+function Section([string]$t) { Log ''; Log ('=' * 64); Log ('== ' + $t); Log ('=' * 64) }
+function Probe([string]$label, [scriptblock]$action) {
+ try {
+ $out = (& $action | Out-String).Trim()
+ if ($out) { Log ('[OK] ' + $label + ' => ' + $out) }
+ else { Log ('[OK] ' + $label + ' (空)') }
+ } catch {
+ Log ('[FAIL] ' + $label + ' : ' + $_.Exception.Message)
+ }
+}
+function Test-Port([int]$p) {
+ try {
+ $c = New-Object System.Net.Sockets.TcpClient
+ $iar = $c.BeginConnect('127.0.0.1', $p, $null, $null)
+ $ok = $iar.AsyncWaitHandle.WaitOne(400, $false)
+ $result = $false
+ if ($ok) { $result = $c.Connected }
+ $c.Close()
+ if ($result) { return 'OPEN' } else { return 'closed' }
+ } catch {
+ return 'error(' + $_.Exception.Message + ')'
+ }
+}
+
+Log '=============================================================='
+Log 'WorkDaddy Windows 移植 - 环境探测'
+Log '=============================================================='
+Log ('时间 : ' + (Get-Date -Format 'yyyy-MM-dd HH:mm:ss'))
+Log ('用户 : ' + $env:USERNAME)
+Log ('桌面 : ' + $desktop)
+
+Section '1. 系统信息'
+Probe 'OS 版本' {
+ $os = Get-CimInstance Win32_OperatingSystem -ErrorAction SilentlyContinue | Select-Object -First 1
+ if ($os) { $os.Caption + ' | Version ' + $os.Version + ' | ' + $os.OSArchitecture } else { '未知' }
+}
+Probe '处理器架构' { $env:PROCESSOR_ARCHITECTURE }
+Probe 'PowerShell 版本' { $PSVersionTable.PSVersion.ToString() }
+Probe '管理员权限' { ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) }
+Probe '系统语言' { try { (Get-WinSystemLocale).Name } catch { 'unknown' } }
+
+Section '2. Node.js 可用性'
+Probe 'node 命令' {
+ $c = Get-Command node -ErrorAction SilentlyContinue
+ if ($c) {
+ $v = (& node -v 2>$null)
+ $c.Source + ' v' + $v
+ } else { 'NOT_FOUND (PATH 中无 node)' }
+}
+Probe '常见 node 安装位置' {
+ $cands = @(
+ "$env:ProgramFiles\nodejs\node.exe",
+ "${env:ProgramFiles(x86)}\nodejs\node.exe",
+ "$env:LOCALAPPDATA\Programs\nodejs\node.exe",
+ "$env:APPDATA\npm\node.exe",
+ "$env:USERPROFILE\.workbuddy\binaries\node\versions\*\node.exe"
+ )
+ foreach ($c in $cands) {
+ $hit = Get-Item $c -ErrorAction SilentlyContinue
+ if ($hit) { ('{0} => 存在' -f $hit.FullName) } else { ('{0} => 不存在' -f $c) }
+ }
+}
+
+Section '3. WorkBuddy 进程'
+Probe '运行中的相关进程' {
+ $procs = Get-Process -ErrorAction SilentlyContinue |
+ Where-Object { $_.ProcessName -match 'WorkBuddy|CodeBuddy|Electron|crashpad' } |
+ Select-Object ProcessName, Id, Path | Format-Table -AutoSize | Out-String
+ if ($procs.Trim()) { $procs.Trim() } else { '无相关进程在运行' }
+}
+
+Section '4. WorkBuddy 安装位置'
+Probe '卸载注册表项(DisplayName 匹配)' {
+ $keys = @(
+ 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*',
+ 'HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*',
+ 'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*'
+ )
+ $items = Get-ItemProperty $keys -ErrorAction SilentlyContinue |
+ Where-Object { $_.DisplayName -match 'WorkBuddy|CodeBuddy' } |
+ Select-Object DisplayName, DisplayVersion, InstallLocation, DisplayIcon |
+ Format-List | Out-String
+ if ($items.Trim()) { $items.Trim() } else { '注册表中未找到' }
+}
+Probe '常见 exe 候选路径' {
+ $cands = @(
+ "$env:LOCALAPPDATA\Programs\WorkBuddy\WorkBuddy.exe",
+ "$env:LOCALAPPDATA\Programs\WorkBuddy\CodeBuddy.exe",
+ "$env:ProgramFiles\WorkBuddy\WorkBuddy.exe",
+ "${env:ProgramFiles(x86)}\WorkBuddy\WorkBuddy.exe",
+ "$env:LOCALAPPDATA\WorkBuddy\WorkBuddy.exe",
+ "$env:APPDATA\WorkBuddy\WorkBuddy.exe",
+ "$env:LOCALAPPDATA\CodeBuddy\CodeBuddy.exe",
+ "$env:LOCALAPPDATA\Programs\CodeBuddy\CodeBuddy.exe",
+ "$env:LOCALAPPDATA\Programs\CodeBuddy\WorkBuddy.exe"
+ )
+ foreach ($c in $cands) {
+ if (Test-Path $c) {
+ $vi = (Get-Item $c -ErrorAction SilentlyContinue).VersionInfo
+ ('{0} [存在] FileVersion={1} ProductVersion={2}' -f $c, $vi.FileVersion, $vi.ProductVersion)
+ } else {
+ ('{0} [不存在]' -f $c)
+ }
+ }
+}
+Probe 'LOCALAPPDATA\Programs 下的应用目录' {
+ $dir = "$env:LOCALAPPDATA\Programs"
+ if (Test-Path $dir) {
+ $names = Get-ChildItem $dir -Directory -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Name
+ if ($names) { ($names -join ', ') } else { '空' }
+ } else { '目录不存在' }
+}
+
+Section '5. auth 登录文件 (移植关键, 必须确认真实路径)'
+Probe 'APPDATA 下相关目录' {
+ $d = Get-ChildItem $env:APPDATA -Directory -Force -ErrorAction SilentlyContinue |
+ Where-Object { $_.Name -match 'CodeBuddy|WorkBuddy|WBWork' } | Select-Object -ExpandProperty FullName
+ if ($d) { ($d -join "`n") } else { '无' }
+}
+Probe 'LOCALAPPDATA 下相关目录' {
+ $d = Get-ChildItem $env:LOCALAPPDATA -Directory -Force -ErrorAction SilentlyContinue |
+ Where-Object { $_.Name -match 'CodeBuddy|WorkBuddy|WBWork' } | Select-Object -ExpandProperty FullName
+ if ($d) { ($d -join "`n") } else { '无' }
+}
+Probe '候选 auth 文件存在性' {
+ $cands = @(
+ "$env:APPDATA\CodeBuddyExtension\Data\Public\auth\workbuddy-desktop.info",
+ "$env:APPDATA\CodeBuddyExtension\Data\auth\workbuddy-desktop.info",
+ "$env:APPDATA\CodeBuddy\Data\Public\auth\workbuddy-desktop.info",
+ "$env:LOCALAPPDATA\CodeBuddyExtension\Data\Public\auth\workbuddy-desktop.info",
+ "$env:USERPROFILE\.workbuddy\auth\workbuddy-desktop.info",
+ "$env:USERPROFILE\.codebuddy\auth\workbuddy-desktop.info"
+ )
+ foreach ($c in $cands) { ('{0} => {1}' -f $c, (Test-Path $c)) }
+}
+Probe '递归搜索 workbuddy-desktop.info (APPDATA + LOCALAPPDATA, 深度12)' {
+ $found = @()
+ foreach ($r in @($env:APPDATA, $env:LOCALAPPDATA)) {
+ if (Test-Path $r) {
+ $found += Get-ChildItem $r -Recurse -Depth 12 -Filter 'workbuddy-desktop.info' -File -Force -ErrorAction SilentlyContinue |
+ Select-Object -First 5 -ExpandProperty FullName
+ }
+ }
+ if ($found.Count) { ($found -join "`n") } else { '未找到 (可能尚未登录过, 或路径不同)' }
+}
+Probe '递归搜索其他可能 auth 文件 (目录内找 *.info)' {
+ $found = @()
+ foreach ($r in @($env:APPDATA, $env:LOCALAPPDATA)) {
+ if (Test-Path $r) {
+ $found += Get-ChildItem $r -Recurse -Depth 8 -Filter '*.info' -File -Force -ErrorAction SilentlyContinue |
+ Where-Object { $_.Name -notmatch '^\$' } | Select-Object -First 10 -ExpandProperty FullName
+ }
+ }
+ if ($found.Count) { ($found -join "`n") } else { '无 *.info 文件' }
+}
+Probe 'CodeBuddyExtension 目录树结构(若存在)' {
+ $p = "$env:APPDATA\CodeBuddyExtension"
+ $alt = "$env:LOCALAPPDATA\CodeBuddyExtension"
+ $root = $null
+ if (Test-Path "$p\Data") { $root = $p } elseif (Test-Path "$alt\Data") { $root = $alt }
+ if ($root) {
+ Get-ChildItem $root -Recurse -Depth 5 -Force -ErrorAction SilentlyContinue |
+ Where-Object { $_.Name -match 'auth|Public|Data' } | Select-Object -First 20 -ExpandProperty FullName
+ } else { 'CodeBuddyExtension 目录不存在' }
+}
+
+Section '6. ~/.workbuddy 数据目录 (会话/设置)'
+Probe '.workbuddy 目录' { ('{0} => {1}' -f "$env:USERPROFILE\.workbuddy", (Test-Path "$env:USERPROFILE\.workbuddy")) }
+Probe '.workbuddy 顶层内容' {
+ $p = "$env:USERPROFILE\.workbuddy"
+ if (Test-Path $p) {
+ $rows = Get-ChildItem $p -Force -ErrorAction SilentlyContinue | Select-Object Name, Length
+ ($rows | Format-Table -AutoSize | Out-String).Trim()
+ } else { '无' }
+}
+Probe 'workbuddy.db (会话库)' {
+ $f = "$env:USERPROFILE\.workbuddy\workbuddy.db"
+ if (Test-Path $f) { ('{0} 大小={1} bytes' -f $f, (Get-Item $f).Length) } else { '不存在' }
+}
+Probe '关键配置文件存在性' {
+ $base = "$env:USERPROFILE\.workbuddy"
+ @('settings.json','MEMORY.md','SOUL.md','USER.md','IDENTITY.md','mcp.json','skills','memory','binaries','automations') | ForEach-Object {
+ (' {0,-14} => {1}' -f $_, (Test-Path (Join-Path $base $_)))
+ }
+}
+
+Section '7. CDP 调试端口现状'
+Probe 'TCP 9222' { Test-Port 9222 }
+Probe 'TCP 9223' { Test-Port 9223 }
+Probe 'TCP 9333' { Test-Port 9333 }
+Probe 'TCP 47832 (若已装 WorkDaddy)' { Test-Port 47832 }
+Probe '9222 端点版本信息' {
+ if ((Test-Port 9222) -eq 'OPEN') {
+ try {
+ $req = [System.Net.HttpWebRequest]::Create('http://127.0.0.1:9222/json/version')
+ $req.Timeout = 3000
+ $resp = $req.GetResponse()
+ $reader = New-Object System.IO.StreamReader($resp.GetResponseStream())
+ $txt = $reader.ReadToEnd()
+ $reader.Close()
+ $resp.Close()
+ $txt
+ } catch { 'HTTP 请求失败: ' + $_.Exception.Message }
+ } else { '端口未开 (正常, WorkBuddy 需以 --remote-debugging-port 启动)' }
+}
+
+Section '8. 其他环境'
+Probe 'LOCALAPPDATA 可写性' {
+ $t = Join-Path $env:LOCALAPPDATA ('wbd-probe-' + [guid]::NewGuid().ToString('N') + '.tmp')
+ try { [IO.File]::WriteAllText($t, 'x'); Remove-Item $t -Force -ErrorAction SilentlyContinue; '可写 OK' }
+ catch { 'FAIL: ' + $_.Exception.Message }
+}
+Probe '用户主目录相关目录' {
+ $d = Get-ChildItem $env:USERPROFILE -Directory -Force -ErrorAction SilentlyContinue |
+ Where-Object { $_.Name -match 'workbuddy|codebuddy|WorkBuddy|CodeBuddy' } | Select-Object -ExpandProperty Name
+ if ($d) { ($d -join ', ') } else { '无' }
+}
+Probe '打开目录/文件命令可用性' {
+ $expl = Get-Command explorer.exe -ErrorAction SilentlyContinue
+ $rundll = Get-Command rundll32.exe -ErrorAction SilentlyContinue
+ $sch = Get-Command schtasks.exe -ErrorAction SilentlyContinue
+ $task = Get-Command taskkill.exe -ErrorAction SilentlyContinue
+ ('explorer={0} rundll32={1} schtasks={2} taskkill={3}' -f
+ ($(if ($expl) { 'yes' } else { 'no' })),
+ ($(if ($rundll) { 'yes' } else { 'no' })),
+ ($(if ($sch) { 'yes' } else { 'no' })),
+ ($(if ($task) { 'yes' } else { 'no' })))
+}
+Probe 'Windows Defender 实时保护' {
+ try { (Get-MpComputerStatus -ErrorAction Stop).RealTimeProtectionEnabled }
+ catch { '查询失败(可忽略)' }
+}
+
+Log ''
+Log ('==============================================================')
+Log ('探测完成。日志文件: ' + $logFile)
+Log ('==============================================================')
+
+try {
+ $utf8bom = New-Object System.Text.UTF8Encoding($true)
+ [IO.File]::WriteAllText($logFile, $sb.ToString(), $utf8bom)
+} catch {
+ Write-Host ('写日志文件失败: ' + $_.Exception.Message)
+}
\ No newline at end of file
diff --git a/scripts/win/setup.sed b/scripts/win/setup.sed
new file mode 100644
index 0000000..1828194
--- /dev/null
+++ b/scripts/win/setup.sed
@@ -0,0 +1,26 @@
+; IExpress 自解压安装包配置 —— 用于把 scripts\ 打成 WorkDaddy-Setup.exe
+; 用法:iexpress /N /Q setup.sed (由 make-setup.cmd 调用,自动填充源目录占位符)
+[Version]
+Class=IEXPRESS
+SEDVersion=3
+
+[Options]
+PackagePurpose=InstallApp
+ShowInstallProgramWindow=1
+HideExtractAnimationHandler=1
+UseCustomHeader=0
+UseCustomFooter=0
+MaxExtractTime=2147483647
+
+[SourceFiles]
+SourceFiles0=__SCRIPTS_DIR__
+
+[SourceFiles0]
+%FILE0%=
+
+[Strings]
+AppName=WorkDaddy
+AppVer=__VERSION__
+AppComments=WorkDaddy – WorkBuddy 增强工具(Windows 安装包)
+AppURL=
+InstallProgram=%comspec% /d /c install-win.cmd