agent-loft 0.2.82 → 0.2.83

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 CHANGED
@@ -55,7 +55,7 @@ Logo 就是这个意思:一大两小几颗星(多个 agent)站在同一张
55
55
  - 输入框里的小圆环显示上下文窗口占用;模型按钮显示实际的模型和思考程度(如「Opus 5.5 high」)。
56
56
  - 滚动和 ChatGPT 一样:发出的问题顶到最上面、下面留白,回复长到屏幕底部才跟着往下滚;回复过程中自己滚动了就不再自动滚,下次发消息再恢复。
57
57
  - 定时发送:右上角「更多」→「定时发送」,默认排在 5 小时额度重置后 5 分钟(弹窗里提示 5 小时 / 7 天额度的重置时间),由服务端到点发出,关掉页面也会发。适合额度用完、要等刷新才能接着干活的时候。
58
- - 侧栏直接显示各个文件夹,Web 会话按工作目录归类(目录可以拖动排序,右键可置顶;排好的顺序跟着账号走、各设备一致,新消息不会打乱),飞书会话按机器人分组,微信会话也单独分组,两者都能展开 / 折叠并记住状态,收起时仍显示运行中和待处理提示(飞书分组右键仍可看历史会话)。渠道分组行右侧平时显示飞书或微信图标,鼠标悬停时切成加号;点击加号在 Web 开新对话,沿用该分组最近会话的专家和工作目录。项目名、渠道分组名和有分叉的会话后面有个小三角,点一下折叠 / 展开(分叉折叠后显示「N 个嵌套会话」);分叉出来的会话缩进挂在原会话下面,用一条细线连着;标题放不下时尾巴淡出;Web 和飞书会话都先用首条消息命名,再同步 agent 自动生成的标题,旧飞书会话会从历史记录补名,双击可手动重命名;鼠标移到会话上,行尾显示对应的专家图标;定时任务的时钟图标始终放在最右侧。
58
+ - 侧栏直接显示各个文件夹,Web 会话按工作目录归类(目录可以拖动排序,右键可置顶;排好的顺序跟着账号走、各设备一致,新消息不会打乱),飞书会话按机器人分组,微信的当前与历史会话按账号分组,两者都能展开 / 折叠并记住状态,收起时仍显示运行中和待处理提示(飞书分组右键仍可看历史会话)。渠道分组行右侧平时显示飞书或微信图标,鼠标悬停时切成加号;点击加号在 Web 开新对话,沿用该分组最近会话的专家和工作目录。项目名、渠道分组名和有分叉的会话后面有个小三角,点一下折叠 / 展开(分叉折叠后显示「N 个嵌套会话」);分叉出来的会话缩进挂在原会话下面,用一条细线连着;标题放不下时尾巴淡出;Web 和飞书会话都先用首条消息命名,再同步 agent 自动生成的标题,旧飞书会话会从历史记录补名,双击可手动重命名;鼠标移到会话上,行尾显示对应的专家图标;定时任务的时钟图标始终放在最右侧。
59
59
  - **搜索**:侧栏「搜索」弹窗,搜全部会话的标题、目录名和聊天内容(不开记忆也能搜),可以按专家筛;电脑和手机上弹窗都固定高度,结果在内部滚动,手机上从底部展开;↑↓ 选、回车打开。
60
60
  - **侧栏菜单**:项目上方的「更多」支持点击或鼠标悬停展开,设置入口也在这里。「编辑侧边栏」可勾选直接显示的菜单、拖动调整顺序,未勾选的收进「更多」;配置跟着账号走,电脑和手机共用。
61
61
  - 会话页顶部标题前是专家的头像,PC 端头像与会话名称字号一致(15px);鼠标停上去或点一下,看专家的说明、模型、能力和当前工作目录。
@@ -96,7 +96,7 @@ Logo 就是这个意思:一大两小几颗星(多个 agent)站在同一张
96
96
  - 桌面:走 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
97
  - 终端:新终端开在当前对话的工作目录里,可以开多个标签;`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
98
  - 管理员能用;成员要管理员在 设置 → 用户 里单独「开通远程控制」。终端、桌面在 设置 → 远程控制 里各有总开关。
99
- - **微信 ClawBot**:设置 → 账号 → 微信 →「扫码连接微信」,用手机微信扫码并确认(要求微信 8.0.70 以上,「设置 → 插件」里有 ClawBot;这个功能腾讯还在逐步放量)。每个人连自己的微信,这条对话归扫码的人,用他的记忆和工具,只认扫码的这个微信号;服务端主动连向腾讯,不需要公网地址。微信里发文字或语音(要微信能转成文字),不发过程,只显示「正在输入」,结束后发结果;授权和提问是一条文字,回复数字处理(`1` 允许一次、`0` 拒绝,含义固定),网页上也能处理。`/new`、`/stop`、`/model`、`/expert` 等命令都能用。连接后可在同一设置页的「微信使用的专家」中选择专家并点击「切换专家」,也能在首次发微信消息前选好;切换会开启新会话,和微信里的 `/expert` 共用同一份选择。
99
+ - **微信 ClawBot**:设置 → 账号 → 微信 →「扫码连接微信」,用手机微信扫码并确认(要求微信 8.0.70 以上,「设置 → 插件」里有 ClawBot;这个功能腾讯还在逐步放量)。每个人连自己的微信,会话归扫码的人,用他的记忆和工具,只认扫码的这个微信号;发送 `/new` 创建独立会话并保留旧记录,Web 微信分组里可以查看和续聊历史;服务端主动连向腾讯,不需要公网地址。微信里发文字或语音(要微信能转成文字),不发过程,只显示「正在输入」,结束后发结果;授权和提问是一条文字,回复数字处理(`1` 允许一次、`0` 拒绝,含义固定),网页上也能处理。`/new`、`/stop`、`/model`、`/expert` 等命令都能用。连接后可在同一设置页的「微信使用的专家」中选择专家并点击「切换专家」,也能在首次发微信消息前选好;已有聊天内容时,切换会创建独立会话并保留旧记录,和微信里的 `/expert` 共用同一份选择。
100
100
 
101
101
  微信的限制(官方没公布具体数字,以下来自社区实测,agent-loft 按此处理):每条入站消息之后约能发 10 条,所以长回复每次发 3 段,回「继续」接着发,额度用完时在网页上说明;约 24 小时没在微信里说话后微信会拒绝发送,定时任务的结果可能发不过去,这时改走网页提示和系统推送。接口受理了但没给 `message_id` 时手机可能没收到(微信可能在静默限制账号),设置页和对话里会提示。Web 上说的话回复留在 Web,不花微信的额度。暂不支持群聊和收发图片、文件。
102
102
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-loft",
3
- "version": "0.2.82",
3
+ "version": "0.2.83",
4
4
  "type": "module",
5
5
  "description": "多个 agent 的工作台:把本机 Claude Code / Codex 放到一处统一管理,用飞书和 Web 页面随时驱动——会话、审批、模型切换都共用",
6
6
  "keywords": [
@@ -657,7 +657,7 @@ 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
661
  const all = hub.list(visible).filter((c) => !c.hidden);
662
662
  const pending = interactions.listPending().filter((i) => visible(getConversation(i.convKey)));
663
663
  const recent = pageOf(all.filter(inRecent), null, clampLimit(url.searchParams.get("recent"), 10));
@@ -679,14 +679,20 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
679
679
  for (const page of dirPages.values()) for (const c of page.conversations) keep.set(c.key, c);
680
680
  const asking = new Set(pending.map((i) => i.convKey));
681
681
  const bots = new Set<string>();
682
+ const weixinUsers = new Set<string>();
682
683
  for (const c of all) {
683
684
  // all 已按活跃时间从新到旧:每个机器人遇到的第一条就是它最近的
684
685
  if (c.channel === "feishu" && !bots.has(c.channelId)) {
685
686
  bots.add(c.channelId);
686
687
  keep.set(c.key, c);
687
688
  }
688
- // 微信不在「最近」的分页里,但侧栏上总要有它那一行
689
- if (c.busy || asking.has(c.key) || c.channel === "weixin") keep.set(c.key, c);
689
+ if (c.channel === "weixin" && !weixinUsers.has(c.channelId)) {
690
+ weixinUsers.add(c.channelId);
691
+ keep.set(c.key, c);
692
+ const active = byKey.get(weixinKey(c.channelId));
693
+ if (active) keep.set(active.key, active);
694
+ }
695
+ if (c.busy || asking.has(c.key)) keep.set(c.key, c);
690
696
  }
691
697
  // 正开着的会话(可能是后面几页里的,重连时页面上还显示着它)
692
698
  const current = byKey.get(url.searchParams.get("current") ?? "");
@@ -837,10 +843,17 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
837
843
  }
838
844
 
839
845
  // ----- 会话 -----
840
- // 侧栏按页拉:recent / dir / bot 按树分页;bot 不传 limit 时保留历史弹窗的平铺列表。
846
+ // 侧栏按页拉:recent / dir / bot / weixin 按树分页;bot 不传 limit 时保留历史弹窗的平铺列表。
841
847
  if (p === "/api/conversations/page" && method === "GET") {
842
848
  const all = hub.list(visible).filter((c) => !c.hidden);
843
849
  const scope = url.searchParams.get("scope");
850
+ if (scope === "weixin") {
851
+ const owner = url.searchParams.get("user") ?? user.id;
852
+ const list = all.filter((c) => c.channel === "weixin" && c.channelId === owner);
853
+ const before = parseCursor(url.searchParams.get("at"), url.searchParams.get("key"));
854
+ sendJson(res, 200, pageOf(list, before, clampLimit(url.searchParams.get("limit"), 5)));
855
+ return;
856
+ }
844
857
  if (scope === "bot") {
845
858
  const bot = url.searchParams.get("bot") ?? "";
846
859
  const list = all.filter((c) => c.channel === "feishu" && c.channelId === bot);
@@ -852,7 +865,7 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
852
865
  sendJson(res, 200, page);
853
866
  return;
854
867
  }
855
- if (scope !== "recent" && scope !== "dir") throw new HttpError(400, "scope 只能是 recent / dir / bot");
868
+ if (scope !== "recent" && scope !== "dir") throw new HttpError(400, "scope 只能是 recent / dir / bot / weixin");
856
869
  const list = scope === "recent" ? all.filter(inRecent) : all.filter(inDir(url.searchParams.get("dir") ?? ""));
857
870
  const before = parseCursor(url.searchParams.get("at"), url.searchParams.get("key"));
858
871
  sendJson(res, 200, pageOf(list, before, clampLimit(url.searchParams.get("limit"), 10)));
@@ -1145,6 +1158,7 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
1145
1158
  if (sub === "action" && method === "POST") {
1146
1159
  const body = await readJsonBody<{ action?: string; value?: string; cwd?: string }>(req);
1147
1160
  const value = String(body.value ?? "");
1161
+ const previousWeixinKey = conv.channel === "weixin" ? weixinKey(conv.channelId) : undefined;
1148
1162
  let text: string;
1149
1163
  switch (body.action) {
1150
1164
  case "new":
@@ -1186,9 +1200,11 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
1186
1200
  default:
1187
1201
  throw new HttpError(400, "未知操作");
1188
1202
  }
1189
- // 飞书会话上的操作,在飞书里也说一声
1190
- if (conv.channel !== "web") hub.notice(key, `💻 Web:${text}`);
1191
- sendJson(res, 200, { text, info: hub.info(key) });
1203
+ const currentWeixinKey = previousWeixinKey ? weixinKey(conv.channelId) : undefined;
1204
+ const nextKey = currentWeixinKey && currentWeixinKey !== previousWeixinKey ? currentWeixinKey : key;
1205
+ // IM 会话上的操作,在对应渠道里也说一声。
1206
+ if (conv.channel !== "web") hub.notice(nextKey, `💻 Web:${text}`);
1207
+ sendJson(res, 200, { text, info: hub.info(nextKey) });
1192
1208
  return;
1193
1209
  }
1194
1210
  }
@@ -1,4 +1,4 @@
1
- // 一个微信绑定 = 一条长轮询 + 一条会话(weixin:<用户 id>)。
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
- readonly key: string;
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 === this.key) this.onHubEvent(env);
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 && (conv.channel === "web" || conv.channel === "feishu") && shown.text.trim()) {
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.clearFullPermission(key);
1237
- updateAgentBinding(key, conv.agent, { sessionId: undefined, forkFrom: undefined, model: model || undefined, effort: undefined });
1238
- this.emitEvent(key, { type: "meta" });
1239
- const runtime = await this.runtimeNow(key);
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.clearFullPermission(key);
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
- updateAgentBinding(key, conv.agent, { sessionId, forkFrom: undefined });
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
- updateConversation(key, { cwd: resolved, cwdExplicit: true, perAgent });
1701
- this.emitEvent(key, { type: "meta" });
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 会变,所以会话键跟着 agent-loft 用户走,不跟 bot 走。
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 const weixinKey = (userId: string): string => `weixin:${userId}`;
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 account: WeixinAccount = { ...params, boundAt: Date.now(), cursor: "", sentSinceInbound: 0 };
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);
@@ -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(S.current);
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);
@@ -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.key;
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
- // 微信每个人一条对话,也使用 IM 分组;沿用旧排序键,升级后位置不变。
633
+ // 微信按账号归组,当前及历史对话共用一个分组;排序键沿用旧版单条会话的位置。
634
+ const weixinGroups = new Map();
628
635
  for (const c of visible.filter((c) => c.channel === "weixin")) {
629
- const id = `weixin:${c.key}`;
630
- const expanded = sideState.weixinOpen.includes(c.key);
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: [c], expanded,
633
- toggle: () => toggleSide("weixinOpen", c.key),
643
+ id, channel: "weixin", name: "微信", convs, expanded,
644
+ toggle: () => toggleSide("weixinOpen", `weixin:${user}`),
634
645
  })];
635
- if (expanded) rows.push(convRow(c, " sub", `微信 · ${agentLabel(c.agent)} · ${c.cwd}`));
636
- botRows.push({ id, at: c.activeAt, rows });
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) ----