agent-loft 0.2.43 → 0.2.45

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.
@@ -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
+ }
@@ -1,6 +1,6 @@
1
1
  import { $app, fill, h, icon, toast } from "../lib/dom.js";
2
2
  import { api } from "../lib/api.js";
3
- import { desktop, desktopMenu, desktopQuota, desktopSettings, remoteTabs, S, ui } from "../state.js";
3
+ import { desktop, desktopMenu, desktopQuota, desktopSettings, framed, remoteTabs, S, ui } from "../state.js";
4
4
  import { clearAppBadge, WS } from "../lib/ws.js";
5
5
  import { showAuth } from "./auth.js";
6
6
  import {
@@ -20,7 +20,8 @@ import {
20
20
  } from "./sidebar.js";
21
21
  import { applyDesktopQuota, loadQuota, renderQuota } from "./quota.js";
22
22
  import { openBotConversations, openConvContextMenu, runDesktopMenu, usableAgents } from "./topbar.js";
23
- import { showMenu } from "../lib/overlay.js";
23
+ import { confirmDialog, showMenu } from "../lib/overlay.js";
24
+ import { applyShellInfo, handleAllowEmbed, HOME, mountSwitcher, refreshShellPush, routeToServer, shellBooted, switchServer } from "../lib/shell.js";
24
25
  import { bindScrollWatch, newDraft, openConversation, scrollToBottom } from "./messages.js";
25
26
  import { renderComposer } from "./composer.js";
26
27
  import { createNav } from "./msg-nav.js";
@@ -91,6 +92,23 @@ window.addEventListener("keydown", (e) => {
91
92
  }
92
93
  });
93
94
 
95
+ // 多服务器(lib/shell.js):外壳让打开某条对话(点了这台的通知)、点了「管理服务器…」、切到别的服务器
96
+ document.addEventListener("aim:shell-open", (e) => {
97
+ if (e.detail && e.detail !== S.current) void openConversation(e.detail);
98
+ });
99
+ document.addEventListener("aim:open-settings", (e) => openSettings(e.detail));
100
+ document.addEventListener("aim:server-leave", () => closeSide());
101
+
102
+ /**
103
+ * 通知点开的地址:别的服务器的带着 srv=那台的 id(服务端 push.ts 的 relay),交给外壳切过去。
104
+ * 返回 true 表示已经交出去了
105
+ */
106
+ function routeNotice(url) {
107
+ const srv = url.searchParams.get("srv");
108
+ if (!srv || srv === HOME) return false;
109
+ return routeToServer(srv, decodeURIComponent(url.hash.slice(1)));
110
+ }
111
+
94
112
  /** 定时任务页:第一次打开时才加载 */
95
113
  export function openTasksView() {
96
114
  import("./tasks.js").then(
@@ -113,6 +131,14 @@ export async function boot() {
113
131
  S.quotaRefreshMin = data.quotaRefreshMin ?? 10;
114
132
  S.quotaEnabled = data.quotaEnabled !== false;
115
133
  S.remote = data.remote ?? null;
134
+ // 通知优先;刷新保留当前历史记录里的服务器;新打开的本机会话链接显示本机。
135
+ const landing = new URL(location.href);
136
+ const srv = landing.searchParams.get("srv");
137
+ if (srv) {
138
+ landing.searchParams.delete("srv");
139
+ history.replaceState(history.state, "", `${landing.pathname}${landing.search}${srv === HOME ? landing.hash : ""}`);
140
+ }
141
+ applyShellInfo(data.servers, srv || history.state?.loftServer || (location.hash.length > 1 ? HOME : undefined));
116
142
  applyBootstrap(data);
117
143
  S.pending = new Map(data.pending.map((i) => [i.id, i]));
118
144
  const enabled = usableAgents().map((a) => a.id);
@@ -122,6 +148,7 @@ export async function boot() {
122
148
  WS.connect();
123
149
  if (desktopQuota) desktop.onQuota(applyDesktopQuota);
124
150
  else void loadQuota();
151
+ if (srv && srv !== HOME) routeToServer(srv, decodeURIComponent(landing.hash.slice(1)));
125
152
  const fromHash = decodeURIComponent(location.hash.slice(1));
126
153
  // 地址里带了会话就打开它;否则打开「最近」里最近活跃的那个对话,一个都没有才进新对话页
127
154
  const latest = [...S.convs.values()].filter((c) => !c.hidden).sort((a, b) => b.activeAt - a.activeAt)[0];
@@ -150,17 +177,26 @@ export async function boot() {
150
177
  if (!document.querySelector(".overlay .settings")) void openSettings();
151
178
  });
152
179
  }
153
- if ("serviceWorker" in navigator) {
180
+ // 被嵌在别的服务器的页面里时,通知、角标都归外壳管
181
+ if ("serviceWorker" in navigator && !framed) {
154
182
  navigator.serviceWorker.register("/sw.js").catch(() => {});
155
183
  clearAppBadge();
156
- void releaseForeignPushSub().catch(() => {});
184
+ void releaseForeignPushSub()
185
+ .catch(() => {})
186
+ .then(() => refreshShellPush());
157
187
  // 点了系统通知、页面本来就开着:跳到通知对应的会话
158
188
  navigator.serviceWorker.addEventListener("message", (e) => {
159
189
  if (e.data?.type !== "open") return;
160
- const key = decodeURIComponent(new URL(e.data.url, location.origin).hash.slice(1));
190
+ const url = new URL(e.data.url, location.origin);
191
+ if (routeNotice(url)) return;
192
+ // 这台自己的通知:外壳正显示着别的服务器的话切回来
193
+ switchServer(HOME);
194
+ const key = decodeURIComponent(url.hash.slice(1));
161
195
  if (key && key !== S.current) void openConversation(key);
162
196
  });
163
197
  }
198
+ shellBooted();
199
+ void handleAllowEmbed(confirmDialog, toast);
164
200
  }
165
201
 
166
202
  function renderLayout() {
@@ -219,6 +255,8 @@ function renderLayout() {
219
255
  ui.sidebar = h(
220
256
  "aside",
221
257
  { class: "sidebar" },
258
+ // 左上角切换服务器(lib/shell.js),没有别的服务器时藏着
259
+ mountSwitcher("sidebar", h("div", { class: "side-switch", hidden: true })),
222
260
  h(
223
261
  "div",
224
262
  { class: "side-top" },
@@ -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
 
@@ -36,7 +37,7 @@ export function newDraft() {
36
37
  ui.follow = true;
37
38
  setBusy(false);
38
39
  renderScheduled();
39
- history.replaceState(null, "", location.pathname);
40
+ history.replaceState(history.state, "", location.pathname);
40
41
  WS.presence();
41
42
  renderTopbar();
42
43
  renderEmpty();
@@ -82,7 +83,7 @@ export async function openConversation(key) {
82
83
  ui.follow = true;
83
84
  renderChips();
84
85
  renderScheduled();
85
- history.replaceState(null, "", `#${encodeURIComponent(key)}`);
86
+ history.replaceState(history.state, "", `#${encodeURIComponent(key)}`);
86
87
  WS.presence();
87
88
  renderTopbar();
88
89
  renderSidebar();
@@ -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) {
@@ -73,7 +73,7 @@ export async function openRemote(tab) {
73
73
  async function select(tab) {
74
74
  R.tab = tab;
75
75
  localStorage.setItem("aim.remoteTab", tab);
76
- history.replaceState(null, "", `#remote/${tab}`);
76
+ history.replaceState(history.state, "", `#remote/${tab}`);
77
77
  renderSwitch();
78
78
  ui.remoteDesk.hidden = tab !== "desktop";
79
79
  ui.remoteTerm.hidden = tab !== "terminal";
@@ -97,7 +97,7 @@ export function leaveRemote() {
97
97
  const before = R.before;
98
98
  R.before = null;
99
99
  if (before === "tasks") return openTasksView();
100
- history.replaceState(null, "", S.current ? `#${encodeURIComponent(S.current)}` : location.pathname);
100
+ history.replaceState(history.state, "", S.current ? `#${encodeURIComponent(S.current)}` : location.pathname);
101
101
  // 对话区藏着的时候滚动位置没了:放回原处
102
102
  ui.messages.scrollTop = R.scroll ?? ui.messages.scrollTop;
103
103
  renderTopbar();
@@ -4,6 +4,7 @@ import { desktop, remoteTabs, S, ui } from "../state.js";
4
4
  import { baseName } from "./topbar.js";
5
5
  import { newDraft, openConversation } from "./messages.js";
6
6
  import { leaveRemote } from "./remote.js";
7
+ import { reportShellState } from "../lib/shell.js";
7
8
 
8
9
  // ---------- 侧栏标题跑马灯:名字被省略时,hover 来回滚动显示全名 ----------
9
10
 
@@ -388,11 +389,12 @@ function moreButton(st, count, limit, load) {
388
389
 
389
390
  /** 待处理的授权 / 提问和正在跑的会话,报给桌面端显示在菜单栏里 */
390
391
  export function reportDesktop() {
391
- if (!desktop) return;
392
- const pending = [...S.pending.values()]
393
- .filter((i) => !i.settled)
394
- .map((i) => ({ id: i.id, key: i.convKey, title: i.spec.title, conv: convTitle(S.convs.get(i.convKey)) }));
392
+ const open = [...S.pending.values()].filter((i) => !i.settled);
395
393
  const busy = [...S.convs.values()].filter((c) => c.busy).length;
394
+ // 多服务器:左上角切换列表里这台的角标
395
+ reportShellState(open.length, busy);
396
+ if (!desktop) return;
397
+ const pending = open.map((i) => ({ id: i.id, key: i.convKey, title: i.spec.title, conv: convTitle(S.convs.get(i.convKey)) }));
396
398
  desktop.setState({ pending, busy });
397
399
  }
398
400
 
@@ -87,7 +87,7 @@ export async function openTasks() {
87
87
  S.view = "tasks";
88
88
  S.items = [];
89
89
  S.turnAi = null;
90
- history.replaceState(null, "", "#tasks");
90
+ history.replaceState(history.state, "", "#tasks");
91
91
  WS.presence();
92
92
  ui.spacer.style.height = "0px";
93
93
  // 对话页的「贴底跟随」在这里不要:内容一变它就会滚到最底下