dsh-ws-recency 0.24.1 → 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 +10 -4
  2. package/client.js +522 -125
  3. package/index.js +181 -9
  4. package/package.json +1 -1
package/README.md CHANGED
@@ -82,7 +82,8 @@ DSH 原生的置顶只把会话顶到**它所属工作区分组的第一行**,
82
82
  - 每条记录是一张**卡片**:标题、来源(已删除 / 移动前的旧副本 / 已归档)、轮次、步骤、token 总量、日志大小、时间、原目录(归档的统计按日志大小缓存,第一次读完后不再重算);
83
83
  已删除会话的标题与统计在删除时就写进 `.wsr-trash.json`,旧条目则在第一次打开面板时从日志里补算并缓存;
84
84
  - 恢复/扫描/移动之后宿主会广播 `api-session/added`;面板与「扫描并刷新」都能重载页面(不重启应用)让侧栏立刻看到改动;
85
- - 移动操作留下的旧副本会标成「移动时的旧副本」,只允许彻底删除。
85
+ - 移动操作留下的旧副本会标成「移动时的旧副本」,只允许彻底删除;
86
+ - 所有确认(删除、恢复、彻底删除、移动、取消归档)都是**页面内弹层**,不调用系统 `confirm`/`alert`:系统对话框在 Windows 上关掉后会让渲染进程丢掉键盘焦点,表现为输入框点不进去、切换会话也没用,只能切走再切回来(0.24.2 修)。
86
87
 
87
88
  ## 六、Token 消耗统计
88
89
 
@@ -92,9 +93,11 @@ DSH 原生的置顶只把会话顶到**它所属工作区分组的第一行**,
92
93
  - **消耗分布图**(按内容估算):主 agent 自己(思考 / 回复 / 用户消息 / 系统提示)vs 每个工具,每个来源一条带颜色的横条,按占用长度直观对比;色相由工具身份决定(常用工具人工指定,其余按名字哈希,跨会话稳定),明艳度随占比排名递减;
93
94
  - **参数 / 结果两段**:每个工具那条横条拆成「参数」(淡色,模型自己写的命令 / 文件内容)和「结果」(实色,环境返回的内容),一眼看出贵在输入还是贵在输出。图例在图右上角;
94
95
  - **「参数计入主 agent」开关**(设置 → 通用):工具参数严格说是模型写的,不属于工具消耗。打开后每个工具只算返回结果,参数量并入主 agent——实测一个 pwsh 偏重的会话,pwsh 从 37.6% 掉到约 20%,主 agent 从 40.4% 升到约 58%。表格里「参数」列仍在,只是显示为淡色并计入主 agent 那一行;
95
- - **明细表**:调用次数、参数估算、结果估算、合计、占比,按合计降序,默认折叠,点「显示明细」展开。
96
+ - **明细表**:调用次数、参数估算、结果估算、合计、占比,按合计降序;
97
+ - **三个 tab(0.25.0)**:摘要卡片常驻顶部,下面按「分布统计 / 放大归因 / 明细」分页,页面不再一长条。打开时记住上次停留的 tab;
98
+ - **放大成本 / 账单归因(0.25.0)**:账单 = 每步上下文之和,所以一块内容的真实成本不是它出现时的 token 数,而是「token × 之后还会被重读多少步」。放大归因页给出:每步上下文曲线(面积≈账单)、账单构成(工具结果 / 工具参数 / 主 agent / 用户 / 系统)、以及按内容块排序的放大排行——进入第几步、原始 token、重读次数、放大后 token、占整场账单的百分比,以及「压到 20% 可省多少」。单次 9k 的 read 在 350 步的会话里会放大成 300 万 token(约 3% 账单),这样小数字才能读出结论。压缩之后旧内容不再重读,放大窗口会从压缩点截断。
96
99
 
97
- 口径说明:prompt 的 token 是「整段上下文每一步都计费」,没法精确归属到某一条消息,所以「主 agent / 工具」的拆分是按内容长度估算(中文≈1 token/字,英文≈4 字符/token),用来比较占比;**总量是真的**。数据从会话日志算,跨重启也能看。大会话第一次打开约 1–2 秒(29MB 日志实测 1.2 秒),10 秒内重复打开走缓存。
100
+ 口径说明:prompt 的 token 是「整段上下文每一步都计费」,没法精确归属到某一条消息,所以「主 agent / 工具」的拆分是按内容长度估算(中文≈1 token/字,英文≈4 字符/token),用来比较占比;**总量是真的**。放大排行里的块大小同样是估算,但账单总量、每步上下文、放大倍数的分母都来自真实 usage。思维链通常不回传给模型,因此不计入放大排行。数据从会话日志算,跨重启也能看。大会话第一次打开约 1–2 秒(29MB 日志实测 1.2 秒),10 秒内重复打开走缓存。
98
101
 
99
102
  宿主半(`index.js`)把统计与删除的路由挂在 webServer 上;如果面板报“宿主半未加载”,说明应用还没重启加载新版本。0.10.1 起面板失败时会带上 HTTP 状态和 `/ws-recency/health` 的自检结果,便于定位。
100
103
 
@@ -139,6 +142,9 @@ DSH 原生的置顶只把会话顶到**它所属工作区分组的第一行**,
139
142
 
140
143
  发送走宿主 API(0.24.1 起):`ctx.sessions.using(id, …)` 保持会话可寻址,再调 `session.prompt([{type:"text",…}], "queue")`;菜单项也能对不在前台的会话发起交接。只有在 Client 没有 `sessions` 服务时才退回旧路:写入当前会话的输入框、250ms 后按回车、必要时再补两次;目标会话不在屏幕上时不写错输入框,卡片会提示按回车。
141
144
 
145
+ 卡片只在**这一轮结束之后**才出现(0.24.2 修):轮询会比对回复的日志序号与「本轮是否还在跑」,只认点击之后产生、且已经收尾的那条回复——之前它读的是「全日志最后一条非空回复」,只要新轮先落一条工具步骤,就会把上一轮里的旧交接块当成答案,交接刚开始还在处理就弹卡;卡片也只挂在产生它的那一轮下面,不再在每个旧轮下面重复出现。
146
+
147
+
142
148
  ## 设置
143
149
 
144
150
  **设置 → 通用**:
@@ -175,7 +181,7 @@ dsh plugin --profile <profile> add github:chyxhtc/dsh-ws-recency
175
181
  或固定版本的预构建包:
176
182
 
177
183
  ```powershell
178
- dsh plugin --profile <profile> add https://github.com/chyxhtc/dsh-ws-recency/releases/download/v0.24.1/dsh-ws-recency-0.24.1.tgz
184
+ dsh plugin --profile <profile> add https://github.com/chyxhtc/dsh-ws-recency/releases/download/v0.25.0/dsh-ws-recency-0.25.0.tgz
179
185
  ```
180
186
 
181
187
  装完把 `dsh-ws-recency` 加进 `~/.hypers-work/profiles/<profile>/package.json` 的 `dsh.profile.bundles`,重启应用。
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);
1708
-
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");
2014
+ var distributionPanel = statsDiv("wsr-stats-panel");
2015
+ distributionPanel.appendChild(chart);
2016
+ distributionPanel.appendChild(statsDiv("wsr-stats-note", t("stats.note")));
1714
2017
 
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,6 +2292,8 @@
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;
1958
2297
 
1959
2298
  /** Retention-source tag the Host books this plugin's borrows under. */
1960
2299
  var HANDOFF_SOURCE = "dsh-ws-recency";
@@ -2237,10 +2576,34 @@
2237
2576
  return "";
2238
2577
  }
2239
2578
 
2240
- /** Start the watch: the next reply that carries a handoff block becomes the card. */
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. */
2241
2603
  function watchHandoff(sessionId) {
2242
2604
  handoffSession = sessionId;
2243
2605
  handoffTries = 0;
2606
+ handoffStartedAt = Date.now();
2244
2607
  stopHandoffPolling();
2245
2608
  if (typeof window === "undefined") return;
2246
2609
  function tick() {
@@ -2249,16 +2612,24 @@
2249
2612
  handoffPost({ action: "tail", sessionId: sessionId }).then(function (answer) {
2250
2613
  if (handoffSession !== sessionId) return;
2251
2614
  if (answer !== null && answer.ok === true) {
2252
- var replies = typeof answer.replies === "number" ? answer.replies : 0;
2253
- 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)) {
2254
2619
  var found = handoffBlockOf(answer.text);
2255
2620
  if (found !== "") {
2256
- 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
+ });
2257
2628
  return;
2258
2629
  }
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
2630
  }
2631
+ /* Not ready yet (turn still open, text not newer, or no block in
2632
+ this reply): keep looking at the same session. */
2262
2633
  }
2263
2634
  if (handoffTries > 150) {
2264
2635
  setHandoffState({ sessionId: "", phase: "idle", block: "", needsEnter: false });
@@ -2270,10 +2641,12 @@
2270
2641
  handoffTimer = window.setTimeout(tick, 4000);
2271
2642
  });
2272
2643
  }
2273
- /* The baseline is the reply count before the instruction is answered. */
2644
+ /* The baseline is where the log stood before the instruction is answered. */
2274
2645
  handoffPost({ action: "tail", sessionId: sessionId }).then(function (answer) {
2275
2646
  if (handoffSession !== sessionId) return;
2276
- 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);
2277
2650
  handoffTimer = window.setTimeout(tick, 1500);
2278
2651
  }).catch(function () {
2279
2652
  handoffTimer = window.setTimeout(tick, 3000);
@@ -2286,7 +2659,8 @@
2286
2659
  /* The card starts in its "working" state; if the Host refuses the send
2287
2660
  the fallback flips needsEnter so the card tells the user to press
2288
2661
  Enter instead of pretending the handoff is running. */
2289
- setHandoffState({ sessionId: sessionId, phase: "running", block: "", needsEnter: false });
2662
+ var startTurn = latestTurnNumber();
2663
+ setHandoffState({ sessionId: sessionId, phase: "running", block: "", needsEnter: false, afterTurn: startTurn === null ? undefined : startTurn });
2290
2664
  sendToSession(sessionId, handoffInstruction());
2291
2665
  watchHandoff(sessionId);
2292
2666
  }
@@ -2363,7 +2737,8 @@
2363
2737
  /** Ask the current Session to rewrite the handoff with the user's adjustments. */
2364
2738
  function rewriteHandoff(sessionId, extra) {
2365
2739
  var text = extra.trim() === "" ? t("handoff.regeneratePrompt") : t("handoff.adjustPrompt") + "\n\n" + extra.trim();
2366
- setHandoffState({ sessionId: sessionId, phase: "running", block: "", needsEnter: false });
2740
+ var startTurn = latestTurnNumber();
2741
+ setHandoffState({ sessionId: sessionId, phase: "running", block: "", needsEnter: false, afterTurn: startTurn === null ? undefined : startTurn });
2367
2742
  sendToSession(sessionId, text);
2368
2743
  handoffBaseline = 0;
2369
2744
  handoffTries = 0;
@@ -2396,6 +2771,23 @@
2396
2771
 
2397
2772
  var state = live;
2398
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
+ }
2399
2791
  if (state.phase === "running") {
2400
2792
  return h("div", { className: "wsr-handoff-live" }, state.needsEnter === true ? t("handoff.pressEnter") : t("handoff.preparing"));
2401
2793
  }
@@ -2713,13 +3105,14 @@
2713
3105
  restore.className = "wsr-btn";
2714
3106
  restore.textContent = t("trash.restore");
2715
3107
  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));
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
+ });
2723
3116
  });
2724
3117
  });
2725
3118
  actions.appendChild(restore);
@@ -2729,13 +3122,14 @@
2729
3122
  purge.className = "wsr-btn wsr-btn-danger";
2730
3123
  purge.textContent = t("trash.purge");
2731
3124
  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));
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
+ });
2739
3133
  });
2740
3134
  });
2741
3135
  actions.appendChild(purge);
@@ -2850,13 +3244,14 @@
2850
3244
 
2851
3245
  var act = function (entry, action) {
2852
3246
  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));
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
+ });
2860
3255
  });
2861
3256
  };
2862
3257
 
@@ -2864,22 +3259,23 @@
2864
3259
  var question = action === "unarchive" ? t("archive.confirmUnarchive")
2865
3260
  : action === "forget" ? t("archive.confirmForget")
2866
3261
  : 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));
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
+ });
2883
3279
  });
2884
3280
  };
2885
3281
 
@@ -3385,6 +3781,7 @@
3385
3781
  current: currentHandoffState,
3386
3782
  set: setHandoffState,
3387
3783
  blockOf: handoffBlockOf,
3784
+ readyOf: handoffAnswerReady,
3388
3785
  start: startHandoff,
3389
3786
  rewrite: rewriteHandoff,
3390
3787
  carry: carryHandoff,
package/index.js CHANGED
@@ -32,7 +32,7 @@ import { dirname, join } from "node:path";
32
32
  export const name = "ws-recency";
33
33
 
34
34
  /** Version marker reported by the health route. */
35
- export const HOST_VERSION = "0.24.1";
35
+ export const HOST_VERSION = "0.25.0";
36
36
 
37
37
  /**
38
38
  * Exact routes the client half calls. Registered on the bare web server, so they
@@ -306,6 +306,31 @@ function blockText(content) {
306
306
  return text;
307
307
  }
308
308
 
309
+ /**
310
+ * A one-line hint of what a tool call touched, for the amplified ranking.
311
+ *
312
+ * The argument text is the model's own JSON; the interesting field is the first
313
+ * path/command/query it names, and a malformed or non-string argument simply
314
+ * yields no hint.
315
+ */
316
+ function toolDetail(args) {
317
+ if (typeof args !== "string") return "";
318
+ try {
319
+ const parsed = JSON.parse(args);
320
+ const value = parsed?.file_path ?? parsed?.path ?? parsed?.command ?? parsed?.pattern ?? parsed?.query ?? parsed?.url ?? parsed?.name;
321
+ if (typeof value === "string" && value.trim() !== "") return value.trim().replace(/\s+/g, " ").slice(0, 80);
322
+ } catch {
323
+ /* not JSON: no hint */
324
+ }
325
+ return "";
326
+ }
327
+
328
+ /** First non-empty line, trimmed, for a user/system block's label. */
329
+ function snippetOf(text, limit = 80) {
330
+ const line = String(text ?? "").split("\n")[0].trim().replace(/\s+/g, " ");
331
+ return line.slice(0, limit);
332
+ }
333
+
309
334
  /**
310
335
  * Aggregate one session's events into costs.
311
336
  *
@@ -321,6 +346,15 @@ export function aggregateSession(events) {
321
346
  };
322
347
  const tools = new Map();
323
348
  const callNames = new Map();
349
+ /* Real per-step context, so the bill can be attributed back to the content
350
+ that produced it instead of to the step that happened to be running. */
351
+ const steps = [];
352
+ /** Content blocks with the step before which they enter the prompt. */
353
+ const blocks = [];
354
+ /** Tool-call blocks by call id, so a result can extend its own call. */
355
+ const callBlocks = new Map();
356
+ /** Steps at which a compaction dropped the prefix; blocks stop being re-read. */
357
+ const compactions = [];
324
358
  const toolOf = (name) => {
325
359
  const key = typeof name === "string" && name !== "" ? name : "unknown";
326
360
  let entry = tools.get(key);
@@ -334,6 +368,9 @@ export function aggregateSession(events) {
334
368
  for (const event of events) {
335
369
  if (event === null || typeof event !== "object") continue;
336
370
  const data = event.data ?? {};
371
+ if (typeof event.type === "string" && event.type.toLowerCase().indexOf("compact") !== -1) {
372
+ compactions.push(steps.length);
373
+ }
337
374
  if (typeof event.time === "number") {
338
375
  if (summary.session.createdAt === 0 || event.time < summary.session.createdAt) summary.session.createdAt = event.time;
339
376
  if (event.time > summary.session.lastAt) summary.session.lastAt = event.time;
@@ -359,13 +396,24 @@ export function aggregateSession(events) {
359
396
  summary.totals.cacheReadTokens += Number(usage.cacheReadTokens) || 0;
360
397
  summary.totals.outputTokens += Number(usage.outputTokens) || 0;
361
398
  summary.totals.totalTokens += Number(usage.totalTokens) || 0;
399
+ steps.push({
400
+ input: Number(usage.inputTokens) || 0,
401
+ cacheRead: Number(usage.cacheReadTokens) || 0,
402
+ output: Number(usage.outputTokens) || 0,
403
+ });
362
404
  }
405
+ /* Whatever this reply said or requested enters the prompt of the next
406
+ step. Reasoning is deliberately left out: providers usually do not
407
+ resend it, so it would be counted as amplified when it never is. */
363
408
  const content = data.message !== null && data.message !== undefined ? data.message.content : undefined;
364
409
  for (const block of Array.isArray(content) ? content : []) {
365
410
  if (block === null || typeof block !== "object") continue;
366
411
  if (block.type === "reasoning") summary.estimate.agent.reasoning += estimateTokens(block.text);
367
- else if (block.type === "text") summary.estimate.agent.text += estimateTokens(block.text);
368
- else if (block.type === "tool-call" && block.id !== undefined) callNames.set(String(block.id), block.name);
412
+ else if (block.type === "text") {
413
+ const tokens = estimateTokens(block.text);
414
+ summary.estimate.agent.text += tokens;
415
+ if (tokens > 0) blocks.push({ kind: "agent", name: "agent", detail: snippetOf(block.text), tokens, entry: steps.length });
416
+ } else if (block.type === "tool-call" && block.id !== undefined) callNames.set(String(block.id), block.name);
369
417
  }
370
418
  break;
371
419
  }
@@ -374,21 +422,48 @@ export function aggregateSession(events) {
374
422
  if (data.callId !== undefined) callNames.set(String(data.callId), name);
375
423
  const entry = toolOf(name);
376
424
  entry.calls += 1;
377
- entry.args += estimateTokens(data.arguments);
425
+ const args = estimateTokens(data.arguments);
426
+ entry.args += args;
427
+ const block = {
428
+ kind: "tool",
429
+ name: typeof name === "string" && name !== "" ? name : "unknown",
430
+ detail: toolDetail(data.arguments),
431
+ tokens: args,
432
+ args,
433
+ results: 0,
434
+ entry: steps.length,
435
+ };
436
+ blocks.push(block);
437
+ if (data.callId !== undefined) callBlocks.set(String(data.callId), block);
378
438
  break;
379
439
  }
380
440
  case "tool/result": {
381
- const name = callNames.get(String(data.toolCallId ?? data.message?.source?.callId ?? ""));
441
+ const callId = String(data.toolCallId ?? data.message?.source?.callId ?? "");
442
+ const name = callNames.get(callId);
382
443
  const entry = toolOf(name);
383
- entry.results += estimateTokens(blockText(data.message !== null && data.message !== undefined ? data.message.content : data.content));
444
+ const results = estimateTokens(blockText(data.message !== null && data.message !== undefined ? data.message.content : data.content));
445
+ entry.results += results;
446
+ const block = callBlocks.get(callId);
447
+ if (block !== undefined) {
448
+ block.results += results;
449
+ block.tokens += results;
450
+ } else if (results > 0) {
451
+ blocks.push({ kind: "tool", name: typeof name === "string" && name !== "" ? name : "unknown", detail: "", tokens: results, args: 0, results, entry: steps.length });
452
+ }
384
453
  break;
385
454
  }
386
455
  case "user/message": {
387
- summary.estimate.agent.user += estimateTokens(blockText(data.message !== null && data.message !== undefined ? data.message.content : data.content));
456
+ const text = blockText(data.message !== null && data.message !== undefined ? data.message.content : data.content);
457
+ const tokens = estimateTokens(text);
458
+ summary.estimate.agent.user += tokens;
459
+ if (tokens > 0) blocks.push({ kind: "user", name: "user", detail: snippetOf(text), tokens, entry: steps.length });
388
460
  break;
389
461
  }
390
462
  case "system/message": {
391
- summary.estimate.agent.system += estimateTokens(blockText(data.message !== null && data.message !== undefined ? data.message.content : data.content));
463
+ const text = blockText(data.message !== null && data.message !== undefined ? data.message.content : data.content);
464
+ const tokens = estimateTokens(text);
465
+ summary.estimate.agent.system += tokens;
466
+ if (tokens > 0) blocks.push({ kind: "system", name: "system", detail: snippetOf(text), tokens, entry: steps.length });
392
467
  break;
393
468
  }
394
469
  default:
@@ -408,6 +483,85 @@ export function aggregateSession(events) {
408
483
  for (const entry of list) entry.share = entry.total / grand;
409
484
  summary.estimate.agent.share = agent.total / grand;
410
485
  }
486
+
487
+ /* -------------------------------------------------------------------------
488
+ * Amplified cost: the bill is `sum(context per step)`, so a block that enters
489
+ * early is paid for again on every later step. Its share of the bill is
490
+ * `tokens x remaining steps`, not the tokens it showed at the moment it
491
+ * appeared. That is what makes "top steps" useless and "top content" useful.
492
+ * ----------------------------------------------------------------------- */
493
+ const totalSteps = steps.length;
494
+ const bill = steps.reduce((sum, step) => sum + step.input + step.cacheRead, 0);
495
+ const limitFor = (entry) => {
496
+ let limit = totalSteps;
497
+ /* Conservative: a compaction recorded before step k replaces everything up
498
+ to k, so a block that entered at k is not re-read afterwards either. */
499
+ for (const at of compactions) if (at >= entry && at < limit) limit = at;
500
+ return limit;
501
+ };
502
+ const byKind = new Map();
503
+ const addKind = (kind, tokens, remaining) => {
504
+ let entry = byKind.get(kind);
505
+ if (entry === undefined) {
506
+ entry = { kind, tokens: 0, amplified: 0 };
507
+ byKind.set(kind, entry);
508
+ }
509
+ entry.tokens += tokens;
510
+ entry.amplified += tokens * remaining;
511
+ };
512
+ for (const block of blocks) {
513
+ const limit = limitFor(block.entry);
514
+ block.remaining = Math.max(0, limit - block.entry);
515
+ block.amplified = block.tokens * block.remaining;
516
+ if (block.kind === "tool") {
517
+ addKind("results", block.results, block.remaining);
518
+ addKind("args", block.args, block.remaining);
519
+ } else {
520
+ addKind(block.kind, block.tokens, block.remaining);
521
+ }
522
+ }
523
+ const attributed = [...byKind.values()].reduce((sum, entry) => sum + entry.amplified, 0);
524
+ const ranked = blocks
525
+ .filter((block) => block.amplified > 0)
526
+ .sort((a, b) => b.amplified - a.amplified)
527
+ .slice(0, 15)
528
+ .map((block) => ({
529
+ kind: block.kind,
530
+ name: block.name,
531
+ detail: block.detail,
532
+ entry: block.entry + 1,
533
+ remaining: block.remaining,
534
+ tokens: block.tokens,
535
+ args: block.args || 0,
536
+ results: block.results || 0,
537
+ amplified: block.amplified,
538
+ share: bill > 0 ? block.amplified / bill : 0,
539
+ saving: Math.round(block.amplified * 0.8),
540
+ }));
541
+
542
+ /* Downsample the context curve: at most 96 points keeps the panel cheap. */
543
+ const series = [];
544
+ if (totalSteps > 0) {
545
+ const buckets = Math.min(96, totalSteps);
546
+ const size = Math.ceil(totalSteps / buckets);
547
+ for (let start = 0; start < totalSteps; start += size) {
548
+ const end = Math.min(totalSteps, start + size);
549
+ let sum = 0;
550
+ for (let index = start; index < end; index += 1) sum += steps[index].input + steps[index].cacheRead;
551
+ series.push({ step: start + 1, context: Math.round(sum / (end - start)) });
552
+ }
553
+ }
554
+ summary.amplified = {
555
+ bill,
556
+ attributed,
557
+ share: bill > 0 ? attributed / bill : 0,
558
+ steps: totalSteps,
559
+ series,
560
+ blocks: ranked,
561
+ byKind: [...byKind.values()]
562
+ .map((entry) => ({ ...entry, share: bill > 0 ? entry.amplified / bill : 0 }))
563
+ .sort((a, b) => b.amplified - a.amplified),
564
+ };
411
565
  return summary;
412
566
  }
413
567
 
@@ -1368,8 +1522,24 @@ export async function handleHandoffRequest(ctx, req, res) {
1368
1522
  let text = "";
1369
1523
  let at = 0;
1370
1524
  let replies = 0;
1525
+ /** `seq` of the newest assistant text; the Client compares it with its start. */
1526
+ let textSeq = 0;
1527
+ /** `seq` of the newest event of any kind (a turn can add tool steps). */
1528
+ let lastSeq = 0;
1529
+ /** Turn of the newest assistant text, so the card renders on that turn only. */
1530
+ let turn;
1531
+ let turnOpen = false;
1371
1532
  for (const event of events) {
1372
1533
  if (event === null || typeof event !== "object") continue;
1534
+ if (typeof event.seq === "number" && event.seq > lastSeq) lastSeq = event.seq;
1535
+ if (event.type === "turn/start") {
1536
+ turnOpen = true;
1537
+ continue;
1538
+ }
1539
+ if (event.type === "turn/end") {
1540
+ turnOpen = false;
1541
+ continue;
1542
+ }
1373
1543
  if (event.type !== "assistant/message") continue;
1374
1544
  replies += 1;
1375
1545
  const content = event.data?.message?.content ?? event.data?.content;
@@ -1381,9 +1551,11 @@ export async function handleHandoffRequest(ctx, req, res) {
1381
1551
  if (joined !== "") {
1382
1552
  text = joined;
1383
1553
  at = typeof event.time === "number" ? event.time : 0;
1554
+ if (typeof event.seq === "number") textSeq = event.seq;
1555
+ if (typeof event.data?.turn === "number") turn = event.data.turn;
1384
1556
  }
1385
1557
  }
1386
- sendJson(res, 200, { ok: true, text, at, replies });
1558
+ sendJson(res, 200, { ok: true, text, at, replies, textSeq, lastSeq, turn, turnOpen });
1387
1559
  }
1388
1560
 
1389
1561
  export async function handleTrashListRequest(ctx, req, res) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-ws-recency",
3
- "version": "0.24.1",
3
+ "version": "0.25.0",
4
4
  "description": "Sidebar session management for DeepSeek Harness: workspace groups sorted by latest activity, stale history folded, a global pinned section, follow-up marks, session delete into a recoverable trash, archived sessions managed from that same trash panel, per-session token statistics with an argument/result split and an option to count tool arguments as the agent's writing, and moving a session to another workspace.",
5
5
  "license": "MIT",
6
6
  "author": "chyxhtc",