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.
- package/README.md +3 -1
- package/package.json +1 -1
- package/src/channels/web/api.ts +146 -3
- package/src/channels/web/http.ts +12 -0
- package/src/channels/web/push.ts +130 -6
- package/src/channels/web/server.ts +4 -3
- package/src/core/config.ts +36 -0
- package/src/core/hub.ts +14 -0
- package/src/core/reply-files.ts +142 -0
- package/src/core/servers.ts +134 -0
- package/src/core/uploads.ts +1 -1
- package/src/core/visualize.ts +123 -0
- package/web/css/messages.css +271 -0
- package/web/css/servers.css +265 -0
- package/web/index.html +1 -0
- package/web/lib/api.js +1 -0
- package/web/lib/markdown.js +5 -3
- package/web/lib/overlay.js +1 -1
- package/web/lib/push.js +8 -1
- package/web/lib/shell.js +691 -0
- package/web/lib/ws.js +7 -1
- package/web/settings/common.js +3 -0
- package/web/settings/index.js +2 -0
- package/web/settings/notify.js +7 -2
- package/web/settings/security.js +8 -3
- package/web/settings/servers.js +207 -0
- package/web/state.js +2 -0
- package/web/views/auth.js +3 -1
- package/web/views/composer.js +1 -1
- package/web/views/file-preview.js +342 -0
- package/web/views/layout.js +43 -5
- package/web/views/messages.js +5 -4
- package/web/views/remote.js +2 -2
- package/web/views/sidebar.js +6 -4
- package/web/views/tasks.js +1 -1
package/web/lib/shell.js
ADDED
|
@@ -0,0 +1,691 @@
|
|
|
1
|
+
import { $app, fill, h, icon } from "./dom.js";
|
|
2
|
+
import { api } from "./api.js";
|
|
3
|
+
import { closeMenu, showMenu } from "./overlay.js";
|
|
4
|
+
import { currentPushSub } from "./push.js";
|
|
5
|
+
import { desktop, framed, isAdmin, S, ui } from "../state.js";
|
|
6
|
+
|
|
7
|
+
// ---------- 多服务器:左上角切换到别的 agent-loft ----------
|
|
8
|
+
//
|
|
9
|
+
// 像 Codex 桌面端左上角那样切换。别的服务器的页面原样嵌在 iframe 里,各自登录、各自直连自己的
|
|
10
|
+
// 服务端(回复流、终端、远程桌面都不经过这台);切走时 iframe 只是藏起来,连接一直在。
|
|
11
|
+
// 同一份前端两种身份:
|
|
12
|
+
// - 外壳(host):服务端配了别的服务器(bootstrap 的 servers),这台页面管着一排 iframe;
|
|
13
|
+
// - 被嵌(guest):自己在外壳的 iframe 里,左上角的切换列表由外壳发过来,点了告诉外壳。
|
|
14
|
+
// 两边用 postMessage 说话,只认对方的 origin:外壳只认列表里那台的地址、且是自己那个 iframe 发来的;
|
|
15
|
+
// 被嵌的只认 window.parent(服务端的 frame-ancestors 保证了它是允许嵌这台的地址)。
|
|
16
|
+
//
|
|
17
|
+
// 推送:手机上只有添加到主屏幕的外壳能订阅。外壳把订阅连同签名用的密钥发给各台,各台存到自己的
|
|
18
|
+
// 服务端,之后直接推到手机上(服务端 push.ts 的 relay);点开通知回到外壳,地址里的 srv= 说是哪台。
|
|
19
|
+
|
|
20
|
+
const NS = "agent-loft";
|
|
21
|
+
/** 外壳自己在列表里的 id(和服务端 core/servers.ts 的 SELF_ID 一致) */
|
|
22
|
+
export const HOME = "home";
|
|
23
|
+
const LAST = "aim.server";
|
|
24
|
+
/** 页面加载完了还没报到:多半是被拒绝嵌入、卡在登录网关,或者连不上 */
|
|
25
|
+
const READY_WAIT_MS = 4000;
|
|
26
|
+
/** 一直没加载完 */
|
|
27
|
+
const LOAD_WAIT_MS = 25000;
|
|
28
|
+
|
|
29
|
+
export const SH = {
|
|
30
|
+
/** "host":外壳;"guest":被嵌着;null:没有多服务器 */
|
|
31
|
+
role: null,
|
|
32
|
+
/** [{ id, name, icon, url?, pending, busy, state }],第一个是外壳自己。state:ready / loading / down */
|
|
33
|
+
servers: [],
|
|
34
|
+
/** 外壳上正在显示哪台 */
|
|
35
|
+
current: HOME,
|
|
36
|
+
/** 被嵌时:这台在外壳列表里的 id,外壳现在是不是正显示着这台,外壳的地址 */
|
|
37
|
+
self: null,
|
|
38
|
+
active: true,
|
|
39
|
+
hostOrigin: null,
|
|
40
|
+
/** 要转给各台的推送订阅 { subscription, vapid }(外壳上开了通知才有) */
|
|
41
|
+
push: null,
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
/** 这个页面现在是不是用户眼前那一个:外壳切到了别的服务器、或者被嵌着但没在显示,就不算 */
|
|
45
|
+
export function shownHere() {
|
|
46
|
+
if (SH.role === "host") return SH.current === HOME;
|
|
47
|
+
if (SH.role === "guest") return SH.active;
|
|
48
|
+
return true;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const emit = (name, detail) => document.dispatchEvent(new CustomEvent(name, { detail }));
|
|
52
|
+
|
|
53
|
+
// ---------- 左上角的切换按钮 ----------
|
|
54
|
+
|
|
55
|
+
/** 挂着切换按钮的容器:侧栏顶部、登录页、iframe 还没就绪时的浮动按钮。同名的后挂的顶替先挂的 */
|
|
56
|
+
const mounted = new Map();
|
|
57
|
+
|
|
58
|
+
export function mountSwitcher(name, el) {
|
|
59
|
+
mounted.set(name, el);
|
|
60
|
+
renderSwitcher(el);
|
|
61
|
+
return el;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function rerender() {
|
|
65
|
+
for (const el of mounted.values()) renderSwitcher(el);
|
|
66
|
+
// 切换器重绘会更新 hidden;已就绪的 iframe 不能再被加载期间的浮动按钮盖住。
|
|
67
|
+
for (const f of frames.values()) f.pill.hidden = f.ready;
|
|
68
|
+
emit("aim:servers");
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const currentId = () => (SH.role === "guest" ? SH.self : SH.current);
|
|
72
|
+
|
|
73
|
+
function srvIcon(s, cls = "srv-icon") {
|
|
74
|
+
if (s.icon) return h("span", { class: cls }, s.icon);
|
|
75
|
+
// 没设图标:名字的第一个字
|
|
76
|
+
return h("span", { class: `${cls} letter` }, [...(s.name || "?")][0].toUpperCase());
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function renderSwitcher(el) {
|
|
80
|
+
const cur = SH.servers.find((s) => s.id === currentId());
|
|
81
|
+
el.hidden = !SH.role || SH.servers.length < 2 || !cur;
|
|
82
|
+
if (el.hidden) return fill(el);
|
|
83
|
+
// 别的服务器上有等你处理的:按钮上也标出来,不用点开才知道
|
|
84
|
+
const ask = SH.servers.filter((s) => s !== cur).reduce((n, s) => n + (s.pending || 0), 0);
|
|
85
|
+
const btn = h(
|
|
86
|
+
"button",
|
|
87
|
+
{ class: "server-switch", title: "切换服务器", "aria-haspopup": "menu" },
|
|
88
|
+
srvIcon(cur),
|
|
89
|
+
h("span", { class: "srv-name" }, cur.name),
|
|
90
|
+
ask ? h("span", { class: "srv-badge", title: `别的服务器上有 ${ask} 项等你处理` }, ask) : null,
|
|
91
|
+
h("span", { class: "srv-chev" }, icon("down")),
|
|
92
|
+
);
|
|
93
|
+
btn.onclick = () => {
|
|
94
|
+
if (ui.menu?.anchor === btn) return closeMenu();
|
|
95
|
+
openSwitchMenu(btn);
|
|
96
|
+
};
|
|
97
|
+
fill(el, btn);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function openSwitchMenu(btn) {
|
|
101
|
+
const cur = currentId();
|
|
102
|
+
const items = SH.servers.map((s) => ({
|
|
103
|
+
class: `srv-item${s.id === cur ? " on" : ""}`,
|
|
104
|
+
label: [
|
|
105
|
+
srvIcon(s),
|
|
106
|
+
h("span", { class: "srv-item-name" }, s.name),
|
|
107
|
+
s.pending
|
|
108
|
+
? h("span", { class: "srv-badge", title: `${s.pending} 项等你处理` }, s.pending)
|
|
109
|
+
: s.busy
|
|
110
|
+
? h("span", { class: "srv-busy", title: `${s.busy} 个对话正在运行` })
|
|
111
|
+
: s.state === "down"
|
|
112
|
+
? h("span", { class: "srv-down" }, "没连上")
|
|
113
|
+
: null,
|
|
114
|
+
s.id === cur ? h("span", { class: "srv-check" }, "✓") : null,
|
|
115
|
+
],
|
|
116
|
+
onclick: () => pickServer(s.id),
|
|
117
|
+
}));
|
|
118
|
+
// 服务器在外壳那台的设置里管:被嵌着的页面里不放入口(那是另一台的设置)
|
|
119
|
+
if (SH.role === "host" && isAdmin()) items.push("sep", { class: "srv-manage", label: "管理服务器…", onclick: () => emit("aim:open-settings", "服务器") });
|
|
120
|
+
showMenu(btn, items);
|
|
121
|
+
if (ui.menu) ui.menu.anchor = btn;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function pickServer(id) {
|
|
125
|
+
if (id === currentId()) return;
|
|
126
|
+
emit("aim:server-leave");
|
|
127
|
+
if (SH.role === "host") switchServer(id);
|
|
128
|
+
else if (SH.role === "guest") toHost({ t: "switch", to: id });
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
// ---------- 外壳 ----------
|
|
132
|
+
|
|
133
|
+
/** id → { s, wrap, iframe, overlay, pill, ready, loaded, timers, queue, insets } */
|
|
134
|
+
const frames = new Map();
|
|
135
|
+
/** 已从列表移除、还在等远端退订完成的页面 */
|
|
136
|
+
const retiringFrames = new Set();
|
|
137
|
+
let cleanupId = 0;
|
|
138
|
+
let box = null;
|
|
139
|
+
/** 这台自己的待处理、运行数(sidebar.js 报上来) */
|
|
140
|
+
let local = { pending: 0, busy: 0 };
|
|
141
|
+
|
|
142
|
+
const post = (f, msg) => f.iframe.contentWindow?.postMessage({ ns: NS, ...msg }, f.s.url);
|
|
143
|
+
|
|
144
|
+
function sendWhenReady(f, msg) {
|
|
145
|
+
if (f.ready) post(f, msg);
|
|
146
|
+
else f.queue.push(msg);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
const publicServers = () => SH.servers.map(({ id, name, icon: ic, pending, busy, state }) => ({ id, name, icon: ic, pending, busy, state }));
|
|
150
|
+
|
|
151
|
+
let broadcastQueued = false;
|
|
152
|
+
/** 列表、角标变了:告诉各台(它们左上角的切换按钮要跟着变)。连着几次变化只发一次 */
|
|
153
|
+
function broadcastServers() {
|
|
154
|
+
if (broadcastQueued) return;
|
|
155
|
+
broadcastQueued = true;
|
|
156
|
+
queueMicrotask(() => {
|
|
157
|
+
broadcastQueued = false;
|
|
158
|
+
const servers = publicServers();
|
|
159
|
+
for (const f of frames.values()) if (f.ready) post(f, { t: "servers", servers });
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function stateOf(f) {
|
|
164
|
+
return f.ready ? "ready" : f.down ? "down" : "loading";
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
function setFrameState(f) {
|
|
168
|
+
if (f.stale) return;
|
|
169
|
+
f.s.state = stateOf(f);
|
|
170
|
+
f.overlay.hidden = f.ready || f.dismissed;
|
|
171
|
+
f.pill.hidden = f.ready;
|
|
172
|
+
if (!f.ready) {
|
|
173
|
+
fill(
|
|
174
|
+
f.overlay,
|
|
175
|
+
f.down
|
|
176
|
+
? h(
|
|
177
|
+
"div",
|
|
178
|
+
{ class: "srv-card" },
|
|
179
|
+
h("h3", {}, `${f.s.name} 没有响应`),
|
|
180
|
+
h(
|
|
181
|
+
"ul",
|
|
182
|
+
{},
|
|
183
|
+
h("li", {}, "那台还没允许这台嵌入:点「打开并授权」,在新页面里确认"),
|
|
184
|
+
h("li", {}, "前面有登录网关(比如 Cloudflare Access):在新页面里先验证一次"),
|
|
185
|
+
h("li", {}, "那台的 agent-loft 版本太旧(要支持多服务器的版本),或者现在连不上"),
|
|
186
|
+
),
|
|
187
|
+
h(
|
|
188
|
+
"div",
|
|
189
|
+
{ class: "row" },
|
|
190
|
+
h("button", { class: "btn primary", onclick: () => openForAuth(f.s) }, "打开并授权"),
|
|
191
|
+
h("button", { class: "btn", onclick: () => reloadFrame(f) }, "重试"),
|
|
192
|
+
h("button", { class: "btn ghost", onclick: () => ((f.dismissed = true), setFrameState(f)) }, "关掉提示"),
|
|
193
|
+
),
|
|
194
|
+
)
|
|
195
|
+
: h("div", { class: "srv-loading" }, h("span", { class: "spinner" }), `正在打开 ${f.s.name}…`),
|
|
196
|
+
);
|
|
197
|
+
}
|
|
198
|
+
rerender();
|
|
199
|
+
broadcastServers();
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** 在新标签页打开那台,带上 allow-embed:那边的管理员确认后就允许这台嵌入,再通知这边重新加载 */
|
|
203
|
+
export function openForAuth(s) {
|
|
204
|
+
window.open(`${s.url}/?allow-embed=${encodeURIComponent(location.origin)}`, "_blank");
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
function waitReady(f, ms) {
|
|
208
|
+
clearTimeout(f.timer);
|
|
209
|
+
f.timer = setTimeout(() => {
|
|
210
|
+
if (f.ready) return;
|
|
211
|
+
f.down = true;
|
|
212
|
+
setFrameState(f);
|
|
213
|
+
}, ms);
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* 页面加载时 CSP 的 frame-src 里有哪些地址(服务端按当时的列表出的)。之后新加的,
|
|
218
|
+
* 要刷新页面拿到新的 CSP 才嵌得进来
|
|
219
|
+
*/
|
|
220
|
+
let frameable = null;
|
|
221
|
+
export const canFrame = (url) => !!frameable?.has(url);
|
|
222
|
+
|
|
223
|
+
function createFrame(s) {
|
|
224
|
+
if (!canFrame(s.url)) {
|
|
225
|
+
const f = { s, iframe: h("iframe", { title: s.name }), ready: false, down: true, dismissed: false, queue: [], timer: 0, stale: true };
|
|
226
|
+
f.overlay = h(
|
|
227
|
+
"div",
|
|
228
|
+
{ class: "srv-overlay" },
|
|
229
|
+
h("div", { class: "srv-card" }, h("h3", {}, `${s.name} 是刚加的`), h("p", {}, "刷新一下页面才能打开它。"), h("div", { class: "row" }, h("button", { class: "btn primary", onclick: () => location.reload() }, "刷新页面"))),
|
|
230
|
+
);
|
|
231
|
+
f.pill = mountSwitcher(`pill:${s.id}`, h("div", { class: "srv-pill" }));
|
|
232
|
+
f.wrap = h("div", { class: "server-frame" }, f.overlay, f.pill);
|
|
233
|
+
frames.set(s.id, f);
|
|
234
|
+
box.append(f.wrap);
|
|
235
|
+
s.state = "down";
|
|
236
|
+
return f;
|
|
237
|
+
}
|
|
238
|
+
const iframe = h("iframe", {
|
|
239
|
+
src: `${s.url}/`,
|
|
240
|
+
title: s.name,
|
|
241
|
+
// 语音输入、复制粘贴、远程桌面全屏
|
|
242
|
+
allow: "microphone; clipboard-read; clipboard-write; fullscreen; autoplay; screen-wake-lock",
|
|
243
|
+
allowfullscreen: true,
|
|
244
|
+
});
|
|
245
|
+
const f = { s, iframe, ready: false, down: false, dismissed: false, queue: [], timer: 0 };
|
|
246
|
+
f.overlay = h("div", { class: "srv-overlay" });
|
|
247
|
+
f.pill = mountSwitcher(`pill:${s.id}`, h("div", { class: "srv-pill" }));
|
|
248
|
+
f.wrap = h("div", { class: "server-frame" }, iframe, f.overlay, f.pill);
|
|
249
|
+
iframe.addEventListener("load", () => {
|
|
250
|
+
// 页面加载完还没报到:等一小会儿,还没有就提示
|
|
251
|
+
if (!f.ready) waitReady(f, READY_WAIT_MS);
|
|
252
|
+
});
|
|
253
|
+
waitReady(f, LOAD_WAIT_MS);
|
|
254
|
+
frames.set(s.id, f);
|
|
255
|
+
box.append(f.wrap);
|
|
256
|
+
setFrameState(f);
|
|
257
|
+
return f;
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
function reloadFrame(f) {
|
|
261
|
+
f.ready = false;
|
|
262
|
+
f.down = false;
|
|
263
|
+
f.dismissed = false;
|
|
264
|
+
f.iframe.src = `${f.s.url}/`;
|
|
265
|
+
waitReady(f, LOAD_WAIT_MS);
|
|
266
|
+
setFrameState(f);
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
function dropFrame(f) {
|
|
270
|
+
clearTimeout(f.timer);
|
|
271
|
+
mounted.delete(`pill:${f.s.id}`);
|
|
272
|
+
frames.delete(f.s.id);
|
|
273
|
+
f.wrap.hidden = true;
|
|
274
|
+
if (!f.ready || !SH.push) {
|
|
275
|
+
f.wrap.remove();
|
|
276
|
+
return Promise.resolve();
|
|
277
|
+
}
|
|
278
|
+
// postMessage 是异步的,等远端完成退订再销毁页面;超时也要回收失联的 iframe。
|
|
279
|
+
retiringFrames.add(f);
|
|
280
|
+
return new Promise((resolve) => {
|
|
281
|
+
f.cleanupId = ++cleanupId;
|
|
282
|
+
f.finishCleanup = () => {
|
|
283
|
+
clearTimeout(f.timer);
|
|
284
|
+
retiringFrames.delete(f);
|
|
285
|
+
f.wrap.remove();
|
|
286
|
+
resolve();
|
|
287
|
+
};
|
|
288
|
+
f.timer = setTimeout(f.finishCleanup, 8000);
|
|
289
|
+
post(f, { t: "push-off", endpoint: SH.push.subscription.endpoint, request: f.cleanupId });
|
|
290
|
+
});
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/** 安全区(刘海、底部横条):iframe 里拿到的多半是 0,由外壳在外面垫上差额 */
|
|
294
|
+
function safeInsets() {
|
|
295
|
+
const probe = h("div", {
|
|
296
|
+
style: {
|
|
297
|
+
position: "fixed",
|
|
298
|
+
visibility: "hidden",
|
|
299
|
+
pointerEvents: "none",
|
|
300
|
+
paddingTop: "env(safe-area-inset-top)",
|
|
301
|
+
paddingRight: "env(safe-area-inset-right)",
|
|
302
|
+
paddingBottom: "env(safe-area-inset-bottom)",
|
|
303
|
+
paddingLeft: "env(safe-area-inset-left)",
|
|
304
|
+
},
|
|
305
|
+
});
|
|
306
|
+
document.body.append(probe);
|
|
307
|
+
const cs = getComputedStyle(probe);
|
|
308
|
+
const out = { top: parseFloat(cs.paddingTop) || 0, right: parseFloat(cs.paddingRight) || 0, bottom: parseFloat(cs.paddingBottom) || 0, left: parseFloat(cs.paddingLeft) || 0 };
|
|
309
|
+
probe.remove();
|
|
310
|
+
return out;
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
function padFrame(f) {
|
|
314
|
+
const mine = safeInsets();
|
|
315
|
+
const theirs = f.insets ?? { top: 0, right: 0, bottom: 0, left: 0 };
|
|
316
|
+
const gap = (k) => `${Math.max(0, mine[k] - (theirs[k] || 0))}px`;
|
|
317
|
+
f.wrap.style.padding = `${gap("top")} ${gap("right")} ${gap("bottom")} ${gap("left")}`;
|
|
318
|
+
}
|
|
319
|
+
addEventListener("resize", () => {
|
|
320
|
+
for (const f of frames.values()) padFrame(f);
|
|
321
|
+
});
|
|
322
|
+
|
|
323
|
+
function showCurrent() {
|
|
324
|
+
if (!box) return;
|
|
325
|
+
// 跟着当前历史记录保存:刷新沿用这台,新打开的对话链接仍可直接定位本机。
|
|
326
|
+
history.replaceState({ ...history.state, loftServer: SH.current }, "");
|
|
327
|
+
box.hidden = SH.current === HOME;
|
|
328
|
+
for (const [id, f] of frames) f.wrap.classList.toggle("on", id === SH.current);
|
|
329
|
+
// 别的服务器盖在上面时,底下这台的页面不能被 Tab 到、不能被读屏读到
|
|
330
|
+
$app.inert = SH.current !== HOME;
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
/** 外壳上切到哪台 */
|
|
334
|
+
export function switchServer(id) {
|
|
335
|
+
if (SH.role !== "host" || !SH.servers.some((s) => s.id === id)) return;
|
|
336
|
+
closeMenu();
|
|
337
|
+
if (id !== SH.current) {
|
|
338
|
+
SH.current = id;
|
|
339
|
+
localStorage.setItem(LAST, id);
|
|
340
|
+
showCurrent();
|
|
341
|
+
for (const f of frames.values()) if (f.ready) post(f, { t: "active", current: id });
|
|
342
|
+
emit("aim:shell-active");
|
|
343
|
+
rerender();
|
|
344
|
+
}
|
|
345
|
+
const f = frames.get(id);
|
|
346
|
+
if (f) {
|
|
347
|
+
padFrame(f);
|
|
348
|
+
f.iframe.focus();
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
/**
|
|
353
|
+
* 点了别的服务器的通知:切过去,让那台打开那条对话。srv 不认识(列表里删掉了)返回 false,
|
|
354
|
+
* 留在这台
|
|
355
|
+
*/
|
|
356
|
+
export function routeToServer(srv, key) {
|
|
357
|
+
if (SH.role !== "host" || !srv || srv === HOME) return false;
|
|
358
|
+
const f = frames.get(srv);
|
|
359
|
+
if (!f) return false;
|
|
360
|
+
switchServer(srv);
|
|
361
|
+
if (key) sendWhenReady(f, { t: "open", key });
|
|
362
|
+
return true;
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
/**
|
|
366
|
+
* 服务端给的列表(bootstrap 的 servers)。启动时、设置里改了之后调;null 就是没有别的服务器了。
|
|
367
|
+
* 首次调用时 want 是想先显示哪台(通知点进来的、上次看的)
|
|
368
|
+
*/
|
|
369
|
+
export function applyShellInfo(info, want) {
|
|
370
|
+
if (desktop || framed) return;
|
|
371
|
+
frameable ??= new Set((info?.list ?? []).map((s) => s.url));
|
|
372
|
+
if (!info?.list?.length) {
|
|
373
|
+
if (SH.role !== "host") return;
|
|
374
|
+
const cleanup = Promise.all([...frames.values()].map(dropFrame));
|
|
375
|
+
SH.role = null;
|
|
376
|
+
SH.servers = [];
|
|
377
|
+
SH.current = HOME;
|
|
378
|
+
showCurrent();
|
|
379
|
+
const oldBox = box;
|
|
380
|
+
box = null;
|
|
381
|
+
void cleanup.then(() => oldBox?.remove());
|
|
382
|
+
emit("aim:shell-active");
|
|
383
|
+
rerender();
|
|
384
|
+
return;
|
|
385
|
+
}
|
|
386
|
+
const first = SH.role !== "host";
|
|
387
|
+
SH.role = "host";
|
|
388
|
+
const old = new Map(SH.servers.map((s) => [s.id, s]));
|
|
389
|
+
SH.servers = [
|
|
390
|
+
{ id: HOME, name: info.self.name, icon: info.self.icon, ...local, state: "ready" },
|
|
391
|
+
...info.list.map((s) => ({ pending: 0, busy: 0, state: "loading", ...old.get(s.id), ...s })),
|
|
392
|
+
];
|
|
393
|
+
if (!box) {
|
|
394
|
+
box = h("div", { class: "server-frames", hidden: true });
|
|
395
|
+
document.body.append(box);
|
|
396
|
+
}
|
|
397
|
+
for (const f of [...frames.values()]) {
|
|
398
|
+
const s = SH.servers.find((x) => x.id === f.s.id);
|
|
399
|
+
if (!s || s.url !== f.s.url) dropFrame(f);
|
|
400
|
+
else f.s = s;
|
|
401
|
+
}
|
|
402
|
+
for (const s of SH.servers) if (s.id !== HOME && !frames.has(s.id)) createFrame(s);
|
|
403
|
+
for (const f of frames.values()) {
|
|
404
|
+
f.iframe.title = f.s.name;
|
|
405
|
+
setFrameState(f);
|
|
406
|
+
}
|
|
407
|
+
rerender();
|
|
408
|
+
if (first) {
|
|
409
|
+
const last = localStorage.getItem(LAST);
|
|
410
|
+
const pick = want ?? last ?? HOME;
|
|
411
|
+
SH.current = SH.servers.some((s) => s.id === pick) ? pick : HOME;
|
|
412
|
+
} else if (!SH.servers.some((s) => s.id === SH.current)) SH.current = HOME;
|
|
413
|
+
showCurrent();
|
|
414
|
+
if (SH.current !== HOME) padFrame(frames.get(SH.current));
|
|
415
|
+
emit("aim:shell-active");
|
|
416
|
+
rerender();
|
|
417
|
+
broadcastServers();
|
|
418
|
+
void refreshShellPush();
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
function onGuestMessage(f, m) {
|
|
422
|
+
switch (m.t) {
|
|
423
|
+
case "ready":
|
|
424
|
+
f.ready = true;
|
|
425
|
+
f.down = false;
|
|
426
|
+
f.dismissed = false;
|
|
427
|
+
clearTimeout(f.timer);
|
|
428
|
+
f.insets = m.insets;
|
|
429
|
+
padFrame(f);
|
|
430
|
+
post(f, { t: "hello", self: f.s.id, servers: publicServers(), current: SH.current, push: SH.push });
|
|
431
|
+
for (const msg of f.queue.splice(0)) post(f, msg);
|
|
432
|
+
setFrameState(f);
|
|
433
|
+
return;
|
|
434
|
+
case "bye":
|
|
435
|
+
// 那台的页面要换了(刷新、跳去登录网关):等新页面报到
|
|
436
|
+
f.ready = false;
|
|
437
|
+
setFrameState(f);
|
|
438
|
+
return;
|
|
439
|
+
case "state": {
|
|
440
|
+
const pending = Math.max(0, Math.min(999, Number(m.pending) || 0));
|
|
441
|
+
const busy = Math.max(0, Math.min(999, Number(m.busy) || 0));
|
|
442
|
+
if (pending === f.s.pending && busy === f.s.busy) return;
|
|
443
|
+
Object.assign(f.s, { pending, busy });
|
|
444
|
+
rerender();
|
|
445
|
+
broadcastServers();
|
|
446
|
+
return;
|
|
447
|
+
}
|
|
448
|
+
case "switch":
|
|
449
|
+
if (typeof m.to === "string") switchServer(m.to);
|
|
450
|
+
return;
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
/** 这台自己的待处理、运行数变了(侧栏重画时报):外壳上更新自己那项,被嵌时报给外壳 */
|
|
455
|
+
export function reportShellState(pending, busy) {
|
|
456
|
+
if (pending === local.pending && busy === local.busy) return;
|
|
457
|
+
local = { pending, busy };
|
|
458
|
+
if (SH.role === "host") {
|
|
459
|
+
Object.assign(SH.servers[0], local);
|
|
460
|
+
rerender();
|
|
461
|
+
broadcastServers();
|
|
462
|
+
} else if (SH.role === "guest") {
|
|
463
|
+
toHost({ t: "state", ...local });
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
// ---------- 推送:外壳把订阅转给各台 ----------
|
|
468
|
+
|
|
469
|
+
const b64url = (buf) => btoa(String.fromCharCode(...new Uint8Array(buf))).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
470
|
+
|
|
471
|
+
/** 这个浏览器的通知订阅开了 / 关了:告诉各台。设置里开关通知后、启动时调 */
|
|
472
|
+
export async function refreshShellPush() {
|
|
473
|
+
if (SH.role !== "host") return;
|
|
474
|
+
let next = null;
|
|
475
|
+
const sub = await currentPushSub();
|
|
476
|
+
if (sub) {
|
|
477
|
+
try {
|
|
478
|
+
const vapid = await api("/api/push/relay-key");
|
|
479
|
+
// 订阅得是对着这台的公钥开的,各台用这把密钥签名才推得过去
|
|
480
|
+
const key = sub.options?.applicationServerKey;
|
|
481
|
+
if (!key || b64url(key) === vapid.publicKey) next = { subscription: sub.toJSON(), vapid };
|
|
482
|
+
} catch {
|
|
483
|
+
// 拿不到就先不转
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
const old = SH.push;
|
|
487
|
+
if (old?.subscription.endpoint === next?.subscription.endpoint) return;
|
|
488
|
+
SH.push = next;
|
|
489
|
+
for (const f of frames.values()) {
|
|
490
|
+
if (!f.ready) continue;
|
|
491
|
+
if (next) post(f, { t: "push", push: next });
|
|
492
|
+
else post(f, { t: "push-off", endpoint: old.subscription.endpoint });
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
// ---------- 被嵌着 ----------
|
|
497
|
+
|
|
498
|
+
function toHost(msg) {
|
|
499
|
+
if (SH.hostOrigin) window.parent.postMessage({ ns: NS, ...msg }, SH.hostOrigin);
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
/** 登录完了、打开过的页面才处理的:外壳让打开的对话 */
|
|
503
|
+
let pendingOpen = null;
|
|
504
|
+
let relayed = null;
|
|
505
|
+
let relayWork = Promise.resolve();
|
|
506
|
+
let relayStopped = false;
|
|
507
|
+
|
|
508
|
+
/** 把外壳转来的推送订阅存到这台的服务端(要登录了才行;同一个订阅、同一个账号只存一次) */
|
|
509
|
+
function applyRelayPush() {
|
|
510
|
+
if (SH.role !== "guest" || !SH.push || !S.user || relayStopped) return;
|
|
511
|
+
const me = SH.servers.find((s) => s.id === SH.self);
|
|
512
|
+
const label = me ? `${me.icon} ${me.name}`.trim() : "";
|
|
513
|
+
const mark = JSON.stringify([S.user.id, SH.push.subscription.endpoint, SH.self, label]);
|
|
514
|
+
if (relayed === mark) return;
|
|
515
|
+
relayed = mark;
|
|
516
|
+
const body = {
|
|
517
|
+
subscription: SH.push.subscription,
|
|
518
|
+
vapid: SH.push.vapid,
|
|
519
|
+
via: { origin: SH.hostOrigin, server: SH.self, label },
|
|
520
|
+
};
|
|
521
|
+
relayWork = relayWork.catch(() => {}).then(() => api("/api/push/relay", {
|
|
522
|
+
method: "POST",
|
|
523
|
+
body,
|
|
524
|
+
})).catch((err) => {
|
|
525
|
+
if (relayed === mark) relayed = null;
|
|
526
|
+
console.warn("[多服务器] 通知订阅没转过来:", err.message);
|
|
527
|
+
});
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
/** 退出登录或外壳移除这台:先等正在注册的请求结束,再撤销这台的订阅。 */
|
|
531
|
+
export function dropRelayPush(endpoint = SH.push?.subscription.endpoint, loggingOut = true) {
|
|
532
|
+
if (SH.role !== "guest") return Promise.resolve();
|
|
533
|
+
if (loggingOut) relayStopped = true;
|
|
534
|
+
relayed = null;
|
|
535
|
+
if (!S.user || typeof endpoint !== "string") return Promise.resolve();
|
|
536
|
+
relayWork = relayWork.catch(() => {}).then(() => api("/api/push/unsubscribe", {
|
|
537
|
+
method: "POST",
|
|
538
|
+
body: { endpoint },
|
|
539
|
+
// 超时回收 iframe 时,已经发出的退订请求仍能完成。
|
|
540
|
+
keepalive: true,
|
|
541
|
+
}));
|
|
542
|
+
return relayWork;
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
function onHostMessage(origin, m) {
|
|
546
|
+
switch (m.t) {
|
|
547
|
+
case "hello":
|
|
548
|
+
SH.role = "guest";
|
|
549
|
+
SH.hostOrigin = origin;
|
|
550
|
+
SH.self = m.self;
|
|
551
|
+
SH.servers = Array.isArray(m.servers) ? m.servers : [];
|
|
552
|
+
SH.current = m.current;
|
|
553
|
+
SH.active = m.current === m.self;
|
|
554
|
+
SH.push = m.push ?? null;
|
|
555
|
+
document.documentElement.classList.add("in-shell");
|
|
556
|
+
toHost({ t: "state", ...local });
|
|
557
|
+
emit("aim:shell-active");
|
|
558
|
+
rerender();
|
|
559
|
+
applyRelayPush();
|
|
560
|
+
return;
|
|
561
|
+
case "servers":
|
|
562
|
+
if (Array.isArray(m.servers)) SH.servers = m.servers;
|
|
563
|
+
rerender();
|
|
564
|
+
applyRelayPush();
|
|
565
|
+
return;
|
|
566
|
+
case "active":
|
|
567
|
+
SH.current = m.current;
|
|
568
|
+
SH.active = m.current === SH.self;
|
|
569
|
+
emit("aim:shell-active");
|
|
570
|
+
return;
|
|
571
|
+
case "open":
|
|
572
|
+
if (typeof m.key !== "string") return;
|
|
573
|
+
if (S.user) emit("aim:shell-open", m.key);
|
|
574
|
+
else pendingOpen = m.key;
|
|
575
|
+
return;
|
|
576
|
+
case "push":
|
|
577
|
+
SH.push = m.push ?? null;
|
|
578
|
+
applyRelayPush();
|
|
579
|
+
return;
|
|
580
|
+
case "push-off":
|
|
581
|
+
SH.push = null;
|
|
582
|
+
void dropRelayPush(m.endpoint, false).then(() => {
|
|
583
|
+
toHost({ t: "push-off-done", request: m.request });
|
|
584
|
+
}).catch((err) => console.warn("[多服务器] 通知订阅没有撤销:", err.message));
|
|
585
|
+
return;
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
/** 页面启动完(登录了、主界面画好了):被嵌时把攒着的事办了 */
|
|
590
|
+
export function shellBooted() {
|
|
591
|
+
if (SH.role !== "guest") return;
|
|
592
|
+
relayStopped = false;
|
|
593
|
+
toHost({ t: "state", ...local });
|
|
594
|
+
applyRelayPush();
|
|
595
|
+
if (pendingOpen) {
|
|
596
|
+
emit("aim:shell-open", pendingOpen);
|
|
597
|
+
pendingOpen = null;
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
window.addEventListener("message", (e) => {
|
|
602
|
+
const m = e.data;
|
|
603
|
+
if (!m || typeof m !== "object" || m.ns !== NS || typeof m.t !== "string") return;
|
|
604
|
+
if (framed) {
|
|
605
|
+
if (e.source !== window.parent || (SH.hostOrigin && e.origin !== SH.hostOrigin)) return;
|
|
606
|
+
onHostMessage(e.origin, m);
|
|
607
|
+
return;
|
|
608
|
+
}
|
|
609
|
+
// 删掉最后一台后 role 已经清空,仍要接收退订确认。
|
|
610
|
+
for (const f of retiringFrames) {
|
|
611
|
+
if (e.source === f.iframe.contentWindow && e.origin === f.s.url) {
|
|
612
|
+
if (m.t === "push-off-done" && m.request === f.cleanupId) f.finishCleanup();
|
|
613
|
+
return;
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
if (SH.role !== "host") return;
|
|
617
|
+
for (const f of frames.values()) {
|
|
618
|
+
if (f.iframe.contentWindow !== e.source) continue;
|
|
619
|
+
if (e.origin === f.s.url) onGuestMessage(f, m);
|
|
620
|
+
return;
|
|
621
|
+
}
|
|
622
|
+
// 新标签页里那台授权完了(openForAuth):重新加载它
|
|
623
|
+
if (m.t === "embed-allowed") {
|
|
624
|
+
for (const f of frames.values()) if (f.s.url === e.origin) reloadFrame(f);
|
|
625
|
+
}
|
|
626
|
+
});
|
|
627
|
+
|
|
628
|
+
if (framed) {
|
|
629
|
+
// 报到:外壳收到后回 hello。这条不带任何内容,发给谁都无所谓
|
|
630
|
+
window.parent.postMessage({ ns: NS, t: "ready", insets: safeInsets() }, "*");
|
|
631
|
+
addEventListener("pagehide", () => toHost({ t: "bye" }));
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
// ---------- 被别的服务器嵌:在新标签页里确认(地址带 ?allow-embed=外壳地址) ----------
|
|
635
|
+
|
|
636
|
+
/**
|
|
637
|
+
* 一加载就记下来、从地址里去掉:没登录的话要等登录完才处理,那时地址早被别处改过了。
|
|
638
|
+
* 要授权的外壳地址;处理过就清掉
|
|
639
|
+
*/
|
|
640
|
+
let allowEmbed = (() => {
|
|
641
|
+
const params = new URLSearchParams(location.search);
|
|
642
|
+
const raw = params.get("allow-embed");
|
|
643
|
+
if (!raw) return null;
|
|
644
|
+
params.delete("allow-embed");
|
|
645
|
+
const rest = params.toString();
|
|
646
|
+
history.replaceState(history.state, "", `${location.pathname}${rest ? `?${rest}` : ""}${location.hash}`);
|
|
647
|
+
return framed ? null : raw;
|
|
648
|
+
})();
|
|
649
|
+
|
|
650
|
+
/** 页面启动(登录)后调。不是管理员只提示;确认了就加进允许嵌入的地址,告诉打开它的外壳重新加载 */
|
|
651
|
+
export async function handleAllowEmbed(confirmDialog, toast) {
|
|
652
|
+
const raw = allowEmbed;
|
|
653
|
+
allowEmbed = null;
|
|
654
|
+
if (!raw) return;
|
|
655
|
+
let origin;
|
|
656
|
+
try {
|
|
657
|
+
origin = new URL(raw).origin;
|
|
658
|
+
} catch {
|
|
659
|
+
return;
|
|
660
|
+
}
|
|
661
|
+
if (origin === "null" || origin === location.origin) return;
|
|
662
|
+
if (!isAdmin()) {
|
|
663
|
+
toast(`${origin} 想切换到这台,要这台的管理员来授权`, 6000);
|
|
664
|
+
return;
|
|
665
|
+
}
|
|
666
|
+
let cfg;
|
|
667
|
+
try {
|
|
668
|
+
cfg = await api("/api/config");
|
|
669
|
+
} catch (err) {
|
|
670
|
+
toast(err.message);
|
|
671
|
+
return;
|
|
672
|
+
}
|
|
673
|
+
const embedders = cfg.servers?.embedders ?? [];
|
|
674
|
+
if (!embedders.includes(origin)) {
|
|
675
|
+
const ok = await confirmDialog({
|
|
676
|
+
title: "允许在别的服务器上切换到这台?",
|
|
677
|
+
message: `${origin} 的页面左上角会多出这台,切过来时这台的页面嵌在那边显示(照样要登录这台的账号,聊天内容不经过那台)。以后不想要了,在 设置 → 服务器 里移除。`,
|
|
678
|
+
confirmText: "允许",
|
|
679
|
+
});
|
|
680
|
+
if (!ok) return;
|
|
681
|
+
try {
|
|
682
|
+
await api("/api/config", { method: "PUT", body: { servers: { embedders: [...embedders, origin] } } });
|
|
683
|
+
} catch (err) {
|
|
684
|
+
toast(err.message);
|
|
685
|
+
return;
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
window.opener?.postMessage({ ns: NS, t: "embed-allowed" }, origin);
|
|
689
|
+
toast(window.opener ? "已允许,回到原来的页面就能切过来了" : `已允许,回到 ${origin} 刷新一下就能切过来了`, 6000);
|
|
690
|
+
if (window.opener) setTimeout(() => window.close(), 1500);
|
|
691
|
+
}
|