chore(format): 撤销误入提交的整体重排,并关闭本仓库的格式化器

# 发生了什么

pi-lens 内置「安全格式化」:它会自动安装 biome 并对**编辑过的文件**跑
`biome format --write`。本机原先没有任何 biome 配置,于是 biome 用它自己的
默认值 —— tab 缩进 + 双引号 —— 把文件整体重写。

我在 19a3161 那次提交里用了 `git add -A`,把这批与功能无关的重排一起扫了进去:
约 7000 行改动散落在 20 个文件上,使那次提交无法审查,还掩盖了
server/internal/handler/permission.go 的一处删行(实为文件末尾空行,无代码丢失)。

# 为什么是「关掉」而不是「配置成我们的风格」

试过把缩进/引号/lineWidth 全部对齐本仓库习惯(biome.json + space/2/single/
lineWidth 120):`biome format --write` 仍然改动 17 个文件。原因是本仓库从未按
biome 的规则排版过 —— 注释按语义换行、数组与调用按可读性手工折行,
这些无法由格式化器还原。也就是说只要格式化器开着,每次编辑都会产生与内容无关的
大面积 diff,把真正的改动埋掉。

因此 biome.jsonc 里 formatter 与 linter 都关闭:本仓库的静态检查由
tsc / go vet / tree-sitter / ast-grep 与各自测试套件承担,不引入会改动无关行的
自动修复。

(pi-lens 这一版把 format 服务的 enabled 硬编码为 true,没有配置开关,
所以只能在仓库侧用 biome 配置让它不动文件;已验证 `biome format --write`
对这些文件零改动。)

# 本提交内容

把 19a3161 里除「有意改动」外的 20 个文件还原到重排前的样子。
19a3161 中真正有意的改动是 deploy/install.sh 的扩展注册与
plugins/pi-mail-bridge/extension/index.ts 新文件,两者原样保留。

验证:Go 全量、三桥插件(320/362/409)、前端 196 全绿;
`biome format --write` 对还原后的文件零改动。
This commit is contained in:
2026-09-11 12:03:51 +08:00
parent 19a3161ee4
commit 429149e118
21 changed files with 5603 additions and 6668 deletions

View File

@ -34,61 +34,59 @@
* 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");
// 最后一段可能是被切断的半行,留到下一个 chunk
buffer = lines.pop() ?? "";
function push(chunk) {
buffer += chunk;
const events = [];
const lines = buffer.split('\n');
// 最后一段可能是被切断的半行,留到下一个 chunk
buffer = lines.pop() ?? '';
for (let line of lines) {
if (line.length > 0 && line.charAt(line.length - 1) === "\r") {
line = line.slice(0, -1);
}
if (line.startsWith(":")) continue;
for (let line of lines) {
if (line.length > 0 && line.charAt(line.length - 1) === '\r') {
line = line.slice(0, -1);
}
if (line.startsWith(':')) continue;
if (line.startsWith("id:")) {
curId = line.slice(3).trim();
} else if (line.startsWith("event:")) {
curEvent = line.slice(6).trim();
} else if (line.startsWith("data:")) {
let value = line.slice(5);
if (value.startsWith(" ")) value = value.slice(1);
curData = curData.length > 0 ? `${curData}\n${value}` : value;
} 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 = "";
}
}
return events;
}
if (line.startsWith('id:')) {
curId = line.slice(3).trim();
} else if (line.startsWith('event:')) {
curEvent = line.slice(6).trim();
} else if (line.startsWith('data:')) {
let value = line.slice(5);
if (value.startsWith(' ')) value = value.slice(1);
curData = curData.length > 0 ? `${curData}\n${value}` : value;
} 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 = '';
}
}
return events;
}
function reset() {
buffer = "";
curEvent = "";
curData = "";
curId = "";
}
function reset() {
buffer = '';
curEvent = '';
curData = '';
curId = '';
}
return {
push,
reset,
lastEventId: () => lastEventId,
setLastEventId: (id) => {
lastEventId = id || "";
},
};
return {
push,
reset,
lastEventId: () => lastEventId,
setLastEventId: (id) => { lastEventId = id || ''; },
};
}
/**
@ -100,93 +98,82 @@ 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,
}) {
const controller = new AbortController();
const parser = createFrameParser();
export function createSSEClient({ authHeaders, baseURL, path, onEvent, log = console.error }) {
const controller = new AbortController();
const parser = createFrameParser();
function stop() {
controller.abort();
}
function stop() {
controller.abort();
}
function reconnect(delay) {
if (controller.signal.aborted) return;
setTimeout(() => connect(), delay);
}
function reconnect(delay) {
if (controller.signal.aborted) return;
setTimeout(() => connect(), delay);
}
function connect() {
if (controller.signal.aborted) return;
function connect() {
if (controller.signal.aborted) return;
const headers = { ...authHeaders(), Accept: "text/event-stream" };
// 只有 lastEventId 非空(= 已经收过事件)时才是重连:首次连接不带,
// 否则服务端会把环形缓冲里的旧事件全回放一遍,插件重启后重复处理一批已处理的邮件。
const lastEventID = parser.lastEventId();
if (lastEventID) {
headers["Last-Event-ID"] = lastEventID;
log(`SSE 重连,从事件 ${lastEventID} 之后续传`);
}
const headers = { ...authHeaders(), Accept: 'text/event-stream' };
// 只有 lastEventId 非空(= 已经收过事件)时才是重连:首次连接不带,
// 否则服务端会把环形缓冲里的旧事件全回放一遍,插件重启后重复处理一批已处理的邮件。
const lastEventID = parser.lastEventId();
if (lastEventID) {
headers['Last-Event-ID'] = lastEventID;
log(`SSE 重连,从事件 ${lastEventID} 之后续传`);
}
fetch(`${baseURL}${path}`, { headers, signal: controller.signal })
.then((res) => {
if (!res.ok || !res.body) {
log(`SSE 建连失败: HTTP ${res.status}`);
return reconnect(5000);
}
const reader = res.body.getReader();
const decoder = new TextDecoder();
fetch(`${baseURL}${path}`, { headers, signal: controller.signal })
.then((res) => {
if (!res.ok || !res.body) {
log(`SSE 建连失败: HTTP ${res.status}`);
return reconnect(5000);
}
const reader = res.body.getReader();
const decoder = new TextDecoder();
function read() {
reader
.read()
.then(({ done, value }) => {
if (done) {
parser.reset();
return reconnect(3000);
}
for (const ev of parser.push(
decoder.decode(value, { stream: true }),
)) {
try {
onEvent(ev.event, JSON.parse(ev.data));
} catch (e) {
log(`SSE 事件处理失败: ${e?.message || e}`);
}
}
read();
})
.catch((e) => {
if (controller.signal.aborted) return;
log(`SSE 读取中断: ${e?.message || e}`);
parser.reset();
reconnect(5000);
});
}
read();
})
.catch((e) => {
if (controller.signal.aborted) return;
log(`SSE 连接错误: ${e?.message || e}`);
parser.reset();
reconnect(5000);
});
}
function read() {
reader.read().then(({ done, value }) => {
if (done) {
parser.reset();
return reconnect(3000);
}
for (const ev of parser.push(decoder.decode(value, { stream: true }))) {
try {
onEvent(ev.event, JSON.parse(ev.data));
} catch (e) {
log(`SSE 事件处理失败: ${e?.message || e}`);
}
}
read();
}).catch((e) => {
if (controller.signal.aborted) return;
log(`SSE 读取中断: ${e?.message || e}`);
parser.reset();
reconnect(5000);
});
}
read();
})
.catch((e) => {
if (controller.signal.aborted) return;
log(`SSE 连接错误: ${e?.message || e}`);
parser.reset();
reconnect(5000);
});
}
connect();
connect();
return {
stop,
/**
* 清掉断点(不终止连接)。
*
* 换 Gateway 地址时必须调lastEventID 是**旧** Gateway 环形缓冲里的序号,
* 拿去问新 Gateway 会命中一段完全无关的历史(或直接被拒),
* 得到的事件属于别人的会话。
*/
reset: () => parser.setLastEventId(""),
};
return {
stop,
/**
* 清掉断点(不终止连接)。
*
* 换 Gateway 地址时必须调lastEventID 是**旧** Gateway 环形缓冲里的序号,
* 拿去问新 Gateway 会命中一段完全无关的历史(或直接被拒),
* 得到的事件属于别人的会话。
*/
reset: () => parser.setLastEventId(''),
};
}

View File

@ -32,25 +32,23 @@
/** 问题是否带可选项。 */
export function hasOptions(question) {
return Array.isArray(question?.options) && question.options.length > 0;
return Array.isArray(question?.options) && question.options.length > 0;
}
/** 一个 DSH 问题的可选项 label 列表(保序)。 */
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);
if (!hasOptions(question)) return [];
return question.options
.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() : "";
if (header && text) return `${header}: ${text}`;
return header || text || "(未提供问题)";
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 || '(未提供问题)';
}
/**
@ -60,56 +58,51 @@ export function questionTitle(question) {
* @returns {{ question: string, options: string[], context: string, multiSelect: boolean }}
*/
export function flattenQuestions(questions) {
const list = Array.isArray(questions) ? questions.filter(Boolean) : [];
if (list.length === 0) {
throw new Error("ask_user_question 至少需要一个 question");
}
const list = Array.isArray(questions) ? questions.filter(Boolean) : [];
if (list.length === 0) {
throw new Error('ask_user_question 至少需要一个 question');
}
const lines = [];
const options = [];
const seen = new Set();
let anyMulti = false;
const lines = [];
const options = [];
const seen = new Set();
let anyMulti = false;
list.forEach((q, i) => {
const title = questionTitle(q);
lines.push(`${i + 1}. ${title}`);
const detail = typeof q?.detail === "string" ? q.detail.trim() : "";
if (detail) lines.push(` ${detail}`);
list.forEach((q, i) => {
const title = questionTitle(q);
lines.push(`${i + 1}. ${title}`);
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 ? "(可多选)" : ""}`,
);
for (const label of labels) {
if (!seen.has(label)) {
seen.add(label);
options.push(label);
}
}
} else {
lines.push(" (请直接填写回答)");
}
if (q?.multiSelect === true) anyMulti = true;
});
const labels = optionLabels(q);
if (labels.length > 0) {
lines.push(` 可选项:${labels.join(' / ')}${q.multiSelect ? '(可多选)' : ''}`);
for (const label of labels) {
if (!seen.has(label)) {
seen.add(label);
options.push(label);
}
}
} else {
lines.push(' (请直接填写回答)');
}
if (q?.multiSelect === true) anyMulti = true;
});
// 多问题时必须允许多选:不同问题的选项要能一起勾选。
const multiSelect = list.length > 1 ? options.length > 0 : anyMulti;
// 多问题时必须允许多选:不同问题的选项要能一起勾选。
const multiSelect = list.length > 1 ? options.length > 0 : anyMulti;
const question =
list.length === 1 ? questionTitle(list[0]) : `${list.length} 个问题待回答`;
const context = [
list.length === 1 ? "" : "模型提出了多个问题,请在「回复」里一并回答:",
...lines,
"",
options.length > 0
? "可直接勾选下方的选项;补充说明写在备注里。"
: "这题没有预设选项,请把回答写在备注里。",
]
.filter((l) => l !== "")
.join("\n");
const question = list.length === 1 ? questionTitle(list[0]) : `${list.length} 个问题待回答`;
const context = [
list.length === 1 ? '' : '模型提出了多个问题,请在「回复」里一并回答:',
...lines,
'',
options.length > 0
? '可直接勾选下方的选项;补充说明写在备注里。'
: '这题没有预设选项,请把回答写在备注里。',
].filter((l) => l !== '').join('\n');
return { question, options, context, multiSelect };
return { question, options, context, multiSelect };
}
/**
@ -121,55 +114,51 @@ export function flattenQuestions(questions) {
* @returns {{ answers: Array<{id: string, selected: string[], custom?: string}> }}
*/
export function answersFromDecision(questions, decision, note) {
const list = Array.isArray(questions) ? questions.filter(Boolean) : [];
const labels = String(decision || "")
.split("\n")
.map((s) => s.trim())
.filter(Boolean);
const custom = typeof note === "string" ? note.trim() : "";
const list = Array.isArray(questions) ? questions.filter(Boolean) : [];
const labels = String(decision || '')
.split('\n')
.map((s) => s.trim())
.filter(Boolean);
const custom = typeof note === 'string' ? note.trim() : '';
// 单问题:忠实映射(选项 → selected备注 → custom
if (list.length === 1) {
const q = list[0];
const id = String(q?.id ?? "0");
if (!hasOptions(q)) {
// 无选项题:人类把答案写在决策文本或备注里,都属于「自由文本回答」。
const text = custom || labels.join("\n");
return {
answers: [{ id, selected: [], ...(text ? { custom: text } : {}) }],
};
}
return {
answers: [
{
id,
selected: labels,
...(custom ? { custom } : {}),
},
],
};
}
// 单问题:忠实映射(选项 → selected备注 → custom
if (list.length === 1) {
const q = list[0];
const id = String(q?.id ?? '0');
if (!hasOptions(q)) {
// 无选项题:人类把答案写在决策文本或备注里,都属于「自由文本回答」。
const text = custom || labels.join('\n');
return { answers: [{ id, selected: [], ...(text ? { custom: text } : {}) }] };
}
return {
answers: [{
id,
selected: labels,
...(custom ? { custom } : {}),
}],
};
}
// 多问题:按 label 归属把选择分配给各自的问题;备注归给第一个问题。
let customUsed = false;
const answers = list.map((q, i) => {
const id = String(q?.id ?? String(i));
const labels_q = optionLabels(q);
const selected = labels.filter((l) => labels_q.includes(l));
let qCustom;
if (custom && !customUsed) {
qCustom = custom;
customUsed = true;
}
// 无选项题且人没写备注:退而把决策文本整段给它(否则它的答案永远是空的)。
if (qCustom === undefined && !hasOptions(q) && note === undefined) {
const text = labels.join("\n");
if (text) qCustom = text;
}
return { id, selected, ...(qCustom ? { custom: qCustom } : {}) };
});
// 多问题:按 label 归属把选择分配给各自的问题;备注归给第一个问题。
let customUsed = false;
const answers = list.map((q, i) => {
const id = String(q?.id ?? String(i));
const labels_q = optionLabels(q);
const selected = labels.filter((l) => labels_q.includes(l));
let qCustom;
if (custom && !customUsed) {
qCustom = custom;
customUsed = true;
}
// 无选项题且人没写备注:退而把决策文本整段给它(否则它的答案永远是空的)。
if (qCustom === undefined && !hasOptions(q) && note === undefined) {
const text = labels.join('\n');
if (text) qCustom = text;
}
return { id, selected, ...(qCustom ? { custom: qCustom } : {}) };
});
return { answers };
return { answers };
}
/**
@ -178,13 +167,10 @@ 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() : "";
if (labels.length > 0 || custom) return false;
// 全部问题都没有选项、人也没写字 → 确实什么都没答
const list = Array.isArray(questions) ? questions.filter(Boolean) : [];
return list.some((q) => hasOptions(q)) || list.length === 0;
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) : [];
return list.some((q) => hasOptions(q)) || list.length === 0;
}