dsh-ws-recency 0.24.1 → 0.25.1

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 +11 -4
  2. package/client.js +569 -133
  3. package/index.js +181 -9
  4. package/package.json +1 -1
package/client.js CHANGED
@@ -107,6 +107,9 @@
107
107
  ".wsr-pin-ws{flex:none;max-width:40%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:11px;color:var(--dsw-alias-label-tertiary)}",
108
108
  ".wsr-pin-unpin{flex:none;border:none;background:transparent;color:var(--dsw-alias-label-tertiary);cursor:pointer;font-size:11px;padding:2px 4px;border-radius:4px;visibility:hidden}",
109
109
  ".wsr-pin-row:hover .wsr-pin-unpin{visibility:visible}",
110
+ ".wsr-pin-row[" + STATE_ATTR + '="running"] .wsr-pin-title{color:#4f8ef7}',
111
+ ".wsr-pin-row[" + STATE_ATTR + '="unread"] .wsr-pin-title{color:#3fae6b}',
112
+ ".wsr-pin-row[" + STATE_ATTR + '="followup"] .wsr-pin-title{color:#d99a2b}',
110
113
  ".wsr-pin-unpin:hover{color:var(--dsw-alias-label-primary)}",
111
114
  ".wsr-pill{box-sizing:border-box;border:none;background:0 0;color:var(--dsw-alias-label-tertiary);font:inherit;font-variant-numeric:tabular-nums;line-height:inherit;white-space:nowrap;border-radius:var(--dsw-radius-sm,6px);display:inline-flex;align-items:center;gap:6px;padding:1px 8px;cursor:pointer}",
112
115
  ".wsr-pill:hover{background:var(--dsw-alias-interactive-bg-hover,rgba(255,255,255,.08));color:var(--dsw-alias-label-secondary,#cfd3d8)}",
@@ -212,6 +215,12 @@
212
215
  ".wsr-btn:hover{background:var(--dsw-alias-interactive-bg-hover,rgba(255,255,255,.08))}",
213
216
  ".wsr-btn-danger{border-color:var(--dsw-alias-state-error-primary,#d9534f);color:var(--dsw-alias-state-error-primary,#d9534f)}",
214
217
  ".wsr-danger{border-color:var(--dsw-alias-state-error-primary,#d9534f);color:var(--dsw-alias-state-error-primary,#d9534f)}",
218
+ /* In-app confirmation: native window.confirm leaves the renderer
219
+ without keyboard focus on Windows (the composer then ignores
220
+ clicks until the app loses and regains focus). */
221
+ ".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}",
222
+ ".wsr-confirm-text{white-space:pre-wrap;font-size:13px;line-height:1.65}",
223
+ ".wsr-confirm-actions{display:flex;justify-content:flex-end;gap:8px}",
215
224
  ".wsr-chart{display:flex;flex-direction:column;gap:6px}",
216
225
  ".wsr-chart-head{display:flex;align-items:center;justify-content:space-between;gap:10px}",
217
226
  ".wsr-chart-title{font-size:11px;color:var(--dsw-alias-label-tertiary)}",
@@ -227,8 +236,6 @@
227
236
  ".wsr-chart-legend-text{white-space:nowrap}",
228
237
  ".wsr-chart-value{text-align:right;font-variant-numeric:tabular-nums}",
229
238
  ".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
239
  ".wsr-stats-details{display:flex;flex-direction:column;gap:8px}",
233
240
  ".wsr-stats-table{display:flex;flex-direction:column}",
234
241
  ".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 +245,35 @@
238
245
  ".wsr-td-strong{font-weight:600}",
239
246
  ".wsr-td-dim{color:var(--dsw-alias-label-tertiary);opacity:.65}",
240
247
  ".wsr-stats-note{color:var(--dsw-alias-label-tertiary);font-size:11px;line-height:1.5}",
248
+ /* Three views, one dialog: distribution, amplification, details. */
249
+ ".wsr-stats-tabs{display:flex;gap:2px;border-bottom:.5px solid rgba(255,255,255,.08)}",
250
+ ".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}",
251
+ ".wsr-stats-tab:hover{color:var(--dsw-alias-label-primary)}",
252
+ ".wsr-stats-tab-active{color:var(--dsw-alias-label-primary);border-bottom-color:var(--dsw-alias-brand-primary,#4f7cff)}",
253
+ ".wsr-stats-panels{display:flex;flex-direction:column;gap:10px}",
254
+ ".wsr-stats-panel{display:flex;flex-direction:column;gap:10px}",
255
+ /* Amplified cost: the bill is the area under the context curve, so the
256
+ ranking is by content x remaining steps, not by step tokens. */
257
+ ".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))}",
258
+ ".wsr-amplified-head{display:flex;align-items:baseline;justify-content:space-between;gap:10px;flex-wrap:wrap}",
259
+ ".wsr-amplified-title{font-size:12px;font-weight:600}",
260
+ ".wsr-amplified-summary{font-size:11px;color:var(--dsw-alias-label-tertiary)}",
261
+ ".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)}",
262
+ ".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))}",
263
+ ".wsr-context-caption{font-size:10px;color:var(--dsw-alias-label-tertiary)}",
264
+ ".wsr-kind-legend{display:flex;flex-wrap:wrap;gap:10px}",
265
+ ".wsr-kind{display:flex;align-items:center;gap:5px;font-size:11px;color:var(--dsw-alias-label-tertiary)}",
266
+ ".wsr-kind-dot{width:8px;height:8px;border-radius:2px;flex:none}",
267
+ ".wsr-amplified-list{display:flex;flex-direction:column;gap:2px}",
268
+ ".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)}",
269
+ ".wsr-amplified-main{min-width:0;display:flex;flex-direction:column;gap:1px}",
270
+ ".wsr-amplified-name{font-size:12px;font-weight:500;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}",
271
+ ".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}",
272
+ ".wsr-amplified-meta{font-size:10px;color:var(--dsw-alias-label-tertiary)}",
273
+ ".wsr-amplified-value{text-align:right;font-weight:600;font-variant-numeric:tabular-nums;font-size:12px}",
274
+ ".wsr-amplified-share{text-align:right;color:var(--dsw-alias-label-tertiary);font-size:11px;font-variant-numeric:tabular-nums}",
275
+ ".wsr-amplified-if{grid-column:1 / -1;font-size:10px;color:var(--dsw-alias-label-tertiary)}",
276
+ ".wsr-amplified-empty{font-size:11px;color:var(--dsw-alias-label-tertiary)}",
241
277
  ".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
278
  ".wsr-toggle:hover{color:var(--dsw-alias-label-secondary)}",
243
279
  '[' + STATE_ATTR + '="running"] [class*="_title"]{color:#4f8ef7}',
@@ -378,14 +414,30 @@
378
414
  "archive.workspace": "工作区",
379
415
  "move.failed": "移动失败:",
380
416
  "stats.chart": "消耗分布",
381
- "stats.details.show": "显示明细 ▾",
382
- "stats.details.hide": "收起明细 ▴",
383
417
  "composer.analysis": "用量分析",
384
418
  "stats.legend.args": "参数(模型写的)",
385
419
  "stats.legend.results": "结果(环境返回的)",
386
420
  "stats.argModeNote": "当前把工具参数计入主 agent:每个工具只算返回结果,表格里「参数」列显示为淡色(那些 token 记在主 agent 那一行)。",
421
+ "stats.amplified.title": "放大成本(账单归因)",
422
+ "stats.amplified.summary": "账单 {bill} token;可归因内容经重读放大后占 {share}({attributed})",
423
+ "stats.amplified.contextCaption": "每步上下文(面积≈账单):越早进入的内容被重读越多",
424
+ "stats.amplified.point": "第 {step} 步 · {context}",
425
+ "stats.amplified.meta": "第 {entry} 步进入 · {tokens} token × {remaining} 次重读",
426
+ "stats.amplified.whatIf": "若压到 20%,可省 {save}({share})",
427
+ "stats.amplified.empty": "没有可归因的放大内容(压缩后或旧日志可能缺失)",
428
+ "stats.amplified.note": "放大成本按内容长度估算;账单总量来自真实 usage。思维链通常不回传,故未计入。",
429
+ "stats.amplified.results": "工具结果",
430
+ "stats.amplified.args": "工具参数",
431
+ "stats.amplified.agent": "主 agent 输出",
432
+ "stats.amplified.user": "用户消息",
433
+ "stats.amplified.system": "系统消息",
434
+ "stats.tab.distribution": "分布统计",
435
+ "stats.tab.amplified": "放大归因",
436
+ "stats.tab.details": "明细",
387
437
  "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
438
  "trash.failed": "\u5220\u9664\u5931\u8d25\uff1a",
439
+ "confirm.cancel": "\u53d6\u6d88",
440
+ "confirm.ok": "\u786e\u8ba4",
389
441
  };
390
442
  var EN = {
391
443
  "settings.title": "Fold history after (days)",
@@ -509,14 +561,30 @@
509
561
  "archive.workspace": "workspace",
510
562
  "move.failed": "Move failed: ",
511
563
  "stats.chart": "Where the tokens went",
512
- "stats.details.show": "Show details",
513
- "stats.details.hide": "Hide details",
514
564
  "composer.analysis": "Usage analysis",
515
565
  "stats.legend.args": "arguments (written by the model)",
516
566
  "stats.legend.results": "results (returned by the environment)",
517
567
  "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.",
568
+ "stats.amplified.title": "Amplified cost (what the bill pays for)",
569
+ "stats.amplified.summary": "Bill {bill} tokens; attributable content amplifies to {share} ({attributed})",
570
+ "stats.amplified.contextCaption": "Context per step (area ≈ bill): earlier content is re-read more",
571
+ "stats.amplified.point": "step {step} · {context}",
572
+ "stats.amplified.meta": "entered at step {entry} · {tokens} tokens × {remaining} re-reads",
573
+ "stats.amplified.whatIf": "at 20%, saves {save} ({share})",
574
+ "stats.amplified.empty": "No amplifiable content (compacted or older logs may lack it)",
575
+ "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.",
576
+ "stats.amplified.results": "tool results",
577
+ "stats.amplified.args": "tool arguments",
578
+ "stats.amplified.agent": "agent output",
579
+ "stats.amplified.user": "user messages",
580
+ "stats.amplified.system": "system messages",
581
+ "stats.tab.distribution": "Distribution",
582
+ "stats.tab.amplified": "Amplified",
583
+ "stats.tab.details": "Details",
518
584
  "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
585
  "trash.failed": "Delete failed: ",
586
+ "confirm.cancel": "Cancel",
587
+ "confirm.ok": "Confirm",
520
588
  };
521
589
 
522
590
  /* Resolved lazily: the dictionaries are declared further down this closure. */
@@ -540,7 +608,14 @@
540
608
  }
541
609
  var dictionary = fallbackDictionary();
542
610
  var text = (dictionary && dictionary[key]) || key;
543
- if (params !== undefined && params.n !== undefined) text = text.replace("{n}", String(params.n));
611
+ /* The host's translate may interpolate; the local fallback has to do
612
+ it itself, or every template would render its braces verbatim. */
613
+ if (params !== undefined && params !== null) {
614
+ for (var name in params) {
615
+ if (!Object.prototype.hasOwnProperty.call(params, name)) continue;
616
+ text = text.split("{" + name + "}").join(String(params[name]));
617
+ }
618
+ }
544
619
  return text;
545
620
  }
546
621
 
@@ -1018,10 +1093,11 @@
1018
1093
  return false;
1019
1094
  }
1020
1095
 
1021
- function pinnedRowElement(item) {
1096
+ function pinnedRowElement(item, state) {
1022
1097
  var row = document.createElement("div");
1023
1098
  row.className = "wsr-pin-row";
1024
1099
  row.setAttribute("data-row-key", "pin:" + item.id);
1100
+ setRowState(row, state === undefined ? null : state);
1025
1101
  var title = document.createElement("span");
1026
1102
  title.className = "wsr-pin-title";
1027
1103
  title.textContent = item.title;
@@ -1050,8 +1126,7 @@
1050
1126
  }
1051
1127
 
1052
1128
  /** Hide the copies inside their own groups so nothing is listed twice. */
1053
- function hideOriginalRows(entries, pinnedIds) {
1054
- for (var i = 0; i < entries.length; i += 1) {
1129
+ function hideOriginalRows(entries, pinnedIds) { for (var i = 0; i < entries.length; i += 1) {
1055
1130
  var rows = rowElements(entries[i].section);
1056
1131
  for (var j = 0; j < rows.length; j += 1) {
1057
1132
  var id = sessionIdOf(rows[j]);
@@ -1066,6 +1141,30 @@
1066
1141
  }
1067
1142
  }
1068
1143
 
1144
+ /** One session's running / unread / follow-up state, or null. */
1145
+ function statesOfId(states, id) {
1146
+ if (states === null || states === undefined || id === null || id === undefined || id === "") return null;
1147
+ var state = states[id];
1148
+ return state === undefined ? null : state;
1149
+ }
1150
+
1151
+ /**
1152
+ * Push the current state onto the pin rows already in the DOM.
1153
+ *
1154
+ * The section is rebuilt only when the pinned set or its labels change, so
1155
+ * a session that starts running has to be recoloured in place - otherwise
1156
+ * its row would keep the state it had when the section was last built.
1157
+ */
1158
+ function applyPinStates(host, states) {
1159
+ if (host === null || typeof host.querySelectorAll !== "function") return;
1160
+ var rows = host.querySelectorAll('[data-row-key^="pin:"]');
1161
+ for (var i = 0; i < rows.length; i += 1) {
1162
+ var key = rows[i].getAttribute("data-row-key");
1163
+ var id = key === null ? "" : key.slice("pin:".length);
1164
+ setRowState(rows[i], statesOfId(states, id));
1165
+ }
1166
+ }
1167
+
1069
1168
  /**
1070
1169
  * Render the "pinned" section above every workspace group.
1071
1170
  *
@@ -1073,7 +1172,7 @@
1073
1172
  * (flex order -1), rebuilt only when the pinned set or its labels change. The
1074
1173
  * host keeps owning the list; the workspace grouping below is untouched.
1075
1174
  */
1076
- function renderPinned(entries, sessions, workspaces, settings) {
1175
+ function renderPinned(entries, sessions, workspaces, settings, states) {
1077
1176
  if (typeof document === "undefined") return;
1078
1177
  var items = pinnedItemsOf(sessions, workspaces, settings);
1079
1178
 
@@ -1112,8 +1211,10 @@
1112
1211
  head.className = "wsr-pin-head";
1113
1212
  head.textContent = t("pin.head");
1114
1213
  pinHost.appendChild(head);
1115
- for (var i = 0; i < items.length; i += 1) pinHost.appendChild(pinnedRowElement(items[i]));
1214
+ for (var i = 0; i < items.length; i += 1) pinHost.appendChild(pinnedRowElement(items[i], statesOfId(states, items[i].id)));
1116
1215
  }
1216
+ /* The state can change while the pinned set stays the same. */
1217
+ applyPinStates(pinHost, states);
1117
1218
  var pinnedIds = new Set(items.map(function (item) { return item.id; }));
1118
1219
  hideOriginalRows(entries, pinnedIds);
1119
1220
  }
@@ -1145,7 +1246,13 @@
1145
1246
  * is never inferred, and only an explicit clear removes it. Running and
1146
1247
  * unread outrank it on screen; once they pass, amber comes back.
1147
1248
  */
1148
- function decorateRows(entries, sessions, statuses, settings) {
1249
+ /**
1250
+ * running / unread / follow-up per session id.
1251
+ *
1252
+ * Both the host's rows and the plugin's own pinned rows read this, so a
1253
+ * pinned session keeps the same colour it had inside its group.
1254
+ */
1255
+ function statesOf(sessions, statuses, settings) {
1149
1256
  var flags = settings.followUps;
1150
1257
  var byId = sessions.byId || {};
1151
1258
  var states = {};
@@ -1166,7 +1273,10 @@
1166
1273
  var flagged = flags[id] !== undefined;
1167
1274
  states[id] = running ? "running" : unread ? "unread" : flagged ? "followup" : null;
1168
1275
  }
1276
+ return states;
1277
+ }
1169
1278
 
1279
+ function decorateRows(entries, states) {
1170
1280
  for (var i = 0; i < entries.length; i += 1) {
1171
1281
  var rows = rowElements(entries[i].section);
1172
1282
  for (var j = 0; j < rows.length; j += 1) {
@@ -1186,6 +1296,34 @@
1186
1296
  return typeof id === "string" && id !== "" ? id : null;
1187
1297
  }
1188
1298
 
1299
+ /**
1300
+ * The highest turn number currently rendered in the conversation.
1301
+ *
1302
+ * The handoff card lives in the `turnTail` slot, which renders once per
1303
+ * turn; without this the card would appear under every reply. A running
1304
+ * handoff may only speak from the tail of the turn it just started.
1305
+ */
1306
+ function latestTurnNumber() {
1307
+ if (typeof document === "undefined") return null;
1308
+ var body = null;
1309
+ try { body = document.querySelector("[data-conversation-content]"); } catch (error) { body = null; }
1310
+ var elements;
1311
+ try {
1312
+ elements = body !== null && body !== undefined && typeof body.querySelectorAll === "function"
1313
+ ? body.querySelectorAll("[data-turn-tail]")
1314
+ : (typeof document.querySelectorAll === "function" ? document.querySelectorAll("[data-turn-tail]") : []);
1315
+ } catch (error) {
1316
+ return null;
1317
+ }
1318
+ var max = null;
1319
+ for (var i = 0; i < elements.length; i += 1) {
1320
+ var value = Number(elements[i].getAttribute("data-turn-tail"));
1321
+ if (!isFinite(value)) continue;
1322
+ if (max === null || value > max) max = value;
1323
+ }
1324
+ return max;
1325
+ }
1326
+
1189
1327
  /** The nearest horizontal flex row above the stats: the whole footer dock. */
1190
1328
  function composerDockOf(row) {
1191
1329
  var node = row;
@@ -1325,8 +1463,9 @@
1325
1463
 
1326
1464
  orderGroups(entries, latestByWorkspace(sessions, workspaces));
1327
1465
  foldRows(entries, settings, sessions, Date.now());
1328
- renderPinned(entries, sessions, workspaces, settings);
1329
- if (settings.colors) decorateRows(entries, sessions, data.statuses, settings);
1466
+ var states = settings.colors ? statesOf(sessions, data.statuses, settings) : null;
1467
+ renderPinned(entries, sessions, workspaces, settings, states);
1468
+ if (states !== null) decorateRows(entries, states);
1330
1469
  decorateComposerStats();
1331
1470
  }
1332
1471
 
@@ -1415,29 +1554,28 @@
1415
1554
  return h(Item, {
1416
1555
  icon: typeof Icon === "function" ? h(Icon, {}) : undefined,
1417
1556
  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
- });
1557
+ askConfirm(t("trash.confirm"), function () {
1558
+ fetch("/ws-recency/session-trash?sessionId=" + encodeURIComponent(props.sessionId), {
1559
+ method: "POST",
1560
+ headers: { "content-type": "application/json" },
1561
+ body: JSON.stringify({ sessionId: props.sessionId }),
1432
1562
  })
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);
1437
- })
1438
- .catch(function (error) {
1439
- if (typeof window.alert === "function") window.alert(t("trash.failed") + (error && error.message ? error.message : error));
1440
- });
1563
+ .then(function (response) {
1564
+ return response.text().then(function (text) {
1565
+ var parsed = null;
1566
+ try { parsed = JSON.parse(text); } catch (error) { parsed = null; }
1567
+ return { status: response.status, text: text, json: parsed };
1568
+ });
1569
+ })
1570
+ .then(function (result) {
1571
+ if (result.json !== null && result.json.ok === true) return;
1572
+ var reason = (result.json !== null && result.json.error) || (result.text || "").trim().slice(0, 120) || "(empty response)";
1573
+ askNotice(t("trash.failed") + "HTTP " + result.status + " \u00b7 " + reason);
1574
+ })
1575
+ .catch(function (error) {
1576
+ askNotice(t("trash.failed") + (error && error.message ? error.message : error));
1577
+ });
1578
+ });
1441
1579
  },
1442
1580
  }, t("menu.trash"));
1443
1581
  }
@@ -1445,6 +1583,8 @@
1445
1583
  /* ------------------------- token statistics ------------------------- */
1446
1584
 
1447
1585
  var statsModal = null;
1586
+ /** Which stats tab stays selected across openings. */
1587
+ var statsTab = "distribution";
1448
1588
 
1449
1589
  function formatTokens(value) {
1450
1590
  var n = Number(value) || 0;
@@ -1460,6 +1600,8 @@
1460
1600
  }
1461
1601
 
1462
1602
  function closeStatsPanel() {
1603
+ /* A confirmation may sit on top of the panel it was opened from. */
1604
+ closeConfirm(null);
1463
1605
  if (statsModal !== null) {
1464
1606
  if (typeof statsModal.remove === "function") statsModal.remove();
1465
1607
  statsModal = null;
@@ -1480,6 +1622,113 @@
1480
1622
  return node;
1481
1623
  }
1482
1624
 
1625
+ /* --------------------------- in-app dialogs ------------------------- *
1626
+ * `window.confirm` / `window.alert` are native dialogs. On Windows the
1627
+ * renderer comes back from one without keyboard focus: clicking the
1628
+ * composer does nothing, switching sessions does not help, and only
1629
+ * leaving the app and coming back fixes it. These stay in the page and
1630
+ * never take the window's focus away.
1631
+ * ------------------------------------------------------------------- */
1632
+
1633
+ var confirmBackdrop = null;
1634
+ var confirmPrevious = null;
1635
+ var confirmKey = null;
1636
+
1637
+ /** Close the current dialog; `onConfirm` runs only for an accept. */
1638
+ function closeConfirm(onConfirm) {
1639
+ var backdrop = confirmBackdrop;
1640
+ confirmBackdrop = null;
1641
+ if (backdrop !== null && typeof backdrop.remove === "function") backdrop.remove();
1642
+ if (typeof document !== "undefined" && confirmKey !== null && typeof document.removeEventListener === "function") {
1643
+ document.removeEventListener("keydown", confirmKey);
1644
+ }
1645
+ confirmKey = null;
1646
+ var previous = confirmPrevious;
1647
+ confirmPrevious = null;
1648
+ if (previous !== null && previous !== undefined && previous.isConnected !== false && typeof previous.focus === "function") {
1649
+ try { previous.focus(); } catch (error) { /* the element may be gone */ }
1650
+ }
1651
+ if (typeof onConfirm === "function") onConfirm();
1652
+ }
1653
+
1654
+ /**
1655
+ * Ask before acting, in the page.
1656
+ *
1657
+ * @param question - message shown in the dialog.
1658
+ * @param onConfirm - runs when the user accepts; omitted for a notice.
1659
+ * @param notice - render a single acknowledge button.
1660
+ */
1661
+ function askConfirm(question, onConfirm, notice) {
1662
+ if (typeof document === "undefined") return;
1663
+ closeConfirm();
1664
+ var isNotice = notice === true;
1665
+ confirmPrevious = typeof document.activeElement !== "undefined" ? document.activeElement : null;
1666
+
1667
+ var backdrop = statsDiv("wsr-modal-backdrop");
1668
+ backdrop.setAttribute("data-wsr-confirm", isNotice ? "notice" : "confirm");
1669
+ var panel = statsDiv("wsr-confirm");
1670
+ panel.setAttribute("role", "dialog");
1671
+ panel.setAttribute("aria-modal", "true");
1672
+ panel.setAttribute("tabindex", "-1");
1673
+ panel.appendChild(statsDiv("wsr-confirm-text", question));
1674
+
1675
+ var actions = statsDiv("wsr-confirm-actions");
1676
+ var cancel = document.createElement("button");
1677
+ cancel.type = "button";
1678
+ cancel.className = "wsr-qcancel";
1679
+ cancel.textContent = t("confirm.cancel");
1680
+ cancel.addEventListener("click", function (event) {
1681
+ if (event !== undefined && typeof event.stopPropagation === "function") event.stopPropagation();
1682
+ closeConfirm(null);
1683
+ });
1684
+ var accept = document.createElement("button");
1685
+ accept.type = "button";
1686
+ accept.className = "wsr-qsubmit";
1687
+ accept.setAttribute("data-wsr-confirm-ok", "true");
1688
+ accept.textContent = t("confirm.ok");
1689
+ accept.addEventListener("click", function (event) {
1690
+ if (event !== undefined && typeof event.stopPropagation === "function") event.stopPropagation();
1691
+ closeConfirm(isNotice ? null : onConfirm);
1692
+ });
1693
+ if (!isNotice) actions.appendChild(cancel);
1694
+ actions.appendChild(accept);
1695
+ panel.appendChild(actions);
1696
+
1697
+ panel.addEventListener("click", function (event) {
1698
+ if (event !== undefined && typeof event.stopPropagation === "function") event.stopPropagation();
1699
+ });
1700
+ backdrop.addEventListener("click", function (event) {
1701
+ if (event === undefined || event.target === backdrop) closeConfirm(null);
1702
+ });
1703
+ backdrop.appendChild(panel);
1704
+ document.body.appendChild(backdrop);
1705
+ confirmBackdrop = backdrop;
1706
+
1707
+ confirmKey = function (event) {
1708
+ if (event === undefined) return;
1709
+ if (event.key === "Escape") {
1710
+ if (typeof event.preventDefault === "function") event.preventDefault();
1711
+ closeConfirm(null);
1712
+ return;
1713
+ }
1714
+ if (event.key === "Enter" && !isNotice) {
1715
+ if (typeof event.preventDefault === "function") event.preventDefault();
1716
+ closeConfirm(onConfirm);
1717
+ }
1718
+ if (event.key === "Enter" && isNotice) {
1719
+ if (typeof event.preventDefault === "function") event.preventDefault();
1720
+ closeConfirm(null);
1721
+ }
1722
+ };
1723
+ if (typeof document.addEventListener === "function") document.addEventListener("keydown", confirmKey);
1724
+ try { accept.focus(); } catch (error) { /* focus is best effort */ }
1725
+ }
1726
+
1727
+ /** A one-button notice, used when a request fails. */
1728
+ function askNotice(message) {
1729
+ askConfirm(message, null, true);
1730
+ }
1731
+
1483
1732
  /** One table row: source, calls, argument tokens, result tokens, total, share. */
1484
1733
  function statsRow(label, calls, args, results, total, share, dimArgs) {
1485
1734
  var row = document.createElement("div");
@@ -1628,6 +1877,99 @@
1628
1877
  return "hsl(" + hue + ", " + saturation + "%, " + lightness + "%)";
1629
1878
  }
1630
1879
 
1880
+ var AMPLIFIED_KIND = {
1881
+ results: ["stats.amplified.results", "#4f8ef7"],
1882
+ args: ["stats.amplified.args", "#8fa3c8"],
1883
+ agent: ["stats.amplified.agent", "#7a6cff"],
1884
+ user: ["stats.amplified.user", "#6fbf73"],
1885
+ system: ["stats.amplified.system", "#c9a227"],
1886
+ };
1887
+
1888
+ /**
1889
+ * The bill's shape, then its amplified ranking.
1890
+ *
1891
+ * A step's token count is just "context at that moment", which is nearly
1892
+ * the same on every step; the number that explains the bill is a content
1893
+ * block's tokens times the number of later steps that re-read it. The
1894
+ * host half computes that attribution; this only draws it.
1895
+ */
1896
+ function buildAmplified(stats) {
1897
+ var amplified = stats.amplified;
1898
+ if (amplified === null || amplified === undefined || !Array.isArray(amplified.series)) return null;
1899
+ var bill = Number(amplified.bill) || 0;
1900
+ var section = statsDiv("wsr-amplified");
1901
+
1902
+ var head = statsDiv("wsr-amplified-head");
1903
+ head.appendChild(statsDiv("wsr-amplified-title", t("stats.amplified.title")));
1904
+ head.appendChild(statsDiv("wsr-amplified-summary", t("stats.amplified.summary", {
1905
+ bill: formatTokens(bill),
1906
+ share: formatShare(Number(amplified.share) || 0),
1907
+ attributed: formatTokens(amplified.attributed || 0),
1908
+ })));
1909
+ section.appendChild(head);
1910
+
1911
+ var series = amplified.series;
1912
+ var largest = 1;
1913
+ for (var i = 0; i < series.length; i += 1) {
1914
+ if (Number(series[i].context) > largest) largest = Number(series[i].context);
1915
+ }
1916
+ var chart = statsDiv("wsr-context-chart");
1917
+ for (var j = 0; j < series.length; j += 1) {
1918
+ var bar = statsDiv("wsr-context-bar");
1919
+ bar.style.height = Math.max(2, Math.round((Number(series[j].context) / largest) * 100)) + "%";
1920
+ bar.setAttribute("title", t("stats.amplified.point", { step: String(series[j].step), context: formatTokens(series[j].context) }));
1921
+ chart.appendChild(bar);
1922
+ }
1923
+ section.appendChild(chart);
1924
+ section.appendChild(statsDiv("wsr-context-caption", t("stats.amplified.contextCaption")));
1925
+
1926
+ var kinds = amplified.byKind || [];
1927
+ if (kinds.length > 0) {
1928
+ var legend = statsDiv("wsr-kind-legend");
1929
+ for (var k = 0; k < kinds.length; k += 1) {
1930
+ var kind = kinds[k];
1931
+ var known = AMPLIFIED_KIND[kind.kind];
1932
+ var item = statsDiv("wsr-kind");
1933
+ var dot = statsDiv("wsr-kind-dot");
1934
+ dot.style.background = known === undefined ? "#9aa0a6" : known[1];
1935
+ item.appendChild(dot);
1936
+ item.appendChild(statsDiv("", t(known === undefined ? kind.kind : known[0]) + " " + formatShare(kind.share || 0)));
1937
+ legend.appendChild(item);
1938
+ }
1939
+ section.appendChild(legend);
1940
+ }
1941
+
1942
+ var list = statsDiv("wsr-amplified-list");
1943
+ var blocks = amplified.blocks || [];
1944
+ if (blocks.length === 0) list.appendChild(statsDiv("wsr-amplified-empty", t("stats.amplified.empty")));
1945
+ for (var b = 0; b < blocks.length; b += 1) {
1946
+ var block = blocks[b];
1947
+ var known = AMPLIFIED_KIND[block.kind];
1948
+ var row = statsDiv("wsr-amplified-row");
1949
+ var main = statsDiv("wsr-amplified-main");
1950
+ main.appendChild(statsDiv("wsr-amplified-name", block.kind === "tool" ? String(block.name) : t(known === undefined ? block.kind : known[0])));
1951
+ if (typeof block.detail === "string" && block.detail !== "") main.appendChild(statsDiv("wsr-amplified-detail", block.detail));
1952
+ main.appendChild(statsDiv("wsr-amplified-meta", t("stats.amplified.meta", {
1953
+ entry: String(block.entry),
1954
+ tokens: formatTokens(block.tokens),
1955
+ remaining: String(block.remaining),
1956
+ })));
1957
+ row.appendChild(main);
1958
+ row.appendChild(statsDiv("wsr-amplified-value", formatTokens(block.amplified)));
1959
+ row.appendChild(statsDiv("wsr-amplified-share", formatShare(block.share || 0)));
1960
+ if (Number(block.remaining) > 0 && Number(block.saving) > 0) {
1961
+ row.appendChild(statsDiv("wsr-amplified-if", t("stats.amplified.whatIf", {
1962
+ save: formatTokens(block.saving),
1963
+ share: formatShare(Number(block.saving) / (bill > 0 ? bill : 1)),
1964
+ })));
1965
+ }
1966
+ list.appendChild(row);
1967
+ }
1968
+ section.appendChild(list);
1969
+ section.appendChild(statsDiv("wsr-stats-note", t("stats.amplified.note")));
1970
+ return section;
1971
+ }
1972
+
1631
1973
  function renderStats(body, stats) {
1632
1974
  body.textContent = "";
1633
1975
  while (body.firstChild !== null) body.removeChild(body.firstChild);
@@ -1652,6 +1994,10 @@
1652
1994
  }
1653
1995
  body.appendChild(grid);
1654
1996
 
1997
+ /* Three views instead of one long page: distribution, amplification,
1998
+ details. The summary cards stay above the tabs for every view. */
1999
+ var amplifiedSection = buildAmplified(stats);
2000
+
1655
2001
  var tools = estimate.tools || [];
1656
2002
  var mode = argModeOf();
1657
2003
  var movedArgs = 0;
@@ -1704,16 +2050,12 @@
1704
2050
  var largest = 1;
1705
2051
  for (var m = 0; m < entries.length; m += 1) if (entries[m].value > largest) largest = entries[m].value;
1706
2052
  for (var k = 0; k < entries.length; k += 1) chart.appendChild(chartBar(entries[k], largest));
1707
- body.appendChild(chart);
2053
+ var distributionPanel = statsDiv("wsr-stats-panel");
2054
+ distributionPanel.appendChild(chart);
2055
+ distributionPanel.appendChild(statsDiv("wsr-stats-note", t("stats.note")));
1708
2056
 
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";
2057
+ /* The table is now its own tab instead of a folded section. */
2058
+ var detailsPanel = statsDiv("wsr-stats-panel wsr-stats-details");
1717
2059
 
1718
2060
  var table = statsDiv("wsr-stats-table");
1719
2061
  var head = document.createElement("div");
@@ -1729,24 +2071,57 @@
1729
2071
  var toolValue = mode === "agent" ? toolResults : (toolRow.total || toolArgs + toolResults);
1730
2072
  table.appendChild(statsRow(toolRow.name, toolRow.calls, toolArgs, toolResults, toolValue, shareOf(toolValue), mode === "agent"));
1731
2073
  }
1732
- details.appendChild(table);
1733
- details.appendChild(statsDiv("wsr-stats-detail", t("stats.agentDetail", {
2074
+ detailsPanel.appendChild(table);
2075
+ detailsPanel.appendChild(statsDiv("wsr-stats-detail", t("stats.agentDetail", {
1734
2076
  reasoning: formatTokens(agent.reasoning),
1735
2077
  text: formatTokens(agent.text),
1736
2078
  user: formatTokens(agent.user),
1737
2079
  system: formatTokens(agent.system),
1738
2080
  })));
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")));
2081
+ if (mode === "agent") detailsPanel.appendChild(statsDiv("wsr-stats-note", t("stats.argModeNote")));
2082
+
2083
+ var tabs = statsDiv("wsr-stats-tabs");
2084
+ tabs.setAttribute("role", "tablist");
2085
+ var panels = statsDiv("wsr-stats-panels");
2086
+ var defs = [["distribution", "stats.tab.distribution", distributionPanel]];
2087
+ if (amplifiedSection !== null) {
2088
+ var amplifiedPanel = statsDiv("wsr-stats-panel");
2089
+ amplifiedPanel.appendChild(amplifiedSection);
2090
+ defs.push(["amplified", "stats.tab.amplified", amplifiedPanel]);
2091
+ }
2092
+ defs.push(["details", "stats.tab.details", detailsPanel]);
2093
+ var tabButtons = {};
2094
+ var selectTab = function (id) {
2095
+ statsTab = id;
2096
+ for (var index = 0; index < defs.length; index += 1) {
2097
+ var def = defs[index];
2098
+ var active = def[0] === id;
2099
+ if (tabButtons[def[0]] !== undefined) {
2100
+ tabButtons[def[0]].className = "wsr-stats-tab" + (active ? " wsr-stats-tab-active" : "");
2101
+ tabButtons[def[0]].setAttribute("aria-selected", active ? "true" : "false");
2102
+ }
2103
+ def[2].style.display = active ? "" : "none";
2104
+ }
2105
+ };
2106
+ for (var d = 0; d < defs.length; d += 1) {
2107
+ (function (def) {
2108
+ var button = document.createElement("button");
2109
+ button.type = "button";
2110
+ button.className = "wsr-stats-tab";
2111
+ button.setAttribute("role", "tab");
2112
+ button.setAttribute("data-wsr-stats-tab", def[0]);
2113
+ button.textContent = t(def[1]);
2114
+ button.addEventListener("click", function () { selectTab(def[0]); });
2115
+ tabButtons[def[0]] = button;
2116
+ tabs.appendChild(button);
2117
+ panels.appendChild(def[2]);
2118
+ })(defs[d]);
2119
+ }
2120
+ var initialTab = statsTab;
2121
+ if (initialTab === "amplified" && amplifiedSection === null) initialTab = "distribution";
2122
+ selectTab(initialTab);
2123
+ body.appendChild(tabs);
2124
+ body.appendChild(panels);
1750
2125
  }
1751
2126
 
1752
2127
  function openStatsPanel(sessionId) {
@@ -1869,36 +2244,37 @@
1869
2244
  if (!isCurrent) {
1870
2245
  row.addEventListener("click", function () {
1871
2246
  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
- });
2247
+ askConfirm(t("move.confirm", { workspace: label }), function () {
2248
+ body.textContent = t("move.working");
2249
+ fetch("/ws-recency/session-move?sessionId=" + encodeURIComponent(sessionId), {
2250
+ method: "POST",
2251
+ headers: { "content-type": "application/json" },
2252
+ body: JSON.stringify({ sessionId: sessionId, workspaceId: item.workspaceId }),
1885
2253
  })
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 });
2254
+ .then(function (response) {
2255
+ return response.text().then(function (text) {
2256
+ var parsed = null;
2257
+ try { parsed = JSON.parse(text); } catch (error) { parsed = null; }
2258
+ return { status: response.status, text: text, json: parsed };
2259
+ });
2260
+ })
2261
+ .then(function (result) {
2262
+ if (result.json !== null && result.json.ok === true) {
2263
+ if (result.json.repaired === true) {
2264
+ body.textContent = t("move.repaired", { workspace: label });
2265
+ return;
2266
+ }
2267
+ body.textContent = t("move.done", { workspace: label });
2268
+ if (result.json.live === true) body.textContent += t("move.doneLive");
1890
2269
  return;
1891
2270
  }
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
- });
2271
+ var reason = (result.json !== null && result.json.error) || (result.text || "").trim().slice(0, 160) || "(empty response)";
2272
+ body.textContent = t("move.failed") + "HTTP " + result.status + " \u00b7 " + reason;
2273
+ })
2274
+ .catch(function (error) {
2275
+ body.textContent = t("move.failed") + (error && error.message ? error.message : error);
2276
+ });
2277
+ });
1902
2278
  });
1903
2279
  }
1904
2280
  list.appendChild(row);
@@ -1955,6 +2331,8 @@
1955
2331
  var handoffBaseline = 0;
1956
2332
  var handoffTries = 0;
1957
2333
  var handoffSession = null;
2334
+ /** Wall clock of the instruction/rewrite: older replies are never the answer. */
2335
+ var handoffStartedAt = 0;
1958
2336
 
1959
2337
  /** Retention-source tag the Host books this plugin's borrows under. */
1960
2338
  var HANDOFF_SOURCE = "dsh-ws-recency";
@@ -2237,10 +2615,34 @@
2237
2615
  return "";
2238
2616
  }
2239
2617
 
2240
- /** Start the watch: the next reply that carries a handoff block becomes the card. */
2618
+ /**
2619
+ * Whether a tail answer is a *new, finished* reply worth reading.
2620
+ *
2621
+ * Three guards, because the tail always reports the newest assistant text
2622
+ * in the whole log:
2623
+ * - the session must have no open turn: a freshly started turn logs
2624
+ * assistant messages with only reasoning/tool-call blocks, and if the
2625
+ * previous reply happened to be a handoff note the old text would be
2626
+ * read as the answer while the model is still working;
2627
+ * - the text must be newer than the moment the instruction went out;
2628
+ * - an older Host without `seq`/`turnOpen` falls back to the timestamp.
2629
+ */
2630
+ function handoffAnswerReady(answer, baseline) {
2631
+ if (answer === null || answer === undefined || answer.ok !== true) return false;
2632
+ if (answer.turnOpen === true) return false;
2633
+ var seqFresh = typeof answer.textSeq === "number" && answer.textSeq !== 0 && typeof baseline === "number" && answer.textSeq > baseline;
2634
+ var timeFresh = typeof answer.at === "number" && answer.at > 0 && handoffStartedAt > 0 && answer.at > handoffStartedAt;
2635
+ if (seqFresh || timeFresh) return true;
2636
+ /* A Host too old to report either marker: the caller's count is all we have. */
2637
+ if ((typeof answer.textSeq !== "number" || answer.textSeq === 0) && (typeof answer.at !== "number" || answer.at === 0)) return true;
2638
+ return false;
2639
+ }
2640
+
2641
+ /** Start the watch: the next finished reply that carries a handoff block becomes the card. */
2241
2642
  function watchHandoff(sessionId) {
2242
2643
  handoffSession = sessionId;
2243
2644
  handoffTries = 0;
2645
+ handoffStartedAt = Date.now();
2244
2646
  stopHandoffPolling();
2245
2647
  if (typeof window === "undefined") return;
2246
2648
  function tick() {
@@ -2249,16 +2651,24 @@
2249
2651
  handoffPost({ action: "tail", sessionId: sessionId }).then(function (answer) {
2250
2652
  if (handoffSession !== sessionId) return;
2251
2653
  if (answer !== null && answer.ok === true) {
2252
- var replies = typeof answer.replies === "number" ? answer.replies : 0;
2253
- if (replies > handoffBaseline) {
2654
+ var reached = typeof answer.lastSeq === "number"
2655
+ ? answer.lastSeq > handoffBaseline
2656
+ : (typeof answer.replies === "number" ? answer.replies > handoffBaseline : false);
2657
+ if (reached && handoffAnswerReady(answer, handoffBaseline)) {
2254
2658
  var found = handoffBlockOf(answer.text);
2255
2659
  if (found !== "") {
2256
- setHandoffState({ sessionId: sessionId, phase: "ready", block: found, needsEnter: false });
2660
+ setHandoffState({
2661
+ sessionId: sessionId,
2662
+ phase: "ready",
2663
+ block: found,
2664
+ needsEnter: false,
2665
+ turn: typeof answer.turn === "number" ? answer.turn : undefined,
2666
+ });
2257
2667
  return;
2258
2668
  }
2259
- /* Keep looking at this same reply: it may still be streaming, and a
2260
- reply without a block is not a reason to move past it. */
2261
2669
  }
2670
+ /* Not ready yet (turn still open, text not newer, or no block in
2671
+ this reply): keep looking at the same session. */
2262
2672
  }
2263
2673
  if (handoffTries > 150) {
2264
2674
  setHandoffState({ sessionId: "", phase: "idle", block: "", needsEnter: false });
@@ -2270,10 +2680,12 @@
2270
2680
  handoffTimer = window.setTimeout(tick, 4000);
2271
2681
  });
2272
2682
  }
2273
- /* The baseline is the reply count before the instruction is answered. */
2683
+ /* The baseline is where the log stood before the instruction is answered. */
2274
2684
  handoffPost({ action: "tail", sessionId: sessionId }).then(function (answer) {
2275
2685
  if (handoffSession !== sessionId) return;
2276
- handoffBaseline = answer !== null && answer.ok === true && typeof answer.replies === "number" ? answer.replies : 0;
2686
+ handoffBaseline = answer !== null && answer.ok === true && typeof answer.lastSeq === "number"
2687
+ ? answer.lastSeq
2688
+ : (answer !== null && answer.ok === true && typeof answer.replies === "number" ? answer.replies : 0);
2277
2689
  handoffTimer = window.setTimeout(tick, 1500);
2278
2690
  }).catch(function () {
2279
2691
  handoffTimer = window.setTimeout(tick, 3000);
@@ -2286,7 +2698,8 @@
2286
2698
  /* The card starts in its "working" state; if the Host refuses the send
2287
2699
  the fallback flips needsEnter so the card tells the user to press
2288
2700
  Enter instead of pretending the handoff is running. */
2289
- setHandoffState({ sessionId: sessionId, phase: "running", block: "", needsEnter: false });
2701
+ var startTurn = latestTurnNumber();
2702
+ setHandoffState({ sessionId: sessionId, phase: "running", block: "", needsEnter: false, afterTurn: startTurn === null ? undefined : startTurn });
2290
2703
  sendToSession(sessionId, handoffInstruction());
2291
2704
  watchHandoff(sessionId);
2292
2705
  }
@@ -2363,7 +2776,8 @@
2363
2776
  /** Ask the current Session to rewrite the handoff with the user's adjustments. */
2364
2777
  function rewriteHandoff(sessionId, extra) {
2365
2778
  var text = extra.trim() === "" ? t("handoff.regeneratePrompt") : t("handoff.adjustPrompt") + "\n\n" + extra.trim();
2366
- setHandoffState({ sessionId: sessionId, phase: "running", block: "", needsEnter: false });
2779
+ var startTurn = latestTurnNumber();
2780
+ setHandoffState({ sessionId: sessionId, phase: "running", block: "", needsEnter: false, afterTurn: startTurn === null ? undefined : startTurn });
2367
2781
  sendToSession(sessionId, text);
2368
2782
  handoffBaseline = 0;
2369
2783
  handoffTries = 0;
@@ -2396,6 +2810,23 @@
2396
2810
 
2397
2811
  var state = live;
2398
2812
  if (state === null || state === undefined || state.sessionId !== sessionId) return null;
2813
+ /* One rendered `turnTail` per turn: show the card only on the turn the
2814
+ note came from, and the progress line only on the newest turn (the
2815
+ open one). Props without a turn number keep the old behaviour. */
2816
+ var turn = props !== undefined && props !== null && typeof props.turn === "number" ? props.turn : null;
2817
+ if (state.phase === "running" && turn !== null) {
2818
+ if (typeof state.afterTurn === "number") {
2819
+ /* Only a turn that started after the click can be the answer. */
2820
+ if (turn <= state.afterTurn) return null;
2821
+ } else {
2822
+ var latest = latestTurnNumber();
2823
+ if (latest !== null && turn !== latest) return null;
2824
+ }
2825
+ }
2826
+ if (state.phase === "ready" && turn !== null) {
2827
+ var target = typeof state.turn === "number" ? state.turn : latestTurnNumber();
2828
+ if (target !== null && turn !== target) return null;
2829
+ }
2399
2830
  if (state.phase === "running") {
2400
2831
  return h("div", { className: "wsr-handoff-live" }, state.needsEnter === true ? t("handoff.pressEnter") : t("handoff.preparing"));
2401
2832
  }
@@ -2713,13 +3144,14 @@
2713
3144
  restore.className = "wsr-btn";
2714
3145
  restore.textContent = t("trash.restore");
2715
3146
  restore.addEventListener("click", function () {
2716
- if (typeof window.confirm === "function" && !window.confirm(t("trash.confirmRestore"))) return;
2717
- load(t("trash.working"));
2718
- post({ action: "restore", name: entry.name }).then(function (result) {
2719
- var ok = result.json !== null && result.json.ok === true;
2720
- load(ok ? t("trash.restored") : t("trash.failed") + (result.json && result.json.error ? result.json.error : result.text));
2721
- }).catch(function (error) {
2722
- load(t("trash.failed") + (error && error.message ? error.message : error));
3147
+ askConfirm(t("trash.confirmRestore"), function () {
3148
+ load(t("trash.working"));
3149
+ post({ action: "restore", name: entry.name }).then(function (result) {
3150
+ var ok = result.json !== null && result.json.ok === true;
3151
+ load(ok ? t("trash.restored") : t("trash.failed") + (result.json && result.json.error ? result.json.error : result.text));
3152
+ }).catch(function (error) {
3153
+ load(t("trash.failed") + (error && error.message ? error.message : error));
3154
+ });
2723
3155
  });
2724
3156
  });
2725
3157
  actions.appendChild(restore);
@@ -2729,13 +3161,14 @@
2729
3161
  purge.className = "wsr-btn wsr-btn-danger";
2730
3162
  purge.textContent = t("trash.purge");
2731
3163
  purge.addEventListener("click", function () {
2732
- if (typeof window.confirm === "function" && !window.confirm(t("trash.confirmPurge"))) return;
2733
- load(t("trash.working"));
2734
- post({ action: "purge", name: entry.name }).then(function (result) {
2735
- var ok = result.json !== null && result.json.ok === true;
2736
- load(ok ? t("trash.purged") : t("trash.failed") + (result.json && result.json.error ? result.json.error : result.text));
2737
- }).catch(function (error) {
2738
- load(t("trash.failed") + (error && error.message ? error.message : error));
3164
+ askConfirm(t("trash.confirmPurge"), function () {
3165
+ load(t("trash.working"));
3166
+ post({ action: "purge", name: entry.name }).then(function (result) {
3167
+ var ok = result.json !== null && result.json.ok === true;
3168
+ load(ok ? t("trash.purged") : t("trash.failed") + (result.json && result.json.error ? result.json.error : result.text));
3169
+ }).catch(function (error) {
3170
+ load(t("trash.failed") + (error && error.message ? error.message : error));
3171
+ });
2739
3172
  });
2740
3173
  });
2741
3174
  actions.appendChild(purge);
@@ -2850,13 +3283,14 @@
2850
3283
 
2851
3284
  var act = function (entry, action) {
2852
3285
  var question = action === "restore" ? t("trash.confirmRestore") : t("trash.confirmPurge");
2853
- if (typeof window.confirm === "function" && !window.confirm(question)) return;
2854
- load(t("trash.working"));
2855
- trashPost({ action: action, name: entry.name }).then(function (result) {
2856
- var ok = result.json !== null && result.json.ok === true;
2857
- load(ok ? (action === "restore" ? t("trash.restored") : t("trash.purged")) : t("trash.failed") + (result.json && result.json.error ? result.json.error : result.text));
2858
- }).catch(function (error) {
2859
- load(t("trash.failed") + (error && error.message ? error.message : error));
3286
+ askConfirm(question, function () {
3287
+ load(t("trash.working"));
3288
+ trashPost({ action: action, name: entry.name }).then(function (result) {
3289
+ var ok = result.json !== null && result.json.ok === true;
3290
+ load(ok ? (action === "restore" ? t("trash.restored") : t("trash.purged")) : t("trash.failed") + (result.json && result.json.error ? result.json.error : result.text));
3291
+ }).catch(function (error) {
3292
+ load(t("trash.failed") + (error && error.message ? error.message : error));
3293
+ });
2860
3294
  });
2861
3295
  };
2862
3296
 
@@ -2864,22 +3298,23 @@
2864
3298
  var question = action === "unarchive" ? t("archive.confirmUnarchive")
2865
3299
  : action === "forget" ? t("archive.confirmForget")
2866
3300
  : t("archive.confirmDelete");
2867
- if (typeof window.confirm === "function" && !window.confirm(question)) return;
2868
- load(t("trash.working"));
2869
- trashPost({ action: action, sessionId: entry.sessionId }).then(function (result) {
2870
- if (result.json === null || result.json.ok !== true) {
2871
- load(t("archive.failed") + (result.json && result.json.error ? result.json.error : result.text));
2872
- return;
2873
- }
2874
- if (action === "unarchive") {
2875
- load(t("archive.unarchived") + (result.json.listed === false ? t("archive.noWorkspace") : ""));
2876
- } else if (action === "forget") {
2877
- load(t("archive.forgotten"));
2878
- } else {
2879
- load(t("archive.deleted"));
2880
- }
2881
- }).catch(function (error) {
2882
- load(t("archive.failed") + (error && error.message ? error.message : error));
3301
+ askConfirm(question, function () {
3302
+ load(t("trash.working"));
3303
+ trashPost({ action: action, sessionId: entry.sessionId }).then(function (result) {
3304
+ if (result.json === null || result.json.ok !== true) {
3305
+ load(t("archive.failed") + (result.json && result.json.error ? result.json.error : result.text));
3306
+ return;
3307
+ }
3308
+ if (action === "unarchive") {
3309
+ load(t("archive.unarchived") + (result.json.listed === false ? t("archive.noWorkspace") : ""));
3310
+ } else if (action === "forget") {
3311
+ load(t("archive.forgotten"));
3312
+ } else {
3313
+ load(t("archive.deleted"));
3314
+ }
3315
+ }).catch(function (error) {
3316
+ load(t("archive.failed") + (error && error.message ? error.message : error));
3317
+ });
2883
3318
  });
2884
3319
  };
2885
3320
 
@@ -3385,6 +3820,7 @@
3385
3820
  current: currentHandoffState,
3386
3821
  set: setHandoffState,
3387
3822
  blockOf: handoffBlockOf,
3823
+ readyOf: handoffAnswerReady,
3388
3824
  start: startHandoff,
3389
3825
  rewrite: rewriteHandoff,
3390
3826
  carry: carryHandoff,