agent-loft 0.2.43 → 0.2.44
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -0
- package/package.json +1 -1
- package/src/channels/web/api.ts +106 -0
- package/src/core/hub.ts +14 -0
- package/src/core/reply-files.ts +142 -0
- package/src/core/uploads.ts +1 -1
- package/src/core/visualize.ts +123 -0
- package/web/css/messages.css +271 -0
- package/web/lib/markdown.js +5 -3
- package/web/views/file-preview.js +342 -0
- package/web/views/messages.js +3 -2
package/README.md
CHANGED
|
@@ -43,6 +43,7 @@ Logo 就是这个意思:一大两小几颗星(多个 agent)站在同一张
|
|
|
43
43
|
- 回复逐字显示,markdown 和代码高亮,思考过程和工具调用可以折叠;每条回复下方显示用时、费用和完成时间,可以复制,也可以「从这里分叉」成一条新会话(原会话不动);自己发的消息也能一键复制。
|
|
44
44
|
- 授权卡、提问卡直接在页面上点。
|
|
45
45
|
- 附件:粘贴、拖拽,手机上可以拍照;可以预览和下载。附件存在服务端的专用上传目录里,开新会话或切换目录时清理。
|
|
46
|
+
- 回复里提到的文件(链接、`路径`、正文里的绝对路径,Claude 和 Codex 都认)点一下就能预览:图片、PDF、音视频、markdown、代码和文本直接看,网页渲染出来看(也能切到源码),其它的下载。Codex 的 visualize 插件画的图表(回复里的 `visualize{"path":…}`)和官方客户端一样直接嵌在回复里。网页和图表放在沙箱里显示,碰不到登录态和本站接口。只认这条对话里 agent 回复写过的路径;私钥、`.ssh`、`.env`、各种凭据和 agent-loft 自己的配置数据一律不给看。
|
|
46
47
|
- 语音输入:用浏览器自带的语音识别(Chrome / Edge / Safari,需要 HTTPS)。
|
|
47
48
|
- 新对话页:点大标题里的目录名,在目录树里逐层选工作目录;输入框上方选 agent,右下角选模型和思考程度。会话进行中用 `/agent` 切换 agent,模型和思考程度随时可换。
|
|
48
49
|
- 输入框里的小圆环显示上下文窗口占用;模型按钮显示实际的模型和思考程度(如「Opus 5.5 high」)。
|
package/package.json
CHANGED
package/src/channels/web/api.ts
CHANGED
|
@@ -11,6 +11,8 @@ import { approve, listApproved, listPending, revoke } from "../../core/pairing.j
|
|
|
11
11
|
import { getConversation, listConversations, updateConversation } from "../../core/store.js";
|
|
12
12
|
import { addScheduled, clearScheduled, removeScheduled } from "../../core/scheduled.js";
|
|
13
13
|
import { resolveUploadFile, saveBuffer, sniff, uploadKeyOf } from "../../core/uploads.js";
|
|
14
|
+
import { mentions, replyFileType, resolveReplyFile } from "../../core/reply-files.js";
|
|
15
|
+
import { HTML_CSP, HTML_MAX, htmlDocument } from "../../core/visualize.js";
|
|
14
16
|
import {
|
|
15
17
|
createUser,
|
|
16
18
|
getUser,
|
|
@@ -133,6 +135,82 @@ function serveUpload(res: ServerResponse, user: User, requested: string, downloa
|
|
|
133
135
|
fs.createReadStream(file).pipe(res);
|
|
134
136
|
}
|
|
135
137
|
|
|
138
|
+
// ---------- agent 回复里提到的文件 ----------
|
|
139
|
+
|
|
140
|
+
/** 每条会话 agent 回复的全文(从 agent 记录里读,比较慢):缓存一会儿,一屏好几张图不用每张都读一遍 */
|
|
141
|
+
const replyTextCache = new Map<string, { at: number; text: string }>();
|
|
142
|
+
|
|
143
|
+
async function historyReplyText(key: string): Promise<string> {
|
|
144
|
+
const messages = await hub.history(key);
|
|
145
|
+
const text = messages.filter((m) => m.role === "assistant").map((m) => m.text).join("\n");
|
|
146
|
+
replyTextCache.delete(key);
|
|
147
|
+
replyTextCache.set(key, { at: Date.now(), text });
|
|
148
|
+
// 只留最近的几十条会话
|
|
149
|
+
for (const k of replyTextCache.keys()) {
|
|
150
|
+
if (replyTextCache.size <= 50) break;
|
|
151
|
+
replyTextCache.delete(k);
|
|
152
|
+
}
|
|
153
|
+
return text;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** 这条会话的 agent 回复里写没写过这个路径。缓存里没有、缓存又不是刚读的,就重读一次再说 */
|
|
157
|
+
async function replyMentions(key: string, requested: string): Promise<boolean> {
|
|
158
|
+
if (mentions(hub.recentReplyText(key), requested)) return true;
|
|
159
|
+
const cached = replyTextCache.get(key);
|
|
160
|
+
if (cached && mentions(cached.text, requested)) return true;
|
|
161
|
+
if (cached && Date.now() - cached.at < 3000) return false;
|
|
162
|
+
return mentions(await historyReplyText(key), requested);
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* 回复里的文件:stat=1 只回名字和大小;其余返回内容,支持 Range(视频拖进度、iOS 放视频都要它)。
|
|
167
|
+
* 图片、PDF、音视频按类型 inline,别的一律当下载 —— HTML 之类不能在本站域名下被当网页打开
|
|
168
|
+
*/
|
|
169
|
+
function serveReplyFile(req: IncomingMessage, res: ServerResponse, file: string, opts: { stat: boolean; download: boolean }): void {
|
|
170
|
+
const st = fs.statSync(file);
|
|
171
|
+
const name = path.basename(file);
|
|
172
|
+
if (opts.stat) {
|
|
173
|
+
sendJson(res, 200, { name, path: file, size: st.size, mtime: st.mtimeMs });
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
const type = replyFileType(file);
|
|
177
|
+
const inline = !opts.download && !!type;
|
|
178
|
+
const headers: Record<string, string | number> = {
|
|
179
|
+
...SECURITY_HEADERS,
|
|
180
|
+
"Content-Type": inline ? type! : "application/octet-stream",
|
|
181
|
+
"Content-Disposition": `${inline ? "inline" : "attachment"}; filename*=UTF-8''${encodeURIComponent(name)}`,
|
|
182
|
+
"Accept-Ranges": "bytes",
|
|
183
|
+
"Cache-Control": "private, no-cache",
|
|
184
|
+
"Last-Modified": new Date(st.mtimeMs).toUTCString(),
|
|
185
|
+
};
|
|
186
|
+
if (type === "application/pdf") {
|
|
187
|
+
// 预览窗里用 iframe 嵌 PDF:要允许本站嵌入。Chrome 带 sandbox 的文档不显示 PDF,这里不加
|
|
188
|
+
// (所有接口的响应事先都带上了 SECURITY_HEADERS,见 server.ts,这里得把那个也去掉)
|
|
189
|
+
delete headers["X-Frame-Options"];
|
|
190
|
+
res.removeHeader("X-Frame-Options");
|
|
191
|
+
headers["Content-Security-Policy"] = "default-src 'none'; frame-ancestors 'self'";
|
|
192
|
+
} else {
|
|
193
|
+
headers["Content-Security-Policy"] = "default-src 'none'; img-src 'self'; media-src 'self'; style-src 'unsafe-inline'; sandbox";
|
|
194
|
+
}
|
|
195
|
+
const range = /^bytes=(\d*)-(\d*)$/.exec(String(req.headers.range ?? ""));
|
|
196
|
+
if (range && (range[1] || range[2])) {
|
|
197
|
+
let start = range[1] ? Number(range[1]) : Math.max(0, st.size - Number(range[2]));
|
|
198
|
+
let end = range[1] && range[2] ? Math.min(Number(range[2]), st.size - 1) : st.size - 1;
|
|
199
|
+
if (start >= st.size || start > end) {
|
|
200
|
+
res.writeHead(416, { ...headers, "Content-Range": `bytes */${st.size}` });
|
|
201
|
+
res.end();
|
|
202
|
+
return;
|
|
203
|
+
}
|
|
204
|
+
start = Math.max(0, start);
|
|
205
|
+
end = Math.max(start, end);
|
|
206
|
+
res.writeHead(206, { ...headers, "Content-Range": `bytes ${start}-${end}/${st.size}`, "Content-Length": end - start + 1 });
|
|
207
|
+
fs.createReadStream(file, { start, end }).pipe(res);
|
|
208
|
+
return;
|
|
209
|
+
}
|
|
210
|
+
res.writeHead(200, { ...headers, "Content-Length": st.size });
|
|
211
|
+
fs.createReadStream(file).pipe(res);
|
|
212
|
+
}
|
|
213
|
+
|
|
136
214
|
// ---------- 飞书扫码创建应用 ----------
|
|
137
215
|
|
|
138
216
|
type Registration = {
|
|
@@ -761,6 +839,34 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
|
|
|
761
839
|
});
|
|
762
840
|
return;
|
|
763
841
|
}
|
|
842
|
+
// agent 回复里提到的文件:只认回复里写过的路径,敏感文件(私钥、凭据…)不给
|
|
843
|
+
if (sub === "file" && method === "GET") {
|
|
844
|
+
const requested = url.searchParams.get("path") ?? "";
|
|
845
|
+
const file = resolveReplyFile(requested, conv.cwd);
|
|
846
|
+
if (!file || !(await replyMentions(key, requested))) throw new HttpError(404, "文件不存在,或者不能查看");
|
|
847
|
+
serveReplyFile(req, res, file, { stat: url.searchParams.get("stat") === "1", download: url.searchParams.get("download") === "1" });
|
|
848
|
+
return;
|
|
849
|
+
}
|
|
850
|
+
// 回复里的 HTML(Codex visualize 画的图表、agent 写的网页):套好外壳放进沙箱显示,规矩和上面一样
|
|
851
|
+
if (sub === "html" && method === "GET") {
|
|
852
|
+
const requested = url.searchParams.get("path") ?? "";
|
|
853
|
+
const file = resolveReplyFile(requested, conv.cwd);
|
|
854
|
+
if (!file || !/\.html?$/i.test(file) || !(await replyMentions(key, requested))) throw new HttpError(404, "文件不存在,或者不能查看");
|
|
855
|
+
if (fs.statSync(file).size > HTML_MAX) throw new HttpError(413, "文件太大,下载下来看吧");
|
|
856
|
+
const doc = Buffer.from(htmlDocument(fs.readFileSync(file, "utf8"), path.basename(file)));
|
|
857
|
+
// 要能嵌进对话里:去掉所有响应默认带的 X-Frame-Options(见 server.ts)
|
|
858
|
+
res.removeHeader("X-Frame-Options");
|
|
859
|
+
res.writeHead(200, {
|
|
860
|
+
"X-Content-Type-Options": "nosniff",
|
|
861
|
+
"Referrer-Policy": "no-referrer",
|
|
862
|
+
"Content-Security-Policy": HTML_CSP,
|
|
863
|
+
"Content-Type": "text/html; charset=utf-8",
|
|
864
|
+
"Content-Length": doc.length,
|
|
865
|
+
"Cache-Control": "private, no-cache",
|
|
866
|
+
});
|
|
867
|
+
res.end(doc);
|
|
868
|
+
return;
|
|
869
|
+
}
|
|
764
870
|
if (sub === "upload" && method === "POST") {
|
|
765
871
|
const data = await readBody(req, 50 * 1024 * 1024);
|
|
766
872
|
const name = url.searchParams.get("name") ?? undefined;
|
package/src/core/hub.ts
CHANGED
|
@@ -403,6 +403,20 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd] }>
|
|
|
403
403
|
return buf.filter((e) => e.seq > since);
|
|
404
404
|
}
|
|
405
405
|
|
|
406
|
+
/**
|
|
407
|
+
* 缓冲区里 agent 回复的文字(含进行中这一轮已经流出来的)。刚出的回复 agent 的记录里可能还没写进去,
|
|
408
|
+
* 查回复里提到过哪些文件时和历史一起看
|
|
409
|
+
*/
|
|
410
|
+
recentReplyText(key: string): string {
|
|
411
|
+
const parts: string[] = [];
|
|
412
|
+
let streaming = "";
|
|
413
|
+
for (const { ev } of this.buffers.get(key) ?? []) {
|
|
414
|
+
if (ev.type === "delta") streaming += ev.text;
|
|
415
|
+
else if (ev.type === "text" || ev.type === "result") parts.push(ev.text);
|
|
416
|
+
}
|
|
417
|
+
return [...parts, streaming].join("\n");
|
|
418
|
+
}
|
|
419
|
+
|
|
406
420
|
/** 正在进行的这一轮(从最后一条用户消息起),给刚打开页面的客户端补画用。 */
|
|
407
421
|
liveTurn(key: string): EventEnvelope[] {
|
|
408
422
|
if (!this.isBusy(key)) return [];
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
// agent 回复里提到的文件:网页上点开预览 / 下载。
|
|
2
|
+
//
|
|
3
|
+
// 只放行这条会话的 agent 回复里真的写过的路径(防止拼个地址就读服务器上任意文件),
|
|
4
|
+
// 再挡掉密钥、凭据一类的敏感文件 —— agent 写过也不给看。
|
|
5
|
+
import fs from "node:fs";
|
|
6
|
+
import os from "node:os";
|
|
7
|
+
import path from "node:path";
|
|
8
|
+
import { home } from "../home.js";
|
|
9
|
+
import { uploadsRoot } from "./uploads.js";
|
|
10
|
+
|
|
11
|
+
/** 路径里出现这些目录名就不给看(私钥、云凭据、密码库…) */
|
|
12
|
+
const SENSITIVE_DIRS = new Set([".ssh", ".gnupg", ".aws", ".azure", ".kube", ".docker", ".password-store", ".gcloud"]);
|
|
13
|
+
|
|
14
|
+
/** 家目录下这些位置不给看(相对家目录) */
|
|
15
|
+
const SENSITIVE_HOME = [
|
|
16
|
+
".config/gcloud",
|
|
17
|
+
".config/gh",
|
|
18
|
+
".claude/.credentials.json",
|
|
19
|
+
".codex/auth.json",
|
|
20
|
+
".netrc",
|
|
21
|
+
".git-credentials",
|
|
22
|
+
".npmrc",
|
|
23
|
+
".pypirc",
|
|
24
|
+
];
|
|
25
|
+
|
|
26
|
+
/** 系统里不给看的 */
|
|
27
|
+
const SENSITIVE_SYSTEM = ["/proc", "/sys", "/dev", "/etc/shadow", "/etc/gshadow", "/etc/sudoers", "/etc/sudoers.d"];
|
|
28
|
+
|
|
29
|
+
/** 文件名:.env(示例文件除外)、私钥、证书私钥、密钥库 */
|
|
30
|
+
function sensitiveName(name: string): boolean {
|
|
31
|
+
const n = name.toLowerCase();
|
|
32
|
+
if (/^\.env(\.|$)/.test(n) && !/\.(example|sample|template)$/.test(n)) return true;
|
|
33
|
+
if (/^id_(rsa|dsa|ecdsa|ed25519)/.test(n)) return true;
|
|
34
|
+
return /\.(pem|key|p12|pfx|jks|keystore|kdbx)$/.test(n);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function within(file: string, dir: string): boolean {
|
|
38
|
+
return file === dir || file.startsWith(dir.endsWith(path.sep) ? dir : dir + path.sep);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function isSensitivePath(file: string): boolean {
|
|
42
|
+
const parts = file.split(path.sep);
|
|
43
|
+
if (parts.some((p) => SENSITIVE_DIRS.has(p))) return true;
|
|
44
|
+
if (sensitiveName(path.basename(file))) return true;
|
|
45
|
+
const userHome = os.homedir();
|
|
46
|
+
if (SENSITIVE_HOME.some((p) => within(file, path.join(userHome, p)))) return true;
|
|
47
|
+
if (SENSITIVE_SYSTEM.some((p) => within(file, p))) return true;
|
|
48
|
+
// agent-loft 自己的配置和数据(飞书密钥、账号、登录态…);上传的附件除外,那些本来就能看
|
|
49
|
+
return within(file, home) && !within(file, uploadsRoot);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** 「file:///a/b」「~/a」「相对路径」→ 绝对路径(相对路径按会话的工作目录算) */
|
|
53
|
+
export function expandPath(p: string, cwd: string): string {
|
|
54
|
+
let s = p.trim();
|
|
55
|
+
if (s.startsWith("file://")) {
|
|
56
|
+
s = s.slice("file://".length);
|
|
57
|
+
try {
|
|
58
|
+
s = decodeURIComponent(s);
|
|
59
|
+
} catch {
|
|
60
|
+
// 编码坏了就按原样
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
if (s === "~" || s.startsWith("~/")) s = path.join(os.homedir(), s.slice(1));
|
|
64
|
+
return path.resolve(cwd, s);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* 解析成可以给前端看的真实文件路径:存在、是普通文件、解析符号链接前后都不敏感。不行返回 undefined
|
|
69
|
+
*/
|
|
70
|
+
export function resolveReplyFile(p: string, cwd: string): string | undefined {
|
|
71
|
+
if (!p.trim() || p.includes("\0")) return undefined;
|
|
72
|
+
try {
|
|
73
|
+
const abs = expandPath(p, cwd);
|
|
74
|
+
if (isSensitivePath(abs)) return undefined;
|
|
75
|
+
const real = fs.realpathSync(abs);
|
|
76
|
+
if (isSensitivePath(real)) return undefined;
|
|
77
|
+
return fs.statSync(real).isFile() ? real : undefined;
|
|
78
|
+
} catch {
|
|
79
|
+
return undefined;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** 回复里百分号编码的路径(链接地址常见)也解开一份,两种写法都能对上 */
|
|
84
|
+
function withDecoded(text: string): string {
|
|
85
|
+
if (!text.includes("%")) return text;
|
|
86
|
+
const decoded = text.replace(/(?:%[0-9a-f]{2})+/gi, (m) => {
|
|
87
|
+
try {
|
|
88
|
+
return decodeURIComponent(m);
|
|
89
|
+
} catch {
|
|
90
|
+
return m;
|
|
91
|
+
}
|
|
92
|
+
});
|
|
93
|
+
return decoded === text ? text : `${text}\n${decoded}`;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** 路径里能出现的字符:前后挨着这些就说明只对上了别的路径的一截(比如 a.ts 对上 src/a.ts) */
|
|
97
|
+
const PATH_CHAR = /[\p{L}\p{N}_\-./~@+]/u;
|
|
98
|
+
|
|
99
|
+
/** text 里有没有完整地写着 p(不是别的路径的一部分) */
|
|
100
|
+
export function mentions(text: string, p: string): boolean {
|
|
101
|
+
const needle = p.trim();
|
|
102
|
+
if (!needle) return false;
|
|
103
|
+
const hay = withDecoded(text);
|
|
104
|
+
for (let i = hay.indexOf(needle); i >= 0; i = hay.indexOf(needle, i + 1)) {
|
|
105
|
+
const before = hay[i - 1];
|
|
106
|
+
const after = hay[i + needle.length];
|
|
107
|
+
// 末尾的「.」是句号,不算路径的一部分
|
|
108
|
+
const afterOk = !after || !PATH_CHAR.test(after) || (after === "." && !PATH_CHAR.test(hay[i + needle.length + 1] ?? " "));
|
|
109
|
+
if ((!before || !PATH_CHAR.test(before)) && afterOk) return true;
|
|
110
|
+
}
|
|
111
|
+
return false;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
const TYPES: Record<string, string> = {
|
|
115
|
+
png: "image/png",
|
|
116
|
+
jpg: "image/jpeg",
|
|
117
|
+
jpeg: "image/jpeg",
|
|
118
|
+
gif: "image/gif",
|
|
119
|
+
webp: "image/webp",
|
|
120
|
+
avif: "image/avif",
|
|
121
|
+
bmp: "image/bmp",
|
|
122
|
+
ico: "image/x-icon",
|
|
123
|
+
svg: "image/svg+xml",
|
|
124
|
+
pdf: "application/pdf",
|
|
125
|
+
mp4: "video/mp4",
|
|
126
|
+
m4v: "video/mp4",
|
|
127
|
+
webm: "video/webm",
|
|
128
|
+
mov: "video/quicktime",
|
|
129
|
+
mp3: "audio/mpeg",
|
|
130
|
+
m4a: "audio/mp4",
|
|
131
|
+
aac: "audio/aac",
|
|
132
|
+
wav: "audio/wav",
|
|
133
|
+
ogg: "audio/ogg",
|
|
134
|
+
oga: "audio/ogg",
|
|
135
|
+
opus: "audio/ogg",
|
|
136
|
+
flac: "audio/flac",
|
|
137
|
+
};
|
|
138
|
+
|
|
139
|
+
/** 浏览器里直接打开的类型;其余(包括 HTML)一律当下载 / 纯文本,不在本站域名下当网页执行 */
|
|
140
|
+
export function replyFileType(file: string): string | undefined {
|
|
141
|
+
return TYPES[path.extname(file).slice(1).toLowerCase()];
|
|
142
|
+
}
|
package/src/core/uploads.ts
CHANGED
|
@@ -7,7 +7,7 @@ import path from "node:path";
|
|
|
7
7
|
import { dataDir } from "../home.js";
|
|
8
8
|
import type { AttachmentInfo, AttachmentKind, SavedAttachment } from "./types.js";
|
|
9
9
|
|
|
10
|
-
const uploadsRoot = path.join(dataDir, "uploads");
|
|
10
|
+
export const uploadsRoot = path.join(dataDir, "uploads");
|
|
11
11
|
|
|
12
12
|
export function uploadsDirFor(key: string): string {
|
|
13
13
|
return path.join(uploadsRoot, encodeURIComponent(key));
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
// 回复里的 HTML:Codex 的 visualize 插件画的图表(回复里单独一行 visualize{"path":"…"}),
|
|
2
|
+
// 以及 agent 写出来的普通 HTML 文件。网页上放进沙箱 iframe 里显示。
|
|
3
|
+
//
|
|
4
|
+
// visualize 写的是 HTML 片段,要套上插件自带的样式和脚本(和插件的 scripts/render.py 一样)才是完整的页面。
|
|
5
|
+
// 插件装在本机 Codex 的目录里,找不到就用一份最小的样式兜底。
|
|
6
|
+
import fs from "node:fs";
|
|
7
|
+
import os from "node:os";
|
|
8
|
+
import path from "node:path";
|
|
9
|
+
|
|
10
|
+
/** 和 visualize 插件约定的一样:图表只能从这几个 CDN 加载资源,不能联网请求别的 */
|
|
11
|
+
const RESOURCES = [
|
|
12
|
+
"blob:",
|
|
13
|
+
"data:",
|
|
14
|
+
"https://cdnjs.cloudflare.com",
|
|
15
|
+
"https://cdn.jsdelivr.net",
|
|
16
|
+
"https://esm.sh",
|
|
17
|
+
"https://fonts.bunny.net",
|
|
18
|
+
"https://fonts.googleapis.com",
|
|
19
|
+
"https://fonts.gstatic.com",
|
|
20
|
+
"https://unpkg.com",
|
|
21
|
+
].join(" ");
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* 沙箱(不带 allow-same-origin):页面是个匿名的源,读不到本站的登录态、调不了本站接口;
|
|
25
|
+
* connect-src 只给 blob / data,也就没法把东西发出去
|
|
26
|
+
*/
|
|
27
|
+
export const HTML_CSP = [
|
|
28
|
+
"sandbox allow-scripts",
|
|
29
|
+
"default-src 'none'",
|
|
30
|
+
`script-src 'unsafe-inline' 'unsafe-eval' 'wasm-unsafe-eval' ${RESOURCES}`,
|
|
31
|
+
`style-src 'unsafe-inline' ${RESOURCES}`,
|
|
32
|
+
`img-src ${RESOURCES}`,
|
|
33
|
+
`font-src ${RESOURCES}`,
|
|
34
|
+
`media-src ${RESOURCES}`,
|
|
35
|
+
"worker-src blob:",
|
|
36
|
+
"connect-src blob: data:",
|
|
37
|
+
"frame-src 'none'",
|
|
38
|
+
"object-src 'none'",
|
|
39
|
+
"base-uri 'none'",
|
|
40
|
+
"form-action 'none'",
|
|
41
|
+
"frame-ancestors 'self'",
|
|
42
|
+
].join("; ");
|
|
43
|
+
|
|
44
|
+
/** 太大的不显示(插件自己限制片段 1 MB) */
|
|
45
|
+
export const HTML_MAX = 2 * 1024 * 1024;
|
|
46
|
+
|
|
47
|
+
const FRAGMENT_PLACEHOLDER = "<!--__INLINE_VISUALIZATION_FRAGMENT__-->";
|
|
48
|
+
const DOCUMENT_MARKUP = /<!doctype\s|<\s*(?:html|head|body)(?:\s|>)/i;
|
|
49
|
+
|
|
50
|
+
/** 插件目录:$CODEX_HOME/plugins/cache/<来源>/visualize/<版本>/skills/visualize/assets,有多个版本取最新的 */
|
|
51
|
+
function findAssets(): string | undefined {
|
|
52
|
+
const cache = path.join(process.env.CODEX_HOME ?? path.join(os.homedir(), ".codex"), "plugins", "cache");
|
|
53
|
+
const found: { dir: string; version: string }[] = [];
|
|
54
|
+
try {
|
|
55
|
+
for (const source of fs.readdirSync(cache)) {
|
|
56
|
+
const base = path.join(cache, source, "visualize");
|
|
57
|
+
let versions: string[] = [];
|
|
58
|
+
try {
|
|
59
|
+
versions = fs.readdirSync(base);
|
|
60
|
+
} catch {
|
|
61
|
+
continue;
|
|
62
|
+
}
|
|
63
|
+
for (const version of versions) {
|
|
64
|
+
const dir = path.join(base, version, "skills", "visualize", "assets");
|
|
65
|
+
if (fs.existsSync(path.join(dir, "visualize.css"))) found.push({ dir, version });
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
} catch {
|
|
69
|
+
return undefined;
|
|
70
|
+
}
|
|
71
|
+
found.sort((a, b) => a.version.localeCompare(b.version, undefined, { numeric: true }));
|
|
72
|
+
return found.at(-1)?.dir;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** 没装插件时的兜底:插件约定的几个常用变量 */
|
|
76
|
+
const FALLBACK_CSS = `:root{color-scheme:light dark;--background:transparent;--foreground:light-dark(rgb(26 28 31),rgb(255 255 255));--muted-foreground:light-dark(rgb(26 28 31/50%),rgb(255 255 255/50%));--border:light-dark(rgb(0 0 0/10%),rgb(255 255 255/12%));--card:color-mix(in oklab,var(--foreground) 5%,transparent);--primary:light-dark(rgb(51 156 255),rgb(131 195 255));--viz-series-1:#339cff;--viz-series-2:#f59e0b;--viz-series-3:#10b981;--viz-series-4:#ef4444;--viz-series-5:#8b5cf6}
|
|
77
|
+
body{margin:0;font:14px/1.5 system-ui,-apple-system,"PingFang SC","Microsoft YaHei",sans-serif;color:var(--foreground)}
|
|
78
|
+
.text-small{font-size:12px}.text-muted{color:var(--muted-foreground)}.tabular-nums{font-variant-numeric:tabular-nums}
|
|
79
|
+
.viz-row{display:flex;justify-content:space-between;gap:8px;align-items:baseline}`;
|
|
80
|
+
|
|
81
|
+
/** 把高度告诉外面的页面(iframe 跟着内容变高),见 web/views/file-preview.js */
|
|
82
|
+
const SIZE_REPORTER = `<script>(()=>{const post=()=>parent!==window&&parent.postMessage({type:"aloft-html-size",height:Math.ceil(document.documentElement.scrollHeight)},"*");new ResizeObserver(post).observe(document.documentElement);addEventListener("load",post);post()})()</script>`;
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* 给网页显示用的完整 HTML。片段套上插件的外壳;本来就是完整页面的原样,只在末尾加上报高度的脚本。
|
|
86
|
+
* 背景透明,和对话的底色融在一起
|
|
87
|
+
*/
|
|
88
|
+
export function htmlDocument(source: string, title: string): string {
|
|
89
|
+
if (DOCUMENT_MARKUP.test(source)) {
|
|
90
|
+
const at = source.search(/<\/body\s*>/i);
|
|
91
|
+
return at >= 0 ? source.slice(0, at) + SIZE_REPORTER + source.slice(at) : source + SIZE_REPORTER;
|
|
92
|
+
}
|
|
93
|
+
const assets = findAssets();
|
|
94
|
+
let css = FALLBACK_CSS;
|
|
95
|
+
let body = source;
|
|
96
|
+
if (assets) {
|
|
97
|
+
try {
|
|
98
|
+
css = fs.readFileSync(path.join(assets, "visualize.css"), "utf8");
|
|
99
|
+
const kit = fs.readFileSync(path.join(assets, "visualize.html"), "utf8");
|
|
100
|
+
body = kit.includes(FRAGMENT_PLACEHOLDER) ? kit.replace(FRAGMENT_PLACEHOLDER, () => source) : source + kit;
|
|
101
|
+
} catch {
|
|
102
|
+
css = FALLBACK_CSS;
|
|
103
|
+
body = source;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
const esc = (s: string) => s.replace(/[&<>"]/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[c]!);
|
|
107
|
+
return `<!doctype html>
|
|
108
|
+
<html lang="zh-CN">
|
|
109
|
+
<head>
|
|
110
|
+
<meta charset="utf-8">
|
|
111
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
112
|
+
<meta name="referrer" content="no-referrer">
|
|
113
|
+
<title>${esc(title)}</title>
|
|
114
|
+
<style>${css}
|
|
115
|
+
:root{--color-background-primary:transparent;background:transparent!important}html>body{padding:0;margin:0}</style>
|
|
116
|
+
</head>
|
|
117
|
+
<body>
|
|
118
|
+
${body}
|
|
119
|
+
${SIZE_REPORTER}
|
|
120
|
+
</body>
|
|
121
|
+
</html>
|
|
122
|
+
`;
|
|
123
|
+
}
|
package/web/css/messages.css
CHANGED
|
@@ -901,3 +901,274 @@ a.att-file:hover {
|
|
|
901
901
|
color: var(--fg);
|
|
902
902
|
background: var(--bg-hover);
|
|
903
903
|
}
|
|
904
|
+
|
|
905
|
+
/* ---------- 回复里提到的文件:能点开预览(views/file-preview.js) ---------- */
|
|
906
|
+
.md a.file-link {
|
|
907
|
+
color: var(--link);
|
|
908
|
+
text-decoration: none;
|
|
909
|
+
border-bottom: 1px dashed currentColor;
|
|
910
|
+
cursor: pointer;
|
|
911
|
+
}
|
|
912
|
+
|
|
913
|
+
.md a.file-link:hover {
|
|
914
|
+
border-bottom-style: solid;
|
|
915
|
+
}
|
|
916
|
+
|
|
917
|
+
.md a.file-link code {
|
|
918
|
+
color: inherit;
|
|
919
|
+
}
|
|
920
|
+
|
|
921
|
+
.md a.file-link.file-img {
|
|
922
|
+
border: 0;
|
|
923
|
+
display: inline-block;
|
|
924
|
+
}
|
|
925
|
+
|
|
926
|
+
.md a.file-link.file-img img {
|
|
927
|
+
max-width: min(100%, 420px);
|
|
928
|
+
max-height: 320px;
|
|
929
|
+
border-radius: 8px;
|
|
930
|
+
border: 1px solid var(--border);
|
|
931
|
+
display: block;
|
|
932
|
+
}
|
|
933
|
+
|
|
934
|
+
.file-viewer {
|
|
935
|
+
position: fixed;
|
|
936
|
+
inset: 0;
|
|
937
|
+
z-index: 60;
|
|
938
|
+
background: rgba(0, 0, 0, 0.55);
|
|
939
|
+
display: flex;
|
|
940
|
+
align-items: center;
|
|
941
|
+
justify-content: center;
|
|
942
|
+
padding: 24px;
|
|
943
|
+
animation: fade-in 0.12s ease-out;
|
|
944
|
+
}
|
|
945
|
+
|
|
946
|
+
.fv-panel {
|
|
947
|
+
background: var(--bg);
|
|
948
|
+
border-radius: 14px;
|
|
949
|
+
box-shadow: var(--shadow);
|
|
950
|
+
width: min(1000px, 100%);
|
|
951
|
+
height: min(88vh, 100%);
|
|
952
|
+
display: flex;
|
|
953
|
+
flex-direction: column;
|
|
954
|
+
overflow: hidden;
|
|
955
|
+
}
|
|
956
|
+
|
|
957
|
+
.fv-head {
|
|
958
|
+
display: flex;
|
|
959
|
+
align-items: center;
|
|
960
|
+
gap: 10px;
|
|
961
|
+
padding: 10px 12px 10px 16px;
|
|
962
|
+
border-bottom: 1px solid var(--border);
|
|
963
|
+
}
|
|
964
|
+
|
|
965
|
+
.fv-title {
|
|
966
|
+
flex: 1;
|
|
967
|
+
min-width: 0;
|
|
968
|
+
}
|
|
969
|
+
|
|
970
|
+
.fv-name {
|
|
971
|
+
font-weight: 600;
|
|
972
|
+
font-size: 15px;
|
|
973
|
+
overflow: hidden;
|
|
974
|
+
text-overflow: ellipsis;
|
|
975
|
+
white-space: nowrap;
|
|
976
|
+
}
|
|
977
|
+
|
|
978
|
+
.fv-sub {
|
|
979
|
+
color: var(--fg-soft);
|
|
980
|
+
font-size: 12px;
|
|
981
|
+
overflow: hidden;
|
|
982
|
+
text-overflow: ellipsis;
|
|
983
|
+
white-space: nowrap;
|
|
984
|
+
}
|
|
985
|
+
|
|
986
|
+
.fv-actions {
|
|
987
|
+
display: flex;
|
|
988
|
+
gap: 8px;
|
|
989
|
+
}
|
|
990
|
+
|
|
991
|
+
.fv-actions .btn {
|
|
992
|
+
padding: 5px 12px;
|
|
993
|
+
font-size: 13px;
|
|
994
|
+
text-decoration: none;
|
|
995
|
+
color: inherit;
|
|
996
|
+
}
|
|
997
|
+
|
|
998
|
+
.fv-body {
|
|
999
|
+
flex: 1;
|
|
1000
|
+
min-height: 0;
|
|
1001
|
+
overflow: auto;
|
|
1002
|
+
display: flex;
|
|
1003
|
+
flex-direction: column;
|
|
1004
|
+
}
|
|
1005
|
+
|
|
1006
|
+
.fv-loading,
|
|
1007
|
+
.fv-empty {
|
|
1008
|
+
margin: auto;
|
|
1009
|
+
display: flex;
|
|
1010
|
+
flex-direction: column;
|
|
1011
|
+
align-items: center;
|
|
1012
|
+
gap: 14px;
|
|
1013
|
+
color: var(--fg-soft);
|
|
1014
|
+
padding: 24px;
|
|
1015
|
+
text-align: center;
|
|
1016
|
+
}
|
|
1017
|
+
|
|
1018
|
+
.fv-empty .btn {
|
|
1019
|
+
text-decoration: none;
|
|
1020
|
+
color: inherit;
|
|
1021
|
+
}
|
|
1022
|
+
|
|
1023
|
+
.fv-img,
|
|
1024
|
+
.fv-media {
|
|
1025
|
+
margin: auto;
|
|
1026
|
+
max-width: 100%;
|
|
1027
|
+
max-height: 100%;
|
|
1028
|
+
object-fit: contain;
|
|
1029
|
+
display: block;
|
|
1030
|
+
}
|
|
1031
|
+
|
|
1032
|
+
.fv-img {
|
|
1033
|
+
padding: 12px;
|
|
1034
|
+
box-sizing: border-box;
|
|
1035
|
+
}
|
|
1036
|
+
|
|
1037
|
+
.fv-media {
|
|
1038
|
+
background: #000;
|
|
1039
|
+
}
|
|
1040
|
+
|
|
1041
|
+
.fv-audio {
|
|
1042
|
+
margin: auto;
|
|
1043
|
+
width: min(480px, 90%);
|
|
1044
|
+
}
|
|
1045
|
+
|
|
1046
|
+
.fv-frame {
|
|
1047
|
+
flex: 1;
|
|
1048
|
+
border: 0;
|
|
1049
|
+
width: 100%;
|
|
1050
|
+
background: #fff;
|
|
1051
|
+
}
|
|
1052
|
+
|
|
1053
|
+
.fv-code {
|
|
1054
|
+
margin: 0;
|
|
1055
|
+
padding: 14px 16px;
|
|
1056
|
+
font-family: var(--mono);
|
|
1057
|
+
font-size: 13px;
|
|
1058
|
+
line-height: 1.55;
|
|
1059
|
+
background: var(--code-bg);
|
|
1060
|
+
flex: 1;
|
|
1061
|
+
white-space: pre;
|
|
1062
|
+
tab-size: 4;
|
|
1063
|
+
}
|
|
1064
|
+
|
|
1065
|
+
.fv-code code.hljs {
|
|
1066
|
+
background: transparent;
|
|
1067
|
+
padding: 0;
|
|
1068
|
+
}
|
|
1069
|
+
|
|
1070
|
+
.fv-doc {
|
|
1071
|
+
padding: 16px 24px;
|
|
1072
|
+
max-width: 820px;
|
|
1073
|
+
width: 100%;
|
|
1074
|
+
box-sizing: border-box;
|
|
1075
|
+
margin: 0 auto;
|
|
1076
|
+
}
|
|
1077
|
+
|
|
1078
|
+
.fv-cut {
|
|
1079
|
+
padding: 6px 16px;
|
|
1080
|
+
font-size: 12px;
|
|
1081
|
+
color: var(--fg-soft);
|
|
1082
|
+
background: var(--bg-soft);
|
|
1083
|
+
border-bottom: 1px solid var(--border);
|
|
1084
|
+
}
|
|
1085
|
+
|
|
1086
|
+
@media (max-width: 768px) {
|
|
1087
|
+
.file-viewer {
|
|
1088
|
+
padding: 0;
|
|
1089
|
+
}
|
|
1090
|
+
|
|
1091
|
+
.fv-panel {
|
|
1092
|
+
width: 100%;
|
|
1093
|
+
height: 100%;
|
|
1094
|
+
border-radius: 0;
|
|
1095
|
+
padding-top: env(safe-area-inset-top);
|
|
1096
|
+
padding-bottom: env(safe-area-inset-bottom);
|
|
1097
|
+
}
|
|
1098
|
+
|
|
1099
|
+
.fv-head {
|
|
1100
|
+
flex-wrap: wrap;
|
|
1101
|
+
}
|
|
1102
|
+
|
|
1103
|
+
.fv-actions {
|
|
1104
|
+
order: 3;
|
|
1105
|
+
width: 100%;
|
|
1106
|
+
}
|
|
1107
|
+
}
|
|
1108
|
+
|
|
1109
|
+
/* ---------- Codex visualize 画的图表:嵌在回复里(views/file-preview.js) ---------- */
|
|
1110
|
+
.md .viz {
|
|
1111
|
+
margin: 0.8em 0;
|
|
1112
|
+
}
|
|
1113
|
+
|
|
1114
|
+
.viz-frame {
|
|
1115
|
+
display: block;
|
|
1116
|
+
width: 100%;
|
|
1117
|
+
height: 320px;
|
|
1118
|
+
border: 0;
|
|
1119
|
+
background: transparent;
|
|
1120
|
+
/* 和页面一样跟着系统深浅色走:配色方案不一致时浏览器会给 iframe 垫一层不透明的底 */
|
|
1121
|
+
color-scheme: light dark;
|
|
1122
|
+
}
|
|
1123
|
+
|
|
1124
|
+
.viz-loading {
|
|
1125
|
+
height: 120px;
|
|
1126
|
+
display: flex;
|
|
1127
|
+
align-items: center;
|
|
1128
|
+
justify-content: center;
|
|
1129
|
+
}
|
|
1130
|
+
|
|
1131
|
+
.viz-actions {
|
|
1132
|
+
display: flex;
|
|
1133
|
+
justify-content: flex-end;
|
|
1134
|
+
gap: 4px;
|
|
1135
|
+
margin-top: 2px;
|
|
1136
|
+
}
|
|
1137
|
+
|
|
1138
|
+
.md .viz-btn {
|
|
1139
|
+
font-size: 12px;
|
|
1140
|
+
color: var(--fg-soft);
|
|
1141
|
+
background: none;
|
|
1142
|
+
border: 0;
|
|
1143
|
+
padding: 2px 6px;
|
|
1144
|
+
border-radius: 6px;
|
|
1145
|
+
text-decoration: none;
|
|
1146
|
+
cursor: pointer;
|
|
1147
|
+
}
|
|
1148
|
+
|
|
1149
|
+
.md .viz-btn:hover {
|
|
1150
|
+
background: var(--bg-hover);
|
|
1151
|
+
color: var(--fg);
|
|
1152
|
+
}
|
|
1153
|
+
|
|
1154
|
+
.viz-error {
|
|
1155
|
+
font-size: 13px;
|
|
1156
|
+
color: var(--fg-soft);
|
|
1157
|
+
padding: 10px 12px;
|
|
1158
|
+
border: 1px dashed var(--border);
|
|
1159
|
+
border-radius: 10px;
|
|
1160
|
+
}
|
|
1161
|
+
|
|
1162
|
+
.viz-path {
|
|
1163
|
+
font-family: var(--mono);
|
|
1164
|
+
font-size: 12px;
|
|
1165
|
+
margin-top: 2px;
|
|
1166
|
+
word-break: break-all;
|
|
1167
|
+
}
|
|
1168
|
+
|
|
1169
|
+
.fv-frame.fv-html {
|
|
1170
|
+
background: transparent;
|
|
1171
|
+
color-scheme: light dark;
|
|
1172
|
+
padding: 12px 16px;
|
|
1173
|
+
box-sizing: border-box;
|
|
1174
|
+
}
|
package/web/lib/markdown.js
CHANGED
|
@@ -7,9 +7,9 @@ import { h, toast } from "./dom.js";
|
|
|
7
7
|
|
|
8
8
|
marked.setOptions({ gfm: true, breaks: true });
|
|
9
9
|
|
|
10
|
-
export function renderMarkdown(text) {
|
|
10
|
+
export function renderMarkdown(text, opts) {
|
|
11
11
|
const div = h("div", { class: "md" });
|
|
12
|
-
patchMarkdown(div, text);
|
|
12
|
+
patchMarkdown(div, text, opts);
|
|
13
13
|
return div;
|
|
14
14
|
}
|
|
15
15
|
|
|
@@ -17,9 +17,10 @@ export function renderMarkdown(text) {
|
|
|
17
17
|
* 把 div 里的 markdown 更新成 text,只重画变了的块(段落、列表、代码块…)。
|
|
18
18
|
* 流式输出时前面的块不再变,每帧只需重画最后一两块;选中的文字、代码块的横向滚动也不会被冲掉。
|
|
19
19
|
* live = 还在输出:最后一块随时会变,先不高亮,等它定下来再高亮。
|
|
20
|
+
* enhance(box):每块画好后再加工一下(比如把回复里的文件路径变成能点开的)。
|
|
20
21
|
* 按块拼起来和整段解析的结果一样(marked 的 parser 本来就是逐块拼接的)。
|
|
21
22
|
*/
|
|
22
|
-
export function patchMarkdown(div, text, { live = false } = {}) {
|
|
23
|
+
export function patchMarkdown(div, text, { live = false, enhance } = {}) {
|
|
23
24
|
const tokens = marked.lexer(text ?? "");
|
|
24
25
|
const links = JSON.stringify(tokens.links ?? {});
|
|
25
26
|
// 引用式链接的定义可能在后面才出现(流式输出时地址还会一点点变长),会影响前面的块:定义变了就整个重画
|
|
@@ -52,6 +53,7 @@ export function patchMarkdown(div, text, { live = false } = {}) {
|
|
|
52
53
|
const box = document.createElement("div");
|
|
53
54
|
box.innerHTML = DOMPurify.sanitize(marked.parser(chunk), { ADD_ATTR: ["target"] });
|
|
54
55
|
decorate(box, final);
|
|
56
|
+
enhance?.(box);
|
|
55
57
|
const nodes = [...box.childNodes];
|
|
56
58
|
div.append(...nodes);
|
|
57
59
|
blocks.push({ raw: raws[i], final, nodes });
|
|
@@ -0,0 +1,342 @@
|
|
|
1
|
+
// agent 回复里提到的文件:路径变成能点的链接,点开在弹层里预览(图片 / PDF / 音视频 / 文本代码),其它的下载。
|
|
2
|
+
// 能不能看由服务端判断(只认回复里写过的路径、挡掉密钥之类的敏感文件,见 core/reply-files.ts)。
|
|
3
|
+
import hljs from "/vendor/hljs.js";
|
|
4
|
+
import { h, icon, starsLoader, toast } from "../lib/dom.js";
|
|
5
|
+
import { api } from "../lib/api.js";
|
|
6
|
+
import { renderMarkdown } from "../lib/markdown.js";
|
|
7
|
+
import { S } from "../state.js";
|
|
8
|
+
|
|
9
|
+
const fileUrl = (key, p, extra = "") =>
|
|
10
|
+
`/api/conversations/${encodeURIComponent(key)}/file?path=${encodeURIComponent(p)}${extra}`;
|
|
11
|
+
/** 网页(含 Codex visualize 画的图表)套好外壳、放进沙箱显示的地址 */
|
|
12
|
+
const htmlUrl = (key, p) => `/api/conversations/${encodeURIComponent(key)}/html?path=${encodeURIComponent(p)}`;
|
|
13
|
+
|
|
14
|
+
// ---------- 认路径 ----------
|
|
15
|
+
|
|
16
|
+
/** 末尾的行号:a.ts:12、a.ts:12:5、a.ts:12-20、a.ts#L12、a.ts#L12-L20 */
|
|
17
|
+
const LINE_SUFFIX = /(?::\d+(?:[:-]\d+)?|#L\d+(?:-L?\d+)?)$/;
|
|
18
|
+
|
|
19
|
+
/** 不带目录的文件名只认这些常见的文档 / 媒体后缀(a.js、Vue.js 这种多半是在说技术名词,不认) */
|
|
20
|
+
const BARE_EXT = /\.(md|markdown|txt|pdf|png|jpe?g|gif|webp|svg|csv|tsv|xlsx?|docx?|pptx?|html?|zip|tgz|gz|mp4|mov|webm|mp3|m4a|wav|log)$/i;
|
|
21
|
+
|
|
22
|
+
/** 路径里不该有的字符(通配符、模板、管道…) */
|
|
23
|
+
const NOT_PATH = /[\s*?{}$<>|"'`]/;
|
|
24
|
+
|
|
25
|
+
function stripLine(p) {
|
|
26
|
+
return p.replace(LINE_SUFFIX, "");
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** 行内代码里的字:像不像一个文件路径。像就返回去掉行号后的路径 */
|
|
30
|
+
function codePath(text) {
|
|
31
|
+
const t = stripLine(text.trim());
|
|
32
|
+
if (!t || t.length > 400 || NOT_PATH.test(t) || /^[a-z][\w+.-]*:\/\/(?!\/)/i.test(t)) return null;
|
|
33
|
+
if (/^(?:file:\/\/)?(?:~|\.{1,2})?\//.test(t)) {
|
|
34
|
+
if (t.startsWith("//")) return null;
|
|
35
|
+
// 至少两级(/a/b),或者带后缀(/a.md):单独一个 / 、/tmp 这种多半是在说目录
|
|
36
|
+
const segs = t.replace(/^(?:file:\/\/)?(?:~|\.{1,2})?\//, "").split("/").filter(Boolean);
|
|
37
|
+
return segs.length >= 2 || /\.[A-Za-z]\w{0,9}$/.test(t) ? t : null;
|
|
38
|
+
}
|
|
39
|
+
// 相对路径:a/b.ts 这种带目录、带后缀的
|
|
40
|
+
if (/^[\p{L}\p{N}_.@+-]+(?:\/[\p{L}\p{N}_.@+-]+)+$/u.test(t) && /\.[A-Za-z]\w{0,9}$/.test(t)) return t;
|
|
41
|
+
if (/^[\p{L}\p{N}_.@+-]+$/u.test(t) && BARE_EXT.test(t)) return t;
|
|
42
|
+
return null;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** 链接地址是不是本机文件(没有协议的、file://、绝对路径)。是就返回路径 */
|
|
46
|
+
function hrefPath(raw) {
|
|
47
|
+
if (!raw || raw.startsWith("#") || raw.startsWith("//")) return null;
|
|
48
|
+
if (/^[a-z][\w+.-]*:/i.test(raw) && !raw.startsWith("file://")) return null;
|
|
49
|
+
let p = raw;
|
|
50
|
+
// marked 会把地址里的中文、空格编码掉;服务端拿回复原文对,要还原成原样
|
|
51
|
+
try {
|
|
52
|
+
p = decodeURI(raw);
|
|
53
|
+
} catch {
|
|
54
|
+
// 编码坏了就按原样
|
|
55
|
+
}
|
|
56
|
+
return stripLine(p) || null;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** 正文里的绝对路径(要带后缀,免得把「/ 斜杠」之类的当成路径) */
|
|
60
|
+
const TEXT_PATH = /(?<![\p{L}\p{N}_./~:-])(?:file:\/\/)?~?\/(?!\/)[^\s<>"'`()()[\]{},。;:!?、“”‘’「」|*]+\.[A-Za-z0-9]{1,10}(?::\d+(?::\d+)?)?(?![\p{L}\p{N}_/-])/gu;
|
|
61
|
+
|
|
62
|
+
function fileLink(key, p, ...children) {
|
|
63
|
+
return h(
|
|
64
|
+
"a",
|
|
65
|
+
{
|
|
66
|
+
class: "file-link",
|
|
67
|
+
href: fileUrl(key, p),
|
|
68
|
+
target: "_blank",
|
|
69
|
+
rel: "noopener",
|
|
70
|
+
title: `${p}\n点击预览`,
|
|
71
|
+
onclick: (e) => {
|
|
72
|
+
// 新标签页打开(Ctrl / ⌘ / 中键)照浏览器的来
|
|
73
|
+
if (e.ctrlKey || e.metaKey || e.shiftKey || e.button !== 0) return;
|
|
74
|
+
e.preventDefault();
|
|
75
|
+
openReplyFile(key, p);
|
|
76
|
+
},
|
|
77
|
+
},
|
|
78
|
+
...children,
|
|
79
|
+
);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** patchMarkdown 的 enhance:把一块回复里的文件路径(链接、行内代码、正文里的绝对路径、图片)变成能点开的 */
|
|
83
|
+
export function linkReplyFiles(box) {
|
|
84
|
+
const key = S.current;
|
|
85
|
+
if (!key) return;
|
|
86
|
+
embedVisualizations(box, key);
|
|
87
|
+
for (const a of box.querySelectorAll("a[href]")) {
|
|
88
|
+
const p = hrefPath(a.getAttribute("href"));
|
|
89
|
+
if (!p) continue;
|
|
90
|
+
a.replaceWith(fileLink(key, p, ...a.childNodes));
|
|
91
|
+
}
|
|
92
|
+
for (const code of box.querySelectorAll("code")) {
|
|
93
|
+
if (code.closest("pre, a")) continue;
|
|
94
|
+
const p = codePath(code.textContent);
|
|
95
|
+
if (p) code.replaceWith(fileLink(key, p, code.cloneNode(true)));
|
|
96
|
+
}
|
|
97
|
+
for (const img of box.querySelectorAll("img[src]")) {
|
|
98
|
+
const p = hrefPath(img.getAttribute("src"));
|
|
99
|
+
if (!p) continue;
|
|
100
|
+
const alt = img.getAttribute("alt") || p.split("/").pop();
|
|
101
|
+
const pic = h("img", { src: fileUrl(key, p), alt, loading: "lazy" });
|
|
102
|
+
const link = fileLink(key, p, pic);
|
|
103
|
+
link.classList.add("file-img");
|
|
104
|
+
// 打不开(文件没了、不能看):退回成一个文字链接,点了会说明原因
|
|
105
|
+
pic.onerror = () => link.replaceChildren(alt);
|
|
106
|
+
img.replaceWith(link);
|
|
107
|
+
}
|
|
108
|
+
linkTextPaths(box, key);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function linkTextPaths(box, key) {
|
|
112
|
+
const walker = document.createTreeWalker(box, NodeFilter.SHOW_TEXT, {
|
|
113
|
+
acceptNode: (n) => (n.parentElement?.closest("pre, code, a") ? NodeFilter.FILTER_REJECT : NodeFilter.FILTER_ACCEPT),
|
|
114
|
+
});
|
|
115
|
+
const nodes = [];
|
|
116
|
+
for (let n = walker.nextNode(); n; n = walker.nextNode()) if (n.nodeValue.includes("/")) nodes.push(n);
|
|
117
|
+
for (const node of nodes) {
|
|
118
|
+
const text = node.nodeValue;
|
|
119
|
+
const parts = [];
|
|
120
|
+
let last = 0;
|
|
121
|
+
for (const m of text.matchAll(TEXT_PATH)) {
|
|
122
|
+
parts.push(text.slice(last, m.index), fileLink(key, stripLine(m[0]), m[0]));
|
|
123
|
+
last = m.index + m[0].length;
|
|
124
|
+
}
|
|
125
|
+
if (last === 0) continue;
|
|
126
|
+
parts.push(text.slice(last));
|
|
127
|
+
node.replaceWith(...parts.filter((x) => x !== ""));
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
// ---------- Codex visualize 画的图表 ----------
|
|
132
|
+
//
|
|
133
|
+
// Codex 自带的 visualize 插件把图表写成 HTML 片段,回复里单独一行 visualize{"path":"…"} 标出放在哪
|
|
134
|
+
// (官方客户端照这个把图表嵌进对话)。这里一样嵌进来:服务端套好插件的外壳,放进沙箱 iframe
|
|
135
|
+
|
|
136
|
+
const VIZ_LINE = /^\s*(?:::)?visualize\s*(\{.*\})\s*$/s;
|
|
137
|
+
|
|
138
|
+
function vizSpec(text) {
|
|
139
|
+
const m = VIZ_LINE.exec(text);
|
|
140
|
+
if (!m) return null;
|
|
141
|
+
try {
|
|
142
|
+
const spec = JSON.parse(m[1]);
|
|
143
|
+
return typeof spec?.path === "string" && spec.path ? spec : null;
|
|
144
|
+
} catch {
|
|
145
|
+
// 还在输出、JSON 还没写完:先当普通文字
|
|
146
|
+
return null;
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function embedVisualizations(box, key) {
|
|
151
|
+
for (const p of box.querySelectorAll("p")) {
|
|
152
|
+
if (!p.textContent.includes("visualize")) continue;
|
|
153
|
+
const whole = vizSpec(p.textContent);
|
|
154
|
+
if (whole) {
|
|
155
|
+
p.replaceWith(vizFrame(key, whole));
|
|
156
|
+
continue;
|
|
157
|
+
}
|
|
158
|
+
// 和别的文字挤在同一段里(中间只隔了一个换行)
|
|
159
|
+
for (const n of [...p.childNodes]) {
|
|
160
|
+
const spec = n.nodeType === Node.TEXT_NODE ? vizSpec(n.nodeValue) : null;
|
|
161
|
+
if (!spec) continue;
|
|
162
|
+
if (n.previousSibling?.nodeName === "BR") n.previousSibling.remove();
|
|
163
|
+
if (n.nextSibling?.nodeName === "BR") n.nextSibling.remove();
|
|
164
|
+
n.replaceWith(vizFrame(key, spec));
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
function vizFrame(key, spec) {
|
|
170
|
+
const page = htmlUrl(key, spec.path);
|
|
171
|
+
const name = spec.title || spec.path.split("/").pop();
|
|
172
|
+
const box = h("div", { class: `viz${spec.mode === "wide" ? " wide" : ""}` }, h("div", { class: "viz-loading" }, starsLoader()));
|
|
173
|
+
// 先问一下能不能看:不能的话 iframe 里只会是一页报错
|
|
174
|
+
void api(`${fileUrl(key, spec.path)}&stat=1`).then(
|
|
175
|
+
() => {
|
|
176
|
+
const frame = h("iframe", { class: "viz-frame", src: page, sandbox: "allow-scripts", referrerpolicy: "no-referrer", loading: "lazy", title: name });
|
|
177
|
+
box.replaceChildren(
|
|
178
|
+
frame,
|
|
179
|
+
h(
|
|
180
|
+
"div",
|
|
181
|
+
{ class: "viz-actions" },
|
|
182
|
+
h("button", { class: "viz-btn", onclick: () => openReplyFile(key, spec.path) }, "放大"),
|
|
183
|
+
h("a", { class: "viz-btn", href: page, target: "_blank", rel: "noopener" }, "新标签页打开"),
|
|
184
|
+
),
|
|
185
|
+
);
|
|
186
|
+
},
|
|
187
|
+
(err) => box.replaceChildren(h("div", { class: "viz-error" }, `图表显示不了:${err.message}`, h("div", { class: "viz-path" }, spec.path))),
|
|
188
|
+
);
|
|
189
|
+
return box;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
// 沙箱里的页面报自己的高度(core/visualize.ts 加的脚本),iframe 跟着变高
|
|
193
|
+
addEventListener("message", (e) => {
|
|
194
|
+
if (e.data?.type !== "aloft-html-size" || !Number.isFinite(e.data.height)) return;
|
|
195
|
+
for (const frame of document.querySelectorAll("iframe.viz-frame")) {
|
|
196
|
+
if (frame.contentWindow !== e.source) continue;
|
|
197
|
+
// 有的页面按视口高度排版,iframe 一变高它也跟着变高:设个上限,别无限长下去
|
|
198
|
+
const height = Math.min(Math.max(Math.ceil(e.data.height), 60), 1600);
|
|
199
|
+
if (Math.abs(frame.offsetHeight - height) > 2) frame.style.height = `${height}px`;
|
|
200
|
+
}
|
|
201
|
+
});
|
|
202
|
+
|
|
203
|
+
// ---------- 预览 ----------
|
|
204
|
+
|
|
205
|
+
const IMAGE = /\.(png|jpe?g|gif|webp|avif|bmp|ico|svg)$/i;
|
|
206
|
+
const VIDEO = /\.(mp4|m4v|webm|mov)$/i;
|
|
207
|
+
const AUDIO = /\.(mp3|m4a|aac|wav|ogg|oga|opus|flac)$/i;
|
|
208
|
+
const MARKDOWN = /\.(md|markdown)$/i;
|
|
209
|
+
const HTML = /\.html?$/i;
|
|
210
|
+
/** 网页超过这么大就不显示了(和服务端 core/visualize.ts 的 HTML_MAX 一致) */
|
|
211
|
+
const HTML_MAX = 2 * 1024 * 1024;
|
|
212
|
+
/** 明摆着不是文本的:不去读内容,直接给下载 */
|
|
213
|
+
const BINARY = /\.(zip|gz|tgz|bz2|xz|7z|rar|tar|docx?|xlsx?|pptx?|key|numbers|pages|exe|dmg|iso|bin|so|dylib|o|class|jar|wasm|sqlite|db|woff2?|ttf|otf|psd|ai|sketch)$/i;
|
|
214
|
+
/** 文本最多读这么多来预览 */
|
|
215
|
+
const TEXT_MAX = 1024 * 1024;
|
|
216
|
+
|
|
217
|
+
function fmtSize(n) {
|
|
218
|
+
if (!Number.isFinite(n)) return "";
|
|
219
|
+
if (n < 1024) return `${n} B`;
|
|
220
|
+
if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;
|
|
221
|
+
return `${(n / 1024 / 1024).toFixed(1)} MB`;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/** 文件预览弹层:先拿名字和大小,再按类型画内容。点外面、按 Esc 关闭 */
|
|
225
|
+
export async function openReplyFile(key, p) {
|
|
226
|
+
const url = fileUrl(key, p);
|
|
227
|
+
const body = h("div", { class: "fv-body" }, h("div", { class: "fv-loading" }, starsLoader("lg")));
|
|
228
|
+
const title = h("div", { class: "fv-title" }, h("div", { class: "fv-name" }, p.split("/").pop() || p), h("div", { class: "fv-sub" }, p));
|
|
229
|
+
const actions = h("div", { class: "fv-actions" });
|
|
230
|
+
const close = () => {
|
|
231
|
+
overlay.remove();
|
|
232
|
+
document.removeEventListener("keydown", onKey, true);
|
|
233
|
+
};
|
|
234
|
+
const onKey = (e) => {
|
|
235
|
+
if (e.key !== "Escape") return;
|
|
236
|
+
e.preventDefault();
|
|
237
|
+
close();
|
|
238
|
+
};
|
|
239
|
+
const overlay = h(
|
|
240
|
+
"div",
|
|
241
|
+
{ class: "file-viewer", onclick: (e) => e.target === overlay && close() },
|
|
242
|
+
h(
|
|
243
|
+
"div",
|
|
244
|
+
{ class: "fv-panel" },
|
|
245
|
+
h("div", { class: "fv-head" }, title, actions, h("button", { class: "icon-btn", title: "关闭", onclick: close }, icon("x"))),
|
|
246
|
+
body,
|
|
247
|
+
),
|
|
248
|
+
);
|
|
249
|
+
document.body.append(overlay);
|
|
250
|
+
document.addEventListener("keydown", onKey, true);
|
|
251
|
+
|
|
252
|
+
let info;
|
|
253
|
+
try {
|
|
254
|
+
info = await api(`${url}&stat=1`);
|
|
255
|
+
} catch (err) {
|
|
256
|
+
close();
|
|
257
|
+
toast(err.message);
|
|
258
|
+
return;
|
|
259
|
+
}
|
|
260
|
+
if (!overlay.isConnected) return;
|
|
261
|
+
title.lastChild.textContent = [info.path, fmtSize(info.size)].filter(Boolean).join(" · ");
|
|
262
|
+
title.firstChild.textContent = info.name;
|
|
263
|
+
const download = h("a", { class: "btn", href: `${url}&download=1`, download: info.name }, "下载");
|
|
264
|
+
const newTab = h("a", { class: "btn ghost", href: url, target: "_blank", rel: "noopener" }, "新标签页打开");
|
|
265
|
+
const name = info.name;
|
|
266
|
+
const media = IMAGE.test(name) || VIDEO.test(name) || AUDIO.test(name) || /\.pdf$/i.test(name);
|
|
267
|
+
actions.replaceChildren(...(media ? [newTab, download] : [download]));
|
|
268
|
+
|
|
269
|
+
if (IMAGE.test(name)) {
|
|
270
|
+
const img = h("img", { class: "fv-img", src: url, alt: name });
|
|
271
|
+
img.onerror = () => body.replaceChildren(notPreviewable("图片打不开", download));
|
|
272
|
+
return body.replaceChildren(img);
|
|
273
|
+
}
|
|
274
|
+
if (/\.pdf$/i.test(name)) return body.replaceChildren(h("iframe", { class: "fv-frame", src: url, title: name }));
|
|
275
|
+
if (VIDEO.test(name)) return body.replaceChildren(h("video", { class: "fv-media", src: url, controls: true, playsinline: true, preload: "metadata" }));
|
|
276
|
+
if (AUDIO.test(name)) return body.replaceChildren(h("audio", { class: "fv-audio", src: url, controls: true, preload: "metadata" }));
|
|
277
|
+
if (BINARY.test(name)) return body.replaceChildren(notPreviewable("这种文件不能在网页里预览", download));
|
|
278
|
+
if (info.size === 0) return body.replaceChildren(notPreviewable("空文件", null));
|
|
279
|
+
|
|
280
|
+
const showText = async () => {
|
|
281
|
+
const view = await textView(url, info, download);
|
|
282
|
+
if (overlay.isConnected) body.replaceChildren(...view);
|
|
283
|
+
};
|
|
284
|
+
// 网页:放进沙箱里显示出来,也能切到源码
|
|
285
|
+
if (HTML.test(name) && info.size <= HTML_MAX) {
|
|
286
|
+
const page = htmlUrl(key, p);
|
|
287
|
+
const frame = h("iframe", { class: "fv-frame fv-html", src: page, sandbox: "allow-scripts", referrerpolicy: "no-referrer", title: name });
|
|
288
|
+
const toggle = h(
|
|
289
|
+
"button",
|
|
290
|
+
{
|
|
291
|
+
class: "btn ghost",
|
|
292
|
+
onclick: () => {
|
|
293
|
+
const toSource = toggle.textContent === "源码";
|
|
294
|
+
toggle.textContent = toSource ? "预览" : "源码";
|
|
295
|
+
if (toSource) void showText();
|
|
296
|
+
else body.replaceChildren(frame);
|
|
297
|
+
},
|
|
298
|
+
},
|
|
299
|
+
"源码",
|
|
300
|
+
);
|
|
301
|
+
actions.replaceChildren(toggle, h("a", { class: "btn ghost", href: page, target: "_blank", rel: "noopener" }, "新标签页打开"), download);
|
|
302
|
+
return body.replaceChildren(frame);
|
|
303
|
+
}
|
|
304
|
+
await showText();
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/** 当文本显示:太大只读开头,有 NUL 字节的是二进制。返回要放进 body 的节点 */
|
|
308
|
+
async function textView(url, info, download) {
|
|
309
|
+
let buf;
|
|
310
|
+
try {
|
|
311
|
+
const res = await fetch(url, { credentials: "same-origin", headers: info.size > TEXT_MAX ? { Range: `bytes=0-${TEXT_MAX - 1}` } : {} });
|
|
312
|
+
if (!res.ok) throw new Error(`读取失败(${res.status})`);
|
|
313
|
+
buf = new Uint8Array(await res.arrayBuffer());
|
|
314
|
+
} catch (err) {
|
|
315
|
+
return [notPreviewable(err.message, download)];
|
|
316
|
+
}
|
|
317
|
+
if (buf.subarray(0, 8192).includes(0)) return [notPreviewable("这个文件不是文本,不能在网页里预览", download)];
|
|
318
|
+
const text = new TextDecoder("utf-8").decode(buf);
|
|
319
|
+
const cut = info.size > buf.length ? h("div", { class: "fv-cut" }, `文件有 ${fmtSize(info.size)},这里只显示前 ${fmtSize(buf.length)},完整内容请下载`) : null;
|
|
320
|
+
const view = MARKDOWN.test(info.name) ? h("div", { class: "fv-doc" }, renderMarkdown(text)) : codeView(text, info.name);
|
|
321
|
+
return cut ? [cut, view] : [view];
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
function codeView(text, name) {
|
|
325
|
+
const code = h("code", {});
|
|
326
|
+
const ext = (/\.([\w+-]+)$/.exec(name)?.[1] ?? "").toLowerCase();
|
|
327
|
+
const lang = hljs.getLanguage(ext) ? ext : null;
|
|
328
|
+
// 高亮很慢:太大的就原样显示
|
|
329
|
+
if (lang && text.length < 300_000) {
|
|
330
|
+
try {
|
|
331
|
+
code.innerHTML = hljs.highlight(text, { language: lang, ignoreIllegals: true }).value;
|
|
332
|
+
code.classList.add("hljs");
|
|
333
|
+
} catch {
|
|
334
|
+
code.textContent = text;
|
|
335
|
+
}
|
|
336
|
+
} else code.textContent = text;
|
|
337
|
+
return h("pre", { class: "fv-code" }, code);
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
function notPreviewable(message, download) {
|
|
341
|
+
return h("div", { class: "fv-empty" }, h("div", {}, message), download ? download.cloneNode(true) : null);
|
|
342
|
+
}
|
package/web/views/messages.js
CHANGED
|
@@ -11,6 +11,7 @@ import { renderChips, setBusy } from "./composer.js";
|
|
|
11
11
|
import { renderScheduled } from "./schedule.js";
|
|
12
12
|
import { changeCwd, doAction, forkConversation } from "./conv-actions.js";
|
|
13
13
|
import { scheduleNav } from "./msg-nav.js";
|
|
14
|
+
import { linkReplyFiles } from "./file-preview.js";
|
|
14
15
|
|
|
15
16
|
// ---------- 打开会话 ----------
|
|
16
17
|
|
|
@@ -520,13 +521,13 @@ function patchAi(item) {
|
|
|
520
521
|
v.bodyKey = bodyKey;
|
|
521
522
|
v.body = silent
|
|
522
523
|
? body
|
|
523
|
-
? h("details", { class: "silent-run" }, h("summary", {}, "🔕 定时任务:这次无需提醒"), renderMarkdown(body))
|
|
524
|
+
? h("details", { class: "silent-run" }, h("summary", {}, "🔕 定时任务:这次无需提醒"), renderMarkdown(body, { enhance: linkReplyFiles }))
|
|
524
525
|
: h("div", { class: "silent-run" }, "🔕 定时任务:这次无需提醒")
|
|
525
526
|
: body
|
|
526
527
|
? h("div", { class: "md" })
|
|
527
528
|
: null;
|
|
528
529
|
}
|
|
529
|
-
if (bodyKey === "md") patchMarkdown(v.body, body, { live: working });
|
|
530
|
+
if (bodyKey === "md") patchMarkdown(v.body, body, { live: working, enhance: linkReplyFiles });
|
|
530
531
|
|
|
531
532
|
// 还在回复:末尾挂上星星动画和实时用时;什么都还没出来时旁边带一句「思考中…」
|
|
532
533
|
if (working) {
|