agent-loft 0.2.50 → 0.2.52

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.
@@ -136,7 +136,7 @@ function checkList(items, picked, empty) {
136
136
  function openEditor(data, e, reload, preset) {
137
137
  const src = e ?? preset ?? {};
138
138
  const name = h("input", { value: src.name ?? "", maxlength: "40", placeholder: "比如:证券观察员" });
139
- const avatar = avatarPicker(src, () => engine.value, !e);
139
+ const avatar = avatarPicker(src, !e);
140
140
  const desc = h("input", { value: src.description ?? "", maxlength: "500", placeholder: "一句话说它是干什么的(选专家时、当子智能体时都看这句)" });
141
141
  const engine = h(
142
142
  "select",
@@ -189,7 +189,6 @@ function openEditor(data, e, reload, preset) {
189
189
  subField.hidden = eng !== "claude";
190
190
  baseField.hidden = eng !== "claude";
191
191
  perms.setEngine(eng);
192
- avatar.refresh();
193
192
  void models.load(eng);
194
193
  };
195
194
  const sync = () => (cwdField.hidden = perms.access() === "web");
@@ -305,18 +304,18 @@ function permChecks(src) {
305
304
  const AVATAR_PX = 128;
306
305
 
307
306
  /**
308
- * 头像:点一下选图片,居中裁成正方形、缩到 128px 再上传。没传就用引擎的图标(以前设过 emoji 的还显示 emoji)。
307
+ * 头像:点一下选图片,居中裁成正方形、缩到 128px 再上传。没传时显示加号。
309
308
  * src.avatar 是已有头像的地址;isNew(复制一份)时把它读成 data URL 一起带上。
310
309
  * payload():没动过就不带 avatar(服务端沿用),去掉了带空字符串
311
310
  */
312
- function avatarPicker(src, engineOf, isNew) {
311
+ function avatarPicker(src, isNew) {
313
312
  let value; // undefined = 没动过;"" = 去掉;data URL = 新的
314
313
  let shown = src.avatar || "";
315
- const preview = h("button", { type: "button", class: "avatar-preview", title: "上传头像" });
314
+ const preview = h("button", { type: "button", class: "avatar-preview", title: "上传头像", "aria-label": "上传头像" });
316
315
  const file = h("input", { type: "file", accept: "image/*", hidden: true });
317
316
  const remove = h("button", { type: "button", class: "btn small" }, "去掉");
318
317
  const refresh = () => {
319
- fill(preview, shown ? h("img", { src: shown, alt: "" }) : !value && value !== "" && src.icon ? h("span", { class: "avatar-emoji" }, src.icon) : agentIcon(engineOf()));
318
+ fill(preview, shown ? h("img", { src: shown, alt: "", draggable: "false" }) : icon("plus"));
320
319
  remove.hidden = !shown;
321
320
  };
322
321
  preview.onclick = () => file.click();
@@ -347,9 +346,9 @@ function avatarPicker(src, engineOf, isNew) {
347
346
  })
348
347
  .catch(() => {});
349
348
  }
349
+ refresh();
350
350
  return {
351
- el: h("div", { class: "avatar-field" }, preview, h("div", { class: "avatar-btns" }, h("button", { type: "button", class: "btn small", onclick: () => file.click() }, "上传"), remove), file),
352
- refresh,
351
+ el: h("div", { class: "avatar-field" }, preview, remove, file),
353
352
  payload: () => (value === undefined ? {} : { avatar: value }),
354
353
  };
355
354
  }
@@ -151,6 +151,11 @@ function hasDraft() {
151
151
 
152
152
  export function updateSendBtn() {
153
153
  if (!ui.sendBtn) return;
154
+ if (S.editingMessage === S.current && S.current) {
155
+ ui.sendBtn.disabled = true;
156
+ ui.sendBtn.title = "正在恢复消息…";
157
+ return;
158
+ }
154
159
  // 已经点了发送、还在等服务器确认:转圈,不能再点,避免以为没点上又点一次
155
160
  if (S.sending) {
156
161
  ui.sendBtn.innerHTML = '<span class="send-spinner"></span>';
@@ -1,4 +1,4 @@
1
- import { agentIcon, fill, h, toast } from "../lib/dom.js";
1
+ import { agentIcon, fill, h, icon, toast } from "../lib/dom.js";
2
2
  import { api } from "../lib/api.js";
3
3
  import { relTime } from "../lib/time.js";
4
4
  import { S, ui } from "../state.js";
@@ -7,6 +7,7 @@ import { agentCatalog, baseName, catalogDefaults, draftPick, modelName, renderCo
7
7
  import { closeMenu, confirmDialog, modal, placePopover, showPopover } from "../lib/overlay.js";
8
8
  import { newDraft, openConversation, renderEmpty } from "./messages.js";
9
9
  import { setDraftExpert } from "./experts.js";
10
+ import { preloadCommands } from "./slash.js";
10
11
 
11
12
  // ---------- 会话操作 ----------
12
13
 
@@ -47,6 +48,7 @@ export async function forkConversation(anchor, key = S.current) {
47
48
  export function switchAgent(id) {
48
49
  if (S.current) return;
49
50
  setDraftExpert(id);
51
+ preloadCommands();
50
52
  renderTopbar();
51
53
  renderEmpty();
52
54
  }
@@ -209,6 +211,8 @@ export async function changeCwd(pick) {
209
211
  let showHidden = localStorage.getItem("aim.cwdHidden") === "1";
210
212
  let listing = null;
211
213
  let seq = 0;
214
+ let loading = false;
215
+ let creating = false;
212
216
 
213
217
  const crumbs = h("div", { class: "dir-crumbs" });
214
218
  const list = h("div", { class: "dir-list" });
@@ -225,23 +229,44 @@ export async function changeCwd(pick) {
225
229
  void load(manual.value.trim());
226
230
  }
227
231
  };
232
+ const folderName = h("input", { class: "dir-manual", placeholder: "文件夹名称", "aria-label": "文件夹名称", maxlength: "255", required: true, autocomplete: "off", spellcheck: "false" });
233
+ const create = h("button", { type: "submit", class: "btn primary small" }, "创建");
234
+ const cancelCreate = h("button", { type: "button", class: "btn small", onclick: () => (createForm.hidden = true) }, "取消");
235
+ const createForm = h("form", {
236
+ class: "dir-create", hidden: true,
237
+ onsubmit: (e) => {
238
+ e.preventDefault();
239
+ void createFolder();
240
+ },
241
+ }, folderName, create, cancelCreate);
242
+ const newFolder = h("button", {
243
+ type: "button", class: "btn small", disabled: true,
244
+ onclick: () => {
245
+ createForm.hidden = false;
246
+ folderName.value = "";
247
+ folderName.focus();
248
+ },
249
+ }, icon("plus"), "新建文件夹");
228
250
  const body = h(
229
251
  "div",
230
252
  { class: "modal-body" },
231
253
  crumbs,
232
- h("div", { class: "row", style: { gap: "8px", alignItems: "center" } }, manual, h("label", { class: "check" }, hiddenBox, "显示隐藏")),
254
+ manual,
255
+ h("div", { class: "dir-actions" }, h("label", { class: "check" }, hiddenBox, "显示隐藏"), newFolder),
256
+ createForm,
233
257
  list,
234
258
  );
235
259
  const go = h("button", { class: "btn primary", disabled: true }, goLabel);
236
260
  const note = h("span", { class: "muted grow" }, pick ? "" : draft ? "发送第一条消息时在这个目录开会话" : "切换后开新会话");
237
261
  const close = modal({
238
262
  title: pick || draft ? "选择工作目录" : "切换工作目录",
263
+ className: "dir-picker",
239
264
  body,
240
265
  foot: h("div", { class: "modal-foot", style: { alignItems: "center" } }, note, go),
241
266
  });
242
267
 
243
268
  go.onclick = async () => {
244
- if (!listing) return;
269
+ if (!listing || loading || creating) return;
245
270
  close();
246
271
  if (pick) {
247
272
  pick.onPick(listing.path);
@@ -250,12 +275,46 @@ export async function changeCwd(pick) {
250
275
  if (draft) {
251
276
  S.draftCwd = listing.path === listing.root ? null : listing.path;
252
277
  S.draftCwdPicked = true;
278
+ preloadCommands();
253
279
  if (!S.current) renderEmpty();
254
280
  return;
255
281
  }
256
282
  await doAction("cd", listing.path);
257
283
  };
258
284
 
285
+ function syncActions() {
286
+ go.disabled = loading || creating || !listing || listing.path === current;
287
+ newFolder.disabled = loading || creating || !listing;
288
+ create.disabled = loading || creating;
289
+ cancelCreate.disabled = creating;
290
+ folderName.disabled = creating;
291
+ create.textContent = creating ? "创建中…" : "创建";
292
+ }
293
+
294
+ async function createFolder() {
295
+ const name = folderName.value.trim();
296
+ if (!listing || loading || creating || !name) return;
297
+ const my = seq;
298
+ const parent = listing.path;
299
+ creating = true;
300
+ syncActions();
301
+ try {
302
+ const data = await api("/api/dirs", { method: "POST", body: { path: parent, name } });
303
+ if (my !== seq || !body.isConnected) return;
304
+ createForm.hidden = true;
305
+ await load(data.path);
306
+ } catch (err) {
307
+ if (body.isConnected) {
308
+ toast(err.message);
309
+ folderName.disabled = false;
310
+ folderName.focus();
311
+ }
312
+ } finally {
313
+ creating = false;
314
+ syncActions();
315
+ }
316
+ }
317
+
259
318
  function renderCrumbs() {
260
319
  const parts = listing.rel ? listing.rel.split(/[\\/]/) : [];
261
320
  const rootName = listing.root.split(/[\\/]/).filter(Boolean).pop() || listing.root;
@@ -302,16 +361,16 @@ export async function changeCwd(pick) {
302
361
 
303
362
  async function load(rel) {
304
363
  const my = ++seq;
305
- go.disabled = true;
364
+ loading = true;
365
+ createForm.hidden = true;
366
+ syncActions();
306
367
  fill(list, h("span", { class: "spinner" }));
307
368
  try {
308
369
  const data = await api(`/api/dirs?path=${encodeURIComponent(rel)}`);
309
370
  if (my !== seq) return;
310
371
  listing = data;
311
372
  manual.value = "";
312
- go.disabled = false;
313
373
  go.textContent = data.path === current ? "已是当前目录" : goLabel;
314
- if (data.path === current) go.disabled = true;
315
374
  renderCrumbs();
316
375
  renderList();
317
376
  } catch (err) {
@@ -322,8 +381,12 @@ export async function changeCwd(pick) {
322
381
  }
323
382
  // 进不去就留在原地
324
383
  toast(err.message);
325
- go.disabled = listing.path === current;
326
384
  renderList();
385
+ } finally {
386
+ if (my === seq) {
387
+ loading = false;
388
+ syncActions();
389
+ }
327
390
  }
328
391
  }
329
392
 
@@ -95,7 +95,7 @@ export function renderInteraction(item) {
95
95
  "div",
96
96
  { class: "ix-buttons" },
97
97
  spec.allowSession
98
- ? h("button", { class: "btn accent", onclick: () => ixOp(ix.id, "decide", { decision: "allow-session" }) }, "本会话全部允许")
98
+ ? h("button", { class: "btn primary", onclick: () => ixOp(ix.id, "decide", { decision: "allow-session" }) }, "本会话全部允许")
99
99
  : null,
100
100
  h("button", { class: `btn${spec.allowSession ? "" : " accent"}`, onclick: () => ixOp(ix.id, "decide", { decision: "allow-once" }) }, "允许一次"),
101
101
  // 会落盘、对所有人生效的「总是允许」只给管理员
@@ -28,6 +28,7 @@ import { bindFileDrop, renderComposer } from "./composer.js";
28
28
  import { openSearch } from "./conv-search.js";
29
29
  import { createNav } from "./msg-nav.js";
30
30
  import { renameConv } from "./conv-actions.js";
31
+ import { clearCommandCache, preloadCommands } from "./slash.js";
31
32
  import { releaseForeignPushSub } from "../lib/push.js";
32
33
 
33
34
  // ---------- 主界面 ----------
@@ -122,6 +123,7 @@ export function openTasksView() {
122
123
  export async function boot() {
123
124
  const me = await api("/api/me");
124
125
  if (!me.authed) return showAuth();
126
+ clearCommandCache();
125
127
  WS.stopped = false;
126
128
  WS.epoch = null;
127
129
  WS.hellos = 0;
@@ -164,6 +166,7 @@ export async function boot() {
164
166
  else if (fromHash && S.convs.has(fromHash)) await openConversation(fromHash);
165
167
  else if (latest) await openConversation(latest.key);
166
168
  else newDraft();
169
+ preloadCommands();
167
170
  // 以前的技能页地址:技能现在在设置里
168
171
  if (fromHash === "skills") openSettings("技能");
169
172
  // 点了桌面端的系统通知 / 菜单栏里的待处理项:跳到对应会话
@@ -262,7 +265,7 @@ function renderLayout() {
262
265
  h(
263
266
  "div",
264
267
  { class: "side-top" },
265
- h("button", { class: "btn new-chat", onclick: () => (newDraft(), closeSide()) }, icon("compose"), "新聊天"),
268
+ h("button", { class: "btn new-chat", onclick: () => (newDraft(), closeSide()) }, icon("plus"), "新建"),
266
269
  ),
267
270
  // 搜索:弹窗里搜标题和聊天内容,可以按专家筛
268
271
  h("button", { class: "btn new-chat side-nav search-nav", onclick: () => openSearch() }, icon("search"), "搜索"),
@@ -1,4 +1,4 @@
1
- import { fill, h, icon, starsLoader } from "../lib/dom.js";
1
+ import { fill, h, icon, starsLoader, toast } from "../lib/dom.js";
2
2
  import { api } from "../lib/api.js";
3
3
  import { clockTime, liveDuration, serverNow, setServerTime, tidyFooter } from "../lib/time.js";
4
4
  import { copyText, patchMarkdown, renderMarkdown } from "../lib/markdown.js";
@@ -7,13 +7,14 @@ import { WS } from "../lib/ws.js";
7
7
  import { agentLabel, convTitle, renderSidebar } from "./sidebar.js";
8
8
  import { baseName, renderContext, renderTopbar, updateCtxVisibility, usableAgents } from "./topbar.js";
9
9
  import { insertCard, renderInteraction, upsertInteraction } from "./interaction.js";
10
- import { renderChips, setBusy } from "./composer.js";
10
+ import { renderChips, setBusy, updateSendBtn } from "./composer.js";
11
11
  import { renderScheduled } from "./schedule.js";
12
12
  import { changeCwd, doAction, forkConversation } from "./conv-actions.js";
13
13
  import { scheduleNav } from "./msg-nav.js";
14
14
  import { linkReplyFiles } from "./file-preview.js";
15
15
  import { setTodos } from "./todos.js";
16
16
  import { expertIcon, findExpert } from "./experts.js";
17
+ import { preloadCommands } from "./slash.js";
17
18
 
18
19
  // ---------- 打开会话 ----------
19
20
 
@@ -48,6 +49,7 @@ export function newDraft() {
48
49
  renderSidebar();
49
50
  scheduleNav();
50
51
  ui.input?.focus();
52
+ preloadCommands();
51
53
  }
52
54
 
53
55
  export function renderEmpty() {
@@ -109,6 +111,7 @@ export async function openConversation(key) {
109
111
  const token = ++S.loadToken;
110
112
  if (S.current && S.current !== key) WS.raw({ t: "unsub", key: S.current });
111
113
  S.current = key;
114
+ if (S.convs.has(key)) preloadCommands();
112
115
  S.items = [];
113
116
  S.turnAi = null;
114
117
  turnStartAt = null;
@@ -145,6 +148,7 @@ export async function openConversation(key) {
145
148
  // 侧栏分页:打开的可能是还没拉到的那条(通知、地址里带的),拿到了就补进侧栏
146
149
  const known = S.convs.has(key);
147
150
  S.convs.set(key, data.info);
151
+ preloadCommands();
148
152
  if (!known) renderSidebar();
149
153
  S.allowedAgents = data.allowedAgents;
150
154
  if (Number.isFinite(data.serverTime)) setServerTime(data.serverTime);
@@ -160,7 +164,7 @@ export async function openConversation(key) {
160
164
  bulk = true;
161
165
  try {
162
166
  for (const m of data.messages) {
163
- if (m.role === "user") addItem({ type: "user", text: m.text, files: m.attachments ?? [], origin: null });
167
+ if (m.role === "user") addItem({ type: "user", text: m.text, files: m.attachments ?? [], origin: null, anchor: m.anchor });
164
168
  else if (m.role === "question") addItem({ type: "ix", id: m.question.id, ix: historyQuestion(key, m) });
165
169
  else addItem({ type: "ai", steps: m.steps ?? [], committed: m.text, partial: "", done: true, footer: m.footer, at: m.ts, anchor: m.anchor, segment: m.segment });
166
170
  }
@@ -311,8 +315,18 @@ let bulk = false;
311
315
  export function addItem(item) {
312
316
  ui.msgInner.querySelector(".empty")?.remove();
313
317
  item.el = renderItem(item);
314
- ui.msgInner.append(item.el);
315
- S.items.push(item);
318
+ // 当前回复拆成多段或恢复排队消息时,回复和交互卡仍在后续排队输入之前。
319
+ const activeUser = S.items.findLastIndex((it) => it.type === "user" && !it.queued);
320
+ const queued = item.type === "ai" || item.type === "ix"
321
+ ? S.items.findIndex((it, i) => i > activeUser && it.type === "user" && it.queued)
322
+ : -1;
323
+ if (queued >= 0) {
324
+ S.items[queued].el.before(item.el);
325
+ S.items.splice(queued, 0, item);
326
+ } else {
327
+ ui.msgInner.append(item.el);
328
+ S.items.push(item);
329
+ }
316
330
  if (bulk) return item;
317
331
  if (item.type === "user") {
318
332
  clampLongUsers([item]);
@@ -458,7 +472,45 @@ function clampLongUsers(items) {
458
472
  }
459
473
  }
460
474
 
461
- /** 排队中的消息下面:「排队中 · 打断并发送」;停止、会话切换后没发出去的:「没有发出」 */
475
+ async function editUserMessage(item, queued, button) {
476
+ const key = S.current;
477
+ if (!key || S.editingMessage || S.sending) return;
478
+ S.editingMessage = key;
479
+ button.disabled = true;
480
+ updateSendBtn();
481
+ try {
482
+ const result = await api(`/api/conversations/${encodeURIComponent(key)}/${queued ? "cancel-queued" : "rewind"}`, {
483
+ method: "POST",
484
+ body: { id: item.id, anchor: item.anchor, sessionId: S.convs.get(key)?.sessionId },
485
+ });
486
+ if (S.current !== key) return;
487
+ if (!queued && !result.queued) await openConversation(key);
488
+ if (S.current !== key) return;
489
+ for (const upload of S.uploads) if (upload.url) URL.revokeObjectURL(upload.url);
490
+ S.uploads = result.draft.uploads;
491
+ ui.input.value = result.draft.text;
492
+ renderChips();
493
+ ui.input.dispatchEvent(new Event("input", { bubbles: true }));
494
+ ui.input.focus();
495
+ if (result.draft.missing) toast("部分附件已被清理,请重新添加");
496
+ } catch (err) {
497
+ toast(err.message);
498
+ } finally {
499
+ S.editingMessage = null;
500
+ button.disabled = false;
501
+ updateSendBtn();
502
+ }
503
+ }
504
+
505
+ function editButton(item, queued = false) {
506
+ const label = queued ? "撤销并编辑" : "回退到此处";
507
+ return h("button", {
508
+ class: "icon-btn", title: label, "aria-label": label,
509
+ onclick: (e) => void editUserMessage(item, queued, e.currentTarget),
510
+ }, icon("undo"));
511
+ }
512
+
513
+ /** 排队中的消息可立即发送或撤销编辑;停止后没发出去的显示「没有发出」 */
462
514
  function queueNote(item, state) {
463
515
  if (state === "dropped") return h("div", { class: "queue-note dropped" }, "没有发出");
464
516
  return h(
@@ -466,12 +518,15 @@ function queueNote(item, state) {
466
518
  { class: "queue-note" },
467
519
  h("span", { class: "shimmer" }, "排队中,等上一条回复完"),
468
520
  h("button", { class: "queue-jump", title: "停掉正在进行的回复,马上处理这条", onclick: () => void doAction("jump", item.id) }, "打断并发送"),
521
+ editButton(item, true),
469
522
  );
470
523
  }
471
524
 
472
525
  /** state:queued / dropped / null(轮到它了,去掉标记) */
473
526
  function setQueueState(item, state) {
474
527
  item.queued = state === "queued";
528
+ const actions = item.el.querySelector(".user-actions");
529
+ if (actions) actions.hidden = item.queued;
475
530
  const next = state ? queueNote(item, state) : null;
476
531
  if (item.queueEl && next) item.queueEl.replaceWith(next);
477
532
  else if (item.queueEl) item.queueEl.remove();
@@ -491,9 +546,10 @@ function renderItem(item) {
491
546
  renderUserFiles(item.files),
492
547
  item.text ? (item.bubble = h("div", { class: "msg-user" }, origin ? h("span", { class: "origin" }, origin) : null, item.text)) : null,
493
548
  (item.queueEl = item.queued ? queueNote(item, "queued") : null),
494
- item.text
495
- ? h("div", { class: "user-actions" }, h("button", { class: "icon-btn", title: "复制", onclick: () => copyText(item.text) }, icon("copy")))
496
- : null,
549
+ h("div", { class: "user-actions", hidden: item.queued },
550
+ item.text ? h("button", { class: "icon-btn", title: "复制", onclick: () => copyText(item.text) }, icon("copy")) : null,
551
+ editButton(item),
552
+ ),
497
553
  );
498
554
  }
499
555
  case "ai":
@@ -642,6 +698,21 @@ export function applyEvent(env) {
642
698
  S.seq.set(env.key, env.seq);
643
699
  const ev = env.ev;
644
700
  switch (ev.type) {
701
+ case "user_anchor": {
702
+ const item = S.items.find((it) => it.type === "user" && it.id === ev.id);
703
+ if (item) item.anchor = ev.anchor;
704
+ return;
705
+ }
706
+ case "history_reset": {
707
+ if (S.editingMessage === env.key) return;
708
+ const uploads = S.uploads;
709
+ void openConversation(env.key).then(() => {
710
+ if (S.current !== env.key) return;
711
+ S.uploads = uploads;
712
+ renderChips();
713
+ });
714
+ return;
715
+ }
645
716
  case "user": {
646
717
  // 排队的消息:正在进行的那一轮照常在上面接着输出,这条等轮到它(queue 事件)再挂占位
647
718
  const queued = !!ev.queued;
@@ -669,6 +740,14 @@ export function applyEvent(env) {
669
740
  }
670
741
  case "queue": {
671
742
  const it = S.items.find((i) => i.type === "user" && i.id === ev.id);
743
+ if (it && ev.state === "removed") {
744
+ it.el.remove();
745
+ S.items = S.items.filter((item) => item !== it);
746
+ if (ui.pinEl === it.el) ui.pinEl = null;
747
+ scheduleNav();
748
+ afterLayout();
749
+ return;
750
+ }
672
751
  if (it) setQueueState(it, ev.state === "dropped" ? "dropped" : null);
673
752
  // 轮到它了(上一轮刚出结果):挂上「思考中」占位,用时从现在算。被当成提问的回答时那一轮还在跑,不用挂
674
753
  if (ev.state === "started" && (!S.turnAi || S.turnAi.done)) {
@@ -4,19 +4,45 @@ import { userScrolled } from "./messages.js";
4
4
 
5
5
  // ---------- 消息区右边的快速定位(像网页版 ChatGPT) ----------
6
6
  // 每条用户消息一道短横线,竖着排在滚动条旁边,正看到的那条高亮;平时淡淡的,滚动时清楚些。
7
- // 鼠标移上去展开成列表,显示每条消息的开头,点一下跳过去。用户消息少于 3 条时不显示;窄屏(手机)不显示。
7
+ // 鼠标移上去展开成列表,显示每条消息的开头,点一下跳过去。用户消息少于 3 条时不显示。
8
+ // 手机用短轨道定位:按住拖动预览问题,松手跳转;只在手动滚动和操作时显示。
8
9
 
9
10
  const MIN_USERS = 3;
11
+ const HIDE_DELAY = 1600;
12
+ const compact = matchMedia("(max-width: 768px), (hover: none)");
10
13
  let entries = [];
11
14
  let activeIdx = -1;
12
15
  let scheduled = false;
13
16
  let scrollRaf = 0;
14
17
  let scrollingTimer = 0;
18
+ let builtFor = null;
19
+ let scrubbing = null;
20
+
21
+ compact.addEventListener("change", () => {
22
+ resetScrolling();
23
+ updateActive();
24
+ });
15
25
 
16
26
  export function createNav() {
27
+ resetScrolling();
28
+ builtFor = null;
29
+ entries = [];
17
30
  ui.navTicks = h("div", { class: "msg-nav-ticks" });
18
31
  ui.navPanel = h("div", { class: "msg-nav-panel" });
19
- ui.nav = h("nav", { class: "msg-nav", hidden: true, "aria-label": "消息快速定位", onpointerenter: revealActiveRow }, ui.navTicks, ui.navPanel);
32
+ ui.navTrack = h("div", { class: "msg-nav-track", "aria-hidden": "true" });
33
+ ui.navRail = h("div", {
34
+ class: "msg-nav-rail", role: "slider", tabindex: "0", "aria-label": "拖动定位用户消息", "aria-orientation": "vertical", "aria-valuemin": "1",
35
+ onpointerdown: startScrubbing, onpointermove: moveScrubbing, onpointerup: finishScrubbing,
36
+ onpointercancel: cancelPointer, onlostpointercapture: cancelPointer, onkeydown: onRailKey,
37
+ onfocus: markScrolling, onblur: markScrolling,
38
+ }, ui.navTrack);
39
+ ui.navCount = h("span", { class: "msg-nav-count" });
40
+ ui.navSnippet = h("span", { class: "msg-nav-snippet" });
41
+ const preview = h("div", { class: "msg-nav-preview", "aria-hidden": "true" }, ui.navCount, ui.navSnippet);
42
+ ui.nav = h("nav", { class: "msg-nav", hidden: true, "aria-label": "消息快速定位", onpointerenter: revealActiveRow, onpointerdown: markScrolling }, ui.navTicks, ui.navPanel, ui.navRail, preview);
43
+ ui.navTicks.addEventListener("scroll", () => {
44
+ if (ui.nav.classList.contains("scrolling")) markScrolling();
45
+ }, { passive: true });
20
46
  ui.messages.addEventListener("scroll", onScroll, { passive: true });
21
47
  return ui.nav;
22
48
  }
@@ -41,24 +67,39 @@ function snippet(item) {
41
67
  function build() {
42
68
  if (!ui.nav) return;
43
69
  const users = S.view ? [] : S.items.filter((it) => it.type === "user" && it.el?.isConnected);
70
+ if (builtFor !== S.current || users.length < MIN_USERS) resetScrolling();
71
+ else if (scrubbing) {
72
+ cancelScrubbing();
73
+ markScrolling();
74
+ }
75
+ builtFor = S.current;
44
76
  ui.nav.hidden = users.length < MIN_USERS;
45
77
  activeIdx = -1;
46
78
  if (ui.nav.hidden) {
47
79
  entries = [];
48
80
  ui.navTicks.replaceChildren();
49
81
  ui.navPanel.replaceChildren();
82
+ ui.navTrack.replaceChildren();
50
83
  return;
51
84
  }
52
85
  entries = users.map((item, i) => {
53
86
  const label = snippet(item);
54
87
  return {
55
88
  item,
89
+ label,
56
90
  tick: h("button", { class: "msg-nav-tick", "aria-label": `第 ${i + 1} 条:${label}`, onclick: () => jump(item) }, h("i")),
57
91
  row: h("button", { class: "msg-nav-row", onclick: () => jump(item) }, label),
58
92
  };
59
93
  });
60
94
  ui.navTicks.replaceChildren(...entries.map((e) => e.tick));
61
95
  ui.navPanel.replaceChildren(...entries.map((e) => e.row));
96
+ const marks = Math.min(entries.length, 9);
97
+ ui.navRail.style.setProperty("--nav-rail-height", `${Math.min(156, 56 + (marks - 1) * 16)}px`);
98
+ ui.navTrack.replaceChildren(
99
+ ...Array.from({ length: marks }, (_, i) => h("i", { class: `msg-nav-mark${i % 2 === 0 ? " major" : ""}`, style: { top: `${i / (marks - 1) * 100}%` } })),
100
+ h("span", { class: "msg-nav-thumb" }),
101
+ );
102
+ ui.navRail.setAttribute("aria-valuemax", String(entries.length));
62
103
  updateActive();
63
104
  }
64
105
 
@@ -68,16 +109,34 @@ function covered() {
68
109
  }
69
110
 
70
111
  function jump(item) {
71
- if (!item.el?.isConnected) return;
112
+ if (!item?.el?.isConnected) return;
72
113
  userScrolled();
73
114
  ui.messages.scrollTo({ top: Math.max(0, item.el.offsetTop - covered() - 12), behavior: "smooth" });
74
115
  }
75
116
 
76
- function onScroll() {
117
+ function resetScrolling() {
118
+ cancelScrubbing();
119
+ clearTimeout(scrollingTimer);
120
+ cancelAnimationFrame(scrollRaf);
121
+ scrollRaf = 0;
122
+ ui.nav?.classList.remove("scrolling");
123
+ }
124
+
125
+ function markScrolling() {
77
126
  if (!entries.length) return;
78
127
  ui.nav.classList.add("scrolling");
79
128
  clearTimeout(scrollingTimer);
80
- scrollingTimer = setTimeout(() => ui.nav.classList.remove("scrolling"), 1200);
129
+ if (scrubbing) return;
130
+ scrollingTimer = setTimeout(() => {
131
+ if (compact.matches && document.activeElement === ui.navRail) return;
132
+ ui.nav.classList.remove("scrolling");
133
+ }, HIDE_DELAY);
134
+ }
135
+
136
+ function onScroll() {
137
+ if (!entries.length) return;
138
+ // 自动跟随模型回复时不打扰阅读;手动滚动才唤出手机上的轨道。
139
+ if (!compact.matches || ui.follow === false) markScrolling();
81
140
  if (scrollRaf) return;
82
141
  scrollRaf = requestAnimationFrame(() => {
83
142
  scrollRaf = 0;
@@ -87,6 +146,7 @@ function onScroll() {
87
146
 
88
147
  /** 正看到的:顶部往下三分之一处以上、最后一条用户消息;已经滚到底就是最后一条 */
89
148
  function updateActive() {
149
+ if (!entries.length || scrubbing) return;
90
150
  const m = ui.messages;
91
151
  const line = m.scrollTop + covered() + m.clientHeight * 0.3;
92
152
  let idx = 0;
@@ -97,13 +157,80 @@ function updateActive() {
97
157
  else break;
98
158
  }
99
159
  }
160
+ selectEntry(idx);
161
+ }
162
+
163
+ function selectEntry(idx) {
164
+ const entry = entries[idx];
165
+ if (!entry) return;
166
+ ui.nav.style.setProperty("--nav-progress", String(idx / (entries.length - 1)));
167
+ ui.navRail.setAttribute("aria-valuenow", String(idx + 1));
168
+ ui.navRail.setAttribute("aria-valuetext", `第 ${idx + 1} 条,共 ${entries.length} 条:${entry.label}`);
169
+ ui.navCount.textContent = `${idx + 1} / ${entries.length}`;
170
+ ui.navSnippet.textContent = entry.label;
100
171
  if (idx === activeIdx) return;
101
172
  entries[activeIdx]?.tick.classList.remove("on");
102
173
  entries[activeIdx]?.row.classList.remove("on");
103
174
  activeIdx = idx;
104
175
  entries[idx].tick.classList.add("on");
105
176
  entries[idx].row.classList.add("on");
106
- keepVisible(ui.navTicks, entries[idx].tick);
177
+ if (!compact.matches) keepVisible(ui.navTicks, entries[idx].tick);
178
+ }
179
+
180
+ function scrubTo(clientY) {
181
+ const rect = ui.navTrack.getBoundingClientRect();
182
+ if (!rect.height) return;
183
+ const fraction = Math.max(0, Math.min(1, (clientY - rect.top) / rect.height));
184
+ scrubbing.index = Math.round(fraction * (entries.length - 1));
185
+ selectEntry(scrubbing.index);
186
+ }
187
+
188
+ function startScrubbing(e) {
189
+ if (!compact.matches || !entries.length || e.button !== 0 || scrubbing) return;
190
+ e.preventDefault();
191
+ scrubbing = { pointerId: e.pointerId, index: activeIdx, key: S.current };
192
+ ui.navRail.setPointerCapture(e.pointerId);
193
+ ui.nav.classList.add("scrubbing");
194
+ markScrolling();
195
+ scrubTo(e.clientY);
196
+ }
197
+
198
+ function moveScrubbing(e) {
199
+ if (scrubbing?.pointerId !== e.pointerId) return;
200
+ scrubTo(e.clientY);
201
+ }
202
+
203
+ function finishScrubbing(e) {
204
+ if (scrubbing?.pointerId !== e.pointerId) return;
205
+ scrubTo(e.clientY);
206
+ const target = scrubbing;
207
+ cancelScrubbing();
208
+ if (target.key === S.current) jump(entries[target.index]?.item);
209
+ markScrolling();
210
+ }
211
+
212
+ function cancelScrubbing() {
213
+ const pointerId = scrubbing?.pointerId;
214
+ scrubbing = null;
215
+ ui.nav?.classList.remove("scrubbing");
216
+ if (pointerId !== undefined && ui.navRail?.hasPointerCapture(pointerId)) ui.navRail.releasePointerCapture(pointerId);
217
+ updateActive();
218
+ }
219
+
220
+ function cancelPointer(e) {
221
+ if (scrubbing?.pointerId !== e.pointerId) return;
222
+ cancelScrubbing();
223
+ markScrolling();
224
+ }
225
+
226
+ function onRailKey(e) {
227
+ const delta = { ArrowUp: -1, ArrowLeft: -1, ArrowDown: 1, ArrowRight: 1, PageUp: -5, PageDown: 5 }[e.key];
228
+ if (!entries.length || (delta === undefined && e.key !== "Home" && e.key !== "End")) return;
229
+ e.preventDefault();
230
+ const idx = e.key === "Home" ? 0 : e.key === "End" ? entries.length - 1 : Math.max(0, Math.min(entries.length - 1, activeIdx + delta));
231
+ selectEntry(idx);
232
+ jump(entries[idx].item);
233
+ markScrolling();
107
234
  }
108
235
 
109
236
  /** 横线太多、竖条装不下时它自己能滚:让高亮的那道留在看得见的地方(不用 scrollIntoView,免得把外层也带着滚) */
@@ -115,6 +242,7 @@ function keepVisible(box, el) {
115
242
 
116
243
  /** 展开列表时:列表滚到正看到的那条 */
117
244
  function revealActiveRow() {
245
+ if (compact.matches) return;
118
246
  const row = entries[activeIdx]?.row;
119
247
  if (row) ui.navPanel.scrollTop = Math.max(0, row.offsetTop - ui.navPanel.clientHeight / 2);
120
248
  }