Skip to content

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

增加无感登录功能;支持会话自动复制;支持配置多个同名模型;修复版本更新;修复 BUG;

[email protected]184fc38e2cf3
diff --git a/AGENTS.md b/AGENTS.md
new file mode 100644
index 0000000..030605a
--- /dev/null
+++ b/AGENTS.md
@@ -0,0 +1,103 @@
+# WorkDaddy Agent Guide
+
+## Project Overview
+
+WorkDaddy is a local enhancement layer for the WorkBuddy desktop app. It connects to the running Electron renderer through Chrome DevTools Protocol (CDP), injects a small control panel, and runs a local HTTP daemon for account backups, account switching, themes, sessions, and related utilities.
+
+The repository is deliberately lightweight:
+
+- Runtime code is plain Node.js and browser JavaScript. There is no `package.json` build pipeline.
+- `scripts/daemon.js` is the main local service and CDP coordinator.
+- `scripts/inject.js` is the injected UI and its inline CSS.
+- `scripts/theme-patches.js` contains hot-loaded CSS patches for WorkBuddy's own DOM.
+- `scripts/lib.js` owns account file parsing, backup, switching, and data-directory compatibility.
+- `scripts/win-launcher.js`, `scripts/watchdog.js`, and the PowerShell/cmd scripts are the Windows startup/update path.
+- `WorkDaddy.app` is a packaged macOS artifact. Treat `scripts/` as the source of truth; update the app bundle only when the task explicitly asks for a packaged artifact or release output.
+
+## Non-Negotiable Principles
+
+1. Diagnose the reported behavior against the current code before changing it. A historical report is evidence, not proof that the current version is broken.
+2. Keep changes narrow. Do not refactor unrelated code, rename public API routes, or change the account-file format without a concrete compatibility reason.
+3. Preserve WorkBuddy's installation, signature, and official app bundle. WorkDaddy should operate through CDP and local files rather than modifying `app.asar`.
+4. Never log, upload, or paste access tokens, cookies, account backup contents, or private keys. Sentry breadcrumbs and errors must remain redacted.
+5. Account switching is intentionally smooth: replace the selected JSON backup and refresh the running renderer through CDP. Do not call `quitWorkBuddy()` or `relaunchWorkBuddy()` from the normal `/api/switch` path.
+6. When changing daemon behavior, increment `DAEMON_VERSION` and `DAEMON_BUILD_ID` in `scripts/daemon.js`. Launchers use these values to replace stale daemon processes that still have old code in memory.
+
+## UI Direction (Highest Priority)
+
+The injected panel is a compact WorkBuddy-native tool surface, not a marketing page. Any UI change must look like it belongs beside the current WorkBuddy interface and the existing WorkDaddy panel.
+
+### Visual language
+
+- Preserve the current compact, information-dense layout: a bottom-right floating robot button opens a roughly `460px` panel with a capped viewport height, tabs, scrollable content, and small repeated account/session rows.
+- Reuse the existing CSS variables first: `--wb-bg-*`, `--wb-border-*`, `--wb-color-text-*`, `--wb-icon-*`, `--wb-button-*`, and `--wb-accent-*`. Add a new literal color only when an existing token cannot express the state.
+- Keep the established material language: translucent surfaces, restrained borders, subtle shadows, and backdrop blur where the surrounding theme already uses it. Do not introduce a separate visual system, loud gradients, neon decoration, oversized cards, or a new font family.
+- Keep the existing density and scale: panel headings around 13–16px, body text around 11–13px, compact controls, and stable icon-button dimensions. Match nearby controls instead of inventing a larger component.
+- Keep the existing radius hierarchy: panel and large surfaces may be about 14–18px; cards and grouped controls about 8–12px; compact icon buttons about 6–9px; status badges remain pill-shaped.
+
+### Theme behavior
+
+- Every new surface and text color must work in both the default/light theme and the WorkDaddy dark theme.
+- The dark theme is represented by `html.cb-dark` / `html[data-theme="dark"]` and the relevant `body[data-vscode-theme-name]` values. Test both selectors when writing CSS overrides.
+- Never rely on a light-only hardcoded foreground/background pair. Check contrast for normal, hover, selected, disabled, warning, error, and success states.
+- Theme-specific WorkBuddy DOM fixes belong in `scripts/theme-patches.js`; WorkDaddy component styles belong in `scripts/inject.js`.
+- A page reload or reinjection must restore the selected theme. Do not create a style element or observer that survives reinjection without an idempotent cleanup path.
+
+### Layout and interaction
+
+- Use stable dimensions for panels, rows, buttons, lists, and modal content. Hover and selected states must not change layout or cause visible jitter.
+- Keep scroll ownership clear: the panel body and session list may scroll, but a modal must be centered relative to the panel/viewport rather than the scrolled account list.
+- Modals use the existing centered fixed mask pattern (`.wbs-modal-mask`, `.wbs-modal`, `.wbs-modal-actions`). The mask must block pointer events from reaching WorkBuddy while open; do not allow click-through.
+- Use familiar icons for icon-only actions and give unfamiliar icons a `title` tooltip. Do not replace a known symbol with a rounded text button when an icon is sufficient.
+- Use radio controls for mutually exclusive modes, segmented controls for view modes, switches for binary settings, and normal buttons for explicit commands.
+- Avoid hover animations that resize text, borders, or the containing row. Prefer color, opacity, or shadow transitions.
+- Keep long Chinese copy inside its parent. Let descriptions wrap naturally; do not use fixed heights that clip text on narrow windows.
+- Preserve keyboard and pointer behavior: visible focus, label inputs, dismissible dialogs, and no event propagation into WorkBuddy when a WorkDaddy overlay is active.
+
+### UI implementation boundaries
+
+- `scripts/inject.js` is executed inside WorkBuddy's renderer. Avoid assumptions about React ownership and do not mutate official component state unless the existing adapter already does so.
+- Make injected DOM idempotent. On reinjection, remove or reuse prior WorkDaddy roots/styles/observers instead of stacking duplicate panels, timers, listeners, or MutationObservers.
+- Prefer event delegation and narrow observers. Broad mutation scans can freeze or crash the WorkBuddy renderer during conversation changes.
+- Escape user/account/session text before assigning it to `innerHTML`; use text nodes or the existing escaping helper where possible.
+- Do not use private WorkBuddy RPCs or reorder operations in a session-switching path unless there is a regression test and a documented reason. These paths have historically caused renderer crashes.
+
+## Backend and Platform Rules
+
+- The daemon binds to loopback only. Keep local API routes on `127.0.0.1`; validate request bodies and file paths before acting.
+- Account backups live under the WorkDaddy data directory. Preserve existing permissions and never delete user account data as part of a UI or runtime refactor.
+- Normal account switching must be JSON replacement plus CDP reload. Fake logout is the exceptional flow that may exit/relaunch WorkBuddy to reach the login page.
+- macOS uses launchd and the WorkDaddy app launcher; Windows uses the watchdog, `win-launcher.js`, `launcher.cmd`, and PowerShell scripts. Keep platform-specific process handling in the platform-specific files.
+- Windows file replacement must account for locks held by running `launcher.cmd`/`cmd.exe`. Do not kill broad process names such as every `Electron` process; match the intended executable/path narrowly.
+- If a launcher or daemon update changes code loaded into a long-running process, use a version/build bump so the launcher cannot reuse stale in-memory code.
+
+## Change Workflow
+
+1. Read the surrounding code and existing tests before editing.
+2. State the suspected cause and a falsifiable check when debugging a report.
+3. Add or update a focused regression test at the closest reliable seam before the fix. For platform-only behavior, static assertions are acceptable when the platform is unavailable, but document the missing runtime verification.
+4. Implement the smallest compatible fix. Keep user-facing copy in Chinese consistent with neighboring UI copy.
+5. Run the relevant syntax checks and the complete test suite before handoff.
+6. For UI changes, inspect both light and dark selectors and, when a WorkBuddy renderer is available, verify the actual injected panel after reload/reinjection. Check narrow-window wrapping and scroll position for modal/list changes.
+7. Review `git diff --check`, confirm no sensitive data or generated artifacts were added, and report any platform tests that could not run.
+
+## Verification Commands
+
+From the repository root:
+
+```bash
+node --check scripts/daemon.js
+node --check scripts/inject.js
+node --check scripts/win-launcher.js
+node --test test/*.test.js
+git diff --check
+```
+
+PowerShell syntax and real installer/update smoke tests should be run on Windows (or in an environment with `pwsh`). Do not claim those checks passed based only on macOS static inspection.
+
+## Commit and Delivery Notes
+
+- Work on a dedicated branch based on the requested base branch.
+- Keep logically related fixes together; avoid metadata-only churn and unrelated formatting changes.
+- Do not push, merge, or modify `main` unless the user explicitly asks for it.
+- When delivering a packaged app, state exactly which source files were synchronized into the artifact and whether the running daemon/WorkBuddy process was restarted.
diff --git a/README.md b/README.md
index a5e4b77..51ae135 100644
--- a/README.md
+++ b/README.md
@@ -33,7 +33,8 @@ v1.0.3 演示图(非最新版)
- **自动领每日积分**:打开面板即对全部账号静默签到,幂等缓存,不打断你。
- **暂存提示词**:输入框边上一键把草稿「暂存」到待发送队列——图片 / 文件 / 引用原样保留,择机发送。
- **切换精美主题**:内置毛玻璃官方主题,多套预设壁纸,支持自定义壁纸。
-- **账号间会话迁移**:把 A 账号的整段历史会话一键复制到 B 账号,跨账号继续接龙。
+- **账号间会话迁移**:自动或手动跨账号复制会话,跨账号继续接龙。
+- **模型切换更便捷**:解决 WorkBuddy 不支持添加多个同名模型的问题。
- **强化决策弹窗**:WorkBuddy 让你选/确认时,弹窗来点而不是文本询问(省得打字)。
- **防止电脑休眠**:睡前任务未完成,开启休眠模式,任务结束后自动切换成允许休眠。
diff --git a/scripts/apply-update.ps1 b/scripts/apply-update.ps1
index af18a98..d15bebe 100644
--- a/scripts/apply-update.ps1
+++ b/scripts/apply-update.ps1
@@ -1,24 +1,38 @@
-# 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 有文件锁,必须先杀进程再替换。
+# WorkDaddy Windows 自动更新替换脚本。
+# 独立于 daemon 运行:停止 watchdog、替换安装目录、启动新版并验证 API;失败时保留日志并回滚。
+[CmdletBinding()]
param(
[Parameter(Mandatory = $true)][string]$SrcZip,
[string]$AppDir = (Join-Path $env:LOCALAPPDATA 'Programs\WorkDaddy'),
- [string]$Port = '47832'
+ [string]$Port = '47832',
+ [string]$LogPath = '',
+ [string]$AttemptId = 'unknown'
)
-$ErrorActionPreference = 'Continue'
+$ErrorActionPreference = 'Stop'
$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
+if ([string]::IsNullOrWhiteSpace($LogPath)) { $LogPath = Join-Path $LogDir 'apply.log' }
+$transcriptStarted = $false
+try {
+ Start-Transcript -Path $LogPath -Append -Force | Out-Null
+ $transcriptStarted = $true
+} catch {
+ # Transcript is diagnostic only; continue with Write-Host if the file cannot be opened.
+}
+
+function Write-ApplyLog {
+ param([Parameter(Mandatory = $true)][string]$Message)
+ Write-Host ("[apply] {0} {1}" -f (Get-Date -Format 'yyyy-MM-ddTHH:mm:ssK'), $Message)
+}
-Write-Host "[apply] $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') start src=$SrcZip dst=$AppDir"
+function Stop-ApplyTranscript {
+ if ($script:transcriptStarted) {
+ try { Stop-Transcript | Out-Null } catch {}
+ $script:transcriptStarted = $false
+ }
+}
function Test-ExclusiveFile {
param([string]$Path)
@@ -42,116 +56,146 @@ function Release-LockedLauncher {
Get-CimInstance Win32_Process -Filter "Name = 'cmd.exe'" -ErrorAction SilentlyContinue | ForEach-Object {
$commandLine = ([string]$_.CommandLine).Replace('/', '\').ToLowerInvariant()
if ($commandLine.Contains($needle) -and $_.ProcessId -ne $PID) {
- taskkill /F /T /PID $_.ProcessId 2>$null | Out-Null
+ & taskkill /F /T /PID $_.ProcessId 2>$null | Out-Null
}
}
- } catch {}
- for ($i = 0; $i -lt 10; $i++) {
+ } catch {
+ Write-ApplyLog "扫描 launcher.cmd 锁失败: $($_.Exception.Message)"
+ }
+ for ($i = 0; $i -lt 20; $i++) {
if (Test-ExclusiveFile $LauncherPath) { return $true }
Start-Sleep -Milliseconds 300
}
return (Test-ExclusiveFile $LauncherPath)
}
-# 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 {}
-}
+function Stop-WatchdogAndPort {
+ $pidFile = Join-Path $DataDir 'watchdog.pid'
+ if (Test-Path -LiteralPath $pidFile) {
+ try {
+ $watchdogPid = [int]((Get-Content -LiteralPath $pidFile -Raw).Trim())
+ if ($watchdogPid -gt 0) {
+ Write-ApplyLog "停止 watchdog pid=$watchdogPid"
+ # 【重要】绝不能带 /T!taskkill 的 /T 按 ParentProcessId 递归连坐整棵子树,
+ # 而本脚本(powershell)就是 watchdog→daemon→powershell 链上的叶子,/T 会把自身也杀掉,
+ # 导致替换从未执行(apply.log 里做完「停止 watchdog」这步就没下文了)。
+ # 只精确杀 watchdog 一个进程即可;daemon 已被 daemon.js 自我退出,端口兜底逻辑单独处理。
+ & taskkill /F /PID $watchdogPid 2>$null | Out-Null
+ }
+ } catch {
+ Write-ApplyLog "停止 watchdog 失败: $($_.Exception.Message)"
+ }
+ }
-# 2) 兜底:按 API 端口杀残留进程
-# watchdog PID 可能来自旧版本或已失效;不要在端口仍被占用时无条件等待 30 秒。
-$waitSec = 0
-while ($waitSec -lt 10) {
- $listening = @(netstat -ano | Select-String (":$Port\s") | Select-String 'LISTENING')
- if ($listening.Count -eq 0) { break }
- # 给被 taskkill 的进程最多几秒退出;仍占用时立即强制清理,避免更新假死。
- if ($waitSec -ge 3) {
- foreach ($line in $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 }
+ for ($wait = 0; $wait -lt 15; $wait++) {
+ $listening = @(netstat -ano | Select-String (":$Port\s") | Select-String 'LISTENING')
+ if ($listening.Count -eq 0) { return }
+ if ($wait -ge 3) {
+ foreach ($line in $listening) {
+ $parts = ($line.ToString().Trim() -split '\s+')
+ $portPid = $parts[$parts.Count - 1]
+ if ($portPid -match '^\d+$') {
+ Write-ApplyLog "端口 $Port 仍被 pid=$portPid 占用,强制结束"
+ # 同样不要 /T:占用端口的进程极可能是 daemon(本脚本的父链成员),/T 会连坐自身。
+ & taskkill /F /PID $portPid 2>$null | Out-Null
+ }
+ }
}
+ Start-Sleep -Seconds 1
}
- Start-Sleep -Seconds 1
- $waitSec++
+ $remaining = @(netstat -ano | Select-String (":$Port\s") | Select-String 'LISTENING')
+ if ($remaining.Count -gt 0) { throw "端口 $Port 在 15 秒后仍被占用" }
}
-$listening = @(netstat -ano | Select-String (":$Port\s") | Select-String 'LISTENING')
-foreach ($line in $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'
-foreach ($launcherToRelease in @(
- (Join-Path $AppDir 'scripts\launcher.cmd'),
- (Join-Path $oldDir 'scripts\launcher.cmd')
-)) {
- if (-not (Release-LockedLauncher $launcherToRelease)) {
- Write-Host "[apply] 无法释放 launcher.cmd 文件锁: $launcherToRelease"
- Stop-Transcript
- exit 2
+function Rollback-App {
+ param([string]$OldDir, [string]$TargetDir)
+ Write-ApplyLog "开始回滚旧版本"
+ try { Stop-WatchdogAndPort } catch { Write-ApplyLog "回滚前停止新版进程失败: $($_.Exception.Message)" }
+ try { if (Test-Path -LiteralPath $TargetDir) { Remove-Item -LiteralPath $TargetDir -Recurse -Force -ErrorAction SilentlyContinue } } catch {}
+ if (Test-Path -LiteralPath $OldDir) {
+ try { Move-Item -LiteralPath $OldDir -Destination $TargetDir -Force -ErrorAction Stop } catch {
+ Write-ApplyLog "回滚失败: $($_.Exception.Message)"
+ }
+ }
+ $oldLauncher = Join-Path $TargetDir 'scripts\launcher.cmd'
+ $oldLauncherVbs = Join-Path $TargetDir 'scripts\launcher-hidden.vbs'
+ try {
+ if (Test-Path -LiteralPath $oldLauncherVbs) {
+ Start-Process -FilePath (Join-Path $env:WINDIR 'System32\wscript.exe') -ArgumentList ('//nologo "' + $oldLauncherVbs + '"') -WorkingDirectory (Split-Path $oldLauncher) -ErrorAction Stop | Out-Null
+ } elseif (Test-Path -LiteralPath $oldLauncher) {
+ Start-Process -FilePath $oldLauncher -WorkingDirectory (Split-Path $oldLauncher) -ErrorAction Stop | Out-Null
+ }
+ } catch {
+ Write-ApplyLog "回滚后启动旧 launcher 失败: $($_.Exception.Message)"
}
}
-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 无法原地覆盖已存在目录)
+$oldDir = "$AppDir.old"
$tmpDir = Join-Path $env:TEMP ("workdaddy-update-" + [guid]::NewGuid().ToString('N'))
-New-Item -ItemType Directory -Force -Path $tmpDir | Out-Null
+$backupMade = $false
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
-}
+ Write-ApplyLog "start attempt=$AttemptId src=$SrcZip dst=$AppDir port=$Port pid=$PID"
+ if (-not (Test-Path -LiteralPath $SrcZip -PathType Leaf)) { throw "更新包不存在: $SrcZip" }
+ Stop-WatchdogAndPort
-# 定位 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
+ foreach ($launcherPath in @((Join-Path $AppDir 'scripts\launcher.cmd'), (Join-Path $oldDir 'scripts\launcher.cmd'))) {
+ if (-not (Release-LockedLauncher $launcherPath)) { throw "无法释放 launcher.cmd 文件锁: $launcherPath" }
+ }
-# 复制内容(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
-}
+ if (Test-Path -LiteralPath $oldDir) { Remove-Item -LiteralPath $oldDir -Recurse -Force -ErrorAction Stop }
+ if (Test-Path -LiteralPath $AppDir) {
+ Move-Item -LiteralPath $AppDir -Destination $oldDir -Force -ErrorAction Stop
+ $backupMade = $true
+ }
-# 5) 校验启动器后清理备份并拉起(launcher 幂等:检测 daemon 后启动 watchdog)
-$launcher = Join-Path (Join-Path $AppDir 'scripts') 'launcher.cmd'
-$launcherVbs = Join-Path (Join-Path $AppDir 'scripts') 'launcher-hidden.vbs'
-if (-not (Test-Path $launcher)) {
- Write-Host '[apply] 新版本缺少 scripts\\launcher.cmd,回滚旧版本'
- Remove-Item -Recurse -Force $AppDir -ErrorAction SilentlyContinue
- if (Test-Path $oldDir) { Move-Item -Force $oldDir $AppDir -ErrorAction SilentlyContinue }
- Stop-Transcript
- exit 3
-}
-if (Test-Path $launcherVbs) {
- # wscript.exe 不创建控制台,自动更新重启时也不再弹出空白 Windows Terminal。
- Start-Process -FilePath (Join-Path $env:WINDIR 'System32\wscript.exe') -ArgumentList ('//nologo "' + $launcherVbs + '"') -WorkingDirectory (Split-Path $launcher)
-} else {
- # 兼容旧版本目录:直接启动 launcher.cmd。
- Start-Process -FilePath $launcher -WorkingDirectory (Split-Path $launcher)
+ New-Item -ItemType Directory -Force -Path $tmpDir | Out-Null
+ Expand-Archive -LiteralPath $SrcZip -DestinationPath $tmpDir -Force
+ $srcRoot = $tmpDir
+ if (-not (Test-Path (Join-Path $tmpDir 'scripts\daemon.js'))) {
+ $hit = Get-ChildItem -LiteralPath $tmpDir -Recurse -Filter 'daemon.js' -File | Select-Object -First 1
+ if ($hit) { $srcRoot = Split-Path $hit.FullName -Parent | Split-Path -Parent }
+ }
+ foreach ($required in @('scripts\daemon.js', 'scripts\launcher.cmd', 'scripts\win-launcher.js')) {
+ if (-not (Test-Path (Join-Path $srcRoot $required) -PathType Leaf)) { throw "更新包缺少 $required" }
+ }
+
+ New-Item -ItemType Directory -Force -Path $AppDir | Out-Null
+ & robocopy $srcRoot $AppDir /MIR /NFL /NDL /NJH /NJS /NP | Out-Null
+ $rc = $LASTEXITCODE
+ Write-ApplyLog "robocopy code=$rc"
+ if ($rc -ge 8) { throw "robocopy 复制失败 (code=$rc)" }
+
+ $launcher = Join-Path $AppDir 'scripts\launcher.cmd'
+ $launcherVbs = Join-Path $AppDir 'scripts\launcher-hidden.vbs'
+ if (Test-Path -LiteralPath $launcherVbs) {
+ $started = Start-Process -FilePath (Join-Path $env:WINDIR 'System32\wscript.exe') -ArgumentList ('//nologo "' + $launcherVbs + '"') -WorkingDirectory (Split-Path $launcher) -PassThru -ErrorAction Stop
+ } else {
+ $started = Start-Process -FilePath $launcher -WorkingDirectory (Split-Path $launcher) -PassThru -ErrorAction Stop
+ }
+ Write-ApplyLog "已启动新版 launcher pid=$($started.Id),等待 daemon"
+ $ready = $false
+ for ($i = 0; $i -lt 60; $i++) {
+ try {
+ $status = Invoke-RestMethod -Uri ("http://127.0.0.1:{0}/api/status" -f $Port) -Method Get -TimeoutSec 2
+ if ($status.version) { $ready = $true; Write-ApplyLog "新版 daemon 已就绪 version=$($status.version)"; break }
+ } catch {}
+ Start-Sleep -Seconds 1
+ }
+ if (-not $ready) { throw '新版 daemon 在 60 秒内未就绪' }
+
+ if (Test-Path -LiteralPath $oldDir) {
+ Remove-Item -LiteralPath $oldDir -Recurse -Force -ErrorAction SilentlyContinue
+ }
+ Write-ApplyLog "done attempt=$AttemptId"
+ Stop-ApplyTranscript
+ exit 0
+} catch {
+ Write-ApplyLog "FAILED attempt=$AttemptId error=$($_.Exception.Message)"
+ if ($backupMade) { Rollback-App -OldDir $oldDir -TargetDir $AppDir }
+ Stop-ApplyTranscript
+ exit 1
+} finally {
+ try { if (Test-Path -LiteralPath $tmpDir) { Remove-Item -LiteralPath $tmpDir -Recurse -Force -ErrorAction SilentlyContinue } } catch {}
+ # 清除更新标记:无论成败都不再阻止 watchdog 拉起 daemon(避免留下「daemon 死光」的悬空状态)
+ try { Remove-Item -LiteralPath (Join-Path $LogDir 'pending.json') -Force -ErrorAction SilentlyContinue } catch {}
}
-Remove-Item -Recurse -Force $oldDir -ErrorAction SilentlyContinue
-Write-Host "[apply] $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') done"
-Stop-Transcript
-exit 0
diff --git a/scripts/apply-update.sh b/scripts/apply-update.sh
index 2d4c6c2..0a0f915 100644
--- a/scripts/apply-update.sh
+++ b/scripts/apply-update.sh
@@ -1,51 +1,96 @@
#!/usr/bin/env bash
-# WorkDaddy 自动更新辅助脚本(业界标准 Sparkle 同款:独立进程接管替换,运行中的 app 无法自删)
-# 由 daemon.js applyUpdate() 调用,参数:
-# $1 更新源 app 路径(update 目录里解包出的新 WorkDaddy.app)
-# $2 目标 app 路径(默认 /Applications/WorkDaddy.app)
-# $3 本地 API 端口(等待旧 daemon 退出用,默认 47832)
-# $4 日志路径
-# 流程:等端口释放 → 备份旧版(.old 可回滚) → 拷贝新版 → 清隔离属性 → 拉起新版
-set -uo pipefail
+# WorkDaddy macOS 自动更新辅助脚本。
+# 这个脚本必须是独立进程:daemon 会在它启动后退出,脚本负责停服、替换、校验和重启。
+set -Eeuo pipefail
SRC_APP="${1:?缺少源 app 路径}"
-APP_PATH="${2:-/Applications/WorkDaddy.app}"
+APP_PATH="${2:?缺少目标 app 路径}"
UI_PORT="${3:-47832}"
LOG="${4:-$HOME/Library/Application Support/WorkDaddy/update/apply.log}"
+ATTEMPT_ID="${5:-unknown}"
+LABEL="com.workbuddy.workdaddy"
+
mkdir -p "$(dirname "$LOG")"
exec >>"$LOG" 2>&1
-echo "[apply] $(date '+%F %T') start src=$SRC_APP dst=$APP_PATH"
+timestamp() { date -u '+%FT%TZ'; }
+log() { printf '[apply] %s %s\n' "$(timestamp)" "$*"; }
+fail() {
+ local code="${2:-1}"
+ log "FAILED code=$code message=$1"
+ exit "$code"
+}
+on_unhandled_error() {
+ local code="$?"
+ log "FAILED code=$code command=${BASH_COMMAND:-unknown}"
+ exit "$code"
+}
+trap on_unhandled_error ERR
+
+log "start attempt=$ATTEMPT_ID src=$SRC_APP dst=$APP_PATH port=$UI_PORT pid=$$"
+[ -d "$SRC_APP" ] || fail "源应用不存在: $SRC_APP" 10
+[ -f "$SRC_APP/Contents/Info.plist" ] || fail "源应用缺少 Contents/Info.plist" 11
+[ -f "$SRC_APP/Contents/Resources/scripts/daemon.js" ] || fail "源应用缺少 daemon.js" 12
+[ -x "$SRC_APP/Contents/MacOS/launcher" ] || fail "源应用 launcher 不可执行" 13
+
+# KeepAlive/launchd 是异步的;先停服务,再按进程和端口确认旧 daemon 已退出。
+UID_NUM="$(id -u)"
+launchctl bootout "gui/$UID_NUM/$LABEL" 2>&1 || log "launchctl bootout 返回非零(可能本来未注册)"
+launchctl remove "$LABEL" 2>&1 || log "launchctl remove 返回非零(可能本来未注册)"
+pkill -f "$APP_PATH/Contents/Resources/scripts/daemon.js" 2>&1 || true
+pkill -f "WorkDaddy.app/Contents/Resources/scripts/daemon.js" 2>&1 || true
-# 1) 先终止旧 daemon,再等待端口释放——运行中的 app 无法被替换。
-# launchd bootout 是异步的;先杀进程可以避免正常更新路径白等 30 秒。
-pkill -f "$APP_PATH/Contents/Resources/scripts/daemon.js" 2>/dev/null || true
-pkill -f "scripts/daemon.js" 2>/dev/null || true
+PORT_READY=0
for i in $(seq 1 30); do
- if ! lsof -ti tcp:"$UI_PORT" >/dev/null 2>&1; then break; fi
+ if ! lsof -nP -ti tcp:"$UI_PORT" -sTCP:LISTEN >/dev/null 2>&1; then PORT_READY=1; break; fi
sleep 1
done
-# KeepAlive 可能在第一次 pkill 后短暂拉起旧 daemon;替换前再清一次。
-pkill -f "$APP_PATH/Contents/Resources/scripts/daemon.js" 2>/dev/null || true
-pkill -f "scripts/daemon.js" 2>/dev/null || true
-sleep 1
-
-# 2) 备份旧版(失败可回滚:mv WorkDaddy.app.old WorkDaddy.app)
-rm -rf "$APP_PATH.old"
-if [ -d "$APP_PATH" ]; then
- mv "$APP_PATH" "$APP_PATH.old"
+if [ "$PORT_READY" != "1" ]; then
+ log "端口 $UI_PORT 在 30 秒后仍被占用,拒绝覆盖应用"
+ fail "旧 daemon 未退出" 20
+fi
+
+OLD_PATH="${APP_PATH}.old"
+rm -rf "$OLD_PATH"
+if [ -e "$APP_PATH" ]; then
+ mv "$APP_PATH" "$OLD_PATH" || fail "无法备份旧应用: $APP_PATH" 21
fi
-# 3) 拷贝新版
+rollback() {
+ local code="${1:-30}"
+ log "开始回滚 code=$code"
+ pkill -f "$APP_PATH/Contents/Resources/scripts/daemon.js" 2>&1 || true
+ rm -rf "$APP_PATH" || true
+ if [ -e "$OLD_PATH" ]; then
+ mv "$OLD_PATH" "$APP_PATH" || log "回滚失败: $OLD_PATH -> $APP_PATH"
+ fi
+ if [ -x "$APP_PATH/Contents/MacOS/launcher" ]; then
+ open -n "$APP_PATH" || log "回滚后启动旧应用失败"
+ fi
+ exit "$code"
+}
+
mkdir -p "$(dirname "$APP_PATH")"
-cp -R "$SRC_APP" "$APP_PATH"
-chmod -R u+rwX "$APP_PATH"
+cp -R "$SRC_APP" "$APP_PATH" || rollback 22
+chmod -R u+rwX "$APP_PATH" || rollback 23
+xattr -cr "$APP_PATH" 2>&1 || log "清除隔离属性失败(继续,可能已无隔离属性)"
-# 4) 清 Gatekeeper 隔离属性(否则首次打开被拦;自动更新场景用户已信任过本应用)
-xattr -cr "$APP_PATH" 2>/dev/null || true
+[ -f "$APP_PATH/Contents/Info.plist" ] || rollback 24
+[ -f "$APP_PATH/Contents/Resources/scripts/daemon.js" ] || rollback 25
+[ -x "$APP_PATH/Contents/MacOS/launcher" ] || rollback 26
-# 5) 拉起新版(launcher 自带"版本不一致强制重启 daemon + 注入"逻辑)
-open "$APP_PATH"
+# open 只负责派发应用,随后必须验证新的 daemon 真的回来了;不能把 open 返回 0 当作更新成功。
+open -n "$APP_PATH" || rollback 27
+log "已派发新版应用,等待 daemon 端口恢复"
+READY=0
+for i in $(seq 1 45); do
+ if curl -fsS --max-time 1 "http://127.0.0.1:${UI_PORT}/api/status" >/dev/null 2>&1; then READY=1; break; fi
+ sleep 1
+done
+if [ "$READY" != "1" ]; then
+ log "新版 daemon 在 45 秒内未恢复,保留日志与旧版备份: $OLD_PATH"
+ rollback 28
+fi
-echo "[apply] $(date '+%F %T') done"
+log "done attempt=$ATTEMPT_ID app=$APP_PATH"
exit 0
diff --git a/scripts/apply-update.vbs b/scripts/apply-update.vbs
new file mode 100644
index 0000000..96859f0
--- /dev/null
+++ b/scripts/apply-update.vbs
@@ -0,0 +1,31 @@
+Option Explicit
+
+' WorkDaddy 自动更新中介脚本(Windows)。
+'
+' 为什么需要它:
+' Node 在 Windows 上 spawn 的子进程会被放进 Job Object,父进程(daemon)退出时 job 关闭,
+' 子进程会被 KILL_ON_JOB_CLOSE 连带杀死;而 detached:true 虽能解耦,但 PowerShell 5.1 / cmd.exe
+' 是 console 程序,在 detached(无控制台)环境下宿主初始化会静默退出、-File 脚本根本不执行。
+' wscript.exe 是 GUI 子系统进程(不依赖控制台),其 WScript.Shell.Run 通过 ShellExecute 创建
+' 完全独立的进程树,父进程死活都不影响更新脚本继续执行。这就是 Windows 上唯一可靠的
+' "父进程退出后子进程仍继续" 通道。
+'
+' 【ShellExecute 的坑】sh.Run 的命令行第一个 token 必须是"可解析的可执行文件":
+' 带双引号包裹的完整路径("C:\...\powershell.exe")或裸名(powershell.exe)才可靠——
+' 实测"完整路径不带引号"(V2) 与"引号路径"(V1) 都可能静默失败;裸名 100% 可靠。
+' 因此这里固定写死 powershell.exe 裸名(System32 恒在 PATH),后续所有参数一律加双引号。
+'
+' 用法(由 daemon.js applyUpdate() 调用):
+' wscript.exe //nologo apply-update.vbs <apply-update.ps1> <srcZip> <appDir> <port> <applyLog> <attemptId>
+
+Dim shell, i, cmd
+Set shell = CreateObject("WScript.Shell")
+
+cmd = "powershell.exe -NoProfile -ExecutionPolicy Bypass -File "
+For i = 0 To WScript.Arguments.Count - 1
+ cmd = cmd & " """ & WScript.Arguments(i) & """"
+Next
+If WScript.Arguments.Count = 0 Then WScript.Quit 1
+
+' 0 = 隐藏窗口;False = 不等待(本脚本立即退出,powershell 继续在独立进程树中执行)
+shell.Run cmd, 0, False
\ No newline at end of file
diff --git a/scripts/build-win-zip.sh b/scripts/build-win-zip.sh
index 8238b6b..468b7a5 100644
--- a/scripts/build-win-zip.sh
+++ b/scripts/build-win-zip.sh
@@ -1,14 +1,14 @@
#!/usr/bin/env bash
# WorkDaddy Windows 发布包打包脚本(在 macOS/Linux 上运行即可产出 Windows zip)
-# 产出:release/windows/WorkDaddy-<ver>-win64.zip(顶层含 scripts\,供 install-win.cmd / apply-update.ps1 使用)
+# 产出: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="${WORKDADDY_BUILD_VERSION:-$(grep -o "DAEMON_VERSION = '[^']*'" scripts/daemon.js | head -1 | cut -d"'" -f2)}"
-OUT="release/windows/WorkDaddy-${VERSION}-win64.zip"
+VERSION="$(grep -o "DAEMON_VERSION = '[^']*'" scripts/daemon.js | head -1 | cut -d"'" -f2)"
+OUT="release/WorkDaddy-${VERSION}-win64.zip"
echo "==> 版本: ${VERSION}"
echo "==> 产物: ${OUT}"
@@ -42,73 +42,8 @@ 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"
-cat > "$STAGE/安装失败自主解决提示词.txt" <<'EOF'
-WorkDaddy Windows 安装失败自助修复
-==================================
-
-你是 WorkDaddy 的故障修复 agent。用户已经无法正常安装或启动 WorkDaddy,请在用户明确授权的范围内完成排查、修复和自动上报。
-
-一、准备源码
-
-1. 在一个新的临时目录执行:
-
- git clone https://github.com/babygoton/WorkDaddy.git
- cd WorkDaddy
-
-2. 先阅读 README.md、scripts/install-win.ps1、scripts/install-win.cmd、scripts/launcher.cmd、scripts/win-launcher.js、scripts/daemon.js,以及用户提供的 PowerShell/cmd 错误和 %APPDATA%\\WorkDaddy\\*.log。不要读取、复制、上传或修改以下内容:
-
- - %APPDATA%\\WorkDaddy\\accounts\\
- - WorkBuddy 登录文件、Cookie、数据库、环境变量、私有密钥
-
-二、复现问题
-
-1. 只在源码目录中操作。优先从源码根目录执行:
-
- powershell -NoProfile -ExecutionPolicy Bypass -File .\\scripts\\install-win.ps1
-
-2. 如果需要验证启动流程,再执行:
-
- .\\scripts\\launcher.cmd
-
-3. 记录实际失败命令、完整错误文本、Windows 版本、Node 版本和 WorkBuddy 版本。不要猜测根因。
-
-三、修复问题
-
-1. 只修改 GitHub 源码目录,不直接修改 %LOCALAPPDATA%\\Programs\\WorkDaddy 或用户数据目录。
-2. 保持现有 Windows 用户态安装方式和安全边界;不要删除账号数据,不要关闭现有脱敏逻辑。
-3. 修改后重新执行最小复现命令,并运行:
-
- node --check scripts/sentry-report.js
- node --check scripts/daemon.js
- node --check scripts/win-launcher.js
- node --test test/*.test.js
-
-四、生成修复报告
-
-在源码根目录创建 WORKDADDY_FIX_REPORT.md,必须包含:
-
- - 原始问题和复现命令
- - 确认的根因;如果没有确认,写“未确认”
- - 修改的文件和每个修改的目的
- - 测试命令和实际结果
- - 用户安装时需要重新执行的命令
-
-五、自动上报
-
-只有在修复已经通过测试后,执行:
-
- node scripts\\sentry-report.js --stage agent-fix --level info --message-file WORKDADDY_FIX_REPORT.md --tags-json '{"source":"workbuddy-agent","status":"fixed","platform":"windows"}'
-
-命令输出必须是 JSON。看到 sent=true 表示已发送;看到 queued=true 表示网络暂时不可用,报告已写入 WorkDaddy 的 telemetry/outbox,后续会自动重试。不要把 token、账号备份、数据库或完整日志放进 WORKDADDY_FIX_REPORT.md。
-
-如果测试仍未通过,不得伪造 fixed 状态;可以改用 status=unresolved 上报,并在报告中写清楚阻塞原因。
-EOF
# 3.2) scripts\ 本体(含 node_modules/ws、builtin)
cp -R scripts "$STAGE/scripts"
-if [ -n "${WORKDADDY_BUILD_VERSION:-}" ]; then
- perl -0pi -e "s/(const DAEMON_VERSION = ')[^']+(';)/\${1}${VERSION}\${2}/" \
- "$STAGE/scripts/daemon.js"
-fi
# 3.2a) Logo 图标:放入 scripts\(install-win.ps1 从 SrcDir 同名找并复制到安装目录根)
if [ -f "$DIR/release/WorkDaddy.ico" ]; then
cp "$DIR/release/WorkDaddy.ico" "$STAGE/scripts/WorkDaddy.ico"
@@ -123,6 +58,17 @@ rm -rf "$STAGE/scripts/win/probe" "$STAGE/scripts/win/probe/"* 2>/dev/null || tr
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.3.5) 非 ASCII 文件名守护(必杀项)
+# Windows 的 .NET Expand-Archive 解压含非 ASCII 条目名的 zip 时,文件名按 OEM 代码页解码成
+# 非法字符,直接抛「路径中具有非法字符」→ Windows 自动更新在解压阶段崩溃,备份/替换/回滚全失效。
+# 发布包严禁混入中文/特殊字符文件名(曾出现过「安装失败自主解决提示词.txt」导致 1.0.6 更新必炸)。
+if find "$STAGE" -not -path '*/node_modules/*' 2>/dev/null | LC_ALL=C grep -q '[^ -~]'; then
+ echo "==> ERROR: 发布包包含非 ASCII 文件路径(.NET Expand-Archive 解压必失败),已终止打包!"
+ find "$STAGE" -not -path '*/node_modules/*' 2>/dev/null | LC_ALL=C grep '[^ -~]' | head -20
+ rm -rf "$STAGE"
+ exit 3
+fi
+echo "==> 非 ASCII 文件名守护通过(全 ASCII 路径)"
# 3.4) 打包:zip 优先;无 zip 的环境用 Windows 系统自带 bsdtar(生成标准 / 分隔符 zip)。
# 绝不用 PowerShell Compress-Archive —— 它产出反斜杠分隔符,非标准 zip 会被解压工具把
# scripts\daemon.js 当单个文件名,导致解压结构错乱、入口秒退。
@@ -142,4 +88,4 @@ 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 自动静默升级)。"
+echo "每 6 小时自动检查更新(GitHub Releases 需同时上传 .dmg 与 -win64.zip 两个资产,Windows 自动静默升级)。"
\ No newline at end of file
diff --git a/scripts/daemon.js b/scripts/daemon.js
index 8297a6d..2c48d94 100644
--- a/scripts/daemon.js
+++ b/scripts/daemon.js
@@ -56,6 +56,28 @@ const {
deleteAccount,
backupPath,
updateMeta,
+ canonicalWorkspace,
+ getAutoCopyRules,
+ setAutoCopyRule,
+ getAutoCopySession,
+ ensureAutoCopySession,
+ addAutoCopySessionMember,
+ moveAutoCopySession,
+ removeAutoCopySession,
+ removeAutoCopyAccount,
+ getAutoCopyMapping,
+ setAutoCopyMapping,
+ deleteAutoCopyMapping,
+ workbuddyModelsFile,
+ listOfficialModels,
+ readOfficialModel,
+ deleteOfficialModels,
+ listModelBackups,
+ backupOfficialModel,
+ copyModelBackup,
+ editModelBackup,
+ deleteModelBackups,
+ enableModelBackup,
} = require('./lib.js');
const { extractCreditSegments, sortCreditSegments } = require('./credit-segments.js');
const { captureException } = require('./sentry-report.js');
@@ -74,7 +96,18 @@ const DATA_DIR = defaultDataDir();
// 1.0.5:修复自动更新「缺少解包后的新应用」——下载阶段只落 .dmg 从未解包,
// applyUpdate 现改为在安装前调用 extractAppFromDmg 解出 WorkDaddy.app(幂等),
// 解包函数亦增强(清理残留挂载点、只读挂载、校验 dmg 内存在 WorkDaddy.app)
-// 1.0.6:daemon 单实例锁、启动竞态修复、注入结果校验与本地诊断快照;
+// 1.0.5(修复版打包):修复 Windows 自动更新三大卡死根因,让「更新已启动,WorkDaddy 即将重启」
+// 到真正更新完成:
+// ① daemon spawn powershell 曾被 detached:true + stdio:'ignore' 拉起,PowerShell 5.1(console 程序)
+// 在 detached(无控制台)下宿主静默退出、-File 脚本从不执行 → apply.log 永不生成、替换永不发生;
+// ② 即便去掉 detached,Node 在 Windows 上给子进程套的 Job Object 会在 daemon 退出时(KILL_ON_JOB_CLOSE)
+// 连带杀死 powershell,替换中断在「停止 watchdog」一步;
+// ③ 发布包内曾混入非 ASCII 文件名(安装失败自主解决提示词.txt),Windows .NET Expand-Archive 解压时
+// 文件名解码成非法字符直接抛「路径中具有非法字符」→ 备份/替换/回滚全部失效。
+// 修复:更新脚本改由 wscript.exe(GUI 子系统)+ apply-update.vbs 中介经 ShellExecute 启动独立进程树,
+// daemon 随即自我退出释放文件锁;apply-update.ps1 对 watchdog 与端口进程一律 taskkill 不带 /T 精确杀,
+// 避免连坐自身;打包脚本 build-win-zip.sh 增加非 ASCII 文件名守护,杜绝中文/特殊字符条目进入安装包。
+// 另:daemon 单实例锁、启动竞态修复、注入结果校验与本地诊断快照;
// 修复跨平台自动更新并展示按到期时间拆分的积分明细
// 1.0.7:兼容无全局 WebSocket 的 Node 18/20,使用内置 ws 建立 CDP
// 1.0.8:去除 launchd 重定向造成的重复日志,并记录 launcher 选择的 Node 运行时
@@ -86,8 +119,17 @@ const DATA_DIR = defaultDataDir();
// 账号切换始终使用 JSON 替换 + CDP 刷新,不退出 WorkBuddy
// 1.0.13:Windows 安装/更新释放 launcher.cmd 文件锁;延长 CDP 启动等待;
// 补充便携版 WorkBuddy 路径探测,并在重启后恢复主窗口
-const DAEMON_VERSION = '1.0.13';
-const DAEMON_BUILD_ID = 'windows-hardening-20260821';
+// 1.0.14:自动更新使用独立尝试记录、严格脚本退出码、安装后 daemon 校验;
+// macOS 不再把更新目标硬编码为 /Applications/WorkDaddy.app
+// 1.0.15:会话/空间自动复制规则,切换账号后异步幂等复制并提供进度状态
+// 1.0.16:全局会话 lineage、迁移/删除清理、快速切换复制队列与任务组只读
+// 1.0.17:会话摘要去重统计与本地模型备份/启用管理
+// 1.0.18:模型页展示脱敏详情,支持官方/本地模型批量操作及本地备份复制/编辑
+// 1.0.19:官方模型批量删除、模型卡片稳定布局与固定 650px 面板
+// 1.0.20:模型卡片悬浮操作、官方连通测试、完整长度脱敏 API Key
+// 1.0.21:模型页改为当前/备选模型列表风格,去除刷新入口并优化字段排版
+const DAEMON_VERSION = '1.0.7';
+const DAEMON_BUILD_ID = 'release-1.0.7-20260822';
const HOST = '127.0.0.1';
const IS_WIN = process.platform === 'win32'; // Windows 移植:平台分支开关(macOS 行为保持不变)
// Windows 安装目录(install.ps1 铺、launcher 用、更新替换目标),对应 macOS 的 /Applications/WorkDaddy.app
@@ -185,6 +227,7 @@ const UPDATE_CHECK_INTERVAL = 6 * 3600 * 1000; // 每 6 小时检查一次(Git
const UPDATE_REQ_TIMEOUT = 10000; // 网络超时,超时静默失败不阻塞面板
const UPDATE_DIR = path.join(DATA_DIR, 'update'); // 下载/解包目录
const UPDATE_CHECK_CACHE = path.join(DATA_DIR, 'update-check.json');
+const UPDATE_ATTEMPT_FILE = path.join(UPDATE_DIR, 'last-attempt.json');
// 更新状态机(面板轮询用):idle | checking | downloading | verifying | installing | done | error
const updateState = {
status: 'idle',
@@ -195,9 +238,28 @@ const updateState = {
message: '',
error: null,
checkedAt: 0,
+ attemptId: null,
};
let updateTimer = null;
+function writeUpdateAttempt(attempt) {
+ try {
+ fs.mkdirSync(UPDATE_DIR, { recursive: true });
+ const tmp = UPDATE_ATTEMPT_FILE + '.tmp.' + process.pid;
+ fs.writeFileSync(tmp, JSON.stringify(attempt, null, 2) + '\n', { mode: 0o600 });
+ fs.renameSync(tmp, UPDATE_ATTEMPT_FILE);
+ } catch (e) {
+ log('[update] 更新尝试记录写入失败: ' + e.message);
+ }
+}
+
+function macWorkDaddyAppPath() {
+ if (process.env.WBSWITCH_APP_PATH) return path.resolve(process.env.WBSWITCH_APP_PATH);
+ const bundledInfo = path.resolve(__dirname, '../../..', 'Contents', 'Info.plist');
+ if (fs.existsSync(bundledInfo)) return path.resolve(__dirname, '../../..');
+ return '/Applications/WorkDaddy.app';
+}
+
// 简单 semver 比较:a > b → 1,a < b → -1,相等 → 0(忽略预发布后缀)
function semverCompare(a, b) {
const pa = String(a || '').replace(/^v/, '').split(/[-+]/)[0].split('.').map((n) => parseInt(n, 10) || 0);
@@ -592,27 +654,101 @@ function applyUpdate() {
if (!updateState.downloaded) return Promise.reject(new Error('尚未下载完成'));
updateState.status = 'installing';
updateState.message = '正在安装新版本…';
- const { execFile } = require('child_process');
+ updateState.error = null;
+ const { spawn } = require('child_process');
+ const attempt = {
+ id: crypto.randomUUID(),
+ status: 'starting',
+ platform: process.platform,
+ fromVersion: DAEMON_VERSION,
+ targetVersion: updateState.latest,
+ startedAt: new Date().toISOString(),
+ pid: process.pid,
+ dataDir: DATA_DIR,
+ };
+ updateState.attemptId = attempt.id;
+ writeUpdateAttempt(attempt);
+ const applyLog = path.join(UPDATE_DIR, 'apply.log');
+ const markAttemptFailure = (error, stage = 'update-script') => {
+ attempt.status = stage;
+ attempt.finishedAt = new Date().toISOString();
+ attempt.error = error && error.message ? error.message : String(error);
+ writeUpdateAttempt(attempt);
+ log('[update] 更新尝试失败 stage=' + stage + ': ' + attempt.error);
+ captureException(error, { stage, extra: { platform: process.platform, attemptId: attempt.id, targetVersion: updateState.latest } }).catch(() => {});
+ };
+ const markSpawnFailure = (error) => markAttemptFailure(error, 'spawn-error');
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)],
+ if (!fs.existsSync(scriptPath)) {
+ const error = new Error('缺少 apply-update.ps1');
+ markAttemptFailure(error, 'preflight-error');
+ return Promise.reject(error);
+ }
+ if (!fs.existsSync(srcZip)) {
+ const error = new Error('缺少解压后的新版本包');
+ markAttemptFailure(error, 'preflight-error');
+ return Promise.reject(error);
+ }
+ attempt.sourcePackage = srcZip;
+ attempt.targetApp = appDir;
+ writeUpdateAttempt(attempt);
+ log('[update] 执行 apply-update.ps1 attempt=' + attempt.id + ' log=' + applyLog);
+ // 【更新标记】写入 pending.json:watchdog 检测到它在 daemon 退出后【不自动重启 daemon】,
+ // 双重保险(配合本函数末尾「先精确停 watchdog 再自我退出」),彻底杜绝 watchdog 在替换窗口期
+ // 复活 daemon 抢占 47832 端口的竞态(历史上第一轮更新偶发失败、需点第二次才成功的根因)。
+ // apply-update.ps1 成功/失败都负责删除该标记。
+ const pendingFile = path.join(UPDATE_DIR, 'pending.json');
+ try { fs.writeFileSync(pendingFile, JSON.stringify({ attempt: attempt.id, at: new Date().toISOString() })); } catch (_) {}
+ // 【Windows 更新进程模型真相 · 挖坑实录 2.0】这条路踩遍三种写法,全部实例验证:
+ // ① detached:true + stdio:'ignore':PowerShell 5.1(console 程序)在 detached(无控制台)下宿主
+ // 初始化静默退出,-File 脚本根本不执行 → apply.log 永不生成、替换永不发生,面板一直「重启中」。
+ // ② 不 detached + pipe 收集输出:脚本能跑,但 Node 在 Windows 上 spawn 的子进程位于 Job Object,
+ // daemon 自我退出 → job 关闭 → powershell 被连带杀死(实测日志停在「停止 watchdog」一步)。
+ // ③ detached + cmd.exe /c 中转:cmd 同为 console 程序,一样不执行。
+ // 唯一可靠的「父进程死后子进程照跑」通道:wscript.exe(GUI 子系统,不依赖控制台)做中介,
+ // VBS 内 WScript.Shell.Run 用 ShellExecute 创建完全独立于 Node Job Object 的 powershell 进程。
+ const applyVbs = path.join(__dirname, 'apply-update.vbs');
+ if (!fs.existsSync(applyVbs)) {
+ const error = new Error('缺少 apply-update.vbs');
+ markAttemptFailure(error, 'preflight-error');
+ return Promise.reject(error);
+ }
+ const wscript = path.join(process.env.SystemRoot || 'C:\\Windows', 'System32', 'wscript.exe');
+ const child = spawn(
+ wscript,
+ ['//nologo', applyVbs, scriptPath, srcZip, appDir, String(ACTUAL_PORT), applyLog, attempt.id],
{ detached: true, stdio: 'ignore', windowsHide: true }
);
+ child.once('error', markSpawnFailure);
+ child.once('spawn', () => {
+ attempt.status = 'script-started';
+ attempt.scriptPid = child.pid;
+ writeUpdateAttempt(attempt);
+ log('[update] apply-update.ps1 已启动(经 wscript 中介) pid=' + child.pid);
+ });
child.unref();
- return Promise.resolve({ ok: true, message: '更新已启动,WorkDaddy 即将重启' });
+ // 【竞态加固 · 更新标记】daemon 自我退出后,watchdog 默认会在 3s 后重启新的 daemon 抢占 47832,
+ // 干扰替换。防复活职责完全交给「update/pending.json 更新标记」:watchdog 检测到标记后不自动
+ // 重启 daemon(见 watchdog.js),标记由 apply-update.ps1 finally 清理。
+ // ⚠️ 千万不要在这里用 spawnSync 去杀 watchdog / 做任何同步操作:spawnSync 会阻塞 Node 事件循环,
+ // daemon 将既无法响应 API(面板报「daemon 不可达」)也无法执行下面这行 process.exit(0),
+ // 安装目录一直被占用 → Mov-Item 报「正在使用中」→ 更新必失败(实测 4 连败的根因)。
+ // 直接干净退出即可,退出过程零阻塞(毫秒级)。
+ setTimeout(() => { try { process.exit(0); } catch (_) {} }, 800);
+ return Promise.resolve({ ok: true, message: '已启动更新,正在替换文件并自动重启,请稍候…' });
}
const scriptPath = path.join(__dirname, 'apply-update.sh');
- const appPath = '/Applications/WorkDaddy.app';
+ const appPath = macWorkDaddyAppPath();
const srcApp = path.join(UPDATE_DIR, 'WorkDaddy.app');
- if (!fs.existsSync(scriptPath)) return Promise.reject(new Error('缺少 apply-update.sh'));
+ if (!fs.existsSync(scriptPath)) {
+ const error = new Error('缺少 apply-update.sh');
+ markAttemptFailure(error, 'preflight-error');
+ return Promise.reject(error);
+ }
// 解出新应用:下载阶段只落了 .dmg,这里才把 WorkDaddy.app 从 dmg 解到 UPDATE_DIR(幂等:已解出则复用)
const dmgPath = path.join(UPDATE_DIR, 'WorkDaddy-' + updateState.latest + '.dmg');
const preUnpack = fs.existsSync(srcApp)
@@ -621,15 +757,24 @@ function applyUpdate() {
? (updateState.message = '正在解包新应用…', extractAppFromDmg(dmgPath))
: Promise.reject(new Error('缺少安装包(未找到已下载的 dmg)')));
return preUnpack.then((p) => {
- if (!fs.existsSync(p)) return Promise.reject(new Error('缺少解包后的新应用'));
- // 停掉自身 launchd 服务(KeepAlive 会在新版本启动后接管)
- execFile('launchctl', ['bootout', 'gui/' + process.getuid(), 'com.workbuddy.workdaddy'], () => {
- execFile('launchctl', ['remove', 'com.workbuddy.workdaddy'], () => {});
+ if (!fs.existsSync(p)) throw new Error('缺少解包后的新应用');
+ attempt.sourceApp = p;
+ attempt.targetApp = appPath;
+ writeUpdateAttempt(attempt);
+ log('[update] 执行 apply-update.sh attempt=' + attempt.id + ' src=' + p + ' dst=' + appPath + ' log=' + applyLog);
+ const child = spawn('bash', [scriptPath, p, appPath, String(ACTUAL_PORT), applyLog, attempt.id], { detached: true, stdio: 'ignore' });
+ child.once('error', markSpawnFailure);
+ child.once('spawn', () => {
+ attempt.status = 'script-started';
+ attempt.scriptPid = child.pid;
+ writeUpdateAttempt(attempt);
+ log('[update] apply-update.sh 已启动 pid=' + child.pid);
});
- log('[update] 执行 apply-update.sh,daemon 即将退出');
- const child = require('child_process').spawn('bash', [scriptPath, p, appPath, String(ACTUAL_PORT)], { detached: true, stdio: 'ignore' });
child.unref();
- return { ok: true, message: '更新已启动,WorkDaddy 即将重启' };
+ return { ok: true, message: '已启动更新,正在替换文件并自动重启,请稍候…' };
+ }).catch((error) => {
+ if (attempt.status === 'starting') markAttemptFailure(error, 'preflight-error');
+ throw error;
});
}
@@ -1714,12 +1859,17 @@ function sessionRangeMs(range) {
// tasks/<id>/、file-history/<id>/、artifact-index/<id>.json(全部以新 id 命名复制)
function copySessionFiles(wbHome, oldId, newId) {
const fsMod = fs;
+ const result = { copied: 0, failed: 0 };
const copyOne = (from, to) => {
try {
if (!fsMod.existsSync(from)) return;
fsMod.mkdirSync(path.dirname(to), { recursive: true });
fsMod.cpSync(from, to, { recursive: true, force: true });
- } catch (e) { log('[sessions-copy] 复制文件失败 ' + from + ': ' + e.message); }
+ result.copied++;
+ } catch (e) {
+ result.failed++;
+ log('[sessions-copy] 复制文件失败 ' + from + ': ' + e.message);
+ }
};
// 1) projects/<项目hash>/<id>.jsonl 与 <id>/ 目录(消息正文核心)
const projDir = path.join(wbHome, 'projects');
@@ -1743,6 +1893,238 @@ function copySessionFiles(wbHome, oldId, newId) {
// 5) artifact-index/<id>.json
copyOne(path.join(wbHome, 'artifact-index', oldId + '.json'), path.join(wbHome, 'artifact-index', newId + '.json'));
log('[sessions-copy] 已复制消息文件 ' + oldId + ' -> ' + newId);
+ return result;
+}
+
+const SESSION_COPY_COLUMNS = [
+ 'id', 'cwd', 'user_id', 'title', 'custom_title', 'status', 'created_at', 'updated_at',
+ 'last_activity_at', 'is_playground', 'source_mode', 'is_background_automation', 'mode', 'model',
+ 'expert_id', 'expert_locale', 'expert_runtime_identity', 'expert_marketplace', 'permission_mode',
+ 'use_sandbox_cli', 'project_id',
+];
+const sessionCopyLocks = new Map();
+
+function isTaskSessionRecord(cwd) {
+ return /[\\/]WorkBuddy[\\/]\d{4}-\d{2}-\d{2}[-]\d{2}[-]\d{2}[-]\d{2}/i.test(String(cwd || ''));
+}
+
+function sqlQuote(value) {
+ return "'" + String(value == null ? '' : value).replace(/'/g, "''") + "'";
+}
+
+function sqlNullable(value) {
+ return value === null || value === undefined || value === '' ? 'NULL' : sqlQuote(value);
+}
+
+async function insertCopiedSession(src, targetUid, newId) {
+ const vals = [
+ sqlQuote(newId),
+ sqlQuote(src.cwd || ''),
+ sqlQuote(targetUid),
+ sqlQuote(src.title || ''),
+ sqlQuote(src.custom_title || ''),
+ sqlQuote(src.status || 'Pending'),
+ String(src.created_at || Date.now()),
+ String(Date.now()),
+ String(src.last_activity_at || src.updated_at || Date.now()),
+ String(src.is_playground || 0),
+ sqlNullable(src.source_mode),
+ src.is_background_automation === null || src.is_background_automation === undefined || src.is_background_automation === '' ? 'NULL' : String(src.is_background_automation),
+ sqlNullable(src.mode),
+ sqlNullable(src.model),
+ sqlNullable(src.expert_id),
+ sqlNullable(src.expert_locale),
+ sqlNullable(src.expert_runtime_identity),
+ sqlNullable(src.expert_marketplace),
+ sqlNullable(src.permission_mode),
+ src.use_sandbox_cli === null || src.use_sandbox_cli === undefined || src.use_sandbox_cli === '' ? 'NULL' : String(src.use_sandbox_cli),
+ sqlNullable(src.project_id),
+ ];
+ await sqliteRun('INSERT INTO sessions (' + SESSION_COPY_COLUMNS.join(',') + ') VALUES (' + vals.join(',') + ');');
+}
+
+async function copySessionRecord(src, targetUid, options = {}) {
+ const sourceUid = String(options.sourceUid || src.user_id || '').trim();
+ const auto = !!options.auto;
+ const wbHome = path.join(os.homedir(), '.workbuddy');
+ let lineageId = options.lineageId || null;
+ const sourceLineage = sourceUid ? getAutoCopySession(DATA_DIR, sourceUid, src.id) : { lineageId: null, enabled: false };
+ if (!lineageId && sourceLineage.enabled) lineageId = sourceLineage.lineageId;
+ if (auto && sourceUid && !lineageId) lineageId = ensureAutoCopySession(DATA_DIR, sourceUid, src.id);
+ const perform = async () => {
+ if (sourceUid && lineageId) {
+ const mapping = getAutoCopyMapping(DATA_DIR, lineageId, targetUid);
+ if (mapping && mapping.targetId) {
+ const existing = await sqliteQuery('SELECT id, user_id FROM sessions WHERE id = ' + sqlQuote(mapping.targetId) + ' AND deleted_at IS NULL LIMIT 1;');
+ if (existing.length && String(existing[0].user_id || '') === String(targetUid)) {
+ const files = copySessionFiles(wbHome, src.id, mapping.targetId);
+ addAutoCopySessionMember(DATA_DIR, lineageId, targetUid, mapping.targetId);
+ setAutoCopyMapping(DATA_DIR, lineageId, targetUid, {
+ targetId: mapping.targetId,
+ status: files.failed ? 'partial' : 'copied',
+ failedFiles: files.failed,
+ });
+ return { status: files.failed ? 'partial' : 'skipped', sourceId: src.id, targetId: mapping.targetId, failedFiles: files.failed };
+ }
+ deleteAutoCopyMapping(DATA_DIR, lineageId, targetUid);
+ }
+ }
+
+ const newId = crypto.randomUUID();
+ await insertCopiedSession(src, targetUid, newId);
+ const files = copySessionFiles(wbHome, src.id, newId);
+ if (lineageId) {
+ addAutoCopySessionMember(DATA_DIR, lineageId, targetUid, newId);
+ setAutoCopyMapping(DATA_DIR, lineageId, targetUid, {
+ targetId: newId,
+ status: files.failed ? 'partial' : 'copied',
+ failedFiles: files.failed,
+ });
+ }
+ return { status: files.failed ? 'partial' : 'copied', sourceId: src.id, targetId: newId, failedFiles: files.failed };
+ };
+ if (!lineageId) return perform();
+ const lockKey = JSON.stringify([lineageId, String(targetUid || '')]);
+ const previous = sessionCopyLocks.get(lockKey) || Promise.resolve();
+ const current = previous.catch(() => {}).then(perform);
+ sessionCopyLocks.set(lockKey, current);
+ try {
+ return await current;
+ } finally {
+ if (sessionCopyLocks.get(lockKey) === current) sessionCopyLocks.delete(lockKey);
+ }
+}
+
+async function buildAutoCopyPlan(sourceUid, targetUid) {
+ const source = String(sourceUid || '').trim();
+ const target = String(targetUid || '').trim();
+ if (!source || !target || source === target) return [];
+ const rules = getAutoCopyRules(DATA_DIR, source);
+ if (!rules.sessionIds.length && !rules.workspaces.length) return [];
+ const rows = await sqliteQuery(
+ 'SELECT id, cwd, user_id, title, custom_title, status, created_at, updated_at, last_activity_at, is_playground, source_mode, is_background_automation, mode, model, expert_id, expert_locale, expert_runtime_identity, expert_marketplace, permission_mode, use_sandbox_cli, project_id ' +
+ 'FROM sessions WHERE deleted_at IS NULL AND user_id = ' + sqlQuote(source) + ' ORDER BY created_at DESC;'
+ );
+ const sessionSet = new Set(rules.sessionIds);
+ const workspaceSet = new Set(rules.workspaces.map(canonicalWorkspace));
+ return rows
+ .filter((row) => !isTaskSessionRecord(row.cwd))
+ .filter((row) => sessionSet.has(String(row.id)) || workspaceSet.has(canonicalWorkspace(row.cwd)))
+ .map((row) => Object.assign({}, row, { lineageId: rules.lineages[String(row.id)] || null }));
+}
+
+const autoCopyJobs = new Map();
+const autoCopyQueue = [];
+let autoCopyWorkerRunning = false;
+
+function hasPendingAutoCopyTo(uid) {
+ const target = String(uid || '').trim();
+ if (!target) return false;
+ for (const job of autoCopyJobs.values()) {
+ if (job.targetUid === target && (job.status === 'queued' || job.status === 'running')) return true;
+ }
+ return false;
+}
+
+function pruneAutoCopyJobs() {
+ const completed = Array.from(autoCopyJobs.values())
+ .filter((job) => job.status === 'done' || job.status === 'partial' || job.status === 'error')
+ .sort((a, b) => (a.finishedAt || 0) - (b.finishedAt || 0));
+ while (completed.length > 100) {
+ const oldest = completed.shift();
+ autoCopyJobs.delete(oldest.id);
+ }
+}
+
+function runAutoCopyQueue() {
+ if (autoCopyWorkerRunning || !autoCopyQueue.length) return;
+ autoCopyWorkerRunning = true;
+ const item = autoCopyQueue.shift();
+ item.run()
+ .catch((e) => {
+ const job = item.job;
+ job.status = 'error';
+ job.error = e.message;
+ job.finishedAt = Date.now();
+ log(`[sessions-auto-copy] 任务失败: ${e.message}`);
+ const cleanup = setTimeout(() => autoCopyJobs.delete(job.id), 30 * 60 * 1000);
+ if (cleanup.unref) cleanup.unref();
+ pruneAutoCopyJobs();
+ })
+ .finally(() => {
+ autoCopyWorkerRunning = false;
+ runAutoCopyQueue();
+ });
+}
+
+function startAutoCopyJob(sourceUid, targetUid, plan) {
+ const id = crypto.randomUUID();
+ const job = {
+ id,
+ status: 'queued',
+ sourceUid,
+ targetUid,
+ plan: Array.isArray(plan) ? plan : [],
+ total: Array.isArray(plan) ? plan.length : 0,
+ processed: 0,
+ copied: 0,
+ skipped: 0,
+ failed: 0,
+ partial: 0,
+ error: null,
+ startedAt: Date.now(),
+ };
+ autoCopyJobs.set(id, job);
+ const run = async () => {
+ job.status = 'running';
+ // A rapid switch chain may enqueue this job before the previous copy has
+ // created the target rows. Re-plan after the queue reaches this job.
+ job.plan = await buildAutoCopyPlan(sourceUid, targetUid);
+ job.total = job.plan.length;
+ for (const src of job.plan) {
+ try {
+ const result = await copySessionRecord(src, targetUid, {
+ sourceUid,
+ lineageId: src.lineageId || undefined,
+ auto: true,
+ });
+ if (result.status === 'skipped') job.skipped++;
+ else if (result.status === 'partial') job.partial++;
+ else job.copied++;
+ if (result.failedFiles) job.failed += result.failedFiles;
+ } catch (e) {
+ job.failed++;
+ log(`[sessions-auto-copy] ${sourceUid} -> ${targetUid} 会话 ${src.id} 失败: ${e.message}`);
+ }
+ job.processed++;
+ }
+ job.status = job.failed || job.partial ? 'partial' : 'done';
+ job.finishedAt = Date.now();
+ log(`[sessions-auto-copy] ${sourceUid} -> ${targetUid} 完成 total=${job.total} copied=${job.copied} skipped=${job.skipped} partial=${job.partial} failed=${job.failed}`);
+ const cleanup = setTimeout(() => autoCopyJobs.delete(id), 30 * 60 * 1000);
+ if (cleanup.unref) cleanup.unref();
+ pruneAutoCopyJobs();
+ };
+ // Serialising jobs makes a chain such as h -> s -> x observe the sessions
+ // created by the preceding job, even when the user switches rapidly.
+ autoCopyQueue.push({ job, run });
+ runAutoCopyQueue();
+ return job;
+}
+
+function publicAutoCopyJob(job) {
+ if (!job) return null;
+ return {
+ id: job.id,
+ status: job.status,
+ total: job.total,
+ processed: job.processed,
+ copied: job.copied,
+ skipped: job.skipped,
+ partial: job.partial,
+ failed: job.failed,
+ error: job.error,
+ };
}
// 真实删除会话的消息文件:projects/<项目>/<id>.jsonl + <id>/、workspace/sessions/<id>/、
@@ -3075,8 +3457,9 @@ function handleApi(req, res) {
if (!uid) return json(res, 400, { ok: false, error: '缺少 uid' });
try {
const r = deleteAccount(DATA_DIR, uid);
+ const rulesRemoved = removeAutoCopyAccount(DATA_DIR, uid);
log(`[delete] 已永久删除账号备份 ${uid}`);
- return json(res, 200, { ok: true, deleted: r.deleted, uid });
+ return json(res, 200, { ok: true, deleted: r.deleted, uid, rulesRemoved });
} catch (e) {
return json(res, 500, { ok: false, error: e.message });
}
@@ -3462,15 +3845,207 @@ function handleApi(req, res) {
if (uid) clauses.push("user_id = '" + uid.replace(/'/g, "''") + "'");
if (rangeMs) clauses.push('created_at >= ' + rangeMs);
return sqliteQuery("SELECT id, cwd, user_id, title, custom_title, status, created_at, updated_at, last_activity_at, is_playground, project_id FROM sessions WHERE " + clauses.join(' AND ') + " ORDER BY created_at DESC;")
- .then((rows) => json(res, 200, { ok: true, sessions: rows, count: rows.length, uid, range }))
+ .then((rows) => {
+ const rulesByUid = {};
+ rows.forEach((row) => {
+ const owner = String(row.user_id || '').trim();
+ if (!owner || rulesByUid[owner]) return;
+ const rules = getAutoCopyRules(DATA_DIR, owner);
+ rulesByUid[owner] = { sessions: new Set(rules.sessionIds), workspaces: new Set(rules.workspaces) };
+ });
+ const sessions = rows.map((row) => {
+ const rules = rulesByUid[String(row.user_id || '').trim()] || { sessions: new Set(), workspaces: new Set() };
+ return Object.assign({}, row, {
+ autoCopySession: rules.sessions.has(String(row.id)),
+ autoCopyWorkspace: rules.workspaces.has(canonicalWorkspace(row.cwd)),
+ });
+ });
+ const currentRules = uid
+ ? (rulesByUid[uid] || (() => {
+ const rules = getAutoCopyRules(DATA_DIR, uid);
+ return { sessions: new Set(rules.sessionIds), workspaces: new Set(rules.workspaces) };
+ })())
+ : null;
+ return json(res, 200, {
+ ok: true,
+ sessions,
+ count: sessions.length,
+ uid,
+ range,
+ autoCopy: currentRules ? { sessionIds: Array.from(currentRules.sessions), workspaces: Array.from(currentRules.workspaces) } : null,
+ });
+ })
.catch((e) => json(res, 500, { ok: false, error: e.message }));
}
// 会话空间列表:GET /api/sessions/workspaces
if (req.method === 'GET' && p === '/api/sessions/workspaces') {
- return sqliteQuery("SELECT DISTINCT cwd FROM sessions WHERE deleted_at IS NULL AND cwd IS NOT NULL AND cwd != '' ORDER BY cwd;")
+ return sqliteQuery("SELECT DISTINCT cwd FROM sessions WHERE deleted_at IS NULL AND cwd IS NOT NULL AND cwd != '' ORDER BY cwd;")
.then((rows) => json(res, 200, { ok: true, workspaces: rows.map((r) => r.cwd) }))
.catch((e) => json(res, 500, { ok: false, error: e.message }));
}
+ // 模型连通测试:只返回网络/HTTP 状态,不记录或回传 URL 查询参数、API Key 等敏感内容。
+ // 大多数 OpenAI 兼容服务的根路径不响应(404),因此按候选顺序探测真实端点:
+ // {base}/models → {base}/v1/models(base 未带版本前缀时)→ base 本身。
+ // 2xx/3xx/401/403/400/405 视为端点真实命中并立即返回;404/5xx/网络错误则继续尝试下一个候选。
+ async function probeModelEndpoint(model) {
+ // url 可能是完整端点(.../v1/chat/completions),先规约到 base 再按候选探测
+ let base = String(model && model.url || '').trim().replace(/\/+$/, '');
+ if (!/^https?:\/\//i.test(base)) throw new Error('模型 URL 仅支持 http/https');
+ if (/\/chat\/completions$/i.test(base)) base = base.replace(/\/chat\/completions$/i, '');
+ const headers = { Accept: 'application/json, text/plain, */*', 'User-Agent': 'WorkDaddy probe/1.0' };
+ if (model.apiKey) headers.Authorization = 'Bearer ' + String(model.apiKey);
+ const candidates = [base + '/models'];
+ if (!/\/v\d+$/i.test(base)) candidates.push(base + '/v1/models');
+ candidates.push(base);
+ let lastStatus = 0;
+ let lastError = '';
+ for (const target of candidates) {
+ let response = null;
+ try {
+ response = await fetch(target, { method: 'HEAD', headers, redirect: 'manual', signal: AbortSignal.timeout(6000) });
+ if (response.status === 405 || response.status === 501) {
+ response = await fetch(target, { method: 'GET', headers, redirect: 'manual', signal: AbortSignal.timeout(6000) });
+ }
+ } catch (e) {
+ lastError = (e && e.message) || String(e);
+ continue;
+ }
+ const status = response.status;
+ lastStatus = status;
+ if (status === 404) continue; // 路径不存在:尝试下一个候选
+ if (status >= 200 && status < 500) {
+ return {
+ status,
+ reachable: true,
+ authorized: status >= 200 && status < 300,
+ message: status >= 200 && status < 300
+ ? '接口可用'
+ : (status === 401 || status === 403 ? '接口可达,但 API Key 可能无效' : `接口返回 HTTP ${status}`),
+ };
+ }
+ }
+ const message = lastStatus ? `接口返回 HTTP ${lastStatus}` : (lastError ? `请求失败:${lastError}` : '无法连接模型服务');
+ return { status: lastStatus, reachable: false, authorized: false, message };
+ }
+
+ // 模型管理:列表返回供模型页 UI 展示的摘要(apiKey 明文,供 cell/编辑弹窗直接展示;
+ // 仅本机 loopback 服务,不写日志、不上传)。备份文件保留完整配置,参考 docs 下工作流说明。
+ if (req.method === 'GET' && p === '/api/models') {
+ let official = [];
+ let officialError = null;
+ try {
+ official = listOfficialModels();
+ } catch (e) {
+ officialError = e.message;
+ }
+ return json(res, 200, { ok: true, file: workbuddyModelsFile(), official, officialError, backups: listModelBackups(DATA_DIR) });
+ }
+ if (req.method === 'POST' && p === '/api/models/backup') {
+ return readBody(req).then((body) => {
+ try {
+ const backup = backupOfficialModel(DATA_DIR, body && body.index);
+ return json(res, 200, { ok: true, backup });
+ } catch (e) {
+ return json(res, 400, { ok: false, error: e.message });
+ }
+ });
+ }
+ if (req.method === 'POST' && p === '/api/models/delete-official') {
+ return readBody(req).then((body) => {
+ try {
+ const indexes = Array.isArray(body && body.indexes) ? body.indexes : [];
+ const result = deleteOfficialModels(workbuddyModelsFile(), indexes);
+ return json(res, 200, { ok: true, deleted: result.deleted, official: result.official, backups: listModelBackups(DATA_DIR) });
+ } catch (e) {
+ return json(res, 400, { ok: false, error: e.message });
+ }
+ });
+ }
+ if (req.method === 'POST' && p === '/api/models/test') {
+ return readBody(req).then(async (body) => {
+ try {
+ const index = Number(body && body.index);
+ const model = readOfficialModel(workbuddyModelsFile(), index);
+ const result = await probeModelEndpoint(model);
+ return json(res, 200, { ok: true, result });
+ } catch (e) {
+ return json(res, 400, { ok: false, error: e.message });
+ }
+ });
+ }
+ if (req.method === 'POST' && p === '/api/models/copy') {
+ return readBody(req).then((body) => {
+ try {
+ const backupId = String((body && body.backupId) || '');
+ if (!backupId) return json(res, 400, { ok: false, error: '缺少模型备份标识' });
+ const copied = copyModelBackup(DATA_DIR, backupId);
+ return json(res, 200, { ok: true, copied, backups: listModelBackups(DATA_DIR) });
+ } catch (e) {
+ return json(res, 400, { ok: false, error: e.message });
+ }
+ });
+ }
+ if (req.method === 'POST' && p === '/api/models/edit') {
+ return readBody(req).then((body) => {
+ try {
+ const backupId = String((body && body.backupId) || '');
+ if (!backupId) return json(res, 400, { ok: false, error: '缺少模型备份标识' });
+ const patch = body && body.patch && typeof body.patch === 'object' ? body.patch : {};
+ const edited = editModelBackup(DATA_DIR, backupId, patch);
+ return json(res, 200, { ok: true, edited, backups: listModelBackups(DATA_DIR) });
+ } catch (e) {
+ return json(res, 400, { ok: false, error: e.message });
+ }
+ });
+ }
+ if (req.method === 'POST' && p === '/api/models/delete') {
+ return readBody(req).then((body) => {
+ try {
+ const ids = Array.isArray(body && body.backupIds) ? body.backupIds : [];
+ if (!ids.length) return json(res, 400, { ok: false, error: '未选择模型备份' });
+ const deleted = deleteModelBackups(DATA_DIR, ids);
+ return json(res, 200, { ok: true, deleted, backups: listModelBackups(DATA_DIR) });
+ } catch (e) {
+ return json(res, 400, { ok: false, error: e.message });
+ }
+ });
+ }
+ if (req.method === 'POST' && p === '/api/models/enable') {
+ return readBody(req).then((body) => {
+ try {
+ const backupId = String((body && body.backupId) || '');
+ if (!backupId) return json(res, 400, { ok: false, error: '缺少模型备份标识' });
+ const enabled = enableModelBackup(DATA_DIR, backupId);
+ return json(res, 200, { ok: true, enabled, official: listOfficialModels(), backups: listModelBackups(DATA_DIR) });
+ } catch (e) {
+ return json(res, 400, { ok: false, error: e.message });
+ }
+ });
+ }
+ // 自动复制规则:POST /api/sessions/auto-copy { uid, kind: session|workspace, key, enabled }
+ if (req.method === 'POST' && p === '/api/sessions/auto-copy') {
+ return readBody(req).then(async (body) => {
+ try {
+ const uid = String(body.uid || '').trim();
+ const kind = body.kind === 'workspace' ? 'workspace' : 'session';
+ const key = String(body.key || '').trim();
+ if (!uid || !key) return json(res, 400, { ok: false, error: '缺少自动复制规则参数' });
+ if (kind === 'session') {
+ const rows = await sqliteQuery('SELECT user_id FROM sessions WHERE id = ' + sqlQuote(key) + ' AND deleted_at IS NULL LIMIT 1;');
+ if (!rows.length || String(rows[0].user_id || '') !== uid) return json(res, 404, { ok: false, error: '会话不存在或不属于该账号' });
+ }
+ const rules = setAutoCopyRule(DATA_DIR, { uid, kind, key, enabled: body.enabled !== false });
+ return json(res, 200, { ok: true, uid, kind, key: kind === 'workspace' ? canonicalWorkspace(key) : key, rules });
+ } catch (e) {
+ return json(res, 400, { ok: false, error: e.message });
+ }
+ });
+ }
+ // 自动复制任务状态:GET /api/sessions/auto-copy/status?id=<jobId>
+ if (req.method === 'GET' && p === '/api/sessions/auto-copy/status') {
+ const job = autoCopyJobs.get(url.searchParams.get('id') || '');
+ return job ? json(res, 200, { ok: true, job: publicAutoCopyJob(job) }) : json(res, 404, { ok: false, error: '自动复制任务不存在' });
+ }
// 复制会话:POST /api/sessions/copy { ids, targetUid }(保留原会话,复制记录+消息文件到目标账号)
if (req.method === 'POST' && p === '/api/sessions/copy') {
return readBody(req).then(async (body) => {
@@ -3480,42 +4055,12 @@ function handleApi(req, res) {
if (!targetUid) return json(res, 400, { ok: false, error: '未指定目标账号' });
try {
const esc = ids.map((i) => "'" + String(i).replace(/'/g, "''") + "'").join(',');
- const tU = targetUid.replace(/'/g, "''");
// 1) 取出源会话(含 cwd 用于定位消息文件)
const srcRows = await sqliteQuery("SELECT id, cwd, user_id, title, custom_title, status, created_at, updated_at, last_activity_at, is_playground, source_mode, is_background_automation, mode, model, expert_id, expert_locale, expert_runtime_identity, expert_marketplace, permission_mode, use_sandbox_cli, project_id FROM sessions WHERE id IN (" + esc + ") AND deleted_at IS NULL;");
if (!srcRows.length) return json(res, 404, { ok: false, error: '源会话不存在' });
- const wbHome = path.join(os.homedir(), '.workbuddy');
let copied = 0;
for (const src of srcRows) {
- const newId = crypto.randomUUID();
- // 2) INSERT 新会话记录
- const cols = ['id', 'cwd', 'user_id', 'title', 'custom_title', 'status', 'created_at', 'updated_at', 'last_activity_at', 'is_playground', 'source_mode', 'is_background_automation', 'mode', 'model', 'expert_id', 'expert_locale', 'expert_runtime_identity', 'expert_marketplace', 'permission_mode', 'use_sandbox_cli', 'project_id'];
- const vals = [
- "'" + newId + "'",
- "'" + String(src.cwd || '').replace(/'/g, "''") + "'",
- "'" + tU + "'",
- "'" + String(src.title || '').replace(/'/g, "''") + "'",
- "'" + String(src.custom_title || '').replace(/'/g, "''") + "'",
- "'" + String(src.status || 'Pending').replace(/'/g, "''") + "'",
- String(src.created_at || Date.now()),
- String(Date.now()),
- String(src.last_activity_at || src.updated_at || Date.now()),
- String(src.is_playground || 0),
- src.source_mode ? "'" + String(src.source_mode).replace(/'/g, "''") + "'" : 'NULL',
- src.is_background_automation === null || src.is_background_automation === undefined || src.is_background_automation === '' ? 'NULL' : String(src.is_background_automation),
- src.mode ? "'" + String(src.mode).replace(/'/g, "''") + "'" : 'NULL',
- src.model ? "'" + String(src.model).replace(/'/g, "''") + "'" : 'NULL',
- src.expert_id ? "'" + String(src.expert_id).replace(/'/g, "''") + "'" : 'NULL',
- src.expert_locale ? "'" + String(src.expert_locale).replace(/'/g, "''") + "'" : 'NULL',
- src.expert_runtime_identity ? "'" + String(src.expert_runtime_identity).replace(/'/g, "''") + "'" : 'NULL',
- src.expert_marketplace ? "'" + String(src.expert_marketplace).replace(/'/g, "''") + "'" : 'NULL',
- src.permission_mode ? "'" + String(src.permission_mode).replace(/'/g, "''") + "'" : 'NULL',
- src.use_sandbox_cli === null || src.use_sandbox_cli === undefined || src.use_sandbox_cli === '' ? 'NULL' : String(src.use_sandbox_cli),
- src.project_id ? "'" + String(src.project_id).replace(/'/g, "''") + "'" : 'NULL',
- ];
- await sqliteRun("INSERT INTO sessions (" + cols.join(',') + ") VALUES (" + vals.join(',') + ");");
- // 3) 复制消息文件(jsonl + 目录 + 索引)
- copySessionFiles(wbHome, src.id, newId);
+ await copySessionRecord(src, targetUid);
copied++;
}
return json(res, 200, { ok: true, copied, targetUid });
@@ -3526,15 +4071,29 @@ function handleApi(req, res) {
}
// 迁移会话:POST /api/sessions/migrate { ids, targetUid }
if (req.method === 'POST' && p === '/api/sessions/migrate') {
- return readBody(req).then((body) => {
+ return readBody(req).then(async (body) => {
const ids = Array.isArray(body.ids) ? body.ids.filter((x) => typeof x === 'string') : [];
const targetUid = (body.targetUid || '').trim();
if (!ids.length) return json(res, 400, { ok: false, error: '未选择会话' });
if (!targetUid) return json(res, 400, { ok: false, error: '未指定目标账号' });
- const esc = ids.map((i) => "'" + String(i).replace(/'/g, "''") + "'").join(',');
- return sqliteRun("UPDATE sessions SET user_id = '" + targetUid.replace(/'/g, "''") + "', updated_at = " + Date.now() + " WHERE id IN (" + esc + ");")
- .then(() => json(res, 200, { ok: true, moved: ids.length, targetUid }))
- .catch((e) => json(res, 500, { ok: false, error: e.message }));
+ try {
+ const esc = ids.map((i) => sqlQuote(i)).join(',');
+ const before = await sqliteQuery('SELECT id, user_id FROM sessions WHERE id IN (' + esc + ') AND deleted_at IS NULL;');
+ await sqliteRun("UPDATE sessions SET user_id = " + sqlQuote(targetUid) + ", updated_at = " + Date.now() + " WHERE id IN (" + esc + ");");
+ let rulesMoved = 0;
+ for (const row of before) {
+ if (String(row.user_id || '') === targetUid) continue;
+ try {
+ if (moveAutoCopySession(DATA_DIR, row.user_id, targetUid, row.id)) rulesMoved++;
+ } catch (e) {
+ // The DB move is complete; surface rule maintenance separately so it can be retried.
+ log(`[sessions-auto-copy] 迁移规则 ${row.id} 失败: ${e.message}`);
+ }
+ }
+ return json(res, 200, { ok: true, moved: before.length, requested: ids.length, targetUid, rulesMoved });
+ } catch (e) {
+ return json(res, 500, { ok: false, error: e.message });
+ }
});
}
// 删除会话(真实删除):POST /api/sessions/delete { ids }——删除 DB 记录 + 该账号下全部会话文件(不可恢复)
@@ -3543,15 +4102,24 @@ function handleApi(req, res) {
const ids = Array.isArray(body.ids) ? body.ids.filter((x) => typeof x === 'string') : [];
if (!ids.length) return json(res, 400, { ok: false, error: '未选择会话' });
try {
- const esc = ids.map((i) => "'" + String(i).replace(/'/g, "''") + "'").join(',');
+ const esc = ids.map((i) => sqlQuote(i)).join(',');
+ const before = await sqliteQuery('SELECT id, user_id FROM sessions WHERE id IN (' + esc + ');');
// 1) 真实删除 DB 记录(非软删)
await sqliteRun("DELETE FROM sessions WHERE id IN (" + esc + ");");
// 2) 删除本地消息文件(jsonl/目录/workspace/tasks/file-history/artifact-index)
const wbHome = path.join(os.homedir(), '.workbuddy');
let filesRemoved = 0;
for (const id of ids) filesRemoved += deleteSessionFiles(wbHome, id);
+ let rulesRemoved = 0;
+ for (const row of before) {
+ try {
+ if (removeAutoCopySession(DATA_DIR, row.user_id, row.id)) rulesRemoved++;
+ } catch (e) {
+ log(`[sessions-auto-copy] 删除规则 ${row.id} 失败: ${e.message}`);
+ }
+ }
log(`[sessions-delete] 已真实删除 ${ids.length} 个会话(DB + ${filesRemoved} 项文件)`);
- return json(res, 200, { ok: true, deleted: ids.length, filesRemoved });
+ return json(res, 200, { ok: true, deleted: before.length, requested: ids.length, filesRemoved, rulesRemoved });
} catch (e) {
return json(res, 500, { ok: false, error: e.message });
}
@@ -3788,6 +4356,8 @@ function handleApi(req, res) {
latest: updateState.latest,
hasUpdate: updateState.hasUpdate,
downloaded: updateState.downloaded,
+ attemptId: updateState.attemptId,
+ applyLog: path.join(UPDATE_DIR, 'apply.log'),
});
}
if (req.method === 'POST' && p === '/api/update-download') {
@@ -3802,7 +4372,7 @@ function handleApi(req, res) {
}
if (req.method === 'POST' && p === '/api/update-apply') {
return applyUpdate()
- .then((r) => json(res, 200, r))
+ .then((r) => json(res, 200, { ...r, attemptId: updateState.attemptId, applyLog: path.join(UPDATE_DIR, 'apply.log') }))
.catch((e) => json(res, 200, { ok: false, error: e.message }));
}
@@ -3980,6 +4550,16 @@ function handleApi(req, res) {
const uid = (body.uid || '').trim();
if (!uid) return json(res, 400, { ok: false, error: '缺少 uid' });
try {
+ // 先记录源账号并规划自动复制内容;切换后异步执行,避免阻塞 WorkBuddy 刷新。
+ const sourceUid = String((currentAccount() || {}).uid || '').trim();
+ let autoCopyPlan = [];
+ if (sourceUid && sourceUid !== uid) {
+ try {
+ autoCopyPlan = await buildAutoCopyPlan(sourceUid, uid);
+ } catch (e) {
+ log(`[sessions-auto-copy] 规划失败 ${sourceUid} -> ${uid}: ${e.message}`);
+ }
+ }
const acct = switchTo(DATA_DIR, uid, log);
const hint = '登录文件已切换,请重启 WorkBuddy 使新账号生效';
let reloaded = false;
@@ -3996,11 +4576,15 @@ function handleApi(req, res) {
log(`[switch] CDP 刷新失败: ${e.message}`);
}
}
+ const autoCopyJob = (autoCopyPlan.length || hasPendingAutoCopyTo(sourceUid))
+ ? startAutoCopyJob(sourceUid, uid, autoCopyPlan)
+ : null;
return json(res, 200, {
ok: true,
uid: acct.uid,
nickname: acct.nickname,
reloaded,
+ autoCopy: autoCopyJob ? { jobId: autoCopyJob.id, total: autoCopyJob.total } : { total: 0 },
hint: reloaded ? '已切换并触发窗口刷新' : hint,
});
} catch (e) {
diff --git a/scripts/inject.js b/scripts/inject.js
index ac7b67f..300b176 100644
--- a/scripts/inject.js
+++ b/scripts/inject.js
@@ -110,11 +110,27 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
var SWITCH_SVG =
'<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">' +
'<path d="M16 3l4 4-4 4"/><path d="M20 7H8"/><path d="M8 21l-4-4 4-4"/><path d="M4 17h12"/></svg>';
+ var AUTO_COPY_SVG =
+ '<svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">' +
+ '<rect x="8" y="8" width="12" height="12" rx="2"/><path d="M4 16V6a2 2 0 0 1 2-2h10"/><path d="M15 3l3 1-1 3"/></svg>';
var TRASH_SVG =
'<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">' +
'<path d="M3 6h18"/><path d="M8 6V4a1 1 0 0 1 1-1h6a1 1 0 0 1 1 1v2"/>' +
'<path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/>' +
'<path d="M10 11v6"/><path d="M14 11v6"/></svg>';
+ var MODEL_BACKUP_SVG =
+ '<svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2Z"/><polyline points="17 21 17 13 7 13 7 21"/><polyline points="7 3 7 8 15 8"/></svg>';
+ var MODEL_TEST_SVG =
+ '<svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><polygon points="13 2 3 14 11 14 10 22 21 10 13 10 13 2"/></svg>';
+ var MODEL_COPY_SVG =
+ '<svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><rect x="8" y="8" width="12" height="12" rx="2"/><path d="M4 16V6a2 2 0 0 1 2-2h10"/></svg>';
+ var MODEL_EDIT_SVG =
+ '<svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="m4 16-.8 4.8L8 20l11.5-11.5a2.1 2.1 0 0 0-3-3L5 17z"/><path d="m14.5 7.5 2 2"/></svg>';
+ var MODEL_ENABLE_SVG =
+ '<svg viewBox="0 0 24 24" width="15" height="15" fill="currentColor"><path d="M8 5.2a1 1 0 0 1 1.55-.83l9.6 6.8a1 1 0 0 1 0 1.66l-9.6 6.8A1 1 0 0 1 8 18.8V5.2Z"/></svg>';
+ // 小贴士提示图标(灯泡,tips 通知风格)
+ var MODEL_TIP_SVG =
+ '<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M9 18h6"/><path d="M10 22h4"/><path d="M12 2a7 7 0 0 0-4 12.7c.6.5 1 1.4 1 2.3h6c0-.9.4-1.8 1-2.3A7 7 0 0 0 12 2Z"/></svg>';
var GIFT_SVG =
'<svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">' +
'<rect x="3" y="8" width="18" height="4" rx="1"/>' +
@@ -560,6 +576,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'<button class="wbs-tab active" type="button" data-tab="account"><svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg><span>账号</span></button>',
'<button class="wbs-tab" type="button" data-tab="theme"><svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 2a10 10 0 1 0 10 10c0-1.5-1-2-2-2h-3a2 2 0 0 1-2-2c0-1.5 1-2 1-2h2c0-3-2-4-6-4z"/><circle cx="13.5" cy="6.5" r="1"/><circle cx="17.5" cy="10.5" r="1"/><circle cx="8.5" cy="7.5" r="1"/><circle cx="6.5" cy="12.5" r="1"/></svg><span>主题</span></button>',
'<button class="wbs-tab" type="button" data-tab="sessions"><svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg><span>会话</span></button>',
+ '<button class="wbs-tab" type="button" data-tab="models"><svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m12 2 9 5-9 5-9-5 9-5Z"/><path d="m3 12 9 5 9-5"/><path d="m3 17 9 5 9-5"/></svg><span>模型</span></button>',
'<button class="wbs-tab" type="button" data-tab="enhance"><svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M13 2L3 14h9l-1 8 10-12h-9l1-8z"/></svg><span>增强</span></button>',
'<button class="wbs-tab" type="button" data-tab="about"><svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></svg><span>关于</span></button>',
'</div>',
@@ -567,6 +584,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'<div class="wbs-pane active" data-pane="account"></div>',
'<div class="wbs-pane" data-pane="theme"></div>',
'<div class="wbs-pane" data-pane="sessions"></div>',
+ '<div class="wbs-pane" data-pane="models"></div>',
'<div class="wbs-pane" data-pane="enhance"></div>',
'<div class="wbs-pane" data-pane="about"></div>',
'</div>',
@@ -1326,6 +1344,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
var accountsPane = root.querySelector('[data-pane="account"]');
var themePane = root.querySelector('[data-pane="theme"]');
var sessionsPane = root.querySelector('[data-pane="sessions"]');
+ var modelsPane = root.querySelector('[data-pane="models"]');
var enhancePane = root.querySelector('[data-pane="enhance"]');
var aboutPane = root.querySelector('[data-pane="about"]');
var logoutBtn = root.querySelector('[data-act="logout"]');
@@ -1459,6 +1478,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
for (var j = 0; j < panes.length; j++) panes[j].classList.toggle('active', panes[j].getAttribute('data-pane') === name);
if (name === 'theme') { if (themePane && !themePane.dataset.built) buildThemePane(); loadWallpapers(); }
if (name === 'sessions' && sessionsPane && !sessionsPane.dataset.built) buildSessionsPane();
+ if (name === 'models' && modelsPane && !modelsPane.dataset.built) buildModelsPane();
if (name === 'enhance' && enhancePane && !enhancePane.dataset.built) buildEnhancePane();
if (name === 'about' && aboutPane && !aboutPane.dataset.built) buildAboutPane();
}
@@ -1470,7 +1490,25 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
}
// ===== 会话 pane(构建:账号/时间筛选 + 按空间分组[默认2条/展开10条] + 刷新 + 批量操作[迁移/删除])=====
- var sessionsState = { uid: undefined, range: '7d', list: [], selected: {}, wsExpanded: {}, accounts: [], batchMode: false };
+ var sessionsState = { uid: undefined, range: '7d', list: [], selected: {}, wsExpanded: {}, accounts: [], batchMode: false, autoCopy: null };
+ function isTaskSessionRecordUI(cwd) {
+ return /[\\/]WorkBuddy[\\/]\d{4}-\d{2}-\d{2}[-]\d{2}[-]\d{2}[-]\d{2}/i.test(String(cwd || ''));
+ }
+ function canonicalWorkspaceUI(cwd) {
+ var value = String(cwd || '').trim().replace(/\\/g, '/');
+ if (!value) return '';
+ value = value.replace(/\/+/g, '/');
+ var parts = value.split('/');
+ var out = [];
+ parts.forEach(function (part) {
+ if (!part || part === '.') return;
+ if (part === '..') { if (out.length && out[out.length - 1] !== '..') out.pop(); return; }
+ out.push(part);
+ });
+ value = (value.charAt(0) === '/' ? '/' : '') + out.join('/');
+ if (value.length > 1) value = value.replace(/\/+$/, '');
+ return value;
+ }
var SESS_WS_INIT = 2; // 每个空间默认显示条数
var SESS_WS_STEP = 10; // 展开一次追加条数
function buildSessionsPane() {
@@ -1554,6 +1592,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
if (sessionsState.uid !== undefined) url += '&uid=' + encodeURIComponent(sessionsState.uid);
api(url).then(function (d) {
sessionsState.list = (d && d.sessions) || [];
+ sessionsState.autoCopy = (d && d.autoCopy) || null;
sessionsState.selected = {};
sessionsState.wsExpanded = {};
renderSessions();
@@ -1571,7 +1610,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
});
}
- // 按空间分组渲染:每个空间最多显示 INIT 条 + 展开按钮(每次 +STEP)
+ // 按空间分组渲染:每个空间最多显示 INIT 条 + 展开按钮(每次 +STEP)。
+ // 自动复制只支持会话和空间;任务组本身没有自动复制按钮。
function renderSessions() {
var listEl = sessionsPane.querySelector('#wbs-sess-list');
var countEl = sessionsPane.querySelector('#wbs-sess-count');
@@ -1581,99 +1621,115 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
if (countEl) countEl.textContent = '0 个会话';
return;
}
- // 分组(保持空间出现顺序:按该空间最早会话时间倒序)
- // 区分「任务」与「空间」:任务 = 未选择具体项目,cwd 为 WorkBuddy/<时间戳> 自动目录
- function isTaskSession(s) {
- return /\/WorkBuddy\/\d{4}-\d{2}-\d{2}-\d{2}-\d{2}-\d{2}/.test(s.cwd || '');
+ function canEditAutoCopy(uid) { return sessionsState.uid !== '' && !!uid; }
+ function autoCopyButton(kind, key, uid, enabled, inherited) {
+ if (!canEditAutoCopy(uid)) return '';
+ var title = inherited ? '随空间自动复制' : (enabled ? '取消自动复制' : '切换账号时自动复制');
+ var disabled = inherited ? ' disabled' : '';
+ return '<button class="wbs-sess-auto' + (enabled ? ' active' : '') + (inherited ? ' inherited' : '') + '" type="button" data-auto-kind="' + kind + '" data-auto-key="' + escAttr(key) + '" data-auto-uid="' + escAttr(uid) + '" aria-label="' + escAttr(title) + '" title="' + escAttr(title) + '" aria-pressed="' + (enabled ? 'true' : 'false') + '"' + disabled + '><span class="wbs-sess-auto-label">自动复制</span><span class="wbs-sess-auto-switch' + (enabled ? ' on' : '') + '" aria-hidden="true"><span></span></span></button>';
}
var tasks = [];
var groups = {};
var wsOrder = [];
sessionsState.list.forEach(function (s) {
- if (isTaskSession(s)) { tasks.push(s); return; }
- var w = s.cwd || '(未指定空间)';
- if (!groups[w]) { groups[w] = []; wsOrder.push(w); }
- groups[w].push(s);
+ if (isTaskSessionRecordUI(s.cwd)) { tasks.push(s); return; }
+ var cwd = s.cwd || '(未指定空间)';
+ var owner = String(s.user_id || sessionsState.uid || '');
+ var groupKey = owner + '::' + cwd;
+ if (!groups[groupKey]) { groups[groupKey] = { cwd: cwd, uid: owner, items: [] }; wsOrder.push(groupKey); }
+ groups[groupKey].items.push(s);
});
var total = sessionsState.list.length;
var html = '';
var batch = sessionsState.batchMode;
- // 任务区(未选择项目的会话)
if (tasks.length) {
var taskKey = '__TASKS__';
var taskShown = (sessionsState.wsExpanded[taskKey] || SESS_WS_INIT);
var taskVis = tasks.slice(0, taskShown);
var taskMore = tasks.length - taskVis.length;
- var taskCheckedAll = tasks.every(function (s) { return sessionsState.selected[s.id]; });
html += '<div class="wbs-sess-group wbs-sess-tasks">' +
'<div class="wbs-sess-group-head">' +
- (batch ? '<input type="checkbox" class="wbs-ws-check" data-ws="__TASKS__"' + (taskCheckedAll ? ' checked' : '') + '>' : '') +
'<span class="wbs-sess-group-name" title="未选择项目的会话"><span class="wbs-sess-group-type">任务</span></span>' +
'<span class="wbs-sess-group-count">' + tasks.length + '</span>' +
'</div>';
taskVis.forEach(function (s) {
var title = s.custom_title || s.title || '(无标题)';
- var sel = sessionsState.selected[s.id] ? ' checked' : '';
- html += '<label class="wbs-sess-row">' +
- (batch ? '<input type="checkbox" class="wbs-sess-check" data-id="' + s.id + '"' + sel + '>' : '') +
+ html += '<div class="wbs-sess-row">' +
'<span class="wbs-sess-main"><span class="wbs-sess-title">' + esc(title) + '</span>' +
'<span class="wbs-sess-meta">' + fmtHumanTime(s.created_at) + '</span></span>' +
- '</label>';
+ '</div>';
});
- if (taskMore > 0) {
- html += '<button class="wbs-sess-more" type="button" data-ws="__TASKS__">展开 ' + Math.min(taskMore, SESS_WS_STEP) + ' 条(剩余 ' + taskMore + ')</button>';
- }
+ if (taskMore > 0) html += '<button class="wbs-sess-more" type="button" data-ws="__TASKS__">展开 ' + Math.min(taskMore, SESS_WS_STEP) + ' 条(剩余 ' + taskMore + ')</button>';
html += '</div>';
}
- // 空间区(按 cwd 分组)
- wsOrder.forEach(function (w) {
- var arr = groups[w];
- var shown = (sessionsState.wsExpanded[w] || SESS_WS_INIT);
+ wsOrder.forEach(function (groupKey) {
+ var group = groups[groupKey];
+ var arr = group.items;
+ var shown = (sessionsState.wsExpanded[groupKey] || SESS_WS_INIT);
var vis = arr.slice(0, shown);
var more = arr.length - vis.length;
var checkedAll = arr.every(function (s) { return sessionsState.selected[s.id]; });
+ var workspaceMarked = arr.some(function (s) { return !!s.autoCopyWorkspace; });
+ var autoWorkspace = group.cwd === '(未指定空间)' ? '' : autoCopyButton('workspace', group.cwd, group.uid, workspaceMarked, false);
html += '<div class="wbs-sess-group">' +
'<div class="wbs-sess-group-head">' +
- (batch ? '<input type="checkbox" class="wbs-ws-check" data-ws="' + esc(w) + '"' + (checkedAll ? ' checked' : '') + '>' : '') +
- '<span class="wbs-sess-group-name" title="' + esc(w) + '"><span class="wbs-sess-group-type">空间</span>' + esc(shortWs(w)) + '</span>' +
+ (batch ? '<input type="checkbox" class="wbs-ws-check" data-ws="' + escAttr(groupKey) + '"' + (checkedAll ? ' checked' : '') + '>' : '') +
+ '<span class="wbs-sess-group-name" title="' + escAttr(group.cwd) + '"><span class="wbs-sess-group-type">空间</span>' + esc(shortWs(group.cwd)) + '</span>' +
+ (batch ? '' : autoWorkspace) +
'<span class="wbs-sess-group-count">' + arr.length + '</span>' +
'</div>';
vis.forEach(function (s) {
var title = s.custom_title || s.title || '(无标题)';
var sel = sessionsState.selected[s.id] ? ' checked' : '';
- html += '<label class="wbs-sess-row">' +
- (batch ? '<input type="checkbox" class="wbs-sess-check" data-id="' + s.id + '"' + sel + '>' : '') +
+ var inherited = !!s.autoCopyWorkspace;
+ var marked = !!s.autoCopySession || inherited;
+ html += '<div class="wbs-sess-row">' +
+ (batch ? '<input type="checkbox" class="wbs-sess-check" data-id="' + escAttr(s.id) + '"' + sel + '>' : '') +
'<span class="wbs-sess-main"><span class="wbs-sess-title">' + esc(title) + '</span>' +
'<span class="wbs-sess-meta">' + fmtHumanTime(s.created_at) + '</span></span>' +
- '</label>';
+ (batch ? '' : autoCopyButton('session', s.id, s.user_id, marked, inherited)) +
+ '</div>';
});
- if (more > 0) {
- html += '<button class="wbs-sess-more" type="button" data-ws="' + esc(w) + '">展开 ' + Math.min(more, SESS_WS_STEP) + ' 条(剩余 ' + more + ')</button>';
- }
+ if (more > 0) html += '<button class="wbs-sess-more" type="button" data-ws="' + escAttr(groupKey) + '">展开 ' + Math.min(more, SESS_WS_STEP) + ' 条(剩余 ' + more + ')</button>';
html += '</div>';
});
listEl.innerHTML = html;
- if (countEl) countEl.textContent = total + ' 个会话';
+ updateSessionSummary(countEl);
bindSessEvents(listEl);
}
+ function activeAutoCopyCount() {
+ return sessionsState.list.filter(function (s) {
+ return !isTaskSessionRecordUI(s.cwd) && (!!s.autoCopySession || !!s.autoCopyWorkspace);
+ }).length;
+ }
+ function updateSessionSummary(countEl) {
+ if (!countEl) return;
+ countEl.innerHTML = '<span class="wbs-sess-summary-tag">共 ' + sessionsState.list.length + ' 个会话</span>' +
+ '<span class="wbs-sess-summary-tag wbs-sess-summary-auto">自动复制 ' + activeAutoCopyCount() + '</span>';
+ }
function shortWs(w) {
- var parts = w.split('/').filter(Boolean);
+ var parts = String(w || '').replace(/\\/g, '/').split('/').filter(Boolean);
return parts.length >= 2 ? parts.slice(-2).join('/') : w;
}
// 会话列表内事件委托
function bindSessEvents(listEl) {
listEl.onclick = function (e) {
var t = e.target;
+ var autoBtn = t.closest ? t.closest('.wbs-sess-auto') : null;
+ if (autoBtn) {
+ e.preventDefault();
+ e.stopPropagation();
+ if (autoBtn.disabled) return;
+ toggleAutoCopyRule(autoBtn.getAttribute('data-auto-kind'), autoBtn.getAttribute('data-auto-key'), autoBtn.getAttribute('data-auto-uid'), autoBtn.getAttribute('aria-pressed') !== 'true');
+ return;
+ }
// 空间/任务勾选
var wsCheck = t.closest ? t.closest('.wbs-ws-check') : null;
if (wsCheck) {
var w = wsCheck.getAttribute('data-ws');
- var arr;
- if (w === '__TASKS__') {
- arr = sessionsState.list.filter(function (s) { return /\/WorkBuddy\/\d{4}-\d{2}-\d{2}-\d{2}-\d{2}-\d{2}/.test(s.cwd || ''); });
- } else {
- arr = sessionsState.list.filter(function (s) { return (s.cwd || '(未指定空间)') === w; });
- }
+ var arr = sessionsState.list.filter(function (s) {
+ return !isTaskSessionRecordUI(s.cwd) && String(s.user_id || sessionsState.uid || '') + '::' + (s.cwd || '(未指定空间)') === w;
+ });
var on = wsCheck.checked;
arr.forEach(function (s) { sessionsState.selected[s.id] = on; });
renderSessions();
@@ -1702,10 +1758,72 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
});
});
}
+ function toggleAutoCopyRule(kind, key, uid, enabled) {
+ if (!kind || !key || !uid) return;
+ var listEl = sessionsPane.querySelector('#wbs-sess-list');
+ var snapshot = sessionsState.list.map(function (s) {
+ return { id: s.id, autoCopySession: !!s.autoCopySession, autoCopyWorkspace: !!s.autoCopyWorkspace };
+ });
+ var oldAutoCopy = sessionsState.autoCopy;
+ var changedKey = kind === 'workspace' ? canonicalWorkspaceUI(key) : String(key);
+ sessionsState.list.forEach(function (s) {
+ if (kind === 'session' && String(s.id) === changedKey && String(s.user_id || '') === String(uid)) s.autoCopySession = enabled;
+ if (kind === 'workspace' && canonicalWorkspaceUI(s.cwd) === changedKey) s.autoCopyWorkspace = enabled;
+ });
+ updateAutoCopyButtons(listEl);
+ api('/api/sessions/auto-copy', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ uid: uid, kind: kind, key: key, enabled: enabled }),
+ }).then(function (response) {
+ if (response && response.rules) sessionsState.autoCopy = response.rules;
+ toast(enabled ? '已开启切换账号时自动复制' : '已关闭自动复制', false, root);
+ updateSessCount();
+ }).catch(function (e) {
+ sessionsState.list.forEach(function (s) {
+ var previous = snapshot.find(function (x) { return x.id === s.id; });
+ if (previous) { s.autoCopySession = previous.autoCopySession; s.autoCopyWorkspace = previous.autoCopyWorkspace; }
+ });
+ sessionsState.autoCopy = oldAutoCopy;
+ updateAutoCopyButtons(listEl);
+ toast('自动复制设置失败: ' + (e.message || e), true, root);
+ });
+ }
+ function updateAutoCopyButtons(listEl) {
+ if (!listEl) return;
+ listEl.querySelectorAll('.wbs-sess-auto').forEach(function (button) {
+ var kind = button.getAttribute('data-auto-kind');
+ var key = button.getAttribute('data-auto-key') || '';
+ var uid = button.getAttribute('data-auto-uid') || '';
+ var state = false;
+ var inherited = false;
+ if (kind === 'workspace') {
+ state = sessionsState.list.some(function (s) { return canonicalWorkspaceUI(s.cwd) === canonicalWorkspaceUI(key) && !!s.autoCopyWorkspace; });
+ } else {
+ var session = sessionsState.list.find(function (s) { return String(s.id) === String(key) && String(s.user_id || '') === String(uid); });
+ if (session) {
+ inherited = !!session.autoCopyWorkspace;
+ state = !!session.autoCopySession || inherited;
+ }
+ }
+ var title = inherited ? '随空间自动复制' : (state ? '取消自动复制' : '切换账号时自动复制');
+ button.classList.toggle('active', state);
+ button.classList.toggle('inherited', inherited);
+ button.disabled = inherited;
+ button.setAttribute('aria-pressed', state ? 'true' : 'false');
+ button.setAttribute('aria-label', title);
+ button.setAttribute('title', title);
+ var knob = button.querySelector('.wbs-sess-auto-switch');
+ if (knob) knob.classList.toggle('on', state);
+ });
+ }
function updateSessCount() {
- var n = Object.keys(sessionsState.selected).filter(function (k) { return sessionsState.selected[k]; }).length;
+ var n = sessionsState.list.filter(function (s) { return !isTaskSessionRecordUI(s.cwd) && sessionsState.selected[s.id]; }).length;
var countEl = sessionsPane.querySelector('#wbs-sess-count');
- if (countEl) countEl.textContent = sessionsState.list.length + ' 个会话' + (sessionsState.batchMode ? ',已选 ' + n : '');
+ updateSessionSummary(countEl);
+ if (countEl && sessionsState.batchMode) {
+ countEl.insertAdjacentHTML('beforeend', '<span class="wbs-sess-summary-selected">已选 ' + n + '</span>');
+ }
// 未选中会话时隐藏「复制/删除」按钮(仅批量模式可见)
var cp = sessionsPane.querySelector('#wbs-sess-copy');
var dl = sessionsPane.querySelector('#wbs-sess-delete');
@@ -1718,7 +1836,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
if (!sessionsPane) return;
var btn = sessionsPane.querySelector('#wbs-sess-check-all');
if (!btn) return;
- var allSel = sessionsState.list.length > 0 && sessionsState.list.every(function (s) { return sessionsState.selected[s.id]; });
+ var selectable = sessionsState.list.filter(function (s) { return !isTaskSessionRecordUI(s.cwd); });
+ var allSel = selectable.length > 0 && selectable.every(function (s) { return sessionsState.selected[s.id]; });
var ico = btn.querySelector('.wbs-sess-check-ico');
var lbl = btn.querySelector('.wbs-sess-check-label');
if (ico) {
@@ -1733,6 +1852,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
if (lbl) lbl.textContent = allSel ? '取消全选' : '全选';
}
function esc(t) { return String(t == null ? '' : t).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;'); }
+ function escAttr(t) { return esc(t).replace(/"/g, '&quot;').replace(/'/g, '&#39;'); }
// 人性化时间:刚刚 / x 分钟前 / x 小时前 / 昨天 / x 天前 / 日期
function fmtHumanTime(ts) {
if (!ts) return '-';
@@ -1793,9 +1913,10 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
var checkAll = sessionsPane.querySelector('#wbs-sess-check-all');
if (checkAll) {
checkAll.addEventListener('click', function () {
- var allSel = sessionsState.list.length > 0 && sessionsState.list.every(function (s) { return sessionsState.selected[s.id]; });
+ var selectable = sessionsState.list.filter(function (s) { return !isTaskSessionRecordUI(s.cwd); });
+ var allSel = selectable.length > 0 && selectable.every(function (s) { return sessionsState.selected[s.id]; });
sessionsState.selected = {};
- if (!allSel) sessionsState.list.forEach(function (s) { sessionsState.selected[s.id] = true; });
+ if (!allSel) selectable.forEach(function (s) { sessionsState.selected[s.id] = true; });
renderSessions();
updateSessCount();
});
@@ -1911,13 +2032,309 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
};
}
function selectedSessIds() {
- return sessionsState.list.filter(function (s) { return sessionsState.selected[s.id]; }).map(function (s) { return s.id; });
+ return sessionsState.list.filter(function (s) { return !isTaskSessionRecordUI(s.cwd) && sessionsState.selected[s.id]; }).map(function (s) { return s.id; });
}
function showSessModal(show) {
var mask = sessionsPane.querySelector('#wbs-sess-modal');
if (mask) mask.style.display = show ? '' : 'none';
}
+ // ===== 模型 pane(当前模型 + WorkDaddy 本地备份) =====
+ var modelsState = { tab: 'official', official: [], groups: [], selected: {}, batch: false, officialError: '' };
+ function buildModelsPane() {
+ if (!modelsPane) return;
+ modelsPane.dataset.built = '1';
+ modelsPane.innerHTML =
+ '<div class="wbs-pcard wbs-model-card">' +
+ '<div class="wbs-model-tabs" role="tablist">' +
+ '<button class="wbs-model-tab active" type="button" data-model-tab="official">当前模型<span class="wbs-model-tab-count" id="wbs-model-official-count">0</span></button>' +
+ '<button class="wbs-model-tab" type="button" data-model-tab="mine">备选模型<span class="wbs-model-tab-count" id="wbs-model-mine-count">0</span></button>' +
+ '</div>' +
+ '<div class="wbs-model-toolbar">' +
+ '<span class="wbs-model-count" id="wbs-model-count"></span>' +
+ '<span class="wbs-model-toolbar-spacer"></span>' +
+ '<button class="wbs-sess-bbtn" type="button" id="wbs-model-batch" style="display:none">批量管理</button>' +
+ '</div>' +
+ '<div class="wbs-model-batchbar" id="wbs-model-batchbar" style="display:none">' +
+ '<button class="wbs-sess-bbtn wbs-model-check-all" type="button" id="wbs-model-check-all">全选</button>' +
+ '<span class="wbs-model-batch-count" id="wbs-model-batch-count">已选 0</span>' +
+ '<button class="wbs-sess-bbtn wbs-model-batch-action" type="button" id="wbs-model-batch-action"></button>' +
+ '<button class="wbs-sess-bbtn wbs-sess-done" type="button" id="wbs-model-done">取消</button>' +
+ '</div>' +
+ '<div class="wbs-model-tip" id="wbs-model-tip" style="display:none"><span class="wbs-model-tip-ico">' + MODEL_TIP_SVG + '</span><strong>小贴士</strong><span>解决 WorkBuddy 不支持多个同名模型的问题。</span></div>' +
+ '<div class="wbs-model-list" id="wbs-model-list"><div class="wbs-empty">加载中…</div></div>' +
+ '</div>' +
+ '<div class="wbs-modal-mask" id="wbs-model-confirm" style="display:none"><div class="wbs-modal"><div class="wbs-modal-title" id="wbs-model-confirm-title">确认操作</div><div class="wbs-modal-body" id="wbs-model-confirm-body"></div><div class="wbs-modal-actions"><button class="wbs-modal-btn" type="button" id="wbs-model-confirm-cancel">取消</button><button class="wbs-modal-btn wbs-modal-ok" type="button" id="wbs-model-confirm-ok">确定</button></div></div></div>' +
+ '<div class="wbs-modal-mask" id="wbs-model-edit" style="display:none"><div class="wbs-modal wbs-model-edit-modal"><div class="wbs-modal-title">编辑模型</div><div class="wbs-model-edit-form"><label class="wbs-model-edit-field"><span>名称</span><input id="wbs-model-edit-name" type="text" autocomplete="off"></label><label class="wbs-model-edit-field"><span>URL</span><input id="wbs-model-edit-url" type="url" autocomplete="off"></label><label class="wbs-model-edit-field"><span>API Key</span><span class="wbs-model-secret-wrap"><input id="wbs-model-edit-key" type="password" autocomplete="off"><button class="wbs-model-eye" id="wbs-model-edit-eye" type="button" title="显示或隐藏 API Key" aria-label="显示或隐藏 API Key"><svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M2 12s3.5-6 10-6 10 6 10 6-3.5 6-10 6S2 12 2 12Z"/><circle cx="12" cy="12" r="2.5"/></svg></button></span></label></div><div class="wbs-modal-actions"><button class="wbs-modal-btn" type="button" id="wbs-model-edit-cancel">取消</button><button class="wbs-modal-btn wbs-modal-ok" type="button" id="wbs-model-edit-save">保存</button></div></div></div>';
+ wireModelsPane();
+ loadModels();
+ }
+ // 前端脱敏:与后端 maskApiKey 一致。cell 列表展示短脱敏串,title 同样脱敏;编辑弹窗用明文原值
+ function maskModelKey(apiKey) {
+ var value = String(apiKey || '');
+ if (!value) return '';
+ if (value.length <= 8) return '••••••';
+ var prefix = value.slice(0, Math.min(3, value.length - 8));
+ return prefix + '••••' + value.slice(-4);
+ }
+ function modelDetailsHtml(model) {
+ var url = model.url || '-';
+ var masked = maskModelKey(model.apiKey);
+ var key = masked || '未设置';
+ return '<div class="wbs-model-details">' +
+ '<div class="wbs-model-field"><span>url</span><strong class="wbs-model-url" title="' + escAttr(url) + '">' + esc(url) + '</strong></div>' +
+ '<div class="wbs-model-field"><span>apiKey</span><strong class="wbs-model-key" title="' + escAttr(key) + '">' + esc(key) + '</strong></div>' +
+ '</div>';
+ }
+ function modelRowHtml(model, options) {
+ options = options || {};
+ var selectionKey = options.selectionKey || '';
+ var checked = selectionKey && modelsState.selected[selectionKey] ? ' checked' : '';
+ var checkbox = modelsState.batch && selectionKey ? '<input class="wbs-model-check" type="checkbox" data-model-select="' + escAttr(selectionKey) + '"' + checked + '>' : '';
+ // 按钮组占流固定在标题行右侧,仅 hover/focus cell 时由透明变不透明,布局与高度恒定
+ var actions = options.official
+ ? '<div class="wbs-model-actions">' +
+ '<button class="wbs-model-icon-action" type="button" data-model-backup="' + model.index + '" title="备份" aria-label="备份">' + MODEL_BACKUP_SVG + '</button>' +
+ '<button class="wbs-model-icon-action" type="button" data-model-test="' + model.index + '" title="连通测试" aria-label="连通测试">' + MODEL_TEST_SVG + '</button>' +
+ '<button class="wbs-model-icon-action wbs-model-danger-action" type="button" data-model-delete-official="' + model.index + '" title="删除" aria-label="删除">' + TRASH_SVG + '</button>' +
+ '</div>'
+ : '<div class="wbs-model-actions">' +
+ '<button class="wbs-model-icon-action" type="button" data-model-copy="' + escAttr(model.backupId) + '" title="复制" aria-label="复制">' + MODEL_COPY_SVG + '</button>' +
+ '<button class="wbs-model-icon-action" type="button" data-model-edit="' + escAttr(model.backupId) + '" title="编辑" aria-label="编辑">' + MODEL_EDIT_SVG + '</button>' +
+ '<button class="wbs-model-action wbs-model-enable" type="button" data-model-enable="' + escAttr(model.backupId) + '" title="启用"><span class="wbs-model-enable-icon">' + MODEL_ENABLE_SVG + '</span><span>启用</span></button>' +
+ '</div>';
+ var tags = '<span class="wbs-model-tag">' + esc(model.vendor || '-') + '</span>' +
+ '<span class="wbs-model-tag wbs-model-tag-id" title="' + escAttr(model.id || '-') + '">' + esc(model.id || '-') + '</span>';
+ return '<div class="wbs-model-row' + (options.official ? '' : ' wbs-model-backup-row') + '">' +
+ '<div class="wbs-model-main">' +
+ '<div class="wbs-model-title-row">' + checkbox +
+ '<div class="wbs-model-name" title="' + escAttr(model.name || model.id || '') + '">' + esc(model.name || model.id || '(未命名)') + '</div>' +
+ actions +
+ '</div>' +
+ '<div class="wbs-model-tag-row">' + tags + '</div>' +
+ modelDetailsHtml(model) +
+ '</div></div>';
+ }
+ function loadModels() {
+ if (!modelsPane) return;
+ var list = modelsPane.querySelector('#wbs-model-list');
+ if (list) list.innerHTML = '<div class="wbs-empty">加载中…</div>';
+ api('/api/models').then(function (data) {
+ modelsState.official = data.official || [];
+ modelsState.groups = data.backups || [];
+ modelsState.officialError = data.officialError || '';
+ renderModels();
+ }).catch(function (e) {
+ modelsState.official = [];
+ modelsState.groups = [];
+ modelsState.officialError = e.message || String(e);
+ if (list) list.innerHTML = '<div class="wbs-empty">模型加载失败:' + esc(e.message || e) + '</div>';
+ updateModelCounts();
+ });
+ }
+ function updateModelCounts() {
+ if (!modelsPane) return;
+ var officialCount = modelsPane.querySelector('#wbs-model-official-count');
+ var mineCount = modelsPane.querySelector('#wbs-model-mine-count');
+ var count = modelsPane.querySelector('#wbs-model-count');
+ var backupCount = modelsState.groups.reduce(function (n, group) { return n + (group.items || []).length; }, 0);
+ if (officialCount) officialCount.textContent = modelsState.official.length;
+ if (mineCount) mineCount.textContent = backupCount;
+ if (count) count.textContent = modelsState.tab === 'official' ? '共 ' + modelsState.official.length + ' 个模型' : '共 ' + backupCount + ' 个备选';
+ }
+ function renderModels() {
+ if (!modelsPane) return;
+ var list = modelsPane.querySelector('#wbs-model-list');
+ if (!list) return;
+ modelsPane.querySelectorAll('.wbs-model-tab').forEach(function (tab) {
+ tab.classList.toggle('active', tab.getAttribute('data-model-tab') === modelsState.tab);
+ });
+ var batchBtn = modelsPane.querySelector('#wbs-model-batch');
+ if (batchBtn) batchBtn.style.display = !modelsState.batch ? '' : 'none';
+ var batchbar = modelsPane.querySelector('#wbs-model-batchbar');
+ if (batchbar) batchbar.style.display = modelsState.batch ? '' : 'none';
+ var tip = modelsPane.querySelector('#wbs-model-tip');
+ if (tip) tip.style.display = modelsState.tab === 'mine' && !modelsState.batch ? '' : 'none';
+ updateModelCounts();
+ if (modelsState.tab === 'official') {
+ if (modelsState.officialError) { list.innerHTML = '<div class="wbs-empty">当前模型加载失败:' + esc(modelsState.officialError) + '</div>'; return; }
+ if (!modelsState.official.length) { list.innerHTML = '<div class="wbs-empty">没有找到当前模型配置</div>'; return; }
+ list.innerHTML = modelsState.official.map(function (model) { return modelRowHtml(model, { official: true, selectionKey: 'official:' + model.index }); }).join('');
+ updateModelBatchState();
+ return;
+ }
+ if (!modelsState.groups.length) { list.innerHTML = '<div class="wbs-empty">还没有模型备份</div>'; return; }
+ list.innerHTML = modelsState.groups.map(function (group) {
+ var items = group.items || [];
+ return '<div class="wbs-model-group"><div class="wbs-model-group-head"><span class="wbs-model-group-title">' + esc(group.name || '(未命名模型)') + '</span><span class="wbs-model-group-count">' + items.length + '</span></div>' + items.map(function (model) {
+ return modelRowHtml(model, { selectionKey: 'backup:' + model.backupId });
+ }).join('') + '</div>';
+ }).join('');
+ updateModelBatchState();
+ }
+ function updateModelBatchState() {
+ if (!modelsPane) return;
+ var ids = Object.keys(modelsState.selected).filter(function (id) { return modelsState.selected[id]; });
+ var count = modelsPane.querySelector('#wbs-model-batch-count');
+ var action = modelsPane.querySelector('#wbs-model-batch-action');
+ if (count) count.textContent = '已选 ' + ids.length;
+ if (action) {
+ action.disabled = !ids.length;
+ action.textContent = '删除选中';
+ }
+ var all = modelsState.tab === 'official' ? modelsState.official.map(function (m) { return 'official:' + m.index; }) : modelsState.groups.reduce(function (out, group) { return out.concat((group.items || []).map(function (m) { return 'backup:' + m.backupId; })); }, []);
+ var allSelected = all.length > 0 && all.every(function (id) { return modelsState.selected[id]; });
+ var checkAll = modelsPane.querySelector('#wbs-model-check-all');
+ if (checkAll) checkAll.textContent = allSelected ? '取消全选' : '全选';
+ }
+ function showModelConfirm(title, bodyText, onConfirm) {
+ var mask = modelsPane.querySelector('#wbs-model-confirm');
+ var titleEl = modelsPane.querySelector('#wbs-model-confirm-title');
+ var body = modelsPane.querySelector('#wbs-model-confirm-body');
+ var ok = modelsPane.querySelector('#wbs-model-confirm-ok');
+ var cancel = modelsPane.querySelector('#wbs-model-confirm-cancel');
+ titleEl.textContent = title;
+ body.textContent = bodyText;
+ mask.style.display = '';
+ var close = function () { mask.style.display = 'none'; ok.onclick = null; cancel.onclick = null; };
+ cancel.onclick = close;
+ mask.onclick = function (event) { if (event.target === mask) close(); };
+ ok.onclick = function () { close(); onConfirm(); };
+ }
+ function wireModelsPane() {
+ modelsPane.addEventListener('click', function (event) {
+ var tab = event.target.closest ? event.target.closest('.wbs-model-tab') : null;
+ if (tab) { modelsState.tab = tab.getAttribute('data-model-tab') || 'official'; modelsState.batch = false; modelsState.selected = {}; renderModels(); return; }
+ var backup = event.target.closest ? event.target.closest('[data-model-backup]') : null;
+ if (backup) {
+ api('/api/models/backup', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ index: Number(backup.getAttribute('data-model-backup')) }) })
+ .then(function () { toast('模型已备份到「备选模型」', false, root); modelsState.tab = 'mine'; modelsState.batch = false; modelsState.selected = {}; loadModels(); })
+ .catch(function (e) { toast('模型备份失败:' + (e.message || e), true, root); });
+ return;
+ }
+ var modelTest = event.target.closest ? event.target.closest('[data-model-test]') : null;
+ if (modelTest) {
+ var testIndex = Number(modelTest.getAttribute('data-model-test'));
+ modelTest.disabled = true;
+ api('/api/models/test', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ index: testIndex }) })
+ .then(function (data) {
+ var result = data && data.result || {};
+ toast(result.message || ('接口返回 HTTP ' + (result.status || '-')), !(result.authorized), root);
+ })
+ .catch(function (e) { toast('连通测试失败:' + (e.message || e), true, root); })
+ .finally(function () { modelTest.disabled = false; });
+ return;
+ }
+ var officialDelete = event.target.closest ? event.target.closest('[data-model-delete-official]') : null;
+ if (officialDelete) {
+ var officialIndex = Number(officialDelete.getAttribute('data-model-delete-official'));
+ showModelConfirm('删除当前模型?', '删除后会直接修改官方 models.json,已备份到「备选模型」的配置不会受影响。', function () {
+ api('/api/models/delete-official', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ indexes: [officialIndex] }) })
+ .then(function () { toast('当前模型已删除', false, root); loadModels(); })
+ .catch(function (e) { toast('删除当前模型失败:' + (e.message || e), true, root); });
+ });
+ return;
+ }
+ var copy = event.target.closest ? event.target.closest('[data-model-copy]') : null;
+ if (copy) {
+ var copyId = copy.getAttribute('data-model-copy');
+ copy.disabled = true;
+ api('/api/models/copy', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ backupId: copyId }) })
+ .then(function () { toast('模型已复制', false, root); loadModels(); })
+ .catch(function (e) { toast('复制模型失败:' + (e.message || e), true, root); copy.disabled = false; });
+ return;
+ }
+ var edit = event.target.closest ? event.target.closest('[data-model-edit]') : null;
+ if (edit) { openModelEdit(edit.getAttribute('data-model-edit')); return; }
+ var enable = event.target.closest ? event.target.closest('[data-model-enable]') : null;
+ if (enable) {
+ var backupId = enable.getAttribute('data-model-enable');
+ showModelConfirm('启用模型配置?', '这会把该备份覆盖到官方 models.json 中,同 id 的旧配置将被移除。', function () {
+ enable.disabled = true;
+ api('/api/models/enable', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ backupId: backupId }) })
+ .then(function () { toast('模型已启用', false, root); loadModels(); })
+ .catch(function (e) { toast('启用模型失败:' + (e.message || e), true, root); renderModels(); });
+ });
+ return;
+ }
+ var batch = event.target.closest ? event.target.closest('#wbs-model-batch') : null;
+ if (batch) { modelsState.batch = true; modelsState.selected = {}; renderModels(); return; }
+ var checkAll = event.target.closest ? event.target.closest('#wbs-model-check-all') : null;
+ if (checkAll) {
+ var all = modelsState.tab === 'official' ? modelsState.official.map(function (m) { return 'official:' + m.index; }) : modelsState.groups.reduce(function (out, group) { return out.concat((group.items || []).map(function (m) { return 'backup:' + m.backupId; })); }, []);
+ var allSelected = all.length > 0 && all.every(function (id) { return modelsState.selected[id]; });
+ all.forEach(function (id) { modelsState.selected[id] = !allSelected; });
+ renderModels();
+ return;
+ }
+ var done = event.target.closest ? event.target.closest('#wbs-model-done') : null;
+ if (done) { modelsState.batch = false; modelsState.selected = {}; renderModels(); return; }
+ var batchAction = event.target.closest ? event.target.closest('#wbs-model-batch-action') : null;
+ if (batchAction && !batchAction.disabled) {
+ var ids = Object.keys(modelsState.selected).filter(function (id) { return modelsState.selected[id]; });
+ if (modelsState.tab === 'official') {
+ showModelConfirm('删除当前模型?', '删除后会直接修改官方 models.json,已备份到「备选模型」的配置不会受影响。', function () {
+ var indexes = ids.map(function (id) { return Number(id.slice('official:'.length)); });
+ api('/api/models/delete-official', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ indexes: indexes }) })
+ .then(function () { toast('已删除 ' + indexes.length + ' 个当前模型', false, root); modelsState.batch = false; modelsState.selected = {}; loadModels(); })
+ .catch(function (e) { toast('删除当前模型失败:' + (e.message || e), true, root); });
+ });
+ } else {
+ showModelConfirm('删除模型备份?', '删除后无法恢复,但不会影响官方 models.json。', function () {
+ var backupIds = ids.map(function (id) { return id.slice('backup:'.length); });
+ api('/api/models/delete', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ backupIds: backupIds }) })
+ .then(function () { toast('已删除 ' + backupIds.length + ' 个模型备份', false, root); modelsState.batch = false; modelsState.selected = {}; loadModels(); })
+ .catch(function (e) { toast('删除模型备份失败:' + (e.message || e), true, root); });
+ });
+ }
+ }
+ });
+ modelsPane.addEventListener('change', function (event) {
+ var checkbox = event.target.closest ? event.target.closest('.wbs-model-check') : null;
+ if (!checkbox) return;
+ modelsState.selected[checkbox.getAttribute('data-model-select')] = checkbox.checked;
+ updateModelBatchState();
+ });
+ }
+
+ function findModelBackup(backupId) {
+ for (var i = 0; i < modelsState.groups.length; i++) {
+ var item = (modelsState.groups[i].items || []).find(function (m) { return m.backupId === backupId; });
+ if (item) return item;
+ }
+ return null;
+ }
+ function openModelEdit(backupId) {
+ var item = findModelBackup(backupId);
+ var mask = modelsPane.querySelector('#wbs-model-edit');
+ if (!item || !mask) return;
+ var name = modelsPane.querySelector('#wbs-model-edit-name');
+ var url = modelsPane.querySelector('#wbs-model-edit-url');
+ var key = modelsPane.querySelector('#wbs-model-edit-key');
+ var eye = modelsPane.querySelector('#wbs-model-edit-eye');
+ var save = modelsPane.querySelector('#wbs-model-edit-save');
+ var cancel = modelsPane.querySelector('#wbs-model-edit-cancel');
+ name.value = item.name || item.id || '';
+ url.value = item.url || '';
+ key.value = item.apiKey || '';
+ key.type = 'password';
+ key.dataset.originalMask = item.apiKey || '';
+ save.disabled = false;
+ mask.style.display = '';
+ var close = function () { mask.style.display = 'none'; };
+ cancel.onclick = close;
+ mask.onclick = function (event) { if (event.target === mask) close(); };
+ eye.onclick = function () { key.type = key.type === 'password' ? 'text' : 'password'; };
+ save.onclick = function () {
+ var patch = { name: name.value, url: url.value };
+ if (key.value !== key.dataset.originalMask) patch.apiKey = key.value;
+ save.disabled = true;
+ api('/api/models/edit', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ backupId: backupId, patch: patch }) })
+ .then(function () { close(); toast('模型已保存', false, root); loadModels(); })
+ .catch(function (e) { toast('保存模型失败:' + (e.message || e), true, root); save.disabled = false; });
+ };
+ }
+
// ===== 主题 pane(构建:主题选择 + 背景图来源切换[官方壁纸/自定义上传] + 毛玻璃 + 头像)=====
function buildThemePane() {
if (!themePane) return;
@@ -2017,6 +2434,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'<button class="wbs-update-btn" id="wbs-update-btn" type="button">立即更新</button>' +
'<span class="wbs-update-progress" id="wbs-update-progress" style="display:none"></span>' +
'</div>' +
+ '<div class="wbs-update-bar" id="wbs-update-bar" style="display:none;height:6px;border-radius:3px;background:color-mix(in srgb,var(--wb-button-primary-bg,#1f1f1f) 22%,transparent);overflow:hidden;margin-top:8px"><i id="wbs-update-bar-fill" style="display:block;height:100%;width:0;border-radius:3px;background:var(--wb-button-primary-bg,#1f1f1f);transition:width .6s ease"></i></div>' +
'</div>' +
'<div class="wbs-pcard wbs-about-hero">' +
'<div class="wbs-about-name" id="wbs-about-name">WorkDaddy</div>' +
@@ -2061,9 +2479,10 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
checkForUpdate();
}
- // 自动更新 UI:查询 /api/update-check → 有新版则 tab 红点 + 更新卡片 → 点击走 下载→安装→自动重启
+ // 自动更新 UI:查询 /api/update-check(force=1 每次面板打开都强制刷新,不受 daemon 6 小时缓存限制)
+ // → 有新版则 tab 红点 + 更新卡片 → 点击走 下载→安装→自动重启
function checkForUpdate() {
- api('/api/update-check').then(function (d) {
+ api('/api/update-check?force=1').then(function (d) {
if (!d || !d.hasUpdate) return; // 无更新或检查失败:不打扰
var tab = root.querySelector('.wbs-tab[data-tab="about"]');
if (tab) tab.classList.add('wbs-tab-dot');
@@ -2090,8 +2509,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
var card = aboutPane.querySelector('#wbs-update-card');
if (!btn || !card) return;
btn.disabled = true;
- btn.textContent = '准备中…';
- if (prog) prog.style.display = '';
+ btn.textContent = '更新中…';
+ if (prog) { prog.style.display = ''; prog.textContent = '正在准备更新…'; }
api('/api/update-download', { method: 'POST' }).then(function (d) {
if (!d.ok) throw new Error(d.error || '下载失败');
return pollUpdateProgress(prog, btn, card);
@@ -2102,52 +2521,100 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
});
}
- // 轮询 /api/update-status 直到 installing → 触发 apply → 等待 done(daemon 即将退出,UI 不再轮询)
+ // 轮询 /api/update-status 直到下载完成 → 触发 apply → daemon 自我退出进入「重启等待」。
+ // 重启期间 /api/update-status 会连接失败(daemon 已退出换文件)——这属于"正常重启"而非失败,
+ // 继续重试直到新 daemon 起来并报告新版本号,才算完成。全程用分阶段文案反馈,不再一句「即将重启」了事。
+ // 重启等待阶段的分阶段预估进度(替换/启动真实耗时不透明,按安装向导惯例分步推进,
+ // 让用户看到进度而非一句「30~60 秒」干等;新 daemon 真正就绪后以实际版本收尾)
+ var REBOOT_STEPS = [
+ { t: 0, pct: 12, text: '正在停止旧版服务…' },
+ { t: 3000, pct: 30, text: '正在写入新版本文件…' },
+ { t: 9000, pct: 55, text: '正在启动新版本…' },
+ { t: 16000, pct: 80, text: '正在连接新服务…' },
+ { t: 26000, pct: 95, text: '快完成了,请稍候…' },
+ ];
function pollUpdateProgress(prog, btn, card) {
return new Promise(function (resolve, reject) {
var rounds = 0;
+ var rebooting = false;
+ var rebootElapsed = 0;
+ var bar = card ? card.querySelector('#wbs-update-bar') : null;
+ var barFill = bar ? bar.querySelector('#wbs-update-bar-fill') : null;
+ function renderRebootUi() {
+ var text = 'WorkDaddy 正在重启,更新即将完成,请稍候…';
+ var pct = 95;
+ for (var i = 0; i < REBOOT_STEPS.length; i++) {
+ if (rebootElapsed >= REBOOT_STEPS[i].t) { text = REBOOT_STEPS[i].text; pct = REBOOT_STEPS[i].pct; }
+ }
+ if (rebootElapsed > 45000) { text = '启动较慢,请耐心等待…(也可双击桌面 WorkDaddy 图标手动启动)'; pct = 99; }
+ if (prog) prog.textContent = text;
+ if (bar) bar.style.display = '';
+ if (barFill) barFill.style.width = pct + '%';
+ }
var timer = setInterval(function () {
rounds++;
api('/api/update-status').then(function (s) {
if (!prog) return;
- if (s.status === 'downloading' || s.status === 'verifying') {
+ if (!s) throw new Error('status-empty');
+ if (rebooting) {
+ // 重启等待阶段:新 daemon 已就绪且有版本 → 完成
+ var newVer = s.version;
+ if (newVer && (!WBS_VERSION || WBS_VERSION.indexOf('__WBS_') === 0 || newVer !== WBS_VERSION)) {
+ clearInterval(timer);
+ if (bar) bar.style.display = '';
+ if (barFill) barFill.style.width = '100%';
+ prog.textContent = '✅ 已升级到 v' + newVer + ',更新完成';
+ if (btn) btn.textContent = '已完成';
+ resolve(true);
+ } else {
+ rebootElapsed += 1000;
+ renderRebootUi();
+ }
+ return;
+ }
+ var st = s.status;
+ if (st === 'downloading' || st === 'verifying') {
prog.textContent = s.message + (s.progress ? ' ' + s.progress + '%' : '');
- } else if (s.status === 'installing') {
- prog.textContent = '安装中… 完成后将自动重启';
+ } else if (st === 'installing') {
+ prog.textContent = '正在安装新版本…';
if (btn) btn.textContent = '安装中…';
- // 触发安装
- api('/api/update-apply', { method: 'POST' }).then(function (r) {
- if (r.ok) {
- prog.textContent = r.message || '更新完成,正在重启…';
- if (btn) btn.textContent = '重启中…';
- clearInterval(timer);
- resolve(true);
- } else {
- clearInterval(timer);
- reject(new Error(r.error || '安装失败'));
- }
- }).catch(function (e) { clearInterval(timer); reject(e); });
- } else if (s.status === 'error') {
+ fireApply();
+ } else if (st === 'error') {
clearInterval(timer);
reject(new Error(s.error || s.message || '更新出错'));
- } else if (s.status === 'idle' && s.downloaded) {
- // 下载完成待安装
+ } else if (st === 'idle' && s.downloaded) {
prog.textContent = '下载完成,准备安装…';
- api('/api/update-apply', { method: 'POST' }).then(function (r) {
- if (r.ok) {
- prog.textContent = r.message || '更新完成,正在重启…';
- if (btn) btn.textContent = '重启中…';
- clearInterval(timer);
- resolve(true);
- } else {
- clearInterval(timer);
- reject(new Error(r.error || '安装失败'));
- }
- }).catch(function (e) { clearInterval(timer); reject(e); });
+ fireApply();
+ } else if (st === 'idle' && s.hasUpdate) {
+ prog.textContent = s.message || '发现新版本,准备更新…';
}
- if (rounds > 600) { clearInterval(timer); reject(new Error('更新超时')); } // 10 分钟兜底
- }).catch(function (e) { clearInterval(timer); reject(e); });
- }, 500);
+ }).catch(function (e) {
+ // 连接断开(daemon 已退出替换文件)= 正在重启;稍等片刻再进入等待态
+ if (!rebooting && rounds > 2) { enterRebootWait(); return; }
+ if (rebooting) { rebootElapsed += 1000; renderRebootUi(); return; }
+ clearInterval(timer); reject(new Error((e && e.message) || '更新失败'));
+ });
+
+ function fireApply() {
+ if (rebooting) return;
+ api('/api/update-apply', { method: 'POST' }).then(function (r) {
+ if (r && r.ok) { enterRebootWait(); }
+ else { clearInterval(timer); reject(new Error((r && r.error) || '安装失败')); }
+ }).catch(function (e2) {
+ var msg = String((e2 && e2.message) || e2);
+ if (/ECONNREFUSED|Failed to fetch|NetworkError|load failed/i.test(msg)) { enterRebootWait(); }
+ else { clearInterval(timer); reject(new Error((e2 && e2.message) || '安装失败')); }
+ });
+ }
+
+ function enterRebootWait() {
+ if (rebooting) return;
+ rebooting = true;
+ rebootElapsed = 0;
+ renderRebootUi();
+ if (btn) btn.textContent = '重启中…';
+ }
+ }, 1000);
});
}
@@ -2369,9 +2836,8 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
// 面板高度固定为主题页高度:防止切 tab 时高度忽高忽低(首次主题页壁纸渲染后锁定一次)
function lockPanelHeight() {
if (!panel || panel.dataset.hLocked) return;
- var r = panel.getBoundingClientRect();
- if (r.height < 100) return; // 面板未显示/尺寸异常不锁
- panel.style.height = Math.round(r.height) + 'px';
+ panel.style.height = '650px';
+ panel.style.maxHeight = '650px';
panel.dataset.hLocked = '1';
var bodyEl = panel.querySelector('.wbs-body');
if (bodyEl) bodyEl.style.overflowY = 'auto';
@@ -2443,6 +2909,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
fab.classList.toggle('hidden', open); // 打开时隐藏按钮
if (open) {
refresh();
+ checkForUpdate(); // 打开面板即检测更新(每次打开都强制查一次新版本)
} else {
stopCheckinPolling();
state.creditRunId++;
@@ -3427,6 +3894,33 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
});
}
+ function pollAutoCopyJob(jobId, accountName) {
+ if (!jobId) return;
+ var attempts = 0;
+ var poll = function () {
+ attempts++;
+ api('/api/sessions/auto-copy/status?id=' + encodeURIComponent(jobId)).then(function (d) {
+ var job = d && d.job;
+ if (!job) return;
+ if (job.status === 'queued' || job.status === 'running') {
+ if (attempts < 120) setBuildTimeout(poll, 700);
+ return;
+ }
+ if (job.status === 'done') {
+ toast('已切换到「' + accountName + '」,已复制 ' + job.total + ' 个会话', false, root);
+ } else if (job.status === 'partial') {
+ toast('已切换到「' + accountName + '」,复制完成,' + job.failed + ' 项失败', true, root);
+ } else {
+ toast('已切换到「' + accountName + '」,自动复制失败', true, root);
+ }
+ setBuildTimeout(refresh, 900);
+ }).catch(function () {
+ if (attempts < 120) setBuildTimeout(poll, 1000);
+ });
+ };
+ setBuildTimeout(poll, 700);
+ }
+
// token 过期状态:< 7 天 / 已过期 -> 红字高亮
function tokenState(expiresAt, account) {
if (isIdentityExpired(account)) return { warn: true, expired: true, label: expiresAt ? fmtDateTime(expiresAt) : '-' };
@@ -3507,13 +4001,15 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
body: JSON.stringify({ uid: btn.dataset.uid, reload: true }),
})
.then(function (r) {
+ var autoCopy = r && r.autoCopy;
toast(
r.reloaded
- ? '已切换为「' + (r.nickname || r.uid) + '」,开始领取积分…'
+ ? (autoCopy && autoCopy.jobId ? '已切换为「' + (r.nickname || r.uid) + '」,正在复制已标记会话…' : '已切换为「' + (r.nickname || r.uid) + '」,开始领取积分…')
: '已切换为「' + (r.nickname || r.uid) + '」,重启后生效',
false,
root
);
+ if (autoCopy && autoCopy.jobId) pollAutoCopyJob(autoCopy.jobId, r.nickname || r.uid);
setBuildTimeout(refresh, 1500);
})
.catch(function (e) { toast('切换失败: ' + e.message, true, root); })
@@ -3918,7 +4414,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'.wbs-fab:hover{transform:scale(0.5)}',
'.wbs-fab:active{transform:scale(0.5) translate(2px,2px)}',
/* 面板:毛玻璃主题(半透明 + 模糊,背景图透出) */
- '.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{position:absolute;right:0;bottom:0;width:460px;height:650px;max-height:650px;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}',
@@ -3928,7 +4424,7 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'.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)}',
+ '.wbs-body{overflow-y:auto;padding:10px 10px 6px;flex:1;min-height:0;height:calc(650px - 170px);max-height:none}',
/* 账号卡片:头像 + 信息 + 右侧操作 */
'.wbs-card{display:block;padding:10px 12px;border-radius:12px;margin-bottom:4px;transition:background .12s}',
'.wbs-card:hover{background:var(--wb-bg-hover,#f7f8fa)}',
@@ -4123,7 +4619,81 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'.wbs-sess-delbtn{padding:7px;color:var(--wb-icon-secondary,#555)}',
'.wbs-sess-delbtn:hover{color:#ff6b6b;border-color:color-mix(in srgb,#ff6b6b 45%,transparent);background:color-mix(in srgb,#ff6b6b 8%,transparent)}',
'.wbs-sess-delbtn.armed{color:#fff;background:#ff6b6b;border-color:#ff6b6b}',
- '.wbs-sess-count{font-size:12px;color:var(--wb-icon-tertiary,#999);margin-left:auto}',
+ '.wbs-sess-count{display:flex;align-items:center;gap:5px;margin-left:auto;min-width:0}',
+ '.wbs-sess-summary-tag{display:inline-flex;align-items:center;min-height:22px;padding:0 8px;border:1px solid var(--wb-border-default,#e5e5e5);border-radius:999px;background:color-mix(in srgb,var(--wb-bg-tertiary,#f0f0f0) 70%,transparent);color:var(--wb-icon-secondary,#666);font-size:11px;white-space:nowrap}',
+ '.wbs-sess-summary-auto{border-color:color-mix(in srgb,var(--wb-button-primary-bg,#1f1f1f) 24%,var(--wb-border-default,#e5e5e5));color:var(--wb-button-primary-bg,#1f1f1f);background:color-mix(in srgb,var(--wb-button-primary-bg,#1f1f1f) 8%,transparent)}',
+ '.wbs-sess-summary-selected{font-size:11px;color:var(--wb-icon-tertiary,#999);white-space:nowrap}',
+ '.wbs-model-card{display:flex;flex:1;flex-direction:column;min-height:0;padding:10px 12px 12px}',
+ '.wbs-model-tabs{display:flex;gap:4px;padding:3px;margin-bottom:10px;border-radius:10px;background:var(--wb-bg-tertiary,#f0f0f0)}',
+ '.wbs-model-tab{display:flex;align-items:center;justify-content:center;gap:7px;flex:1;min-width:0;padding:9px 8px;border:0;border-radius:8px;background:transparent;color:var(--wb-icon-secondary,#666);font-size:14px;font-weight:650;line-height:1;font-family:inherit;cursor:pointer;transition:background .15s,color .15s}',
+ '.wbs-model-tab:hover{color:var(--wb-color-text-primary,#1f1f1f)}',
+ '.wbs-model-tab.active{background:var(--wb-button-primary-bg,#1f1f1f);color:var(--wb-button-primary-fg,#fff);box-shadow:0 1px 4px rgba(0,0,0,.16)}',
+ '.wbs-model-tab-count{font-size:12px;opacity:.72;font-variant-numeric:tabular-nums}',
+ '.wbs-model-toolbar{display:flex;align-items:center;gap:6px;min-height:28px;margin-bottom:7px}',
+ '.wbs-model-toolbar-spacer{flex:1}',
+ '.wbs-model-count{font-size:13px;color:var(--wb-icon-tertiary,#888)}',
+ '.wbs-model-batchbar{display:flex;align-items:center;gap:6px;margin-bottom:7px;padding:6px 8px;border:1px solid var(--wb-border-default,#e5e5e5);border-radius:9px;background:color-mix(in srgb,var(--wb-bg-secondary,#fff) 18%,transparent)}',
+ '.wbs-model-batch-count{font-size:11px;color:var(--wb-icon-tertiary,#999)}',
+ '.wbs-model-batch-action{margin-left:auto}',
+ '.wbs-model-batchbar .wbs-sess-done{margin-left:0}',
+ '.wbs-model-batch-action:disabled{opacity:.45;cursor:not-allowed}',
+ '.wbs-model-list{display:flex;flex:1;min-height:0;flex-direction:column;gap:6px;max-height:none;overflow-y:auto;scrollbar-width:thin;scrollbar-color:transparent transparent}',
+ '.wbs-model-list:hover{scrollbar-color:rgba(128,128,128,.45) transparent}',
+ '.wbs-model-list::-webkit-scrollbar{width:6px}',
+ '.wbs-model-list::-webkit-scrollbar-thumb{background:transparent;border-radius:3px}',
+ '.wbs-model-list:hover::-webkit-scrollbar-thumb{background:rgba(128,128,128,.45)}',
+ '.wbs-model-row{display:flex;align-items:flex-start;box-sizing:border-box;width:100%;gap:10px;padding:10px 8px;border:0;border-radius:10px;background:transparent;transition:background .15s}',
+ '.wbs-model-row:hover{background:var(--wb-bg-hover,#f5f5f5)}',
+ '.wbs-model-main{min-width:0;flex:1}',
+ // 第一行:自定义名(左)+ 操作按钮组(右,占流固定;hover/focus cell 时由透明变不透明)
+ '.wbs-model-title-row{display:flex;align-items:center;gap:9px;min-width:0;margin-bottom:6px}',
+ '.wbs-model-name{min-width:0;flex:0 1 auto;font-size:14px;font-weight:650;color:var(--wb-color-text-primary,#1f1f1f);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}',
+ '.wbs-model-details{display:flex;flex-direction:column;gap:4px;min-width:0}',
+ // 第二行:vendor 标签 + 模型 id 标签
+ '.wbs-model-tag-row{display:flex;flex-wrap:wrap;align-items:center;gap:6px;min-width:0;margin-bottom:6px}',
+ '.wbs-model-tag{display:inline-flex;align-items:center;max-width:100%;padding:2px 8px;border:1px solid color-mix(in srgb,var(--wb-border-default,#e5e5e5) 85%,transparent);border-radius:999px;background:var(--wb-bg-tertiary,#f0f0f0);color:var(--wb-icon-secondary,#555);font-size:11px;font-weight:500;line-height:1.3;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}',
+ '.wbs-model-tag-id{color:var(--wb-icon-secondary,#666);font-family:ui-monospace,SFMono-Regular,Menlo,monospace}',
+ '.wbs-model-field{display:grid;grid-template-columns:52px minmax(0,1fr);align-items:center;gap:6px;min-width:0;font-size:12px;line-height:1.35}',
+ '.wbs-model-field span{min-width:0;color:var(--wb-icon-tertiary,#999);font-family:ui-monospace,SFMono-Regular,Menlo,monospace}',
+ '.wbs-model-field strong{display:block;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--wb-icon-secondary,#666);font-weight:500;text-align:left}',
+ // url 与 apiKey:完整展示,允许换行,不做省略截断(批量/悬浮切换不影响宽度与行高)
+ '.wbs-model-field strong.wbs-model-url,.wbs-model-field strong.wbs-model-key{white-space:normal;overflow-wrap:anywhere;word-break:break-all}',
+ '.wbs-model-key{letter-spacing:.2px}',
+ // 按钮组占流于标题行右侧,位置恒定;仅 hover/focus cell 时透明度 0→1
+ '.wbs-model-actions{display:flex;align-items:center;gap:4px;flex:0 0 auto;margin-left:auto;opacity:0;transition:opacity .15s}',
+ '.wbs-model-row:hover .wbs-model-actions,.wbs-model-row:focus-within .wbs-model-actions{opacity:1}',
+ '.wbs-model-action{display:inline-flex;align-items:center;justify-content:center;gap:4px;flex:0 0 auto;min-height:28px;padding:6px 10px;border:1px solid var(--wb-border-default,#e5e5e5);border-radius:8px;background:var(--wb-bg-popover,#fff);color:var(--wb-icon-secondary,#555);font-size:11px;font-weight:600;line-height:1;font-family:inherit;cursor:pointer;transition:background .15s,color .15s,border-color .15s}',
+ '.wbs-model-action:hover{background:var(--wb-button-primary-bg,#1f1f1f);border-color:var(--wb-button-primary-bg,#1f1f1f);color:var(--wb-button-primary-fg,#fff)}',
+ '.wbs-model-icon-action{display:inline-flex;align-items:center;justify-content:center;width:28px;height:28px;padding:0;border:1px solid transparent;border-radius:7px;background:var(--wb-bg-hover,#f7f8fa);color:var(--wb-icon-secondary,#555);cursor:pointer;transition:background .15s,color .15s,border-color .15s}',
+ '.wbs-model-icon-action:hover{background:color-mix(in srgb,var(--wb-button-primary-bg,#1f1f1f) 12%,transparent);border-color:transparent;color:var(--wb-color-text-primary,#1f1f1f)}',
+ '.wbs-model-icon-action:disabled{opacity:.45;cursor:wait}',
+ '.wbs-model-danger-action{background:var(--wb-bg-hover,#f7f8fa);color:var(--wb-icon-secondary,#555)}',
+ '.wbs-model-danger-action:hover{background:#ffecec;color:#f53f3f;border-color:transparent}',
+ '.wbs-model-enable{color:var(--wb-color-text-primary,#1f1f1f);background:var(--wb-bg-tertiary,#f0f0f0)}',
+ '.wbs-model-enable:hover{background:var(--wb-button-primary-bg,#1f1f1f);border-color:var(--wb-button-primary-bg,#1f1f1f);color:var(--wb-button-primary-fg,#fff)}',
+ '.wbs-model-enable-icon{display:inline-flex;align-items:center}',
+ '.wbs-model-group{display:flex;flex-direction:column;gap:3px}',
+ // 备选模型组与组之间:浅色细分隔线(仅出现在组间,首个组无)
+ '.wbs-model-group + .wbs-model-group{border-top:1px solid color-mix(in srgb,var(--wb-border-default,#e5e5e5) 55%,transparent);padding-top:9px}',
+ '.wbs-model-group-head{display:flex;align-items:center;gap:7px;padding:5px 4px 4px}',
+ '.wbs-model-group-title{display:inline-flex;align-items:center;max-width:calc(100% - 30px);padding:3px 9px;border-radius:999px;background:var(--wb-bg-tertiary,#f0f0f0);color:var(--wb-icon-secondary,#555);font-size:12px;font-weight:650;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}',
+ '.wbs-model-group-count{margin-left:auto;flex:0 0 auto;padding:2px 7px;border-radius:999px;background:var(--wb-bg-tertiary,#f0f0f0);color:var(--wb-icon-tertiary,#999);font-size:11px}',
+ '.wbs-model-check{margin:0;accent-color:var(--wb-button-primary-bg,#1f1f1f);flex:0 0 auto}',
+ // 小贴士:tips 通知条样式(圆角浅底 + 灯泡图标 + 标题)
+ '.wbs-model-tip{display:flex;align-items:center;gap:8px;margin:0 0 8px;padding:7px 11px;border:1px solid color-mix(in srgb,var(--wb-border-default,#e5e5e5) 82%,transparent);border-radius:10px;background:var(--wb-bg-tertiary,#f0f0f0);color:var(--wb-icon-tertiary,#777);font-size:11px;line-height:1.5;box-shadow:0 1px 3px rgba(0,0,0,.05)}',
+ '.wbs-model-tip-ico{display:inline-flex;align-items:center;flex:0 0 auto;color:var(--wb-icon-secondary,#555)}',
+ '.wbs-model-tip strong{flex:0 0 auto;color:var(--wb-color-text-secondary,#555);font-weight:650}',
+ '.wbs-model-tip span{min-width:0}',
+ '.wbs-model-edit-modal{width:min(390px,calc(100vw - 36px))}',
+ '.wbs-model-edit-form{display:flex;flex-direction:column;gap:11px;margin-bottom:20px}',
+ '.wbs-model-edit-field{display:flex;flex-direction:column;gap:5px;font-size:11px;color:var(--wb-icon-secondary,#666)}',
+ '.wbs-model-edit-field input{box-sizing:border-box;width:100%;min-height:32px;padding:6px 9px;border:1px solid var(--wb-border-default,#e5e5e5);border-radius:8px;background:var(--wb-bg-secondary,#fff);color:var(--wb-color-text-primary,#1f1f1f);font:inherit;outline:none}',
+ '.wbs-model-edit-field input:focus{border-color:var(--wb-button-primary-bg,#1f1f1f);box-shadow:0 0 0 2px color-mix(in srgb,var(--wb-button-primary-bg,#1f1f1f) 16%,transparent)}',
+ '.wbs-secret-wrap,.wbs-model-secret-wrap{position:relative;display:block}',
+ '.wbs-model-secret-wrap input{padding-right:34px}',
+ '.wbs-model-eye{position:absolute;right:4px;top:3px;width:27px;height:27px;display:flex;align-items:center;justify-content:center;border:0;border-radius:6px;background:transparent;color:var(--wb-icon-tertiary,#888);cursor:pointer}',
+ '.wbs-model-eye:hover{background:var(--wb-bg-hover,#f5f5f5);color:var(--wb-color-text-primary,#1f1f1f)}',
+ '.wbs-model-edit-field small{font-size:10px;color:var(--wb-icon-tertiary,#999)}',
'.wbs-sess-list{max-height:320px;overflow-y:auto;display:flex;flex-direction:column;gap:6px;margin-bottom:8px;scrollbar-width:thin;scrollbar-color:transparent transparent}',
'.wbs-sess-list:hover{scrollbar-color:rgba(128,128,128,.45) transparent}',
'.wbs-sess-list::-webkit-scrollbar{width:6px}',
@@ -4138,13 +4708,24 @@ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
'.wbs-sess-group-count{font-size:10px;color:var(--wb-icon-tertiary,#999);background:var(--wb-bg-tertiary,#f0f0f0);border-radius:9px;padding:1px 7px}',
'.wbs-sess-more{width:100%;padding:5px 8px;margin-top:4px;border:1px dashed var(--wb-border-default,#e5e5e5);border-radius:8px;background:transparent;color:var(--wb-icon-secondary,#555);font-size:11px;cursor:pointer;transition:all .15s;line-height:1}',
'.wbs-sess-more:hover{border-color:var(--wb-border-strong,#bbb);color:var(--wb-color-text-primary,#1f1f1f)}',
- '.wbs-sess-row{display:flex;align-items:flex-start;gap:8px;padding:6px 8px;border:1px solid transparent;border-radius:8px;cursor:pointer;transition:all .15s}',
+ '.wbs-sess-row{display:flex;align-items:flex-start;gap:8px;padding:6px 8px;border:1px solid transparent;border-radius:8px;cursor:pointer;transition:background .15s}',
'.wbs-sess-row:hover{background:var(--wb-bg-hover,#f5f5f5)}',
+ '.wbs-sess-tasks .wbs-sess-row{cursor:default}',
'.wbs-sess-row:has(input:checked){border-color:#fff;background:color-mix(in srgb,#fff 10%,transparent)}',
'.wbs-sess-row input{margin:2px 0 0;accent-color:#fff;flex-shrink:0}',
- '.wbs-sess-main{display:flex;flex-direction:column;gap:2px;min-width:0}',
+ '.wbs-sess-main{display:flex;flex-direction:column;gap:2px;min-width:0;flex:1}',
'.wbs-sess-title{font-size:12px;font-weight:600;color:var(--wb-color-text-primary,#1f1f1f);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}',
'.wbs-sess-meta{font-size:11px;color:var(--wb-icon-tertiary,#999)}',
+ '.wbs-sess-auto{display:inline-flex;align-items:center;justify-content:flex-end;gap:6px;flex:0 0 auto;min-width:76px;height:26px;margin-top:-2px;border:1px solid transparent;border-radius:7px;background:transparent;color:var(--wb-icon-tertiary,#999);cursor:pointer;padding:0 3px 0 5px;transition:background .15s,color .15s,opacity .15s;font:inherit}',
+ '.wbs-sess-auto:hover{background:var(--wb-bg-hover,#f5f5f5);color:var(--wb-color-text-primary,#1f1f1f)}',
+ '.wbs-sess-auto.active{color:var(--wb-button-primary-bg,#1f1f1f)}',
+ '.wbs-sess-auto.inherited{color:var(--wb-button-primary-bg,#1f1f1f);opacity:.62;cursor:default}',
+ '.wbs-sess-auto:disabled{cursor:default}',
+ '.wbs-sess-auto-label{font-size:11px;line-height:1;white-space:nowrap}',
+ '.wbs-sess-auto-switch{position:relative;display:inline-flex;align-items:center;width:24px;height:14px;flex:0 0 24px;border-radius:999px;background:var(--wb-bg-tertiary,#dedede);transition:background .15s}',
+ '.wbs-sess-auto-switch span{width:10px;height:10px;margin-left:2px;border-radius:50%;background:var(--wb-bg-popover,#fff);box-shadow:0 1px 2px rgba(0,0,0,.18);transition:transform .15s}',
+ '.wbs-sess-auto-switch.on{background:var(--wb-button-primary-bg,#1f1f1f)}',
+ '.wbs-sess-auto-switch.on span{transform:translateX(10px);background:var(--wb-button-primary-fg,#fff)}',
'.wbs-sess-actions{display:flex;gap:8px;justify-content:flex-end;padding-top:2px}',
'.wbs-sess-del{flex-shrink:0;padding:7px 12px;border:1px solid #ff6b6b;border-radius:9px;background:color-mix(in srgb,#ff6b6b 10%,transparent);color:#ff6b6b;font-size:12px;cursor:pointer;line-height:1;transition:all .15s}',
'.wbs-sess-del:hover{background:#ff6b6b;color:#fff}',
diff --git a/scripts/lib.js b/scripts/lib.js
index 9cf957a..13ff596 100644
--- a/scripts/lib.js
+++ b/scripts/lib.js
@@ -15,6 +15,7 @@
const fs = require('fs');
const os = require('os');
const path = require('path');
+const crypto = require('crypto');
const IS_WIN = process.platform === 'win32';
@@ -69,6 +70,538 @@ function accountsDir(dataDir) {
function metaFile(dataDir) {
return path.join(dataDir, 'meta.json');
}
+
+function workbuddyModelsFile() {
+ return path.join(os.homedir(), '.workbuddy', 'models.json');
+}
+
+function modelBackupsDir(dataDir) {
+ return path.join(dataDir, 'models');
+}
+
+function maskApiKey(apiKey) {
+ const value = String(apiKey || '');
+ if (!value) return '';
+ if (value.length <= 8) return '••••••';
+ const prefix = value.slice(0, Math.min(3, value.length - 4));
+ const suffix = value.slice(-4);
+ const middleLength = Math.max(1, value.length - prefix.length - suffix.length);
+ return `${prefix}${'•'.repeat(middleLength)}${suffix}`;
+}
+
+// 模型列表摘要。默认脱敏 apiKey;UI 需要明文展示(模型页 cell / 编辑弹窗)时传 { revealKey: true }。
+function sanitizeModel(model, opts) {
+ const value = model && typeof model === 'object' && !Array.isArray(model) ? model : {};
+ const revealKey = !!(opts && opts.revealKey);
+ return {
+ id: String(value.id || value.name || ''),
+ name: String(value.name || value.id || ''),
+ vendor: String(value.vendor || ''),
+ url: String(value.url || '').split('?')[0].split('#')[0],
+ apiKey: revealKey ? String(value.apiKey || '') : maskApiKey(value.apiKey),
+ supportsToolCall: !!value.supportsToolCall,
+ supportsImages: !!value.supportsImages,
+ supportsReasoning: !!value.supportsReasoning,
+ };
+}
+
+function readModelsFile(file = workbuddyModelsFile()) {
+ if (!fs.existsSync(file)) throw new Error(`未找到模型配置文件: ${file}`);
+ let parsed;
+ try {
+ parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
+ } catch (e) {
+ throw new Error(`模型配置文件不是有效 JSON: ${e.message}`);
+ }
+ if (Array.isArray(parsed)) return { file, format: 'array', models: parsed };
+ if (parsed && typeof parsed === 'object' && Array.isArray(parsed.models)) {
+ return { file, format: 'object', models: parsed.models, wrapper: parsed };
+ }
+ throw new Error('模型配置文件格式不受支持:应为数组或包含 models 数组的对象');
+}
+
+function writeModelsFile(parsed, models) {
+ const output = parsed.format === 'array' ? models : Object.assign({}, parsed.wrapper, { models });
+ const file = parsed.file;
+ const dir = path.dirname(file);
+ fs.mkdirSync(dir, { recursive: true });
+ let mode = 0o600;
+ try { mode = fs.statSync(file).mode & 0o777; } catch (_) {}
+ const tmp = `${file}.tmp.${process.pid}`;
+ fs.writeFileSync(tmp, JSON.stringify(output, null, 2) + '\n', { mode });
+ fs.renameSync(tmp, file);
+ try { fs.chmodSync(file, mode); } catch (_) {}
+}
+
+function modelBackupPath(dataDir, backupId) {
+ const id = String(backupId || '');
+ if (!/^[A-Za-z0-9_-]{8,100}$/.test(id)) throw new Error('非法模型备份标识');
+ return path.join(modelBackupsDir(dataDir), `${id}.json`);
+}
+
+function readModelBackup(dataDir, backupId) {
+ const file = modelBackupPath(dataDir, backupId);
+ if (!fs.existsSync(file)) throw new Error('模型备份不存在');
+ let record;
+ try { record = JSON.parse(fs.readFileSync(file, 'utf8')); } catch (e) { throw new Error(`模型备份损坏: ${e.message}`); }
+ if (!record || record.schema !== 1 || !record.model || typeof record.model !== 'object' || Array.isArray(record.model)) {
+ throw new Error('模型备份格式不受支持');
+ }
+ return { file, record };
+}
+
+function listModelBackups(dataDir) {
+ const dir = modelBackupsDir(dataDir);
+ let names = [];
+ try { names = fs.readdirSync(dir).filter((name) => /^[A-Za-z0-9_-]{8,100}\.json$/.test(name)); } catch (_) {}
+ const records = [];
+ for (const name of names) {
+ const backupId = name.slice(0, -5);
+ try {
+ const { record } = readModelBackup(dataDir, backupId);
+ const summary = sanitizeModel(record.model, { revealKey: true });
+ records.push({ backupId, createdAt: record.createdAt || null, ...summary });
+ } catch (_) {
+ // Ignore damaged files in the list; an explicit enable/delete still reports an error.
+ }
+ }
+ records.sort((a, b) => String(b.createdAt || '').localeCompare(String(a.createdAt || '')));
+ const groups = {};
+ for (const record of records) {
+ const key = record.id || '(未命名模型)';
+ // 组名用模型名(id):组内每个备份的自定义 name 可能不同,只有模型名一致
+ if (!groups[key]) groups[key] = { id: key, name: key, items: [] };
+ groups[key].items.push(record);
+ }
+ return Object.values(groups);
+}
+
+function listOfficialModels(file = workbuddyModelsFile()) {
+ const parsed = readModelsFile(file);
+ return parsed.models.map((model, index) => Object.assign({ index }, sanitizeModel(model, { revealKey: true })));
+}
+
+function readOfficialModel(file = workbuddyModelsFile(), index) {
+ const parsed = readModelsFile(file);
+ const position = Number(index);
+ if (!Number.isInteger(position) || position < 0 || position >= parsed.models.length) throw new Error('模型索引无效');
+ const model = parsed.models[position];
+ if (!model || typeof model !== 'object' || Array.isArray(model)) throw new Error('模型配置无效');
+ return model;
+}
+
+function deleteOfficialModels(file = workbuddyModelsFile(), indexes) {
+ const parsed = readModelsFile(file);
+ const positions = Array.isArray(indexes)
+ ? Array.from(new Set(indexes.map((value) => Number(value)).filter((value) => Number.isInteger(value) && value >= 0 && value < parsed.models.length)))
+ : [];
+ if (!positions.length) throw new Error('未选择当前模型');
+ const selected = new Set(positions);
+ const next = parsed.models.filter((_, index) => !selected.has(index));
+ writeModelsFile(parsed, next);
+ return { deleted: positions.length, official: next.map((model, index) => Object.assign({ index }, sanitizeModel(model))) };
+}
+
+function backupOfficialModel(dataDir, index, modelsFile = workbuddyModelsFile()) {
+ const parsed = readModelsFile(modelsFile);
+ const position = Number(index);
+ if (!Number.isInteger(position) || position < 0 || position >= parsed.models.length) throw new Error('模型索引无效');
+ const model = parsed.models[position];
+ if (!model || typeof model !== 'object' || Array.isArray(model)) throw new Error('模型配置无效');
+ const backupId = crypto.randomUUID();
+ const createdAt = new Date().toISOString();
+ fs.mkdirSync(modelBackupsDir(dataDir), { recursive: true, mode: 0o700 });
+ const file = modelBackupPath(dataDir, backupId);
+ fs.writeFileSync(file, JSON.stringify({ schema: 1, backupId, createdAt, model }, null, 2) + '\n', { mode: 0o600 });
+ return { backupId, createdAt, ...sanitizeModel(model) };
+}
+
+function writeModelBackup(dataDir, record) {
+ fs.mkdirSync(modelBackupsDir(dataDir), { recursive: true, mode: 0o700 });
+ const file = modelBackupPath(dataDir, record.backupId);
+ const tmp = `${file}.tmp.${process.pid}`;
+ fs.writeFileSync(tmp, JSON.stringify(record, null, 2) + '\n', { mode: 0o600 });
+ fs.renameSync(tmp, file);
+ try { fs.chmodSync(file, 0o600); } catch (_) {}
+}
+
+function copyModelBackup(dataDir, backupId) {
+ const { record } = readModelBackup(dataDir, backupId);
+ const copied = Object.assign({}, record, {
+ backupId: crypto.randomUUID(),
+ createdAt: new Date().toISOString(),
+ model: Object.assign({}, record.model),
+ });
+ writeModelBackup(dataDir, copied);
+ return { backupId: copied.backupId, createdAt: copied.createdAt, ...sanitizeModel(copied.model) };
+}
+
+function editModelBackup(dataDir, backupId, patch) {
+ const { record } = readModelBackup(dataDir, backupId);
+ const input = patch && typeof patch === 'object' && !Array.isArray(patch) ? patch : {};
+ const model = Object.assign({}, record.model);
+ for (const field of ['name', 'url', 'apiKey']) {
+ if (!Object.prototype.hasOwnProperty.call(input, field)) continue;
+ if (typeof input[field] !== 'string' || input[field].length > 20000) throw new Error(`模型${field}格式无效`);
+ model[field] = input[field];
+ }
+ const modelId = String(model.id || model.name || '').trim();
+ if (!modelId) throw new Error('模型备份缺少 id/name,无法保存');
+ if (!String(model.name || '').trim()) model.name = modelId;
+ const updated = Object.assign({}, record, { model });
+ writeModelBackup(dataDir, updated);
+ return { backupId: updated.backupId, createdAt: updated.createdAt || null, ...sanitizeModel(model) };
+}
+
+function deleteModelBackups(dataDir, backupIds) {
+ const ids = Array.isArray(backupIds) ? backupIds : [];
+ let deleted = 0;
+ for (const id of ids) {
+ try {
+ const file = modelBackupPath(dataDir, id);
+ if (fs.existsSync(file)) { fs.unlinkSync(file); deleted++; }
+ } catch (_) {}
+ }
+ return deleted;
+}
+
+function enableModelBackup(dataDir, backupId, file = workbuddyModelsFile()) {
+ const { record } = readModelBackup(dataDir, backupId);
+ const modelId = String(record.model.id || record.model.name || '').trim();
+ if (!modelId) throw new Error('模型备份缺少 id/name,无法启用');
+ const parsed = readModelsFile(file);
+ const models = parsed.models.slice();
+ const first = models.findIndex((model) => String(model && (model.id || model.name) || '') === modelId);
+ const next = [];
+ let inserted = false;
+ for (const model of models) {
+ const id = String(model && (model.id || model.name) || '');
+ if (id === modelId) {
+ if (!inserted) { next.push(record.model); inserted = true; }
+ } else next.push(model);
+ }
+ if (!inserted) next.push(record.model);
+ writeModelsFile(parsed, next);
+ return { backupId, id: modelId, replaced: first >= 0, ...sanitizeModel(record.model) };
+}
+
+function readMeta(dataDir) {
+ let meta = { accounts: {} };
+ try {
+ meta = JSON.parse(fs.readFileSync(metaFile(dataDir), 'utf8'));
+ } catch (_) {
+ /* 首次运行或旧版本没有 meta.json */
+ }
+ if (!meta || typeof meta !== 'object' || Array.isArray(meta)) meta = {};
+ if (!meta.accounts || typeof meta.accounts !== 'object' || Array.isArray(meta.accounts)) meta.accounts = {};
+ return meta;
+}
+
+function writeMeta(dataDir, meta) {
+ ensureDirs(dataDir);
+ const mf = metaFile(dataDir);
+ const tmp = `${mf}.tmp.${process.pid}`;
+ fs.writeFileSync(tmp, JSON.stringify(meta, null, 2), { mode: 0o600 });
+ fs.renameSync(tmp, mf);
+ try { fs.chmodSync(mf, 0o600); } catch (_) {}
+}
+
+/** 使用稳定路径键,不要求路径当前存在(空间可能已被移动或卸载)。 */
+function canonicalWorkspace(cwd) {
+ let value = String(cwd || '').trim();
+ if (!value) return '';
+ value = value.replace(/\\/g, '/');
+ value = path.posix.normalize(value);
+ if (value === '.') return '';
+ if (value.length > 1) value = value.replace(/\/+$/, '');
+ return IS_WIN ? value.toLowerCase() : value;
+}
+
+function ensureAutoCopyMeta(meta) {
+ const current = meta.autoCopy;
+ if (current && current.version === 2 && current.sessions && current.sessionIndex && current.workspaces && current.copies) {
+ return current;
+ }
+
+ // 1.0.15 stored rules under sourceUid. Convert them once to global session lineages
+ // and global workspace paths so a migration/copy keeps the same shared identity.
+ const legacy = current && typeof current === 'object' && !Array.isArray(current) ? current : {};
+ const next = { version: 2, sessions: {}, sessionIndex: {}, workspaces: {}, copies: {} };
+ const legacySessions = legacy.sessions && typeof legacy.sessions === 'object' ? legacy.sessions : {};
+ for (const sourceUid of Object.keys(legacySessions)) {
+ const bucket = legacySessions[sourceUid];
+ if (!bucket || typeof bucket !== 'object' || Array.isArray(bucket)) continue;
+ for (const sessionId of Object.keys(bucket)) {
+ const legacyRule = bucket[sessionId];
+ if (legacyRule === false || (legacyRule && typeof legacyRule === 'object' && legacyRule.enabled === false)) continue;
+ const lineageId = crypto.randomUUID();
+ next.sessions[lineageId] = { enabled: true, members: [{ uid: sourceUid, id: sessionId }], createdAt: Date.now() };
+ if (!next.sessionIndex[sourceUid]) next.sessionIndex[sourceUid] = {};
+ next.sessionIndex[sourceUid][sessionId] = lineageId;
+ }
+ }
+ const legacyWorkspaces = legacy.workspaces && typeof legacy.workspaces === 'object' ? legacy.workspaces : {};
+ for (const sourceUid of Object.keys(legacyWorkspaces)) {
+ const bucket = legacyWorkspaces[sourceUid];
+ if (!bucket || typeof bucket !== 'object' || Array.isArray(bucket)) continue;
+ for (const cwd of Object.keys(bucket)) {
+ if (bucket[cwd] === false) continue;
+ const canonical = canonicalWorkspace(cwd);
+ if (canonical) next.workspaces[canonical] = String(bucket[cwd] || cwd);
+ }
+ }
+ const legacyCopies = legacy.copies && typeof legacy.copies === 'object' ? legacy.copies : {};
+ for (const oldKey of Object.keys(legacyCopies)) {
+ try {
+ const parts = JSON.parse(oldKey);
+ if (!Array.isArray(parts) || parts.length !== 3) continue;
+ const lineageId = next.sessionIndex[String(parts[0] || '')] && next.sessionIndex[String(parts[0] || '')][String(parts[2] || '')];
+ if (lineageId) next.copies[JSON.stringify([lineageId, String(parts[1] || '')])] = legacyCopies[oldKey];
+ } catch (_) {}
+ }
+ meta.autoCopy = next;
+ return next;
+}
+
+function readAutoCopyConfig(dataDir) {
+ const meta = readMeta(dataDir);
+ const wasCurrent = !!(meta.autoCopy && meta.autoCopy.version === 2);
+ const autoCopy = ensureAutoCopyMeta(meta);
+ if (!wasCurrent) writeMeta(dataDir, meta);
+ return {
+ sessions: autoCopy.sessions,
+ sessionIndex: autoCopy.sessionIndex,
+ workspaces: autoCopy.workspaces,
+ copies: autoCopy.copies,
+ };
+}
+
+function autoCopyRuleKey(lineageId, targetUid) {
+ return JSON.stringify([String(lineageId || ''), String(targetUid || '')]);
+}
+
+function getAutoCopyRules(dataDir, uid) {
+ const config = readAutoCopyConfig(dataDir);
+ const sourceUid = String(uid || '').trim();
+ const index = config.sessionIndex[sourceUid] || {};
+ const sessionIds = [];
+ const lineages = {};
+ for (const sessionId of Object.keys(index)) {
+ const lineageId = index[sessionId];
+ const lineage = config.sessions[lineageId];
+ if (lineage && lineage.enabled !== false) {
+ sessionIds.push(sessionId);
+ lineages[sessionId] = lineageId;
+ }
+ }
+ return {
+ sessionIds,
+ lineages,
+ workspaces: Object.keys(config.workspaces),
+ };
+}
+
+function setAutoCopyRule(dataDir, { uid, kind, key, enabled }) {
+ const sourceUid = String(uid || '').trim();
+ if (kind !== 'session' && kind !== 'workspace') throw new Error('无效的自动复制规则类型');
+ const value = kind === 'workspace' ? canonicalWorkspace(key) : String(key || '').trim();
+ if (!value) throw new Error('缺少自动复制规则标识');
+ const meta = readMeta(dataDir);
+ const config = ensureAutoCopyMeta(meta);
+ if (kind === 'workspace') {
+ if (enabled) config.workspaces[value] = String(key || '').trim();
+ else delete config.workspaces[value];
+ writeMeta(dataDir, meta);
+ return getAutoCopyRules(dataDir, sourceUid);
+ }
+ if (!sourceUid) throw new Error('缺少源账号 uid');
+ if (!config.sessionIndex[sourceUid]) config.sessionIndex[sourceUid] = {};
+ const lineageId = config.sessionIndex[sourceUid][value];
+ if (enabled) {
+ const lineage = lineageId && config.sessions[lineageId]
+ ? config.sessions[lineageId]
+ : { enabled: true, members: [], createdAt: Date.now() };
+ if (!lineageId) {
+ const createdId = crypto.randomUUID();
+ config.sessions[createdId] = lineage;
+ config.sessionIndex[sourceUid][value] = createdId;
+ addLineageMember(lineage, sourceUid, value);
+ } else {
+ lineage.enabled = true;
+ addLineageMember(lineage, sourceUid, value);
+ }
+ } else {
+ if (lineageId && config.sessions[lineageId]) config.sessions[lineageId].enabled = false;
+ }
+ writeMeta(dataDir, meta);
+ return getAutoCopyRules(dataDir, sourceUid);
+}
+
+function addLineageMember(lineage, uid, id) {
+ if (!Array.isArray(lineage.members)) lineage.members = [];
+ if (!lineage.members.some((member) => member && member.uid === uid && member.id === id)) {
+ lineage.members.push({ uid, id });
+ }
+}
+
+function getAutoCopySession(dataDir, uid, sessionId) {
+ const config = readAutoCopyConfig(dataDir);
+ const lineageId = config.sessionIndex[String(uid || '').trim()] && config.sessionIndex[String(uid || '').trim()][String(sessionId || '').trim()];
+ const lineage = lineageId ? config.sessions[lineageId] : null;
+ return { lineageId: lineageId || null, enabled: !!(lineage && lineage.enabled !== false) };
+}
+
+function ensureAutoCopySession(dataDir, uid, sessionId) {
+ const meta = readMeta(dataDir);
+ const config = ensureAutoCopyMeta(meta);
+ const sourceUid = String(uid || '').trim();
+ const id = String(sessionId || '').trim();
+ if (!sourceUid || !id) throw new Error('缺少共享会话标识');
+ if (!config.sessionIndex[sourceUid]) config.sessionIndex[sourceUid] = {};
+ let lineageId = config.sessionIndex[sourceUid][id];
+ if (!lineageId || !config.sessions[lineageId]) {
+ lineageId = crypto.randomUUID();
+ config.sessions[lineageId] = { enabled: true, members: [], createdAt: Date.now() };
+ config.sessionIndex[sourceUid][id] = lineageId;
+ }
+ addLineageMember(config.sessions[lineageId], sourceUid, id);
+ writeMeta(dataDir, meta);
+ return lineageId;
+}
+
+function addAutoCopySessionMember(dataDir, lineageId, uid, sessionId) {
+ const meta = readMeta(dataDir);
+ const config = ensureAutoCopyMeta(meta);
+ const lineage = config.sessions[String(lineageId || '')];
+ if (!lineage) return false;
+ const sourceUid = String(uid || '').trim();
+ const id = String(sessionId || '').trim();
+ if (!sourceUid || !id) return false;
+ if (!config.sessionIndex[sourceUid]) config.sessionIndex[sourceUid] = {};
+ const previousLineageId = config.sessionIndex[sourceUid][id];
+ if (previousLineageId && previousLineageId !== String(lineageId) && config.sessions[previousLineageId]) {
+ config.sessions[previousLineageId].members = (config.sessions[previousLineageId].members || [])
+ .filter((member) => !(member && member.uid === sourceUid && member.id === id));
+ }
+ config.sessionIndex[sourceUid][id] = String(lineageId);
+ addLineageMember(lineage, sourceUid, id);
+ writeMeta(dataDir, meta);
+ return true;
+}
+
+function moveAutoCopySession(dataDir, fromUid, toUid, sessionId) {
+ const meta = readMeta(dataDir);
+ const config = ensureAutoCopyMeta(meta);
+ const from = String(fromUid || '').trim();
+ const to = String(toUid || '').trim();
+ const id = String(sessionId || '').trim();
+ if (!from || !to || !id || from === to) return false;
+ const lineageId = config.sessionIndex[from] && config.sessionIndex[from][id];
+ if (!lineageId || !config.sessions[lineageId]) return false;
+ if (config.sessionIndex[from]) delete config.sessionIndex[from][id];
+ if (!config.sessionIndex[to]) config.sessionIndex[to] = {};
+ config.sessionIndex[to][id] = lineageId;
+ const lineage = config.sessions[lineageId];
+ lineage.members = (lineage.members || []).filter((member) => !(member && member.uid === from && member.id === id));
+ addLineageMember(lineage, to, id);
+ writeMeta(dataDir, meta);
+ return true;
+}
+
+function removeAutoCopySession(dataDir, uid, sessionId) {
+ const meta = readMeta(dataDir);
+ const config = ensureAutoCopyMeta(meta);
+ const sourceUid = String(uid || '').trim();
+ const id = String(sessionId || '').trim();
+ const lineageId = config.sessionIndex[sourceUid] && config.sessionIndex[sourceUid][id];
+ if (!lineageId) return false;
+ delete config.sessionIndex[sourceUid][id];
+ const lineage = config.sessions[lineageId];
+ if (lineage) {
+ lineage.members = (lineage.members || []).filter((member) => !(member && member.uid === sourceUid && member.id === id));
+ if (!lineage.members.length) {
+ delete config.sessions[lineageId];
+ for (const key of Object.keys(config.copies)) {
+ try {
+ const parts = JSON.parse(key);
+ if (Array.isArray(parts) && parts[0] === lineageId) delete config.copies[key];
+ } catch (_) {
+ // Ignore malformed legacy mapping keys; they cannot match a valid lineage.
+ }
+ }
+ }
+ }
+ writeMeta(dataDir, meta);
+ return true;
+}
+
+function removeAutoCopyAccount(dataDir, uid) {
+ const sourceUid = String(uid || '').trim();
+ if (!sourceUid) return 0;
+ const meta = readMeta(dataDir);
+ const config = ensureAutoCopyMeta(meta);
+ const index = config.sessionIndex[sourceUid] || {};
+ const entries = Object.keys(index).map((sessionId) => ({ sessionId, lineageId: index[sessionId] }));
+ let removed = 0;
+ for (const entry of entries) {
+ delete index[entry.sessionId];
+ const lineage = config.sessions[entry.lineageId];
+ if (!lineage) continue;
+ lineage.members = (lineage.members || []).filter((member) => !(member && member.uid === sourceUid && member.id === entry.sessionId));
+ if (!lineage.members.length) {
+ delete config.sessions[entry.lineageId];
+ for (const key of Object.keys(config.copies)) {
+ try {
+ const parts = JSON.parse(key);
+ if (Array.isArray(parts) && parts[0] === entry.lineageId) delete config.copies[key];
+ } catch (_) {}
+ }
+ }
+ removed++;
+ }
+ if (entries.length) {
+ delete config.sessionIndex[sourceUid];
+ writeMeta(dataDir, meta);
+ }
+ return removed;
+}
+
+function resolveMappingLineage(config, lineageOrUid, maybeSessionId) {
+ if (maybeSessionId === undefined) return String(lineageOrUid || '');
+ const sourceUid = String(lineageOrUid || '').trim();
+ const sessionId = String(maybeSessionId || '').trim();
+ return config.sessionIndex[sourceUid] && config.sessionIndex[sourceUid][sessionId]
+ ? config.sessionIndex[sourceUid][sessionId]
+ : '';
+}
+
+// The optional legacy sessionId argument keeps 1.0.15 local callers compatible
+// while all persisted keys use lineageId + targetUid.
+function getAutoCopyMapping(dataDir, lineageOrUid, targetUid, maybeSessionId) {
+ const config = readAutoCopyConfig(dataDir);
+ const lineageId = resolveMappingLineage(config, lineageOrUid, maybeSessionId);
+ return config.copies[autoCopyRuleKey(lineageId, targetUid)] || null;
+}
+
+function setAutoCopyMapping(dataDir, lineageOrUid, targetUid, mappingOrSessionId, maybeMapping) {
+ const meta = readMeta(dataDir);
+ const config = ensureAutoCopyMeta(meta);
+ const legacyCall = arguments.length >= 5;
+ const lineageId = resolveMappingLineage(config, lineageOrUid, legacyCall ? mappingOrSessionId : undefined);
+ const mapping = legacyCall ? maybeMapping : mappingOrSessionId;
+ const key = autoCopyRuleKey(lineageId, targetUid);
+ config.copies[key] = Object.assign({}, mapping, { updatedAt: Date.now() });
+ writeMeta(dataDir, meta);
+ return config.copies[key];
+}
+
+function deleteAutoCopyMapping(dataDir, lineageOrUid, targetUid, maybeSessionId) {
+ const meta = readMeta(dataDir);
+ const config = ensureAutoCopyMeta(meta);
+ const lineageId = resolveMappingLineage(config, lineageOrUid, maybeSessionId);
+ delete config.copies[autoCopyRuleKey(lineageId, targetUid)];
+ writeMeta(dataDir, meta);
+}
function logFile(dataDir) {
return path.join(dataDir, 'daemon.log');
}
@@ -192,14 +725,7 @@ function readAuthFile() {
/** 更新 meta.json(uid -> nickname/uin/phone/时间) */
function updateMeta(dataDir, info) {
- const mf = metaFile(dataDir);
- let meta = { accounts: {} };
- try {
- meta = JSON.parse(fs.readFileSync(mf, 'utf8'));
- if (!meta.accounts) meta.accounts = {};
- } catch (_) {
- /* 首次运行 */
- }
+ const meta = readMeta(dataDir);
const now = Date.now();
const prev = meta.accounts[info.uid] || {};
meta.accounts[info.uid] = {
@@ -210,7 +736,7 @@ function updateMeta(dataDir, info) {
firstSeen: prev.firstSeen || now,
lastSeen: now,
};
- fs.writeFileSync(mf, JSON.stringify(meta, null, 2), { mode: 0o600 });
+ writeMeta(dataDir, meta);
return meta;
}
@@ -355,12 +881,38 @@ module.exports = {
migrateLegacyDataDir,
accountsDir,
metaFile,
+ workbuddyModelsFile,
+ modelBackupsDir,
+ maskApiKey,
+ sanitizeModel,
+ listOfficialModels,
+ readOfficialModel,
+ readModelBackup,
+ deleteOfficialModels,
+ listModelBackups,
+ backupOfficialModel,
+ copyModelBackup,
+ editModelBackup,
+ deleteModelBackups,
+ enableModelBackup,
logFile,
backupPath,
retireLogoutMarker,
ensureDirs,
readAuthFile,
updateMeta,
+ canonicalWorkspace,
+ getAutoCopyRules,
+ setAutoCopyRule,
+ getAutoCopySession,
+ ensureAutoCopySession,
+ addAutoCopySessionMember,
+ moveAutoCopySession,
+ removeAutoCopySession,
+ removeAutoCopyAccount,
+ getAutoCopyMapping,
+ setAutoCopyMapping,
+ deleteAutoCopyMapping,
backupCurrent,
listAccounts,
switchTo,
diff --git a/scripts/watchdog.js b/scripts/watchdog.js
index cb5c064..ce73a58 100644
--- a/scripts/watchdog.js
+++ b/scripts/watchdog.js
@@ -22,6 +22,7 @@ const 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');
+const UPDATE_PENDING_FILE = path.join(DATA_DIR, 'update', 'pending.json'); // 自动更新进行中标记(update 目录由 apply 流程创建)
function log(...args) {
const line = `[${new Date().toISOString()}] ${args.join(' ')}\n`;
@@ -85,6 +86,13 @@ function startDaemon() {
child.on('exit', (code, signal) => {
child = null;
if (stopping) { log('daemon 已退出(watchdog 停止中)'); return; }
+ // 自动更新标记存在:daemon 是在「更新替换」窗口内退出的(apply-update.ps1 正在换文件),
+ // 绝不能立刻重启 daemon 抢占 47832 端口,否则会干扰替换甚至导致更新失败(历史偶发根因)。
+ // 标记由 apply-update.ps1 成功/失败后删除;删除后靠新版 launcher/手动启动重新拉起。
+ if (fs.existsSync(UPDATE_PENDING_FILE)) {
+ log('检测到更新标记 pending.json,跳过自动重启 daemon(等待 apply-update.ps1 完成替换)');
+ return;
+ }
log('daemon 退出 code=' + code + ' signal=' + signal + ',' + restartDelay + 'ms 后重启');
setTimeout(startDaemon, restartDelay);
restartDelay = Math.min(restartDelay * 2, 60000);
diff --git a/test/auto-copy-rules.test.js b/test/auto-copy-rules.test.js
new file mode 100644
index 0000000..df73a53
--- /dev/null
+++ b/test/auto-copy-rules.test.js
@@ -0,0 +1,187 @@
+'use strict';
+
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const test = require('node:test');
+
+const {
+ metaFile,
+ canonicalWorkspace,
+ getAutoCopyRules,
+ setAutoCopyRule,
+ getAutoCopySession,
+ addAutoCopySessionMember,
+ moveAutoCopySession,
+ removeAutoCopySession,
+ removeAutoCopyAccount,
+ setAutoCopyMapping,
+ getAutoCopyMapping,
+ listOfficialModels,
+ maskApiKey,
+ sanitizeModel,
+ deleteOfficialModels,
+ listModelBackups,
+ backupOfficialModel,
+ copyModelBackup,
+ editModelBackup,
+ deleteModelBackups,
+ enableModelBackup,
+} = require('../scripts/lib.js');
+
+function tempDataDir() {
+ return fs.mkdtempSync(path.join(os.tmpdir(), 'workdaddy-auto-copy-'));
+}
+
+function writeMeta(dataDir, value) {
+ fs.writeFileSync(metaFile(dataDir), JSON.stringify(value, null, 2), { mode: 0o600 });
+}
+
+test('legacy account-scoped rules migrate to global lineages and workspace paths', () => {
+ const dataDir = tempDataDir();
+ const oldKey = JSON.stringify(['h', 's', 'session-a']);
+ writeMeta(dataDir, {
+ accounts: {},
+ autoCopy: {
+ version: 1,
+ sessions: { h: { 'session-a': true } },
+ workspaces: { h: { '/Users/example/Repo/': '/Users/example/Repo/' }, s: { '/Users/example/Repo': '/Users/example/Repo' } },
+ copies: { [oldKey]: { targetId: 'session-copy' } },
+ },
+ });
+
+ const rules = getAutoCopyRules(dataDir, 'h');
+ assert.deepEqual(rules.sessionIds, ['session-a']);
+ assert.equal(rules.workspaces.length, 1);
+ assert.equal(canonicalWorkspace('/Users/example/Repo/'), '/Users/example/Repo');
+ const lineage = getAutoCopySession(dataDir, 'h', 'session-a');
+ assert.ok(lineage.lineageId);
+ assert.equal(lineage.enabled, true);
+ assert.equal(getAutoCopyMapping(dataDir, lineage.lineageId, 's').targetId, 'session-copy');
+ assert.equal(JSON.parse(fs.readFileSync(metaFile(dataDir), 'utf8')).autoCopy.version, 2);
+});
+
+test('marked session keeps one lineage through migration and repeated account switching', () => {
+ const dataDir = tempDataDir();
+ setAutoCopyRule(dataDir, { uid: 'h', kind: 'session', key: 'session-a', enabled: true });
+ const original = getAutoCopySession(dataDir, 'h', 'session-a');
+ addAutoCopySessionMember(dataDir, original.lineageId, 's', 'session-s');
+ setAutoCopyMapping(dataDir, original.lineageId, 's', { targetId: 'session-s' });
+
+ assert.equal(moveAutoCopySession(dataDir, 'h', 'x', 'session-a'), true);
+ const moved = getAutoCopySession(dataDir, 'x', 'session-a');
+ assert.equal(moved.lineageId, original.lineageId);
+ assert.equal(moved.enabled, true);
+ assert.equal(getAutoCopySession(dataDir, 'h', 'session-a').lineageId, null);
+ assert.equal(getAutoCopySession(dataDir, 's', 'session-s').lineageId, original.lineageId);
+ assert.equal(getAutoCopyMapping(dataDir, original.lineageId, 's').targetId, 'session-s');
+
+ // One global unmark disables the shared session for every account member.
+ setAutoCopyRule(dataDir, { uid: 'x', kind: 'session', key: 'session-a', enabled: false });
+ assert.equal(getAutoCopySession(dataDir, 's', 'session-s').enabled, false);
+ assert.equal(getAutoCopySession(dataDir, 'x', 'session-a').enabled, false);
+});
+
+test('deleting the last lineage member removes mappings, while other members retain them', () => {
+ const dataDir = tempDataDir();
+ setAutoCopyRule(dataDir, { uid: 'h', kind: 'session', key: 'session-a', enabled: true });
+ const lineageId = getAutoCopySession(dataDir, 'h', 'session-a').lineageId;
+ addAutoCopySessionMember(dataDir, lineageId, 's', 'session-s');
+ setAutoCopyMapping(dataDir, lineageId, 's', { targetId: 'session-s' });
+
+ assert.equal(removeAutoCopySession(dataDir, 'h', 'session-a'), true);
+ assert.equal(getAutoCopyMapping(dataDir, lineageId, 's').targetId, 'session-s');
+ assert.equal(removeAutoCopyAccount(dataDir, 's'), 1);
+ assert.equal(getAutoCopyMapping(dataDir, lineageId, 's'), null);
+});
+
+test('workspace rules are global across source accounts', () => {
+ const dataDir = tempDataDir();
+ setAutoCopyRule(dataDir, { uid: 'h', kind: 'workspace', key: '/Users/h/Repo/', enabled: true });
+ assert.deepEqual(getAutoCopyRules(dataDir, 'h').workspaces, ['/Users/h/Repo']);
+ assert.deepEqual(getAutoCopyRules(dataDir, 's').workspaces, ['/Users/h/Repo']);
+ setAutoCopyRule(dataDir, { uid: 's', kind: 'workspace', key: '/Users/h/Repo', enabled: false });
+ assert.deepEqual(getAutoCopyRules(dataDir, 'h').workspaces, []);
+});
+
+test('long account chains reuse one lineage and clean up without duplicate members', () => {
+ const dataDir = tempDataDir();
+ setAutoCopyRule(dataDir, { uid: 'h', kind: 'session', key: 'session-chain', enabled: true });
+ const lineageId = getAutoCopySession(dataDir, 'h', 'session-chain').lineageId;
+ for (let i = 0; i < 100; i++) {
+ addAutoCopySessionMember(dataDir, lineageId, 'account-' + i, 'copy-' + i);
+ addAutoCopySessionMember(dataDir, lineageId, 'account-' + i, 'copy-' + i);
+ setAutoCopyMapping(dataDir, lineageId, 'account-' + i, { targetId: 'copy-' + i });
+ }
+ const meta = JSON.parse(fs.readFileSync(metaFile(dataDir), 'utf8'));
+ assert.equal(meta.autoCopy.sessions[lineageId].members.length, 101);
+ for (let i = 0; i < 100; i++) assert.equal(getAutoCopySession(dataDir, 'account-' + i, 'copy-' + i).lineageId, lineageId);
+ assert.equal(removeAutoCopyAccount(dataDir, 'h'), 1);
+ assert.equal(getAutoCopyMapping(dataDir, lineageId, 'account-99').targetId, 'copy-99');
+ for (let i = 0; i < 100; i++) assert.equal(removeAutoCopyAccount(dataDir, 'account-' + i), 1);
+ assert.equal(getAutoCopyMapping(dataDir, lineageId, 'account-99'), null);
+});
+
+test('model backups preserve full local config while enabling one id removes official duplicates', () => {
+ const dataDir = tempDataDir();
+ const modelsFile = path.join(dataDir, 'models.json');
+ const official = [
+ { id: 'same-id', name: 'Old label', apiKey: 'secret-a', url: 'https://one.invalid' },
+ { id: 'same-id', name: 'New label', apiKey: 'secret-b', url: 'https://two.invalid' },
+ { id: 'other-id', name: 'Other', apiKey: 'secret-c' },
+ ];
+ fs.writeFileSync(modelsFile, JSON.stringify(official));
+ assert.equal(listOfficialModels(modelsFile).length, 3);
+ // 模型页 UI 需要明文展示 apiKey(cell / 编辑弹窗),列表接口按 { revealKey: true } 返回明文;
+ // sanitizeModel 默认仍脱敏,供非展示场景使用。
+ assert.equal(listOfficialModels(modelsFile)[0].apiKey, 'secret-a');
+ assert.equal(sanitizeModel(official[0]).apiKey, '••••••');
+ assert.notEqual(sanitizeModel(official[0]).apiKey, 'secret-a');
+
+ const backup = backupOfficialModel(dataDir, 1, modelsFile);
+ assert.equal(backup.id, 'same-id');
+ assert.equal(listModelBackups(dataDir)[0].items.length, 1);
+ const enabled = enableModelBackup(dataDir, backup.backupId, modelsFile);
+ assert.equal(enabled.id, 'same-id');
+ const after = JSON.parse(fs.readFileSync(modelsFile, 'utf8'));
+ assert.equal(after.filter((model) => model.id === 'same-id').length, 1);
+ assert.equal(after.find((model) => model.id === 'same-id').apiKey, 'secret-b');
+
+ const copied = copyModelBackup(dataDir, backup.backupId);
+ assert.notEqual(copied.backupId, backup.backupId);
+ assert.equal(copied.apiKey, '••••••');
+ const edited = editModelBackup(dataDir, copied.backupId, { name: 'Edited label', url: 'https://edited.invalid', apiKey: 'secret-edited' });
+ assert.equal(edited.name, 'Edited label');
+ assert.equal(edited.url, 'https://edited.invalid');
+ assert.equal(edited.apiKey, 'sec••••••ited');
+ assert.equal(listModelBackups(dataDir).find((group) => group.id === 'same-id').items.length, 2);
+
+ assert.equal(deleteModelBackups(dataDir, [backup.backupId, copied.backupId]), 2);
+ assert.equal(listModelBackups(dataDir).length, 0);
+});
+
+test('official model batch deletion only changes official config and leaves backups intact', () => {
+ const dataDir = tempDataDir();
+ const modelsFile = path.join(dataDir, 'models.json');
+ fs.writeFileSync(modelsFile, JSON.stringify([
+ { id: 'one', name: 'One', apiKey: 'secret-one' },
+ { id: 'two', name: 'Two', apiKey: 'secret-two' },
+ { id: 'three', name: 'Three', apiKey: 'secret-three' },
+ ]));
+ const backup = backupOfficialModel(dataDir, 1, modelsFile);
+ const result = deleteOfficialModels(modelsFile, [0, 2]);
+ assert.equal(result.deleted, 2);
+ assert.deepEqual(JSON.parse(fs.readFileSync(modelsFile, 'utf8')).map((model) => model.id), ['two']);
+ assert.equal(listModelBackups(dataDir)[0].items[0].id, 'two');
+ assert.equal(fs.existsSync(path.join(dataDir, 'models', backup.backupId + '.json')), true);
+});
+
+test('api keys keep their full masked length without exposing the middle', () => {
+ const raw = 'sk-abcdefghijklmnopqrstuvwxyz0123456789-dlzj';
+ const masked = maskApiKey(raw);
+ assert.equal(masked.length, raw.length);
+ assert.equal(masked.slice(0, 3), 'sk-');
+ assert.equal(masked.slice(-4), 'dlzj');
+ assert.equal(masked.includes('abcdef'), false);
+});
diff --git a/test/update-layout.test.js b/test/update-layout.test.js
index fa176e2..aa8562f 100644
--- a/test/update-layout.test.js
+++ b/test/update-layout.test.js
@@ -7,17 +7,20 @@ const test = require('node:test');
const repoRoot = path.resolve(__dirname, '..');
const read = (name) => fs.readFileSync(path.join(repoRoot, 'scripts', name), 'utf8');
+const lib = require(path.join(repoRoot, 'scripts', 'lib.js'));
test('Windows updater launches the installed scripts launcher', () => {
const script = read('apply-update.ps1');
- assert.match(script, /Join-Path\s+\(Join-Path\s+\$AppDir\s+'scripts'\)\s+'launcher\.cmd'/);
- assert.match(script, /Join-Path\s+\(Join-Path\s+\$AppDir\s+'scripts'\)\s+'launcher-hidden\.vbs'/);
+ assert.match(script, /Join-Path\s+\$AppDir\s+'scripts\\launcher\.cmd'/);
+ assert.match(script, /Join-Path\s+\$AppDir\s+'scripts\\launcher-hidden\.vbs'/);
+ assert.match(script, /Start-Process[\s\S]*-ErrorAction Stop/);
+ assert.match(script, /Invoke-RestMethod[\s\S]*\/api\/status/);
});
test('Windows updater stops the watchdog before waiting for the API port', () => {
const script = read('apply-update.ps1');
- const stop = script.indexOf('taskkill /F /T /PID $wpid');
- const wait = script.indexOf('$waitSec = 0');
+ const stop = script.indexOf('function Stop-WatchdogAndPort');
+ const wait = script.indexOf('for ($wait = 0; $wait -lt 15; $wait++)');
assert.notEqual(stop, -1);
assert.notEqual(wait, -1);
assert.ok(stop < wait, 'watchdog shutdown must precede the port wait');
@@ -34,7 +37,7 @@ test('Windows install and update release a locked launcher before replacing it',
assert.match(update, /FileShare\]\s*::None/);
assert.match(update, /launcher\.cmd/);
assert.match(update, /Get-CimInstance\s+Win32_Process/);
- assert.ok(update.indexOf('Release-LockedLauncher') < update.indexOf('Move-Item -Force $AppDir $oldDir'), 'update must release launcher before moving the old app');
+ assert.ok(update.indexOf('Release-LockedLauncher') < update.indexOf('Move-Item -LiteralPath $AppDir'), 'update must release launcher before moving the old app');
});
test('macOS updater stops the daemon before waiting for the API port', () => {
@@ -46,6 +49,21 @@ test('macOS updater stops the daemon before waiting for the API port', () => {
assert.ok(stop < wait, 'daemon shutdown must precede the port wait');
});
+test('updaters fail loudly and leave a durable attempt trail', () => {
+ const daemon = read('daemon.js');
+ const mac = read('apply-update.sh');
+ const win = read('apply-update.ps1');
+ assert.match(daemon, /UPDATE_ATTEMPT_FILE/);
+ assert.match(daemon, /script-started/);
+ assert.match(daemon, /macWorkDaddyAppPath/);
+ assert.match(mac, /set -Eeuo pipefail/);
+ assert.match(mac, /rollback/);
+ assert.match(mac, /等待 daemon 端口恢复/);
+ assert.match(win, /\$ErrorActionPreference = 'Stop'/);
+ assert.match(win, /Rollback-App/);
+ assert.match(win, /新版 daemon 在 60 秒内未就绪/);
+});
+
test('account switching refreshes WorkBuddy after replacing auth without restarting it', () => {
const script = read('daemon.js');
const lib = read('lib.js');
@@ -191,3 +209,84 @@ test('zero credits omit the empty-state label', () => {
const script = read('inject.js');
assert.match(script, /if \(!list\.length\) return Number\(credits\) === 0 \? '' : '<div class="wbs-credit-empty">暂无可用积分<\/div>'/);
});
+
+test('auto-copy rules persist sessions and canonical workspace keys without leaking account metadata', () => {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'workdaddy-auto-copy-'));
+ try {
+ lib.setAutoCopyRule(dir, { uid: 'source-a', kind: 'session', key: 'session-1', enabled: true });
+ lib.setAutoCopyRule(dir, { uid: 'source-a', kind: 'workspace', key: '/Users/example/project/', enabled: true });
+ let rules = lib.getAutoCopyRules(dir, 'source-a');
+ assert.deepEqual(rules.sessionIds, ['session-1']);
+ assert.deepEqual(rules.workspaces, ['/Users/example/project']);
+ assert.equal(lib.canonicalWorkspace('/Users/example/project/'), '/Users/example/project');
+
+ const lineageId = lib.getAutoCopySession(dir, 'source-a', 'session-1').lineageId;
+ lib.setAutoCopyMapping(dir, lineageId, 'target-b', { targetId: 'copied-1', status: 'copied' });
+ assert.equal(lib.getAutoCopyMapping(dir, lineageId, 'target-b').targetId, 'copied-1');
+ lib.deleteAutoCopyMapping(dir, lineageId, 'target-b');
+ assert.equal(lib.getAutoCopyMapping(dir, lineageId, 'target-b'), null);
+
+ lib.setAutoCopyRule(dir, { uid: 'source-a', kind: 'session', key: 'session-1', enabled: false });
+ rules = lib.getAutoCopyRules(dir, 'source-a');
+ assert.deepEqual(rules.sessionIds, []);
+ const meta = JSON.parse(fs.readFileSync(path.join(dir, 'meta.json'), 'utf8'));
+ assert.ok(meta.autoCopy);
+ assert.equal(meta.accounts && Object.keys(meta.accounts).length, 0);
+ } finally {
+ fs.rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test('automatic session copy has a status endpoint, idempotency mapping, and no task-level marker', () => {
+ const daemon = read('daemon.js');
+ const inject = read('inject.js');
+ assert.match(daemon, /POST' && p === '\/api\/sessions\/auto-copy'/);
+ assert.match(daemon, /GET' && p === '\/api\/sessions\/auto-copy\/status'/);
+ assert.match(daemon, /getAutoCopyMapping\(DATA_DIR, lineageId, targetUid\)/);
+ assert.match(daemon, /startAutoCopyJob\(sourceUid, uid, autoCopyPlan\)/);
+ assert.match(inject, /data-auto-kind="' \+ kind \+ '"/);
+ assert.match(inject, /autoCopyButton\('workspace'/);
+ assert.match(inject, /autoCopyButton\('session'/);
+ assert.match(inject, /任务组本身没有自动复制按钮/);
+});
+
+test('session summary counts effective sessions and models tab only exposes sanitized model APIs', () => {
+ const daemon = read('daemon.js');
+ const inject = read('inject.js');
+ assert.match(inject, /function activeAutoCopyCount\(\)/);
+ assert.match(inject, /wbs-sess-summary-tag/);
+ assert.match(inject, /data-tab="models"/);
+ assert.match(inject, /data-model-tab="official"/);
+ assert.match(inject, /data-model-tab="mine"/);
+ assert.match(daemon, /GET' && p === '\/api\/models'/);
+ assert.match(daemon, /POST' && p === '\/api\/models\/backup'/);
+ assert.match(daemon, /POST' && p === '\/api\/models\/delete-official'/);
+ assert.match(daemon, /POST' && p === '\/api\/models\/test'/);
+ assert.match(daemon, /POST' && p === '\/api\/models\/copy'/);
+ assert.match(daemon, /POST' && p === '\/api\/models\/edit'/);
+ assert.match(daemon, /POST' && p === '\/api\/models\/delete'/);
+ assert.match(daemon, /POST' && p === '\/api\/models\/enable'/);
+ // 模型页 UI 明文展示 apiKey:列表走 sanitizeModel(model, { revealKey: true }),默认仍脱敏
+ assert.match(read('lib.js'), /function sanitizeModel\(model, opts\)/);
+ assert.match(read('lib.js'), /revealKey/);
+ assert.match(read('lib.js'), /function maskApiKey\(apiKey\)/);
+ assert.match(read('lib.js'), /function copyModelBackup\(dataDir, backupId\)/);
+ assert.match(read('lib.js'), /function editModelBackup\(dataDir, backupId, patch\)/);
+ assert.match(read('lib.js'), /modelBackupsDir\(dataDir\)/);
+ assert.match(inject, /data-model-copy=/);
+ assert.match(inject, /data-model-edit=/);
+ assert.match(inject, /wbs-model-check-all/);
+ assert.match(inject, /wbs-model-edit-eye/);
+ assert.match(inject, /小贴士.*解决 WorkBuddy 不支持多个同名模型的问题/);
+ assert.match(inject, /data-model-tab="official">当前模型/);
+ assert.match(inject, /data-model-tab="mine">备选模型/);
+ assert.doesNotMatch(inject, /id="wbs-model-refresh"/);
+ assert.match(inject, /wbs-model-group-title/);
+ assert.match(inject, /delete-official/);
+ assert.match(inject, /data-model-test=/);
+ assert.match(inject, /MODEL_BACKUP_SVG/);
+ assert.match(inject, /MODEL_COPY_SVG/);
+ assert.doesNotMatch(inject, /不修改时保持原 API Key/);
+ assert.match(inject, /height:650px/);
+ assert.doesNotMatch(inject, /模型备份保存在 WorkDaddy 本地目录/);
+});
diff --git "a/\345\256\211\350\243\205\345\244\261\350\264\245\350\207\252\344\270\273\350\247\243\345\206\263\346\217\220\347\244\272\350\257\215.txt" "b/\345\256\211\350\243\205\345\244\261\350\264\245\350\207\252\344\270\273\350\247\243\345\206\263\346\217\220\347\244\272\350\257\215.txt"
new file mode 100644
index 0000000..b9ade27
--- /dev/null
+++ "b/\345\256\211\350\243\205\345\244\261\350\264\245\350\207\252\344\270\273\350\247\243\345\206\263\346\217\220\347\244\272\350\257\215.txt"
@@ -0,0 +1,59 @@
+WorkDaddy Windows 安装失败自助修复
+==================================
+
+你是 WorkDaddy 的故障修复 agent。用户已经无法正常安装或启动 WorkDaddy,请在用户明确授权的范围内完成排查、修复和自动上报。
+
+一、准备源码
+
+1. 在一个新的临时目录执行:
+
+ git clone https://github.com/babygoton/WorkDaddy.git
+ cd WorkDaddy
+
+2. 先阅读 README.md、scripts/install-win.ps1、scripts/install-win.cmd、scripts/launcher.cmd、scripts/win-launcher.js、scripts/daemon.js,以及用户提供的 PowerShell/cmd 错误和 %APPDATA%\\WorkDaddy\\*.log。不要读取、复制、上传或修改以下内容:
+
+ - %APPDATA%\\WorkDaddy\\accounts\\
+ - WorkBuddy 登录文件、Cookie、数据库、环境变量、私有密钥
+
+二、复现问题
+
+1. 只在源码目录中操作。优先从源码根目录执行:
+
+ powershell -NoProfile -ExecutionPolicy Bypass -File .\\scripts\\install-win.ps1
+
+2. 如果需要验证启动流程,再执行:
+
+ .\\scripts\\launcher.cmd
+
+3. 记录实际失败命令、完整错误文本、Windows 版本、Node 版本和 WorkBuddy 版本。不要猜测根因。
+
+三、修复问题
+
+1. 只修改 GitHub 源码目录,不直接修改 %LOCALAPPDATA%\\Programs\\WorkDaddy 或用户数据目录。
+2. 保持现有 Windows 用户态安装方式和安全边界;不要删除账号数据,不要关闭现有脱敏逻辑。
+3. 修改后重新执行最小复现命令,并运行:
+
+ node --check scripts/sentry-report.js
+ node --check scripts/daemon.js
+ node --check scripts/win-launcher.js
+ node --test test/*.test.js
+
+四、生成修复报告
+
+在源码根目录创建 WORKDADDY_FIX_REPORT.md,必须包含:
+
+ - 原始问题和复现命令
+ - 确认的根因;如果没有确认,写“未确认”
+ - 修改的文件和每个修改的目的
+ - 测试命令和实际结果
+ - 用户安装时需要重新执行的命令
+
+五、自动上报
+
+只有在修复已经通过测试后,执行:
+
+ node scripts\\sentry-report.js --stage agent-fix --level info --message-file WORKDADDY_FIX_REPORT.md --tags-json '{"source":"workbuddy-agent","status":"fixed","platform":"windows"}'
+
+命令输出必须是 JSON。看到 sent=true 表示已发送;看到 queued=true 表示网络暂时不可用,报告已写入 WorkDaddy 的 telemetry/outbox,后续会自动重试。不要把 token、账号备份、数据库或完整日志放进 WORKDADDY_FIX_REPORT.md。
+
+如果测试仍未通过,不得伪造 fixed 状态;可以改用 status=unresolved 上报,并在报告中写清楚阻塞原因。