Просмотр исходного кода

发布 v0.4.70:修复桌面登录、电脑连接和图片展示

Samien 1 месяц назад
Родитель
Сommit
b16ce43cff

+ 6 - 6
README.md

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

+ 6 - 3
desktop/main.mjs

@@ -30,6 +30,9 @@ else {
   let remoteMode = false, remoteURL = '', serverModeActive = false, switchingMode = false
   let recoveringService = false
   const serviceURL = () => remoteMode ? remoteURL : manager?.state.url
+  // Use the same Chromium networking as server detection/navigation. Auth owns
+  // its cookie jar: do not send or overwrite another account's browser cookies.
+  const authFetch = (url, options) => net.fetch(url, { ...options, credentials: 'omit' })
   const serviceOrigins = () => {
     try { return remoteMode && remoteURL ? [new URL(remoteURL).origin] : manager?.state.url ? [new URL(manager.state.url).origin] : [] }
     catch { return [] }
@@ -346,7 +349,7 @@ else {
     async function authorizeComputer(server,session){
       const previous=await hostManager.read().catch(()=>undefined)
       const previousHostId=previous&&new URL(previous.serverURL).origin===new URL(server).origin?previous.hostId:undefined
-      const registration=await enrollDesktopHost(session,{name:hostname(),installId:await hostManager.installIdentity(),previousHostId})
+      const registration=await enrollDesktopHost(session,{name:hostname(),installId:await hostManager.installIdentity(),previousHostId},authFetch)
       await hostManager.adopt({protocol:1,serverURL:server,hostId:registration.host.id,token:registration.token,...(server.startsWith('http://')?{allowInsecureLan:true}:{})})
       return registration
     }
@@ -409,9 +412,9 @@ else {
         await runnerManager.start().catch(error => runnerManager.publish(error.message))
         return manager.state.url
       },
-      register: ({ serverURL, username, password }) => remoteRegistration(serverURL, { username, password }),
+      register: ({ serverURL, username, password }) => remoteRegistration(serverURL, { username, password }, authFetch),
       authenticate: async ({ mode, serverURL, setup, username, password }) => {
-        const auth = await remoteSession(serverURL, { setup, username, password })
+        const auth = await remoteSession(serverURL, { setup, username, password }, authFetch)
         for (const cookie of auth.cookieDetails) {
           await electronSession.defaultSession.cookies.set({ url: serverURL, ...cookie,
             httpOnly: true, secure: cookie.secure || serverURL.startsWith('https://') })

+ 33 - 2
desktop/onboarding-flow.test.mjs

@@ -11,6 +11,7 @@ test('first launch, failed connection and remote login all stay in the only main
   const home = await realpath(await mkdtemp(join(tmpdir(), 'yaoyao-onboarding-')))
   let loginCount = 0
   let registrationCount = 0
+  let loginRole = 'user', enrollmentCount = 0
   let holdBootstrap = false, replyBootstrap, sessionValid = true
   const server = createServer((req, res) => {
     const json = (value, status = 200) => { res.statusCode = status; res.setHeader('content-type', 'application/json'); res.end(JSON.stringify(value)) }
@@ -26,7 +27,7 @@ test('first launch, failed connection and remote login all stay in the only main
         assert.deepEqual(JSON.parse(raw), { username: 'new-child', password: 'child-password' })
         assert.equal(req.headers['x-csrf-token'], 'fixture')
         assert.ok(String(req.headers.cookie).includes('csrf=fixture'))
-        assert.ok(!String(req.headers.cookie).includes('session=fixture'))
+        assert.ok(!String(req.headers.cookie).includes('session='))
         json({ registrationStatus: 'pending', message: '注册成功,请等待管理员开通' }, 201)
       }); return
     }
@@ -34,12 +35,21 @@ test('first launch, failed connection and remote login all stay in the only main
       let raw = ''; req.on('data', chunk => { raw += chunk }); req.on('end', () => {
         loginCount++
         const body = JSON.parse(raw)
+        assert.ok(!String(req.headers.cookie).includes('session='))
         if (body.username !== 'user' || body.password !== 'correct-password') return json({ error: 'wrong' }, 401)
         if (req.headers['x-csrf-token'] !== 'fixture' || !String(req.headers.cookie).includes('csrf=fixture')) return json({ error: 'csrf' }, 403)
         res.setHeader('set-cookie', 'session=fixture; Path=/; HttpOnly; Max-Age=3600; SameSite=Strict')
-        json({ user: { id: 'fixture-user', username: 'user', role: 'user' }, csrfToken: 'fixture' })
+        json({ user: { id: 'fixture-user', username: 'user', role: loginRole }, csrfToken: 'fixture' })
       }); return
     }
+    if (req.url === '/api/app/admin/desktop-hosts') {
+      enrollmentCount++
+      assert.equal(req.headers.origin, url)
+      assert.equal(req.headers['x-csrf-token'], 'fixture')
+      assert.ok(String(req.headers.cookie).includes('session=fixture'))
+      // Exercise authorization without provisioning a real computer in the fixture.
+      return json({ error: 'enrollment unavailable' }, 503)
+    }
     res.setHeader('content-type', 'text/html; charset=utf-8'); res.end('<title>已登录远程夭夭</title><h1>远程工作区</h1>')
   })
   await new Promise(done => server.listen(0, '127.0.0.1', done))
@@ -49,6 +59,12 @@ test('first launch, failed connection and remote login all stay in the only main
     app = await electron.launch({ args: [root], cwd: root, env: { ...process.env,
       HERMES_YAOYAO_DESKTOP_TEST_HOME: home, HERMES_YAOYAO_DESKTOP_TEST_MODE: 'ask', HERMES_YAOYAO_DESKTOP_TEST_SYNC: '0' } })
     const page = await app.firstWindow()
+    // The connectivity check can succeed through Chromium while Node sockets
+    // are unavailable (for example, after a macOS local-network permission change).
+    await app.evaluate(({ session }, origin) => {
+      globalThis.fetch = async () => { throw new TypeError('fetch failed', { cause: { code: 'EHOSTUNREACH' } }) }
+      return session.defaultSession.cookies.set({ url: origin, name: 'session', value: 'previous-account', httpOnly: true })
+    }, url)
     const errors = []; page.on('pageerror', error => errors.push(error.message))
     await expect(page.getByRole('heading', { name: '开始使用夭夭' })).toBeVisible()
     assert.equal(app.windows().length, 1)
@@ -72,6 +88,9 @@ test('first launch, failed connection and remote login all stay in the only main
     await expect(page.locator('#confirmation-field')).toBeHidden()
     assert.equal(registrationCount, 1)
     assert.equal(loginCount, 0, 'registration never signs in or authorizes this computer')
+    assert.equal(await app.evaluate(async ({ session }, origin) =>
+      (await session.defaultSession.cookies.get({ url: origin, name: 'session' }))[0]?.value, url),
+    'previous-account', 'registration does not replace the active browser session')
     assert.match(page.url(), /boot.html$/)
     await page.locator('#username').fill('user')
     await page.locator('#password').fill('wrong-password')
@@ -146,6 +165,18 @@ test('first launch, failed connection and remote login all stay in the only main
     await expect(reopened.locator('#login-form')).toBeVisible()
     await expect(reopened.locator('#session-loading')).toBeHidden()
     assert.equal(app.windows().length, 1)
+    loginRole = 'admin'
+    await app.evaluate(() => {
+      globalThis.fetch = async () => { throw new TypeError('fetch failed', { cause: { code: 'EHOSTUNREACH' } }) }
+    })
+    await reopened.locator('#username').fill('user')
+    await reopened.locator('#password').fill('correct-password')
+    await reopened.locator('#submit').click()
+    await expect(reopened.locator('#login-error')).toContainText('账号已登录,但电脑授权未恢复')
+    assert.equal(enrollmentCount, 1, 'computer authorization also uses the reachable Chromium transport')
+    assert.equal((await reopened.evaluate(() => window.yaoyaoDesktop.status())).authenticated, true)
+    await reopened.locator('#submit').click()
+    await reopened.waitForURL(url + '/**')
   } finally {
     await app?.close().catch(() => {})
     await new Promise(done => { server.close(done); server.closeAllConnections() })

+ 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.69;仅 AMD64:samienluo/yaoyao:v0.4.69-amd。
+# 固定版本:samienluo/yaoyao:v0.4.70;仅 AMD64:samienluo/yaoyao:v0.4.70-amd。
 # 留空时使用本地构建名称 yaoyao:local。
 # YAOYAO_DESKTOP_IMAGE=hermes-yaoyao-desktop:0.4.0
 # Cursor Universal 兼容桌面的本地构建名称;基础镜像在 deploy/computer/Dockerfile.cursor 中固定。

+ 7 - 7
docs/docker-install.md

@@ -12,14 +12,14 @@
 
 | 标签 | 架构 |
 | --- | --- |
-| `v0.4.69-amd` | `linux/amd64` |
-| `v0.4.69` | `linux/amd64`、`linux/arm64`,拉取时自动匹配 |
-| `latest` | 最新稳定通用镜像,当前指向与 `v0.4.69` 相同的镜像 |
+| `v0.4.70-amd` | `linux/amd64` |
+| `v0.4.70` | `linux/amd64`、`linux/arm64`,拉取时自动匹配 |
+| `latest` | 最新稳定通用镜像,当前指向与 `v0.4.70` 相同的镜像 |
 
 ```sh
-docker pull samienluo/yaoyao:v0.4.69
+docker pull samienluo/yaoyao:v0.4.70
 # 需要固定 AMD64 时:
-docker pull samienluo/yaoyao:v0.4.69-amd
+docker pull samienluo/yaoyao:v0.4.70-amd
 ```
 
 每次新版本发布都会更新 `latest`,旧版本标签继续保留。需要固定部署版本时使用具体版本标签。
@@ -34,7 +34,7 @@ cp docker.env.example docker.env
 
 | 配置 | 用途 |
 | --- | --- |
-| `HERMES_YAOYAO_IMAGE` | 远程镜像可设为 `samienluo/yaoyao:v0.4.69` 或 `samienluo/yaoyao:latest`;未设置时使用本地构建名称 |
+| `HERMES_YAOYAO_IMAGE` | 远程镜像可设为 `samienluo/yaoyao:v0.4.70` 或 `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.69
+HERMES_YAOYAO_IMAGE=samienluo/yaoyao:v0.4.70
 YAOYAO_CURSOR_DESKTOP_IMAGE=samienluo/yaoyao-desktop:v0.4.12-cursor-amd
 ```
 

+ 43 - 0
docs/releases/v0.4.70.md

@@ -0,0 +1,43 @@
+# 夭夭 AI v0.4.70
+
+本次发布 Web、macOS Apple Silicon 桌面版和 Docker 双架构镜像,不提供 APK。
+
+## 更新内容
+
+- 修复桌面端检测服务器成功后仍无法登录的问题:注册、登录和电脑授权统一使用与连接检测相同的网络通道,保持登录会话独立,避免携带或覆盖其他账号的浏览器登录状态。
+- 修复已停用的电脑仍出现在 Bot 设备清单中的问题;停用记录不会被残留连接或消息来源重新加入清单。
+- 修复聊天中的 MEDIA 图片引用和归档附件重复展示,正确关联正文图片与保存后的附件地址。
+- 在聊天电脑面板补齐共享桌面选择和连接入口,显示已连接、不可用等状态;连接失败时保留错误提示,避免被状态刷新清除。
+
+## 升级说明
+
+- 升级前备份完整 `.yaoyao` 数据目录,建议先更新服务端,再更新桌面客户端。
+- 已安装正式签名版的用户可使用“下载更新 → 重启更新”;历史开发签名版请先手动安装正式 DMG。
+- 桌面使用 Developer ID Application 正式分发签名及 Apple 公证,提供完整自动更新附件。
+- 本次不构建、不上传 APK,旧版本标签和附件继续保留。
+- 主项目采用 Apache-2.0,第三方组件保留各自许可与署名。
+
+## 下载
+
+- `Yaoyao-0.4.70-arm64.dmg`:macOS Apple Silicon 首次安装或手动更新。
+- `Yaoyao-0.4.70-arm64.zip`、DMG 与 ZIP 对应的 `.blockmap`、`latest-mac.yml`:桌面自动更新载荷与清单。
+- `Yaoyao-0.4.70-source.tar.gz`:Web/桌面源码及部署配置。
+- `SHA256SUMS.txt`:所有发布附件的 SHA-256 校验值。
+
+## Docker Hub
+
+| 镜像 | 架构 |
+| --- | --- |
+| `samienluo/yaoyao:v0.4.70-amd` | `linux/amd64` |
+| `samienluo/yaoyao:v0.4.70` | `linux/amd64`、`linux/arm64` |
+| `samienluo/yaoyao:latest` | 验证后更新为同一通用镜像 |
+
+```sh
+docker pull samienluo/yaoyao:v0.4.70
+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.70`。镜像发布到 Docker Hub,GitHub 提供桌面安装及更新包、源码和校验文件。
+
+附件摘要、镜像摘要与实际验证结果见 [GitHub 发布页](https://github.com/Lsamien/yaoyao/releases/tag/v0.4.70)。

+ 2 - 2
package-lock.json

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

+ 1 - 1
package.json

@@ -1,6 +1,6 @@
 {
   "name": "yaoyao",
-  "version": "0.4.69",
+  "version": "0.4.70",
   "private": true,
   "license": "Apache-2.0",
   "description": "夭夭 AI:聊天、多 Agent 团队、文件库与电脑工作空间",

+ 3 - 3
release.json

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

+ 25 - 5
src/client/components/workspace/LocalVmChatPanel.vue

@@ -17,6 +17,16 @@ const showDesktop=computed(()=>computers.value.scriptMachine||computers.value.se
 const cloud=ref<{configured:boolean;running:boolean;connected:boolean;mode?:string}>(),connectionSettings=ref(false)
 const showCloud=computed(()=>computers.value.cloud)
 const showVm=computed(()=>computers.value.vm&&!!state.value)
+const composeDesktopId=ref('')
+const composeDesktop=computed(()=>state.value?.desktops?.find(d=>d.id===composeDesktopId.value))
+const composeConnected=computed(()=>!!state.value?.enabled&&state.value.desktopId===composeDesktopId.value)
+const canConnectCompose=computed(()=>state.value?.fixedCapacity&&!busy.value&&!state.value.inUse&&!agent.value?.temporaryGoalId&&!composeConnected.value&&composeDesktop.value?.online&&composeDesktop.value.ready&&composeDesktop.value.available!==false)
+watch(()=>state.value,value=>{
+ if(!value?.fixedCapacity){composeDesktopId.value='';return}
+ if(value.desktops?.some(d=>d.id===composeDesktopId.value))return
+ const available=value.desktops?.filter(d=>d.online&&d.ready&&d.available!==false)??[]
+ composeDesktopId.value=value.desktopId??(available.length===1?available[0]!.id:'')
+})
 const desktopHosts=computed(()=>(native.value?.hosts??[]).filter(host=>host.id==='local'?computers.value.serverComputer:computers.value.scriptMachine))
 const serverHost=computed(()=>desktopHosts.value.find(host=>host.id==='local'))
 const activeEnvLine=computed(()=>[
@@ -43,7 +53,7 @@ const previewEmptyText=computed(()=>{
  if(!target)return previewKey.value?'所选电脑已不可用,请重新选择':'暂无已开放的电脑'
  if(target.backend==='desktop'){const host=native.value?.hosts?.find(h=>h.id===target.host);return !host?.online?'这台电脑已离线':host.local.ready?'正在读取电脑画面…':'请完成这台电脑的屏幕控制授权'}
  if(target.backend==='cloud')return cloud.value?.configured?(cloud.value?.running?'正在连接桌面…':'打开云端电脑后可查看桌面'):'尚未连接 Grok Bot 账号'
- if(!state.value?.enabled)return '未使用电脑'
+ if(!state.value?.enabled)return state.value?.fixedCapacity?'请先连接下方的共享桌面':'未使用电脑'
  if(state.value.problem)return state.value.problem
  if(!state.value.image)return '本地虚拟机尚未准备'
  if(state.value.container==='missing')return '尚未创建虚拟机'
@@ -92,7 +102,12 @@ async function refresh(){
   error.value=''
  }catch(e){if(version===revision)error.value=e instanceof Error?e.message:'无法读取电脑画面'}finally{if(version===revision)loading.value=false}
 }
-async function run(work:()=>Promise<unknown>){let ok=true;if(busy.value)return false;busy.value=true;error.value='';try{await work();emit('changed')}catch(e){ok=false;error.value=e instanceof Error?e.message:'电脑操作未完成'}finally{busy.value=false;await refresh()}return ok}
+async function run(work:()=>Promise<unknown>){let failure='';if(busy.value)return false;busy.value=true;error.value='';try{await work();emit('changed')}catch(e){failure=e instanceof Error&&e.message?e.message:'电脑操作未完成'}finally{busy.value=false;await refresh();if(failure)error.value=failure}return !failure}
+async function connectCompose(){
+ if(!canConnectCompose.value)return
+ const id=selected.value,desktopId=composeDesktopId.value
+ if(await run(()=>apiRequest(`/api/app/agents/${encodeURIComponent(id)}/local-vm`,{method:'PUT',body:{enabled:true,desktopId}}))&&selected.value===id)previewKey.value='vm'
+}
 async function openDesktop(backend:'desktop'|'cloud'|'vm',host?:string){
  const selectedAgent=agent.value
  if(!selectedAgent||busy.value)return
@@ -110,7 +125,7 @@ function action(value:LocalVmAction){
 }
 async function cycle(){const version=revision;await refresh();if(!closed&&version===revision)timer=setTimeout(cycle,3000)}
 watch(()=>props.agents.map(a=>a.id).join(','),()=>{if(!props.agents.some(a=>a.id===selected.value))selected.value=props.agents[0]?.id??''},{immediate:true})
-watch(selected,()=>{revision++;previewRevision++;state.value=undefined;native.value=undefined;cloud.value=undefined;frame.value=undefined;error.value='';loading.value=true;previewKey.value='';clearTimeout(timer);void cycle()},{immediate:true})
+watch(selected,()=>{revision++;previewRevision++;state.value=undefined;composeDesktopId.value='';native.value=undefined;cloud.value=undefined;frame.value=undefined;error.value='';loading.value=true;previewKey.value='';clearTimeout(timer);void cycle()},{immediate:true})
 watch(()=>props.active,value=>{if(value)void refresh()})
 onBeforeUnmount(()=>{closed=true;revision++;previewRevision++;clearTimeout(timer)})
 </script>
@@ -149,13 +164,18 @@ onBeforeUnmount(()=>{closed=true;revision++;previewRevision++;clearTimeout(timer
      <p v-if="!isAdmin&&!cloud?.configured" class="hint">请由管理员为当前账号配置 Grok Bot 连接。</p>
     </template>
     <template v-if="showVm&&state">
-     <p>{{agent.temporaryGoalId?'临时助手的电脑由当前任务管理':state.mode==='shared'?'共享虚拟机 · 与其他成员共用桌面和工作文件':'此机器人的独立虚拟机'}}</p>
+     <p>{{agent.temporaryGoalId?'临时助手的电脑由当前任务管理':state.fixedCapacity||state.mode==='shared'?'共享虚拟机 · 与其他成员共用桌面和工作文件':'此机器人的独立虚拟机'}}</p>
      <p v-if="state.problem" class="problem" role="alert" aria-label="本地虚拟机状态">{{state.problem}}</p>
+     <template v-if="state.fixedCapacity&&!agent.temporaryGoalId">
+      <label>共享桌面<select v-model="composeDesktopId" aria-label="共享桌面" :disabled="busy||state.inUse"><option value="" disabled>请选择共享桌面</option><option v-for="desktop in state.desktops" :key="desktop.id" :value="desktop.id" :disabled="!desktop.online||!desktop.ready||desktop.available===false">{{desktop.name}}{{desktop.available===false?' · 不可用':!desktop.online?' · 离线':!desktop.ready?' · 正在启动':''}}</option></select></label>
+      <button class="primary" data-testid="connect-compose-desktop" :disabled="!canConnectCompose" @click="connectCompose">{{composeConnected?'已连接':'连接所选桌面'}}</button>
+      <p v-if="!state.desktops?.length" class="hint">暂无可连接的共享桌面,请检查本地虚拟机设置。</p>
+     </template>
      <template v-if="!state.fixedCapacity&&state.images?.length&&!agent.temporaryGoalId">
       <label>虚拟机镜像<select :value="state.imageKey??''" :disabled="busy||state.inUse||state.container!=='missing'" @change="run(()=>apiRequest(base()+'/image',{method:'PUT',body:{imageKey:($event.target as HTMLSelectElement).value}}))"><option v-if="!state.imageKey" value="" disabled>{{state.image?'当前保留的镜像':'请选择已准备的镜像'}}</option><option v-for="image in state.images" :key="image.key" :value="image.key" :disabled="!image.ready">{{image.name}}{{image.ready?'':' · 未准备'}}</option></select></label>
       <p class="hint">{{state.mode==='shared'?'同一共享桌面只能使用一个镜像,选择会对所有共享成员生效。':'此桌面的镜像、文件和浏览器资料与其他独立桌面分开。'}}{{state.container!=='missing'?'切换镜像前请先移除实例。':''}}</p>
      </template>
-     <button v-if="!state.image" class="primary" :disabled="!isAdmin" @click="emit('settings')">设置本地虚拟机</button>
+     <button v-if="!state.fixedCapacity&&!state.image" class="primary" :disabled="!isAdmin" @click="emit('settings')">设置本地虚拟机</button>
      <button v-else-if="!state.fixedCapacity&&state.container==='missing'&&!agent.temporaryGoalId" class="primary" :disabled="busy" @click="action('create')">创建 {{agent.name}} 的虚拟机</button>
      <button v-else-if="!state.fixedCapacity&&state.container==='stopped'&&!agent.temporaryGoalId" class="primary" :disabled="busy" @click="action('start')">启动虚拟机</button>
      <template v-else-if="state.container==='running'">

+ 8 - 2
src/client/components/workspace/viewModels.ts

@@ -392,8 +392,14 @@ export function workspaceMessagesToUi(messages: import('@shared/workspace').Work
     taskReference: message.taskReference,
     error: message.error, runId: message.runId,
     profile: message.agentId, createdAt: message.createdAt,
-    content: (message.communication?.content ?? (message.role === 'assistant' ? visibleMessageText(message.content) : message.content)).replace(/(!?\[[^\]]*\])\(<?([^)>]+)>?\)/g, (whole, label: string, path: string) => {
-      const file = message.attachments.find(file => file.sourcePath === path)
+    // Resolve legacy MEDIA references before mapping paths to archived file URLs,
+    // so the renderer can identify body media and trailing attachments as one file.
+    content: (message.communication?.content ?? (message.role === 'assistant'
+      ? normalizeAssistantMediaMarkdown(visibleMessageText(message.content), message.status === 'streaming')
+      : message.content)).replace(/(!?\[[^\]]*\])\(<?([^)>]+)>?\)/g, (whole, label: string, path: string) => {
+      const sourcePath = serverFilePath(path)
+      const file = message.attachments.find(file => file.sourcePath === path
+        || (sourcePath && file.sourcePath && serverFilePath(file.sourcePath, false) === sourcePath))
       return file ? `${label}(/api/app/files/${file.id}/${label.startsWith('!') ? 'preview' : 'download'})` : whole
     }),
     reasoning: message.role === 'assistant' ? messageReasoningText(message.content, message.reasoning) : message.reasoning,

+ 4 - 1
src/server/desktopEnvironments.ts

@@ -153,10 +153,13 @@ export class DesktopEnvironments {
  snapshot(owner:string,agent?:WorkspaceAgent,deviceHost?:string,policy?:{script:boolean;server:boolean;maxMiB:number}):DesktopEnvironmentSnapshot {
   const capturedAt=Date.now(),global=policy??{...this.computers(),maxMiB:(()=>{try{return readHostTools(this.store.home).fileTransferMaxMiB}catch{return 25}})()}
   const records=this.store.list<import('../shared/desktopHost.js').DesktopHostRecord>('_system','desktop-host')
+  const revoked=new Set(records.filter(record=>!record.enabled).map(record=>record.id))
   const states=[...this.sessions.values()]
   for(const record of records)if(!states.some(host=>host.key===record.id))states.push(newHostState(record.id,true))
   if(deviceHost&&!states.some(host=>host.key===deviceHost))states.push(newHostState(deviceHost,deviceHost!=='local'))
-  const hosts:BotDeviceSnapshot[]=states.map((s):BotDeviceSnapshot=>{
+  // Revoked pairings remain stored for reauthorization, not as offline computers.
+  // Filter after merging sessions and message origin so neither can resurrect them.
+  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

+ 108 - 0
tests/client/composeDesktopConnection.test.ts

@@ -0,0 +1,108 @@
+import {afterEach,beforeEach,expect,it,vi} from 'vitest'
+import {flushPromises,mount} from '@vue/test-utils'
+import Panel from '../../src/client/components/workspace/LocalVmChatPanel.vue'
+import {apiRequest} from '../../src/client/api/client'
+
+vi.mock('../../src/client/api/client',()=>({apiRequest:vi.fn()}))
+const agent={id:'bot',name:'小民',nodeId:'local',profile:'default',execution:'profile',computer:'auto'} as any
+const desktop={id:'cursor',name:'Cursor 开发桌面',online:true,ready:true,available:true}
+let state:any,problem:string
+const mountPanel=()=>mount(Panel,{props:{agents:[agent],isAdmin:true,active:true},global:{stubs:{AppIcon:true,GrokAuthPanel:true}}})
+beforeEach(()=>{
+ vi.spyOn(document,'hidden','get').mockReturnValue(false)
+ problem=''
+ state={fixedCapacity:true,enabled:false,desktops:[{...desktop}]}
+ vi.mocked(apiRequest).mockImplementation(async(path,options:any)=>{
+  if(path.endsWith('/host-tools'))return {vm:true,cloud:false,serverComputer:false,scriptMachine:false} as any
+  if(path.endsWith('/desktop-environment'))return {hosts:[]} as any
+  if(path.endsWith('/cloud-computer'))return {configured:false} as any
+  if(path.includes('/computer/frame?backend=vm'))return {data:'fixture',width:100,height:80} as any
+  if(options?.method==='PUT'){
+   if(problem)throw new Error(problem)
+   state={...state,desktopId:options.body.desktopId,enabled:true,container:'running',ready:true,image:true,mode:'shared'}
+   return {agent:{...agent,computerEnvironmentId:state.desktopId}} as any
+  }
+  return state
+ })
+})
+afterEach(()=>{vi.restoreAllMocks();vi.clearAllMocks()})
+
+it('connects an unassigned bot to an existing Compose desktop and opens the VM viewer',async()=>{
+ const wrapper=mountPanel()
+ try{
+  await flushPromises()
+  expect(wrapper.get('[aria-label="共享桌面"]').element).toHaveProperty('value','cursor')
+  expect(vi.mocked(apiRequest).mock.calls.some(([,o])=>o?.method==='PUT')).toBe(false)
+  await wrapper.get('[data-testid="connect-compose-desktop"]').trigger('click');await flushPromises()
+  expect(apiRequest).toHaveBeenCalledWith('/api/app/agents/bot/local-vm',{method:'PUT',body:{enabled:true,desktopId:'cursor'}})
+  expect(wrapper.emitted('changed')).toHaveLength(1)
+  expect(wrapper.get('.preview img').attributes('src')).toContain('base64,fixture')
+  expect(wrapper.findAll('button').some(b=>b.text()==='设置本地虚拟机')).toBe(false)
+  await wrapper.findAll('button').find(b=>b.text()==='打开桌面')!.trigger('click')
+  expect(wrapper.emitted('desktop')?.at(-1)).toEqual([agent,'vm',undefined])
+ }finally{wrapper.unmount()}
+})
+
+it.each([
+ {online:false}, {ready:false}, {available:false},
+])('does not connect an unavailable desktop: %j',async unavailable=>{
+ state.desktops=[{...desktop,...unavailable}]
+ const wrapper=mountPanel()
+ try{
+  await flushPromises()
+  expect(wrapper.get('[aria-label="共享桌面"] option[value="cursor"]').attributes('disabled')).toBeDefined()
+  expect(wrapper.get('[data-testid="connect-compose-desktop"]').attributes('disabled')).toBeDefined()
+ }finally{wrapper.unmount()}
+})
+
+it('requires an explicit choice with several desktops and preserves it across refreshes',async()=>{
+ state.desktops.push({...desktop,id:'standard',name:'标准桌面'})
+ const wrapper=mountPanel()
+ try{
+  await flushPromises()
+  expect(wrapper.get('[data-testid="connect-compose-desktop"]').attributes('disabled')).toBeDefined()
+  await wrapper.get('[aria-label="共享桌面"]').setValue('standard')
+  await wrapper.setProps({active:false});await wrapper.setProps({active:true});await flushPromises()
+  expect(wrapper.get('[aria-label="共享桌面"]').element).toHaveProperty('value','standard')
+  await wrapper.get('[data-testid="connect-compose-desktop"]').trigger('click');await flushPromises()
+  expect(apiRequest).toHaveBeenCalledWith('/api/app/agents/bot/local-vm',{method:'PUT',body:{enabled:true,desktopId:'standard'}})
+ }finally{wrapper.unmount()}
+})
+
+it('keeps a rejected binding visible and does not claim the desktop is connected',async()=>{
+ problem='请连接启用 Compose 桌面模式的执行节点'
+ const wrapper=mountPanel()
+ try{
+  await flushPromises();await wrapper.get('[data-testid="connect-compose-desktop"]').trigger('click');await flushPromises()
+  expect(wrapper.get('[role="alert"]').text()).toBe(problem)
+  expect(wrapper.emitted('changed')).toBeUndefined()
+  expect(wrapper.findAll('button').some(b=>b.text()==='打开桌面')).toBe(false)
+ }finally{wrapper.unmount()}
+})
+
+it('keeps the existing assignment and blocks changes while the desktop is in use',async()=>{
+ state={...state,enabled:true,desktopId:'cursor',container:'running',ready:true,image:true,inUse:true}
+ const wrapper=mountPanel()
+ try{
+  await flushPromises()
+  expect(wrapper.get('[aria-label="共享桌面"]').element).toHaveProperty('value','cursor')
+  expect(wrapper.get('[aria-label="共享桌面"]').attributes('disabled')).toBeDefined()
+  expect(wrapper.get('[data-testid="connect-compose-desktop"]').text()).toBe('已连接')
+  expect(wrapper.get('[data-testid="connect-compose-desktop"]').attributes('disabled')).toBeDefined()
+ }finally{wrapper.unmount()}
+})
+
+it('does not reuse another bot selection or bind a desktop that became unavailable',async()=>{
+ state.desktops.push({...desktop,id:'standard',name:'标准桌面'})
+ const wrapper=mountPanel()
+ try{
+  await flushPromises();await wrapper.get('[aria-label="共享桌面"]').setValue('standard')
+  await wrapper.setProps({agents:[{...agent,id:'other'}]});await flushPromises()
+  expect(wrapper.get('[aria-label="共享桌面"]').element).toHaveProperty('value','')
+  await wrapper.get('[aria-label="共享桌面"]').setValue('standard')
+  state={...state,desktops:state.desktops.map((d:any)=>({...d,online:false}))}
+  await wrapper.setProps({active:false});await wrapper.setProps({active:true});await flushPromises()
+  expect(wrapper.get('[data-testid="connect-compose-desktop"]').attributes('disabled')).toBeDefined()
+  expect(vi.mocked(apiRequest).mock.calls.some(([,o])=>o?.method==='PUT')).toBe(false)
+ }finally{wrapper.unmount()}
+})

+ 41 - 0
tests/client/messageMedia.test.ts

@@ -3,6 +3,7 @@ import { describe, expect, it } from 'vitest'
 import MarkdownContent from '@/components/messages/MarkdownContent.vue'
 import { normalizeChatMessage } from '@/utils/normalize'
 import { chatMessageToUi, workspaceMessagesToUi } from '@/components/workspace/viewModels'
+import type { WorkspaceMessage } from '@shared/workspace'
 
 const attachments = [
   { id: 'doc', name: 'bamboo-sample.txt', size: 134, kind: 'file' as const, url: '/api/app/files/doc/download' },
@@ -43,4 +44,44 @@ describe('ordered message media', () => {
     expect(wrapper.findAll('.message-file')).toHaveLength(1)
     expect(wrapper.text()).toBe('bamboo-sample.txt134 B')
   })
+  it.each([
+    '/Users/samien/Agents/zhuer/2026-09-22/dingtalk-current-page.png',
+    '/tmp/截图 文件(1).png',
+    '/tmp/screenshot%20copy.png',
+  ])('renders a workspace MEDIA reference and its archived attachment once: %s', async sourcePath => {
+    const original: WorkspaceMessage = {
+      id: 'screenshot', conversationId: 'chat', seq: 1, role: 'assistant', agentId: 'bot',
+      content: `当前画面:\n\nMEDIA:${sourcePath}\n\n截图完成。`, reasoning: '',
+      status: 'complete', createdAt: 1, tools: [],
+      attachments: [{ id: 'screenshot-file', name: sourcePath.split('/').at(-1)!, sourcePath, mimeType: 'image/png', size: 3590111, sender: 'agent', createdAt: 1 }],
+    }
+    const message = workspaceMessagesToUi([original])[0]!
+    const wrapper = mount(MarkdownContent, { props: {
+      content: message.content, attachments: message.attachments, separateMedia: true, fileCards: true, legacyMedia: true,
+    } })
+    expect(wrapper.findAll('.message-media')).toHaveLength(1)
+    expect(wrapper.get('img').attributes('src')).toBe('/api/app/files/screenshot-file/preview')
+    expect([...wrapper.get('.message-parts').element.children].map(el => el.className)).toEqual(['message-prose', 'message-media', 'message-prose'])
+    await wrapper.get('.message-media__image').trigger('click')
+    expect(wrapper.emitted('preview')?.[0]?.[0]).toEqual(message.attachments![0])
+    expect(original.content).toContain(`MEDIA:${sourcePath}`)
+    wrapper.unmount()
+  })
+  it('reconciles a late workspace attachment without duplicating the streamed image or hiding a distinct same-name file', async () => {
+    const original: WorkspaceMessage = {
+      id: 'stream', conversationId: 'chat', seq: 1, role: 'assistant', agentId: 'bot',
+      content: 'MEDIA:/tmp/first/screenshot.png\n', reasoning: '', status: 'streaming', createdAt: 1, tools: [], attachments: [],
+    }
+    const props = () => {
+      const message = workspaceMessagesToUi([original])[0]!
+      return { content: message.content, attachments: message.attachments, streaming: message.status === 'streaming' }
+    }
+    const wrapper = mount(MarkdownContent, { props: { ...props(), separateMedia: true, fileCards: true, legacyMedia: true } })
+    expect(wrapper.findAll('img')).toHaveLength(1)
+    original.status = 'complete'
+    original.attachments = ['first', 'second'].map(id => ({ id, name: 'screenshot.png', sourcePath: `/tmp/${id}/screenshot.png`, mimeType: 'image/png', size: 123, sender: 'agent', createdAt: 1 }))
+    await wrapper.setProps(props())
+    expect(wrapper.findAll('img').map(image => image.attributes('src'))).toEqual(['/api/app/files/first/preview', '/api/app/files/second/preview'])
+    wrapper.unmount()
+  })
 })

+ 25 - 3
tests/server/desktopEnvironments.test.ts

@@ -392,20 +392,42 @@ it('snapshots negotiated host facts per owner without inventing paths for old cl
  expect(service.snapshot('owner',agent).hosts.find(host=>host.id==='local')?.metadata?.fileRoots).toEqual(['/Users/fixture'])
 })
 
-it('keeps offline and disabled registered computers visible with actionable reasons',()=>{
- store.put('_system','desktop-host',HOST_B,{id:HOST_B,name:'尚未连接',enabled:false,tokenHash:'private',createdAt:1})
+it('keeps enabled offline registered computers visible with actionable reasons',()=>{
+ store.put('_system','desktop-host',HOST_B,{id:HOST_B,name:'尚未连接',enabled:true,tokenHash:'private',createdAt:1})
  service.remoteExchange(HOST_A,{host:{...host,id:randomUUID(),name:'连接电脑',full:[ownerKey('owner')],environment:environmentMetadata},results:[]})
  const saved=service.snapshot('owner',agent,HOST_A)
  vi.useFakeTimers();vi.advanceTimersByTime(16000)
  const offline=service.snapshot('owner',agent,HOST_A)
  expect(offline.hosts.find(host=>host.id===HOST_A)).toMatchObject({source:true,online:false,capabilities:{shell:{enabled:false,status:'offline'}}})
  expect(offline.hosts.find(host=>host.id===HOST_A)?.metadata).toBeUndefined()
- expect(offline.hosts.find(host=>host.id===HOST_B)).toMatchObject({name:'尚未连接',open:false,capabilities:{view:{enabled:false,status:'disabled'}}})
+ expect(offline.hosts.find(host=>host.id===HOST_B)).toMatchObject({name:'尚未连接',online:false,open:true,capabilities:{view:{enabled:false,status:'offline'}}})
  expect(saved.hosts.find(host=>host.id===HOST_A)?.capabilities.shell.status).toBe('ready')
  expect(service.deviceContextLine('owner',HOST_A)).toContain('不能回退到服务器')
  expect(JSON.stringify(offline)).not.toContain('private')
 })
 
+it.each([false,true])('excludes revoked computers from Bot inventory even with a stale session: %s',staleSession=>{
+ const record={id:HOST_B,name:'旧配对电脑',enabled:false,tokenHash:'private',createdAt:1}
+ store.put('_system','desktop-host',HOST_B,record)
+ service.exchange({host,results:[]})
+ service.remoteExchange(HOST_A,{host:{...host,id:randomUUID(),name:'studio'},results:[]})
+ if(staleSession)service.remoteExchange(HOST_B,{host:{...host,id:randomUUID(),name:record.name},results:[]})
+ for(const source of [HOST_A,HOST_B]){
+  const snapshot=service.snapshot('owner',agent,source)
+  expect(snapshot.hosts.map(host=>host.id)).toEqual(['local',HOST_A])
+  expect(snapshot.sourceHost).toBe(source)
+  const inventory=service.onlineHostsLine('owner',source)
+  expect(inventory).toContain('host="server"')
+  expect(inventory).toContain(`host="${HOST_A}"`)
+  expect(inventory).not.toContain(HOST_B)
+  expect(inventory).not.toContain(record.name)
+ }
+ expect(service.deviceContextLine('owner',HOST_B)).toContain('不能回退到服务器')
+ expect(store.get('_system','desktop-host',HOST_B)).toEqual(record)
+ store.put('_system','desktop-host',HOST_B,{...record,enabled:true})
+ expect(service.snapshot('owner',agent).hosts.map(host=>host.id)).toEqual(['local',HOST_A,HOST_B])
+})
+
 it('distinguishes human takeover from grants and rechecks revocation after collecting a snapshot',async()=>{
  host.full=[ownerKey('owner')];drive()
  const ticket=await take(),snapshot=service.snapshot('owner',agent,'local'),server=snapshot.hosts[0]!