Files
MailUI4Agents/web/src/api/client.ts
JianFeeeee 07e6b789b2 feat: 配额下沉到会话 + 窄屏覆盖式布局 + 工作列表卡片视图
## 配额重构:废除 Agent 终身额度

原实现在 agents 上放一个 max_rounds/used_rounds 计数器,used_rounds 单调递增、
永不重置 —— 跑满就要管理员手工重置才能再干活。那是把一次性资源模型套在长期
在线的服务上,且并行任务互相抢额度。

改为:
- 唯一被强制的预算是【会话】的往返预算(sessions.max_rounds/used_rounds),
  写信时给、对话页里随时改 —— 配额的语义是「这件事值得多少个来回」,
  那是任务的属性而不是 Agent 的属性
- agents.default_rounds 只作为「派给这个 Agent 的新任务」的默认值(默认 20)
- agents.used_rounds 降级为纯统计
- 新建会话速率限制(1h/20 条)堵住用 .new 开一串新会话绕过预算;
  人类不受限(agentLimiterKey 返回空串即不计量)

## 窄屏适配(用户反馈「窄屏基本不可用」)

原先只有三栏并排:60(导航)+320(列表)+详情,375px 屏上详情被挤到 0。

第一版做成「一次只显示一栏」,用户纠正应当是新页面覆盖老页面并带动画,
于是重做为覆盖式:
- NarrowStack:底层列表始终挂载,详情绝对定位盖在上面。两个好处 ——
  列表滚动位置与选中态天然保留;退出动画有东西可播(直接卸载再渲染另一个
  组件的话,没有任何一帧能让旧页面往右滑出去)
- 因此必须区分「逻辑上是否打开」与「是否还在 DOM 里」:关闭时先播 200ms
  滑出,动画结束才卸载
- 入场用双层 requestAnimationFrame:必须让浏览器至少绘制一帧「在右侧之外」
  的状态,否则挂载与 translate-x-0 在同一帧内完成,transition 不触发
- 窄屏专属控件用 useIsNarrow() 条件渲染而非 md:hidden —— 后者只是视觉隐藏,
  宽屏用户按 Tab 会聚焦到看不见的返回按钮
- 底部导航 + 抽屉侧栏 + env(safe-area-inset-bottom)

## 工作列表卡片视图(Phase 7.1 最后一项)

中间栏可切列表/卡片。列表答「跟谁在聊」,卡片答「在聊什么、进展如何」:
主题 + 最新一封的发件人与摘要 + 往返预算徽标。

- 两种视图共用同一份数据与同一套动作;归档确认框也共用 —— 归档是破坏性操作,
  换个视图就换套确认 UI 只会让人对「自己点了什么」更没底
- 预算徽标在「不限」时不显示(对每张卡片都成立的「0/0」是纯噪声)
- 数据一次取回,不让卡片为每条会话再打一次库

## 修掉的缺陷

- GET /me/sessions 一直 500:ListSessionsFor 的 SELECT 加了预算两列却没加进
  Scan,列数不匹配。联系人栏一条数据都拉不到,而错误只是「Failed to list sessions」
- GET /sessions/{id} 忘了填充附件:前端会话视图走的是这个端点,于是 Agent
  回信里的附件在 UI 上完全不存在(另一个端点填了但没人调用)
- 插件曾完全没在加载:为了可测在 index.js 里 export 了辅助函数与一个 Map,
  而 opencode 把入口模块的每一个导出都当成插件工厂逐个检查,多导出一个 Map
  就 "Plugin export is not a function",插件静默失效、邮件全投不进去。
  逻辑挪到 lib/relay-dedup.js,并加断言钉住「入口只有 default 导出」
- 同一件事发两封邮件:模型带附件主动回信后,session.idle 又把它最后那段话
  自动转了一遍(生产实测 311 与 342 字节各一封)。explicitSends 记录本轮
  主动发信,自动转发据此让位;relay_key 幂等管不了这个 —— 那个键保证的是
  「同一条消息不转两次」
- SQLite 时间戳只有秒精度:同秒插入的多封邮件排序不确定(实测同秒插 5 封,
  顺序由随机 UUID 决定)。「会话里最早那封」(决定联系人身份)与「最后那封」
  (决定最新进展)都会取错。NOW() 升到微秒 + mails 的 INSERT 显式传它
  (改 schema 默认值只对新库生效,SQLite 没有 ALTER COLUMN)+ 所有
  ORDER BY created_at 补 mail_id 兜底
- fillAttachments 从逐封查询改成一次 IN(...):原来是 N+1,200 封的会话打开
  要打 200 次库
- repo 层 5 处 rows.Next() 循环补 rows.Err():没有它,读到一半连接断掉会
  静默返回部分结果,UI 上表现为「邮件凭空少了几封」
- go:embed 占位页改名 placeholder.html:叫 index.html 会被 Vite 产物覆盖并
  提交进去,而它引用的 assets/ 是被忽略的 —— 新克隆打开是白屏

## 回复/转发栏

- 两处都加抄送(可折叠);原邮件带抄送时多一个「回复全部」,回填用
  cc_list[].raw 而非重拼 name@path(后者会丢掉会话段)
- 会话视图每张卡片加转发入口:转发之前只存在于单封邮件视图,而人多数时间
  待在会话视图里,等于功能在 UI 上找不到
- ReplyBar 的错误从 console.error 改为显示出来:预算耗尽、地址不存在、
  速率限制都走这条路,之前点发送毫无反应

## 测试

- repo: 列顺序(三个 SQL 分支)、卡片字段、previewRunes 边界、时间戳亚秒精度、
  批量附件查询、速率限制(80 goroutine 断言恰好 20 条通过)
- web: 窄屏布局 16 条结构性断言(覆盖而非分栏、延迟卸载、双层 rAF、
  条件渲染而非 md:hidden)
- 插件: 自动转发去重 17 条(含「入口只有 default 导出」不变量)
- install.sh 把插件测试也纳入部署前门禁
2026-09-02 14:16:46 +08:00

498 lines
15 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import type { User } from '../types';
import type { Agent, Attachment, Contact, HumanSession, Mail, PermissionRequest, SuggestResult, SessionDetail, ThreadPage, RenameProposal, SessionBudget } from '../types';
import { API_BASE, authHeaders, withToken } from './config';
export { API_BASE, setToken, getToken, authHeaders, withToken } from './config';
const BASE = API_BASE;
export class ApiError extends Error {
status: number;
retryAfter?: number;
constructor(status: number, message: string, retryAfter?: number) {
super(message);
this.status = status;
this.retryAfter = retryAfter;
}
}
let onUnauthorized: (() => void) | null = null;
export function setUnauthorizedHandler(fn: () => void) {
onUnauthorized = fn;
}
async function request<T>(method: string, path: string, body?: unknown): Promise<T> {
const init: RequestInit = {
method,
// Cookie 模式需要 include带 Bearer 时多发一个 Cookie 也无害
credentials: 'include',
headers: { 'Content-Type': 'application/json', ...authHeaders() }
};
if (body !== undefined) init.body = JSON.stringify(body);
const res = await fetch(`${BASE}${path}`, init);
if (!res.ok) {
const payload = await res.json().catch(() => ({ error: res.statusText }));
if (res.status === 401 && !path.startsWith('/auth/login') && !path.startsWith('/setup')) {
onUnauthorized?.();
}
throw new ApiError(res.status, payload.error || `HTTP ${res.status}`, payload.retry_after);
}
return res.json();
}
// ---------- 首次初始化 ----------
export async function setupStatus() {
return request<{ needs_setup: boolean }>('GET', '/setup/status');
}
export async function setupAdmin(payload: {
username: string;
password: string;
display_name?: string;
}) {
return request<{ user: User }>('POST', '/setup/admin', payload);
}
// ---------- 认证 ----------
export async function login(username: string, password: string) {
return request<{ user: User }>('POST', '/auth/login', { username, password });
}
export async function logout() {
return request<{ status: string }>('POST', '/auth/logout');
}
export async function me() {
return request<{ user: User }>('GET', '/auth/me');
}
export async function changePassword(oldPassword: string, newPassword: string) {
return request<{ status: string }>('POST', '/auth/password', {
old_password: oldPassword,
new_password: newPassword
});
}
// ---------- 管理员:用户管理 ----------
export async function adminListUsers() {
return request<{ users: User[] }>('GET', '/admin/users');
}
export async function adminCreateUser(payload: {
username: string;
password: string;
display_name?: string;
role?: string;
allowed_agents?: string[];
allowed_paths?: string[];
}) {
return request<{ user: User }>('POST', '/admin/users', payload);
}
export async function adminUpdateUser(
id: string,
payload: {
display_name?: string;
role?: string;
status?: string;
allowed_agents?: string[];
allowed_paths?: string[];
}
) {
return request<{ user: User }>('PUT', `/admin/users/${id}`, payload);
}
export async function adminDisableUser(id: string) {
return request<{ status: string }>('DELETE', `/admin/users/${id}`);
}
export async function adminResetPassword(id: string, newPassword: string) {
return request<{ status: string }>('POST', `/admin/users/${id}/reset`, {
new_password: newPassword
});
}
export async function adminListScopes() {
const r = await request<{ agents: string[]; paths: string[] }>('GET', '/admin/scopes');
return r;
}
// ---------- 密钥 ----------
export type KeyType = 'permanent' | 'one_time' | 'timed';
/** 密钥全文 key_token 仅在创建响应里出现一次,列表只给 token_hint。 */
export interface AgentKey {
key_id: string;
key_token?: string;
token_hint: string;
agent_name: string | null;
key_type: KeyType;
label: string;
expires_at: string | null;
used_at: string | null;
created_at: string;
}
export interface UserKey {
key_id: string;
key_token?: string;
token_hint: string;
label: string;
key_type: KeyType;
expires_at: string | null;
used_at: string | null;
created_at: string;
}
export interface CreateKeyPayload {
key_type: KeyType;
label?: string;
/** 仅 timed 需要 */
expires_hours?: number;
/** 仅 Agent 密钥:留空 = 待绑定,首次注册时落定 */
agent_name?: string;
/** 仅 Agent 密钥:登记客户端已在本地生成的密钥 */
key_token?: string;
}
export async function adminListAgentKeys(agentName?: string) {
const q = agentName ? `?agent_name=${encodeURIComponent(agentName)}` : '';
return request<{ keys: AgentKey[] }>('GET', `/admin/agent-keys${q}`);
}
export async function adminCreateAgentKey(payload: CreateKeyPayload) {
return request<{ key: AgentKey }>('POST', '/admin/agent-keys', payload);
}
export async function adminDeleteAgentKey(id: string) {
return request<{ status: string }>('DELETE', `/admin/agent-keys/${id}`);
}
export async function adminBindAgentKey(id: string, agentName: string) {
return request<{ status: string; agent_name: string }>(
'POST',
`/admin/agent-keys/${id}/bind`,
{ agent_name: agentName }
);
}
export async function listMyKeys() {
return request<{ keys: UserKey[] }>('GET', '/me/keys');
}
export async function createMyKey(payload: CreateKeyPayload) {
return request<{ key: UserKey }>('POST', '/me/keys', payload);
}
export async function deleteMyKey(id: string) {
return request<{ status: string }>('DELETE', `/me/keys/${id}`);
}
// ---------- Agents ----------
export async function listAgents(status?: string) {
const q = status ? `?status=${encodeURIComponent(status)}` : '';
return request<{ agents: Agent[] }>('GET', `/agents${q}`);
}
// ---------- 自己的邮箱 ----------
export interface SendMailOpts {
cc?: string;
reply_to?: string;
/** 仅在用 .new 新建会话时生效:给新会话命名,之后可用 name@path.<别名> 续谈 */
session_alias?: string;
/** 先用 uploadAttachment 上传取得的 id 列表 */
attachment_ids?: string[];
/**
* 本任务的往返预算0/省略 = 不限)。仅在新建会话时生效;
* 续谈已有会话请用 updateSessionBudget对话页里可随时改
*/
max_rounds?: number;
}
export async function sendMail(
to: string,
subject: string,
body: string,
opts: SendMailOpts = {}
) {
return request<{
mail_id: string;
session_id: string;
session_alias: string;
budget_max?: number;
budget_used?: number;
budget_remaining?: number;
}>('POST', '/me/mail/send', {
to,
subject,
body,
cc: opts.cc ?? '',
reply_to: opts.reply_to ?? '',
session_alias: opts.session_alias ?? '',
attachment_ids: opts.attachment_ids ?? [],
// null 而非 00 是「不限」的合法取值,省略才表示「不设置」
max_rounds: opts.max_rounds ?? null
});
}
export async function getInbox(status = 'all', limit = 50) {
return request<{ mails: Mail[]; total: number }>(
'GET',
`/me/mail/inbox?status=${encodeURIComponent(status)}&limit=${limit}`
);
}
export async function getSent() {
return request<{ mails: Mail[] }>('GET', '/me/mail/sent');
}
export async function getMail(id: string) {
return request<Mail>('GET', `/mail/${id}`);
}
export async function markMailRead(id: string) {
return request<{ status: string }>('POST', `/mail/${id}/read`);
}
/**
* 取线索的一块。
*
* dir=around 首屏(锚点 + 部分祖先 + 部分子孙up/down 配 offset 增量加载。
* 树可跨会话,服务端按会话逐个鉴权,看不到的节点不返回并计入 hidden。
*/
export async function getMailThread(
id: string,
opts: { dir?: 'around' | 'up' | 'down'; offset?: number; limit?: number } = {}
) {
const q = new URLSearchParams();
if (opts.dir) q.set('dir', opts.dir);
if (opts.offset !== undefined) q.set('offset', String(opts.offset));
if (opts.limit !== undefined) q.set('limit', String(opts.limit));
const qs = q.toString();
return request<ThreadPage>('GET', `/mail/${id}/thread${qs ? '?' + qs : ''}`);
}
// ---------- 附件 ----------
/**
* 上传附件,返回 attachment_id。
*
* 不能走 request():那里固定 Content-Type: application/json
* 而 multipart 必须让浏览器自己带 boundary。
*/
export async function uploadAttachment(file: File, onProgress?: (pct: number) => void) {
const form = new FormData();
form.append('file', file);
// 需要进度就用 XHR —— fetch 至今没有上传进度事件
if (onProgress) {
return new Promise<{ attachment: Attachment }>((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open('POST', `${BASE}/me/attachments`);
xhr.withCredentials = true;
for (const [k, v] of Object.entries(authHeaders())) xhr.setRequestHeader(k, v);
xhr.upload.onprogress = e => {
if (e.lengthComputable) onProgress(Math.round((e.loaded / e.total) * 100));
};
xhr.onload = () => {
let payload: { attachment?: Attachment; error?: string } = {};
try {
payload = JSON.parse(xhr.responseText);
} catch {
/* 非 JSON 响应按状态码处理 */
}
if (xhr.status >= 200 && xhr.status < 300 && payload.attachment) {
resolve({ attachment: payload.attachment });
} else {
if (xhr.status === 401) onUnauthorized?.();
reject(new ApiError(xhr.status, payload.error || `HTTP ${xhr.status}`));
}
};
xhr.onerror = () => reject(new ApiError(0, '网络错误'));
xhr.send(form);
});
}
const res = await fetch(`${BASE}/me/attachments`, {
method: 'POST',
credentials: 'include',
// 不设 Content-Typemultipart 的 boundary 要交给浏览器生成
headers: authHeaders(),
body: form
});
if (!res.ok) {
const payload = await res.json().catch(() => ({ error: res.statusText }));
if (res.status === 401) onUnauthorized?.();
throw new ApiError(res.status, payload.error || `HTTP ${res.status}`);
}
return res.json() as Promise<{ attachment: Attachment }>;
}
export async function deleteAttachment(id: string) {
return request<{ status: string }>('DELETE', `/me/attachments/${id}`);
}
/**
* 附件下载链接。由浏览器直接发起(<a download>),因此无法带 Authorization 头:
* Cookie 模式靠同源 Cookie密钥模式回退到 ?access_token=。
*/
export function attachmentURL(id: string) {
return withToken(`${BASE}/me/attachments/${id}`);
}
/** 人类可读的字节数 */
export function formatSize(n: number) {
if (n < 1024) return `${n} B`;
if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;
return `${(n / 1024 / 1024).toFixed(1)} MB`;
}
export interface ForwardPayload {
/** 新收件人的三维地址 */
to: string;
/** 转发说明,置于引用原文之前 */
comment?: string;
cc?: string;
/** 留空则自动加 Fwd: 前缀 */
subject?: string;
/** 仅当 to 以 .new 结尾时生效 */
session_alias?: string;
}
export async function forwardMail(id: string, payload: ForwardPayload) {
return request<{
mail_id: string;
session_id: string;
session_alias: string;
forwarded_from: string;
}>('POST', `/me/mail/${id}/forward`, {
to: payload.to,
comment: payload.comment ?? '',
cc: payload.cc ?? '',
subject: payload.subject ?? '',
session_alias: payload.session_alias ?? ''
});
}
// ---------- 配额 ----------
/**
* Agent 的新任务默认预算与累计统计。
*
* 没有「剩余额度」字段 —— 额度属于具体任务(会话),见 SessionBudget。
* 这里只有「派给它的新任务默认几个来回」与「一共发了多少信」。
*/
export interface AgentStats {
agent_name: string;
/** 派给该 Agent 的新任务默认多少个来回0 = 不限) */
default_rounds: number;
/** 累计发信数,纯统计,不拦请求 */
sent_total: number;
/** 参与的未归档会话数,配合默认值判断设多少合适 */
active_sessions: number;
}
export async function adminListAgentStats() {
return request<{ quotas: AgentStats[] }>('GET', '/admin/quotas');
}
/** 改该 Agent 的新任务默认预算0 = 不限)。 */
export async function adminSetDefaultRounds(agentName: string, defaultRounds: number) {
return request<{ quota: AgentStats }>(
'PUT',
`/admin/quotas/${encodeURIComponent(agentName)}`,
{ default_rounds: defaultRounds }
);
}
// ---------- Sessions ----------
export async function getHumanSessions() {
return request<{ sessions: HumanSession[] }>('GET', '/me/sessions');
}
export async function getSessionDetail(id: string) {
return request<SessionDetail>('GET', `/sessions/${id}`);
}
export async function updateSessionAlias(id: string, alias: string) {
return request<{ status: string; alias: string }>('PUT', `/sessions/${id}/alias`, { alias });
}
/**
* 取该会话里最新一条尚未处理的改名提议Agent 在邮件正文里提的)。
* 已接受(提议就是当前别名)或已驳回的不再返回。
*/
export async function getRenameProposal(id: string) {
return request<{ proposal: RenameProposal | null }>('GET', `/sessions/${id}/rename-proposal`);
}
/** 本会话(= 本任务)的往返预算。 */
export async function getSessionBudget(id: string) {
return request<SessionBudget>('GET', `/sessions/${id}/budget`);
}
/**
* 改本会话的往返预算。
*
* max_rounds = 0 表示不限reset 把已用次数归零。两者可同时给
* (「加到 20 并从头算」是一次很自然的操作,拆成两个请求只会多一次往返)。
*/
export async function updateSessionBudget(
id: string,
patch: { max_rounds?: number; reset?: boolean }
) {
return request<SessionBudget>('PUT', `/sessions/${id}/budget`, patch);
}
/** 驳回当前提议。记下来,提示条不再反复弹同一个建议。 */
export async function dismissRenameProposal(id: string) {
return request<{ status: string; dismissed?: string }>(
'POST',
`/sessions/${id}/rename-proposal/dismiss`
);
}
// ---------- Contacts ----------
export async function listContacts(archived = false) {
return request<{ contacts: Contact[] }>('GET', `/contacts?archived=${archived}`);
}
export async function suggestAddress(name?: string, path?: string) {
const p = new URLSearchParams();
if (name) p.set('name', name);
if (path) p.set('path', path);
return request<SuggestResult>('GET', `/contacts/suggest?${p.toString()}`);
}
export async function archiveContact(payload: { address?: string; session_id?: string }) {
return request<{ status: string; session_id: string; session_alias: string }>(
'POST',
'/contacts/archive',
payload
);
}
// ---------- Permission ----------
export async function decidePermission(mailId: string, decision: string, note?: string) {
return request<{ status: string; decision_mail_id: string }>('POST', '/permission/decide', {
mail_id: mailId,
decision,
note: note ?? ''
});
}
export async function listPendingPermissions() {
return request<{ requests: PermissionRequest[] }>('GET', '/permission/pending');
}