dsh-planbox-dyb 0.8.3 → 0.8.4

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.
Files changed (4) hide show
  1. package/README.md +10 -8
  2. package/client.js +426 -125
  3. package/index.js +131 -38
  4. package/package.json +1 -1
package/README.md CHANGED
@@ -22,22 +22,24 @@ dsh plugin --profile web add dsh-planbox-dyb
22
22
 
23
23
  ## 面板
24
24
 
25
- - **已登记**:你点「加入计划任务」手动登记的任务。
26
- - **异常中断**:上一回合报错或崩溃中断的会话。
27
- - **扫描到**:模型登记或从会话消息里扫到的任务。
25
+ - **手动**:你点「加入计划任务」手动登记的任务。
26
+ - **发现**:模型登记、助手结尾出现「重启」和「需要」(间隔不超过 5 个字符,且「需要」前没有「不」),或从会话消息里扫到的任务。
27
+ - **中断**:上一回合报错或崩溃中断的会话。
28
28
 
29
- 每行会标注对应的「第 N 轮」对话;同会话的手动登记和自动结果分开显示。
29
+ 同一个会话的回合放在一块,手动、发现、中断混排,按由旧到新排列。最近从计划任务点开过的会话排在最前,其余按任务更新时间排序。手动登记同一回合后,该回合的发现或中断记录让位,显示为手动。
30
+
31
+ 每行会标注对应的「第 N 轮」对话;同会话的手动登记和发现结果分开显示。手动登记会记下你点的是哪一轮,之后从这一轮开头查看。
30
32
 
31
33
  按钮:
32
34
 
33
35
  - **建议**:把续跑建议填进输入框,不发送;输入框已有内容会先确认是否从下一行追加。
34
- - **查看**:跳到对应会话,不关闭面板,并把该任务置顶;会提示打开的是第几轮对话。
36
+ - **详情**:在当前行展开完整说明、下一步和校验信息;点整行仍跳到对应会话;行内保留「第 N 轮」锚点。跳转期间行内标签旁显示「跳转中…」,完成或超时后消失。
35
37
  - **忽略**:删除这一条;扫描/异常项会隐藏到该会话下次更新。
36
- - **全部忽略**:确认后清空当前列表。
37
- - **中断恢复**:只处理「异常中断」,每项发一句「继续」;发送成功后记录删除,不跟踪后续进度。
38
+ - **全部忽略**:确认后清空当前列表;点确认框以外的位置会取消确认。
39
+ - **中断恢复**:只处理「中断」,每项发一句「继续」;发送成功后记录删除,不跟踪后续进度。
38
40
 
39
41
  ## 注意
40
42
 
41
43
  - 只支持 DSH Web;headless 没有面板。
42
44
  - 不自动续跑、不跟踪任务是否完成,进度需要你自己看会话。
43
- - 可以和自动续跑插件共存;已被自动续跑的会话会从「异常中断」消失,「中断恢复」投递前也会复核,不会重复发。
45
+ - 可以和自动续跑插件共存;已被自动续跑的会话会从「中断」消失,「中断恢复」投递前也会复核,不会重复发。
package/client.js CHANGED
@@ -15,7 +15,7 @@ window.__ModuleLoader__.load({
15
15
  const NS = "planbox";
16
16
  const API = "/api/planbox";
17
17
  const POLL_MS = 60_000;
18
- const CLIENT_VERSION = "0.8.3";
18
+ const CLIENT_VERSION = "0.8.4";
19
19
 
20
20
  const FALLBACK = {
21
21
  open: "计划任务",
@@ -24,20 +24,22 @@ window.__ModuleLoader__.load({
24
24
  refresh: "重新扫描",
25
25
  empty: "没有发现计划任务。在会话里说“重启后继续”,或点回答下方的「加入计划任务」登记。",
26
26
  hint: "扫描会话中…",
27
- queueTag: "已登记",
28
- scanTag: "扫描到",
29
- abnormalTag: "异常中断",
30
- registeredSection: "已登记({n})",
31
- abnormalSection: "异常中断({n})",
32
- pinnedSection: "正在查看",
33
- scannedSection: "扫描到({n})",
27
+ queueTag: "手动",
28
+ scanTag: "发现",
29
+ abnormalTag: "中断",
30
+ registeredSection: "手动({n})",
31
+ abnormalSection: "中断({n})",
32
+ pinnedSection: "当前详情",
33
+ scannedSection: "发现({n})",
34
+ sessionCount: "{n} 条",
34
35
  running: "运行中",
35
36
  anchorTurn: "第 {turn} 轮",
36
37
  anchorTurnSeq: "第 {turn} 轮 · #{seq}",
37
38
  anchorSeq: "消息 #{seq}",
38
- viewAnchor: "已打开:{label}",
39
+ jumping: "跳转中",
39
40
  resume: "继续",
40
- view: "查看",
41
+ view: "详情",
42
+ detailEmpty: "无更多详情",
41
43
  resumeAll: "中断恢复",
42
44
  ignoreAll: "全部忽略",
43
45
  ignoreAllConfirm: "确定忽略全部 {n} 项?扫描/中断项会写入忽略记录。",
@@ -65,8 +67,6 @@ window.__ModuleLoader__.load({
65
67
  fillAppendText: "是否从下一行开始填入建议?",
66
68
  fillOk: "确定",
67
69
  fillCancel: "取消",
68
- fillDone: "已填入建议",
69
- fillCopied: "无法直接填入,已复制到剪贴板",
70
70
  fillFailed: "填入失败:{message}",
71
71
  };
72
72
 
@@ -80,20 +80,22 @@ window.__ModuleLoader__.load({
80
80
  empty:
81
81
  "No pending tasks found. Say “continue after restart” in a session, or use “Add to pending” under a reply.",
82
82
  hint: "Scanning sessions…",
83
- queueTag: "Registered",
83
+ queueTag: "Manual",
84
84
  scanTag: "Found",
85
- abnormalTag: "Abnormally interrupted",
86
- registeredSection: "Registered ({n})",
87
- abnormalSection: "Abnormally interrupted ({n})",
85
+ abnormalTag: "Interrupted",
86
+ registeredSection: "Manual ({n})",
87
+ abnormalSection: "Interrupted ({n})",
88
88
  pinnedSection: "Viewing",
89
- scannedSection: "Scanned ({n})",
89
+ scannedSection: "Found ({n})",
90
+ sessionCount: "{n} items",
90
91
  running: "Running",
91
92
  anchorTurn: "Turn {turn}",
92
93
  anchorTurnSeq: "Turn {turn} · #{seq}",
93
94
  anchorSeq: "Message #{seq}",
94
- viewAnchor: "Opened: {label}",
95
+ jumping: "Jumping",
95
96
  resume: "Resume",
96
- view: "View",
97
+ view: "Details",
98
+ detailEmpty: "No more details",
97
99
  resumeAll: "Restore interrupted",
98
100
  ignoreAll: "Ignore all",
99
101
  ignoreAllConfirm: "Ignore all {n}? Scanned and interrupted items will be hidden.",
@@ -121,8 +123,6 @@ window.__ModuleLoader__.load({
121
123
  fillAppendText: "Append the suggestion below the existing text?",
122
124
  fillOk: "Append",
123
125
  fillCancel: "Cancel",
124
- fillDone: "Suggestion filled",
125
- fillCopied: "Copied to clipboard instead",
126
126
  fillFailed: "Fill failed: {message}",
127
127
  };
128
128
 
@@ -219,9 +219,6 @@ window.__ModuleLoader__.load({
219
219
  ".dpb-tail-btn[data-state=\"error\"]{color:#ff9a9d;border-color:rgba(255,154,157,.5)}",
220
220
  ".dpb-badge{position:absolute;top:-4px;right:-4px;min-width:15px;height:15px;padding:0 4px;border-radius:999px;background:#e5484d;color:#fff;font-size:10px;line-height:15px;text-align:center;font-variant-numeric:tabular-nums;box-shadow:0 0 0 2px var(--dsw-alias-bg-layer-1,#1e1e1f)}",
221
221
  ".dpb-backdrop{position:fixed;inset:0;background:transparent;z-index:79}",
222
- ".dpb-toast{position:fixed;left:12px;bottom:100px;z-index:81;padding:7px 10px;border-radius:8px;background:var(--dsw-alias-bg-layer-1,#1e1e1f);border:1px solid var(--dsw-elevation-stroke-color,rgba(255,255,255,.12));box-shadow:0 8px 24px rgba(0,0,0,.35);font-size:12px;color:var(--dsw-alias-label-primary,#e8eaed)}",
223
- ".dpb-toast.ok{color:#8fd18f}",
224
- ".dpb-toast.bad{color:#ff9a9d}",
225
222
  ".dpb-modal-backdrop{position:fixed;inset:0;z-index:90;display:flex;align-items:center;justify-content:center;background:rgba(0,0,0,.45)}",
226
223
  ".dpb-modal{width:min(360px,calc(100vw - 40px));padding:16px 18px 12px;border-radius:12px;background:var(--dsw-alias-bg-layer-1,#1e1e1f);border:1px solid var(--dsw-elevation-stroke-color,rgba(255,255,255,.14));box-shadow:0 18px 46px rgba(0,0,0,.5);color:var(--dsw-alias-label-primary,#e8eaed);font-size:13px;box-sizing:border-box}",
227
224
  ".dpb-modal-title{font-weight:600;margin-bottom:6px}",
@@ -257,12 +254,24 @@ window.__ModuleLoader__.load({
257
254
  ".dpb-tag.queue{background:rgba(76,141,255,.18);color:#9dbcff}",
258
255
  ".dpb-tag.abnormal{background:rgba(229,72,77,.16);color:#ff9a9d}",
259
256
  ".dpb-tag.scan{background:rgba(255,196,0,.16);color:#e7c063}",
257
+ ".dpb-jumping{flex:none;display:inline-flex;align-items:center;gap:3px;font-size:10px;line-height:15px;color:var(--dsw-alias-state-business-primary,#4c8dff)}",
258
+ ".dpb-dots{display:inline-flex;gap:1px}",
259
+ ".dpb-dots i{width:2px;height:2px;border-radius:50%;background:currentColor;animation:dpb-jumping-dot 1.1s infinite ease-in-out}",
260
+ ".dpb-dots i:nth-child(2){animation-delay:.18s}",
261
+ ".dpb-dots i:nth-child(3){animation-delay:.36s}",
262
+ "@keyframes dpb-jumping-dot{0%,80%,100%{opacity:.2}40%{opacity:1}}",
260
263
  ".dpb-section{padding:9px 9px 3px;font-size:10.5px;line-height:15px;letter-spacing:.03em;color:var(--dsw-alias-label-tertiary,#8b8f95)}",
264
+ ".dpb-session{margin:0 0 6px;padding:0 4px 4px;border-left:2px solid var(--dsw-alias-border-secondary,rgba(255,255,255,.08))}",
265
+ ".dpb-session-head{display:flex;align-items:center;gap:6px;padding:5px 5px 3px;font-size:10.5px;line-height:15px;color:var(--dsw-alias-label-secondary,#b6bac0)}",
266
+ ".dpb-session-title{min-width:0;flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-weight:600}",
267
+ ".dpb-session-count{flex:none;color:var(--dsw-alias-label-tertiary,#8b8f95);font-variant-numeric:tabular-nums}",
261
268
  ".dpb-section-pinned{color:var(--dsw-alias-state-business-primary,#4c8dff);font-weight:600}",
262
269
  ".dpb-section-abnormal{color:#ff9a9d}",
263
270
  ".dpb-next{font-size:11px;line-height:16px;color:#9dbcff;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}",
264
271
  ".dpb-snippet{font-size:11.5px;line-height:17px;color:var(--dsw-alias-label-secondary,#b6bac0);display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden;overflow-wrap:anywhere}",
265
272
  ".dpb-meta{display:flex;align-items:center;gap:5px;font-size:10.5px;line-height:15px;color:var(--dsw-alias-label-tertiary,#8b8f95);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}",
273
+ ".dpb-detail{margin-top:7px;padding:8px 9px;border-radius:8px;background:rgba(128,128,128,.1);font-size:11.5px;line-height:18px;color:var(--dsw-alias-label-secondary,#b6bac0);white-space:pre-wrap;word-break:break-word;max-height:260px;overflow:auto;cursor:text}",
274
+ ".dpb-detail-anchor{margin-top:6px;color:var(--dsw-alias-label-tertiary,#8b8f95);font-size:10.5px}",
266
275
  ".dpb-anchor{flex:none;color:var(--dsw-alias-state-business-primary,#4c8dff)}",
267
276
  ".dpb-dot{opacity:.6}",
268
277
  ".dpb-row-actions{flex:none;display:flex;align-items:center;gap:2px}",
@@ -340,13 +349,74 @@ window.__ModuleLoader__.load({
340
349
  });
341
350
  }
342
351
  // 会话切换可能导致组件的宿主重新挂载;把面板开关和置顶项记在模块级,避免“查看”后面板消失。
343
- const panelState = { open: false, pinnedId: null };
352
+ const panelState = { open: false, pinnedId: null, jumpingId: null };
353
+ const RECENT_KEY = "dsh-planbox-dyb:recent-sessions";
344
354
 
345
- function tagFor(item) {
346
- if (item.source === "abnormal") return { key: "abnormalTag", className: "abnormal" };
347
- if (item.source === "queue" && item.origin !== "model") {
348
- return { key: "queueTag", className: "queue" };
355
+ function readRecentSessions() {
356
+ const recent = new Map();
357
+ try {
358
+ const raw = globalThis.localStorage?.getItem(RECENT_KEY);
359
+ if (typeof raw !== "string" || raw === "") return recent;
360
+ const parsed = JSON.parse(raw);
361
+ for (const [sessionId, at] of Object.entries(parsed ?? {})) {
362
+ const value = Number(at);
363
+ if (typeof sessionId === "string" && Number.isFinite(value)) recent.set(sessionId, value);
364
+ }
365
+ } catch {
366
+ /* 读取失败就按内存顺序 */
349
367
  }
368
+ return recent;
369
+ }
370
+
371
+ const recentSessions = readRecentSessions();
372
+
373
+ function markSessionOpened(sessionId) {
374
+ if (typeof sessionId !== "string" || sessionId === "") return;
375
+ recentSessions.set(sessionId, Date.now());
376
+ try {
377
+ globalThis.localStorage?.setItem(
378
+ RECENT_KEY,
379
+ JSON.stringify(Object.fromEntries(recentSessions)),
380
+ );
381
+ } catch {
382
+ /* 存不下就只保留内存顺序 */
383
+ }
384
+ }
385
+
386
+ function emitJumping() {
387
+ if (
388
+ typeof window !== "undefined" &&
389
+ typeof window.dispatchEvent === "function" &&
390
+ typeof CustomEvent !== "undefined"
391
+ ) {
392
+ window.dispatchEvent(new CustomEvent("dsh-planbox-dyb:jumping"));
393
+ }
394
+ }
395
+
396
+ function setJumping(id) {
397
+ panelState.jumpingId = id;
398
+ emitJumping();
399
+ }
400
+
401
+ function finishJump(id) {
402
+ if (panelState.jumpingId !== id) return;
403
+ panelState.jumpingId = null;
404
+ emitJumping();
405
+ }
406
+
407
+ function kindOfItem(item) {
408
+ if (item?.kind === "manual" || item?.kind === "auto" || item?.kind === "interrupted") {
409
+ return item.kind;
410
+ }
411
+ if (item?.source === "abnormal") return "interrupted";
412
+ if (item?.source === "queue" && item?.origin !== "model") return "manual";
413
+ return "auto";
414
+ }
415
+
416
+ function tagFor(item) {
417
+ const kind = kindOfItem(item);
418
+ if (kind === "interrupted") return { key: "abnormalTag", className: "abnormal" };
419
+ if (kind === "manual") return { key: "queueTag", className: "queue" };
350
420
  return { key: "scanTag", className: "scan" };
351
421
  }
352
422
 
@@ -381,8 +451,141 @@ window.__ModuleLoader__.load({
381
451
  return "";
382
452
  }
383
453
 
454
+ /** 已渲染时滚到回合开头:从 turn-tail 往前找到上一回合边界后的第一个节点。 */
455
+ function scrollTurnStart(turn, root = document) {
456
+ const scope = root ?? document;
457
+ const tail = scope.querySelector?.(`[data-turn-tail="${turn}"]`);
458
+ if (tail === null || tail === undefined) return false;
459
+ let first = tail;
460
+ let node = tail;
461
+ while (node.previousElementSibling !== null) {
462
+ const previous = node.previousElementSibling;
463
+ if (previous.matches?.("[data-turn-tail]")) break;
464
+ first = previous;
465
+ node = previous;
466
+ }
467
+ first.scrollIntoView({ block: "start", behavior: "auto" });
468
+ return true;
469
+ }
470
+
471
+ /** 回合导航是虚拟列表;目标回合不在可视区时先滚动导航轨,再点它的按钮。 */
472
+ function nudgeTurnRail(root, turn) {
473
+ const buttons = [...root.querySelectorAll("button[data-index][aria-label]")];
474
+ if (buttons.length === 0) return false;
475
+ let scroller = buttons[0].parentElement;
476
+ while (scroller !== null) {
477
+ const overflow =
478
+ typeof getComputedStyle === "function"
479
+ ? getComputedStyle(scroller).overflowY
480
+ : scroller.style.overflowY;
481
+ if (
482
+ scroller.scrollHeight > scroller.clientHeight &&
483
+ (overflow === "auto" || overflow === "scroll")
484
+ ) {
485
+ break;
486
+ }
487
+ scroller = scroller.parentElement;
488
+ }
489
+ if (scroller === null || scroller.clientHeight === 0) return false;
490
+ let offset = null;
491
+ for (const button of buttons) {
492
+ const label = button.getAttribute("aria-label") || "";
493
+ const labelTurn = /第\s*(\d+)\s*轮/.exec(label) ?? /turn\s+(\d+)/i.exec(label);
494
+ const index = Number(button.getAttribute("data-index"));
495
+ if (labelTurn !== null && Number.isFinite(index)) {
496
+ offset = Number(labelTurn[1]) - index;
497
+ break;
498
+ }
499
+ }
500
+ if (offset === null) return false;
501
+ const targetIndex = turn - offset;
502
+ const targetTop = Math.max(
503
+ 0,
504
+ Math.min(
505
+ scroller.scrollHeight - scroller.clientHeight,
506
+ targetIndex * 10 + 6 - scroller.clientHeight / 2,
507
+ ),
508
+ );
509
+ scroller.scrollTop = targetTop;
510
+ return true;
511
+ }
512
+
513
+ /** 打开会话后尽量定位到锚点回合开头;只在新会话挂载后操作,避免误点旧会话的导航。 */
514
+ function revealTurn(turn, sessionId, onDone) {
515
+ let settled = false;
516
+ const done = () => {
517
+ if (settled) return;
518
+ settled = true;
519
+ if (typeof onDone === "function") onDone();
520
+ };
521
+ if (!(turn > 0) || typeof document === "undefined") {
522
+ done();
523
+ return;
524
+ }
525
+ let attempts = 0;
526
+ let railNudged = false;
527
+ const tick = () => {
528
+ if (settled) return;
529
+ const matches = sessionId
530
+ ? document.querySelectorAll(`[data-conversation-session="${sessionId}"]`)
531
+ : [];
532
+ const root = sessionId
533
+ ? [...matches].find(
534
+ (element) =>
535
+ element.querySelector("[data-turn-tail], button[data-index]") !== null,
536
+ ) ?? null
537
+ : document;
538
+ if (sessionId && root === null) {
539
+ attempts += 1;
540
+ if (attempts < 200) globalThis.setTimeout(tick, 120);
541
+ else done();
542
+ return;
543
+ }
544
+ const buttons = root.querySelectorAll("button[data-index][aria-label]");
545
+ for (const button of buttons) {
546
+ if (button.disabled || button.getAttribute("aria-busy") === "true") continue;
547
+ const label = button.getAttribute("aria-label") || "";
548
+ if (
549
+ label.includes(`第 ${turn} 轮`) ||
550
+ new RegExp(`\\bturn ${turn}\\b`, "i").test(label)
551
+ ) {
552
+ button.click();
553
+ // 按钮触发的是 DSH 自己的加载/滚动,留一点时间让指示器覆盖这段等待。
554
+ globalThis.setTimeout(done, 1_200);
555
+ return;
556
+ }
557
+ }
558
+ if (!railNudged && nudgeTurnRail(root, turn)) {
559
+ railNudged = true;
560
+ attempts += 1;
561
+ globalThis.setTimeout(tick, 180);
562
+ return;
563
+ }
564
+ if (scrollTurnStart(turn, root)) {
565
+ done();
566
+ return;
567
+ }
568
+ attempts += 1;
569
+ if (attempts < 200) globalThis.setTimeout(tick, 120);
570
+ else done();
571
+ };
572
+ globalThis.setTimeout(tick, 180);
573
+ }
574
+
384
575
  function Row(props) {
385
- const { item, t, busy, pinned, onOpen, onDismiss, onSuggest } = props;
576
+ const {
577
+ item,
578
+ t,
579
+ busy,
580
+ pinned,
581
+ hideTitle,
582
+ jumping,
583
+ expanded = false,
584
+ onOpen,
585
+ onDismiss,
586
+ onSuggest,
587
+ onDetail,
588
+ } = props;
386
589
  const queue = item.source === "queue";
387
590
  const tag = tagFor(item);
388
591
  const detail = queue ? item.snippet || item.prompt : item.snippet;
@@ -392,9 +595,22 @@ window.__ModuleLoader__.load({
392
595
  anchor === "" || !item.anchor?.at
393
596
  ? anchor
394
597
  : `${anchor} · ${new Date(item.anchor.at).toLocaleString()}`;
395
- // 整行可点:和「查看」同一条路径(跳转 + 置顶),行内按钮自己 stopPropagation。
396
- const open = () => onOpen(item.sessionId, item.id, item.anchor);
397
598
  const next = nextStep(item);
599
+ const detailParts = [];
600
+ if (full !== "") detailParts.push(full);
601
+ if (next !== null) detailParts.push(next.full);
602
+ if (item.snapshot?.filesTouched?.length) {
603
+ detailParts.push(`涉及文件:\n${item.snapshot.filesTouched.join("\n")}`);
604
+ }
605
+ if (item.snapshot?.verifyCommand) detailParts.push(`验证:${item.snapshot.verifyCommand}`);
606
+ if (item.snapshot?.lastFailedCommand) {
607
+ detailParts.push(`上次失败:${item.snapshot.lastFailedCommand}`);
608
+ }
609
+ const detailText = detailParts.join("\n\n");
610
+ const toggle = () => {
611
+ if (typeof onDetail === "function") onDetail(item);
612
+ };
613
+ const open = () => onOpen(item.sessionId, item.id, item.anchor);
398
614
  return h(
399
615
  "div",
400
616
  {
@@ -416,23 +632,46 @@ window.__ModuleLoader__.load({
416
632
  h(
417
633
  "div",
418
634
  { className: "dpb-row-head" },
419
- h("span", { className: "dpb-title", title: item.title }, item.title),
635
+ hideTitle ? null : h("span", { className: "dpb-title" }, item.title),
420
636
  h("span", { className: "dpb-tag " + tag.className }, t(tag.key)),
637
+ jumping
638
+ ? h(
639
+ "span",
640
+ { className: "dpb-jumping", "aria-live": "polite" },
641
+ t("jumping"),
642
+ h(
643
+ "span",
644
+ { className: "dpb-dots", "aria-hidden": "true" },
645
+ h("i", null),
646
+ h("i", null),
647
+ h("i", null),
648
+ ),
649
+ )
650
+ : null,
421
651
  ),
422
- detail
423
- ? h("div", { className: "dpb-snippet", title: full || detail }, detail)
424
- : null,
425
- next ? h("div", { className: "dpb-next", title: next.full }, next.text) : null,
652
+ detail ? h("div", { className: "dpb-snippet" }, detail) : null,
653
+ next ? h("div", { className: "dpb-next" }, next.text) : null,
426
654
  h(
427
655
  "div",
428
656
  { className: "dpb-meta" },
429
- anchor !== ""
430
- ? h("span", { className: "dpb-anchor", title: anchorTitle }, anchor)
431
- : null,
657
+ anchor !== "" ? h("span", { className: "dpb-anchor" }, anchor) : null,
432
658
  h("span", null, ago(t, item.updatedAt)),
433
659
  item.running ? h("span", { className: "dpb-dot" }, "·") : null,
434
660
  item.running ? h("span", null, t("running")) : null,
435
661
  ),
662
+ expanded
663
+ ? h(
664
+ "div",
665
+ {
666
+ className: "dpb-detail",
667
+ onClick: (event) => event.stopPropagation(),
668
+ },
669
+ h("div", { className: "dpb-detail-text" }, detailText === "" ? t("detailEmpty") : detailText),
670
+ anchorTitle !== ""
671
+ ? h("div", { className: "dpb-detail-anchor" }, anchorTitle)
672
+ : null,
673
+ )
674
+ : null,
436
675
  ),
437
676
  h(
438
677
  "div",
@@ -461,7 +700,7 @@ window.__ModuleLoader__.load({
461
700
  "aria-label": t("view"),
462
701
  onClick: (event) => {
463
702
  event.stopPropagation();
464
- onOpen(item.sessionId, item.id, item.anchor);
703
+ toggle();
465
704
  },
466
705
  },
467
706
  t("view"),
@@ -487,32 +726,76 @@ window.__ModuleLoader__.load({
487
726
 
488
727
  /** 「中断恢复」只处理异常中断项。 */
489
728
  function restorableItems(items) {
490
- return items.filter((item) => item.source === "abnormal");
729
+ return items.filter((item) => kindOfItem(item) === "interrupted");
491
730
  }
492
731
 
493
- function groupPending(items) {
494
- return {
495
- registered: items.filter((item) => item.source === "queue" && item.origin !== "model"),
496
- abnormal: items.filter((item) => item.source === "abnormal"),
497
- scanned: items.filter((item) =>
498
- item.source === "queue" ? item.origin === "model" : item.source !== "abnormal",
499
- ),
500
- };
732
+ /** 按会话聚合,手动/发现/中断混排;最近点开过的会话优先,其余按任务最近更新。 */
733
+ function groupSessions(items, recent = recentSessions) {
734
+ const groups = new Map();
735
+ for (const item of items) {
736
+ const key = item.sessionId ?? "";
737
+ const group = groups.get(key);
738
+ if (group === undefined) groups.set(key, [item]);
739
+ else group.push(item);
740
+ }
741
+ const latest = (group) => Math.max(...group.map((item) => Number(item.updatedAt ?? 0)));
742
+ return [...groups.entries()]
743
+ .map(([sessionId, group]) => ({
744
+ sessionId,
745
+ title: String(group[0]?.title ?? ""),
746
+ openedAt: Number(recent?.get(sessionId) ?? 0),
747
+ items: group.sort(
748
+ (left, right) =>
749
+ Number(left.anchor?.turn ?? 0) - Number(right.anchor?.turn ?? 0) ||
750
+ Number(left.anchor?.at ?? left.updatedAt ?? 0) -
751
+ Number(right.anchor?.at ?? right.updatedAt ?? 0) ||
752
+ Number(left.updatedAt ?? 0) - Number(right.updatedAt ?? 0),
753
+ ),
754
+ }))
755
+ .sort(
756
+ (left, right) =>
757
+ (right.openedAt || latest(right.items)) - (left.openedAt || latest(left.items)),
758
+ );
501
759
  }
502
760
 
503
- /** 把正在查看的任务单独置顶,其余仍按已登记/异常中断/扫描到分区。 */
761
+ /** 把正在查看的任务单独置顶,其余按会话聚合。 */
504
762
  function orderPending(items, pinnedId) {
505
763
  const pinned = items.find((item) => item.id === pinnedId) ?? null;
506
764
  const rest = pinned === null ? items : items.filter((item) => item.id !== pinnedId);
507
- return { pinned, ...groupPending(rest) };
765
+ return { pinned, sessions: groupSessions(rest) };
508
766
  }
509
767
 
510
768
  function Panel(props) {
511
- const { t, items, loading, busy, busyAction, error, result, pinnedId, onClose, onRefresh, onResume, onOpen, onDismiss, onSuggest, onDismissAll } = props;
769
+ const { t, items, loading, busy, busyAction, error, result, pinnedId, jumpingId, onClose, onRefresh, onResume, onOpen, onDismiss, onSuggest, onDismissAll } = props;
512
770
  const [confirmDismiss, setConfirmDismiss] = React.useState(false);
771
+ const [detailId, setDetailId] = React.useState(null);
772
+ const confirmRef = React.useRef(null);
773
+ const ignoreAllRef = React.useRef(null);
513
774
  // 「中断恢复」只处理异常中断项,其余任务由用户自己审核。
514
775
  const interrupted = restorableItems(items);
515
776
 
777
+ React.useEffect(() => {
778
+ if (detailId !== null && !items.some((item) => item.id === detailId)) {
779
+ setDetailId(null);
780
+ }
781
+ }, [detailId, items]);
782
+
783
+ const toggleDetail = React.useCallback((item) => {
784
+ setDetailId((current) => (current === item.id ? null : item.id));
785
+ }, []);
786
+
787
+ React.useEffect(() => {
788
+ if (!confirmDismiss) return undefined;
789
+ const onPointerDown = (event) => {
790
+ const target = event.target;
791
+ if (confirmRef.current?.contains(target)) return;
792
+ if (ignoreAllRef.current?.contains(target)) return;
793
+ setConfirmDismiss(false);
794
+ };
795
+ document.addEventListener("pointerdown", onPointerDown, true);
796
+ return () => document.removeEventListener("pointerdown", onPointerDown, true);
797
+ }, [confirmDismiss]);
798
+
516
799
  React.useEffect(() => {
517
800
  const onKeyDown = (event) => {
518
801
  if (event.key !== "Escape") return;
@@ -530,7 +813,7 @@ window.__ModuleLoader__.load({
530
813
  } else if (items.length === 0) {
531
814
  body = h("div", { className: "dpb-hint" }, t("empty"));
532
815
  } else {
533
- const { pinned, registered, abnormal, scanned } = orderPending(items, pinnedId);
816
+ const { pinned, sessions } = orderPending(items, pinnedId);
534
817
  const nodes = [];
535
818
  if (pinned !== null) {
536
819
  nodes.push(
@@ -541,50 +824,55 @@ window.__ModuleLoader__.load({
541
824
  ),
542
825
  );
543
826
  nodes.push(
544
- h(Row, { key: pinned.id, item: pinned, t, busy, pinned: true, onOpen, onDismiss, onSuggest }),
545
- );
546
- }
547
- if (registered.length > 0) {
548
- nodes.push(
549
- h(
550
- "div",
551
- { className: "dpb-section", key: "section-registered" },
552
- t("registeredSection", { n: registered.length }),
553
- ),
827
+ h(Row, {
828
+ key: pinned.id,
829
+ item: pinned,
830
+ t,
831
+ busy,
832
+ pinned: true,
833
+ jumping: jumpingId === pinned.id,
834
+ expanded: detailId === pinned.id,
835
+ onOpen,
836
+ onDismiss,
837
+ onSuggest,
838
+ onDetail: toggleDetail,
839
+ }),
554
840
  );
555
- for (const item of registered) {
556
- nodes.push(
557
- h(Row, { key: item.id, item, t, busy, onOpen, onDismiss, onSuggest }),
558
- );
559
- }
560
841
  }
561
- if (abnormal.length > 0) {
562
- nodes.push(
842
+ for (let index = 0; index < sessions.length; index += 1) {
843
+ const group = sessions[index];
844
+ const groupNodes = [
563
845
  h(
564
846
  "div",
565
- { className: "dpb-section dpb-section-abnormal", key: "section-abnormal" },
566
- t("abnormalSection", { n: abnormal.length }),
847
+ { className: "dpb-session-head", key: "head" },
848
+ h("span", { className: "dpb-session-title" }, group.title === "" ? t("title") : group.title),
849
+ h("span", { className: "dpb-session-count" }, t("sessionCount", { n: group.items.length })),
567
850
  ),
568
- );
569
- for (const item of abnormal) {
570
- nodes.push(
571
- h(Row, { key: item.id, item, t, busy, onOpen, onDismiss, onSuggest }),
851
+ ];
852
+ for (const item of group.items) {
853
+ groupNodes.push(
854
+ h(Row, {
855
+ key: item.id,
856
+ item,
857
+ t,
858
+ busy,
859
+ hideTitle: true,
860
+ jumping: jumpingId === item.id,
861
+ expanded: detailId === item.id,
862
+ onOpen,
863
+ onDismiss,
864
+ onSuggest,
865
+ onDetail: toggleDetail,
866
+ }),
572
867
  );
573
868
  }
574
- }
575
- if (scanned.length > 0) {
576
869
  nodes.push(
577
870
  h(
578
871
  "div",
579
- { className: "dpb-section", key: "section-scanned" },
580
- t("scannedSection", { n: scanned.length }),
872
+ { className: "dpb-session", key: `session-${index}` },
873
+ groupNodes,
581
874
  ),
582
875
  );
583
- for (const item of scanned) {
584
- nodes.push(
585
- h(Row, { key: item.id, item, t, busy, onOpen, onDismiss, onSuggest }),
586
- );
587
- }
588
876
  }
589
877
  body = nodes;
590
878
  }
@@ -643,7 +931,7 @@ window.__ModuleLoader__.load({
643
931
  confirmDismiss
644
932
  ? h(
645
933
  "div",
646
- { className: "dpb-confirm" },
934
+ { className: "dpb-confirm", ref: confirmRef },
647
935
  h("span", { className: "dpb-confirm-text" }, t("ignoreAllConfirm", { n: items.length })),
648
936
  h(
649
937
  "button",
@@ -680,6 +968,7 @@ window.__ModuleLoader__.load({
680
968
  {
681
969
  type: "button",
682
970
  className: "dpb-secondary",
971
+ ref: ignoreAllRef,
683
972
  disabled: busy || items.length === 0,
684
973
  onClick: () => setConfirmDismiss(true),
685
974
  },
@@ -714,9 +1003,10 @@ window.__ModuleLoader__.load({
714
1003
  const [error, setError] = React.useState(null);
715
1004
  const [result, setResult] = React.useState(null);
716
1005
  const [pinnedId, setPinnedId] = React.useState(panelState.pinnedId);
717
- // 「建议」:pendingFill 非空时弹确认框;fillNotice 是短暂的操作反馈。
1006
+ // 「建议」:pendingFill 非空时弹确认框。
718
1007
  const [pendingFill, setPendingFill] = React.useState(null);
719
- const [fillNotice, setFillNotice] = React.useState(null);
1008
+ const [jumpingId, setJumpingState] = React.useState(panelState.jumpingId);
1009
+ const [, bumpRecent] = React.useState(0);
720
1010
  const loadSeq = React.useRef(0);
721
1011
  const busyRef = React.useRef(false);
722
1012
 
@@ -728,11 +1018,29 @@ window.__ModuleLoader__.load({
728
1018
  panelState.pinnedId = pinnedId;
729
1019
  }, [pinnedId]);
730
1020
 
1021
+ React.useEffect(() => {
1022
+ const syncJumping = () => setJumpingState(panelState.jumpingId);
1023
+ window.addEventListener("dsh-planbox-dyb:jumping", syncJumping);
1024
+ return () => window.removeEventListener("dsh-planbox-dyb:jumping", syncJumping);
1025
+ }, []);
1026
+
1027
+ const markJumping = React.useCallback((id) => {
1028
+ panelState.jumpingId = id;
1029
+ setJumpingState(id);
1030
+ emitJumping();
1031
+ }, []);
1032
+
1033
+ const clearJumping = React.useCallback((id) => {
1034
+ finishJump(id);
1035
+ }, []);
1036
+
731
1037
  const closePanel = React.useCallback(() => {
732
1038
  panelState.open = false;
733
1039
  panelState.pinnedId = null;
1040
+ panelState.jumpingId = null;
734
1041
  setOpen(false);
735
1042
  setPinnedId(null);
1043
+ setJumpingState(null);
736
1044
  }, []);
737
1045
 
738
1046
  const muted = React.useRef(false);
@@ -887,14 +1195,14 @@ window.__ModuleLoader__.load({
887
1195
 
888
1196
  const openSession = React.useCallback(
889
1197
  (sessionId, itemId, anchor) => {
1198
+ // 最近点开过的会话排到最前;切换可能导致组件重挂载,顺序也写进模块级缓存。
1199
+ markSessionOpened(sessionId);
1200
+ bumpRecent((value) => value + 1);
890
1201
  // 会话切换可能让组件重挂载,先把“面板开着 + 看的是哪条”同步写进模块状态。
891
1202
  panelState.open = true;
892
1203
  panelState.pinnedId = itemId ?? null;
893
1204
  setPinnedId(itemId ?? null);
894
- const label = anchorText(t, { anchor });
895
- if (label !== "") {
896
- setFillNotice({ bad: false, text: t("viewAnchor", { label }) });
897
- }
1205
+ if (itemId !== null && itemId !== undefined) markJumping(itemId);
898
1206
  let workspace = null;
899
1207
  try {
900
1208
  workspace = pluginCtx?.get?.("uiWorkspace") ?? null;
@@ -904,26 +1212,25 @@ window.__ModuleLoader__.load({
904
1212
  if (workspace !== null && typeof workspace.openSession === "function") {
905
1213
  try {
906
1214
  workspace.openSession(sessionId);
1215
+ revealTurn(anchor?.turn, sessionId, () => {
1216
+ if (itemId !== null && itemId !== undefined) clearJumping(itemId);
1217
+ });
907
1218
  return;
908
1219
  } catch (cause) {
909
1220
  /* 回退到 URL 跳转 */
910
1221
  }
911
1222
  }
1223
+ if (itemId !== null && itemId !== undefined) clearJumping(itemId);
912
1224
  window.location.assign(`/?session=${encodeURIComponent(sessionId)}`);
913
1225
  },
914
- [t],
1226
+ [t, markJumping, clearJumping],
915
1227
  );
916
-
917
1228
  const copySuggestion = React.useCallback(
918
1229
  async (text) => {
919
1230
  try {
920
1231
  await navigator.clipboard.writeText(text);
921
- setFillNotice({ bad: false, text: t("fillCopied") });
922
1232
  } catch (cause) {
923
- setFillNotice({
924
- bad: true,
925
- text: t("fillFailed", { message: String(cause?.message ?? cause) }),
926
- });
1233
+ setError(t("fillFailed", { message: String(cause?.message ?? cause) }));
927
1234
  }
928
1235
  },
929
1236
  [t],
@@ -942,6 +1249,8 @@ window.__ModuleLoader__.load({
942
1249
  const workspace = clientService("uiWorkspace");
943
1250
  if (workspace && typeof workspace.openSession === "function") {
944
1251
  try {
1252
+ markSessionOpened(item.sessionId);
1253
+ bumpRecent((value) => value + 1);
945
1254
  workspace.openSession(item.sessionId);
946
1255
  } catch (cause) {
947
1256
  /* 切不过去也继续尝试填当前会话 */
@@ -967,7 +1276,6 @@ window.__ModuleLoader__.load({
967
1276
  whenDraftExists: "keep",
968
1277
  });
969
1278
  if (first === "applied") {
970
- setFillNotice({ bad: false, text: t("fillDone") });
971
1279
  return;
972
1280
  }
973
1281
  if (first !== "preserved") throw new Error(String(first));
@@ -991,22 +1299,14 @@ window.__ModuleLoader__.load({
991
1299
  if (pending === null) return;
992
1300
  try {
993
1301
  const result = pending.apply();
994
- if (result === "applied") setFillNotice({ bad: false, text: t("fillDone") });
995
- else setFillNotice({ bad: true, text: t("fillFailed", { message: String(result) }) });
1302
+ if (result !== "applied") {
1303
+ setError(t("fillFailed", { message: String(result) }));
1304
+ }
996
1305
  } catch (cause) {
997
- setFillNotice({
998
- bad: true,
999
- text: t("fillFailed", { message: String(cause?.message ?? cause) }),
1000
- });
1306
+ setError(t("fillFailed", { message: String(cause?.message ?? cause) }));
1001
1307
  }
1002
1308
  }, [pendingFill, t]);
1003
1309
 
1004
- React.useEffect(() => {
1005
- if (fillNotice === null) return undefined;
1006
- const timer = window.setTimeout(() => setFillNotice(null), 2600);
1007
- return () => window.clearTimeout(timer);
1008
- }, [fillNotice]);
1009
-
1010
1310
  const label = t("open");
1011
1311
  const badge = items.length;
1012
1312
 
@@ -1037,16 +1337,6 @@ window.__ModuleLoader__.load({
1037
1337
  : h("span", { className: "dpb-trigger-label" }, label),
1038
1338
  badge > 0 ? h("span", { className: "dpb-badge" }, badge > 99 ? "99+" : badge) : null,
1039
1339
  ),
1040
- fillNotice === null
1041
- ? null
1042
- : ReactDOM.createPortal(
1043
- h(
1044
- "div",
1045
- { className: "dpb-toast " + (fillNotice.bad ? "bad" : "ok") },
1046
- fillNotice.text,
1047
- ),
1048
- document.body,
1049
- ),
1050
1340
  pendingFill === null
1051
1341
  ? null
1052
1342
  : ReactDOM.createPortal(
@@ -1103,6 +1393,7 @@ window.__ModuleLoader__.load({
1103
1393
  error,
1104
1394
  result,
1105
1395
  pinnedId,
1396
+ jumpingId,
1106
1397
  onClose: closePanel,
1107
1398
  onRefresh: () => load(true),
1108
1399
  onOpen: openSession,
@@ -1122,6 +1413,8 @@ window.__ModuleLoader__.load({
1122
1413
  const [state, setState] = React.useState("idle");
1123
1414
  const timer = React.useRef(0);
1124
1415
  const sessionId = props.sessionId;
1416
+ const turn = Number(props.turn?.turn ?? props.turn ?? 0) || 0;
1417
+ const seq = Number(props.seq ?? 0) || 0;
1125
1418
 
1126
1419
  React.useEffect(
1127
1420
  () => () => {
@@ -1139,7 +1432,12 @@ window.__ModuleLoader__.load({
1139
1432
  await request(`${API}/defer`, {
1140
1433
  method: "POST",
1141
1434
  headers: { "content-type": "application/json" },
1142
- body: JSON.stringify({ sessionId }),
1435
+ body: JSON.stringify({
1436
+ sessionId,
1437
+ ...(turn > 0
1438
+ ? { anchor: { turn, seq, at: Date.now(), kind: "user" } }
1439
+ : {}),
1440
+ }),
1143
1441
  });
1144
1442
  setState("done");
1145
1443
  window.dispatchEvent(new CustomEvent("dsh-planbox-dyb:changed"));
@@ -1235,11 +1533,14 @@ window.__ModuleLoader__.load({
1235
1533
  AutoResumeAction,
1236
1534
  Row,
1237
1535
  Panel,
1238
- groupPending,
1536
+ groupSessions,
1239
1537
  orderPending,
1240
1538
  tagFor,
1241
1539
  restorableItems,
1242
1540
  anchorText,
1541
+ revealTurn,
1542
+ scrollTurnStart,
1543
+ nudgeTurnRail,
1243
1544
  nextStep,
1244
1545
  },
1245
1546
  };
package/index.js CHANGED
@@ -54,6 +54,13 @@ const SCAN_MAX_SESSIONS = 80;
54
54
  const SCAN_CONCURRENCY = 6;
55
55
  /** 异常中断默认只回溯 7 天,避免历史 error/interrupted 会话永远堆在面板里。 */
56
56
  const DEFAULT_ABNORMAL_WINDOW_MS = 7 * 24 * 60 * 60 * 1000;
57
+ /** 助手结尾的“需要重启”只自动收最近 24 小时的会话,避免历史会话全部堆进来。 */
58
+ const DEFAULT_RESTART_WINDOW_MS = 24 * 60 * 60 * 1000;
59
+ const DEFAULT_RESTART_GAP = 5;
60
+ const RESTART_NEEDED_PATTERN = (gap) => [
61
+ new RegExp(`(?<!不)重启[\\s\\S]{0,${gap}}(?<!不)需要`),
62
+ new RegExp(`(?<!不)需要[\\s\\S]{0,${gap}}(?<!不)重启`),
63
+ ];
57
64
  const MARKER_PATTERNS = [
58
65
  /等?重启后(?:继续|接着)/,
59
66
  /等?重启再(?:继续|接着)?/,
@@ -340,12 +347,19 @@ export function createStore(options = {}) {
340
347
  );
341
348
  },
342
349
 
343
- /** 新增(同一会话、同一来源类别只保留最新一条;手动与自动分开)。 */
350
+ /** 新增:自动按会话更新;手动只在同一回合内更新,不同回合分别保留。 */
344
351
  add(entry) {
345
352
  const automatic = entry.origin === 'model';
346
- const items = store.queue().filter(
347
- (item) => !(item.sessionId === entry.sessionId && (item.origin === 'model') === automatic),
348
- );
353
+ const entryTurn = automatic
354
+ ? 0
355
+ : Number(entry.anchor?.turn ?? 0) || Number(entry.anchor?.seq ?? 0) || 0;
356
+ const items = store.queue().filter((item) => {
357
+ if (item.sessionId !== entry.sessionId) return true;
358
+ if ((item.origin === 'model') !== automatic) return true;
359
+ if (automatic) return false;
360
+ const itemTurn = Number(item.anchor?.turn ?? 0) || Number(item.anchor?.seq ?? 0) || 0;
361
+ return itemTurn !== entryTurn;
362
+ });
349
363
  items.unshift(entry);
350
364
  writeJsonAtomic(queueFile, { version: 1, items });
351
365
  return entry;
@@ -458,6 +472,7 @@ function queueItems(store) {
458
472
  .queue()
459
473
  .map((entry) => {
460
474
  const prompt = typeof entry.prompt === 'string' ? entry.prompt : '';
475
+ const origin = entry.origin === 'model' ? 'model' : 'manual';
461
476
  return {
462
477
  id: entry.id,
463
478
  source: 'queue',
@@ -466,7 +481,8 @@ function queueItems(store) {
466
481
  prompt,
467
482
  snippet: tailOf(prompt),
468
483
  detailSource: 'prompt',
469
- origin: entry.origin === 'model' ? 'model' : 'manual',
484
+ origin,
485
+ kind: origin === 'model' ? 'auto' : 'manual',
470
486
  note: typeof entry.note === 'string' ? entry.note : '',
471
487
  snapshot: entry.snapshot && typeof entry.snapshot === 'object' ? entry.snapshot : null,
472
488
  anchor: normalizeAnchor(entry.anchor),
@@ -561,6 +577,7 @@ function detectCandidate(summary, tail, turn, options) {
561
577
  return {
562
578
  id: `abnormal:${sessionId}`,
563
579
  source: 'abnormal',
580
+ kind: 'interrupted',
564
581
  sessionId,
565
582
  title: summaryTitle(summary),
566
583
  snippet: tailOf(detail),
@@ -572,6 +589,25 @@ function detectCandidate(summary, tail, turn, options) {
572
589
  };
573
590
  }
574
591
 
592
+ const restartWindow =
593
+ Number(summary.updatedAt ?? 0) > 0 &&
594
+ now - Number(summary.updatedAt ?? now) <= restartWindowMs();
595
+ if (summary.running !== true && restartWindow && restartNeededIn(tail.lastAssistantText)) {
596
+ return {
597
+ id: `scan:${sessionId}`,
598
+ source: 'scan',
599
+ kind: 'auto',
600
+ sessionId,
601
+ title: summaryTitle(summary),
602
+ snippet: snippetAround(tail.lastAssistantText, RESTART_NEEDED_PATTERN(restartGapChars())),
603
+ prompt: tailOf(tail.lastAssistantText, 240),
604
+ anchor: normalizeAnchor(options.anchor),
605
+ updatedAt: Number(summary.updatedAt ?? options.now),
606
+ running: false,
607
+ cwd: typeof summary.cwd === 'string' ? summary.cwd : undefined,
608
+ };
609
+ }
610
+
575
611
  const realUserText = tail.lastRealUserText ?? '';
576
612
  if (realUserText === '' || isAutoPrompt(realUserText) || !markerIn(realUserText)) return null;
577
613
 
@@ -589,9 +625,31 @@ function detectCandidate(summary, tail, turn, options) {
589
625
  };
590
626
  }
591
627
 
628
+ /** 判断文本里“重启”和“需要”的间隔,可由 DSH_PLANBOX_RESTART_GAP 覆盖(0–20,默认 5)。 */
629
+ export function restartGapChars() {
630
+ const raw = Number(process.env.DSH_PLANBOX_RESTART_GAP ?? DEFAULT_RESTART_GAP);
631
+ if (!Number.isFinite(raw) || raw < 0 || raw > 20) return DEFAULT_RESTART_GAP;
632
+ return Math.floor(raw);
633
+ }
634
+
635
+ /** 助手重启结论的自动收集窗口,可由 DSH_PLANBOX_RESTART_HOURS 覆盖(0 = 不限,默认 24 小时)。 */
636
+ export function restartWindowMs() {
637
+ const raw = process.env.DSH_PLANBOX_RESTART_HOURS;
638
+ if (raw === undefined || raw.trim() === '') return DEFAULT_RESTART_WINDOW_MS;
639
+ const hours = Number(raw);
640
+ if (!Number.isFinite(hours) || hours < 0) return DEFAULT_RESTART_WINDOW_MS;
641
+ return hours === 0 ? Number.POSITIVE_INFINITY : hours * 60 * 60 * 1000;
642
+ }
643
+
644
+ /** 助手最后一条消息是否同时提到“重启”和“需要”(间隔内,且需要/重启前都不是“不”)。 */
645
+ export function restartNeededIn(text) {
646
+ const value = typeof text === 'string' ? text : '';
647
+ return RESTART_NEEDED_PATTERN(restartGapChars()).some((pattern) => pattern.test(value));
648
+ }
649
+
592
650
  /**
593
651
  * 兜底扫描:找“最后一条真实用户消息在说等重启后继续”的会话。
594
- * 主路径是模型调用 planbox_defer 主动登记,扫描只负责兜底。
652
+ * 主路径是模型调用 planbox_defer 主动登记,扫描只负责兜底;助手明确说“DSH 重启:需要”也自动收。
595
653
  * @param {object} ctx - 宿主上下文(需要 sessionController)。
596
654
  * @param {ReturnType<typeof createStore>} store - 持久存储。
597
655
  * @param {{ refresh?: boolean, signal?: AbortSignal, now?: number }} [options] - 扫描选项。
@@ -698,24 +756,61 @@ export async function scanCandidates(ctx, store, options = {}) {
698
756
  * @param {{ refresh?: boolean, signal?: AbortSignal, now?: number }} [options] - 选项。
699
757
  * @returns {Promise<{ items: object[], queueCount: number, scanCount: number, scannedAt: number, scanError?: string }>} 汇总。
700
758
  */
759
+ function turnOfItem(item) {
760
+ return Number(item?.anchor?.turn ?? 0) || 0;
761
+ }
762
+
763
+ /** 统一任务类别:manual / auto / interrupted。 */
764
+ export function kindOf(item) {
765
+ if (item?.kind === 'manual' || item?.kind === 'auto' || item?.kind === 'interrupted') {
766
+ return item.kind;
767
+ }
768
+ if (item?.source === 'abnormal') return 'interrupted';
769
+ if (item?.source === 'queue' && item?.origin !== 'model') return 'manual';
770
+ return 'auto';
771
+ }
772
+
701
773
  export async function collectPending(ctx, store, options = {}) {
702
774
  const [queue, scanned] = await Promise.all([
703
775
  queueItemsWithDetails(ctx, store, options),
704
776
  scanCandidates(ctx, store, options),
705
777
  ]);
706
- // 只有自动登记项会吞掉同会话的扫描结果;手动登记与自动结果要分开显示。
707
- const known = new Set(
708
- queue.filter((item) => item.origin === 'model').map((item) => item.sessionId),
709
- );
710
- const extra = scanned.items
711
- .filter((item) => !known.has(item.sessionId))
712
- .sort((left, right) => right.updatedAt - left.updatedAt);
713
778
 
714
- const items = [...queue, ...extra].map((item) => ({ ...item, suggestion: suggestionFor(item) }));
779
+ const priority = { auto: 1, interrupted: 2, manual: 3 };
780
+ const merged = new Map();
781
+ for (const item of [...queue, ...scanned.items]) {
782
+ const kind = kindOf(item);
783
+ const normalized = item.kind === kind ? item : { ...item, kind };
784
+ const key =
785
+ turnOfItem(normalized) > 0
786
+ ? `${normalized.sessionId}\u0000${turnOfItem(normalized)}`
787
+ : `id:${normalized.id}`;
788
+ const current = merged.get(key);
789
+ if (current === undefined) {
790
+ merged.set(key, normalized);
791
+ continue;
792
+ }
793
+ const currentPriority = priority[kindOf(current)];
794
+ const nextPriority = priority[kind];
795
+ if (nextPriority > currentPriority) {
796
+ merged.set(key, normalized);
797
+ } else if (
798
+ nextPriority === currentPriority &&
799
+ current.source !== 'queue' &&
800
+ normalized.source === 'queue'
801
+ ) {
802
+ merged.set(key, normalized);
803
+ }
804
+ }
805
+
806
+ const items = [...merged.values()]
807
+ .sort((left, right) => right.updatedAt - left.updatedAt)
808
+ .map((item) => ({ ...item, suggestion: suggestionFor(item) }));
809
+ const visibleQueue = items.filter((item) => item.source === 'queue');
715
810
  return {
716
811
  items,
717
- queueCount: queue.length,
718
- scanCount: extra.length,
812
+ queueCount: visibleQueue.length,
813
+ scanCount: items.length - visibleQueue.length,
719
814
  scannedAt: scanned.scannedAt,
720
815
  ...(scanned.scanError === undefined ? {} : { scanError: scanned.scanError }),
721
816
  };
@@ -835,6 +930,9 @@ function resumeText(item) {
835
930
  // 异常中断的会话,直接发一句“继续”最自然;完整上下文本来就在会话里。
836
931
  return '继续';
837
932
  }
933
+ if (item.source === 'scan' && item.prompt) {
934
+ return `${RESUME_PREFIX}DSH 已重启,请继续这个任务:${item.prompt}`;
935
+ }
838
936
  return (
839
937
  `${RESUME_PREFIX}DSH 已重启。请接着处理本会话里此前标注“等重启后继续”的任务:` +
840
938
  '先确认上次做到哪里,再从未完成处继续,不要重做已完成的部分;如果任务已经完成,请简短说明。'
@@ -1024,7 +1122,7 @@ export async function deferFromSession(ctx, store, sessionId, overrides = {}, op
1024
1122
 
1025
1123
  let title = String(overrides.title ?? '').trim();
1026
1124
  let prompt = String(overrides.prompt ?? '').trim();
1027
- let anchor = null;
1125
+ let anchor = normalizeAnchor(overrides.anchor);
1028
1126
 
1029
1127
  const controller = withTimeout(options.signal, 8_000);
1030
1128
  if (title === '') {
@@ -1041,7 +1139,7 @@ export async function deferFromSession(ctx, store, sessionId, overrides = {}, op
1041
1139
  { address: { kind: 'session', sessionId: target }, maxMessages: 30 },
1042
1140
  controller,
1043
1141
  );
1044
- anchor = anchorOf(page?.records);
1142
+ if (anchor === null) anchor = anchorOf(page?.records);
1045
1143
  if (prompt === '') {
1046
1144
  const lastUser = tailMessages(page?.records).lastRealUserText;
1047
1145
  if (lastUser !== '') prompt = lastUser.slice(0, 200);
@@ -1128,6 +1226,7 @@ export function registerRoutes(ctx, store, connection) {
1128
1226
  title: typeof body?.title === 'string' ? body.title : undefined,
1129
1227
  prompt: typeof body?.prompt === 'string' ? body.prompt : undefined,
1130
1228
  note: typeof body?.note === 'string' ? body.note : undefined,
1229
+ anchor: body?.anchor,
1131
1230
  origin: 'manual',
1132
1231
  },
1133
1232
  );
@@ -1300,7 +1399,7 @@ export function createToolDefinitions(ctx, store) {
1300
1399
 
1301
1400
  const listTool = {
1302
1401
  name: 'planbox_list',
1303
- description: '列出计划任务:已登记、异常中断、扫描到三类。',
1402
+ description: '列出计划任务:手动、发现、中断三类。',
1304
1403
  parameters: { type: 'object', additionalProperties: false, properties: {} },
1305
1404
  output: {
1306
1405
  schema: {
@@ -1317,6 +1416,7 @@ export function createToolDefinitions(ctx, store) {
1317
1416
  id: { type: 'string' },
1318
1417
  source: { type: 'string' },
1319
1418
  origin: { type: 'string' },
1419
+ kind: { type: 'string' },
1320
1420
  sessionId: { type: 'string' },
1321
1421
  title: { type: 'string' },
1322
1422
  anchor: {
@@ -1354,12 +1454,8 @@ export function createToolDefinitions(ctx, store) {
1354
1454
  render(_args, value) {
1355
1455
  if (value.count === 0) return [{ type: 'text', text: '当前没有计划任务。' }];
1356
1456
  const line = (item) => {
1357
- const tag =
1358
- item.source === 'abnormal'
1359
- ? '异常中断'
1360
- : item.source === 'queue' && item.origin !== 'model'
1361
- ? '已登记'
1362
- : '扫描到';
1457
+ const kind = kindOf(item);
1458
+ const tag = kind === 'manual' ? '手动' : kind === 'interrupted' ? '中断' : '发现';
1363
1459
  const detail = item.snippet ? `\n ${item.snippet}` : '';
1364
1460
  const anchor =
1365
1461
  item.anchor?.turn > 0
@@ -1369,22 +1465,18 @@ export function createToolDefinitions(ctx, store) {
1369
1465
  : '';
1370
1466
  return `- [${tag}] ${item.title}(${item.sessionId})${anchor}${detail}`;
1371
1467
  };
1372
- const registered = value.items.filter(
1373
- (item) => item.source === 'queue' && item.origin !== 'model',
1374
- );
1375
- const abnormal = value.items.filter((item) => item.source === 'abnormal');
1376
- const scanned = value.items.filter((item) =>
1377
- item.source === 'queue' ? item.origin === 'model' : item.source !== 'abnormal',
1378
- );
1468
+ const manual = value.items.filter((item) => kindOf(item) === 'manual');
1469
+ const auto = value.items.filter((item) => kindOf(item) === 'auto');
1470
+ const interrupted = value.items.filter((item) => kindOf(item) === 'interrupted');
1379
1471
  const sections = [];
1380
- if (registered.length > 0) {
1381
- sections.push(`【已登记】\n${registered.map(line).join('\n')}`);
1472
+ if (manual.length > 0) {
1473
+ sections.push(`【手动】\n${manual.map(line).join('\n')}`);
1382
1474
  }
1383
- if (abnormal.length > 0) {
1384
- sections.push(`【异常中断】\n${abnormal.map(line).join('\n')}`);
1475
+ if (auto.length > 0) {
1476
+ sections.push(`【发现】\n${auto.map(line).join('\n')}`);
1385
1477
  }
1386
- if (scanned.length > 0) {
1387
- sections.push(`【扫描到】\n${scanned.map(line).join('\n')}`);
1478
+ if (interrupted.length > 0) {
1479
+ sections.push(`【中断】\n${interrupted.map(line).join('\n')}`);
1388
1480
  }
1389
1481
  return [{ type: 'text', text: `计划任务共 ${value.count} 条:\n\n${sections.join('\n\n')}` }];
1390
1482
  },
@@ -1398,6 +1490,7 @@ export function createToolDefinitions(ctx, store) {
1398
1490
  id: item.id,
1399
1491
  source: item.source,
1400
1492
  origin: item.origin ?? 'manual',
1493
+ kind: kindOf(item),
1401
1494
  sessionId: item.sessionId,
1402
1495
  title: item.title,
1403
1496
  ...(item.anchor === null || item.anchor === undefined ? {} : { anchor: item.anchor }),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-planbox-dyb",
3
- "version": "0.8.3",
3
+ "version": "0.8.4",
4
4
  "description": "PlanBox:DSH 计划任务收件箱——重启前登记、重启后审核并恢复中断任务。宿主 Windows / macOS / Linux,客户端任意现代浏览器(含 iOS / iPadOS Safari)。",
5
5
  "license": "MIT",
6
6
  "author": "ZhibinYU",