fix(electron): Phase 3 验收抓到的两个静默缺陷 —— 白屏与登录
Phase 3(写信 + 附件 + 权限面板)的验收脚本第一次跑就把这两件事翻出来了,
两个都**表现正常**:进程活着、窗口标题对、接口能通,只有结果不对。
## 1. 打包后的应用是白屏(vite 的 base 缺省值)
`vite.config.ts` 没设 `base`,Vite 按默认的 `/` 生成 `src="/assets/index-xxx.js"`。
同一份 dist 有两个宿主:网关在 `/` 下伺服它(Web 正常),Electron 用 `loadFile()`
从 **file:///…/dist/index.html** 加载它 —— 绝对路径在那儿解析成
`file:///assets/index-xxx.js`(不存在),**JS 根本没加载**。
现场:`#root` 里一个子节点都没有。没有报错对话框,控制台里只有一条不起眼的
资源加载失败。而当时所有既有检查都是绿的:`npm run build` 成功、deb 元数据检查、
asar 内容清点(**它们只看文件在不在,不看文件引用什么**)。
修法:`base: './'` —— 两边都对(Web 在 /index.html 里 `./assets/x.js` → `/assets/x.js`;
Electron 在 dist/index.html 里 → `dist/assets/x.js`)。
## 2. 桌面壳用账号密码登录是断的,而且静默失败
账号密码登录靠 `SameSite=Lax` 的会话 Cookie,而桌面壳的页面是 `file://`
(**不透明源**)—— Chromium 按第三方上下文处理它,Cookie **不予存储**。
实测现场:`POST /auth/login` 返 **200**、响应体能读出用户名,但 `document.cookie`
是空的,紧接着的 `/auth/me` 返 **401**;界面停在登录页,看起来像「密码错了」,
而同样的账号密码用 curl 登录是成功的。所以这不是凭据问题。
修法:桌面壳里**不再给账号密码表**(一个必然失败的按钮比没有更糟),改成粘贴
**用户密钥**(`Authorization: Bearer`,桌面端本来就该这么用):
- preload 显式声明 `__AGENTMAIL_SHELL__ = 'desktop'`(宿主契约,而不是让渲染层
sniff 协议;顺带让 jsdom 里可测 —— 那里的 `location.protocol` 不可重写)
- 新增 `authStore.loginWithKey`:成功后才留下令牌,失败**还原**(否则之后每个请求
都会带上这个坏 key 并 401,而人看到的是「重输一次也不行」)
- 顺手修了 label 与 input 没有关联(`htmlFor`/`id`)—— 无障碍缺陷,也让测试能按标签查
## 验收
- 结构性守卫进 `npm test`(`test/packaging.test.mjs`,不需要浏览器):base 必须是
相对路径、产物里不能有绝对资源引用、**安装包里的 dist 与当前构建一致**
(前端改了没重打包时,装上去的人看到的是旧界面,两边不一致却谁都不报错)。
判据自检过:把 base 改回 `/` 或把产物改回绝对路径,各自都能让对应那条变红。
- 组件测试 6 条(两种壳的形态、密钥成功/失败、空密钥不可提交)。
- `test/manual/desktop-phase3-verify.mjs`:真起打包好的应用(xvfb + CDP),
一条贯穿的链 —— 用桌面 UI 写信带附件 → 外部核验信与附件真到了网关 →
这封信触发 zcode 的真实授权请求 → 在桌面**授权面板**里点同意 →
外部核验 **Agent 真的执行了**(标记文件出现)。第二次跑 14/14 全绿。
- 客户端全量 222/222;网关换新产物后 Web 依旧正常(相对路径在 `/` 下同样成立,
实测渲染出收件箱、无控制台错误),并真发一封邮件确认回信到达。
## 判据自己的错(记一笔)
第一次跑时「附件真的挂在信上」报红,而库里那 41 字节的附件**明明挂在信上** ——
我把端点写成了 `/me/mail/{id}`(不存在,404),正确是 `/mail/{id}`。
判据用错端点时以「附件是空的」现形,看起来像功能 bug。
另:`pkill -f 'agentmail-web'` 会把**自己这条命令**也杀掉(命令行里含同样的字符串),
表现是「脚本没有任何输出、退出码 143」。改用端口定位(`ss -tlnp | grep :9223`)。
This commit is contained in:
@ -81,6 +81,54 @@ Electron 二进制在 `~/.cache/electron/`(首次需要网络,`electron-v44.
|
||||
> ⚠️ 当前 `author.email` 是容器占位值 `jianf@noreply.localhost`,
|
||||
> `homepage` 是内网 Gitea 地址。**正式对外分发前必须替换成真实值。**
|
||||
|
||||
## 两个坑:白屏与登录(都是静默的)
|
||||
|
||||
### 1. 白屏 —— `vite.config.ts` 必须写 `base: './'`
|
||||
|
||||
同一份 `dist/` 有两个宿主:网关在 `/` 下伺服它(Web),Electron 用
|
||||
`loadFile()` 从 **`file:///…/dist/index.html`** 加载它(桌面)。
|
||||
Vite 的默认 base 是 `/`,产物里写的是 `src="/assets/index-xxx.js"` ——
|
||||
在 `file://` 下它会解析成 `file:///assets/index-xxx.js`(不存在),
|
||||
**JS 根本没加载**。
|
||||
|
||||
现场非常不显眼:进程活着、窗口标题是 `AgentMail`、CDP 连得上、
|
||||
**``#root`` 里一个子节点都没有**。没有报错对话框,控制台里只有一条
|
||||
不起眼的资源加载失败。
|
||||
|
||||
改回绝对路径的后果是桌面端直接不可用,而 `npm run build`、deb 元数据检查、
|
||||
asar 内容清点**全都是绿的**(它们只看文件在不在,不看文件引用什么)。
|
||||
所以有一条结构性断言把它钉住(进 `npm test`):
|
||||
|
||||
```bash
|
||||
node --test test/packaging.test.mjs
|
||||
```
|
||||
|
||||
它验三件事:`vite.config.ts` 里的 `base` 是相对的;产物里没有绝对资源引用;
|
||||
**安装包里的 dist 与当前构建一致**(前端改了没重打包时,装上去的人看到的是旧界面,
|
||||
两边不一致但谁都不报错)。
|
||||
|
||||
### 2. 桌面壳不能用账号密码登录(会话 Cookie 存不下来)
|
||||
|
||||
账号密码登录靠 `SameSite=Lax` 的会话 Cookie,而桌面壳的页面是 `file://`
|
||||
(**不透明源**)—— Chromium 按第三方上下文处理它,**Cookie 不予存储**。
|
||||
|
||||
实测现场:`POST /auth/login` 返回 **200**、响应体能读出用户名,
|
||||
但 `document.cookie` 是空的,紧接着的 `/auth/me` 返回 **401**;
|
||||
界面停在登录页,看起来像「密码错了」,而同样的账号密码用 curl 登录是成功的。
|
||||
|
||||
所以桌面壳里**不提供**账号密码表单(一个必然失败的按钮比没有更糟),
|
||||
改成粘贴**用户密钥**(`Authorization: Bearer`):
|
||||
|
||||
```bash
|
||||
# 启动时注入(推荐:脚本化部署)
|
||||
AGENTMAIL_USER_KEY=<用户密钥> ./agentmail-web
|
||||
```
|
||||
|
||||
也可以用主进程环境变量 `AGENTMAIL_GATEWAY_URL` 指向别的网关。
|
||||
用户密钥在网页版的「账号 → 用户密钥」里创建,`electron/main.cjs` 把它经 preload
|
||||
注入成 `__AGENTMAIL_TOKEN__`,`src/api/config.ts` 从此对**所有**请求(含 SSE 与附件下载)
|
||||
自动带上。
|
||||
|
||||
## 两个产物的实质区别(实测)
|
||||
|
||||
| | AppImage | deb |
|
||||
|
||||
@ -20,6 +20,17 @@ function getInjected(name) {
|
||||
|
||||
contextBridge.exposeInMainWorld('__AGENTMAIL_API_BASE__', getInjected('api-base') || 'http://127.0.0.1:8180/api/v1');
|
||||
contextBridge.exposeInMainWorld('__AGENTMAIL_TOKEN__', getInjected('token') || undefined);
|
||||
// 显式声明「我是桌面壳」。
|
||||
//
|
||||
// 渲染层靠它决定登录页给不给账号密码:那条路在桌面壳里**注定失败**
|
||||
// (`file://` 是不透明源,SameSite=Lax 的会话 Cookie 存不下来,详见
|
||||
// authStore.loginWithKey 的注释)。
|
||||
//
|
||||
// 用显式标识而不是让渲染层自己去 sniff `location.protocol === 'file:'`:
|
||||
// 后者是推断出来的事实,而这里是一个由宿主声明的契约 —— 也让它可测
|
||||
// (jsdom 的 `location.protocol` 根本不可写)。渲染层仍保留 protocol 兜底,
|
||||
// 涵盖「有人直接把 dist 用 file:// 打开」这种情况。
|
||||
contextBridge.exposeInMainWorld('__AGENTMAIL_SHELL__', 'desktop');
|
||||
|
||||
contextBridge.exposeInMainWorld('agentmail', {
|
||||
/** Gateway 基础地址(主进程 env 或默认 127.0.0.1:8180) */
|
||||
|
||||
@ -19,7 +19,7 @@
|
||||
"build:linux": "vite build && electron-builder --linux",
|
||||
"preview": "vite preview",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "node test/markdown-xss.test.mjs && node test/narrow-layout.test.mjs && node test/theme.test.mjs && node test/background.test.mjs && vitest run",
|
||||
"test": "node test/markdown-xss.test.mjs && node test/narrow-layout.test.mjs && node test/theme.test.mjs && node test/background.test.mjs && node test/packaging.test.mjs && vitest run",
|
||||
"test:narrow": "node test/manual/narrow-verify.mjs",
|
||||
"test:wide": "node test/manual/wide-regression.mjs",
|
||||
"test:components": "vitest run",
|
||||
|
||||
@ -14,6 +14,8 @@ declare global {
|
||||
interface Window {
|
||||
__AGENTMAIL_API_BASE__?: string;
|
||||
__AGENTMAIL_TOKEN__?: string;
|
||||
/** 宿主壳标识;Electron preload 会设成 'desktop'。见 components/LoginPage 的说明 */
|
||||
__AGENTMAIL_SHELL__?: string;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -2,15 +2,35 @@ import { useEffect, useRef, useState } from 'react';
|
||||
import { useAuthStore } from '../stores/authStore';
|
||||
import { BrandMarkIcon, SpinnerIcon } from './icons';
|
||||
|
||||
/**
|
||||
* 当前是不是桌面壳。
|
||||
*
|
||||
* 它决定了**能不能用账号密码登录**:那条路靠 `SameSite=Lax` 的会话 Cookie,
|
||||
* 而 `file://` 是不透明源,Chromium 按第三方上下文处理它、不予存储
|
||||
* (实测:`/auth/login` 返 200,但 `document.cookie` 为空,接着 `/auth/me` 401)。
|
||||
* 详见 `stores/authStore.ts` 的 `loginWithKey` 注释。
|
||||
*
|
||||
* 主路径是宿主显式声明的 `__AGENTMAIL_SHELL__`(Electron preload 设 'desktop');
|
||||
* protocol 是兜底,涵盖「有人直接把 dist 用 file:// 打开」这件事。
|
||||
*/
|
||||
function isDesktopShell(): boolean {
|
||||
if (typeof window === 'undefined') return false;
|
||||
if (window.__AGENTMAIL_SHELL__ === 'desktop') return true;
|
||||
return window.location?.protocol === 'file:';
|
||||
}
|
||||
|
||||
export default function LoginPage() {
|
||||
const login = useAuthStore(s => s.login);
|
||||
const loginWithKey = useAuthStore(s => s.loginWithKey);
|
||||
const error = useAuthStore(s => s.error);
|
||||
const retryAfter = useAuthStore(s => s.retryAfter);
|
||||
const submitting = useAuthStore(s => s.submitting);
|
||||
const clearError = useAuthStore(s => s.clearError);
|
||||
|
||||
const desktop = isDesktopShell();
|
||||
const [username, setUsername] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [userKey, setUserKey] = useState('');
|
||||
const [countdown, setCountdown] = useState(0);
|
||||
const userRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
@ -36,11 +56,18 @@ export default function LoginPage() {
|
||||
}, [retryAfter]);
|
||||
|
||||
const locked = countdown > 0;
|
||||
const canSubmit = username.trim() !== '' && password !== '' && !submitting && !locked;
|
||||
const canSubmit = desktop
|
||||
? userKey.trim() !== '' && !submitting
|
||||
: username.trim() !== '' && password !== '' && !submitting && !locked;
|
||||
|
||||
const submit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!canSubmit) return;
|
||||
if (desktop) {
|
||||
const ok = await loginWithKey(userKey);
|
||||
if (!ok) setUserKey('');
|
||||
return;
|
||||
}
|
||||
const ok = await login(username, password);
|
||||
if (!ok) setPassword('');
|
||||
};
|
||||
@ -62,10 +89,42 @@ export default function LoginPage() {
|
||||
<p className="mt-1 text-xs text-gray-500">邮件驱动的多智能体协作平台</p>
|
||||
</div>
|
||||
|
||||
<form onSubmit={submit} className="space-y-3">
|
||||
<form onSubmit={submit} className="space-y-3" data-shell={desktop ? 'desktop' : 'browser'}>
|
||||
{/*
|
||||
桌面壳不给账号密码:那条路在这里**注定失败**(见 authStore.loginWithKey
|
||||
的注释:file:// 是不透明源,SameSite=Lax 的会话 Cookie 存不下来)。
|
||||
给一个必然失败的按钮比不给更糟 —— 人会以为是自己密码打错了。
|
||||
*/}
|
||||
{desktop ? (
|
||||
<>
|
||||
<div>
|
||||
<label className="block text-2xs font-medium text-gray-500 mb-1">用户名</label>
|
||||
<label htmlFor="login-user-key" className="block text-2xs font-medium text-gray-500 mb-1">用户密钥</label>
|
||||
<input
|
||||
id="login-user-key"
|
||||
ref={userRef}
|
||||
type="password"
|
||||
value={userKey}
|
||||
onChange={e => {
|
||||
setUserKey(e.target.value);
|
||||
if (error) clearError();
|
||||
}}
|
||||
placeholder="在网页版「账号」页创建,或启动时用 AGENTMAIL_USER_KEY 注入"
|
||||
autoComplete="off"
|
||||
spellCheck={false}
|
||||
className="w-full text-sm border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-100 focus:border-blue-400"
|
||||
/>
|
||||
<p className="mt-1 text-3xs text-gray-500 leading-relaxed">
|
||||
桌面客户端用密钥登录。网页版可以填账号密码,这里不行 ——
|
||||
浏览器的会话 Cookie 在不透明源(file://)下不会被保存。
|
||||
</p>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<div>
|
||||
<label htmlFor="login-username" className="block text-2xs font-medium text-gray-500 mb-1">用户名</label>
|
||||
<input
|
||||
id="login-username"
|
||||
ref={userRef}
|
||||
value={username}
|
||||
onChange={e => {
|
||||
@ -79,8 +138,9 @@ export default function LoginPage() {
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-2xs font-medium text-gray-500 mb-1">密码</label>
|
||||
<label htmlFor="login-password" className="block text-2xs font-medium text-gray-500 mb-1">密码</label>
|
||||
<input
|
||||
id="login-password"
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={e => {
|
||||
@ -91,6 +151,8 @@ export default function LoginPage() {
|
||||
className="w-full text-sm border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-100 focus:border-blue-400"
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<p className="text-xs text-red-600 bg-red-50 border border-red-100 rounded-md px-2.5 py-1.5">
|
||||
@ -105,7 +167,7 @@ export default function LoginPage() {
|
||||
className="w-full inline-flex items-center justify-center gap-2 py-2 text-sm font-medium rounded-md bg-blue-600 text-white hover:bg-blue-700 disabled:opacity-40 disabled:cursor-not-allowed transition-colors"
|
||||
>
|
||||
{submitting && <SpinnerIcon className="w-3.5 h-3.5" />}
|
||||
{submitting ? '登录中' : locked ? `已锁定 ${countdown}s` : '登录'}
|
||||
{submitting ? '登录中' : desktop ? '进入' : locked ? `已锁定 ${countdown}s` : '登录'}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
@ -14,6 +14,27 @@ interface AuthState {
|
||||
|
||||
bootstrap: () => Promise<void>;
|
||||
login: (username: string, password: string) => Promise<boolean>;
|
||||
/**
|
||||
* 桌面壳(file://)专用:用用户密钥登录。
|
||||
*
|
||||
* # 为什么桌面端不能用账号密码
|
||||
*
|
||||
* 账号密码登录靠**会话 Cookie**,而网关下发的是 `SameSite=Lax`。
|
||||
* 桌面客户端用 `loadFile()` 从 `file:///…/dist/index.html` 加载页面,
|
||||
* 那是个**不透明源**(`location.origin === 'file://'`):Chromium 按第三方上下文
|
||||
* 处理它,`SameSite=Lax` 的 Cookie **不予存储**。
|
||||
*
|
||||
* 实测的现场:`POST /auth/login` 返回 200、响应体能读出用户名,
|
||||
* 但 `document.cookie` 是空的,紧接着的 `/auth/me` 返回 401 ——
|
||||
* 于是界面停在登录页,看起来像「密码错了」,而密码是对的。
|
||||
* (外部用 curl 拿同样的账号密码登录是成功的,所以这不是凭据问题。)
|
||||
*
|
||||
* 桌面端的本该用法是**用户密钥**(`Authorization: Bearer`):
|
||||
* `electron/main.cjs` 会把 `AGENTMAIL_USER_KEY` / `AGENTMAIL_TOKEN`
|
||||
* 通过 preload 注入成 `__AGENTMAIL_TOKEN__`,这条路径实测完全可用。
|
||||
* 这个方法给「没注入环境变量、人手工粘一个 key」的情况用。
|
||||
*/
|
||||
loginWithKey: (key: string) => Promise<boolean>;
|
||||
logout: () => Promise<void>;
|
||||
clearError: () => void;
|
||||
/** 401 时由 api client 回调 */
|
||||
@ -59,6 +80,26 @@ export const useAuthStore = create<AuthState>(set => ({
|
||||
set({ phase: 'anonymous', user: null, error: null });
|
||||
},
|
||||
|
||||
loginWithKey: async key => {
|
||||
const trimmed = key.trim();
|
||||
if (!trimmed) return false;
|
||||
set({ submitting: true, error: null, retryAfter: null });
|
||||
const previous = api.getToken();
|
||||
api.setToken(trimmed);
|
||||
try {
|
||||
const { user } = await api.me();
|
||||
set({ phase: 'authenticated', user, submitting: false });
|
||||
return true;
|
||||
} catch (err) {
|
||||
// 失败要把令牌还原:留着一个错的 key 在内存里,会让**之后每一个**请求
|
||||
// 都带上它并 401,而人看到的却是「密钥不对」之后的一次正常登录尝试也失败。
|
||||
api.setToken(previous);
|
||||
const msg = err instanceof Error ? err.message : String(err);
|
||||
set({ error: `密钥不可用:${msg}`, submitting: false });
|
||||
return false;
|
||||
}
|
||||
},
|
||||
|
||||
clearError: () => set({ error: null, retryAfter: null }),
|
||||
|
||||
markAnonymous: () => set({ phase: 'anonymous', user: null })
|
||||
|
||||
121
client/electron/test/components/LoginPage.test.tsx
Normal file
121
client/electron/test/components/LoginPage.test.tsx
Normal file
@ -0,0 +1,121 @@
|
||||
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest';
|
||||
import { render, screen, waitFor } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import React from 'react';
|
||||
|
||||
import LoginPage from '../../src/components/LoginPage';
|
||||
import * as api from '../../src/api/client';
|
||||
import { useAuthStore } from '../../src/stores/authStore';
|
||||
|
||||
/**
|
||||
* 登录页的两种形态。
|
||||
*
|
||||
* # 这一条不是「多测一个分支」,而是一次真实故障的回归
|
||||
*
|
||||
* 打包后的桌面应用(Electron 用 `loadFile()` 从 `file://` 加载)**白屏之外还有第二个坑**:
|
||||
* 登录页照常出现、账号密码填对、`POST /auth/login` 也返回 200,
|
||||
* 但**页面停在登录页不动**,并且接口开始报 401。
|
||||
*
|
||||
* 根因是会话 Cookie 存不下来:网关下发 `SameSite=Lax`,而 `file://` 是不透明源,
|
||||
* Chromium 按第三方上下文处理它、不予存储。实测现场是
|
||||
* `document.cookie === ''` 且紧接着的 `/auth/me` 返回 401 ——
|
||||
* 用同样的账号密码从外部 curl 登录却是成功的,所以这不是凭据问题。
|
||||
*
|
||||
* 因此桌面壳里**不该出现**一个注定失败的账号密码表单:那会让人以为密码打错了。
|
||||
* 它应当换成用户密钥(`Authorization: Bearer`)—— 桌面端本来就该用这种方式。
|
||||
*/
|
||||
|
||||
/**
|
||||
* 切换「壳」。
|
||||
*
|
||||
* 用的是宿主显式声明的 `__AGENTMAIL_SHELL__`,而不是去改 `location.protocol` ——
|
||||
* jsdom 里那个属性**不可重定义**(`TypeError: Cannot redefine property: protocol`),
|
||||
* 而更根本的理由是:壳身份本来就该是宿主声明的契约,不该靠渲染层 sniff 协议。
|
||||
*/
|
||||
function setShell(shell: 'desktop' | 'browser') {
|
||||
if (shell === 'desktop') window.__AGENTMAIL_SHELL__ = 'desktop';
|
||||
else delete window.__AGENTMAIL_SHELL__;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
useAuthStore.setState({
|
||||
phase: 'anonymous',
|
||||
user: null,
|
||||
error: null,
|
||||
retryAfter: null,
|
||||
submitting: false
|
||||
});
|
||||
api.setToken(null);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
setShell('browser');
|
||||
api.setToken(null);
|
||||
});
|
||||
|
||||
describe('登录页(浏览器外壳)', () => {
|
||||
it('给账号密码,不给密钥输入', () => {
|
||||
setShell('browser');
|
||||
render(<LoginPage />);
|
||||
expect(screen.getByLabelText('用户名')).toBeInTheDocument();
|
||||
expect(screen.getByLabelText('密码')).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: '登录' })).toBeInTheDocument();
|
||||
expect(screen.queryByLabelText('用户密钥')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('用户名/密码为空时不能提交', async () => {
|
||||
setShell('browser');
|
||||
render(<LoginPage />);
|
||||
expect(screen.getByRole('button', { name: '登录' })).toBeDisabled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('登录页(桌面外壳,file://)', () => {
|
||||
it('★ 不给账号密码表单,给用户密钥', () => {
|
||||
setShell('desktop');
|
||||
render(<LoginPage />);
|
||||
// 反向对照:账号密码那两个字段必须**不在**
|
||||
expect(screen.queryByLabelText('密码')).not.toBeInTheDocument();
|
||||
expect(screen.queryByLabelText('用户名')).not.toBeInTheDocument();
|
||||
expect(screen.getByLabelText('用户密钥')).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: '进入' })).toBeInTheDocument();
|
||||
// 必须把原因说出来,否则用户会以为自己装错了版本
|
||||
expect(screen.getByText(/浏览器.*Cookie|Cookie.*不透明源|会话 Cookie/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('★ 密钥可用时进入应用(走 Bearer,不靠 Cookie)', async () => {
|
||||
setShell('desktop');
|
||||
const me = vi.spyOn(api, 'me').mockResolvedValue({
|
||||
user: { user_id: 'u1', username: 'gui-lab', display_name: 'GUI', role: 'user' } as never
|
||||
});
|
||||
render(<LoginPage />);
|
||||
await userEvent.type(screen.getByLabelText('用户密钥'), 'k'.repeat(32));
|
||||
await userEvent.click(screen.getByRole('button', { name: '进入' }));
|
||||
await waitFor(() => expect(useAuthStore.getState().phase).toBe('authenticated'));
|
||||
expect(me).toHaveBeenCalled();
|
||||
// 令牌真的进了 api 层(之后的每个请求都靠它)
|
||||
expect(api.getToken()).toBe('k'.repeat(32));
|
||||
});
|
||||
|
||||
it('★ 密钥不可用时:报错、清空输入、**不把坏密钥留在内存里**', async () => {
|
||||
setShell('desktop');
|
||||
vi.spyOn(api, 'me').mockRejectedValue(new Error('Unauthorized'));
|
||||
render(<LoginPage />);
|
||||
const input = screen.getByLabelText('用户密钥');
|
||||
await userEvent.type(input, 'bad-key');
|
||||
await userEvent.click(screen.getByRole('button', { name: '进入' }));
|
||||
await waitFor(() => expect(useAuthStore.getState().error).toMatch(/密钥不可用/));
|
||||
// 关键:没还原的话,之后**每一次**请求都会带上这个坏 key 并 401,
|
||||
// 而人看到的却是「重输一次也还是不行」。
|
||||
expect(api.getToken()).toBeNull();
|
||||
expect((input as HTMLInputElement).value).toBe('');
|
||||
expect(useAuthStore.getState().phase).toBe('anonymous');
|
||||
});
|
||||
|
||||
it('密钥为空时不能提交(不要发一次注定 401 的请求)', () => {
|
||||
setShell('desktop');
|
||||
render(<LoginPage />);
|
||||
expect(screen.getByRole('button', { name: '进入' })).toBeDisabled();
|
||||
});
|
||||
});
|
||||
@ -45,6 +45,7 @@ ADMIN_PW=<密码> npm run test:wide
|
||||
| `inbox-group-verify.mjs` | 收件箱按会话分组 |
|
||||
| `theme-verify.mjs` | 深浅两色的 WCAG 对比度 |
|
||||
| `accent-verify.mjs` | 强调色(红/绿/橙/黄/蓝)17 组配色,两模式各一遍 |
|
||||
| `desktop-phase3-verify.mjs` | **桌面客户端**:写信 + 附件 + 权限面板(见下) |
|
||||
|
||||
`narrow-probe-helper.mjs` 里两个函数值得单独知道:
|
||||
|
||||
@ -66,6 +67,29 @@ ADMIN_PW=<密码> npm run test:wide
|
||||
Tailwind 不生成未被使用的基础类,探它必然得到透明背景 —— 那是假阳性。
|
||||
它们由 `../theme.test.mjs` 的档位断言覆盖。
|
||||
|
||||
## 桌面客户端那一个(`desktop-phase3-verify.mjs`)
|
||||
|
||||
它不连共享浏览器,而是**自己起打包好的 Electron 应用**(xvfb + `--remote-debugging-port`),
|
||||
然后走一条贯穿全流程的链:
|
||||
|
||||
```bash
|
||||
ADMIN_PW=<密码> DESKTOP_BIN=release/linux-unpacked/agentmail-web \
|
||||
node test/manual/desktop-phase3-verify.mjs
|
||||
```
|
||||
|
||||
1. 用桌面 UI 写一封信、**带一个附件**,发给 `zcode`
|
||||
2. 外部(直接打网关 API)核验:信真的在、附件真的挂着 —— 界面说「已发送」不算证据
|
||||
3. 这封信让 `zcode` 触发一次**真实的授权请求**(执行门禁)
|
||||
4. 在桌面的**授权面板**里点「同意」
|
||||
5. 外部核验:决策被记录 **且** Agent 真把命令执行了(标记文件出现)
|
||||
|
||||
第 5 步是这条链的重点:它证明界面上的那一下点击真的走到了 Agent 那侧。
|
||||
只验界面变成「已同意」的话,一个只在本地改状态、根本没提交给网关的实现也能全绿。
|
||||
|
||||
第一条判据是「**应用渲染出内容了吗**」(`#root` 有子节点)—— 白屏时后面每一条都会
|
||||
以奇怪的方式失败,而真正的原因只以一条资源错误出现。这个脚本第一次跑就靠它抓到了
|
||||
`base` 那个白屏缺陷(见 `../packaging.test.mjs`)。
|
||||
|
||||
## 已知限制
|
||||
|
||||
headless Chromium 报告 `hover: none`,因此 `.reveal`(只在支持悬停的设备上隐藏)
|
||||
|
||||
380
client/electron/test/manual/desktop-phase3-verify.mjs
Normal file
380
client/electron/test/manual/desktop-phase3-verify.mjs
Normal file
@ -0,0 +1,380 @@
|
||||
/**
|
||||
* 桌面客户端 Phase 3 验收:写信 + 附件 + 权限面板。
|
||||
*
|
||||
* # 为什么是一条贯穿的路径,而不是三段独立的检查
|
||||
*
|
||||
* 三段连成一条链之后,每一段的「成功」都能被**外部**核验,而不是只看界面说了什么:
|
||||
*
|
||||
* 1. 用桌面 UI 写信,**带一个附件**,发给 zcode
|
||||
* 2. 外部核验:网关里真的有这封信、真的挂着 1 个附件(界面说「已发送」不算证据)
|
||||
* 3. 这封信让 zcode 触发一次**真实的授权请求**(我们刚做的执行门禁)
|
||||
* 4. 在桌面的**授权**面板里点「同意」
|
||||
* 5. 外部核验:决策被记录 **且** Agent 真的把命令执行了(标记文件出现)
|
||||
*
|
||||
* 第 5 步是关键 —— 它证明「桌面界面上的那一下点击」真的走到了 Agent 那侧。
|
||||
* 只验界面变成「已同意」的话,一个只在本地改状态、根本没提交给网关的实现
|
||||
* 也能全绿。
|
||||
*
|
||||
* # 这个脚本抓到的第一个真缺陷(白屏)
|
||||
*
|
||||
* 第一次跑的时候,判据 A「应用起来了吗」就红了:`#root` 里**一个子节点都没有**。
|
||||
* 根因是 `vite.config.ts` 没设 `base`,产物里写的是绝对路径 `/assets/index-xxx.js`;
|
||||
* 网关在 `/` 下伺服它没问题,但 Electron 用 `loadFile()` 从
|
||||
* `file:///…/dist/index.html` 加载时,绝对路径会解析成 `file:///assets/…`(不存在)。
|
||||
* 窗口标题、进程、CDP 全都正常,只有页面是白的。
|
||||
*
|
||||
* 所以判据 A 必须放在最前面,而且要断言**渲染出来了**,不能只断言「进程活着」
|
||||
* 或「页面加载完成」—— 后者在 JS 根本没加载时同样会成功。
|
||||
*
|
||||
* 用法:
|
||||
* ADMIN_PW=<密码> node test/manual/desktop-phase3-verify.mjs
|
||||
*
|
||||
* 环境变量:
|
||||
* ADMIN_USER 登录用户名,默认 gui-lab
|
||||
* ADMIN_PW 必填
|
||||
* AGENTMAIL_URL 网关地址,默认 http://127.0.0.1:8180
|
||||
* DESKTOP_CDP 桌面应用的 CDP 端点,默认 http://127.0.0.1:9223
|
||||
* DESKTOP_BIN 打包产物可执行文件;给了就由本脚本自己起(xvfb + CDP)
|
||||
* DESKTOP_LAUNCH 1/0,默认给了 DESKTOP_BIN 就起
|
||||
* AGENT_NAME 收件 Agent,默认 zcode
|
||||
* PLAYWRIGHT playwright 入口
|
||||
*/
|
||||
|
||||
const PW = process.env.PLAYWRIGHT || '/usr/lib/node_modules/playwright/index.mjs';
|
||||
const { chromium } = await import(PW);
|
||||
const { spawn } = await import('node:child_process');
|
||||
const { writeFileSync, mkdirSync } = await import('node:fs');
|
||||
const { join } = await import('node:path');
|
||||
const { existsSync, readFileSync } = await import('node:fs');
|
||||
|
||||
const CDP = process.env.DESKTOP_CDP || 'http://127.0.0.1:9223';
|
||||
const GW = (process.env.AGENTMAIL_URL || 'http://127.0.0.1:8180').replace(/\/$/, '');
|
||||
const API = `${GW}/api/v1`;
|
||||
const USER = process.env.ADMIN_USER || 'gui-lab';
|
||||
const PASS = process.env.ADMIN_PW || '';
|
||||
const AGENT = process.env.AGENT_NAME || 'zcode';
|
||||
const BIN = process.env.DESKTOP_BIN || '';
|
||||
const LAUNCH = process.env.DESKTOP_LAUNCH ? process.env.DESKTOP_LAUNCH === '1' : !!BIN;
|
||||
const MARK = `PHASE3-${Date.now()}`;
|
||||
const TMP = '/tmp/desktop-phase3';
|
||||
const KEY_FILE = process.env.DESKTOP_KEY_FILE || '/root/gotmp/desktop-phase3-key.txt';
|
||||
|
||||
const failed = [];
|
||||
const chk = (name, ok, note = '') => {
|
||||
console.log(` ${ok ? '通过' : '失败'} ${name}${note ? ' — ' + note : ''}`);
|
||||
if (!ok) failed.push(name);
|
||||
};
|
||||
|
||||
if (!PASS) {
|
||||
console.error('需要 ADMIN_PW');
|
||||
process.exit(2);
|
||||
}
|
||||
|
||||
// ─── 外部观察者:直接打网关 API(与界面完全独立的第二条路)──────────────
|
||||
|
||||
let cookie = '';
|
||||
async function api(path, init = {}) {
|
||||
const res = await fetch(API + path, {
|
||||
...init,
|
||||
headers: { 'Content-Type': 'application/json', ...(cookie ? { Cookie: cookie } : {}), ...(init.headers || {}) }
|
||||
});
|
||||
const text = await res.text();
|
||||
let body = {};
|
||||
try {
|
||||
body = text ? JSON.parse(text) : {};
|
||||
} catch {
|
||||
body = { raw: text.slice(0, 300) };
|
||||
}
|
||||
return { status: res.status, body, setCookie: res.headers.get('set-cookie') || '' };
|
||||
}
|
||||
|
||||
async function login() {
|
||||
const r = await api('/auth/login', { method: 'POST', body: JSON.stringify({ username: USER, password: PASS }) });
|
||||
if (r.status !== 200) throw new Error(`登录失败 HTTP ${r.status} ${JSON.stringify(r.body).slice(0, 200)}`);
|
||||
cookie = r.setCookie.split(';')[0];
|
||||
}
|
||||
|
||||
/** 收件箱里带这个标记、且**不是**权限请求的信(权限请求里会带命令原文)。 */
|
||||
async function findSent(mark) {
|
||||
for (const box of ['/me/mail/sent', '/me/mail/inbox']) {
|
||||
const r = await api(`${box}?limit=30`);
|
||||
const mails = r.body?.mails || [];
|
||||
const hit = mails.find(
|
||||
m => `${m.subject || ''} ${m.body || ''}`.includes(mark) && !String(m.subject || '').includes('权限请求')
|
||||
);
|
||||
if (hit) return { ...hit, box };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// ─── 起应用(可选)────────────────────────────────────────────────────
|
||||
|
||||
let child = null;
|
||||
async function ensureCdp() {
|
||||
for (let i = 0; i < 40; i++) {
|
||||
try {
|
||||
const r = await fetch(`${CDP}/json/version`);
|
||||
if (r.ok) return true;
|
||||
} catch {
|
||||
/* 还没起来 */
|
||||
}
|
||||
await new Promise(r => setTimeout(r, 500));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
if (LAUNCH) {
|
||||
if (!existsSync(BIN)) {
|
||||
console.error(`找不到可执行文件:${BIN}`);
|
||||
process.exit(2);
|
||||
}
|
||||
console.log(`启动桌面应用:${BIN}`);
|
||||
child = spawn(
|
||||
'xvfb-run',
|
||||
['-a', '-s', '-screen 0 1400x900x24', BIN, '--no-sandbox', '--disable-gpu', `--remote-debugging-port=${new URL(CDP).port}`],
|
||||
{
|
||||
env: { ...process.env, AGENTMAIL_GATEWAY_URL: GW, DBUS_SESSION_BUS_ADDRESS: 'disabled:' },
|
||||
stdio: ['ignore', 'pipe', 'pipe']
|
||||
}
|
||||
);
|
||||
child.stdout.on('data', () => {});
|
||||
child.stderr.on('data', () => {});
|
||||
}
|
||||
|
||||
const up = await ensureCdp();
|
||||
if (!up) {
|
||||
console.error(`CDP 端点不可用:${CDP}`);
|
||||
if (child) child.kill('SIGKILL');
|
||||
process.exit(2);
|
||||
}
|
||||
|
||||
const browser = await chromium.connectOverCDP(CDP);
|
||||
const ctx = browser.contexts()[0] ?? (await browser.newContext());
|
||||
const page =
|
||||
ctx.pages().find(p => p.url().startsWith('file:') || p.url().includes('index.html')) ?? ctx.pages()[0];
|
||||
if (!page) {
|
||||
console.error('没找到应用窗口');
|
||||
process.exit(2);
|
||||
}
|
||||
await page.setViewportSize({ width: 1280, height: 800 });
|
||||
|
||||
const consoleErrors = [];
|
||||
page.on('console', m => {
|
||||
if (m.type() === 'error') consoleErrors.push(m.text().slice(0, 200));
|
||||
});
|
||||
page.on('pageerror', e => consoleErrors.push('pageerror: ' + String(e).slice(0, 200)));
|
||||
|
||||
const shot = n => page.screenshot({ path: join(TMP, `${n}.png`) }).catch(() => {});
|
||||
mkdirSync(TMP, { recursive: true });
|
||||
|
||||
try {
|
||||
console.log(`\n桌面 Phase 3 验收(标记 ${MARK})\n`);
|
||||
|
||||
// ─── A. 应用真的渲染出来了吗(白屏判据)───────────────────────────
|
||||
await page.waitForTimeout(2500);
|
||||
const boot = await page.evaluate(() => {
|
||||
const root = document.getElementById('root');
|
||||
return {
|
||||
title: document.title,
|
||||
children: root ? root.children.length : -1,
|
||||
textLen: (root?.innerText || '').trim().length,
|
||||
apiBase: window.__AGENTMAIL_API_BASE__ || ''
|
||||
};
|
||||
});
|
||||
// ★ 这一条必须放最前面:JS 没加载时,后面每一条都会以奇怪的方式失败,
|
||||
// 而真正的原因(资源路径)只以一条不起眼的资源错误出现。
|
||||
chk(
|
||||
'A. 应用渲染出了内容(不是白屏)',
|
||||
boot.children > 0 && boot.textLen > 0,
|
||||
`#root 子节点=${boot.children} 文本=${boot.textLen} 字`
|
||||
);
|
||||
chk('A. preload 注入的 API 基地址正确', boot.apiBase === API, `实际 ${boot.apiBase || '(空)'} 期望 ${API}`);
|
||||
// 资源加载失败会让「白屏」看起来像「后端不可用」,单独看一眼
|
||||
const resErr = consoleErrors.filter(t => /Failed to load resource/.test(t));
|
||||
chk('A. 没有资源加载失败', resErr.length === 0, resErr.slice(0, 2).join(' | '));
|
||||
if (failed.length) await shot('00-blank');
|
||||
|
||||
// ─── B. 登录 ──────────────────────────────────────────────────────
|
||||
// 登录页在**桌面壳**里给的是「用户密钥」,不是账号密码 —— 见
|
||||
// src/components/LoginPage.tsx:file:// 是不透明源,SameSite=Lax 的会话 Cookie
|
||||
// 存不下来,账号密码那条路在这里注定失败(而且会静默失败)。
|
||||
const needLogin = (await page.locator('input[type=password]').count()) > 0;
|
||||
let how = '已是登录态';
|
||||
if (needLogin) {
|
||||
const keyField = page.locator('#login-user-key');
|
||||
if (await keyField.count()) {
|
||||
const key = process.env.DESKTOP_KEY || (existsSync(KEY_FILE) ? readFileSync(KEY_FILE, 'utf8').trim() : '');
|
||||
if (!key) {
|
||||
chk('B. 登录', false, `桌面壳需要用户密钥:设 DESKTOP_KEY 或写到 ${KEY_FILE}`);
|
||||
throw new Error('缺用户密钥');
|
||||
}
|
||||
await keyField.fill(key);
|
||||
await page.locator('button[type=submit]').first().click();
|
||||
how = '用用户密钥(Bearer)进入';
|
||||
} else {
|
||||
await page.locator('input[type=text], input:not([type])').first().fill(USER);
|
||||
await page.locator('input[type=password]').fill(PASS);
|
||||
await page.locator('button[type=submit]').first().click();
|
||||
how = '用账号密码登录(浏览器壳)';
|
||||
}
|
||||
await page.waitForTimeout(3500);
|
||||
}
|
||||
const loggedIn = (await page.locator('input[type=password]').count()) === 0;
|
||||
chk('B. 登录成功(离开登录页)', loggedIn, how);
|
||||
await shot('10-inbox');
|
||||
|
||||
await login(); // 外部观察者
|
||||
chk('B. 外部观察者登录成功', cookie.length > 0);
|
||||
|
||||
// ─── C. 写信 + 附件 + 发送 ────────────────────────────────────────
|
||||
await page.locator('button[title="新建邮件"], button:has-text("新建")').first().click();
|
||||
await page.waitForTimeout(800);
|
||||
await page.locator('input[placeholder*="deepseekharness"]').first().fill(AGENT);
|
||||
await page.locator('input[placeholder="更新特性分支"]').fill(`Phase3 验收 ${MARK}`);
|
||||
await page.locator('textarea').first().fill(
|
||||
`请用 run_command 执行:echo ${MARK} > /tmp/desktop-phase3/${MARK}.txt\n` +
|
||||
`然后回信告诉我结果。这是需要授权的动作,如果被拒绝请说明原因。`
|
||||
);
|
||||
|
||||
// 附件:input 是 hidden 的,交给 playwright 直接塞文件(真实用户点的是「添加附件」)
|
||||
const attachPath = join(TMP, `${MARK}.txt`);
|
||||
writeFileSync(attachPath, `Phase3 附件内容 ${MARK}\n`);
|
||||
await page.locator('input[type=file]').setInputFiles(attachPath);
|
||||
// 上传是异步的:等「1 个附件」出现,而不是设完就往下走
|
||||
let attachSeen = false;
|
||||
for (let i = 0; i < 20; i++) {
|
||||
const t = await page.locator('body').innerText();
|
||||
if (/1 个附件/.test(t)) {
|
||||
attachSeen = true;
|
||||
break;
|
||||
}
|
||||
await page.waitForTimeout(500);
|
||||
}
|
||||
chk('C. 附件上传完成(界面显示 1 个附件)', attachSeen);
|
||||
await shot('20-compose');
|
||||
|
||||
await page.locator('button:has-text("发送")').last().click();
|
||||
let sentMsg = '';
|
||||
for (let i = 0; i < 30; i++) {
|
||||
sentMsg = await page.locator('body').innerText();
|
||||
if (/已发送/.test(sentMsg)) break;
|
||||
await page.waitForTimeout(500);
|
||||
}
|
||||
chk('C. 界面报告已发送', /已发送/.test(sentMsg), sentMsg.match(/已发送[^\n]{0,40}/)?.[0] || '');
|
||||
|
||||
// 外部核验:信真的在网关里、真的带附件
|
||||
let mail = null;
|
||||
for (let i = 0; i < 20; i++) {
|
||||
mail = await findSent(MARK);
|
||||
if (mail) break;
|
||||
await new Promise(r => setTimeout(r, 1000));
|
||||
}
|
||||
chk('C. 外部核验:信真的到了网关', !!mail, mail ? `${mail.box} ${mail.subject}` : '找不到');
|
||||
if (mail) {
|
||||
// 端点要选对:单封邮件是 `/mail/{id}`(挂在 /me 组下但路径不带 me 前缀),
|
||||
// `/me/mail/{id}` 不存在、会 404 —— 判据写错端点时会以「附件是空的」现形,
|
||||
// 看起来像功能 bug。实测踩过一次。
|
||||
const detail = await api(`/mail/${mail.mail_id}`);
|
||||
const att = detail.body?.attachments || [];
|
||||
chk(
|
||||
'C. 外部核验:附件真的挂在信上',
|
||||
att.length === 1 && String(att[0]?.filename || '').includes(MARK),
|
||||
`HTTP ${detail.status} 附件=${JSON.stringify(att.map(a => a.filename))}`
|
||||
);
|
||||
}
|
||||
|
||||
// ─── D. 权限面板 ──────────────────────────────────────────────────
|
||||
// 上面那封信会让 Agent 触发一次真实授权请求。等它出现(**按唯一标记**定位,
|
||||
// 待决列表里有历史积压,用「第一条新的」会拿到别人的)。
|
||||
console.log(' 等 Agent 发起授权请求…');
|
||||
let pending = null;
|
||||
for (let i = 0; i < 90; i++) {
|
||||
const r = await api('/permission/pending');
|
||||
const reqs = r.body?.requests || [];
|
||||
pending = reqs.find(q => JSON.stringify(q).includes(MARK));
|
||||
if (pending) break;
|
||||
await new Promise(r => setTimeout(r, 2000));
|
||||
}
|
||||
chk('D. 出现了属于本次实验的授权请求', !!pending, pending ? `mail=${String(pending.mail_id).slice(0, 8)}` : '90 次轮询未等到');
|
||||
|
||||
if (pending) {
|
||||
// 界面侧:切到「授权」面板,确认它把这个请求列出来了
|
||||
await page.locator('button:has-text("授权")').first().click();
|
||||
await page.waitForTimeout(1500);
|
||||
// 刷新一次列表,避免依赖 SSE 是否已推送
|
||||
await page.evaluate(() => window.dispatchEvent(new Event('focus')));
|
||||
await page.waitForTimeout(1500);
|
||||
const panelText = await page.locator('body').innerText();
|
||||
chk('D. 授权面板里列出了它', panelText.includes(MARK.slice(0, 20)), '按标记片段找');
|
||||
await shot('30-permissions');
|
||||
|
||||
// 点开那条请求,在详情里点「同意」
|
||||
const row = page.locator(`text=${MARK.slice(0, 16)}`).first();
|
||||
if (await row.count()) {
|
||||
await row.click();
|
||||
await page.waitForTimeout(1500);
|
||||
}
|
||||
const agree = page.locator('button:has-text("同意")').first();
|
||||
const hasAgree = (await agree.count()) > 0;
|
||||
chk('D. 详情里出现了「同意」按钮', hasAgree);
|
||||
if (hasAgree) {
|
||||
await agree.click();
|
||||
await page.waitForTimeout(2500);
|
||||
await shot('31-decided');
|
||||
}
|
||||
|
||||
// 外部核验 1:决策被记录,且**确实来自这次界面点击**
|
||||
let decided = null;
|
||||
for (let i = 0; i < 20; i++) {
|
||||
const r = await api('/permission/pending');
|
||||
const still = (r.body?.requests || []).find(q => q.mail_id === pending.mail_id);
|
||||
if (!still) {
|
||||
decided = 'gone-from-pending';
|
||||
break;
|
||||
}
|
||||
await new Promise(r2 => setTimeout(r2, 1000));
|
||||
}
|
||||
chk('D. 外部核验:请求已离开待决列表', !!decided, decided || '');
|
||||
|
||||
// 外部核验 2(最关键):Agent 真的执行了 —— 文件出现且内容等于标记
|
||||
const markerPath = join(TMP, `${MARK}.txt`);
|
||||
let content = null;
|
||||
for (let i = 0; i < 60; i++) {
|
||||
if (existsSync(markerPath)) {
|
||||
content = readFileSync(markerPath, 'utf8').trim();
|
||||
break;
|
||||
}
|
||||
await new Promise(r => setTimeout(r, 2000));
|
||||
}
|
||||
chk(
|
||||
'D. ★ 外部核验:Agent 真的执行了(标记文件出现)',
|
||||
content === MARK,
|
||||
content === null ? `${markerPath} 不存在(界面点了同意,但没走到 Agent)` : JSON.stringify(content)
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
console.log(`\n 异常:${String(e).slice(0, 300)}`);
|
||||
failed.push('脚本异常');
|
||||
await shot('99-error');
|
||||
} finally {
|
||||
if (consoleErrors.length) {
|
||||
console.log('\n 控制台错误(去重后前 5 条):');
|
||||
for (const t of [...new Set(consoleErrors)].slice(0, 5)) console.log(' ', t);
|
||||
}
|
||||
try {
|
||||
await browser.close();
|
||||
} catch {
|
||||
/* 断连无妨 */
|
||||
}
|
||||
if (child) {
|
||||
// 等它真的退出:只发信号不等,下次跑会撞上旧窗口(同 SSE 那次的教训)
|
||||
child.kill('SIGTERM');
|
||||
for (let i = 0; i < 20 && child.exitCode === null; i++) await new Promise(r => setTimeout(r, 200));
|
||||
if (child.exitCode === null) child.kill('SIGKILL');
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`\n 结果:${failed.length === 0 ? '全部通过' : `${failed.length} 项失败`}`);
|
||||
for (const f of failed) console.log(` ✗ ${f}`);
|
||||
console.log(` 截图:${TMP}`);
|
||||
process.exit(failed.length === 0 ? 0 : 1);
|
||||
89
client/electron/test/packaging.test.mjs
Normal file
89
client/electron/test/packaging.test.mjs
Normal file
@ -0,0 +1,89 @@
|
||||
/**
|
||||
* 桌面安装包的结构性断言(进 `npm test`,不需要浏览器)。
|
||||
*
|
||||
* # 为什么必须有一条这样的测试
|
||||
*
|
||||
* 这一条来自一次真实的白屏事故:`vite.config.ts` 没有设 `base`,Vite 于是按
|
||||
* 默认的 `/` 生成绝对路径 `src="/assets/index-xxx.js"`。Web 侧一切正常
|
||||
* (网关在 `/` 下伺服),但 Electron 用 `loadFile()` 从
|
||||
* **file:///…/dist/index.html** 加载同一份产物 —— 绝对路径会解析成
|
||||
* `file:///assets/index-xxx.js`(不存在),**JS 根本没加载**。
|
||||
* 表现是「应用起来了、窗口标题对、`#root` 里一个节点都没有」:
|
||||
* 页面全白,没有报错对话框,控制台里只有一条不起眼的资源加载失败。
|
||||
*
|
||||
* 而当时所有既有检查都是绿的:
|
||||
*
|
||||
* - `npm run build` 成功(它只管产物能不能生成)
|
||||
* - deb/AppImage 结构检查通过(BUILD.md 里那套:元数据、chrome-sandbox 权限、
|
||||
* asar 里有 dist —— **都只看文件在不在,不看它引用什么**)
|
||||
*
|
||||
* 所以这里断言的是**产物内部的引用形态**,而不是「文件存在」。
|
||||
*
|
||||
* 另一条同样静默的风险:安装包里的 `dist/` 是构建时的快照。前端改了却没重打包,
|
||||
* 装上去的人看到的是旧界面,而 Web 上是新的 —— 两边不一致但谁都不报错。
|
||||
*/
|
||||
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync, existsSync } from 'node:fs';
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const HERE = dirname(fileURLToPath(import.meta.url));
|
||||
const ROOT = join(HERE, '..');
|
||||
const DIST_HTML = join(ROOT, 'dist', 'index.html');
|
||||
|
||||
test('★ vite 的 base 必须是相对路径(否则 Electron 白屏)', () => {
|
||||
const cfg = readFileSync(join(ROOT, 'vite.config.ts'), 'utf8');
|
||||
// 不能只看 `base:` 出现在注释里 —— 断言的是真的有一条 base 配置语句
|
||||
assert.match(
|
||||
cfg,
|
||||
/^\s*base:\s*['"]\.\/['"]/m,
|
||||
"vite.config.ts 必须写 base: './':同一份 dist 会被 Electron 从 file:// 加载," +
|
||||
'绝对路径 /assets/... 在那儿解析不到,应用会白屏'
|
||||
);
|
||||
});
|
||||
|
||||
test('★ 构建产物里不能有绝对资源路径(这条能在没浏览器时抓住白屏)', () => {
|
||||
if (!existsSync(DIST_HTML)) {
|
||||
// 没构建过就跳过,但**要说出来**:静默跳过会让人以为验过了
|
||||
console.log('(dist/index.html 不存在 —— 先 cd client/electron && npm run build 才验得到)');
|
||||
return;
|
||||
}
|
||||
const html = readFileSync(DIST_HTML, 'utf8');
|
||||
const abs = [...html.matchAll(/(?:src|href)="(\/[^"]*)"/g)].map(m => m[1]);
|
||||
assert.deepEqual(
|
||||
abs,
|
||||
[],
|
||||
`产物里有绝对资源路径,Electron 从 file:// 加载时会白屏:\n ${abs.join('\n ')}`
|
||||
);
|
||||
// 反向对照:相对引用必须真的在(否则「没有绝对路径」可能只是因为什么都没引用)
|
||||
const rel = [...html.matchAll(/(?:src|href)="\.\/([^"]*)"/g)].map(m => m[1]);
|
||||
assert.ok(rel.length >= 2, `产物应有多个相对资源引用,实际 ${rel.length} 个`);
|
||||
assert.ok(
|
||||
rel.some(p => p.endsWith('.js')) && rel.some(p => p.endsWith('.css')),
|
||||
`相对引用里应同时含 js 与 css,实际:${rel.join(', ')}`
|
||||
);
|
||||
});
|
||||
|
||||
test('★ 安装包里的 dist 必须与当前构建一致(否则装上去的是旧界面)', () => {
|
||||
// 「文件存在」不算 —— 要比**内容**。比的是每个资源的文件名(Vite 带内容哈希),
|
||||
// 所以只要前端产物变了,这里就会红。
|
||||
const asar = join(ROOT, 'release', 'linux-unpacked', 'resources', 'app.asar');
|
||||
if (!existsSync(asar) || !existsSync(DIST_HTML)) {
|
||||
console.log('(没有安装包或没有 dist —— 打包前这条不适用)');
|
||||
return;
|
||||
}
|
||||
const list = execFileSync('npx', ['asar', 'list', asar], { encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 });
|
||||
const wanted = [...readFileSync(DIST_HTML, 'utf8').matchAll(/\.\/(assets\/[^"]+)/g)].map(m => m[1]);
|
||||
|
||||
const missing = wanted.filter(p => !list.includes(`/dist/${p}`));
|
||||
assert.deepEqual(
|
||||
missing,
|
||||
[],
|
||||
'安装包里的 dist 与当前构建不一致(前端改了但没重打包):\n' +
|
||||
` 缺:${missing.join(', ')}\n` +
|
||||
' 重打:npx electron-builder --linux -c.electronDownload.isVerifyChecksum=false'
|
||||
);
|
||||
});
|
||||
@ -3,6 +3,18 @@ import react from '@vitejs/plugin-react';
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
// ★ 必须是相对路径。
|
||||
//
|
||||
// 同一份 `dist/` 有两个宿主:网关在 `/` 下伺服它(Web),Electron 用
|
||||
// `loadFile()` 从 **file:///…/dist/index.html** 加载它(桌面)。
|
||||
// Vite 的默认 base 是 `/`,产物里写的是 `/assets/index-xxx.js` ——
|
||||
// 在 file:// 下它会解析成 `file:///assets/index-xxx.js`(不存在),
|
||||
// 于是 **Electron 应用白屏**:`#root` 里一个子节点都没有,
|
||||
// 而且加载失败只以一条资源错误出现,看起来像「应用没起来」。
|
||||
//
|
||||
// 相对路径两边都对:Web 在 `/index.html` 里 `./assets/x.js` → `/assets/x.js`;
|
||||
// Electron 在 `dist/index.html` 里 `./assets/x.js` → `dist/assets/x.js`。
|
||||
base: './',
|
||||
server: {
|
||||
port: 5173,
|
||||
proxy: {
|
||||
|
||||
Reference in New Issue
Block a user