agent-loft 0.2.67 → 0.2.68

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
@@ -62,6 +62,7 @@ Logo 就是这个意思:一大两小几颗星(多个 agent)站在同一张
62
62
  - 太长的消息先收起,点「展开显示」看全文;对话里有至少 3 条用户消息时,右侧显示快速定位尺,电脑上鼠标移入查看消息开头、点击跳转;手机上手动滚动时显示短轨道,按住拖动可预览问题和位置,松手跳转,停止操作约 1.6 秒后隐藏。
63
63
  - 回复底部的 token 数自动按大小显示为 K、M 等单位。
64
64
  - 侧栏按页加载:每个项目目录和飞书机器人分组先显示 5 条,点「展开显示」每次再拉 10 条。
65
+ - 项目和飞书分组可混合拖拽排序,飞书可以放在项目前面或项目之间;右键(触屏长按)可置顶、上移、下移或按最近活跃重排。顺序按账号保存,刷新、换设备后保留,新消息不会改变已排好的位置。
65
66
  - 侧栏底部显示 Claude / Codex 的订阅额度(5 小时 / 7 天窗口,以及多久后重置);关了额度查询就整块不显示。
66
67
  - 右上角「更多」最下面显示当前会话累计消耗的 token 分布(输入 / 缓存写入 / 缓存读取 / 输出,Claude 还有按 API 价格估算的费用)。设置也在「更多」里。
67
68
  - 设置 → 用量:按日 / 月 / 年(默认按月)统计 token 和金额,有每天(每月)的柱状图,按 agent、模型、用户(管理员才有)分开看;成员只看到自己的。管理员还可查看服务端本机直接使用的 Claude Code、Codex 桌面端和 CLI 用量,和 Agent Loft 的用量分开显示、避免重复计算。金额都是按 API 价格算的参考值:Agent Loft 的 Claude 用它自己报的费用,Codex 和直接用的 Claude Code 按模型单价 × token 估算(OpenAI 单价来自 LiteLLM 公开价格表,内置快照、联网时每天更新)。Agent Loft 的账从 0.2.34 开始记录;本机直接使用的用量可回溯已有会话记录。
@@ -172,6 +173,7 @@ agent-loft service install
172
173
  这个服务能让 agent 在你的机器上执行命令,等于一个远程 shell。
173
174
 
174
175
  - Web 登录密码用 scrypt 哈希保存。首次建管理员必须用启动日志里的一次性设置码,防止「谁先打开页面谁就成了主人」。
176
+ - 管理员在 设置 → 用户 添加成员时,或点已有成员的「使用权限」,可以分别设置共享专家、内置 Agent、服务器切换为「全部允许(含以后新增)」或指定列表(可全部取消);旧账号沿用全部允许。共享专家和内置 Agent 分别授权,成员自己创建的专家仍可使用;收回权限后旧对话可查看,但不能继续调用,相关定时任务会暂停。服务器权限控制本机切换列表,当前服务器保持可用,各台服务器仍各自登录和管理账号。每个用户都可以在 设置 → 账号 修改自己的账号名称(也是登录名),修改不影响原有对话和登录设备。
175
177
  - 多用户只隔开**界面上**的东西:会话列表、授权 / 提问卡、通知、记忆、`/sessions` 能列出和恢复的 agent 会话;设置、飞书机器人和飞书会话只给管理员(绑定了账号的飞书私聊除外,它归绑定的人);会落盘、对所有人生效的「总是允许」(Claude 的总是允许名单、Codex 的 execpolicy)只有管理员能点。**它不是安全边界**:所有 agent 都以同一个系统用户运行,任何用户都能让 agent 读到这台机器上的文件(别人的对话记录、配置里的密钥),用的也是同一个 Claude / Codex 订阅。只给信任的人开账号;要真正隔离,就每人用自己的系统用户各跑一份 agent-loft。
176
178
  - 从老版本升级:原来的登录密码自动变成管理员 `admin`,已登录的设备不用重新登录。
177
179
  - 登录态通过 HttpOnly cookie 保存,服务端只存它的哈希。同一 IP 连续输错 5 次锁 15 分钟。所有写请求和 WebSocket 都校验 Origin。页面开启了严格的 CSP。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-loft",
3
- "version": "0.2.67",
3
+ "version": "0.2.68",
4
4
  "type": "module",
5
5
  "description": "多个 agent 的工作台:把本机 Claude Code / Codex 放到一处统一管理,用飞书和 Web 页面随时驱动——会话、审批、模型切换都共用",
6
6
  "keywords": [
@@ -499,7 +499,7 @@ function adminOnly(p: string): boolean {
499
499
  );
500
500
  }
501
501
 
502
- function publicMe(user: User) {
502
+ function publicMe(user: Pick<User, "id" | "name" | "role">) {
503
503
  return { id: user.id, name: user.name, role: user.role };
504
504
  }
505
505
 
@@ -680,6 +680,7 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
680
680
  id,
681
681
  label: d?.label ?? id,
682
682
  enabled: hub.enabledAgents().some((e) => e.id === id),
683
+ allowed: canUseExpert(user.id, id),
683
684
  capabilities: d?.capabilities ?? {},
684
685
  // 输入框模型列表里显示哪些,空 = 全部
685
686
  models: config().agents[id].models.filter((m) => typeof m === "string"),
@@ -700,20 +701,20 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
700
701
  // 展开着的目录带上翻页游标(没带 next 的目录前端还没拉过)
701
702
  dirs: dirsOf(all).map((d) => (dirPages.has(d.dir) ? { ...d, next: dirPages.get(d.dir)!.next } : d)),
702
703
  },
703
- // 「项目」目录的顺序(拖拽排的),跟着账号走;null = 还没存过
704
+ // 项目和飞书分组的混合顺序,跟着账号走;沿用目录排序字段兼容旧数据
704
705
  dirOrder: getDirOrder(user.id) ?? null,
705
706
  sidebarNav: getSidebarNav(user.id),
706
707
  pending,
707
708
  user: publicMe(user),
708
709
  remote: remoteStatus(user),
709
710
  // 左上角切换服务器:没加别的服务器是 null
710
- servers: shellInfo(config().servers),
711
+ servers: shellInfo(config().servers, user),
711
712
  serverTime: Date.now(),
712
713
  });
713
714
  return;
714
715
  }
715
716
 
716
- // ----- 侧栏「项目」目录顺序:order 整份换掉,append 只把新目录接在最后 -----
717
+ // ----- 侧栏分组顺序:order 整份换掉,append 只把新分组接在最后 -----
717
718
  if (p === "/api/ui/dir-order" && method === "PUT") {
718
719
  const body = await readJsonBody<{ order?: unknown; append?: unknown }>(req);
719
720
  const order = body.order !== undefined ? setDirOrder(user.id, body.order) : appendDirOrder(user.id, body.append);
@@ -746,7 +747,7 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
746
747
  // 多服务器(core/servers.ts):外壳把这个浏览器的订阅连同签名密钥转给嵌着的各台(web/lib/shell.js),
747
748
  // 各台直接推到手机上,不经过外壳。密钥只在加了别的服务器时给
748
749
  if (p === "/api/push/relay-key" && method === "GET") {
749
- if (!config().servers.list.length) throw new HttpError(404, "没有加别的服务器");
750
+ if (!shellInfo(config().servers, user)) throw new HttpError(404, "没有可用的其他服务器");
750
751
  sendJson(res, 200, vapidKeyPair());
751
752
  return;
752
753
  }
@@ -866,8 +867,8 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
866
867
  const body = await readJsonBody<{ expert?: string; agent?: string; cwd?: string }>(req);
867
868
  const enabled = hub.enabledAgents().map((d) => d.id);
868
869
  const wanted = body.expert ?? body.agent;
869
- if (wanted && !canUseExpert(user.id, wanted)) throw new HttpError(400, "这个专家不存在或已取消共享");
870
- const expertId = wanted || enabled[0];
870
+ if (wanted && !canUseExpert(user.id, wanted)) throw new HttpError(400, "这个专家或 Agent 不存在、已取消共享或未获授权");
871
+ const expertId = wanted || hub.expertChoices(user.id, enabled)[0]?.id;
871
872
  if (!expertId) throw new HttpError(400, "没有可用的 agent");
872
873
  const custom = isBuiltin(expertId) ? undefined : getExpert(expertId);
873
874
  const agent = custom ? custom.engine : expertId;
@@ -1379,6 +1380,15 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
1379
1380
  return;
1380
1381
  }
1381
1382
 
1383
+ // 修改自己的登录名:只允许改名称,沿用现有设备和会话归属。
1384
+ if (p === "/api/account" && method === "PATCH") {
1385
+ const body = await readJsonBody<{ name?: unknown }>(req);
1386
+ if (typeof body.name !== "string") throw new HttpError(400, "请填写账号名称");
1387
+ const updated = userOp(() => patchUser(user.id, { name: body.name as string }));
1388
+ sendJson(res, 200, { user: publicMe(updated) });
1389
+ return;
1390
+ }
1391
+
1382
1392
  // ----- 用户管理(管理员) -----
1383
1393
  if (p === "/api/users" && method === "GET") {
1384
1394
  const devices = listWebSessions();
@@ -1390,6 +1400,11 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
1390
1400
  feishuLinks: listLinks(u.id).length,
1391
1401
  })),
1392
1402
  me: user.id,
1403
+ resources: {
1404
+ experts: availableExperts(user.id).filter((e) => e.shared).map((e) => ({ id: e.id, name: e.name })),
1405
+ agents: [...AGENT_IDS].map((id) => ({ id, name: hub.label(id) })),
1406
+ servers: config().servers.list.map(({ id, name }) => ({ id, name })),
1407
+ },
1393
1408
  });
1394
1409
  return;
1395
1410
  }
@@ -1412,11 +1427,11 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
1412
1427
  }
1413
1428
  }
1414
1429
  if (p === "/api/users" && method === "POST") {
1415
- const body = await readJsonBody<{ name?: string; password?: string; role?: Role }>(req);
1430
+ const body = await readJsonBody<{ name?: string; password?: string; role?: Role; remote?: boolean; permissions?: unknown }>(req);
1416
1431
  sendJson(
1417
1432
  res,
1418
1433
  200,
1419
- userOp(() => createUser({ name: String(body.name ?? ""), password: String(body.password ?? ""), role: body.role === "admin" ? "admin" : "member" })),
1434
+ userOp(() => createUser({ name: String(body.name ?? ""), password: String(body.password ?? ""), role: body.role === "admin" ? "admin" : "member", ...(typeof body.remote === "boolean" ? { remote: body.remote } : {}), ...(body.permissions !== undefined ? { permissions: body.permissions } : {}) })),
1420
1435
  );
1421
1436
  return;
1422
1437
  }
@@ -1425,7 +1440,7 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
1425
1440
  const id = userMatch[1]!;
1426
1441
  if (!getUser(id)) throw new HttpError(404, "用户不存在");
1427
1442
  if (method === "PATCH") {
1428
- const body = await readJsonBody<{ name?: string; role?: Role; disabled?: boolean; password?: string; remote?: boolean }>(req);
1443
+ const body = await readJsonBody<{ name?: string; role?: Role; disabled?: boolean; password?: string; remote?: boolean; permissions?: unknown }>(req);
1429
1444
  if (id === user.id && (body.disabled === true || (body.role !== undefined && body.role !== "admin"))) {
1430
1445
  throw new HttpError(400, "不能停用自己,也不能取消自己的管理员");
1431
1446
  }
@@ -1437,6 +1452,7 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
1437
1452
  ...(typeof body.disabled === "boolean" ? { disabled: body.disabled } : {}),
1438
1453
  ...(typeof body.password === "string" ? { password: body.password } : {}),
1439
1454
  ...(typeof body.remote === "boolean" ? { remote: body.remote } : {}),
1455
+ ...(body.permissions !== undefined ? { permissions: body.permissions } : {}),
1440
1456
  }),
1441
1457
  );
1442
1458
  // 管理员在用户列表里重置了自己的密码:当前这台换个新登录态,别把自己踢出去
@@ -21,6 +21,8 @@ import {
21
21
  } from "../../core/experts.js";
22
22
  import { builtinAgentDefaults, setBuiltinAgentDefaults } from "../../core/builtin-agents.js";
23
23
  import { hub } from "../../core/hub.js";
24
+ import { config } from "../../core/config.js";
25
+ import { shellInfo } from "../../core/servers.js";
24
26
  import { claudeMachineMcp, createMcp, deleteMcp, getMcp, listMcp, MACHINE_PREFIX, MCP_LIMITS, mcpView, updateMcp, type McpInput } from "../../core/mcp.js";
25
27
  import { activeSkills } from "../../core/skills.js";
26
28
  import { isAdmin, type User } from "../../core/users.js";
@@ -95,7 +97,7 @@ export async function handleExpertsApi(req: IncomingMessage, res: ServerResponse
95
97
 
96
98
  if (p === "/api/agents/defaults" && method === "GET") {
97
99
  sendJson(res, 200, {
98
- agents: builtinAgentDefaults(user.id),
100
+ agents: Object.fromEntries(Object.entries(builtinAgentDefaults(user.id)).filter(([id]) => canUseExpert(user.id, id))),
99
101
  skills: activeSkills(user.id).map((s) => ({ id: s.id, name: s.name, description: s.description })),
100
102
  mcp: listMcp(user.id).map((s) => ({ id: s.id, name: s.name, description: s.description })),
101
103
  ...(await machineMcp(user).then((m) => m ? { machineMcp: m, machinePrefix: MACHINE_PREFIX } : {})),
@@ -104,8 +106,9 @@ export async function handleExpertsApi(req: IncomingMessage, res: ServerResponse
104
106
  }
105
107
  if (p === "/api/agents/defaults" && method === "PUT") {
106
108
  const body = await readJsonBody<{ agents?: unknown }>(req);
109
+ if (body.agents && typeof body.agents === "object" && Object.keys(body.agents).some((id) => !canUseExpert(user.id, id))) throw new HttpError(403, "没有使用这个内置 Agent 的权限");
107
110
  try {
108
- sendJson(res, 200, { agents: setBuiltinAgentDefaults(user.id, body.agents) });
111
+ sendJson(res, 200, { agents: Object.fromEntries(Object.entries(setBuiltinAgentDefaults(user.id, body.agents)).filter(([id]) => canUseExpert(user.id, id))) });
109
112
  } catch (err) {
110
113
  throw bad(err);
111
114
  }
@@ -116,7 +119,7 @@ export async function handleExpertsApi(req: IncomingMessage, res: ServerResponse
116
119
  const enabled = hub.enabledAgents().map((d) => d.id);
117
120
  sendJson(res, 200, {
118
121
  experts: availableExperts(user.id).map((e) => expertView(e, user.id)),
119
- builtin: enabled.map((id) => ({ id, name: hub.label(id), engine: id })),
122
+ builtin: enabled.filter((id) => canUseExpert(user.id, id)).map((id) => ({ id, name: hub.label(id), engine: id })),
120
123
  engines: enabled,
121
124
  templates: EXPERT_TEMPLATES.map((t) => ({ id: t.id, label: t.label, expert: t.expert })),
122
125
  access: ACCESS_LEVELS.map((id) => ({ id, label: ACCESS_LABEL[id] })),
@@ -129,7 +132,12 @@ export async function handleExpertsApi(req: IncomingMessage, res: ServerResponse
129
132
  }
130
133
 
131
134
  if (p === "/api/experts/brief" && method === "GET") {
132
- sendJson(res, 200, { experts: availableExperts(user.id).map(expertBrief) });
135
+ sendJson(res, 200, {
136
+ experts: availableExperts(user.id).map(expertBrief),
137
+ builtin: hub.enabledAgents().filter((d) => canUseExpert(user.id, d.id)).map((d) => d.id),
138
+ user: { id: user.id, name: user.name, role: user.role },
139
+ servers: shellInfo(config().servers, user),
140
+ });
133
141
  return true;
134
142
  }
135
143
 
@@ -14,7 +14,7 @@ import { dataDir, readJson, writeJsonAtomic } from "../home.js";
14
14
  import { resolveWorkspacePath } from "./config.js";
15
15
  import { claudeMachineMcp, getMcp, isMachineId, machineName, specOf, type McpSpec } from "./mcp.js";
16
16
  import { activeSkills, canSee, getSkill } from "./skills.js";
17
- import { getUser } from "./users.js";
17
+ import { canUseResource, getUser } from "./users.js";
18
18
 
19
19
  export type Engine = "claude" | "codex";
20
20
  export const ENGINES: readonly Engine[] = ["claude", "codex"];
@@ -196,13 +196,13 @@ export function getExpert(id: string): Expert | undefined {
196
196
 
197
197
  /** 共享只开放使用权,不转移专家、工具或会话的所有权。无身份的飞书聊天不能用。 */
198
198
  export function canUseExpert(owner: string | undefined, id: string): boolean {
199
- if (isBuiltin(id)) return true;
199
+ if (isBuiltin(id)) return !owner || canUseResource(getUser(owner), "agents", id);
200
200
  const e = getExpert(id);
201
201
  if (!e || !owner) return false;
202
202
  if (e.owner === owner) return true;
203
203
  const creator = getUser(e.owner);
204
204
  const user = getUser(owner);
205
- return e.shared === true && !!creator && !creator.disabled && !!user && !user.disabled;
205
+ return e.shared === true && !!creator && !creator.disabled && canUseResource(user, "experts", id);
206
206
  }
207
207
 
208
208
  /** 发布者沿用专家原有的工具选择;其他人未配置时不加载技能和 MCP。 */
package/src/core/hub.ts CHANGED
@@ -292,10 +292,12 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd] }>
292
292
  }
293
293
  });
294
294
  expertToolEvents.on("changed", (owner) => this.personalChanged(new Set([owner]), true));
295
- userEvents.on("changed", () => {
295
+ userEvents.on("changed", (accessChanged) => {
296
+ if (!accessChanged) return;
297
+ // 自定义专家还可能加载了权限已变更的子智能体;空闲后重新构建工具。
296
298
  for (const [key, live] of this.live) {
297
299
  const conv = getConversation(key);
298
- if (!conv?.expert || canUseExpert(memoryOwnerOf(conv), conv.expert)) continue;
300
+ if (!conv || (!conv.expert && canUseExpert(memoryOwnerOf(conv), conv.agent))) continue;
299
301
  this.staleLive.add(live.id);
300
302
  this.dropIfStale(key);
301
303
  }
@@ -419,7 +421,7 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd] }>
419
421
 
420
422
  /** 对话的专家,给顶栏和列表看 */
421
423
  expertBadge(conv: Pick<Conversation, "agent" | "expert" | "owner" | "channel">): ExpertBadge {
422
- if (!conv.expert) return { id: conv.agent, name: this.label(conv.agent), builtin: true };
424
+ if (!conv.expert) return { id: conv.agent, name: this.label(conv.agent), builtin: true, ...(!canUseExpert(memoryOwnerOf(conv), conv.agent) ? { missing: true } : {}) };
423
425
  const e = getExpert(conv.expert);
424
426
  if (!e || !canUseExpert(memoryOwnerOf(conv), e.id)) return { id: conv.expert, name: "(专家已删除或未共享)", missing: true };
425
427
  return {
@@ -456,7 +458,7 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd] }>
456
458
  */
457
459
  expertChoices(owner: string | undefined, allowedAgents: string[], allowedExperts?: string[]): { id: string; label: string; engine: string }[] {
458
460
  const usable = new Set(this.enabledAgents().map((d) => d.id).filter((a) => allowedAgents.includes(a)));
459
- const builtin = [...usable].map((a) => ({ id: a, label: this.label(a), engine: a }));
461
+ const builtin = [...usable].filter((a) => canUseExpert(owner, a)).map((a) => ({ id: a, label: this.label(a), engine: a }));
460
462
  const own = owner ? availableExperts(owner).filter((e) => usable.has(e.engine)) : [];
461
463
  return [...builtin, ...own.map((e) => ({ id: e.id, label: `${e.icon ? `${e.icon} ` : ""}${e.name}`, engine: e.engine }))].filter((e) => allowedExperts === undefined || allowedExperts.includes(e.id));
462
464
  }
@@ -665,7 +667,7 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd] }>
665
667
  // 先检查 agent 还启用着:设置里关掉了,已经打开的会话也不能再用
666
668
  const driver = this.requireDriver(conv.agent);
667
669
  // 撤回共享后,即使上一轮还在运行,也不能把新输入交给缓存着的会话。
668
- if (conv.expert && !canUseExpert(memoryOwnerOf(conv), conv.expert)) throw new Error("这条对话用的专家已经删除或取消共享了。新开一个对话,换个专家吧。");
670
+ if (!canUseExpert(memoryOwnerOf(conv), conv.expert ?? conv.agent)) throw new Error("这条对话用的专家或 Agent 已删除、取消共享或未获授权。新开一个对话,换个专家吧。");
669
671
  const existing = this.live.get(key);
670
672
  if (existing && existing.agent === conv.agent && existing.cwd === conv.cwd && !opts.resumeId) {
671
673
  return existing.session;
@@ -11,6 +11,7 @@
11
11
  import crypto from "node:crypto";
12
12
  import os from "node:os";
13
13
  import type { AppConfig } from "./config.js";
14
+ import { canUseResource, type User } from "./users.js";
14
15
 
15
16
  export type ServerEntry = AppConfig["servers"]["list"][number];
16
17
 
@@ -106,11 +107,12 @@ export function selfName(cfg: AppConfig["servers"]): string {
106
107
  }
107
108
 
108
109
  /** 页面要的:左上角的切换列表。没加别的服务器就是 null(不显示切换) */
109
- export function shellInfo(cfg: AppConfig["servers"]) {
110
- if (cfg.list.length === 0) return null;
110
+ export function shellInfo(cfg: AppConfig["servers"], user?: User) {
111
+ const list = cfg.list.filter((s) => !user || canUseResource(user, "servers", s.id));
112
+ if (list.length === 0) return null;
111
113
  return {
112
114
  self: { id: SELF_ID, name: selfName(cfg), icon: cfg.selfIcon },
113
- list: cfg.list.map(({ id, name, icon, url }) => ({ id, name, icon, url })),
115
+ list: list.map(({ id, name, icon, url }) => ({ id, name, icon, url })),
114
116
  };
115
117
  }
116
118
 
@@ -51,18 +51,18 @@ type Resolved = { key: string } | { pause: string } | { error: string };
51
51
  /** 这次该发到哪条对话;专用对话还没有(或者被删了)就新建一条 */
52
52
  function resolveConv(task: Task): Resolved {
53
53
  const missingExpert = (id: string | undefined) => !!id && !canUseExpert(task.owner, id);
54
- const deletedExpert = { pause: "任务用的专家已经删除或取消共享了,任务已暂停。编辑任务换一个专家再启用。" };
54
+ const deletedExpert = { pause: "任务用的专家已经删除、取消共享,或专家 / Agent 未获授权,任务已暂停。编辑任务换一个专家再启用。" };
55
55
  if (task.target.kind === "conv") {
56
56
  const conv = getConversation(task.target.key);
57
57
  if (!conv || conv.hidden) return { pause: "回复的那条对话已经被删除,任务已暂停。可以改成「专用对话」后再启用。" };
58
58
  if (ownerOf(conv) !== task.owner) return { pause: "回复的那条对话已经不属于你了,任务已暂停。" };
59
- if (missingExpert(conv.expert)) return deletedExpert;
59
+ if (missingExpert(conv.expert ?? conv.agent)) return deletedExpert;
60
60
  return { key: conv.key };
61
61
  }
62
62
  // 复用专用对话前也要检查,不能等到新建对话时才发现专家已删除。
63
- if (missingExpert(task.expert)) return deletedExpert;
63
+ if (missingExpert(task.expert ?? task.agent)) return deletedExpert;
64
64
  const existing = task.target.key ? getConversation(task.target.key) : undefined;
65
- if (existing && !existing.hidden && existing.taskId === task.id && ownerOf(existing) === task.owner) return missingExpert(existing.expert) ? deletedExpert : { key: existing.key };
65
+ if (existing && !existing.hidden && existing.taskId === task.id && ownerOf(existing) === task.owner) return missingExpert(existing.expert ?? existing.agent) ? deletedExpert : { key: existing.key };
66
66
 
67
67
  // 专家被删了:不能换成别的专家去跑(权限可能大得多),暂停等用户改
68
68
  const expert = task.expert ? getExpert(task.expert) : undefined;
@@ -1,5 +1,5 @@
1
1
  // 每个用户的界面偏好,跟着账号走(换手机、换浏览器、桌面端都一样)。
2
- // 侧栏菜单的显示、顺序,以及「项目」目录的顺序。
2
+ // 侧栏菜单的显示、顺序,以及项目和飞书分组的混合顺序。
3
3
  import path from "node:path";
4
4
  import { dataDir, readJson, writeJsonAtomic } from "../home.js";
5
5
 
@@ -29,7 +29,7 @@ function cleanDirs(list: unknown): string[] {
29
29
  return [...new Set(list.filter((d): d is string => typeof d === "string" && d.length > 0 && d.length < 4096))].slice(0, MAX_DIRS);
30
30
  }
31
31
 
32
- /** 目录顺序;undefined = 这个用户还没在服务端存过(前端可以把本地的迁上来) */
32
+ /** 分组顺序:项目用目录路径,飞书用 feishu:<机器人 id>。沿用旧字段,兼容已有项目排序。 */
33
33
  export function getDirOrder(userId: string): string[] | undefined {
34
34
  return load()[userId]?.dirOrder;
35
35
  }
@@ -43,7 +43,7 @@ export function setDirOrder(userId: string, order: unknown): string[] {
43
43
  return dirOrder;
44
44
  }
45
45
 
46
- /** 新出现的目录接在最后。只追加没有的,不动已有的名次 —— 别的设备同时在拖也不会被盖掉 */
46
+ /** 新分组接在最后。只追加没有的,不动已有的名次 —— 别的设备同时在拖也不会被盖掉 */
47
47
  export function appendDirOrder(userId: string, dirs: unknown): string[] {
48
48
  const all = load();
49
49
  const cur = all[userId]?.dirOrder ?? [];
package/src/core/users.ts CHANGED
@@ -16,6 +16,9 @@ import { dataDir, readJson, writeJsonAtomic } from "../home.js";
16
16
  import { config } from "./config.js";
17
17
 
18
18
  export type Role = "admin" | "member";
19
+ export type ResourceKind = "experts" | "agents" | "servers";
20
+ /** 未设置 / null = 全部(含以后新增);[] = 不允许使用。只限制成员。 */
21
+ export type ResourcePermissions = Partial<Record<ResourceKind, string[] | null>>;
19
22
 
20
23
  export type User = {
21
24
  id: string;
@@ -27,6 +30,7 @@ export type User = {
27
30
  disabled?: boolean;
28
31
  /** 成员能不能用远程控制(终端、桌面)。管理员一直能用,不看这个 */
29
32
  remote?: boolean;
33
+ permissions?: ResourcePermissions;
30
34
  };
31
35
 
32
36
  export type PublicUser = Omit<User, "passwordHash">;
@@ -34,8 +38,8 @@ export type PublicUser = Omit<User, "passwordHash">;
34
38
  type StoreShape = { users: User[] };
35
39
 
36
40
  const usersPath = path.join(dataDir, "users.json");
37
- /** 用户增删改、停用、改密码:登录态要重新校验 */
38
- export const userEvents = new EventEmitter<{ changed: [] }>();
41
+ /** 登录态总要重新校验;accessChanged 只在使用权限、角色或可用账号发生变化时为 true。 */
42
+ export const userEvents = new EventEmitter<{ changed: [accessChanged: boolean] }>();
39
43
 
40
44
  let cache: User[] | null = null;
41
45
  let loadedMtime = 0;
@@ -67,11 +71,11 @@ function load(): User[] {
67
71
  return cache;
68
72
  }
69
73
 
70
- function save(list: User[]): void {
74
+ function save(list: User[], accessChanged = true): void {
71
75
  cache = list;
72
76
  writeJsonAtomic(usersPath, { users: list });
73
77
  loadedMtime = mtimeOf(usersPath);
74
- userEvents.emit("changed");
78
+ userEvents.emit("changed", accessChanged);
75
79
  }
76
80
 
77
81
  /**
@@ -99,7 +103,7 @@ function newId(): string {
99
103
 
100
104
  function publicUser(u: User): PublicUser {
101
105
  const { passwordHash: _hidden, ...rest } = u;
102
- return { ...rest };
106
+ return structuredClone(rest);
103
107
  }
104
108
 
105
109
  // ---------- 密码 ----------
@@ -173,6 +177,23 @@ export function canUseRemote(user: Pick<User, "role" | "disabled" | "remote"> |
173
177
  return user.role === "admin" || user.remote === true;
174
178
  }
175
179
 
180
+ export function canUseResource(user: Pick<User, "role" | "disabled" | "permissions"> | undefined, kind: ResourceKind, id: string): boolean {
181
+ if (!user || user.disabled) return false;
182
+ return user.role === "admin" || user.permissions?.[kind] == null || user.permissions[kind]!.includes(id);
183
+ }
184
+
185
+ function cleanPermissions(value: unknown, current: ResourcePermissions = {}): ResourcePermissions {
186
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("使用权限格式不对");
187
+ const next = structuredClone(current);
188
+ for (const [kind, ids] of Object.entries(value)) {
189
+ if (!["experts", "agents", "servers"].includes(kind)) throw new Error("未知的使用权限");
190
+ if (ids !== null && (!Array.isArray(ids) || ids.length > 200 || ids.some((id) => typeof id !== "string" || !/^[\w-]{1,100}$/.test(id)))) throw new Error("使用权限必须是 ID 列表或 null");
191
+ if (kind === "agents" && ids?.some((id: string) => !["claude", "codex"].includes(id))) throw new Error("未知的内置 Agent");
192
+ next[kind as ResourceKind] = ids === null ? null : [...new Set(ids as string[])];
193
+ }
194
+ return next;
195
+ }
196
+
176
197
  /**
177
198
  * 升级前的登录态、推送订阅没有记是谁的:都算最早的那个管理员的(就是迁移出来的 admin)。
178
199
  */
@@ -212,7 +233,7 @@ function assertAdminLeft(list: User[]): void {
212
233
  if (!list.some((u) => u.role === "admin" && !u.disabled)) throw new Error("至少要保留一个能登录的管理员");
213
234
  }
214
235
 
215
- export function createUser(params: { name: string; password: string; role?: Role }): PublicUser {
236
+ export function createUser(params: { name: string; password: string; role?: Role; remote?: boolean; permissions?: unknown }): PublicUser {
216
237
  const list = load();
217
238
  const name = checkName(params.name);
218
239
  if (list.some((u) => u.name.toLowerCase() === name.toLowerCase())) throw new Error(`用户名「${name}」已经有人用了`);
@@ -223,6 +244,8 @@ export function createUser(params: { name: string; password: string; role?: Role
223
244
  role: params.role === "admin" ? "admin" : "member",
224
245
  passwordHash: hashPassword(params.password),
225
246
  createdAt: Date.now(),
247
+ ...(params.remote === true ? { remote: true } : {}),
248
+ ...(params.permissions !== undefined ? { permissions: cleanPermissions(params.permissions) } : {}),
226
249
  };
227
250
  save([...list, user]);
228
251
  return publicUser(user);
@@ -230,7 +253,7 @@ export function createUser(params: { name: string; password: string; role?: Role
230
253
 
231
254
  export function updateUser(
232
255
  id: string,
233
- patch: { name?: string; role?: Role; disabled?: boolean; password?: string; remote?: boolean },
256
+ patch: { name?: string; role?: Role; disabled?: boolean; password?: string; remote?: boolean; permissions?: unknown },
234
257
  ): PublicUser {
235
258
  const list = load().map((u) => ({ ...u }));
236
259
  const user = list.find((u) => u.id === id);
@@ -249,12 +272,13 @@ export function updateUser(
249
272
  if (patch.remote) user.remote = true;
250
273
  else delete user.remote;
251
274
  }
275
+ if (patch.permissions !== undefined) user.permissions = cleanPermissions(patch.permissions, user.permissions);
252
276
  if (patch.password !== undefined) {
253
277
  checkPassword(patch.password);
254
278
  user.passwordHash = hashPassword(patch.password);
255
279
  }
256
280
  assertAdminLeft(list);
257
- save(list);
281
+ save(list, patch.permissions !== undefined || patch.role !== undefined || patch.disabled !== undefined);
258
282
  return publicUser(user);
259
283
  }
260
284
 
@@ -95,6 +95,32 @@
95
95
  flex-wrap: wrap;
96
96
  }
97
97
 
98
+ /* 用户权限表单在整行下方展开,手机上也有足够的宽度。 */
99
+ .user-entry {
100
+ flex-direction: column;
101
+ align-items: stretch;
102
+ }
103
+
104
+ .user-entry-head {
105
+ display: flex;
106
+ align-items: center;
107
+ gap: 10px;
108
+ }
109
+
110
+ .user-entry-head > .row {
111
+ flex-shrink: 0;
112
+ }
113
+
114
+ .user-entry > div:empty {
115
+ display: none;
116
+ }
117
+
118
+ .user-permissions {
119
+ display: flex;
120
+ flex-direction: column;
121
+ gap: 12px;
122
+ }
123
+
98
124
  /* 用户列表:重置密码就地展开的输入框 */
99
125
  .user-reset {
100
126
  margin-top: 8px;
@@ -201,7 +201,7 @@ button.conv-group:hover {
201
201
  color: var(--fg);
202
202
  }
203
203
 
204
- /* 拖动目录排序:被拖的行变淡,落点处画一条横线 */
204
+ /* 项目 / 飞书分组拖动排序:被拖的行变淡,落点处画一条横线 */
205
205
  .proj-row.dragging {
206
206
  opacity: 0.4;
207
207
  }
@@ -183,7 +183,7 @@ function builtinDefaultsSection() {
183
183
  sync();
184
184
  return { el: h("div", { class: "field" }, h("span", {}, label), mode, list), value: () => mode.value === "inherit" ? null : inputs.filter((x) => x.input.checked).map((x) => x.id) };
185
185
  };
186
- const panels = ["claude", "codex"].map((engine) => {
186
+ const panels = ["claude", "codex"].filter((engine) => data.agents[engine]).map((engine) => {
187
187
  const label = engine === "claude" ? "Claude Code" : "Codex";
188
188
  const prefs = data.agents[engine];
189
189
  const skills = picker(`${label} 技能`, data.skills, prefs.skills, "全部已启用的个人技能(含以后新增)");
@@ -198,6 +198,7 @@ function builtinDefaultsSection() {
198
198
  fill(section, h("h4", {}, "内置 Agent 默认加载"),
199
199
  h("p", { class: "skill-note" }, "仅影响你当前账号使用的内置 Agent;自定义专家继续使用各自的配置。保存后,下次发消息生效,正在执行的任务不受影响。"),
200
200
  ...panels,
201
+ !panels.length ? h("p", { class: "muted" }, "没有获授权的内置 Agent,请联系管理员配置使用权限。") : null,
201
202
  h("small", {}, "技能和 MCP 可分别全部取消。记忆、定时任务、技能管理等系统工具仍按功能设置提供。"),
202
203
  h("div", { class: "row" }, saveButton(async () => {
203
204
  const agents = Object.fromEntries(Object.entries(choices).map(([engine, c]) => [engine, { skills: c.skills.value(), machineSkills: c.machineSkills.checked, mcp: c.mcp.value() }]));
@@ -23,11 +23,13 @@ export async function accountTab(page) {
23
23
  };
24
24
  const old = h("input", { type: "password", autocomplete: "current-password" });
25
25
  const pw = h("input", { type: "password", autocomplete: "new-password" });
26
+ const name = h("input", { value: S.user?.name ?? "", autocomplete: "username", autocapitalize: "off", spellcheck: "false", maxlength: "32" });
27
+ const currentName = h("span", {}, S.user?.name ?? "");
26
28
  const devicesBox = h("div", { class: "section" }, h("h4", {}, "已登录的设备"), h("span", { class: "spinner" }));
27
29
  page.append(
28
30
  h(
29
31
  "div",
30
- { class: "section" },
32
+ { class: "section", "data-form": "" },
31
33
  h(
32
34
  "h4",
33
35
  {},
@@ -35,7 +37,14 @@ export async function accountTab(page) {
35
37
  h("span", { class: "grow" }),
36
38
  logout,
37
39
  ),
38
- S.user ? h("div", {}, S.user.name, " ", h("span", { class: "status-tag" }, S.user.role === "admin" ? "管理员" : "成员")) : null,
40
+ S.user ? h("div", {}, currentName, " ", h("span", { class: "status-tag" }, S.user.role === "admin" ? "管理员" : "成员")) : null,
41
+ field("账号名称", name, "也是登录时使用的用户名。1~32 个字符,可用文字、数字和 _ . @ -;修改后请用新名称登录。"),
42
+ h("div", { class: "row" }, saveButton(async () => {
43
+ const data = await api("/api/account", { method: "PATCH", body: { name: name.value.trim() } });
44
+ S.user = data.user;
45
+ name.value = currentName.textContent = data.user.name;
46
+ toast("账号名称已修改");
47
+ }, "保存账号名称")),
39
48
  ),
40
49
  h(
41
50
  "div",
@@ -6,6 +6,32 @@ import { field, saveButton } from "./common.js";
6
6
  import { networkSection } from "./general.js";
7
7
  import { deviceList } from "./security.js";
8
8
 
9
+ /** null 沿用全部;指定列表可以全部取消,新增资源不会自动加入。 */
10
+ function permissionFields(resources, permissions = {}) {
11
+ const pickers = {};
12
+ const el = h("div", { class: "user-permissions" });
13
+ for (const [kind, label] of [["experts", "共享专家"], ["agents", "内置 Agent"], ["servers", "服务器切换"]]) {
14
+ const selected = permissions[kind];
15
+ const items = resources?.[kind] ?? [];
16
+ const known = new Set(items.map((item) => item.id));
17
+ const missing = (selected ?? []).filter((id) => !known.has(id)).map((id) => ({ id, name: `${id}(暂不可用)` }));
18
+ const mode = h("select", { "aria-label": `${label}范围` },
19
+ h("option", { value: "all", selected: selected == null }, "全部允许(含以后新增)"),
20
+ h("option", { value: "pick", selected: selected != null }, "仅允许勾选项(可全部取消)"));
21
+ const inputs = [...items, ...missing].map((item) => ({ id: item.id, input: h("input", { type: "checkbox", checked: selected == null || selected.includes(item.id) }), name: item.name }));
22
+ const list = h("div", { class: "check-list" }, inputs.length
23
+ ? inputs.map(({ input, name }) => h("label", { class: "check-item" }, input, h("span", {}, name)))
24
+ : h("small", {}, kind === "servers" ? "尚未添加其他服务器" : "暂无可选项"));
25
+ const sync = () => { list.hidden = mode.value !== "pick"; };
26
+ mode.onchange = sync;
27
+ sync();
28
+ pickers[kind] = () => mode.value === "all" ? null : inputs.filter((x) => x.input.checked).map((x) => x.id);
29
+ el.append(h("div", { class: "field" }, h("span", {}, label), mode, list));
30
+ }
31
+ el.append(h("small", {}, "自己创建的专家仍可使用。内置 Agent 权限只控制直接使用 Claude Code / Codex,不影响已获授权的专家。当前服务器保持可用;其他服务器仍需各自登录,由对应服务器管理账号权限。"));
32
+ return { el, value: () => Object.fromEntries(Object.entries(pickers).map(([kind, value]) => [kind, value()])) };
33
+ }
34
+
9
35
  // ---------- 用户(管理员) ----------
10
36
 
11
37
  export async function usersTab(page) {
@@ -34,6 +60,17 @@ export async function usersTab(page) {
34
60
  };
35
61
  const patch = (u, body) => api(`/api/users/${encodeURIComponent(u.id)}`, { method: "PATCH", body });
36
62
 
63
+ const permissionsRow = (u, holder) => {
64
+ const picker = permissionFields(data.resources, u.permissions);
65
+ const save = saveButton(async () => {
66
+ await patch(u, { permissions: picker.value() });
67
+ toast(`已更新「${u.name}」的使用权限`);
68
+ reload();
69
+ }, "保存使用权限");
70
+ fill(holder, h("div", { "data-form": "" }, h("h4", {}, "使用权限"), picker.el,
71
+ h("div", { class: "row" }, save, h("button", { class: "btn", onclick: () => fill(holder) }, "取消"))));
72
+ };
73
+
37
74
  /** 重置密码:就地展开一个输入框 */
38
75
  const resetRow = (u, holder) => {
39
76
  const pw = h("input", { type: "password", autocomplete: "new-password", placeholder: "新密码(至少 8 位)" });
@@ -158,7 +195,8 @@ export async function usersTab(page) {
158
195
  const extra = h("div");
159
196
  return h(
160
197
  "div",
161
- { class: "list-item" },
198
+ { class: "list-item user-entry" },
199
+ h("div", { class: "user-entry-head" },
162
200
  h(
163
201
  "div",
164
202
  { class: "grow" },
@@ -173,9 +211,11 @@ export async function usersTab(page) {
173
211
  u.role !== "admin" && u.remote ? h("span", { class: "status-tag" }, "远程控制") : null,
174
212
  ),
175
213
  h("div", { class: "s" }, `创建于 ${relTime(u.createdAt)} · ${u.devices} 台设备已登录${u.feishuLinks ? ` · 绑定了 ${u.feishuLinks} 个飞书账号` : ""}`),
176
- extra,
177
214
  ),
178
- actions(u, self, extra),
215
+ h("div", { class: "row" },
216
+ u.role !== "admin" ? h("button", { class: "btn small", onclick: () => permissionsRow(u, extra) }, "使用权限") : null,
217
+ actions(u, self, extra))),
218
+ extra,
179
219
  );
180
220
  }),
181
221
  );
@@ -183,17 +223,29 @@ export async function usersTab(page) {
183
223
  const name = h("input", { autocomplete: "off", autocapitalize: "off", spellcheck: "false", placeholder: "登录用的名字" });
184
224
  const pw = h("input", { type: "password", autocomplete: "new-password", placeholder: "至少 8 位" });
185
225
  const role = h("select", {}, h("option", { value: "member" }, "成员"), h("option", { value: "admin" }, "管理员"));
226
+ const permissions = permissionFields(data.resources);
227
+ const remote = h("input", { type: "checkbox" });
228
+ const memberOptions = h("div", { class: "user-permissions" }, permissions.el,
229
+ h("div", { class: "field" }, h("span", {}, "远程权限"), h("label", { class: "check-item" }, remote, h("span", {}, "允许使用终端和桌面"))));
230
+ role.onchange = () => { memberOptions.hidden = role.value === "admin"; };
186
231
  fill(
187
232
  addBox,
188
233
  h("h4", {}, "添加用户"),
189
234
  field("用户名", name),
190
235
  field("密码", pw, "告诉对方,让他登录后在 设置 →「账号」里自己改掉"),
191
236
  field("角色", role, "成员只能用自己的对话;管理员能改所有设置、管理用户"),
237
+ memberOptions,
192
238
  h(
193
239
  "div",
194
240
  { class: "row" },
195
241
  saveButton(async () => {
196
- await api("/api/users", { method: "POST", body: { name: name.value.trim(), password: pw.value, role: role.value } });
242
+ if (role.value === "member" && remote.checked && !(await confirmDialog({
243
+ title: `给「${name.value.trim()}」开通远程控制?`,
244
+ message: "他能以运行 agent-loft 的系统用户直接使用终端和桌面,读写服务器上的文件、安装软件、停止服务,不经过授权卡。只开给完全信任的人。",
245
+ confirmText: "开通并添加", danger: true,
246
+ }))) return false;
247
+ await api("/api/users", { method: "POST", body: { name: name.value.trim(), password: pw.value, role: role.value,
248
+ ...(role.value === "member" ? { remote: remote.checked, permissions: permissions.value() } : {}) } });
197
249
  toast(`已添加「${name.value.trim()}」`);
198
250
  // 先标成已保存再刷新,免得离开提醒
199
251
  addBox.removeAttribute("data-dirty");
@@ -2,6 +2,7 @@ import { agentIcon, h } from "../lib/dom.js";
2
2
  import { api } from "../lib/api.js";
3
3
  import { S } from "../state.js";
4
4
  import { agentLabel } from "./sidebar.js";
5
+ import { applyShellInfo } from "../lib/shell.js";
5
6
 
6
7
  // ---------- 专家:新对话、定时任务里选 ----------
7
8
  // 内置专家就是能用的 agent(Claude Code / Codex),自定义专家在「设置 → 专家」里建。
@@ -18,7 +19,7 @@ function usableEngines() {
18
19
  export function expertChoices() {
19
20
  const engines = usableEngines();
20
21
  return [
21
- ...engines.map((id) => ({ id, name: agentLabel(id), engine: id, builtin: true })),
22
+ ...engines.filter((id) => S.agents.find((a) => a.id === id)?.allowed !== false).map((id) => ({ id, name: agentLabel(id), engine: id, builtin: true })),
22
23
  ...S.experts.filter((e) => engines.includes(e.engine)),
23
24
  ];
24
25
  }
@@ -66,6 +67,9 @@ export async function reloadExperts() {
66
67
  try {
67
68
  const d = await api("/api/experts/brief");
68
69
  S.experts = d.experts ?? [];
70
+ if (Array.isArray(d.builtin)) for (const a of S.agents) a.allowed = d.builtin.includes(a.id);
71
+ if (d.user) S.user = d.user;
72
+ if ("servers" in d) applyShellInfo(d.servers);
69
73
  } catch {
70
74
  // 拉不到就先用旧的
71
75
  }
@@ -8,11 +8,12 @@ import {
8
8
  bootstrapQuery,
9
9
  closeSide,
10
10
  marquee,
11
- moveProjectDir,
12
- projDirs,
11
+ botGroupId,
12
+ moveSidebarGroup,
13
+ sidebarGroups,
13
14
  renderSidebar,
14
15
  reportDesktop,
15
- resetProjectOrder,
16
+ resetSidebarGroupOrder,
16
17
  setSideWidth,
17
18
  startMarquee,
18
19
  startSideResize,
@@ -232,23 +233,19 @@ function renderLayout() {
232
233
  lastDown = { key, at: now };
233
234
  });
234
235
  ui.convList.addEventListener("contextmenu", (e) => {
235
- // 飞书机器人那一行:右键看这个机器人的所有聊天
236
+ // 项目和飞书共用移动菜单;触屏也可以通过长按调整混合顺序。
236
237
  const bot = e.target.closest?.("[data-bot]")?.dataset.bot;
237
- if (bot) {
238
- e.preventDefault();
239
- showMenu({ x: e.clientX, y: e.clientY }, [{ label: "历史会话…", onclick: () => openBotConversations(bot) }]);
240
- return;
241
- }
242
- // 项目目录那一行:调整顺序(触屏上拖不动,靠这个菜单)
243
238
  const dir = e.target.closest?.("[data-dir]")?.dataset.dir;
244
- if (dir) {
245
- const i = projDirs.indexOf(dir);
239
+ const group = bot ? botGroupId(bot) : dir;
240
+ if (group) {
241
+ const i = sidebarGroups.indexOf(group);
246
242
  const moves = [
247
- ...(i > 0 ? [{ label: "置顶", onclick: () => moveProjectDir(dir, null) }, { label: "上移", onclick: () => moveProjectDir(dir, projDirs[i - 1]) }] : []),
248
- ...(i >= 0 && i < projDirs.length - 1 ? [{ label: "下移", onclick: () => moveProjectDir(dir, projDirs[i + 1], true) }] : []),
243
+ ...(i > 0 ? [{ label: "置顶", onclick: () => moveSidebarGroup(group, null) }, { label: "上移", onclick: () => moveSidebarGroup(group, sidebarGroups[i - 1]) }] : []),
244
+ ...(i >= 0 && i < sidebarGroups.length - 1 ? [{ label: "下移", onclick: () => moveSidebarGroup(group, sidebarGroups[i + 1], true) }] : []),
249
245
  ];
250
- const reset = projDirs.length > 1 ? [{ label: "按最近活跃重排", onclick: resetProjectOrder }] : [];
246
+ const reset = sidebarGroups.length > 1 ? [{ label: "按最近活跃重排", onclick: resetSidebarGroupOrder }] : [];
251
247
  const items = moves.length && reset.length ? [...moves, "sep", ...reset] : [...moves, ...reset];
248
+ if (bot) items.push(...(items.length ? ["sep"] : []), { label: "历史会话…", onclick: () => openBotConversations(bot) });
252
249
  if (!items.length) return;
253
250
  e.preventDefault();
254
251
  showMenu({ x: e.clientX, y: e.clientY }, items);
@@ -240,15 +240,15 @@ function agentShort(id) {
240
240
  return id === "claude" ? "Claude" : id === "codex" ? "Codex" : id;
241
241
  }
242
242
 
243
- /** 侧栏状态:展开的项目和机器人、折叠的分组和分叉、目录顺序(more 是老版本的,不再用) */
243
+ /** 侧栏状态:order 混排目录路径和 feishu:<机器人 id>,兼容原有的目录顺序。 */
244
244
  export const sideState = { open: [], botOpen: [], more: [], folded: [], forkFolded: [], order: [], ...JSON.parse(localStorage.getItem("aim.side") || "{}") };
245
245
 
246
246
  /**
247
- * 「项目」目录的顺序固定按 sideState.order,新消息不会把目录顶到前面。
248
- * 顺序存在服务端、跟着账号走(换设备也一样);新出现的目录接在最后(几个一起出现时按活跃排),
247
+ * 项目和飞书分组共用 sideState.order,新消息不会改变分组位置。
248
+ * 顺序存在服务端、跟着账号走(换设备也一样);新出现的分组接在最后,
249
249
  * 接上之后名次也就定了
250
250
  */
251
- function orderProjectDirs(dirs) {
251
+ function orderSidebarGroups(dirs) {
252
252
  const rank = new Map(sideState.order.map((d, i) => [d, i]));
253
253
  const ranked = dirs.filter((d) => rank.has(d)).sort((a, b) => rank.get(a) - rank.get(b));
254
254
  const fresh = dirs.filter((d) => !rank.has(d));
@@ -277,42 +277,95 @@ async function putDirOrder(body) {
277
277
  scheduleSidebar();
278
278
  }
279
279
  } catch (err) {
280
- toast(`保存目录顺序失败:${err.message}`);
280
+ toast(`保存侧栏顺序失败:${err.message}`);
281
281
  }
282
282
  }
283
283
 
284
- /** 当前侧栏里显示的目录顺序(renderSidebar 时记下,拖拽 / 右键菜单用) */
285
- export let projDirs = [];
286
- /** 同一批目录按最近活跃的顺序(「按最近活跃重排」用) */
287
- let projDirsByActivity = [];
284
+ /** 飞书的排序键与绝对目录路径分开,改机器人名称不会影响位置。 */
285
+ export const botGroupId = (id) => `feishu:${id}`;
288
286
 
289
- /** 把目录 dir 挪到 target 前面(after 为 true 时挪到后面);target 为 null 表示挪到最前 */
290
- export function moveProjectDir(dir, target, after = false) {
287
+ /** 当前侧栏里显示的混合顺序(拖拽 / 右键菜单用) */
288
+ export let sidebarGroups = [];
289
+ /** 同一批分组按最近活跃的顺序(「按最近活跃重排」用) */
290
+ let groupsByActivity = [];
291
+
292
+ /** 移到另一个分组前 / 后;target 为 null 时置顶。隐藏的分组仍保留在已存顺序中。 */
293
+ export function moveSidebarGroup(dir, target, after = false) {
291
294
  if (dir === target) return;
292
- const list = projDirs.filter((d) => d !== dir);
295
+ const list = sidebarGroups.filter((d) => d !== dir);
293
296
  const idx = target === null ? 0 : list.indexOf(target);
294
297
  if (idx < 0) return;
295
298
  list.splice(idx + (after ? 1 : 0), 0, dir);
296
299
  // 暂时没显示出来的目录(会话都被隐藏了之类)保留原来的名次,排在后面
297
- setProjectOrder([...list, ...sideState.order.filter((d) => !list.includes(d))]);
300
+ setSidebarGroupOrder([...list, ...sideState.order.filter((d) => !list.includes(d))]);
298
301
  }
299
302
 
300
303
  /** 按最近活跃重排一次,之后照样固定 */
301
- export function resetProjectOrder() {
302
- setProjectOrder([...projDirsByActivity, ...sideState.order.filter((d) => !projDirsByActivity.includes(d))]);
304
+ export function resetSidebarGroupOrder() {
305
+ setSidebarGroupOrder([...groupsByActivity, ...sideState.order.filter((d) => !groupsByActivity.includes(d))]);
303
306
  }
304
307
 
305
- function setProjectOrder(order) {
308
+ function setSidebarGroupOrder(order) {
306
309
  sideState.order = order;
307
310
  saveSideState();
308
311
  if (orderSynced) void putDirOrder({ order });
309
312
  renderSidebar();
310
313
  }
311
314
 
312
- /** 正在拖的目录。拖的过程中侧栏不重绘(重绘会换掉被拖的元素,拖拽就断了),松手后补一次 */
313
- let dirDrag = null;
315
+ /** 拖动过程中暂停重绘,防止被拖的元素被替换;结束后补上更新。 */
316
+ let groupDrag = null;
314
317
  let sidebarStale = false;
315
318
 
319
+ function groupDragAttrs(id) {
320
+ const clearDrop = () => ui.convList.querySelectorAll(".drop-before, .drop-after").forEach((el) => el.classList.remove("drop-before", "drop-after"));
321
+ const isAfter = (e) => {
322
+ const r = e.currentTarget.getBoundingClientRect();
323
+ return e.clientY > r.top + r.height / 2;
324
+ };
325
+ const endDrag = () => {
326
+ groupDrag = null;
327
+ clearDrop();
328
+ if (sidebarStale) renderSidebar();
329
+ };
330
+ return {
331
+ draggable: "true",
332
+ ondragstart: (e) => {
333
+ groupDrag = id;
334
+ e.dataTransfer.effectAllowed = "move";
335
+ e.dataTransfer.setData("text/plain", id);
336
+ e.currentTarget.classList.add("dragging");
337
+ stopMarquee();
338
+ },
339
+ ondragend: (e) => {
340
+ e.currentTarget.classList.remove("dragging");
341
+ endDrag();
342
+ },
343
+ ondragover: (e) => {
344
+ if (!groupDrag) return;
345
+ e.preventDefault();
346
+ e.dataTransfer.dropEffect = "move";
347
+ const after = isAfter(e);
348
+ if (!e.currentTarget.classList.contains(after ? "drop-after" : "drop-before")) {
349
+ clearDrop();
350
+ if (groupDrag !== id) e.currentTarget.classList.add(after ? "drop-after" : "drop-before");
351
+ }
352
+ },
353
+ ondragleave: (e) => {
354
+ if (!e.currentTarget.contains(e.relatedTarget)) e.currentTarget.classList.remove("drop-before", "drop-after");
355
+ },
356
+ ondrop: (e) => {
357
+ if (!groupDrag) return;
358
+ e.preventDefault();
359
+ const from = groupDrag;
360
+ const after = isAfter(e);
361
+ groupDrag = null;
362
+ clearDrop();
363
+ if (from !== id) moveSidebarGroup(from, id, after);
364
+ else if (sidebarStale) renderSidebar();
365
+ },
366
+ };
367
+ }
368
+
316
369
  function toggleSide(list, id) {
317
370
  const set = new Set(sideState[list]);
318
371
  set.has(id) ? set.delete(id) : set.add(id);
@@ -450,7 +503,7 @@ export function reportDesktop() {
450
503
 
451
504
  export function renderSidebar() {
452
505
  if (!ui.convList) return;
453
- if (dirDrag) {
506
+ if (groupDrag) {
454
507
  sidebarStale = true;
455
508
  return;
456
509
  }
@@ -490,8 +543,7 @@ export function renderSidebar() {
490
543
  c.taskId ? h("span", { class: "brand-icon task-mark", title: "定时任务的对话", html: ICON.clock }) : null,
491
544
  );
492
545
 
493
- const nodes = [];
494
- // 飞书机器人和项目一样展开会话,独立显示在文件夹后面。
546
+ // 飞书和项目共用排序,展开后的会话跟随所属分组。
495
547
  if (cur?.channel === "feishu" && cur.key !== autoOpenedFor) {
496
548
  autoOpenedFor = cur.key;
497
549
  if (!sideState.botOpen.includes(cur.channelId)) {
@@ -507,12 +559,12 @@ export function renderSidebar() {
507
559
  const expanded = sideState.botOpen.includes(bot.id);
508
560
  const rows = [h(
509
561
  "div",
510
- { class: "proj-row bot-row", "data-bot": bot.id },
562
+ { class: "proj-row bot-row", "data-bot": bot.id, ...groupDragAttrs(botGroupId(bot.id)) },
511
563
  h(
512
564
  "button",
513
565
  {
514
566
  class: "conv-item proj",
515
- title: `飞书 · ${bot.name}`,
567
+ title: `飞书 · ${bot.name}\n拖动可调整顺序,右键更多操作`,
516
568
  "aria-expanded": String(expanded),
517
569
  onclick: () => toggleSide("botOpen", bot.id),
518
570
  },
@@ -553,12 +605,13 @@ export function renderSidebar() {
553
605
  if (btn) rows.push(h("div", { class: "sub-more" }, btn));
554
606
  }
555
607
  botRows.push({
608
+ id: botGroupId(bot.id),
556
609
  at: latest?.activeAt ?? 0,
557
610
  rows,
558
611
  });
559
612
  }
560
613
 
561
- // ---- Web 会话直接按工作目录分组,目录按用户排的顺序(见 orderProjectDirs) ----
614
+ // ---- Web 会话直接按工作目录分组,目录按用户排的顺序(见 orderSidebarGroups) ----
562
615
  const byDir = new Map();
563
616
  for (const c of visible.filter((c) => c.channel === "web")) {
564
617
  if (!byDir.has(c.cwd)) byDir.set(c.cwd, []);
@@ -575,65 +628,21 @@ export function renderSidebar() {
575
628
  // 目录行要全部显示:服务端给了每个目录最近的活跃时间,加上本地已有的(刚建的、刚变活跃的)
576
629
  const dirAt = new Map(pages.dirAt);
577
630
  for (const [dir, convs] of byDir) dirAt.set(dir, Math.max(dirAt.get(dir) ?? 0, convs[0].activeAt));
578
- projDirsByActivity = [...dirAt.keys()].sort((a, b) => dirAt.get(b) - dirAt.get(a));
579
- projDirs = orderProjectDirs(projDirsByActivity);
631
+ const dirsByActivity = [...dirAt.keys()].sort((a, b) => dirAt.get(b) - dirAt.get(a));
632
+ const groupRows = new Map(botRows.map((group) => [group.id, group.rows]));
633
+ const groupAt = new Map([...dirAt, ...botRows.map((group) => [group.id, group.at])]);
634
+ groupsByActivity = [...groupAt.keys()].sort((a, b) => groupAt.get(b) - groupAt.get(a));
635
+ sidebarGroups = orderSidebarGroups([...dirsByActivity, ...botRows.sort((a, b) => b.at - a.at).map((group) => group.id)]);
580
636
  if (dirAt.size) {
581
- const clearDrop = () => ui.convList.querySelectorAll(".drop-before, .drop-after").forEach((el) => el.classList.remove("drop-before", "drop-after"));
582
- const endDrag = () => {
583
- dirDrag = null;
584
- clearDrop();
585
- if (sidebarStale) renderSidebar();
586
- };
587
- for (const dir of projDirs) {
637
+ for (const dir of dirsByActivity) {
588
638
  const convs = byDir.get(dir) ?? [];
589
639
  const expanded = sideState.open.includes(dir);
590
- // 鼠标在目标行的上半截就插到它前面,下半截插到后面
591
- const isAfter = (e, row) => {
592
- const r = row.getBoundingClientRect();
593
- return e.clientY > r.top + r.height / 2;
594
- };
595
- nodes.push(
640
+ const rows = [];
641
+ groupRows.set(dir, rows);
642
+ rows.push(
596
643
  h(
597
644
  "div",
598
- {
599
- class: "proj-row",
600
- "data-dir": dir,
601
- draggable: "true",
602
- ondragstart: (e) => {
603
- dirDrag = dir;
604
- e.dataTransfer.effectAllowed = "move";
605
- e.dataTransfer.setData("text/plain", dir);
606
- e.currentTarget.classList.add("dragging");
607
- stopMarquee();
608
- },
609
- ondragend: (e) => {
610
- e.currentTarget.classList.remove("dragging");
611
- endDrag();
612
- },
613
- ondragover: (e) => {
614
- if (!dirDrag) return;
615
- e.preventDefault();
616
- e.dataTransfer.dropEffect = "move";
617
- const after = isAfter(e, e.currentTarget);
618
- if (!e.currentTarget.classList.contains(after ? "drop-after" : "drop-before")) {
619
- clearDrop();
620
- if (dirDrag !== dir) e.currentTarget.classList.add(after ? "drop-after" : "drop-before");
621
- }
622
- },
623
- ondragleave: (e) => {
624
- if (!e.currentTarget.contains(e.relatedTarget)) e.currentTarget.classList.remove("drop-before", "drop-after");
625
- },
626
- ondrop: (e) => {
627
- if (!dirDrag) return;
628
- e.preventDefault();
629
- const from = dirDrag;
630
- const after = isAfter(e, e.currentTarget);
631
- dirDrag = null;
632
- clearDrop();
633
- if (from !== dir) moveProjectDir(from, dir, after);
634
- else if (sidebarStale) renderSidebar();
635
- },
636
- },
645
+ { class: "proj-row", "data-dir": dir, ...groupDragAttrs(dir) },
637
646
  h(
638
647
  "button",
639
648
  { class: "conv-item proj", title: `${dir}\n拖动可调整顺序,右键可置顶`, onclick: () => toggleSide("open", dir) },
@@ -684,13 +693,13 @@ export function renderSidebar() {
684
693
  // 「展开显示」按主对话算条数,分叉跟着主对话一起出现
685
694
  const forest = loadedPrefix(st, forkForest(convs));
686
695
  for (const node of forest.slice(0, st.show)) {
687
- nodes.push(renderForkNode(node, (c, orphan, fold) => convRow(c, " sub", agentLabel(c.agent), orphan, fold)));
696
+ rows.push(renderForkNode(node, (c, orphan, fold) => convRow(c, " sub", agentLabel(c.agent), orphan, fold)));
688
697
  }
689
698
  const btn = moreButton(st, forest.length, PROJECT_LIMIT, load);
690
- if (btn) nodes.push(h("div", { class: "sub-more" }, btn));
699
+ if (btn) rows.push(h("div", { class: "sub-more" }, btn));
691
700
  }
692
701
  }
693
- nodes.push(...botRows.sort((a, b) => b.at - a.at).flatMap((r) => r.rows));
702
+ const nodes = sidebarGroups.flatMap((id) => groupRows.get(id) ?? []);
694
703
  if (!nodes.length) nodes.push(h("div", { class: "conv-empty" }, "还没有会话"));
695
704
  paintList(nodes, askKeys.size);
696
705
  }