Jelajahi Sumber

发布 v0.4.71:修复断线恢复并提供 Windows 测试客户端

Samien 1 bulan lalu
induk
melakukan
98bc9b38c6
81 mengubah file dengan 2396 tambahan dan 257 penghapusan
  1. 49 0
      .github/workflows/windows-client.yml
  2. 6 6
      README.md
  3. 11 7
      desktop/auto-update-manager.mjs
  4. 1 1
      desktop/auto-update-manager.test.mjs
  5. 1 1
      desktop/boot.html
  6. 11 0
      desktop/boot.js
  7. 15 2
      desktop/credentials.mjs
  8. 33 15
      desktop/environment-host.mjs
  9. 13 10
      desktop/host-files.mjs
  10. 8 8
      desktop/host-files.test.mjs
  11. 6 2
      desktop/host-manager.mjs
  12. 3 3
      desktop/host-manager.test.mjs
  13. 34 20
      desktop/main.mjs
  14. 4 4
      desktop/mode-switch.test.mjs
  15. 5 1
      desktop/onboarding.mjs
  16. 31 0
      desktop/platform.mjs
  17. 36 0
      desktop/platform.test.mjs
  18. 1 1
      desktop/preferences.test.mjs
  19. 1 1
      desktop/remote-login.mjs
  20. 7 6
      desktop/update-manager.mjs
  21. 14 0
      desktop/update-manager.test.mjs
  22. 2 2
      desktop/update.html
  23. 1 1
      desktop/update.js
  24. 49 0
      desktop/windows-input.mjs
  25. 47 0
      desktop/windows-shell.mjs
  26. 112 0
      desktop/windows-smoke.test.mjs
  27. 135 0
      desktop/windows-upgrade.test.mjs
  28. 116 0
      desktop/windows.test.mjs
  29. 14 0
      desktop/windows/CMakeLists.txt
  30. 214 0
      desktop/windows/computer-helper.cpp
  31. 1 1
      docker.env.example
  32. 7 5
      docs/desktop-hosts.md
  33. 7 7
      docs/docker-install.md
  34. 4 0
      docs/release-process.md
  35. 47 0
      docs/releases/v0.4.71.md
  36. 60 0
      docs/verification/windows-client-2026-09-22/README.md
  37. 3 0
      docs/verification/windows-client-2026-09-22/evidence/SHA256SUMS-win-x64.txt
  38. TEMPAT SAMPAH
      docs/verification/windows-client-2026-09-22/evidence/remote-login.png
  39. 19 0
      docs/verification/windows-client-2026-09-22/evidence/smoke.json
  40. TEMPAT SAMPAH
      docs/verification/windows-client-2026-09-22/evidence/upgrade-ready.png
  41. TEMPAT SAMPAH
      docs/verification/windows-client-2026-09-22/evidence/upgrade-restored.png
  42. 14 0
      docs/verification/windows-client-2026-09-22/evidence/upgrade.json
  43. 57 0
      docs/windows-client.md
  44. 17 0
      electron-builder.yml
  45. 2 2
      package-lock.json
  46. 5 2
      package.json
  47. 3 3
      release.json
  48. 1 1
      scripts/build-desktop.mjs
  49. 43 0
      scripts/build-windows-desktop.mjs
  50. 18 0
      scripts/build-windows-icon.cjs
  51. 2 2
      scripts/bundle-desktop-updater.mjs
  52. 4 0
      scripts/test-windows-desktop.mjs
  53. 61 0
      scripts/windows-desktop-release.mjs
  54. 2 3
      src/client/api/chatTranscript.ts
  55. 5 3
      src/client/api/httpRealtime.ts
  56. 5 5
      src/client/components/app/DesktopHostSettingsPanel.vue
  57. 8 7
      src/client/components/app/DesktopModePanel.vue
  58. 1 1
      src/client/components/app/HostToolsPanel.vue
  59. 1 1
      src/client/components/app/RunnerSettingsPanel.vue
  60. 4 4
      src/client/components/workspace/LocalVmChatPanel.vue
  61. 1 1
      src/client/env.d.ts
  62. 47 34
      src/client/views/ConversationsView.vue
  63. 11 5
      src/server/chatTranscriptApi.ts
  64. 7 7
      src/server/desktopEnvironments.ts
  65. 72 17
      src/server/realtimeBroker.ts
  66. 43 6
      src/server/workspaceGateway.ts
  67. 111 32
      src/server/workspaceRuntime.ts
  68. 1 1
      src/server/workspaceScheduler.ts
  69. 19 5
      src/server/workspaceToolLease.ts
  70. 4 3
      src/shared/fileTransferEndpoint.mjs
  71. 22 0
      src/shared/hostPaths.mjs
  72. 99 0
      tests/client/conversationRecovery.test.ts
  73. 39 0
      tests/client/httpRealtimeRecovery.test.ts
  74. 34 0
      tests/client/ordinaryTranscriptV2.test.ts
  75. 22 1
      tests/server/desktopEnvironments.test.ts
  76. 72 0
      tests/server/ordinaryTranscriptReplay.test.ts
  77. 115 1
      tests/server/realtimeBroker.test.ts
  78. 3 3
      tests/server/workspace.test.ts
  79. 62 1
      tests/server/workspaceGateway.test.ts
  80. 189 0
      tests/server/workspaceReconnect.test.ts
  81. 42 2
      tests/server/workspaceTeamTools.test.ts

+ 49 - 0
.github/workflows/windows-client.yml

@@ -0,0 +1,49 @@
+name: Windows client
+on:
+  workflow_dispatch:
+  push:
+    branches: ['codex/windows-client*']
+  pull_request:
+    paths: ['desktop/**', 'scripts/**', 'src/**', 'tests/**', 'package*.json', 'electron-builder.yml', '.github/workflows/windows-client.yml']
+permissions:
+  contents: read
+jobs:
+  windows:
+    runs-on: windows-2022
+    timeout-minutes: 30
+    steps:
+      - uses: actions/checkout@v4
+        with:
+          fetch-depth: 0
+      - uses: actions/setup-node@v4
+        with:
+          node-version: '24'
+          cache: npm
+      - run: npm ci
+      - run: npm run typecheck
+      - run: npx vitest run tests/server/desktopEnvironments.test.ts tests/server/desktopHosts.test.ts
+      - run: npm run desktop:pack:win
+      - run: npm run desktop:test:win
+        env:
+          DESKTOP_TEST_EXECUTABLE: ${{ github.workspace }}\desktop-release\windows-x64\win-unpacked\Yaoyao.exe
+      - run: node --test desktop/windows-upgrade.test.mjs
+        env:
+          DESKTOP_TEST_UPGRADE: '1'
+      - uses: actions/upload-artifact@v4
+        with:
+          name: yaoyao-windows-x64-unsigned
+          path: |
+            desktop-release/windows-x64/*.exe
+            desktop-release/windows-x64/*.blockmap
+            desktop-release/windows-x64/latest.yml
+            desktop-release/windows-x64/SHA256SUMS-win-x64.txt
+            desktop-release/windows-x64/BUILD-INFO.json
+            desktop-release/windows-x64/README.txt
+            docs/windows-client.md
+          if-no-files-found: error
+      - uses: actions/upload-artifact@v4
+        if: always()
+        with:
+          name: windows-client-test-evidence
+          path: test-results/windows-client
+          if-no-files-found: ignore

+ 6 - 6
README.md

@@ -1,6 +1,6 @@
 # 夭夭 AI
 
-当前 Web 与 macOS 桌面发布版本:**v0.4.70**。桌面版提供 Apple Silicon(arm64)DMG,详见 [发布说明](docs/releases/v0.4.70.md)。
+当前 Web 与 macOS 桌面发布版本:**v0.4.71**。桌面版提供 Apple Silicon(arm64)正式 DMG,并附 Windows x64 未签名测试安装包,详见 [发布说明](docs/releases/v0.4.71.md)。
 
 夭夭 AI 为网页、iOS 和安卓提供统一的 Agent、群聊、文件库及语音配置服务。Hermes 通过标准 9119 HTTP/WebSocket 接口执行任务。
 
@@ -40,7 +40,7 @@ Web 数据默认保存在 `~/.yaoyao`,可用 `YAOYAO_HOME` 指定(兼容 `HE
 
 ## macOS 桌面版
 
-在 [v0.4.70 发布页](https://github.com/Lsamien/yaoyao/releases/tag/v0.4.70) 下载 `Yaoyao-0.4.70-arm64.dmg`,将“夭夭”拖到应用程序后打开。首次启动会核对并同步配套本机 Web 服务;普通退出保留后台运行,“停止后台服务并退出”可完整停止本应用管理的后台。详细说明见 [macOS App](docs/macos-app.md)。
+在 [v0.4.71 发布页](https://github.com/Lsamien/yaoyao/releases/tag/v0.4.71) 下载 `Yaoyao-0.4.71-arm64.dmg`,将“夭夭”拖到应用程序后打开。首次启动会核对并同步配套本机 Web 服务;普通退出保留后台运行,“停止后台服务并退出”可完整停止本应用管理的后台。详细说明见 [macOS App](docs/macos-app.md)。
 
 桌面安装包的签名、公证状态及自动升级可用范围见对应版本的 GitHub 发布说明。
 
@@ -50,11 +50,11 @@ Web 数据默认保存在 `~/.yaoyao`,可用 `YAOYAO_HOME` 指定(兼容 `HE
 
 | 镜像 | 架构 |
 | --- | --- |
-| `samienluo/yaoyao:v0.4.70-amd` | AMD64 |
-| `samienluo/yaoyao:v0.4.70` | 自动匹配 AMD64 / ARM64 |
-| `samienluo/yaoyao:latest` | 最新稳定版通用镜像,当前与 `v0.4.70` 相同 |
+| `samienluo/yaoyao:v0.4.71-amd` | AMD64 |
+| `samienluo/yaoyao:v0.4.71` | 自动匹配 AMD64 / ARM64 |
+| `samienluo/yaoyao:latest` | 最新稳定版通用镜像,当前与 `v0.4.71` 相同 |
 
-准备好 Docker Engine/Compose 和容器可访问的 Hermes 9119 服务,在仓库目录将 `docker.env.example` 复制为 `docker.env`。配置上游地址,并设置 `HERMES_YAOYAO_IMAGE=samienluo/yaoyao:v0.4.70`(或 `samienluo/yaoyao:latest`),即可使用远程镜像:
+准备好 Docker Engine/Compose 和容器可访问的 Hermes 9119 服务,在仓库目录将 `docker.env.example` 复制为 `docker.env`。配置上游地址,并设置 `HERMES_YAOYAO_IMAGE=samienluo/yaoyao:v0.4.71`(或 `samienluo/yaoyao:latest`),即可使用远程镜像:
 
 ```sh
 docker compose --env-file docker.env pull web

+ 11 - 7
desktop/auto-update-manager.mjs

@@ -18,12 +18,13 @@ function errorMessage(error) {
  * The patched MacUpdater resolves downloadUpdate only after native staging.
  * Native staging cannot be canceled or retried safely in the same process. */
 export class DesktopAutoUpdateManager {
-  constructor({ driver, version, arch = process.arch, prepareInstall = async () => {}, recoverInstall = async () => {}, stagingTimeout = 300000, restartTimeout = 120000 }) {
-    Object.assign(this, { driver, prepareInstall, recoverInstall, stagingTimeout, restartTimeout })
+  constructor({ driver, version, arch = process.arch, platform = process.platform, prepareInstall = async () => {}, recoverInstall = async () => {}, stagingTimeout = 300000, restartTimeout = 120000 }) {
+    Object.assign(this, { driver, platform, prepareInstall, recoverInstall, stagingTimeout, restartTimeout })
     this.state = { phase: 'idle', installMode: 'restart', currentVersion: version, arch, available: false,
       received: 0, total: 0, message: '点击检查 App 更新', releasePageUrl, retryable: true }
     driver.autoDownload = false
-    driver.autoInstallOnAppQuit = true
+    // NSIS installation must follow our explicit connection/process cleanup.
+    driver.autoInstallOnAppQuit = platform !== 'win32'
     driver.autoRunAppAfterInstall = true
     driver.allowPrerelease = false
     driver.allowDowngrade = false
@@ -37,9 +38,11 @@ export class DesktopAutoUpdateManager {
     driver.on('update-downloaded', () => {
       if (this.operation !== 'downloading' || this.recoveryRequired || this.cancelled) return
       this.nativeStarted = true
-      this.set({ phase: 'preparing', message: '下载完成,正在验证签名并准备安装…' })
-      this.stagingTimer = setTimeout(() => this.failure(new Error('准备更新超时')), this.stagingTimeout)
-      this.stagingTimer.unref?.()
+      this.set({ phase: 'preparing', message: platform === 'win32' ? '下载完成,正在核对安装包…' : '下载完成,正在验证签名并准备安装…' })
+      if (platform !== 'win32') {
+        this.stagingTimer = setTimeout(() => this.failure(new Error('准备更新超时')), this.stagingTimeout)
+        this.stagingTimer.unref?.()
+      }
     })
   }
   set(patch) { this.state = { ...this.state, ...patch } }
@@ -109,7 +112,8 @@ export class DesktopAutoUpdateManager {
     if (this.recoveryRequired || this.cancelled) return
     this.failed = true
     clearTimeout(this.stagingTimer); clearTimeout(this.restartTimer)
-    this.recoveryRequired = Boolean(this.nativeStarted)
+    this.recoveryRequired = Boolean(this.nativeStarted && (this.platform !== 'win32' || this.installAttempted))
+    if (this.platform === 'win32' && !this.recoveryRequired) this.nativeStarted = false
     const suffix = this.recoveryRequired ? ' 请退出并重新打开 App 后再尝试。' : ''
     const silent = this.manual === false && !this.nativeStarted
     this.set({ phase: silent ? 'idle' : 'failed',

+ 1 - 1
desktop/auto-update-manager.test.mjs

@@ -9,7 +9,7 @@ function fixture(t, options = {}) {
   driver.checkForUpdates = async () => ({ isUpdateAvailable: true, updateInfo: { version: '0.4.63', releaseNotes: '<b>纯文本说明</b>' }, cancellationToken: { cancel() { calls.push('cancel') } } })
   driver.downloadUpdate = async () => { driver.emit('update-downloaded'); return ['update.zip'] }
   driver.quitAndInstall = () => calls.push('install')
-  const manager = new DesktopAutoUpdateManager({ driver, version: '0.4.62', ...options })
+  const manager = new DesktopAutoUpdateManager({ driver, platform: 'darwin', version: '0.4.62', ...options })
   t.after(() => { manager.stopChecking(); clearTimeout(manager.stagingTimer); clearTimeout(manager.restartTimer) })
   return { manager, driver, calls }
 }

+ 1 - 1
desktop/boot.html

@@ -18,7 +18,7 @@
     <li id="step-prepare"><span class="step-dot"><b>2</b><svg><use href="boot-icons.svg#check"/></svg></span>准备服务</li>
     <li id="step-account"><span class="step-dot"><b>3</b><svg><use href="boot-icons.svg#check"/></svg></span><span id="account-step-title">登录账号</span></li>
   </ol>
-  <section class="section choice-section" aria-labelledby="choice-title">
+  <section id="choice-section" class="section choice-section" aria-labelledby="choice-title">
     <h2 id="choice-title"><span>01</span>选择服务器</h2>
     <fieldset id="mode-options" class="mode-options"><legend class="sr-only">服务器运行方式</legend>
       <label class="mode-option"><input type="radio" name="mode" value="local"><svg class="mode-icon"><use href="boot-icons.svg#monitor"/></svg><span><strong>本机运行</strong><small>在这台电脑准备并运行服务</small></span></label>

+ 11 - 0
desktop/boot.js

@@ -16,6 +16,17 @@ function display(next) {
     initialized = true
   }
   const busy = pending || state.busy
+  const clientOnly = state.supportedModes && !state.supportedModes.includes('server')
+  $('choice-section').hidden = Boolean(clientOnly)
+  $('step-choice').hidden = Boolean(clientOnly)
+  if (clientOnly) {
+    $('prepare-title').firstElementChild.textContent = '01'
+    $('account-title').firstElementChild.textContent = '02'
+    $('step-prepare').querySelector('b').textContent = '1'
+    $('step-account').querySelector('b').textContent = '2'
+    $('help').firstElementChild.hidden = true
+    $('help').lastElementChild.textContent = '更换服务器不会迁移原服务器上的数据。连接失败时请检查服务器地址和网络。'
+  }
   const local = state.mode === 'local'
   const ready = ['ready', 'authenticating', 'entering'].includes(state.phase) && !serverDirty
   const setup = ready && state.setupRequired

+ 15 - 2
desktop/credentials.mjs

@@ -4,8 +4,9 @@ import {readFileSync} from 'node:fs'
 import {join} from 'node:path'
 import {homedir} from 'node:os'
 const prefix=Buffer.from('YAOYAO-RUNNER-KEYCHAIN-1\n')
+const windowsPrefix=Buffer.from('YAOYAO-WINDOWS-DPAPI-1\n')
 export class DesktopCredentials {
-  constructor({home,helper,legacyDecrypt}){this.home=home;this.helper=helper;this.legacyDecrypt=legacyDecrypt}
+  constructor({home,helper,legacyDecrypt,platform=process.platform,safeStorage}){Object.assign(this,{home,helper,legacyDecrypt,platform,safeStorage})}
   get account(){
     let identity=this.home
     try {
@@ -25,8 +26,20 @@ export class DesktopCredentials {
       child.stdin.on('error',()=>{});child.stdin.end(input)
     })
   }
-  async encrypt(value){return Buffer.concat([prefix,await this.invoke('encrypt',Buffer.from(value))])}
+  async encrypt(value){
+    if(this.platform==='win32'){
+      if(Buffer.byteLength(value)>1048576)throw new Error('电脑配置超过加密大小上限')
+      if(!await this.safeStorage?.isAsyncEncryptionAvailable())throw new Error('系统加密暂不可用,请稍后重试')
+      return Buffer.concat([windowsPrefix,await this.safeStorage.encryptStringAsync(value)])
+    }
+    return Buffer.concat([prefix,await this.invoke('encrypt',Buffer.from(value))])
+  }
   async decrypt(value){
+    if(this.platform==='win32'){
+      if(!value.subarray(0,windowsPrefix.length).equals(windowsPrefix))throw new Error('此电脑配置不属于 Windows,请重新登录授权')
+      try{return (await this.safeStorage.decryptStringAsync(value.subarray(windowsPrefix.length))).result}
+      catch{throw new Error('无法解锁电脑配置,请使用原 Windows 账号或重新登录授权')}
+    }
     if(value.subarray(0,prefix.length).equals(prefix))return (await this.invoke('decrypt',value.subarray(prefix.length))).toString('utf8')
     // Existing safeStorage files remain readable after the user grants normal OS access.
     let timer

+ 33 - 15
desktop/environment-host.mjs

@@ -1,5 +1,5 @@
-import {app,desktopCapturer,dialog,screen,shell,systemPreferences} from 'electron'
-import {hostname} from 'node:os'
+import {app,desktopCapturer,dialog,screen,shell,systemPreferences,powerMonitor} from 'electron'
+import {hostname,homedir} from 'node:os'
 import {readFileSync,writeFileSync,mkdirSync} from 'node:fs'
 import {join} from 'node:path'
 import {randomUUID} from 'node:crypto'
@@ -9,38 +9,53 @@ import {listHostFiles,readHostFile,writeHostFile,receiveHostFile,execHostShell}
 import {exchangeDesktopEnvironment as exchange} from './environment-exchange.mjs'
 import {HostEnvironmentReporter} from './host-environment.mjs'
 import {FileTransferFiles} from './file-transfer.mjs'
+import {desktopPlatform} from './platform.mjs'
+import {WindowsInput,windowsFrame,sameWindowsDisplay} from './windows-input.mjs'
 
 /** Command execution shared by the loopback server and remote computers. */
 export class DesktopHostCore {
- constructor({root,dataRoot}){this.root=root;this.dataRoot=dataRoot;this.home=process.env.HOME||'/';this.environmentReporter=new HostEnvironmentReporter(this.home);this.id=randomUUID();this.results=[];this.running=new Set();this.closed=false;this.browser=new BrowserEnvironment(join(dataRoot,'bot-browsers'));this.approved=new Set();this.approvedFull=new Set();this.permissionsFile=join(dataRoot,'computer-permissions.json');try{const stored=JSON.parse(readFileSync(this.permissionsFile,'utf8'));const screen=Array.isArray(stored)?stored:stored.screen;const full=Array.isArray(stored)?[]:stored.full;if(Array.isArray(screen))for(const key of screen)if(/^[a-f0-9]{64}$/.test(key))this.approved.add(key);if(Array.isArray(full))for(const key of full)if(/^[a-f0-9]{64}$/.test(key))this.approvedFull.add(key)}catch{}this.frames=new Map()}
+ constructor({root,dataRoot}){this.root=root;this.dataRoot=dataRoot;this.home=homedir();this.environmentReporter=new HostEnvironmentReporter(this.home);this.id=randomUUID();this.results=[];this.running=new Set();this.closed=false;this.browser=new BrowserEnvironment(join(dataRoot,'bot-browsers'));this.approved=new Set();this.approvedFull=new Set();this.permissionsFile=join(dataRoot,'computer-permissions.json');try{const stored=JSON.parse(readFileSync(this.permissionsFile,'utf8'));const screen=Array.isArray(stored)?stored:stored.screen;const full=Array.isArray(stored)?[]:stored.full;if(Array.isArray(screen))for(const key of screen)if(/^[a-f0-9]{64}$/.test(key))this.approved.add(key);if(Array.isArray(full))for(const key of full)if(/^[a-f0-9]{64}$/.test(key))this.approvedFull.add(key)}catch{}this.frames=new Map();this.shells=new Set();this.platform=desktopPlatform();this.native=this.platform.windows?new WindowsInput(root,app.isPackaged):undefined;this.windowsScreen=false;this.locked=false;this.lastProbe=0;this.onLock=()=>{this.locked=true;this.windowsScreen=false;this.native?.cancel();this.frames.clear()};this.onUnlock=()=>{this.locked=false;this.lastProbe=0};this.onDisplayChanged=()=>{this.frames.clear();this.lastProbe=0};if(this.platform.windows){powerMonitor.on('lock-screen',this.onLock);powerMonitor.on('unlock-screen',this.onUnlock);for(const event of ['display-added','display-removed','display-metrics-changed'])screen.on(event,this.onDisplayChanged)}}
  transfers=new Map()
- info(){return {id:this.id,name:hostname(),platform:process.platform,screen:process.platform==='darwin'&&systemPreferences.getMediaAccessStatus('screen')==='granted',accessibility:process.platform==='darwin'&&systemPreferences.isTrustedAccessibilityClient(false),approved:[...this.approved],full:[...this.approvedFull],...this.environmentReporter.fields()}}
+ info(){return {id:this.id,name:hostname(),platform:process.platform,screen:this.platform.windows?this.windowsScreen:process.platform==='darwin'&&systemPreferences.getMediaAccessStatus('screen')==='granted',accessibility:this.platform.windows?this.native.available:process.platform==='darwin'&&systemPreferences.isTrustedAccessibilityClient(false),approved:[...this.approved],full:[...this.approvedFull],...this.environmentReporter.fields()}}
+ async prepareInfo(force=false){
+  if(!this.native||this.closed||this.locked||!this.approved.size)return
+  if(!force&&Date.now()-this.lastProbe<2000)return
+  this.lastProbe=Date.now();const epoch=this.id
+  const available=await this.native.probe()
+  try{const d=screen.getPrimaryDisplay();const sources=available?await desktopCapturer.getSources({types:['screen'],thumbnailSize:{width:1,height:1}}):[]
+   if(epoch!==this.id||this.closed||this.locked){this.native.cancel();return}
+   this.windowsScreen=sources.some(s=>s.display_id===String(d.id)&&!s.thumbnail.isEmpty())
+  }catch{this.windowsScreen=false}
+  if(!this.windowsScreen||!this.native.available)this.frames.clear()
+ }
+ async cancelOperations(){this.windowsScreen=false;this.lastProbe=0;for(const task of this.shells)task.controller.abort();await Promise.allSettled([this.native?.cancel(),...[...this.shells].map(task=>task.promise)])}
  acceptCapabilities(capabilities){this.environmentReporter.accept(capabilities)}
  async clearTransfers(){const transfers=[...this.transfers.values()];this.transfers.clear();await Promise.allSettled(transfers.map(transfer=>transfer.close()))}
- async revoke(){this.approved.clear();this.approvedFull.clear();this.save();this.frames.clear();this.id=randomUUID();await this.clearTransfers()}
- async recycle(){this.environmentReporter.reset();this.results=[];this.id=randomUUID();await this.clearTransfers();await this.browser.close()}
+ async revoke(){this.approved.clear();this.approvedFull.clear();this.save();this.frames.clear();this.id=randomUUID();await this.cancelOperations();await this.clearTransfers()}
+ async recycle(){this.environmentReporter.reset();this.results=[];this.id=randomUUID();await this.cancelOperations();await this.clearTransfers();await this.browser.close()}
  save(){mkdirSync(this.dataRoot,{recursive:true,mode:0o700});writeFileSync(this.permissionsFile,JSON.stringify({screen:[...this.approved],full:[...this.approvedFull]}),{mode:0o600})}
  takeResults(){const sent=this.results.slice();this.results.splice(0,sent.length);return sent}
  async handle(commands){for(const c of commands??[]){if(this.running.has(c.id))continue;this.running.add(c.id);const epoch=this.id;void this.execute(c).then(value=>{if(epoch===this.id)this.results.push({id:c.id,value})},error=>{if(epoch===this.id)this.results.push({id:c.id,error:String(error.message).slice(0,500)})}).finally(()=>this.running.delete(c.id))}}
  async execute(c){const epoch=this.id;if(Date.now()>c.deadline||this.closed)throw new Error('桌面请求已过期');if(!/^[a-f0-9]{64}$/.test(c.owner))throw new Error('桌面请求身份无效')
   if(c.operation==='authorize'){
-   if(process.platform!=='darwin')throw new Error('此电脑暂不支持本机控制')
+   if(!this.platform.computer)throw new Error('此电脑暂不支持本机控制')
    const full=c.scope==='full'
    const {response}=await dialog.showMessageBox({type:'question',title:full?'授权文件与命令':'授权本机控制',
-    message:`允许夭夭账号「${String(c.account??'当前账号').slice(0,100)}」的机器人${full?'使用这台 Mac 的文件并执行命令':'查看和操作这台 Mac'}?`,
-    detail:full?'机器人可以列出、读取和写入你用户主目录内的文件,并在这台 Mac 上执行 shell 命令。仅对信任的机器人开启;可随时在夭夭菜单中撤销。':'授权后,机器人和该账号的 Web、手机端可以查看屏幕,并在接管时操作鼠标和键盘。你可以在夭夭菜单中撤销。',
+    message:`允许夭夭账号「${String(c.account??'当前账号').slice(0,100)}」的机器人${full?'使用这台电脑的文件并执行命令':'查看和操作这台电脑'}?`,
+    detail:full?'机器人可以列出、读取和写入你用户主目录内的文件,并在这台电脑上执行 shell 命令。仅对信任的机器人开启;可随时在夭夭菜单中撤销。':'授权后,机器人和该账号的 Web、手机端可以查看屏幕,并在接管时操作鼠标和键盘。你可以在夭夭菜单中撤销。',
     buttons:full?['取消','允许文件与命令']:['取消','允许并检查系统权限'],defaultId:0,cancelId:0})
    if(response!==1||Date.now()>c.deadline||this.closed||epoch!==this.id)throw new Error(full?'文件与命令授权已取消':'本机控制授权已取消')
    if(full)this.approvedFull.add(c.owner);else this.approved.add(c.owner);this.save()
    if(full)return {ok:true}
+   if(this.native){await this.prepareInfo(true);return {ok:true}}
    if(!systemPreferences.isTrustedAccessibilityClient(false))systemPreferences.isTrustedAccessibilityClient(true)
    if(systemPreferences.getMediaAccessStatus('screen')!=='granted'){await desktopCapturer.getSources({types:['screen'],thumbnailSize:{width:1,height:1}}).catch(()=>{});if(systemPreferences.getMediaAccessStatus('screen')!=='granted')await shell.openExternal('x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture')}
    return {ok:true}
   }
   if(c.operation==='file'||c.operation==='shell'){
-   if(process.platform!=='darwin')throw new Error('此电脑暂不支持文件与命令')
+   if(!this.platform.computer)throw new Error('此电脑暂不支持文件与命令')
    if(!this.approvedFull.has(c.owner))throw new Error('请在桌面端授权文件与命令访问')
-   if(c.operation==='shell')return execHostShell(this.home,c.action)
+   if(c.operation==='shell'){const controller=new AbortController();const task={controller,promise:execHostShell(this.home,c.action,{signal:controller.signal,helper:this.native?.helper})};this.shells.add(task);try{return await task.promise}finally{this.shells.delete(task)}}
    const action=c.action??{}
    if(typeof action.op==='string'&&action.op.startsWith('transfer-')){
     const key=c.owner+':'+c.resource
@@ -63,20 +78,23 @@ export class DesktopHostCore {
    if(c.operation==='view')return this.browser.view(c.resource)
    return this.browser.input(c.resource,c.action,c.frame)
   }
-  const info=this.info();if(!info.approved.includes(c.owner)||!info.screen||!info.accessibility)throw new Error('请在桌面端授权,并在系统设置开启屏幕录制和辅助功能')
+  await this.prepareInfo(true)
+  if(this.closed||epoch!==this.id||Date.now()>c.deadline)throw new Error('电脑授权已改变,请重新操作')
+  const info=this.info();if(!info.approved.includes(c.owner)||!info.screen||!info.accessibility)throw new Error(this.platform.windows?'请授权本机控制,并在 Windows 上解锁电脑、恢复桌面会话':'请在桌面端授权,并在系统设置开启屏幕录制和辅助功能')
   if(c.operation==='open')return {ok:true}
-  if(c.operation==='view'){const d=screen.getPrimaryDisplay(),sources=await desktopCapturer.getSources({types:['screen'],thumbnailSize:{width:1600,height:1200}}),source=sources.find(s=>s.display_id===String(d.id));if(!source||source.thumbnail.isEmpty())throw new Error('系统尚未允许读取屏幕');const dimensions=source.thumbnail.getSize();this.frames.set(c.resource,{display:d.id,...dimensions,bounds:d.bounds});return {data:source.thumbnail.toPNG().toString('base64'),...dimensions}}
+  if(c.operation==='view'){const d=screen.getPrimaryDisplay(),sources=await desktopCapturer.getSources({types:['screen'],thumbnailSize:{width:1600,height:1200}}),source=sources.find(s=>s.display_id===String(d.id));if(!source||source.thumbnail.isEmpty())throw new Error('系统尚未允许读取屏幕');if(this.closed||epoch!==this.id||this.locked||Date.now()>c.deadline)throw new Error('电脑授权或会话已改变');const dimensions=source.thumbnail.getSize();this.frames.set(c.resource,this.native?windowsFrame(d,dimensions,screen.dipToScreenRect(null,d.bounds)):{display:d.id,...dimensions,bounds:d.bounds});return {data:source.thumbnail.toPNG().toString('base64'),...dimensions}}
   if(c.operation!=='input')throw new Error('本机操作无效')
   const f=this.frames.get(c.resource),d=screen.getPrimaryDisplay();if(!f||f.display!==d.id||JSON.stringify(f.bounds)!==JSON.stringify(d.bounds)||f.width!==c.frame?.width||f.height!==c.frame?.height)throw new Error('显示器已变化,请刷新画面')
+  if(this.native){if(!sameWindowsDisplay(f,d,screen.dipToScreenRect(null,d.bounds)))throw new Error('显示器已变化,请刷新画面');return this.native.call({action:c.action,frame:f})}
   return new Promise((resolve,reject)=>{const child=execFile(join(this.root,app.isPackaged?'computer-helper':'computer-helper-dev'),[],{timeout:10000,maxBuffer:65536},(error,stdout,stderr)=>{if(error)reject(new Error(stderr.trim()||'系统未接受电脑输入'));else{try{resolve(JSON.parse(stdout))}catch{reject(new Error('电脑助手响应无效'))}}});child.stdin.end(JSON.stringify({action:c.action,frame:f}))})
  }
- async close(){this.closed=true;await this.recycle()}
+ async close(){this.closed=true;powerMonitor.removeListener('lock-screen',this.onLock);powerMonitor.removeListener('unlock-screen',this.onUnlock);for(const event of ['display-added','display-removed','display-metrics-changed'])screen.removeListener(event,this.onDisplayChanged);await this.recycle()}
 }
 
 export class DesktopEnvironmentHost {
  constructor({manager,root,dataRoot}){this.manager=manager;this.core=new DesktopHostCore({root,dataRoot});this.closed=false;this.timer=undefined;this.instance=undefined}
  revoke(){return this.core.revoke()}
- async cycle(){if(this.closed)return;try{const record=await this.manager.readRecord();if(record){const verified=await this.manager.verify(record);record.url=verified.url;if(this.instance&&this.instance!==record.instanceId)await this.core.recycle();this.instance=record.instanceId;const value=await exchange(record,{host:this.core.info(),results:this.core.takeResults()});this.core.acceptCapabilities(value.capabilities);await this.core.handle(value.commands??[])}}catch{this.core.acceptCapabilities(undefined)}finally{if(!this.closed)this.timer=setTimeout(()=>void this.cycle(),400)}}
+ async cycle(){if(this.closed)return;try{const record=await this.manager.readRecord();if(record){const verified=await this.manager.verify(record);record.url=verified.url;if(this.instance&&this.instance!==record.instanceId)await this.core.recycle();this.instance=record.instanceId;await this.core.prepareInfo();const value=await exchange(record,{host:this.core.info(),results:this.core.takeResults()});this.core.acceptCapabilities(value.capabilities);await this.core.handle(value.commands??[])}}catch{this.core.acceptCapabilities(undefined)}finally{if(!this.closed)this.timer=setTimeout(()=>void this.cycle(),400)}}
  start(){this.closed=false;this.core.closed=false;void this.cycle()}
  async close(){this.closed=true;clearTimeout(this.timer);await this.core.close()}
 }

+ 13 - 10
desktop/host-files.mjs

@@ -1,10 +1,12 @@
 import {readdir,readFile,writeFile,mkdir,stat,realpath,open,link,rename,unlink} from 'node:fs/promises'
 import {createHash,randomUUID} from 'node:crypto'
-import {join,resolve,sep} from 'node:path'
+import {join,resolve} from 'node:path'
 import {homedir} from 'node:os'
 import {execFile} from 'node:child_process'
+import {hostPathInput,pathInside} from '../src/shared/hostPaths.mjs'
+import {windowsShell} from './windows-shell.mjs'
 
-export const HOST_SHELL='/bin/zsh'
+export const HOST_SHELL=process.platform==='win32'?join(process.env.SystemRoot||'C:\\Windows','System32','WindowsPowerShell','v1.0','powershell.exe'):'/bin/zsh'
 export const FILE_READ_LIMIT=12*1024*1024
 export const FILE_WRITE_LIMIT=10*1024*1024
 export const FILE_LIST_LIMIT=500
@@ -15,9 +17,9 @@ export const SHELL_TIMEOUT_MAX=120000
  *  through .., absolute outsiders and symlinks pointing out of the root. */
 export async function resolveWithin(root,input,kind='target'){
   const base=await realpath(root)
-  const raw=String(input??'').replace(/^~\//,'').replace(/^~$/,'')
-  if(/\u0000/.test(raw))throw new Error('路径无效')
+  const raw=hostPathInput(input)
   const target=resolve(base,raw)
+  if(!pathInside(base,target))throw new Error('路径超出允许范围')
   let real=target
   try{real=await realpath(target)}catch(error){
     if(kind==='existing')throw new Error('文件或目录不存在')
@@ -26,10 +28,10 @@ export async function resolveWithin(root,input,kind='target'){
       for(;;){
         try{
           const parent=await realpath(directory)
-          if(parent!==base&&!parent.startsWith(base+sep))throw new Error('路径超出允许范围')
+          if(!pathInside(base,parent))throw new Error('路径超出允许范围')
           break
         }catch(failure){
-          if(failure.message==='路径超出允许范围')throw failure
+          if(failure.code!=='ENOENT')throw failure
           const next=join(directory,'..')
           if(directory===next)throw error
           directory=next
@@ -38,7 +40,7 @@ export async function resolveWithin(root,input,kind='target'){
       return {base,target}
     }
   }
-  if(real!==base&&!real.startsWith(base+sep))throw new Error('路径超出允许范围')
+  if(!pathInside(base,real))throw new Error('路径超出允许范围')
   return {base,target}
 }
 
@@ -101,14 +103,15 @@ export async function receiveHostFile(root,input){
   }finally{await handle.close();await unlink(temporary).catch(error=>{if(error.code!=='ENOENT')throw error})}
 }
 
-export async function execHostShell(root,input){
+export async function execHostShell(root,input,{signal,helper}={}){
   const command=String(input?.command??'')
   if(!command.trim())throw new Error('命令为空')
   const timeout=Math.min(Math.max(Number(input?.timeoutMs)||60000,1000),SHELL_TIMEOUT_MAX)
   let cwd
-  try{cwd=resolve(String(root),String(input?.cwd??'').replace(/^~\//,'').replace(/^~$/,''))}catch{cwd=String(root)}
+  try{cwd=resolve(String(root),String(input?.cwd??'').replace(process.platform==='win32'?/^~[\\/]/:/^~\//,'').replace(/^~$/,''))}catch{cwd=String(root)}
+  if(process.platform==='win32')return windowsShell(HOST_SHELL,command,{cwd,timeout,signal,helper,limit:SHELL_OUTPUT_LIMIT})
   return new Promise(done=>{
-    execFile(HOST_SHELL,['-c',command],{cwd,timeout,killSignal:'SIGKILL',maxBuffer:1024*1024,env:{...process.env,TERM:'dumb'}},(error,stdout,stderr)=>{
+    execFile(HOST_SHELL,['-c',command],{cwd,timeout,signal,killSignal:'SIGKILL',maxBuffer:1024*1024,env:{...process.env,TERM:'dumb'}},(error,stdout,stderr)=>{
       const clip=value=>Buffer.from(value??'','utf8').subarray(0,SHELL_OUTPUT_LIMIT).toString('utf8')
       done({command,exitCode:error?typeof error.code==='number'?error.code:1:0,timedOut:error?.killed===true&&error?.signal==='SIGKILL',stdout:clip(stdout),stderr:clip(stderr)})
     })

+ 8 - 8
desktop/host-files.test.mjs

@@ -1,6 +1,6 @@
 import {test} from 'node:test'
 import assert from 'node:assert/strict'
-import {mkdtemp,mkdir,writeFile,readFile,readdir,symlink,rm} from 'node:fs/promises'
+import {mkdtemp,mkdir,writeFile,readFile,readdir,symlink,rm,realpath} from 'node:fs/promises'
 import {createHash} from 'node:crypto'
 import {tmpdir} from 'node:os'
 import {join} from 'node:path'
@@ -30,7 +30,7 @@ test('path escapes are refused for every operation',async()=>{
  const outside=await mkdtemp(join(tmpdir(),'yaoyao-host-files-out-'))
  try{
   await writeFile(join(outside,'secret.txt'),'secret','utf8')
-  await symlink(outside,join(root,'escape'))
+  await symlink(outside,join(root,'escape'),process.platform==='win32'?'junction':'dir')
   await writeFile(join(root,'keep.txt'),'keep','utf8')
   await assert.rejects(()=>resolveWithin(root,'../x'),/超出允许范围/)
   await assert.rejects(()=>resolveWithin(root,'/etc/passwd'),/超出允许范围/)
@@ -64,7 +64,7 @@ test('receives verified binary and empty files atomically and preserves existing
   const empty={...input,path:'Desktop/empty',data:'',sha256:createHash('sha256').update('').digest('hex')}
   assert.equal((await receiveHostFile(target,empty)).size,0)
   assert.equal((await readFile(join(target,'Desktop','empty'))).length,0)
-  await symlink(source,join(target,'escape'))
+  await symlink(source,join(target,'escape'),process.platform==='win32'?'junction':'dir')
   await assert.rejects(()=>receiveHostFile(target,{...input,path:'escape/evil.bin'}),/超出允许范围/)
   assert.deepEqual((await readdir(join(target,'Desktop'))).sort(),['a.bin','empty'])
  }finally{await rm(source,{recursive:true,force:true});await rm(target,{recursive:true,force:true})}
@@ -74,14 +74,14 @@ test('shell execution reports stdout, exit codes, timeouts and cwd stays in root
  const root=await mkdtemp(join(tmpdir(),'yaoyao-host-files-'))
  try{
   await mkdir(join(root,'work'))
-  const ok=await execHostShell(root,{command:'pwd',cwd:'work'})
+  const ok=await execHostShell(root,{command:process.platform==='win32'?'(Get-Location).Path':'pwd',cwd:'work'})
   assert.equal(ok.exitCode,0)
-  assert.ok(ok.stdout.includes(`${root}/work`),ok.stdout)
-  const failing=await execHostShell(root,{command:'echo boom >&2; exit 7'})
+  assert.equal((await realpath(ok.stdout.trim())).toLowerCase(),(await realpath(join(root,'work'))).toLowerCase())
+  const failing=await execHostShell(root,{command:process.platform==='win32'?"[Console]::Error.WriteLine('boom'); exit 7":'echo boom >&2; exit 7'})
   assert.equal(failing.exitCode,7);assert.equal(failing.stderr.trim(),'boom')
-  const timed=await execHostShell(root,{command:'sleep 5',timeoutMs:1000})
+  const timed=await execHostShell(root,{command:process.platform==='win32'?'Start-Sleep -Seconds 5':'sleep 5',timeoutMs:1000})
   assert.equal(timed.timedOut,true);assert.notEqual(timed.exitCode,0)
-  const escaped=await execHostShell(root,{command:'cd / && pwd'})
+  const escaped=await execHostShell(root,{command:process.platform==='win32'?'Set-Location $env:SystemRoot; (Get-Location).Path':'cd / && pwd'})
   assert.equal(escaped.exitCode,0)
   await assert.rejects(()=>execHostShell(root,{command:'  '}),/命令为空/)
  }finally{await rm(root,{recursive:true,force:true})}

+ 6 - 2
desktop/host-manager.mjs

@@ -67,7 +67,7 @@ export class DesktopHostManager {
   let encrypted
   try{encrypted=await readFile(this.path)}catch(error){if(error.code==='ENOENT')return;throw error}
   try{return parseDesktopHostConfiguration(JSON.parse(await this.options.decrypt(encrypted)))}
-  catch{throw new Error('无法解锁电脑配置,请检查钥匙串或重新导入')}
+  catch{throw new Error('无法解锁电脑配置,请使用原系统账号或重新登录授权')}
  }
  importFile(path){
   const generation=++this.generation
@@ -114,10 +114,14 @@ export class DesktopHostManager {
   const config=this.config,core=this.core
   if(!config||!core||this.core!==core)return
   try{
+   await core.prepareInfo?.()
+   if(this.config!==config||this.core!==core)return
    const value=await remoteExchange(config,{host:core.info(),results:core.takeResults()})
    this.backoff=400
    if(this.config!==config||this.core!==core)return
-   this.publish(`电脑已连接 ${new URL(config.serverURL).host}`)
+   this.publish(process.platform==='win32'&&!(Array.isArray(value.capabilities?.desktopPlatforms)&&value.capabilities.desktopPlatforms.includes('win32'))
+    ? '已连接;服务器尚不支持 Windows 电脑操作,请升级服务器(聊天可继续使用)'
+    : `电脑已连接 ${new URL(config.serverURL).host}`)
    core.acceptCapabilities?.(value.capabilities)
    await core.handle(value.commands??[])
   }catch(error){

+ 3 - 3
desktop/host-manager.test.mjs

@@ -52,7 +52,7 @@ test('concurrent first logins share one persistent installation identity',async(
   assert.equal(await readFile(join(home,'desktop-install-id'),'utf8'),ids[0])
   await manager.forget()
   assert.equal(await new DesktopHostManager(manager.options).installIdentity(),ids[0])
-  assert.equal((await stat(join(home,'desktop-install-id'))).mode&0o077,0)
+  if(process.platform!=='win32')assert.equal((await stat(join(home,'desktop-install-id'))).mode&0o077,0)
  }finally{await rm(home,{recursive:true,force:true})}
 })
 
@@ -74,7 +74,7 @@ test('imports an encrypted config, exchanges with the paired server and stops on
   let body='';req.on('data',chunk=>{body+=chunk});req.on('end',()=>{
    exchanges.push(JSON.parse(body))
    res.setHeader('content-type','application/json')
-   res.end(JSON.stringify(exchanges.length===1?{commands:[{id:randomUUID(),deadline:Date.now()+30000,mode:'local',owner:'a'.repeat(64),resource:'local',profile:'persistent',operation:'open'}]}:{commands:[]}))
+   res.end(JSON.stringify({capabilities:{desktopPlatforms:['darwin','win32']},...(exchanges.length===1?{commands:[{id:randomUUID(),deadline:Date.now()+30000,mode:'local',owner:'a'.repeat(64),resource:'local',profile:'persistent',operation:'open'}]}:{commands:[]})}))
   })
  })
  await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve))
@@ -82,7 +82,7 @@ test('imports an encrypted config, exchanges with the paired server and stops on
  try{
   await manager.importFile(configPath)
   const mode=await stat(join(home,'desktop-host.enc'))
-  assert.equal(mode.mode&0o077,0)
+  if(process.platform!=='win32')assert.equal(mode.mode&0o077,0)
   await sleep(1500)
   assert.ok(cores.length>=1)
   assert.equal(cores[0].closed,false)

+ 34 - 20
desktop/main.mjs

@@ -17,12 +17,16 @@ import { DesktopUpdateManager } from './update-manager.mjs'
 import { DesktopAutoUpdateManager } from './auto-update-manager.mjs'
 import { createRequire } from 'node:module'
 import { installComputerViewer } from './computer-viewer.mjs'
+import { desktopPlatform, desktopMenu, loginItemOptions } from './platform.mjs'
 
 const desktopRoot = dirname(fileURLToPath(import.meta.url))
 const fixtureHome = process.env.HERMES_YAOYAO_DESKTOP_TEST_HOME
+const platform = desktopPlatform()
+const loginOptions = loginItemOptions()
 // Fixture identity also isolates Chromium cookies, window state and the app lock.
 if (fixtureHome) app.setPath('userData', join(fixtureHome, 'desktop'))
 app.setName('夭夭')
+if (platform.windows) app.setAppUserModelId('cn.samien.yaoyao.desktop')
 if (!app.requestSingleInstanceLock()) { app.quit() }
 else {
   let window, tray, manager, runnerManager, quitting = false, closing = false, timer
@@ -61,6 +65,7 @@ else {
   })
   ipcMain.handle('desktop:retry', async event => {
     if (!trustedBoot(event)) throw new Error('不允许此页面启动桌面服务')
+    if (!platform.server) throw new Error('此客户端不支持在本机运行服务器')
     manager.restarts = []
     return onboarding.prepare()
   })
@@ -162,7 +167,8 @@ else {
       if (closeComputerViewer.owns(contents)) { callback(['fullscreen', 'clipboard-sanitized-write'].includes(permission)); return }
       if (!trustedService(contents, details.requestingUrl)) { callback(false); return }
       if (permission === 'media' && details.mediaTypes?.length && details.mediaTypes.every(type => type === 'audio')) {
-        void systemPreferences.askForMediaAccess('microphone').then(callback, () => callback(false))
+        if (platform.windows) callback(systemPreferences.getMediaAccessStatus('microphone') !== 'denied')
+        else void systemPreferences.askForMediaAccess('microphone').then(callback, () => callback(false))
       } else callback(['notifications', 'clipboard-sanitized-write', 'fullscreen'].includes(permission))
     })
     window.on('close', event => { if (!quitting) { event.preventDefault(); window.hide() } })
@@ -238,7 +244,7 @@ else {
             await manager?.reconnect().catch(error=>log(error.message))
             await runnerManager?.start().catch(error=>log(error.message))
           }
-          stateChanged(manager.state)
+          if (manager) stateChanged(manager.state)
           timer=setInterval(()=>{if(serverModeActive)void manager.check()},10000);timer.unref()
           updater?.startChecking?.()
           show()
@@ -278,14 +284,16 @@ else {
   })
   app.whenReady().then(async () => {
     await preferences.load()
-    startHidden = preferences.value.backgroundAtLogin && app.getLoginItemSettings().wasOpenedAtLogin
+    startHidden = preferences.value.backgroundAtLogin && (platform.windows
+      ? process.argv.includes('--yaoyao-login') : app.getLoginItemSettings().wasOpenedAtLogin)
     const packageVersion = JSON.parse(readFileSync(join(root, 'release.json'), 'utf8')).webVersion
     const buildInfo=JSON.parse(readFileSync(join(root,'build-info.json'),'utf8'))
     const releases = await import(pathToFileURL(join(root, 'github-release.mjs')).href)
     if ((app.isPackaged && !fixtureHome) || (fixtureHome && process.env.HERMES_YAOYAO_DESKTOP_TEST_AUTO_UPDATE === '1')) {
-      const { autoUpdater } = createRequire(import.meta.url)(join(root, 'electron-updater.cjs'))
+      const updateModule = createRequire(import.meta.url)(join(root, 'electron-updater.cjs'))
+      const autoUpdater = platform.windows ? new updateModule.NsisUpdater() : updateModule.autoUpdater
       autoUpdater.logger = Object.fromEntries(['info', 'warn', 'error', 'debug'].map(level => [level, (...values) => log(`[更新:${level}] ${values.join(' ')}`)]))
-      updater = new DesktopAutoUpdateManager({ driver: autoUpdater, version: packageVersion,
+      updater = new DesktopAutoUpdateManager({ driver: autoUpdater, version: packageVersion, platform: platform.platform,
         prepareInstall: prepareUpdateRestart, recoverInstall: recoverUpdateRestart })
       updater.startChecking()
     } else {
@@ -294,6 +302,8 @@ else {
         fetchImpl: (...args) => net.fetch(...args) })
     }
     app.setAboutPanelOptions({applicationName:'夭夭',applicationVersion:packageVersion,version:`${String(buildInfo.commit).slice(0,12)}${buildInfo.dirty?' · 工作区快照':''}`})
+    const credentials=new DesktopCredentials({home,platform:platform.platform,safeStorage,helper:join(root,app.isPackaged?'keychain-helper':'keychain-helper-dev'),legacyDecrypt:async bytes=>(await safeStorage.decryptStringAsync(bytes)).result})
+    if (platform.server) {
     manager = new DesktopServiceManager({ home, port, version: packageVersion, log, onState: stateChanged,
       prepareHome: !fixtureHome ? onProgress => migrateLocalData({ home, port, root, onProgress }) : undefined,
       stopBackground: (app.isPackaged && !fixtureHome) || (fixtureHome && process.env.HERMES_YAOYAO_DESKTOP_TEST_SYNC === '1')
@@ -316,13 +326,13 @@ else {
     })
     environmentHost=new DesktopEnvironmentHost({manager,root,dataRoot:app.getPath('userData')})
     const { parseRunnerConfiguration } = await import(pathToFileURL(join(root,'runner-config.mjs')).href)
-    const credentials=new DesktopCredentials({home,helper:join(root,app.isPackaged?'keychain-helper':'keychain-helper-dev'),legacyDecrypt:async bytes=>(await safeStorage.decryptStringAsync(bytes)).result})
     runnerManager = new DesktopRunnerManager({home,validate:parseRunnerConfiguration,
       encrypt:value=>credentials.encrypt(value),
       decrypt:bytes=>credentials.decrypt(bytes),
       onState:message=>{log(`Runner: ${message}`);const item=Menu.getApplicationMenu()?.getMenuItemById('runner-status');if(item)item.label=message},
       fork:()=>utilityProcess.fork(join(root,'runner.mjs'),['--desktop-ipc'],{cwd:root,stdio:'pipe',env:{HOME:homedir(),PATH:[join(homedir(),'.local/bin'),join(homedir(),'.orbstack/bin'),'/opt/homebrew/bin','/usr/local/bin',process.env.PATH||'/usr/bin:/bin'].join(':'),NODE_ENV:'production',NODE_USE_ENV_PROXY:'0'}}),
     })
+    }
     async function runnerAction(action){try{await action()}catch(error){await dialog.showMessageBox(window,{type:'error',message:'执行节点操作未完成',detail:error.message})}}
     hostManager=new DesktopHostManager({home,root,dataRoot:app.getPath('userData'),
       createCore:({root,dataRoot})=>new DesktopHostCore({root,dataRoot}),
@@ -361,7 +371,8 @@ else {
     }
     ipcMain.handle('desktop:mode-state',event=>{
       requireModePage(event)
-      return {mode:remoteMode?'client':'server',serverURL:serviceURL()||'',switching:switchingMode}
+      return {mode:remoteMode||!platform.server?'client':'server',serverURL:serviceURL()||'',switching:switchingMode,
+        platform:platform.platform,supportedModes:platform.supportedModes}
     })
     ipcMain.handle('desktop:mode-switch',async(event,mode)=>{
       requireModePage(event)
@@ -399,9 +410,11 @@ else {
       if (enrolled?.serverURL) await preferences.setRemoteServer(enrolled.serverURL)
     }
     onboarding = new DesktopOnboarding({
+      platform: platform.platform, supportedModes: platform.supportedModes,
       remoteServer: () => preferences.value.remoteServer,
       inspect: server => inspectServer(server, (...args) => net.fetch(...args)),
       prepareLocal: async ({ force }) => {
+        if (!platform.server) throw new Error('此客户端不支持在本机运行服务器')
         serverModeActive = true; remoteMode = false; remoteURL = ''
         await hostManager.stop()
         manager.restarts = []
@@ -432,9 +445,9 @@ else {
         if (mode === 'remote') {
           // Detach only; an independently installed local service keeps running.
           serverModeActive = false
-          await environmentHost.close()
-          await runnerManager.stop()
-          await manager.stop()
+          await environmentHost?.close()
+          await runnerManager?.stop()
+          await manager?.stop()
           remoteMode = true; remoteURL = serverURL
           await preferences.setRemoteServer(serverURL)
           const enrolled = await hostManager.read().catch(error => { log(error.message); return undefined })
@@ -481,6 +494,7 @@ else {
       if(ask)ask.checked=preferences.value.startupChoice==='ask'
     }
     async function switchMode(mode) {
+      if (mode === 'local' && !platform.server) return { ok: false, error: '此客户端不支持在本机运行服务器' }
       if (closing || quitting) return { ok: false, error: 'App 正在退出' }
       if (switchingMode || onboarding.busy) return { ok: false, error: '当前步骤尚未完成,请稍候' }
       switchingMode = true; syncModeMenu()
@@ -495,7 +509,7 @@ else {
       const selection=await dialog.showOpenDialog(window,{title:'导入执行节点配置',properties:['openFile'],filters:[{name:'Runner 配置',extensions:['json']}]})
       if(!selection.canceled&&selection.filePaths[0]&&!closing)await runnerAction(()=>runnerManager.importFile(selection.filePaths[0]))
     }
-    Menu.setApplicationMenu(Menu.buildFromTemplate([
+    Menu.setApplicationMenu(Menu.buildFromTemplate(desktopMenu([
       { label: '夭夭', submenu: [{ role: 'about', label: '关于夭夭' }, { type: 'separator' },
         { id:'desktop-service-status',label:'正在连接后台服务…',enabled:false },
         { label: '显示窗口', click: show }, { label: '在浏览器中打开', click: () => { const url = serviceURL(); if (url) safeExternal(url) } },
@@ -506,16 +520,16 @@ else {
           click:async()=>{try{await manager.retrySynchronization()}catch(error){log(error.message)}} },
         { id:'desktop-sync-force', label:'使用当前 App 覆盖同版本 Web', enabled:false,
           click:async()=>{if(closing||quitting||!manager.canForceSynchronization)return;try{await manager.retrySynchronization({force:true})}catch(error){log(error.message)}} },
-        { id:'desktop-login', label:'登录 macOS 时启动', type:'checkbox', enabled:app.isPackaged, checked:app.getLoginItemSettings().openAtLogin,
-          click:async item=>{try{app.setLoginItemSettings({openAtLogin:item.checked});item.checked=app.getLoginItemSettings().openAtLogin}catch(error){item.checked=app.getLoginItemSettings().openAtLogin;await dialog.showMessageBox(window,{type:'error',message:'无法修改登录启动设置',detail:error.message})}} },
+        { id:'desktop-login', label:'登录 macOS 时启动', type:'checkbox', enabled:app.isPackaged, checked:app.getLoginItemSettings(loginOptions).openAtLogin,
+          click:async item=>{try{app.setLoginItemSettings({...loginOptions,openAtLogin:item.checked});item.checked=app.getLoginItemSettings(loginOptions).openAtLogin}catch(error){item.checked=app.getLoginItemSettings(loginOptions).openAtLogin;await dialog.showMessageBox(window,{type:'error',message:'无法修改登录启动设置',detail:error.message})}} },
         { id:'desktop-background', label:'登录启动时仅驻留菜单栏', type:'checkbox', checked:preferences.value.backgroundAtLogin,
           click:async item=>{try{await preferences.setBackgroundAtLogin(item.checked)}catch(error){item.checked=preferences.value.backgroundAtLogin;await dialog.showMessageBox(window,{type:'error',message:error.message})}} },
         { id:'desktop-update-check', label:'检查 App 更新…', click:showUpdates },
-        { id:'desktop-update-help', label:'App 更新与回退…', click:()=>dialog.showMessageBox(window,{type:'info',message:`夭夭 App ${packageVersion}`,detail:`App 构建:${String(buildInfo.commit).slice(0,12)}\n\n通过“检查 App 更新”下载新版,准备完成后点击“重启更新”。此操作只更新当前电脑的 App,不升级远程服务器;独立后台服务继续运行。开发运行时提供手动安装包下载。\n\n服务器模式下,首次启动同步较旧的本机 Web,已有较新的 Web 保留。Web 降级通过服务器的回滚入口处理;数据库结构不兼容时不能直接降级。\n\n数据目录:${home}`,buttons:['知道了','打开数据目录']}).then(result=>{if(result.response===1)shell.showItemInFolder(home)}) },
+        { id:'desktop-update-help', label:'App 更新与回退…', click:()=>dialog.showMessageBox(window,{type:'info',message:`夭夭 App ${packageVersion}`,detail:`App 构建:${String(buildInfo.commit).slice(0,12)}\n\n通过“检查 App 更新”下载新版,准备完成后点击“重启更新”。此操作只更新当前电脑的 App,不升级远程服务器。开发运行时提供手动安装包下载。${platform.server ? "\n\n独立后台服务继续运行。服务器模式下,首次启动同步较旧的本机 Web,已有较新的 Web 保留。Web 降级通过服务器的回滚入口处理;数据库结构不兼容时不能直接降级。" : ""}\n\n数据目录:${home}`,buttons:['知道了','打开数据目录']}).then(result=>{if(result.response===1)shell.showItemInFolder(home)}) },
         { type: 'separator' },
         { role: 'hide', label: '隐藏夭夭' }, { role: 'hideOthers', label: '隐藏其他' }, { role: 'unhide', label: '显示全部' },
         { type: 'separator' },
-        {label:'撤销本机控制授权',click:()=>{void environmentHost.revoke();void hostManager?.revoke()}},
+        {label:'撤销本机控制授权',click:()=>{void environmentHost?.revoke();void hostManager?.revoke()}},
         { id:'desktop-quit',label:'退出夭夭(后台继续运行)',accelerator:'CommandOrControl+Q',click:()=>requestQuit() },
         { id:'desktop-stop-and-quit',label:'停止后台服务并退出',click:()=>requestQuit(true) }] },
       {label:'执行节点',submenu:[{id:'runner-status',label:'未配置执行节点',enabled:false},{type:'separator'},
@@ -534,19 +548,19 @@ else {
         {id:'desktop-host-reconnect',label:'重新连接',click:()=>hostAction(()=>hostManager.start())},
         {id:'desktop-host-forget',label:'断开并忘记配置',click:()=>hostAction(()=>hostManager.forget())}]},
       { role: 'editMenu', label: '编辑' }, { role: 'viewMenu', label: '显示' }, { role: 'windowMenu', label: '窗口' },
-    ]))
+    ])))
     const icon = nativeImage.createFromPath(join(desktopRoot, 'icon.png')).resize({ width: 20, height: 20 })
-    icon.setTemplateImage(true)
+    if (!platform.windows) icon.setTemplateImage(true)
     tray = new Tray(icon)
     tray.setToolTip('夭夭')
-    tray.setContextMenu(Menu.buildFromTemplate([{ label: '打开夭夭', click: show }, { label: '查看日志', click: () => shell.showItemInFolder(logFile) }, { type: 'separator' }, { label: '退出夭夭(后台继续运行)', click: () => requestQuit() }, { label: '停止后台服务并退出', click: () => requestQuit(true) }]))
+    tray.setContextMenu(Menu.buildFromTemplate(desktopMenu([{ label: '打开夭夭', click: show }, { label: '查看日志', click: () => shell.showItemInFolder(logFile) }, { type: 'separator' }, { label: '退出夭夭(后台继续运行)', click: () => requestQuit() }, { label: '停止后台服务并退出', click: () => requestQuit(true) }])))
     tray.on('click', show)
     // Restore a saved session behind neutral loading feedback. The guide only
     // becomes visible if a connection or account actually needs attention.
-    const startupMode = preferences.value.startupChoice === 'ask'
+    const startupMode = !platform.server ? 'remote' : preferences.value.startupChoice === 'ask'
       ? (fixtureHome && process.env.HERMES_YAOYAO_DESKTOP_TEST_MODE !== 'ask' ? 'local' : null)
       : preferences.value.startupChoice
-    const restoreSession = Boolean(startupMode && (startupMode === 'local' || preferences.value.remoteServer))
+    const restoreSession = Boolean(startupMode && (startupMode === 'local' || preferences.value.remoteServer)) && (platform.server || preferences.value.startupChoice !== 'ask')
     onboarding.open({ mode: startupMode, serverURL: preferences.value.remoteServer,
       remember: preferences.value.startupChoice !== 'ask', restoring: restoreSession })
     // Finish the initial navigation before a remembered session enters its server.

+ 4 - 4
desktop/mode-switch.test.mjs

@@ -28,12 +28,12 @@ test('signed-in desktop pages can switch both ways; other windows cannot control
   try{
     app=await electron.launch({args:[root],cwd:root,env:{...process.env,HERMES_YAOYAO_DESKTOP_TEST_HOME:home,HERMES_YAOYAO_DESKTOP_PORT:String(local.address().port),HERMES_YAOYAO_DESKTOP_TEST_SYNC:'0'}})
     const page=await app.firstWindow();releaseIdentity();await page.waitForURL(origin+'/**')
-    assert.deepEqual(await page.evaluate(()=>window.yaoyaoDesktop.modeState()),{mode:'server',serverURL:origin,switching:false})
+    assert.deepEqual(await page.evaluate(()=>window.yaoyaoDesktop.modeState()),{mode:'server',serverURL:origin,switching:false,platform:'darwin',supportedModes:['client','server']})
     assert.deepEqual(await page.evaluate(()=>window.yaoyaoDesktop.authorizeComputer('csrf-test')),{registered:false})
     assert.equal(await page.evaluate(()=>window.yaoyaoDesktop.switchMode('invalid').then(()=>false,()=>true)),true)
     await page.evaluate(()=>{void window.yaoyaoDesktop.switchMode('client')})
     await page.waitForURL(remoteURL+'/**')
-    assert.deepEqual(await page.evaluate(()=>window.yaoyaoDesktop.modeState()),{mode:'client',serverURL:remoteURL,switching:false})
+    assert.deepEqual(await page.evaluate(()=>window.yaoyaoDesktop.modeState()),{mode:'client',serverURL:remoteURL,switching:false,platform:'darwin',supportedModes:['client','server']})
     await expect.poll(async()=>JSON.parse(await readFile(join(home,'desktop-preferences.json'),'utf8')).startupChoice).toBe('remote')
     // Unchecking "ask at startup" must retain the active client role.
     await app.evaluate(({Menu})=>{const item=Menu.getApplicationMenu().getMenuItemById('desktop-host-ask');item.click(item)})
@@ -50,7 +50,7 @@ test('signed-in desktop pages can switch both ways; other windows cannot control
     assert.deepEqual(denied,[true,true,true,true])
     await page.evaluate(()=>{void window.yaoyaoDesktop.switchMode('server')})
     await page.waitForURL(origin+'/**')
-    await expect.poll(()=>page.evaluate(()=>window.yaoyaoDesktop.modeState())).toEqual({mode:'server',serverURL:origin,switching:false})
+    await expect.poll(()=>page.evaluate(()=>window.yaoyaoDesktop.modeState())).toEqual({mode:'server',serverURL:origin,switching:false,platform:'darwin',supportedModes:['client','server']})
     assert.equal(JSON.parse(await readFile(join(home,'desktop-preferences.json'),'utf8')).startupChoice,'local')
     assert.equal(local.listening,true,'switching must leave an independent service running')
     assert.equal(remote.listening,true)
@@ -71,7 +71,7 @@ test('signed-in desktop pages can switch both ways; other windows cannot control
     await page.locator('#prepare-local').click()
     await page.locator('#submit').click()
     await page.waitForURL(origin+'/**')
-    await expect.poll(()=>page.evaluate(()=>window.yaoyaoDesktop.modeState())).toEqual({mode:'server',serverURL:origin,switching:false})
+    await expect.poll(()=>page.evaluate(()=>window.yaoyaoDesktop.modeState())).toEqual({mode:'server',serverURL:origin,switching:false,platform:'darwin',supportedModes:['client','server']})
   }finally{
     releaseIdentity();await app?.close().catch(()=>{})
     await Promise.all([local,remote].map(server=>new Promise(done=>{server.close(done);server.closeAllConnections()})))

+ 5 - 1
desktop/onboarding.mjs

@@ -8,9 +8,12 @@ export class DesktopOnboarding {
     this.open()
   }
   get busy() { return ['preparing', 'authenticating', 'entering'].includes(this.state.phase) }
-  snapshot() { return { ...this.state, history: [...this.state.history], busy: this.busy } }
+  snapshot() { return { ...this.state, history: [...this.state.history], busy: this.busy,
+    platform: this.options.platform ?? process.platform, supportedModes: this.options.supportedModes ?? ['client', 'server'] } }
   open({ mode = null, serverURL = '', remember = false, forceLogin = false, restoring = false } = {}) {
     if (this.state && this.busy) throw new Error('当前步骤尚未完成,请稍候')
+    if (mode === 'local' && !this.snapshotModes().includes('server')) throw new Error('此客户端不支持在本机运行服务器')
+    if (!mode && !this.snapshotModes().includes('server')) mode = 'remote'
     this.state = { active: true, mode, serverURL, remember, forceLogin, restoring, phase: 'idle', stage: 'checking',
       setupRequired: false, registrationAvailable: false, registrationNotice: '', authenticated: false, username: '', message: '', error: '',
       canForceSync: false, history: [] }
@@ -20,6 +23,7 @@ export class DesktopOnboarding {
     if (!['local', 'remote'].includes(mode)) throw new Error('请选择运行方式')
     return this.open({ mode, serverURL: this.options.remoteServer(), remember: this.state.remember })
   }
+  snapshotModes() { return this.options.supportedModes ?? ['client', 'server'] }
   serviceChanged(service) {
     if (!this.state.active || this.state.mode !== 'local') return
     this.state.stage = service.stage || this.state.stage

+ 31 - 0
desktop/platform.mjs

@@ -0,0 +1,31 @@
+/** Platform policy is shared by startup, native menus and the renderer bridge. */
+export function desktopPlatform(platform = process.platform) {
+  return Object.freeze({ platform, server: platform === 'darwin',
+    supportedModes: platform === 'darwin' ? ['client', 'server'] : ['client'],
+    computer: ['darwin', 'win32'].includes(platform), windows: platform === 'win32' })
+}
+
+export function loginItemOptions(platform = process.platform, executable = process.execPath) {
+  return platform === 'win32' ? { path: executable, args: ['--yaoyao-login'] } : {}
+}
+
+export function desktopMenu(template, platform = process.platform) {
+  if (platform === 'darwin') return template
+  const excluded = new Set(['desktop-local-vm', 'desktop-sync-notice', 'desktop-sync-retry',
+    'desktop-sync-force', 'desktop-stop-and-quit', 'desktop-host-use-local', 'desktop-host-ask'])
+  const result = []
+  for (const item of template) {
+    if (excluded.has(item.id) || item.label === '执行节点' || ['hide', 'hideOthers', 'unhide'].includes(item.role)) continue
+    const next = { ...item }
+    if (next.submenu) next.submenu = desktopMenu(next.submenu, platform)
+    if (next.id === 'desktop-login') next.label = '登录 Windows 时启动'
+    if (next.id === 'desktop-background') next.label = '登录启动时仅驻留托盘'
+    if (next.id === 'desktop-service-status') next.label = '尚未连接服务器'
+    if (next.label === '退出夭夭(后台继续运行)') next.label = '退出夭夭'
+    if (next.label === '停止后台服务并退出') continue
+    if (next.type === 'separator' && (!result.length || result.at(-1).type === 'separator')) continue
+    result.push(next)
+  }
+  if (result.at(-1)?.type === 'separator') result.pop()
+  return result
+}

+ 36 - 0
desktop/platform.test.mjs

@@ -0,0 +1,36 @@
+import { test } from 'node:test'
+import assert from 'node:assert/strict'
+import { desktopPlatform, desktopMenu, loginItemOptions } from './platform.mjs'
+import { DesktopOnboarding } from './onboarding.mjs'
+import { hostPathInput, pathInside } from '../src/shared/hostPaths.mjs'
+
+test('Windows can only connect to a server, including direct onboarding calls', () => {
+  const platform = desktopPlatform('win32')
+  assert.deepEqual(platform.supportedModes, ['client'])
+  const onboarding = new DesktopOnboarding({ ...platform, remoteServer: () => '' })
+  assert.equal(onboarding.snapshot().mode, 'remote')
+  assert.equal(onboarding.snapshot().platform, 'win32')
+  assert.throws(() => onboarding.select('local'), /不支持/)
+  assert.throws(() => onboarding.open({ mode: 'local' }), /不支持/)
+  assert.equal(onboarding.select('remote').mode, 'remote')
+  assert.deepEqual(desktopPlatform('darwin').supportedModes, ['client', 'server'])
+})
+test('Windows menus retain useful actions and omit all local service actions', () => {
+  const template = [{ label: '夭夭', submenu: [{ role: 'hide' }, { id: 'desktop-local-vm' }, { id: 'desktop-login' }, { id: 'desktop-quit', label: '退出夭夭(后台继续运行)' }] },
+    { label: '执行节点', submenu: [{ id: 'runner-import' }] }, { label: '运行模式', submenu: [{ id: 'desktop-host-use-local' }, { label: '更换服务器…' }] }]
+  const windows = desktopMenu(template, 'win32')
+  assert.equal(windows.length, 2)
+  assert.deepEqual(windows[0].submenu.map(item => item.label), ['登录 Windows 时启动', '退出夭夭'])
+  assert.deepEqual(windows[1].submenu, [{ label: '更换服务器…' }])
+  assert.equal(desktopMenu(template, 'darwin'), template)
+  assert.deepEqual(loginItemOptions('win32', 'C:\\Apps\\Yaoyao.exe'), { path: 'C:\\Apps\\Yaoyao.exe', args: ['--yaoyao-login'] })
+})
+test('Windows file boundaries handle drive casing, separators, traversal and device paths', () => {
+  const root = 'C:\\Users\\张三'
+  for (const path of ['c:\\users\\张三\\Documents\\a.txt', 'C:/Users/张三/Desktop/a.txt', root]) assert.equal(pathInside(root, path, 'win32'), true, path)
+  for (const path of ['C:\\Users\\张三2\\a.txt', 'D:\\Users\\张三\\a.txt', 'C:\\Users\\张三\\..\\secret']) assert.equal(pathInside(root, path, 'win32'), false, path)
+  assert.equal(hostPathInput('~\\Documents\\中文.txt', 'win32'), 'Documents\\中文.txt')
+  for (const path of ['C:secret', '\\\\server\\share', '\\\\?\\C:\\secret', 'a.txt:secret', 'CON', 'x\\NUL.txt', 'x.\\secret', 'a\0b']) assert.throws(() => hostPathInput(path, 'win32'), /路径无效/, path)
+  assert.equal(hostPathInput('notes:today', 'darwin'), 'notes:today')
+  assert.equal(pathInside('/home/a', '/home/ab', 'linux'), false)
+})

+ 1 - 1
desktop/preferences.test.mjs

@@ -11,7 +11,7 @@ test('background login remains opt-in and persists without changing system login
     assert.deepEqual(await preferences.load(),{backgroundAtLogin:false,startupChoice:'ask',remoteServer:''})
     await preferences.setBackgroundAtLogin(true)
     assert.deepEqual(await new DesktopPreferences(home).load(),{backgroundAtLogin:true,startupChoice:'ask',remoteServer:''})
-    assert.equal((await stat(preferences.path)).mode&0o777,0o600)
+    if(process.platform!=='win32')assert.equal((await stat(preferences.path)).mode&0o777,0o600)
     await preferences.setBackgroundAtLogin(false)
     assert.deepEqual(await new DesktopPreferences(home).load(),{backgroundAtLogin:false,startupChoice:'ask',remoteServer:''})
   }finally{await rm(home,{recursive:true,force:true})}

+ 1 - 1
desktop/remote-login.mjs

@@ -92,7 +92,7 @@ export async function enrollDesktopHost(session,{name,installId,previousHostId},
     headers:{accept:'application/json','content-type':'application/json',cookie,'x-csrf-token':session.csrfToken,origin:session.origin},
     body:JSON.stringify({name:String(name).slice(0,100),...(installId?{installId}:{}),...(previousHostId?{previousHostId}:{})}),
   })
-  if(response.status===403)throw new Error('需要管理员账号,才能把这台 Mac 注册为可远程控制的电脑')
+  if(response.status===403)throw new Error('需要管理员账号,才能把这台电脑注册为可远程控制的电脑')
   if(!response.ok)throw new Error(`注册电脑失败(HTTP ${response.status})`)
   const result=await response.json()
   if(typeof result?.token!=='string'||!result?.host?.id)throw new Error('注册电脑响应无效')

+ 7 - 6
desktop/update-manager.mjs

@@ -35,7 +35,7 @@ function assertDigest(digest, actual) {
 
 export class DesktopUpdateManager {
   constructor({ version, arch = process.arch, platform = process.platform, cacheRoot, inspect, compare, source, fetchImpl = fetch,
-    verifyImage = (path, signal) => promisify(execFile)('/usr/bin/hdiutil', ['verify', path], { timeout: 120000, signal, maxBuffer: 1024 * 1024 }) }) {
+    verifyImage = (path, signal) => platform === 'win32' ? Promise.resolve() : promisify(execFile)('/usr/bin/hdiutil', ['verify', path], { timeout: 120000, signal, maxBuffer: 1024 * 1024 }) }) {
     Object.assign(this, { version, arch, platform, cacheRoot, inspect, compare, source, fetchImpl, verifyImage })
     this.state = { phase: 'idle', installMode: 'manual', currentVersion: version, arch, message: '点击检查更新', available: false, received: 0, total: 0 }
   }
@@ -53,10 +53,11 @@ export class DesktopUpdateManager {
       controller.signal.throwIfAborted()
       this.release = release
       const version = release.manifest.webVersion
-      this.asset = release.assets.find(asset => asset.name === `Yaoyao-${version}-${this.arch}.dmg`)
-      this.checksum = release.assets.find(asset => asset.name === 'SHA256SUMS.txt')
+      this.asset = release.assets.find(asset => asset.name === (this.platform === 'win32' ? `Yaoyao-${version}-win-${this.arch}-setup.exe` : `Yaoyao-${version}-${this.arch}.dmg`))
+      this.checksum = (this.platform === 'win32' && release.assets.find(asset => asset.name === `SHA256SUMS-win-${this.arch}.txt`))
+        || release.assets.find(asset => asset.name === 'SHA256SUMS.txt')
       const newer = this.compare(version, this.version) > 0
-      const supported = this.platform === 'darwin' && ['arm64', 'x64'].includes(this.arch)
+      const supported = (this.platform === 'darwin' && ['arm64', 'x64'].includes(this.arch) || this.platform === 'win32' && this.arch === 'x64')
         && this.asset?.size > 0 && this.asset.size <= 2 * 1024 ** 3 && this.checksum?.size <= 65536
       this.state = { ...this.state, phase: 'checked', latestVersion: version, notes: release.notes, releasePageUrl: release.releasePageUrl,
         available: Boolean(newer && supported), total: supported ? this.asset.size : 0,
@@ -111,7 +112,7 @@ export class DesktopUpdateManager {
           }
           if (received !== this.asset.size || hash.digest('hex') !== expected) throw new Error('安装包大小或 SHA-256 校验失败')
         } finally { await file.close() }
-        this.state = { ...this.state, phase: 'verifying', message: '正在验证 DMG 完整性…' }
+        this.state = { ...this.state, phase: 'verifying', message: '正在验证安装包完整性…' }
         await this.verifyImage(partial, signal); signal.throwIfAborted()
         await rename(partial, path)
       } else {
@@ -119,7 +120,7 @@ export class DesktopUpdateManager {
         await this.verifyImage(path, signal); signal.throwIfAborted()
       }
       this.file = { path, hash: expected, size: this.asset.size }
-      this.state = { ...this.state, phase: 'ready', received: this.asset.size, message: '校验通过。打开安装包后手动拖入“应用程序”完成安装。' }
+      this.state = { ...this.state, phase: 'ready', received: this.asset.size, message: this.platform === 'win32' ? '校验通过。打开 EXE 安装包完成安装。' : '校验通过。打开安装包后手动拖入“应用程序”完成安装。' }
     } catch (error) { this.failure(error, controller.signal) }
     finally { await rm(partial, { force: true }).catch(() => {}); this.controller = undefined }
     return this.snapshot()

+ 14 - 0
desktop/update-manager.test.mjs

@@ -49,6 +49,20 @@ test('same version with a different commit and unsupported architectures never o
     assert.equal(f.calls.length, 0)
   } finally { await f.clean() }
 })
+test('Windows downloads an EXE using its platform checksum manifest', async () => {
+  const assetName = 'Yaoyao-0.4.2-win-x64-setup.exe'
+  const sums = Buffer.from(`${hash(data)}  ${assetName}\n`)
+  const f = await fixture({ platform: 'win32', arch: 'x64', fetchImpl: async url => new Response(url.endsWith('.exe') ? data : sums) })
+  try {
+    f.release.assets = [
+      { name: assetName, url: prefix + assetName, size: data.length },
+      { name: 'SHA256SUMS-win-x64.txt', url: prefix + 'SHA256SUMS-win-x64.txt', size: sums.length },
+    ]
+    assert.equal((await f.manager.check()).available, true)
+    assert.equal((await f.manager.download()).phase, 'ready')
+    assert.match(await f.manager.verifiedFile(), /win-x64-setup\.exe$/)
+  } finally { await f.clean() }
+})
 test('corrupt or missing checksum, wrong size, and failed image validation never expose a file', async () => {
   for (const failure of ['digest', 'size', 'checksum', 'image']) {
     const f = await fixture()

+ 2 - 2
desktop/update.html

@@ -3,11 +3,11 @@
 <meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'self'; style-src 'self'">
 <title>App 更新 · 夭夭</title><link rel="stylesheet" href="update.css"></head>
 <body><main>
-<header><p class="eyebrow">夭夭 · macOS</p><h1>App 更新</h1><p id="subtitle">更新当前电脑的 App,下载完成后重启安装。</p></header>
+<header><p class="eyebrow">夭夭 · 桌面客户端</p><h1>App 更新</h1><p id="subtitle">更新当前电脑的 App,下载完成后重启安装。</p></header>
 <section class="versions" aria-label="版本信息"><div><span>当前版本</span><strong id="current">—</strong></div><div><span>最新版本</span><strong id="latest">待检查</strong></div></section>
 <p id="status" role="status" aria-live="polite">正在检查…</p><p id="error" role="alert" hidden></p>
 <progress id="progress" aria-label="安装包下载进度" hidden></progress><p id="bytes" class="muted"></p>
 <div class="actions"><button id="check">检查更新</button><button id="download" class="primary" disabled>下载更新</button><button id="cancel" hidden>取消</button><button id="install" class="primary" hidden>重启更新</button><button id="open" class="primary" hidden>打开安装包</button><button id="folder" hidden>打开所在文件夹</button></div>
 <details id="notes-section" hidden><summary>发布说明</summary><pre id="notes"></pre></details>
-<footer><button id="release" class="link">查看 GitHub 发布页</button><p>此处仅更新本机 App。远程服务器版本由服务器管理员管理。</p><p>下载期间可继续使用;重启时会断开本机连接,独立后台服务继续运行。</p></footer>
+<footer><button id="release" class="link">查看 GitHub 发布页</button><p>此处仅更新本机 App。远程服务器版本由服务器管理员管理。</p><p>下载期间可继续使用;重启时会断开本机连接。</p></footer>
 </main><script src="update.js"></script></body></html>

+ 1 - 1
desktop/update.js

@@ -13,7 +13,7 @@ function render(state) {
   byId('subtitle').textContent = automatic ? '更新当前电脑的 App,下载完成后重启安装。' : '开发运行:从 GitHub 下载,校验后手动安装。'
   byId('check').disabled = busy || (automatic && ready) || state.retryable === false
   byId('download').disabled = busy || !state.available; byId('download').hidden = ready
-  byId('download').textContent = automatic ? '下载更新' : state.phase === 'failed' || state.phase === 'cancelled' ? '重试下载' : '下载 DMG'
+  byId('download').textContent = automatic ? '下载更新' : state.phase === 'failed' || state.phase === 'cancelled' ? '重试下载' : '下载安装包'
   byId('cancel').hidden = automatic ? !state.canCancel : !busy
   byId('open').hidden = !ready || automatic; byId('folder').hidden = !ready || automatic
   byId('install').hidden = !automatic || (!ready && state.phase !== 'installing')

+ 49 - 0
desktop/windows-input.mjs

@@ -0,0 +1,49 @@
+import { execFile } from 'node:child_process'
+import { join } from 'node:path'
+
+export function windowsFrame(display, dimensions, physicalBounds) {
+  return { display: display.id, ...dimensions, bounds: display.bounds, scaleFactor: display.scaleFactor, physicalBounds }
+}
+export function sameWindowsDisplay(frame, display, physicalBounds) {
+  return frame?.display === display.id && frame.scaleFactor === display.scaleFactor
+    && JSON.stringify(frame.bounds) === JSON.stringify(display.bounds)
+    && JSON.stringify(frame.physicalBounds) === JSON.stringify(physicalBounds)
+}
+
+export class WindowsInput {
+  constructor(root, packaged, execute = execFile) {
+    this.helper = join(root, packaged ? 'computer-helper.exe' : 'computer-helper-dev.exe')
+    this.execute = execute; this.controllers = new Set(); this.pending = new Set(); this.available = false
+  }
+  async call(value) {
+    const controller = new AbortController()
+    this.controllers.add(controller)
+    let completed, closed
+    const completion = new Promise(resolve => { completed = resolve })
+    this.pending.add(completion)
+    try {
+      return await new Promise((resolve, reject) => {
+        const child = this.execute(this.helper, [], { timeout: 10000, signal: controller.signal, windowsHide: true, maxBuffer: 65536 }, (error, stdout, stderr) => {
+          if (error) { this.available = false; reject(new Error(String(stderr || '').trim() || 'Windows 电脑助手不可用,请检查桌面会话或重新安装客户端')); return }
+          try { const result = JSON.parse(stdout); if (result.ok !== true) throw new Error(); resolve(result) }
+          catch { this.available = false; reject(new Error('Windows 电脑助手响应无效')) }
+        })
+        closed = new Promise(resolve => child.once('close', resolve))
+        child.stdin.on('error', () => {})
+        child.stdin.end(JSON.stringify(value))
+      })
+    } finally {
+      await closed
+      this.controllers.delete(controller)
+      // An aborted drag may have held the button when its process terminated.
+      if (controller.signal.aborted && value.action?.kind === 'drag') await this.call({ operation: 'release-drag' }).catch(() => {})
+      this.pending.delete(completion); completed()
+    }
+  }
+  async probe() {
+    try { await this.call({ operation: 'probe' }); this.available = true }
+    catch { this.available = false }
+    return this.available
+  }
+  cancel() { for (const controller of this.controllers) controller.abort(); this.available = false; return Promise.allSettled([...this.pending]) }
+}

+ 47 - 0
desktop/windows-shell.mjs

@@ -0,0 +1,47 @@
+import { spawn } from 'node:child_process'
+import { resolve as resolvePath } from 'node:path'
+
+export function powershellArguments(command) {
+  const script = `$ProgressPreference = 'SilentlyContinue'\n[Console]::InputEncoding = [Console]::OutputEncoding = $OutputEncoding = New-Object System.Text.UTF8Encoding($false)\n$global:LASTEXITCODE = 0\ntry {\n& {\n${command}\n}\n$ok = $?\nif ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }\nif (-not $ok) { exit 1 }\n} catch { [Console]::Error.WriteLine($_.ToString()); exit 1 }`
+  return ['-NoLogo', '-NoProfile', '-NonInteractive', '-OutputFormat', 'Text', '-EncodedCommand', Buffer.from(script, 'utf16le').toString('base64')]
+}
+
+/** Bound both output streams, and terminate the owned process tree before
+ * resolving a timeout or authorization cancellation. Never spawn a shell. */
+export function windowsShell(shell, command, { cwd, timeout, signal, helper = resolvePath(import.meta.dirname, '../.desktop-build/computer-helper-dev.exe'), limit = 512 * 1024 }) {
+  return new Promise(resolve => {
+    let child, timer, timedOut = false, cancelled = false, finished = false
+    const output = { stdout: [], stderr: [] }, sizes = { stdout: 0, stderr: 0 }
+    const capture = (key, bytes) => {
+      const kept = bytes.subarray(0, Math.max(0, limit - sizes[key]))
+      if (kept.length) output[key].push(kept)
+      sizes[key] += kept.length
+    }
+    const finish = async (code, error) => {
+      if (finished) return
+      finished = true; clearTimeout(timer); signal?.removeEventListener('abort', abort)
+      if (error) capture('stderr', Buffer.from(error.message))
+      resolve({ command, exitCode: timedOut || cancelled || error ? 1 : code ?? 1, timedOut,
+        ...(cancelled ? { cancelled: true } : {}),
+        stdout: Buffer.concat(output.stdout).toString('utf8'), stderr: Buffer.concat(output.stderr).toString('utf8') })
+    }
+    const stop = () => {
+      // The native helper owns a KILL_ON_JOB_CLOSE job. Terminating the helper
+      // closes that kernel handle and the entire owned PowerShell process tree.
+      if (!finished && child?.pid) child.kill()
+    }
+    const abort = () => { cancelled = true; stop() }
+    if (signal?.aborted) { cancelled = true; void finish(1); return }
+    try {
+      child = spawn(helper, ['--shell'], { cwd, windowsHide: true, stdio: ['pipe', 'pipe', 'pipe'], env: { ...process.env, TERM: 'dumb' } })
+      child.stdin.on('error', () => {})
+      child.stdin.end(JSON.stringify({ encoded: powershellArguments(command).at(-1), cwd }))
+      child.stdout.on('data', bytes => capture('stdout', bytes))
+      child.stderr.on('data', bytes => capture('stderr', bytes))
+      child.once('error', error => { void finish(1, error) })
+      child.once('close', code => { void finish(code) })
+      signal?.addEventListener('abort', abort, { once: true })
+      timer = setTimeout(() => { timedOut = true; stop() }, timeout)
+    } catch (error) { void finish(1, error) }
+  })
+}

+ 112 - 0
desktop/windows-smoke.test.mjs

@@ -0,0 +1,112 @@
+import { test } from 'node:test'
+import assert from 'node:assert/strict'
+import { createServer } from 'node:http'
+import { mkdtemp, readFile, readdir, rm, mkdir, writeFile } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import { join, resolve } from 'node:path'
+import { randomUUID } from 'node:crypto'
+import { _electron as electron, expect } from '@playwright/test'
+
+test('packaged Windows client logs in, encrypts pairing, restores its session and never starts a server', { skip: process.platform !== 'win32', timeout: 90000 }, async () => {
+  const home = await mkdtemp(join(tmpdir(), '夭夭-windows-')), hostId = randomUUID(), token = 'windows-fixture-token-not-for-production'
+  let exchanges = 0, app
+  const server = createServer((req, res) => {
+    const json = (body, status = 200) => { res.statusCode = status; res.setHeader('content-type', 'application/json'); res.end(JSON.stringify(body)) }
+    if (req.url === '/api/app/bootstrap') {
+      res.setHeader('set-cookie', 'csrf=fixture; Path=/; HttpOnly')
+      return json({ authenticated: String(req.headers.cookie).includes('session=fixture'), setupRequired: false, csrfToken: 'fixture', serverKind: 'yaoyao-web' })
+    }
+    if (req.url === '/api/app/login') {
+      req.resume(); res.setHeader('set-cookie', 'session=fixture; Path=/; HttpOnly; Max-Age=3600')
+      return json({ user: { id: 'fixture', username: 'admin', role: 'admin' }, csrfToken: 'fixture' })
+    }
+    if (req.url === '/api/app/admin/desktop-hosts') { req.resume(); return json({ host: { id: hostId }, token }) }
+    if (req.url === `/api/desktop-host/v1/${hostId}/exchange`) {
+      let raw = ''; req.on('data', bytes => { raw += bytes }); req.on('end', () => {
+        const body = JSON.parse(raw)
+        assert.equal(body.host.platform, 'win32'); assert.equal(req.headers.authorization, `Bearer ${token}`)
+        exchanges++; json({ commands: [], capabilities: { environmentMetadata: 1, desktopPlatforms: ['darwin', 'win32'] } })
+      }); return
+    }
+    res.setHeader('content-type', 'text/html; charset=utf-8'); res.end('<title>Windows 登录验证</title><h1>远程工作区</h1><textarea id="native-input" style="width:400px;height:140px"></textarea>')
+  })
+  await new Promise(done => server.listen(0, '127.0.0.1', done))
+  const url = `http://127.0.0.1:${server.address().port}`
+  const launch = () => electron.launch({ executablePath: process.env.DESKTOP_TEST_EXECUTABLE || resolve('desktop-release/windows-x64/win-unpacked/Yaoyao.exe'),
+    args: [], env: { ...process.env, HERMES_YAOYAO_DESKTOP_TEST_HOME: home }, timeout: 30000 })
+  const evidence = resolve('test-results/windows-client')
+  try {
+    app = await launch(); let page = await app.firstWindow()
+    await expect(page.locator('#connection-form')).toBeVisible()
+    await expect(page.locator('#choice-section')).toBeHidden()
+    assert.deepEqual((await page.evaluate(() => window.yaoyaoDesktop.status())).supportedModes, ['client'])
+    assert.equal(await page.evaluate(async () => { try { await window.yaoyaoDesktop.selectServer('local'); return false } catch { return true } }), true)
+    await page.locator('#server').fill(url); await page.locator('#detect').click()
+    await expect(page.locator('#login-form')).toBeVisible()
+    await page.locator('#username').fill('admin'); await page.locator('#password').fill('fixture-password'); await page.locator('#remember').check(); await page.locator('#submit').click()
+    await page.waitForURL(url + '/**')
+    const state = await page.evaluate(() => window.yaoyaoDesktop.modeState())
+    assert.equal(state.mode, 'client'); assert.deepEqual(state.supportedModes, ['client'])
+    assert.equal((await page.evaluate(() => window.yaoyaoDesktop.switchMode('server'))).ok, false)
+    await expect.poll(() => exchanges).toBeGreaterThan(0)
+    const bytes = await readFile(join(home, 'desktop-host.enc'))
+    assert.equal(bytes.includes(token), false); assert.equal(bytes.includes('fixture-password'), false)
+    assert.equal(bytes.subarray(0, Buffer.byteLength('YAOYAO-WINDOWS-DPAPI-1\n')).toString(), 'YAOYAO-WINDOWS-DPAPI-1\n')
+    assert.equal((await readdir(home)).includes('service-instance.json'), false)
+    const menu = await app.evaluate(({ Menu }) => ['desktop-host-use-local', 'desktop-stop-and-quit', 'runner-import'].map(id => Boolean(Menu.getApplicationMenu().getMenuItemById(id))))
+    assert.deepEqual(menu, [false, false, false])
+    const native = await app.evaluate(async ({ app, BrowserWindow, screen }, { home, url }) => {
+      const { createRequire } = process.getBuiltinModule('node:module')
+      const { join } = process.getBuiltinModule('node:path')
+      const { DesktopHostCore } = createRequire(join(app.getAppPath(), 'main.mjs'))('./environment-host.mjs')
+      const core = new DesktopHostCore({ root: join(process.resourcesPath, 'runtime'), dataRoot: join(home, 'native-acceptance') })
+      const owner = 'a'.repeat(64), resource = 'b'.repeat(64)
+      const command = { owner, resource, mode: 'local', profile: 'temporary', deadline: Date.now() + 30000 }
+      core.approved.add(owner); core.approvedFull.add(owner)
+      try {
+        const shell = await core.execute({ ...command, operation: 'shell', action: { command: "[Console]::WriteLine('原生命令')" } })
+        if (shell.exitCode !== 0 || shell.stdout.trim() !== '原生命令') throw new Error('打包后的 PowerShell 助手执行失败:' + shell.stderr)
+        await core.execute({ ...command, mode: 'browser', operation: 'open' })
+        await core.execute({ ...command, mode: 'browser', operation: 'browser', action: { kind: 'navigate', url } })
+        const browserFrame = await core.execute({ ...command, mode: 'browser', operation: 'view' })
+        if (!browserFrame.data || (await core.browser.sessions.get(resource).cookies.get({ url })).some(cookie => cookie.name === 'session')) throw new Error('独立浏览器画面或会话隔离失败')
+        let unavailable
+        try { await core.native.call({ operation: 'probe' }) } catch (error) { unavailable = error.message }
+        if (unavailable) return { shell: true, isolatedBrowser: true, screenInput: 'unavailable in CI session', reason: unavailable }
+        const frame = await core.execute({ ...command, operation: 'view' }), display = screen.getPrimaryDisplay()
+        const target = BrowserWindow.getAllWindows().find(w => w.isVisible() && w.webContents.getURL().startsWith(url)), bounds = target.getContentBounds()
+        target.show(); target.focus()
+        const rect = await target.webContents.executeJavaScript('(()=>{const r=document.querySelector("textarea").getBoundingClientRect();return {x:r.x+30,y:r.y+30}})()')
+        const physical = screen.dipToScreenPoint({ x: Math.round(bounds.x + rect.x), y: Math.round(bounds.y + rect.y) })
+        const primary = screen.dipToScreenRect(null, display.bounds)
+        await core.execute({ ...command, operation: 'input', frame, action: { kind: 'click', x: Math.floor(physical.x * frame.width / primary.width), y: Math.floor(physical.y * frame.height / primary.height) } })
+        await core.execute({ ...command, operation: 'input', frame, action: { kind: 'text', text: '你好,Windows🙂' } })
+        for (let i = 0; i < 30; i++) {
+          if (await target.webContents.executeJavaScript('document.querySelector("textarea").value') === '你好,Windows🙂') break
+          await new Promise(done => setTimeout(done, 100))
+        }
+        if (await target.webContents.executeJavaScript('document.querySelector("textarea").value') !== '你好,Windows🙂') throw new Error('原生鼠标点击或 Unicode 输入失败')
+        await core.execute({ ...command, operation: 'input', frame, action: { kind: 'key', key: 'a', modifiers: ['ctrl'] } })
+        await core.execute({ ...command, operation: 'input', frame, action: { kind: 'text', text: '组合键已验证' } })
+        if (await target.webContents.executeJavaScript('document.querySelector("textarea").value') !== '组合键已验证') throw new Error('原生 Ctrl+A 输入失败')
+        screen.emit('display-metrics-changed', {}, display, ['scaleFactor'])
+        let staleRejected = false
+        try { await core.execute({ ...command, operation: 'input', frame, action: { kind: 'key', key: 'Tab' } }) } catch (error) { staleRejected = /刷新画面/.test(error.message) }
+        if (!staleRejected) throw new Error('显示器变化后必须重新截图')
+        await core.revoke()
+        let revoked = false
+        try { await core.execute({ ...command, operation: 'shell', action: { command: 'exit 0' } }) } catch { revoked = true }
+        if (!revoked) throw new Error('撤销后仍允许命令执行')
+        return { shell: true, isolatedBrowser: true, screenshot: true, click: true, unicodeInput: true, ctrlA: true, displayInvalidation: true, revoked: true, scaleFactor: display.scaleFactor }
+      } finally { await core.close() }
+    }, { home, url })
+    await mkdir(evidence, { recursive: true }); await page.screenshot({ path: join(evidence, 'remote-login.png') })
+    await app.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0].close())
+    assert.equal(await app.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0].isVisible()), false)
+    await app.close(); app = undefined
+    const before = exchanges; app = await launch(); page = await app.firstWindow()
+    await page.waitForURL(url + '/**'); await expect.poll(() => exchanges).toBeGreaterThan(before)
+    await writeFile(join(evidence, 'smoke.json'), JSON.stringify({ platform: 'win32', login: true, encryptedPairing: true, sessionRestored: true,
+      clientOnly: true, native, windows10and11Matrix: 'requires Windows 10/11 acceptance; CI runs Windows Server 2022' }, null, 2))
+  } finally { await app?.close().catch(() => {}); await new Promise(done => server.close(done)); await rm(home, { recursive: true, force: true }) }
+})

+ 135 - 0
desktop/windows-upgrade.test.mjs

@@ -0,0 +1,135 @@
+import { test } from 'node:test'
+import assert from 'node:assert/strict'
+import { createServer } from 'node:http'
+import { execFile } from 'node:child_process'
+import { promisify } from 'node:util'
+import { mkdtemp, readFile, writeFile, mkdir, rm, readdir, realpath, copyFile, access } from 'node:fs/promises'
+import { tmpdir, homedir } from 'node:os'
+import { join, resolve, basename } from 'node:path'
+import { randomUUID } from 'node:crypto'
+import { _electron as electron, expect } from '@playwright/test'
+import { powershellArguments } from './windows-shell.mjs'
+const execute = promisify(execFile)
+
+test('installed NSIS client rejects a corrupt update, upgrades and preserves settings and cookies', {
+  skip: process.platform !== 'win32' || process.env.DESKTOP_TEST_UPGRADE !== '1', timeout: 600000,
+}, async () => {
+  const root = resolve(import.meta.dirname, '..'), output = join(root, 'desktop-release/windows-x64')
+  const evidence = join(root, 'test-results/windows-client'), sandbox = await realpath(await mkdtemp(join(tmpdir(), 'yaoyao-upgrade-')))
+  // NSIS relaunches through Explorer, which correctly uses the user's normal
+  // environment instead of inheriting Playwright's fixture-only variables.
+  // This test may touch the normal profile only on a fresh disposable CI user.
+  assert.equal(process.env.GITHUB_ACTIONS, 'true', '安装升级验收只允许在一次性 GitHub Actions 用户下执行')
+  assert.ok(!process.env.YAOYAO_HOME && !process.env.HERMES_YAOYAO_HOME && !process.env.HERMES_YAOYAO_DESKTOP_TEST_HOME)
+  const home = join(homedir(), '.yaoyao'), installed = join(sandbox, 'app'), feed = join(sandbox, 'feed')
+  assert.equal(await access(home).then(() => true).catch(() => false), false, '拒绝覆盖已有用户数据')
+  const executablePath = join(installed, 'Yaoyao.exe'), cacheName = 'yaoyao-upgrade-' + randomUUID()
+  const originalManifest = await readFile(join(root, '.desktop-build/release.json'), 'utf8')
+  const originalPackage = await readFile(join(root, '.desktop-build/shell/package.json'), 'utf8')
+  const version = JSON.parse(originalPackage).version, nextVersion = version.replace(/\d+$/, value => String(Number(value) + 1))
+  let application, logs, userData, corrupt = true, requireCookie = false, restored = 0
+  const server = createServer(async (req, res) => {
+    try {
+      const path = new URL(req.url, 'http://localhost').pathname
+      if (path === '/api/app/bootstrap') {
+        const authenticated = !requireCookie || String(req.headers.cookie).includes('session=upgrade-fixture')
+        if (requireCookie && authenticated) restored++
+        res.setHeader('content-type', 'application/json')
+        res.end(JSON.stringify({ authenticated, csrfToken: 'fixture', user: { role: 'member' }, serverKind: 'yaoyao-web' })); return
+      }
+      if (path.startsWith('/feed/')) {
+        const name = decodeURIComponent(path.slice(6))
+        if (basename(name) !== name) { res.writeHead(404).end(); return }
+        const bytes = corrupt && name.endsWith('.exe') ? Buffer.from('damaged-installer') : await readFile(join(feed, name))
+        res.setHeader('content-length', bytes.length); res.end(bytes); return
+      }
+      res.setHeader('content-type', 'text/html; charset=utf-8'); res.end('<title>升级验收</title><h1>远程工作区</h1>')
+    } catch { res.writeHead(404).end() }
+  })
+  await new Promise(done => server.listen(0, '127.0.0.1', done))
+  const origin = `http://127.0.0.1:${server.address().port}`
+  const shell = join(process.env.SystemRoot, 'System32/WindowsPowerShell/v1.0/powershell.exe')
+  const stopInstalled = async () => {
+    // Only stop this test's executable, never another Yaoyao installation.
+    const literal = executablePath.replaceAll("'", "''")
+    await execute(shell, powershellArguments(`Get-CimInstance Win32_Process | Where-Object { $_.ExecutablePath -eq '${literal}' } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }`), { windowsHide: true }).catch(() => {})
+  }
+  try {
+    await mkdir(home, { recursive: true }); await mkdir(evidence, { recursive: true })
+    const { build, Platform, Arch } = await import('electron-builder')
+    try {
+      await writeFile(join(root, '.desktop-build/release.json'), JSON.stringify({ ...JSON.parse(originalManifest), webVersion: nextVersion }))
+      await writeFile(join(root, '.desktop-build/shell/package.json'), JSON.stringify({ ...JSON.parse(originalPackage), version: nextVersion }))
+      process.env.CSC_IDENTITY_AUTO_DISCOVERY = 'false'
+      await build({ projectDir: root, targets: Platform.WINDOWS.createTarget(['nsis'], Arch.x64), publish: 'never',
+        config: { directories: { output: feed }, forceCodeSigning: false, win: { signExecutable: false } } })
+    } finally {
+      await writeFile(join(root, '.desktop-build/release.json'), originalManifest)
+      await writeFile(join(root, '.desktop-build/shell/package.json'), originalPackage)
+    }
+    await execute(join(output, `Yaoyao-${version}-win-x64-setup.exe`), ['/S', `/D=${installed}`], { timeout: 120000 })
+    console.log('NSIS 安装完成,开始测试隔离更新源')
+    const preferences = { startupChoice: 'remote', remoteServer: origin, backgroundAtLogin: true }
+    await writeFile(join(home, 'desktop-preferences.json'), JSON.stringify(preferences))
+    // This installed test copy alone uses the isolated HTTP update source.
+    await writeFile(join(installed, 'resources/app-update.yml'), JSON.stringify({ provider: 'generic', url: origin + '/feed/', updaterCacheDirName: cacheName }))
+    const launch = () => electron.launch({ executablePath, env: { ...process.env } })
+    application = await launch(); let page = await application.firstWindow(); await page.waitForURL(origin + '/**')
+    logs = await application.evaluate(({ app }) => app.getPath('logs'))
+    userData = await application.evaluate(({ app }) => app.getPath('userData'))
+    assert.equal(await application.evaluate(({ app }) => app.getVersion()), version)
+    await application.evaluate(async ({ session, safeStorage }, { origin, home }) => {
+      await session.defaultSession.cookies.set({ url: origin, name: 'session', value: 'upgrade-fixture', expirationDate: Date.now() / 1000 + 3600 })
+      await session.defaultSession.cookies.flushStore()
+      const fs = process.getBuiltinModule('node:fs')
+      fs.writeFileSync(home + '/upgrade-token.enc', await safeStorage.encryptStringAsync('upgrade-device-identity'))
+    }, { origin, home })
+    requireCookie = true
+    const opened = application.waitForEvent('window'); await page.evaluate(() => window.yaoyaoDesktop.openUpdates())
+    const updates = await opened
+    await expect(updates.locator('#download')).toBeEnabled({ timeout: 30000 })
+    await updates.locator('#download').click()
+    await expect(updates.locator('#error')).toBeVisible({ timeout: 120000 })
+    assert.equal(await updates.evaluate(async () => (await window.yaoyaoUpdate.state()).phase), 'failed')
+    console.log('已拒绝损坏安装包,重试完整下载')
+    corrupt = false
+    await updates.locator('#check').click(); await expect(updates.locator('#download')).toBeEnabled()
+    await updates.locator('#download').click(); await expect(updates.locator('#install')).toBeEnabled({ timeout: 120000 })
+    await updates.screenshot({ path: join(evidence, 'upgrade-ready.png') })
+    console.log('完整更新包已就绪,开始重启替换')
+    const closed = application.waitForEvent('close'); await updates.locator('#install').click().catch(error => { if (!updates.isClosed()) throw error })
+    await closed; application = undefined
+    await expect.poll(async () => readFile(join(installed, 'resources/runtime/release.json'), 'utf8').then(text => JSON.parse(text).webVersion).catch(() => ''),
+      { timeout: 120000 }).toBe(nextVersion)
+    await expect.poll(() => restored, { timeout: 60000 }).toBeGreaterThan(0)
+    console.log('新版本已自动启动,登录 Cookie 保留')
+    await stopInstalled()
+    application = await launch(); page = await application.firstWindow(); await page.waitForURL(origin + '/**')
+    assert.equal(await application.evaluate(({ app }) => app.getVersion()), nextVersion)
+    assert.deepEqual(JSON.parse(await readFile(join(home, 'desktop-preferences.json'), 'utf8')), preferences)
+    assert.equal(await application.evaluate(async ({ safeStorage }, home) => {
+      const fs = process.getBuiltinModule('node:fs'); return (await safeStorage.decryptStringAsync(fs.readFileSync(home + '/upgrade-token.enc'))).result
+    }, home), 'upgrade-device-identity')
+    await page.screenshot({ path: join(evidence, 'upgrade-restored.png') })
+    await application.close(); application = undefined
+    const uninstaller = (await readdir(installed)).find(name => /^Uninstall .*\.exe$/.test(name))
+    assert.ok(uninstaller)
+    await execute(join(installed, uninstaller), ['/S'], { timeout: 120000 })
+    await expect.poll(async () => (await readdir(installed).catch(() => [])).includes('Yaoyao.exe'), { timeout: 30000 }).toBe(false)
+    assert.deepEqual(JSON.parse(await readFile(join(home, 'desktop-preferences.json'), 'utf8')), preferences)
+    await writeFile(join(evidence, 'upgrade.json'), JSON.stringify({ platform: 'win32', from: version, to: nextVersion,
+      installed: true, corruptDownloadRejected: true, nsisReplacement: true, automaticRestart: true,
+      cookieRestored: true, settingsPreserved: true, dpapiPreserved: true, uninstalled: true, dataRetained: true }, null, 2))
+  } catch (error) {
+    for (const [index, page] of (application?.windows() || []).entries()) await page.screenshot({ path: join(evidence, `upgrade-failed-${index}.png`) }).catch(() => {})
+    throw error
+  } finally {
+    await application?.close().catch(() => {}); await stopInstalled()
+    if (logs) await copyFile(join(logs, 'service/server.log'), join(evidence, 'upgrade-main.log')).catch(() => {})
+    server.closeAllConnections(); await new Promise(done => server.close(done))
+    await rm(sandbox, { recursive: true, force: true, maxRetries: 10, retryDelay: 500 })
+    await rm(home, { recursive: true, force: true })
+    if (userData) await rm(userData, { recursive: true, force: true, maxRetries: 10, retryDelay: 500 })
+    await rm(join(process.env.LOCALAPPDATA, cacheName), { recursive: true, force: true }).catch(() => {})
+  }
+})

+ 116 - 0
desktop/windows.test.mjs

@@ -0,0 +1,116 @@
+import { test } from 'node:test'
+import assert from 'node:assert/strict'
+import { mkdtemp, writeFile, readFile, rm, symlink } from 'node:fs/promises'
+import { join } from 'node:path'
+import { tmpdir } from 'node:os'
+import { randomUUID, createHash } from 'node:crypto'
+import { EventEmitter } from 'node:events'
+import { DesktopCredentials } from './credentials.mjs'
+import { DesktopAutoUpdateManager } from './auto-update-manager.mjs'
+import { powershellArguments } from './windows-shell.mjs'
+import { execHostShell } from './host-files.mjs'
+import { windowsFrame, sameWindowsDisplay } from './windows-input.mjs'
+import { FileTransferFiles } from './file-transfer.mjs'
+import { windowsSigningOptions, verifyWindowsArtifacts } from '../scripts/windows-desktop-release.mjs'
+
+test('Windows credentials use the asynchronous OS provider and reject foreign/corrupt ciphertext', async () => {
+  const raw = 'fixture-token', cipher = Buffer.from('opaque-encrypted-value')
+  const store = { isAsyncEncryptionAvailable: async () => true, encryptStringAsync: async value => { assert.equal(value, raw); return cipher },
+    decryptStringAsync: async value => { assert.deepEqual(value, cipher); return { result: raw } } }
+  const credentials = new DesktopCredentials({ home: 'C:\\fixture', platform: 'win32', safeStorage: store })
+  const encrypted = await credentials.encrypt(raw)
+  assert.equal(encrypted.includes(raw), false)
+  assert.equal(await credentials.decrypt(encrypted), raw)
+  await assert.rejects(credentials.decrypt(Buffer.from('YAOYAO-RUNNER-KEYCHAIN-1\ninvalid')), /不属于 Windows/)
+  store.isAsyncEncryptionAvailable = async () => false
+  await assert.rejects(credentials.encrypt(raw), /加密暂不可用/)
+  store.decryptStringAsync = async () => { throw new Error('DPAPI failure') }
+  await assert.rejects(credentials.decrypt(encrypted), /重新登录/)
+})
+test('PowerShell transports quoted Unicode as UTF-16 without shell interpolation', () => {
+  const command = 'Write-Output "你好 $env:USERNAME"; exit 7', args = powershellArguments(command)
+  assert.equal(args.at(-2), '-EncodedCommand')
+  const script = Buffer.from(args.at(-1), 'base64').toString('utf16le')
+  assert.ok(script.includes(command)); assert.match(script, /UTF8Encoding/); assert.match(script, /LASTEXITCODE/)
+})
+test('Windows input invalidates screenshots after DPI, geometry or primary display changes', () => {
+  const d = { id: 1, scaleFactor: 1.5, bounds: { x: 0, y: 0, width: 1280, height: 720 } }
+  const physical = { x: 0, y: 0, width: 1920, height: 1080 }
+  const frame = windowsFrame(d, { width: 1600, height: 900 }, physical)
+  assert.equal(sameWindowsDisplay(frame, d, physical), true)
+  assert.equal(sameWindowsDisplay(frame, { ...d, scaleFactor: 2 }, physical), false)
+  assert.equal(sameWindowsDisplay(frame, { ...d, id: 2 }, physical), false)
+  assert.equal(sameWindowsDisplay(frame, d, { ...physical, width: 2560 }), false)
+})
+test('NSIS installation is explicit and runs exactly once after cleanup', async t => {
+  const driver = new EventEmitter(), events = []
+  driver.checkForUpdates = async () => ({ isUpdateAvailable: true, updateInfo: { version: '1.1.0' } })
+  driver.downloadUpdate = async () => { driver.emit('update-downloaded'); return ['setup.exe'] }
+  driver.quitAndInstall = () => events.push('install')
+  const manager = new DesktopAutoUpdateManager({ driver, platform: 'win32', version: '1.0.0', prepareInstall: async () => events.push('cleanup') })
+  t.after(() => { manager.stopChecking(); clearTimeout(manager.restartTimer) })
+  assert.equal(driver.autoInstallOnAppQuit, false)
+  await manager.check(); await manager.download()
+  assert.equal(manager.snapshot().phase, 'ready'); assert.equal(manager.stagingTimer, undefined)
+  assert.deepEqual(events, [])
+  await manager.install(); await manager.install()
+  assert.deepEqual(events, ['cleanup', 'install'])
+})
+test('NSIS errors before install can retry, while dispatched installs stay fenced', async t => {
+  const driver = new EventEmitter(), manager = new DesktopAutoUpdateManager({ driver, platform: 'win32', version: '1.0.0' })
+  t.after(() => manager.stopChecking())
+  manager.nativeStarted = true; manager.failure(new Error('checksum'))
+  assert.equal(manager.snapshot().retryable, true); assert.equal(manager.nativeStarted, false)
+  manager.nativeStarted = true; manager.installAttempted = true; manager.failure(new Error('installer failed'))
+  assert.equal(manager.snapshot().retryable, false)
+})
+test('signed Windows builds fail closed without a certificate and publisher', async () => {
+  const { validateConfiguration } = await import('app-builder-lib/out/util/config/config.js')
+  const unsigned = windowsSigningOptions({})
+  assert.equal(unsigned.forceCodeSigning, false); assert.equal(unsigned.win.signExecutable, false)
+  await validateConfiguration(unsigned)
+  assert.throws(() => windowsSigningOptions({ YAOYAO_WINDOWS_SIGNED: '1' }), /CSC_LINK/)
+  const result = windowsSigningOptions({ YAOYAO_WINDOWS_SIGNED: '1', CSC_LINK: 'fixture.pfx', YAOYAO_WINDOWS_PUBLISHER: 'Fixture publisher' })
+  assert.equal(result.forceCodeSigning, true); assert.equal(result.win.verifyUpdateCodeSignature, true)
+  assert.equal(result.win.signExecutable, true); assert.equal(result.win.signtoolOptions.publisherName, 'Fixture publisher')
+  await validateConfiguration(result)
+})
+test('Windows artifact verification detects corruption before delivery', async t => {
+  const dir = await mkdtemp(join(tmpdir(), 'yaoyao-win-release-')); t.after(() => rm(dir, { recursive: true, force: true }))
+  const name = 'Yaoyao-1.0.0-win-x64-setup.exe', bytes = Buffer.from('MZ-test-installer')
+  await writeFile(join(dir, name), bytes); await writeFile(join(dir, name + '.blockmap'), 'map')
+  await writeFile(join(dir, 'latest.yml'), JSON.stringify({ version: '1.0.0', files: [{ url: name, size: bytes.length, sha512: createHash('sha512').update(bytes).digest('base64') }] }))
+  await verifyWindowsArtifacts(dir, '1.0.0')
+  assert.match(await readFile(join(dir, 'SHA256SUMS-win-x64.txt'), 'utf8'), /setup\.exe/)
+  await writeFile(join(dir, name), 'corrupt')
+  await assert.rejects(verifyWindowsArtifacts(dir, '1.0.0'), /不匹配/)
+})
+test('native Windows PowerShell preserves Chinese, exit status and cancellation', { skip: process.platform !== 'win32' }, async t => {
+  const root = await mkdtemp(join(tmpdir(), '夭夭-shell-')); t.after(() => rm(root, { recursive: true, force: true }))
+  const result = await execHostShell(root, { command: "[Console]::WriteLine('你好,Windows'); exit 7" })
+  assert.equal(result.stdout.trim(), '你好,Windows'); assert.equal(result.exitCode, 7)
+  const controller = new AbortController()
+  const pending = execHostShell(root, { command: 'Start-Sleep -Seconds 60' }, { signal: controller.signal })
+  setTimeout(() => controller.abort(), 500)
+  assert.equal((await pending).cancelled, true)
+  const childCommand = "$p = Start-Process -FilePath $env:ComSpec -ArgumentList '/c ping -n 60 127.0.0.1 > nul' -WindowStyle Hidden -PassThru; [Console]::WriteLine($p.Id)"
+  for (const wait of [false, true]) {
+    const result = await execHostShell(root, { command: childCommand + (wait ? '; Start-Sleep -Seconds 60' : ''), timeoutMs: 3000 })
+    assert.equal(result.timedOut, wait)
+    const pid = Number(result.stdout.trim()); assert.ok(pid > 0, result.stderr)
+    const alive = await execHostShell(root, { command: `if (Get-Process -Id ${pid} -ErrorAction SilentlyContinue) { exit 1 } else { exit 0 }` })
+    assert.equal(alive.exitCode, 0, 'PowerShell 子进程在结束或超时后必须退出')
+  }
+})
+test('chunked file writes preserve contents and reject directory links outside the root', async t => {
+  const root = await mkdtemp(join(tmpdir(), 'yaoyao-win-files-')), outside = await mkdtemp(join(tmpdir(), 'yaoyao-win-outside-'))
+  const files = new FileTransferFiles(root)
+  t.after(async () => { await files.close(); await rm(root, { recursive: true, force: true }); await rm(outside, { recursive: true, force: true }) })
+  const bytes = Buffer.from('中文附件'), transferId = randomUUID(), path = '中文 文件.txt'
+  await files.call({ op: 'transfer-write-open', transferId, path, maxBytes: 1048576, size: bytes.length, sha256: createHash('sha256').update(bytes).digest('hex'), overwrite: false })
+  await files.call({ op: 'transfer-append', transferId, offset: 0, data: bytes.toString('base64') })
+  await files.call({ op: 'transfer-finish', transferId })
+  assert.equal(await readFile(join(root, path), 'utf8'), '中文附件')
+  await symlink(outside, join(root, 'escape'), process.platform === 'win32' ? 'junction' : 'dir')
+  await assert.rejects(files.path('escape/secret', true), /超出允许范围/)
+})

+ 14 - 0
desktop/windows/CMakeLists.txt

@@ -0,0 +1,14 @@
+cmake_minimum_required(VERSION 3.21)
+project(YaoyaoComputerHelper LANGUAGES CXX)
+if(NOT WIN32 OR NOT MSVC)
+  message(FATAL_ERROR "Build this helper on Windows with MSVC and the Windows 10 SDK")
+endif()
+foreach(target computer-helper computer-helper-dev)
+  add_executable(${target} computer-helper.cpp)
+  target_compile_features(${target} PRIVATE cxx_std_17)
+  target_compile_definitions(${target} PRIVATE UNICODE _UNICODE WIN32_LEAN_AND_MEAN NOMINMAX _WIN32_WINNT=0x0A00)
+  target_compile_options(${target} PRIVATE /W4 /utf-8 /EHsc)
+  set_property(TARGET ${target} PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
+  target_link_libraries(${target} PRIVATE windowsapp user32 advapi32 wtsapi32)
+endforeach()
+target_compile_definitions(computer-helper-dev PRIVATE DEVELOPMENT_HELPER)

+ 214 - 0
desktop/windows/computer-helper.cpp

@@ -0,0 +1,214 @@
+#include <windows.h>
+#include <tlhelp32.h>
+#include <wtsapi32.h>
+#include <winrt/base.h>
+#include <winrt/Windows.Foundation.Collections.h>
+#include <winrt/Windows.Data.Json.h>
+#include <algorithm>
+#include <cmath>
+#include <filesystem>
+#include <iostream>
+#include <map>
+#include <stdexcept>
+#include <string>
+#include <vector>
+
+using winrt::Windows::Data::Json::JsonObject;
+using winrt::Windows::Data::Json::JsonValueType;
+namespace fs = std::filesystem;
+static void require(bool ok, const char* message) { if (!ok) throw std::runtime_error(message); }
+struct Handle {
+  HANDLE value = nullptr;
+  explicit Handle(HANDLE h) : value(h) {}
+  ~Handle() { if (value && value != INVALID_HANDLE_VALUE) CloseHandle(value); }
+  Handle(const Handle&) = delete;
+};
+static std::wstring processPath(HANDLE process) {
+  std::wstring value(32768, L'\0'); DWORD size = static_cast<DWORD>(value.size());
+  require(QueryFullProcessImageNameW(process, 0, value.data(), &size), "无法核对 App 身份");
+  value.resize(size); return fs::weakly_canonical(value).wstring();
+}
+static void checkParent() {
+#ifndef DEVELOPMENT_HELPER
+  Handle snapshot(CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0));
+  require(snapshot.value != INVALID_HANDLE_VALUE, "无法核对 App 身份");
+  PROCESSENTRY32W entry{}; entry.dwSize = sizeof(entry); DWORD parent = 0;
+  if (Process32FirstW(snapshot.value, &entry)) do {
+    if (entry.th32ProcessID == GetCurrentProcessId()) { parent = entry.th32ParentProcessID; break; }
+  } while (Process32NextW(snapshot.value, &entry));
+  Handle process(OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, parent));
+  require(process.value != nullptr, "电脑助手只允许所属 App 调用");
+  auto own = fs::path(processPath(GetCurrentProcess()));
+  auto expected = own.parent_path().parent_path().parent_path() / L"Yaoyao.exe";
+  require(_wcsicmp(processPath(process.value).c_str(), expected.c_str()) == 0, "电脑助手只允许所属 App 调用");
+#endif
+}
+static void checkDesktop() {
+  DWORD session = 0;
+  require(ProcessIdToSessionId(GetCurrentProcessId(), &session), "无法读取 Windows 会话");
+  LPWSTR info = nullptr; DWORD size = 0;
+  require(WTSQuerySessionInformationW(WTS_CURRENT_SERVER_HANDLE, session, WTSConnectState, &info, &size), "无法读取 Windows 会话");
+  bool active = size >= sizeof(WTS_CONNECTSTATE_CLASS) && *reinterpret_cast<WTS_CONNECTSTATE_CLASS*>(info) == WTSActive;
+  WTSFreeMemory(info); require(active, "Windows 会话已断开,请在电脑上重新登录");
+  HDESK desktop = OpenInputDesktop(0, FALSE, DESKTOP_READOBJECTS);
+  require(desktop != nullptr, "Windows 已锁屏或处于安全桌面,请在电脑上恢复后重试");
+  wchar_t name[256]{}; DWORD needed = 0;
+  bool regular = GetUserObjectInformationW(desktop, UOI_NAME, name, sizeof(name), &needed) && _wcsicmp(name, L"Default") == 0;
+  CloseDesktop(desktop);
+  require(regular, "无法控制 Windows 锁屏或 UAC 安全桌面");
+}
+static DWORD integrity(HANDLE process) {
+  HANDLE raw = nullptr; require(OpenProcessToken(process, TOKEN_QUERY, &raw), "无法核对目标窗口权限"); Handle token(raw);
+  DWORD size = 0; GetTokenInformation(token.value, TokenIntegrityLevel, nullptr, 0, &size);
+  std::vector<BYTE> bytes(size);
+  require(size && GetTokenInformation(token.value, TokenIntegrityLevel, bytes.data(), size, &size), "无法核对目标窗口权限");
+  auto label = reinterpret_cast<TOKEN_MANDATORY_LABEL*>(bytes.data());
+  return *GetSidSubAuthority(label->Label.Sid, *GetSidSubAuthorityCount(label->Label.Sid) - 1);
+}
+static void checkWindow(HWND window) {
+  DWORD pid = 0; GetWindowThreadProcessId(window, &pid);
+  if (!pid) return;
+  Handle process(OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid));
+  require(process.value && integrity(process.value) <= integrity(GetCurrentProcess()), "无法操作管理员或受保护窗口,请在电脑上手动操作");
+}
+static void checkForeground() { checkWindow(GetForegroundWindow()); }
+// The non-inheritable job owns PowerShell and every normally spawned child.
+// Killing this helper, timeout, cancellation, or normal completion closes the
+// job and terminates descendants, even when PowerShell has already exited.
+static int runShell(const JsonObject& request) {
+  auto encoded = request.GetNamedString(L"encoded"), cwd = request.GetNamedString(L"cwd");
+  require(encoded.size() > 0 && encoded.size() < 30000, "PowerShell 命令超过长度限制");
+  for (wchar_t ch : encoded) require(iswalnum(ch) || ch == L'+' || ch == L'/' || ch == L'=', "PowerShell 编码无效");
+  wchar_t system[MAX_PATH]{};
+  require(GetSystemDirectoryW(system, MAX_PATH), "无法定位 Windows PowerShell");
+  auto shell = fs::path(system) / L"WindowsPowerShell" / L"v1.0" / L"powershell.exe";
+  std::wstring command = L"\"" + shell.wstring() + L"\" -NoLogo -NoProfile -NonInteractive -OutputFormat Text -EncodedCommand " + std::wstring(encoded);
+  Handle job(CreateJobObjectW(nullptr, nullptr)); require(job.value != nullptr, "无法创建命令进程组");
+  JOBOBJECT_EXTENDED_LIMIT_INFORMATION limits{};
+  limits.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
+  require(SetInformationJobObject(job.value, JobObjectExtendedLimitInformation, &limits, sizeof(limits)), "无法设置命令进程组");
+  STARTUPINFOW startup{}; startup.cb = sizeof(startup); startup.dwFlags = STARTF_USESTDHANDLES;
+  startup.hStdInput = GetStdHandle(STD_INPUT_HANDLE); startup.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE); startup.hStdError = GetStdHandle(STD_ERROR_HANDLE);
+  for (HANDLE handle : {startup.hStdInput, startup.hStdOutput, startup.hStdError})
+    require(SetHandleInformation(handle, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT), "无法连接命令输入输出");
+  PROCESS_INFORMATION created{};
+  require(CreateProcessW(shell.c_str(), command.data(), nullptr, nullptr, TRUE, CREATE_SUSPENDED | CREATE_NO_WINDOW,
+    nullptr, cwd.c_str(), &startup, &created), "无法启动 Windows PowerShell");
+  Handle process(created.hProcess), thread(created.hThread);
+  if (!AssignProcessToJobObject(job.value, process.value)) { TerminateProcess(process.value, 1); throw std::runtime_error("无法接管命令进程组"); }
+  require(ResumeThread(thread.value) != static_cast<DWORD>(-1), "无法启动命令线程");
+  require(WaitForSingleObject(process.value, INFINITE) == WAIT_OBJECT_0, "等待命令失败");
+  DWORD code = 1; require(GetExitCodeProcess(process.value, &code), "无法读取命令退出码");
+  return static_cast<int>(code);
+}
+static double number(const JsonObject& object, const wchar_t* key) {
+  require(object.HasKey(key) && object.GetNamedValue(key).ValueType() == JsonValueType::Number, "电脑输入缺少数值参数");
+  double value = object.GetNamedNumber(key); require(std::isfinite(value), "电脑输入数值无效"); return value;
+}
+static int integer(const JsonObject& object, const wchar_t* key, int fallback, int low, int high) {
+  double value = object.HasKey(key) ? number(object, key) : fallback;
+  require(value >= low && value <= high && std::floor(value) == value, "电脑输入参数超出范围"); return static_cast<int>(value);
+}
+static void send(std::vector<INPUT> events) {
+  checkDesktop(); checkForeground();
+  require(SendInput(static_cast<UINT>(events.size()), events.data(), sizeof(INPUT)) == events.size(), "Windows 未接受输入,请检查目标窗口权限");
+}
+static INPUT key(WORD code, bool up, bool unicode = false) {
+  INPUT input{}; input.type = INPUT_KEYBOARD;
+  input.ki.wVk = unicode ? 0 : code; input.ki.wScan = unicode ? code : 0;
+  input.ki.dwFlags = (unicode ? KEYEVENTF_UNICODE : 0) | (up ? KEYEVENTF_KEYUP : 0);
+  if (!unicode && (code == VK_DELETE || code == VK_HOME || code == VK_END || code == VK_PRIOR || code == VK_NEXT || (code >= VK_LEFT && code <= VK_DOWN))) input.ki.dwFlags |= KEYEVENTF_EXTENDEDKEY;
+  return input;
+}
+static INPUT mouse(DWORD flags, LONG x = 0, LONG y = 0, DWORD data = 0) {
+  INPUT input{}; input.type = INPUT_MOUSE; input.mi.dx = x; input.mi.dy = y; input.mi.dwFlags = flags; input.mi.mouseData = data; return input;
+}
+static POINT point(const JsonObject& action, const JsonObject& frame, const wchar_t* xKey, const wchar_t* yKey) {
+  double width = number(frame, L"width"), height = number(frame, L"height");
+  double x = number(action, xKey), y = number(action, yKey);
+  require(width > 0 && height > 0 && x >= 0 && y >= 0 && x < width && y < height, "输入超出当前画面");
+  auto bounds = frame.GetNamedObject(L"physicalBounds");
+  double bx = number(bounds, L"x"), by = number(bounds, L"y"), bw = number(bounds, L"width"), bh = number(bounds, L"height");
+  require(bx == 0 && by == 0 && bw == GetSystemMetrics(SM_CXSCREEN) && bh == GetSystemMetrics(SM_CYSCREEN), "显示器已变化,请刷新画面");
+  return {static_cast<LONG>(bx + x * bw / width), static_cast<LONG>(by + y * bh / height)};
+}
+static INPUT move(POINT p) {
+  LONG width = GetSystemMetrics(SM_CXVIRTUALSCREEN), height = GetSystemMetrics(SM_CYVIRTUALSCREEN);
+  require(width > 1 && height > 1, "显示器不可用");
+  LONG x = static_cast<LONG>(std::llround((p.x - GetSystemMetrics(SM_XVIRTUALSCREEN)) * 65535.0 / (width - 1)));
+  LONG y = static_cast<LONG>(std::llround((p.y - GetSystemMetrics(SM_YVIRTUALSCREEN)) * 65535.0 / (height - 1)));
+  return mouse(MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_VIRTUALDESK, x, y);
+}
+static void input(const JsonObject& request) {
+  auto action = request.GetNamedObject(L"action"), frame = request.GetNamedObject(L"frame");
+  auto kind = action.GetNamedString(L"kind");
+  if (kind == L"click") {
+    auto p = point(action, frame, L"x", L"y"); auto button = action.GetNamedString(L"button", L"left");
+    checkWindow(GetAncestor(WindowFromPoint(p), GA_ROOT));
+    require(button == L"left" || button == L"right" || button == L"middle", "鼠标按键无效");
+    DWORD down = button == L"right" ? MOUSEEVENTF_RIGHTDOWN : button == L"middle" ? MOUSEEVENTF_MIDDLEDOWN : MOUSEEVENTF_LEFTDOWN;
+    DWORD up = button == L"right" ? MOUSEEVENTF_RIGHTUP : button == L"middle" ? MOUSEEVENTF_MIDDLEUP : MOUSEEVENTF_LEFTUP;
+    int count = integer(action, L"count", 1, 1, 2);
+    send({move(p)}); checkForeground();
+    for (int i = 0; i < count; ++i) { send({mouse(down), mouse(up)}); Sleep(50); }
+  } else if (kind == L"drag") {
+    auto start = point(action, frame, L"fromX", L"fromY"), end = point(action, frame, L"toX", L"toY");
+    checkWindow(GetAncestor(WindowFromPoint(start), GA_ROOT));
+    checkWindow(GetAncestor(WindowFromPoint(end), GA_ROOT));
+    send({move(start), mouse(MOUSEEVENTF_LEFTDOWN)});
+    try { for (int i = 1; i <= 12; ++i) { send({move({start.x + (end.x - start.x) * i / 12, start.y + (end.y - start.y) * i / 12})}); Sleep(12); } }
+    catch (...) { auto up = mouse(MOUSEEVENTF_LEFTUP); SendInput(1, &up, sizeof(INPUT)); throw; }
+    send({mouse(MOUSEEVENTF_LEFTUP)});
+  } else if (kind == L"text") {
+    auto text = action.GetNamedString(L"text"); require(text.size() <= 16000, "输入文本过长");
+    std::vector<INPUT> events;
+    for (wchar_t character : text) { events.push_back(key(character, false, true)); events.push_back(key(character, true, true)); }
+    if (!events.empty()) send(events);
+  } else if (kind == L"key") {
+    const std::map<std::wstring, WORD> keys = {{L"Return", VK_RETURN}, {L"Enter", VK_RETURN}, {L"Tab", VK_TAB}, {L"Space", VK_SPACE}, {L"space", VK_SPACE},
+      {L"BackSpace", VK_BACK}, {L"Backspace", VK_BACK}, {L"Escape", VK_ESCAPE}, {L"Delete", VK_DELETE}, {L"Home", VK_HOME}, {L"End", VK_END},
+      {L"PageUp", VK_PRIOR}, {L"PageDown", VK_NEXT}, {L"Left", VK_LEFT}, {L"Right", VK_RIGHT}, {L"Up", VK_UP}, {L"Down", VK_DOWN}};
+    std::wstring name(action.GetNamedString(L"key")); WORD code = 0;
+    auto found = keys.find(name);
+    if (found != keys.end()) code = found->second;
+    else if (name.size() == 1 && ((name[0] >= L'a' && name[0] <= L'z') || (name[0] >= L'A' && name[0] <= L'Z') || (name[0] >= L'0' && name[0] <= L'9'))) code = static_cast<WORD>(towupper(name[0]));
+    require(code != 0, "暂不支持这个按键");
+    std::vector<WORD> modifiers; std::vector<INPUT> events;
+    if (action.HasKey(L"modifiers")) for (const auto& value : action.GetNamedArray(L"modifiers")) {
+      auto modifier = value.GetString(); WORD m = modifier == L"ctrl" ? VK_CONTROL : modifier == L"alt" ? VK_MENU : modifier == L"shift" ? VK_SHIFT : modifier == L"super" ? VK_LWIN : 0;
+      require(m != 0, "按键修饰符无效"); if (std::find(modifiers.begin(), modifiers.end(), m) == modifiers.end()) modifiers.push_back(m);
+    }
+    for (WORD m : modifiers) events.push_back(key(m, false));
+    events.push_back(key(code, false)); events.push_back(key(code, true));
+    for (auto m = modifiers.rbegin(); m != modifiers.rend(); ++m) events.push_back(key(*m, true));
+    send(events);
+  } else if (kind == L"scroll") {
+    auto direction = action.GetNamedString(L"direction"); int amount = integer(action, L"amount", 3, 1, 50) * WHEEL_DELTA;
+    require(direction == L"up" || direction == L"down" || direction == L"left" || direction == L"right", "滚动方向无效");
+    if (direction == L"down" || direction == L"left") amount = -amount;
+    send({mouse(direction == L"up" || direction == L"down" ? MOUSEEVENTF_WHEEL : MOUSEEVENTF_HWHEEL, 0, 0, static_cast<DWORD>(amount))});
+  } else throw std::runtime_error("电脑操作无效");
+}
+int main(int argc, char** argv) {
+  try {
+    winrt::init_apartment();
+    SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);
+    if (argc == 2 && std::string(argv[1]) == "--self-test") {
+      auto value = JsonObject::Parse(L"{\"count\":2,\"text\":\"中文\"}");
+      require(integer(value, L"count", 1, 1, 2) == 2 && value.GetNamedString(L"text") == L"中文", "JSON 自检失败");
+      std::cout << "{\"ok\":true}"; return 0;
+    }
+    checkParent();
+    std::string bytes; char chunk[4096];
+    while (std::cin.read(chunk, sizeof(chunk)) || std::cin.gcount()) { bytes.append(chunk, static_cast<size_t>(std::cin.gcount())); require(bytes.size() <= 131072, "电脑输入过长"); }
+    auto request = JsonObject::Parse(winrt::to_hstring(bytes));
+    if (argc == 2 && std::string(argv[1]) == "--shell") return runShell(request);
+    checkDesktop();
+    auto operation = request.GetNamedString(L"operation", L"input");
+    if (operation == L"release-drag") { auto up = mouse(MOUSEEVENTF_LEFTUP); SendInput(1, &up, sizeof(INPUT)); }
+    else if (operation != L"probe") input(request);
+    std::cout << "{\"ok\":true}"; return 0;
+  } catch (const winrt::hresult_error&) { std::cerr << "电脑输入格式无效或 Windows 组件不可用\n"; }
+    catch (const std::exception& error) { std::cerr << error.what() << '\n'; }
+  return 1;
+}

+ 1 - 1
docker.env.example

@@ -3,7 +3,7 @@ HERMES_YAOYAO_BIND_ADDRESS=127.0.0.1
 HERMES_YAOYAO_PUBLISHED_PORT=15300
 # 远程通用镜像支持 AMD64 / ARM64;每次发布更新 latest 并保留旧版本标签。
 # HERMES_YAOYAO_IMAGE=samienluo/yaoyao:latest
-# 固定版本:samienluo/yaoyao:v0.4.70;仅 AMD64:samienluo/yaoyao:v0.4.70-amd。
+# 固定版本:samienluo/yaoyao:v0.4.71;仅 AMD64:samienluo/yaoyao:v0.4.71-amd。
 # 留空时使用本地构建名称 yaoyao:local。
 # YAOYAO_DESKTOP_IMAGE=hermes-yaoyao-desktop:0.4.0
 # Cursor Universal 兼容桌面的本地构建名称;基础镜像在 deploy/computer/Dockerfile.cursor 中固定。

+ 7 - 5
docs/desktop-hosts.md

@@ -1,6 +1,6 @@
 # 服务器与电脑
 
-一台服务器集中运行 Web(15300)与 Hermes(9119),其他 Mac 安装夭夭 App 后作为“电脑”出站连接服务器,向服务器上的 Bot 提供自己的真实桌面(截图、键鼠、独立浏览器)。产品中只用两种名称:运行服务的一端叫“服务器”,连接服务器的 Mac 叫“电脑”。服务器自己机器上的 App 继续走本机回环通道,内部编号为 `local`。
+一台服务器集中运行 Web(15300)与 Hermes(9119),其他 Mac 或 Windows 电脑安装夭夭 App 后作为“电脑”出站连接服务器,向服务器上的 Bot 提供自己的真实桌面(截图、键鼠、独立浏览器)。产品中只用两种名称:运行服务的一端叫“服务器”,连接服务器的设备叫“电脑”。服务器自己机器上的 App 继续走本机回环通道,内部编号为 `local`。
 
 ## 服务端执行与统一权限
 
@@ -16,6 +16,8 @@
 - **Hermes 原生工具**:原生终端和文件工具始终操作服务器,与消息来源无关;访问来源客户端应使用 `desktop_*`。全局服务器电脑开关控制 desktop 适配器,旧 `denyServerTools` 字段停用,不再展示未接入的封禁开关。
 - **接管界面**:`/api/app/agents/:id/computer` 系列接受 `backend=desktop|cloud|vm`,桌面可附带 `host`。界面显式选择目标。此处的 `host=local` 是历史 API 的服务器编号,不等于 Bot 工具中随消息变化的别名。
 
+Windows 客户端的构建、未签名安装包和验收记录见 [Windows 客户端](windows-client.md)。Windows 首次启动直接连接服务器,仅支持客户端模式;以下双模式选择与本机服务器说明仅适用于 Mac。
+
 ## 启用流程
 
 1. 在那台 Mac 上启动夭夭 App。**首次启动会询问这台 Mac 的使用方式:「连接服务器(客户端)」或「作为服务器运行」,默认选择客户端**。
@@ -30,10 +32,10 @@
 
 ## 文件与命令(全面操作)
 
-屏幕授权之外是独立的第二档授权「文件与命令」:电脑面板直接提供「授权文件与命令」按钮,无需先完成屏幕授权,Mac 端弹窗单独确认。授权后该账号下所有机器人获得四个工具:
+屏幕授权之外是独立的第二档授权「文件与命令」:电脑面板直接提供「授权文件与命令」按钮,无需先完成屏幕授权,桌面端弹窗单独确认。授权后该账号下所有机器人获得四个工具:
 
-- `desktop_file_list` / `desktop_file_read` / `desktop_file_write`:在这台 Mac 的**用户主目录**范围内列目录、读文件(≤12MB)和写文件(≤10MB);`..`、绝对路径越界和符号链接逃逸都会被拒绝,TCC 保护目录仍按系统权限处理。
-- `desktop_shell`:在主目录执行一条 zsh 命令(最长 120 秒,stdout/stderr 各截断 512KB,超时终止并如实报告)。
+- `desktop_file_list` / `desktop_file_read` / `desktop_file_write`:在这台电脑的**用户主目录**范围内列目录、读文件(≤12MB)和写文件(≤10MB);`..`、绝对路径越界和符号链接逃逸都会被拒绝,TCC 保护目录仍按系统权限处理。
+- `desktop_shell`:在主目录执行一条命令(Mac 使用 zsh,Windows 使用系统 Windows PowerShell)(最长 120 秒,stdout/stderr 各截断 512KB,超时终止并如实报告)。命令按当前系统用户权限执行,不受文件工具主目录边界限制。
 
 两档授权分别记录(`approved` 与 `approvedFull`),「撤销本机控制授权」同时清除;工具目录按账号下可用设备的授权汇总,且每次调用在服务端二次校验。
 
@@ -47,7 +49,7 @@
 
 ## 范围
 
-- 物理机控制仅支持 macOS(屏幕录制、辅助功能与 computer-helper 签名校验均为 macOS 专属)。
+- 物理机控制支持 macOS 和 Windows 10/11 x64。Mac 仍需屏幕录制、辅助功能授权;Windows 检查截图与原生输入助手,拒绝锁屏、安全桌面、断开的会话和高权限窗口,不自动提权。Windows 不托管本机服务器、Hermes、Runner 或虚拟机;服务器提供的功能仍可使用。
 - 本功能只提供真实桌面与独立浏览器环境;远程机器上的 Linux 虚拟桌面(无 Hermes 电脑节点)不在本范围。
 - 服务器侧 Bot 会话、模型与记忆全部留在服务器的 Hermes;卫星机不安装 Hermes。
 

+ 7 - 7
docs/docker-install.md

@@ -12,14 +12,14 @@
 
 | 标签 | 架构 |
 | --- | --- |
-| `v0.4.70-amd` | `linux/amd64` |
-| `v0.4.70` | `linux/amd64`、`linux/arm64`,拉取时自动匹配 |
-| `latest` | 最新稳定通用镜像,当前指向与 `v0.4.70` 相同的镜像 |
+| `v0.4.71-amd` | `linux/amd64` |
+| `v0.4.71` | `linux/amd64`、`linux/arm64`,拉取时自动匹配 |
+| `latest` | 最新稳定通用镜像,当前指向与 `v0.4.71` 相同的镜像 |
 
 ```sh
-docker pull samienluo/yaoyao:v0.4.70
+docker pull samienluo/yaoyao:v0.4.71
 # 需要固定 AMD64 时:
-docker pull samienluo/yaoyao:v0.4.70-amd
+docker pull samienluo/yaoyao:v0.4.71-amd
 ```
 
 每次新版本发布都会更新 `latest`,旧版本标签继续保留。需要固定部署版本时使用具体版本标签。
@@ -34,7 +34,7 @@ cp docker.env.example docker.env
 
 | 配置 | 用途 |
 | --- | --- |
-| `HERMES_YAOYAO_IMAGE` | 远程镜像可设为 `samienluo/yaoyao:v0.4.70` 或 `samienluo/yaoyao:latest`;未设置时使用本地构建名称 |
+| `HERMES_YAOYAO_IMAGE` | 远程镜像可设为 `samienluo/yaoyao:v0.4.71` 或 `samienluo/yaoyao:latest`;未设置时使用本地构建名称 |
 | `HERMES_YAOYAO_UPSTREAM` | Hermes 上游地址,默认 `http://host.docker.internal:9119` |
 | `HERMES_YAOYAO_BIND_ADDRESS` | Web 的宿主机发布地址,默认 `127.0.0.1`;局域网访问可设为 `0.0.0.0` |
 | `HERMES_YAOYAO_PUBLISHED_PORT` | 宿主机 Web 端口,默认 `15300` |
@@ -211,7 +211,7 @@ curl --fail http://127.0.0.1:15300/healthz
 使用 Docker Hub 发布镜像时,在 `docker.env` 设置:
 
 ```dotenv
-HERMES_YAOYAO_IMAGE=samienluo/yaoyao:v0.4.70
+HERMES_YAOYAO_IMAGE=samienluo/yaoyao:v0.4.71
 YAOYAO_CURSOR_DESKTOP_IMAGE=samienluo/yaoyao-desktop:v0.4.12-cursor-amd
 ```
 

+ 4 - 0
docs/release-process.md

@@ -29,6 +29,10 @@ macOS 新版本默认使用 Developer ID Application 正式分发签名、Apple
 
 既有手动安装版客户端需先手动安装一次正式包,之后才能使用“下载更新 → 重启更新”。发布前应使用同一签名身份的两个版本,在隔离机器上验证实际替换与重新启动;单元测试或未签名包的打包成功不能代替这项验收。
 
+### Windows 测试安装包
+
+Windows 原生助手和安装包在 Windows x64 环境从同一发布提交构建,并验证安装、启动和升级。未配置正式证书时须标为未签名测试版;经用户选择交付后,Release 可提供 EXE 与独立测试元数据 ZIP,但不在 Release 根目录上传 Windows `latest.yml`。元数据包含同次构建的更新清单、blockmap、校验值和构建身份。Windows Server CI 与 Windows 10/11 真机验收结果分别说明。
+
 ## Docker Hub 远程镜像
 
 固定仓库为 `samienluo/yaoyao`。以每次发布的 `vX.Y.Z` 为版本标签:

+ 47 - 0
docs/releases/v0.4.71.md

@@ -0,0 +1,47 @@
+# 夭夭 AI v0.4.71
+
+本次发布 Web、macOS Apple Silicon 正式桌面版、Windows x64 未签名测试客户端和 Docker 双架构镜像,不提供 APK。
+
+## 更新内容
+
+- 改善断网、页面切回前台和服务器短暂不可达后的自动恢复,重新同步会话、运行状态与待审批内容,避免重复发送消息。
+- 修复实时事件重连后的补发与游标处理,检测遗漏消息并恢复完整记录,避免界面停留在过期状态。
+- 改善工具授权续期和上游连接恢复:临时网络故障在原授权有效期内重试,明确失效或撤销的授权仍会终止。
+- 新增 Windows 10/11 x64 客户端,可连接已有夭夭服务器,支持聊天、电脑授权、主屏截图与键鼠控制、独立浏览器,以及授权后的文件和命令操作。
+- 完善跨平台设备识别、路径边界、命令取消与子进程清理,以及登录、托盘、退出和更新行为。
+
+## 升级说明
+
+- 升级前备份完整 `.yaoyao` 数据目录,建议先更新服务端,再更新桌面客户端。
+- macOS 桌面使用 Developer ID Application 正式分发签名及 Apple 公证,提供完整自动更新附件;已安装正式签名版的用户可使用“下载更新 → 重启更新”,历史开发签名版请先手动安装正式 DMG。
+- Windows 为未签名测试客户端,可能提示未知发布者;安装到当前用户目录,连接已有服务器,不托管本机服务。Windows 电脑操作需要本次配套服务端支持。
+- Windows 测试更新清单随独立元数据压缩包提供,不写入正式自动更新源。Windows Server CI 验证结果与尚未完成的 Windows 10/11 真机项目分别列出,详见 [客户端说明](../windows-client.md)。
+- 本次不构建、不上传 APK,旧版本标签和附件继续保留。
+- 主项目采用 Apache-2.0,第三方组件保留各自许可与署名。
+
+## 下载
+
+- `Yaoyao-0.4.71-arm64.dmg`:macOS Apple Silicon 首次安装或手动更新。
+- `Yaoyao-0.4.71-arm64.zip`、DMG 与 ZIP 对应的 `.blockmap`、`latest-mac.yml`:macOS 自动更新载荷与清单。
+- `Yaoyao-0.4.71-win-x64-setup.exe`:Windows x64 未签名测试安装包。
+- `Yaoyao-0.4.71-windows-test-metadata.zip`:Windows 测试更新清单、差分文件、构建身份、说明及校验值;解压后与安装包放在同一目录使用。
+- `Yaoyao-0.4.71-source.tar.gz`:Web/桌面源码及部署配置。
+- `SHA256SUMS.txt`:发布附件的 SHA-256 校验值。
+
+## Docker Hub
+
+| 镜像 | 架构 |
+| --- | --- |
+| `samienluo/yaoyao:v0.4.71-amd` | `linux/amd64` |
+| `samienluo/yaoyao:v0.4.71` | `linux/amd64`、`linux/arm64` |
+| `samienluo/yaoyao:latest` | 验证后更新为同一通用镜像 |
+
+```sh
+docker pull samienluo/yaoyao:v0.4.71
+docker compose --env-file docker.env pull web
+docker compose --env-file docker.env up -d --no-build web
+```
+
+Compose 中设置 `HERMES_YAOYAO_IMAGE=samienluo/yaoyao:v0.4.71`。镜像发布到 Docker Hub,GitHub 提供安装及更新附件、源码和校验文件。
+
+附件摘要、镜像摘要与实际验证结果见 [GitHub 发布页](https://github.com/Lsamien/yaoyao/releases/tag/v0.4.71)。

+ 60 - 0
docs/verification/windows-client-2026-09-22/README.md

@@ -0,0 +1,60 @@
+# Windows 客户端验证
+
+版本:0.4.70。目标为 Windows 10/11 x64 客户端;Windows 不托管本机服务器、Hermes、Runner 或虚拟机。交换协议保持版本 1,无数据库迁移。
+
+## Mac 回归
+
+在 Mac 开发环境执行并通过:
+
+- `npm run typecheck`。
+- `npm run desktop:build`,包含生产界面、Mac 桌面资源和 Swift 助手。
+- 服务端 `desktopEnvironments`、`desktopHosts`、`fileTransfer`:75 项。
+- 桌面平台、模式、登录、凭据、路径、文件传输、更新生命周期等相关单元测试。仅依赖 Windows 的原生命令测试在 Mac 跳过,在 Windows CI 运行。
+- Electron 界面回归:首次启动和远程登录、客户端/服务器双向切换、远程及本地重启更新、更新失败恢复;5 项通过。启动反馈与电脑接管窗口也通过初轮回归。
+- Mac 原生更新器代理下载、签名拒绝和等待系统准备完成:2 项通过。
+- 独立 Chromium 标签页、截图与持久会话隔离;本机服务启动、关窗驻留、故障恢复和退出清理:2 项通过。
+
+## Windows 自动化验收
+
+GitHub Actions 使用 Windows Server 2022 x64、Node 24、锁定的 npm 依赖、MSVC/CMake 和 Windows SDK。该环境与 Windows 10/11 真机矩阵分别记录。
+
+工作流:[Windows client](https://github.com/Lsamien/yaoyao/actions/workflows/windows-client.yml)。安装包只交付 Actions artifact,没有发布正式 Release。
+
+已在 Windows CI 实测通过:63 项桌面测试及 58 项服务端测试。打包后的客户端连接本地测试登录服务,验证了管理员登录流程、DPAPI 加密、会话恢复、仅客户端模式、托盘关窗;原生助手验证了 PowerShell 中文输出、退出码、超时、取消与子进程清理。当前交互桌面在 100% 缩放下验证了截图、点击、中文/emoji 输入、Ctrl+A、显示变化作废截图、撤销授权,以及独立浏览器截图与 Cookie 隔离。
+
+最终运行:[35750511967,全流程通过](https://github.com/Lsamien/yaoyao/actions/runs/35750511967)。CI 源码提交为 `4dc2d8b356649291faa2954f32a4558b04bc8c60`,对应本地代码提交 `0edcc1f`。验证时间为 2026-09-22,记录归档于 2026-09-23,系统版本 Windows Server 2022 / `10.0.20348`。
+
+| 验证 | 结果 |
+| --- | --- |
+| 类型检查、生产构建、原生助手编译 | 通过;助手使用静态 MSVC 运行时 |
+| 安装包结构、EXE、blockmap、更新清单及摘要 | 通过;客户端 ASAR 不含项目 `node_modules` |
+| 桌面测试 / 服务端测试 | 63 / 58 项全部通过 |
+| NSIS 当前用户安装 | 通过 |
+| 隔离源损坏包拒绝及重新下载 | 通过 |
+| 0.4.70 → 临时 0.4.71 的实际文件替换 | 通过 |
+| 升级后自动重启、登录 Cookie、设置及 DPAPI 数据 | 通过;使用正常用户数据目录 |
+| 卸载与应用配置保留 | 通过 |
+
+安装升级测试另外 1 项通过,临时 0.4.71 仅用于验证,未发布。隔离更新源未提供旧版 blockmap,本次验证了回退到完整下载后的真实升级;差分下载尚未实测。当前用户安装与升级在一次性 CI 账号中执行,不代表普通用户权限和所有 Windows 10/11 环境均已验收。
+
+交付:[未签名 Windows 安装包及更新文件](https://github.com/Lsamien/yaoyao/actions/runs/35750511967/artifacts/10705091432),[测试证据](https://github.com/Lsamien/yaoyao/actions/runs/35750511967/artifacts/10705211454)。本目录 `evidence` 保存对应 JSON、截图及更新日志。Actions artifacts 保留至 2026-12-21;下载可能需要登录 GitHub。
+
+EXE 文件名为 `Yaoyao-0.4.70-win-x64-setup.exe`,SHA-256:
+
+```text
+25010f11c7f46c15863090887b933205c1c8076f4c5816c80da6c0307819f1d6
+```
+
+完整 [文件校验清单](evidence/SHA256SUMS-win-x64.txt) 取自上述构建日志,与安装包内清单对应。安装包 artifact ZIP 的 SHA-256 为 `1129c806d1d7d0f5f1caabeb5fec252940dc10a2cc56ba5ff22221e02ac96ec4`;测试证据 ZIP 的 SHA-256 为 `ed6950df17a79bd9a8369ce72cf8617db8f4c90b6206a7dcbc4f4902fe6a1bb2`,归档证据下载后已核对。
+
+## 尚需 Windows 10/11 真机验收
+
+以下项目没有可用的 Windows 10/11 真机记录,状态为 **未验证**:
+
+- 干净 Windows 10、Windows 11 普通用户安装;中文 Windows 用户名;登录启动与实际用户登录。
+- 100%、150%、200% 缩放及多显示器切主屏;双击、拖拽、滚动、Alt/Win 组合键。
+- 原生授权对话框的允许与拒绝;人工接管、锁屏、RDP 断开、UAC 安全桌面、高权限窗口拒绝。
+- 与真实夭夭服务器端到端联调:管理员与普通账号、过期会话、更换服务器、断网重连、真实双向文件传输和远程电脑面板。
+- Windows 10/11 上实际升级失败后的恢复、签名发布流程及正式证书校验。
+
+完整操作步骤见 [Windows 客户端说明](../../windows-client.md)。CI 编译或 Windows Server 上的功能测试不替代以上验收。

+ 3 - 0
docs/verification/windows-client-2026-09-22/evidence/SHA256SUMS-win-x64.txt

@@ -0,0 +1,3 @@
+25010f11c7f46c15863090887b933205c1c8076f4c5816c80da6c0307819f1d6  Yaoyao-0.4.70-win-x64-setup.exe
+7e86699fcf41c3a9ea01aa94748db05c72fe54108fac3a534a4b44609511590f  Yaoyao-0.4.70-win-x64-setup.exe.blockmap
+0cd4ac712b77a985badd61999e3858b942a7da9fad77c900c9208ac08020f49d  latest.yml

TEMPAT SAMPAH
docs/verification/windows-client-2026-09-22/evidence/remote-login.png


+ 19 - 0
docs/verification/windows-client-2026-09-22/evidence/smoke.json

@@ -0,0 +1,19 @@
+{
+  "platform": "win32",
+  "login": true,
+  "encryptedPairing": true,
+  "sessionRestored": true,
+  "clientOnly": true,
+  "native": {
+    "shell": true,
+    "isolatedBrowser": true,
+    "screenshot": true,
+    "click": true,
+    "unicodeInput": true,
+    "ctrlA": true,
+    "displayInvalidation": true,
+    "revoked": true,
+    "scaleFactor": 1
+  },
+  "windows10and11Matrix": "requires Windows 10/11 acceptance; CI runs Windows Server 2022"
+}

TEMPAT SAMPAH
docs/verification/windows-client-2026-09-22/evidence/upgrade-ready.png


TEMPAT SAMPAH
docs/verification/windows-client-2026-09-22/evidence/upgrade-restored.png


+ 14 - 0
docs/verification/windows-client-2026-09-22/evidence/upgrade.json

@@ -0,0 +1,14 @@
+{
+  "platform": "win32",
+  "from": "0.4.70",
+  "to": "0.4.71",
+  "installed": true,
+  "corruptDownloadRejected": true,
+  "nsisReplacement": true,
+  "automaticRestart": true,
+  "cookieRestored": true,
+  "settingsPreserved": true,
+  "dpapiPreserved": true,
+  "uninstalled": true,
+  "dataRetained": true
+}

+ 57 - 0
docs/windows-client.md

@@ -0,0 +1,57 @@
+# Windows 客户端
+
+Windows 首版支持 Windows 10/11 x64,安装后连接已有夭夭服务器。聊天、团队、文件库和服务器上的电脑环境沿用服务器功能;当前 Windows 客户端不托管本机 Web、Hermes、Runner 或虚拟机。用户无需安装 Node、Python 或开发工具。
+
+## 使用
+
+1. 安装 `Yaoyao-<版本>-win-x64-setup.exe`,填写服务器地址并登录。测试包未签名,Windows 可能显示未知发布者。安装在当前用户目录,不申请管理员权限。
+2. 管理员登录后会注册这台电脑;普通账号可登录聊天。屏幕控制与文件、命令分别在本机确认授权,可从“电脑”菜单重新授权、导入配置或断开,也可从应用菜单撤销本机授权。
+3. Windows 电脑控制需要配套升级服务器。旧服务器仍可用于聊天;电脑菜单状态会提示升级要求。新版服务器继续支持现有 Mac 客户端。
+4. 截图与键鼠操作面向当前交互会话的主屏。锁屏、会话断开、UAC 安全桌面和高于客户端权限的窗口不能由普通权限客户端控制;在电脑上恢复会话或手动处理受保护操作。
+5. 文件工具限定在用户主目录,拒绝越界、目录联接逃逸、设备路径、UNC 和 NTFS 备用数据流。命令使用 Windows PowerShell,按当前 Windows 用户权限执行,**不受文件工具根目录约束**;命令最长 120 秒,两路输出分别截断至 512 KiB。原生助手使用 Windows Job Object 管理 PowerShell 及其普通子进程,命令结束、超时或撤销时一起清理。
+6. 关闭窗口保留托盘连接;“退出夭夭”断开设备、结束应用自有操作。登录启动默认关闭,开启后可选择仅驻留托盘。更新和卸载默认保留用户数据。
+
+配置与设备令牌位于 `%USERPROFILE%\.yaoyao`(可由既有数据目录环境变量指定),Chromium 会话、浏览器和设备授权位于 Electron `userData`。令牌由当前 Windows 账号的 DPAPI 加密,密码不落盘。复制 Mac 加密文件不能迁移登录,应在 Windows 重新登录授权。
+
+## 构建与安装包
+
+v0.4.71 发布页提供未签名测试 EXE 与独立的测试更新元数据压缩包。元数据包包含 `latest.yml`、blockmap、构建身份与校验值,解压后与 EXE 放在同一目录使用;GitHub Release 根目录不提供 Windows `latest.yml`,测试包不进入正式自动更新源。
+
+日常可以在 Mac 修改共享代码;原生助手和 EXE 安装包在 Windows x64 上构建。需要 Node 24、CMake、Visual Studio 2022 C++ 工具链和 Windows SDK;GitHub Actions `windows-2022` 提供该构建环境。
+
+```powershell
+npm ci
+npm run desktop:pack:win
+npm run desktop:test:win
+```
+
+GitHub Actions 工作流 `Windows client` 支持手动触发、相关 PR 和 `codex/windows-client*` 分支。CI 只上传 artifacts,不发布正式 Release。下载 `yaoyao-windows-x64-unsigned`,其中包含 EXE、blockmap、`latest.yml`、`SHA256SUMS-win-x64.txt` 和构建身份。生成目录为 `desktop-release/windows-x64`。
+
+安装前在下载目录用 PowerShell 核对校验值,EXE 的 SHA-256 应与清单中同名文件一致:
+
+```powershell
+Get-ChildItem *.exe | Get-FileHash -Algorithm SHA256
+Get-Content .\SHA256SUMS-win-x64.txt
+```
+
+默认构建为未签名测试包。正式签名构建设置 `YAOYAO_WINDOWS_SIGNED=1`、`CSC_LINK`、适用的 `CSC_KEY_PASSWORD` 和证书对应的 `YAOYAO_WINDOWS_PUBLISHER`;凭据仅通过 CI secret 或本机环境注入。正式构建强制签名和更新签名校验。
+
+Windows 更新使用 NSIS,只有用户点击“重启更新”才安装,先清理设备连接和自有操作。Windows 使用 `latest.yml`,Mac 继续使用 `latest-mac.yml`。更新附件必须来自同一次构建,并在清单引用的安装包和差分文件齐备后发布;测试包不写入正式更新源。
+
+## 验证记录与人工验收
+
+自动测试覆盖平台模式、路径边界、凭据提供器、更新状态、设备权限与来源路由。Windows CI 另外编译并自检原生助手,测试真实 PowerShell 及子进程清理,以及打包应用的登录、DPAPI 配置保存、会话恢复、菜单与托盘行为。交互会话可用时,测试原生截图、点击、中文/emoji 输入、组合键、显示变化、授权撤销及独立浏览器。升级测试临时构建下一个版本,实际安装、拒绝损坏包、下载、重启替换,再检查设置、Cookie、DPAPI 数据保留与卸载。临时升级版本不会上传或发布。测试证据位于 `test-results/windows-client`,实际运行结果见 [验证记录](verification/windows-client-2026-09-22/README.md)。
+
+以下项目需要真实 Windows 10 和 Windows 11 交互环境,不以 CI 编译或模拟响应代替:
+
+| 项目 | 验收方法 |
+| --- | --- |
+| 安装与卸载 | 干净用户、中文用户名、无开发运行时;核对快捷方式、单实例、数据保留 |
+| 登录与网络 | 管理员及普通账号、会话过期、更换服务器、断网恢复、旧服务器升级提示 |
+| 主屏控制 | 100%、150%、200% 缩放;单击、双击、拖拽、滚动、Ctrl/Alt/Win 组合键及中文/emoji;切主屏后旧截图被拒绝 |
+| 授权与会话 | 分别拒绝/授予两档权限、撤销在途操作、人工接管、锁屏、RDP 断开、UAC 和管理员窗口 |
+| 浏览器与文件 | 独立浏览器与文件双向传输,中文路径、跨盘越界、junction 逃逸、空文件、覆盖保护、校验失败 |
+| 生命周期 | 关闭驻留、退出清理、登录启动、仅托盘启动;不启动本机服务 |
+| 实际升级 | 隔离更新源提供两个递增版本;已安装旧版下载并重启替换新版;版本、设置、登录和设备身份保留;断网、损坏包和安装失败可恢复 |
+
+首版的真实桌面控制与两个已安装版本之间的升级,必须在记录 Windows 版本、构建提交及测试结果后才可标记通过。未执行的项目标记为“未验证”。

+ 17 - 0
electron-builder.yml

@@ -31,10 +31,27 @@ extraResources:
       - electron-updater.cjs
       - keychain-helper
       - computer-helper
+      - computer-helper.exe
       - ui/**/*
       - web-service/**/*
 asar: true
 npmRebuild: false
+win:
+  files:
+    - '**/*'
+    - '!**/node_modules/**'
+  executableName: Yaoyao
+  icon: .desktop-build/branding/icon.ico
+  requestedExecutionLevel: asInvoker
+  artifactName: Yaoyao-${version}-win-${arch}-setup.${ext}
+  target:
+    - target: nsis
+      arch: [x64]
+nsis:
+  oneClick: true
+  perMachine: false
+  allowElevation: false
+  deleteAppDataOnUninstall: false
 mac:
   # Keep the independently signed Node runtime byte-identical to its sealed manifest.
   signIgnore:

+ 2 - 2
package-lock.json

@@ -1,12 +1,12 @@
 {
   "name": "yaoyao",
-  "version": "0.4.70",
+  "version": "0.4.71",
   "lockfileVersion": 3,
   "requires": true,
   "packages": {
     "": {
       "name": "yaoyao",
-      "version": "0.4.70",
+      "version": "0.4.71",
       "license": "Apache-2.0",
       "dependencies": {
         "@koa/bodyparser": "^5.0.0",

+ 5 - 2
package.json

@@ -1,6 +1,6 @@
 {
   "name": "yaoyao",
-  "version": "0.4.70",
+  "version": "0.4.71",
   "private": true,
   "license": "Apache-2.0",
   "description": "夭夭 AI:聊天、多 Agent 团队、文件库与电脑工作空间",
@@ -35,7 +35,10 @@
     "desktop:test": "node --test desktop/*.test.mjs",
     "runner": "node dist-server/runner/index.js",
     "runner:dev": "tsx src/runner/index.ts",
-    "runner:build": "node scripts/build-runner.mjs"
+    "runner:build": "node scripts/build-runner.mjs",
+    "desktop:build:win": "npm run build && node scripts/build-windows-desktop.mjs",
+    "desktop:pack:win": "npm run desktop:build:win && node scripts/windows-desktop-release.mjs",
+    "desktop:test:win": "node scripts/test-windows-desktop.mjs"
   },
   "dependencies": {
     "@koa/bodyparser": "^5.0.0",

+ 3 - 3
release.json

@@ -1,6 +1,6 @@
 {
   "schemaVersion": 1,
-  "releaseVersion": "0.4.70",
-  "webVersion": "0.4.70",
-  "gitTag": "v0.4.70"
+  "releaseVersion": "0.4.71",
+  "webVersion": "0.4.71",
+  "gitTag": "v0.4.71"
 }

+ 1 - 1
scripts/build-desktop.mjs

@@ -34,7 +34,7 @@ await mkdir(shell)
 await cp(resolve(root, 'bin/lib/data-home.mjs'), resolve(shell, 'data-home.mjs'))
 for (const file of await readdir(resolve(root, 'desktop'))) {
   if (file === 'data-home.mjs' || file.endsWith('.test.mjs') || !/\.(js|mjs|cjs|html|css|png|svg)$/.test(file)) continue
-  if(file==='file-transfer.mjs'){await build({entryPoints:[resolve(root,'desktop',file)],outfile:resolve(shell,file),bundle:true,platform:'node',format:'esm',target:'node24'});continue}
+  if(['file-transfer.mjs','host-files.mjs'].includes(file)){await build({entryPoints:[resolve(root,'desktop',file)],outfile:resolve(shell,file),bundle:true,platform:'node',format:'esm',target:'node24'});continue}
   if(/\.(js|mjs|cjs)$/.test(file))execFileSync(process.execPath,['--check',resolve(root,'desktop',file)],{stdio:'inherit'})
   await cp(resolve(root, 'desktop', file), resolve(shell, file))
 }

+ 43 - 0
scripts/build-windows-desktop.mjs

@@ -0,0 +1,43 @@
+import { build } from 'esbuild'
+import { execFileSync } from 'node:child_process'
+import { cp, mkdir, rm, readdir, readFile, writeFile } from 'node:fs/promises'
+import { resolve, join } from 'node:path'
+import { createRequire } from 'node:module'
+import { bundleDesktopUpdater } from './bundle-desktop-updater.mjs'
+
+if (process.platform !== 'win32' || process.arch !== 'x64') throw new Error('Windows x64 原生助手请通过 Windows CI 或 Windows x64 电脑构建')
+const root = resolve(import.meta.dirname, '..'), out = join(root, '.desktop-build'), shell = join(out, 'shell')
+await rm(out, { recursive: true, force: true })
+await mkdir(shell, { recursive: true })
+await mkdir(join(out, 'branding'))
+const native = join(out, 'native')
+execFileSync('cmake', ['-S', join(root, 'desktop/windows'), '-B', native, '-A', 'x64'], { stdio: 'inherit' })
+execFileSync('cmake', ['--build', native, '--config', 'Release'], { stdio: 'inherit' })
+for (const name of ['computer-helper.exe', 'computer-helper-dev.exe']) {
+  await cp(join(native, 'Release', name), join(out, name))
+  execFileSync(join(out, name), ['--self-test'], { stdio: 'inherit' })
+}
+const env = { ...process.env }; delete env.ELECTRON_RUN_AS_NODE
+execFileSync(createRequire(import.meta.url)('electron'), [join(root, 'scripts/build-windows-icon.cjs'),
+  join(root, 'public/icons/icon-512.png'), join(out, 'branding/icon.ico')], { stdio: 'inherit', env })
+await bundleDesktopUpdater(join(out, 'electron-updater.cjs'), 'win32')
+await build({ entryPoints: [join(root, 'src/server/githubReleases.ts')], outfile: join(out, 'github-release.mjs'),
+  bundle: true, platform: 'node', format: 'esm', target: 'node24' })
+await cp(join(root, 'bin/lib/data-home.mjs'), join(shell, 'data-home.mjs'))
+for (const file of await readdir(join(root, 'desktop'))) {
+  if (file === 'data-home.mjs' || file.endsWith('.test.mjs') || !/\.(js|mjs|cjs|html|css|png|svg)$/.test(file)) continue
+  if (['file-transfer.mjs', 'host-files.mjs'].includes(file)) {
+    await build({ entryPoints: [join(root, 'desktop', file)], outfile: join(shell, file), bundle: true, platform: 'node', format: 'esm', target: 'node24' })
+  } else {
+    if (/\.(js|mjs|cjs)$/.test(file)) execFileSync(process.execPath, ['--check', join(root, 'desktop', file)])
+    await cp(join(root, 'desktop', file), join(shell, file))
+  }
+}
+await cp(join(root, 'public/icons/icon-512.png'), join(shell, 'icon.png'))
+await cp(join(root, 'public/icons/icon-512.png'), join(root, 'desktop/icon.png'))
+for (const file of ['release.json', 'build-info.json']) await cp(join(root, file), join(out, file))
+for (const file of ['LICENSE', 'NOTICE', 'THIRD_PARTY_NOTICES.md', 'licenses']) await cp(join(root, file), join(shell, file), { recursive: true })
+const { webVersion: version } = JSON.parse(await readFile(join(root, 'release.json'), 'utf8'))
+await writeFile(join(shell, 'package.json'), JSON.stringify({ name: 'yaoyao-desktop', version, productName: '夭夭',
+  description: '夭夭 AI:Windows 客户端', author: 'YaoYao contributors', license: 'Apache-2.0', main: 'main.mjs', type: 'module' }, null, 2))
+console.log('Windows 客户端与原生助手已构建,不包含本机服务器运行时')

+ 18 - 0
scripts/build-windows-icon.cjs

@@ -0,0 +1,18 @@
+const { app, nativeImage } = require('electron')
+const { readFileSync, writeFileSync } = require('node:fs')
+app.whenReady().then(() => {
+  const source = nativeImage.createFromBuffer(readFileSync(process.argv[2]))
+  if (source.isEmpty()) throw new Error('应用图标无效')
+  const sizes = [16, 32, 48, 256], images = sizes.map(size => source.resize({ width: size, height: size }).toPNG())
+  const header = Buffer.alloc(6 + 16 * sizes.length)
+  header.writeUInt16LE(1, 2); header.writeUInt16LE(sizes.length, 4)
+  let offset = header.length
+  images.forEach((bytes, index) => {
+    const at = 6 + index * 16
+    header[at] = header[at + 1] = sizes[index] % 256
+    header.writeUInt16LE(1, at + 4); header.writeUInt16LE(32, at + 6)
+    header.writeUInt32LE(bytes.length, at + 8); header.writeUInt32LE(offset, at + 12)
+    offset += bytes.length
+  })
+  writeFileSync(process.argv[3], Buffer.concat([header, ...images])); app.quit()
+}).catch(error => { console.error(error.message); app.exit(1) })

+ 2 - 2
scripts/bundle-desktop-updater.mjs

@@ -6,11 +6,11 @@ import { pathToFileURL } from 'node:url'
 import { patchMacUpdater } from './patch-mac-updater.mjs'
 
 const require = createRequire(import.meta.url)
-export async function bundleDesktopUpdater(outfile) {
+export async function bundleDesktopUpdater(outfile, platform = process.platform) {
   await build({ entryPoints: [require.resolve('electron-updater')], outfile,
     bundle: true, platform: 'node', target: 'node24', format: 'cjs', external: ['electron'], legalComments: 'eof' })
   // Pin electron-updater and fail the build if its native staging code changes.
-  await writeFile(outfile, patchMacUpdater(await readFile(outfile, 'utf8')))
+  if (platform === 'darwin') await writeFile(outfile, patchMacUpdater(await readFile(outfile, 'utf8')))
 }
 if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href)
   await bundleDesktopUpdater(resolve(import.meta.dirname, '../.desktop-build/electron-updater.cjs'))

+ 4 - 0
scripts/test-windows-desktop.mjs

@@ -0,0 +1,4 @@
+import { execFileSync } from 'node:child_process'
+const files = ['platform', 'windows', 'windows-smoke', 'onboarding', 'onboarding-renderer', 'host-files', 'host-manager', 'host-environment',
+  'preferences', 'remote-login', 'auto-update-manager', 'update-manager']
+execFileSync(process.execPath, ['--test', ...files.map(name => `desktop/${name}.test.mjs`)], { stdio: 'inherit' })

+ 61 - 0
scripts/windows-desktop-release.mjs

@@ -0,0 +1,61 @@
+import { createHash } from 'node:crypto'
+import { createReadStream } from 'node:fs'
+import { readFile, writeFile, stat } from 'node:fs/promises'
+import { basename, join, resolve } from 'node:path'
+import { pathToFileURL } from 'node:url'
+import { load } from 'js-yaml'
+
+async function hash(path, algorithm, encoding) {
+  const result = createHash(algorithm)
+  for await (const bytes of createReadStream(path)) result.update(bytes)
+  return result.digest(encoding)
+}
+export function windowsSigningOptions(env = process.env) {
+  if (env.YAOYAO_WINDOWS_SIGNED !== '1') return { forceCodeSigning: false, win: { signAndEditExecutable: true, signExecutable: false } }
+  if (!env.CSC_LINK || !env.YAOYAO_WINDOWS_PUBLISHER?.trim()) throw new Error('正式 Windows 包需要 CSC_LINK、CSC_KEY_PASSWORD(如适用)和 YAOYAO_WINDOWS_PUBLISHER')
+  return { forceCodeSigning: true, win: { signExecutable: true,
+    signtoolOptions: { publisherName: env.YAOYAO_WINDOWS_PUBLISHER.trim() }, verifyUpdateCodeSignature: true } }
+}
+export async function verifyWindowsArtifacts(directory, version) {
+  const name = `Yaoyao-${version}-win-x64-setup.exe`
+  const metadata = load(await readFile(join(directory, 'latest.yml'), 'utf8'))
+  if (metadata?.version !== version || metadata.files?.length !== 1 || metadata.files[0].url !== name) throw new Error('Windows 更新清单与安装包不匹配')
+  for (const file of metadata.files) {
+    if (basename(file.url) !== file.url) throw new Error('安装包路径无效')
+    const path = join(directory, file.url), info = await stat(path)
+    if (!info.isFile() || info.size === 0 || info.size !== file.size || file.sha512 !== await hash(path, 'sha512', 'base64')) throw new Error('Windows 安装包大小或 SHA-512 不匹配')
+    const exe = await readFile(path)
+    if (exe.toString('ascii', 0, 2) !== 'MZ') throw new Error('Windows 安装包不是 PE 文件')
+  }
+  if (!(await stat(join(directory, `${name}.blockmap`))).size) throw new Error('Windows 差分更新文件为空')
+  const names = [name, `${name}.blockmap`, 'latest.yml']
+  await writeFile(join(directory, 'SHA256SUMS-win-x64.txt'), (await Promise.all(names.map(async name => `${await hash(join(directory, name), 'sha256', 'hex')}  ${name}`))).join('\n') + '\n')
+  return names
+}
+export async function packageWindowsDesktop() {
+  if (process.platform !== 'win32' || process.arch !== 'x64') throw new Error('请在 Windows x64 CI 或 Windows 电脑打包')
+  const root = resolve(import.meta.dirname, '..'), directory = join(root, 'desktop-release', 'windows-x64')
+  const { version } = JSON.parse(await readFile(join(root, 'package.json'), 'utf8'))
+  const { build, Platform, Arch } = await import('electron-builder')
+  const signing = windowsSigningOptions()
+  if (process.env.YAOYAO_WINDOWS_SIGNED !== '1') process.env.CSC_IDENTITY_AUTO_DISCOVERY = 'false'
+  await build({ projectDir: root, targets: Platform.WINDOWS.createTarget(['nsis'], Arch.x64), publish: 'never',
+    config: { ...signing, directories: { output: directory }, electronUpdaterCompatibility: '>=2.16' } })
+  await verifyWindowsArtifacts(directory, version)
+  const { listPackage } = await import('@electron/asar')
+  if (listPackage(join(directory, 'win-unpacked/resources/app.asar')).some(name => /[\\/]node_modules[\\/]/.test(name))) throw new Error('Windows 客户端意外包含服务器或开发依赖')
+  const feed = load(await readFile(join(directory, 'win-unpacked/resources/app-update.yml'), 'utf8'))
+  if (feed.provider !== 'github' || feed.owner !== 'Lsamien' || feed.repo !== 'yaoyao') throw new Error('Windows 更新源配置无效')
+  if (process.env.YAOYAO_WINDOWS_SIGNED === '1' && ![feed.publisherName].flat().includes(process.env.YAOYAO_WINDOWS_PUBLISHER.trim())) throw new Error('正式 Windows 更新配置缺少发布者签名校验')
+  const info = JSON.parse(await readFile(join(root, 'build-info.json'), 'utf8'))
+  await writeFile(join(directory, 'BUILD-INFO.json'), JSON.stringify({ version, platform: 'win32', arch: 'x64',
+    signing: process.env.YAOYAO_WINDOWS_SIGNED === '1' ? 'signed' : 'unsigned-test', ...info }, null, 2) + '\n')
+  await writeFile(join(directory, 'README.txt'), '夭夭 Windows x64 客户端\n' +
+    (process.env.YAOYAO_WINDOWS_SIGNED === '1' ? '正式签名构建。\n' : '未签名测试包,Windows 可能提示未知发布者。\n') +
+    '支持 Windows 10/11 x64;连接已有夭夭服务器。本机无需 Node、Python、Hermes。\n' +
+    'Windows 电脑操作需要服务器支持;更新清单随本次构建交付,尚未上传正式更新源。\n' +
+    '完整验收步骤见 docs/windows-client.md。CI 构建不代表真实桌面控制已完成验收。\n')
+  console.log(`Windows 安装包及更新清单已校验:${directory}(尚未发布)`)
+  console.log(await readFile(join(directory, 'SHA256SUMS-win-x64.txt'), 'utf8'))
+}
+if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) await packageWindowsDesktop()

+ 2 - 3
src/client/api/chatTranscript.ts

@@ -196,14 +196,13 @@ export class ChatTranscriptClient {
         value.epoch !== current.epoch ||
         typeof cursor !== 'number' ||
         !Number.isSafeInteger(cursor) ||
-        cursor < current.cursor ||
         typeof value.running !== 'boolean' ||
         typeof value.queued !== 'boolean'
       ) throw new TranscriptGap()
-      const nextCursor = cursor
+      if (cursor < current.cursor) return
+      if (cursor > current.cursor) throw new TranscriptGap()
       await this.commit({
         ...current,
-        cursor: nextCursor,
         running: value.running,
         queued: value.queued,
         pendingApproval: value.pendingApproval ?? null,

+ 5 - 3
src/client/api/httpRealtime.ts

@@ -42,13 +42,15 @@ export class HTTPRealtimeChannel {
   private async readLoop(onReady: () => void): Promise<void> {
     let attempt = 0
     while (!this.stopped) {
-      this.abort = new AbortController()
+      const attemptAbort = new AbortController()
+      this.abort = attemptAbort
       let reader: ReadableStreamDefaultReader<Uint8Array> | undefined
       let watchdog: number | undefined
       try {
+        watchdog = window.setTimeout(() => attemptAbort.abort(), 45_000)
         const headers: Record<string, string> = { Accept: 'text/event-stream' }
         if (this.cursor) headers['Last-Event-ID'] = this.cursor
-        const response = await fetch(`/api/realtime/channels/${this.id}/events`, { credentials: 'same-origin', headers, signal: this.abort.signal, cache: 'no-store' })
+        const response = await fetch(`/api/realtime/channels/${this.id}/events`, { credentials: 'same-origin', headers, signal: attemptAbort.signal, cache: 'no-store' })
         if ([401, 403, 404, 409, 428].includes(response.status)) throw new ApiError('实时连接需要重新同步', response.status, 'REALTIME_RESET_REQUIRED')
         if (!response.ok) throw new Error(`SSE HTTP ${response.status}`)
         if (!response.headers.get('content-type')?.startsWith('text/event-stream') || !response.body) throw new ApiError('无效的事件流响应', 502, 'INVALID_EVENT_STREAM')
@@ -56,7 +58,7 @@ export class HTTPRealtimeChannel {
         const parser = new SSEParser(), decoder = new TextDecoder()
         while (!this.stopped) {
           window.clearTimeout(watchdog)
-          watchdog = window.setTimeout(() => this.abort?.abort(), 45_000)
+          watchdog = window.setTimeout(() => attemptAbort.abort(), 45_000)
           const { value, done } = await reader.read()
           if (done) throw new Error('SSE disconnected')
           attempt = 0

+ 5 - 5
src/client/components/app/DesktopHostSettingsPanel.vue

@@ -27,7 +27,7 @@ async function register() {
     if(web.protocol==='http:'&&!['localhost','127.0.0.1','[::1]'].includes(web.hostname)&&!insecure.value)throw new Error('远程电脑请使用 HTTPS,或勾选可信局域网 HTTP')
     const result = await apiRequest<{host:DesktopHostSummary;token:string}>('/api/app/admin/desktop-hosts', {method:'POST',body:{name:name.value.trim()}})
     configuration.value = {protocol:1,serverURL:web.origin,hostId:result.host.id,token:result.token,...(insecure.value?{allowInsecureLan:true}:{})}
-    notice.value = '电脑已注册,请下载配置并在那台 Mac 的夭夭 App 中导入。'
+    notice.value = '电脑已注册,请下载配置并在那台电脑的夭夭 App 中导入。'
     await refresh()
   })
 }
@@ -49,11 +49,11 @@ onMounted(()=>{void action(refresh)})
 
 <template>
   <section class="desktop-host-panel" aria-label="电脑设置">
-    <p>在其他 Mac 上安装夭夭 App 并导入电脑配置后,那台电脑会主动连接服务器,机器人即可操作它的真实桌面。每台电脑单独授权,配置凭据仅注册时下发一次。</p>
+    <p>在其他电脑上安装夭夭 App 并导入电脑配置后,那台电脑会主动连接服务器,机器人即可操作它的真实桌面。每台电脑单独授权,配置凭据仅注册时下发一次。</p>
     <div class="host-toolbar"><strong>已注册电脑</strong><button type="button" :disabled="busy" @click="action(refresh)">刷新状态</button></div>
     <ul v-if="hosts.length" class="host-list">
       <li v-for="host in hosts" :key="host.id">
-        <div><strong>{{ host.name }}</strong><span>{{ !host.enabled ? '已停用' : host.online ? `已连接 · ${host.hostName || host.platform || 'Mac'}` : '待连接' }}</span></div>
+        <div><strong>{{ host.name }}</strong><span>{{ !host.enabled ? '已停用' : host.online ? `已连接 · ${host.hostName || host.platform || '电脑'}` : '待连接' }}</span></div>
         <button v-if="host.enabled" type="button" :disabled="busy" :aria-label="`停用 ${host.name}`" @click="disable(host)">停用</button>
       </li>
     </ul>
@@ -62,13 +62,13 @@ onMounted(()=>{void action(refresh)})
       <label>电脑名称<input v-model="name" required maxlength="100" autocomplete="off" placeholder="书房 iMac" :disabled="busy"></label>
       <small>用于在电脑面板中区分各台机器。</small>
       <label>夭夭服务地址<input v-model="serverURL" type="url" required :disabled="busy"></label>
-      <small>必须能从那台 Mac 访问。</small>
+      <small>必须能从那台电脑访问。</small>
       <label class="host-check"><input v-model="insecure" type="checkbox" :disabled="busy">使用可信局域网 HTTP</label>
       <button class="solid-button" :disabled="busy || !name.trim()">注册电脑</button>
     </form>
     <div v-else class="host-setup">
       <button class="solid-button" type="button" @click="download">下载电脑配置</button>
-      <p>配置包含这台电脑的连接凭据,仅本次可下载。在那台 Mac 上打开夭夭 App,通过菜单「电脑 → 导入电脑配置…」选择下载的 desktop-host.json。</p>
+      <p>配置包含这台电脑的连接凭据,仅本次可下载。在那台电脑上打开夭夭 App,通过菜单「电脑 → 导入电脑配置…」选择下载的 desktop-host.json。</p>
       <small>配置丢失后可停用电脑并重新注册;停用立即断开那台电脑。</small>
     </div>
     <p v-if="error" class="host-error" role="alert">{{ error }}</p>

+ 8 - 7
src/client/components/app/DesktopModePanel.vue

@@ -1,18 +1,19 @@
 <script setup lang="ts">
-import { onMounted, ref } from 'vue'
+import { computed, onMounted, ref } from 'vue'
 import AppIcon from '@/components/common/AppIcon.vue'
 
 type Mode = 'client' | 'server'
 const desktop = window.yaoyaoDesktop
-const state = ref<{ mode: Mode; serverURL: string; switching: boolean }>()
+const state = ref<{ mode: Mode; serverURL: string; switching: boolean; supportedModes?: Mode[] }>()
 const selected = ref<Mode>('client')
 const busy = ref(false)
 const error = ref('')
 const notice = ref('')
-const options = [
+const options = computed(() => ([
   { mode: 'client', title: '客户端模式', description: '连接另一台电脑上的夭夭服务器。本机无需安装 Hermes。', icon: 'link' },
   { mode: 'server', title: '服务器模式', description: '在这台电脑上运行夭夭服务,使用本机 Hermes,并供其他客户端连接。', icon: 'monitor' },
-] as const
+] as const).filter(option => !state.value?.supportedModes || state.value.supportedModes.includes(option.mode)))
+const canSwitch = computed(() => !!state.value && options.value.length > 1)
 
 async function load() {
   busy.value = true; error.value = ''
@@ -49,7 +50,7 @@ onMounted(load)
       <span v-if="state.serverURL">{{ state.serverURL }}</span>
     </div>
     <p v-else-if="busy" role="status">正在读取运行模式…</p>
-    <fieldset :disabled="busy || !state || state.switching">
+    <fieldset v-if="canSwitch" :disabled="busy || !state || state.switching">
       <legend>这台电脑如何使用夭夭?</legend>
       <label v-for="option in options" :key="option.mode" class="mode-option" :class="{ selected: selected === option.mode }">
         <input v-model="selected" type="radio" name="desktop-running-mode" :value="option.mode" />
@@ -57,12 +58,12 @@ onMounted(load)
         <span><strong>{{ option.title }}</strong><small>{{ option.description }}</small></span>
       </label>
     </fieldset>
-    <p class="mode-note">切换后会打开对应服务的页面,并记住选择。数据保留在原服务器;连接另一台服务器时,可能需要登录。</p>
+    <p class="mode-note">{{ canSwitch ? '切换后会打开对应服务的页面,并记住选择。' : '此客户端连接已有服务器。' }}数据保留在原服务器;连接另一台服务器时,可能需要登录。</p>
     <p v-if="error" class="mode-error" role="alert">{{ error }}</p>
     <p v-if="notice" role="status">{{ notice }}</p>
     <div class="mode-actions">
       <button v-if="!state" type="button" :disabled="busy" @click="load">重新读取</button>
-      <button v-else class="mode-primary" type="button" :disabled="busy || state.switching || selected === state.mode" @click="switchMode">
+      <button v-else-if="canSwitch" class="mode-primary" type="button" :disabled="busy || state.switching || selected === state.mode" @click="switchMode">
         {{ busy ? '正在切换…' : selected === state.mode ? '正在使用此模式' : selected === 'client' ? '切换为客户端' : '切换为服务器' }}
       </button>
       <button v-if="desktop?.openRemoteLogin" type="button" :disabled="busy || state?.switching" @click="changeServer">更换服务器…</button>

+ 1 - 1
src/client/components/app/HostToolsPanel.vue

@@ -105,7 +105,7 @@ onMounted(() => { void load(); void loadNames() })
   <section class="host-tools" aria-label="电脑与服务端工具">
     <p>这些开关对所有机器人生效,不再按单个机器人勾选。所有 Bot 共用电脑权限和审批策略。设备是否在线、是否获得系统授权会单独显示。</p>
     <form @submit.prevent="save" @change="changed">
-      <label class="toggle"><input v-model="scriptMachine" type="checkbox" :disabled="loading || saving" /><span><strong>电脑</strong><small>连接服务器的 Mac。机器人按名称点名:文件走文件工具,命令走 shell,只有看窗口或点按时才截图。</small></span></label>
+      <label class="toggle"><input v-model="scriptMachine" type="checkbox" :disabled="loading || saving" /><span><strong>电脑</strong><small>连接服务器的 Mac 或 Windows 电脑。机器人按名称点名:文件走文件工具,命令走 shell,只有看窗口或点按时才截图。</small></span></label>
       <label class="toggle"><input v-model="serverComputer" type="checkbox" :disabled="loading || saving" /><span><strong>服务器</strong><small>夭夭正在运行的这台电脑。文件走文件工具,命令走 shell;只有看窗口或点按时才截图操作。</small></span></label>
       <label class="toggle"><input v-model="vm" type="checkbox" :disabled="loading || saving" /><span><strong>虚拟环境</strong><small>服务端上的隔离桌面。聊天留在夭夭,操作派到虚拟机里。</small></span></label>
       <label class="toggle"><input v-model="cloud" type="checkbox" :disabled="loading || saving" /><span><strong>云虚拟机</strong><small>共享的 Grok Bot 电脑。先看真实桌面,再点击、输入、按键或滚动。</small></span></label>

+ 1 - 1
src/client/components/app/RunnerSettingsPanel.vue

@@ -57,7 +57,7 @@ onMounted(()=>{void action(refresh)})
 
 <template>
   <section class="runner-panel" aria-label="执行节点设置">
-    <p>执行节点只给虚拟环境用。聊天和 Mac 桌面不经过这里。节点要和 Hermes 装在同一台电脑上。</p>
+    <p>执行节点只给虚拟环境用。聊天和真实桌面不经过这里。节点要和 Hermes 装在同一台电脑上。</p>
     <p v-if="bundleAvailable"><a href="/api/app/admin/runners/bundle" download>下载配套执行节点程序</a>(包含桌面资源,需要 Node.js 24 或更高版本)。</p>
     <div class="runner-toolbar"><strong>已注册节点</strong><button type="button" :disabled="busy" @click="action(refresh)">刷新状态</button></div>
     <ul v-if="runners.length" class="runner-list">

+ 4 - 4
src/client/components/workspace/LocalVmChatPanel.vue

@@ -146,14 +146,14 @@ onBeforeUnmount(()=>{closed=true;revision++;previewRevision++;clearTimeout(timer
     <p class="hint">电脑开关在 Bot 设置里,对所有机器人一起生效。</p>
     <div class="computer-options">
     <template v-if="showDesktop">
-      <p>服务器是运行夭夭服务的电脑;电脑是连接这台服务器的 Mac。两者都可改名。「本机」跟你当前发消息所在的电脑走。要文件用文件工具,要命令用 shell;只有需要看窗口或点按时才截图。</p>
+      <p>服务器是运行夭夭服务的电脑;电脑是连接这台服务器的 Mac 或 Windows 电脑。两者都可改名。「本机」跟你当前发消息所在的电脑走。要文件用文件工具,要命令用 shell;只有需要看窗口或点按时才截图。</p>
       <div v-for="host in desktopHosts" :key="host.id" class="host-permission" :class="{offline:!host.online}">
        <div class="host-permission-head"><strong>{{host.id==='local'?('服务器 · '+(host.name||'服务器')):('电脑 · '+(host.name||'未命名'))}}</strong><small>{{host.online?'在线':'离线'}}</small></div>
-       <div class="permission-list"><span>{{host.local.authorized?'✓':'○'}} 屏幕控制授权</span><span>{{host.local.screen?'✓':'○'}} 屏幕录制</span><span>{{host.local.accessibility?'✓':'○'}} 辅助功能</span><span>{{host.local.fullAuthorized?'✓':'○'}} 文件与命令</span></div>
+       <div class="permission-list"><span>{{host.local.authorized?'✓':'○'}} 屏幕控制授权</span><span>{{host.local.screen?'✓':'○'}} {{host.platform==='win32'?'屏幕可用':'屏幕录制'}}</span><span>{{host.local.accessibility?'✓':'○'}} {{host.platform==='win32'?'键鼠可用':'辅助功能'}}</span><span>{{host.local.fullAuthorized?'✓':'○'}} 文件与命令</span></div>
        <button v-if="host.online&&!host.local.ready" class="primary" :disabled="busy||!isAdmin" @click="authorizeHost(host.id)">在桌面端授权</button>
-       <p v-if="host.online&&!host.local.ready" class="hint">在 {{host.id==='local'?'这台':host.name}} Mac 上确认授权,并按系统提示开启权限;系统可能要求重新打开 App。</p>
+       <p v-if="host.online&&!host.local.ready" class="hint">{{host.platform==='win32'?'在 Windows 客户端确认授权,并解锁电脑、保持桌面会话连接。':'在目标 Mac 上确认授权,并按系统提示开启屏幕录制和辅助功能;可能需要重新打开 App。'}}</p>
        <button v-if="host.online&&!host.local.fullAuthorized" :disabled="busy||!isAdmin" @click="authorizeHost(host.id,'full')">授权文件与命令</button>
-       <p v-if="host.online&&!host.local.fullAuthorized" class="hint">授权后,机器人可以在这台 Mac 的用户主目录内读写文件并执行命令;每台电脑单独授权,可随时撤销。</p>
+       <p v-if="host.online&&!host.local.fullAuthorized" class="hint">授权后,机器人可以在这台电脑的用户主目录内读写文件,并以当前用户权限执行命令;每台电脑单独授权,可随时撤销。</p>
       </div>
       <button v-if="serverHost" class="primary" :disabled="busy||!serverHost.online||!serverHost.local.ready" @click="openDesktop('desktop','local')">接管服务器</button>
     </template>

+ 1 - 1
src/client/env.d.ts

@@ -13,7 +13,7 @@ interface Window {
   yaoyaoDesktop?: {
     openLogin?(): Promise<unknown>
     openUpdates?(): Promise<void>
-    modeState?(): Promise<{ mode: 'client' | 'server'; serverURL: string; switching: boolean }>
+    modeState?(): Promise<{ mode: 'client' | 'server'; serverURL: string; switching: boolean; platform?: string; supportedModes?: ('client' | 'server')[] }>
     switchMode?(mode: 'client' | 'server'): Promise<{ ok: boolean; error?: string; pendingLogin?: boolean }>
     openRemoteLogin?(): Promise<void>
     authorizeComputer?(csrfToken: string): Promise<{ registered: boolean; hostId?: string }>

+ 47 - 34
src/client/views/ConversationsView.vue

@@ -299,7 +299,7 @@ async function refresh() {
   conversations.value = transcriptStore.conversations
   if (!cursor) { cursor = c.cursor; transcriptStore.cursor = c.cursor }
 }
-async function load(id = selected.value, append = false) {
+async function load(id = selected.value, append = false, signal?: AbortSignal) {
   if (!id) {
     generation++
     active.value = undefined
@@ -311,6 +311,9 @@ async function load(id = selected.value, append = false) {
     return
   }
   const own = ++generation
+  const owner = auth.user?.id, epoch = accountEpoch
+  const current = () => !disposed && own === generation && !signal?.aborted
+    && auth.user?.id === owner && accountEpoch === epoch
   const previousComposer = composerKey.value
   const previousFiles = composer.value?.filesSnapshot() ?? []
   const previousQuote = quoted.value
@@ -324,11 +327,11 @@ async function load(id = selected.value, append = false) {
     activeTask.value = null;tasks.value = [];assignments.value = [];quoted.value = null;older.value = false
   }
   try {
-    const incoming = cached ?? await apiRequest<WorkspaceDetail>(`/api/app/conversations/${id}?limit=50${requestedTask ? `&taskId=${encodeURIComponent(requestedTask)}` : ''}`)
-    if (disposed || own !== generation) return
+    const incoming = cached ?? await apiRequest<WorkspaceDetail>(`/api/app/conversations/${id}?limit=50${requestedTask ? `&taskId=${encodeURIComponent(requestedTask)}` : ''}`, { signal })
+    if (!current()) return
     const r = cached ?? transcriptStore.finishRead(readToken, incoming)
     if (cached && transcriptStore.staleDetails.has(transcriptKey(id, cached.task?.id))) {
-      queueMicrotask(() => { if (!disposed && active.value?.id === id) void load(id, true) })
+      queueMicrotask(() => { if (current() && active.value?.id === id) void load(id, true, signal) })
     }
     const atBottom = timeline.value?.isFollowingBottom() ?? true
     active.value = r.conversation
@@ -350,28 +353,31 @@ async function load(id = selected.value, append = false) {
         } catch { /* Leave the original draft intact when browser storage is unavailable. */ }
       }
       await nextTick()
+      if (!current()) return
       const saved = taskFiles.get(composerKey.value)
       if (saved?.length) await composer.value?.attachFiles(saved)
+      if (!current()) return
       quoted.value = taskQuotes.get(composerKey.value) ?? null
     }
     if (!append) older.value = r.hasOlder ?? r.messages.length === 50
     if (!append || atBottom) {
       await nextTick()
+      if (!current()) return
       if (!append) timeline.value?.scrollToBottom('auto')
-      void markRead().catch(e => { if (own === generation) error.value = e instanceof Error ? e.message : '同步已读失败' })
+      void markRead().catch(e => { if (current()) error.value = e instanceof Error ? e.message : '同步已读失败' })
     }
   } catch (e) {
-    if (own === generation && requestedTask && e instanceof ApiError && e.status === 404) {
+    if (current() && requestedTask && e instanceof ApiError && e.status === 404) {
       try {
-        const current = await apiRequest<{tasks:WorkspaceTask[]}>(`/api/app/conversations/${id}/tasks`)
-        const fallback = current.tasks[0]
-        if (own === generation && fallback && fallback.id !== requestedTask) {
+        const available = await apiRequest<{tasks:WorkspaceTask[]}>(`/api/app/conversations/${id}/tasks`, { signal })
+        const fallback = available.tasks[0]
+        if (current() && fallback && fallback.id !== requestedTask) {
           await router.replace({query:{...route.query,taskId:fallback.id}})
           return
         }
       } catch { /* A deleted conversation still reports its original error. */ }
     }
-    if (own === generation) error.value = e instanceof Error ? e.message : '加载失败'
+    if (current()) error.value = e instanceof Error ? e.message : '加载失败'
   } finally {
     transcriptStore.cancelRead(readToken)
     if (own === generation) loading.value = false
@@ -470,6 +476,12 @@ let patchEvents = false
 let eventSource: EventSource | undefined
 let eventFrame: number | undefined
 let eventQueue: WorkspaceEvent[] = []
+let recoveryAbort: AbortController | undefined
+function cancelRecovery() {
+  recoveryAbort?.abort(); recoveryAbort = undefined
+  if (timer) clearTimeout(timer)
+  timer = undefined
+}
 function presentDetail(detail: WorkspaceDetail) {
   const atBottom = timeline.value?.isFollowingBottom() ?? true
   active.value = detail.conversation
@@ -501,17 +513,17 @@ function flushEvents() {
     }
   }
 }
-async function hydrateWorkspace() {
+async function hydrateWorkspace(signal: AbortSignal) {
   const owner = auth.user?.id, epoch = accountEpoch
-  const capabilities = await apiRequest<{ features: string[]; csrfToken?: string }>('/api/app/capabilities')
-  if (disposed || accountEpoch !== epoch || auth.user?.id !== owner) return
+  const capabilities = await apiRequest<{ features: string[]; csrfToken?: string }>('/api/app/capabilities', { signal })
+  if (signal.aborted || disposed || accountEpoch !== epoch || auth.user?.id !== owner) return
   patchEvents = capabilities.features.includes(WORKSPACE_PATCH_CAPABILITY)
   knowledgeEnabled.value = capabilities.features.includes('bot-file-memory-v1')
   if (capabilities.csrfToken) setApiCsrfToken(capabilities.csrfToken)
   const readToken = transcriptStore.beginRead()
   try {
-  const snapshot = await apiRequest<WorkspaceSnapshot & { serverIdentity?: ServerIdentity; projects?: WorkspaceProject[] }>('/api/app/workspace/snapshot')
-  if (disposed || accountEpoch !== epoch || auth.user?.id !== owner) return
+  const snapshot = await apiRequest<WorkspaceSnapshot & { serverIdentity?: ServerIdentity; projects?: WorkspaceProject[] }>('/api/app/workspace/snapshot', { signal })
+  if (signal.aborted || disposed || accountEpoch !== epoch || auth.user?.id !== owner) return
   transcriptStore.hydrate(snapshot)
   agents.value = snapshot.agents; conversations.value = transcriptStore.conversations; cursor = snapshot.cursor
   projects.value = snapshot.projects ?? []
@@ -536,7 +548,7 @@ function connectEvents() {
     flushEvents(); error.value = ''
     publishServerIdentity(JSON.parse((event as MessageEvent).data).serverIdentity)
   })
-  source.addEventListener('reset', () => { source.close(); void recoverEvents() })
+  source.addEventListener('reset', () => { if (!disposed && eventSource === source) { source.close(); void recoverEvents() } })
   source.onerror = () => {
     if (disposed || eventSource !== source) return
     error.value = '连接中断,正在重连'
@@ -549,34 +561,41 @@ function connectEvents() {
   }
 }
 function suspendEvents() {
+  cancelRecovery()
   eventSource?.close(); eventSource = undefined
-  if (timer) clearTimeout(timer)
   error.value = '网络已断开,恢复连接后将自动同步'
 }
 function resumeEvents() {
   if (!disposed && auth.user?.id) void recoverEvents()
 }
-async function recoverEvents() {
+async function recoverEvents(initial = false) {
+  cancelRecovery()
+  if (disposed || !auth.user?.id) return
   if (!navigator.onLine) { suspendEvents(); return }
+  const controller = new AbortController(), owner = auth.user.id, epoch = accountEpoch
+  recoveryAbort = controller
+  const current = () => !disposed && !controller.signal.aborted && recoveryAbort === controller
+    && accountEpoch === epoch && auth.user?.id === owner
   eventSource?.close(); eventSource = undefined; eventQueue = []
   if (eventFrame !== undefined) cancelAnimationFrame(eventFrame)
   eventFrame = undefined
   try {
-    await hydrateWorkspace()
-    const detail = selected.value ? transcriptStore.get(selected.value, selectedTask.value || activeTask.value?.id) : undefined
+    await hydrateWorkspace(controller.signal)
+    if (!current()) return
+    const detail = !initial && selected.value ? transcriptStore.get(selected.value, selectedTask.value || activeTask.value?.id) : undefined
     if (detail) {
       presentDetail(detail)
-      if (transcriptStore.staleDetails.has(transcriptKey(detail.conversation.id, detail.task?.id))) await load(detail.conversation.id, true)
-    } else await load()
-    connectEvents()
+      if (transcriptStore.staleDetails.has(transcriptKey(detail.conversation.id, detail.task?.id))) await load(detail.conversation.id, true, controller.signal)
+    } else await load(selected.value, false, controller.signal)
+    if (current()) connectEvents()
   }
   catch (cause) {
-    if (disposed) return
+    if (!current()) return
     if (!navigator.onLine) { suspendEvents(); return }
     error.value = cause instanceof Error ? cause.message : '连接中断'
     if (cause instanceof ApiError && [401, 403].includes(cause.status)) return
     timer = setTimeout(() => void recoverEvents(), 1500)
-  }
+  } finally { if (recoveryAbort === controller) recoveryAbort = undefined }
 }
 async function select(id: string) {
   error.value = ''
@@ -929,7 +948,7 @@ watch(() => auth.user?.id, (owner, previous) => {
   knowledgePanel.value?.close(); knowledgeEnabled.value = false; projects.value = []; knowledgeRevision.value++
   accountEpoch++; busy.value = false
   generation++
-  if (timer) clearTimeout(timer)
+  cancelRecovery()
   text.value = ''; files.value = []; mentions.value = []; quoted.value = null
   pendingRequestId = undefined; pendingFingerprint = ''; uploadedSources = []; uploadedReferences = []
   eventSource?.close(); eventSource = undefined; eventQueue = []
@@ -946,13 +965,7 @@ onMounted(async () => {
   window.addEventListener('offline', suspendEvents)
   window.addEventListener('online', resumeEvents)
   void auth.refreshProfileAvatars().catch(() => undefined)
-  try {
-    await hydrateWorkspace()
-    if (!disposed) connectEvents()
-    await load()
-  } catch (e) {
-    error.value = String(e)
-  }
+  await recoverEvents(true)
 })
 onBeforeUnmount(() => {
   window.removeEventListener('offline', suspendEvents)
@@ -963,7 +976,7 @@ onBeforeUnmount(() => {
   eventSource?.close()
   if (eventFrame !== undefined) cancelAnimationFrame(eventFrame)
   generation++
-  if (timer) clearTimeout(timer)
+  cancelRecovery()
 })
 </script>
 <template>

+ 11 - 5
src/server/chatTranscriptApi.ts

@@ -34,7 +34,7 @@ export function chatTranscriptRouter(cache:ChatCacheCoordinator,auth:LocalAuthSt
   router.get('/api/app/chat/sessions/:id/events',ctx=>{
     const {owner,profile,id}=scope(ctx),version=auth.pushAuthorizationVersion(owner)
     const raw=ctx.get('last-event-id')||String(ctx.query.after??''),parts=raw.split(':')
-    let cursor=Number(parts.at(-1)),closed=false,lastFlush=0
+    let cursor=Number(parts.at(-1)),closed=false,lastFlush=0,ready=false
     transcripts.seed(owner,profile,id)
     const epoch=transcripts.epochFor(owner,profile,id)
     if(parts.length!==2||parts[0]!==epoch||!Number.isSafeInteger(cursor)||cursor<0||cursor>transcripts.cursor(owner,profile,id))throw new HttpError(409,'聊天事件需要重新同步','transcript_reset')
@@ -47,14 +47,19 @@ export function chatTranscriptRouter(cache:ChatCacheCoordinator,auth:LocalAuthSt
       if(res.writableLength+Buffer.byteLength(value)>4*1024*1024){res.write('event: reset\ndata: {}\n\n');close();return false}
       res.write(value);return true
     }
+    const control=()=>({epoch,cursor,...transcripts.control(owner,profile,id)})
     const flush=()=>{
       clearTimeout(timer);timer=undefined
+      if(closed)return
       if(!valid()){close();return}
       if(transcripts.epochFor(owner,profile,id)!==epoch){write('event: reset\ndata: {}\n\n');close();return}
       const events=transcripts.events(owner,profile,id,cursor)
       for(const event of events){if(event.epoch!==epoch){write('event: reset\ndata: {}\n\n');close();return}if(!write(`id: ${epoch}:${event.cursor}\nevent: transcript\ndata: ${JSON.stringify(event)}\n\n`))return;cursor=event.cursor}
       if(events.length)lastFlush=Date.now()
-      if(events.length===250)timer=setTimeout(flush,0)
+      if(events.length===250){timer=setTimeout(flush,0);return}
+      // A control frame must never acknowledge events still waiting in another page.
+      if(cursor!==transcripts.cursor(owner,profile,id)){write('event: reset\ndata: {}\n\n');close();return}
+      if(!ready){ready=true;write(`event: ready\ndata: ${JSON.stringify(control())}\n\n`)}
     }
     const changed=()=>{
       if(closed)return
@@ -67,12 +72,13 @@ export function chatTranscriptRouter(cache:ChatCacheCoordinator,auth:LocalAuthSt
     res.writeHead(200,{'Content-Type':'text/event-stream; charset=utf-8','Cache-Control':'no-store','X-Accel-Buffering':'no'})
     res.flushHeaders();res.once('close',close);res.once('error',close)
     off=transcripts.subscribe(changed)
-    const control=()=>({epoch,cursor:transcripts.cursor(owner,profile,id),...transcripts.control(owner,profile,id)})
-    flush();write(`event: ready\ndata: ${JSON.stringify(control())}\n\n`)
+    flush()
+    if(closed)return
     heartbeat=setInterval(()=>{
       if(!valid()){close();return}
       if(transcripts.epochFor(owner,profile,id)!==epoch){write('event: reset\ndata: {}\n\n');close();return}
-      write(`event: state\ndata: ${JSON.stringify(control())}\n\n`)
+      flush()
+      if(!closed&&ready&&timer===undefined)write(`event: state\ndata: ${JSON.stringify(control())}\n\n`)
     },5_000);heartbeat.unref()
   })
   return router

+ 7 - 7
src/server/desktopEnvironments.ts

@@ -88,9 +88,9 @@ export class DesktopEnvironments {
  get online(){const s=this.sessions.get('local');return !!s&&this.hostOnline(s)}
  get idleForUpdate(){for(const s of this.sessions.values()){for(const key of s.manual.keys())this.current(s,key);if(s.pending.size||s.queue.size||s.manual.size)return false}return true}
  private ownerKey(owner:string){return digest((this.nodes.localNodeID??this.nodes.local.url.toString())+':'+owner)}
- private ready(s:HostState,owner:string){return this.hostOnline(s)&&s.info!.platform==='darwin'&&s.info!.screen&&s.info!.accessibility&&s.info!.approved.includes(this.ownerKey(owner))}
+ private ready(s:HostState,owner:string){return this.hostOnline(s)&&['darwin','win32'].includes(s.info!.platform)&&s.info!.screen&&s.info!.accessibility&&s.info!.approved.includes(this.ownerKey(owner))}
  /** File and shell grant: a separate approval tier held by the desktop app. */
- private readyFull(s:HostState,owner:string){return this.hostOnline(s)&&s.info!.platform==='darwin'&&(s.info!.full??[]).includes(this.ownerKey(owner))}
+ private readyFull(s:HostState,owner:string){return this.hostOnline(s)&&['darwin','win32'].includes(s.info!.platform)&&(s.info!.full??[]).includes(this.ownerKey(owner))}
  fileTools(owner:string,agent:WorkspaceAgent){return this.envTools(owner,agent).file}
  private localSession(){let s=this.sessions.get('local');if(!s){s=newHostState('local',false);this.sessions.set('local',s)}return s}
  /** Default session: agent desktopHost binding, else server local.
@@ -162,7 +162,7 @@ export class DesktopEnvironments {
   const hosts:BotDeviceSnapshot[]=states.filter(s=>!revoked.has(s.key)).map((s):BotDeviceSnapshot=>{
    const info=s.info,online=this.hostOnline(s),record=records.find(record=>record.id===s.key),open=(s.key==='local'?global.server:global.script)&&record?.enabled!==false
    const manual=this.current(s,'local'),waiting=manual?'human_control':s.paused.has('local')?'paused':'ready'
-   const base:DeviceCapabilityStatus|undefined=agent&&(agent.archived||agent.remoteAgentId)?'agent_unavailable':!open?'disabled':!online?'offline':info?.platform!=='darwin'?'unsupported':undefined
+   const base:DeviceCapabilityStatus|undefined=agent&&(agent.archived||agent.remoteAgentId)?'agent_unavailable':!open?'disabled':!online?'offline':!['darwin','win32'].includes(info?.platform??'')?'unsupported':undefined
    const capability=(reason?:DeviceCapabilityStatus):DeviceCapability=>({enabled:!reason,status:reason??waiting})
    const screen=capability(base??(!info?.approved.includes(this.ownerKey(owner))?'not_authorized':!info.screen||!info.accessibility?'system_permission_required':undefined))
    const files=capability(base??(!(info?.full??[]).includes(this.ownerKey(owner))?'not_authorized':undefined))
@@ -178,11 +178,11 @@ export class DesktopEnvironments {
  deviceContextLine(owner:string,deviceHost?:string){return deviceSourceText(this.snapshot(owner,undefined,deviceHost))}
  private agent(owner:string,id:string){const a=this.store.require<WorkspaceAgent>(owner,'agent',id);this.nodes.requireSource(owner,a);if(a.archived||a.remoteAgentId)throw new HttpError(409,'此机器人无法使用桌面环境','computer_unavailable');return a}
  private resource(owner:string,agent:WorkspaceAgent,mode:Mode){return mode==='local'?'local':digest(this.ownerKey(owner)+':'+agent.id+':'+(agent.browserProfile??'persistent'))}
- hostStates(owner:string){return [...this.sessions.values()].map(s=>{const online=this.hostOnline(s),info=online?s.info!:undefined;return {id:s.key,name:this.label(s),platform:info?.platform??'',online,local:{supported:info?.platform==='darwin',authorized:!!info&&info.approved.includes(this.ownerKey(owner)),screen:info?.screen===true,accessibility:info?.accessibility===true,ready:!!info&&this.ready(s,owner),fullAuthorized:!!info&&(info.full??[]).includes(this.ownerKey(owner))},browser:{available:online}}}).sort((a,b)=>a.id==='local'?-1:b.id==='local'?1:a.name.localeCompare(b.name))}
- state(owner:string,agent:WorkspaceAgent){const mode=this.selected(owner,agent),s=this.sessionFor(agent),online=!!s&&this.hostOnline(s),info=online?s!.info:undefined;return {online,host:info?{id:s!.key,name:this.label(s!),platform:info.platform}:null,local:{supported:info?.platform==='darwin',authorized:!!info&&info.approved.includes(this.ownerKey(owner)),screen:info?.screen===true,accessibility:info?.accessibility===true,ready:!!info&&this.ready(s!,owner),fullAuthorized:!!info&&(info.full??[]).includes(this.ownerKey(owner))},browser:{available:online,profile:agent.browserProfile??'persistent'},selected:mode??null,agent:this.store.agentSummary(agent),hosts:this.hostStates(owner)}}
+ hostStates(owner:string){return [...this.sessions.values()].map(s=>{const online=this.hostOnline(s),info=online?s.info!:undefined;return {id:s.key,name:this.label(s),platform:info?.platform??'',online,local:{supported:['darwin','win32'].includes(info?.platform??''),authorized:!!info&&info.approved.includes(this.ownerKey(owner)),screen:info?.screen===true,accessibility:info?.accessibility===true,ready:!!info&&this.ready(s,owner),fullAuthorized:!!info&&(info.full??[]).includes(this.ownerKey(owner))},browser:{available:online}}}).sort((a,b)=>a.id==='local'?-1:b.id==='local'?1:a.name.localeCompare(b.name))}
+ state(owner:string,agent:WorkspaceAgent){const mode=this.selected(owner,agent),s=this.sessionFor(agent),online=!!s&&this.hostOnline(s),info=online?s!.info:undefined;return {online,host:info?{id:s!.key,name:this.label(s!),platform:info.platform}:null,local:{supported:['darwin','win32'].includes(info?.platform??''),authorized:!!info&&info.approved.includes(this.ownerKey(owner)),screen:info?.screen===true,accessibility:info?.accessibility===true,ready:!!info&&this.ready(s!,owner),fullAuthorized:!!info&&(info.full??[]).includes(this.ownerKey(owner))},browser:{available:online,profile:agent.browserProfile??'persistent'},selected:mode??null,agent:this.store.agentSummary(agent),hosts:this.hostStates(owner)}}
  /** Every Bot follows the same global desktop policy. */
  private modeOpen(owner:string,agent:WorkspaceAgent,mode:Mode){return this.selected(owner,agent)===mode}
- private check(s:HostState|undefined,owner:string,agentId:string,mode:Mode,epoch:string,version:number,files=false){const a=this.agent(owner,agentId);if(!s||!this.hostOnline(s)||s.info!.id!==epoch)throw new HttpError(409,'桌面端已断开,请在电脑上打开夭夭后重试。','desktop_offline');if(this.auth.pushAuthorizationVersion(owner)!==version||!this.modeOpen(owner,a,mode))throw new HttpError(410,'电脑授权已改变,请重新连接。','computer_control_expired');this.requireHost(s);if(files&&!this.readyFull(s,owner))throw new HttpError(403,'请在桌面端授权文件与命令访问。','desktop_full_required');if(mode==='local'&&!files&&!this.ready(s,owner))throw new HttpError(403,'请在桌面端授权本机控制,并开启屏幕录制和辅助功能。','desktop_permission_required')}
+ private check(s:HostState|undefined,owner:string,agentId:string,mode:Mode,epoch:string,version:number,files=false){const a=this.agent(owner,agentId);if(!s||!this.hostOnline(s)||s.info!.id!==epoch)throw new HttpError(409,'桌面端已断开,请在电脑上打开夭夭后重试。','desktop_offline');if(this.auth.pushAuthorizationVersion(owner)!==version||!this.modeOpen(owner,a,mode))throw new HttpError(410,'电脑授权已改变,请重新连接。','computer_control_expired');this.requireHost(s);if(files&&!this.readyFull(s,owner))throw new HttpError(403,'请在桌面端授权文件与命令访问。','desktop_full_required');if(mode==='local'&&!files&&!this.ready(s,owner))throw new HttpError(403,s.info!.platform==='win32'?'请在 Windows 客户端授权本机控制,并解锁电脑、恢复桌面会话。':'请在桌面端授权本机控制,并开启屏幕录制和辅助功能。','desktop_permission_required')}
  private invalidate(s:HostState){for(const p of s.pending.values()){if(p.sent&&['input','browser'].includes(String(p.command.operation)))s.paused.add(String(p.command.resource));clearTimeout(p.timer);p.reject(new HttpError(409,'桌面连接已改变;执行结果未确认,不会重试。','desktop_disconnected'))}s.pending.clear();s.frames.clear();for(const [key,m] of s.manual){s.paused.add(key);this.store.remove('_system','computer-control',m.id)}s.manual.clear()}
  close(){this.closed=true;for(const s of this.sessions.values())this.invalidate(s)}
  async bridge(ctx:Koa.Context){
@@ -210,7 +210,7 @@ export class DesktopEnvironments {
   for(const result of value.results){const p=s.pending.get(result.id);if(!p||p.epoch!==value.host.id)continue;s.pending.delete(p.id);clearTimeout(p.timer);try{p.check();if(result.error)throw new HttpError(409,result.error,'desktop_command_failed');p.resolve(result.value)}catch(error){p.reject(error as Error)}}
   const commands:Record<string,unknown>[]=[]
   for(const p of s.pending.values()){if(p.sent)continue;try{p.check();p.sent=true;commands.push({id:p.id,deadline:p.deadline,...p.command})}catch(error){s.pending.delete(p.id);clearTimeout(p.timer);p.reject(error as Error)}if(commands.length>=8)break}
-  return {commands,capabilities:{environmentMetadata:1}}
+  return {commands,capabilities:{environmentMetadata:1,desktopPlatforms:['darwin','win32']}}
  }
  private command(s:HostState,command:Record<string,unknown>,check:()=>void,timeout=30000):Promise<any>{
   check();if(!this.hostOnline(s))throw new HttpError(409,'桌面端未连接,请在电脑上打开夭夭。','desktop_offline')

+ 72 - 17
src/server/realtimeBroker.ts

@@ -330,14 +330,43 @@ export class RealtimeBroker {
     }
     return u
   }
+  private authorized(p: RealtimePrincipal): boolean {
+    try { if (!p.valid()) return false; p.authorize?.('chat'); return true } catch { return false }
+  }
+  private connectionPrincipal(u: Upstream): RealtimePrincipal | undefined {
+    if (this.authorized(u.principal)) return u.principal
+    // A service transport may outlive its first browser session and serve other users.
+    const candidates = [
+      ...[...this.channels.values()].filter(c => c.principal.upstreamKey === u.principal.upstreamKey).map(c => c.principal),
+      ...[...u.routes.values()].flatMap(r => [...r.observers.values()]),
+    ]
+    const principal = candidates.find(p => this.authorized(p))
+    if (principal) u.principal = principal
+    return principal
+  }
+  private scheduleReconnect(u: Upstream): void {
+    if (this.closed || this.upstreams.get(u.principal.upstreamKey) !== u || u.retry || !this.connectionPrincipal(u)) return
+    u.retry = setTimeout(() => {
+      u.retry = undefined
+      void this.connect(u).catch(() => {})
+    }, Math.min(15_000, 500 * 2 ** Math.min(u.attempts++, 5)))
+    u.retry.unref()
+  }
   private connect(u: Upstream): Promise<void> {
+    if (this.closed || this.upstreams.get(u.principal.upstreamKey) !== u) return Promise.reject(new Error('Broker transport closed'))
     if (u.connecting) return u.connecting
     if (u.socket?.readyState === WebSocket.OPEN && u.ready) return Promise.resolve()
+    clearTimeout(u.retry); u.retry = undefined
     u.connecting = (async () => {
-      const url = await u.principal.url('chat')
-      if (this.closed) throw new Error('Broker closed')
+      // Let the previous socket's recovery unwind before starting another generation.
+      await u.recovery?.catch(() => {})
+      const principal = this.connectionPrincipal(u)
+      if (!principal) throw new HttpError(401, 'Authentication expired', 'authentication_required')
+      const url = await principal.url('chat')
+      if (this.closed || this.upstreams.get(principal.upstreamKey) !== u) throw new Error('Broker transport closed')
+      if (!this.authorized(principal)) throw new HttpError(401, 'Authentication expired', 'authentication_required')
       await new Promise<void>((resolve, reject) => {
-        const ws = new WebSocket(url, { agent: u.principal.agent, headers: { Origin: `${url.protocol === 'wss:' ? 'https:' : 'http:'}//${url.host}` }, maxPayload: CHAT_MAX_PAYLOAD, handshakeTimeout: 15_000 })
+        const ws = new WebSocket(url, { agent: principal.agent, headers: { Origin: `${url.protocol === 'wss:' ? 'https:' : 'http:'}//${url.host}` }, maxPayload: CHAT_MAX_PAYLOAD, handshakeTimeout: 15_000 })
         u.socket = ws
         const timeout = setTimeout(() => { reject(new Error('Upstream ready timeout')); ws.terminate() }, 20_000)
         let ready = false
@@ -346,12 +375,20 @@ export class RealtimeBroker {
           let f: Frame
           try { f = JSON.parse(data.toString()) } catch { ws.terminate(); return }
           if (f.method === 'event' && f.params?.type === 'gateway.ready') {
-            clearTimeout(timeout); ready = true; u.ready = f; u.attempts = 0
+            if (ready) return
+            clearTimeout(timeout); ready = true; u.ready = f
             const epoch = f.params.payload?.replay_epoch
             const changed = u.epoch !== undefined && epoch !== u.epoch
             u.epoch = epoch
-            if (u.routes.size) u.recovery = this.recover(u, changed).finally(() => { u.recovery = undefined })
-            resolve()
+            const recovery = u.routes.size ? this.recover(u, changed) : Promise.resolve()
+            u.recovery = recovery
+            void recovery.then(() => {
+              if (this.closed || u.socket !== ws || ws.readyState !== WebSocket.OPEN) throw new Error('Upstream disconnected during recovery')
+              u.attempts = 0
+              resolve()
+            }).catch(error => { reject(error); ws.terminate() }).finally(() => {
+              if (u.recovery === recovery) u.recovery = undefined
+            })
           } else if (f.id !== undefined) {
             const pending = u.pending.get(String(f.id))
             if (pending) { clearTimeout(pending.timer); u.pending.delete(String(f.id)); pending.resolve(f) }
@@ -359,23 +396,24 @@ export class RealtimeBroker {
         })
         let alive = true
         ws.on('pong', () => { alive = true })
-        u.ping = setInterval(() => { if (!alive) ws.terminate(); else if (ws.readyState === WebSocket.OPEN) { alive = false; ws.ping() } }, 25_000)
-        u.ping.unref()
+        const ping = setInterval(() => { if (!alive) ws.terminate(); else if (ws.readyState === WebSocket.OPEN) { alive = false; ws.ping() } }, 25_000)
+        u.ping = ping; ping.unref()
         ws.on('error', () => { if (!ready) reject(new Error('Upstream connection failed')) })
         ws.on('close', () => {
-          clearTimeout(timeout); clearInterval(u.ping)
+          clearTimeout(timeout); clearInterval(ping)
           if (u.socket !== ws) return
           u.socket = undefined; u.ready = undefined
-          if (!ready) reject(new Error('Upstream disconnected'))
+          reject(new Error('Upstream disconnected'))
           for (const pending of u.pending.values()) { clearTimeout(pending.timer); pending.reject(new Error('Upstream disconnected; result unknown')) }
           u.pending.clear()
-          if (!this.closed && this.upstreams.get(u.principal.upstreamKey) === u) {
-            u.retry = setTimeout(() => { u.retry = undefined; void this.connect(u).catch(() => {}) }, Math.min(15_000, 500 * 2 ** Math.min(u.attempts++, 5)))
-            u.retry.unref()
-          }
+          this.scheduleReconnect(u)
         })
       })
-    })().finally(() => { u.connecting = undefined })
+    })().catch(error => {
+      // Credentials and readiness can fail before any WebSocket close callback exists.
+      this.scheduleReconnect(u)
+      throw error
+    }).finally(() => { u.connecting = undefined })
     return u.connecting
   }
   private rpc(u: Upstream, method: string, params: Frame, observed?: (frame: Frame) => void, sent?: (frame: Frame) => void): Promise<Frame> {
@@ -496,6 +534,23 @@ export class RealtimeBroker {
       for (const r of u.routes.values()) {
         const lastSeen = r.seq
         const resumed = await this.rpc(u, 'session.resume', { session_id: r.stored, profile: r.profile, close_on_disconnect: false, omit_messages: true })
+        if (resumed.error?.code === 4007 || resumed.error?.code === 'session_not_found') {
+          // Hermes' session.resume uses 4007 for a missing stored session. Retire
+          // only that route; a deleted session must not reconnect the whole service forever.
+          this.reset(u, 'upstream_session_missing')
+          this.event(u, { method: 'event', params: { type: 'error', session_id: r.runtime,
+            payload: { code: 'session_not_found', message: 'Hermes 中的原会话已不存在,无法恢复。' } } }, true)
+          r.active = false
+          const key = this.routeKey(r.profile, r.stored)
+          u.routes.delete(key); u.byRuntime.delete(r.runtime)
+          this.routeOwners.delete(JSON.stringify([u.principal.instanceKey ?? u.principal.upstreamKey, r.profile, r.stored]))
+          for (const c of this.channels.values()) if (c.principal.upstreamKey === u.principal.upstreamKey) c.routes.delete(key)
+          for (const [id, runtime] of this.interactions) if (id.startsWith(`${u.principal.upstreamKey}:`) && runtime === r.runtime) this.interactions.delete(id)
+          continue
+        }
+        if (resumed.error || typeof resumed.result?.session_id !== 'string' || !resumed.result.session_id) {
+          throw new Error('Upstream session recovery failed')
+        }
         r.workingDirectory = undefined
         r.cwd = typeof resumed.result?.info?.cwd === 'string' ? resumed.result.info.cwd : undefined
         if (typeof resumed.result?.running === 'boolean') r.active = resumed.result.running
@@ -506,7 +561,7 @@ export class RealtimeBroker {
               snapshot?resumed.result:{...resumed.result,inflight:undefined})
           }
         }
-        if (!resumed.result || resumed.result.session_id !== r.runtime || changed) {
+        if (resumed.result.session_id !== r.runtime || changed) {
           if (resumed.result?.session_id) { u.byRuntime.delete(r.runtime); r.runtime = resumed.result.session_id; u.byRuntime.set(r.runtime, r) }
           r.seq = 0; this.reset(u, 'upstream_reset'); restore(true); continue
         }
@@ -514,7 +569,7 @@ export class RealtimeBroker {
         if (replay.error || replay.result?.truncated || replay.result?.epoch !== u.epoch) {this.reset(u, 'upstream_replay_unavailable');restore(true)}
         else {for (const p of replay.result?.events ?? []) this.event(u, { jsonrpc: '2.0', method: 'event', params: p }, true);restore(false)}
       }
-    } catch { this.reset(u, 'upstream_recovery_failed') }
+    } catch (error) { this.reset(u, 'upstream_recovery_failed'); throw error }
     finally {
       u.recovering = false
       const deferred = u.deferred; u.deferred = []

+ 43 - 6
src/server/workspaceGateway.ts

@@ -277,6 +277,10 @@ export class WorkspaceNodes {
 
 /** One server-owned transport per execution binding, never tied to a browser. */
 export class WorkspaceGateway {
+  private closed = false
+  private generation = 0
+  private available = false
+  get connected(): boolean { return this.available }
   private serverRequests = new Map<string, {method:'approval'|'clarify';sessionId:string}>()
   private socket?: WebSocket
   private paired?: WorkspacePairedChannel
@@ -289,15 +293,26 @@ export class WorkspaceGateway {
   onDisconnect: () => void = () => {}
   constructor(readonly target: GatewayTarget,readonly scope?:GatewayExecutionScope) {}
   async connect(): Promise<void> {
-    if(this.target.runner){this.runner=await this.target.runner.open(frame=>this.onEvent(frame),()=>this.onDisconnect(),this.scope);return}
+    if (this.closed) throw new Error('Hermes connection closed')
+    const generation = ++this.generation
+    const active = () => !this.closed && generation === this.generation
+    const disconnected = () => { if(active()){this.available=false;this.onDisconnect()} }
+    if(this.target.runner){
+      const runner=await this.target.runner.open(frame=>{if(active())this.onEvent(frame)},disconnected,this.scope)
+      if(!active()){runner.close();throw new Error('Hermes connection closed')}
+      this.runner=runner;this.available=true;return
+    }
     if (this.target.pairedToken) {
       this.paired = new WorkspacePairedChannel(this.target.url, this.target.pairedToken, this.target.client.fetchImpl,
-        frame => this.onEvent(frame), () => this.onDisconnect())
+        frame => {if(active())this.onEvent(frame)}, disconnected)
       await this.paired.connect()
+      if(!active())throw new Error('Hermes connection closed')
+      this.available = true
       return
     }
     const credential = await this.target.session.webSocketCredential(),
       url = new URL(this.target.url)
+    if (!active()) throw new Error('Hermes connection closed')
     url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:'
     url.pathname = `${url.pathname.replace(/\/$/, '')}/api/ws`
     url.search = ''
@@ -318,7 +333,17 @@ export class WorkspaceGateway {
       socket.terminate()
       failed(new Error('Hermes gateway readiness timed out'))
     }, 20_000)
+    let awaitingPong = false
+    const heartbeat = setInterval(() => {
+      if (!active() || socket.readyState !== WebSocket.OPEN) return
+      if (awaitingPong) { socket.terminate(); return }
+      awaitingPong = true
+      socket.ping()
+    }, 15_000)
+    heartbeat.unref()
+    socket.on('pong', () => { awaitingPong = false })
     socket.on('message', (raw) => {
+      if (!active()) return
       try {
         const frame = JSON.parse(raw.toString()),
           waiter = this.pending.get(String(frame.id))
@@ -360,17 +385,21 @@ export class WorkspaceGateway {
       failed(error)
     })
     socket.on('close', () => {
+      clearInterval(heartbeat)
+      clearTimeout(handshakeTimer)
+      failed(new Error('Hermes connection closed'))
+      if (!active()) return
       for (const waiter of this.pending.values()) {
         clearTimeout(waiter.timer)
         waiter.reject(new Error('Hermes connection closed'))
       }
       this.pending.clear()
       this.serverRequests.clear()
-      this.onDisconnect()
-      clearTimeout(handshakeTimer)
-      failed(new Error('Hermes connection closed'))
+      disconnected()
     })
     await handshake
+    if (!active() || socket.readyState !== WebSocket.OPEN) throw new Error('Hermes connection closed')
+    this.available = true
   }
   private acceptServerRequest(frame:any):boolean {
     if(!['approval','clarify'].includes(frame?.method)||typeof frame.id!=='string'||typeof frame.params?.session_id!=='string')return false
@@ -424,10 +453,18 @@ export class WorkspaceGateway {
     })
   }
   close(): void {
+    this.closed = true
+    this.available = false
+    this.generation++
     this.onDisconnect = () => {}
+    for (const waiter of this.pending.values()) {
+      clearTimeout(waiter.timer)
+      waiter.reject(new Error('Hermes connection closed'))
+    }
+    this.pending.clear()
     this.serverRequests.clear()
     this.paired?.close()
     this.runner?.close()
-    this.socket?.close()
+    this.socket?.terminate()
   }
 }

+ 111 - 32
src/server/workspaceRuntime.ts

@@ -2,6 +2,7 @@ import {type DesktopEnvironments} from './desktopEnvironments.js'
 import {type GrokCloud} from './grokCloud.js'
 import {VmToolSession} from './vmComputer.js'
 import { randomUUID } from 'node:crypto'
+import { setTimeout as delay } from 'node:timers/promises'
 import { readFileSync } from 'node:fs'
 import { z } from 'zod'
 import { WorkspaceStore, parse } from './workspaceStore.js'
@@ -69,6 +70,8 @@ export interface WorkspaceBinding {
   conversationTaskId?: string
   taskId?: string
   contextSeq?: number
+  /** This admitted turn needs its original in-memory tool grant to keep running. */
+  toolsBound?: boolean
 }
 interface LiveTurn {
   gateway: WorkspaceGateway
@@ -385,6 +388,7 @@ export class WorkspaceRuntime extends WorkspaceScheduler {
     let flushTimer: ReturnType<typeof setTimeout> | undefined
     let usageCompletion: Promise<void> | undefined
     let submittedText = ''
+    let reconnecting: Promise<void> | undefined
     const toolController = new AbortController()
     let toolLease: WorkspaceToolLease | undefined
     let pluginLease: OpenBotPlugins | undefined
@@ -460,8 +464,105 @@ export class WorkspaceRuntime extends WorkspaceScheduler {
       } catch (failure) { rejectTurn(failure instanceof Error ? failure : new Error('无法保存执行状态')) }
       finally { vmTools?.close(); if (usageCompletion) void usageCompletion.finally(() => gateway.close()); else gateway.close() }
     }
-    gateway.onDisconnect = () =>
-      finish(completedEvidence ? undefined : new Error('Hermes 连接断开'))
+    const restoreCompleted = async () => {
+      const marker = `[yaoyao-run:${run.runId}:${resultMessage.id}]`
+      let answer: { content?: string; text?: string } | undefined
+      let found = false, seenLastEvent = false
+      for (let page = 0; page < 20 && !found; page++) {
+        const response = await target.session.request(`/api/sessions/${encodeURIComponent(binding!.storedId)}/messages`, {
+          search: new URLSearchParams({ profile: agent.profile, limit: '500', offset: String(page * 500), order: 'latest', include_compacted: 'true' }),
+          maxResponseBytes: 8 * 1024 * 1024,
+        })
+        if (settled) return
+        gateway.scope?.authorize()
+        if (response.status !== 200) throw new Error('无法核对历史')
+        const history = JSON.parse(response.body.toString()).messages
+        if (!Array.isArray(history)) throw new Error('历史响应无效')
+        for (const item of [...history].reverse()) {
+          if (item.role === 'user') {
+            if (String(item.content ?? item.text).includes(marker)) { found = true; break }
+            answer = undefined; seenLastEvent = false
+          } else if (!seenLastEvent && ['assistant', 'tool'].includes(item.role)) {
+            seenLastEvent = true
+            const calls = item.tool_calls
+            const hasCalls = Array.isArray(calls) ? calls.length > 0 : !!calls && calls !== '[]'
+            if (item.role === 'assistant' && !hasCalls && !item.function_call && item.finish_reason !== 'tool_calls' && (item.content || item.text)) answer = item
+          }
+        }
+        if (history.length < 500) break
+      }
+      if (!found || !answer) throw new Error('无法确认本轮的最终回复,正在核对原执行;不会重复提交')
+      resultMessage.content = String(answer.content ?? answer.text)
+      binding!.contextSeq = Math.max(binding!.contextSeq ?? 0, run.contextThroughSeq ?? 0)
+      this.store.put(owner, 'binding', key, binding!)
+      finish()
+    }
+    const lostTools = () => new HttpError(409, '原执行仍在运行,但本轮工具授权已丢失,无法完整恢复;请停止后重新发起。', 'workspace_tool_lease_lost')
+    const recoverTransport = async () => {
+      let attempt = 0
+      while (!settled) {
+        try {
+          gateway.scope?.authorize()
+          await delay(Math.min(30_000, 500 * 2 ** Math.min(attempt++, 6)), undefined, { signal: toolController.signal })
+          gateway.scope?.authorize()
+          if (!gateway.connected) await gateway.connect()
+          if (settled) return
+          gateway.scope?.authorize()
+          const opened = await gateway.rpc('session.resume', { profile: agent.profile, session_id: binding!.storedId, omit_messages: true, close_on_disconnect: false })
+          if (settled) return
+          gateway.scope?.authorize()
+          if (!opened.session_id || (opened.info?.profile_name && opened.info.profile_name !== agent.profile)) throw new Error('Hermes 会话身份不匹配')
+          runtimeId = String(opened.session_id)
+          const previousStoredId = binding!.storedId
+          const storedId = String(opened.stored_session_id ?? opened.session_key ?? opened.resumed ?? previousStoredId)
+          if (!storedId) throw new Error('Hermes 会话身份不匹配')
+          binding!.storedId = storedId
+          binding!.aliases = [...new Set([...binding!.aliases, previousStoredId, storedId])]
+          binding!.runtimeId = runtimeId
+          this.store.put(owner, 'binding', key, binding!)
+          const live = this.live.get(key)
+          if (live?.taskId === run.id) live.runtimeId = runtimeId
+          if (!opened.running) {
+            try { await restoreCompleted() } catch (error) { finish(error instanceof Error ? error : new Error('无法核对原执行')) }
+            return
+          }
+          if (binding!.toolsBound && !toolLease) throw lostTools()
+          if (toolLease) {
+            try { await toolLease.bind() }
+            catch (error) {
+              if (error instanceof HttpError && (error.code === 'team_tools_bind_failed' || error.code === 'hermes_bridge_session_busy')) throw lostTools()
+              throw error
+            }
+          }
+          if (settled) return
+          gateway.scope?.authorize()
+          if (!gateway.connected) continue
+          const current = this.getWork(owner, run.id)
+          current.error = undefined
+          if (current.status === 'uncertain') current.status = 'running'
+          resultMessage.status = 'streaming'; resultMessage.error = undefined
+          this.store.atomic(() => { this.saveWork(owner, current); this.store.saveMessage(owner, resultMessage) })
+          return
+        } catch (error) {
+          if (settled) return
+          try { gateway.scope?.authorize() } catch (revoked) { finish(revoked instanceof Error ? revoked : new Error('本轮授权已结束')); return }
+          if (error instanceof HttpError && error.code === 'workspace_tool_lease_lost') { finish(error); return }
+          // No new prompt is admitted while the original outcome is unknown.
+          const current = this.getWork(owner, run.id)
+          current.error = error instanceof Error ? error.message : '正在恢复 Hermes 连接'
+          this.saveWork(owner, current)
+        }
+      }
+    }
+    gateway.onDisconnect = () => {
+      if (settled || reconnecting) return
+      if (completedEvidence || !submitted || !binding?.storedId || !runtimeId) { finish(completedEvidence ? undefined : new Error('Hermes 连接断开')); return }
+      const current = this.getWork(owner, run.id)
+      current.error = 'Hermes 连接断开,正在恢复原执行'
+      this.saveWork(owner, current)
+      reconnecting = recoverTransport().finally(() => { reconnecting = undefined })
+      void reconnecting.catch(error => finish(error instanceof Error ? error : new Error('无法恢复 Hermes 连接')))
+    }
     gateway.onEvent = (frame: GatewayFrame) => {
       if (settled || !runtimeId || frame.session_id !== runtimeId) return
       const currentTurn = this.getWork(owner, run.id)
@@ -638,6 +739,7 @@ export class WorkspaceRuntime extends WorkspaceScheduler {
       )
         throw new Error('Hermes 会话身份不匹配')
       binding = {
+        toolsBound: recovering ? binding?.toolsBound : undefined,
         memoryVersion: binding?.memoryVersion,
         memoryState: binding?.memoryState,
         memoryPending: binding?.memoryPending,
@@ -671,39 +773,12 @@ export class WorkspaceRuntime extends WorkspaceScheduler {
         throw new Error('运行已停止')
       if (recovering) {
         if (opened.running) {
+          if (binding.toolsBound) throw lostTools()
           const current = this.getWork(owner, run.id)
           current.status = 'running'
           this.saveWork(owner, current)
         } else {
-          const marker = `[yaoyao-run:${run.runId}:${resultMessage.id}]`
-          let answer: { content?: string; text?: string } | undefined
-          let found = false, seenLastEvent = false
-          for (let page = 0; page < 20 && !found; page++) {
-            const response = await target.session.request(`/api/sessions/${encodeURIComponent(storedId)}/messages`, {
-              search: new URLSearchParams({ profile: agent.profile, limit: '500', offset: String(page * 500), order: 'latest', include_compacted: 'true' }),
-              maxResponseBytes: 8 * 1024 * 1024,
-            })
-            if (response.status !== 200) throw new Error('无法核对历史')
-            const history = JSON.parse(response.body.toString()).messages
-            if (!Array.isArray(history)) throw new Error('历史响应无效')
-            for (const item of [...history].reverse()) {
-              if (item.role === 'user') {
-                if (String(item.content ?? item.text).includes(marker)) { found = true; break }
-                answer = undefined; seenLastEvent = false
-              } else if (!seenLastEvent && ['assistant', 'tool'].includes(item.role)) {
-                seenLastEvent = true
-                const calls = item.tool_calls
-                const hasCalls = Array.isArray(calls) ? calls.length > 0 : !!calls && calls !== '[]'
-                if (item.role === 'assistant' && !hasCalls && !item.function_call && item.finish_reason !== 'tool_calls' && (item.content || item.text)) answer = item
-              }
-            }
-            if (history.length < 500) break
-          }
-          if (!found || !answer) throw new Error('无法确认本轮的最终回复,正在核对原执行;不会重复提交')
-          resultMessage.content = String(answer.content ?? answer.text)
-          binding.contextSeq = Math.max(binding.contextSeq ?? 0, run.contextThroughSeq ?? 0)
-          this.store.put(owner, 'binding', key, binding)
-          finish()
+          await restoreCompleted()
         }
       } else {
         if (opened.running) throw new HttpError(409, '上游会话仍在运行', 'session_busy')
@@ -759,6 +834,8 @@ export class WorkspaceRuntime extends WorkspaceScheduler {
             onFailure:error=>{if(!settled)void gateway.rpc('session.interrupt',{session_id:runtimeId}).catch(()=>{}).finally(()=>finish(error))},
           })
           await toolLease.bind();if(settled)return await completion
+          binding.toolsBound = true
+          this.store.put(owner, 'binding', key, binding)
         }
         const workingDirectory = await applyWorkingDirectory((method, params) => gateway.rpc(method, params), runtimeId, cwd, undefined, opened.info?.cwd)
         environment.cwd=workingDirectory?.resolved
@@ -861,6 +938,7 @@ export class WorkspaceRuntime extends WorkspaceScheduler {
       }
       return await completion
     } catch (error) {
+      if (reconnecting && submitted && !settled) return await completion
       finish(error instanceof Error ? error : new Error('执行失败'))
       return await completion
     }
@@ -941,7 +1019,8 @@ export class WorkspaceRuntime extends WorkspaceScheduler {
     const key = this.bindingKey(work.conversationId, work.conversationTaskId, work.agentId)
     const live = this.live.get(key)
     if (live?.taskId === work.id) {
-      await live.gateway.rpc('session.interrupt', { session_id: live.runtimeId })
+      try { await live.gateway.rpc('session.interrupt', { session_id: live.runtimeId }) }
+      catch (error) { if (!live.gateway.connected) live.done(new Error('已停止')); throw error }
       const current = this.getWork(owner, work.id)
       if (['complete', 'failed', 'interrupted'].includes(current.status)) {
         live.done(new Error('已停止'))

+ 1 - 1
src/server/workspaceScheduler.ts

@@ -181,7 +181,7 @@ export abstract class WorkspaceScheduler {
     } else {
       root.status = active.some(t => t.status === 'uncertain') ? 'uncertain' : active.some(t => t.status === 'running') ? 'running' : active.some(t => t.status === 'waiting') ? 'waiting' : tasks.some(t => t.status !== 'queued') ? 'running' : 'queued'
     }
-    root.error = tasks.find(t => t.status === 'uncertain' || t.status === 'failed')?.error
+    root.error = tasks.find(t => t.status === 'uncertain' || t.status === 'failed')?.error ?? active.find(t => t.error)?.error
     this.store.saveRun(owner, root)
     if (done && !wasTerminal) this.onRunSettled(owner, root)
     if (done && !wasTerminal && root.status !== 'interrupted') {

+ 19 - 5
src/server/workspaceToolLease.ts

@@ -30,6 +30,8 @@ async function bridgeRequest(target: GatewayTarget, path: string, body: unknown)
       && /^[a-z0-9][a-z0-9_-]{0,63}$/.test(body.profile) ? ` Profile「${body.profile}」` : ''
     if (path === '/bind' && Object.hasOwn(failures, code))
       throw new HttpError(response.status >= 500 ? 502 : 409, `Hermes${profile}${failures[code]}。`, `hermes_bridge_${code}`)
+    if (response.status >= 500 || response.status === 408 || response.status === 429)
+      throw new HttpError(502, 'Hermes 工具桥暂时不可用,正在重试原授权。', 'team_tools_bridge_unavailable')
     throw new HttpError(409, 'Hermes 工具桥绑定失败,请确认该 Profile 已启用工具桥,并新建会话后重试。', 'team_tools_bind_failed')
   }
   return value
@@ -73,6 +75,7 @@ export async function createWorkspaceToolLease(input: LeaseInput): Promise<Works
   const token = randomBytes(32).toString('base64url'), tokenHash = createHash('sha256').update(token).digest()
   const generation = `${input.workId}:${randomUUID()}`
   let expiresAt = Date.now() + TTL, closed = false, url = ''
+  let renewAfter = Date.now() + 5 * 60_000
   let timer: ReturnType<typeof setInterval> | undefined
   let binding: Promise<void> | undefined, cleanup: Promise<void> | undefined
   let boundRuntimeId = ''
@@ -181,8 +184,9 @@ export async function createWorkspaceToolLease(input: LeaseInput): Promise<Works
     binding = (async () => {
       const bindSession = async () => {
         const current = input.session()
+        const requestedExpiry = Date.now() + TTL
         const result = await bridgeRequest(input.target, '/bind', { native_tools: true, session_id: current.runtimeId,
-          stored_session_id: current.storedId, profile: input.profile, generation, bridge_url: url, token, expires_at: expiresAt,
+          stored_session_id: current.storedId, profile: input.profile, generation, bridge_url: url, token, expires_at: requestedExpiry,
           ...(input.computerPolicy ? {computer_policy: input.computerPolicy} : {}),
           ...(input.workspaceMemory ? {workspace_memory: true} : {}) })
         if(input.workspaceMemory&&result.workspace_memory!==true)
@@ -191,6 +195,10 @@ export async function createWorkspaceToolLease(input: LeaseInput): Promise<Works
           throw new HttpError(409, '请更新 Hermes 的夭夭工具桥,当前版本尚未接管隔离电脑会话。', 'computer_bridge_upgrade_required')
         if (!bound && result.native_tools !== true)
           throw new HttpError(409, 'Hermes 未挂载本轮原生团队工具,请升级或修复工具桥。', 'team_tools_unavailable')
+        // A lost renewal receipt cannot extend the original local grant.
+        assertActive()
+        expiresAt = requestedExpiry
+        renewAfter = Date.now() + 5 * 60_000
         bound = true
       }
       try { await bindSession() }
@@ -214,11 +222,17 @@ export async function createWorkspaceToolLease(input: LeaseInput): Promise<Works
     input.signal.addEventListener('abort', abort, { once: true })
     assertActive()
     timer = setInterval(() => {
-      if (binding) return
       try { assertActive() } catch (error) { void dispose(); input.onFailure(error as Error); return }
-      expiresAt = Date.now() + TTL
-      void bind().catch(error => { void dispose(); input.onFailure(error as Error) })
-    }, 5 * 60_000)
+      if (binding || Date.now() < renewAfter) return
+      void bind().catch(error => {
+        if (closed) return
+        const rejected = error instanceof HttpError && ['team_tools_bind_failed', 'hermes_bridge_session_busy', 'hermes_bridge_agent_initialization_failed'].includes(error.code)
+        const transient = !(error instanceof HttpError) || !rejected && (error.status >= 500 || [408, 429].includes(error.status)
+          || ['hermes_bridge_initializing', 'hermes_bridge_binding_busy', 'hermes_bridge_bridge_catalog_unreachable'].includes(error.code))
+        if (transient && Date.now() < expiresAt) return
+        void dispose(); input.onFailure(error as Error)
+      })
+    }, 30_000)
     timer.unref()
     return { bind, dispose, async profileRequest(path, body) {
       assertActive()

+ 4 - 3
src/shared/fileTransferEndpoint.mjs

@@ -1,6 +1,7 @@
 import { open, realpath, mkdir, mkdtemp, unlink, rename, link, rm } from 'node:fs/promises'
 import { constants } from 'node:fs'
-import { resolve, dirname, join, sep } from 'node:path'
+import { resolve, dirname, join } from 'node:path'
+import { hostPathInput, pathInside } from './hostPaths.mjs'
 import { tmpdir } from 'node:os'
 import { createHash } from 'node:crypto'
 
@@ -16,8 +17,8 @@ export class FileTransferFiles {
   }
   async path(input, writing = false) {
     require(typeof input === 'string' && input.length > 0 && input.length <= 4096 && !input.includes('\0'), '文件路径无效')
-    const root = await realpath(this.root), raw = resolve(root, input.replace(/^~\//, '').replace(/^~$/, ''))
-    const inside = value => !this.confined || value === root || value.startsWith(root + sep)
+    const root = await realpath(this.root), raw = resolve(root, hostPathInput(input))
+    const inside = value => !this.confined || pathInside(root, value)
     require(inside(raw), '路径超出允许范围')
     if (!writing) { const file = await realpath(raw); require(inside(file), '路径超出允许范围'); return file }
     let parent = dirname(raw)

+ 22 - 0
src/shared/hostPaths.mjs

@@ -0,0 +1,22 @@
+import path from 'node:path'
+
+export function hostPathInput(input, platform = process.platform) {
+  const value = String(input ?? '')
+  if (value.includes('\0')) throw new Error('路径无效')
+  if (platform === 'win32') {
+    // File tools never accept device namespaces, UNC shares, drive-relative
+    // paths, alternate data streams, or Win32 names with ambiguous semantics.
+    if (/^[\\/]{2}|^[A-Za-z]:(?![\\/])/.test(value)) throw new Error('路径无效')
+    const rest = value.replace(/^[A-Za-z]:/, '')
+    if (rest.includes(':') || rest.split(/[\\/]/).some(part =>
+      (part !== '.' && part !== '..' && /[ .]$/.test(part)) || /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(part))) throw new Error('路径无效')
+    return value.replace(/^~[\\/]/, '').replace(/^~$/, '')
+  }
+  return value.replace(/^~\//, '').replace(/^~$/, '')
+}
+
+export function pathInside(root, target, platform = process.platform) {
+  const api = platform === 'win32' ? path.win32 : path.posix
+  const relative = api.relative(root, target)
+  return relative === '' || (!api.isAbsolute(relative) && relative !== '..' && !relative.startsWith('..' + api.sep))
+}

+ 99 - 0
tests/client/conversationRecovery.test.ts

@@ -0,0 +1,99 @@
+import { afterEach, beforeEach, expect, it, vi } from 'vitest'
+import { flushPromises, shallowMount, type VueWrapper } from '@vue/test-utils'
+import { shallowRef } from 'vue'
+import { createMemoryHistory, createRouter, matchedRouteKey } from 'vue-router'
+import ConversationsView from '@/views/ConversationsView.vue'
+import WorkspaceMessageTimeline from '@/components/workspace/WorkspaceMessageTimeline.vue'
+import { apiRequest } from '@/api/client'
+
+vi.mock('@/api/client', async importOriginal => ({ ...await importOriginal<typeof import('@/api/client')>(), apiRequest: vi.fn(), setApiCsrfToken: vi.fn() }))
+vi.mock('@/stores/auth', () => ({ useAuthStore: () => ({ user: { id: 'owner' }, profiles: [], refreshProfileAvatars: async () => {} }) }))
+vi.mock('@/stores/theme', () => ({ useThemeStore: () => ({}) }))
+let wrapper: VueWrapper | undefined
+const sources: Array<{ url: string; close: ReturnType<typeof vi.fn> }> = []
+beforeEach(() => {
+  vi.useFakeTimers()
+  sources.length = 0
+  vi.stubGlobal('EventSource', class extends EventTarget {
+    readonly close = vi.fn()
+    constructor(readonly url: string) { super(); sources.push(this) }
+  })
+})
+afterEach(() => {
+  wrapper?.unmount(); wrapper = undefined
+  vi.mocked(apiRequest).mockReset(); vi.restoreAllMocks(); vi.unstubAllGlobals(); vi.useRealTimers()
+})
+async function mountView(path = '/conversations') {
+  const router = createRouter({ history: createMemoryHistory(), routes: [{ path: '/conversations/:id?', component: { template: '<div />' } }] })
+  await router.push(path); await router.isReady()
+  wrapper = shallowMount(ConversationsView, { global: {
+    provide: { [matchedRouteKey as symbol]: shallowRef(router.currentRoute.value.matched[0]) }, plugins: [router],
+    stubs: { WorkspaceShell: { template: '<div><slot name="sidebar" /><slot /></div>' }, ComposerShell: { template: '<div />', methods: { filesSnapshot: () => [] } }, Teleport: true },
+  } })
+  await flushPromises()
+}
+function successfulResponse(path: string) {
+  if (path === '/api/app/capabilities') return { features: [] }
+  if (path === '/api/app/workspace/snapshot') return { agents: [], conversations: [], details: [], cursor: 17 }
+  throw new Error(`Unexpected request ${path}`)
+}
+it('recovers an initial server outage while the browser stays online', async () => {
+  vi.mocked(apiRequest).mockRejectedValueOnce(new Error('服务暂不可用')).mockImplementation(async path => successfulResponse(path) as never)
+  await mountView()
+  expect(sources).toHaveLength(0)
+  await vi.advanceTimersByTimeAsync(1500); await flushPromises()
+  expect(sources.map(source => source.url)).toEqual(['/api/app/events/stream?after=17'])
+  expect(vi.mocked(apiRequest).mock.calls.filter(([path]) => path === '/api/app/capabilities')).toHaveLength(2)
+})
+it('cancels a scheduled initial recovery when the view is destroyed', async () => {
+  vi.mocked(apiRequest).mockRejectedValue(new Error('服务暂不可用'))
+  await mountView()
+  wrapper!.unmount(); wrapper = undefined
+  await vi.advanceTimersByTimeAsync(10_000)
+  expect(apiRequest).toHaveBeenCalledTimes(1)
+  expect(sources).toHaveLength(0)
+})
+it('aborts an in-flight snapshot and prevents a late response from connecting after destruction', async () => {
+  let signal: AbortSignal | undefined, release!: (value: unknown) => void
+  vi.mocked(apiRequest).mockImplementation(async (path, options) => {
+    if (path === '/api/app/capabilities') return successfulResponse(path) as never
+    signal = options?.signal as AbortSignal
+    return new Promise(resolve => { release = resolve })
+  })
+  await mountView()
+  expect(signal?.aborted).toBe(false)
+  wrapper!.unmount(); wrapper = undefined
+  expect(signal?.aborted).toBe(true)
+  release(successfulResponse('/api/app/workspace/snapshot'))
+  await flushPromises(); await vi.advanceTimersByTimeAsync(10_000)
+  expect(sources).toHaveLength(0)
+  expect(apiRequest).toHaveBeenCalledTimes(2)
+})
+it('cancels recovery while offline and restarts it only when connectivity returns', async () => {
+  let online = true
+  vi.spyOn(navigator, 'onLine', 'get').mockImplementation(() => online)
+  vi.mocked(apiRequest).mockRejectedValueOnce(new Error('服务暂不可用')).mockImplementation(async path => successfulResponse(path) as never)
+  await mountView()
+  online = false; window.dispatchEvent(new Event('offline'))
+  await vi.advanceTimersByTimeAsync(10_000)
+  expect(apiRequest).toHaveBeenCalledTimes(1)
+  online = true; window.dispatchEvent(new Event('online')); await flushPromises()
+  expect(sources.map(source => source.url)).toEqual(['/api/app/events/stream?after=17'])
+})
+it('aborts a pending detail on going offline and ignores its late response', async () => {
+  let online = true, signal: AbortSignal | undefined, release!: (value: unknown) => void
+  vi.spyOn(navigator, 'onLine', 'get').mockImplementation(() => online)
+  vi.mocked(apiRequest).mockImplementation(async (path, options) => {
+    if (!path.startsWith('/api/app/conversations/')) return successfulResponse(path) as never
+    signal = options?.signal as AbortSignal
+    return new Promise(resolve => { release = resolve })
+  })
+  await mountView('/conversations/c')
+  expect(signal?.aborted).toBe(false)
+  online = false; window.dispatchEvent(new Event('offline'))
+  expect(signal?.aborted).toBe(true)
+  release({ conversation: { id: 'c', kind: 'direct', name: '迟到会话', memberIds: [], readSeq: 0, lastSeq: 0 }, messages: [], run: null, interactions: [], context: null })
+  await flushPromises(); await vi.advanceTimersByTimeAsync(5000)
+  expect(wrapper!.findComponent(WorkspaceMessageTimeline).props('title')).not.toBe('迟到会话')
+  expect(sources).toHaveLength(0)
+})

+ 39 - 0
tests/client/httpRealtimeRecovery.test.ts

@@ -0,0 +1,39 @@
+import { afterEach, expect, it, vi } from 'vitest'
+import { HTTPRealtimeChannel } from '@/api/httpRealtime'
+const api = vi.hoisted(() => ({ request: vi.fn() }))
+vi.mock('@/api/client', async importOriginal => ({ ...await importOriginal<typeof import('@/api/client')>(), apiRequest: api.request }))
+afterEach(() => { vi.unstubAllGlobals(); vi.useRealTimers(); api.request.mockReset() })
+
+it('times out response headers on every reconnect and preserves the received cursor', async () => {
+  vi.useFakeTimers()
+  api.request.mockResolvedValue({ id: 'channel' })
+  let firstStream!: ReadableStreamDefaultController<Uint8Array>
+  const attempts: RequestInit[] = []
+  vi.stubGlobal('fetch', vi.fn((_url: unknown, options: RequestInit) => {
+    attempts.push(options)
+    if (attempts.length > 1) return new Promise((_resolve, reject) => {
+      options.signal?.addEventListener('abort', () => reject(new Error('headers timed out')), { once: true })
+    })
+    return Promise.resolve(new Response(new ReadableStream<Uint8Array>({ start(controller) {
+      firstStream = controller
+      controller.enqueue(new TextEncoder().encode('id: epoch:9\nevent: frame\ndata: {"params":{"type":"gateway.ready"}}\n\n'))
+    } }), { headers: { 'content-type': 'text/event-stream' } }))
+  }))
+  const failed = vi.fn(), channel = new HTTPRealtimeChannel(async () => {}, failed)
+  try {
+    await channel.open('chat')
+    firstStream.error(new Error('connection lost'))
+    await vi.advanceTimersByTimeAsync(500)
+    expect(attempts).toHaveLength(2)
+    await vi.advanceTimersByTimeAsync(45_000)
+    expect(attempts[1].signal?.aborted).toBe(true)
+    await vi.advanceTimersByTimeAsync(1000)
+    expect(attempts).toHaveLength(3)
+    expect(attempts[2].headers).toMatchObject({ 'Last-Event-ID': 'epoch:9' })
+    expect(failed).not.toHaveBeenCalled()
+  } finally {
+    channel.close()
+    await vi.advanceTimersByTimeAsync(60_000)
+    expect(attempts).toHaveLength(3)
+  }
+})

+ 34 - 0
tests/client/ordinaryTranscriptV2.test.ts

@@ -62,6 +62,40 @@ describe('ordinary v2 durable Web replica', () => {
     } as unknown as TranscriptSnapshot)
     expect(client.snapshot).toBeUndefined()
   })
+  it('rejects an ahead control cursor and ignores a delayed control without replacing state', async () => {
+    const { client, changed } = setup()
+    const saved = { ...client.snapshot, running: true, queued: true, liveStatus: '进行中' }
+    client.restore(saved)
+    await expect(client.control({ epoch: saved.epoch, cursor: saved.cursor + 1, running: false, queued: false })).rejects.toThrow('版本不连续')
+    await client.control({ epoch: saved.epoch, cursor: saved.cursor - 1, running: false, queued: false })
+    expect(changed).not.toHaveBeenCalled()
+    expect(client.snapshot).toEqual(saved)
+    client.close()
+  })
+  it.each(['ready', 'state'])('repairs a %s cursor gap with a snapshot instead of skipping messages', async event => {
+    vi.useFakeTimers()
+    const { client, changed } = setup()
+    const repaired = { ...fixture.snapshot, cursor: 3, hasOlder: false,
+      messages: [{ ...fixture.snapshot.messages[0], revision: 3, content: '补齐的消息' }] }
+    api.request.mockResolvedValue(repaired)
+    let attempts = 0
+    vi.stubGlobal('fetch', vi.fn((_url: unknown, options: RequestInit) => {
+      attempts++
+      return Promise.resolve(new Response(new ReadableStream<Uint8Array>({ start(controller) {
+        if (attempts === 1) controller.enqueue(new TextEncoder().encode(`event: ${event}\ndata: ${JSON.stringify({ epoch: repaired.epoch, cursor: 3, running: false, queued: false })}\n\n`))
+        options.signal?.addEventListener('abort', () => { try { controller.close() } catch {} }, { once: true })
+      } }), { status: 200 }))
+    }))
+    const running = client.run()
+    try {
+      await vi.advanceTimersByTimeAsync(1000)
+      expect(api.request).toHaveBeenCalledWith(expect.stringContaining('/snapshot?'), expect.anything())
+      expect(changed.mock.lastCall![0]).toMatchObject({ cursor: 3, messages: repaired.messages })
+      expect(attempts).toBe(2)
+    } finally {
+      client.close(); await running; vi.unstubAllGlobals(); vi.useRealTimers()
+    }
+  })
   it('reopens an inactive event connection without dropping the durable cursor', async () => {
     vi.useFakeTimers()
     const { client } = setup()

+ 22 - 1
tests/server/desktopEnvironments.test.ts

@@ -36,6 +36,27 @@ it('uses global desktop capabilities for legacy, modern and temporary Bots',asyn
 
 function drive(handle:(c:any)=>unknown=c=>c.operation==='view'?{data:Buffer.from('fixture frame').toString('base64'),width:1280,height:800}:{ok:true}){let results:any[]=[];service.exchange({host,results});const p=setInterval(()=>{const value=service.exchange({host,results});results=value.commands.map(c=>({id:c.id,value:handle(c)}))},5);pollers.add(p);poller=p}
 const HOST_A='11111111-aaaa-4bbb-8ccc-111111111111',HOST_B='22222222-aaaa-4bbb-8ccc-222222222222'
+it('admits Windows computers with independent screen and file grants and preserves source routing',async()=>{
+ const seen:any[]=[]
+ const win={...host,platform:'win32',name:'Windows 工作电脑',full:[ownerKey('owner')],screen:false,accessibility:false}
+ driveRemote(HOST_A,win,c=>{seen.push(c);return {entries:[],path:c.action?.path}})
+ const status=service.hostStates('owner').find(h=>h.id===HOST_A)!
+ expect(status.local).toMatchObject({supported:true,ready:false,fullAuthorized:true})
+ const listing=await service.call('owner',agent.id,'desktop_file_list',{path:'C:\\Users\\测试\\Documents'},new AbortController().signal,()=>{},'local',service.hostEpochs('owner',agent),HOST_A)
+ expect(listing.entries).toEqual([])
+ expect(seen[0].action.path).toBe('C:\\Users\\测试\\Documents')
+ win.screen=true;win.accessibility=true
+ service.remoteExchange(HOST_A,{host:win,results:[]})
+ expect(service.hostStates('owner').find(h=>h.id===HOST_A)!.local.ready).toBe(true)
+ win.full=[];win.approved=[]
+ service.remoteExchange(HOST_A,{host:win,results:[]})
+ expect(service.hostStates('owner').find(h=>h.id===HOST_A)!.local).toMatchObject({ready:false,fullAuthorized:false})
+ await expect(service.call('owner',agent.id,'desktop_file_list',{},new AbortController().signal,()=>{},'local',service.hostEpochs('owner',agent),HOST_A)).rejects.toMatchObject({code:'desktop_full_required'})
+})
+it('unrecognized desktop platforms remain unsupported',()=>{
+ service.remoteExchange(HOST_A,{host:{...host,platform:'unknown',full:[ownerKey('owner')]},results:[]})
+ expect(service.hostStates('owner').find(h=>h.id===HOST_A)!.local).toMatchObject({supported:false,ready:false})
+})
 function driveRemote(id:string,hostInfo:any,handle:(c:any)=>unknown=c=>c.operation==='view'?{data:Buffer.from('remote frame').toString('base64'),width:1280,height:800}:{ok:true}){let results:any[]=[];service.remoteExchange(id,{host:hostInfo,results});const p=setInterval(()=>{const value=service.remoteExchange(id,{host:hostInfo,results});results=value.commands.map(c=>({id:c.id,value:handle(c)}))},5);pollers.add(p);poller=p}
 it('defaults bot work to the customer machine and uses that binding while the server desktop is also online',async()=>{
  agent=store.updateAgent('owner',agent.id,{computer:'local',desktopHost:HOST_A})
@@ -379,7 +400,7 @@ it('lists stable tool targets and separate per-host capabilities without claimin
 const environmentMetadata={version:1 as const,osRelease:'25.0.0',arch:'arm64',shell:'/bin/zsh',homeDirectory:'/Users/fixture',defaultCwd:'/Users/fixture',fileRoots:['/Users/fixture'],shellScope:'user' as const,timezone:'Asia/Shanghai'}
 it('snapshots negotiated host facts per owner without inventing paths for old clients',()=>{
  const result=service.exchange({host:{...host,full:[ownerKey('owner')],fileTransferVersion:1,environment:environmentMetadata},results:[]})
- expect(result.capabilities).toEqual({environmentMetadata:1})
+ expect(result.capabilities).toEqual({environmentMetadata:1,desktopPlatforms:['darwin','win32']})
  service.remoteExchange(HOST_A,{host:{...host,id:randomUUID(),name:'旧客户端'},results:[]})
  const snapshot=service.snapshot('owner',agent,'local'),server=snapshot.hosts.find(host=>host.id==='local')!
  expect(server.metadata).toEqual(environmentMetadata)

+ 72 - 0
tests/server/ordinaryTranscriptReplay.test.ts

@@ -0,0 +1,72 @@
+// @vitest-environment node
+import Koa from 'koa'
+import { mkdtempSync, rmSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import type { Server } from 'node:http'
+import { afterEach, expect, it, vi } from 'vitest'
+import { ChatCacheStore, type ChatCacheCoordinator } from '../../src/server/chatCache'
+import { chatTranscriptRouter } from '../../src/server/chatTranscriptApi'
+import type { LocalAuthStore } from '../../src/server/localAuth'
+import { ChatTranscriptClient } from '../../src/client/api/chatTranscript'
+import type { TranscriptSnapshot } from '../../src/shared/chatTranscript'
+
+const scope = ['owner', 'p', 's'] as const
+const fixtures: Array<{ home: string; store: ChatCacheStore; server: Server }> = []
+afterEach(async () => {
+  vi.unstubAllGlobals()
+  for (const { home, store, server } of fixtures.splice(0)) {
+    store.close()
+    server.closeAllConnections()
+    await new Promise<void>(resolve => server.close(() => resolve()))
+    rmSync(home, { recursive: true, force: true })
+  }
+})
+
+it.each([300, 1000])('replays %i committed events through the HTTP router before confirming the cursor', async count => {
+  const home = mkdtempSync(join(tmpdir(), 'ordinary-replay-')), store = new ChatCacheStore(home)
+  store.recordCommand(...scope, 'session.create', { source: 'web' })
+  store.transcripts.seed(...scope)
+  const base = store.transcripts.snapshot(...scope, {}, 'current')
+  for (let i = 0; i < count; i++) {
+    store.transcripts.upsert(...scope, { id: `m${i}`, role: 'assistant', content: `消息${i}`, status: 'complete' }, i)
+  }
+  const finalCursor = store.transcripts.cursor(...scope)
+  const auth = {
+    require: () => ({ id: scope[0] }), current: () => ({ id: scope[0] }),
+    canUseSource: () => true, isUserActive: () => true, pushAuthorizationVersion: () => 1,
+  } as unknown as LocalAuthStore
+  const router = chatTranscriptRouter({ store, schedule: () => {} } as unknown as ChatCacheCoordinator, auth)
+  const app = new Koa().use(router.routes()).use(router.allowedMethods())
+  const server = app.listen(0, '127.0.0.1')
+  fixtures.push({ home, store, server })
+  await new Promise<void>(resolve => server.once('listening', resolve))
+  const origin = `http://127.0.0.1:${(server.address() as { port: number }).port}`
+  const nativeFetch = globalThis.fetch
+  const requested: string[] = []
+  vi.stubGlobal('fetch', (input: string | URL | Request, init?: RequestInit) => {
+    requested.push(String(input))
+    return nativeFetch(new URL(String(input), origin), init)
+  })
+  let checkpoint: TranscriptSnapshot = base, commits = 0
+  const failed = vi.fn()
+  const client = new ChatTranscriptClient('p', 's', async value => { checkpoint = value; commits++ }, failed)
+  client.restore(base)
+  const running = client.run()
+  try {
+    // Restored checkpoint, every event, then ready; no snapshot repair is necessary.
+    await vi.waitFor(() => expect(commits).toBe(count + 2), { timeout: 5000 })
+    expect(checkpoint.cursor).toBe(finalCursor)
+    expect(checkpoint.messages).toEqual(store.transcripts.all(...scope))
+    expect(checkpoint.messages).toHaveLength(count)
+    expect(failed).not.toHaveBeenCalled()
+    expect(requested).toEqual(['/api/app/chat/sessions/s/events?profile=p'])
+    store.transcripts.upsert(...scope, { id: 'live', role: 'assistant', content: '重连后新增', status: 'complete' }, count)
+    await vi.waitFor(() => expect(checkpoint.messages).toHaveLength(count + 1))
+    expect(checkpoint.messages.at(-1)?.content).toBe('重连后新增')
+    expect(failed).not.toHaveBeenCalled()
+  } finally {
+    client.close()
+    await running
+  }
+}, 15_000)

+ 115 - 1
tests/server/realtimeBroker.test.ts

@@ -8,7 +8,7 @@ import { RealtimeBroker, type RealtimeActivity, type RealtimePrincipal, type Str
 import { RealtimeReceipts } from '../../src/server/realtimeReceipts.js'
 
 const cleanup: Array<() => void> = []
-afterEach(() => cleanup.splice(0).reverse().forEach(f => f()))
+afterEach(() => { cleanup.splice(0).reverse().forEach(f => f()); vi.restoreAllMocks() })
 async function fixture() {
   const home = mkdtempSync(join(tmpdir(), 'yaoyao-realtime-test-'))
   const ws = new WebSocketServer({ port: 0, host: '127.0.0.1' })
@@ -18,6 +18,8 @@ async function fixture() {
   let count = 0
   let seq = 0, truncate = false, dropPrompt = false
   let cwd = '/old-session', busy = false, rejectCwd = false
+  let loseResumeReply = false
+  let resumeError: number | undefined
   const history: any[] = []
   let peer: WebSocket
   ws.on('connection', socket => {
@@ -26,6 +28,11 @@ async function fixture() {
     socket.on('message', raw => {
       const f = JSON.parse(raw.toString()); commands.push(f)
       if (f.method === 'prompt.submit' && dropPrompt) { socket.terminate(); return }
+      if (f.method === 'session.resume' && loseResumeReply) { loseResumeReply = false; return }
+      if (f.method === 'session.resume' && resumeError !== undefined) {
+        socket.send(JSON.stringify({ id: f.id, error: { code: resumeError, message: resumeError === 4007 ? 'session not found' : 'database temporarily unavailable' } }))
+        resumeError = undefined; return
+      }
       if (f.method === 'profiles.list') {
         socket.send(JSON.stringify({id:f.id,result:{profiles:[{name:'default',ui_meta:{'hermes-bots':{chat:'stored-1'}}}]}}))
       } else if (f.method === 'session.events.since') {
@@ -53,6 +60,8 @@ async function fixture() {
   return { home, broker, principal, commands, activities, count: () => count, advance: (n: number) => { now += n },
     cwd: () => cwd, busy: () => { busy = true }, rejectCwd: () => { rejectCwd = true },
     disconnect: () => peer!.terminate(), truncate: () => { truncate = true }, dropPrompt: () => { dropPrompt = true },
+    loseResumeReply: () => { loseResumeReply = true },
+    failNextResume: (code: number) => { resumeError = code },
     emit: (type: string, payload: unknown) => {
       const params = { type, session_id: 'runtime-1', seq: ++seq, payload }; history.push(params)
       if (peer!.readyState === 1) peer!.send(JSON.stringify({ method: 'event', params }))
@@ -355,6 +364,111 @@ describe('realtime broker', () => {
     expect(f.count()).toBe(2)
     expect(received.filter(e => e.event === 'reset')).toHaveLength(0)
   })
+  it('keeps retrying credential failures and replays missed events without resubmitting prompts', async () => {
+    const f = await fixture(), p = f.principal('alice'), url = vi.fn(p.url)
+    const channel = await f.broker.create({ ...p, url }, 'chat')
+    await f.broker.command(channel, 'open', resume)
+    await f.broker.command(channel, 'send-once', { method: 'prompt.submit', params: { session_id: 'runtime-1', text: 'once' } })
+    const received: StreamEntry[] = []
+    f.broker.subscribe(channel, undefined, entry => received.push(entry))
+    url.mockRejectedValueOnce(new Error('Hermes is restarting')).mockRejectedValueOnce(new Error('Ticket endpoint unavailable'))
+    f.disconnect(); f.emit('message.delta', { text: 'missed-during-restart' })
+    await vi.waitFor(() => expect(received.filter(e => e.data.includes('missed-during-restart'))).toHaveLength(1), { timeout: 5000 })
+    expect(url).toHaveBeenCalledTimes(4)
+    expect(f.count()).toBe(2)
+    expect(f.commands.filter(command => command.method === 'prompt.submit')).toHaveLength(1)
+  }, 7000)
+  it('shares one credential attempt when clients reconnect during the retry delay', async () => {
+    const f = await fixture(), p = f.principal('alice'), url = vi.fn(p.url)
+    await f.broker.create({ ...p, url }, 'chat')
+    let release!: (url: URL) => void
+    url.mockImplementationOnce(() => new Promise(resolve => { release = resolve }))
+    f.disconnect()
+    await vi.waitFor(() => expect(url).toHaveBeenCalledTimes(2))
+    const second = f.broker.create({ ...p, url }, 'chat')
+    const third = f.broker.create({ ...p, url }, 'chat')
+    release(await p.url('chat'))
+    await Promise.all([second, third])
+    expect(url).toHaveBeenCalledTimes(2)
+    expect(f.count()).toBe(2)
+  })
+  it('retries a connected gateway whose session recovery never replies', async () => {
+    const f = await fixture(), channel = await f.broker.create(f.principal('alice'), 'chat')
+    await f.broker.command(channel, 'open', resume)
+    const received: StreamEntry[] = []
+    f.broker.subscribe(channel, undefined, entry => received.push(entry))
+    const setTimeout = globalThis.setTimeout
+    vi.spyOn(globalThis, 'setTimeout').mockImplementation(((callback: (...args: any[]) => void, ms?: number, ...args: any[]) =>
+      setTimeout(callback, ms === 120_000 ? 30 : ms, ...args)) as typeof globalThis.setTimeout)
+    f.loseResumeReply(); f.disconnect(); f.emit('message.delta', { text: 'after-recovery-timeout' })
+    await vi.waitFor(() => expect(received.some(e => e.data.includes('after-recovery-timeout'))).toBe(true), { timeout: 3000 })
+    expect(f.count()).toBe(3)
+    expect(received.some(e => e.data.includes('upstream_recovery_failed'))).toBe(true)
+  })
+  it('retries an explicit temporary session recovery error instead of reporting ready', async () => {
+    const f = await fixture(), channel = await f.broker.create(f.principal('alice'), 'chat')
+    await f.broker.command(channel, 'open', resume)
+    const received: StreamEntry[] = []
+    f.broker.subscribe(channel, undefined, entry => received.push(entry))
+    f.failNextResume(5000); f.disconnect(); f.emit('message.delta', { text: 'after-temporary-resume-error' })
+    await vi.waitFor(() => expect(received.some(e => e.data.includes('after-temporary-resume-error'))).toBe(true), { timeout: 3000 })
+    expect(f.count()).toBe(3)
+    expect(channel.routes.size).toBe(1)
+  })
+  it('retires a missing stored session without endlessly reconnecting the service', async () => {
+    const f = await fixture(), channel = await f.broker.create(f.principal('alice'), 'chat')
+    await f.broker.command(channel, 'open', resume)
+    const received: StreamEntry[] = []
+    f.broker.subscribe(channel, undefined, entry => received.push(entry))
+    f.failNextResume(4007); f.disconnect()
+    await vi.waitFor(() => expect(received.some(e => e.data.includes('session_not_found'))).toBe(true), { timeout: 2500 })
+    expect(channel.routes.size).toBe(0)
+    await new Promise(resolve => setTimeout(resolve, 1200))
+    expect(f.count()).toBe(2)
+    expect(f.commands.filter(command => command.method === 'session.resume')).toHaveLength(2)
+  })
+  it('does not reopen a socket when authorization is revoked during credential lookup', async () => {
+    const f = await fixture(), p = f.principal('alice')
+    let valid = true, release!: (url: URL) => void
+    const url = vi.fn(p.url)
+    await f.broker.create({ ...p, valid: () => valid, url }, 'chat')
+    url.mockImplementationOnce(() => new Promise(resolve => { release = resolve }))
+    f.disconnect()
+    await vi.waitFor(() => expect(url).toHaveBeenCalledTimes(2))
+    valid = false
+    release(await p.url('chat'))
+    await new Promise(resolve => setTimeout(resolve, 650))
+    expect(url).toHaveBeenCalledTimes(2)
+    expect(f.count()).toBe(1)
+  })
+  it('does not reopen a socket after shutdown with credentials still pending', async () => {
+    const f = await fixture(), p = f.principal('alice'), url = vi.fn(p.url)
+    await f.broker.create({ ...p, url }, 'chat')
+    let release!: (url: URL) => void
+    url.mockImplementationOnce(() => new Promise(resolve => { release = resolve }))
+    f.disconnect()
+    await vi.waitFor(() => expect(url).toHaveBeenCalledTimes(2))
+    f.broker.close()
+    release(await p.url('chat'))
+    await new Promise(resolve => setTimeout(resolve, 650))
+    expect(url).toHaveBeenCalledTimes(2)
+    expect(f.count()).toBe(1)
+  })
+  it('recovers a shared service connection for another authorized user after its first user expires', async () => {
+    const f = await fixture()
+    let firstValid = true
+    const firstURL = vi.fn(f.principal('alice').url), secondURL = vi.fn(f.principal('bob').url)
+    await f.broker.create({ ...f.principal('alice'), valid: () => firstValid, url: firstURL }, 'chat')
+    const channel = await f.broker.create({ ...f.principal('bob'), url: secondURL }, 'chat')
+    await f.broker.command(channel, 'open', resume)
+    const received: StreamEntry[] = []
+    f.broker.subscribe(channel, undefined, entry => received.push(entry))
+    firstValid = false
+    f.disconnect(); f.emit('message.delta', { text: 'still-authorized' })
+    await vi.waitFor(() => expect(received.some(e => e.data.includes('still-authorized'))).toBe(true), { timeout: 2500 })
+    expect(firstURL).toHaveBeenCalledTimes(1)
+    expect(secondURL).toHaveBeenCalledTimes(1)
+  })
   it('reports reset when upstream history was truncated', async () => {
     const f = await fixture(), c = await f.broker.create(f.principal('alice'), 'chat')
     await f.broker.command(c, 'open', resume)

+ 3 - 3
tests/server/workspace.test.ts

@@ -570,7 +570,7 @@ describe('Web-owned workspace', () => {
     }
     const run = runtime.send(owner, c.id, { requestId: randomUUID(), content: '修改一次' })
     await vi.waitFor(() =>
-      expect(store.require<WorkspaceRun>(owner, 'run', run.id).status).toBe('uncertain'),
+      expect(store.require<WorkspaceRun>(owner, 'run', run.id).error).toContain('正在恢复原执行'),
     )
     runtime.close()
     const configured = requests.filter(r => r.method === 'config.set').length
@@ -1250,7 +1250,7 @@ it('recovers a partially completed parallel batch after restart without resubmit
   const last=pending.get(c.name)!
   recoveryByStored.set(storedByRuntime.get(last.p.session_id)!,[{role:'user',content:last.p.text},{role:'assistant',content:'丙已完成'}])
   last.socket.terminate()
-  await vi.waitFor(()=>expect(store.require<WorkspaceRun>(owner,'run',root.id).status).toBe('uncertain'))
+  await vi.waitFor(()=>expect(store.require<WorkspaceRun>(owner,'run',root.id).error).toContain('正在恢复原执行'))
   runtime.close();runtime=new WorkspaceRuntime(store,nodes,uploads);runtime.start()
   await finished(root.id)
   expect(admin).toBe(2)
@@ -1530,7 +1530,7 @@ it('upgrades an admitted v0.3.7 execution without submitting its prompt again',
   const a=agent('升级执行'),c=direct(a.id)
   reply=(socket,p)=>{recoveryHistory=[{role:'user',content:p.text},{role:'assistant',content:'升级前已完成'}];socket.terminate()}
   const root=runtime.send(owner,c.id,{requestId:randomUUID(),content:'只执行一次'})
-  await vi.waitFor(()=>expect(store.require<WorkspaceRun>(owner,'run',root.id).status).toBe('uncertain'))
+  await vi.waitFor(()=>expect(store.require<WorkspaceRun>(owner,'run',root.id).error).toContain('正在恢复原执行'))
   runtime.close()
   const old=store.list<any>(owner,'turn')[0]!
   for(const task of store.list<any>(owner,'turn'))store.remove(owner,'turn',task.id)

+ 62 - 1
tests/server/workspaceGateway.test.ts

@@ -1,5 +1,5 @@
 // @vitest-environment node
-import {expect,it} from 'vitest'
+import {expect,it,vi} from 'vitest'
 import {WebSocketServer,type WebSocket} from 'ws'
 import {WorkspaceGateway,type GatewayFrame,type GatewayTarget} from '../../src/server/workspaceGateway'
 
@@ -45,3 +45,64 @@ it('adapts Hermes server requests, scopes answers, restores pending cards and wi
     await new Promise<void>(done=>server.close(()=>done()))
   }
 })
+
+it('ignores frames and closes from the previous socket after a reconnect', async () => {
+  const server = new WebSocketServer({port: 0, host: '127.0.0.1'})
+  await new Promise<void>(resolve => server.once('listening', resolve))
+  let current!: WebSocket, pending: any
+  server.on('connection', socket => {
+    current = socket
+    socket.send(JSON.stringify({method: 'event', params: {type: 'gateway.ready'}}))
+    socket.on('message', raw => { pending = JSON.parse(String(raw)) })
+  })
+  const target = {url: new URL(`http://127.0.0.1:${(server.address() as {port:number}).port}`), client: {},
+    session: {webSocketCredential: async () => ({name: 'ticket', value: 'fixture'})}} as unknown as GatewayTarget
+  const gateway = new WorkspaceGateway(target), events = vi.fn(), disconnect = vi.fn()
+  gateway.onEvent = events; gateway.onDisconnect = disconnect
+  try {
+    await gateway.connect()
+    const previous = (gateway as any).socket as WebSocket
+    current.terminate()
+    await expect.poll(() => disconnect.mock.calls.length).toBe(1)
+    await gateway.connect()
+    const reply = gateway.rpc('session.resume', {session_id: 'stored'})
+    await expect.poll(() => pending?.method).toBe('session.resume')
+    previous.emit('message', Buffer.from(JSON.stringify({method: 'event', params: {type: 'message.complete', session_id: 'stale'}})))
+    previous.emit('close')
+    expect(gateway.connected).toBe(true)
+    expect(disconnect).toHaveBeenCalledOnce()
+    expect(events.mock.calls.some(([frame]) => frame.session_id === 'stale')).toBe(false)
+    current.send(JSON.stringify({id: pending.id, result: {session_id: 'current'}}))
+    await expect(reply).resolves.toEqual({session_id: 'current'})
+  } finally {
+    gateway.close(); for (const client of server.clients) client.terminate()
+    await new Promise<void>(resolve => server.close(() => resolve()))
+  }
+})
+
+it('detects a half-open connection when Hermes stops answering pings', async () => {
+  vi.useFakeTimers({toFake: ['setInterval', 'clearInterval']})
+  const server = new WebSocketServer({port: 0, host: '127.0.0.1', autoPong: false})
+  await new Promise<void>(resolve => server.once('listening', resolve))
+  const ping = vi.fn()
+  server.on('connection', socket => {
+    socket.on('ping', ping)
+    socket.send(JSON.stringify({method: 'event', params: {type: 'gateway.ready'}}))
+  })
+  const target = {url: new URL(`http://127.0.0.1:${(server.address() as {port:number}).port}`), client: {},
+    session: {webSocketCredential: async () => ({name: 'ticket', value: 'fixture'})}} as unknown as GatewayTarget
+  const gateway = new WorkspaceGateway(target), disconnect = vi.fn()
+  gateway.onDisconnect = disconnect
+  try {
+    await gateway.connect()
+    await vi.advanceTimersByTimeAsync(15_000)
+    await expect.poll(() => ping.mock.calls.length).toBe(1)
+    await vi.advanceTimersByTimeAsync(15_000)
+    await expect.poll(() => disconnect.mock.calls.length).toBe(1)
+    expect(gateway.connected).toBe(false)
+  } finally {
+    gateway.close(); for (const client of server.clients) client.terminate()
+    await new Promise<void>(resolve => server.close(() => resolve()))
+    vi.useRealTimers()
+  }
+})

+ 189 - 0
tests/server/workspaceReconnect.test.ts

@@ -0,0 +1,189 @@
+// @vitest-environment node
+import {afterEach, beforeEach, expect, it, vi} from 'vitest'
+import {mkdtempSync, rmSync} from 'node:fs'
+import {tmpdir} from 'node:os'
+import {join} from 'node:path'
+import {randomUUID} from 'node:crypto'
+import {WebSocketServer, type WebSocket} from 'ws'
+import {WorkspaceStore} from '../../src/server/workspaceStore'
+import {WorkspaceRuntime} from '../../src/server/workspaceRuntime'
+import {type GatewayTarget, type WorkspaceNodes} from '../../src/server/workspaceGateway'
+import {type WorkspacePlugins} from '../../src/server/botPlugins/workspacePlugins'
+import {UploadStore} from '../../src/server/uploads'
+
+const owner = 'reconnect-user'
+let home: string, store: WorkspaceStore, uploads: UploadStore, runtime: WorkspaceRuntime
+let server: WebSocketServer, socket: WebSocket, target: GatewayTarget, nodes: WorkspaceNodes
+let running: boolean, authorized: boolean, acknowledgePrompt: boolean, holdCredential: (() => Promise<void>) | undefined
+let holdBind: (() => Promise<void>) | undefined
+let resumedRuntimeId: string, resumedStoredId: string, historyPaths: string[]
+let rpc: Array<{method: string; params: any}>, binds: any[], unbinds: any[], history: any[]
+let pluginDispose: ReturnType<typeof vi.fn>, pluginCall: ReturnType<typeof vi.fn>
+beforeEach(async () => {
+  home = mkdtempSync(join(tmpdir(), 'yaoyao-workspace-reconnect-'))
+  store = new WorkspaceStore(home); uploads = new UploadStore(home)
+  running = true; authorized = true; acknowledgePrompt = true; holdCredential = undefined; holdBind = undefined
+  resumedRuntimeId = 'runtime'; resumedStoredId = 'stored'; historyPaths = []
+  rpc = []; binds = []; unbinds = []; history = []
+  server = new WebSocketServer({port: 0, host: '127.0.0.1'})
+  await new Promise<void>(resolve => server.once('listening', resolve))
+  target = {
+    url: new URL(`http://127.0.0.1:${(server.address() as {port: number}).port}`), client: {directAgent: undefined},
+    session: {
+      webSocketCredential: async () => { await holdCredential?.(); return {name: 'ticket', value: 'fixture'} },
+      request: async (path: string, options: any) => {
+        if (path.endsWith('/bind')) { binds.push(options.body); await holdBind?.() }
+        if (path.endsWith('/unbind')) unbinds.push(options.body)
+        if (path.startsWith('/api/sessions/')) historyPaths.push(path)
+        const value = path.endsWith('/capabilities') ? {ready: true, native_tools: true, in_process: true}
+          : path.startsWith('/api/plugins/yaoyao-bot-bridge/') ? {ok: true, native_tools: true}
+          : path === '/api/config' ? {terminal: {}} : {messages: history}
+        return {status: 200, body: Buffer.from(JSON.stringify(value)), headers: new Headers()}
+      },
+    },
+  } as unknown as GatewayTarget
+  nodes = {requireSource: () => {}, target: () => target} as unknown as WorkspaceNodes
+  runtime = new WorkspaceRuntime(store, nodes, uploads, () => authorized)
+  pluginDispose = vi.fn(async () => {})
+  pluginCall = vi.fn(async () => ({message: '插件仍可使用'}))
+  runtime.plugins = {selected: () => true, open: async () => ({services: () => [],
+    catalog: () => [{id: 'plugin_fixture', name: 'plugin_fixture', description: '回归测试', inputSchema: {type: 'object'}}],
+    call: pluginCall, dispose: pluginDispose,
+  })} as unknown as WorkspacePlugins
+  server.on('connection', connection => {
+    socket = connection
+    connection.send(JSON.stringify({method: 'event', params: {type: 'gateway.ready'}}))
+    connection.on('message', raw => {
+      const frame = JSON.parse(String(raw)); rpc.push(frame)
+      const result = frame.method === 'session.create' ? {session_id: 'runtime', stored_session_id: 'stored', running: false, info: {profile_name: 'default'}}
+        : frame.method === 'session.resume' ? {session_id: resumedRuntimeId, stored_session_id: resumedStoredId, running, info: {profile_name: 'default'}}
+        : {status: 'streaming'}
+      if (frame.method !== 'prompt.submit' || acknowledgePrompt) connection.send(JSON.stringify({id: frame.id, result}))
+    })
+  })
+})
+afterEach(async () => {
+  runtime.close()
+  await new Promise(resolve => setTimeout(resolve, 20))
+  for (const client of server.clients) client.terminate()
+  await new Promise<void>(resolve => server.close(() => resolve()))
+  uploads.close(); store.close(); rmSync(home, {recursive: true, force: true})
+})
+async function start() {
+  const agent = store.createAgent(owner, {name: '恢复测试', profile: 'default'})
+  const conversation = store.list<any>(owner, 'conversation').find(c => c.kind === 'direct' && c.memberIds[0] === agent.id)
+  const run = runtime.send(owner, conversation.id, {requestId: randomUUID(), content: '只执行一次'})
+  await expect.poll(() => rpc.filter(r => r.method === 'prompt.submit')).toHaveLength(1)
+  return {run, conversation, agent}
+}
+async function callback(path: string, body: unknown) {
+  const lease = binds[0]
+  return fetch(lease.bridge_url + path, {method: 'POST', headers: {Authorization: `Bearer ${lease.token}`, 'Content-Type': 'application/json'}, body: JSON.stringify(body)})
+}
+function complete(text = '恢复完成') { socket.send(JSON.stringify({method: 'event', params: {type: 'message.complete', session_id: 'runtime', payload: {text}}})) }
+
+it.each([true, false])('keeps the original tool and plugin grants through running recovery (prompt receipt=%s)', async receipt => {
+  acknowledgePrompt = receipt
+  const {run, conversation, agent} = await start()
+  const first = binds[0]
+  socket.terminate()
+  await expect.poll(() => binds.length).toBe(2)
+  expect(binds[1]).toMatchObject({generation: first.generation, token: first.token, bridge_url: first.bridge_url})
+  expect(unbinds).toHaveLength(0)
+  expect(pluginDispose).not.toHaveBeenCalled()
+  const catalog = await (await callback('/tools/list', {})).json()
+  const tool = catalog.tools.find((t: any) => t.name === 'workspace_list_agents')
+  const result = await (await callback('/tools/call', {toolId: tool.id, arguments: {}, callId: 'after-reconnect'})).json()
+  expect(result.structuredContent.agents).toEqual(expect.arrayContaining([expect.objectContaining({id: agent.id})]))
+  const plugin = catalog.tools.find((t: any) => t.name === 'plugin_fixture')
+  await callback('/tools/call', {toolId: plugin.id, arguments: {}, callId: 'plugin-after-reconnect'})
+  expect(pluginCall).toHaveBeenCalledOnce()
+  complete()
+  await expect.poll(() => store.require<any>(owner, 'run', run.id).status).toBe('complete')
+  expect(store.messages(owner, conversation.id).at(-1)?.content).toBe('恢复完成')
+  expect(rpc.filter(r => r.method === 'prompt.submit')).toHaveLength(1)
+  await expect.poll(() => unbinds.length).toBe(1)
+  expect(pluginDispose).toHaveBeenCalledOnce()
+})
+
+it('reconciles completion during a disconnect without renewing or resubmitting the finished turn', async () => {
+  const {run, conversation} = await start()
+  history = [{role: 'user', content: rpc.find(r => r.method === 'prompt.submit')!.params.text}, {role: 'assistant', content: '断线期间完成'}]
+  running = false; socket.terminate()
+  await expect.poll(() => store.require<any>(owner, 'run', run.id).status).toBe('complete')
+  expect(store.messages(owner, conversation.id).at(-1)?.content).toBe('断线期间完成')
+  expect(binds).toHaveLength(1)
+  expect(rpc.filter(r => r.method === 'prompt.submit')).toHaveLength(1)
+})
+
+it('continues reconnecting if the replacement socket closes while the original grant is renewing', async () => {
+  const {run} = await start()
+  let release!: () => void
+  holdBind = () => new Promise<void>(resolve => { release = resolve })
+  socket.terminate()
+  await expect.poll(() => binds.length).toBe(2)
+  socket.terminate()
+  await expect.poll(() => server.clients.size).toBe(0)
+  holdBind = undefined; release()
+  await expect.poll(() => binds.length, {timeout: 3000}).toBe(3)
+  expect(new Set(binds.map(b => b.generation)).size).toBe(1)
+  complete()
+  await expect.poll(() => store.require<any>(owner, 'run', run.id).status).toBe('complete')
+  expect(rpc.filter(r => r.method === 'prompt.submit')).toHaveLength(1)
+})
+
+it('follows resumed runtime and compacted stored IDs for tool renewal and subsequent history reconciliation', async () => {
+  const {run} = await start()
+  resumedRuntimeId = 'runtime-after-resume'; resumedStoredId = 'compacted-tip'
+  socket.terminate()
+  await expect.poll(() => binds.length).toBe(2)
+  expect(binds[1]).toMatchObject({session_id: resumedRuntimeId, stored_session_id: resumedStoredId, generation: binds[0].generation})
+  expect(store.list<any>(owner, 'binding')[0]).toMatchObject({runtimeId: resumedRuntimeId, storedId: resumedStoredId, aliases: ['stored', 'compacted-tip']})
+  running = false
+  history = [{role: 'user', content: rpc.find(r => r.method === 'prompt.submit')!.params.text}, {role: 'assistant', content: '压缩后完成'}]
+  socket.terminate()
+  await expect.poll(() => store.require<any>(owner, 'run', run.id).status).toBe('complete')
+  expect(historyPaths).toEqual(['/api/sessions/compacted-tip/messages'])
+  expect(rpc.filter(r => r.method === 'prompt.submit')).toHaveLength(1)
+})
+
+it.each(['stop', 'revoke', 'close'] as const)('revokes callbacks and cannot revive a detached turn after %s', async action => {
+  const {run} = await start()
+  socket.terminate()
+  await expect.poll(() => store.require<any>(owner, 'run', run.id).error).toContain('正在恢复原执行')
+  if (action === 'stop') await runtime.stop(owner, run.id)
+  else if (action === 'revoke') authorized = false
+  else runtime.close()
+  await expect.poll(() => unbinds.length).toBe(1)
+  await expect(callback('/tools/list', {})).rejects.toThrow()
+  expect(pluginDispose).toHaveBeenCalledOnce()
+  expect(binds).toHaveLength(1)
+  expect(rpc.filter(r => r.method === 'prompt.submit')).toHaveLength(1)
+  if (action === 'stop') expect(store.require<any>(owner, 'run', run.id).status).toBe('interrupted')
+})
+
+it('does not create a late WebSocket when the service closes during reconnect credentials', async () => {
+  const {run} = await start()
+  let release!: () => void
+  const credential = new Promise<void>(resolve => { release = resolve })
+  let waiting = false
+  holdCredential = () => { waiting = true; return credential }
+  socket.terminate()
+  await expect.poll(() => waiting).toBe(true)
+  runtime.close(); release()
+  await expect.poll(() => unbinds.length).toBe(1)
+  expect(server.clients.size).toBe(0)
+  expect(rpc.filter(r => r.method === 'session.resume')).toHaveLength(0)
+  expect(store.require<any>(owner, 'run', run.id).status).toBe('uncertain')
+})
+
+it('keeps a running turn uncertain after process restart when its original tools cannot be restored', async () => {
+  const {run} = await start()
+  runtime.close()
+  runtime = new WorkspaceRuntime(store, nodes, uploads, () => authorized)
+  runtime.start()
+  await expect.poll(() => store.require<any>(owner, 'run', run.id).error).toContain('本轮工具授权已丢失')
+  expect(store.require<any>(owner, 'run', run.id).status).toBe('uncertain')
+  expect(binds).toHaveLength(1)
+  expect(rpc.filter(r => r.method === 'prompt.submit')).toHaveLength(1)
+})

+ 42 - 2
tests/server/workspaceTeamTools.test.ts

@@ -267,13 +267,13 @@ describe('Bot self rules', () => {
   })
 })
 
-async function mount(signal = new AbortController().signal) {
+async function mount(signal = new AbortController().signal, onFailure: (error: Error) => void = () => {}) {
   const lease = await createWorkspaceToolLease({
     target, profile:manager.profile, workId:work.id,
     session:()=>({runtimeId:'runtime',storedId:'stored'}),signal,
     assertActive:()=>{runtime.teamTools.assertTurn(owner,work.id)},
     catalog:()=>[...runtime.teamTools.catalog(owner,work.id),...runtime.knowledgeTools.catalog(owner,work.id,false)],
-    call:(id,args)=>runtime.knowledgeTools.handles(id)?runtime.knowledgeTools.call(owner,work.id,id,args,false):runtime.teamTools.call(owner,work.id,id,args),onFailure:()=>{},
+    call:(id,args)=>runtime.knowledgeTools.handles(id)?runtime.knowledgeTools.call(owner,work.id,id,args,false):runtime.teamTools.call(owner,work.id,id,args),onFailure,
   })
   leases.push(lease); await lease.bind()
   return lease
@@ -283,6 +283,46 @@ function http(path:string, body:unknown, options:RequestInit={}) {
 }
 
 describe('loopback tool lease', () => {
+  it.each(['503', 'upstream_unavailable'])('retains the original grant through %s renewal failures, then renews after recovery', async failure => {
+    vi.useFakeTimers({toFake: ['Date', 'setInterval', 'clearInterval']})
+    try {
+      const failed = vi.fn()
+      await mount(undefined, failed)
+      const original = {...binding}, request = vi.mocked(target.session.request).getMockImplementation()!
+      let unavailable = true
+      vi.mocked(target.session.request).mockImplementation(async (path, options) => {
+        if (path.endsWith('/bind') && unavailable) {
+          if (failure === 'upstream_unavailable') throw new HttpError(502, 'Unable to reach Hermes', 'upstream_unavailable')
+          return {status: 503, body: Buffer.from('{}'), headers: new Headers()}
+        }
+        return request(path, options)
+      })
+      await vi.advanceTimersByTimeAsync(5 * 60_000)
+      expect(failed).not.toHaveBeenCalled()
+      expect((await http('/tools/list', {})).status).toBe(200)
+      unavailable = false
+      await vi.advanceTimersByTimeAsync(30_000)
+      expect(binding).toMatchObject({generation: original.generation, token: original.token, bridge_url: original.bridge_url})
+      expect(binding!.expires_at).toBeGreaterThan(original.expires_at)
+      expect(failed).not.toHaveBeenCalled()
+    } finally { vi.useRealTimers() }
+  })
+
+  it.each([401, 503])('retires a lease on rejected renewal or its original expiry (HTTP %s)', async status => {
+    vi.useFakeTimers({toFake: ['Date', 'setInterval', 'clearInterval']})
+    try {
+      const failed = vi.fn()
+      await mount(undefined, failed)
+      const request = vi.mocked(target.session.request).getMockImplementation()!
+      vi.mocked(target.session.request).mockImplementation(async (path, options) => path.endsWith('/bind')
+        ? {status, body: Buffer.from('{}'), headers: new Headers()} : request(path, options))
+      await vi.advanceTimersByTimeAsync((status === 401 ? 5 : 30) * 60_000)
+      expect(failed).toHaveBeenCalledOnce()
+      expect(failed.mock.calls[0]![0]).toMatchObject({code: status === 401 ? 'team_tools_bind_failed' : 'team_tools_expired'})
+      await expect(http('/tools/list', {})).rejects.toThrow()
+    } finally { vi.useRealTimers() }
+  })
+
   it('updates self rules through the bridge without ending the current tool lease', async () => {
     await mount()
     const catalog = await (await http('/tools/list',{})).json()