agent-loft 0.2.82 → 0.2.84
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 -2
- package/package.json +1 -1
- package/src/channels/web/api.ts +35 -10
- package/src/channels/web/assets.ts +50 -0
- package/src/channels/web/http.ts +5 -0
- package/src/channels/web/server.ts +90 -11
- package/src/channels/weixin/bot.ts +11 -4
- package/src/channels/weixin/conversation.ts +1 -2
- package/src/core/hub.ts +45 -18
- package/src/core/weixin-accounts.ts +13 -5
- package/web/index.html +6 -6
- package/web/lib/diagrams.js +5 -3
- package/web/lib/markdown.js +3 -3
- package/web/sw.js +3 -2
- package/web/views/conv-actions.js +1 -1
- package/web/views/desktop.js +1 -1
- package/web/views/file-preview.js +1 -1
- package/web/views/sidebar.js +33 -11
- package/web/views/terminal.js +3 -3
package/README.md
CHANGED
|
@@ -55,7 +55,7 @@ Logo 就是这个意思:一大两小几颗星(多个 agent)站在同一张
|
|
|
55
55
|
- 输入框里的小圆环显示上下文窗口占用;模型按钮显示实际的模型和思考程度(如「Opus 5.5 high」)。
|
|
56
56
|
- 滚动和 ChatGPT 一样:发出的问题顶到最上面、下面留白,回复长到屏幕底部才跟着往下滚;回复过程中自己滚动了就不再自动滚,下次发消息再恢复。
|
|
57
57
|
- 定时发送:右上角「更多」→「定时发送」,默认排在 5 小时额度重置后 5 分钟(弹窗里提示 5 小时 / 7 天额度的重置时间),由服务端到点发出,关掉页面也会发。适合额度用完、要等刷新才能接着干活的时候。
|
|
58
|
-
- 侧栏直接显示各个文件夹,Web
|
|
58
|
+
- 侧栏直接显示各个文件夹,Web 会话按工作目录归类(目录可以拖动排序,右键可置顶;排好的顺序跟着账号走、各设备一致,新消息不会打乱),飞书会话按机器人分组,微信的当前与历史会话按账号分组,两者都能展开 / 折叠并记住状态,收起时仍显示运行中和待处理提示(飞书分组右键仍可看历史会话)。渠道分组行右侧平时显示飞书或微信图标,鼠标悬停时切成加号;点击加号在 Web 开新对话,沿用该分组最近会话的专家和工作目录。项目名、渠道分组名和有分叉的会话后面有个小三角,点一下折叠 / 展开(分叉折叠后显示「N 个嵌套会话」);分叉出来的会话缩进挂在原会话下面,用一条细线连着;标题放不下时尾巴淡出;Web 和飞书会话都先用首条消息命名,再同步 agent 自动生成的标题,旧飞书会话会从历史记录补名,双击可手动重命名;鼠标移到会话上,行尾显示对应的专家图标;定时任务的时钟图标始终放在最右侧。
|
|
59
59
|
- **搜索**:侧栏「搜索」弹窗,搜全部会话的标题、目录名和聊天内容(不开记忆也能搜),可以按专家筛;电脑和手机上弹窗都固定高度,结果在内部滚动,手机上从底部展开;↑↓ 选、回车打开。
|
|
60
60
|
- **侧栏菜单**:项目上方的「更多」支持点击或鼠标悬停展开,设置入口也在这里。「编辑侧边栏」可勾选直接显示的菜单、拖动调整顺序,未勾选的收进「更多」;配置跟着账号走,电脑和手机共用。
|
|
61
61
|
- 会话页顶部标题前是专家的头像,PC 端头像与会话名称字号一致(15px);鼠标停上去或点一下,看专家的说明、模型、能力和当前工作目录。
|
|
@@ -70,6 +70,7 @@ Logo 就是这个意思:一大两小几颗星(多个 agent)站在同一张
|
|
|
70
70
|
- 右上角「更多」最下面显示当前会话累计消耗的 token 分布(输入 / 缓存写入 / 缓存读取 / 输出,Claude 还有按 API 价格估算的费用)。设置也在「更多」里。
|
|
71
71
|
- 设置 → 用量:按日 / 月 / 年(默认按月)统计 token 和金额,有每天(每月)的柱状图,按 agent、模型、用户(管理员才有)分开看;成员只看到自己的。管理员还可查看服务端本机直接使用的 Claude Code、Codex 桌面端和 CLI 用量,和 Agent Loft 的用量分开显示、避免重复计算。金额都是按 API 价格算的参考值:Agent Loft 的 Claude 用它自己报的费用,Codex 和直接用的 Claude Code 按模型单价 × token 估算(OpenAI 单价来自 LiteLLM 公开价格表,内置快照、联网时每天更新)。Agent Loft 的账从 0.2.34 开始记录;本机直接使用的用量可回溯已有会话记录。
|
|
72
72
|
- 「添加到主屏幕」后当 App 用;切到后台再回来会自动重连,补上错过的内容。
|
|
73
|
+
- 前端资源按指纹长缓存:再次打开不用逐个向服务端确认,升级或改了文件后刷新页面自动换新。
|
|
73
74
|
- 手机顶栏采用实色圆形按钮和「专家+更多」胶囊按钮组;从左边缘右滑展开侧栏,在侧栏或遮罩上左滑收起,短滑会回弹。消息底部操作栏与下一条消息之间留 4px。
|
|
74
75
|
- **网页多服务器切换**:在 设置 → 服务器 添加其他 agent-loft,再点「授权」到对方页面确认,侧栏左上角就能切换;各台分别登录,切走后保持连接,列表显示待处理数和运行状态,刷新后保留选择。几台需使用同一主域名下的 HTTPS 地址(例如 `mac.example.com`、`nas.example.com`)。在外层页面开启系统通知后,各台的提醒都能推到同一个主屏幕 App,点通知自动切到对应服务器和对话。见[使用指南](docs/产品介绍.md#在网页和手机上切换多台服务器)。
|
|
75
76
|
- **系统通知**:Web 会话回复完成、出错、需要授权或提问时推送到手机 / 电脑(设置 → 通知 → 「在此设备开启通知」,可以发测试通知)。飞书会话由飞书提醒,正在前台看着的会话不推。需要 HTTPS 访问,iPhone 需 iOS 16.4+ 且从主屏幕图标打开。
|
|
@@ -96,7 +97,7 @@ Logo 就是这个意思:一大两小几颗星(多个 agent)站在同一张
|
|
|
96
97
|
- 桌面:走 VNC 协议,网页里用 noVNC 显示,鼠标、键盘、剪贴板都能用,进来时不自动连、点「连接桌面」才连,工具栏上选画质:流畅 / 标准(默认)/ 高清由服务端把画面缩小到长边 1280 / 1920 / 2560、只把变了的地方压成 JPEG 发过来(macOS 屏幕共享只给无损的 ZRLE,5K 屏一整屏 30MB,原样转发隔着公网几秒一帧),原画是原样转发、只适合局域网;远程那边接了几块屏时可以只看其中一块(按系统里的显示器名称选,服务端只截那块再缩,比几块屏拼在一起缩小清楚得多;macOS 的各块屏位置要从屏幕共享发来的画面里学,第一次连上要几秒,原画下不能选);可以缩放到窗口或按原始大小看、全屏(手机上也能,iPhone 上是铺满页面)、「只看不控制」、发送 Ctrl+Alt+Del 之类的组合键。手机上有两种手势(右上角切换,「?」看说明):**触控板模式**(默认)屏幕上有个指针,单指滑动移动、轻点单击、双指轻点右键、长按后拖动是按住左键拖、双指滑动滚动;**触摸模式**点哪就点哪。两种模式都能双指捏合在本地放大画面(放大后小按钮也点得准,右下角「还原」),画面下面一排 Esc / Tab / Ctrl / Alt / Win / 方向键,Ctrl、Alt、Win 点一下会粘住,带给下一个按键或点击;键盘按钮弹出软键盘打字,中文输入法也能用。Linux 上 agent-loft 在有人连时用 x11vnc 共享当前的桌面(Xorg 会话;只听 127.0.0.1、随机端口、每次随机密码,需要 `sudo apt install x11vnc`),没人连着 30 分钟后停掉;macOS 上在 设置 → 远程控制 里改用「已有的 VNC 服务」,接系统自带的屏幕共享:填 VNC 密码,或者屏幕共享没开 VNC 密码时填 Mac 的用户名和登录密码(苹果认证,由服务端登录)。
|
|
97
98
|
- 终端:新终端开在当前对话的工作目录里,可以开多个标签;`Ctrl+Shift+C` / `Ctrl+Shift+V` 复制粘贴。`` Ctrl+` `` 在对话下面拉出终端面板(高度可拖动),面板和远程控制里的是同一批终端。关掉页面、手机切到后台、断线都不结束 shell,重新打开时接着用、补上错过的输出,别的设备上也能接上;没有页面连着超过 30 分钟(设置里可改)才结束,点标签上的 × 立即结束。依赖可选的原生模块 `node-pty`:Linux 上安装时要现场编译(需要 `make`、`g++`、`python3`),没装好时终端用不了,其他功能照常。手机上单指上下滑翻看历史(在 less、vim 里是翻页),长按选中文字、接着拖动扩大选区,再点「复制」;终端下面多一排 Esc / Tab / Ctrl / Alt / 方向键 / Home / End / PgUp / PgDn / 粘贴。iOS 上软键盘弹出来时这排键会垫到键盘上面。
|
|
98
99
|
- 管理员能用;成员要管理员在 设置 → 用户 里单独「开通远程控制」。终端、桌面在 设置 → 远程控制 里各有总开关。
|
|
99
|
-
- **微信 ClawBot**:设置 → 账号 → 微信 →「扫码连接微信」,用手机微信扫码并确认(要求微信 8.0.70 以上,「设置 → 插件」里有 ClawBot
|
|
100
|
+
- **微信 ClawBot**:设置 → 账号 → 微信 →「扫码连接微信」,用手机微信扫码并确认(要求微信 8.0.70 以上,「设置 → 插件」里有 ClawBot;这个功能腾讯还在逐步放量)。每个人连自己的微信,会话归扫码的人,用他的记忆和工具,只认扫码的这个微信号;发送 `/new` 创建独立会话并保留旧记录,Web 微信分组里可以查看和续聊历史;服务端主动连向腾讯,不需要公网地址。微信里发文字或语音(要微信能转成文字),不发过程,只显示「正在输入」,结束后发结果;授权和提问是一条文字,回复数字处理(`1` 允许一次、`0` 拒绝,含义固定),网页上也能处理。`/new`、`/stop`、`/model`、`/expert` 等命令都能用。连接后可在同一设置页的「微信使用的专家」中选择专家并点击「切换专家」,也能在首次发微信消息前选好;已有聊天内容时,切换会创建独立会话并保留旧记录,和微信里的 `/expert` 共用同一份选择。
|
|
100
101
|
|
|
101
102
|
微信的限制(官方没公布具体数字,以下来自社区实测,agent-loft 按此处理):每条入站消息之后约能发 10 条,所以长回复每次发 3 段,回「继续」接着发,额度用完时在网页上说明;约 24 小时没在微信里说话后微信会拒绝发送,定时任务的结果可能发不过去,这时改走网页提示和系统推送。接口受理了但没给 `message_id` 时手机可能没收到(微信可能在静默限制账号),设置页和对话里会提示。Web 上说的话回复留在 Web,不花微信的额度。暂不支持群聊和收发图片、文件。
|
|
102
103
|
|
package/package.json
CHANGED
package/src/channels/web/api.ts
CHANGED
|
@@ -74,7 +74,7 @@ import {
|
|
|
74
74
|
} from "./auth.js";
|
|
75
75
|
import { canSeeConv, pushOwnedBy, sessionVisibleTo } from "./access.js";
|
|
76
76
|
import { clampLimit, dirsOf, inDir, inRecent, pageOf, parseCursor, searchConvs } from "./conv-pages.js";
|
|
77
|
-
import { clientIp, cookies, HttpError, isHttps, readBody, readJsonBody, SECURITY_HEADERS, sendJson } from "./http.js";
|
|
77
|
+
import { clientIp, cookies, HttpError, isHttps, readBody, readJsonBody, SECURITY_HEADERS, sendJson, setServerTiming } from "./http.js";
|
|
78
78
|
import { handleTasksApi } from "./tasks-api.js";
|
|
79
79
|
import { handleLibraryApi } from "./library-api.js";
|
|
80
80
|
import { attachToConversation, canSeeFile, deleteConversationFiles, getLibraryFile } from "../../core/library.js";
|
|
@@ -657,7 +657,8 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
|
|
|
657
657
|
// ----- 总览 -----
|
|
658
658
|
if (p === "/api/bootstrap" && method === "GET") {
|
|
659
659
|
// 会话只给侧栏第一屏要的(见 conv-pages.ts):「最近」的前 recent 棵树、展开着的目录各自的前几棵,
|
|
660
|
-
//
|
|
660
|
+
// 每个 IM 分组最近的一条(微信另含当前会话),再加上正在跑的、等你处理的。其余展开后分页拉取。
|
|
661
|
+
const startedAt = performance.now();
|
|
661
662
|
const all = hub.list(visible).filter((c) => !c.hidden);
|
|
662
663
|
const pending = interactions.listPending().filter((i) => visible(getConversation(i.convKey)));
|
|
663
664
|
const recent = pageOf(all.filter(inRecent), null, clampLimit(url.searchParams.get("recent"), 10));
|
|
@@ -679,14 +680,20 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
|
|
|
679
680
|
for (const page of dirPages.values()) for (const c of page.conversations) keep.set(c.key, c);
|
|
680
681
|
const asking = new Set(pending.map((i) => i.convKey));
|
|
681
682
|
const bots = new Set<string>();
|
|
683
|
+
const weixinUsers = new Set<string>();
|
|
682
684
|
for (const c of all) {
|
|
683
685
|
// all 已按活跃时间从新到旧:每个机器人遇到的第一条就是它最近的
|
|
684
686
|
if (c.channel === "feishu" && !bots.has(c.channelId)) {
|
|
685
687
|
bots.add(c.channelId);
|
|
686
688
|
keep.set(c.key, c);
|
|
687
689
|
}
|
|
688
|
-
|
|
689
|
-
|
|
690
|
+
if (c.channel === "weixin" && !weixinUsers.has(c.channelId)) {
|
|
691
|
+
weixinUsers.add(c.channelId);
|
|
692
|
+
keep.set(c.key, c);
|
|
693
|
+
const active = byKey.get(weixinKey(c.channelId));
|
|
694
|
+
if (active) keep.set(active.key, active);
|
|
695
|
+
}
|
|
696
|
+
if (c.busy || asking.has(c.key)) keep.set(c.key, c);
|
|
690
697
|
}
|
|
691
698
|
// 正开着的会话(可能是后面几页里的,重连时页面上还显示着它)
|
|
692
699
|
const current = byKey.get(url.searchParams.get("current") ?? "");
|
|
@@ -696,6 +703,9 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
|
|
|
696
703
|
const parent = c.forkOf ? byKey.get(c.forkOf) : undefined;
|
|
697
704
|
if (parent) keep.set(parent.key, parent);
|
|
698
705
|
}
|
|
706
|
+
const titlesAt = performance.now();
|
|
707
|
+
const conversations = await hub.backfillFeishuTitles([...keep.values()]);
|
|
708
|
+
setServerTiming(res, { titles: performance.now() - titlesAt, total: performance.now() - startedAt });
|
|
699
709
|
sendJson(res, 200, {
|
|
700
710
|
agents: [...AGENT_IDS].map((id) => {
|
|
701
711
|
const d = hub.driver(id);
|
|
@@ -718,7 +728,7 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
|
|
|
718
728
|
workspaceRoot: config().workspaceRoot,
|
|
719
729
|
quotaRefreshMin: config().web.quotaRefreshMin,
|
|
720
730
|
quotaEnabled: config().web.quotaEnabled,
|
|
721
|
-
conversations
|
|
731
|
+
conversations,
|
|
722
732
|
sidebar: {
|
|
723
733
|
recent: { next: recent.next },
|
|
724
734
|
// 展开着的目录带上翻页游标(没带 next 的目录前端还没拉过)
|
|
@@ -837,10 +847,17 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
|
|
|
837
847
|
}
|
|
838
848
|
|
|
839
849
|
// ----- 会话 -----
|
|
840
|
-
// 侧栏按页拉:recent / dir / bot 按树分页;bot 不传 limit 时保留历史弹窗的平铺列表。
|
|
850
|
+
// 侧栏按页拉:recent / dir / bot / weixin 按树分页;bot 不传 limit 时保留历史弹窗的平铺列表。
|
|
841
851
|
if (p === "/api/conversations/page" && method === "GET") {
|
|
842
852
|
const all = hub.list(visible).filter((c) => !c.hidden);
|
|
843
853
|
const scope = url.searchParams.get("scope");
|
|
854
|
+
if (scope === "weixin") {
|
|
855
|
+
const owner = url.searchParams.get("user") ?? user.id;
|
|
856
|
+
const list = all.filter((c) => c.channel === "weixin" && c.channelId === owner);
|
|
857
|
+
const before = parseCursor(url.searchParams.get("at"), url.searchParams.get("key"));
|
|
858
|
+
sendJson(res, 200, pageOf(list, before, clampLimit(url.searchParams.get("limit"), 5)));
|
|
859
|
+
return;
|
|
860
|
+
}
|
|
844
861
|
if (scope === "bot") {
|
|
845
862
|
const bot = url.searchParams.get("bot") ?? "";
|
|
846
863
|
const list = all.filter((c) => c.channel === "feishu" && c.channelId === bot);
|
|
@@ -852,7 +869,7 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
|
|
|
852
869
|
sendJson(res, 200, page);
|
|
853
870
|
return;
|
|
854
871
|
}
|
|
855
|
-
if (scope !== "recent" && scope !== "dir") throw new HttpError(400, "scope 只能是 recent / dir / bot");
|
|
872
|
+
if (scope !== "recent" && scope !== "dir") throw new HttpError(400, "scope 只能是 recent / dir / bot / weixin");
|
|
856
873
|
const list = scope === "recent" ? all.filter(inRecent) : all.filter(inDir(url.searchParams.get("dir") ?? ""));
|
|
857
874
|
const before = parseCursor(url.searchParams.get("at"), url.searchParams.get("key"));
|
|
858
875
|
sendJson(res, 200, pageOf(list, before, clampLimit(url.searchParams.get("limit"), 10)));
|
|
@@ -999,13 +1016,17 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
|
|
|
999
1016
|
// b) 读之前和读之后是同一轮还在进行(快照里缺的部分由 live 事件补上)。
|
|
1000
1017
|
// 其余情况(读的过程中有一轮结束了、或者开始了新的一轮)都重读。
|
|
1001
1018
|
const turnStartSeq = () => hub.liveTurn(key)[0]?.seq ?? 0;
|
|
1019
|
+
const startedAt = performance.now();
|
|
1020
|
+
let readMs = 0;
|
|
1002
1021
|
let messages: Awaited<ReturnType<typeof hub.history>> = [];
|
|
1003
1022
|
let consistent = false;
|
|
1004
1023
|
for (let i = 0; i < 5 && !consistent; i++) {
|
|
1005
1024
|
if (i > 0) await new Promise((r) => setTimeout(r, 200));
|
|
1006
1025
|
const before = hub.currentSeq();
|
|
1007
1026
|
const startBefore = turnStartSeq();
|
|
1027
|
+
const readAt = performance.now();
|
|
1008
1028
|
messages = await hub.history(key);
|
|
1029
|
+
readMs += performance.now() - readAt;
|
|
1009
1030
|
const changed = (hub.eventsSince(key, before) ?? [null]).length > 0;
|
|
1010
1031
|
const startAfter = turnStartSeq();
|
|
1011
1032
|
consistent = !changed || (startBefore !== 0 && startBefore === startAfter);
|
|
@@ -1028,6 +1049,7 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
|
|
|
1028
1049
|
messages = messages.slice(0, lastUser);
|
|
1029
1050
|
}
|
|
1030
1051
|
}
|
|
1052
|
+
setServerTiming(res, { read: readMs, total: performance.now() - startedAt });
|
|
1031
1053
|
sendJson(res, 200, {
|
|
1032
1054
|
info: hub.info(key),
|
|
1033
1055
|
messages,
|
|
@@ -1145,6 +1167,7 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
|
|
|
1145
1167
|
if (sub === "action" && method === "POST") {
|
|
1146
1168
|
const body = await readJsonBody<{ action?: string; value?: string; cwd?: string }>(req);
|
|
1147
1169
|
const value = String(body.value ?? "");
|
|
1170
|
+
const previousWeixinKey = conv.channel === "weixin" ? weixinKey(conv.channelId) : undefined;
|
|
1148
1171
|
let text: string;
|
|
1149
1172
|
switch (body.action) {
|
|
1150
1173
|
case "new":
|
|
@@ -1186,9 +1209,11 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
|
|
|
1186
1209
|
default:
|
|
1187
1210
|
throw new HttpError(400, "未知操作");
|
|
1188
1211
|
}
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
1212
|
+
const currentWeixinKey = previousWeixinKey ? weixinKey(conv.channelId) : undefined;
|
|
1213
|
+
const nextKey = currentWeixinKey && currentWeixinKey !== previousWeixinKey ? currentWeixinKey : key;
|
|
1214
|
+
// IM 会话上的操作,在对应渠道里也说一声。
|
|
1215
|
+
if (conv.channel !== "web") hub.notice(nextKey, `💻 Web:${text}`);
|
|
1216
|
+
sendJson(res, 200, { text, info: hub.info(nextKey) });
|
|
1192
1217
|
return;
|
|
1193
1218
|
}
|
|
1194
1219
|
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
// 前端静态资源的版本前缀:/v/<指纹>/app.js。
|
|
2
|
+
//
|
|
3
|
+
// 没有构建步骤,文件名里没有内容哈希。以前全部 no-cache,每次打开都要把六十来个文件逐个确认一遍。
|
|
4
|
+
// 现在页面(每次都重新拿)把资源地址写成带指纹的,这些地址可以放心长缓存:
|
|
5
|
+
// - 模块之间都是相对路径 import,入口带上前缀,整棵依赖树自然都带上;
|
|
6
|
+
// - 文件一变指纹就变,刷新页面拿到的是新地址;
|
|
7
|
+
// - 指纹跟最新的不一致(升级后还开着的旧页面懒加载):照样给当前的文件,但不让长缓存。
|
|
8
|
+
// 不带前缀的老地址继续能用,还是 no-cache。
|
|
9
|
+
import { createHash } from "node:crypto";
|
|
10
|
+
import fs from "node:fs/promises";
|
|
11
|
+
import path from "node:path";
|
|
12
|
+
|
|
13
|
+
const VERSIONED = /^\/v\/([0-9a-f]{12})(\/.*)$/;
|
|
14
|
+
|
|
15
|
+
/** /v/<指纹>/xxx → 指纹和真正的路径;不是这个形式就 undefined */
|
|
16
|
+
export function parseVersioned(pathname: string): { token: string; pathname: string } | undefined {
|
|
17
|
+
const m = VERSIONED.exec(pathname);
|
|
18
|
+
return m ? { token: m[1]!, pathname: m[2]! } : undefined;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** 页面里的样式和入口脚本写成带指纹的地址。图标、manifest、sw.js 地址要稳定,不动 */
|
|
22
|
+
export function stampIndex(html: string, token: string): string {
|
|
23
|
+
return html.replace(/\b(href|src)="\/(css\/|vendor\/|app\.js)/g, `$1="/v/${token}/$2`);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
async function listFiles(dir: string): Promise<string[]> {
|
|
27
|
+
const entries = await fs.readdir(dir, { withFileTypes: true });
|
|
28
|
+
const nested = await Promise.all(
|
|
29
|
+
entries.map((e) => {
|
|
30
|
+
const full = path.join(dir, e.name);
|
|
31
|
+
return e.isDirectory() ? listFiles(full) : Promise.resolve(e.isFile() ? [full] : []);
|
|
32
|
+
}),
|
|
33
|
+
);
|
|
34
|
+
return nested.flat();
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* 指纹:程序版本 + 前端目录和 extra 里每个文件的路径、大小、修改时间。
|
|
39
|
+
* 只 stat 不读内容,打开页面时算一次也不费事;开发时改了前端文件,不重启、刷新就能拿到新的。
|
|
40
|
+
*/
|
|
41
|
+
export async function assetToken(version: string, webRoot: string, extra: string[]): Promise<string> {
|
|
42
|
+
const files = [...(await listFiles(webRoot)), ...extra].sort();
|
|
43
|
+
const stats = await Promise.all(
|
|
44
|
+
files.map(async (file) => {
|
|
45
|
+
const stat = await fs.stat(file).catch(() => null);
|
|
46
|
+
return stat ? `${file}:${stat.size}:${stat.mtimeMs}` : `${file}:-`;
|
|
47
|
+
}),
|
|
48
|
+
);
|
|
49
|
+
return createHash("sha256").update(version).update("\0").update(stats.join("\0")).digest("hex").slice(0, 12);
|
|
50
|
+
}
|
package/src/channels/web/http.ts
CHANGED
|
@@ -124,6 +124,11 @@ export function sendJson(res: ServerResponse, status: number, body: unknown): vo
|
|
|
124
124
|
);
|
|
125
125
|
}
|
|
126
126
|
|
|
127
|
+
/** 接口各段耗时(毫秒):浏览器开发者工具的 Timing 里能看到,要在 sendJson 之前调用 */
|
|
128
|
+
export function setServerTiming(res: ServerResponse, parts: Record<string, number>): void {
|
|
129
|
+
res.setHeader("Server-Timing", Object.entries(parts).map(([name, ms]) => `${name};dur=${ms.toFixed(1)}`).join(", "));
|
|
130
|
+
}
|
|
131
|
+
|
|
127
132
|
export const SECURITY_HEADERS: Record<string, string> = {
|
|
128
133
|
"X-Content-Type-Options": "nosniff",
|
|
129
134
|
"X-Frame-Options": "DENY",
|
|
@@ -25,6 +25,7 @@ import { currentUser, handleApi, takeUploads } from "./api.js";
|
|
|
25
25
|
import { authEvents, ensureSetupToken, sessionUser } from "./auth.js";
|
|
26
26
|
import { canSeeKey, sessionVisibleTo } from "./access.js";
|
|
27
27
|
import { cookies } from "./http.js";
|
|
28
|
+
import { assetToken, parseVersioned, stampIndex } from "./assets.js";
|
|
28
29
|
import { compressedFile, compressibleExt, MIN_SIZE, pickEncoding } from "./compress.js";
|
|
29
30
|
import { COOKIE } from "./api.js";
|
|
30
31
|
import { HttpError, pageHeaders, sameOrigin, SECURITY_HEADERS, sendJson } from "./http.js";
|
|
@@ -79,10 +80,11 @@ const MIME: Record<string, string> = {
|
|
|
79
80
|
};
|
|
80
81
|
|
|
81
82
|
/**
|
|
82
|
-
*
|
|
83
|
+
* 不带指纹的地址 no-cache + Last-Modified:每次都向服务端确认一下,没变就回 304。
|
|
83
84
|
* 升级后前端的 js、css 和 vendor 都会变,但地址不变,带 max-age 的话刷新页面还会拿到旧的。
|
|
85
|
+
* 带最新指纹的地址(见 assets.ts)内容不会再变,immutable:下次打开不用再问。
|
|
84
86
|
*/
|
|
85
|
-
function serveFile(req: http.IncomingMessage, res: http.ServerResponse, file: string): void {
|
|
87
|
+
function serveFile(req: http.IncomingMessage, res: http.ServerResponse, file: string, immutable = false): void {
|
|
86
88
|
fs.stat(file, (err, stat) => {
|
|
87
89
|
if (err || !stat.isFile()) {
|
|
88
90
|
res.writeHead(404, SECURITY_HEADERS);
|
|
@@ -93,10 +95,11 @@ function serveFile(req: http.IncomingMessage, res: http.ServerResponse, file: st
|
|
|
93
95
|
const since = Date.parse(req.headers["if-modified-since"] ?? "");
|
|
94
96
|
const headers = {
|
|
95
97
|
...pageHeaders(),
|
|
96
|
-
"Cache-Control": "no-cache",
|
|
98
|
+
"Cache-Control": immutable ? "max-age=31536000, immutable" : "no-cache",
|
|
97
99
|
"Last-Modified": lastModified.toUTCString(),
|
|
98
100
|
};
|
|
99
|
-
// 页面本身不回 304:它的 CSP(允许谁嵌、能嵌谁)跟着设置变,304
|
|
101
|
+
// 页面本身不回 304:它的 CSP(允许谁嵌、能嵌谁)跟着设置变,304 带回的新头浏览器不一定换上。
|
|
102
|
+
// 平时页面走 serveIndex,这里的判断留给它出错时的退路
|
|
100
103
|
if (!Number.isNaN(since) && lastModified.getTime() <= since && path.extname(file) !== ".html") {
|
|
101
104
|
res.writeHead(304, headers);
|
|
102
105
|
res.end();
|
|
@@ -131,18 +134,93 @@ function novncFile(pathname: string): string | undefined {
|
|
|
131
134
|
return path.join(pkgDir("@novnc/novnc"), rel);
|
|
132
135
|
}
|
|
133
136
|
|
|
137
|
+
/** 指纹要盖住的 vendor 文件。noVNC 是一整个目录,看它的 package.json 就够了 */
|
|
138
|
+
function vendorFiles(): string[] {
|
|
139
|
+
const files: string[] = [];
|
|
140
|
+
for (const resolve of [...Object.values(VENDOR), () => pkgFile("@novnc/novnc", "package.json")]) {
|
|
141
|
+
try {
|
|
142
|
+
files.push(resolve());
|
|
143
|
+
} catch {
|
|
144
|
+
// 没装上的包:请求它时本来就是 404
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
return files;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** 最近一次算出的指纹。每次打开页面都重算;带指纹的请求只跟它比,不用每个文件都扫一遍目录 */
|
|
151
|
+
let latestToken: Promise<string> | undefined;
|
|
152
|
+
|
|
153
|
+
function refreshToken(): Promise<string> {
|
|
154
|
+
const job = assetToken(RUNNING_VERSION, webRoot, vendorFiles());
|
|
155
|
+
latestToken = job;
|
|
156
|
+
job.catch(() => {
|
|
157
|
+
if (latestToken === job) latestToken = undefined;
|
|
158
|
+
});
|
|
159
|
+
return job;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* 页面本身:资源地址写成带指纹的。每次都重新给,不回 304(它的 CSP 跟着设置变,见 serveFile)。
|
|
164
|
+
* 指纹算失败了就退回原样的页面:地址不带指纹,慢一点但能用。
|
|
165
|
+
*/
|
|
166
|
+
function serveIndex(req: http.IncomingMessage, res: http.ServerResponse, file: string): void {
|
|
167
|
+
void (async () => {
|
|
168
|
+
const [token, stat] = await Promise.all([refreshToken(), fs.promises.stat(file)]);
|
|
169
|
+
const read = async () => Buffer.from(stampIndex(await fs.promises.readFile(file, "utf8"), token));
|
|
170
|
+
const encoding = stat.size >= MIN_SIZE ? pickEncoding(req.headers) : undefined;
|
|
171
|
+
const body = encoding ? await compressedFile(`${file}#${token}`, stat.mtimeMs, stat.size, encoding, read) : await read();
|
|
172
|
+
if (res.headersSent || res.destroyed) return;
|
|
173
|
+
res.writeHead(200, {
|
|
174
|
+
...pageHeaders(),
|
|
175
|
+
"Cache-Control": "no-cache",
|
|
176
|
+
"Content-Type": MIME[".html"]!,
|
|
177
|
+
"Content-Length": body.length,
|
|
178
|
+
Vary: "Accept-Encoding",
|
|
179
|
+
...(encoding ? { "Content-Encoding": encoding } : {}),
|
|
180
|
+
});
|
|
181
|
+
res.end(body);
|
|
182
|
+
})().catch(() => {
|
|
183
|
+
if (!res.headersSent && !res.destroyed) serveFile(req, res, file);
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
|
|
134
187
|
function serveStatic(req: http.IncomingMessage, res: http.ServerResponse, url: URL): void {
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
188
|
+
const versioned = parseVersioned(url.pathname);
|
|
189
|
+
if (versioned) {
|
|
190
|
+
// 带指纹的只给资源。没有扩展名的地址不回退到页面:这种请求不会是用户打开页面
|
|
191
|
+
if (!path.extname(versioned.pathname) || path.extname(versioned.pathname) === ".html") {
|
|
192
|
+
res.writeHead(404, SECURITY_HEADERS);
|
|
193
|
+
res.end();
|
|
194
|
+
return;
|
|
195
|
+
}
|
|
196
|
+
void (latestToken ?? refreshToken())
|
|
197
|
+
.catch(() => undefined)
|
|
198
|
+
.then((token) => {
|
|
199
|
+
try {
|
|
200
|
+
servePath(req, res, versioned.pathname, token === versioned.token);
|
|
201
|
+
} catch (err) {
|
|
202
|
+
console.error("[web] 静态文件出错:", err);
|
|
203
|
+
if (!res.headersSent) res.writeHead(500);
|
|
204
|
+
res.end();
|
|
205
|
+
}
|
|
206
|
+
});
|
|
207
|
+
return;
|
|
208
|
+
}
|
|
209
|
+
servePath(req, res, url.pathname, false);
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
function servePath(req: http.IncomingMessage, res: http.ServerResponse, pathname: string, immutable: boolean): void {
|
|
213
|
+
if (pathname.startsWith("/vendor/novnc/")) {
|
|
214
|
+
const file = novncFile(pathname);
|
|
215
|
+
if (file) return serveFile(req, res, file, immutable);
|
|
138
216
|
res.writeHead(404, SECURITY_HEADERS);
|
|
139
217
|
res.end();
|
|
140
218
|
return;
|
|
141
219
|
}
|
|
142
|
-
const vendor = VENDOR[
|
|
220
|
+
const vendor = VENDOR[pathname];
|
|
143
221
|
if (vendor) {
|
|
144
222
|
try {
|
|
145
|
-
serveFile(req, res, vendor());
|
|
223
|
+
serveFile(req, res, vendor(), immutable);
|
|
146
224
|
} catch {
|
|
147
225
|
res.writeHead(404);
|
|
148
226
|
res.end();
|
|
@@ -151,7 +229,7 @@ function serveStatic(req: http.IncomingMessage, res: http.ServerResponse, url: U
|
|
|
151
229
|
}
|
|
152
230
|
let rel: string;
|
|
153
231
|
try {
|
|
154
|
-
rel = decodeURIComponent(
|
|
232
|
+
rel = decodeURIComponent(pathname);
|
|
155
233
|
} catch {
|
|
156
234
|
res.writeHead(400, SECURITY_HEADERS);
|
|
157
235
|
res.end("bad request");
|
|
@@ -169,7 +247,8 @@ function serveStatic(req: http.IncomingMessage, res: http.ServerResponse, url: U
|
|
|
169
247
|
res.end();
|
|
170
248
|
return;
|
|
171
249
|
}
|
|
172
|
-
|
|
250
|
+
if (file === path.join(webRoot, "index.html")) return serveIndex(req, res, file);
|
|
251
|
+
serveFile(req, res, file, immutable);
|
|
173
252
|
}
|
|
174
253
|
|
|
175
254
|
// ---------- WebSocket ----------
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// 一个微信绑定 = 一条长轮询 +
|
|
1
|
+
// 一个微信绑定 = 一条长轮询 + 一条当前会话;历史会话保留在同一用户的微信分组。
|
|
2
2
|
//
|
|
3
3
|
// 和飞书的差别都来自微信的限制,别按飞书的习惯改回去:
|
|
4
4
|
// - 消息发出去不能改,所以不发过程,只显示「正在输入」,一轮结束发一次结果;
|
|
@@ -60,7 +60,8 @@ export type WeixinStatus = {
|
|
|
60
60
|
|
|
61
61
|
export class WeixinBot {
|
|
62
62
|
readonly client: IlinkClient;
|
|
63
|
-
|
|
63
|
+
get key(): string { return weixinKey(this.account.userId); }
|
|
64
|
+
private eventKey: string | undefined;
|
|
64
65
|
status: WeixinStatus = { state: "stopped", since: Date.now() };
|
|
65
66
|
private dedup = new Dedup();
|
|
66
67
|
private stop_ = new AbortController();
|
|
@@ -86,7 +87,6 @@ export class WeixinBot {
|
|
|
86
87
|
|
|
87
88
|
constructor(readonly account: WeixinAccount) {
|
|
88
89
|
this.client = new IlinkClient(account.baseUrl, account.botToken);
|
|
89
|
-
this.key = weixinKey(account.userId);
|
|
90
90
|
}
|
|
91
91
|
|
|
92
92
|
private get user(): User | undefined {
|
|
@@ -108,7 +108,14 @@ export class WeixinBot {
|
|
|
108
108
|
|
|
109
109
|
start(): void {
|
|
110
110
|
const onEvent = (env: EventEnvelope) => {
|
|
111
|
-
if (env.key
|
|
111
|
+
if (env.key !== this.key) return;
|
|
112
|
+
if (this.eventKey !== env.key) {
|
|
113
|
+
this.eventKey = env.key;
|
|
114
|
+
this.lastOrigin = undefined;
|
|
115
|
+
this.shown = undefined;
|
|
116
|
+
this.pendingChunks = [];
|
|
117
|
+
}
|
|
118
|
+
this.onHubEvent(env);
|
|
112
119
|
};
|
|
113
120
|
hub.on("event", onEvent);
|
|
114
121
|
this.offs.push(() => hub.off("event", onEvent));
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
//
|
|
1
|
+
// 设置页和微信入站共用当前会话、同一份专家选择;切换后保留旧对话。
|
|
2
2
|
import { hub } from "../../core/hub.js";
|
|
3
3
|
import { getConversation } from "../../core/store.js";
|
|
4
4
|
import { weixinKey } from "../../core/weixin-accounts.js";
|
|
@@ -23,7 +23,6 @@ export async function ensureWeixinConversation(userId: string): Promise<string[]
|
|
|
23
23
|
defaultAgent: first.engine,
|
|
24
24
|
expert: first.id,
|
|
25
25
|
owner: userId,
|
|
26
|
-
title: "微信",
|
|
27
26
|
});
|
|
28
27
|
} else if (!choices.some((e) => e.id === (existed.expert ?? existed.agent))) {
|
|
29
28
|
await hub.setExpert(key, first.id, allowed);
|
package/src/core/hub.ts
CHANGED
|
@@ -21,6 +21,7 @@ import {
|
|
|
21
21
|
getConversation,
|
|
22
22
|
isExpired,
|
|
23
23
|
listConversations,
|
|
24
|
+
putConversation,
|
|
24
25
|
recordSessionOwner,
|
|
25
26
|
touchConversation,
|
|
26
27
|
updateAgentBinding,
|
|
@@ -58,6 +59,7 @@ import { mcpEvents } from "./mcp.js";
|
|
|
58
59
|
import { isMachineCommand, sessionSkills } from "./skill-runtime.js";
|
|
59
60
|
import { skillEvents } from "./skills.js";
|
|
60
61
|
import { isSilentReply } from "./task-prompt.js";
|
|
62
|
+
import { patchWeixinAccount } from "./weixin-accounts.js";
|
|
61
63
|
|
|
62
64
|
// ---------- 事件 ----------
|
|
63
65
|
|
|
@@ -1067,7 +1069,7 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd] }>
|
|
|
1067
1069
|
// 闲置过期要按这次说话之前的活跃时间判断,所以先记下、后 touch
|
|
1068
1070
|
const lastActive = conv.activeAt;
|
|
1069
1071
|
touchConversation(key);
|
|
1070
|
-
if (!conv.title && conv.titleAuto !== false &&
|
|
1072
|
+
if (!conv.title && conv.titleAuto !== false && ["web", "feishu", "weixin"].includes(conv.channel) && shown.text.trim()) {
|
|
1071
1073
|
// 先用首条消息占位,第一轮结束后换成 agent 自己生成的短标题(syncTitle)
|
|
1072
1074
|
updateConversation(key, { title: shown.text.trim().replace(/\s+/g, " ").slice(0, 40), titleAuto: true });
|
|
1073
1075
|
this.emitEvent(key, { type: "meta" });
|
|
@@ -1229,14 +1231,33 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd] }>
|
|
|
1229
1231
|
return { ...(model ? { model } : {}), ...(effort ? { effort } : {}) };
|
|
1230
1232
|
}
|
|
1231
1233
|
|
|
1234
|
+
/** 微信的聊天入口与列表记录分开:切换上下文时新建记录,历史、附件和索引留在旧 key。 */
|
|
1235
|
+
private nextWeixinConversation(conv: Conversation, patch: Partial<Conversation> = {}): Conversation {
|
|
1236
|
+
if (conv.channel !== "weixin") return conv;
|
|
1237
|
+
const now = Math.max(Date.now(), conv.createdAt + 1);
|
|
1238
|
+
const next: Conversation = {
|
|
1239
|
+
key: `weixin:${conv.channelId}:${crypto.randomUUID()}`,
|
|
1240
|
+
channel: "weixin", channelId: conv.channelId,
|
|
1241
|
+
agent: conv.agent, expert: conv.expert, owner: conv.owner,
|
|
1242
|
+
cwd: conv.cwd, cwdExplicit: conv.cwdExplicit,
|
|
1243
|
+
...(requestedPermission(conv) === "edit" ? { permission: "edit" } : {}),
|
|
1244
|
+
perAgent: {}, createdAt: now, activeAt: now,
|
|
1245
|
+
...patch,
|
|
1246
|
+
};
|
|
1247
|
+
putConversation(next);
|
|
1248
|
+
patchWeixinAccount(conv.channelId, { conversationKey: next.key });
|
|
1249
|
+
return next;
|
|
1250
|
+
}
|
|
1251
|
+
|
|
1232
1252
|
private async newSessionNow(key: string, model: string | undefined, op: SwitchOp): Promise<string> {
|
|
1233
1253
|
const conv = getConversation(key)!;
|
|
1234
1254
|
await this.drop(key, "已开新会话");
|
|
1235
1255
|
this.markSwitched(key, op.seq);
|
|
1236
|
-
this.
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
|
|
1256
|
+
const next = this.nextWeixinConversation(conv);
|
|
1257
|
+
this.clearFullPermission(next.key);
|
|
1258
|
+
updateAgentBinding(next.key, next.agent, { sessionId: undefined, forkFrom: undefined, model: model || undefined, effort: undefined });
|
|
1259
|
+
this.emitEvent(next.key, { type: "meta" });
|
|
1260
|
+
const runtime = await this.runtimeNow(next.key);
|
|
1240
1261
|
return `已开新会话(${this.label(conv.agent)},模型 ${runtime.model ?? "默认"}${
|
|
1241
1262
|
runtime.effort ? `,思考 ${runtime.effort}` : ""
|
|
1242
1263
|
})。`;
|
|
@@ -1249,11 +1270,12 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd] }>
|
|
|
1249
1270
|
if (!current) return "当前还没有可分叉的会话。";
|
|
1250
1271
|
await this.drop(key, "已分叉会话");
|
|
1251
1272
|
this.markSwitched(key, op.seq);
|
|
1252
|
-
this.
|
|
1273
|
+
const next = this.nextWeixinConversation(conv, { forkOf: key, perAgent: { [conv.agent]: { ...binding } } });
|
|
1274
|
+
this.clearFullPermission(next.key);
|
|
1253
1275
|
// 只记下意图,下一条消息时才真正分叉(见 session() 里的 pendingFork)
|
|
1254
|
-
updateAgentBinding(key, conv.agent, { forkFrom: current });
|
|
1255
|
-
touchConversation(key);
|
|
1256
|
-
this.emitEvent(key, { type: "meta" });
|
|
1276
|
+
updateAgentBinding(next.key, conv.agent, { forkFrom: current });
|
|
1277
|
+
touchConversation(next.key);
|
|
1278
|
+
this.emitEvent(next.key, { type: "meta" });
|
|
1257
1279
|
return "已分叉,原会话保留。下一条消息起在分叉出来的新会话里继续。";
|
|
1258
1280
|
}
|
|
1259
1281
|
|
|
@@ -1265,11 +1287,12 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd] }>
|
|
|
1265
1287
|
}
|
|
1266
1288
|
await this.drop(key, "会话已切换");
|
|
1267
1289
|
this.markSwitched(key, op.seq);
|
|
1268
|
-
|
|
1290
|
+
const next = this.nextWeixinConversation(conv, { perAgent: { [conv.agent]: { ...agentBinding(conv) } } });
|
|
1291
|
+
updateAgentBinding(next.key, conv.agent, { sessionId, forkFrom: undefined });
|
|
1269
1292
|
// 显式恢复 = 用户要接着它聊:刷新活跃时间,否则下一条消息会按恢复前的闲置时间判成过期
|
|
1270
|
-
touchConversation(key);
|
|
1271
|
-
this.session(key, { resumeId: sessionId });
|
|
1272
|
-
this.emitEvent(key, { type: "meta" });
|
|
1293
|
+
touchConversation(next.key);
|
|
1294
|
+
this.session(next.key, { resumeId: sessionId });
|
|
1295
|
+
this.emitEvent(next.key, { type: "meta" });
|
|
1273
1296
|
const note =
|
|
1274
1297
|
originCwd && originCwd !== conv.cwd
|
|
1275
1298
|
? `\n\n注意:这条会话原本在 \`${originCwd}\`,恢复后会在 \`${conv.cwd}\` 里继续 —— 上下文都在,但读写范围跟着当前工作目录走。`
|
|
@@ -1535,10 +1558,13 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd] }>
|
|
|
1535
1558
|
if (expertIdOf(conv) === hit.id) return `当前已经是 ${hit.label}。`;
|
|
1536
1559
|
await this.drop(key, `已换成 ${hit.label}`);
|
|
1537
1560
|
this.markSwitched(key, op.seq);
|
|
1561
|
+
const hasHistory = Object.values(conv.perAgent).some((b) => b.sessionId || b.forkFrom)
|
|
1562
|
+
|| this.buffers.get(key)?.some(({ ev }) => ev.type === "user" || ev.type === "result");
|
|
1563
|
+
const next = hasHistory ? this.nextWeixinConversation(conv) : conv;
|
|
1538
1564
|
// 新会话:所有 agent 的旧会话都不接着用(专家换了,上下文里的人设、权限都不对了)
|
|
1539
|
-
updateConversation(key, { agent: hit.engine, expert: isBuiltin(hit.id) ? undefined : hit.id, perAgent: {} });
|
|
1540
|
-
this.clearFullPermission(key);
|
|
1541
|
-
this.emitEvent(key, { type: "meta" });
|
|
1565
|
+
updateConversation(next.key, { agent: hit.engine, expert: isBuiltin(hit.id) ? undefined : hit.id, perAgent: {} });
|
|
1566
|
+
this.clearFullPermission(next.key);
|
|
1567
|
+
this.emitEvent(next.key, { type: "meta" });
|
|
1542
1568
|
return `已换成专家「${hit.label}」,开了新会话。`;
|
|
1543
1569
|
}
|
|
1544
1570
|
|
|
@@ -1697,8 +1723,9 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd] }>
|
|
|
1697
1723
|
const perAgent = Object.fromEntries(
|
|
1698
1724
|
Object.entries(conv.perAgent).map(([a, b]) => [a, { ...b, sessionId: undefined, forkFrom: undefined }]),
|
|
1699
1725
|
);
|
|
1700
|
-
|
|
1701
|
-
|
|
1726
|
+
const next = this.nextWeixinConversation(conv);
|
|
1727
|
+
updateConversation(next.key, { cwd: resolved, cwdExplicit: true, perAgent });
|
|
1728
|
+
this.emitEvent(next.key, { type: "meta" });
|
|
1702
1729
|
return `工作目录已切换到 ${resolved},下条消息将开新会话。`;
|
|
1703
1730
|
}
|
|
1704
1731
|
|
|
@@ -3,12 +3,13 @@
|
|
|
3
3
|
// 和飞书不一样,这里没有「机器人」和「绑定码」:用户登录 Web 后自己扫码,扫码的人就是这个账号的主人,
|
|
4
4
|
// 这条微信对话也只认扫码的这个微信号(ClawBot 本身只能由账号所有者私聊使用)。
|
|
5
5
|
//
|
|
6
|
-
// 重新扫码后 iLink 的 bot id
|
|
6
|
+
// 重新扫码后 iLink 的 bot id 会变,所以当前会话指向跟着 agent-loft 用户保存,不跟 bot 走。
|
|
7
7
|
//
|
|
8
8
|
// 这个文件里有 bot token,权限 0600,也不进 config.json(配置接口要给管理员看,token 是个人的)。
|
|
9
9
|
import { EventEmitter } from "node:events";
|
|
10
10
|
import path from "node:path";
|
|
11
11
|
import { dataDir, readJson, writeJsonAtomic } from "../home.js";
|
|
12
|
+
import { listConversations } from "./store.js";
|
|
12
13
|
|
|
13
14
|
export type WeixinAccount = {
|
|
14
15
|
/** agent-loft 用户 */
|
|
@@ -26,6 +27,8 @@ export type WeixinAccount = {
|
|
|
26
27
|
lastInboundAt?: number;
|
|
27
28
|
/** 上一条入站消息之后发出去了多少条(微信限制每条入站之后能发的条数) */
|
|
28
29
|
sentSinceInbound: number;
|
|
30
|
+
/** 当前接收微信消息的对话;旧绑定未设置时沿用 weixin:<用户 id>。 */
|
|
31
|
+
conversationKey?: string;
|
|
29
32
|
};
|
|
30
33
|
|
|
31
34
|
const storePath = path.join(dataDir, "weixin-accounts.json");
|
|
@@ -44,8 +47,12 @@ function save(): void {
|
|
|
44
47
|
/** changed:绑定多了、少了或者换了凭据。游标、令牌这些运行时字段变化不发 */
|
|
45
48
|
export const weixinAccountEvents = new EventEmitter<{ changed: [] }>();
|
|
46
49
|
|
|
47
|
-
/**
|
|
48
|
-
export
|
|
50
|
+
/** 这个用户当前的微信对话。旧对话保留原 key,开新会话只更换这个指向。 */
|
|
51
|
+
export function weixinKey(userId: string): string {
|
|
52
|
+
return load()[userId]?.conversationKey
|
|
53
|
+
?? listConversations().filter((c) => c.channel === "weixin" && c.channelId === userId).sort((a, b) => b.createdAt - a.createdAt)[0]?.key
|
|
54
|
+
?? `weixin:${userId}`;
|
|
55
|
+
}
|
|
49
56
|
|
|
50
57
|
export function getWeixinAccount(userId: string): WeixinAccount | undefined {
|
|
51
58
|
return load()[userId];
|
|
@@ -64,14 +71,15 @@ export function bindWeixinAccount(params: { userId: string; botId: string; botTo
|
|
|
64
71
|
for (const [userId, account] of Object.entries(all)) {
|
|
65
72
|
if (userId !== params.userId && account.ilinkUserId === params.ilinkUserId) delete all[userId];
|
|
66
73
|
}
|
|
67
|
-
const
|
|
74
|
+
const conversationKey = all[params.userId]?.conversationKey;
|
|
75
|
+
const account: WeixinAccount = { ...params, boundAt: Date.now(), cursor: "", sentSinceInbound: 0, ...(conversationKey ? { conversationKey } : {}) };
|
|
68
76
|
all[params.userId] = account;
|
|
69
77
|
save();
|
|
70
78
|
weixinAccountEvents.emit("changed");
|
|
71
79
|
return account;
|
|
72
80
|
}
|
|
73
81
|
|
|
74
|
-
export function patchWeixinAccount(userId: string, patch: Partial<Pick<WeixinAccount, "cursor" | "contextToken" | "lastInboundAt" | "sentSinceInbound">>): void {
|
|
82
|
+
export function patchWeixinAccount(userId: string, patch: Partial<Pick<WeixinAccount, "cursor" | "contextToken" | "lastInboundAt" | "sentSinceInbound" | "conversationKey">>): void {
|
|
75
83
|
const account = load()[userId];
|
|
76
84
|
if (!account) return;
|
|
77
85
|
Object.assign(account, patch);
|
package/web/index.html
CHANGED
|
@@ -15,26 +15,26 @@
|
|
|
15
15
|
<link rel="stylesheet" href="/vendor/hljs-light.css" media="(prefers-color-scheme: light)" />
|
|
16
16
|
<link rel="stylesheet" href="/vendor/hljs-dark.css" media="(prefers-color-scheme: dark)" />
|
|
17
17
|
<!-- 顺序就是层叠顺序,不要随意调换 -->
|
|
18
|
-
<link rel="stylesheet" href="/css/base.css
|
|
18
|
+
<link rel="stylesheet" href="/css/base.css" />
|
|
19
19
|
<link rel="stylesheet" href="/css/sidebar.css" />
|
|
20
|
-
<link rel="stylesheet" href="/css/topbar.css
|
|
21
|
-
<link rel="stylesheet" href="/css/messages.css
|
|
20
|
+
<link rel="stylesheet" href="/css/topbar.css" />
|
|
21
|
+
<link rel="stylesheet" href="/css/messages.css" />
|
|
22
22
|
<link rel="stylesheet" href="/css/albums.css" />
|
|
23
23
|
<link rel="stylesheet" href="/css/loader.css" />
|
|
24
24
|
<link rel="stylesheet" href="/css/composer.css" />
|
|
25
|
-
<link rel="stylesheet" href="/css/overlay.css
|
|
25
|
+
<link rel="stylesheet" href="/css/overlay.css" />
|
|
26
26
|
<link rel="stylesheet" href="/css/search.css" />
|
|
27
27
|
<link rel="stylesheet" href="/css/settings.css" />
|
|
28
28
|
<link rel="stylesheet" href="/css/schedule.css" />
|
|
29
29
|
<link rel="stylesheet" href="/css/todos.css" />
|
|
30
|
-
<link rel="stylesheet" href="/css/tasks.css
|
|
30
|
+
<link rel="stylesheet" href="/css/tasks.css" />
|
|
31
31
|
<link rel="stylesheet" href="/css/library.css" />
|
|
32
32
|
<link rel="stylesheet" href="/css/skills.css" />
|
|
33
33
|
<link rel="stylesheet" href="/css/experts.css" />
|
|
34
34
|
<link rel="stylesheet" href="/css/terminal.css" />
|
|
35
35
|
<link rel="stylesheet" href="/css/remote.css" />
|
|
36
36
|
<link rel="stylesheet" href="/css/servers.css" />
|
|
37
|
-
<link rel="stylesheet" href="/css/mobile.css
|
|
37
|
+
<link rel="stylesheet" href="/css/mobile.css" />
|
|
38
38
|
</head>
|
|
39
39
|
<body>
|
|
40
40
|
<div id="app"><div class="boot"><span class="loft-loader xl" role="img" aria-label="加载中"><svg viewBox="96 56 320 388" aria-hidden="true"><defs><linearGradient id="boot-g" gradientUnits="userSpaceOnUse" x1="104" y1="104" x2="408" y2="408"><stop offset="0" stop-color="#3b82f6"/><stop offset="1" stop-color="#06b6d4"/></linearGradient></defs><path class="ll-shadow" d="M256 296L404 364L256 432L108 364Z" fill="url(#boot-g)"/><path class="ll-plate" d="M256 252L404 320L256 388L108 320Z" fill="url(#boot-g)"/><path class="ll-star ll-l" d="M152 186C158.46 217.54 158.46 217.54 190 224C158.46 230.46 158.46 230.46 152 262C145.54 230.46 145.54 230.46 114 224C145.54 217.54 145.54 217.54 152 186Z" fill="url(#boot-g)"/><path class="ll-star ll-c" d="M256 82C268.92 145.08 268.92 145.08 332 158C268.92 170.92 268.92 170.92 256 234C243.08 170.92 243.08 170.92 180 158C243.08 145.08 243.08 145.08 256 82Z" fill="url(#boot-g)"/><path class="ll-star ll-r" d="M360 186C366.46 217.54 366.46 217.54 398 224C366.46 230.46 366.46 230.46 360 262C353.54 230.46 353.54 230.46 322 224C353.54 217.54 353.54 217.54 360 186Z" fill="url(#boot-g)"/></svg></span></div></div>
|
package/web/lib/diagrams.js
CHANGED
|
@@ -124,7 +124,9 @@ darkQuery.addEventListener("change", () => {
|
|
|
124
124
|
});
|
|
125
125
|
|
|
126
126
|
const scripts = {};
|
|
127
|
-
|
|
127
|
+
/** vendor 脚本的地址:跟着当前模块走,页面用了带版本的地址(见服务端 assets.ts)这里也带上 */
|
|
128
|
+
function loadScript(file, name) {
|
|
129
|
+
const src = new URL(`../vendor/${file}`, import.meta.url).href;
|
|
128
130
|
return (scripts[src] ??= new Promise((resolve, reject) => {
|
|
129
131
|
const s = document.createElement("script");
|
|
130
132
|
s.src = src;
|
|
@@ -293,7 +295,7 @@ function chartOption(spec) {
|
|
|
293
295
|
}
|
|
294
296
|
|
|
295
297
|
async function drawChart(box) {
|
|
296
|
-
const echarts = await loadScript("
|
|
298
|
+
const echarts = await loadScript("echarts.js", "echarts");
|
|
297
299
|
box._chart?.dispose();
|
|
298
300
|
const chart = echarts.init(box._body, null, { renderer: "svg" });
|
|
299
301
|
box._chart = chart;
|
|
@@ -340,7 +342,7 @@ let mermaidTheme;
|
|
|
340
342
|
function drawMermaid(box) {
|
|
341
343
|
// mermaid 同一时间只能画一张(共用一个全局状态),排队
|
|
342
344
|
const job = mermaidQueue.then(async () => {
|
|
343
|
-
const mermaid = await loadScript("
|
|
345
|
+
const mermaid = await loadScript("mermaid.js", "mermaid");
|
|
344
346
|
const theme = mode() === "dark" ? "dark" : "default";
|
|
345
347
|
if (mermaidTheme !== theme) {
|
|
346
348
|
const font = getComputedStyle(document.documentElement).getPropertyValue("--font").trim();
|
package/web/lib/markdown.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import DOMPurify from "
|
|
2
|
-
import hljs from "
|
|
3
|
-
import { marked } from "
|
|
1
|
+
import DOMPurify from "../vendor/purify.js";
|
|
2
|
+
import hljs from "../vendor/hljs.js";
|
|
3
|
+
import { marked } from "../vendor/marked.js";
|
|
4
4
|
import { diagramLang, mountDiagram, unmountDiagrams } from "./diagrams.js";
|
|
5
5
|
import { h, toast } from "./dom.js";
|
|
6
6
|
|
package/web/sw.js
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
// 最小的 Service Worker
|
|
1
|
+
// 最小的 Service Worker:只管系统通知和角标。
|
|
2
2
|
// 不缓存任何东西 —— 这是一个实时操作本机的工具,离线时显示旧页面只会误导人。
|
|
3
|
+
// 也不要加空的 fetch 监听:有的浏览器会让每个请求都先经过 Service Worker,白白变慢;
|
|
4
|
+
// 从浏览器菜单「添加到主屏幕」不需要它。
|
|
3
5
|
self.addEventListener("install", () => self.skipWaiting());
|
|
4
6
|
self.addEventListener("activate", (event) => event.waitUntil(self.clients.claim()));
|
|
5
|
-
self.addEventListener("fetch", () => {});
|
|
6
7
|
|
|
7
8
|
// 服务端推来的通知(回复完成、需要授权)。iOS 要求每条推送都必须弹出通知,否则会收回推送权限
|
|
8
9
|
self.addEventListener("push", (event) => {
|
|
@@ -22,7 +22,7 @@ export async function doAction(action, value, extra = {}) {
|
|
|
22
22
|
S.convs.set(res.info.key, res.info);
|
|
23
23
|
renderTopbar();
|
|
24
24
|
toast(res.text);
|
|
25
|
-
if (["new", "fork", "resume", "agent", "cd"].includes(action)) await openConversation(
|
|
25
|
+
if (["new", "fork", "resume", "agent", "cd"].includes(action)) await openConversation(res.info.key);
|
|
26
26
|
return res;
|
|
27
27
|
} catch (err) {
|
|
28
28
|
toast(err.message);
|
package/web/views/desktop.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// agent 回复里提到的文件:路径变成能点的链接,点开在弹层里预览(图片 / PDF / 音视频 / 文本代码),其它的下载。
|
|
2
2
|
// 能不能看由服务端判断(只认回复里写过的路径、挡掉密钥之类的敏感文件,见 core/reply-files.ts)。
|
|
3
|
-
import hljs from "
|
|
3
|
+
import hljs from "../vendor/hljs.js";
|
|
4
4
|
import { h, icon, starsLoader, toast } from "../lib/dom.js";
|
|
5
5
|
import { api } from "../lib/api.js";
|
|
6
6
|
import { renderMarkdown } from "../lib/markdown.js";
|
package/web/views/sidebar.js
CHANGED
|
@@ -389,7 +389,7 @@ const MORE_STEP = 10;
|
|
|
389
389
|
// next:下一页的游标;null = 没有更多了;undefined = 这个目录还没拉过。
|
|
390
390
|
|
|
391
391
|
/** full:老版本服务端一次给了全部,不用再拉 */
|
|
392
|
-
const pages = { recent: { show: RECENT_LIMIT, next: null, loading: false }, dirs: new Map(), bots: new Map(), dirAt: new Map(), full: false };
|
|
392
|
+
const pages = { recent: { show: RECENT_LIMIT, next: null, loading: false }, dirs: new Map(), bots: new Map(), weixin: new Map(), dirAt: new Map(), full: false };
|
|
393
393
|
|
|
394
394
|
function dirState(dir) {
|
|
395
395
|
let st = pages.dirs.get(dir);
|
|
@@ -403,6 +403,12 @@ function botState(id) {
|
|
|
403
403
|
return st;
|
|
404
404
|
}
|
|
405
405
|
|
|
406
|
+
function weixinState(id) {
|
|
407
|
+
let st = pages.weixin.get(id);
|
|
408
|
+
if (!st) pages.weixin.set(id, (st = { show: PROJECT_LIMIT, next: pages.full ? null : undefined, loading: false }));
|
|
409
|
+
return st;
|
|
410
|
+
}
|
|
411
|
+
|
|
406
412
|
/** /api/bootstrap 的参数:按现在显示了多少条要(重连后整份换掉时,已经展开的不会缩回去) */
|
|
407
413
|
export function bootstrapQuery() {
|
|
408
414
|
const q = new URLSearchParams({ recent: String(pages.recent.show), open: JSON.stringify(sideState.open.map((d) => [d, dirState(d).show])) });
|
|
@@ -416,8 +422,8 @@ export function applyBootstrap(data) {
|
|
|
416
422
|
S.sidebarNav = data.sidebarNav ?? null;
|
|
417
423
|
S.convs = new Map(data.conversations.map((c) => [c.key, c]));
|
|
418
424
|
pages.full = !data.sidebar;
|
|
419
|
-
// bootstrap
|
|
420
|
-
for (const st of pages.bots.values()) {
|
|
425
|
+
// bootstrap 只带 IM 分组最近/当前的一条;展开的列表需要重新补齐。
|
|
426
|
+
for (const st of [...pages.bots.values(), ...pages.weixin.values()]) {
|
|
421
427
|
st.next = pages.full ? null : undefined;
|
|
422
428
|
st.failed = false;
|
|
423
429
|
}
|
|
@@ -549,7 +555,7 @@ export function renderSidebar() {
|
|
|
549
555
|
if ((cur?.channel === "feishu" || cur?.channel === "weixin") && cur.key !== autoOpenedFor) {
|
|
550
556
|
autoOpenedFor = cur.key;
|
|
551
557
|
const list = cur.channel === "feishu" ? sideState.botOpen : sideState.weixinOpen;
|
|
552
|
-
const id = cur.channel === "feishu" ? cur.channelId : cur.
|
|
558
|
+
const id = cur.channel === "feishu" ? cur.channelId : `weixin:${cur.channelId}`;
|
|
553
559
|
if (!list.includes(id)) {
|
|
554
560
|
list.push(id);
|
|
555
561
|
saveSideState();
|
|
@@ -624,16 +630,32 @@ export function renderSidebar() {
|
|
|
624
630
|
});
|
|
625
631
|
}
|
|
626
632
|
|
|
627
|
-
//
|
|
633
|
+
// 微信按账号归组,当前及历史对话共用一个分组;排序键沿用旧版单条会话的位置。
|
|
634
|
+
const weixinGroups = new Map();
|
|
628
635
|
for (const c of visible.filter((c) => c.channel === "weixin")) {
|
|
629
|
-
|
|
630
|
-
|
|
636
|
+
if (!weixinGroups.has(c.channelId)) weixinGroups.set(c.channelId, []);
|
|
637
|
+
weixinGroups.get(c.channelId).push(c);
|
|
638
|
+
}
|
|
639
|
+
for (const [user, convs] of weixinGroups) {
|
|
640
|
+
const id = `weixin:weixin:${user}`;
|
|
641
|
+
const expanded = sideState.weixinOpen.includes(`weixin:${user}`);
|
|
631
642
|
const rows = [imGroupRow({
|
|
632
|
-
id, channel: "weixin", name: "微信", convs
|
|
633
|
-
toggle: () => toggleSide("weixinOpen",
|
|
643
|
+
id, channel: "weixin", name: "微信", convs, expanded,
|
|
644
|
+
toggle: () => toggleSide("weixinOpen", `weixin:${user}`),
|
|
634
645
|
})];
|
|
635
|
-
if (expanded)
|
|
636
|
-
|
|
646
|
+
if (expanded) {
|
|
647
|
+
const st = weixinState(user);
|
|
648
|
+
const load = (limit) => fetchPage(st, { scope: "weixin", user, limit: String(limit) });
|
|
649
|
+
if (st.next === undefined && !st.loading && !st.failed) void load(st.show);
|
|
650
|
+
const forest = loadedPrefix(st, forkForest(convs));
|
|
651
|
+
for (const node of forest.slice(0, st.show)) {
|
|
652
|
+
rows.push(renderForkNode(node, (c, orphan, fold) => convRow(c, " sub", `微信 · ${agentLabel(c.agent)} · ${c.cwd}`, orphan, fold)));
|
|
653
|
+
}
|
|
654
|
+
if (st.failed) rows.push(h("button", { class: "conv-more", onclick: () => { void load(st.show); renderSidebar(); } }, "加载失败,点击重试"));
|
|
655
|
+
const btn = moreButton(st, forest.length, PROJECT_LIMIT, load);
|
|
656
|
+
if (btn) rows.push(h("div", { class: "sub-more" }, btn));
|
|
657
|
+
}
|
|
658
|
+
botRows.push({ id, at: convs[0].activeAt, rows });
|
|
637
659
|
}
|
|
638
660
|
|
|
639
661
|
// ---- Web 会话直接按工作目录分组,目录按用户排的顺序(见 orderSidebarGroups) ----
|
package/web/views/terminal.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { Terminal } from "
|
|
2
|
-
import { FitAddon } from "
|
|
1
|
+
import { Terminal } from "../vendor/xterm.js";
|
|
2
|
+
import { FitAddon } from "../vendor/xterm-fit.js";
|
|
3
3
|
import { fill, h, icon, isTouch, toast } from "../lib/dom.js";
|
|
4
4
|
import { api } from "../lib/api.js";
|
|
5
5
|
import { S, ui } from "../state.js";
|
|
@@ -80,7 +80,7 @@ dark.addEventListener("change", () => {
|
|
|
80
80
|
});
|
|
81
81
|
|
|
82
82
|
// xterm 的样式:第一次用到终端时才加载
|
|
83
|
-
document.head.append(h("link", { rel: "stylesheet", href: "
|
|
83
|
+
document.head.append(h("link", { rel: "stylesheet", href: new URL("../vendor/xterm.css", import.meta.url).href }));
|
|
84
84
|
|
|
85
85
|
// ---------- 面板 ----------
|
|
86
86
|
|