dsh-all-usage 1.1.4 → 1.1.5
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.
- package/CHANGELOG.md +14 -3
- package/README.md +22 -8
- package/lib/ledger.js +4 -2
- package/lib/plugin.js +3 -0
- package/lib/session-sync.js +267 -112
- package/lib/usage-core.js +7 -0
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -2,7 +2,19 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes to `dsh-all-usage` are documented here.
|
|
4
4
|
|
|
5
|
-
## [
|
|
5
|
+
## [1.1.5] - 2026-09-07
|
|
6
|
+
|
|
7
|
+
### Added
|
|
8
|
+
|
|
9
|
+
- Workspace registries are now kept fresh by an automatic **probe**: all-usage listens to DSH's `domain/changed` event for the workspace domain and, on any durable registry write (create/delete/rename/reorder/archive/attach/detach), rereads `workspaceRegistry.list()`. The sync is incremental — only added workspaces are scanned (the sessions that belong to them) and removed workspaces have their sessions subtracted via inverse folding, while unchanged workspaces reuse their computed aggregates and ledger with zero rescan. The manual Refresh workspaces control, its `POST /api/all-usage/workspaces/refresh` route, and the refresh-workspaces client button were removed. Usage remains intentionally restricted to registered workspaces; unregistered cwds are ignored.
|
|
10
|
+
|
|
11
|
+
### Fixed
|
|
12
|
+
|
|
13
|
+
- Usage is strictly limited to DSH-registered workspaces: sessions whose cwd does not map to `workspaceRegistry.list()` (including existing directories absent from the registry) are ignored, and legacy `unregistered:` ledger rows are never resurrected as history.
|
|
14
|
+
- Ledger rows whose persisted `sourceCwd` no longer maps to a registered workspace (for example the session directory was removed) are skipped during recovery instead of being restored as stale data; the workspace source path is now persisted with every ledger record so restart recovery can validate ownership.
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
## [1.1.4] - 2026-09-03
|
|
6
18
|
|
|
7
19
|
### Added
|
|
8
20
|
|
|
@@ -38,8 +50,6 @@ All notable changes to `dsh-all-usage` are documented here.
|
|
|
38
50
|
- Build-time SVG validation now decodes XML entities before checking, rejects unquoted URI attributes, external CSS url()/image-set() and @import targets (including escaped/commented/CDO-CDC/namespaced <svg:style> forms), DOCTYPE/CDATA/processing instructions and every external-resource element; the CSS checks run only on style attributes and <style> bodies so icon text and comments stay inert. It lives in scripts/svg-guard.mjs so the tests exercise the exact same guard with adversarial fixtures.
|
|
39
51
|
- Bundle the icon provenance required for release: the manifest pins the upstream commit, records per-file upstream paths and modification flags, and assets/model-icons/LICENSE.upstream-lobe-icons.txt ships the MIT notice, copyright, trademark disclaimer and the local modifications. The build fails if the pinned revision, licence file or per-file attribution is missing.
|
|
40
52
|
|
|
41
|
-
## [1.1.4] - 2026-09-03
|
|
42
|
-
|
|
43
53
|
### Fixed
|
|
44
54
|
|
|
45
55
|
- Hardened the model-icon build guard after an independent audit: the CSS checks now reject CDO/CDC-adjacent `@import`, external `@import` inside namespaced `<svg:style>` elements, CSS-escaped `url(` identifiers and external `image-set()` targets, all matching Blink's own tokenizer. Style-attribute `url(...)` references are checked on both the raw and entity-decoded document so `"` quoting cannot split a payload while encoded `@import` is still caught after decoding.
|
|
@@ -235,6 +245,7 @@ This release reduces historical scan work, storage write amplification, and Dash
|
|
|
235
245
|
- Allowed same-origin browser balance GET requests that omit `Origin` while retaining token protection.
|
|
236
246
|
- Standardized English date buckets, range filters, streaks, heatmap dates, and export timestamps on UTC.
|
|
237
247
|
|
|
248
|
+
[1.1.5]: https://github.com/ParticleLight/dsh-all-usage/releases/tag/v1.1.5
|
|
238
249
|
[1.1.4]: https://github.com/ParticleLight/dsh-all-usage/releases/tag/v1.1.4
|
|
239
250
|
[1.1.3]: https://github.com/ParticleLight/dsh-all-usage/releases/tag/v1.1.3
|
|
240
251
|
[1.1.2]: https://github.com/ParticleLight/dsh-all-usage/releases/tag/v1.1.2
|
package/README.md
CHANGED
|
@@ -11,7 +11,7 @@ DeepSeek Harness 全量用量看板:按模型、供应商、工作区和时间
|
|
|
11
11
|
### 功能
|
|
12
12
|
|
|
13
13
|
- **热力图**:53 周使用热力图;按工作区筛选并查看每日回合与 Token 明细
|
|
14
|
-
- **模型统计**:支持混合查看、按模型合并、按供应商汇总三种维度,展示调用次数、各类 Token
|
|
14
|
+
- **模型统计**:支持混合查看、按模型合并、按供应商汇总三种维度,展示调用次数、各类 Token 与缓存命中率;模型行与筛选下拉显示真实厂商品牌 SVG 图标(未知/混牌保持中性)
|
|
15
15
|
- **摘要与工作区**:Token 用量、缓存命中、估算成本、账户余额、连续使用、工作区 Token 分布和明细
|
|
16
16
|
- **成本统计**:从 models.dev 同步模型价格;按输入、输出、缓存读取和缓存写入四个桶计算,保存价格快照,明确区分已计价、免费模型和未计价调用
|
|
17
17
|
- **导出**:按当前时间范围和模型聚合方式导出 CSV
|
|
@@ -30,11 +30,12 @@ DeepSeek Harness 全量用量看板:按模型、供应商、工作区和时间
|
|
|
30
30
|
### 兼容性与已知限制
|
|
31
31
|
|
|
32
32
|
- **运行环境**:需要 Node.js `>=22 <25`;CI 会在 Node 22 和 Node 24 上运行测试、语法检查和 npm 包内容检查。
|
|
33
|
-
- **DSH 兼容**:`package.json` 声明 DSH runtime `>=0.1.1-rc.1 <0.1.2`,已使用 `0.1.1-rc.2` 和 `0.1.1-rc.1` 的真实 Cordis
|
|
33
|
+
- **DSH 兼容**:`package.json` 声明 DSH runtime `>=0.1.1-rc.1 <0.1.2`,已使用 `0.1.1-rc.2` 和 `0.1.1-rc.1` 的真实 Cordis 服务链验证;`0.1.2-rc.1` 已通过本人实际使用验证兼容,但尚未纳入 CI smoke 矩阵。
|
|
34
34
|
- **Web 服务依赖**:Host 将 `webServer` 声明为必需依赖,确保服务晚挂载时由 DSH 等待后再执行插件;该包面向 DSH Web profile,不提供无 WebServer 的 headless 路由。HTTP 守卫还会检查真实 socket peer,反向代理只有在连接本身来自 loopback 时才会被接受。
|
|
35
35
|
|
|
36
36
|
| DSH runtime | Node.js 支持 | 真实 Cordis smoke | 结论 |
|
|
37
37
|
| --- | --- | --- | --- |
|
|
38
|
+
| `0.1.2-rc.1` | `>=22 <25` | 通过(本人实际使用验证,未纳入 CI) | 已实际验证兼容 |
|
|
38
39
|
| `0.1.1-rc.2` | `>=22 <25`,CI 覆盖 22/24 | 通过(当前 Node 24) | 已声明、已验证 |
|
|
39
40
|
| `0.1.1-rc.1` | `>=22 <25`,CI 覆盖 22/24 | 通过(当前 Node 24) | 已声明、已验证 |
|
|
40
41
|
| 其他版本 | `>=22 <25` | 未测试 | 不在已验证矩阵内 |
|
|
@@ -44,7 +45,7 @@ DeepSeek Harness 全量用量看板:按模型、供应商、工作区和时间
|
|
|
44
45
|
- **中断请求**:上游请求被中断时可能只有 `assistant/chunk` 的 usage,没有最终 `assistant/message`;本插件会保留该 chunk 用量。同一 `turn / step` 后续出现最终 message 时,message 会替换 chunk。若上游完全没有 usage 事件,则无法从响应内容精确恢复 Token。
|
|
45
46
|
- **估算成本**:成本是基于 models.dev 价格和 DSH usage 桶的估算,不是供应商账单;目录不可用或模型没有官方匹配时不会猜测价格,而是显示未计价。缓存读取、缓存写入和 reasoning 的口径取决于 DSH 上游事件。
|
|
46
47
|
- **分层价格**:models.dev 的 tiered/context-dependent 价格按本次请求的输入上下文(fresh input + cache read + cache write)选择对应档位;阈值边界遵循目录定义,无法验证的异常 tier 仍显示为 unsupported。
|
|
47
|
-
-
|
|
48
|
+
- **工作区边界**:只有 cwd 能映射到 DSH 已注册工作区的会话才进入统计;未注册 cwd(包括已存在但未在 registry 中登记的目录)会被忽略。工作区注册列表通过 DSH 的 `domain/changed` 探针自动同步:注册表一有改动就重读并只对新增/删除的工作区做增量处理,未变化的已有工作区直接复用已计算账本,不会全量重扫。会话尚未成功 flush 前删除或损坏的日志无法由独立账本恢复。
|
|
48
49
|
|
|
49
50
|
### 本地统计与官方账单
|
|
50
51
|
|
|
@@ -53,7 +54,7 @@ DeepSeek Harness 全量用量看板:按模型、供应商、工作区和时间
|
|
|
53
54
|
- 本地统计读取 DSH 的 `assistant/chunk`、最终 `assistant/message` 和其他会话事件,按同一 `turn / step` 去重和替换;官方账单可能按供应商自己的请求、分词器、舍入、折扣、免费额度和结算周期计算。
|
|
54
55
|
- 失败请求只要留下 usage chunk,就会进入本地统计;供应商是否对该失败请求收费,应以官方账单为准。
|
|
55
56
|
- 价格来自 models.dev 的公开模型目录和本地显式覆盖;目录价格、供应商实际价格、区域费率和账单折扣可能不同。成本字段应理解为估算值。
|
|
56
|
-
-
|
|
57
|
+
- 本地统计只包含已注册工作区;未注册 cwd 与已删除目录的旧 ledger 不进入统计,并可能因日志损坏、清理或上游没有发出 usage 而少于官方账单。
|
|
57
58
|
|
|
58
59
|
### 可复现事件示例
|
|
59
60
|
|
|
@@ -102,6 +103,12 @@ node scripts/replay-fixture.mjs fixtures/usage-events.json
|
|
|
102
103
|
|
|
103
104
|
### 最近更新
|
|
104
105
|
|
|
106
|
+
**v1.1.4**
|
|
107
|
+
|
|
108
|
+
- **模型品牌图标**:请求日志、选中调用详情、模型统计表、成本设置匹配表、环形图图例与模型筛选下拉现在显示真实厂商品牌 SVG(DeepSeek、OpenAI、Claude、Gemini、Meta、Zhipu、xAI、Qwen、Doubao、Kimi、MiniMax);模型命名空间优先于 DSH 供应商名,未知或混牌行保持中性。图标在构建期以 data URI 内嵌并由 scripts/svg-guard.mjs 校验(实体解码、CSS 转义/CDO/命名空间、url()/image-set() 均覆盖,注释与文本不误杀),运行时零网络请求。
|
|
109
|
+
- **构建安全加固**:补齐 CDO/CDC 邻接 at-import、命名空间 style 元素、CSS 转义 url() 与外部 image-set() 四类绕过,并把 CSS 检查收窄到 style 属性与 style 体;对抗用例现在断言拒绝原因。
|
|
110
|
+
- 三张用量仪表盘截图刷新为当前 UI。
|
|
111
|
+
|
|
105
112
|
**v1.1.3**
|
|
106
113
|
|
|
107
114
|
- 成本统计支持经验证的 context-tiered 官方费率、可展开费率表和显式价格覆盖。
|
|
@@ -197,7 +204,7 @@ A full usage dashboard for DeepSeek Harness. Analyze tokens, cache behavior, est
|
|
|
197
204
|
### Features
|
|
198
205
|
|
|
199
206
|
- **Heatmap**: a 53-week activity heatmap with workspace filters and daily turn/token details
|
|
200
|
-
- **Model analytics**: mixed view, model-merged view, and provider summary with calls, token categories, and cache hit rate
|
|
207
|
+
- **Model analytics**: mixed view, model-merged view, and provider summary with calls, token categories, and cache hit rate; model rows and the model filter dropdown render vendor brand SVG icons (neutral for unknown or mixed brands)
|
|
201
208
|
- **Summary and workspaces**: processed tokens, cache hits, estimated cost, account balance, usage streaks, workspace distribution, and details
|
|
202
209
|
- **Cost statistics**: sync model prices from models.dev, calculate four cost buckets, persist price snapshots, and distinguish priced, free, ambiguous, and unpriced calls
|
|
203
210
|
- **CSV export**: export data using the selected time range and aggregation mode
|
|
@@ -216,11 +223,12 @@ A full usage dashboard for DeepSeek Harness. Analyze tokens, cache behavior, est
|
|
|
216
223
|
### Compatibility and Known Limitations
|
|
217
224
|
|
|
218
225
|
- **Runtime**: Node.js `>=22 <25` is required. CI runs the test suite, syntax checks, and package-content checks on Node 22 and Node 24.
|
|
219
|
-
- **DSH compatibility**: `package.json` declares DSH runtime `>=0.1.1-rc.1 <0.1.2`; the real Cordis service chain is verified on `0.1.1-rc.2` and `0.1.1-rc.1`.
|
|
226
|
+
- **DSH compatibility**: `package.json` declares DSH runtime `>=0.1.1-rc.1 <0.1.2`; the real Cordis service chain is verified on `0.1.1-rc.2` and `0.1.1-rc.1`. `0.1.2-rc.1` has also been verified compatible through the maintainer's real-world use, but is not yet covered by the CI smoke matrix.
|
|
220
227
|
- **Web service dependency**: the Host declares `webServer` as a required dependency, so DSH waits for a late-mounted service before applying the plugin; this package targets the DSH Web profile and does not expose routes without WebServer. The HTTP guard also checks the actual socket peer, so a reverse proxy is accepted only when the connection itself is loopback.
|
|
221
228
|
|
|
222
229
|
| DSH runtime | Node.js support | Real Cordis smoke | Conclusion |
|
|
223
230
|
| --- | --- | --- | --- |
|
|
231
|
+
| `0.1.2-rc.1` | `>=22 <25` | Passed through maintainer use (not in CI) | Verified compatible in real-world use |
|
|
224
232
|
| `0.1.1-rc.2` | `>=22 <25`, CI covers 22/24 | Passed (current Node 24) | Declared and verified |
|
|
225
233
|
| `0.1.1-rc.1` | `>=22 <25`, CI covers 22/24 | Passed (current Node 24) | Declared and verified |
|
|
226
234
|
| Other versions | `>=22 <25` | Not tested | Outside the verified matrix |
|
|
@@ -230,7 +238,7 @@ An unlisted DSH version is not necessarily incompatible. Include the DSH, Node.j
|
|
|
230
238
|
- **Interrupted requests**: an interrupted upstream request may emit only `assistant/chunk` usage and never produce a final `assistant/message`; that chunk is retained. A later final message for the same turn/step replaces it. If the upstream emits no usage event at all, exact token usage cannot be reconstructed from response text.
|
|
231
239
|
- **Estimated cost**: cost is an estimate based on models.dev rates and DSH usage buckets, not a provider invoice. Unavailable catalogs and unmatched models remain unpriced instead of receiving guessed rates. Cache reads, cache writes, and reasoning follow the buckets reported by the upstream DSH event.
|
|
232
240
|
- **Tiered prices**: models.dev context-tiered entries select the applicable rate from the request input context (fresh input plus cache read/write tokens); malformed schedules remain unsupported.
|
|
233
|
-
- **
|
|
241
|
+
- **Workspace boundary**: only sessions whose cwd maps to a DSH-registered workspace are included. Unregistered cwds, including existing directories absent from the registry, are ignored. The registry is kept fresh by a `domain/changed` probe: any durable workspace-domain write triggers a reread, and only added/removed workspaces are reprocessed incrementally — unchanged workspaces reuse their computed aggregates and ledger. Data deleted or corrupted before a successful session flush cannot be recovered from the separate ledger.
|
|
234
242
|
|
|
235
243
|
### Local Statistics vs Official Billing
|
|
236
244
|
|
|
@@ -239,7 +247,7 @@ This plugin reports replayable statistics from local DSH event logs; it is not a
|
|
|
239
247
|
- Local statistics read DSH `assistant/chunk`, final `assistant/message`, and related session events, then deduplicate and replace samples by logical `turn / step`. Official billing may use a provider tokenizer, rounding rules, discounts, free quotas, and billing periods.
|
|
240
248
|
- A failed request is included locally whenever it leaves a usage chunk; whether the provider charged for that failed request must be checked against the official bill.
|
|
241
249
|
- Prices come from the public models.dev catalog and local explicit overrides. Catalog prices can differ from provider prices, regional rates, and invoice discounts, so the cost field is an estimate.
|
|
242
|
-
- Local statistics include only
|
|
250
|
+
- Local statistics include registered workspaces only; unregistered cwds and old ledger rows for deleted directories are excluded, and totals can still be lower than the official bill when logs are damaged, cleaned up, or the upstream emits no usage event.
|
|
243
251
|
|
|
244
252
|
### Reproducible Event Examples
|
|
245
253
|
|
|
@@ -288,6 +296,12 @@ The command loads the real plugin Host, calls its compatible APIs, checks the do
|
|
|
288
296
|
|
|
289
297
|
### Latest Update
|
|
290
298
|
|
|
299
|
+
**v1.1.4**
|
|
300
|
+
|
|
301
|
+
- **Vendor brand icons**: request logs, selected-call details, the model summary table, the cost-settings match table, donut legends, and the model filter dropdown now render real vendor brand SVGs (DeepSeek, OpenAI, Claude, Gemini, Meta, Zhipu, xAI, Qwen, Doubao, Kimi, MiniMax); the model namespace wins over the DSH provider name, and unknown or mixed-brand rows stay neutral. Icons are embedded as data URIs at build time and validated by scripts/svg-guard.mjs (entity decoding, CSS escapes/CDO/namespaced styles, url()/image-set() all covered, comments and text stay inert), with zero runtime network access.
|
|
302
|
+
- **Build hardening**: per the independent audit, closed four bypass classes (CDO/CDC-adjacent at-import, namespaced style elements, CSS-escaped url(), external image-set()) and scoped the CSS checks to style attributes and bodies; adversarial fixtures now assert the rejection reason.
|
|
303
|
+
- Refreshed the three usage-dashboard screenshots to the current UI.
|
|
304
|
+
|
|
291
305
|
**v1.1.3**
|
|
292
306
|
|
|
293
307
|
- Added validated context-tiered official pricing, expandable rate schedules, and explicit price overrides.
|
package/lib/ledger.js
CHANGED
|
@@ -238,7 +238,8 @@ export function createLedger(host) {
|
|
|
238
238
|
}, { costPrevious: previousUsage.get(key) })
|
|
239
239
|
if (result.accepted && usageEvent.kind === 'message') currentIdentity = identity
|
|
240
240
|
}
|
|
241
|
-
|
|
241
|
+
const sourceCwd = session && session.header && typeof session.header.cwd === 'string' ? session.header.cwd : undefined
|
|
242
|
+
return { version: LEDGER_VERSION, sessionId: sid, workspaceId, ...(sourceCwd === undefined ? {} : { sourceCwd }), lastSeq, source, updatedAt: nextLedgerRevision(), lastRevision: typeof revision === 'string' ? revision : undefined, sourceRevision: typeof revision === 'string' ? revision : undefined, lastIdentity: currentIdentity, contextTimes: Array.from(contextTimes.entries()).map(([key, time]) => ({ key, time })), turns: Array.from(turns.values()), usage: Array.from(usage.values()) }
|
|
242
243
|
}
|
|
243
244
|
function normalizeLedgerRecord(raw, key) {
|
|
244
245
|
if (raw === null || typeof raw !== 'object' || (raw.version !== LEDGER_VERSION && raw.version !== PREVIOUS_LEDGER_VERSION && raw.version !== LEGACY_LEDGER_VERSION) || typeof raw.sessionId !== 'string' || raw.sessionId !== key) return null
|
|
@@ -279,7 +280,8 @@ export function createLedger(host) {
|
|
|
279
280
|
}
|
|
280
281
|
const lastUsage = Array.from(usageMap.values()).at(-1)
|
|
281
282
|
const lastIdentity = coerceIdentity(raw.lastIdentity || raw.sourceRevisionIdentity || (lastUsage && lastUsage.identity))
|
|
282
|
-
const
|
|
283
|
+
const sourceCwd = typeof raw.sourceCwd === 'string' && raw.sourceCwd.trim() !== '' ? raw.sourceCwd : undefined
|
|
284
|
+
const normalizedRecord = { version: LEDGER_VERSION, sessionId: raw.sessionId, workspaceId: raw.workspaceId, ...(sourceCwd === undefined ? {} : { sourceCwd }), lastSeq: validLedgerSeq(raw.lastSeq) ? raw.lastSeq : -1, source: raw.source === 'flush' ? 'flush' : 'scan', updatedAt, lastRevision: typeof raw.lastRevision === 'string' ? raw.lastRevision : (typeof raw.sourceRevision === 'string' ? raw.sourceRevision : undefined), sourceRevision: typeof raw.sourceRevision === 'string' ? raw.sourceRevision : (typeof raw.lastRevision === 'string' ? raw.lastRevision : undefined), lastIdentity, contextTimes: Array.from(contextMap.entries()).map(([key, time]) => ({ key, time })), turns: Array.from(turnMap.values()), usage: Array.from(usageMap.values()) }
|
|
283
285
|
if (rebuildReason !== undefined) normalizedRecord.rebuildRequired = rebuildReason
|
|
284
286
|
Object.defineProperty(normalizedRecord, 'needsUpgrade', { value: needsUpgrade, enumerable: false, writable: true })
|
|
285
287
|
return normalizedRecord
|
package/lib/plugin.js
CHANGED
|
@@ -100,6 +100,9 @@ function apply(ctx) {
|
|
|
100
100
|
reconcilePending: false,
|
|
101
101
|
reconcileInFlight: false,
|
|
102
102
|
reconcileTimer: null,
|
|
103
|
+
workspaceSyncTimer: null,
|
|
104
|
+
workspaceSyncInFlight: false,
|
|
105
|
+
workspaceSyncPending: false,
|
|
103
106
|
}
|
|
104
107
|
|
|
105
108
|
const host = { ctx, services, state, webServer: services.webServer, aggregation: null, ledger: null, pricing: null, balance: null, sessionSync: null, aliases: null }
|
package/lib/session-sync.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
import { contextTimeKey, extractUsageEvent, pickPricingTime, touchContextTimes } from './usage-core.js'
|
|
1
|
+
import { contextTimeKey, extractUsageEvent, pickPricingTime, touchContextTimes, workspacePathKey } from './usage-core.js'
|
|
2
2
|
|
|
3
3
|
const RECONCILE_INTERVAL_MS = 120000
|
|
4
4
|
const RECONCILE_HINT_DELAY_MS = 3000
|
|
5
|
+
const WORKSPACE_SYNC_DEBOUNCE_MS = 300
|
|
5
6
|
|
|
6
7
|
export function createSessionSync(host) {
|
|
7
8
|
const { ctx, state } = host
|
|
@@ -107,13 +108,56 @@ export function createSessionSync(host) {
|
|
|
107
108
|
state.ledgerDirtySessions.add(sid)
|
|
108
109
|
state.ledgerDirtyEpochs.set(sid, (state.ledgerDirtyEpochs.get(sid) || 0) + 1)
|
|
109
110
|
}
|
|
111
|
+
function buildWorkspaceSnapshot(workspaces) {
|
|
112
|
+
const wsMeta = new Map()
|
|
113
|
+
const pathIndex = new Map()
|
|
114
|
+
const memberOf = new Map()
|
|
115
|
+
for (const w of workspaces) {
|
|
116
|
+
const id = w && w.id
|
|
117
|
+
const path = w && typeof w.path === 'string' ? w.path : ''
|
|
118
|
+
const title = w && typeof w.title === 'string' ? w.title : ''
|
|
119
|
+
if (id === undefined) continue
|
|
120
|
+
wsMeta.set(id, { id, title, path })
|
|
121
|
+
if (path !== '') pathIndex.set(workspacePathKey(path), id)
|
|
122
|
+
if (w && Array.isArray(w.sessionIds)) {
|
|
123
|
+
for (const sid of w.sessionIds) memberOf.set(sid, id)
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
return { wsMeta, pathIndex, memberOf }
|
|
127
|
+
}
|
|
128
|
+
function installWorkspaceSnapshot(next) {
|
|
129
|
+
let metadataChanged = state.wsMeta.size !== next.wsMeta.size || state.pathIndex.size !== next.pathIndex.size || state.memberOf.size !== next.memberOf.size
|
|
130
|
+
if (!metadataChanged) {
|
|
131
|
+
for (const [id, value] of next.wsMeta) {
|
|
132
|
+
const previous = state.wsMeta.get(id)
|
|
133
|
+
if (previous === undefined || previous.title !== value.title || previous.path !== value.path) { metadataChanged = true; break }
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
if (!metadataChanged) {
|
|
137
|
+
for (const [path, id] of next.pathIndex) if (state.pathIndex.get(path) !== id) { metadataChanged = true; break }
|
|
138
|
+
}
|
|
139
|
+
if (!metadataChanged) {
|
|
140
|
+
for (const [sid, id] of next.memberOf) if (state.memberOf.get(sid) !== id) { metadataChanged = true; break }
|
|
141
|
+
}
|
|
142
|
+
state.wsMeta.clear()
|
|
143
|
+
state.pathIndex.clear()
|
|
144
|
+
state.memberOf.clear()
|
|
145
|
+
for (const [id, value] of next.wsMeta) state.wsMeta.set(id, value)
|
|
146
|
+
for (const [path, id] of next.pathIndex) state.pathIndex.set(path, id)
|
|
147
|
+
for (const [sid, id] of next.memberOf) state.memberOf.set(sid, id)
|
|
148
|
+
if (metadataChanged) markStatsChanged('metadata')
|
|
149
|
+
return metadataChanged
|
|
150
|
+
}
|
|
151
|
+
function workspaceForCwd(cwd) {
|
|
152
|
+
if (typeof cwd !== 'string' || cwd === '') return undefined
|
|
153
|
+
return state.pathIndex.get(workspacePathKey(cwd))
|
|
154
|
+
}
|
|
110
155
|
function wsForLiveSession(session, sid) {
|
|
111
156
|
let wsId = state.memberOf.get(sid)
|
|
112
157
|
if (wsId !== undefined) return wsId
|
|
113
158
|
const header = session && session.header
|
|
114
159
|
const cwd = header && typeof header.cwd === 'string' ? header.cwd : ''
|
|
115
|
-
|
|
116
|
-
wsId = state.pathIndex.get(cwd)
|
|
160
|
+
wsId = workspaceForCwd(cwd)
|
|
117
161
|
if (wsId !== undefined) state.memberOf.set(sid, wsId)
|
|
118
162
|
return wsId
|
|
119
163
|
}
|
|
@@ -259,6 +303,81 @@ export function createSessionSync(host) {
|
|
|
259
303
|
return undefined
|
|
260
304
|
})
|
|
261
305
|
}
|
|
306
|
+
function scanOneSession(sid, record, wsId, generation, snapshots) {
|
|
307
|
+
return enqueue(sid, async () => {
|
|
308
|
+
if (state.disposed || generation !== state.aggregationGeneration) return
|
|
309
|
+
try {
|
|
310
|
+
if (state.sessionSeq.has(sid) && !state.liveResyncPending.has(sid)) return
|
|
311
|
+
// v1.0.8: when the persisted log revision is unchanged since the last ledger
|
|
312
|
+
// write, the whole readSession (full event transfer) is skipped — the ledger
|
|
313
|
+
// record is applied directly and the live feed keeps catching new events.
|
|
314
|
+
const previousRecord = state.ledgerRecords.get(sid)
|
|
315
|
+
const revision = snapshots === null ? undefined : snapshots.get(sid)
|
|
316
|
+
if (!state.liveResyncPending.has(sid) && previousRecord !== undefined && previousRecord.needsUpgrade !== true && previousRecord.rebuildRequired === undefined && previousRecord.workspaceId === wsId && typeof previousRecord.lastRevision === 'string' && typeof revision === 'string' && revision === previousRecord.lastRevision) {
|
|
317
|
+
state.sync.sessionsSkippedByRevision += 1
|
|
318
|
+
applyLedgerRecord(previousRecord, 'ledger-reuse')
|
|
319
|
+
state.sessionSeq.set(sid, previousRecord.lastSeq)
|
|
320
|
+
state.sessionCount.add(sid)
|
|
321
|
+
markStatsChanged('scan')
|
|
322
|
+
return
|
|
323
|
+
}
|
|
324
|
+
state.sync.sessionsRead += 1
|
|
325
|
+
markStatsChanged('scan')
|
|
326
|
+
const snap = await ctx.sessionQuery.readSession(sid)
|
|
327
|
+
if (state.disposed || generation !== state.aggregationGeneration) return
|
|
328
|
+
if (snap && Array.isArray(snap.events)) {
|
|
329
|
+
// v1.0.7: incremental seed — the durable ledger doubles as a per-session
|
|
330
|
+
// cursor (cc-switch session_log_sync mtime+offset parity). An unchanged
|
|
331
|
+
// session applies its canonical record directly and never re-folds;
|
|
332
|
+
// a changed session seeds the previous record once, then folds only the
|
|
333
|
+
// new tail (previously every listed session was re-read and fully rebuilt).
|
|
334
|
+
const sequence = sequenceProfile(snap.events)
|
|
335
|
+
const currentLastSeq = sequence.lastSeq
|
|
336
|
+
const previous = state.ledgerRecords.get(sid)
|
|
337
|
+
const canFoldTail = previous !== undefined && previous.needsUpgrade !== true && previous.rebuildRequired === undefined && previous.workspaceId === wsId && !sequence.nonMonotonic && !sequence.hasInvalid && previous.lastSeq >= 0 && currentLastSeq > previous.lastSeq
|
|
338
|
+
if (canFoldTail) {
|
|
339
|
+
applyLedgerRecord(previous, 'ledger-reuse')
|
|
340
|
+
foldEvents(wsId, snap.events, previous.lastSeq, sid, 'scan')
|
|
341
|
+
} else {
|
|
342
|
+
// A changed revision with no new tail may still contain a replacement;
|
|
343
|
+
// rebuild from the complete read instead of trusting lastSeq alone.
|
|
344
|
+
foldEvents(wsId, snap.events, undefined, sid, 'scan')
|
|
345
|
+
}
|
|
346
|
+
const ledger = buildLedgerRecord({ id: sid, header: record.header, events: snap.events }, wsId, 'scan', revision, previous, !sequence.hasInvalid)
|
|
347
|
+
const canonical = ledger === null ? state.ledgerRecords.get(sid) : (canFoldTail ? storeLedgerRecord(ledger) : replaceLedgerRecord(ledger))
|
|
348
|
+
if (canonical === ledger) {
|
|
349
|
+
void persistLedgerRecord(ledger)
|
|
350
|
+
}
|
|
351
|
+
const observedLastSeq = state.sessionSeq.get(sid)
|
|
352
|
+
const nextLastSeq = Math.max(currentLastSeq, observedLastSeq === undefined ? -1 : observedLastSeq)
|
|
353
|
+
state.sessionSeq.set(sid, nextLastSeq)
|
|
354
|
+
state.sessionCount.add(sid)
|
|
355
|
+
if (observedLastSeq === undefined || observedLastSeq <= currentLastSeq) cancelLiveResync(sid)
|
|
356
|
+
else scheduleLiveResync(sid, wsId, generation)
|
|
357
|
+
}
|
|
358
|
+
} catch (err) {
|
|
359
|
+
if (generation !== state.aggregationGeneration) return
|
|
360
|
+
state.sync.sessionsFailed += 1
|
|
361
|
+
state.scan.failed += 1
|
|
362
|
+
noteSyncError('session-read-failed')
|
|
363
|
+
const saved = state.ledgerRecords.get(sid)
|
|
364
|
+
if (saved !== undefined) {
|
|
365
|
+
applyLedgerRecord(saved, 'ledger-recovery')
|
|
366
|
+
if (saved.turns.length > 0 || saved.usage.length > 0) state.sync.sessionsRestoredFromLedger += 1
|
|
367
|
+
state.sessionSeq.set(sid, -1)
|
|
368
|
+
state.sessionCount.add(sid)
|
|
369
|
+
} else {
|
|
370
|
+
state.sessionSeq.set(sid, -1)
|
|
371
|
+
}
|
|
372
|
+
} finally {
|
|
373
|
+
if (generation === state.aggregationGeneration) {
|
|
374
|
+
state.scan.scanned += 1
|
|
375
|
+
markStatsChanged('scan')
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
})
|
|
379
|
+
}
|
|
380
|
+
|
|
262
381
|
async function runBaseline(generation = state.aggregationGeneration) {
|
|
263
382
|
if (state.scan.started || state.disposed || generation !== state.aggregationGeneration) return
|
|
264
383
|
state.scan.started = true
|
|
@@ -268,40 +387,7 @@ export function createSessionSync(host) {
|
|
|
268
387
|
let setupFailed = false
|
|
269
388
|
try {
|
|
270
389
|
const workspaces = ctx.workspaceRegistry.list()
|
|
271
|
-
|
|
272
|
-
const nextPathIndex = new Map()
|
|
273
|
-
const nextMemberOf = new Map()
|
|
274
|
-
for (const w of workspaces) {
|
|
275
|
-
const id = w && w.id
|
|
276
|
-
const path = w && typeof w.path === 'string' ? w.path : ''
|
|
277
|
-
const title = w && typeof w.title === 'string' ? w.title : ''
|
|
278
|
-
if (id === undefined) continue
|
|
279
|
-
nextWsMeta.set(id, { id, title, path })
|
|
280
|
-
if (path !== '') nextPathIndex.set(path, id)
|
|
281
|
-
if (w && Array.isArray(w.sessionIds)) {
|
|
282
|
-
for (const sid of w.sessionIds) nextMemberOf.set(sid, id)
|
|
283
|
-
}
|
|
284
|
-
}
|
|
285
|
-
let metadataChanged = state.wsMeta.size !== nextWsMeta.size || state.pathIndex.size !== nextPathIndex.size || state.memberOf.size !== nextMemberOf.size
|
|
286
|
-
if (!metadataChanged) {
|
|
287
|
-
for (const [id, value] of nextWsMeta) {
|
|
288
|
-
const previous = state.wsMeta.get(id)
|
|
289
|
-
if (previous === undefined || previous.title !== value.title || previous.path !== value.path) { metadataChanged = true; break }
|
|
290
|
-
}
|
|
291
|
-
}
|
|
292
|
-
if (!metadataChanged) {
|
|
293
|
-
for (const [path, id] of nextPathIndex) if (state.pathIndex.get(path) !== id) { metadataChanged = true; break }
|
|
294
|
-
}
|
|
295
|
-
if (!metadataChanged) {
|
|
296
|
-
for (const [sid, id] of nextMemberOf) if (state.memberOf.get(sid) !== id) { metadataChanged = true; break }
|
|
297
|
-
}
|
|
298
|
-
state.wsMeta.clear()
|
|
299
|
-
state.pathIndex.clear()
|
|
300
|
-
state.memberOf.clear()
|
|
301
|
-
for (const [id, value] of nextWsMeta) state.wsMeta.set(id, value)
|
|
302
|
-
for (const [path, id] of nextPathIndex) state.pathIndex.set(path, id)
|
|
303
|
-
for (const [sid, id] of nextMemberOf) state.memberOf.set(sid, id)
|
|
304
|
-
if (metadataChanged) markStatsChanged('metadata')
|
|
390
|
+
installWorkspaceSnapshot(buildWorkspaceSnapshot(workspaces))
|
|
305
391
|
} catch (err) {
|
|
306
392
|
console.error('[all-usage] workspace list failed:', err)
|
|
307
393
|
setupFailed = true
|
|
@@ -353,11 +439,18 @@ export function createSessionSync(host) {
|
|
|
353
439
|
if (record === undefined || record === null || record.header === undefined) continue
|
|
354
440
|
const sid = record.header.id
|
|
355
441
|
const cwd = typeof record.header.cwd === 'string' ? record.header.cwd : ''
|
|
356
|
-
const wsId =
|
|
442
|
+
const wsId = workspaceForCwd(cwd)
|
|
357
443
|
if (sid !== undefined && wsId !== undefined) listedSessionIds.add(sid)
|
|
358
444
|
}
|
|
359
445
|
for (const [sid, record] of state.ledgerRecords) {
|
|
360
446
|
if (!listedSessionIds.has(sid)) {
|
|
447
|
+
// A ledger row from a deleted cwd is stale historical data, not an
|
|
448
|
+
// active workspace. Registered records remain recoverable; unknown
|
|
449
|
+
// records are recovered only while their source cwd still exists. Old
|
|
450
|
+
// synthetic rows predate sourceCwd persistence and cannot be validated,
|
|
451
|
+
// so they are fail-closed rather than resurrected after a restart.
|
|
452
|
+
if (record.sourceCwd !== undefined && workspaceForCwd(record.sourceCwd) === undefined) continue
|
|
453
|
+
if (typeof record.workspaceId === 'string' && record.workspaceId.startsWith('unregistered:')) continue
|
|
361
454
|
applyLedgerRecord(record, 'ledger-recovery')
|
|
362
455
|
if (record.turns.length > 0 || record.usage.length > 0) state.sync.sessionsRestoredFromLedger += 1
|
|
363
456
|
}
|
|
@@ -372,85 +465,14 @@ export function createSessionSync(host) {
|
|
|
372
465
|
}
|
|
373
466
|
const sid = record.header.id
|
|
374
467
|
const cwd = typeof record.header.cwd === 'string' ? record.header.cwd : ''
|
|
375
|
-
const wsId =
|
|
468
|
+
const wsId = workspaceForCwd(cwd)
|
|
376
469
|
if (sid === undefined || wsId === undefined) {
|
|
377
470
|
state.scan.scanned += 1
|
|
378
471
|
markStatsChanged('scan')
|
|
379
472
|
continue
|
|
380
473
|
}
|
|
381
474
|
listedSessionIds.add(sid)
|
|
382
|
-
await
|
|
383
|
-
if (state.disposed || generation !== state.aggregationGeneration) return
|
|
384
|
-
try {
|
|
385
|
-
if (state.sessionSeq.has(sid) && !state.liveResyncPending.has(sid)) return
|
|
386
|
-
// v1.0.8: when the persisted log revision is unchanged since the last ledger
|
|
387
|
-
// write, the whole readSession (full event transfer) is skipped — the ledger
|
|
388
|
-
// record is applied directly and the live feed keeps catching new events.
|
|
389
|
-
const previousRecord = state.ledgerRecords.get(sid)
|
|
390
|
-
const revision = snapshots === null ? undefined : snapshots.get(sid)
|
|
391
|
-
if (!state.liveResyncPending.has(sid) && previousRecord !== undefined && previousRecord.needsUpgrade !== true && previousRecord.rebuildRequired === undefined && previousRecord.workspaceId === wsId && typeof previousRecord.lastRevision === 'string' && typeof revision === 'string' && revision === previousRecord.lastRevision) {
|
|
392
|
-
state.sync.sessionsSkippedByRevision += 1
|
|
393
|
-
applyLedgerRecord(previousRecord, 'ledger-reuse')
|
|
394
|
-
state.sessionSeq.set(sid, previousRecord.lastSeq)
|
|
395
|
-
state.sessionCount.add(sid)
|
|
396
|
-
markStatsChanged('scan')
|
|
397
|
-
return
|
|
398
|
-
}
|
|
399
|
-
state.sync.sessionsRead += 1
|
|
400
|
-
markStatsChanged('scan')
|
|
401
|
-
const snap = await ctx.sessionQuery.readSession(sid)
|
|
402
|
-
if (state.disposed || generation !== state.aggregationGeneration) return
|
|
403
|
-
if (snap && Array.isArray(snap.events)) {
|
|
404
|
-
// v1.0.7: incremental seed — the durable ledger doubles as a per-session
|
|
405
|
-
// cursor (cc-switch session_log_sync mtime+offset parity). An unchanged
|
|
406
|
-
// session applies its canonical record directly and never re-folds;
|
|
407
|
-
// a changed session seeds the previous record once, then folds only the
|
|
408
|
-
// new tail (previously every listed session was re-read and fully rebuilt).
|
|
409
|
-
const sequence = sequenceProfile(snap.events)
|
|
410
|
-
const currentLastSeq = sequence.lastSeq
|
|
411
|
-
const previous = state.ledgerRecords.get(sid)
|
|
412
|
-
const canFoldTail = previous !== undefined && previous.needsUpgrade !== true && previous.rebuildRequired === undefined && previous.workspaceId === wsId && !sequence.nonMonotonic && !sequence.hasInvalid && previous.lastSeq >= 0 && currentLastSeq > previous.lastSeq
|
|
413
|
-
if (canFoldTail) {
|
|
414
|
-
applyLedgerRecord(previous, 'ledger-reuse')
|
|
415
|
-
foldEvents(wsId, snap.events, previous.lastSeq, sid, 'scan')
|
|
416
|
-
} else {
|
|
417
|
-
// A changed revision with no new tail may still contain a replacement;
|
|
418
|
-
// rebuild from the complete read instead of trusting lastSeq alone.
|
|
419
|
-
foldEvents(wsId, snap.events, undefined, sid, 'scan')
|
|
420
|
-
}
|
|
421
|
-
const ledger = buildLedgerRecord({ id: sid, header: record.header, events: snap.events }, wsId, 'scan', revision, previous, !sequence.hasInvalid)
|
|
422
|
-
const canonical = ledger === null ? state.ledgerRecords.get(sid) : (canFoldTail ? storeLedgerRecord(ledger) : replaceLedgerRecord(ledger))
|
|
423
|
-
if (canonical === ledger) {
|
|
424
|
-
void persistLedgerRecord(ledger)
|
|
425
|
-
}
|
|
426
|
-
const observedLastSeq = state.sessionSeq.get(sid)
|
|
427
|
-
const nextLastSeq = Math.max(currentLastSeq, observedLastSeq === undefined ? -1 : observedLastSeq)
|
|
428
|
-
state.sessionSeq.set(sid, nextLastSeq)
|
|
429
|
-
state.sessionCount.add(sid)
|
|
430
|
-
if (observedLastSeq === undefined || observedLastSeq <= currentLastSeq) cancelLiveResync(sid)
|
|
431
|
-
else scheduleLiveResync(sid, wsId, generation)
|
|
432
|
-
}
|
|
433
|
-
} catch (err) {
|
|
434
|
-
if (generation !== state.aggregationGeneration) return
|
|
435
|
-
state.sync.sessionsFailed += 1
|
|
436
|
-
state.scan.failed += 1
|
|
437
|
-
noteSyncError('session-read-failed')
|
|
438
|
-
const saved = state.ledgerRecords.get(sid)
|
|
439
|
-
if (saved !== undefined) {
|
|
440
|
-
applyLedgerRecord(saved, 'ledger-recovery')
|
|
441
|
-
if (saved.turns.length > 0 || saved.usage.length > 0) state.sync.sessionsRestoredFromLedger += 1
|
|
442
|
-
state.sessionSeq.set(sid, -1)
|
|
443
|
-
state.sessionCount.add(sid)
|
|
444
|
-
} else {
|
|
445
|
-
state.sessionSeq.set(sid, -1)
|
|
446
|
-
}
|
|
447
|
-
} finally {
|
|
448
|
-
if (generation === state.aggregationGeneration) {
|
|
449
|
-
state.scan.scanned += 1
|
|
450
|
-
markStatsChanged('scan')
|
|
451
|
-
}
|
|
452
|
-
}
|
|
453
|
-
})
|
|
475
|
+
await scanOneSession(sid, record, wsId, generation, snapshots)
|
|
454
476
|
if (!(await safeContextTimeout(0))) {
|
|
455
477
|
state.scan.started = false
|
|
456
478
|
noteSyncError('baseline-yield-unavailable')
|
|
@@ -485,13 +507,132 @@ export function createSessionSync(host) {
|
|
|
485
507
|
if (state.reconcilePending) scheduleReconcileHint()
|
|
486
508
|
}
|
|
487
509
|
|
|
510
|
+
function scheduleWorkspaceSync() {
|
|
511
|
+
if (state.disposed) return
|
|
512
|
+
if (state.workspaceSyncTimer !== null) return
|
|
513
|
+
state.workspaceSyncTimer = setTimeout(() => {
|
|
514
|
+
state.workspaceSyncTimer = null
|
|
515
|
+
if (!state.disposed) void runWorkspaceSync()
|
|
516
|
+
}, WORKSPACE_SYNC_DEBOUNCE_MS)
|
|
517
|
+
if (state.workspaceSyncTimer && typeof state.workspaceSyncTimer.unref === 'function') state.workspaceSyncTimer.unref()
|
|
518
|
+
}
|
|
519
|
+
async function runWorkspaceSync() {
|
|
520
|
+
if (state.disposed) return
|
|
521
|
+
if (state.workspaceSyncInFlight) {
|
|
522
|
+
state.workspaceSyncPending = true
|
|
523
|
+
return
|
|
524
|
+
}
|
|
525
|
+
state.workspaceSyncInFlight = true
|
|
526
|
+
try {
|
|
527
|
+
await synchronizeWorkspaceRegistry()
|
|
528
|
+
} catch (err) {
|
|
529
|
+
console.error('[all-usage] workspace synchronize failed:', err)
|
|
530
|
+
noteSyncError('workspace-sync-failed')
|
|
531
|
+
} finally {
|
|
532
|
+
state.workspaceSyncInFlight = false
|
|
533
|
+
if (state.workspaceSyncPending) {
|
|
534
|
+
state.workspaceSyncPending = false
|
|
535
|
+
scheduleWorkspaceSync()
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
async function synchronizeWorkspaceRegistry() {
|
|
540
|
+
// The first baseline reads the registry with the latest list, so a probe
|
|
541
|
+
// arriving before it completes has nothing to add.
|
|
542
|
+
if (state.disposed || !state.scan.done) return
|
|
543
|
+
let workspaces
|
|
544
|
+
try {
|
|
545
|
+
workspaces = ctx.workspaceRegistry.list()
|
|
546
|
+
} catch (err) {
|
|
547
|
+
console.error('[all-usage] workspace list failed:', err)
|
|
548
|
+
noteSyncError('workspace-list-failed')
|
|
549
|
+
return
|
|
550
|
+
}
|
|
551
|
+
const next = buildWorkspaceSnapshot(workspaces)
|
|
552
|
+
const removedWs = new Set()
|
|
553
|
+
for (const id of state.wsMeta.keys()) if (!next.wsMeta.has(id)) removedWs.add(id)
|
|
554
|
+
const addedWs = new Set()
|
|
555
|
+
for (const id of next.wsMeta.keys()) if (!state.wsMeta.has(id)) addedWs.add(id)
|
|
556
|
+
// Reuse path: no membership change — metadata only, zero rescan.
|
|
557
|
+
if (removedWs.size === 0 && addedWs.size === 0) {
|
|
558
|
+
installWorkspaceSnapshot(next)
|
|
559
|
+
return
|
|
560
|
+
}
|
|
561
|
+
// Remove path: subtract every session that belonged to a deregistered workspace.
|
|
562
|
+
if (removedWs.size > 0) {
|
|
563
|
+
const removedSids = new Set()
|
|
564
|
+
for (const [sid, record] of state.ledgerRecords) {
|
|
565
|
+
if (record !== null && record !== undefined && typeof record.workspaceId === 'string' && removedWs.has(record.workspaceId)) removedSids.add(sid)
|
|
566
|
+
}
|
|
567
|
+
for (const [sid, id] of state.memberOf) if (removedWs.has(id)) removedSids.add(sid)
|
|
568
|
+
for (const sid of removedSids) {
|
|
569
|
+
if (typeof sid !== 'string' || sid === '') continue
|
|
570
|
+
host.aggregation.removeSession(sid)
|
|
571
|
+
state.ledgerRecords.delete(sid)
|
|
572
|
+
state.knownSessionIds.delete(sid)
|
|
573
|
+
state.sessionCount.delete(sid)
|
|
574
|
+
state.sessionSeq.delete(sid)
|
|
575
|
+
state.sessionModel.delete(sid)
|
|
576
|
+
state.sessionContextTimes.delete(sid)
|
|
577
|
+
state.memberOf.delete(sid)
|
|
578
|
+
state.liveResyncPending.delete(sid)
|
|
579
|
+
cancelLiveResync(sid)
|
|
580
|
+
}
|
|
581
|
+
for (const id of removedWs) {
|
|
582
|
+
state.perWorkspace.delete(id)
|
|
583
|
+
for (const day of state.byDay.values()) day.byWs.delete(id)
|
|
584
|
+
for (const day of state.byDayUtc.values()) day.byWs.delete(id)
|
|
585
|
+
}
|
|
586
|
+
}
|
|
587
|
+
installWorkspaceSnapshot(next)
|
|
588
|
+
// Add path: scan only the sessions that belong to newly registered workspaces.
|
|
589
|
+
if (addedWs.size === 0) return
|
|
590
|
+
let records = null
|
|
591
|
+
try {
|
|
592
|
+
records = await ctx.sessionQuery.listSessions()
|
|
593
|
+
} catch (err) {
|
|
594
|
+
console.error('[all-usage] session list failed:', err)
|
|
595
|
+
noteSyncError('session-list-failed')
|
|
596
|
+
}
|
|
597
|
+
if (!Array.isArray(records)) return
|
|
598
|
+
state.sync.sessionsTotal = records.length
|
|
599
|
+
markStatsChanged('scan')
|
|
600
|
+
let snapshots = null
|
|
601
|
+
if (sessionPersistence !== undefined && typeof sessionPersistence.listSnapshots === 'function') {
|
|
602
|
+
try {
|
|
603
|
+
const rows = await sessionPersistence.listSnapshots()
|
|
604
|
+
if (Array.isArray(rows)) {
|
|
605
|
+
snapshots = new Map()
|
|
606
|
+
for (const row of rows) {
|
|
607
|
+
const rid = row && row.header && typeof row.header.id === 'string' ? row.header.id : undefined
|
|
608
|
+
if (rid !== undefined && row && typeof row.revision === 'string') snapshots.set(rid, row.revision)
|
|
609
|
+
}
|
|
610
|
+
}
|
|
611
|
+
} catch (err) {
|
|
612
|
+
console.error('[all-usage] session persistence snapshots unavailable:', err)
|
|
613
|
+
markStatsChanged('scan')
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
for (const record of records) {
|
|
617
|
+
if (state.disposed) return
|
|
618
|
+
if (record === undefined || record === null || record.header === undefined) continue
|
|
619
|
+
const sid = record.header.id
|
|
620
|
+
const cwd = typeof record.header.cwd === 'string' ? record.header.cwd : ''
|
|
621
|
+
const wsId = workspaceForCwd(cwd)
|
|
622
|
+
if (sid === undefined || wsId === undefined) continue
|
|
623
|
+
if (!addedWs.has(wsId)) continue
|
|
624
|
+
state.knownSessionIds.add(sid)
|
|
625
|
+
scanOneSession(sid, record, wsId, state.aggregationGeneration, snapshots)
|
|
626
|
+
}
|
|
627
|
+
}
|
|
628
|
+
|
|
488
629
|
function sessionIdsFromRecords(records) {
|
|
489
630
|
const ids = new Set()
|
|
490
631
|
for (const record of records) {
|
|
491
632
|
if (record === undefined || record === null || record.header === undefined) continue
|
|
492
633
|
const sid = record.header.id
|
|
493
634
|
const cwd = typeof record.header.cwd === 'string' ? record.header.cwd : ''
|
|
494
|
-
const wsId =
|
|
635
|
+
const wsId = workspaceForCwd(cwd)
|
|
495
636
|
if (sid !== undefined && wsId !== undefined) ids.add(sid)
|
|
496
637
|
}
|
|
497
638
|
return ids
|
|
@@ -616,6 +757,18 @@ export function createSessionSync(host) {
|
|
|
616
757
|
ctx.on('session/disposed', () => {
|
|
617
758
|
if (!state.disposed) scheduleReconcileHint()
|
|
618
759
|
})
|
|
760
|
+
// Workspace registry probe: DSH emits domain/changed after every durable
|
|
761
|
+
// workspace-domain write (create/delete/rename/reorder/archive/attach/detach).
|
|
762
|
+
// On any such change we re-read workspaceRegistry.list() and, when membership
|
|
763
|
+
// changed, rescan only the affected workspaces — unchanged ones keep their
|
|
764
|
+
// computed aggregates and ledger untouched.
|
|
765
|
+
ctx.on('domain/changed', (change) => {
|
|
766
|
+
if (state.disposed) return
|
|
767
|
+
if (change === undefined || change === null) return
|
|
768
|
+
if (change.domain !== 'workspace') return
|
|
769
|
+
if (change.table !== 'workspaces' && change.table !== '') return
|
|
770
|
+
scheduleWorkspaceSync()
|
|
771
|
+
})
|
|
619
772
|
|
|
620
773
|
return {
|
|
621
774
|
foldEvent,
|
|
@@ -633,6 +786,8 @@ export function createSessionSync(host) {
|
|
|
633
786
|
scheduleNativeBaselineRetry,
|
|
634
787
|
scheduleBaselineRetry,
|
|
635
788
|
runBaseline,
|
|
789
|
+
synchronizeWorkspaceRegistry,
|
|
790
|
+
scheduleWorkspaceSync,
|
|
636
791
|
sessionIdsFromRecords,
|
|
637
792
|
reconcileSessions,
|
|
638
793
|
scheduleReconcileHint,
|
package/lib/usage-core.js
CHANGED
|
@@ -1,3 +1,10 @@
|
|
|
1
|
+
/** Canonical comparison key for Windows workspace paths. */
|
|
2
|
+
export function workspacePathKey(value) {
|
|
3
|
+
if (typeof value !== 'string') return ''
|
|
4
|
+
const normalized = value.trim().replaceAll('\\', '/').toLowerCase()
|
|
5
|
+
return normalized.length > 3 ? normalized.replace(/\/+$/, '') : normalized
|
|
6
|
+
}
|
|
7
|
+
|
|
1
8
|
const TOKEN_FIELDS = Object.freeze({
|
|
2
9
|
input: 'inputTokens',
|
|
3
10
|
output: 'outputTokens',
|