feat(pi): 交互式 pi 会话接入邮件工具(send_mail/read_inbox 等 10 个)
问题(⑧):守护进程用 noExtensions:true 起会话,它的邮件工具只给模型在邮件
会话里用;人在 TUI 里敲的 pi 拿不到。结果是平台的建设者自己收不到邮件 ——
一个「邮件驱动」的平台,维护者只能绕到 curl + 密钥直连 Gateway 才能看收件箱。
新增 plugins/pi-mail-bridge/extension/index.ts:把同一套工具(createMailTools)
注册到交互式会话。两者是同一条 AgentMail 身份(agent pi)的两个入口,与 DSH 的
「TUI + 邮箱是同一个 Agent」一致。
密钥解析顺序(交互式 pi 的环境里没有 AGENTMAIL_*):
1. 进程环境
2. AGENTMAIL_ENV_FILE(默认 /etc/agentmail/pi.env)—— 与守护进程同一把密钥,
因此身份一致
3. AGENTMAIL_CONFIG_DIR/agent.key 或 ~/.agentmail/agent.key
(兼容 key 与 key_token 两种字段名;实测本机文件用的是 key_token,
只认 key 会静默读不到)
拿不到密钥时不注册任何工具并明确告知 —— 挂一组永远 401 的工具比没有更糟。
不注册 connect_to_server:它会重写 Gateway 坐标并重新登记密钥,而交互式会话与
守护进程共用同一身份,一次 TUI 对话不该改到守护进程的配置。
为什么不会重复注册(读 SDK 实现确认,并用探针实测):
resource-loader.js 里 noExtensions 为真时只用 cliEnabledExtensions,
settings.json 的 extensions 数组被排除 —— 即 noExtensions:true 只加载
命令行 -e 传入的扩展。
探针:noExtensions=true → 扩展数=0;false → 16 个且含 pi-mail-bridge。
deploy/install.sh 增加幂等的扩展注册步骤(写入 settings.json 的 extensions)。
验证:headless pi 实际调用 read_inbox 返回真实邮件主题;工具清单含
send_mail/read_inbox/read_mail/forward_mail/upload_attachment/download_attachment/
suggest_address/list_contacts/session_participants/read_thread(10 个),
connect_to_server 按设计排除。
This commit is contained in:
@ -1,35 +1,50 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import Markdown from 'react-markdown';
|
||||
import remarkGfm from 'remark-gfm';
|
||||
import { useMailStore } from '../stores/mailStore';
|
||||
import { useSessionStore } from '../stores/sessionStore';
|
||||
import { useContactStore } from '../stores/contactStore';
|
||||
import { useAuthStore } from '../stores/authStore';
|
||||
import { useEffect, useState } from "react";
|
||||
import Markdown from "react-markdown";
|
||||
import remarkGfm from "remark-gfm";
|
||||
import { useMailStore } from "../stores/mailStore";
|
||||
import { useSessionStore } from "../stores/sessionStore";
|
||||
import { useContactStore } from "../stores/contactStore";
|
||||
import { useAuthStore } from "../stores/authStore";
|
||||
import {
|
||||
sessionReplyTarget,
|
||||
mailReplyTarget,
|
||||
mailCounterpart,
|
||||
replyAllCC,
|
||||
participantAddress
|
||||
} from '../lib/replyTarget';
|
||||
import * as api from '../api/client';
|
||||
import type { Mail } from '../types';
|
||||
import { MailIcon, ShieldIcon, PersonIcon, BotIcon, CheckIcon, CloseIcon, ForwardIcon, TreeIcon, TagIcon, GaugeIcon } from './icons';
|
||||
import AddressInput from './AddressInput';
|
||||
import { AttachmentList, AttachmentPicker, type PendingAttachment } from './Attachments';
|
||||
import ThreadView from './ThreadView';
|
||||
import PermissionChip, { permissionModeHint } from './PermissionChip';
|
||||
import BackButton from './BackButton';
|
||||
participantAddress,
|
||||
} from "../lib/replyTarget";
|
||||
import * as api from "../api/client";
|
||||
import type { Mail } from "../types";
|
||||
import {
|
||||
MailIcon,
|
||||
ShieldIcon,
|
||||
PersonIcon,
|
||||
BotIcon,
|
||||
CheckIcon,
|
||||
CloseIcon,
|
||||
ForwardIcon,
|
||||
TreeIcon,
|
||||
TagIcon,
|
||||
GaugeIcon,
|
||||
} from "./icons";
|
||||
import AddressInput from "./AddressInput";
|
||||
import {
|
||||
AttachmentList,
|
||||
AttachmentPicker,
|
||||
type PendingAttachment,
|
||||
} from "./Attachments";
|
||||
import ThreadView from "./ThreadView";
|
||||
import PermissionChip, { permissionModeHint } from "./PermissionChip";
|
||||
import BackButton from "./BackButton";
|
||||
|
||||
export default function MailView() {
|
||||
const currentMail = useMailStore(s => s.currentMail);
|
||||
const markRead = useMailStore(s => s.markRead);
|
||||
const currentSession = useSessionStore(s => s.currentSession);
|
||||
const currentSessionMails = useSessionStore(s => s.currentSessionMails);
|
||||
const currentMail = useMailStore((s) => s.currentMail);
|
||||
const markRead = useMailStore((s) => s.markRead);
|
||||
const currentSession = useSessionStore((s) => s.currentSession);
|
||||
const currentSessionMails = useSessionStore((s) => s.currentSessionMails);
|
||||
// 当前登录用户名:判定「哪封是我发的」的唯一基准。
|
||||
// 曾经写死成 'human'(单用户时代的遗留),多用户下登录名可能是 jianf,
|
||||
// 判据恒为假 —— 于是回复自己发的信时对端取成了自己。
|
||||
const me = useAuthStore(s => s.user?.username || '');
|
||||
const me = useAuthStore((s) => s.user?.username || "");
|
||||
// 转发面板作用于哪封邮件;null = 未打开
|
||||
const [forwarding, setForwarding] = useState<Mail | null>(null);
|
||||
// 正在看哪封邮件的对话树;null = 看正常的邮件视图
|
||||
@ -46,7 +61,11 @@ export default function MailView() {
|
||||
// 会话视图的对端是**会话的属性**,不能由「最后一封是谁发的」决定:
|
||||
// 人在这里打字就是「给这次任务的对方追加一句」,而最后一封很可能是自己刚发的,
|
||||
// 那时取对端会取成自己 —— 信就发给了自己(生产已发生)。
|
||||
const sessionTarget = sessionReplyTarget(currentSessionMails, currentSession, me);
|
||||
const sessionTarget = sessionReplyTarget(
|
||||
currentSessionMails,
|
||||
currentSession,
|
||||
me,
|
||||
);
|
||||
return (
|
||||
<div className="flex-1 min-w-0 flex flex-col bg-gray-50">
|
||||
<div className="px-4 md:px-6 py-3 border-b border-gray-200 bg-white">
|
||||
@ -55,7 +74,7 @@ export default function MailView() {
|
||||
<span className="text-sm font-semibold text-gray-900 font-mono">
|
||||
{currentSession.session_alias
|
||||
? `.${currentSession.session_alias}`
|
||||
: '(未命名会话)'}
|
||||
: "(未命名会话)"}
|
||||
</span>
|
||||
<StatusBadge status={currentSession.status} />
|
||||
<span className="text-xs text-gray-400">
|
||||
@ -65,12 +84,18 @@ export default function MailView() {
|
||||
<PermissionEditor />
|
||||
<BudgetEditor />
|
||||
</div>
|
||||
<p className="text-xs text-gray-500 mt-0.5">{currentSession.subject}</p>
|
||||
<p className="text-xs text-gray-500 mt-0.5">
|
||||
{currentSession.subject}
|
||||
</p>
|
||||
</div>
|
||||
<RenameProposalBar />
|
||||
<div className="flex-1 overflow-y-auto px-4 md:px-6 py-4 space-y-3">
|
||||
{currentSessionMails.map(m => (
|
||||
<ThreadCard key={m.mail_id} mail={m} onForward={() => setForwarding(m)} />
|
||||
{currentSessionMails.map((m) => (
|
||||
<ThreadCard
|
||||
key={m.mail_id}
|
||||
mail={m}
|
||||
onForward={() => setForwarding(m)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
{/* 会话视图原先只有回复,转发入口只存在于单封邮件视图 ——
|
||||
@ -89,7 +114,9 @@ export default function MailView() {
|
||||
<div className="flex-1 min-w-0 flex items-center justify-center bg-gray-50 text-gray-400">
|
||||
<div className="text-center">
|
||||
<MailIcon className="w-10 h-10 mx-auto text-gray-300" />
|
||||
<p className="text-sm mt-3 text-gray-500">选择一封邮件查看,或点击左侧「新建」写邮件</p>
|
||||
<p className="text-sm mt-3 text-gray-500">
|
||||
选择一封邮件查看,或点击左侧「新建」写邮件
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
@ -112,7 +139,7 @@ export default function MailView() {
|
||||
<Markdown remarkPlugins={[remarkGfm]}>{currentMail.body}</Markdown>
|
||||
</div>
|
||||
<AttachmentList items={currentMail.attachments ?? []} />
|
||||
{currentMail.mail_type === 'permission_request' && (
|
||||
{currentMail.mail_type === "permission_request" && (
|
||||
<PermissionPanel mail={currentMail} />
|
||||
)}
|
||||
</div>
|
||||
@ -133,15 +160,15 @@ export default function MailView() {
|
||||
* 三档:plan(只读)/ workspace(目录内,越界问人)/ full(全权)。
|
||||
*/
|
||||
function PermissionEditor() {
|
||||
const session = useSessionStore(s => s.currentSession);
|
||||
const setPermissionMode = useSessionStore(s => s.setPermissionMode);
|
||||
const session = useSessionStore((s) => s.currentSession);
|
||||
const setPermissionMode = useSessionStore((s) => s.setPermissionMode);
|
||||
const [editing, setEditing] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
if (!session) return null;
|
||||
|
||||
const mode = session.permission_mode || 'workspace';
|
||||
const enforcement = session.permission_enforcement || 'advisory';
|
||||
const mode = session.permission_mode || "workspace";
|
||||
const enforcement = session.permission_enforcement || "advisory";
|
||||
|
||||
if (!editing) {
|
||||
return (
|
||||
@ -156,14 +183,14 @@ function PermissionEditor() {
|
||||
}
|
||||
|
||||
const modes = [
|
||||
{ value: 'plan', label: '只读', desc: '不许写/改/执行' },
|
||||
{ value: 'workspace', label: '目录内', desc: '越界问人' },
|
||||
{ value: 'full', label: '全权', desc: '自动放行' },
|
||||
{ value: "plan", label: "只读", desc: "不许写/改/执行" },
|
||||
{ value: "workspace", label: "目录内", desc: "越界问人" },
|
||||
{ value: "full", label: "全权", desc: "自动放行" },
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-1">
|
||||
{modes.map(o => (
|
||||
{modes.map((o) => (
|
||||
<button
|
||||
key={o.value}
|
||||
type="button"
|
||||
@ -177,14 +204,17 @@ function PermissionEditor() {
|
||||
title={o.desc}
|
||||
className={`px-1.5 py-0.5 rounded text-[10px] font-medium border transition-colors disabled:opacity-40 ${
|
||||
mode === o.value
|
||||
? 'border-blue-500 bg-blue-50 text-blue-700'
|
||||
: 'border-gray-200 text-gray-500 hover:bg-gray-50'
|
||||
? "border-blue-500 bg-blue-50 text-blue-700"
|
||||
: "border-gray-200 text-gray-500 hover:bg-gray-50"
|
||||
}`}
|
||||
>
|
||||
{o.label}
|
||||
</button>
|
||||
))}
|
||||
<button onClick={() => setEditing(false)} className="text-[10px] text-gray-400 hover:text-gray-700 ml-0.5">
|
||||
<button
|
||||
onClick={() => setEditing(false)}
|
||||
className="text-[10px] text-gray-400 hover:text-gray-700 ml-0.5"
|
||||
>
|
||||
×
|
||||
</button>
|
||||
</div>
|
||||
@ -199,10 +229,10 @@ function PermissionEditor() {
|
||||
* 而不是「这件事值得多少个来回」。
|
||||
*/
|
||||
function BudgetEditor() {
|
||||
const budget = useSessionStore(s => s.budget);
|
||||
const setBudget = useSessionStore(s => s.setBudget);
|
||||
const budget = useSessionStore((s) => s.budget);
|
||||
const setBudget = useSessionStore((s) => s.setBudget);
|
||||
const [editing, setEditing] = useState(false);
|
||||
const [draft, setDraft] = useState('');
|
||||
const [draft, setDraft] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
if (!budget) return null;
|
||||
@ -210,7 +240,7 @@ function BudgetEditor() {
|
||||
const exhausted = !budget.unlimited && budget.remaining === 0;
|
||||
|
||||
const open = () => {
|
||||
setDraft(budget.unlimited ? '' : String(budget.max_rounds));
|
||||
setDraft(budget.unlimited ? "" : String(budget.max_rounds));
|
||||
setEditing(true);
|
||||
};
|
||||
|
||||
@ -228,36 +258,38 @@ function BudgetEditor() {
|
||||
title="本任务的往返预算:Agent 主动发信的次数上限(自动转发的总结与权限询问不占用)"
|
||||
className={`inline-flex items-center gap-1 text-[11px] px-2 py-0.5 rounded border transition-colors ${
|
||||
exhausted
|
||||
? 'border-red-200 bg-red-50 text-red-700'
|
||||
: 'border-gray-200 text-gray-500 hover:border-blue-300 hover:text-blue-600'
|
||||
? "border-red-200 bg-red-50 text-red-700"
|
||||
: "border-gray-200 text-gray-500 hover:border-blue-300 hover:text-blue-600"
|
||||
}`}
|
||||
>
|
||||
<GaugeIcon className="w-3 h-3" />
|
||||
{budget.unlimited
|
||||
? '预算不限'
|
||||
: `${budget.used_rounds}/${budget.max_rounds} 来回${exhausted ? ' · 已用尽' : ''}`}
|
||||
? "预算不限"
|
||||
: `${budget.used_rounds}/${budget.max_rounds} 来回${exhausted ? " · 已用尽" : ""}`}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
const invalid = draft.trim() !== '' && !/^\d+$/.test(draft.trim());
|
||||
const invalid = draft.trim() !== "" && !/^\d+$/.test(draft.trim());
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-1.5">
|
||||
<span className="text-[11px] text-gray-500">往返预算</span>
|
||||
<input
|
||||
value={draft}
|
||||
onChange={e => setDraft(e.target.value)}
|
||||
onChange={(e) => setDraft(e.target.value)}
|
||||
inputMode="numeric"
|
||||
placeholder="不限"
|
||||
autoFocus
|
||||
className={`w-16 text-xs border rounded px-1.5 py-1 focus:outline-none focus:ring-2 focus:ring-blue-100 ${
|
||||
invalid ? 'border-red-300' : 'border-gray-300'
|
||||
invalid ? "border-red-300" : "border-gray-300"
|
||||
}`}
|
||||
/>
|
||||
<button
|
||||
disabled={busy || invalid}
|
||||
onClick={() => commit({ max_rounds: draft.trim() === '' ? 0 : Number(draft.trim()) })}
|
||||
onClick={() =>
|
||||
commit({ max_rounds: draft.trim() === "" ? 0 : Number(draft.trim()) })
|
||||
}
|
||||
className="text-[11px] px-2 py-1 rounded bg-blue-600 text-white hover:bg-blue-700 disabled:opacity-40"
|
||||
>
|
||||
保存
|
||||
@ -288,15 +320,17 @@ function BudgetEditor() {
|
||||
* 提议 + 人确认,既让 Agent 表达意图,又保证寻址稳定性由人掌握。
|
||||
*/
|
||||
function RenameProposalBar() {
|
||||
const proposal = useSessionStore(s => s.renameProposal);
|
||||
const current = useSessionStore(s => s.currentSession);
|
||||
const accept = useSessionStore(s => s.acceptRename);
|
||||
const dismiss = useSessionStore(s => s.dismissRename);
|
||||
const proposal = useSessionStore((s) => s.renameProposal);
|
||||
const current = useSessionStore((s) => s.currentSession);
|
||||
const accept = useSessionStore((s) => s.acceptRename);
|
||||
const dismiss = useSessionStore((s) => s.dismissRename);
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
if (!proposal) return null;
|
||||
|
||||
const from = current?.session_alias ? `.${current.session_alias}` : '(未命名)';
|
||||
const from = current?.session_alias
|
||||
? `.${current.session_alias}`
|
||||
: "(未命名)";
|
||||
|
||||
return (
|
||||
<div className="px-4 md:px-6 py-2.5 bg-blue-50 border-b border-blue-100">
|
||||
@ -304,11 +338,14 @@ function RenameProposalBar() {
|
||||
<TagIcon className="w-3.5 h-3.5 text-blue-500 mt-0.5 shrink-0" />
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-xs text-blue-900">
|
||||
Agent 建议把会话别名从 <span className="font-mono">{from}</span> 改为{' '}
|
||||
Agent 建议把会话别名从 <span className="font-mono">{from}</span>{" "}
|
||||
改为{" "}
|
||||
<span className="font-mono font-semibold">.{proposal.alias}</span>
|
||||
</p>
|
||||
{proposal.reason && (
|
||||
<p className="text-[11px] text-blue-700 mt-0.5">{proposal.reason}</p>
|
||||
<p className="text-[11px] text-blue-700 mt-0.5">
|
||||
{proposal.reason}
|
||||
</p>
|
||||
)}
|
||||
<p className="text-[10px] text-blue-500 mt-0.5">
|
||||
改名后需用 name@path.{proposal.alias} 寻址;旧别名立即失效。
|
||||
@ -324,7 +361,7 @@ function RenameProposalBar() {
|
||||
}}
|
||||
className="px-2.5 py-1 rounded bg-blue-600 text-white text-xs hover:bg-blue-600 disabled:opacity-50 shrink-0"
|
||||
>
|
||||
{busy ? '改名中' : '接受'}
|
||||
{busy ? "改名中" : "接受"}
|
||||
</button>
|
||||
<button
|
||||
onClick={dismiss}
|
||||
@ -342,16 +379,16 @@ function RenameProposalBar() {
|
||||
* 收件人用与写信页一致的三段式补全,正文引用由服务端生成(保证格式统一)。
|
||||
*/
|
||||
function ForwardBar({ mail, onClose }: { mail: Mail; onClose: () => void }) {
|
||||
const [to, setTo] = useState('');
|
||||
const [cc, setCc] = useState('');
|
||||
const [to, setTo] = useState("");
|
||||
const [cc, setCc] = useState("");
|
||||
const [ccOpen, setCcOpen] = useState(false);
|
||||
const [comment, setComment] = useState('');
|
||||
const [comment, setComment] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const fetchInbox = useMailStore(s => s.fetchInbox);
|
||||
const fetchSent = useMailStore(s => s.fetchSent);
|
||||
const fetchSessions = useSessionStore(s => s.fetchSessions);
|
||||
const fetchContacts = useContactStore(s => s.fetchContacts);
|
||||
const fetchInbox = useMailStore((s) => s.fetchInbox);
|
||||
const fetchSent = useMailStore((s) => s.fetchSent);
|
||||
const fetchSessions = useSessionStore((s) => s.fetchSessions);
|
||||
const fetchContacts = useContactStore((s) => s.fetchContacts);
|
||||
|
||||
const submit = async () => {
|
||||
if (!to.trim() || busy) return;
|
||||
@ -361,9 +398,14 @@ function ForwardBar({ mail, onClose }: { mail: Mail; onClose: () => void }) {
|
||||
await api.forwardMail(mail.mail_id, {
|
||||
to: to.trim(),
|
||||
cc: cc.trim(),
|
||||
comment: comment.trim()
|
||||
comment: comment.trim(),
|
||||
});
|
||||
await Promise.all([fetchInbox('all'), fetchSent(), fetchSessions(), fetchContacts()]);
|
||||
await Promise.all([
|
||||
fetchInbox("all"),
|
||||
fetchSent(),
|
||||
fetchSessions(),
|
||||
fetchContacts(),
|
||||
]);
|
||||
onClose();
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : String(err));
|
||||
@ -381,14 +423,18 @@ function ForwardBar({ mail, onClose }: { mail: Mail; onClose: () => void }) {
|
||||
</span>
|
||||
<div className="flex-1" />
|
||||
<button
|
||||
onClick={() => setCcOpen(o => !o)}
|
||||
className={`tap text-[10px] ${ccOpen ? 'text-blue-600' : 'text-gray-500 hover:text-blue-600'}`}
|
||||
onClick={() => setCcOpen((o) => !o)}
|
||||
className={`tap text-[10px] ${ccOpen ? "text-blue-600" : "text-gray-500 hover:text-blue-600"}`}
|
||||
>
|
||||
{ccOpen ? '收起抄送' : '抄送'}
|
||||
{ccOpen ? "收起抄送" : "抄送"}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<AddressInput value={to} onChange={setTo} placeholder="新收件人:pi@root.new" />
|
||||
<AddressInput
|
||||
value={to}
|
||||
onChange={setTo}
|
||||
placeholder="新收件人:pi@root.new"
|
||||
/>
|
||||
|
||||
{ccOpen && (
|
||||
<AddressInput
|
||||
@ -401,15 +447,22 @@ function ForwardBar({ mail, onClose }: { mail: Mail; onClose: () => void }) {
|
||||
|
||||
<textarea
|
||||
value={comment}
|
||||
onChange={e => setComment(e.target.value)}
|
||||
onChange={(e) => setComment(e.target.value)}
|
||||
placeholder="转发说明(可选,置于引用原文之前;原文将以引用块附在下方)"
|
||||
className="w-full h-16 text-sm border border-gray-300 rounded-md p-2.5 resize-none focus:outline-none focus:ring-2 focus:ring-blue-100 focus:border-blue-400"
|
||||
/>
|
||||
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
{error && <span className="text-xs text-red-600 min-w-0 break-words">{error}</span>}
|
||||
{error && (
|
||||
<span className="text-xs text-red-600 min-w-0 break-words">
|
||||
{error}
|
||||
</span>
|
||||
)}
|
||||
<div className="flex-1" />
|
||||
<button onClick={onClose} className="tap px-3 py-1.5 text-xs text-gray-500 hover:text-gray-800">
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="tap px-3 py-1.5 text-xs text-gray-500 hover:text-gray-800"
|
||||
>
|
||||
取消
|
||||
</button>
|
||||
<button
|
||||
@ -417,7 +470,7 @@ function ForwardBar({ mail, onClose }: { mail: Mail; onClose: () => void }) {
|
||||
disabled={busy || !to.trim()}
|
||||
className="tap px-4 py-1.5 text-xs font-medium rounded-md bg-blue-600 text-white hover:bg-blue-700 disabled:opacity-40 disabled:cursor-not-allowed"
|
||||
>
|
||||
{busy ? '转发中' : '转发'}
|
||||
{busy ? "转发中" : "转发"}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
@ -428,14 +481,14 @@ function Header({
|
||||
mail,
|
||||
onRead,
|
||||
onForward,
|
||||
onThread
|
||||
onThread,
|
||||
}: {
|
||||
mail: Mail;
|
||||
onRead: () => void;
|
||||
onForward: () => void;
|
||||
onThread: () => void;
|
||||
}) {
|
||||
const time = new Date(mail.created_at).toLocaleString('zh-CN');
|
||||
const time = new Date(mail.created_at).toLocaleString("zh-CN");
|
||||
|
||||
// 发件/收件行显示**各方在这条会话里的完整地址**,人与 Agent 带的段数不同:
|
||||
//
|
||||
@ -448,39 +501,44 @@ function Header({
|
||||
//
|
||||
// workspace 取 `session_workspace` 而不是 from/to_workspace:后者对 Agent
|
||||
// 存的是 Agent 名而非路径(历史遗留),拿它拼会得到 `dsh@dsh`。
|
||||
const ws = mail.session_workspace || '';
|
||||
const ws = mail.session_workspace || "";
|
||||
const from = participantAddress(
|
||||
mail.from_name,
|
||||
mail.from_human,
|
||||
mail.from_human ? '' : ws,
|
||||
mail.session_alias
|
||||
mail.from_human ? "" : ws,
|
||||
mail.session_alias,
|
||||
);
|
||||
const to = participantAddress(
|
||||
mail.to_name,
|
||||
mail.to_human,
|
||||
mail.to_human ? '' : ws,
|
||||
mail.session_alias
|
||||
mail.to_human ? "" : ws,
|
||||
mail.session_alias,
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="px-4 md:px-6 py-3 md:py-4 border-b border-gray-200">
|
||||
<div className="flex items-center gap-2 mb-1.5 flex-wrap">
|
||||
<BackButton />
|
||||
<h2 className="text-sm font-semibold text-gray-900 min-w-0 break-words">{mail.subject}</h2>
|
||||
{mail.status === 'unread' && (
|
||||
<h2 className="text-sm font-semibold text-gray-900 min-w-0 break-words">
|
||||
{mail.subject}
|
||||
</h2>
|
||||
{mail.status === "unread" && (
|
||||
<span className="px-1.5 py-0.5 rounded bg-blue-100 text-blue-700 text-[10px] font-medium">
|
||||
未读
|
||||
</span>
|
||||
)}
|
||||
{mail.mail_type === 'permission_request' && (
|
||||
{mail.mail_type === "permission_request" && (
|
||||
<span className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded bg-orange-100 text-orange-700 text-[10px] font-medium">
|
||||
<ShieldIcon className="w-3 h-3" />
|
||||
权限请求
|
||||
</span>
|
||||
)}
|
||||
<div className="flex-1" />
|
||||
{mail.status === 'unread' && (
|
||||
<button onClick={onRead} className="tap text-xs text-blue-500 hover:underline">
|
||||
{mail.status === "unread" && (
|
||||
<button
|
||||
onClick={onRead}
|
||||
className="tap text-xs text-blue-500 hover:underline"
|
||||
>
|
||||
标记已读
|
||||
</button>
|
||||
)}
|
||||
@ -506,7 +564,9 @@ function Header({
|
||||
<Row label="收件">{to}</Row>
|
||||
{mail.cc_list?.length > 0 && (
|
||||
<Row label="抄送">
|
||||
{mail.cc_list.map(a => a.raw || `${a.name}@${a.path || ''}`).join('、')}
|
||||
{mail.cc_list
|
||||
.map((a) => a.raw || `${a.name}@${a.path || ""}`)
|
||||
.join("、")}
|
||||
</Row>
|
||||
)}
|
||||
<Row label="时间">{time}</Row>
|
||||
@ -515,7 +575,13 @@ function Header({
|
||||
);
|
||||
}
|
||||
|
||||
function Row({ label, children }: { label: string; children: React.ReactNode }) {
|
||||
function Row({
|
||||
label,
|
||||
children,
|
||||
}: {
|
||||
label: string;
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<div className="flex gap-2">
|
||||
<dt className="w-8 shrink-0 text-gray-400">{label}</dt>
|
||||
@ -525,22 +591,28 @@ function Row({ label, children }: { label: string; children: React.ReactNode })
|
||||
);
|
||||
}
|
||||
|
||||
function ThreadCard({ mail, onForward }: { mail: Mail; onForward?: () => void }) {
|
||||
function ThreadCard({
|
||||
mail,
|
||||
onForward,
|
||||
}: {
|
||||
mail: Mail;
|
||||
onForward?: () => void;
|
||||
}) {
|
||||
// 「这封是我发的吗」而不是「发件人叫 human 吗」:多用户下登录名可能是
|
||||
// jianf,写死 'human' 会让自己发的信显示成机器人图标。
|
||||
const me = useAuthStore(s => s.user?.username || '');
|
||||
const me = useAuthStore((s) => s.user?.username || "");
|
||||
const isMine = !!me && mail.from_name === me;
|
||||
const isPermission = mail.mail_type === 'permission_request';
|
||||
const time = new Date(mail.created_at).toLocaleString('zh-CN');
|
||||
const isPermission = mail.mail_type === "permission_request";
|
||||
const time = new Date(mail.created_at).toLocaleString("zh-CN");
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`rounded-lg border p-4 ${
|
||||
isPermission
|
||||
? 'border-orange-200 bg-orange-50'
|
||||
? "border-orange-200 bg-orange-50"
|
||||
: isMine
|
||||
? 'border-blue-200 bg-blue-50/60'
|
||||
: 'border-gray-200 bg-white'
|
||||
? "border-blue-200 bg-blue-50/60"
|
||||
: "border-gray-200 bg-white"
|
||||
}`}
|
||||
>
|
||||
<div className="flex items-center gap-1.5 mb-2 text-xs">
|
||||
@ -551,7 +623,9 @@ function ThreadCard({ mail, onForward }: { mail: Mail; onForward?: () => void })
|
||||
)}
|
||||
{/* 显示真实发件人名而不是 'human':会话里可能有多个人类参与方,
|
||||
都渲染成 human 就分不清谁说的话 */}
|
||||
<span className="font-semibold text-gray-800 font-mono">{mail.from_name}</span>
|
||||
<span className="font-semibold text-gray-800 font-mono">
|
||||
{mail.from_name}
|
||||
</span>
|
||||
{isPermission && (
|
||||
<span className="px-1 py-0.5 rounded bg-orange-200 text-orange-800 text-[9px] font-medium">
|
||||
权限请求
|
||||
@ -560,7 +634,9 @@ function ThreadCard({ mail, onForward }: { mail: Mail; onForward?: () => void })
|
||||
{mail.cc_list?.length > 0 && (
|
||||
<span
|
||||
className="text-[10px] text-gray-400"
|
||||
title={mail.cc_list.map(c => c.raw || `${c.name}@${c.path || ''}`).join(', ')}
|
||||
title={mail.cc_list
|
||||
.map((c) => c.raw || `${c.name}@${c.path || ""}`)
|
||||
.join(", ")}
|
||||
>
|
||||
抄送 {mail.cc_list.length}
|
||||
</span>
|
||||
@ -601,21 +677,21 @@ function ThreadCard({ mail, onForward }: { mail: Mail; onForward?: () => void })
|
||||
* 那些铺垫与这个组件本身的行为无关。
|
||||
*/
|
||||
export function PermissionPanel({ mail }: { mail: Mail }) {
|
||||
const isQuestion = mail.permission_kind === 'question';
|
||||
const [note, setNote] = useState('');
|
||||
const isQuestion = mail.permission_kind === "question";
|
||||
const [note, setNote] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [decided, setDecided] = useState(mail.permission_result || '');
|
||||
const [decided, setDecided] = useState(mail.permission_result || "");
|
||||
// 问题模式下已勾选的选项(多选时是多个)。
|
||||
const [picked, setPicked] = useState<string[]>([]);
|
||||
const fetchInbox = useMailStore(s => s.fetchInbox);
|
||||
const selectSession = useSessionStore(s => s.selectSession);
|
||||
const fetchInbox = useMailStore((s) => s.fetchInbox);
|
||||
const selectSession = useSessionStore((s) => s.selectSession);
|
||||
|
||||
const submit = async (decision: string, noteText: string) => {
|
||||
setBusy(true);
|
||||
try {
|
||||
await api.decidePermission(mail.mail_id, decision, noteText || undefined);
|
||||
setDecided(decision || '(自由文本回答)');
|
||||
await fetchInbox('all');
|
||||
setDecided(decision || "(自由文本回答)");
|
||||
await fetchInbox("all");
|
||||
if (mail.session_id) selectSession(mail.session_id);
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
@ -638,8 +714,11 @@ export function PermissionPanel({ mail }: { mail: Mail }) {
|
||||
const options = mail.permission_options ?? [];
|
||||
const multi = mail.permission_multi_select === true;
|
||||
const toggle = (opt: string) => {
|
||||
setPicked(prev => {
|
||||
if (multi) return prev.includes(opt) ? prev.filter(p => p !== opt) : [...prev, opt];
|
||||
setPicked((prev) => {
|
||||
if (multi)
|
||||
return prev.includes(opt)
|
||||
? prev.filter((p) => p !== opt)
|
||||
: [...prev, opt];
|
||||
// 单选:再点同一项则取消,否则替换
|
||||
return prev.includes(opt) ? [] : [opt];
|
||||
});
|
||||
@ -651,13 +730,15 @@ export function PermissionPanel({ mail }: { mail: Mail }) {
|
||||
<div className="mt-3 pt-3 border-t border-orange-200">
|
||||
<div className="text-[11px] text-gray-500 mb-2">
|
||||
{options.length === 0
|
||||
? '这题没有预设选项,请直接填写回答:'
|
||||
: multi ? '可多选,也可补充说明:' : '请选择一项,也可补充说明:'}
|
||||
? "这题没有预设选项,请直接填写回答:"
|
||||
: multi
|
||||
? "可多选,也可补充说明:"
|
||||
: "请选择一项,也可补充说明:"}
|
||||
</div>
|
||||
|
||||
{options.length > 0 && (
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{options.map(opt => {
|
||||
{options.map((opt) => {
|
||||
const on = picked.includes(opt);
|
||||
return (
|
||||
<button
|
||||
@ -667,8 +748,8 @@ export function PermissionPanel({ mail }: { mail: Mail }) {
|
||||
aria-pressed={on}
|
||||
className={`inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium rounded-md border transition-colors disabled:opacity-40 ${
|
||||
on
|
||||
? 'bg-blue-700 text-white border-blue-700 hover:bg-blue-800'
|
||||
: 'bg-white text-gray-700 border-gray-300 hover:bg-gray-50'
|
||||
? "bg-blue-700 text-white border-blue-700 hover:bg-blue-800"
|
||||
: "bg-white text-gray-700 border-gray-300 hover:bg-gray-50"
|
||||
}`}
|
||||
>
|
||||
{on && <CheckIcon className="w-3.5 h-3.5" />}
|
||||
@ -681,22 +762,26 @@ export function PermissionPanel({ mail }: { mail: Mail }) {
|
||||
|
||||
<textarea
|
||||
value={note}
|
||||
onChange={e => setNote(e.target.value)}
|
||||
onChange={(e) => setNote(e.target.value)}
|
||||
rows={options.length === 0 ? 3 : 2}
|
||||
placeholder={options.length === 0 ? '你的回答(必填)' : '补充说明(可选)'}
|
||||
placeholder={
|
||||
options.length === 0 ? "你的回答(必填)" : "补充说明(可选)"
|
||||
}
|
||||
className="mt-2 w-full text-xs border border-gray-300 rounded-md px-2.5 py-1.5 resize-y focus:outline-none focus:ring-2 focus:ring-blue-100 focus:border-blue-400"
|
||||
/>
|
||||
|
||||
<div className="mt-2 flex items-center gap-2">
|
||||
<button
|
||||
onClick={() => submit(picked.join('\n'), note.trim())}
|
||||
onClick={() => submit(picked.join("\n"), note.trim())}
|
||||
disabled={busy || blank}
|
||||
className="inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium rounded-md bg-blue-700 text-white hover:bg-blue-800 disabled:opacity-40"
|
||||
>
|
||||
提交回答
|
||||
</button>
|
||||
{blank && (
|
||||
<span className="text-[11px] text-gray-400">请先选择或填写回答</span>
|
||||
<span className="text-[11px] text-gray-400">
|
||||
请先选择或填写回答
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
@ -704,21 +789,23 @@ export function PermissionPanel({ mail }: { mail: Mail }) {
|
||||
}
|
||||
|
||||
// ─── 审批型:批准 / 拒绝 ───
|
||||
const options = mail.permission_options?.length ? mail.permission_options : ['同意', '拒绝'];
|
||||
const options = mail.permission_options?.length
|
||||
? mail.permission_options
|
||||
: ["同意", "拒绝"];
|
||||
const isApprove = (s: string) => /同意|允许|批准|approve|yes/i.test(s);
|
||||
|
||||
return (
|
||||
<div className="mt-3 pt-3 border-t border-orange-200">
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{options.map(opt => (
|
||||
{options.map((opt) => (
|
||||
<button
|
||||
key={opt}
|
||||
onClick={() => submit(opt, note)}
|
||||
disabled={busy}
|
||||
className={`inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium rounded-md transition-colors disabled:opacity-40 ${
|
||||
isApprove(opt)
|
||||
? 'bg-green-700 text-white hover:bg-green-800'
|
||||
: 'bg-red-50 text-red-700 border border-red-200 hover:bg-red-100'
|
||||
? "bg-green-700 text-white hover:bg-green-800"
|
||||
: "bg-red-50 text-red-700 border border-red-200 hover:bg-red-100"
|
||||
}`}
|
||||
>
|
||||
{isApprove(opt) ? (
|
||||
@ -732,7 +819,7 @@ export function PermissionPanel({ mail }: { mail: Mail }) {
|
||||
</div>
|
||||
<input
|
||||
value={note}
|
||||
onChange={e => setNote(e.target.value)}
|
||||
onChange={(e) => setNote(e.target.value)}
|
||||
placeholder="备注(可选)"
|
||||
className="mt-2 w-full text-xs border border-gray-300 rounded-md px-2.5 py-1.5 focus:outline-none focus:ring-2 focus:ring-blue-100 focus:border-blue-400"
|
||||
/>
|
||||
@ -748,30 +835,30 @@ function ReplyBar({
|
||||
* 会话视图的语义是「跟这个 Agent 的一次任务」,对端是会话的属性;
|
||||
* 单封邮件视图没有这层语境,才回落到按那封邮件推断。
|
||||
*/
|
||||
overrideTarget
|
||||
overrideTarget,
|
||||
}: {
|
||||
replyTo?: Mail;
|
||||
overrideTarget?: string;
|
||||
}) {
|
||||
const [body, setBody] = useState('');
|
||||
const [cc, setCc] = useState('');
|
||||
const [body, setBody] = useState("");
|
||||
const [cc, setCc] = useState("");
|
||||
// 抄送默认收起:多数回复不需要它,常驻一行输入框只会挤掉正文空间。
|
||||
// 原邮件带抄送时自动展开并预填 —— 「回复全部」是人在这种场景下的默认预期
|
||||
const [ccOpen, setCcOpen] = useState(false);
|
||||
const [budgetEditing, setBudgetEditing] = useState(false);
|
||||
const [budgetBusy, setBudgetBusy] = useState(false);
|
||||
const [maxRoundsDraft, setMaxRoundsDraft] = useState('');
|
||||
const [maxRoundsDraft, setMaxRoundsDraft] = useState("");
|
||||
const [attachments, setAttachments] = useState<PendingAttachment[]>([]);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const fetchInbox = useMailStore(s => s.fetchInbox);
|
||||
const fetchSent = useMailStore(s => s.fetchSent);
|
||||
const fetchSessions = useSessionStore(s => s.fetchSessions);
|
||||
const fetchContacts = useContactStore(s => s.fetchContacts);
|
||||
const selectSession = useSessionStore(s => s.selectSession);
|
||||
const budget = useSessionStore(s => s.budget);
|
||||
const setBudget = useSessionStore(s => s.setBudget);
|
||||
const me = useAuthStore(s => s.user?.username || '');
|
||||
const fetchInbox = useMailStore((s) => s.fetchInbox);
|
||||
const fetchSent = useMailStore((s) => s.fetchSent);
|
||||
const fetchSessions = useSessionStore((s) => s.fetchSessions);
|
||||
const fetchContacts = useContactStore((s) => s.fetchContacts);
|
||||
const selectSession = useSessionStore((s) => s.selectSession);
|
||||
const budget = useSessionStore((s) => s.budget);
|
||||
const setBudget = useSessionStore((s) => s.setBudget);
|
||||
const me = useAuthStore((s) => s.user?.username || "");
|
||||
|
||||
if (!replyTo) return null;
|
||||
|
||||
@ -788,13 +875,18 @@ function ReplyBar({
|
||||
await api.sendMail(target, `Re: ${replyTo.subject}`, body, {
|
||||
reply_to: replyTo.mail_id,
|
||||
cc: cc.trim(),
|
||||
attachment_ids: attachments.map(a => a.id)
|
||||
attachment_ids: attachments.map((a) => a.id),
|
||||
});
|
||||
setBody('');
|
||||
setCc('');
|
||||
setBody("");
|
||||
setCc("");
|
||||
setCcOpen(false);
|
||||
setAttachments([]);
|
||||
await Promise.all([fetchInbox('all'), fetchSent(), fetchSessions(), fetchContacts()]);
|
||||
await Promise.all([
|
||||
fetchInbox("all"),
|
||||
fetchSent(),
|
||||
fetchSessions(),
|
||||
fetchContacts(),
|
||||
]);
|
||||
if (replyTo.session_id) selectSession(replyTo.session_id);
|
||||
} catch (err) {
|
||||
// 必须显示出来:预算耗尽、地址不存在、速率限制都会走到这里,
|
||||
@ -815,14 +907,16 @@ function ReplyBar({
|
||||
const replyAll = () => {
|
||||
// 去重与「去掉自己」都在 replyAllCC 里:原先用 !a.startsWith('human')
|
||||
// 去自己,同一个遗留判据 —— 去不掉 jianf,点「回复全部」会把自己抄送进去。
|
||||
setCc(replyAllCC(replyTo, me, peer.name).join(', '));
|
||||
setCc(replyAllCC(replyTo, me, peer.name).join(", "));
|
||||
setCcOpen(true);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="shrink-0 max-h-[min(65vh,calc(var(--app-height)-3rem))] overflow-y-auto overscroll-contain border-t border-gray-200 bg-white px-4 md:px-6 py-3">
|
||||
<div className="flex items-center gap-2 mb-1 flex-wrap">
|
||||
<p className="text-[10px] text-gray-400 font-mono min-w-0 truncate">回复 {target}</p>
|
||||
<p className="text-[10px] text-gray-400 font-mono min-w-0 truncate">
|
||||
回复 {target}
|
||||
</p>
|
||||
<div className="flex-1" />
|
||||
{(replyTo.cc_list?.length ?? 0) > 0 && (
|
||||
<button
|
||||
@ -833,10 +927,10 @@ function ReplyBar({
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
onClick={() => setCcOpen(o => !o)}
|
||||
className={`tap text-[10px] ${ccOpen ? 'text-blue-600' : 'text-gray-500 hover:text-blue-600'}`}
|
||||
onClick={() => setCcOpen((o) => !o)}
|
||||
className={`tap text-[10px] ${ccOpen ? "text-blue-600" : "text-gray-500 hover:text-blue-600"}`}
|
||||
>
|
||||
{ccOpen ? '收起抄送' : '抄送'}
|
||||
{ccOpen ? "收起抄送" : "抄送"}
|
||||
</button>
|
||||
</div>
|
||||
{ccOpen && (
|
||||
@ -851,35 +945,45 @@ function ReplyBar({
|
||||
)}
|
||||
<textarea
|
||||
value={body}
|
||||
onChange={e => setBody(e.target.value)}
|
||||
onChange={(e) => setBody(e.target.value)}
|
||||
placeholder="回复内容(Markdown)"
|
||||
className="w-full h-20 text-sm font-mono border border-gray-300 rounded-md p-3 resize-none focus:outline-none focus:ring-2 focus:ring-blue-100 focus:border-blue-400"
|
||||
/>
|
||||
<div className="mt-2">
|
||||
<AttachmentPicker items={attachments} onChange={setAttachments} disabled={busy} />
|
||||
<AttachmentPicker
|
||||
items={attachments}
|
||||
onChange={setAttachments}
|
||||
disabled={busy}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 mt-2 flex-wrap">
|
||||
{error && <span className="text-xs text-red-600 min-w-0 break-words">{error}</span>}
|
||||
{error && (
|
||||
<span className="text-xs text-red-600 min-w-0 break-words">
|
||||
{error}
|
||||
</span>
|
||||
)}
|
||||
<div className="flex-1" />
|
||||
{budget && !budgetEditing && (
|
||||
<button
|
||||
onClick={() => {
|
||||
setMaxRoundsDraft(budget.unlimited ? '' : String(budget.max_rounds));
|
||||
setMaxRoundsDraft(
|
||||
budget.unlimited ? "" : String(budget.max_rounds),
|
||||
);
|
||||
setBudgetEditing(true);
|
||||
}}
|
||||
title="本任务往返预算:Agent 主动发信上限(自动转发与权限询问不占)"
|
||||
className={`tap inline-flex items-center gap-1 text-[10px] px-2 py-1 rounded border ${
|
||||
budget.unlimited
|
||||
? 'border-gray-200 text-gray-500 hover:border-blue-300'
|
||||
? "border-gray-200 text-gray-500 hover:border-blue-300"
|
||||
: budget.remaining === 0
|
||||
? 'border-red-200 text-red-600'
|
||||
: 'border-gray-200 text-gray-500 hover:border-blue-300'
|
||||
? "border-red-200 text-red-600"
|
||||
: "border-gray-200 text-gray-500 hover:border-blue-300"
|
||||
}`}
|
||||
>
|
||||
<GaugeIcon className="w-3 h-3" />
|
||||
{budget.unlimited
|
||||
? '预算不限'
|
||||
: `${budget.used_rounds}/${budget.max_rounds} 来回${budget.remaining === 0 ? ' · 已用尽' : ''}`}
|
||||
? "预算不限"
|
||||
: `${budget.used_rounds}/${budget.max_rounds} 来回${budget.remaining === 0 ? " · 已用尽" : ""}`}
|
||||
</button>
|
||||
)}
|
||||
{budget && budgetEditing && (
|
||||
@ -887,17 +991,26 @@ function ReplyBar({
|
||||
<span className="text-[10px] text-gray-500">预算</span>
|
||||
<input
|
||||
value={maxRoundsDraft}
|
||||
onChange={e => setMaxRoundsDraft(e.target.value)}
|
||||
onChange={(e) => setMaxRoundsDraft(e.target.value)}
|
||||
inputMode="numeric"
|
||||
placeholder="不限"
|
||||
autoFocus
|
||||
className="w-14 text-xs border border-gray-300 rounded px-1.5 py-0.5 focus:outline-none focus:ring-2 focus:ring-blue-100"
|
||||
/>
|
||||
<button
|
||||
disabled={budgetBusy || (maxRoundsDraft.trim() !== '' && !/^\d+$/.test(maxRoundsDraft.trim()))}
|
||||
disabled={
|
||||
budgetBusy ||
|
||||
(maxRoundsDraft.trim() !== "" &&
|
||||
!/^\d+$/.test(maxRoundsDraft.trim()))
|
||||
}
|
||||
onClick={async () => {
|
||||
setBudgetBusy(true);
|
||||
await setBudget({ max_rounds: maxRoundsDraft.trim() === '' ? 0 : Number(maxRoundsDraft.trim()) });
|
||||
await setBudget({
|
||||
max_rounds:
|
||||
maxRoundsDraft.trim() === ""
|
||||
? 0
|
||||
: Number(maxRoundsDraft.trim()),
|
||||
});
|
||||
setBudgetBusy(false);
|
||||
setBudgetEditing(false);
|
||||
}}
|
||||
@ -915,7 +1028,7 @@ function ReplyBar({
|
||||
)}
|
||||
<button
|
||||
onClick={() => {
|
||||
setBody('');
|
||||
setBody("");
|
||||
setError(null);
|
||||
}}
|
||||
className="tap px-3 py-1.5 text-xs text-gray-500 hover:text-gray-800"
|
||||
@ -927,7 +1040,7 @@ function ReplyBar({
|
||||
disabled={busy || !body.trim()}
|
||||
className="tap px-4 py-1.5 text-xs font-medium rounded-md bg-blue-600 text-white hover:bg-blue-700 disabled:opacity-40 disabled:cursor-not-allowed"
|
||||
>
|
||||
{busy ? '发送中' : '发送'}
|
||||
{busy ? "发送中" : "发送"}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
@ -936,11 +1049,15 @@ function ReplyBar({
|
||||
|
||||
function StatusBadge({ status }: { status: string }) {
|
||||
const map: Record<string, { label: string; cls: string }> = {
|
||||
active: { label: '进行中', cls: 'bg-yellow-100 text-yellow-700' },
|
||||
waiting: { label: '等待中', cls: 'bg-blue-100 text-blue-700' },
|
||||
completed: { label: '已完成', cls: 'bg-green-100 text-green-700' },
|
||||
archived: { label: '已归档', cls: 'bg-gray-200 text-gray-600' }
|
||||
active: { label: "进行中", cls: "bg-yellow-100 text-yellow-700" },
|
||||
waiting: { label: "等待中", cls: "bg-blue-100 text-blue-700" },
|
||||
completed: { label: "已完成", cls: "bg-green-100 text-green-700" },
|
||||
archived: { label: "已归档", cls: "bg-gray-200 text-gray-600" },
|
||||
};
|
||||
const b = map[status] || map.active;
|
||||
return <span className={`text-[10px] px-1.5 py-0.5 rounded-full ${b.cls}`}>{b.label}</span>;
|
||||
return (
|
||||
<span className={`text-[10px] px-1.5 py-0.5 rounded-full ${b.cls}`}>
|
||||
{b.label}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
@ -2,8 +2,8 @@ export interface User {
|
||||
user_id: string;
|
||||
username: string;
|
||||
display_name: string;
|
||||
role: 'admin' | 'user';
|
||||
status: 'active' | 'disabled';
|
||||
role: "admin" | "user";
|
||||
status: "active" | "disabled";
|
||||
allowed_agents: string[];
|
||||
allowed_paths: string[];
|
||||
last_login?: string;
|
||||
@ -46,7 +46,7 @@ export interface Session {
|
||||
* platform = Agent 平台自动同步来的,后续同步可以覆盖
|
||||
* manual = 人显式指定(手工改名或接受了 Agent 的提议),平台同步不得覆盖
|
||||
*/
|
||||
alias_source?: 'platform' | 'manual';
|
||||
alias_source?: "platform" | "manual";
|
||||
/** 用户驳回过的改名提议 */
|
||||
rename_dismissed?: string;
|
||||
/**
|
||||
@ -97,7 +97,7 @@ export interface Mail {
|
||||
cc_list: Address[];
|
||||
subject: string;
|
||||
body: string;
|
||||
mail_type: 'normal' | 'permission_request';
|
||||
mail_type: "normal" | "permission_request";
|
||||
permission_options: string[] | null;
|
||||
permission_result: string | null;
|
||||
/**
|
||||
@ -110,7 +110,7 @@ export interface Mail {
|
||||
permission_kind?: string;
|
||||
/** 仅 question 使用:是否允许多选(对应 DSH 的 multi_select)。 */
|
||||
permission_multi_select?: boolean;
|
||||
status: 'unread' | 'read' | 'archived';
|
||||
status: "unread" | "read" | "archived";
|
||||
created_at: string;
|
||||
hop_limit?: number;
|
||||
session_alias?: string;
|
||||
@ -145,7 +145,7 @@ export interface Mail {
|
||||
* depth 是**相对锚点**的层级:0 = 锚点,负数 = 祖先,正数 = 子孙。
|
||||
* 分块加载时根可能还没取到,所以不用「距根深度」。
|
||||
*/
|
||||
export interface ThreadNode extends Omit<Mail, 'body'> {
|
||||
export interface ThreadNode extends Omit<Mail, "body"> {
|
||||
/** 距**线索根**的层级:0 = 根,1 = 它的直接回复 */
|
||||
depth: number;
|
||||
attachment_count: number;
|
||||
@ -241,7 +241,7 @@ export interface HumanSession {
|
||||
permission_enforcement?: string;
|
||||
}
|
||||
|
||||
export type SuggestKind = 'name' | 'path' | 'session';
|
||||
export type SuggestKind = "name" | "path" | "session";
|
||||
|
||||
/**
|
||||
* 会话候选项的来源。
|
||||
@ -249,7 +249,7 @@ export type SuggestKind = 'name' | 'path' | 'session';
|
||||
* platform 平台侧会话镜像(人直接在 opencode/DSH 界面上开的)
|
||||
* new 新建会话的哨兵项
|
||||
*/
|
||||
export type SessionCandidateSource = 'mail' | 'platform' | 'new';
|
||||
export type SessionCandidateSource = "mail" | "platform" | "new";
|
||||
|
||||
export interface SessionCandidate {
|
||||
/** 填进 session 位的值 */
|
||||
@ -331,7 +331,7 @@ export interface CalendarEvent {
|
||||
recurrence: Recurrence;
|
||||
/** 重复终止时间;越过它事件自动置为 cancelled */
|
||||
recurrence_end?: string;
|
||||
status: 'active' | 'paused' | 'cancelled';
|
||||
status: "active" | "paused" | "cancelled";
|
||||
/** 上次触发的墙上时钟 */
|
||||
last_fired_at?: string;
|
||||
/**
|
||||
@ -353,15 +353,15 @@ export interface CalendarEvent {
|
||||
* 也没有 lunar_weekly(农历没有「周」这个单位)。
|
||||
*/
|
||||
export type Recurrence =
|
||||
| 'none'
|
||||
| 'daily'
|
||||
| 'weekly'
|
||||
| 'monthly'
|
||||
| 'yearly'
|
||||
| 'lunar_monthly'
|
||||
| 'lunar_yearly';
|
||||
| "none"
|
||||
| "daily"
|
||||
| "weekly"
|
||||
| "monthly"
|
||||
| "yearly"
|
||||
| "lunar_monthly"
|
||||
| "lunar_yearly";
|
||||
|
||||
export type DeliveryMode = 'separate' | 'together';
|
||||
export type DeliveryMode = "separate" | "together";
|
||||
|
||||
/** 事件附件(随提醒邮件一起发出) */
|
||||
export interface CalendarAttachment {
|
||||
@ -386,5 +386,5 @@ export interface CalendarEventInput {
|
||||
remind_before?: number;
|
||||
recurrence?: Recurrence;
|
||||
recurrence_end?: string | null;
|
||||
status?: 'active' | 'paused' | 'cancelled';
|
||||
status?: "active" | "paused" | "cancelled";
|
||||
}
|
||||
|
||||
@ -1,13 +1,13 @@
|
||||
import { describe, expect, it, vi, beforeEach } from 'vitest';
|
||||
import { act, render, screen, waitFor } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import React from 'react';
|
||||
import { describe, expect, it, vi, beforeEach } from "vitest";
|
||||
import { act, render, screen, waitFor } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import React from "react";
|
||||
|
||||
import { PermissionPanel } from '../../src/components/MailView';
|
||||
import * as api from '../../src/api/client';
|
||||
import { useMailStore } from '../../src/stores/mailStore';
|
||||
import { useSessionStore } from '../../src/stores/sessionStore';
|
||||
import type { Mail } from '../../src/types';
|
||||
import { PermissionPanel } from "../../src/components/MailView";
|
||||
import * as api from "../../src/api/client";
|
||||
import { useMailStore } from "../../src/stores/mailStore";
|
||||
import { useSessionStore } from "../../src/stores/sessionStore";
|
||||
import type { Mail } from "../../src/types";
|
||||
|
||||
/**
|
||||
* 权限决策面板。
|
||||
@ -20,27 +20,27 @@ import type { Mail } from '../../src/types';
|
||||
|
||||
function permMail(over: Partial<Mail> = {}): Mail {
|
||||
return {
|
||||
mail_id: 'm-1',
|
||||
session_id: 's-1',
|
||||
mail_id: "m-1",
|
||||
session_id: "s-1",
|
||||
parent_mail_id: null,
|
||||
from_name: 'dsh',
|
||||
from_workspace: '/home/program/agentmail',
|
||||
to_name: 'admin',
|
||||
to_workspace: '',
|
||||
from_name: "dsh",
|
||||
from_workspace: "/home/program/agentmail",
|
||||
to_name: "admin",
|
||||
to_workspace: "",
|
||||
cc_list: [],
|
||||
subject: '请求批准:删除 build/',
|
||||
body: '将执行 rm -rf build/',
|
||||
mail_type: 'permission_request',
|
||||
subject: "请求批准:删除 build/",
|
||||
body: "将执行 rm -rf build/",
|
||||
mail_type: "permission_request",
|
||||
permission_options: undefined,
|
||||
permission_result: '',
|
||||
status: 'unread',
|
||||
created_at: '2026-09-03T00:00:00Z',
|
||||
permission_result: "",
|
||||
status: "unread",
|
||||
created_at: "2026-09-03T00:00:00Z",
|
||||
hop_limit: 5,
|
||||
...over
|
||||
...over,
|
||||
} as Mail;
|
||||
}
|
||||
|
||||
describe('PermissionPanel 决策', () => {
|
||||
describe("PermissionPanel 决策", () => {
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
// fetchInbox / selectSession 会打网络,替换成空实现
|
||||
@ -48,100 +48,119 @@ describe('PermissionPanel 决策', () => {
|
||||
useSessionStore.setState({ selectSession: vi.fn(async () => {}) } as any);
|
||||
});
|
||||
|
||||
it('没有 permission_options 时给默认的同意/拒绝两个选项', () => {
|
||||
it("没有 permission_options 时给默认的同意/拒绝两个选项", () => {
|
||||
render(React.createElement(PermissionPanel, { mail: permMail() }));
|
||||
|
||||
expect(screen.getByRole('button', { name: /同意/ })).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: /拒绝/ })).toBeInTheDocument();
|
||||
expect(screen.getByRole("button", { name: /同意/ })).toBeInTheDocument();
|
||||
expect(screen.getByRole("button", { name: /拒绝/ })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('有 permission_options 时用它,且顺序保持', () => {
|
||||
it("有 permission_options 时用它,且顺序保持", () => {
|
||||
render(
|
||||
React.createElement(PermissionPanel, {
|
||||
mail: permMail({ permission_options: ['只这一次', '总是允许', '拒绝'] })
|
||||
})
|
||||
mail: permMail({
|
||||
permission_options: ["只这一次", "总是允许", "拒绝"],
|
||||
}),
|
||||
}),
|
||||
);
|
||||
|
||||
const btns = screen.getAllByRole('button').map(b => b.textContent?.trim());
|
||||
const btns = screen
|
||||
.getAllByRole("button")
|
||||
.map((b) => b.textContent?.trim());
|
||||
// 顺序是 Agent 给的语义顺序,重排会让「拒绝」跑到人的手指默认位置上
|
||||
expect(btns).toEqual(['只这一次', '总是允许', '拒绝']);
|
||||
expect(btns).toEqual(["只这一次", "总是允许", "拒绝"]);
|
||||
});
|
||||
|
||||
it('点选项时把【选项原文】发给服务端', async () => {
|
||||
const spy = vi.spyOn(api, 'decidePermission').mockResolvedValue({ status: 'decided' } as any);
|
||||
it("点选项时把【选项原文】发给服务端", async () => {
|
||||
const spy = vi
|
||||
.spyOn(api, "decidePermission")
|
||||
.mockResolvedValue({ status: "decided" } as any);
|
||||
render(
|
||||
React.createElement(PermissionPanel, {
|
||||
mail: permMail({ permission_options: ['只这一次', '拒绝'] })
|
||||
})
|
||||
mail: permMail({ permission_options: ["只这一次", "拒绝"] }),
|
||||
}),
|
||||
);
|
||||
|
||||
await userEvent.click(screen.getByRole('button', { name: /只这一次/ }));
|
||||
await userEvent.click(screen.getByRole("button", { name: /只这一次/ }));
|
||||
|
||||
// 关键:不能归一化成 allow/deny —— 「只这一次」与「总是允许」的区别
|
||||
// 只有 Agent 侧的权限机制懂,服务端与前端都不该替它翻译
|
||||
await waitFor(() =>
|
||||
expect(spy).toHaveBeenCalledWith('m-1', '只这一次', undefined)
|
||||
expect(spy).toHaveBeenCalledWith("m-1", "只这一次", undefined),
|
||||
);
|
||||
});
|
||||
|
||||
it('填了备注时一起发出去', async () => {
|
||||
const spy = vi.spyOn(api, 'decidePermission').mockResolvedValue({ status: 'decided' } as any);
|
||||
it("填了备注时一起发出去", async () => {
|
||||
const spy = vi
|
||||
.spyOn(api, "decidePermission")
|
||||
.mockResolvedValue({ status: "decided" } as any);
|
||||
render(React.createElement(PermissionPanel, { mail: permMail() }));
|
||||
|
||||
await userEvent.type(screen.getByPlaceholderText('备注(可选)'), '只删 build,别动 dist');
|
||||
await userEvent.click(screen.getByRole('button', { name: /同意/ }));
|
||||
await userEvent.type(
|
||||
screen.getByPlaceholderText("备注(可选)"),
|
||||
"只删 build,别动 dist",
|
||||
);
|
||||
await userEvent.click(screen.getByRole("button", { name: /同意/ }));
|
||||
|
||||
await waitFor(() =>
|
||||
expect(spy).toHaveBeenCalledWith('m-1', '同意', '只删 build,别动 dist')
|
||||
expect(spy).toHaveBeenCalledWith("m-1", "同意", "只删 build,别动 dist"),
|
||||
);
|
||||
});
|
||||
|
||||
it('备注为空时传 undefined 而不是空字符串', async () => {
|
||||
const spy = vi.spyOn(api, 'decidePermission').mockResolvedValue({ status: 'decided' } as any);
|
||||
it("备注为空时传 undefined 而不是空字符串", async () => {
|
||||
const spy = vi
|
||||
.spyOn(api, "decidePermission")
|
||||
.mockResolvedValue({ status: "decided" } as any);
|
||||
render(React.createElement(PermissionPanel, { mail: permMail() }));
|
||||
|
||||
await userEvent.click(screen.getByRole('button', { name: /同意/ }));
|
||||
await userEvent.click(screen.getByRole("button", { name: /同意/ }));
|
||||
|
||||
// 空串会在决策邮件里留一行空的「备注:」
|
||||
await waitFor(() => expect(spy).toHaveBeenCalledWith('m-1', '同意', undefined));
|
||||
await waitFor(() =>
|
||||
expect(spy).toHaveBeenCalledWith("m-1", "同意", undefined),
|
||||
);
|
||||
});
|
||||
|
||||
it('决策后变成「已处理」,不再显示按钮', async () => {
|
||||
vi.spyOn(api, 'decidePermission').mockResolvedValue({ status: 'decided' } as any);
|
||||
it("决策后变成「已处理」,不再显示按钮", async () => {
|
||||
vi.spyOn(api, "decidePermission").mockResolvedValue({
|
||||
status: "decided",
|
||||
} as any);
|
||||
render(React.createElement(PermissionPanel, { mail: permMail() }));
|
||||
|
||||
await userEvent.click(screen.getByRole('button', { name: /同意/ }));
|
||||
await userEvent.click(screen.getByRole("button", { name: /同意/ }));
|
||||
|
||||
await waitFor(() => expect(screen.getByText('已处理:')).toBeInTheDocument());
|
||||
await waitFor(() =>
|
||||
expect(screen.getByText("已处理:")).toBeInTheDocument(),
|
||||
);
|
||||
// 还能点第二次的话人会以为第一次没生效,而服务端那边早已决策
|
||||
expect(screen.queryByRole('button')).toBeNull();
|
||||
expect(screen.queryByRole("button")).toBeNull();
|
||||
});
|
||||
|
||||
it('已经有 permission_result 的邮件直接显示结论', () => {
|
||||
it("已经有 permission_result 的邮件直接显示结论", () => {
|
||||
render(
|
||||
React.createElement(PermissionPanel, {
|
||||
mail: permMail({ permission_result: '拒绝' })
|
||||
})
|
||||
mail: permMail({ permission_result: "拒绝" }),
|
||||
}),
|
||||
);
|
||||
|
||||
expect(screen.getByText('拒绝')).toBeInTheDocument();
|
||||
expect(screen.queryByRole('button')).toBeNull();
|
||||
expect(screen.getByText("拒绝")).toBeInTheDocument();
|
||||
expect(screen.queryByRole("button")).toBeNull();
|
||||
});
|
||||
|
||||
it('提交中禁用所有按钮,避免重复决策', async () => {
|
||||
it("提交中禁用所有按钮,避免重复决策", async () => {
|
||||
let release: (v: any) => void = () => {};
|
||||
vi.spyOn(api, 'decidePermission').mockReturnValue(
|
||||
new Promise(res => {
|
||||
vi.spyOn(api, "decidePermission").mockReturnValue(
|
||||
new Promise((res) => {
|
||||
release = res;
|
||||
}) as any
|
||||
}) as any,
|
||||
);
|
||||
render(React.createElement(PermissionPanel, { mail: permMail() }));
|
||||
|
||||
await userEvent.click(screen.getByRole('button', { name: /同意/ }));
|
||||
await userEvent.click(screen.getByRole("button", { name: /同意/ }));
|
||||
|
||||
// 一次危险操作被批准两次,Agent 那边可能真的执行两遍
|
||||
await waitFor(() => {
|
||||
for (const b of screen.getAllByRole('button')) {
|
||||
for (const b of screen.getAllByRole("button")) {
|
||||
expect(b).toBeDisabled();
|
||||
}
|
||||
});
|
||||
@ -149,56 +168,64 @@ describe('PermissionPanel 决策', () => {
|
||||
// 收尾:让悬挂的 Promise 落定并等状态更新走完,
|
||||
// 否则组件在测试结束后才 setState,React 会报 act 警告
|
||||
await act(async () => {
|
||||
release({ status: 'decided' });
|
||||
release({ status: "decided" });
|
||||
});
|
||||
await waitFor(() => expect(screen.getByText('已处理:')).toBeInTheDocument());
|
||||
await waitFor(() =>
|
||||
expect(screen.getByText("已处理:")).toBeInTheDocument(),
|
||||
);
|
||||
});
|
||||
|
||||
it('提交失败时恢复可点,不假装已决策', async () => {
|
||||
vi.spyOn(api, 'decidePermission').mockRejectedValue(new Error('500'));
|
||||
vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||
it("提交失败时恢复可点,不假装已决策", async () => {
|
||||
vi.spyOn(api, "decidePermission").mockRejectedValue(new Error("500"));
|
||||
vi.spyOn(console, "error").mockImplementation(() => {});
|
||||
render(React.createElement(PermissionPanel, { mail: permMail() }));
|
||||
|
||||
await userEvent.click(screen.getByRole('button', { name: /同意/ }));
|
||||
await userEvent.click(screen.getByRole("button", { name: /同意/ }));
|
||||
|
||||
// 失败后显示「已处理」是最糟的结果:人以为批过了,Agent 还在等
|
||||
await waitFor(() => expect(screen.getByRole('button', { name: /同意/ })).toBeEnabled());
|
||||
expect(screen.queryByText('已处理:')).toBeNull();
|
||||
await waitFor(() =>
|
||||
expect(screen.getByRole("button", { name: /同意/ })).toBeEnabled(),
|
||||
);
|
||||
expect(screen.queryByText("已处理:")).toBeNull();
|
||||
});
|
||||
|
||||
it('决策成功后刷新收件箱并选中该会话', async () => {
|
||||
vi.spyOn(api, 'decidePermission').mockResolvedValue({ status: 'decided' } as any);
|
||||
it("决策成功后刷新收件箱并选中该会话", async () => {
|
||||
vi.spyOn(api, "decidePermission").mockResolvedValue({
|
||||
status: "decided",
|
||||
} as any);
|
||||
const fetchInbox = vi.fn(async () => {});
|
||||
const selectSession = vi.fn(async () => {});
|
||||
useMailStore.setState({ fetchInbox } as any);
|
||||
useSessionStore.setState({ selectSession } as any);
|
||||
|
||||
render(React.createElement(PermissionPanel, { mail: permMail() }));
|
||||
await userEvent.click(screen.getByRole('button', { name: /同意/ }));
|
||||
await userEvent.click(screen.getByRole("button", { name: /同意/ }));
|
||||
|
||||
// 不刷新的话列表里那封还是「未读的权限请求」,人会以为没生效
|
||||
await waitFor(() => {
|
||||
expect(fetchInbox).toHaveBeenCalledWith('all');
|
||||
expect(selectSession).toHaveBeenCalledWith('s-1');
|
||||
expect(fetchInbox).toHaveBeenCalledWith("all");
|
||||
expect(selectSession).toHaveBeenCalledWith("s-1");
|
||||
});
|
||||
});
|
||||
|
||||
it('同意类选项用绿色,其余用红色', () => {
|
||||
it("同意类选项用绿色,其余用红色", () => {
|
||||
render(
|
||||
React.createElement(PermissionPanel, {
|
||||
mail: permMail({ permission_options: ['允许', 'approve', '拒绝', '算了'] })
|
||||
})
|
||||
mail: permMail({
|
||||
permission_options: ["允许", "approve", "拒绝", "算了"],
|
||||
}),
|
||||
}),
|
||||
);
|
||||
|
||||
const cls = (name: string) =>
|
||||
screen.getByRole('button', { name: new RegExp(name) }).className;
|
||||
screen.getByRole("button", { name: new RegExp(name) }).className;
|
||||
|
||||
// 颜色是唯一的视觉提示:点错一次就放行了一个危险操作
|
||||
expect(cls('允许')).toContain('bg-green-700');
|
||||
expect(cls('approve')).toContain('bg-green-700');
|
||||
expect(cls('拒绝')).toContain('text-red-700');
|
||||
expect(cls("允许")).toContain("bg-green-700");
|
||||
expect(cls("approve")).toContain("bg-green-700");
|
||||
expect(cls("拒绝")).toContain("text-red-700");
|
||||
// 不在同意词表里的一律按「否」处理 —— 宁可让人多看一眼
|
||||
expect(cls('算了')).toContain('text-red-700');
|
||||
expect(cls("算了")).toContain("text-red-700");
|
||||
});
|
||||
});
|
||||
|
||||
@ -210,7 +237,7 @@ describe('PermissionPanel 决策', () => {
|
||||
* - 不能把问题渲染成同意/拒绝(那会让人点出一个毫无意义的答案)
|
||||
* - 空回答不能提交(模型会拿到一个什么都没说的结果继续跑)
|
||||
*/
|
||||
describe('PermissionPanel 回答问题', () => {
|
||||
describe("PermissionPanel 回答问题", () => {
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
useMailStore.setState({ fetchInbox: vi.fn(async () => {}) } as any);
|
||||
@ -218,109 +245,134 @@ describe('PermissionPanel 回答问题', () => {
|
||||
});
|
||||
|
||||
const questionMail = (over: Partial<Mail> = {}): Mail =>
|
||||
permMail({ permission_kind: 'question', ...over });
|
||||
permMail({ permission_kind: "question", ...over });
|
||||
|
||||
it('问题不带选项时:不渲染同意/拒绝,只给自由文本', () => {
|
||||
render(React.createElement(PermissionPanel, { mail: questionMail({ permission_options: [] }) }));
|
||||
|
||||
expect(screen.queryByRole('button', { name: /同意/ })).toBeNull();
|
||||
expect(screen.queryByRole('button', { name: /拒绝/ })).toBeNull();
|
||||
expect(screen.getByPlaceholderText('你的回答(必填)')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('问题带选项时:渲染选项按钮(而不是同意/拒绝)', () => {
|
||||
it("问题不带选项时:不渲染同意/拒绝,只给自由文本", () => {
|
||||
render(
|
||||
React.createElement(PermissionPanel, {
|
||||
mail: questionMail({ permission_options: ['方案 A', '方案 B'] })
|
||||
})
|
||||
mail: questionMail({ permission_options: [] }),
|
||||
}),
|
||||
);
|
||||
|
||||
expect(screen.getByRole('button', { name: /方案 A/ })).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: /方案 B/ })).toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: /^同意$/ })).toBeNull();
|
||||
expect(screen.queryByRole("button", { name: /同意/ })).toBeNull();
|
||||
expect(screen.queryByRole("button", { name: /拒绝/ })).toBeNull();
|
||||
expect(screen.getByPlaceholderText("你的回答(必填)")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('单选:再点已选项会取消,不会同时选中两个', async () => {
|
||||
it("问题带选项时:渲染选项按钮(而不是同意/拒绝)", () => {
|
||||
render(
|
||||
React.createElement(PermissionPanel, {
|
||||
mail: questionMail({ permission_options: ['A', 'B'] })
|
||||
})
|
||||
mail: questionMail({ permission_options: ["方案 A", "方案 B"] }),
|
||||
}),
|
||||
);
|
||||
const a = screen.getByRole('button', { name: /^A$/ });
|
||||
const b = screen.getByRole('button', { name: /^B$/ });
|
||||
|
||||
expect(screen.getByRole("button", { name: /方案 A/ })).toBeInTheDocument();
|
||||
expect(screen.getByRole("button", { name: /方案 B/ })).toBeInTheDocument();
|
||||
expect(screen.queryByRole("button", { name: /^同意$/ })).toBeNull();
|
||||
});
|
||||
|
||||
it("单选:再点已选项会取消,不会同时选中两个", async () => {
|
||||
render(
|
||||
React.createElement(PermissionPanel, {
|
||||
mail: questionMail({ permission_options: ["A", "B"] }),
|
||||
}),
|
||||
);
|
||||
const a = screen.getByRole("button", { name: /^A$/ });
|
||||
const b = screen.getByRole("button", { name: /^B$/ });
|
||||
|
||||
await userEvent.click(a);
|
||||
expect(a).toHaveAttribute('aria-pressed', 'true');
|
||||
expect(a).toHaveAttribute("aria-pressed", "true");
|
||||
await userEvent.click(b);
|
||||
expect(b).toHaveAttribute('aria-pressed', 'true');
|
||||
expect(a).toHaveAttribute('aria-pressed', 'false');
|
||||
expect(b).toHaveAttribute("aria-pressed", "true");
|
||||
expect(a).toHaveAttribute("aria-pressed", "false");
|
||||
});
|
||||
|
||||
it('多选:可同时选中多项,提交时用换行拼接', async () => {
|
||||
const spy = vi.spyOn(api, 'decidePermission').mockResolvedValue({ status: 'decided' } as any);
|
||||
it("多选:可同时选中多项,提交时用换行拼接", async () => {
|
||||
const spy = vi
|
||||
.spyOn(api, "decidePermission")
|
||||
.mockResolvedValue({ status: "decided" } as any);
|
||||
render(
|
||||
React.createElement(PermissionPanel, {
|
||||
mail: questionMail({ permission_options: ['A', 'B'], permission_multi_select: true })
|
||||
})
|
||||
mail: questionMail({
|
||||
permission_options: ["A", "B"],
|
||||
permission_multi_select: true,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
|
||||
await userEvent.click(screen.getByRole('button', { name: /^A$/ }));
|
||||
await userEvent.click(screen.getByRole('button', { name: /^B$/ }));
|
||||
await userEvent.click(screen.getByRole('button', { name: /提交回答/ }));
|
||||
await userEvent.click(screen.getByRole("button", { name: /^A$/ }));
|
||||
await userEvent.click(screen.getByRole("button", { name: /^B$/ }));
|
||||
await userEvent.click(screen.getByRole("button", { name: /提交回答/ }));
|
||||
|
||||
// 服务端按换行拆分多选答案,不能拼接成 "AB" 或数组字符串
|
||||
await waitFor(() => expect(spy).toHaveBeenCalledWith('m-1', 'A\nB', undefined));
|
||||
await waitFor(() =>
|
||||
expect(spy).toHaveBeenCalledWith("m-1", "A\nB", undefined),
|
||||
);
|
||||
});
|
||||
|
||||
it('空回答禁止提交(模型不能拿到一个什么都没说的结果)', async () => {
|
||||
const spy = vi.spyOn(api, 'decidePermission').mockResolvedValue({ status: 'decided' } as any);
|
||||
render(React.createElement(PermissionPanel, { mail: questionMail({ permission_options: [] }) }));
|
||||
it("空回答禁止提交(模型不能拿到一个什么都没说的结果)", async () => {
|
||||
const spy = vi
|
||||
.spyOn(api, "decidePermission")
|
||||
.mockResolvedValue({ status: "decided" } as any);
|
||||
render(
|
||||
React.createElement(PermissionPanel, {
|
||||
mail: questionMail({ permission_options: [] }),
|
||||
}),
|
||||
);
|
||||
|
||||
const submit = screen.getByRole('button', { name: /提交回答/ });
|
||||
const submit = screen.getByRole("button", { name: /提交回答/ });
|
||||
expect(submit).toBeDisabled();
|
||||
expect(screen.getByText('请先选择或填写回答')).toBeInTheDocument();
|
||||
expect(screen.getByText("请先选择或填写回答")).toBeInTheDocument();
|
||||
|
||||
await userEvent.type(screen.getByPlaceholderText('你的回答(必填)'), '配置在 /etc/foo.conf');
|
||||
await userEvent.type(
|
||||
screen.getByPlaceholderText("你的回答(必填)"),
|
||||
"配置在 /etc/foo.conf",
|
||||
);
|
||||
expect(submit).toBeEnabled();
|
||||
await userEvent.click(submit);
|
||||
await waitFor(() =>
|
||||
expect(spy).toHaveBeenCalledWith('m-1', '', '配置在 /etc/foo.conf')
|
||||
expect(spy).toHaveBeenCalledWith("m-1", "", "配置在 /etc/foo.conf"),
|
||||
);
|
||||
});
|
||||
|
||||
it('选了选项又写了备注:两者都发出去', async () => {
|
||||
const spy = vi.spyOn(api, 'decidePermission').mockResolvedValue({ status: 'decided' } as any);
|
||||
it("选了选项又写了备注:两者都发出去", async () => {
|
||||
const spy = vi
|
||||
.spyOn(api, "decidePermission")
|
||||
.mockResolvedValue({ status: "decided" } as any);
|
||||
render(
|
||||
React.createElement(PermissionPanel, {
|
||||
mail: questionMail({ permission_options: ['方案 A'] })
|
||||
})
|
||||
mail: questionMail({ permission_options: ["方案 A"] }),
|
||||
}),
|
||||
);
|
||||
|
||||
await userEvent.click(screen.getByRole('button', { name: /方案 A/ }));
|
||||
await userEvent.type(screen.getByPlaceholderText('补充说明(可选)'), '但要先备份');
|
||||
await userEvent.click(screen.getByRole('button', { name: /提交回答/ }));
|
||||
await userEvent.click(screen.getByRole("button", { name: /方案 A/ }));
|
||||
await userEvent.type(
|
||||
screen.getByPlaceholderText("补充说明(可选)"),
|
||||
"但要先备份",
|
||||
);
|
||||
await userEvent.click(screen.getByRole("button", { name: /提交回答/ }));
|
||||
|
||||
await waitFor(() =>
|
||||
expect(spy).toHaveBeenCalledWith('m-1', '方案 A', '但要先备份')
|
||||
expect(spy).toHaveBeenCalledWith("m-1", "方案 A", "但要先备份"),
|
||||
);
|
||||
});
|
||||
|
||||
it('问题已回答过:显示结论,不再显示任何输入控件', () => {
|
||||
it("问题已回答过:显示结论,不再显示任何输入控件", () => {
|
||||
render(
|
||||
React.createElement(PermissionPanel, {
|
||||
mail: questionMail({ permission_result: '方案 A' })
|
||||
})
|
||||
mail: questionMail({ permission_result: "方案 A" }),
|
||||
}),
|
||||
);
|
||||
|
||||
expect(screen.getByText(/已处理/)).toBeInTheDocument();
|
||||
expect(screen.queryByRole('button')).toBeNull();
|
||||
expect(screen.queryByRole("button")).toBeNull();
|
||||
});
|
||||
|
||||
it('审批型(无 permission_kind)仍然走同意/拒绝路径', () => {
|
||||
it("审批型(无 permission_kind)仍然走同意/拒绝路径", () => {
|
||||
render(React.createElement(PermissionPanel, { mail: permMail() }));
|
||||
|
||||
// 回归防护:question 分支不能把普通审批也带走
|
||||
expect(screen.getByRole('button', { name: /同意/ })).toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: /提交回答/ })).toBeNull();
|
||||
expect(screen.getByRole("button", { name: /同意/ })).toBeInTheDocument();
|
||||
expect(screen.queryByRole("button", { name: /提交回答/ })).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
@ -60,6 +60,40 @@ else
|
||||
echo " 未找到 pi SDK($PI_SDK),跳过 pi 插件测试"
|
||||
fi
|
||||
|
||||
# pi 邮件工具扩展:给**交互式**会话装上 send_mail / read_inbox。
|
||||
#
|
||||
# 守护进程(pi-mail-bridge.service)用 noExtensions:true 起会话,它的邮件工具
|
||||
# 只给模型在邮件会话里用;人在 TUI 里敲的 pi 拿不到。结果是平台的建设者自己
|
||||
# 收不到邮件,只能绕到 curl + 密钥直连 Gateway。这个扩展补上那一侧 ——
|
||||
# TUI 与邮箱是同一条 AgentMail 身份(agent pi)的两个入口。
|
||||
#
|
||||
# 为什么不会重复注册:noExtensions:true 只加载 CLI `-e` 传的扩展,
|
||||
# settings.json 的 extensions 数组会被排除(见 SDK resource-loader.js),
|
||||
# 因此守护进程的 worker 里零扩展、本扩展只作用于交互式会话。
|
||||
if [[ -d "$PI_SDK" ]]; then
|
||||
PI_HOME="${SUDO_USER:+$(getent passwd "$SUDO_USER" | cut -d: -f6)}"
|
||||
PI_HOME="${PI_HOME:-$HOME}"
|
||||
PI_SETTINGS="$PI_HOME/.pi/agent/settings.json"
|
||||
EXT_PATH="$REPO/plugins/pi-mail-bridge/extension/index.ts"
|
||||
if [[ -d "$PI_HOME/.pi/agent" || -f "$PI_SETTINGS" ]]; then
|
||||
install -d "$(dirname "$PI_SETTINGS")"
|
||||
node -e '
|
||||
const fs = require("fs");
|
||||
const [path, target] = process.argv.slice(1);
|
||||
let cfg = {};
|
||||
try { cfg = JSON.parse(fs.readFileSync(path, "utf8")); } catch { /* 新建 */ }
|
||||
const list = Array.isArray(cfg.extensions) ? cfg.extensions : [];
|
||||
if (list.includes(target)) { console.log(" 已注册,幂等跳过"); process.exit(0); }
|
||||
list.push(target);
|
||||
cfg.extensions = list;
|
||||
fs.writeFileSync(path, JSON.stringify(cfg, null, 2) + "\n");
|
||||
console.log(" 已注册 " + target);
|
||||
' "$PI_SETTINGS" "$EXT_PATH"
|
||||
else
|
||||
echo " 未找到 $PI_HOME/.pi/agent,跳过(手动在 settings.json 加 extensions: [\"$EXT_PATH\"])"
|
||||
fi
|
||||
fi
|
||||
|
||||
echo "==> 前端产物嵌入 Gateway"
|
||||
# 只清构建产物,不能 rm -rf 整个目录:
|
||||
# placeholder.html 在版本库里(让 go:embed 在新克隆里能编译),
|
||||
|
||||
10
plugins/dsh-mail-bridge/lib/mail-session-id.d.ts
vendored
10
plugins/dsh-mail-bridge/lib/mail-session-id.d.ts
vendored
@ -1,3 +1,9 @@
|
||||
export declare function dshSessionIdForMail(mailSessionID: any): string;
|
||||
export declare function matchesMailSession(dshSessionId: any, mailSessionID: any): boolean;
|
||||
export declare function pickMailSession(dshSessionIds: any[] | undefined, mailSessionID: any): string | undefined;
|
||||
export declare function matchesMailSession(
|
||||
dshSessionId: any,
|
||||
mailSessionID: any,
|
||||
): boolean;
|
||||
export declare function pickMailSession(
|
||||
dshSessionIds: any[] | undefined,
|
||||
mailSessionID: any,
|
||||
): string | undefined;
|
||||
|
||||
@ -24,7 +24,7 @@
|
||||
|
||||
/** 首次尝试使用的 DSH 会话 id。 */
|
||||
export function dshSessionIdForMail(mailSessionID) {
|
||||
return `mail-${String(mailSessionID ?? '')}`;
|
||||
return `mail-${String(mailSessionID ?? "")}`;
|
||||
}
|
||||
|
||||
/**
|
||||
@ -35,11 +35,11 @@ export function dshSessionIdForMail(mailSessionID) {
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function matchesMailSession(dshSessionId, mailSessionID) {
|
||||
const id = String(dshSessionId ?? '');
|
||||
const id = String(dshSessionId ?? "");
|
||||
const base = dshSessionIdForMail(mailSessionID);
|
||||
if (id === base) return true;
|
||||
// 模型降级重试:mail-<id>-r1 / -r2 / …
|
||||
const suffix = id.startsWith(`${base}-r`) ? id.slice(base.length + 2) : '';
|
||||
const suffix = id.startsWith(`${base}-r`) ? id.slice(base.length + 2) : "";
|
||||
return suffix.length > 0 && /^\d+$/.test(suffix);
|
||||
}
|
||||
|
||||
|
||||
12
plugins/dsh-mail-bridge/lib/user-question.d.ts
vendored
12
plugins/dsh-mail-bridge/lib/user-question.d.ts
vendored
@ -7,7 +7,15 @@ export declare function flattenQuestions(questions: any[]): {
|
||||
context: string;
|
||||
multiSelect: boolean;
|
||||
};
|
||||
export declare function answersFromDecision(questions: any[], decision: string, note?: string): {
|
||||
export declare function answersFromDecision(
|
||||
questions: any[],
|
||||
decision: string,
|
||||
note?: string,
|
||||
): {
|
||||
answers: Array<{ id: string; selected: string[]; custom?: string }>;
|
||||
};
|
||||
export declare function isBlankAnswer(questions: any[], decision: string, note?: string): boolean;
|
||||
export declare function isBlankAnswer(
|
||||
questions: any[],
|
||||
decision: string,
|
||||
note?: string,
|
||||
): boolean;
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@ -6,59 +6,69 @@
|
||||
* 运行时仍按旧档位执行 —— 人以为自己收紧了权限。
|
||||
*/
|
||||
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
|
||||
import {
|
||||
dshSessionIdForMail,
|
||||
matchesMailSession,
|
||||
pickMailSession,
|
||||
} from '../lib/mail-session-id.js';
|
||||
} from "../lib/mail-session-id.js";
|
||||
|
||||
test('首次尝试的 id 是 mail-<邮件会话 id>', () => {
|
||||
assert.equal(dshSessionIdForMail('abc-123'), 'mail-abc-123');
|
||||
test("首次尝试的 id 是 mail-<邮件会话 id>", () => {
|
||||
assert.equal(dshSessionIdForMail("abc-123"), "mail-abc-123");
|
||||
});
|
||||
|
||||
test('匹配首次尝试的 id', () => {
|
||||
assert.equal(matchesMailSession('mail-abc', 'abc'), true);
|
||||
test("匹配首次尝试的 id", () => {
|
||||
assert.equal(matchesMailSession("mail-abc", "abc"), true);
|
||||
});
|
||||
|
||||
test('匹配模型降级重试的 -r<i>', () => {
|
||||
assert.equal(matchesMailSession('mail-abc-r1', 'abc'), true);
|
||||
assert.equal(matchesMailSession('mail-abc-r12', 'abc'), true);
|
||||
test("匹配模型降级重试的 -r<i>", () => {
|
||||
assert.equal(matchesMailSession("mail-abc-r1", "abc"), true);
|
||||
assert.equal(matchesMailSession("mail-abc-r12", "abc"), true);
|
||||
});
|
||||
|
||||
test('不匹配别的会话(前缀相同也不行)', () => {
|
||||
assert.equal(matchesMailSession('mail-abcdef', 'abc'), false, 'mail-abc 的前缀不能吃掉 mail-abcdef');
|
||||
assert.equal(matchesMailSession('mail-abd', 'abc'), false);
|
||||
assert.equal(matchesMailSession('other-abc', 'abc'), false);
|
||||
assert.equal(matchesMailSession('', 'abc'), false);
|
||||
test("不匹配别的会话(前缀相同也不行)", () => {
|
||||
assert.equal(
|
||||
matchesMailSession("mail-abcdef", "abc"),
|
||||
false,
|
||||
"mail-abc 的前缀不能吃掉 mail-abcdef",
|
||||
);
|
||||
assert.equal(matchesMailSession("mail-abd", "abc"), false);
|
||||
assert.equal(matchesMailSession("other-abc", "abc"), false);
|
||||
assert.equal(matchesMailSession("", "abc"), false);
|
||||
});
|
||||
|
||||
test('不匹配非数字后缀(避免误吞其它会话)', () => {
|
||||
assert.equal(matchesMailSession('mail-abc-rx', 'abc'), false);
|
||||
assert.equal(matchesMailSession('mail-abc-r', 'abc'), false);
|
||||
assert.equal(matchesMailSession('mail-abc-retry', 'abc'), false);
|
||||
test("不匹配非数字后缀(避免误吞其它会话)", () => {
|
||||
assert.equal(matchesMailSession("mail-abc-rx", "abc"), false);
|
||||
assert.equal(matchesMailSession("mail-abc-r", "abc"), false);
|
||||
assert.equal(matchesMailSession("mail-abc-retry", "abc"), false);
|
||||
});
|
||||
|
||||
test('pickMailSession 优先首次尝试,而不是数组顺序', () => {
|
||||
test("pickMailSession 优先首次尝试,而不是数组顺序", () => {
|
||||
// 数组顺序可能来自 ctx.agents.list(),与尝试顺序无关
|
||||
assert.equal(pickMailSession(['mail-abc-r2', 'mail-abc-r1', 'mail-abc'], 'abc'), 'mail-abc');
|
||||
assert.equal(
|
||||
pickMailSession(["mail-abc-r2", "mail-abc-r1", "mail-abc"], "abc"),
|
||||
"mail-abc",
|
||||
);
|
||||
});
|
||||
|
||||
test('pickMailSession 没有首次尝试时取序号最小的重试', () => {
|
||||
assert.equal(pickMailSession(['mail-abc-r3', 'mail-abc-r1', 'mail-abc-r2'], 'abc'), 'mail-abc-r1');
|
||||
test("pickMailSession 没有首次尝试时取序号最小的重试", () => {
|
||||
assert.equal(
|
||||
pickMailSession(["mail-abc-r3", "mail-abc-r1", "mail-abc-r2"], "abc"),
|
||||
"mail-abc-r1",
|
||||
);
|
||||
});
|
||||
|
||||
test('pickMailSession 找不到时返回 undefined(调用方据此跳过)', () => {
|
||||
assert.equal(pickMailSession(['other-1', 'mail-def'], 'abc'), undefined);
|
||||
assert.equal(pickMailSession([], 'abc'), undefined);
|
||||
assert.equal(pickMailSession(undefined, 'abc'), undefined);
|
||||
test("pickMailSession 找不到时返回 undefined(调用方据此跳过)", () => {
|
||||
assert.equal(pickMailSession(["other-1", "mail-def"], "abc"), undefined);
|
||||
assert.equal(pickMailSession([], "abc"), undefined);
|
||||
assert.equal(pickMailSession(undefined, "abc"), undefined);
|
||||
});
|
||||
|
||||
test('接管的平台会话推不出 id:不能被误判成邮件会话', () => {
|
||||
test("接管的平台会话推不出 id:不能被误判成邮件会话", () => {
|
||||
// 平台自己生成的 id(如 DSH 界面里开的会话)与邮件会话无关,
|
||||
// 匹配函数必须说「不是」,否则会给错误的会话改档位。
|
||||
assert.equal(matchesMailSession('session-7f3a91', 'abc'), false);
|
||||
assert.equal(pickMailSession(['session-7f3a91'], 'abc'), undefined);
|
||||
assert.equal(matchesMailSession("session-7f3a91", "abc"), false);
|
||||
assert.equal(pickMailSession(["session-7f3a91"], "abc"), undefined);
|
||||
});
|
||||
|
||||
@ -9,10 +9,10 @@
|
||||
* 生产上表现为「新邮件偶尔收不到」「权限决策点了没反应」,且日志里一个字都没有。
|
||||
*/
|
||||
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
|
||||
import { createFrameParser } from '../lib/sse-client.js';
|
||||
import { createFrameParser } from "../lib/sse-client.js";
|
||||
|
||||
/** JSON.parse 的测试包装:解析失败让断言带原文失败,而不是抛未捕获异常。 */
|
||||
function parse(s) {
|
||||
@ -23,107 +23,118 @@ function parse(s) {
|
||||
}
|
||||
}
|
||||
|
||||
test('完整帧一次喂入:正常解析', () => {
|
||||
test("完整帧一次喂入:正常解析", () => {
|
||||
const p = createFrameParser();
|
||||
const events = p.push('id: 7\nevent: new_mail\ndata: {"mail_id":"m1"}\n\n');
|
||||
assert.equal(events.length, 1);
|
||||
assert.equal(events[0].event, 'new_mail');
|
||||
assert.deepEqual(parse(events[0].data), { mail_id: 'm1' });
|
||||
assert.equal(events[0].id, '7');
|
||||
assert.equal(p.lastEventId(), '7');
|
||||
assert.equal(events[0].event, "new_mail");
|
||||
assert.deepEqual(parse(events[0].data), { mail_id: "m1" });
|
||||
assert.equal(events[0].id, "7");
|
||||
assert.equal(p.lastEventId(), "7");
|
||||
});
|
||||
|
||||
test('帧被切在换行处:跨 chunk 保住 event 名(原 bug 的核心)', () => {
|
||||
test("帧被切在换行处:跨 chunk 保住 event 名(原 bug 的核心)", () => {
|
||||
const p = createFrameParser();
|
||||
// chunk1 恰好停在 event 行之后、data 行之前
|
||||
const first = p.push('id: 12\nevent: content_delta\n');
|
||||
assert.deepEqual(first, [], '半帧不该派发');
|
||||
const first = p.push("id: 12\nevent: content_delta\n");
|
||||
assert.deepEqual(first, [], "半帧不该派发");
|
||||
|
||||
const second = p.push('data: {"x":1}\n\n');
|
||||
assert.equal(second.length, 1, '跨 chunk 的半帧必须被拼回完整事件,而不是丢弃');
|
||||
assert.equal(second[0].event, 'content_delta');
|
||||
assert.equal(p.lastEventId(), '12');
|
||||
assert.equal(
|
||||
second.length,
|
||||
1,
|
||||
"跨 chunk 的半帧必须被拼回完整事件,而不是丢弃",
|
||||
);
|
||||
assert.equal(second[0].event, "content_delta");
|
||||
assert.equal(p.lastEventId(), "12");
|
||||
});
|
||||
|
||||
test('帧被切在行中间:buffer 保留半行', () => {
|
||||
test("帧被切在行中间:buffer 保留半行", () => {
|
||||
const p = createFrameParser();
|
||||
const a = p.push('event: new_ma');
|
||||
const a = p.push("event: new_ma");
|
||||
assert.deepEqual(a, []);
|
||||
const b = p.push('il\ndata: {"mail_id":"m9"}\n\n');
|
||||
assert.equal(b.length, 1);
|
||||
assert.equal(b[0].event, 'new_mail');
|
||||
assert.equal(b[0].event, "new_mail");
|
||||
});
|
||||
|
||||
test('一个 chunk 里多帧连续:全部派发', () => {
|
||||
test("一个 chunk 里多帧连续:全部派发", () => {
|
||||
const p = createFrameParser();
|
||||
const events = p.push(
|
||||
'event: new_mail\ndata: {"n":1}\n\n' +
|
||||
'event: new_mail\ndata: {"n":2}\n\n' +
|
||||
'event: session_update\ndata: {"n":3}\n\n'
|
||||
'event: session_update\ndata: {"n":3}\n\n',
|
||||
);
|
||||
assert.equal(events.length, 3);
|
||||
assert.deepEqual(events.map((e) => e.event), ['new_mail', 'new_mail', 'session_update']);
|
||||
assert.deepEqual(
|
||||
events.map((e) => e.event),
|
||||
["new_mail", "new_mail", "session_update"],
|
||||
);
|
||||
});
|
||||
|
||||
test('注释/心跳行被忽略,不影响后续帧', () => {
|
||||
test("注释/心跳行被忽略,不影响后续帧", () => {
|
||||
const p = createFrameParser();
|
||||
const events = p.push(': heartbeat\n\nevent: new_mail\ndata: {"n":1}\n\n');
|
||||
assert.equal(events.length, 1);
|
||||
assert.equal(events[0].event, 'new_mail');
|
||||
assert.equal(events[0].event, "new_mail");
|
||||
});
|
||||
|
||||
test('多行 data 用换行拼接', () => {
|
||||
test("多行 data 用换行拼接", () => {
|
||||
const p = createFrameParser();
|
||||
const events = p.push('event: x\ndata: line1\ndata: line2\n\n');
|
||||
assert.equal(events[0].data, 'line1\nline2');
|
||||
const events = p.push("event: x\ndata: line1\ndata: line2\n\n");
|
||||
assert.equal(events[0].data, "line1\nline2");
|
||||
});
|
||||
|
||||
test('CRLF 不被当成事件名或 JSON 的一部分', () => {
|
||||
test("CRLF 不被当成事件名或 JSON 的一部分", () => {
|
||||
const p = createFrameParser();
|
||||
const events = p.push('id: 3\r\nevent: new_mail\r\ndata: {"n":1}\r\n\r\n');
|
||||
assert.equal(events.length, 1);
|
||||
assert.equal(events[0].event, 'new_mail');
|
||||
assert.equal(events[0].id, '3');
|
||||
assert.equal(events[0].event, "new_mail");
|
||||
assert.equal(events[0].id, "3");
|
||||
assert.deepEqual(parse(events[0].data), { n: 1 });
|
||||
});
|
||||
|
||||
test('事件 id 只向前推进:重放旧 id 不回退断点', () => {
|
||||
test("事件 id 只向前推进:重放旧 id 不回退断点", () => {
|
||||
const p = createFrameParser();
|
||||
p.push('id: 10\nevent: new_mail\ndata: {"n":1}\n\n');
|
||||
assert.equal(p.lastEventId(), '10');
|
||||
assert.equal(p.lastEventId(), "10");
|
||||
// 服务端重放一条更早的事件:断点不该退回 5,否则下次重连会重复回放 6..10
|
||||
p.push('id: 5\nevent: new_mail\ndata: {"n":0}\n\n');
|
||||
assert.equal(p.lastEventId(), '5', '解析器如实记录当前 id(是否回退由使用方决定)');
|
||||
assert.equal(
|
||||
p.lastEventId(),
|
||||
"5",
|
||||
"解析器如实记录当前 id(是否回退由使用方决定)",
|
||||
);
|
||||
});
|
||||
|
||||
test('id 在派发前记录:回调抛异常也不丢断点', () => {
|
||||
test("id 在派发前记录:回调抛异常也不丢断点", () => {
|
||||
const p = createFrameParser();
|
||||
p.push('id: 42\nevent: new_mail\ndata: {"n":1}\n\n');
|
||||
assert.equal(p.lastEventId(), '42');
|
||||
assert.equal(p.lastEventId(), "42");
|
||||
});
|
||||
|
||||
test('只有 data 没有 event 不派发(避免把心跳数据当事件)', () => {
|
||||
test("只有 data 没有 event 不派发(避免把心跳数据当事件)", () => {
|
||||
const p = createFrameParser();
|
||||
const events = p.push('data: {"orphan":true}\n\n');
|
||||
assert.deepEqual(events, []);
|
||||
});
|
||||
|
||||
test('reset 清缓冲但保留断点(重连后仍能续传)', () => {
|
||||
test("reset 清缓冲但保留断点(重连后仍能续传)", () => {
|
||||
const p = createFrameParser();
|
||||
p.push('id: 99\nevent: a\ndata: {"n":1}\n\n');
|
||||
p.push('event: partial'); // 半帧
|
||||
p.push("event: partial"); // 半帧
|
||||
p.reset();
|
||||
assert.equal(p.lastEventId(), '99', '断点必须保留,否则重连从头回放');
|
||||
assert.equal(p.lastEventId(), "99", "断点必须保留,否则重连从头回放");
|
||||
// reset 后半帧不该复活
|
||||
const after = p.push('data: {"n":2}\n\n');
|
||||
assert.deepEqual(after, []);
|
||||
});
|
||||
|
||||
test('setLastEventId 清空 = 换 Gateway 后不再拿旧序号问新服务端', () => {
|
||||
test("setLastEventId 清空 = 换 Gateway 后不再拿旧序号问新服务端", () => {
|
||||
const p = createFrameParser();
|
||||
p.push('id: 123\nevent: a\ndata: {"n":1}\n\n');
|
||||
assert.equal(p.lastEventId(), '123');
|
||||
assert.equal(p.lastEventId(), "123");
|
||||
// connect_to_server 换了坐标:旧序号属于旧 Gateway 的环形缓冲,必须丢掉
|
||||
p.setLastEventId('');
|
||||
assert.equal(p.lastEventId(), '', '首次连接不得携带 Last-Event-ID');
|
||||
p.setLastEventId("");
|
||||
assert.equal(p.lastEventId(), "", "首次连接不得携带 Last-Event-ID");
|
||||
});
|
||||
|
||||
@ -1,5 +1,11 @@
|
||||
import { z } from "zod";
|
||||
import { readFileSync, writeFileSync, mkdirSync, existsSync, statSync } from "node:fs";
|
||||
import {
|
||||
readFileSync,
|
||||
writeFileSync,
|
||||
mkdirSync,
|
||||
existsSync,
|
||||
statSync,
|
||||
} from "node:fs";
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { homedir } from "node:os";
|
||||
import { join, dirname, basename } from "node:path";
|
||||
@ -34,17 +40,34 @@ import {
|
||||
shouldSkipAutoRelay,
|
||||
} from "./lib/relay-dedup.js";
|
||||
import { adoptedSessionID, adoptMissingMessage } from "./lib/adopt.js";
|
||||
import { autoRelayDecision, replyInstruction, inboundHeadline } from "./lib/relay-policy.js";
|
||||
import {
|
||||
autoRelayDecision,
|
||||
replyInstruction,
|
||||
inboundHeadline,
|
||||
} from "./lib/relay-policy.js";
|
||||
import { clampRelayKey, isPermanentFailure } from "./lib/relay-key.js";
|
||||
import { BoundedMap, BoundedSet, MAX_TRACKED_MAILS, MAX_TRACKED_SESSIONS } from "./lib/bounded.js";
|
||||
import { appendRenameProposal, renameProposalNote } from "./lib/rename-proposal.js";
|
||||
import {
|
||||
BoundedMap,
|
||||
BoundedSet,
|
||||
MAX_TRACKED_MAILS,
|
||||
MAX_TRACKED_SESSIONS,
|
||||
} from "./lib/bounded.js";
|
||||
import {
|
||||
appendRenameProposal,
|
||||
renameProposalNote,
|
||||
} from "./lib/rename-proposal.js";
|
||||
import { createSSEClient } from "./lib/sse-client.js";
|
||||
// opencode 原生支持三态权限,免批由它自己记(response:"always"),
|
||||
// 所以这里只借用决策文本的判定,不需要 createGrantStore。
|
||||
import { isAlwaysDecision, isApproval } from "./lib/permission-grants.js";
|
||||
import { opencodePermissions, normalizeMode, modeBriefing } from "./lib/permission-mode.js";
|
||||
import {
|
||||
opencodePermissions,
|
||||
normalizeMode,
|
||||
modeBriefing,
|
||||
} from "./lib/permission-mode.js";
|
||||
|
||||
const GATEWAY_URL = process.env.AGENTMAIL_GATEWAY_URL || "http://127.0.0.1:8180";
|
||||
const GATEWAY_URL =
|
||||
process.env.AGENTMAIL_GATEWAY_URL || "http://127.0.0.1:8180";
|
||||
const AGENT_NAME = process.env.AGENTMAIL_AGENT_NAME || "opencode";
|
||||
// 收到邮件后自动开会话处理时使用的模型
|
||||
const REPLY_PROVIDER = process.env.AGENTMAIL_REPLY_PROVIDER || "llmsproxy";
|
||||
@ -57,7 +80,8 @@ const REPLY_MODEL = process.env.AGENTMAIL_REPLY_MODEL || "AUTO";
|
||||
// 2. ~/.agentmail/agent.key(首次安装时本地生成并落盘)
|
||||
// 没有密钥时退回旧的 name/secret 方式,保证老配置不被这次改动打断。
|
||||
|
||||
const CONFIG_DIR = process.env.AGENTMAIL_CONFIG_DIR || join(homedir(), ".agentmail");
|
||||
const CONFIG_DIR =
|
||||
process.env.AGENTMAIL_CONFIG_DIR || join(homedir(), ".agentmail");
|
||||
const KEY_FILE = join(CONFIG_DIR, "agent.key");
|
||||
const CONFIG_FILE = join(CONFIG_DIR, "config.json");
|
||||
|
||||
@ -68,7 +92,9 @@ function readLocalKey() {
|
||||
try {
|
||||
if (!existsSync(KEY_FILE)) return null;
|
||||
const raw = JSON.parse(readFileSync(KEY_FILE, "utf8"));
|
||||
return typeof raw?.key_token === "string" && raw.key_token ? raw.key_token : null;
|
||||
return typeof raw?.key_token === "string" && raw.key_token
|
||||
? raw.key_token
|
||||
: null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
@ -80,11 +106,17 @@ function generateLocalKey() {
|
||||
mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 });
|
||||
writeFileSync(
|
||||
KEY_FILE,
|
||||
JSON.stringify({ key_token: token, created_at: new Date().toISOString() }, null, 2),
|
||||
{ mode: 0o600 }
|
||||
JSON.stringify(
|
||||
{ key_token: token, created_at: new Date().toISOString() },
|
||||
null,
|
||||
2,
|
||||
),
|
||||
{ mode: 0o600 },
|
||||
);
|
||||
console.error(`[mail-bridge] 已在 ${KEY_FILE} 生成本地密钥。`);
|
||||
console.error(`[mail-bridge] 该密钥需管理员在 AgentMail 后台登记后才能接入:`);
|
||||
console.error(
|
||||
`[mail-bridge] 该密钥需管理员在 AgentMail 后台登记后才能接入:`,
|
||||
);
|
||||
console.error(`[mail-bridge] ${token}`);
|
||||
return token;
|
||||
}
|
||||
@ -95,12 +127,20 @@ function saveConfig(extra) {
|
||||
mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 });
|
||||
let cur = {};
|
||||
if (existsSync(CONFIG_FILE)) {
|
||||
try { cur = JSON.parse(readFileSync(CONFIG_FILE, "utf8")); } catch { /* 损坏就重写 */ }
|
||||
try {
|
||||
cur = JSON.parse(readFileSync(CONFIG_FILE, "utf8"));
|
||||
} catch {
|
||||
/* 损坏就重写 */
|
||||
}
|
||||
}
|
||||
writeFileSync(
|
||||
CONFIG_FILE,
|
||||
JSON.stringify({ ...cur, gateway_url: GATEWAY_URL, agent_name: AGENT_NAME, ...extra }, null, 2),
|
||||
{ mode: 0o600 }
|
||||
JSON.stringify(
|
||||
{ ...cur, gateway_url: GATEWAY_URL, agent_name: AGENT_NAME, ...extra },
|
||||
null,
|
||||
2,
|
||||
),
|
||||
{ mode: 0o600 },
|
||||
);
|
||||
} catch (e) {
|
||||
console.error("[mail-bridge] 写 config.json 失败:", e?.message || e);
|
||||
@ -121,7 +161,9 @@ function authHeaders() {
|
||||
// ─── HTTP ───
|
||||
|
||||
async function apiGet(path) {
|
||||
const res = await fetch(`${GATEWAY_URL}/api/v1${path}`, { headers: authHeaders() });
|
||||
const res = await fetch(`${GATEWAY_URL}/api/v1${path}`, {
|
||||
headers: authHeaders(),
|
||||
});
|
||||
if (!res.ok) throw new Error(`GET ${path} failed: ${res.status}`);
|
||||
return res.json();
|
||||
}
|
||||
@ -168,22 +210,42 @@ async function syncSessionNaming(mailSessionID, { alias, title }) {
|
||||
// ─── Tools(直接用 zod 定义,不依赖 @opencode-ai/plugin) ───
|
||||
|
||||
const sendMailTool = {
|
||||
description: "发送邮件。三维地址 name@path.session:省略 session 投递到默认会话,.new 强制新建会话,.具体别名 必须是已存在的会话(否则无法送达)。回复来信请传 reply_to。",
|
||||
description:
|
||||
"发送邮件。三维地址 name@path.session:省略 session 投递到默认会话,.new 强制新建会话,.具体别名 必须是已存在的会话(否则无法送达)。回复来信请传 reply_to。",
|
||||
args: {
|
||||
to: z.string().describe("收件人:name / name@path(默认会话)/ name@path.new(新建)/ name@path.别名(已有会话)"),
|
||||
to: z
|
||||
.string()
|
||||
.describe(
|
||||
"收件人:name / name@path(默认会话)/ name@path.new(新建)/ name@path.别名(已有会话)",
|
||||
),
|
||||
subject: z.string().describe("邮件主题"),
|
||||
body: z.string().describe("邮件正文(Markdown)"),
|
||||
cc: z.string().optional().describe("抄送,逗号分隔多个三维地址"),
|
||||
reply_to: z.string().optional().describe("回复某封邮件时传其 mail_id,回信会落回同一会话"),
|
||||
session_alias: z.string().optional().describe("仅在用 .new 新建会话时生效:给新会话命名,之后可用 name@path.<别名> 续谈。别名全局唯一,不可含 . / @ 空白,不可为 new"),
|
||||
attachment_ids: z.array(z.string()).optional().describe("附件 ID 列表,先用 upload_attachment 上传取得"),
|
||||
propose_alias: z.string()
|
||||
reply_to: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe("回复某封邮件时传其 mail_id,回信会落回同一会话"),
|
||||
session_alias: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe(
|
||||
"仅在用 .new 新建会话时生效:给新会话命名,之后可用 name@path.<别名> 续谈。别名全局唯一,不可含 . / @ 空白,不可为 new",
|
||||
),
|
||||
attachment_ids: z
|
||||
.array(z.string())
|
||||
.optional()
|
||||
.describe("附件 ID 列表,先用 upload_attachment 上传取得"),
|
||||
propose_alias: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe(
|
||||
"建议把当前会话改名成这个别名(例如摸清问题后从 witty-planet 改成 fix-login-leak)。" +
|
||||
"这只是建议:别名是人的寻址入口,实际改名由用户在界面上确认。不可含 . / @ 空白,不可为 new"
|
||||
"这只是建议:别名是人的寻址入口,实际改名由用户在界面上确认。不可含 . / @ 空白,不可为 new",
|
||||
),
|
||||
propose_reason: z.string().optional().describe("改名理由,一句话,展示给用户看"),
|
||||
propose_reason: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe("改名理由,一句话,展示给用户看"),
|
||||
},
|
||||
// context 带 sessionID:用它记下「模型这一轮亲手发过信」,
|
||||
// 让 session.idle 的自动转发让位,避免同一件事发两封。
|
||||
@ -193,7 +255,10 @@ const sendMailTool = {
|
||||
// (三平台共用)—— 各写一遍的话少个空格就静默失效:邮件照常发出,
|
||||
// 提议凭空消失,而模型以为自己提过了。
|
||||
const { body, proposed } = appendRenameProposal(
|
||||
args.body, args.propose_alias, args.propose_reason);
|
||||
args.body,
|
||||
args.propose_alias,
|
||||
args.propose_reason,
|
||||
);
|
||||
|
||||
const result = await apiPost("/mail/send", {
|
||||
to: args.to,
|
||||
@ -224,9 +289,15 @@ const sendMailTool = {
|
||||
: "";
|
||||
// 别名取服务端回的 rename_proposed:它跑过 normalizeAlias,
|
||||
// 回显本地值会让模型记住一个不存在的名字
|
||||
const note = renameProposalNote(result.rename_proposed, args.propose_alias, proposed);
|
||||
return `已发送。Mail ID: ${result.mail_id},Session: ${result.session_id}${alias}${budget}` +
|
||||
(note ? `\n${note}` : "");
|
||||
const note = renameProposalNote(
|
||||
result.rename_proposed,
|
||||
args.propose_alias,
|
||||
proposed,
|
||||
);
|
||||
return (
|
||||
`已发送。Mail ID: ${result.mail_id},Session: ${result.session_id}${alias}${budget}` +
|
||||
(note ? `\n${note}` : "")
|
||||
);
|
||||
},
|
||||
};
|
||||
|
||||
@ -239,8 +310,14 @@ const forwardMailTool = {
|
||||
to: z.string().describe("新收件人的三维地址"),
|
||||
comment: z.string().optional().describe("转发说明,置于引用原文之前"),
|
||||
cc: z.string().optional().describe("抄送,逗号分隔多个三维地址"),
|
||||
subject: z.string().optional().describe("自定义主题;留空则自动加 Fwd: 前缀"),
|
||||
session_alias: z.string().optional().describe("仅在目标地址以 .new 结尾时生效:给新会话命名"),
|
||||
subject: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe("自定义主题;留空则自动加 Fwd: 前缀"),
|
||||
session_alias: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe("仅在目标地址以 .new 结尾时生效:给新会话命名"),
|
||||
},
|
||||
async execute(args) {
|
||||
const result = await apiPost(`/mail/${args.mail_id}/forward`, {
|
||||
@ -257,7 +334,10 @@ const forwardMailTool = {
|
||||
const readInboxTool = {
|
||||
description: "查阅收件箱中的邮件。收到新邮件通知后应立即调用此工具。",
|
||||
args: {
|
||||
filter: z.enum(["unread", "all"]).optional().describe("过滤条件,默认 unread"),
|
||||
filter: z
|
||||
.enum(["unread", "all"])
|
||||
.optional()
|
||||
.describe("过滤条件,默认 unread"),
|
||||
limit: z.number().optional().describe("返回数量,默认 5"),
|
||||
},
|
||||
async execute(args) {
|
||||
@ -277,8 +357,8 @@ const readInboxTool = {
|
||||
if (ids.length) {
|
||||
// 标记失败不该让 read_inbox 失败 —— 正文已经取到了,
|
||||
// 代价只是下次会重复看到,比丢掉这次读取轻。
|
||||
apiPost("/mail/read", { mail_ids: ids }).catch(e =>
|
||||
console.error("[mail-bridge] 标记已读失败:", e?.message || e)
|
||||
apiPost("/mail/read", { mail_ids: ids }).catch((e) =>
|
||||
console.error("[mail-bridge] 标记已读失败:", e?.message || e),
|
||||
);
|
||||
}
|
||||
return listed;
|
||||
@ -292,7 +372,10 @@ const uploadAttachmentTool = {
|
||||
"未随邮件发出的附件 24 小时后自动清理。",
|
||||
args: {
|
||||
path: z.string().describe("要上传的本地文件绝对路径"),
|
||||
filename: z.string().optional().describe("自定义展示文件名,默认取路径的最后一段"),
|
||||
filename: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe("自定义展示文件名,默认取路径的最后一段"),
|
||||
},
|
||||
async execute(args) {
|
||||
const filePath = args.path;
|
||||
@ -320,21 +403,27 @@ const uploadAttachmentTool = {
|
||||
if (!res.ok) throw new Error(data.error || `上传失败: ${res.status}`);
|
||||
|
||||
const a = data.attachment;
|
||||
return `已上传 ${a.filename}(${formatSize(a.size_bytes)})。attachment_id: ${a.attachment_id}\n` +
|
||||
`在 send_mail 的 attachment_ids 里带上这个 id 才会随邮件发出。`;
|
||||
return (
|
||||
`已上传 ${a.filename}(${formatSize(a.size_bytes)})。attachment_id: ${a.attachment_id}\n` +
|
||||
`在 send_mail 的 attachment_ids 里带上这个 id 才会随邮件发出。`
|
||||
);
|
||||
},
|
||||
};
|
||||
|
||||
const downloadAttachmentTool = {
|
||||
description: "下载邮件附件到本地文件。attachment_id 从 read_inbox 的附件清单里取。",
|
||||
description:
|
||||
"下载邮件附件到本地文件。attachment_id 从 read_inbox 的附件清单里取。",
|
||||
args: {
|
||||
attachment_id: z.string().describe("附件 ID"),
|
||||
save_to: z.string().describe("保存到的本地绝对路径"),
|
||||
},
|
||||
async execute(args) {
|
||||
const res = await fetch(`${GATEWAY_URL}/api/v1/attachments/${args.attachment_id}`, {
|
||||
const res = await fetch(
|
||||
`${GATEWAY_URL}/api/v1/attachments/${args.attachment_id}`,
|
||||
{
|
||||
headers: authHeaders(),
|
||||
});
|
||||
},
|
||||
);
|
||||
if (!res.ok) {
|
||||
const data = await res.json().catch(() => ({}));
|
||||
throw new Error(data.error || `下载失败: ${res.status}`);
|
||||
@ -403,10 +492,16 @@ const sessionParticipantsTool = {
|
||||
"列出某条会话的全部参与方(发件人/收件人/抄送方)及各自的可投递地址," +
|
||||
"并标出谁还没回应。**要回给抄收方或向第三方转达时先用它拿地址**。",
|
||||
args: {
|
||||
session_id: z.string().describe("会话 ID(read_inbox 未直接给出时可从 read_thread 或新邮件通知取得)"),
|
||||
session_id: z
|
||||
.string()
|
||||
.describe(
|
||||
"会话 ID(read_inbox 未直接给出时可从 read_thread 或新邮件通知取得)",
|
||||
),
|
||||
},
|
||||
async execute(args) {
|
||||
const data = await apiGet(`/agent/sessions/${args.session_id}/participants`);
|
||||
const data = await apiGet(
|
||||
`/agent/sessions/${args.session_id}/participants`,
|
||||
);
|
||||
return renderParticipants(data);
|
||||
},
|
||||
};
|
||||
@ -417,7 +512,10 @@ const readThreadTool = {
|
||||
"用它确认别人已经说了什么,避免重复提问或重复汇报。",
|
||||
args: {
|
||||
mail_id: z.string().describe("线索中任一封邮件的 ID"),
|
||||
offset: z.number().optional().describe("分页偏移,续取时传上次返回的 next_offset"),
|
||||
offset: z
|
||||
.number()
|
||||
.optional()
|
||||
.describe("分页偏移,续取时传上次返回的 next_offset"),
|
||||
},
|
||||
async execute(args) {
|
||||
const qs = args.offset ? `?offset=${args.offset}` : "";
|
||||
@ -443,13 +541,16 @@ const readMailTool = {
|
||||
`会话: #${data.session_alias || "未命名"}(session_id: ${m.session_id || "?"})`,
|
||||
];
|
||||
if (Array.isArray(m.cc_list) && m.cc_list.length) {
|
||||
lines.push(`抄送: ${m.cc_list.map(c => c?.raw || c?.name).join("、")}`);
|
||||
lines.push(`抄送: ${m.cc_list.map((c) => c?.raw || c?.name).join("、")}`);
|
||||
}
|
||||
if (Array.isArray(m.attachments) && m.attachments.length) {
|
||||
lines.push(
|
||||
`附件: ${m.attachments
|
||||
.map(a => `${a.filename}(${formatSize(a.size_bytes)}, id=${a.attachment_id})`)
|
||||
.join("、")}`
|
||||
.map(
|
||||
(a) =>
|
||||
`${a.filename}(${formatSize(a.size_bytes)}, id=${a.attachment_id})`,
|
||||
)
|
||||
.join("、")}`,
|
||||
);
|
||||
}
|
||||
lines.push("", m.body || "(空正文)", "");
|
||||
@ -458,13 +559,15 @@ const readMailTool = {
|
||||
lines.push(
|
||||
"可投递地址: " +
|
||||
data.participants
|
||||
.filter(p => p.address && p.name !== AGENT_NAME)
|
||||
.map(p => `${p.address}(${p.role})`)
|
||||
.join("、")
|
||||
.filter((p) => p.address && p.name !== AGENT_NAME)
|
||||
.map((p) => `${p.address}(${p.role})`)
|
||||
.join("、"),
|
||||
);
|
||||
}
|
||||
if (data.reply_address) {
|
||||
lines.push(`回信给发件人用 ${data.reply_address},或传 reply_to=${m.mail_id}。`);
|
||||
lines.push(
|
||||
`回信给发件人用 ${data.reply_address},或传 reply_to=${m.mail_id}。`,
|
||||
);
|
||||
}
|
||||
return lines.join("\n");
|
||||
},
|
||||
@ -498,8 +601,16 @@ const connectToServerTool = {
|
||||
"连接到 AgentMail Gateway:登记本机密钥并完成注册。首次安装或换了 Gateway 地址时调用。" +
|
||||
"密钥若未在后台登记过,此处会返回需要登记的密钥全文。",
|
||||
args: {
|
||||
gateway_url: z.string().optional().describe("Gateway 地址,如 https://mail.example.com;省略则用当前配置"),
|
||||
key_token: z.string().optional().describe("管理员签发的 Agent 密钥;省略则用本地密钥(不存在时自动生成)"),
|
||||
gateway_url: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe("Gateway 地址,如 https://mail.example.com;省略则用当前配置"),
|
||||
key_token: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe(
|
||||
"管理员签发的 Agent 密钥;省略则用本地密钥(不存在时自动生成)",
|
||||
),
|
||||
},
|
||||
async execute(args) {
|
||||
if (args.key_token) {
|
||||
@ -508,8 +619,12 @@ const connectToServerTool = {
|
||||
mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 });
|
||||
writeFileSync(
|
||||
KEY_FILE,
|
||||
JSON.stringify({ key_token: AGENT_KEY, created_at: new Date().toISOString() }, null, 2),
|
||||
{ mode: 0o600 }
|
||||
JSON.stringify(
|
||||
{ key_token: AGENT_KEY, created_at: new Date().toISOString() },
|
||||
null,
|
||||
2,
|
||||
),
|
||||
{ mode: 0o600 },
|
||||
);
|
||||
} else if (!AGENT_KEY) {
|
||||
AGENT_KEY = generateLocalKey();
|
||||
@ -518,8 +633,15 @@ const connectToServerTool = {
|
||||
const url = (args.gateway_url || GATEWAY_URL).replace(/\/+$/, "");
|
||||
const res = await fetch(`${url}/api/v1/agent/register`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json", Authorization: `Bearer ${AGENT_KEY}` },
|
||||
body: JSON.stringify({ name: AGENT_NAME, workspaces: [], platform: "opencode" }),
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${AGENT_KEY}`,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
name: AGENT_NAME,
|
||||
workspaces: [],
|
||||
platform: "opencode",
|
||||
}),
|
||||
});
|
||||
const data = await res.json().catch(() => ({}));
|
||||
|
||||
@ -629,7 +751,8 @@ async function resolveSessionForMail(client, directory, data, kind) {
|
||||
} catch {
|
||||
ok = false;
|
||||
}
|
||||
if (!ok) throw new Error(adoptMissingMessage(adoptedID, "可能已在界面上删除"));
|
||||
if (!ok)
|
||||
throw new Error(adoptMissingMessage(adoptedID, "可能已在界面上删除"));
|
||||
if (mailSessionID) {
|
||||
sessionMap.set(mailSessionID, adoptedID);
|
||||
reverseMap.set(adoptedID, mailSessionID);
|
||||
@ -637,7 +760,9 @@ async function resolveSessionForMail(client, directory, data, kind) {
|
||||
// 轮次结束要把总结转回发件人。不标记的话邮件投进去了却永远没有回音。
|
||||
mailDrivenSessions.add(adoptedID);
|
||||
}
|
||||
console.error(`[mail-bridge] 接管平台会话 ${adoptedID}(邮件会话 ${mailSessionID})`);
|
||||
console.error(
|
||||
`[mail-bridge] 接管平台会话 ${adoptedID}(邮件会话 ${mailSessionID})`,
|
||||
);
|
||||
return { sessionID: adoptedID, reused: true, adopted: true };
|
||||
}
|
||||
|
||||
@ -649,10 +774,14 @@ async function resolveSessionForMail(client, directory, data, kind) {
|
||||
//
|
||||
// 校验逻辑与 DSH 侧共用(lib/workspace.js):目录不存在时不创建、
|
||||
// 拒绝相对路径。opencode 的兜底是插件启动时的 directory。
|
||||
const { cwd: wantDir, grouped } = resolveWorkspaceCwd(data.to_workspace, directory);
|
||||
const { cwd: wantDir, grouped } = resolveWorkspaceCwd(
|
||||
data.to_workspace,
|
||||
directory,
|
||||
);
|
||||
if (!grouped && data.to_workspace) {
|
||||
console.error(
|
||||
`[mail-bridge] 工作目录 ${data.to_workspace} 不可用,回退到 ${wantDir || "(平台默认)"}`);
|
||||
`[mail-bridge] 工作目录 ${data.to_workspace} 不可用,回退到 ${wantDir || "(平台默认)"}`,
|
||||
);
|
||||
}
|
||||
|
||||
// 故意不传 title:opencode 只在标题缺省时才让模型按首轮对话生成摘要标题,
|
||||
@ -679,7 +808,8 @@ async function resolveSessionForMail(client, directory, data, kind) {
|
||||
// 标题要等模型生成,走 session.updated 事件。
|
||||
if (session.slug) {
|
||||
syncSessionNaming(mailSessionID, { alias: session.slug }).then((res) => {
|
||||
if (res?.alias) console.error(`[mail-bridge] 别名同步 ${sessionID} -> ${res.alias}`);
|
||||
if (res?.alias)
|
||||
console.error(`[mail-bridge] 别名同步 ${sessionID} -> ${res.alias}`);
|
||||
});
|
||||
}
|
||||
}
|
||||
@ -730,11 +860,13 @@ async function relaySummary(client, directory, sessionID) {
|
||||
// 未完成的消息(还在生成/被中断)不转:转出去是半截话
|
||||
if (!m.info.time?.completed) continue;
|
||||
const text = (m.parts || [])
|
||||
.filter(p => p.type === "text" && !p.synthetic && !p.ignored && p.text)
|
||||
.map(p => p.text)
|
||||
.filter((p) => p.type === "text" && !p.synthetic && !p.ignored && p.text)
|
||||
.map((p) => p.text)
|
||||
.join("\n")
|
||||
.trim();
|
||||
if (text) { last = { id: m.info.id, text }; }
|
||||
if (text) {
|
||||
last = { id: m.info.id, text };
|
||||
}
|
||||
break;
|
||||
}
|
||||
if (!last) {
|
||||
@ -775,10 +907,14 @@ async function relaySummary(client, directory, sessionID) {
|
||||
// - reply_to 相同:它已经回过这封信了
|
||||
// relay_key 的幂等管不了这个 —— 那个键保证「同一条消息不转两次」,
|
||||
// 而这里是「模型已经自己发过了」。
|
||||
if (shouldSkipAutoRelay(explicitSends.get(sessionID), ctx.replyTo, ctx.mailID)) {
|
||||
if (
|
||||
shouldSkipAutoRelay(explicitSends.get(sessionID), ctx.replyTo, ctx.mailID)
|
||||
) {
|
||||
explicitSends.delete(sessionID);
|
||||
relayedSummaries.set(sessionID, last.id); // 记下这条已「处理」,别下次 idle 又转
|
||||
console.error(`[mail-bridge] 本轮模型已主动回信 ${ctx.replyTo},跳过自动转发`);
|
||||
console.error(
|
||||
`[mail-bridge] 本轮模型已主动回信 ${ctx.replyTo},跳过自动转发`,
|
||||
);
|
||||
return null;
|
||||
}
|
||||
|
||||
@ -865,8 +1001,10 @@ async function replyPermission(client, directory, data) {
|
||||
// (空串、历史数据里的旧选项、将来服务端新增的选项)都会放行一次
|
||||
// 没人批准的危险操作。判断顺序也重要:always 必须先判,因为 isApproval
|
||||
// 对「一直同意」同样为真。
|
||||
const response = isAlwaysDecision(decision) ? "always"
|
||||
: isApproval(decision) ? "once"
|
||||
const response = isAlwaysDecision(decision)
|
||||
? "always"
|
||||
: isApproval(decision)
|
||||
? "once"
|
||||
: "reject";
|
||||
|
||||
await client.postSessionIdPermissionsPermissionId({
|
||||
@ -875,13 +1013,20 @@ async function replyPermission(client, directory, data) {
|
||||
body: { response },
|
||||
});
|
||||
pendingPermissions.delete(permID);
|
||||
console.error(`[mail-bridge] 权限 ${permID} -> ${response}(决策人 ${data.decided_by || "?"})`);
|
||||
console.error(
|
||||
`[mail-bridge] 权限 ${permID} -> ${response}(决策人 ${data.decided_by || "?"})`,
|
||||
);
|
||||
return { sessionID };
|
||||
}
|
||||
|
||||
// 把一封来信投递给对应的 opencode 会话(已绑定则续谈,未绑定则新开)。
|
||||
async function deliverMail(client, directory, data, kind) {
|
||||
const { sessionID, reused } = await resolveSessionForMail(client, directory, data, kind);
|
||||
const { sessionID, reused } = await resolveSessionForMail(
|
||||
client,
|
||||
directory,
|
||||
data,
|
||||
kind,
|
||||
);
|
||||
|
||||
// 新一轮开始:清掉上一轮「模型主动发过信」的记录。
|
||||
// 不清的话,上一轮亲手回过信会永久压掉这个会话之后所有的自动转发。
|
||||
@ -907,8 +1052,13 @@ async function deliverMail(client, directory, data, kind) {
|
||||
const fromHuman = data.from_human === true;
|
||||
// opencode 1.18+ 不支持 session.create permission 参数,
|
||||
// 只能在提示词里告知模型档位约束(advisory 路径)。
|
||||
const permBriefing = modeBriefing({ mode: normalizeMode(data.permission_mode), enforcement: 'advisory', workspace: directory || '' });
|
||||
const text = kind === "permission"
|
||||
const permBriefing = modeBriefing({
|
||||
mode: normalizeMode(data.permission_mode),
|
||||
enforcement: "advisory",
|
||||
workspace: directory || "",
|
||||
});
|
||||
const text =
|
||||
kind === "permission"
|
||||
? `你之前发起的权限请求已有结论:${data.decision}(决策人:${data.decided_by || "用户"})。请据此继续后续工作。`
|
||||
: [
|
||||
inboundHeadline({
|
||||
@ -955,7 +1105,9 @@ async function deliverMail(client, directory, data, kind) {
|
||||
query: directory ? { directory } : undefined,
|
||||
body: {
|
||||
// route 为 undefined 表示不指定模型,交给平台自己选
|
||||
...(route ? { model: { providerID: route.provider, modelID: route.model } } : {}),
|
||||
...(route
|
||||
? { model: { providerID: route.provider, modelID: route.model } }
|
||||
: {}),
|
||||
parts: [{ type: "text", text }],
|
||||
},
|
||||
});
|
||||
@ -970,7 +1122,9 @@ async function deliverMail(client, directory, data, kind) {
|
||||
const outcome = await watching.result;
|
||||
if (outcome.ok) {
|
||||
if (failures.length > 0) {
|
||||
console.error(`[mail-bridge] ${label} 成功(前 ${failures.length} 个失败)`);
|
||||
console.error(
|
||||
`[mail-bridge] ${label} 成功(前 ${failures.length} 个失败)`,
|
||||
);
|
||||
}
|
||||
return { sessionID, reused };
|
||||
}
|
||||
@ -997,7 +1151,8 @@ async function deliverMail(client, directory, data, kind) {
|
||||
}
|
||||
throw new Error(
|
||||
`划定范围内的 ${failures.length} 个模型全部失败:` +
|
||||
failures.map(f => f.error).join(" | "));
|
||||
failures.map((f) => f.error).join(" | "),
|
||||
);
|
||||
}
|
||||
|
||||
// ─── 首轮结果观察 ───
|
||||
@ -1018,7 +1173,9 @@ const turnWatchers = new Map(); // sessionID -> { resolve, timer }
|
||||
*/
|
||||
function awaitFirstTurn(sessionID, timeoutMs = 60000) {
|
||||
let settle;
|
||||
const result = new Promise(res => { settle = res; });
|
||||
const result = new Promise((res) => {
|
||||
settle = res;
|
||||
});
|
||||
const finish = (r) => {
|
||||
const w = turnWatchers.get(sessionID);
|
||||
if (!w) return;
|
||||
@ -1062,14 +1219,16 @@ export default async function mailBridge(input) {
|
||||
saveConfig({ registered_at: new Date().toISOString() });
|
||||
console.error(
|
||||
`[mail-bridge] 已接入 ${GATEWAY_URL},身份 ${AGENT_NAME}` +
|
||||
`(${AGENT_KEY ? "密钥认证" : "name/secret 认证"})。`
|
||||
`(${AGENT_KEY ? "密钥认证" : "name/secret 认证"})。`,
|
||||
);
|
||||
} catch (e) {
|
||||
// 密钥未登记时这里会报「密钥无效」——必须说清楚该做什么,
|
||||
// 否则用户只看到一句 401 不知道要拿密钥去后台登记。
|
||||
console.error("[mail-bridge] 注册失败:", e?.message);
|
||||
if (AGENT_KEY) {
|
||||
console.error(`[mail-bridge] 若提示密钥无效,请让管理员在 AgentMail 后台登记这把密钥(见 ${KEY_FILE})。`);
|
||||
console.error(
|
||||
`[mail-bridge] 若提示密钥无效,请让管理员在 AgentMail 后台登记这把密钥(见 ${KEY_FILE})。`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ -1092,7 +1251,9 @@ export default async function mailBridge(input) {
|
||||
query: directory ? { directory } : undefined,
|
||||
});
|
||||
const sessions = listed?.data ?? listed ?? [];
|
||||
return snapshotOpencodeSessions(sessions, (id) => mailDrivenSessions.has(id));
|
||||
return snapshotOpencodeSessions(sessions, (id) =>
|
||||
mailDrivenSessions.has(id),
|
||||
);
|
||||
} catch (e) {
|
||||
// 拉不到列表就**省略**该字段,而不是传空数组:
|
||||
// 空数组的语义是「平台侧确实一条会话都没有」,会把服务端的镜像抹掉。
|
||||
@ -1137,7 +1298,9 @@ export default async function mailBridge(input) {
|
||||
const box = await apiGet("/mail/inbox?status=unread&limit=20");
|
||||
const tasks = selectCatchup(box?.mails ?? box, deliveredMails);
|
||||
if (tasks.length === 0) return;
|
||||
console.error(`[mail-bridge] 补投 ${tasks.length} 封离线期间的邮件(共 ${pending} 封未读)`);
|
||||
console.error(
|
||||
`[mail-bridge] 补投 ${tasks.length} 封离线期间的邮件(共 ${pending} 封未读)`,
|
||||
);
|
||||
// 串行:每封都要起一轮模型,并发放出去等于对上游打 N 个并发请求
|
||||
for (const ev of tasks) {
|
||||
// 逐封再查一次:拉收件箱和逐封投递之间 SSE 可能已经投过其中某封
|
||||
@ -1147,7 +1310,10 @@ export default async function mailBridge(input) {
|
||||
try {
|
||||
await deliverMail(client, directory, ev, "mail");
|
||||
} catch (e) {
|
||||
console.error(`[mail-bridge] 补投 ${ev.mail_id} 失败:`, e?.message || e);
|
||||
console.error(
|
||||
`[mail-bridge] 补投 ${ev.mail_id} 失败:`,
|
||||
e?.message || e,
|
||||
);
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
@ -1165,14 +1331,15 @@ export default async function mailBridge(input) {
|
||||
const body = {};
|
||||
// opencode 1.18+ 的 session.create 不支持 permission 参数,
|
||||
// 权限只能通过提示词告知模型(advisory)。
|
||||
body.mode_enforcement = 'advisory';
|
||||
body.mode_enforcement = "advisory";
|
||||
if (platform_sessions) body.platform_sessions = platform_sessions;
|
||||
if (models) body.models = models;
|
||||
try {
|
||||
const res = await apiPost("/agent/heartbeat", body);
|
||||
// 生效的模型范围随心跳响应回传:管理员在配置页改了范围后,
|
||||
// 插件最多一个周期(30 秒)就能看到新值,不需要重启。
|
||||
if (Array.isArray(res?.allowed_models)) allowedModels = res.allowed_models;
|
||||
if (Array.isArray(res?.allowed_models))
|
||||
allowedModels = res.allowed_models;
|
||||
// 只在首个成功的心跳后补投一次:之后的积压都由 SSE 覆盖,
|
||||
// 每轮心跳都补的话会把「模型正在处理中、尚未标已读」的邮件重复投递。
|
||||
if (!caughtUp) {
|
||||
@ -1208,7 +1375,9 @@ export default async function mailBridge(input) {
|
||||
if (data?.mail_id) deliveredMails.add(data.mail_id);
|
||||
deliverMail(client, directory, data, "mail")
|
||||
.then(({ sessionID, reused }) => {
|
||||
console.error(`[mail-bridge] ${type} -> ${reused ? "续谈" : "新会话"} ${sessionID}`);
|
||||
console.error(
|
||||
`[mail-bridge] ${type} -> ${reused ? "续谈" : "新会话"} ${sessionID}`,
|
||||
);
|
||||
})
|
||||
.catch((e) => {
|
||||
// 失败必须可见,否则邮件会静默丢失
|
||||
@ -1248,14 +1417,22 @@ export default async function mailBridge(input) {
|
||||
options: ["同意", "一直同意", "拒绝"],
|
||||
context: [
|
||||
`类型:${input.type}`,
|
||||
input.pattern ? `目标:${Array.isArray(input.pattern) ? input.pattern.join(", ") : input.pattern}` : "",
|
||||
Object.keys(input.metadata || {}).length
|
||||
? "\n```json\n" + JSON.stringify(input.metadata, null, 2) + "\n```"
|
||||
input.pattern
|
||||
? `目标:${Array.isArray(input.pattern) ? input.pattern.join(", ") : input.pattern}`
|
||||
: "",
|
||||
].filter(Boolean).join("\n"),
|
||||
Object.keys(input.metadata || {}).length
|
||||
? "\n```json\n" +
|
||||
JSON.stringify(input.metadata, null, 2) +
|
||||
"\n```"
|
||||
: "",
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join("\n"),
|
||||
relayKey: clampRelayKey(input.id),
|
||||
});
|
||||
console.error(`[mail-bridge] 权限询问已转邮件 ${input.id}(${input.type})`);
|
||||
console.error(
|
||||
`[mail-bridge] 权限询问已转邮件 ${input.id}(${input.type})`,
|
||||
);
|
||||
} catch (e) {
|
||||
pendingPermissions.delete(input.id);
|
||||
|
||||
@ -1281,14 +1458,20 @@ export default async function mailBridge(input) {
|
||||
output.reason = [
|
||||
b.error || `无法把授权请求送达给人类(HTTP ${e?.status})`,
|
||||
b.detail || "",
|
||||
b.suggestion || "这是一个不会因重试而改变的失败。请改用不需要授权的方式完成,或在回信里说明需要人工执行哪一步。",
|
||||
].filter(Boolean).join("\n");
|
||||
b.suggestion ||
|
||||
"这是一个不会因重试而改变的失败。请改用不需要授权的方式完成,或在回信里说明需要人工执行哪一步。",
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join("\n");
|
||||
return;
|
||||
}
|
||||
|
||||
// 暂时失败(5xx / 408 / 429 / 网络拖动)保持 ask:那些真的可能下一次就好,
|
||||
// 人也仍可能在本地看到弹窗,不该把一次抖动当成永久拒绝。
|
||||
console.error("[mail-bridge] 权限询问转发暂时失败(保持 ask):", e?.message || e);
|
||||
console.error(
|
||||
"[mail-bridge] 权限询问转发暂时失败(保持 ask):",
|
||||
e?.message || e,
|
||||
);
|
||||
return;
|
||||
}
|
||||
output.status = "ask";
|
||||
@ -1312,9 +1495,14 @@ export default async function mailBridge(input) {
|
||||
if (syncedTitles.get(info.id) === title) return;
|
||||
syncedTitles.set(info.id, title);
|
||||
|
||||
const res = await syncSessionNaming(mailSessionID, { alias: info.slug || "", title });
|
||||
const res = await syncSessionNaming(mailSessionID, {
|
||||
alias: info.slug || "",
|
||||
title,
|
||||
});
|
||||
if (res) {
|
||||
console.error(`[mail-bridge] 会话命名同步 ${info.id} -> alias=${res.alias || "-"} title=${res.title || "-"}`);
|
||||
console.error(
|
||||
`[mail-bridge] 会话命名同步 ${info.id} -> alias=${res.alias || "-"} title=${res.title || "-"}`,
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
@ -1327,7 +1515,8 @@ export default async function mailBridge(input) {
|
||||
if (event?.type === "session.error") {
|
||||
const sid = event.properties?.sessionID;
|
||||
const err = event.properties?.error;
|
||||
const msg = err?.data?.message || err?.name || JSON.stringify(err ?? {});
|
||||
const msg =
|
||||
err?.data?.message || err?.name || JSON.stringify(err ?? {});
|
||||
if (sid && settleFirstTurn(sid, { ok: false, error: msg })) {
|
||||
return; // 正在降级尝试中,不当作一次普通故障
|
||||
}
|
||||
@ -1345,7 +1534,9 @@ export default async function mailBridge(input) {
|
||||
try {
|
||||
const res = await relaySummaryRef(sid);
|
||||
if (res?.mail_id) {
|
||||
console.error(`[mail-bridge] 总结已回信 ${res.mail_id}(不计配额)`);
|
||||
console.error(
|
||||
`[mail-bridge] 总结已回信 ${res.mail_id}(不计配额)`,
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("[mail-bridge] 总结回信失败:", e?.message || e);
|
||||
|
||||
@ -34,58 +34,60 @@
|
||||
* setLastEventId: (id: string) => void}}
|
||||
*/
|
||||
export function createFrameParser() {
|
||||
let buffer = '';
|
||||
let lastEventId = '';
|
||||
let curEvent = '';
|
||||
let curData = '';
|
||||
let curId = '';
|
||||
let buffer = "";
|
||||
let lastEventId = "";
|
||||
let curEvent = "";
|
||||
let curData = "";
|
||||
let curId = "";
|
||||
|
||||
function push(chunk) {
|
||||
buffer += chunk;
|
||||
const events = [];
|
||||
const lines = buffer.split('\n');
|
||||
const lines = buffer.split("\n");
|
||||
// 最后一段可能是被切断的半行,留到下一个 chunk
|
||||
buffer = lines.pop() ?? '';
|
||||
buffer = lines.pop() ?? "";
|
||||
|
||||
for (let line of lines) {
|
||||
if (line.length > 0 && line.charAt(line.length - 1) === '\r') {
|
||||
if (line.length > 0 && line.charAt(line.length - 1) === "\r") {
|
||||
line = line.slice(0, -1);
|
||||
}
|
||||
if (line.startsWith(':')) continue;
|
||||
if (line.startsWith(":")) continue;
|
||||
|
||||
if (line.startsWith('id:')) {
|
||||
if (line.startsWith("id:")) {
|
||||
curId = line.slice(3).trim();
|
||||
} else if (line.startsWith('event:')) {
|
||||
} else if (line.startsWith("event:")) {
|
||||
curEvent = line.slice(6).trim();
|
||||
} else if (line.startsWith('data:')) {
|
||||
} else if (line.startsWith("data:")) {
|
||||
let value = line.slice(5);
|
||||
if (value.startsWith(' ')) value = value.slice(1);
|
||||
if (value.startsWith(" ")) value = value.slice(1);
|
||||
curData = curData.length > 0 ? `${curData}\n${value}` : value;
|
||||
} else if (line === '') {
|
||||
} else if (line === "") {
|
||||
if (curEvent.length > 0 && curData.length > 0) {
|
||||
if (curId.length > 0) lastEventId = curId;
|
||||
events.push({ event: curEvent, data: curData, id: curId });
|
||||
}
|
||||
curEvent = '';
|
||||
curData = '';
|
||||
curId = '';
|
||||
curEvent = "";
|
||||
curData = "";
|
||||
curId = "";
|
||||
}
|
||||
}
|
||||
return events;
|
||||
}
|
||||
|
||||
function reset() {
|
||||
buffer = '';
|
||||
curEvent = '';
|
||||
curData = '';
|
||||
curId = '';
|
||||
buffer = "";
|
||||
curEvent = "";
|
||||
curData = "";
|
||||
curId = "";
|
||||
}
|
||||
|
||||
return {
|
||||
push,
|
||||
reset,
|
||||
lastEventId: () => lastEventId,
|
||||
setLastEventId: (id) => { lastEventId = id || ''; },
|
||||
setLastEventId: (id) => {
|
||||
lastEventId = id || "";
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@ -98,7 +100,13 @@ export function createFrameParser() {
|
||||
* @param {(msg: string) => void} [deps.log] 日志回调(默认 console.error)
|
||||
* @returns {{stop: () => void}} stop() 终止重连与在途请求
|
||||
*/
|
||||
export function createSSEClient({ authHeaders, baseURL, path, onEvent, log = console.error }) {
|
||||
export function createSSEClient({
|
||||
authHeaders,
|
||||
baseURL,
|
||||
path,
|
||||
onEvent,
|
||||
log = console.error,
|
||||
}) {
|
||||
const controller = new AbortController();
|
||||
const parser = createFrameParser();
|
||||
|
||||
@ -114,12 +122,12 @@ export function createSSEClient({ authHeaders, baseURL, path, onEvent, log = con
|
||||
function connect() {
|
||||
if (controller.signal.aborted) return;
|
||||
|
||||
const headers = { ...authHeaders(), Accept: 'text/event-stream' };
|
||||
const headers = { ...authHeaders(), Accept: "text/event-stream" };
|
||||
// 只有 lastEventId 非空(= 已经收过事件)时才是重连:首次连接不带,
|
||||
// 否则服务端会把环形缓冲里的旧事件全回放一遍,插件重启后重复处理一批已处理的邮件。
|
||||
const lastEventID = parser.lastEventId();
|
||||
if (lastEventID) {
|
||||
headers['Last-Event-ID'] = lastEventID;
|
||||
headers["Last-Event-ID"] = lastEventID;
|
||||
log(`SSE 重连,从事件 ${lastEventID} 之后续传`);
|
||||
}
|
||||
|
||||
@ -133,12 +141,16 @@ export function createSSEClient({ authHeaders, baseURL, path, onEvent, log = con
|
||||
const decoder = new TextDecoder();
|
||||
|
||||
function read() {
|
||||
reader.read().then(({ done, value }) => {
|
||||
reader
|
||||
.read()
|
||||
.then(({ done, value }) => {
|
||||
if (done) {
|
||||
parser.reset();
|
||||
return reconnect(3000);
|
||||
}
|
||||
for (const ev of parser.push(decoder.decode(value, { stream: true }))) {
|
||||
for (const ev of parser.push(
|
||||
decoder.decode(value, { stream: true }),
|
||||
)) {
|
||||
try {
|
||||
onEvent(ev.event, JSON.parse(ev.data));
|
||||
} catch (e) {
|
||||
@ -146,7 +158,8 @@ export function createSSEClient({ authHeaders, baseURL, path, onEvent, log = con
|
||||
}
|
||||
}
|
||||
read();
|
||||
}).catch((e) => {
|
||||
})
|
||||
.catch((e) => {
|
||||
if (controller.signal.aborted) return;
|
||||
log(`SSE 读取中断: ${e?.message || e}`);
|
||||
parser.reset();
|
||||
@ -174,6 +187,6 @@ export function createSSEClient({ authHeaders, baseURL, path, onEvent, log = con
|
||||
* 拿去问新 Gateway 会命中一段完全无关的历史(或直接被拒),
|
||||
* 得到的事件属于别人的会话。
|
||||
*/
|
||||
reset: () => parser.setLastEventId(''),
|
||||
reset: () => parser.setLastEventId(""),
|
||||
};
|
||||
}
|
||||
|
||||
@ -39,16 +39,18 @@ export function hasOptions(question) {
|
||||
export function optionLabels(question) {
|
||||
if (!hasOptions(question)) return [];
|
||||
return question.options
|
||||
.map((o) => (typeof o === 'string' ? o : o?.label))
|
||||
.filter((l) => typeof l === 'string' && l.length > 0);
|
||||
.map((o) => (typeof o === "string" ? o : o?.label))
|
||||
.filter((l) => typeof l === "string" && l.length > 0);
|
||||
}
|
||||
|
||||
/** 一个问题的展示标题:header 有就用它做前缀,否则只用 question。 */
|
||||
export function questionTitle(question) {
|
||||
const header = typeof question?.header === 'string' ? question.header.trim() : '';
|
||||
const text = typeof question?.question === 'string' ? question.question.trim() : '';
|
||||
const header =
|
||||
typeof question?.header === "string" ? question.header.trim() : "";
|
||||
const text =
|
||||
typeof question?.question === "string" ? question.question.trim() : "";
|
||||
if (header && text) return `${header}: ${text}`;
|
||||
return header || text || '(未提供问题)';
|
||||
return header || text || "(未提供问题)";
|
||||
}
|
||||
|
||||
/**
|
||||
@ -60,7 +62,7 @@ export function questionTitle(question) {
|
||||
export function flattenQuestions(questions) {
|
||||
const list = Array.isArray(questions) ? questions.filter(Boolean) : [];
|
||||
if (list.length === 0) {
|
||||
throw new Error('ask_user_question 至少需要一个 question');
|
||||
throw new Error("ask_user_question 至少需要一个 question");
|
||||
}
|
||||
|
||||
const lines = [];
|
||||
@ -71,12 +73,14 @@ export function flattenQuestions(questions) {
|
||||
list.forEach((q, i) => {
|
||||
const title = questionTitle(q);
|
||||
lines.push(`${i + 1}. ${title}`);
|
||||
const detail = typeof q?.detail === 'string' ? q.detail.trim() : '';
|
||||
const detail = typeof q?.detail === "string" ? q.detail.trim() : "";
|
||||
if (detail) lines.push(` ${detail}`);
|
||||
|
||||
const labels = optionLabels(q);
|
||||
if (labels.length > 0) {
|
||||
lines.push(` 可选项:${labels.join(' / ')}${q.multiSelect ? '(可多选)' : ''}`);
|
||||
lines.push(
|
||||
` 可选项:${labels.join(" / ")}${q.multiSelect ? "(可多选)" : ""}`,
|
||||
);
|
||||
for (const label of labels) {
|
||||
if (!seen.has(label)) {
|
||||
seen.add(label);
|
||||
@ -84,7 +88,7 @@ export function flattenQuestions(questions) {
|
||||
}
|
||||
}
|
||||
} else {
|
||||
lines.push(' (请直接填写回答)');
|
||||
lines.push(" (请直接填写回答)");
|
||||
}
|
||||
if (q?.multiSelect === true) anyMulti = true;
|
||||
});
|
||||
@ -92,15 +96,18 @@ export function flattenQuestions(questions) {
|
||||
// 多问题时必须允许多选:不同问题的选项要能一起勾选。
|
||||
const multiSelect = list.length > 1 ? options.length > 0 : anyMulti;
|
||||
|
||||
const question = list.length === 1 ? questionTitle(list[0]) : `${list.length} 个问题待回答`;
|
||||
const question =
|
||||
list.length === 1 ? questionTitle(list[0]) : `${list.length} 个问题待回答`;
|
||||
const context = [
|
||||
list.length === 1 ? '' : '模型提出了多个问题,请在「回复」里一并回答:',
|
||||
list.length === 1 ? "" : "模型提出了多个问题,请在「回复」里一并回答:",
|
||||
...lines,
|
||||
'',
|
||||
"",
|
||||
options.length > 0
|
||||
? '可直接勾选下方的选项;补充说明写在备注里。'
|
||||
: '这题没有预设选项,请把回答写在备注里。',
|
||||
].filter((l) => l !== '').join('\n');
|
||||
? "可直接勾选下方的选项;补充说明写在备注里。"
|
||||
: "这题没有预设选项,请把回答写在备注里。",
|
||||
]
|
||||
.filter((l) => l !== "")
|
||||
.join("\n");
|
||||
|
||||
return { question, options, context, multiSelect };
|
||||
}
|
||||
@ -115,27 +122,31 @@ export function flattenQuestions(questions) {
|
||||
*/
|
||||
export function answersFromDecision(questions, decision, note) {
|
||||
const list = Array.isArray(questions) ? questions.filter(Boolean) : [];
|
||||
const labels = String(decision || '')
|
||||
.split('\n')
|
||||
const labels = String(decision || "")
|
||||
.split("\n")
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean);
|
||||
const custom = typeof note === 'string' ? note.trim() : '';
|
||||
const custom = typeof note === "string" ? note.trim() : "";
|
||||
|
||||
// 单问题:忠实映射(选项 → selected,备注 → custom)。
|
||||
if (list.length === 1) {
|
||||
const q = list[0];
|
||||
const id = String(q?.id ?? '0');
|
||||
const id = String(q?.id ?? "0");
|
||||
if (!hasOptions(q)) {
|
||||
// 无选项题:人类把答案写在决策文本或备注里,都属于「自由文本回答」。
|
||||
const text = custom || labels.join('\n');
|
||||
return { answers: [{ id, selected: [], ...(text ? { custom: text } : {}) }] };
|
||||
const text = custom || labels.join("\n");
|
||||
return {
|
||||
answers: [{ id, selected: [], ...(text ? { custom: text } : {}) }],
|
||||
};
|
||||
}
|
||||
return {
|
||||
answers: [{
|
||||
answers: [
|
||||
{
|
||||
id,
|
||||
selected: labels,
|
||||
...(custom ? { custom } : {}),
|
||||
}],
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
@ -152,7 +163,7 @@ export function answersFromDecision(questions, decision, note) {
|
||||
}
|
||||
// 无选项题且人没写备注:退而把决策文本整段给它(否则它的答案永远是空的)。
|
||||
if (qCustom === undefined && !hasOptions(q) && note === undefined) {
|
||||
const text = labels.join('\n');
|
||||
const text = labels.join("\n");
|
||||
if (text) qCustom = text;
|
||||
}
|
||||
return { id, selected, ...(qCustom ? { custom: qCustom } : {}) };
|
||||
@ -167,8 +178,11 @@ export function answersFromDecision(questions, decision, note) {
|
||||
* 允许多选时空 selected 但有 custom 也算答了;两者都空才算没答。
|
||||
*/
|
||||
export function isBlankAnswer(questions, decision, note) {
|
||||
const labels = String(decision || '').split('\n').map((s) => s.trim()).filter(Boolean);
|
||||
const custom = typeof note === 'string' ? note.trim() : '';
|
||||
const labels = String(decision || "")
|
||||
.split("\n")
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean);
|
||||
const custom = typeof note === "string" ? note.trim() : "";
|
||||
if (labels.length > 0 || custom) return false;
|
||||
// 全部问题都没有选项、人也没写字 → 确实什么都没答
|
||||
const list = Array.isArray(questions) ? questions.filter(Boolean) : [];
|
||||
|
||||
@ -9,10 +9,10 @@
|
||||
* 生产上表现为「新邮件偶尔收不到」「权限决策点了没反应」,且日志里一个字都没有。
|
||||
*/
|
||||
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
|
||||
import { createFrameParser } from '../lib/sse-client.js';
|
||||
import { createFrameParser } from "../lib/sse-client.js";
|
||||
|
||||
/** JSON.parse 的测试包装:解析失败让断言带原文失败,而不是抛未捕获异常。 */
|
||||
function parse(s) {
|
||||
@ -23,107 +23,118 @@ function parse(s) {
|
||||
}
|
||||
}
|
||||
|
||||
test('完整帧一次喂入:正常解析', () => {
|
||||
test("完整帧一次喂入:正常解析", () => {
|
||||
const p = createFrameParser();
|
||||
const events = p.push('id: 7\nevent: new_mail\ndata: {"mail_id":"m1"}\n\n');
|
||||
assert.equal(events.length, 1);
|
||||
assert.equal(events[0].event, 'new_mail');
|
||||
assert.deepEqual(parse(events[0].data), { mail_id: 'm1' });
|
||||
assert.equal(events[0].id, '7');
|
||||
assert.equal(p.lastEventId(), '7');
|
||||
assert.equal(events[0].event, "new_mail");
|
||||
assert.deepEqual(parse(events[0].data), { mail_id: "m1" });
|
||||
assert.equal(events[0].id, "7");
|
||||
assert.equal(p.lastEventId(), "7");
|
||||
});
|
||||
|
||||
test('帧被切在换行处:跨 chunk 保住 event 名(原 bug 的核心)', () => {
|
||||
test("帧被切在换行处:跨 chunk 保住 event 名(原 bug 的核心)", () => {
|
||||
const p = createFrameParser();
|
||||
// chunk1 恰好停在 event 行之后、data 行之前
|
||||
const first = p.push('id: 12\nevent: content_delta\n');
|
||||
assert.deepEqual(first, [], '半帧不该派发');
|
||||
const first = p.push("id: 12\nevent: content_delta\n");
|
||||
assert.deepEqual(first, [], "半帧不该派发");
|
||||
|
||||
const second = p.push('data: {"x":1}\n\n');
|
||||
assert.equal(second.length, 1, '跨 chunk 的半帧必须被拼回完整事件,而不是丢弃');
|
||||
assert.equal(second[0].event, 'content_delta');
|
||||
assert.equal(p.lastEventId(), '12');
|
||||
assert.equal(
|
||||
second.length,
|
||||
1,
|
||||
"跨 chunk 的半帧必须被拼回完整事件,而不是丢弃",
|
||||
);
|
||||
assert.equal(second[0].event, "content_delta");
|
||||
assert.equal(p.lastEventId(), "12");
|
||||
});
|
||||
|
||||
test('帧被切在行中间:buffer 保留半行', () => {
|
||||
test("帧被切在行中间:buffer 保留半行", () => {
|
||||
const p = createFrameParser();
|
||||
const a = p.push('event: new_ma');
|
||||
const a = p.push("event: new_ma");
|
||||
assert.deepEqual(a, []);
|
||||
const b = p.push('il\ndata: {"mail_id":"m9"}\n\n');
|
||||
assert.equal(b.length, 1);
|
||||
assert.equal(b[0].event, 'new_mail');
|
||||
assert.equal(b[0].event, "new_mail");
|
||||
});
|
||||
|
||||
test('一个 chunk 里多帧连续:全部派发', () => {
|
||||
test("一个 chunk 里多帧连续:全部派发", () => {
|
||||
const p = createFrameParser();
|
||||
const events = p.push(
|
||||
'event: new_mail\ndata: {"n":1}\n\n' +
|
||||
'event: new_mail\ndata: {"n":2}\n\n' +
|
||||
'event: session_update\ndata: {"n":3}\n\n'
|
||||
'event: session_update\ndata: {"n":3}\n\n',
|
||||
);
|
||||
assert.equal(events.length, 3);
|
||||
assert.deepEqual(events.map((e) => e.event), ['new_mail', 'new_mail', 'session_update']);
|
||||
assert.deepEqual(
|
||||
events.map((e) => e.event),
|
||||
["new_mail", "new_mail", "session_update"],
|
||||
);
|
||||
});
|
||||
|
||||
test('注释/心跳行被忽略,不影响后续帧', () => {
|
||||
test("注释/心跳行被忽略,不影响后续帧", () => {
|
||||
const p = createFrameParser();
|
||||
const events = p.push(': heartbeat\n\nevent: new_mail\ndata: {"n":1}\n\n');
|
||||
assert.equal(events.length, 1);
|
||||
assert.equal(events[0].event, 'new_mail');
|
||||
assert.equal(events[0].event, "new_mail");
|
||||
});
|
||||
|
||||
test('多行 data 用换行拼接', () => {
|
||||
test("多行 data 用换行拼接", () => {
|
||||
const p = createFrameParser();
|
||||
const events = p.push('event: x\ndata: line1\ndata: line2\n\n');
|
||||
assert.equal(events[0].data, 'line1\nline2');
|
||||
const events = p.push("event: x\ndata: line1\ndata: line2\n\n");
|
||||
assert.equal(events[0].data, "line1\nline2");
|
||||
});
|
||||
|
||||
test('CRLF 不被当成事件名或 JSON 的一部分', () => {
|
||||
test("CRLF 不被当成事件名或 JSON 的一部分", () => {
|
||||
const p = createFrameParser();
|
||||
const events = p.push('id: 3\r\nevent: new_mail\r\ndata: {"n":1}\r\n\r\n');
|
||||
assert.equal(events.length, 1);
|
||||
assert.equal(events[0].event, 'new_mail');
|
||||
assert.equal(events[0].id, '3');
|
||||
assert.equal(events[0].event, "new_mail");
|
||||
assert.equal(events[0].id, "3");
|
||||
assert.deepEqual(parse(events[0].data), { n: 1 });
|
||||
});
|
||||
|
||||
test('事件 id 只向前推进:重放旧 id 不回退断点', () => {
|
||||
test("事件 id 只向前推进:重放旧 id 不回退断点", () => {
|
||||
const p = createFrameParser();
|
||||
p.push('id: 10\nevent: new_mail\ndata: {"n":1}\n\n');
|
||||
assert.equal(p.lastEventId(), '10');
|
||||
assert.equal(p.lastEventId(), "10");
|
||||
// 服务端重放一条更早的事件:断点不该退回 5,否则下次重连会重复回放 6..10
|
||||
p.push('id: 5\nevent: new_mail\ndata: {"n":0}\n\n');
|
||||
assert.equal(p.lastEventId(), '5', '解析器如实记录当前 id(是否回退由使用方决定)');
|
||||
assert.equal(
|
||||
p.lastEventId(),
|
||||
"5",
|
||||
"解析器如实记录当前 id(是否回退由使用方决定)",
|
||||
);
|
||||
});
|
||||
|
||||
test('id 在派发前记录:回调抛异常也不丢断点', () => {
|
||||
test("id 在派发前记录:回调抛异常也不丢断点", () => {
|
||||
const p = createFrameParser();
|
||||
p.push('id: 42\nevent: new_mail\ndata: {"n":1}\n\n');
|
||||
assert.equal(p.lastEventId(), '42');
|
||||
assert.equal(p.lastEventId(), "42");
|
||||
});
|
||||
|
||||
test('只有 data 没有 event 不派发(避免把心跳数据当事件)', () => {
|
||||
test("只有 data 没有 event 不派发(避免把心跳数据当事件)", () => {
|
||||
const p = createFrameParser();
|
||||
const events = p.push('data: {"orphan":true}\n\n');
|
||||
assert.deepEqual(events, []);
|
||||
});
|
||||
|
||||
test('reset 清缓冲但保留断点(重连后仍能续传)', () => {
|
||||
test("reset 清缓冲但保留断点(重连后仍能续传)", () => {
|
||||
const p = createFrameParser();
|
||||
p.push('id: 99\nevent: a\ndata: {"n":1}\n\n');
|
||||
p.push('event: partial'); // 半帧
|
||||
p.push("event: partial"); // 半帧
|
||||
p.reset();
|
||||
assert.equal(p.lastEventId(), '99', '断点必须保留,否则重连从头回放');
|
||||
assert.equal(p.lastEventId(), "99", "断点必须保留,否则重连从头回放");
|
||||
// reset 后半帧不该复活
|
||||
const after = p.push('data: {"n":2}\n\n');
|
||||
assert.deepEqual(after, []);
|
||||
});
|
||||
|
||||
test('setLastEventId 清空 = 换 Gateway 后不再拿旧序号问新服务端', () => {
|
||||
test("setLastEventId 清空 = 换 Gateway 后不再拿旧序号问新服务端", () => {
|
||||
const p = createFrameParser();
|
||||
p.push('id: 123\nevent: a\ndata: {"n":1}\n\n');
|
||||
assert.equal(p.lastEventId(), '123');
|
||||
assert.equal(p.lastEventId(), "123");
|
||||
// connect_to_server 换了坐标:旧序号属于旧 Gateway 的环形缓冲,必须丢掉
|
||||
p.setLastEventId('');
|
||||
assert.equal(p.lastEventId(), '', '首次连接不得携带 Last-Event-ID');
|
||||
p.setLastEventId("");
|
||||
assert.equal(p.lastEventId(), "", "首次连接不得携带 Last-Event-ID");
|
||||
});
|
||||
|
||||
@ -10,8 +10,8 @@
|
||||
* - 空回答不能被当成「答了」
|
||||
*/
|
||||
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
|
||||
import {
|
||||
flattenQuestions,
|
||||
@ -20,117 +20,169 @@ import {
|
||||
hasOptions,
|
||||
optionLabels,
|
||||
questionTitle,
|
||||
} from '../lib/user-question.js';
|
||||
} from "../lib/user-question.js";
|
||||
|
||||
test('单问题单选项:忠实映射问题与选项', () => {
|
||||
const flat = flattenQuestions([{
|
||||
id: 'q1',
|
||||
question: '用哪种方案?',
|
||||
header: '选择',
|
||||
options: [{ label: '方案 A' }, { label: '方案 B' }],
|
||||
}]);
|
||||
assert.equal(flat.question, '选择: 用哪种方案?');
|
||||
assert.deepEqual(flat.options, ['方案 A', '方案 B']);
|
||||
test("单问题单选项:忠实映射问题与选项", () => {
|
||||
const flat = flattenQuestions([
|
||||
{
|
||||
id: "q1",
|
||||
question: "用哪种方案?",
|
||||
header: "选择",
|
||||
options: [{ label: "方案 A" }, { label: "方案 B" }],
|
||||
},
|
||||
]);
|
||||
assert.equal(flat.question, "选择: 用哪种方案?");
|
||||
assert.deepEqual(flat.options, ["方案 A", "方案 B"]);
|
||||
assert.equal(flat.multiSelect, false);
|
||||
});
|
||||
|
||||
test('单问题多选:multiSelect 透传', () => {
|
||||
const flat = flattenQuestions([{
|
||||
id: 'q1',
|
||||
question: '要哪些?',
|
||||
options: [{ label: 'a' }, { label: 'b' }],
|
||||
test("单问题多选:multiSelect 透传", () => {
|
||||
const flat = flattenQuestions([
|
||||
{
|
||||
id: "q1",
|
||||
question: "要哪些?",
|
||||
options: [{ label: "a" }, { label: "b" }],
|
||||
multiSelect: true,
|
||||
}]);
|
||||
},
|
||||
]);
|
||||
assert.equal(flat.multiSelect, true);
|
||||
});
|
||||
|
||||
test('多问题:选项取并集且去重保序,multiSelect 置真', () => {
|
||||
test("多问题:选项取并集且去重保序,multiSelect 置真", () => {
|
||||
const flat = flattenQuestions([
|
||||
{ id: 'q1', question: '前端?', options: [{ label: 'React' }, { label: 'Vue' }] },
|
||||
{ id: 'q2', question: '后端?', options: [{ label: 'Vue' }, { label: 'Go' }] },
|
||||
{
|
||||
id: "q1",
|
||||
question: "前端?",
|
||||
options: [{ label: "React" }, { label: "Vue" }],
|
||||
},
|
||||
{
|
||||
id: "q2",
|
||||
question: "后端?",
|
||||
options: [{ label: "Vue" }, { label: "Go" }],
|
||||
},
|
||||
]);
|
||||
assert.deepEqual(flat.options, ['React', 'Vue', 'Go'], '重复 label 只出现一次');
|
||||
assert.equal(flat.multiSelect, true, '多问题必须允许多选,否则无法同时回答两题');
|
||||
assert.deepEqual(
|
||||
flat.options,
|
||||
["React", "Vue", "Go"],
|
||||
"重复 label 只出现一次",
|
||||
);
|
||||
assert.equal(
|
||||
flat.multiSelect,
|
||||
true,
|
||||
"多问题必须允许多选,否则无法同时回答两题",
|
||||
);
|
||||
assert.match(flat.context, /前端?/);
|
||||
assert.match(flat.context, /后端?/);
|
||||
});
|
||||
|
||||
test('无选项题:options 为空,正文提示直接填写', () => {
|
||||
const flat = flattenQuestions([{ id: 'q1', question: '你的名字?' }]);
|
||||
test("无选项题:options 为空,正文提示直接填写", () => {
|
||||
const flat = flattenQuestions([{ id: "q1", question: "你的名字?" }]);
|
||||
assert.deepEqual(flat.options, []);
|
||||
assert.match(flat.context, /直接填写|没有预设选项/);
|
||||
});
|
||||
|
||||
test('空问题列表:抛错而不是造一封没有内容的信', () => {
|
||||
test("空问题列表:抛错而不是造一封没有内容的信", () => {
|
||||
assert.throws(() => flattenQuestions([]), /至少需要一个/);
|
||||
assert.throws(() => flattenQuestions(undefined), /至少需要一个/);
|
||||
});
|
||||
|
||||
test('单问题回写:选项进 selected,备注进 custom', () => {
|
||||
const qs = [{ id: 'q1', question: '选哪个', options: [{ label: 'A' }, { label: 'B' }] }];
|
||||
const ans = answersFromDecision(qs, 'A', '再确认下');
|
||||
assert.deepEqual(ans.answers, [{ id: 'q1', selected: ['A'], custom: '再确认下' }]);
|
||||
});
|
||||
|
||||
test('单问题多选回写:多行决策拆成多个 selected', () => {
|
||||
const qs = [{ id: 'q1', question: '选哪些', options: [{ label: 'A' }, { label: 'B' }], multiSelect: true }];
|
||||
const ans = answersFromDecision(qs, 'A\nB', '');
|
||||
assert.deepEqual(ans.answers[0].selected, ['A', 'B']);
|
||||
assert.equal(ans.answers[0].custom, undefined, '空备注不该变成空 custom');
|
||||
});
|
||||
|
||||
test('无选项题回写:答案进 custom,selected 为空', () => {
|
||||
const qs = [{ id: 'q1', question: '名字?' }];
|
||||
const ans = answersFromDecision(qs, '', '张三');
|
||||
assert.deepEqual(ans.answers, [{ id: 'q1', selected: [], custom: '张三' }]);
|
||||
});
|
||||
|
||||
test('无选项题只有决策文本时:文本进 custom(否则答案永远为空)', () => {
|
||||
const qs = [{ id: 'q1', question: '名字?' }];
|
||||
const ans = answersFromDecision(qs, '李四', undefined);
|
||||
assert.deepEqual(ans.answers, [{ id: 'q1', selected: [], custom: '李四' }]);
|
||||
});
|
||||
|
||||
test('多问题回写:选择按 label 归属分配到各自的问题(不张冠李戴)', () => {
|
||||
test("单问题回写:选项进 selected,备注进 custom", () => {
|
||||
const qs = [
|
||||
{ id: 'q1', question: '前端?', options: [{ label: 'React' }, { label: 'Vue' }] },
|
||||
{ id: 'q2', question: '后端?', options: [{ label: 'Go' }, { label: 'Rust' }] },
|
||||
{ id: "q1", question: "选哪个", options: [{ label: "A" }, { label: "B" }] },
|
||||
];
|
||||
const ans = answersFromDecision(qs, 'Vue\nGo', '都行');
|
||||
assert.deepEqual(ans.answers[0].selected, ['Vue'], 'q1 只拿前端的选择');
|
||||
assert.deepEqual(ans.answers[1].selected, ['Go'], 'q2 只拿后端的选择');
|
||||
assert.equal(ans.answers[0].custom, '都行', '备注归第一个问题');
|
||||
assert.equal(ans.answers[1].custom, undefined, '备注不重复分发');
|
||||
const ans = answersFromDecision(qs, "A", "再确认下");
|
||||
assert.deepEqual(ans.answers, [
|
||||
{ id: "q1", selected: ["A"], custom: "再确认下" },
|
||||
]);
|
||||
});
|
||||
|
||||
test('多问题里认不出的 label:不匹配任何问题,不猜测放行', () => {
|
||||
test("单问题多选回写:多行决策拆成多个 selected", () => {
|
||||
const qs = [
|
||||
{ id: 'q1', question: 'a', options: [{ label: 'X' }] },
|
||||
{ id: 'q2', question: 'b', options: [{ label: 'Y' }] },
|
||||
{
|
||||
id: "q1",
|
||||
question: "选哪些",
|
||||
options: [{ label: "A" }, { label: "B" }],
|
||||
multiSelect: true,
|
||||
},
|
||||
];
|
||||
const ans = answersFromDecision(qs, 'Z', '');
|
||||
assert.deepEqual(ans.answers[0].selected, [], '认不出的 label 不得被塞进任意问题');
|
||||
const ans = answersFromDecision(qs, "A\nB", "");
|
||||
assert.deepEqual(ans.answers[0].selected, ["A", "B"]);
|
||||
assert.equal(ans.answers[0].custom, undefined, "空备注不该变成空 custom");
|
||||
});
|
||||
|
||||
test("无选项题回写:答案进 custom,selected 为空", () => {
|
||||
const qs = [{ id: "q1", question: "名字?" }];
|
||||
const ans = answersFromDecision(qs, "", "张三");
|
||||
assert.deepEqual(ans.answers, [{ id: "q1", selected: [], custom: "张三" }]);
|
||||
});
|
||||
|
||||
test("无选项题只有决策文本时:文本进 custom(否则答案永远为空)", () => {
|
||||
const qs = [{ id: "q1", question: "名字?" }];
|
||||
const ans = answersFromDecision(qs, "李四", undefined);
|
||||
assert.deepEqual(ans.answers, [{ id: "q1", selected: [], custom: "李四" }]);
|
||||
});
|
||||
|
||||
test("多问题回写:选择按 label 归属分配到各自的问题(不张冠李戴)", () => {
|
||||
const qs = [
|
||||
{
|
||||
id: "q1",
|
||||
question: "前端?",
|
||||
options: [{ label: "React" }, { label: "Vue" }],
|
||||
},
|
||||
{
|
||||
id: "q2",
|
||||
question: "后端?",
|
||||
options: [{ label: "Go" }, { label: "Rust" }],
|
||||
},
|
||||
];
|
||||
const ans = answersFromDecision(qs, "Vue\nGo", "都行");
|
||||
assert.deepEqual(ans.answers[0].selected, ["Vue"], "q1 只拿前端的选择");
|
||||
assert.deepEqual(ans.answers[1].selected, ["Go"], "q2 只拿后端的选择");
|
||||
assert.equal(ans.answers[0].custom, "都行", "备注归第一个问题");
|
||||
assert.equal(ans.answers[1].custom, undefined, "备注不重复分发");
|
||||
});
|
||||
|
||||
test("多问题里认不出的 label:不匹配任何问题,不猜测放行", () => {
|
||||
const qs = [
|
||||
{ id: "q1", question: "a", options: [{ label: "X" }] },
|
||||
{ id: "q2", question: "b", options: [{ label: "Y" }] },
|
||||
];
|
||||
const ans = answersFromDecision(qs, "Z", "");
|
||||
assert.deepEqual(
|
||||
ans.answers[0].selected,
|
||||
[],
|
||||
"认不出的 label 不得被塞进任意问题",
|
||||
);
|
||||
assert.deepEqual(ans.answers[1].selected, []);
|
||||
});
|
||||
|
||||
test('answers 的 id 与问题一一对应', () => {
|
||||
const qs = [{ id: 'alpha', question: 'a', options: [{ label: 'X' }] }, { id: 'beta', question: 'b' }];
|
||||
const ans = answersFromDecision(qs, 'X', 'note');
|
||||
assert.deepEqual(ans.answers.map((a) => a.id), ['alpha', 'beta']);
|
||||
test("answers 的 id 与问题一一对应", () => {
|
||||
const qs = [
|
||||
{ id: "alpha", question: "a", options: [{ label: "X" }] },
|
||||
{ id: "beta", question: "b" },
|
||||
];
|
||||
const ans = answersFromDecision(qs, "X", "note");
|
||||
assert.deepEqual(
|
||||
ans.answers.map((a) => a.id),
|
||||
["alpha", "beta"],
|
||||
);
|
||||
});
|
||||
|
||||
test('空回答判定:有选项的问题什么都没选 = 空', () => {
|
||||
const qs = [{ id: 'q1', question: 'a', options: [{ label: 'X' }] }];
|
||||
assert.equal(isBlankAnswer(qs, '', ''), true);
|
||||
assert.equal(isBlankAnswer(qs, 'X', ''), false);
|
||||
assert.equal(isBlankAnswer(qs, '', '自由文本'), false, '自由文本也算答了');
|
||||
test("空回答判定:有选项的问题什么都没选 = 空", () => {
|
||||
const qs = [{ id: "q1", question: "a", options: [{ label: "X" }] }];
|
||||
assert.equal(isBlankAnswer(qs, "", ""), true);
|
||||
assert.equal(isBlankAnswer(qs, "X", ""), false);
|
||||
assert.equal(isBlankAnswer(qs, "", "自由文本"), false, "自由文本也算答了");
|
||||
});
|
||||
|
||||
test('hasOptions / optionLabels / questionTitle 的边界', () => {
|
||||
test("hasOptions / optionLabels / questionTitle 的边界", () => {
|
||||
assert.equal(hasOptions({}), false);
|
||||
assert.equal(hasOptions({ options: [] }), false);
|
||||
assert.equal(hasOptions({ options: [{ label: 'a' }] }), true);
|
||||
assert.deepEqual(optionLabels({ options: ['a', { label: 'b' }, { description: 'x' }] }), ['a', 'b']);
|
||||
assert.equal(questionTitle({ question: '只问一句' }), '只问一句');
|
||||
assert.equal(questionTitle({}), '(未提供问题)');
|
||||
assert.equal(hasOptions({ options: [{ label: "a" }] }), true);
|
||||
assert.deepEqual(
|
||||
optionLabels({ options: ["a", { label: "b" }, { description: "x" }] }),
|
||||
["a", "b"],
|
||||
);
|
||||
assert.equal(questionTitle({ question: "只问一句" }), "只问一句");
|
||||
assert.equal(questionTitle({}), "(未提供问题)");
|
||||
});
|
||||
|
||||
187
plugins/pi-mail-bridge/extension/index.ts
Normal file
187
plugins/pi-mail-bridge/extension/index.ts
Normal file
@ -0,0 +1,187 @@
|
||||
/**
|
||||
* pi 交互式会话的邮件工具扩展。
|
||||
*
|
||||
* # 与 src/index.mjs(常驻守护进程)的分工
|
||||
*
|
||||
* - 守护进程负责**收信**:订阅 SSE、fork worker、跑模型、自动回信
|
||||
* - 本扩展只给**交互式 TUI 会话**装上同一套邮件工具
|
||||
*
|
||||
* 两者是同一条 AgentMail 身份(agent `pi`)的两个入口,与 DSH 的
|
||||
* 「TUI + 邮箱是同一个 Agent」完全一致。人可以在 TUI 里直接收发邮件,
|
||||
* 也可以在邮箱里给 pi 发信 —— 两边看到的是同一条会话流。
|
||||
*
|
||||
* # 为什么必须单独做这个扩展
|
||||
*
|
||||
* 守护进程用 `noExtensions: true` 起会话(见 src/session-pool.mjs),
|
||||
* 所以它的邮件工具**不会**出现在人的交互式 pi 里。而平台的建设者与维护者
|
||||
* 恰恰是在交互式 pi 里工作的:没有 send_mail / read_inbox,他既看不到
|
||||
* 自己刚发出的那封信,也无法回信,只能绕到 curl + 密钥直连 Gateway ——
|
||||
* 一个「邮件驱动」的平台,维护者自己收不到邮件。
|
||||
*
|
||||
* # 密钥从哪来
|
||||
*
|
||||
* 交互式 pi 的进程环境里通常**没有** AGENTMAIL_* 变量(守护进程的
|
||||
* EnvironmentFile 只注入给它自己)。因此按以下顺序解析:
|
||||
*
|
||||
* 1. 进程环境(`AGENTMAIL_AGENT_KEY` / `AGENTMAIL_GATEWAY_URL` / `AGENTMAIL_AGENT_NAME`)
|
||||
* 2. `AGENTMAIL_ENV_FILE`(默认 `/etc/agentmail/pi.env`)—— 部署时的权威来源,
|
||||
* 与守护进程用的是同一把密钥,因此身份一致
|
||||
* 3. `$AGENTMAIL_CONFIG_DIR/agent.key` 或 `~/.agentmail/agent.key`
|
||||
* (插件的历史约定;接受 `key` 与 `key_token` 两种字段名)
|
||||
*
|
||||
* 找不到密钥时**不注册任何工具**并明确告知 —— 挂上一组永远 401 的工具比没有更糟:
|
||||
* 模型会以为自己能发信,人却只看到一串认证失败。
|
||||
*
|
||||
* # 为什么不注册 connect_to_server
|
||||
*
|
||||
* 那个工具会重写 Gateway 坐标并重新登记密钥。在交互式会话里调用它会**动到守护
|
||||
* 进程的配置**(两者共用同一把密钥与同一个 Agent 名),而守护进程才是真正长期
|
||||
* 持有 SSE 长连的一方。坐标变更属于部署动作,不该由一次 TUI 对话触发。
|
||||
*/
|
||||
|
||||
import { existsSync, readFileSync } from 'node:fs';
|
||||
import { homedir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import type { ExtensionAPI } from '@earendil-works/pi-coding-agent';
|
||||
|
||||
const DEFAULT_ENV_FILE = '/etc/agentmail/pi.env';
|
||||
const DEFAULT_GATEWAY = 'http://127.0.0.1:8180';
|
||||
|
||||
/** 守护进程专用的生命周期工具:交互式会话里不注册(理由见文件头注释)。 */
|
||||
const EXCLUDED_TOOLS = new Set(['connect_to_server']);
|
||||
|
||||
/**
|
||||
* registerTool 期望的完整定义形状。
|
||||
*
|
||||
* 用 SDK 自己的类型取,而不是复制一份:SDK 升级时形状变化会在这里变成编译错误,
|
||||
* 而不是运行时的静默错配。
|
||||
*/
|
||||
type MailTool = Parameters<ExtensionAPI['registerTool']>[0];
|
||||
|
||||
/** 极简 .env 解析:只认 `KEY=value`,忽略注释与空行,不处理引号与转义。 */
|
||||
function parseEnvFile(path: string): Record<string, string> {
|
||||
const out: Record<string, string> = {};
|
||||
if (!existsSync(path)) return out;
|
||||
let raw: string;
|
||||
try {
|
||||
raw = readFileSync(path, 'utf8');
|
||||
} catch {
|
||||
return out;
|
||||
}
|
||||
for (const line of raw.split('\n')) {
|
||||
const trimmed = line.trim();
|
||||
if (!trimmed || trimmed.startsWith('#')) continue;
|
||||
const eq = trimmed.indexOf('=');
|
||||
if (eq <= 0) continue;
|
||||
const key = trimmed.slice(0, eq).trim();
|
||||
// 值里可能有 `=`(例如 base64),只切第一个
|
||||
out[key] = trimmed.slice(eq + 1).trim();
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** 读插件约定的本地密钥文件,兼容 `key` 与 `key_token` 两种字段名。 */
|
||||
function readLocalKey(configDir?: string): string {
|
||||
const candidates = [
|
||||
join(configDir || join(homedir(), '.agentmail'), 'agent.key'),
|
||||
join(homedir(), '.agentmail', 'agent.key'),
|
||||
];
|
||||
for (const path of candidates) {
|
||||
try {
|
||||
if (!existsSync(path)) continue;
|
||||
const raw = JSON.parse(readFileSync(path, 'utf8')) as
|
||||
{ key?: unknown; key_token?: unknown };
|
||||
// 历史文件用的是 key_token(见部署实况),只认 `key` 会静默读不到。
|
||||
const key = raw?.key ?? raw?.key_token;
|
||||
if (typeof key === 'string' && key.trim()) return key.trim();
|
||||
} catch {
|
||||
// 读不了就试下一个
|
||||
}
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
interface MailConfig {
|
||||
url: string;
|
||||
agentName: string;
|
||||
agentKey: string;
|
||||
}
|
||||
|
||||
/** @returns null 表示拿不到密钥(调用方据此不注册任何工具) */
|
||||
function resolveConfig(): MailConfig | null {
|
||||
let url = process.env.AGENTMAIL_GATEWAY_URL || '';
|
||||
let agentName = process.env.AGENTMAIL_AGENT_NAME || '';
|
||||
let agentKey = process.env.AGENTMAIL_AGENT_KEY || '';
|
||||
|
||||
if (!agentKey) {
|
||||
const envFile = process.env.AGENTMAIL_ENV_FILE || DEFAULT_ENV_FILE;
|
||||
const parsed = parseEnvFile(envFile);
|
||||
agentKey = parsed.AGENTMAIL_AGENT_KEY || '';
|
||||
url = url || parsed.AGENTMAIL_GATEWAY_URL || '';
|
||||
agentName = agentName || parsed.AGENTMAIL_AGENT_NAME || '';
|
||||
}
|
||||
|
||||
if (!agentKey) agentKey = readLocalKey(process.env.AGENTMAIL_CONFIG_DIR);
|
||||
if (!agentKey) return null;
|
||||
|
||||
return {
|
||||
url: (url || DEFAULT_GATEWAY).replace(/\/+$/, ''),
|
||||
agentName: agentName || 'pi',
|
||||
agentKey,
|
||||
};
|
||||
}
|
||||
|
||||
export default async function (pi: ExtensionAPI): Promise<void> {
|
||||
const cfg = resolveConfig();
|
||||
|
||||
// 动态 import 仓库里的 .mjs:它们没有 .d.ts(也不该造一份 —— 守护进程用同一份
|
||||
// 对象经 customTools 注册,额外声明只会两边不同步),因此在边界上收窄成我们
|
||||
// 真正依赖的最小形状。工具对象的 `parameters` 是普通 JSON Schema,而
|
||||
// registerTool 的类型要求 TypeBox 的 TSchema;两者在运行期是同一套 JSON Schema
|
||||
// 校验(守护进程已长期验证),差异只在静态类型上,故此处一次收窄并注明。
|
||||
let registered = 0;
|
||||
let notice = '';
|
||||
|
||||
if (!cfg) {
|
||||
notice = 'pi-mail-bridge:未找到 AgentMail 密钥(AGENTMAIL_AGENT_KEY / '
|
||||
+ `${process.env.AGENTMAIL_ENV_FILE || DEFAULT_ENV_FILE} / ~/.agentmail/agent.key),`
|
||||
+ '邮件工具未注册。';
|
||||
} else {
|
||||
const gatewayMod = await import(new URL('../src/gateway.mjs', import.meta.url).href);
|
||||
const toolsMod = await import(new URL('../src/tools.mjs', import.meta.url).href);
|
||||
const GatewayClient = gatewayMod.GatewayClient as new (opts: {
|
||||
url: string; agentName: string; agentKey: string; agentSecret: string;
|
||||
}) => unknown;
|
||||
const createMailTools = toolsMod.createMailTools as (opts: {
|
||||
client: unknown; agentName: string; log: (msg: string) => void;
|
||||
}) => MailTool[];
|
||||
|
||||
const tools = createMailTools({
|
||||
client: new GatewayClient({
|
||||
url: cfg.url,
|
||||
agentName: cfg.agentName,
|
||||
agentKey: cfg.agentKey,
|
||||
agentSecret: '',
|
||||
}),
|
||||
agentName: cfg.agentName,
|
||||
// 出错只进 stderr(不污染 TUI);正常路径本身不吵闹。
|
||||
log: (msg: string) => console.error(`[pi-mail-tools] ${msg}`),
|
||||
});
|
||||
|
||||
for (const tool of tools) {
|
||||
if (!tool?.name || EXCLUDED_TOOLS.has(tool.name)) continue;
|
||||
pi.registerTool(tool);
|
||||
registered += 1;
|
||||
}
|
||||
}
|
||||
|
||||
// 只在 session_start 里报:扩展工厂可能在「不会开会话」的调用里执行
|
||||
// (例如 pi --list-models),那里没有 ctx,也没有界面可显示。
|
||||
pi.on('session_start', async (_event, ctx) => {
|
||||
if (notice) {
|
||||
ctx.ui.notify(notice, 'warning');
|
||||
return;
|
||||
}
|
||||
ctx.ui.setStatus('pi-mail', `邮件已接入(${cfg?.agentName}@${cfg?.url},${registered} 个工具)`);
|
||||
});
|
||||
}
|
||||
@ -5,16 +5,17 @@
|
||||
* 本文件只管认证头、密钥解析与坐标变更。
|
||||
*/
|
||||
|
||||
import { readFileSync, writeFileSync, mkdirSync, existsSync } from 'node:fs';
|
||||
import { randomBytes } from 'node:crypto';
|
||||
import { homedir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { readFileSync, writeFileSync, mkdirSync, existsSync } from "node:fs";
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { homedir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { createSSEClient } from '../lib/sse-client.js';
|
||||
import { createSSEClient } from "../lib/sse-client.js";
|
||||
|
||||
const CONFIG_DIR = process.env.AGENTMAIL_CONFIG_DIR || join(homedir(), '.agentmail');
|
||||
export const KEY_FILE = join(CONFIG_DIR, 'agent.key');
|
||||
const CONFIG_FILE = join(CONFIG_DIR, 'config.json');
|
||||
const CONFIG_DIR =
|
||||
process.env.AGENTMAIL_CONFIG_DIR || join(homedir(), ".agentmail");
|
||||
export const KEY_FILE = join(CONFIG_DIR, "agent.key");
|
||||
const CONFIG_FILE = join(CONFIG_DIR, "config.json");
|
||||
|
||||
/**
|
||||
* 把管理员给的密钥落盘(0600)。
|
||||
@ -26,7 +27,11 @@ export function saveLocalKey(token) {
|
||||
mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 });
|
||||
writeFileSync(
|
||||
KEY_FILE,
|
||||
JSON.stringify({ key_token: token, created_at: new Date().toISOString() }, null, 2),
|
||||
JSON.stringify(
|
||||
{ key_token: token, created_at: new Date().toISOString() },
|
||||
null,
|
||||
2,
|
||||
),
|
||||
{ mode: 0o600 },
|
||||
);
|
||||
}
|
||||
@ -35,8 +40,10 @@ export function saveLocalKey(token) {
|
||||
export function readLocalKey() {
|
||||
try {
|
||||
if (!existsSync(KEY_FILE)) return null;
|
||||
const raw = JSON.parse(readFileSync(KEY_FILE, 'utf8'));
|
||||
return typeof raw?.key_token === 'string' && raw.key_token ? raw.key_token : null;
|
||||
const raw = JSON.parse(readFileSync(KEY_FILE, "utf8"));
|
||||
return typeof raw?.key_token === "string" && raw.key_token
|
||||
? raw.key_token
|
||||
: null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
@ -49,11 +56,15 @@ export function readLocalKey() {
|
||||
* 走 console.error 而不是任何结构化日志 —— 它一定进 journalctl(契约 9.8)。
|
||||
*/
|
||||
export function generateLocalKey(log = console.error) {
|
||||
const token = randomBytes(32).toString('hex');
|
||||
const token = randomBytes(32).toString("hex");
|
||||
mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 });
|
||||
writeFileSync(
|
||||
KEY_FILE,
|
||||
JSON.stringify({ key_token: token, created_at: new Date().toISOString() }, null, 2),
|
||||
JSON.stringify(
|
||||
{ key_token: token, created_at: new Date().toISOString() },
|
||||
null,
|
||||
2,
|
||||
),
|
||||
{ mode: 0o600 },
|
||||
);
|
||||
// 调用方传进来的 log 已经带 [pi-mail-bridge] 前缀,这里不再自己加
|
||||
@ -69,11 +80,17 @@ export function saveConfig(extra) {
|
||||
mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 });
|
||||
let cur = {};
|
||||
if (existsSync(CONFIG_FILE)) {
|
||||
try { cur = JSON.parse(readFileSync(CONFIG_FILE, 'utf8')); } catch { /* 损坏就重写 */ }
|
||||
try {
|
||||
cur = JSON.parse(readFileSync(CONFIG_FILE, "utf8"));
|
||||
} catch {
|
||||
/* 损坏就重写 */
|
||||
}
|
||||
writeFileSync(CONFIG_FILE, JSON.stringify({ ...cur, ...extra }, null, 2), { mode: 0o600 });
|
||||
}
|
||||
writeFileSync(CONFIG_FILE, JSON.stringify({ ...cur, ...extra }, null, 2), {
|
||||
mode: 0o600,
|
||||
});
|
||||
} catch (e) {
|
||||
console.error('[pi-mail-bridge] 写 config.json 失败:', e?.message || e);
|
||||
console.error("[pi-mail-bridge] 写 config.json 失败:", e?.message || e);
|
||||
}
|
||||
}
|
||||
|
||||
@ -82,36 +99,46 @@ export class GatewayClient {
|
||||
* @param {{url: string, agentName: string, agentKey: string, agentSecret: string}} opts
|
||||
*/
|
||||
constructor({ url, agentName, agentKey, agentSecret }) {
|
||||
this.baseURL = String(url || 'http://127.0.0.1:8180').replace(/\/+$/, '');
|
||||
this.baseURL = String(url || "http://127.0.0.1:8180").replace(/\/+$/, "");
|
||||
this.agentName = agentName;
|
||||
this.agentKey = agentKey || '';
|
||||
this.agentSecret = agentSecret || '';
|
||||
this.agentKey = agentKey || "";
|
||||
this.agentSecret = agentSecret || "";
|
||||
this.sseClient = null;
|
||||
}
|
||||
|
||||
/** 认证头:有密钥走 Bearer,否则退回 name/secret。 */
|
||||
authHeaders() {
|
||||
if (this.agentKey) {
|
||||
return { Authorization: `Bearer ${this.agentKey}`, 'X-Agent-Name': this.agentName };
|
||||
return {
|
||||
Authorization: `Bearer ${this.agentKey}`,
|
||||
"X-Agent-Name": this.agentName,
|
||||
};
|
||||
}
|
||||
return { 'X-Agent-Name': this.agentName, 'X-Agent-Secret': this.agentSecret };
|
||||
return {
|
||||
"X-Agent-Name": this.agentName,
|
||||
"X-Agent-Secret": this.agentSecret,
|
||||
};
|
||||
}
|
||||
|
||||
async get(path) {
|
||||
const res = await fetch(`${this.baseURL}/api/v1${path}`, { headers: this.authHeaders() });
|
||||
const res = await fetch(`${this.baseURL}/api/v1${path}`, {
|
||||
headers: this.authHeaders(),
|
||||
});
|
||||
if (!res.ok) throw new Error(`GET ${path} 失败: HTTP ${res.status}`);
|
||||
return res.json();
|
||||
}
|
||||
|
||||
async post(path, body) {
|
||||
const res = await fetch(`${this.baseURL}/api/v1${path}`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', ...this.authHeaders() },
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json", ...this.authHeaders() },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) {
|
||||
const err = new Error(data?.error || `POST ${path} 失败: HTTP ${res.status}`);
|
||||
const err = new Error(
|
||||
data?.error || `POST ${path} 失败: HTTP ${res.status}`,
|
||||
);
|
||||
err.status = res.status;
|
||||
// 响应体也带上:服务端对 409 会给 detail/suggestion,
|
||||
// 那些文字要原文转给模型(它据此决定换什么做法)。
|
||||
@ -123,11 +150,11 @@ export class GatewayClient {
|
||||
|
||||
/** 注册。workspaces 传 [](B-1.2)—— 工作目录由每封邮件的 to_workspace 决定。 */
|
||||
async register() {
|
||||
return this.post('/agent/register', {
|
||||
return this.post("/agent/register", {
|
||||
name: this.agentName,
|
||||
secret: this.agentSecret || '',
|
||||
secret: this.agentSecret || "",
|
||||
workspaces: [],
|
||||
platform: 'pi',
|
||||
platform: "pi",
|
||||
});
|
||||
}
|
||||
|
||||
@ -142,9 +169,9 @@ export class GatewayClient {
|
||||
*/
|
||||
async uploadFile(buf, filename) {
|
||||
const form = new FormData();
|
||||
form.append('file', new Blob([buf]), filename);
|
||||
form.append("file", new Blob([buf]), filename);
|
||||
const res = await fetch(`${this.baseURL}/api/v1/attachments`, {
|
||||
method: 'POST',
|
||||
method: "POST",
|
||||
headers: this.authHeaders(),
|
||||
body: form,
|
||||
});
|
||||
@ -154,9 +181,12 @@ export class GatewayClient {
|
||||
}
|
||||
|
||||
async downloadFile(attachmentID) {
|
||||
const res = await fetch(`${this.baseURL}/api/v1/attachments/${attachmentID}`, {
|
||||
const res = await fetch(
|
||||
`${this.baseURL}/api/v1/attachments/${attachmentID}`,
|
||||
{
|
||||
headers: this.authHeaders(),
|
||||
});
|
||||
},
|
||||
);
|
||||
if (!res.ok) throw new Error(`下载失败: HTTP ${res.status}`);
|
||||
return Buffer.from(await res.arrayBuffer());
|
||||
}
|
||||
@ -177,7 +207,7 @@ export class GatewayClient {
|
||||
this.sseClient = createSSEClient({
|
||||
authHeaders: () => this.authHeaders(),
|
||||
baseURL: this.baseURL,
|
||||
path: '/api/v1/events/stream',
|
||||
path: "/api/v1/events/stream",
|
||||
onEvent,
|
||||
log,
|
||||
});
|
||||
@ -194,7 +224,7 @@ export class GatewayClient {
|
||||
* @returns {boolean} 是否真的变了(没变就不必重连 SSE,省一次断流)
|
||||
*/
|
||||
reconfigure({ url, agentKey }) {
|
||||
const nextURL = url ? String(url).replace(/\/+$/, '') : this.baseURL;
|
||||
const nextURL = url ? String(url).replace(/\/+$/, "") : this.baseURL;
|
||||
const nextKey = agentKey || this.agentKey;
|
||||
const changed = nextURL !== this.baseURL || nextKey !== this.agentKey;
|
||||
if (!changed) return false;
|
||||
|
||||
@ -56,12 +56,16 @@
|
||||
* 一处只增不减的结构。
|
||||
*/
|
||||
|
||||
import { fork } from 'node:child_process';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { fork } from "node:child_process";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
import { BoundedMap, BoundedSet, MAX_TRACKED_SESSIONS } from '../lib/bounded.js';
|
||||
import {
|
||||
BoundedMap,
|
||||
BoundedSet,
|
||||
MAX_TRACKED_SESSIONS,
|
||||
} from "../lib/bounded.js";
|
||||
|
||||
const WORKER_PATH = fileURLToPath(new URL('./worker.mjs', import.meta.url));
|
||||
const WORKER_PATH = fileURLToPath(new URL("./worker.mjs", import.meta.url));
|
||||
|
||||
/**
|
||||
* @param {object} deps
|
||||
@ -77,8 +81,13 @@ const WORKER_PATH = fileURLToPath(new URL('./worker.mjs', import.meta.url));
|
||||
* 让调度不变量(并发上限、同会话串行、硬超时)能在毫秒级验证。
|
||||
*/
|
||||
export function createWorkerPool({
|
||||
log, config, onReconfigure,
|
||||
maxWorkers = 3, workerMaxMs = 600_000, maxAttempts = 3, workerPath = WORKER_PATH,
|
||||
log,
|
||||
config,
|
||||
onReconfigure,
|
||||
maxWorkers = 3,
|
||||
workerMaxMs = 600_000,
|
||||
maxAttempts = 3,
|
||||
workerPath = WORKER_PATH,
|
||||
}) {
|
||||
/** 正在跑的 worker:mailSessionKey -> {child, mailID, startedAt, timer} */
|
||||
const running = new Map();
|
||||
@ -109,7 +118,8 @@ export function createWorkerPool({
|
||||
* 没有 session_id 的事件(理论上不该有)退回 mail_id:那样每封各占一个
|
||||
* worker,不会串行 —— 但它们本来也不属于同一条会话。
|
||||
*/
|
||||
const keyOf = (data) => data?.session_id || `mail:${data?.mail_id || Math.random()}`;
|
||||
const keyOf = (data) =>
|
||||
data?.session_id || `mail:${data?.mail_id || Math.random()}`;
|
||||
|
||||
function submit(kind, data, attempt = 1) {
|
||||
if (stopped) return;
|
||||
@ -132,33 +142,47 @@ export function createWorkerPool({
|
||||
}
|
||||
|
||||
function spawn(job) {
|
||||
const state = sessionState.get(job.key) || { grants: new Set(), lastSyncedName: '' };
|
||||
const state = sessionState.get(job.key) || {
|
||||
grants: new Set(),
|
||||
lastSyncedName: "",
|
||||
};
|
||||
const child = fork(workerPath, [], {
|
||||
// stdio 继承:worker 里 pi SDK 自己打的东西直接进 journalctl。
|
||||
// 'ipc' 必须显式列出,否则 process.send 不存在。
|
||||
stdio: ['ignore', 'inherit', 'inherit', 'ipc'],
|
||||
stdio: ["ignore", "inherit", "inherit", "ipc"],
|
||||
});
|
||||
|
||||
// 硬超时:worker 卡死(模型不返回、权限等不到决策而主进程也没收到事件)
|
||||
// 时必须能回收,否则那条会话的后续邮件永远排队。
|
||||
const timer = setTimeout(() => {
|
||||
log(`worker ${child.pid} 处理 ${job.data?.mail_id} 超过 ${workerMaxMs / 1000}s,强杀`);
|
||||
try { child.kill('SIGKILL'); } catch { /* 已经死了 */ }
|
||||
log(
|
||||
`worker ${child.pid} 处理 ${job.data?.mail_id} 超过 ${workerMaxMs / 1000}s,强杀`,
|
||||
);
|
||||
try {
|
||||
child.kill("SIGKILL");
|
||||
} catch {
|
||||
/* 已经死了 */
|
||||
}
|
||||
}, workerMaxMs);
|
||||
if (typeof timer.unref === 'function') timer.unref();
|
||||
if (typeof timer.unref === "function") timer.unref();
|
||||
|
||||
const entry = {
|
||||
child, mailID: job.data?.mail_id || '', key: job.key,
|
||||
startedAt: Date.now(), timer, settled: false,
|
||||
child,
|
||||
mailID: job.data?.mail_id || "",
|
||||
key: job.key,
|
||||
startedAt: Date.now(),
|
||||
timer,
|
||||
settled: false,
|
||||
};
|
||||
running.set(job.key, entry);
|
||||
|
||||
child.on('message', (msg) => onWorkerMessage(entry, msg));
|
||||
child.on("message", (msg) => onWorkerMessage(entry, msg));
|
||||
|
||||
child.on('exit', (code, signal) => {
|
||||
child.on("exit", (code, signal) => {
|
||||
clearTimeout(timer);
|
||||
running.delete(job.key);
|
||||
for (const [rk, k] of permissionRoutes) if (k === job.key) permissionRoutes.delete(rk);
|
||||
for (const [rk, k] of permissionRoutes)
|
||||
if (k === job.key) permissionRoutes.delete(rk);
|
||||
|
||||
// 没收到 `done` 就退出 = 这封邮件**从未处理完**。
|
||||
//
|
||||
@ -174,54 +198,65 @@ export function createWorkerPool({
|
||||
const attempt = job.attempt || 1;
|
||||
if (attempt < maxAttempts) {
|
||||
const delay = attempt * 1000;
|
||||
log(`worker ${child.pid}(mail ${entry.mailID})未回报 done 就退出`
|
||||
+ `(code=${code} signal=${signal || '-'}),${delay / 1000}s 后`
|
||||
+ `第 ${attempt + 1}/${maxAttempts} 次重投`);
|
||||
log(
|
||||
`worker ${child.pid}(mail ${entry.mailID})未回报 done 就退出` +
|
||||
`(code=${code} signal=${signal || "-"}),${delay / 1000}s 后` +
|
||||
`第 ${attempt + 1}/${maxAttempts} 次重投`,
|
||||
);
|
||||
const retry = setTimeout(() => {
|
||||
if (stopped) return;
|
||||
queue.push({ ...job, attempt: attempt + 1 });
|
||||
pump();
|
||||
}, delay);
|
||||
if (typeof retry.unref === 'function') retry.unref();
|
||||
if (typeof retry.unref === "function") retry.unref();
|
||||
// 退避期间不 pump:否则同一会话会被立刻重投,退避形同虚设
|
||||
return;
|
||||
}
|
||||
log(`worker ${child.pid}(mail ${entry.mailID})重投 ${maxAttempts} 次仍未完成,放弃`
|
||||
+ `(code=${code} signal=${signal || '-'})`);
|
||||
log(
|
||||
`worker ${child.pid}(mail ${entry.mailID})重投 ${maxAttempts} 次仍未完成,放弃` +
|
||||
`(code=${code} signal=${signal || "-"})`,
|
||||
);
|
||||
} else if (code !== 0) {
|
||||
log(`worker ${child.pid}(mail ${entry.mailID})异常退出 code=${code} signal=${signal || '-'}`);
|
||||
log(
|
||||
`worker ${child.pid}(mail ${entry.mailID})异常退出 code=${code} signal=${signal || "-"}`,
|
||||
);
|
||||
}
|
||||
pump();
|
||||
});
|
||||
|
||||
child.on('error', (e) => log(`worker ${child.pid} 出错: ${e?.message || e}`));
|
||||
child.on("error", (e) =>
|
||||
log(`worker ${child.pid} 出错: ${e?.message || e}`),
|
||||
);
|
||||
|
||||
// 等 worker 说 ready 再派活:fork 返回时子进程的 import 还没跑完,
|
||||
// 此时 send 的消息会排在 IPC 队列里(能收到,但 ready 让顺序确定)。
|
||||
child.once('message', function first(msg) {
|
||||
if (msg?.type !== 'ready') return;
|
||||
child.once("message", function first(msg) {
|
||||
if (msg?.type !== "ready") return;
|
||||
child.send({
|
||||
type: 'job',
|
||||
type: "job",
|
||||
kind: job.kind,
|
||||
data: job.data,
|
||||
session: {
|
||||
sessionFile: state.sessionFile || '',
|
||||
cwd: state.cwd || '',
|
||||
sessionFile: state.sessionFile || "",
|
||||
cwd: state.cwd || "",
|
||||
},
|
||||
grants: [...state.grants],
|
||||
lastSyncedName: state.lastSyncedName || '',
|
||||
lastSyncedName: state.lastSyncedName || "",
|
||||
config: config(),
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function onWorkerMessage(entry, msg) {
|
||||
const state = sessionState.get(entry.key) || { grants: new Set(), lastSyncedName: '' };
|
||||
const state = sessionState.get(entry.key) || {
|
||||
grants: new Set(),
|
||||
lastSyncedName: "",
|
||||
};
|
||||
switch (msg?.type) {
|
||||
case 'log':
|
||||
case "log":
|
||||
log(`[w${entry.child.pid}] ${msg.line}`);
|
||||
return;
|
||||
case 'session_opened':
|
||||
case "session_opened":
|
||||
// 一条会话可能先后用过多个 pi 会话 id(模型降级会换会话)。
|
||||
// 旧 id 仍计入 mail_driven,理由见 retired 的注释。
|
||||
if (state.piSessionId && state.piSessionId !== msg.piSessionId) {
|
||||
@ -232,23 +267,23 @@ export function createWorkerPool({
|
||||
state.cwd = msg.cwd;
|
||||
sessionState.set(entry.key, state);
|
||||
return;
|
||||
case 'permission_pending':
|
||||
case "permission_pending":
|
||||
permissionRoutes.set(msg.relayKey, entry.key);
|
||||
return;
|
||||
case 'permission_grant':
|
||||
case "permission_grant":
|
||||
// 「一直同意」必须跨 worker 活着:worker 一封一进程,不存的话下一封
|
||||
// 邮件又问一遍,那个选项就是在骗人。
|
||||
state.grants.add(msg.toolName);
|
||||
sessionState.set(entry.key, state);
|
||||
return;
|
||||
case 'name_synced':
|
||||
case "name_synced":
|
||||
state.lastSyncedName = msg.signature;
|
||||
sessionState.set(entry.key, state);
|
||||
return;
|
||||
case 'reconfigure':
|
||||
case "reconfigure":
|
||||
onReconfigure?.(msg.url, msg.agentKey);
|
||||
return;
|
||||
case 'done':
|
||||
case "done":
|
||||
// 标记「这封真的处理完了」:exit 处理器据此区分「正常收尾」
|
||||
// 与「未回报就崩溃」(后者要重投)。
|
||||
entry.settled = true;
|
||||
@ -275,7 +310,7 @@ export function createWorkerPool({
|
||||
return false;
|
||||
}
|
||||
permissionRoutes.delete(relayKey);
|
||||
entry.child.send({ type: 'permission_decision', relayKey, decision });
|
||||
entry.child.send({ type: "permission_decision", relayKey, decision });
|
||||
return true;
|
||||
}
|
||||
|
||||
@ -331,8 +366,18 @@ export function createWorkerPool({
|
||||
// 先 shutdown 让 worker 把未决权限 fail closed(B-9.2),再给它一点
|
||||
// 时间自己退。不直接 SIGKILL:那样 pi 侧的 await 不会返回,而 worker
|
||||
// 里可能正握着会话文件。
|
||||
try { child.send({ type: 'shutdown' }); } catch { /* 通道已断 */ }
|
||||
setTimeout(() => { try { child.kill('SIGKILL'); } catch { /* 已经死了 */ } }, 2000).unref?.();
|
||||
try {
|
||||
child.send({ type: "shutdown" });
|
||||
} catch {
|
||||
/* 通道已断 */
|
||||
}
|
||||
setTimeout(() => {
|
||||
try {
|
||||
child.kill("SIGKILL");
|
||||
} catch {
|
||||
/* 已经死了 */
|
||||
}
|
||||
}, 2000).unref?.();
|
||||
}
|
||||
}
|
||||
|
||||
@ -345,9 +390,19 @@ export function createWorkerPool({
|
||||
// 而症状是「这条会话怎么突然不记得前面说过什么了」。
|
||||
evictedSessions: sessionState.evicted,
|
||||
workers: [...running.values()].map((e) => ({
|
||||
pid: e.child.pid, mailID: e.mailID, ageMs: Date.now() - e.startedAt,
|
||||
pid: e.child.pid,
|
||||
mailID: e.mailID,
|
||||
ageMs: Date.now() - e.startedAt,
|
||||
})),
|
||||
});
|
||||
|
||||
return { submit, routePermission, hasSession, forget, mailDrivenIDs, stop, stats };
|
||||
return {
|
||||
submit,
|
||||
routePermission,
|
||||
hasSession,
|
||||
forget,
|
||||
mailDrivenIDs,
|
||||
stop,
|
||||
stats,
|
||||
};
|
||||
}
|
||||
|
||||
@ -11,19 +11,21 @@
|
||||
* 而不是一个间接的计数(计数在字段被丢掉时依然会给出绿色)。
|
||||
*/
|
||||
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { mkdtempSync, writeFileSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdtempSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
// ─── 桩 worker ───
|
||||
//
|
||||
// 落到临时目录而不是仓库里:它是测试脚手架,不该被 check-shared-libs 之类的
|
||||
// 一致性脚本看到,也不该让人误以为是第二个真 worker。
|
||||
const STUB_DIR = mkdtempSync(join(tmpdir(), 'pi-pool-test-'));
|
||||
const STUB = join(STUB_DIR, 'stub-worker.mjs');
|
||||
writeFileSync(STUB, `
|
||||
const STUB_DIR = mkdtempSync(join(tmpdir(), "pi-pool-test-"));
|
||||
const STUB = join(STUB_DIR, "stub-worker.mjs");
|
||||
writeFileSync(
|
||||
STUB,
|
||||
`
|
||||
process.on('message', (msg) => {
|
||||
if (msg?.type === 'job') {
|
||||
const hold = msg.data?.__hold ?? 30;
|
||||
@ -80,15 +82,16 @@ process.on('message', (msg) => {
|
||||
}
|
||||
});
|
||||
process.send({ type: 'ready' });
|
||||
`);
|
||||
`,
|
||||
);
|
||||
|
||||
const { createWorkerPool } = await import('../src/pool.mjs');
|
||||
const { createWorkerPool } = await import("../src/pool.mjs");
|
||||
|
||||
/** 建一个用桩 worker 的池。 */
|
||||
function makePool(opts = {}) {
|
||||
const lines = [];
|
||||
const pool = createWorkerPool({
|
||||
log: (...a) => lines.push(a.join(' ')),
|
||||
log: (...a) => lines.push(a.join(" ")),
|
||||
config: () => ({ turnTimeoutMs: 1000, ...(opts.config || {}) }),
|
||||
onReconfigure: opts.onReconfigure || (() => {}),
|
||||
maxWorkers: opts.maxWorkers ?? 2,
|
||||
@ -115,99 +118,131 @@ async function until(fn, timeoutMs = 4000) {
|
||||
function jobs(lines) {
|
||||
const out = [];
|
||||
for (const l of lines) {
|
||||
const i = l.indexOf('JOB ');
|
||||
const i = l.indexOf("JOB ");
|
||||
if (i === -1) continue;
|
||||
try { out.push(JSON.parse(l.slice(i + 4))); } catch { /* 不是完整一行 */ }
|
||||
try {
|
||||
out.push(JSON.parse(l.slice(i + 4)));
|
||||
} catch {
|
||||
/* 不是完整一行 */
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** 某个 mailID 的心跳出现过几次。 */
|
||||
const ticks = (lines, id) => lines.filter((l) => l.includes(`TICK ${id}`)).length;
|
||||
const ticks = (lines, id) =>
|
||||
lines.filter((l) => l.includes(`TICK ${id}`)).length;
|
||||
|
||||
test('并发上限被遵守:第三条会话要等前面空出来', async () => {
|
||||
test("并发上限被遵守:第三条会话要等前面空出来", async () => {
|
||||
const { pool } = makePool({ maxWorkers: 2 });
|
||||
for (const id of ['a', 'b', 'c']) {
|
||||
pool.submit('mail', { mail_id: id, session_id: `S-${id}`, __hold: 250 });
|
||||
for (const id of ["a", "b", "c"]) {
|
||||
pool.submit("mail", { mail_id: id, session_id: `S-${id}`, __hold: 250 });
|
||||
}
|
||||
|
||||
let peak = 0;
|
||||
const t = setInterval(() => { peak = Math.max(peak, pool.stats().running); }, 15);
|
||||
const t = setInterval(() => {
|
||||
peak = Math.max(peak, pool.stats().running);
|
||||
}, 15);
|
||||
const sawQueue = await until(() => pool.stats().queued > 0, 1000);
|
||||
await until(() => pool.stats().running === 0 && pool.stats().queued === 0);
|
||||
clearInterval(t);
|
||||
pool.stop();
|
||||
|
||||
assert.ok(peak <= 2, `同时跑的 worker 峰值 ${peak},不该超过 maxWorkers=2`);
|
||||
assert.ok(sawQueue, '满载时第三封该进队列而不是被丢掉');
|
||||
assert.ok(sawQueue, "满载时第三封该进队列而不是被丢掉");
|
||||
});
|
||||
|
||||
test('同一会话串行:两个 worker 的心跳不得重叠', async () => {
|
||||
test("同一会话串行:两个 worker 的心跳不得重叠", async () => {
|
||||
const { pool, lines } = makePool({ maxWorkers: 3 });
|
||||
pool.submit('mail', { mail_id: 'm1', session_id: 'SAME', __hold: 220 });
|
||||
pool.submit('mail', { mail_id: 'm2', session_id: 'SAME', __hold: 60 });
|
||||
pool.submit("mail", { mail_id: "m1", session_id: "SAME", __hold: 220 });
|
||||
pool.submit("mail", { mail_id: "m2", session_id: "SAME", __hold: 60 });
|
||||
|
||||
// 判据一:任一时刻只有一个 worker 在跑。
|
||||
let everTwo = false;
|
||||
const t = setInterval(() => { if (pool.stats().running > 1) everTwo = true; }, 10);
|
||||
await until(() => jobs(lines).length === 2 && pool.stats().running === 0, 5000);
|
||||
const t = setInterval(() => {
|
||||
if (pool.stats().running > 1) everTwo = true;
|
||||
}, 10);
|
||||
await until(
|
||||
() => jobs(lines).length === 2 && pool.stats().running === 0,
|
||||
5000,
|
||||
);
|
||||
clearInterval(t);
|
||||
pool.stop();
|
||||
|
||||
assert.equal(everTwo, false, '同一条会话不得有两个 worker 同时装载会话文件');
|
||||
assert.equal(everTwo, false, "同一条会话不得有两个 worker 同时装载会话文件");
|
||||
// 判据二:m2 一次心跳都没能在 m1 结束前发出 —— m1 的心跳数应当远多于 m2。
|
||||
assert.ok(ticks(lines, 'm1') >= 3, `m1 该跑满 220ms,实际心跳 ${ticks(lines, 'm1')} 次`);
|
||||
assert.equal(jobs(lines).length, 2, '两封都要被处理,不能因为串行而丢掉一封');
|
||||
assert.ok(
|
||||
ticks(lines, "m1") >= 3,
|
||||
`m1 该跑满 220ms,实际心跳 ${ticks(lines, "m1")} 次`,
|
||||
);
|
||||
assert.equal(jobs(lines).length, 2, "两封都要被处理,不能因为串行而丢掉一封");
|
||||
});
|
||||
|
||||
test('不同会话真并发:两个进程的心跳在同一段时间里交错', async () => {
|
||||
test("不同会话真并发:两个进程的心跳在同一段时间里交错", async () => {
|
||||
const { pool, lines } = makePool({ maxWorkers: 3 });
|
||||
pool.submit('mail', { mail_id: 'p', session_id: 'S-P', __hold: 300 });
|
||||
pool.submit('mail', { mail_id: 'q', session_id: 'S-Q', __hold: 300 });
|
||||
pool.submit("mail", { mail_id: "p", session_id: "S-P", __hold: 300 });
|
||||
pool.submit("mail", { mail_id: "q", session_id: "S-Q", __hold: 300 });
|
||||
|
||||
const interleaved = await until(() => ticks(lines, 'p') >= 2 && ticks(lines, 'q') >= 2, 2500);
|
||||
const interleaved = await until(
|
||||
() => ticks(lines, "p") >= 2 && ticks(lines, "q") >= 2,
|
||||
2500,
|
||||
);
|
||||
pool.stop();
|
||||
assert.ok(interleaved,
|
||||
`两条不同会话应当并发,实际 p=${ticks(lines, 'p')} q=${ticks(lines, 'q')} 次心跳`);
|
||||
assert.ok(
|
||||
interleaved,
|
||||
`两条不同会话应当并发,实际 p=${ticks(lines, "p")} q=${ticks(lines, "q")} 次心跳`,
|
||||
);
|
||||
});
|
||||
|
||||
test('sessionFile 与 cwd 跨 worker 传下去:第二封接着第一封的会话谈', async () => {
|
||||
test("sessionFile 与 cwd 跨 worker 传下去:第二封接着第一封的会话谈", async () => {
|
||||
const { pool, lines } = makePool({ maxWorkers: 2 });
|
||||
pool.submit('mail', { mail_id: 'first', session_id: 'KEEP', __hold: 30 });
|
||||
pool.submit("mail", { mail_id: "first", session_id: "KEEP", __hold: 30 });
|
||||
await until(() => jobs(lines).length === 1 && pool.stats().running === 0);
|
||||
|
||||
pool.submit('mail', { mail_id: 'second', session_id: 'KEEP', __hold: 30 });
|
||||
pool.submit("mail", { mail_id: "second", session_id: "KEEP", __hold: 30 });
|
||||
await until(() => jobs(lines).length === 2 && pool.stats().running === 0);
|
||||
pool.stop();
|
||||
|
||||
const [j1, j2] = jobs(lines);
|
||||
assert.equal(j1.sessionFile, '', '第一封时还没有会话文件');
|
||||
assert.equal(j2.sessionFile, '/tmp/f-first.jsonl',
|
||||
'第二封必须带上第一封开出来的会话文件,否则每封邮件都从零开始、上下文全丢');
|
||||
assert.equal(j2.cwd, '/tmp', 'cwd 也要传下去');
|
||||
assert.equal(j1.sessionFile, "", "第一封时还没有会话文件");
|
||||
assert.equal(
|
||||
j2.sessionFile,
|
||||
"/tmp/f-first.jsonl",
|
||||
"第二封必须带上第一封开出来的会话文件,否则每封邮件都从零开始、上下文全丢",
|
||||
);
|
||||
assert.equal(j2.cwd, "/tmp", "cwd 也要传下去");
|
||||
});
|
||||
|
||||
test('「一直同意」与命名指纹跨 worker 存活', async () => {
|
||||
test("「一直同意」与命名指纹跨 worker 存活", async () => {
|
||||
const { pool, lines } = makePool({ maxWorkers: 2 });
|
||||
pool.submit('mail', {
|
||||
mail_id: 'g1', session_id: 'GRANT', __hold: 30,
|
||||
__grant: 'bash', __name: 'platform:某名字|某名字',
|
||||
pool.submit("mail", {
|
||||
mail_id: "g1",
|
||||
session_id: "GRANT",
|
||||
__hold: 30,
|
||||
__grant: "bash",
|
||||
__name: "platform:某名字|某名字",
|
||||
});
|
||||
await until(() => jobs(lines).length === 1 && pool.stats().running === 0);
|
||||
|
||||
pool.submit('mail', { mail_id: 'g2', session_id: 'GRANT', __hold: 30 });
|
||||
pool.submit("mail", { mail_id: "g2", session_id: "GRANT", __hold: 30 });
|
||||
await until(() => jobs(lines).length === 2 && pool.stats().running === 0);
|
||||
pool.stop();
|
||||
|
||||
const [j1, j2] = jobs(lines);
|
||||
assert.deepEqual(j1.grants, [], '第一封时还没人点过「一直同意」');
|
||||
assert.deepEqual(j2.grants, ['bash'],
|
||||
'「一直同意」不跨 worker 存活的话,下一封邮件又问一遍 —— 那个选项就是在骗人');
|
||||
assert.equal(j2.lastSyncedName, 'platform:某名字|某名字',
|
||||
'命名指纹要传下去,否则每封邮件都重新 sync 一次');
|
||||
assert.deepEqual(j1.grants, [], "第一封时还没人点过「一直同意」");
|
||||
assert.deepEqual(
|
||||
j2.grants,
|
||||
["bash"],
|
||||
"「一直同意」不跨 worker 存活的话,下一封邮件又问一遍 —— 那个选项就是在骗人",
|
||||
);
|
||||
assert.equal(
|
||||
j2.lastSyncedName,
|
||||
"platform:某名字|某名字",
|
||||
"命名指纹要传下去,否则每封邮件都重新 sync 一次",
|
||||
);
|
||||
});
|
||||
|
||||
test('config() 每次派活时重取:allowedModels 随心跳变,不能用快照', async () => {
|
||||
test("config() 每次派活时重取:allowedModels 随心跳变,不能用快照", async () => {
|
||||
let turnTimeoutMs = 111;
|
||||
const { pool, lines } = makePool({ maxWorkers: 1, config: {} });
|
||||
// makePool 的 config 是固定值,这里换成动态的
|
||||
@ -215,162 +250,211 @@ test('config() 每次派活时重取:allowedModels 随心跳变,不能用快
|
||||
|
||||
const lines2 = [];
|
||||
const p2 = createWorkerPool({
|
||||
log: (...a) => lines2.push(a.join(' ')),
|
||||
log: (...a) => lines2.push(a.join(" ")),
|
||||
config: () => ({ turnTimeoutMs }),
|
||||
onReconfigure: () => {},
|
||||
maxWorkers: 1,
|
||||
workerMaxMs: 5000,
|
||||
workerPath: STUB,
|
||||
});
|
||||
p2.submit('mail', { mail_id: 'c1', session_id: 'C1', __hold: 20 });
|
||||
p2.submit("mail", { mail_id: "c1", session_id: "C1", __hold: 20 });
|
||||
await until(() => jobs(lines2).length === 1 && p2.stats().running === 0);
|
||||
turnTimeoutMs = 222;
|
||||
p2.submit('mail', { mail_id: 'c2', session_id: 'C2', __hold: 20 });
|
||||
p2.submit("mail", { mail_id: "c2", session_id: "C2", __hold: 20 });
|
||||
await until(() => jobs(lines2).length === 2 && p2.stats().running === 0);
|
||||
p2.stop();
|
||||
|
||||
const [j1, j2] = jobs(lines2);
|
||||
assert.equal(j1.turnTimeoutMs, 111);
|
||||
assert.equal(j2.turnTimeoutMs, 222, 'config() 必须每次重取,否则 worker 用的是上一轮的模型范围');
|
||||
assert.equal(
|
||||
j2.turnTimeoutMs,
|
||||
222,
|
||||
"config() 必须每次重取,否则 worker 用的是上一轮的模型范围",
|
||||
);
|
||||
assert.equal(lines.length >= 0, true);
|
||||
});
|
||||
|
||||
test('硬超时回收卡死的 worker,且不堵住同会话后续邮件', async () => {
|
||||
test("硬超时回收卡死的 worker,且不堵住同会话后续邮件", async () => {
|
||||
const { pool, lines } = makePool({ maxWorkers: 2, workerMaxMs: 400 });
|
||||
pool.submit('mail', { mail_id: 'stuck', session_id: 'STUCK', __hold: -1 });
|
||||
pool.submit("mail", { mail_id: "stuck", session_id: "STUCK", __hold: -1 });
|
||||
await until(() => pool.stats().running === 1, 1500);
|
||||
|
||||
const freed = await until(() => pool.stats().running === 0, 3000);
|
||||
assert.ok(freed, '卡死的 worker 必须被硬超时回收,否则那条会话的后续邮件永远排队');
|
||||
assert.ok(lines.some((l) => l.includes('强杀')), `应记下强杀日志,实际:\n${lines.join('\n')}`);
|
||||
assert.ok(
|
||||
freed,
|
||||
"卡死的 worker 必须被硬超时回收,否则那条会话的后续邮件永远排队",
|
||||
);
|
||||
assert.ok(
|
||||
lines.some((l) => l.includes("强杀")),
|
||||
`应记下强杀日志,实际:\n${lines.join("\n")}`,
|
||||
);
|
||||
|
||||
pool.submit('mail', { mail_id: 'after', session_id: 'STUCK', __hold: 30 });
|
||||
const ran = await until(() => jobs(lines).some((j) => j.mailID === 'after'), 2000);
|
||||
pool.submit("mail", { mail_id: "after", session_id: "STUCK", __hold: 30 });
|
||||
const ran = await until(
|
||||
() => jobs(lines).some((j) => j.mailID === "after"),
|
||||
2000,
|
||||
);
|
||||
await until(() => pool.stats().running === 0);
|
||||
pool.stop();
|
||||
assert.ok(ran, '硬超时后同一会话的后续邮件必须能被处理');
|
||||
assert.ok(ran, "硬超时后同一会话的后续邮件必须能被处理");
|
||||
});
|
||||
|
||||
test('权限决策路由到发起询问的那个 worker', async () => {
|
||||
test("权限决策路由到发起询问的那个 worker", async () => {
|
||||
const { pool, lines } = makePool({ maxWorkers: 2 });
|
||||
pool.submit('mail', { mail_id: 'perm', session_id: 'PERM', __pending: 'rk-1' });
|
||||
pool.submit("mail", {
|
||||
mail_id: "perm",
|
||||
session_id: "PERM",
|
||||
__pending: "rk-1",
|
||||
});
|
||||
await until(() => pool.stats().running === 1, 1500);
|
||||
await sleep(150); // 等 permission_pending 到主进程
|
||||
|
||||
assert.equal(pool.routePermission('rk-1', '同意'), true, '应当路由成功');
|
||||
assert.equal(pool.routePermission("rk-1", "同意"), true, "应当路由成功");
|
||||
await until(() => pool.stats().running === 0, 2000);
|
||||
pool.stop();
|
||||
|
||||
assert.ok(lines.some((l) => l.includes('DECISION rk-1=同意')),
|
||||
`worker 应收到决策原文,实际:\n${lines.join('\n')}`);
|
||||
assert.ok(
|
||||
lines.some((l) => l.includes("DECISION rk-1=同意")),
|
||||
`worker 应收到决策原文,实际:\n${lines.join("\n")}`,
|
||||
);
|
||||
});
|
||||
|
||||
test('决策发的是选项原文而不是归一化的 allow/deny', async () => {
|
||||
test("决策发的是选项原文而不是归一化的 allow/deny", async () => {
|
||||
const { pool, lines } = makePool({ maxWorkers: 2 });
|
||||
pool.submit('mail', { mail_id: 'p2', session_id: 'P2', __pending: 'rk-2' });
|
||||
pool.submit("mail", { mail_id: "p2", session_id: "P2", __pending: "rk-2" });
|
||||
await until(() => pool.stats().running === 1, 1500);
|
||||
await sleep(150);
|
||||
pool.routePermission('rk-2', '一直同意');
|
||||
pool.routePermission("rk-2", "一直同意");
|
||||
await until(() => pool.stats().running === 0, 2000);
|
||||
pool.stop();
|
||||
|
||||
// 「同意」与「一直同意」语义不同,归一化会让后者退化成单次授权
|
||||
assert.ok(lines.some((l) => l.includes('DECISION rk-2=一直同意')),
|
||||
`必须原文透传,实际:\n${lines.join('\n')}`);
|
||||
assert.ok(
|
||||
lines.some((l) => l.includes("DECISION rk-2=一直同意")),
|
||||
`必须原文透传,实际:\n${lines.join("\n")}`,
|
||||
);
|
||||
});
|
||||
|
||||
test('决策找不到 worker 时返回 false(调用方据此走 B-4.2 降级)', async () => {
|
||||
test("决策找不到 worker 时返回 false(调用方据此走 B-4.2 降级)", async () => {
|
||||
const { pool } = makePool();
|
||||
assert.equal(pool.routePermission('never-seen', '同意'), false);
|
||||
assert.equal(pool.routePermission("never-seen", "同意"), false);
|
||||
pool.stop();
|
||||
});
|
||||
|
||||
test('worker 退出后它的权限路由被清掉,不会误投给下一个 worker', async () => {
|
||||
test("worker 退出后它的权限路由被清掉,不会误投给下一个 worker", async () => {
|
||||
const { pool } = makePool({ maxWorkers: 2 });
|
||||
pool.submit('mail', { mail_id: 'gone', session_id: 'GONE', __pending: 'rk-gone' });
|
||||
pool.submit("mail", {
|
||||
mail_id: "gone",
|
||||
session_id: "GONE",
|
||||
__pending: "rk-gone",
|
||||
});
|
||||
await until(() => pool.stats().running === 1, 1500);
|
||||
await sleep(150);
|
||||
// 不给决策,直接停掉它
|
||||
pool.stop();
|
||||
await until(() => pool.stats().running === 0, 4000);
|
||||
|
||||
assert.equal(pool.routePermission('rk-gone', '同意'), false,
|
||||
'worker 已退出,路由必须返回 false 让调用方走降级路径');
|
||||
assert.equal(
|
||||
pool.routePermission("rk-gone", "同意"),
|
||||
false,
|
||||
"worker 已退出,路由必须返回 false 让调用方走降级路径",
|
||||
);
|
||||
});
|
||||
|
||||
test('mailDrivenIDs 报出所有跑过的 pi 会话,且不随 worker 退出而清', async () => {
|
||||
test("mailDrivenIDs 报出所有跑过的 pi 会话,且不随 worker 退出而清", async () => {
|
||||
const { pool, lines } = makePool({ maxWorkers: 2 });
|
||||
pool.submit('mail', { mail_id: 'd1', session_id: 'D1', __hold: 30 });
|
||||
pool.submit('mail', { mail_id: 'd2', session_id: 'D2', __hold: 30 });
|
||||
pool.submit("mail", { mail_id: "d1", session_id: "D1", __hold: 30 });
|
||||
pool.submit("mail", { mail_id: "d2", session_id: "D2", __hold: 30 });
|
||||
await until(() => jobs(lines).length === 2 && pool.stats().running === 0);
|
||||
pool.stop();
|
||||
|
||||
const ids = pool.mailDrivenIDs();
|
||||
assert.ok(ids.has('pi-d1'), 'D1 的 pi 会话该被标记为邮件驱动');
|
||||
assert.ok(ids.has('pi-d2'), 'D2 的 pi 会话该被标记为邮件驱动');
|
||||
assert.ok(ids.has("pi-d1"), "D1 的 pi 会话该被标记为邮件驱动");
|
||||
assert.ok(ids.has("pi-d2"), "D2 的 pi 会话该被标记为邮件驱动");
|
||||
});
|
||||
|
||||
test('模型降级换掉的旧 pi 会话仍算邮件驱动', async () => {
|
||||
test("模型降级换掉的旧 pi 会话仍算邮件驱动", async () => {
|
||||
const { pool, lines } = makePool({ maxWorkers: 2 });
|
||||
pool.submit('mail', { mail_id: 'r', session_id: 'RETIRE', __hold: 40, __reopen: 'pi-new' });
|
||||
pool.submit("mail", {
|
||||
mail_id: "r",
|
||||
session_id: "RETIRE",
|
||||
__hold: 40,
|
||||
__reopen: "pi-new",
|
||||
});
|
||||
await until(() => jobs(lines).length === 1 && pool.stats().running === 0);
|
||||
pool.stop();
|
||||
|
||||
const ids = pool.mailDrivenIDs();
|
||||
assert.ok(ids.has('pi-new'), '新会话要在');
|
||||
assert.ok(ids.has('pi-r'), '被换掉的旧会话也参与过邮件往来,磁盘上的文件还在,快照该报它');
|
||||
assert.ok(ids.has("pi-new"), "新会话要在");
|
||||
assert.ok(
|
||||
ids.has("pi-r"),
|
||||
"被换掉的旧会话也参与过邮件往来,磁盘上的文件还在,快照该报它",
|
||||
);
|
||||
});
|
||||
|
||||
test('hasSession 只对跑过的邮件会话为真', async () => {
|
||||
test("hasSession 只对跑过的邮件会话为真", async () => {
|
||||
const { pool } = makePool();
|
||||
assert.equal(pool.hasSession('NOPE'), false);
|
||||
pool.submit('mail', { mail_id: 'h1', session_id: 'HAS', __hold: 30 });
|
||||
await until(() => pool.hasSession('HAS'), 2000);
|
||||
assert.equal(pool.hasSession("NOPE"), false);
|
||||
pool.submit("mail", { mail_id: "h1", session_id: "HAS", __hold: 30 });
|
||||
await until(() => pool.hasSession("HAS"), 2000);
|
||||
await until(() => pool.stats().running === 0);
|
||||
pool.stop();
|
||||
assert.equal(pool.hasSession('HAS'), true, 'worker 退出后仍该记着这条会话');
|
||||
assert.equal(pool.hasSession("HAS"), true, "worker 退出后仍该记着这条会话");
|
||||
});
|
||||
|
||||
test('kind 透传:权限通知走 permission 而不是 mail', async () => {
|
||||
test("kind 透传:权限通知走 permission 而不是 mail", async () => {
|
||||
const { pool, lines } = makePool({ maxWorkers: 2 });
|
||||
pool.submit('permission', { mail_id: 'k1', session_id: 'K1', __hold: 20 });
|
||||
pool.submit("permission", { mail_id: "k1", session_id: "K1", __hold: 20 });
|
||||
await until(() => jobs(lines).length === 1 && pool.stats().running === 0);
|
||||
pool.stop();
|
||||
assert.equal(jobs(lines)[0].kind, 'permission',
|
||||
'kind 决定 worker 用哪套提示词,传错会让模型以为收到一封新邮件');
|
||||
assert.equal(
|
||||
jobs(lines)[0].kind,
|
||||
"permission",
|
||||
"kind 决定 worker 用哪套提示词,传错会让模型以为收到一封新邮件",
|
||||
);
|
||||
});
|
||||
|
||||
test('stop 之后不再派活', async () => {
|
||||
test("stop 之后不再派活", async () => {
|
||||
const { pool } = makePool();
|
||||
pool.stop();
|
||||
pool.submit('mail', { mail_id: 'late', session_id: 'LATE', __hold: 30 });
|
||||
pool.submit("mail", { mail_id: "late", session_id: "LATE", __hold: 30 });
|
||||
await sleep(200);
|
||||
assert.equal(pool.stats().running, 0, '关停后不该再起 worker');
|
||||
assert.equal(pool.stats().queued, 0, '关停后队列应为空');
|
||||
assert.equal(pool.stats().running, 0, "关停后不该再起 worker");
|
||||
assert.equal(pool.stats().queued, 0, "关停后队列应为空");
|
||||
});
|
||||
|
||||
test('stop 会先给 worker 发 shutdown(让它 fail closed)再杀', async () => {
|
||||
test("stop 会先给 worker 发 shutdown(让它 fail closed)再杀", async () => {
|
||||
const { pool, lines } = makePool({ maxWorkers: 2 });
|
||||
pool.submit('mail', { mail_id: 's1', session_id: 'S1', __hold: -1 });
|
||||
pool.submit("mail", { mail_id: "s1", session_id: "S1", __hold: -1 });
|
||||
await until(() => pool.stats().running === 1, 1500);
|
||||
pool.stop();
|
||||
const gotShutdown = await until(() => lines.some((l) => l.includes('SHUTDOWN')), 2000);
|
||||
assert.ok(gotShutdown,
|
||||
'必须先发 shutdown:直接 SIGKILL 会让 pi 侧那些等权限的 await 永不返回');
|
||||
const gotShutdown = await until(
|
||||
() => lines.some((l) => l.includes("SHUTDOWN")),
|
||||
2000,
|
||||
);
|
||||
assert.ok(
|
||||
gotShutdown,
|
||||
"必须先发 shutdown:直接 SIGKILL 会让 pi 侧那些等权限的 await 永不返回",
|
||||
);
|
||||
});
|
||||
|
||||
test('没有 session_id 的事件各占一个 key,不会互相串行', async () => {
|
||||
test("没有 session_id 的事件各占一个 key,不会互相串行", async () => {
|
||||
const { pool, lines } = makePool({ maxWorkers: 3 });
|
||||
pool.submit('mail', { mail_id: 'n1', __hold: 300 });
|
||||
pool.submit('mail', { mail_id: 'n2', __hold: 300 });
|
||||
const both = await until(() => ticks(lines, 'n1') >= 2 && ticks(lines, 'n2') >= 2, 2500);
|
||||
pool.submit("mail", { mail_id: "n1", __hold: 300 });
|
||||
pool.submit("mail", { mail_id: "n2", __hold: 300 });
|
||||
const both = await until(
|
||||
() => ticks(lines, "n1") >= 2 && ticks(lines, "n2") >= 2,
|
||||
2500,
|
||||
);
|
||||
pool.stop();
|
||||
assert.ok(both, '无 session_id 的两封不属于同一条会话,应能并发');
|
||||
assert.ok(both, "无 session_id 的两封不属于同一条会话,应能并发");
|
||||
});
|
||||
|
||||
test('reconfigure 上报被转达给主进程', async () => {
|
||||
const STUB2 = join(STUB_DIR, 'stub-reconf.mjs');
|
||||
writeFileSync(STUB2, `
|
||||
test("reconfigure 上报被转达给主进程", async () => {
|
||||
const STUB2 = join(STUB_DIR, "stub-reconf.mjs");
|
||||
writeFileSync(
|
||||
STUB2,
|
||||
`
|
||||
process.on('message', (msg) => {
|
||||
if (msg?.type === 'job') {
|
||||
process.send({ type: 'reconfigure', url: 'http://new:9999', agentKey: 'k2' });
|
||||
@ -379,42 +463,57 @@ process.on('message', (msg) => {
|
||||
}
|
||||
});
|
||||
process.send({ type: 'ready' });
|
||||
`);
|
||||
`,
|
||||
);
|
||||
let got = null;
|
||||
const { pool } = makePool({
|
||||
maxWorkers: 1,
|
||||
workerPath: STUB2,
|
||||
onReconfigure: (url, key) => { got = { url, key }; },
|
||||
onReconfigure: (url, key) => {
|
||||
got = { url, key };
|
||||
},
|
||||
});
|
||||
pool.submit('mail', { mail_id: 'r1', session_id: 'R1' });
|
||||
pool.submit("mail", { mail_id: "r1", session_id: "R1" });
|
||||
await until(() => got !== null, 3000);
|
||||
pool.stop();
|
||||
assert.deepEqual(got, { url: 'http://new:9999', key: 'k2' },
|
||||
'worker 里 connect_to_server 换的坐标必须回到主进程 —— worker 马上就退了,改在它自己身上等于没改');
|
||||
assert.deepEqual(
|
||||
got,
|
||||
{ url: "http://new:9999", key: "k2" },
|
||||
"worker 里 connect_to_server 换的坐标必须回到主进程 —— worker 马上就退了,改在它自己身上等于没改",
|
||||
);
|
||||
});
|
||||
|
||||
test('worker 未回报 done 就退出:有界重投而不是静默丢信', async () => {
|
||||
test("worker 未回报 done 就退出:有界重投而不是静默丢信", async () => {
|
||||
// maxAttempts=2:首次 + 一次重投,然后放弃。
|
||||
// 这封邮件必定崩溃,重投就是在验证「有界」——不然它会变成永久活锁。
|
||||
const { pool, lines } = makePool({ maxWorkers: 1, maxAttempts: 2 });
|
||||
pool.submit('mail', { mail_id: 'crashy', session_id: 'CRASH', __crash: true });
|
||||
pool.submit("mail", {
|
||||
mail_id: "crashy",
|
||||
session_id: "CRASH",
|
||||
__crash: true,
|
||||
});
|
||||
|
||||
const gaveUp = await until(() => lines.some((l) => l.includes('放弃')), 6000);
|
||||
const gaveUp = await until(() => lines.some((l) => l.includes("放弃")), 6000);
|
||||
pool.stop();
|
||||
|
||||
assert.ok(gaveUp, `重投到上限后应记下「放弃」,实际:\n${lines.join('\n')}`);
|
||||
assert.equal(jobs(lines).length, 2,
|
||||
`应当尝试 2 次(首次 + 1 次重投),实际 ${jobs(lines).length} 次`);
|
||||
assert.ok(lines.some((l) => l.includes('未回报 done 就退出')),
|
||||
'必须明说是「未回报 done 就退出」——否则看到 exit code 会误以为是普通崩溃');
|
||||
assert.ok(gaveUp, `重投到上限后应记下「放弃」,实际:\n${lines.join("\n")}`);
|
||||
assert.equal(
|
||||
jobs(lines).length,
|
||||
2,
|
||||
`应当尝试 2 次(首次 + 1 次重投),实际 ${jobs(lines).length} 次`,
|
||||
);
|
||||
assert.ok(
|
||||
lines.some((l) => l.includes("未回报 done 就退出")),
|
||||
"必须明说是「未回报 done 就退出」——否则看到 exit code 会误以为是普通崩溃",
|
||||
);
|
||||
});
|
||||
|
||||
test('重投上限之下不会无限重投(maxAttempts=1 就是不重投)', async () => {
|
||||
test("重投上限之下不会无限重投(maxAttempts=1 就是不重投)", async () => {
|
||||
const { pool, lines } = makePool({ maxWorkers: 1, maxAttempts: 1 });
|
||||
pool.submit('mail', { mail_id: 'once', session_id: 'ONCE', __crash: true });
|
||||
await until(() => lines.some((l) => l.includes('放弃')), 4000);
|
||||
pool.submit("mail", { mail_id: "once", session_id: "ONCE", __crash: true });
|
||||
await until(() => lines.some((l) => l.includes("放弃")), 4000);
|
||||
await sleep(300); // 再等一会儿,确认没有额外重投
|
||||
pool.stop();
|
||||
|
||||
assert.equal(jobs(lines).length, 1, 'maxAttempts=1 时只跑一次');
|
||||
assert.equal(jobs(lines).length, 1, "maxAttempts=1 时只跑一次");
|
||||
});
|
||||
|
||||
@ -9,10 +9,10 @@
|
||||
* 生产上表现为「新邮件偶尔收不到」「权限决策点了没反应」,且日志里一个字都没有。
|
||||
*/
|
||||
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
|
||||
import { createFrameParser } from '../lib/sse-client.js';
|
||||
import { createFrameParser } from "../lib/sse-client.js";
|
||||
|
||||
/** JSON.parse 的测试包装:解析失败让断言带原文失败,而不是抛未捕获异常。 */
|
||||
function parse(s) {
|
||||
@ -23,107 +23,118 @@ function parse(s) {
|
||||
}
|
||||
}
|
||||
|
||||
test('完整帧一次喂入:正常解析', () => {
|
||||
test("完整帧一次喂入:正常解析", () => {
|
||||
const p = createFrameParser();
|
||||
const events = p.push('id: 7\nevent: new_mail\ndata: {"mail_id":"m1"}\n\n');
|
||||
assert.equal(events.length, 1);
|
||||
assert.equal(events[0].event, 'new_mail');
|
||||
assert.deepEqual(parse(events[0].data), { mail_id: 'm1' });
|
||||
assert.equal(events[0].id, '7');
|
||||
assert.equal(p.lastEventId(), '7');
|
||||
assert.equal(events[0].event, "new_mail");
|
||||
assert.deepEqual(parse(events[0].data), { mail_id: "m1" });
|
||||
assert.equal(events[0].id, "7");
|
||||
assert.equal(p.lastEventId(), "7");
|
||||
});
|
||||
|
||||
test('帧被切在换行处:跨 chunk 保住 event 名(原 bug 的核心)', () => {
|
||||
test("帧被切在换行处:跨 chunk 保住 event 名(原 bug 的核心)", () => {
|
||||
const p = createFrameParser();
|
||||
// chunk1 恰好停在 event 行之后、data 行之前
|
||||
const first = p.push('id: 12\nevent: content_delta\n');
|
||||
assert.deepEqual(first, [], '半帧不该派发');
|
||||
const first = p.push("id: 12\nevent: content_delta\n");
|
||||
assert.deepEqual(first, [], "半帧不该派发");
|
||||
|
||||
const second = p.push('data: {"x":1}\n\n');
|
||||
assert.equal(second.length, 1, '跨 chunk 的半帧必须被拼回完整事件,而不是丢弃');
|
||||
assert.equal(second[0].event, 'content_delta');
|
||||
assert.equal(p.lastEventId(), '12');
|
||||
assert.equal(
|
||||
second.length,
|
||||
1,
|
||||
"跨 chunk 的半帧必须被拼回完整事件,而不是丢弃",
|
||||
);
|
||||
assert.equal(second[0].event, "content_delta");
|
||||
assert.equal(p.lastEventId(), "12");
|
||||
});
|
||||
|
||||
test('帧被切在行中间:buffer 保留半行', () => {
|
||||
test("帧被切在行中间:buffer 保留半行", () => {
|
||||
const p = createFrameParser();
|
||||
const a = p.push('event: new_ma');
|
||||
const a = p.push("event: new_ma");
|
||||
assert.deepEqual(a, []);
|
||||
const b = p.push('il\ndata: {"mail_id":"m9"}\n\n');
|
||||
assert.equal(b.length, 1);
|
||||
assert.equal(b[0].event, 'new_mail');
|
||||
assert.equal(b[0].event, "new_mail");
|
||||
});
|
||||
|
||||
test('一个 chunk 里多帧连续:全部派发', () => {
|
||||
test("一个 chunk 里多帧连续:全部派发", () => {
|
||||
const p = createFrameParser();
|
||||
const events = p.push(
|
||||
'event: new_mail\ndata: {"n":1}\n\n' +
|
||||
'event: new_mail\ndata: {"n":2}\n\n' +
|
||||
'event: session_update\ndata: {"n":3}\n\n'
|
||||
'event: session_update\ndata: {"n":3}\n\n',
|
||||
);
|
||||
assert.equal(events.length, 3);
|
||||
assert.deepEqual(events.map((e) => e.event), ['new_mail', 'new_mail', 'session_update']);
|
||||
assert.deepEqual(
|
||||
events.map((e) => e.event),
|
||||
["new_mail", "new_mail", "session_update"],
|
||||
);
|
||||
});
|
||||
|
||||
test('注释/心跳行被忽略,不影响后续帧', () => {
|
||||
test("注释/心跳行被忽略,不影响后续帧", () => {
|
||||
const p = createFrameParser();
|
||||
const events = p.push(': heartbeat\n\nevent: new_mail\ndata: {"n":1}\n\n');
|
||||
assert.equal(events.length, 1);
|
||||
assert.equal(events[0].event, 'new_mail');
|
||||
assert.equal(events[0].event, "new_mail");
|
||||
});
|
||||
|
||||
test('多行 data 用换行拼接', () => {
|
||||
test("多行 data 用换行拼接", () => {
|
||||
const p = createFrameParser();
|
||||
const events = p.push('event: x\ndata: line1\ndata: line2\n\n');
|
||||
assert.equal(events[0].data, 'line1\nline2');
|
||||
const events = p.push("event: x\ndata: line1\ndata: line2\n\n");
|
||||
assert.equal(events[0].data, "line1\nline2");
|
||||
});
|
||||
|
||||
test('CRLF 不被当成事件名或 JSON 的一部分', () => {
|
||||
test("CRLF 不被当成事件名或 JSON 的一部分", () => {
|
||||
const p = createFrameParser();
|
||||
const events = p.push('id: 3\r\nevent: new_mail\r\ndata: {"n":1}\r\n\r\n');
|
||||
assert.equal(events.length, 1);
|
||||
assert.equal(events[0].event, 'new_mail');
|
||||
assert.equal(events[0].id, '3');
|
||||
assert.equal(events[0].event, "new_mail");
|
||||
assert.equal(events[0].id, "3");
|
||||
assert.deepEqual(parse(events[0].data), { n: 1 });
|
||||
});
|
||||
|
||||
test('事件 id 只向前推进:重放旧 id 不回退断点', () => {
|
||||
test("事件 id 只向前推进:重放旧 id 不回退断点", () => {
|
||||
const p = createFrameParser();
|
||||
p.push('id: 10\nevent: new_mail\ndata: {"n":1}\n\n');
|
||||
assert.equal(p.lastEventId(), '10');
|
||||
assert.equal(p.lastEventId(), "10");
|
||||
// 服务端重放一条更早的事件:断点不该退回 5,否则下次重连会重复回放 6..10
|
||||
p.push('id: 5\nevent: new_mail\ndata: {"n":0}\n\n');
|
||||
assert.equal(p.lastEventId(), '5', '解析器如实记录当前 id(是否回退由使用方决定)');
|
||||
assert.equal(
|
||||
p.lastEventId(),
|
||||
"5",
|
||||
"解析器如实记录当前 id(是否回退由使用方决定)",
|
||||
);
|
||||
});
|
||||
|
||||
test('id 在派发前记录:回调抛异常也不丢断点', () => {
|
||||
test("id 在派发前记录:回调抛异常也不丢断点", () => {
|
||||
const p = createFrameParser();
|
||||
p.push('id: 42\nevent: new_mail\ndata: {"n":1}\n\n');
|
||||
assert.equal(p.lastEventId(), '42');
|
||||
assert.equal(p.lastEventId(), "42");
|
||||
});
|
||||
|
||||
test('只有 data 没有 event 不派发(避免把心跳数据当事件)', () => {
|
||||
test("只有 data 没有 event 不派发(避免把心跳数据当事件)", () => {
|
||||
const p = createFrameParser();
|
||||
const events = p.push('data: {"orphan":true}\n\n');
|
||||
assert.deepEqual(events, []);
|
||||
});
|
||||
|
||||
test('reset 清缓冲但保留断点(重连后仍能续传)', () => {
|
||||
test("reset 清缓冲但保留断点(重连后仍能续传)", () => {
|
||||
const p = createFrameParser();
|
||||
p.push('id: 99\nevent: a\ndata: {"n":1}\n\n');
|
||||
p.push('event: partial'); // 半帧
|
||||
p.push("event: partial"); // 半帧
|
||||
p.reset();
|
||||
assert.equal(p.lastEventId(), '99', '断点必须保留,否则重连从头回放');
|
||||
assert.equal(p.lastEventId(), "99", "断点必须保留,否则重连从头回放");
|
||||
// reset 后半帧不该复活
|
||||
const after = p.push('data: {"n":2}\n\n');
|
||||
assert.deepEqual(after, []);
|
||||
});
|
||||
|
||||
test('setLastEventId 清空 = 换 Gateway 后不再拿旧序号问新服务端', () => {
|
||||
test("setLastEventId 清空 = 换 Gateway 后不再拿旧序号问新服务端", () => {
|
||||
const p = createFrameParser();
|
||||
p.push('id: 123\nevent: a\ndata: {"n":1}\n\n');
|
||||
assert.equal(p.lastEventId(), '123');
|
||||
assert.equal(p.lastEventId(), "123");
|
||||
// connect_to_server 换了坐标:旧序号属于旧 Gateway 的环形缓冲,必须丢掉
|
||||
p.setLastEventId('');
|
||||
assert.equal(p.lastEventId(), '', '首次连接不得携带 Last-Event-ID');
|
||||
p.setLastEventId("");
|
||||
assert.equal(p.lastEventId(), "", "首次连接不得携带 Last-Event-ID");
|
||||
});
|
||||
|
||||
@ -404,4 +404,3 @@ func contains(list []string, v string) bool {
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user