dsh-ws-recency 0.24.0 → 0.25.0

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 +15 -9
  2. package/client.js +709 -180
  3. package/index.js +181 -9
  4. package/package.json +1 -1
package/client.js CHANGED
@@ -212,6 +212,12 @@
212
212
  ".wsr-btn:hover{background:var(--dsw-alias-interactive-bg-hover,rgba(255,255,255,.08))}",
213
213
  ".wsr-btn-danger{border-color:var(--dsw-alias-state-error-primary,#d9534f);color:var(--dsw-alias-state-error-primary,#d9534f)}",
214
214
  ".wsr-danger{border-color:var(--dsw-alias-state-error-primary,#d9534f);color:var(--dsw-alias-state-error-primary,#d9534f)}",
215
+ /* In-app confirmation: native window.confirm leaves the renderer
216
+ without keyboard focus on Windows (the composer then ignores
217
+ clicks until the app loses and regains focus). */
218
+ ".wsr-confirm{width:min(420px,88vw);display:flex;flex-direction:column;gap:14px;padding:16px;border-radius:12px;background:var(--dsw-alias-bg-layer-1,#1f2226);color:var(--dsw-alias-label-primary,#e8e8e8);border:.5px solid var(--dsw-alias-border-l2,rgba(255,255,255,.16));box-shadow:0 14px 44px rgba(0,0,0,.45);outline:none}",
219
+ ".wsr-confirm-text{white-space:pre-wrap;font-size:13px;line-height:1.65}",
220
+ ".wsr-confirm-actions{display:flex;justify-content:flex-end;gap:8px}",
215
221
  ".wsr-chart{display:flex;flex-direction:column;gap:6px}",
216
222
  ".wsr-chart-head{display:flex;align-items:center;justify-content:space-between;gap:10px}",
217
223
  ".wsr-chart-title{font-size:11px;color:var(--dsw-alias-label-tertiary)}",
@@ -227,8 +233,6 @@
227
233
  ".wsr-chart-legend-text{white-space:nowrap}",
228
234
  ".wsr-chart-value{text-align:right;font-variant-numeric:tabular-nums}",
229
235
  ".wsr-chart-share{text-align:right;color:var(--dsw-alias-label-tertiary);font-variant-numeric:tabular-nums}",
230
- ".wsr-details-toggle{align-self:flex-start;border:none;background:0 0;color:var(--dsw-alias-label-tertiary);font:inherit;font-size:11px;cursor:pointer;padding:2px 0}",
231
- ".wsr-details-toggle:hover{color:var(--dsw-alias-label-primary)}",
232
236
  ".wsr-stats-details{display:flex;flex-direction:column;gap:8px}",
233
237
  ".wsr-stats-table{display:flex;flex-direction:column}",
234
238
  ".wsr-stats-row{display:grid;grid-template-columns:1.4fr .6fr .8fr .8fr .8fr .6fr;gap:6px;padding:6px 4px;border-bottom:.5px solid rgba(255,255,255,.06)}",
@@ -238,6 +242,35 @@
238
242
  ".wsr-td-strong{font-weight:600}",
239
243
  ".wsr-td-dim{color:var(--dsw-alias-label-tertiary);opacity:.65}",
240
244
  ".wsr-stats-note{color:var(--dsw-alias-label-tertiary);font-size:11px;line-height:1.5}",
245
+ /* Three views, one dialog: distribution, amplification, details. */
246
+ ".wsr-stats-tabs{display:flex;gap:2px;border-bottom:.5px solid rgba(255,255,255,.08)}",
247
+ ".wsr-stats-tab{border:none;background:0 0;color:var(--dsw-alias-label-tertiary);font:inherit;font-size:12px;padding:6px 10px;cursor:pointer;border-bottom:2px solid transparent;margin-bottom:-.5px}",
248
+ ".wsr-stats-tab:hover{color:var(--dsw-alias-label-primary)}",
249
+ ".wsr-stats-tab-active{color:var(--dsw-alias-label-primary);border-bottom-color:var(--dsw-alias-brand-primary,#4f7cff)}",
250
+ ".wsr-stats-panels{display:flex;flex-direction:column;gap:10px}",
251
+ ".wsr-stats-panel{display:flex;flex-direction:column;gap:10px}",
252
+ /* Amplified cost: the bill is the area under the context curve, so the
253
+ ranking is by content x remaining steps, not by step tokens. */
254
+ ".wsr-amplified{display:flex;flex-direction:column;gap:8px;padding:10px;border-radius:8px;background:var(--dsw-alias-bg-layer-2,rgba(255,255,255,.04))}",
255
+ ".wsr-amplified-head{display:flex;align-items:baseline;justify-content:space-between;gap:10px;flex-wrap:wrap}",
256
+ ".wsr-amplified-title{font-size:12px;font-weight:600}",
257
+ ".wsr-amplified-summary{font-size:11px;color:var(--dsw-alias-label-tertiary)}",
258
+ ".wsr-context-chart{display:flex;align-items:flex-end;gap:2px;height:54px;padding-top:4px;border-bottom:.5px solid rgba(255,255,255,.08)}",
259
+ ".wsr-context-bar{flex:1;min-width:1px;border-radius:1px 1px 0 0;background:linear-gradient(180deg,rgba(79,124,255,.9),rgba(79,124,255,.3))}",
260
+ ".wsr-context-caption{font-size:10px;color:var(--dsw-alias-label-tertiary)}",
261
+ ".wsr-kind-legend{display:flex;flex-wrap:wrap;gap:10px}",
262
+ ".wsr-kind{display:flex;align-items:center;gap:5px;font-size:11px;color:var(--dsw-alias-label-tertiary)}",
263
+ ".wsr-kind-dot{width:8px;height:8px;border-radius:2px;flex:none}",
264
+ ".wsr-amplified-list{display:flex;flex-direction:column;gap:2px}",
265
+ ".wsr-amplified-row{display:grid;grid-template-columns:1fr 76px 48px;gap:8px;align-items:start;padding:6px 0;border-bottom:.5px solid rgba(255,255,255,.06)}",
266
+ ".wsr-amplified-main{min-width:0;display:flex;flex-direction:column;gap:1px}",
267
+ ".wsr-amplified-name{font-size:12px;font-weight:500;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}",
268
+ ".wsr-amplified-detail{font-size:11px;color:var(--dsw-alias-label-secondary);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-family:ui-monospace,SFMono-Regular,Menlo,monospace}",
269
+ ".wsr-amplified-meta{font-size:10px;color:var(--dsw-alias-label-tertiary)}",
270
+ ".wsr-amplified-value{text-align:right;font-weight:600;font-variant-numeric:tabular-nums;font-size:12px}",
271
+ ".wsr-amplified-share{text-align:right;color:var(--dsw-alias-label-tertiary);font-size:11px;font-variant-numeric:tabular-nums}",
272
+ ".wsr-amplified-if{grid-column:1 / -1;font-size:10px;color:var(--dsw-alias-label-tertiary)}",
273
+ ".wsr-amplified-empty{font-size:11px;color:var(--dsw-alias-label-tertiary)}",
241
274
  ".wsr-toggle{width:100%;height:28px;padding:0 12px 0 calc(28px + var(--dsh-workspace-indent,0px));cursor:pointer;text-align:left;color:var(--dsw-alias-label-tertiary);background:0 0;border:none;font-size:12px}",
242
275
  ".wsr-toggle:hover{color:var(--dsw-alias-label-secondary)}",
243
276
  '[' + STATE_ATTR + '="running"] [class*="_title"]{color:#4f8ef7}',
@@ -378,14 +411,30 @@
378
411
  "archive.workspace": "工作区",
379
412
  "move.failed": "移动失败:",
380
413
  "stats.chart": "消耗分布",
381
- "stats.details.show": "显示明细 ▾",
382
- "stats.details.hide": "收起明细 ▴",
383
414
  "composer.analysis": "用量分析",
384
415
  "stats.legend.args": "参数(模型写的)",
385
416
  "stats.legend.results": "结果(环境返回的)",
386
417
  "stats.argModeNote": "当前把工具参数计入主 agent:每个工具只算返回结果,表格里「参数」列显示为淡色(那些 token 记在主 agent 那一行)。",
418
+ "stats.amplified.title": "放大成本(账单归因)",
419
+ "stats.amplified.summary": "账单 {bill} token;可归因内容经重读放大后占 {share}({attributed})",
420
+ "stats.amplified.contextCaption": "每步上下文(面积≈账单):越早进入的内容被重读越多",
421
+ "stats.amplified.point": "第 {step} 步 · {context}",
422
+ "stats.amplified.meta": "第 {entry} 步进入 · {tokens} token × {remaining} 次重读",
423
+ "stats.amplified.whatIf": "若压到 20%,可省 {save}({share})",
424
+ "stats.amplified.empty": "没有可归因的放大内容(压缩后或旧日志可能缺失)",
425
+ "stats.amplified.note": "放大成本按内容长度估算;账单总量来自真实 usage。思维链通常不回传,故未计入。",
426
+ "stats.amplified.results": "工具结果",
427
+ "stats.amplified.args": "工具参数",
428
+ "stats.amplified.agent": "主 agent 输出",
429
+ "stats.amplified.user": "用户消息",
430
+ "stats.amplified.system": "系统消息",
431
+ "stats.tab.distribution": "分布统计",
432
+ "stats.tab.amplified": "放大归因",
433
+ "stats.tab.details": "明细",
387
434
  "trash.confirm": "\u5220\u9664\u8fd9\u4e2a\u4f1a\u8bdd\uff1f\n\n\u4f1a\u5148\u505c\u6b62\u5b83\u6b63\u5728\u8fdb\u884c\u7684\u5de5\u4f5c\uff0c\u518d\u628a\u65e5\u5fd7\u76ee\u5f55\u79fb\u5165\u56de\u6536\u7ad9\uff08\u4e0d\u662f\u7269\u7406\u5220\u9664\uff0c\u53ef\u4ee5\u624b\u52a8\u6062\u590d\uff09\u3002",
388
435
  "trash.failed": "\u5220\u9664\u5931\u8d25\uff1a",
436
+ "confirm.cancel": "\u53d6\u6d88",
437
+ "confirm.ok": "\u786e\u8ba4",
389
438
  };
390
439
  var EN = {
391
440
  "settings.title": "Fold history after (days)",
@@ -509,14 +558,30 @@
509
558
  "archive.workspace": "workspace",
510
559
  "move.failed": "Move failed: ",
511
560
  "stats.chart": "Where the tokens went",
512
- "stats.details.show": "Show details",
513
- "stats.details.hide": "Hide details",
514
561
  "composer.analysis": "Usage analysis",
515
562
  "stats.legend.args": "arguments (written by the model)",
516
563
  "stats.legend.results": "results (returned by the environment)",
517
564
  "stats.argModeNote": "Tool arguments currently count towards the agent: each tool shows only its results, and the table's \"args\" column is faded because those tokens sit on the agent's row.",
565
+ "stats.amplified.title": "Amplified cost (what the bill pays for)",
566
+ "stats.amplified.summary": "Bill {bill} tokens; attributable content amplifies to {share} ({attributed})",
567
+ "stats.amplified.contextCaption": "Context per step (area ≈ bill): earlier content is re-read more",
568
+ "stats.amplified.point": "step {step} · {context}",
569
+ "stats.amplified.meta": "entered at step {entry} · {tokens} tokens × {remaining} re-reads",
570
+ "stats.amplified.whatIf": "at 20%, saves {save} ({share})",
571
+ "stats.amplified.empty": "No amplifiable content (compacted or older logs may lack it)",
572
+ "stats.amplified.note": "Amplified cost is estimated from content length; the bill total comes from real usage. Reasoning is usually not resent, so it is excluded.",
573
+ "stats.amplified.results": "tool results",
574
+ "stats.amplified.args": "tool arguments",
575
+ "stats.amplified.agent": "agent output",
576
+ "stats.amplified.user": "user messages",
577
+ "stats.amplified.system": "system messages",
578
+ "stats.tab.distribution": "Distribution",
579
+ "stats.tab.amplified": "Amplified",
580
+ "stats.tab.details": "Details",
518
581
  "trash.confirm": "Delete this session?\n\nIt stops whatever the session is running, then moves the log directory into the trash folder (a move, not an erase: you can restore it by hand).",
519
582
  "trash.failed": "Delete failed: ",
583
+ "confirm.cancel": "Cancel",
584
+ "confirm.ok": "Confirm",
520
585
  };
521
586
 
522
587
  /* Resolved lazily: the dictionaries are declared further down this closure. */
@@ -540,7 +605,14 @@
540
605
  }
541
606
  var dictionary = fallbackDictionary();
542
607
  var text = (dictionary && dictionary[key]) || key;
543
- if (params !== undefined && params.n !== undefined) text = text.replace("{n}", String(params.n));
608
+ /* The host's translate may interpolate; the local fallback has to do
609
+ it itself, or every template would render its braces verbatim. */
610
+ if (params !== undefined && params !== null) {
611
+ for (var name in params) {
612
+ if (!Object.prototype.hasOwnProperty.call(params, name)) continue;
613
+ text = text.split("{" + name + "}").join(String(params[name]));
614
+ }
615
+ }
544
616
  return text;
545
617
  }
546
618
 
@@ -1186,6 +1258,34 @@
1186
1258
  return typeof id === "string" && id !== "" ? id : null;
1187
1259
  }
1188
1260
 
1261
+ /**
1262
+ * The highest turn number currently rendered in the conversation.
1263
+ *
1264
+ * The handoff card lives in the `turnTail` slot, which renders once per
1265
+ * turn; without this the card would appear under every reply. A running
1266
+ * handoff may only speak from the tail of the turn it just started.
1267
+ */
1268
+ function latestTurnNumber() {
1269
+ if (typeof document === "undefined") return null;
1270
+ var body = null;
1271
+ try { body = document.querySelector("[data-conversation-content]"); } catch (error) { body = null; }
1272
+ var elements;
1273
+ try {
1274
+ elements = body !== null && body !== undefined && typeof body.querySelectorAll === "function"
1275
+ ? body.querySelectorAll("[data-turn-tail]")
1276
+ : (typeof document.querySelectorAll === "function" ? document.querySelectorAll("[data-turn-tail]") : []);
1277
+ } catch (error) {
1278
+ return null;
1279
+ }
1280
+ var max = null;
1281
+ for (var i = 0; i < elements.length; i += 1) {
1282
+ var value = Number(elements[i].getAttribute("data-turn-tail"));
1283
+ if (!isFinite(value)) continue;
1284
+ if (max === null || value > max) max = value;
1285
+ }
1286
+ return max;
1287
+ }
1288
+
1189
1289
  /** The nearest horizontal flex row above the stats: the whole footer dock. */
1190
1290
  function composerDockOf(row) {
1191
1291
  var node = row;
@@ -1415,29 +1515,28 @@
1415
1515
  return h(Item, {
1416
1516
  icon: typeof Icon === "function" ? h(Icon, {}) : undefined,
1417
1517
  onSelect: function () {
1418
- var question = t("trash.confirm");
1419
- var confirmed = typeof window.confirm === "function" ? window.confirm(question) : false;
1420
- if (!confirmed) return;
1421
- fetch("/ws-recency/session-trash?sessionId=" + encodeURIComponent(props.sessionId), {
1422
- method: "POST",
1423
- headers: { "content-type": "application/json" },
1424
- body: JSON.stringify({ sessionId: props.sessionId }),
1425
- })
1426
- .then(function (response) {
1427
- return response.text().then(function (text) {
1428
- var parsed = null;
1429
- try { parsed = JSON.parse(text); } catch (error) { parsed = null; }
1430
- return { status: response.status, text: text, json: parsed };
1431
- });
1432
- })
1433
- .then(function (result) {
1434
- if (result.json !== null && result.json.ok === true) return;
1435
- var reason = (result.json !== null && result.json.error) || (result.text || "").trim().slice(0, 120) || "(empty response)";
1436
- if (typeof window.alert === "function") window.alert(t("trash.failed") + "HTTP " + result.status + " \u00b7 " + reason);
1518
+ askConfirm(t("trash.confirm"), function () {
1519
+ fetch("/ws-recency/session-trash?sessionId=" + encodeURIComponent(props.sessionId), {
1520
+ method: "POST",
1521
+ headers: { "content-type": "application/json" },
1522
+ body: JSON.stringify({ sessionId: props.sessionId }),
1437
1523
  })
1438
- .catch(function (error) {
1439
- if (typeof window.alert === "function") window.alert(t("trash.failed") + (error && error.message ? error.message : error));
1440
- });
1524
+ .then(function (response) {
1525
+ return response.text().then(function (text) {
1526
+ var parsed = null;
1527
+ try { parsed = JSON.parse(text); } catch (error) { parsed = null; }
1528
+ return { status: response.status, text: text, json: parsed };
1529
+ });
1530
+ })
1531
+ .then(function (result) {
1532
+ if (result.json !== null && result.json.ok === true) return;
1533
+ var reason = (result.json !== null && result.json.error) || (result.text || "").trim().slice(0, 120) || "(empty response)";
1534
+ askNotice(t("trash.failed") + "HTTP " + result.status + " \u00b7 " + reason);
1535
+ })
1536
+ .catch(function (error) {
1537
+ askNotice(t("trash.failed") + (error && error.message ? error.message : error));
1538
+ });
1539
+ });
1441
1540
  },
1442
1541
  }, t("menu.trash"));
1443
1542
  }
@@ -1445,6 +1544,8 @@
1445
1544
  /* ------------------------- token statistics ------------------------- */
1446
1545
 
1447
1546
  var statsModal = null;
1547
+ /** Which stats tab stays selected across openings. */
1548
+ var statsTab = "distribution";
1448
1549
 
1449
1550
  function formatTokens(value) {
1450
1551
  var n = Number(value) || 0;
@@ -1460,6 +1561,8 @@
1460
1561
  }
1461
1562
 
1462
1563
  function closeStatsPanel() {
1564
+ /* A confirmation may sit on top of the panel it was opened from. */
1565
+ closeConfirm(null);
1463
1566
  if (statsModal !== null) {
1464
1567
  if (typeof statsModal.remove === "function") statsModal.remove();
1465
1568
  statsModal = null;
@@ -1480,6 +1583,113 @@
1480
1583
  return node;
1481
1584
  }
1482
1585
 
1586
+ /* --------------------------- in-app dialogs ------------------------- *
1587
+ * `window.confirm` / `window.alert` are native dialogs. On Windows the
1588
+ * renderer comes back from one without keyboard focus: clicking the
1589
+ * composer does nothing, switching sessions does not help, and only
1590
+ * leaving the app and coming back fixes it. These stay in the page and
1591
+ * never take the window's focus away.
1592
+ * ------------------------------------------------------------------- */
1593
+
1594
+ var confirmBackdrop = null;
1595
+ var confirmPrevious = null;
1596
+ var confirmKey = null;
1597
+
1598
+ /** Close the current dialog; `onConfirm` runs only for an accept. */
1599
+ function closeConfirm(onConfirm) {
1600
+ var backdrop = confirmBackdrop;
1601
+ confirmBackdrop = null;
1602
+ if (backdrop !== null && typeof backdrop.remove === "function") backdrop.remove();
1603
+ if (typeof document !== "undefined" && confirmKey !== null && typeof document.removeEventListener === "function") {
1604
+ document.removeEventListener("keydown", confirmKey);
1605
+ }
1606
+ confirmKey = null;
1607
+ var previous = confirmPrevious;
1608
+ confirmPrevious = null;
1609
+ if (previous !== null && previous !== undefined && previous.isConnected !== false && typeof previous.focus === "function") {
1610
+ try { previous.focus(); } catch (error) { /* the element may be gone */ }
1611
+ }
1612
+ if (typeof onConfirm === "function") onConfirm();
1613
+ }
1614
+
1615
+ /**
1616
+ * Ask before acting, in the page.
1617
+ *
1618
+ * @param question - message shown in the dialog.
1619
+ * @param onConfirm - runs when the user accepts; omitted for a notice.
1620
+ * @param notice - render a single acknowledge button.
1621
+ */
1622
+ function askConfirm(question, onConfirm, notice) {
1623
+ if (typeof document === "undefined") return;
1624
+ closeConfirm();
1625
+ var isNotice = notice === true;
1626
+ confirmPrevious = typeof document.activeElement !== "undefined" ? document.activeElement : null;
1627
+
1628
+ var backdrop = statsDiv("wsr-modal-backdrop");
1629
+ backdrop.setAttribute("data-wsr-confirm", isNotice ? "notice" : "confirm");
1630
+ var panel = statsDiv("wsr-confirm");
1631
+ panel.setAttribute("role", "dialog");
1632
+ panel.setAttribute("aria-modal", "true");
1633
+ panel.setAttribute("tabindex", "-1");
1634
+ panel.appendChild(statsDiv("wsr-confirm-text", question));
1635
+
1636
+ var actions = statsDiv("wsr-confirm-actions");
1637
+ var cancel = document.createElement("button");
1638
+ cancel.type = "button";
1639
+ cancel.className = "wsr-qcancel";
1640
+ cancel.textContent = t("confirm.cancel");
1641
+ cancel.addEventListener("click", function (event) {
1642
+ if (event !== undefined && typeof event.stopPropagation === "function") event.stopPropagation();
1643
+ closeConfirm(null);
1644
+ });
1645
+ var accept = document.createElement("button");
1646
+ accept.type = "button";
1647
+ accept.className = "wsr-qsubmit";
1648
+ accept.setAttribute("data-wsr-confirm-ok", "true");
1649
+ accept.textContent = t("confirm.ok");
1650
+ accept.addEventListener("click", function (event) {
1651
+ if (event !== undefined && typeof event.stopPropagation === "function") event.stopPropagation();
1652
+ closeConfirm(isNotice ? null : onConfirm);
1653
+ });
1654
+ if (!isNotice) actions.appendChild(cancel);
1655
+ actions.appendChild(accept);
1656
+ panel.appendChild(actions);
1657
+
1658
+ panel.addEventListener("click", function (event) {
1659
+ if (event !== undefined && typeof event.stopPropagation === "function") event.stopPropagation();
1660
+ });
1661
+ backdrop.addEventListener("click", function (event) {
1662
+ if (event === undefined || event.target === backdrop) closeConfirm(null);
1663
+ });
1664
+ backdrop.appendChild(panel);
1665
+ document.body.appendChild(backdrop);
1666
+ confirmBackdrop = backdrop;
1667
+
1668
+ confirmKey = function (event) {
1669
+ if (event === undefined) return;
1670
+ if (event.key === "Escape") {
1671
+ if (typeof event.preventDefault === "function") event.preventDefault();
1672
+ closeConfirm(null);
1673
+ return;
1674
+ }
1675
+ if (event.key === "Enter" && !isNotice) {
1676
+ if (typeof event.preventDefault === "function") event.preventDefault();
1677
+ closeConfirm(onConfirm);
1678
+ }
1679
+ if (event.key === "Enter" && isNotice) {
1680
+ if (typeof event.preventDefault === "function") event.preventDefault();
1681
+ closeConfirm(null);
1682
+ }
1683
+ };
1684
+ if (typeof document.addEventListener === "function") document.addEventListener("keydown", confirmKey);
1685
+ try { accept.focus(); } catch (error) { /* focus is best effort */ }
1686
+ }
1687
+
1688
+ /** A one-button notice, used when a request fails. */
1689
+ function askNotice(message) {
1690
+ askConfirm(message, null, true);
1691
+ }
1692
+
1483
1693
  /** One table row: source, calls, argument tokens, result tokens, total, share. */
1484
1694
  function statsRow(label, calls, args, results, total, share, dimArgs) {
1485
1695
  var row = document.createElement("div");
@@ -1628,6 +1838,99 @@
1628
1838
  return "hsl(" + hue + ", " + saturation + "%, " + lightness + "%)";
1629
1839
  }
1630
1840
 
1841
+ var AMPLIFIED_KIND = {
1842
+ results: ["stats.amplified.results", "#4f8ef7"],
1843
+ args: ["stats.amplified.args", "#8fa3c8"],
1844
+ agent: ["stats.amplified.agent", "#7a6cff"],
1845
+ user: ["stats.amplified.user", "#6fbf73"],
1846
+ system: ["stats.amplified.system", "#c9a227"],
1847
+ };
1848
+
1849
+ /**
1850
+ * The bill's shape, then its amplified ranking.
1851
+ *
1852
+ * A step's token count is just "context at that moment", which is nearly
1853
+ * the same on every step; the number that explains the bill is a content
1854
+ * block's tokens times the number of later steps that re-read it. The
1855
+ * host half computes that attribution; this only draws it.
1856
+ */
1857
+ function buildAmplified(stats) {
1858
+ var amplified = stats.amplified;
1859
+ if (amplified === null || amplified === undefined || !Array.isArray(amplified.series)) return null;
1860
+ var bill = Number(amplified.bill) || 0;
1861
+ var section = statsDiv("wsr-amplified");
1862
+
1863
+ var head = statsDiv("wsr-amplified-head");
1864
+ head.appendChild(statsDiv("wsr-amplified-title", t("stats.amplified.title")));
1865
+ head.appendChild(statsDiv("wsr-amplified-summary", t("stats.amplified.summary", {
1866
+ bill: formatTokens(bill),
1867
+ share: formatShare(Number(amplified.share) || 0),
1868
+ attributed: formatTokens(amplified.attributed || 0),
1869
+ })));
1870
+ section.appendChild(head);
1871
+
1872
+ var series = amplified.series;
1873
+ var largest = 1;
1874
+ for (var i = 0; i < series.length; i += 1) {
1875
+ if (Number(series[i].context) > largest) largest = Number(series[i].context);
1876
+ }
1877
+ var chart = statsDiv("wsr-context-chart");
1878
+ for (var j = 0; j < series.length; j += 1) {
1879
+ var bar = statsDiv("wsr-context-bar");
1880
+ bar.style.height = Math.max(2, Math.round((Number(series[j].context) / largest) * 100)) + "%";
1881
+ bar.setAttribute("title", t("stats.amplified.point", { step: String(series[j].step), context: formatTokens(series[j].context) }));
1882
+ chart.appendChild(bar);
1883
+ }
1884
+ section.appendChild(chart);
1885
+ section.appendChild(statsDiv("wsr-context-caption", t("stats.amplified.contextCaption")));
1886
+
1887
+ var kinds = amplified.byKind || [];
1888
+ if (kinds.length > 0) {
1889
+ var legend = statsDiv("wsr-kind-legend");
1890
+ for (var k = 0; k < kinds.length; k += 1) {
1891
+ var kind = kinds[k];
1892
+ var known = AMPLIFIED_KIND[kind.kind];
1893
+ var item = statsDiv("wsr-kind");
1894
+ var dot = statsDiv("wsr-kind-dot");
1895
+ dot.style.background = known === undefined ? "#9aa0a6" : known[1];
1896
+ item.appendChild(dot);
1897
+ item.appendChild(statsDiv("", t(known === undefined ? kind.kind : known[0]) + " " + formatShare(kind.share || 0)));
1898
+ legend.appendChild(item);
1899
+ }
1900
+ section.appendChild(legend);
1901
+ }
1902
+
1903
+ var list = statsDiv("wsr-amplified-list");
1904
+ var blocks = amplified.blocks || [];
1905
+ if (blocks.length === 0) list.appendChild(statsDiv("wsr-amplified-empty", t("stats.amplified.empty")));
1906
+ for (var b = 0; b < blocks.length; b += 1) {
1907
+ var block = blocks[b];
1908
+ var known = AMPLIFIED_KIND[block.kind];
1909
+ var row = statsDiv("wsr-amplified-row");
1910
+ var main = statsDiv("wsr-amplified-main");
1911
+ main.appendChild(statsDiv("wsr-amplified-name", block.kind === "tool" ? String(block.name) : t(known === undefined ? block.kind : known[0])));
1912
+ if (typeof block.detail === "string" && block.detail !== "") main.appendChild(statsDiv("wsr-amplified-detail", block.detail));
1913
+ main.appendChild(statsDiv("wsr-amplified-meta", t("stats.amplified.meta", {
1914
+ entry: String(block.entry),
1915
+ tokens: formatTokens(block.tokens),
1916
+ remaining: String(block.remaining),
1917
+ })));
1918
+ row.appendChild(main);
1919
+ row.appendChild(statsDiv("wsr-amplified-value", formatTokens(block.amplified)));
1920
+ row.appendChild(statsDiv("wsr-amplified-share", formatShare(block.share || 0)));
1921
+ if (Number(block.remaining) > 0 && Number(block.saving) > 0) {
1922
+ row.appendChild(statsDiv("wsr-amplified-if", t("stats.amplified.whatIf", {
1923
+ save: formatTokens(block.saving),
1924
+ share: formatShare(Number(block.saving) / (bill > 0 ? bill : 1)),
1925
+ })));
1926
+ }
1927
+ list.appendChild(row);
1928
+ }
1929
+ section.appendChild(list);
1930
+ section.appendChild(statsDiv("wsr-stats-note", t("stats.amplified.note")));
1931
+ return section;
1932
+ }
1933
+
1631
1934
  function renderStats(body, stats) {
1632
1935
  body.textContent = "";
1633
1936
  while (body.firstChild !== null) body.removeChild(body.firstChild);
@@ -1652,6 +1955,10 @@
1652
1955
  }
1653
1956
  body.appendChild(grid);
1654
1957
 
1958
+ /* Three views instead of one long page: distribution, amplification,
1959
+ details. The summary cards stay above the tabs for every view. */
1960
+ var amplifiedSection = buildAmplified(stats);
1961
+
1655
1962
  var tools = estimate.tools || [];
1656
1963
  var mode = argModeOf();
1657
1964
  var movedArgs = 0;
@@ -1704,16 +2011,12 @@
1704
2011
  var largest = 1;
1705
2012
  for (var m = 0; m < entries.length; m += 1) if (entries[m].value > largest) largest = entries[m].value;
1706
2013
  for (var k = 0; k < entries.length; k += 1) chart.appendChild(chartBar(entries[k], largest));
1707
- body.appendChild(chart);
2014
+ var distributionPanel = statsDiv("wsr-stats-panel");
2015
+ distributionPanel.appendChild(chart);
2016
+ distributionPanel.appendChild(statsDiv("wsr-stats-note", t("stats.note")));
1708
2017
 
1709
- /* The table is the detail view: folded away until asked for. */
1710
- var toggle = document.createElement("button");
1711
- toggle.type = "button";
1712
- toggle.className = "wsr-details-toggle";
1713
- toggle.textContent = t("stats.details.show");
1714
-
1715
- var details = statsDiv("wsr-stats-details");
1716
- details.style.display = "none";
2018
+ /* The table is now its own tab instead of a folded section. */
2019
+ var detailsPanel = statsDiv("wsr-stats-panel wsr-stats-details");
1717
2020
 
1718
2021
  var table = statsDiv("wsr-stats-table");
1719
2022
  var head = document.createElement("div");
@@ -1729,24 +2032,57 @@
1729
2032
  var toolValue = mode === "agent" ? toolResults : (toolRow.total || toolArgs + toolResults);
1730
2033
  table.appendChild(statsRow(toolRow.name, toolRow.calls, toolArgs, toolResults, toolValue, shareOf(toolValue), mode === "agent"));
1731
2034
  }
1732
- details.appendChild(table);
1733
- details.appendChild(statsDiv("wsr-stats-detail", t("stats.agentDetail", {
2035
+ detailsPanel.appendChild(table);
2036
+ detailsPanel.appendChild(statsDiv("wsr-stats-detail", t("stats.agentDetail", {
1734
2037
  reasoning: formatTokens(agent.reasoning),
1735
2038
  text: formatTokens(agent.text),
1736
2039
  user: formatTokens(agent.user),
1737
2040
  system: formatTokens(agent.system),
1738
2041
  })));
1739
-
1740
- toggle.addEventListener("click", function () {
1741
- var open = details.style.display !== "none";
1742
- details.style.display = open ? "none" : "";
1743
- toggle.textContent = open ? t("stats.details.show") : t("stats.details.hide");
1744
- });
1745
-
1746
- body.appendChild(toggle);
1747
- body.appendChild(details);
1748
- body.appendChild(statsDiv("wsr-stats-note", t("stats.note")));
1749
- if (mode === "agent") body.appendChild(statsDiv("wsr-stats-note", t("stats.argModeNote")));
2042
+ if (mode === "agent") detailsPanel.appendChild(statsDiv("wsr-stats-note", t("stats.argModeNote")));
2043
+
2044
+ var tabs = statsDiv("wsr-stats-tabs");
2045
+ tabs.setAttribute("role", "tablist");
2046
+ var panels = statsDiv("wsr-stats-panels");
2047
+ var defs = [["distribution", "stats.tab.distribution", distributionPanel]];
2048
+ if (amplifiedSection !== null) {
2049
+ var amplifiedPanel = statsDiv("wsr-stats-panel");
2050
+ amplifiedPanel.appendChild(amplifiedSection);
2051
+ defs.push(["amplified", "stats.tab.amplified", amplifiedPanel]);
2052
+ }
2053
+ defs.push(["details", "stats.tab.details", detailsPanel]);
2054
+ var tabButtons = {};
2055
+ var selectTab = function (id) {
2056
+ statsTab = id;
2057
+ for (var index = 0; index < defs.length; index += 1) {
2058
+ var def = defs[index];
2059
+ var active = def[0] === id;
2060
+ if (tabButtons[def[0]] !== undefined) {
2061
+ tabButtons[def[0]].className = "wsr-stats-tab" + (active ? " wsr-stats-tab-active" : "");
2062
+ tabButtons[def[0]].setAttribute("aria-selected", active ? "true" : "false");
2063
+ }
2064
+ def[2].style.display = active ? "" : "none";
2065
+ }
2066
+ };
2067
+ for (var d = 0; d < defs.length; d += 1) {
2068
+ (function (def) {
2069
+ var button = document.createElement("button");
2070
+ button.type = "button";
2071
+ button.className = "wsr-stats-tab";
2072
+ button.setAttribute("role", "tab");
2073
+ button.setAttribute("data-wsr-stats-tab", def[0]);
2074
+ button.textContent = t(def[1]);
2075
+ button.addEventListener("click", function () { selectTab(def[0]); });
2076
+ tabButtons[def[0]] = button;
2077
+ tabs.appendChild(button);
2078
+ panels.appendChild(def[2]);
2079
+ })(defs[d]);
2080
+ }
2081
+ var initialTab = statsTab;
2082
+ if (initialTab === "amplified" && amplifiedSection === null) initialTab = "distribution";
2083
+ selectTab(initialTab);
2084
+ body.appendChild(tabs);
2085
+ body.appendChild(panels);
1750
2086
  }
1751
2087
 
1752
2088
  function openStatsPanel(sessionId) {
@@ -1869,36 +2205,37 @@
1869
2205
  if (!isCurrent) {
1870
2206
  row.addEventListener("click", function () {
1871
2207
  var label = (item.title && String(item.title)) || baseName(item.path);
1872
- if (typeof window.confirm !== "function" || !window.confirm(t("move.confirm", { workspace: label }))) return;
1873
- body.textContent = t("move.working");
1874
- fetch("/ws-recency/session-move?sessionId=" + encodeURIComponent(sessionId), {
1875
- method: "POST",
1876
- headers: { "content-type": "application/json" },
1877
- body: JSON.stringify({ sessionId: sessionId, workspaceId: item.workspaceId }),
1878
- })
1879
- .then(function (response) {
1880
- return response.text().then(function (text) {
1881
- var parsed = null;
1882
- try { parsed = JSON.parse(text); } catch (error) { parsed = null; }
1883
- return { status: response.status, text: text, json: parsed };
1884
- });
2208
+ askConfirm(t("move.confirm", { workspace: label }), function () {
2209
+ body.textContent = t("move.working");
2210
+ fetch("/ws-recency/session-move?sessionId=" + encodeURIComponent(sessionId), {
2211
+ method: "POST",
2212
+ headers: { "content-type": "application/json" },
2213
+ body: JSON.stringify({ sessionId: sessionId, workspaceId: item.workspaceId }),
1885
2214
  })
1886
- .then(function (result) {
1887
- if (result.json !== null && result.json.ok === true) {
1888
- if (result.json.repaired === true) {
1889
- body.textContent = t("move.repaired", { workspace: label });
2215
+ .then(function (response) {
2216
+ return response.text().then(function (text) {
2217
+ var parsed = null;
2218
+ try { parsed = JSON.parse(text); } catch (error) { parsed = null; }
2219
+ return { status: response.status, text: text, json: parsed };
2220
+ });
2221
+ })
2222
+ .then(function (result) {
2223
+ if (result.json !== null && result.json.ok === true) {
2224
+ if (result.json.repaired === true) {
2225
+ body.textContent = t("move.repaired", { workspace: label });
2226
+ return;
2227
+ }
2228
+ body.textContent = t("move.done", { workspace: label });
2229
+ if (result.json.live === true) body.textContent += t("move.doneLive");
1890
2230
  return;
1891
2231
  }
1892
- body.textContent = t("move.done", { workspace: label });
1893
- if (result.json.live === true) body.textContent += t("move.doneLive");
1894
- return;
1895
- }
1896
- var reason = (result.json !== null && result.json.error) || (result.text || "").trim().slice(0, 160) || "(empty response)";
1897
- body.textContent = t("move.failed") + "HTTP " + result.status + " \u00b7 " + reason;
1898
- })
1899
- .catch(function (error) {
1900
- body.textContent = t("move.failed") + (error && error.message ? error.message : error);
1901
- });
2232
+ var reason = (result.json !== null && result.json.error) || (result.text || "").trim().slice(0, 160) || "(empty response)";
2233
+ body.textContent = t("move.failed") + "HTTP " + result.status + " \u00b7 " + reason;
2234
+ })
2235
+ .catch(function (error) {
2236
+ body.textContent = t("move.failed") + (error && error.message ? error.message : error);
2237
+ });
2238
+ });
1902
2239
  });
1903
2240
  }
1904
2241
  list.appendChild(row);
@@ -1955,12 +2292,65 @@
1955
2292
  var handoffBaseline = 0;
1956
2293
  var handoffTries = 0;
1957
2294
  var handoffSession = null;
2295
+ /** Wall clock of the instruction/rewrite: older replies are never the answer. */
2296
+ var handoffStartedAt = 0;
2297
+
2298
+ /** Retention-source tag the Host books this plugin's borrows under. */
2299
+ var HANDOFF_SOURCE = "dsh-ws-recency";
1958
2300
 
1959
2301
  /** The instruction the user sends to the current Session. */
1960
2302
  function handoffInstruction() {
1961
2303
  return t("handoff.instruction");
1962
2304
  }
1963
2305
 
2306
+ /** The Host's session service, when this Client provides it. */
2307
+ function sessionsService() {
2308
+ var ctx = data.ctx;
2309
+ if (ctx === null || ctx === undefined || typeof ctx.get !== "function") return null;
2310
+ var sessions;
2311
+ try { sessions = ctx.get("sessions"); } catch (error) { sessions = undefined; }
2312
+ return sessions === undefined ? null : sessions;
2313
+ }
2314
+
2315
+ /**
2316
+ * Send one prompt through the Host's own Session controller.
2317
+ *
2318
+ * The composer path further down is a synthetic key event: it depends on
2319
+ * the editor being mounted, focused, and on the insert and the key landing
2320
+ * in different frames. The Session controller owns a real prompt call, so
2321
+ * a plugin can retain the session, wait until it is open, and hand the text
2322
+ * over - no DOM, no key events, and it works for a session that is not the
2323
+ * one on screen (the "..." menu starts a handoff that way).
2324
+ *
2325
+ * @param sessionId - target Session.
2326
+ * @param text - prompt text, sent as one text block.
2327
+ * @param onUnsent - called when the prompt could not be dispatched.
2328
+ * @returns true when a request was dispatched (its promise may still fail).
2329
+ */
2330
+ function promptSession(sessionId, text, onUnsent) {
2331
+ var sessions = sessionsService();
2332
+ if (sessions !== null && typeof sessions.using === "function") {
2333
+ try {
2334
+ sessions.using(sessionId, { source: HANDOFF_SOURCE }, function (reference) {
2335
+ var binding = reference === null || reference === undefined ? undefined : reference.binding;
2336
+ var session = binding === null || binding === undefined ? undefined : binding.session;
2337
+ if (session === undefined || session === null || typeof session.prompt !== "function") throw new Error("session unavailable");
2338
+ return Promise.resolve(session.prompt([{ type: "text", text: text }], "queue")).then(function (result) {
2339
+ if (result !== null && result !== undefined && result.ok === false) throw new Error("the session refused the prompt");
2340
+ return result;
2341
+ });
2342
+ }).catch(function () {
2343
+ if (typeof onUnsent === "function") onUnsent();
2344
+ });
2345
+ return true;
2346
+ } catch (error) {
2347
+ /* fall through to the caller's own path */
2348
+ }
2349
+ }
2350
+ if (typeof onUnsent === "function") onUnsent();
2351
+ return false;
2352
+ }
2353
+
1964
2354
  function handoffPost(payload) {
1965
2355
  return fetch("/ws-recency/handoff", {
1966
2356
  method: "POST",
@@ -2078,9 +2468,12 @@
2078
2468
  }, attempt === 0 ? 250 : 800);
2079
2469
  }
2080
2470
 
2081
- /** Write text into the composer and send it, if the editor is reachable. */
2082
- function sendToSession(text) {
2083
- if (typeof document === "undefined" || typeof text !== "string" || text === "") return false;
2471
+ /** Fallback: write into the open composer and press Enter until it leaves. */
2472
+ function sendThroughComposer(sessionId, text) {
2473
+ if (typeof document === "undefined") return false;
2474
+ /* Never write into another conversation's composer: the open editor
2475
+ belongs to the session on screen, not to the target id. */
2476
+ if (currentConversationId() !== sessionId) return false;
2084
2477
  var editor = composerEditor();
2085
2478
  if (editor === null || editor === undefined) return false;
2086
2479
  if (!writeIntoEditor(editor, text)) return false;
@@ -2088,6 +2481,24 @@
2088
2481
  return true;
2089
2482
  }
2090
2483
 
2484
+ /**
2485
+ * Send one prompt to one Session.
2486
+ *
2487
+ * Preferred: the Host's Session controller (see promptSession). Only when
2488
+ * that seam is unavailable does it fall back to writing into the composer
2489
+ * of the session on screen and pressing Enter; a target that is not on
2490
+ * screen then just reports "press Enter" on the card instead of sending
2491
+ * the instruction into the wrong conversation.
2492
+ */
2493
+ function sendToSession(sessionId, text) {
2494
+ if (typeof text !== "string" || text === "") return false;
2495
+ var fallback = function () {
2496
+ if (sendThroughComposer(sessionId, text)) return;
2497
+ setHandoffState({ sessionId: sessionId, phase: "running", block: "", needsEnter: true });
2498
+ };
2499
+ return promptSession(sessionId, text, fallback);
2500
+ }
2501
+
2091
2502
  function stopHandoffPolling() {
2092
2503
  if (handoffTimer !== null && typeof window.clearTimeout === "function") window.clearTimeout(handoffTimer);
2093
2504
  handoffTimer = null;
@@ -2133,42 +2544,66 @@
2133
2544
  return blocks;
2134
2545
  }
2135
2546
 
2136
- /**
2137
- * Pull the handoff block out of an assistant reply.
2138
- *
2139
- * Both fence kinds are read: the prompt asks for `~~~handoff` (three tildes
2140
- * rarely appear in prose), `' + '```handoff` stays supported for older replies.
2141
- * A fence only counts when it owns its line and is closed by the same kind,
2142
- * so a note that mentions the marker in a sentence cannot cut itself short,
2143
- * and a reply that is still streaming is not captured half-written.
2144
- */
2145
- function handoffBlockOf(text) {
2146
- if (typeof text !== "string") return "";
2147
- var bodyOf = function (openedAt, openedLength, mark) {
2148
- var closer = new RegExp("^[ \\t]*" + mark + "[ \\t]*$", "m");
2149
- var rest = text.slice(openedAt + openedLength);
2150
- var closed = closer.exec(rest);
2151
- if (closed === null) return "";
2152
- return rest.slice(0, closed.index).replace(/^\r?\n/, "").trim();
2153
- };
2154
- var tagged = /^[ \t]*(```|~~~)[ \t]*handoff[ \t]*$/m.exec(text);
2155
- if (tagged !== null) return bodyOf(tagged.index, tagged[0].length, tagged[1]);
2156
- var fence = /^[ \t]*(```|~~~)[ \t]*[a-zA-Z0-9_-]*[ \t]*$/gm;
2157
- var opened;
2158
- while ((opened = fence.exec(text)) !== null) {
2159
- var candidate = bodyOf(opened.index, opened[0].length, opened[1]);
2160
- if (candidate !== "" && candidate.indexOf("#") !== -1) return candidate;
2161
- var next = text.indexOf("\n", opened.index + opened[0].length);
2162
- if (next === -1) return "";
2163
- fence.lastIndex = next + 1;
2164
- }
2165
- return "";
2166
- }
2167
-
2168
- /** Start the watch: the next reply that carries a handoff block becomes the card. */
2547
+ /**
2548
+ * Pull the handoff block out of an assistant reply.
2549
+ *
2550
+ * Both fence kinds are read: the prompt asks for `~~~handoff` (three tildes
2551
+ * rarely appear in prose), `' + '```handoff` stays supported for older replies.
2552
+ * A fence only counts when it owns its line and is closed by the same kind,
2553
+ * so a note that mentions the marker in a sentence cannot cut itself short,
2554
+ * and a reply that is still streaming is not captured half-written.
2555
+ */
2556
+ function handoffBlockOf(text) {
2557
+ if (typeof text !== "string") return "";
2558
+ var bodyOf = function (openedAt, openedLength, mark) {
2559
+ var closer = new RegExp("^[ \\t]*" + mark + "[ \\t]*$", "m");
2560
+ var rest = text.slice(openedAt + openedLength);
2561
+ var closed = closer.exec(rest);
2562
+ if (closed === null) return "";
2563
+ return rest.slice(0, closed.index).replace(/^\r?\n/, "").trim();
2564
+ };
2565
+ var tagged = /^[ \t]*(```|~~~)[ \t]*handoff[ \t]*$/m.exec(text);
2566
+ if (tagged !== null) return bodyOf(tagged.index, tagged[0].length, tagged[1]);
2567
+ var fence = /^[ \t]*(```|~~~)[ \t]*[a-zA-Z0-9_-]*[ \t]*$/gm;
2568
+ var opened;
2569
+ while ((opened = fence.exec(text)) !== null) {
2570
+ var candidate = bodyOf(opened.index, opened[0].length, opened[1]);
2571
+ if (candidate !== "" && candidate.indexOf("#") !== -1) return candidate;
2572
+ var next = text.indexOf("\n", opened.index + opened[0].length);
2573
+ if (next === -1) return "";
2574
+ fence.lastIndex = next + 1;
2575
+ }
2576
+ return "";
2577
+ }
2578
+
2579
+ /**
2580
+ * Whether a tail answer is a *new, finished* reply worth reading.
2581
+ *
2582
+ * Three guards, because the tail always reports the newest assistant text
2583
+ * in the whole log:
2584
+ * - the session must have no open turn: a freshly started turn logs
2585
+ * assistant messages with only reasoning/tool-call blocks, and if the
2586
+ * previous reply happened to be a handoff note the old text would be
2587
+ * read as the answer while the model is still working;
2588
+ * - the text must be newer than the moment the instruction went out;
2589
+ * - an older Host without `seq`/`turnOpen` falls back to the timestamp.
2590
+ */
2591
+ function handoffAnswerReady(answer, baseline) {
2592
+ if (answer === null || answer === undefined || answer.ok !== true) return false;
2593
+ if (answer.turnOpen === true) return false;
2594
+ var seqFresh = typeof answer.textSeq === "number" && answer.textSeq !== 0 && typeof baseline === "number" && answer.textSeq > baseline;
2595
+ var timeFresh = typeof answer.at === "number" && answer.at > 0 && handoffStartedAt > 0 && answer.at > handoffStartedAt;
2596
+ if (seqFresh || timeFresh) return true;
2597
+ /* A Host too old to report either marker: the caller's count is all we have. */
2598
+ if ((typeof answer.textSeq !== "number" || answer.textSeq === 0) && (typeof answer.at !== "number" || answer.at === 0)) return true;
2599
+ return false;
2600
+ }
2601
+
2602
+ /** Start the watch: the next finished reply that carries a handoff block becomes the card. */
2169
2603
  function watchHandoff(sessionId) {
2170
2604
  handoffSession = sessionId;
2171
2605
  handoffTries = 0;
2606
+ handoffStartedAt = Date.now();
2172
2607
  stopHandoffPolling();
2173
2608
  if (typeof window === "undefined") return;
2174
2609
  function tick() {
@@ -2177,16 +2612,24 @@
2177
2612
  handoffPost({ action: "tail", sessionId: sessionId }).then(function (answer) {
2178
2613
  if (handoffSession !== sessionId) return;
2179
2614
  if (answer !== null && answer.ok === true) {
2180
- var replies = typeof answer.replies === "number" ? answer.replies : 0;
2181
- if (replies > handoffBaseline) {
2615
+ var reached = typeof answer.lastSeq === "number"
2616
+ ? answer.lastSeq > handoffBaseline
2617
+ : (typeof answer.replies === "number" ? answer.replies > handoffBaseline : false);
2618
+ if (reached && handoffAnswerReady(answer, handoffBaseline)) {
2182
2619
  var found = handoffBlockOf(answer.text);
2183
2620
  if (found !== "") {
2184
- setHandoffState({ sessionId: sessionId, phase: "ready", block: found, needsEnter: false });
2621
+ setHandoffState({
2622
+ sessionId: sessionId,
2623
+ phase: "ready",
2624
+ block: found,
2625
+ needsEnter: false,
2626
+ turn: typeof answer.turn === "number" ? answer.turn : undefined,
2627
+ });
2185
2628
  return;
2186
2629
  }
2187
- /* Keep looking at this same reply: it may still be streaming, and a
2188
- reply without a block is not a reason to move past it. */
2189
2630
  }
2631
+ /* Not ready yet (turn still open, text not newer, or no block in
2632
+ this reply): keep looking at the same session. */
2190
2633
  }
2191
2634
  if (handoffTries > 150) {
2192
2635
  setHandoffState({ sessionId: "", phase: "idle", block: "", needsEnter: false });
@@ -2198,10 +2641,12 @@
2198
2641
  handoffTimer = window.setTimeout(tick, 4000);
2199
2642
  });
2200
2643
  }
2201
- /* The baseline is the reply count before the instruction is answered. */
2644
+ /* The baseline is where the log stood before the instruction is answered. */
2202
2645
  handoffPost({ action: "tail", sessionId: sessionId }).then(function (answer) {
2203
2646
  if (handoffSession !== sessionId) return;
2204
- handoffBaseline = answer !== null && answer.ok === true && typeof answer.replies === "number" ? answer.replies : 0;
2647
+ handoffBaseline = answer !== null && answer.ok === true && typeof answer.lastSeq === "number"
2648
+ ? answer.lastSeq
2649
+ : (answer !== null && answer.ok === true && typeof answer.replies === "number" ? answer.replies : 0);
2205
2650
  handoffTimer = window.setTimeout(tick, 1500);
2206
2651
  }).catch(function () {
2207
2652
  handoffTimer = window.setTimeout(tick, 3000);
@@ -2211,44 +2656,90 @@
2211
2656
  /** The turn action: send the instruction and wait for the block. */
2212
2657
  function startHandoff(sessionId) {
2213
2658
  if (typeof sessionId !== "string" || sessionId === "") return;
2214
- var sent = sendToSession(handoffInstruction());
2215
- setHandoffState({ sessionId: sessionId, phase: "running", block: "", needsEnter: sent !== true });
2659
+ /* The card starts in its "working" state; if the Host refuses the send
2660
+ the fallback flips needsEnter so the card tells the user to press
2661
+ Enter instead of pretending the handoff is running. */
2662
+ var startTurn = latestTurnNumber();
2663
+ setHandoffState({ sessionId: sessionId, phase: "running", block: "", needsEnter: false, afterTurn: startTurn === null ? undefined : startTurn });
2664
+ sendToSession(sessionId, handoffInstruction());
2216
2665
  watchHandoff(sessionId);
2217
2666
  }
2218
2667
 
2219
- /** The card carries it over: open a fresh Session in the same workspace. */
2668
+ /**
2669
+ * Fallback carry: the Host opened a blank session and keeps the note as an
2670
+ * unsent draft (the pre-0.35 behaviour). Only used when the Session
2671
+ * controller seam is missing or the workspace is unknown.
2672
+ */
2673
+ function startHandoffSession(workspaceId, prompt) {
2674
+ var service = data.service;
2675
+ if (service !== null && service !== undefined && typeof service.startSession === "function") {
2676
+ try {
2677
+ service.startSession(workspaceId, { prompt: prompt, whenDraftExists: "replace" });
2678
+ resetHandoff();
2679
+ autoSendDraft(t("handoff.preamble").slice(0, 12));
2680
+ return true;
2681
+ } catch (error) {
2682
+ /* fall through to the clipboard */
2683
+ }
2684
+ }
2685
+ try {
2686
+ if (navigator !== undefined && navigator.clipboard !== undefined) navigator.clipboard.writeText(prompt);
2687
+ } catch (error) {
2688
+ /* clipboard unavailable */
2689
+ }
2690
+ resetHandoff();
2691
+ return false;
2692
+ }
2693
+
2694
+ /**
2695
+ * The card carries it over: open a fresh Session in the same workspace and
2696
+ * put the note in as its first prompt through the Host's own API.
2697
+ *
2698
+ * `connectWorkspace` creates (or reuses) the blank and returns its id
2699
+ * without navigating; `sessions.using` retains that session until it is
2700
+ * open, so the prompt is the session's real first message - nothing has to
2701
+ * be typed into a composer and no Enter is synthesised.
2702
+ */
2220
2703
  function carryHandoff(sessionId, block) {
2221
2704
  var text = typeof block === "string" ? block.trim() : "";
2222
2705
  if (text === "") return;
2223
2706
  handoffPost({ action: "save", sessionId: sessionId, text: text }).catch(function () { return null; }).then(function () {
2224
2707
  var owner = workspaceOfSession(sessionId);
2225
- var workspaceId = owner === null ? undefined : owner.workspaceId;
2708
+ var workspaceId = owner === null || owner === undefined ? undefined : owner.workspaceId;
2226
2709
  var service = data.service;
2710
+ var sessions = sessionsService();
2227
2711
  var prompt = t("handoff.preamble") + "\n\n" + text;
2228
- if (service !== null && service !== undefined && typeof service.startSession === "function") {
2229
- try {
2230
- service.startSession(workspaceId, { prompt: prompt, whenDraftExists: "replace" });
2712
+ if (workspaceId !== undefined
2713
+ && service !== null && service !== undefined
2714
+ && typeof service.connectWorkspace === "function"
2715
+ && typeof service.openSession === "function"
2716
+ && sessions !== null && typeof sessions.using === "function") {
2717
+ service.connectWorkspace(workspaceId).then(function (newSessionId) {
2718
+ try { service.openSession(newSessionId); } catch (error) { /* the prompt still lands */ }
2719
+ return sessions.using(newSessionId, { source: HANDOFF_SOURCE }, function (reference) {
2720
+ var binding = reference === null || reference === undefined ? undefined : reference.binding;
2721
+ var session = binding === null || binding === undefined ? undefined : binding.session;
2722
+ if (session === undefined || session === null || typeof session.prompt !== "function") throw new Error("session unavailable");
2723
+ return session.prompt([{ type: "text", text: prompt }], "queue");
2724
+ });
2725
+ }).then(function (result) {
2726
+ if (result !== null && result !== undefined && result.ok === false) throw new Error("the session refused the prompt");
2231
2727
  resetHandoff();
2232
- autoSendDraft(t("handoff.preamble").slice(0, 12));
2233
- return;
2234
- } catch (error) {
2235
- /* fall through */
2236
- }
2237
- }
2238
- try {
2239
- if (navigator !== undefined && navigator.clipboard !== undefined) navigator.clipboard.writeText(prompt);
2240
- } catch (error) {
2241
- /* clipboard unavailable */
2728
+ }).catch(function () {
2729
+ startHandoffSession(workspaceId, prompt);
2730
+ });
2731
+ return;
2242
2732
  }
2243
- resetHandoff();
2733
+ startHandoffSession(workspaceId, prompt);
2244
2734
  });
2245
2735
  }
2246
2736
 
2247
2737
  /** Ask the current Session to rewrite the handoff with the user's adjustments. */
2248
2738
  function rewriteHandoff(sessionId, extra) {
2249
2739
  var text = extra.trim() === "" ? t("handoff.regeneratePrompt") : t("handoff.adjustPrompt") + "\n\n" + extra.trim();
2250
- var sent = sendToSession(text);
2251
- setHandoffState({ sessionId: sessionId, phase: "running", block: "", needsEnter: sent !== true });
2740
+ var startTurn = latestTurnNumber();
2741
+ setHandoffState({ sessionId: sessionId, phase: "running", block: "", needsEnter: false, afterTurn: startTurn === null ? undefined : startTurn });
2742
+ sendToSession(sessionId, text);
2252
2743
  handoffBaseline = 0;
2253
2744
  handoffTries = 0;
2254
2745
  handoffSession = sessionId;
@@ -2280,6 +2771,23 @@
2280
2771
 
2281
2772
  var state = live;
2282
2773
  if (state === null || state === undefined || state.sessionId !== sessionId) return null;
2774
+ /* One rendered `turnTail` per turn: show the card only on the turn the
2775
+ note came from, and the progress line only on the newest turn (the
2776
+ open one). Props without a turn number keep the old behaviour. */
2777
+ var turn = props !== undefined && props !== null && typeof props.turn === "number" ? props.turn : null;
2778
+ if (state.phase === "running" && turn !== null) {
2779
+ if (typeof state.afterTurn === "number") {
2780
+ /* Only a turn that started after the click can be the answer. */
2781
+ if (turn <= state.afterTurn) return null;
2782
+ } else {
2783
+ var latest = latestTurnNumber();
2784
+ if (latest !== null && turn !== latest) return null;
2785
+ }
2786
+ }
2787
+ if (state.phase === "ready" && turn !== null) {
2788
+ var target = typeof state.turn === "number" ? state.turn : latestTurnNumber();
2789
+ if (target !== null && turn !== target) return null;
2790
+ }
2283
2791
  if (state.phase === "running") {
2284
2792
  return h("div", { className: "wsr-handoff-live" }, state.needsEnter === true ? t("handoff.pressEnter") : t("handoff.preparing"));
2285
2793
  }
@@ -2380,7 +2888,15 @@
2380
2888
  var Icon = ui.IconDataOutlineRegular;
2381
2889
  return h(Item, {
2382
2890
  icon: typeof Icon === "function" ? h(Icon, {}) : undefined,
2383
- onSelect: function () { openHandoffPanel(props.sessionId); },
2891
+ onSelect: function () {
2892
+ /* Open the conversation first so the running handoff (and later the
2893
+ card) is visible; the prompt itself does not need the composer. */
2894
+ var service = data.service;
2895
+ if (service !== null && service !== undefined && typeof service.openSession === "function") {
2896
+ try { service.openSession(props.sessionId); } catch (error) { /* the send still lands */ }
2897
+ }
2898
+ startHandoff(props.sessionId);
2899
+ },
2384
2900
  }, t("menu.handoff"));
2385
2901
  }
2386
2902
 
@@ -2589,13 +3105,14 @@
2589
3105
  restore.className = "wsr-btn";
2590
3106
  restore.textContent = t("trash.restore");
2591
3107
  restore.addEventListener("click", function () {
2592
- if (typeof window.confirm === "function" && !window.confirm(t("trash.confirmRestore"))) return;
2593
- load(t("trash.working"));
2594
- post({ action: "restore", name: entry.name }).then(function (result) {
2595
- var ok = result.json !== null && result.json.ok === true;
2596
- load(ok ? t("trash.restored") : t("trash.failed") + (result.json && result.json.error ? result.json.error : result.text));
2597
- }).catch(function (error) {
2598
- load(t("trash.failed") + (error && error.message ? error.message : error));
3108
+ askConfirm(t("trash.confirmRestore"), function () {
3109
+ load(t("trash.working"));
3110
+ post({ action: "restore", name: entry.name }).then(function (result) {
3111
+ var ok = result.json !== null && result.json.ok === true;
3112
+ load(ok ? t("trash.restored") : t("trash.failed") + (result.json && result.json.error ? result.json.error : result.text));
3113
+ }).catch(function (error) {
3114
+ load(t("trash.failed") + (error && error.message ? error.message : error));
3115
+ });
2599
3116
  });
2600
3117
  });
2601
3118
  actions.appendChild(restore);
@@ -2605,13 +3122,14 @@
2605
3122
  purge.className = "wsr-btn wsr-btn-danger";
2606
3123
  purge.textContent = t("trash.purge");
2607
3124
  purge.addEventListener("click", function () {
2608
- if (typeof window.confirm === "function" && !window.confirm(t("trash.confirmPurge"))) return;
2609
- load(t("trash.working"));
2610
- post({ action: "purge", name: entry.name }).then(function (result) {
2611
- var ok = result.json !== null && result.json.ok === true;
2612
- load(ok ? t("trash.purged") : t("trash.failed") + (result.json && result.json.error ? result.json.error : result.text));
2613
- }).catch(function (error) {
2614
- load(t("trash.failed") + (error && error.message ? error.message : error));
3125
+ askConfirm(t("trash.confirmPurge"), function () {
3126
+ load(t("trash.working"));
3127
+ post({ action: "purge", name: entry.name }).then(function (result) {
3128
+ var ok = result.json !== null && result.json.ok === true;
3129
+ load(ok ? t("trash.purged") : t("trash.failed") + (result.json && result.json.error ? result.json.error : result.text));
3130
+ }).catch(function (error) {
3131
+ load(t("trash.failed") + (error && error.message ? error.message : error));
3132
+ });
2615
3133
  });
2616
3134
  });
2617
3135
  actions.appendChild(purge);
@@ -2726,13 +3244,14 @@
2726
3244
 
2727
3245
  var act = function (entry, action) {
2728
3246
  var question = action === "restore" ? t("trash.confirmRestore") : t("trash.confirmPurge");
2729
- if (typeof window.confirm === "function" && !window.confirm(question)) return;
2730
- load(t("trash.working"));
2731
- trashPost({ action: action, name: entry.name }).then(function (result) {
2732
- var ok = result.json !== null && result.json.ok === true;
2733
- load(ok ? (action === "restore" ? t("trash.restored") : t("trash.purged")) : t("trash.failed") + (result.json && result.json.error ? result.json.error : result.text));
2734
- }).catch(function (error) {
2735
- load(t("trash.failed") + (error && error.message ? error.message : error));
3247
+ askConfirm(question, function () {
3248
+ load(t("trash.working"));
3249
+ trashPost({ action: action, name: entry.name }).then(function (result) {
3250
+ var ok = result.json !== null && result.json.ok === true;
3251
+ load(ok ? (action === "restore" ? t("trash.restored") : t("trash.purged")) : t("trash.failed") + (result.json && result.json.error ? result.json.error : result.text));
3252
+ }).catch(function (error) {
3253
+ load(t("trash.failed") + (error && error.message ? error.message : error));
3254
+ });
2736
3255
  });
2737
3256
  };
2738
3257
 
@@ -2740,22 +3259,23 @@
2740
3259
  var question = action === "unarchive" ? t("archive.confirmUnarchive")
2741
3260
  : action === "forget" ? t("archive.confirmForget")
2742
3261
  : t("archive.confirmDelete");
2743
- if (typeof window.confirm === "function" && !window.confirm(question)) return;
2744
- load(t("trash.working"));
2745
- trashPost({ action: action, sessionId: entry.sessionId }).then(function (result) {
2746
- if (result.json === null || result.json.ok !== true) {
2747
- load(t("archive.failed") + (result.json && result.json.error ? result.json.error : result.text));
2748
- return;
2749
- }
2750
- if (action === "unarchive") {
2751
- load(t("archive.unarchived") + (result.json.listed === false ? t("archive.noWorkspace") : ""));
2752
- } else if (action === "forget") {
2753
- load(t("archive.forgotten"));
2754
- } else {
2755
- load(t("archive.deleted"));
2756
- }
2757
- }).catch(function (error) {
2758
- load(t("archive.failed") + (error && error.message ? error.message : error));
3262
+ askConfirm(question, function () {
3263
+ load(t("trash.working"));
3264
+ trashPost({ action: action, sessionId: entry.sessionId }).then(function (result) {
3265
+ if (result.json === null || result.json.ok !== true) {
3266
+ load(t("archive.failed") + (result.json && result.json.error ? result.json.error : result.text));
3267
+ return;
3268
+ }
3269
+ if (action === "unarchive") {
3270
+ load(t("archive.unarchived") + (result.json.listed === false ? t("archive.noWorkspace") : ""));
3271
+ } else if (action === "forget") {
3272
+ load(t("archive.forgotten"));
3273
+ } else {
3274
+ load(t("archive.deleted"));
3275
+ }
3276
+ }).catch(function (error) {
3277
+ load(t("archive.failed") + (error && error.message ? error.message : error));
3278
+ });
2759
3279
  });
2760
3280
  };
2761
3281
 
@@ -3257,7 +3777,16 @@
3257
3777
  }
3258
3778
 
3259
3779
  /* Test hook: the card state is a module observable, invisible from outside. */
3260
- exports.__handoff = { current: currentHandoffState, set: setHandoffState, blockOf: handoffBlockOf };
3780
+ exports.__handoff = {
3781
+ current: currentHandoffState,
3782
+ set: setHandoffState,
3783
+ blockOf: handoffBlockOf,
3784
+ readyOf: handoffAnswerReady,
3785
+ start: startHandoff,
3786
+ rewrite: rewriteHandoff,
3787
+ carry: carryHandoff,
3788
+ send: sendToSession,
3789
+ };
3261
3790
 
3262
3791
  exports.name = "dsh-ws-recency";
3263
3792
  exports.inject = inject;