agent-loft 0.2.49 → 0.2.51

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.
@@ -0,0 +1,206 @@
1
+ import { h, icon, toast } from "../lib/dom.js";
2
+ import { api } from "../lib/api.js";
3
+ import { relTime } from "../lib/time.js";
4
+ import { S } from "../state.js";
5
+ import { baseName } from "./topbar.js";
6
+ import { closeSide, convTitle } from "./sidebar.js";
7
+ import { openConversation } from "./messages.js";
8
+ import { leaveRemote } from "./remote.js";
9
+ import { convExpert, expertChoices, expertIcon } from "./experts.js";
10
+
11
+ // ---------- 搜索会话(侧栏「搜索」,服务端见 /api/conversations/search) ----------
12
+ // 弹窗:上面输入框,下面一排专家(默认「全部」),再下面是结果。
13
+ // 搜全部会话的标题、目录名和聊天内容,不只是侧栏已经拉下来的几页;没输入时列最近的。
14
+ // ↑↓ 选,回车打开,Esc 关。
15
+
16
+ let current = null;
17
+
18
+ export function openSearch() {
19
+ if (current) return current.input.focus();
20
+ const st = { q: "", expert: null, results: null, loading: false, seq: 0, timer: 0, sel: 0 };
21
+ const input = h("input", {
22
+ class: "search-input",
23
+ type: "search",
24
+ placeholder: "搜索会话标题、聊天内容",
25
+ enterkeyhint: "search",
26
+ autocomplete: "off",
27
+ oninput: () => {
28
+ st.q = input.value;
29
+ clearTimeout(st.timer);
30
+ st.timer = setTimeout(run, 200);
31
+ },
32
+ });
33
+ const chips = h("div", { class: "search-experts" });
34
+ const list = h("div", { class: "search-results" });
35
+ const close = () => {
36
+ clearTimeout(st.timer);
37
+ st.seq++;
38
+ overlay.remove();
39
+ document.removeEventListener("keydown", onKey, true);
40
+ current = null;
41
+ };
42
+ const overlay = h(
43
+ "div",
44
+ { class: "overlay search-overlay", onclick: (e) => e.target === overlay && close() },
45
+ h(
46
+ "div",
47
+ { class: "search-modal", role: "dialog", "aria-label": "搜索会话" },
48
+ h(
49
+ "div",
50
+ { class: "search-head" },
51
+ h("span", { class: "search-icon" }, icon("search")),
52
+ input,
53
+ h("button", { class: "icon-btn", title: "关闭(Esc)", onclick: close }, icon("x")),
54
+ ),
55
+ chips,
56
+ list,
57
+ ),
58
+ );
59
+
60
+ const open = (c) => {
61
+ close();
62
+ closeSide();
63
+ if (!S.convs.has(c.key)) S.convs.set(c.key, c);
64
+ if (c.key !== S.current) void openConversation(c.key);
65
+ else if (S.view === "remote") leaveRemote();
66
+ };
67
+
68
+ function renderChips() {
69
+ const chip = (id, label, iconEl) =>
70
+ h(
71
+ "button",
72
+ {
73
+ class: `search-chip${st.expert === id ? " on" : ""}`,
74
+ onclick: () => {
75
+ if (st.expert === id) return;
76
+ st.expert = id;
77
+ renderChips();
78
+ void run();
79
+ input.focus();
80
+ },
81
+ },
82
+ iconEl,
83
+ label,
84
+ );
85
+ chips.replaceChildren(chip(null, "全部", null), ...expertChoices().map((e) => chip(e.id, e.name, expertIcon(e))));
86
+ }
87
+
88
+ function renderResults() {
89
+ const { results } = st;
90
+ if (!results) {
91
+ list.replaceChildren(h("div", { class: "search-empty" }, "搜索中…"));
92
+ return;
93
+ }
94
+ if (results.length === 0) {
95
+ list.replaceChildren(h("div", { class: "search-empty" }, st.loading ? "搜索中…" : st.q.trim() ? "没有找到相关的会话" : "还没有会话"));
96
+ return;
97
+ }
98
+ st.sel = Math.min(st.sel, results.length - 1);
99
+ const words = st.q.trim().toLowerCase().split(/\s+/).filter(Boolean);
100
+ list.replaceChildren(
101
+ ...(st.q.trim() ? [] : [h("div", { class: "search-label" }, "最近")]),
102
+ ...results.map(({ conv, snippet }, i) => {
103
+ // 本地有就用本地的(标题是最新的)
104
+ const c = S.convs.get(conv.key) ?? conv;
105
+ const where = c.channel === "feishu" ? "飞书" : baseName(c.cwd);
106
+ return h(
107
+ "button",
108
+ {
109
+ class: `search-hit${i === st.sel ? " sel" : ""}`,
110
+ title: `${convTitle(c)}\n${c.cwd}`,
111
+ onclick: () => open(c),
112
+ onpointermove: () => {
113
+ if (st.sel !== i) select(i, false);
114
+ },
115
+ },
116
+ h("span", { class: "hit-icon" }, expertIcon(convExpert(c))),
117
+ h(
118
+ "span",
119
+ { class: "hit-body" },
120
+ h("span", { class: "hit-title" }, mark(convTitle(c), words)),
121
+ snippet ? h("span", { class: "hit-snippet" }, mark(snippet, words)) : null,
122
+ ),
123
+ h("span", { class: "hit-meta" }, `${where} · ${relTime(c.activeAt)}`),
124
+ );
125
+ }),
126
+ );
127
+ }
128
+
129
+ function select(i, scroll = true) {
130
+ const hits = list.querySelectorAll(".search-hit");
131
+ if (!hits.length) return;
132
+ st.sel = (i + hits.length) % hits.length;
133
+ hits.forEach((el, n) => el.classList.toggle("sel", n === st.sel));
134
+ if (scroll) hits[st.sel].scrollIntoView({ block: "nearest" });
135
+ }
136
+
137
+ async function run() {
138
+ const seq = ++st.seq;
139
+ st.loading = true;
140
+ if (!st.results?.length) renderResults();
141
+ const q = new URLSearchParams({ q: st.q.trim() });
142
+ if (st.expert) q.set("expert", st.expert);
143
+ try {
144
+ const data = await api(`/api/conversations/search?${q}`);
145
+ if (seq !== st.seq) return;
146
+ st.results = data.results;
147
+ } catch (err) {
148
+ if (seq !== st.seq) return;
149
+ st.results = [];
150
+ toast(`搜索失败:${err.message}`);
151
+ }
152
+ st.loading = false;
153
+ st.sel = 0;
154
+ renderResults();
155
+ list.scrollTop = 0;
156
+ }
157
+
158
+ function onKey(e) {
159
+ if (e.key === "Escape") {
160
+ e.preventDefault();
161
+ e.stopPropagation();
162
+ close();
163
+ } else if (e.key === "ArrowDown" || e.key === "ArrowUp") {
164
+ e.preventDefault();
165
+ select(st.sel + (e.key === "ArrowDown" ? 1 : -1));
166
+ } else if (e.key === "Enter" && !e.isComposing && e.target === input) {
167
+ e.preventDefault();
168
+ const hit = st.results?.[st.sel];
169
+ if (hit) open(hit.conv);
170
+ }
171
+ }
172
+
173
+ document.addEventListener("keydown", onKey, true);
174
+ document.body.append(overlay);
175
+ current = { input };
176
+ renderChips();
177
+ renderResults();
178
+ input.focus();
179
+ void run();
180
+ }
181
+
182
+ /** 把查询的词在文字里标出来 */
183
+ function mark(text, words) {
184
+ if (!words.length) return text;
185
+ const lower = text.toLowerCase();
186
+ const out = [];
187
+ let i = 0;
188
+ while (i < text.length) {
189
+ // 从 i 开始最早出现的那个词
190
+ let at = -1;
191
+ let len = 0;
192
+ for (const w of words) {
193
+ const p = lower.indexOf(w, i);
194
+ if (p >= 0 && (at < 0 || p < at || (p === at && w.length > len))) {
195
+ at = p;
196
+ len = w.length;
197
+ }
198
+ }
199
+ if (at < 0) break;
200
+ if (at > i) out.push(text.slice(i, at));
201
+ out.push(h("mark", {}, text.slice(at, at + len)));
202
+ i = at + len;
203
+ }
204
+ out.push(text.slice(i));
205
+ return out;
206
+ }
@@ -44,12 +44,13 @@ export function setDraftExpert(id) {
44
44
  localStorage.setItem("aim.expert", id);
45
45
  const e = syncDraftExpert();
46
46
  if (e) localStorage.setItem("aim.agent", e.engine);
47
- // 换了专家:默认工作目录跟着专家走(没设就是工作区根目录)
48
- S.draftCwd = e?.cwd || null;
47
+ // 换了专家:默认工作目录跟着专家走(没设就是工作区根目录);自己选过目录的就不动
48
+ if (!S.draftCwdPicked) S.draftCwd = e?.cwd || null;
49
49
  }
50
50
 
51
- /** 专家的图标:自定义专家有 emoji 就用 emoji,否则用引擎的图标 */
51
+ /** 专家的图标:自定义专家上传了头像用头像,以前设过 emoji 的用 emoji,否则用引擎的图标 */
52
52
  export function expertIcon(e, cls = "agent-icon") {
53
+ if (e?.avatar) return h("span", { class: `${cls} expert-avatar` }, h("img", { src: e.avatar, alt: "", draggable: "false" }));
53
54
  if (e?.icon) return h("span", { class: `${cls} expert-emoji` }, e.icon);
54
55
  return agentIcon(e?.engine ?? e?.id, cls);
55
56
  }
@@ -24,9 +24,11 @@ import { syncDraftExpert } from "./experts.js";
24
24
  import { confirmDialog, showMenu } from "../lib/overlay.js";
25
25
  import { applyShellInfo, handleAllowEmbed, HOME, mountSwitcher, refreshShellPush, routeToServer, shellBooted, switchServer } from "../lib/shell.js";
26
26
  import { bindScrollWatch, newDraft, openConversation, scrollToBottom } from "./messages.js";
27
- import { renderComposer } from "./composer.js";
27
+ import { bindFileDrop, renderComposer } from "./composer.js";
28
+ import { openSearch } from "./conv-search.js";
28
29
  import { createNav } from "./msg-nav.js";
29
30
  import { renameConv } from "./conv-actions.js";
31
+ import { clearCommandCache, preloadCommands } from "./slash.js";
30
32
  import { releaseForeignPushSub } from "../lib/push.js";
31
33
 
32
34
  // ---------- 主界面 ----------
@@ -121,6 +123,7 @@ export function openTasksView() {
121
123
  export async function boot() {
122
124
  const me = await api("/api/me");
123
125
  if (!me.authed) return showAuth();
126
+ clearCommandCache();
124
127
  WS.stopped = false;
125
128
  WS.epoch = null;
126
129
  WS.hellos = 0;
@@ -163,6 +166,7 @@ export async function boot() {
163
166
  else if (fromHash && S.convs.has(fromHash)) await openConversation(fromHash);
164
167
  else if (latest) await openConversation(latest.key);
165
168
  else newDraft();
169
+ preloadCommands();
166
170
  // 以前的技能页地址:技能现在在设置里
167
171
  if (fromHash === "skills") openSettings("技能");
168
172
  // 点了桌面端的系统通知 / 菜单栏里的待处理项:跳到对应会话
@@ -261,8 +265,10 @@ function renderLayout() {
261
265
  h(
262
266
  "div",
263
267
  { class: "side-top" },
264
- h("button", { class: "btn new-chat", onclick: () => (newDraft(), closeSide()) }, icon("compose"), "新聊天"),
268
+ h("button", { class: "btn new-chat", onclick: () => (newDraft(), closeSide()) }, icon("plus"), "新建"),
265
269
  ),
270
+ // 搜索:弹窗里搜标题和聊天内容,可以按专家筛
271
+ h("button", { class: "btn new-chat side-nav search-nav", onclick: () => openSearch() }, icon("search"), "搜索"),
266
272
  // 「最近」上面的入口,像 ChatGPT 的 Tasks。当前在任务页时高亮(renderSidebar 里切换)
267
273
  (ui.tasksNav = h("button", { class: "btn new-chat side-nav", onclick: () => openTasksView() }, icon("clock"), "定时任务")),
268
274
  // 远程控制:这台机器的桌面和终端。后台连着时右边亮个小绿点(renderSidebar 里切换)
@@ -291,6 +297,7 @@ function renderLayout() {
291
297
  bindScrollWatch();
292
298
  ui.composerWrap = h("div", { class: "composer-wrap" });
293
299
  ui.main = h("main", { class: "main" }, ui.topbar, ui.messages, createNav(), ui.composerWrap);
300
+ bindFileDrop(ui.main);
294
301
  ui.layout = h("div", { class: "layout" }, ui.sidebar, h("div", { class: "scrim", onclick: closeSide }), ui.main);
295
302
  fill($app, ui.layout, h("div", { class: "edge-strip", "aria-hidden": "true" }));
296
303
  renderComposer();
@@ -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
  }
@@ -458,13 +462,52 @@ function clampLongUsers(items) {
458
462
  }
459
463
  }
460
464
 
461
- /** 排队中的消息下面:「排队中 · 打断并发送」;停止、会话切换后没发出去的:「没有发出」 */
465
+ async function editUserMessage(item, queued, button) {
466
+ const key = S.current;
467
+ if (!key || S.editingMessage || S.sending) return;
468
+ S.editingMessage = key;
469
+ button.disabled = true;
470
+ updateSendBtn();
471
+ try {
472
+ const result = await api(`/api/conversations/${encodeURIComponent(key)}/${queued ? "cancel-queued" : "rewind"}`, {
473
+ method: "POST",
474
+ body: { id: item.id, anchor: item.anchor, sessionId: S.convs.get(key)?.sessionId },
475
+ });
476
+ if (S.current !== key) return;
477
+ if (!queued && !result.queued) await openConversation(key);
478
+ if (S.current !== key) return;
479
+ for (const upload of S.uploads) if (upload.url) URL.revokeObjectURL(upload.url);
480
+ S.uploads = result.draft.uploads;
481
+ ui.input.value = result.draft.text;
482
+ renderChips();
483
+ ui.input.dispatchEvent(new Event("input", { bubbles: true }));
484
+ ui.input.focus();
485
+ if (result.draft.missing) toast("部分附件已被清理,请重新添加");
486
+ } catch (err) {
487
+ toast(err.message);
488
+ } finally {
489
+ S.editingMessage = null;
490
+ button.disabled = false;
491
+ updateSendBtn();
492
+ }
493
+ }
494
+
495
+ function editButton(item, queued = false) {
496
+ const label = queued ? "撤销并编辑" : "回退到此处";
497
+ return h("button", {
498
+ class: "icon-btn", title: label, "aria-label": label,
499
+ onclick: (e) => void editUserMessage(item, queued, e.currentTarget),
500
+ }, icon("undo"));
501
+ }
502
+
503
+ /** 排队中的消息可立即发送或撤销编辑;停止后没发出去的显示「没有发出」 */
462
504
  function queueNote(item, state) {
463
505
  if (state === "dropped") return h("div", { class: "queue-note dropped" }, "没有发出");
464
506
  return h(
465
507
  "div",
466
508
  { class: "queue-note" },
467
509
  h("span", { class: "shimmer" }, "排队中,等上一条回复完"),
510
+ editButton(item, true),
468
511
  h("button", { class: "queue-jump", title: "停掉正在进行的回复,马上处理这条", onclick: () => void doAction("jump", item.id) }, "打断并发送"),
469
512
  );
470
513
  }
@@ -491,9 +534,10 @@ function renderItem(item) {
491
534
  renderUserFiles(item.files),
492
535
  item.text ? (item.bubble = h("div", { class: "msg-user" }, origin ? h("span", { class: "origin" }, origin) : null, item.text)) : null,
493
536
  (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,
537
+ h("div", { class: "user-actions" },
538
+ item.text ? h("button", { class: "icon-btn", title: "复制", onclick: () => copyText(item.text) }, icon("copy")) : null,
539
+ editButton(item),
540
+ ),
497
541
  );
498
542
  }
499
543
  case "ai":
@@ -642,6 +686,21 @@ export function applyEvent(env) {
642
686
  S.seq.set(env.key, env.seq);
643
687
  const ev = env.ev;
644
688
  switch (ev.type) {
689
+ case "user_anchor": {
690
+ const item = S.items.find((it) => it.type === "user" && it.id === ev.id);
691
+ if (item) item.anchor = ev.anchor;
692
+ return;
693
+ }
694
+ case "history_reset": {
695
+ if (S.editingMessage === env.key) return;
696
+ const uploads = S.uploads;
697
+ void openConversation(env.key).then(() => {
698
+ if (S.current !== env.key) return;
699
+ S.uploads = uploads;
700
+ renderChips();
701
+ });
702
+ return;
703
+ }
645
704
  case "user": {
646
705
  // 排队的消息:正在进行的那一轮照常在上面接着输出,这条等轮到它(queue 事件)再挂占位
647
706
  const queued = !!ev.queued;
@@ -669,6 +728,14 @@ export function applyEvent(env) {
669
728
  }
670
729
  case "queue": {
671
730
  const it = S.items.find((i) => i.type === "user" && i.id === ev.id);
731
+ if (it && ev.state === "removed") {
732
+ it.el.remove();
733
+ S.items = S.items.filter((item) => item !== it);
734
+ if (ui.pinEl === it.el) ui.pinEl = null;
735
+ scheduleNav();
736
+ afterLayout();
737
+ return;
738
+ }
672
739
  if (it) setQueueState(it, ev.state === "dropped" ? "dropped" : null);
673
740
  // 轮到它了(上一轮刚出结果):挂上「思考中」占位,用时从现在算。被当成提问的回答时那一轮还在跑,不用挂
674
741
  if (ev.state === "started" && (!S.turnAi || S.turnAi.done)) {
@@ -4,7 +4,8 @@ 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;
10
11
  let entries = [];
@@ -12,11 +13,18 @@ let activeIdx = -1;
12
13
  let scheduled = false;
13
14
  let scrollRaf = 0;
14
15
  let scrollingTimer = 0;
16
+ let builtFor = null;
15
17
 
16
18
  export function createNav() {
19
+ resetScrolling();
20
+ builtFor = null;
21
+ entries = [];
17
22
  ui.navTicks = h("div", { class: "msg-nav-ticks" });
18
23
  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);
24
+ ui.nav = h("nav", { class: "msg-nav", hidden: true, "aria-label": "消息快速定位", onpointerenter: revealActiveRow, onpointerdown: markScrolling }, ui.navTicks, ui.navPanel);
25
+ ui.navTicks.addEventListener("scroll", () => {
26
+ if (ui.nav.classList.contains("scrolling")) markScrolling();
27
+ }, { passive: true });
20
28
  ui.messages.addEventListener("scroll", onScroll, { passive: true });
21
29
  return ui.nav;
22
30
  }
@@ -41,6 +49,8 @@ function snippet(item) {
41
49
  function build() {
42
50
  if (!ui.nav) return;
43
51
  const users = S.view ? [] : S.items.filter((it) => it.type === "user" && it.el?.isConnected);
52
+ if (builtFor !== S.current || users.length < MIN_USERS) resetScrolling();
53
+ builtFor = S.current;
44
54
  ui.nav.hidden = users.length < MIN_USERS;
45
55
  activeIdx = -1;
46
56
  if (ui.nav.hidden) {
@@ -73,11 +83,23 @@ function jump(item) {
73
83
  ui.messages.scrollTo({ top: Math.max(0, item.el.offsetTop - covered() - 12), behavior: "smooth" });
74
84
  }
75
85
 
76
- function onScroll() {
86
+ function resetScrolling() {
87
+ clearTimeout(scrollingTimer);
88
+ cancelAnimationFrame(scrollRaf);
89
+ scrollRaf = 0;
90
+ ui.nav?.classList.remove("scrolling");
91
+ }
92
+
93
+ function markScrolling() {
77
94
  if (!entries.length) return;
78
95
  ui.nav.classList.add("scrolling");
79
96
  clearTimeout(scrollingTimer);
80
97
  scrollingTimer = setTimeout(() => ui.nav.classList.remove("scrolling"), 1200);
98
+ }
99
+
100
+ function onScroll() {
101
+ if (!entries.length) return;
102
+ markScrolling();
81
103
  if (scrollRaf) return;
82
104
  scrollRaf = requestAnimationFrame(() => {
83
105
  scrollRaf = 0;
@@ -87,6 +109,7 @@ function onScroll() {
87
109
 
88
110
  /** 正看到的:顶部往下三分之一处以上、最后一条用户消息;已经滚到底就是最后一条 */
89
111
  function updateActive() {
112
+ if (!entries.length) return;
90
113
  const m = ui.messages;
91
114
  const line = m.scrollTop + covered() + m.clientHeight * 0.3;
92
115
  let idx = 0;
@@ -83,15 +83,18 @@ document.addEventListener("visibilitychange", () => {
83
83
  if (Date.now() - quotaState.at >= quotaInterval()) void loadQuota();
84
84
  });
85
85
 
86
- function untilText(ms) {
87
- const sec = Math.floor((ms - Date.now()) / 1000);
88
- if (sec <= 0) return "即将重置";
89
- const d = Math.floor(sec / 86400);
90
- const hh = Math.floor((sec % 86400) / 3600);
91
- const mm = Math.floor((sec % 3600) / 60);
92
- if (d > 0) return `${d} 天 ${hh} 小时后重置`;
93
- if (hh > 0) return `${hh} 小时 ${mm} 分后重置`;
94
- return `${Math.max(1, mm)} 分钟后重置`;
86
+ /** 什么时候重置(和桌面端一样):今天的只写时间(13:02 重置),明天的带「明天」,再往后带日期(11月3日 13:02 重置) */
87
+ function resetText(at) {
88
+ if (at <= Date.now()) return "即将重置";
89
+ const d = new Date(at);
90
+ const time = `${String(d.getHours()).padStart(2, "0")}:${String(d.getMinutes()).padStart(2, "0")}`;
91
+ const today = new Date();
92
+ today.setHours(0, 0, 0, 0);
93
+ const days = Math.round((new Date(d).setHours(0, 0, 0, 0) - today.getTime()) / 86400_000);
94
+ if (days <= 0) return `${time} 重置`;
95
+ if (days === 1) return `明天 ${time} 重置`;
96
+ const year = d.getFullYear() === today.getFullYear() ? "" : `${d.getFullYear()}年`;
97
+ return `${year}${d.getMonth() + 1}月${d.getDate()}日 ${time} 重置`;
95
98
  }
96
99
 
97
100
  function quotaLevel(p) {
@@ -133,7 +136,7 @@ export function renderQuota() {
133
136
  { class: "qt-row" },
134
137
  h("span", { class: "qt-name" }, w.label),
135
138
  h("span", { class: `qt-pct ${quotaLevel(w.percent)}` }, `已用 ${Math.round(w.percent)}%`),
136
- w.resetsAt ? h("span", { class: "qt-reset" }, untilText(w.resetsAt)) : null,
139
+ w.resetsAt ? h("span", { class: "qt-reset" }, resetText(w.resetsAt)) : null,
137
140
  ),
138
141
  ),
139
142
  q.extra ? h("div", { class: "qt-extra" }, q.extra) : null,