@kabmo-labs/kabmo 0.17.0 → 0.18.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.
- package/dist/client/index.html +1 -1
- package/dist/client/index.js +538 -457
- package/dist/client/static/js/index-hp75vsv9.css +1 -0
- package/dist/client/static/js/{index-rerjq5th.js → index-tc09dtca.js} +823 -814
- package/package.json +1 -1
- package/src/client/components/common/MarkdownRenderer.tsx +136 -89
- package/src/client/components/common/anchored-menu/index.test.tsx +141 -0
- package/src/client/components/common/anchored-menu/index.tsx +143 -0
- package/src/client/components/common/markdown-review/ReviewPopover.tsx +144 -0
- package/src/client/components/common/markdown-review/ReviewSummary.tsx +108 -0
- package/src/client/components/common/markdown-review/index.tsx +129 -0
- package/src/client/components/common/server-control/Panel.tsx +33 -23
- package/src/client/components/common/server-control/index.test.tsx +11 -5
- package/src/client/components/common/server-control/index.tsx +10 -8
- package/src/client/components/layout/session-sidebar/CategoryHeader.tsx +42 -21
- package/src/client/components/layout/session-sidebar/CategoryHeader.worktree.test.tsx +36 -17
- package/src/client/components/layout/session-sidebar/CategoryItem.tsx +8 -7
- package/src/client/components/layout/session-sidebar/about-modal/NotesDialog.tsx +94 -0
- package/src/client/components/layout/session-sidebar/about-modal/VersionLine.test.tsx +68 -0
- package/src/client/components/layout/session-sidebar/about-modal/VersionLine.tsx +36 -0
- package/src/client/components/layout/session-sidebar/about-modal/index.tsx +57 -34
- package/src/client/components/layout/session-sidebar/modern/WorkspaceHeader.tsx +28 -10
- package/src/client/components/layout/session-sidebar/modern/WorkspaceSection.tsx +7 -6
- package/src/client/components/layout/session-sidebar/modern/workspace-header.test.tsx +1 -1
- package/src/client/components/layout/update-popup/ReleaseNotes.tsx +8 -3
- package/src/client/components/layout/update-popup/index.tsx +5 -1
- package/src/client/components/mobile/mobile-right-sidebar/FullEditor.tsx +13 -15
- package/src/client/components/mobile/mobile-right-sidebar/Header.tsx +23 -1
- package/src/client/components/mobile/mobile-right-sidebar/MissingFileBanner.tsx +30 -0
- package/src/client/components/mobile/mobile-right-sidebar/PreviewScroller.tsx +18 -2
- package/src/client/components/mobile/mobile-session-sidebar/Item.tsx +22 -67
- package/src/client/components/mobile/mobile-session-sidebar/ItemMenu.tsx +110 -0
- package/src/client/components/settings/SettingsSidebarList.tsx +20 -0
- package/src/client/components/settings/categories/AgentSettings.tsx +23 -50
- package/src/client/components/settings/categories/CommandSettings.tsx +2 -2
- package/src/client/components/settings/categories/McpSettings.tsx +4 -21
- package/src/client/components/settings/categories/OmpSettings.tsx +147 -194
- package/src/client/components/settings/categories/SkillSettings.tsx +2 -2
- package/src/client/components/settings/categories/TokenUsageSettings.tsx +211 -229
- package/src/client/components/settings/categories/agent-settings/DetailPane.tsx +229 -237
- package/src/client/components/settings/categories/agent-settings/ModelPicker.tsx +71 -0
- package/src/client/components/settings/categories/agent-settings/SidebarList.tsx +9 -2
- package/src/client/components/settings/categories/agent-settings/levels.ts +38 -0
- package/src/client/components/settings/categories/behavior-settings/Editor.tsx +27 -7
- package/src/client/components/settings/categories/chat-settings/ToolRenderSection.tsx +23 -5
- package/src/client/components/settings/categories/command-settings/DetailPane.tsx +75 -33
- package/src/client/components/settings/categories/command-settings/SidebarList.tsx +7 -0
- package/src/client/components/settings/categories/mcp-settings/DetailPane.tsx +91 -76
- package/src/client/components/settings/categories/mcp-settings/EnvVarsSection.tsx +83 -0
- package/src/client/components/settings/categories/mcp-settings/ImportModal.tsx +26 -13
- package/src/client/components/settings/categories/mcp-settings/SidebarList.tsx +20 -0
- package/src/client/components/settings/categories/omp-settings/ConfigTabs.tsx +97 -36
- package/src/client/components/settings/categories/omp-settings/EngineHeader.tsx +151 -0
- package/src/client/components/settings/categories/omp-settings/ExtensionsPanel.tsx +68 -32
- package/src/client/components/settings/categories/omp-settings/OrderedChips.tsx +119 -0
- package/src/client/components/settings/categories/omp-settings/PresetBar.tsx +14 -7
- package/src/client/components/settings/categories/omp-settings/RoleEditor.tsx +15 -6
- package/src/client/components/settings/categories/omp-settings/RowEditor.tsx +165 -226
- package/src/client/components/settings/categories/omp-settings/types.ts +28 -0
- package/src/client/components/settings/categories/skill-settings/DetailHeader.tsx +35 -7
- package/src/client/components/settings/categories/skill-settings/DetailPane.tsx +34 -14
- package/src/client/components/settings/categories/skill-settings/SidebarList.tsx +21 -0
- package/src/client/components/settings/categories/skill-settings/pane.test.tsx +15 -6
- package/src/client/components/settings/categories/token-usage-settings/Breakdown.tsx +242 -102
- package/src/client/components/settings/categories/token-usage-settings/Chart.tsx +130 -56
- package/src/client/components/settings/categories/token-usage-settings/Controls.tsx +135 -0
- package/src/client/components/settings/categories/token-usage-settings/MetricsGrid.tsx +55 -33
- package/src/client/components/settings/categories/token-usage-settings/Provenance.tsx +59 -0
- package/src/client/components/settings/categories/token-usage-settings/panel.test.tsx +239 -0
- package/src/client/components/workspace/browser-panel/Screencast.test.ts +1 -0
- package/src/client/components/workspace/browser-panel/Screencast.tsx +17 -22
- package/src/client/components/workspace/browser-panel/TabStrip.test.tsx +158 -0
- package/src/client/components/workspace/browser-panel/TabStrip.tsx +90 -0
- package/src/client/components/workspace/browser-panel/index.tsx +50 -4
- package/src/client/components/workspace/browser-toolbar/index.tsx +41 -1
- package/src/client/components/workspace/chat-timeline/ThinkingSection.tsx +3 -1
- package/src/client/components/workspace/chat-timeline/ToolCallingSection.tsx +2 -0
- package/src/client/components/workspace/chat-timeline/block-chrome.test.tsx +13 -2
- package/src/client/components/workspace/chat-timeline/tool-renderers/panels/Bash.test.ts +88 -0
- package/src/client/components/workspace/chat-timeline/tool-renderers/panels/Bash.tsx +24 -1
- package/src/client/components/workspace/chat-timeline/tool-renderers/panels/Read.test.ts +34 -0
- package/src/client/components/workspace/chat-timeline/tool-renderers/panels/Read.tsx +5 -1
- package/src/client/components/workspace/chat-timeline/tool-renderers/shared/ArtifactChip.tsx +7 -6
- package/src/client/components/workspace/chat-timeline/tool-renderers/styles/Tui.test.tsx +237 -0
- package/src/client/components/workspace/chat-timeline/tool-renderers/styles/Tui.tsx +191 -0
- package/src/client/components/workspace/chat-timeline/tool-renderers/styles/styles.test.tsx +1 -1
- package/src/client/components/workspace/diff-panel/MergeDiffView.tsx +21 -7
- package/src/client/components/workspace/diff-panel/changes.test.ts +51 -0
- package/src/client/components/workspace/diff-panel/changes.ts +28 -12
- package/src/client/components/workspace/diff-panel/merge.test.ts +28 -0
- package/src/client/components/workspace/diff-panel/merge.ts +21 -1
- package/src/client/components/workspace/editor/Body.tsx +7 -0
- package/src/client/components/workspace/editor/FileDocument.tsx +15 -21
- package/src/client/components/workspace/editor/FilePane.tsx +12 -0
- package/src/client/components/workspace/editor/PreviewPane.tsx +70 -0
- package/src/client/components/workspace/editor/Toolbar.tsx +17 -1
- package/src/client/components/workspace/editor/index.tsx +25 -22
- package/src/client/components/workspace/editor/toolbar-clusters.test.ts +14 -0
- package/src/client/components/workspace/editor/toolbar-clusters.tsx +12 -86
- package/src/client/components/workspace/editor/toolbar-toggle.tsx +53 -0
- package/src/client/components/workspace/editor/toolbar-write-clusters.tsx +112 -0
- package/src/client/components/workspace/git-panel/commit-modal.test.ts +5 -3
- package/src/client/components/workspace/user-browser-panel/AddressBar.tsx +5 -0
- package/src/client/components/workspace/user-browser-panel/AnnotateBar.test.tsx +201 -0
- package/src/client/components/workspace/user-browser-panel/AnnotateBar.tsx +112 -0
- package/src/client/components/workspace/user-browser-panel/AnnotateLayer.test.tsx +225 -0
- package/src/client/components/workspace/user-browser-panel/AnnotateLayer.tsx +217 -0
- package/src/client/components/workspace/user-browser-panel/AnnotateTarget.tsx +99 -0
- package/src/client/components/workspace/user-browser-panel/Frame.tsx +30 -1
- package/src/client/components/workspace/user-browser-panel/index.tsx +81 -2
- package/src/client/data/agent-data/builtin.ts +0 -10
- package/src/client/data/agent-data/orchestrator.ts +0 -45
- package/src/client/data/agent-data/specialist.ts +0 -100
- package/src/client/data/mock/token-usage.ts +170 -120
- package/src/client/data/settings/omp-schema.json +33 -1
- package/src/client/hooks/browser/use-annotate.test.ts +143 -0
- package/src/client/hooks/browser/use-annotate.ts +98 -0
- package/src/client/hooks/browser/use-close-tab.test.ts +148 -0
- package/src/client/hooks/browser/use-close-tab.ts +67 -0
- package/src/client/hooks/browser/use-screencast.ts +13 -1
- package/src/client/hooks/chat/composer/browser-context.test.ts +117 -0
- package/src/client/hooks/chat/composer/browser-context.ts +40 -16
- package/src/client/hooks/chat/composer/items.test.ts +1 -1
- package/src/client/hooks/chat/composer/review-context.ts +38 -0
- package/src/client/hooks/chat/composer/use-draft.test.ts +132 -0
- package/src/client/hooks/chat/composer/use-draft.ts +31 -2
- package/src/client/hooks/chat/timeline/row-window.test.ts +15 -2
- package/src/client/hooks/editor/use-document-annotations.ts +124 -0
- package/src/client/hooks/editor/use-editor-panel-ui.ts +52 -0
- package/src/client/hooks/editor/use-file-review-mode.ts +35 -0
- package/src/client/hooks/editor/use-preview-review.ts +148 -0
- package/src/client/hooks/settings/agents.ts +149 -0
- package/src/client/hooks/settings/crud-list.test.ts +28 -6
- package/src/client/hooks/settings/crud-list.ts +96 -57
- package/src/client/hooks/settings/omp-config.ts +164 -0
- package/src/client/hooks/settings/useTokenUsage.ts +125 -0
- package/src/client/hooks/settings/write-feedback.test.ts +104 -0
- package/src/client/hooks/settings/write-feedback.ts +63 -0
- package/src/client/hooks/ui/markdown-hydration.ts +125 -0
- package/src/client/hooks/ui/updates/index.test.ts +100 -1
- package/src/client/hooks/ui/updates/index.ts +50 -0
- package/src/client/hooks/ui/updates/notes.test.ts +138 -0
- package/src/client/hooks/ui/updates/notes.ts +57 -0
- package/src/client/lib/browser/element-at.test.ts +229 -0
- package/src/client/lib/browser/element-at.ts +139 -0
- package/src/client/lib/review/client.ts +73 -0
- package/src/client/lib/router/search-params.ts +42 -20
- package/src/client/tailwind.css +65 -0
- package/src/server/lib/btw/lifecycle.server.ts +2 -2
- package/src/server/lib/db/schema.ts +7 -0
- package/src/server/lib/db/seed-terminal.test.ts +4 -0
- package/src/server/lib/omp/config/agent-definitions.test.ts +273 -0
- package/src/server/lib/omp/config/agents.ts +231 -61
- package/src/server/lib/omp/config/definitions.test.ts +9 -105
- package/src/server/lib/omp/config/extensions.ts +16 -7
- package/src/server/lib/omp/config/omp-config-files.test.ts +27 -0
- package/src/server/lib/omp/rpc/constants.test.ts +11 -0
- package/src/server/lib/omp/rpc/constants.ts +15 -0
- package/src/server/lib/omp/rpc/process.ts +11 -14
- package/src/server/lib/omp/rpc/session-commands.ts +6 -3
- package/src/server/lib/omp/rpc/utility-agent-dir.test.ts +134 -0
- package/src/server/lib/omp/rpc/utility-agent-dir.ts +138 -0
- package/src/server/lib/omp/rpc/utility.ts +12 -0
- package/src/server/lib/review/schema.server.ts +45 -0
- package/src/server/lib/review/store.server.ts +138 -0
- package/src/server/lib/terminal/attach-replay.test.ts +132 -0
- package/src/server/lib/terminal/output.test.ts +166 -0
- package/src/server/lib/terminal/output.ts +104 -0
- package/src/server/lib/terminal/runtime.server.ts +5 -0
- package/src/server/lib/terminal/send-result.test.ts +33 -0
- package/src/server/lib/terminal/send-result.ts +32 -0
- package/src/server/lib/terminal/session.server.ts +45 -11
- package/src/server/lib/terminal/store-liveness.test.ts +4 -0
- package/src/server/lib/updates/active-notes.test.ts +149 -0
- package/src/server/lib/updates/active-notes.ts +75 -0
- package/src/server/lib/updates/changelog-file.ts +42 -11
- package/src/server/lib/updates/changelog.test.ts +15 -1
- package/src/server/lib/updates/omp.ts +42 -15
- package/src/server/lib/updates/release-url.ts +27 -1
- package/src/server/lib/usage/index-parse.test.ts +200 -0
- package/src/server/lib/usage/index-parse.ts +178 -0
- package/src/server/lib/usage/index-query.server.ts +248 -0
- package/src/server/lib/usage/index-scan.server.ts +343 -0
- package/src/server/lib/usage/index-schema.server.ts +82 -0
- package/src/server/lib/usage/index.test.ts +234 -0
- package/src/server/lib/usage/providers.server.ts +4 -53
- package/src/server/routes/browser/index.ts +3 -0
- package/src/server/routes/browser/stream.ts +31 -2
- package/src/server/routes/browser/tabs.test.ts +94 -0
- package/src/server/routes/browser/tabs.ts +85 -0
- package/src/server/routes/index.ts +2 -0
- package/src/server/routes/review/bindings.ts +11 -0
- package/src/server/routes/review/index.ts +127 -0
- package/src/server/routes/review/routes.test.ts +191 -0
- package/src/server/routes/settings/agents.test.ts +180 -0
- package/src/server/routes/settings/agents.ts +95 -102
- package/src/server/routes/settings/mcp.test.ts +135 -0
- package/src/server/routes/settings/mcp.ts +14 -6
- package/src/server/routes/settings/settings-store-routes.test.ts +6 -113
- package/src/server/routes/telemetry/tokens.test.ts +145 -0
- package/src/server/routes/telemetry/tokens.ts +70 -149
- package/src/server/routes/terminal/ws.ts +6 -5
- package/src/server/routes/updates/index.ts +2 -0
- package/src/server/routes/updates/notes.ts +34 -0
- package/src/server/routes/updates/routes.test.ts +49 -0
- package/src/shared/lib/browser/annotate.test.ts +283 -0
- package/src/shared/lib/browser/annotate.ts +231 -0
- package/src/shared/lib/browser/browser-viewer.test.ts +26 -4
- package/src/shared/lib/browser/frame-gate.test.ts +91 -0
- package/src/shared/lib/browser/frame-gate.ts +69 -0
- package/src/shared/lib/browser/frame-params.test.ts +43 -0
- package/src/shared/lib/browser/frame-params.ts +60 -0
- package/src/shared/lib/browser/frame-pipeline.test.ts +132 -0
- package/src/shared/lib/browser/frame-pipeline.ts +80 -0
- package/src/shared/lib/browser/page-context.ts +60 -4
- package/src/shared/lib/browser/snapshot.test.ts +115 -0
- package/src/shared/lib/browser/snapshot.ts +112 -0
- package/src/shared/lib/browser/tab-close.test.ts +74 -0
- package/src/shared/lib/browser/tab-close.ts +77 -0
- package/src/shared/lib/browser/viewer.ts +45 -26
- package/src/shared/lib/chat/timeline/block-chrome.ts +19 -0
- package/src/shared/lib/chat/timeline/tool-render-mode.ts +17 -4
- package/src/shared/lib/chat/tool/artifact.ts +55 -20
- package/src/shared/lib/chat/tool/bash-facts.ts +96 -0
- package/src/shared/lib/chat/tool/minimized.test.ts +98 -0
- package/src/shared/lib/chat/tool/minimized.ts +64 -0
- package/src/shared/lib/chat/tool/summary.test.ts +28 -8
- package/src/shared/lib/chat/tool/summary.ts +3 -32
- package/src/shared/lib/markdown/blocks/anchor.ts +63 -0
- package/src/shared/lib/markdown/blocks/blocks.test.ts +141 -0
- package/src/shared/lib/markdown/blocks/renderer.ts +120 -0
- package/src/shared/lib/markdown/blocks/scan.ts +100 -0
- package/src/shared/lib/markdown/blocks/types.ts +62 -0
- package/src/shared/lib/markdown/marked.ts +58 -147
- package/src/shared/lib/markdown/math-extensions.ts +168 -0
- package/src/shared/lib/markdown/review/prompt.ts +77 -0
- package/src/shared/lib/markdown/review/reconcile.ts +55 -0
- package/src/shared/lib/markdown/review/review.test.ts +96 -0
- package/src/shared/lib/markdown/xml-sections.test.ts +140 -0
- package/src/shared/lib/markdown/xml-sections.ts +139 -0
- package/src/shared/lib/models/provider/label.ts +57 -0
- package/src/shared/lib/omp/config/agent-file.test.ts +54 -0
- package/src/shared/lib/omp/config/agent-file.ts +43 -0
- package/src/shared/lib/omp/config/row-value.test.ts +95 -0
- package/src/shared/lib/omp/config/row-value.ts +97 -0
- package/src/shared/lib/omp/config/schema.test.ts +31 -0
- package/src/shared/lib/omp/config/schema.ts +6 -0
- package/src/shared/lib/omp/rpc/frame.test.ts +48 -47
- package/src/shared/lib/omp/rpc/frame.ts +49 -40
- package/src/shared/lib/ui/menu-anchor.test.ts +69 -0
- package/src/shared/lib/ui/menu-anchor.ts +89 -0
- package/src/shared/lib/usage/breakdown.test.ts +197 -0
- package/src/shared/lib/usage/breakdown.ts +241 -0
- package/src/shared/lib/usage/range.test.ts +204 -0
- package/src/shared/lib/usage/range.ts +240 -0
- package/src/shared/lib/usage/view.test.ts +85 -0
- package/src/shared/lib/usage/view.ts +74 -0
- package/src/shared/types/browser.ts +78 -0
- package/src/shared/types/index.ts +1 -0
- package/src/shared/types/settings/agent.ts +28 -6
- package/src/shared/types/settings/state.ts +4 -3
- package/src/shared/types/settings/write.ts +6 -0
- package/src/shared/types/tokenUsage.ts +128 -21
- package/src/shared/types/updates.ts +20 -0
- package/dist/client/static/js/index-3ve31rzx.css +0 -1
- package/src/server/lib/omp/session/usage/aggregate-shaping.test.ts +0 -149
- package/src/server/lib/omp/session/usage/aggregate.test.ts +0 -243
- package/src/server/lib/omp/session/usage/aggregate.ts +0 -330
- package/src/server/lib/omp/session/usage/shaping.ts +0 -130
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* SPDX-License-Identifier: MIT
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* The Token Usage breakdown and chart view models.
|
|
8
|
+
*
|
|
9
|
+
* Everything here re-folds data the client ALREADY holds: the payload carries
|
|
10
|
+
* the period's daily rows, so the tab switch costs no request, and the chart's
|
|
11
|
+
* bucket width follows the period's own length (`granularityFor`).
|
|
12
|
+
*
|
|
13
|
+
* Two rules that were bugs before:
|
|
14
|
+
*
|
|
15
|
+
* - a provider is part of a row's identity, so one model id served by two
|
|
16
|
+
* accounts is two subtrees rather than one merged cost;
|
|
17
|
+
* - an unpriced turn is counted per RECORD (tokens, no reported cost), never
|
|
18
|
+
* folded into a zero cost that reads as "free".
|
|
19
|
+
*
|
|
20
|
+
* There is no per-day/per-week figure anywhere: a period is a period, and every
|
|
21
|
+
* row is that period's total.
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
import type {
|
|
25
|
+
BreakdownTab,
|
|
26
|
+
BucketGranularity,
|
|
27
|
+
ChartSeriesPoint,
|
|
28
|
+
UsageDayRow,
|
|
29
|
+
UsageProjectRow,
|
|
30
|
+
UsageProviderRow,
|
|
31
|
+
UsageTotals,
|
|
32
|
+
} from '@/shared/types';
|
|
33
|
+
import { bucketKey, bucketLabel, compareDayKeys, daysInWindow, type DayWindow } from '@/shared/lib/usage/range';
|
|
34
|
+
import { cacheHitLabel } from '@/shared/lib/usage/view';
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Chart points for one granularity, plus the per-provider split the stacked
|
|
38
|
+
* area draws.
|
|
39
|
+
*
|
|
40
|
+
* Buckets are the union of the days present — an empty day inside the range is
|
|
41
|
+
* inserted so the line does not draw a straight diagonal over a gap.
|
|
42
|
+
*/
|
|
43
|
+
export interface CadenceBucket {
|
|
44
|
+
key: string;
|
|
45
|
+
label: string;
|
|
46
|
+
cost: number;
|
|
47
|
+
tokens: number;
|
|
48
|
+
byProvider: Record<string, { cost: number; tokens: number }>;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function bucketDays(days: readonly UsageDayRow[], granularity: BucketGranularity): CadenceBucket[] {
|
|
52
|
+
const buckets = new Map<string, CadenceBucket>();
|
|
53
|
+
for (const day of days) {
|
|
54
|
+
const key = bucketKey(day.day, granularity);
|
|
55
|
+
let bucket = buckets.get(key);
|
|
56
|
+
if (!bucket) {
|
|
57
|
+
bucket = { key, label: bucketLabel(key, granularity), cost: 0, tokens: 0, byProvider: {} };
|
|
58
|
+
buckets.set(key, bucket);
|
|
59
|
+
}
|
|
60
|
+
bucket.cost += day.cost;
|
|
61
|
+
bucket.tokens += day.tokens;
|
|
62
|
+
for (const [provider, split] of Object.entries(day.providers)) {
|
|
63
|
+
const current = bucket.byProvider[provider] ?? { cost: 0, tokens: 0 };
|
|
64
|
+
current.cost += split.cost;
|
|
65
|
+
current.tokens += split.tokens;
|
|
66
|
+
bucket.byProvider[provider] = current;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
return [...buckets.values()].sort((a, b) => compareDayKeys(a.key, b.key));
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Flat series for the single-line chart. */
|
|
73
|
+
export function chartSeries(days: readonly UsageDayRow[], granularity: BucketGranularity): ChartSeriesPoint[] {
|
|
74
|
+
return bucketDays(days, granularity).map((bucket) => ({
|
|
75
|
+
label: bucket.label,
|
|
76
|
+
cost: bucket.cost,
|
|
77
|
+
tokens: bucket.tokens,
|
|
78
|
+
}));
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** One row of the breakdown table. */
|
|
82
|
+
export interface BreakdownViewRow {
|
|
83
|
+
/** Stable key (provider slug, model id, day bucket, project path). */
|
|
84
|
+
key: string;
|
|
85
|
+
label: string;
|
|
86
|
+
/** Provider slug for the icon plate; absent on day rows. */
|
|
87
|
+
provider?: string;
|
|
88
|
+
/** Model id, when the row belongs to a provider subtree. */
|
|
89
|
+
model?: string;
|
|
90
|
+
/** `group` rows are provider headers in the two-level tree. */
|
|
91
|
+
kind: 'row' | 'group';
|
|
92
|
+
cost: number;
|
|
93
|
+
tokens: number;
|
|
94
|
+
records: number;
|
|
95
|
+
cacheHit: string;
|
|
96
|
+
/** Share of the period cost, 0..100. */
|
|
97
|
+
sharePercent: number;
|
|
98
|
+
/** Share of the parent provider's cost, for model rows under a group. */
|
|
99
|
+
shareOfParentPercent?: number;
|
|
100
|
+
depth: 0 | 1;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function shareOf(part: number, whole: number): number {
|
|
104
|
+
return whole > 0 ? Math.round((part / whole) * 1000) / 10 : 0;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* The Model tab's two-level tree: each provider, then its models.
|
|
109
|
+
*
|
|
110
|
+
* The provider row is what the panel was missing — `message.provider` was
|
|
111
|
+
* recorded on every usage entry, yet the breakdown keyed on model alone, so
|
|
112
|
+
* two accounts serving `deepseek-v4-1-flash` reported one merged cost
|
|
113
|
+
* ($1 673.86 measured) instead of $1 619.43 + $54.43.
|
|
114
|
+
*/
|
|
115
|
+
export function providerModelRows(providers: readonly UsageProviderRow[], totalCost: number): BreakdownViewRow[] {
|
|
116
|
+
const rows: BreakdownViewRow[] = [];
|
|
117
|
+
for (const provider of providers) {
|
|
118
|
+
rows.push({
|
|
119
|
+
key: `p:${provider.id}`,
|
|
120
|
+
label: provider.name,
|
|
121
|
+
provider: provider.id,
|
|
122
|
+
kind: 'group',
|
|
123
|
+
cost: provider.cost,
|
|
124
|
+
tokens: provider.tokens,
|
|
125
|
+
records: provider.records,
|
|
126
|
+
cacheHit: cacheHitLabel(provider),
|
|
127
|
+
sharePercent: shareOf(provider.cost, totalCost),
|
|
128
|
+
depth: 0,
|
|
129
|
+
});
|
|
130
|
+
for (const model of provider.models) {
|
|
131
|
+
rows.push({
|
|
132
|
+
key: `m:${provider.id}:${model.model}`,
|
|
133
|
+
label: model.model || 'unknown',
|
|
134
|
+
provider: provider.id,
|
|
135
|
+
model: model.model,
|
|
136
|
+
kind: 'row',
|
|
137
|
+
cost: model.cost,
|
|
138
|
+
tokens: model.tokens,
|
|
139
|
+
records: model.records,
|
|
140
|
+
cacheHit: cacheHitLabel(model),
|
|
141
|
+
sharePercent: shareOf(model.cost, totalCost),
|
|
142
|
+
shareOfParentPercent: shareOf(model.cost, provider.cost),
|
|
143
|
+
depth: 1,
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
return rows;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* Time rows for the whole period, oldest first.
|
|
152
|
+
*
|
|
153
|
+
* `window` is the period's own day range: the payload only carries days that
|
|
154
|
+
* saw usage, so without it a quiet Tuesday simply vanished from the table and
|
|
155
|
+
* the list stopped matching the period it claims to describe. A bucket that
|
|
156
|
+
* never carried a record is listed with zeros rather than omitted.
|
|
157
|
+
*/
|
|
158
|
+
export function dayRows(
|
|
159
|
+
days: readonly UsageDayRow[],
|
|
160
|
+
granularity: BucketGranularity,
|
|
161
|
+
totalCost: number,
|
|
162
|
+
window: DayWindow | null,
|
|
163
|
+
): BreakdownViewRow[] {
|
|
164
|
+
const buckets = bucketDays(days, granularity);
|
|
165
|
+
// One pass collects the counters `bucketDays` does not carry (turns and the
|
|
166
|
+
// input split), so no bucket re-scans the day list.
|
|
167
|
+
const extra = new Map<string, { records: number; cacheRead: number; input: number }>();
|
|
168
|
+
for (const day of days) {
|
|
169
|
+
const key = bucketKey(day.day, granularity);
|
|
170
|
+
const current = extra.get(key) ?? { records: 0, cacheRead: 0, input: 0 };
|
|
171
|
+
current.records += day.records;
|
|
172
|
+
current.cacheRead += day.cacheRead;
|
|
173
|
+
current.input += day.input;
|
|
174
|
+
extra.set(key, current);
|
|
175
|
+
}
|
|
176
|
+
// Fill every bucket the window covers, so the table lists the period rather
|
|
177
|
+
// than only the days that happened to carry usage.
|
|
178
|
+
const known = new Set(buckets.map((bucket) => bucket.key));
|
|
179
|
+
for (const day of window ? daysInWindow(window) : []) {
|
|
180
|
+
const key = bucketKey(day, granularity);
|
|
181
|
+
if (known.has(key)) continue;
|
|
182
|
+
known.add(key);
|
|
183
|
+
buckets.push({ key, label: bucketLabel(key, granularity), cost: 0, tokens: 0, byProvider: {} });
|
|
184
|
+
}
|
|
185
|
+
return [...buckets]
|
|
186
|
+
.sort((a, b) => compareDayKeys(a.key, b.key))
|
|
187
|
+
.map((bucket) => {
|
|
188
|
+
const counts = extra.get(bucket.key) ?? { records: 0, cacheRead: 0, input: 0 };
|
|
189
|
+
return {
|
|
190
|
+
key: `d:${bucket.key}`,
|
|
191
|
+
label: bucket.label,
|
|
192
|
+
kind: 'row' as const,
|
|
193
|
+
cost: bucket.cost,
|
|
194
|
+
tokens: bucket.tokens,
|
|
195
|
+
records: counts.records,
|
|
196
|
+
cacheHit: cacheHitLabel(counts),
|
|
197
|
+
sharePercent: shareOf(bucket.cost, totalCost),
|
|
198
|
+
depth: 0 as const,
|
|
199
|
+
};
|
|
200
|
+
});
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/** Project rows, ordered by cost. */
|
|
204
|
+
export function projectRows(projects: readonly UsageProjectRow[], totalCost: number): BreakdownViewRow[] {
|
|
205
|
+
return [...projects]
|
|
206
|
+
.sort((a, b) => b.cost - a.cost)
|
|
207
|
+
.map((project) => ({
|
|
208
|
+
key: `j:${project.project}`,
|
|
209
|
+
label: project.project,
|
|
210
|
+
kind: 'row' as const,
|
|
211
|
+
cost: project.cost,
|
|
212
|
+
tokens: project.tokens,
|
|
213
|
+
records: project.records,
|
|
214
|
+
cacheHit: cacheHitLabel(project),
|
|
215
|
+
sharePercent: shareOf(project.cost, totalCost),
|
|
216
|
+
depth: 0 as const,
|
|
217
|
+
}));
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/** The rows the active tab shows, with the provider tab reusing the tree. */
|
|
221
|
+
export function breakdownRows(
|
|
222
|
+
tab: BreakdownTab,
|
|
223
|
+
payload: {
|
|
224
|
+
totals: UsageTotals;
|
|
225
|
+
providers: readonly UsageProviderRow[];
|
|
226
|
+
days: readonly UsageDayRow[];
|
|
227
|
+
projects: readonly UsageProjectRow[];
|
|
228
|
+
},
|
|
229
|
+
granularity: BucketGranularity,
|
|
230
|
+
window: DayWindow | null,
|
|
231
|
+
): BreakdownViewRow[] {
|
|
232
|
+
switch (tab) {
|
|
233
|
+
case 'provider':
|
|
234
|
+
case 'model':
|
|
235
|
+
return providerModelRows(payload.providers, payload.totals.cost);
|
|
236
|
+
case 'day':
|
|
237
|
+
return dayRows(payload.days, granularity, payload.totals.cost, window);
|
|
238
|
+
case 'project':
|
|
239
|
+
return projectRows(payload.projects, payload.totals.cost);
|
|
240
|
+
}
|
|
241
|
+
}
|
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* SPDX-License-Identifier: MIT
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Day arithmetic for the Token Usage surface.
|
|
8
|
+
*
|
|
9
|
+
* The server decides which rows a period includes and the client buckets those
|
|
10
|
+
* days for the cadence switch, so both sides call THIS module. The cases worth
|
|
11
|
+
* pinning are the ones that made the panel disagree with itself: a UTC-derived
|
|
12
|
+
* day beside a local "Today", a week starting on Sunday, and "last 7 days"
|
|
13
|
+
* silently meaning 7 × 24 h instead of 7 calendar days.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import { describe, expect, test } from 'bun:test';
|
|
17
|
+
|
|
18
|
+
import {
|
|
19
|
+
bucketKey,
|
|
20
|
+
bucketLabel,
|
|
21
|
+
compareDayKeys,
|
|
22
|
+
dayKeyOfTimestamp,
|
|
23
|
+
dayLabel,
|
|
24
|
+
dayRangeLabel,
|
|
25
|
+
dayWindow,
|
|
26
|
+
daysInWindow,
|
|
27
|
+
granularityFor,
|
|
28
|
+
localDayKey,
|
|
29
|
+
spanOfDays,
|
|
30
|
+
parseIsoDay,
|
|
31
|
+
timeRangeOptions,
|
|
32
|
+
} from '@/shared/lib/usage/range';
|
|
33
|
+
|
|
34
|
+
/** A local-time instant, so the cases read the same in every timezone. */
|
|
35
|
+
const at = (year: number, month: number, day: number, hour = 12) => new Date(year, month - 1, day, hour, 0, 0).getTime();
|
|
36
|
+
const NOW = at(2026, 11, 3);
|
|
37
|
+
|
|
38
|
+
describe('localDayKey', () => {
|
|
39
|
+
test('is the local calendar day, not the UTC prefix', () => {
|
|
40
|
+
// 00:30 local is the previous UTC day west of UTC and the same day east of
|
|
41
|
+
// it; the assertion that matters is that it equals the LOCAL date.
|
|
42
|
+
const instant = at(2026, 11, 3, 0);
|
|
43
|
+
expect(localDayKey(instant)).toBe('2026-11-03');
|
|
44
|
+
expect(localDayKey(at(2026, 11, 3, 23))).toBe('2026-11-03');
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
test('an ISO timestamp with no timezone parses as local', () => {
|
|
48
|
+
expect(dayKeyOfTimestamp(new Date(2026, 10, 3, 1, 5).toISOString())).toBe('2026-11-03');
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
test('a missing or unparseable timestamp yields an empty key', () => {
|
|
52
|
+
expect(dayKeyOfTimestamp(undefined)).toBe('');
|
|
53
|
+
expect(dayKeyOfTimestamp('')).toBe('');
|
|
54
|
+
expect(dayKeyOfTimestamp('not-a-date')).toBe('');
|
|
55
|
+
});
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
describe('parseIsoDay', () => {
|
|
59
|
+
test('accepts real calendar days only', () => {
|
|
60
|
+
expect(parseIsoDay('2026-02-28')).toBe('2026-02-28');
|
|
61
|
+
expect(parseIsoDay('2026-02-30')).toBeNull();
|
|
62
|
+
expect(parseIsoDay('2026-13-01')).toBeNull();
|
|
63
|
+
expect(parseIsoDay('3/11/2026')).toBeNull();
|
|
64
|
+
expect(parseIsoDay('')).toBeNull();
|
|
65
|
+
});
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
describe('dayWindow', () => {
|
|
69
|
+
test('today is one local calendar day', () => {
|
|
70
|
+
expect(dayWindow('today', NOW)).toEqual({ from: '2026-11-03', to: '2026-11-03' });
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
test('last 7 days covers seven calendar days including today', () => {
|
|
74
|
+
expect(dayWindow('7d', NOW)).toEqual({ from: '2026-10-28', to: '2026-11-03' });
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
test('last 30 and 90 days scale the same way', () => {
|
|
78
|
+
expect(dayWindow('30d', NOW)).toEqual({ from: '2026-10-05', to: '2026-11-03' });
|
|
79
|
+
expect(dayWindow('90d', NOW)?.from).toBe('2026-08-06');
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
test('all time is unbounded', () => {
|
|
83
|
+
expect(dayWindow('all', NOW)).toBeNull();
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
test('a valid custom pair is inclusive, and an invalid one falls back to 30d', () => {
|
|
87
|
+
expect(dayWindow('custom', NOW, { from: '2026-01-02', to: '2026-01-09' })).toEqual({
|
|
88
|
+
from: '2026-01-02',
|
|
89
|
+
to: '2026-01-09',
|
|
90
|
+
});
|
|
91
|
+
expect(dayWindow('custom', NOW, { from: '2026-01-09', to: '2026-01-02' })).toEqual({
|
|
92
|
+
from: '2026-10-05',
|
|
93
|
+
to: '2026-11-03',
|
|
94
|
+
});
|
|
95
|
+
expect(dayWindow('custom', NOW, { from: 'nope', to: '2026-01-02' })).toEqual({
|
|
96
|
+
from: '2026-10-05',
|
|
97
|
+
to: '2026-11-03',
|
|
98
|
+
});
|
|
99
|
+
});
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
describe('labels', () => {
|
|
103
|
+
test('a day label is short and a single-day range names its year', () => {
|
|
104
|
+
expect(dayLabel('2026-11-03')).toBe('Nov 3');
|
|
105
|
+
expect(dayRangeLabel('2026-11-03', '2026-11-03', NOW)).toBe('Nov 3, 2026');
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
test('a multi-day range prints both sides, omitting this year on the left', () => {
|
|
109
|
+
expect(dayRangeLabel('2026-10-05', '2026-11-03', NOW)).toBe('Oct 5 – Nov 3, 2026');
|
|
110
|
+
expect(dayRangeLabel('2025-12-01', '2026-01-02', NOW)).toBe('Dec 1, 2025 – Jan 2, 2026');
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
test('the picker lists one period per span, each with the dates it covers', () => {
|
|
114
|
+
const options = timeRangeOptions(NOW);
|
|
115
|
+
expect(options.map((option) => option.id)).toEqual(['today', '7d', '30d', '90d', 'all', 'custom']);
|
|
116
|
+
// Day/Week/Month ARE the spans: there is no separate cadence control.
|
|
117
|
+
expect(options.map((option) => option.label)).toEqual(['Day', 'Week', 'Month', '90 days', 'All time', 'Custom…']);
|
|
118
|
+
expect(options[0].dateRange).toBe('Nov 3, 2026');
|
|
119
|
+
expect(options[1].dateRange).toBe('Oct 28 – Nov 3, 2026');
|
|
120
|
+
expect(options[2].dateRange).toBe('Oct 5 – Nov 3, 2026');
|
|
121
|
+
expect(options[4].dateRange).toBe('All time');
|
|
122
|
+
});
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
describe('daysInWindow', () => {
|
|
126
|
+
test('enumerates every calendar day of the span, oldest first', () => {
|
|
127
|
+
expect(daysInWindow({ from: '2026-10-28', to: '2026-11-03' })).toHaveLength(7);
|
|
128
|
+
expect(daysInWindow({ from: '2026-10-28', to: '2026-11-03' })[0]).toBe('2026-10-28');
|
|
129
|
+
expect(daysInWindow({ from: '2026-10-28', to: '2026-11-03' }).at(-1)).toBe('2026-11-03');
|
|
130
|
+
// One day, not zero and not two.
|
|
131
|
+
expect(daysInWindow({ from: '2026-11-03', to: '2026-11-03' })).toEqual(['2026-11-03']);
|
|
132
|
+
});
|
|
133
|
+
|
|
134
|
+
test('a month crosses the month boundary without losing a day', () => {
|
|
135
|
+
const days = daysInWindow({ from: '2026-10-05', to: '2026-11-03' });
|
|
136
|
+
expect(days).toHaveLength(30);
|
|
137
|
+
expect(days).toContain('2026-10-31');
|
|
138
|
+
expect(days).toContain('2026-11-01');
|
|
139
|
+
});
|
|
140
|
+
|
|
141
|
+
test('an inverted or unparseable window yields no days, and a cap bounds it', () => {
|
|
142
|
+
expect(daysInWindow({ from: '2026-11-03', to: '2026-10-01' })).toEqual([]);
|
|
143
|
+
expect(daysInWindow({ from: 'nope', to: '2026-11-03' })).toEqual([]);
|
|
144
|
+
expect(daysInWindow({ from: '2026-01-01', to: '2026-12-31' }, 10)).toHaveLength(10);
|
|
145
|
+
});
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
describe('spanOfDays', () => {
|
|
149
|
+
test('is the first and last recorded day, in either input order', () => {
|
|
150
|
+
expect(spanOfDays(['2026-11-03', '2026-06-24', '2026-09-01'])).toEqual({ from: '2026-06-24', to: '2026-11-03' });
|
|
151
|
+
});
|
|
152
|
+
|
|
153
|
+
test('empty and undated input yield no span', () => {
|
|
154
|
+
expect(spanOfDays([])).toBeNull();
|
|
155
|
+
expect(spanOfDays(['', ''])).toBeNull();
|
|
156
|
+
});
|
|
157
|
+
});
|
|
158
|
+
|
|
159
|
+
describe('granularityFor', () => {
|
|
160
|
+
test('follows the period length, so the chart stays readable', () => {
|
|
161
|
+
expect(granularityFor('today')).toBe('day');
|
|
162
|
+
expect(granularityFor('7d')).toBe('day');
|
|
163
|
+
expect(granularityFor('30d')).toBe('day');
|
|
164
|
+
expect(granularityFor('90d')).toBe('week');
|
|
165
|
+
expect(granularityFor('all')).toBe('month');
|
|
166
|
+
});
|
|
167
|
+
|
|
168
|
+
test('a custom span picks its width from the span itself', () => {
|
|
169
|
+
expect(granularityFor('custom', { from: '2026-11-01', to: '2026-11-10' })).toBe('day');
|
|
170
|
+
expect(granularityFor('custom', { from: '2026-09-01', to: '2026-11-03' })).toBe('week');
|
|
171
|
+
expect(granularityFor('custom', { from: '2025-01-01', to: '2026-11-03' })).toBe('month');
|
|
172
|
+
// An incomplete custom pair is not a span yet.
|
|
173
|
+
expect(granularityFor('custom', { from: 'nope', to: '2026-11-03' })).toBe('day');
|
|
174
|
+
});
|
|
175
|
+
});
|
|
176
|
+
|
|
177
|
+
describe('bucketKey', () => {
|
|
178
|
+
test('day keeps the day', () => {
|
|
179
|
+
expect(bucketKey('2026-11-03', 'day')).toBe('2026-11-03');
|
|
180
|
+
});
|
|
181
|
+
|
|
182
|
+
test('week aligns to Monday', () => {
|
|
183
|
+
// 2026-11-03 is a Tuesday; its Monday is 2026-11-02.
|
|
184
|
+
expect(new Date(2026, 10, 3).getDay()).toBe(2);
|
|
185
|
+
expect(bucketKey('2026-11-03', 'week')).toBe('2026-11-02');
|
|
186
|
+
expect(bucketKey('2026-11-02', 'week')).toBe('2026-11-02');
|
|
187
|
+
// A Sunday belongs to the week that STARTED six days earlier.
|
|
188
|
+
expect(bucketKey('2026-11-08', 'week')).toBe('2026-11-02');
|
|
189
|
+
});
|
|
190
|
+
|
|
191
|
+
test('month keeps the year and month', () => {
|
|
192
|
+
expect(bucketKey('2026-11-03', 'month')).toBe('2026-11');
|
|
193
|
+
});
|
|
194
|
+
|
|
195
|
+
test('bucket labels follow the granularity', () => {
|
|
196
|
+
expect(bucketLabel('2026-11', 'month')).toBe('Nov');
|
|
197
|
+
expect(bucketLabel('2025-11', 'month')).toBe('Nov 2025');
|
|
198
|
+
expect(bucketLabel('2026-11-02', 'week')).toBe('Nov 2');
|
|
199
|
+
});
|
|
200
|
+
|
|
201
|
+
test('day keys sort lexicographically', () => {
|
|
202
|
+
expect(['2026-11-03', '2026-10-05'].sort(compareDayKeys)).toEqual(['2026-10-05', '2026-11-03']);
|
|
203
|
+
});
|
|
204
|
+
});
|
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* SPDX-License-Identifier: MIT
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Day arithmetic for the Token Usage surface: which days a range covers, what
|
|
8
|
+
* a day is called, and how days bucket into weeks and months.
|
|
9
|
+
*
|
|
10
|
+
* Shared deliberately. The SERVER decides which rows a period includes and the
|
|
11
|
+
* CLIENT re-buckets those same rows for the chart and the time tab, so two
|
|
12
|
+
* copies of "what is a week" would draw a chart that disagrees with the table
|
|
13
|
+
* beside it.
|
|
14
|
+
*
|
|
15
|
+
* **A period is a period.** Day / Week / Month / 90 days / All time / Custom are
|
|
16
|
+
* one list of trailing spans, not a grouping choice: every figure in the panel
|
|
17
|
+
* is the total for the selected span. The only derived thing is how those rows
|
|
18
|
+
* are bucketed for the chart, and that follows the period's own length.
|
|
19
|
+
*
|
|
20
|
+
* Every day is a LOCAL calendar day (`YYYY-MM-DD` in the server's timezone),
|
|
21
|
+
* never the UTC prefix of the timestamp. The panel's "Today" is the day the
|
|
22
|
+
* user is in; deriving buckets from the UTC prefix sent a 00:30 WIB record to
|
|
23
|
+
* yesterday's column while the totals counted it in today's.
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
import type { BucketGranularity, TimeRangeOption, TimeRangeType } from '@/shared/types';
|
|
27
|
+
|
|
28
|
+
/** Every range the Tokens endpoint answers for, in display order. */
|
|
29
|
+
export type PresetTimeRange = Exclude<TimeRangeType, 'custom'>;
|
|
30
|
+
export const PRESET_RANGES: readonly PresetTimeRange[] = ['today', '7d', '30d', '90d', 'all'];
|
|
31
|
+
|
|
32
|
+
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
33
|
+
/** Calendar days covered by each trailing preset, today included. */
|
|
34
|
+
const PRESET_DAYS: Record<'7d' | '30d' | '90d', number> = { '7d': 7, '30d': 30, '90d': 90 };
|
|
35
|
+
|
|
36
|
+
const MONTH_LABELS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] as const;
|
|
37
|
+
const ISO_DAY = /^\d{4}-\d{2}-\d{2}$/;
|
|
38
|
+
|
|
39
|
+
function pad2(value: number): string {
|
|
40
|
+
return value < 10 ? `0${value}` : String(value);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** `YYYY-MM-DD` of an instant in LOCAL time. */
|
|
44
|
+
export function localDayKey(ms: number): string {
|
|
45
|
+
const date = new Date(ms);
|
|
46
|
+
return `${date.getFullYear()}-${pad2(date.getMonth() + 1)}-${pad2(date.getDate())}`;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* The local day of an omp entry timestamp, or `''` when it carries none.
|
|
51
|
+
*
|
|
52
|
+
* `''` rather than `undefined` because the rollup's day column is part of its
|
|
53
|
+
* primary key: SQLite treats NULLs as distinct, so two dateless records for
|
|
54
|
+
* one session would both INSERT instead of accumulating into one row.
|
|
55
|
+
*/
|
|
56
|
+
export function dayKeyOfTimestamp(timestamp: string | undefined): string {
|
|
57
|
+
if (!timestamp) return '';
|
|
58
|
+
const ms = Date.parse(timestamp);
|
|
59
|
+
return Number.isNaN(ms) ? '' : localDayKey(ms);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** A half-open-free string window: `''` on either side means unbounded. */
|
|
63
|
+
export interface DayWindow {
|
|
64
|
+
from: string;
|
|
65
|
+
to: string;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Validate a `YYYY-MM-DD` query parameter, rejecting impossible dates. */
|
|
69
|
+
export function parseIsoDay(value: string): string | null {
|
|
70
|
+
if (!ISO_DAY.test(value)) return null;
|
|
71
|
+
const ms = Date.parse(`${value}T00:00:00`);
|
|
72
|
+
if (Number.isNaN(ms)) return null;
|
|
73
|
+
return localDayKey(ms) === value ? value : null;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* The days a range covers. `null` means "every day" (all time).
|
|
78
|
+
*
|
|
79
|
+
* Trailing presets count CALENDAR days with today included — "Last 7 days" is
|
|
80
|
+
* today plus the six before it, which is what the tab promises and what the
|
|
81
|
+
* chart's first/last labels then show.
|
|
82
|
+
*/
|
|
83
|
+
export function dayWindow(
|
|
84
|
+
range: TimeRangeType,
|
|
85
|
+
now: number,
|
|
86
|
+
custom?: { from?: string | null; to?: string | null },
|
|
87
|
+
): DayWindow | null {
|
|
88
|
+
if (range === 'custom') {
|
|
89
|
+
const from = custom?.from ? parseIsoDay(custom.from) : null;
|
|
90
|
+
const to = custom?.to ? parseIsoDay(custom.to) : null;
|
|
91
|
+
if (from && to && from <= to) return { from, to };
|
|
92
|
+
return trailingWindow('30d', now);
|
|
93
|
+
}
|
|
94
|
+
if (range === 'all') return null;
|
|
95
|
+
if (range === 'today') {
|
|
96
|
+
const today = localDayKey(now);
|
|
97
|
+
return { from: today, to: today };
|
|
98
|
+
}
|
|
99
|
+
return trailingWindow(range, now);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function trailingWindow(range: '7d' | '30d' | '90d', now: number): DayWindow {
|
|
103
|
+
const days = PRESET_DAYS[range];
|
|
104
|
+
return { from: localDayKey(now - (days - 1) * DAY_MS), to: localDayKey(now) };
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** Short day label: `2026-11-03` → `Nov 3`. */
|
|
108
|
+
export function dayLabel(dayKey: string): string {
|
|
109
|
+
if (!dayKey) return 'Undated';
|
|
110
|
+
const date = new Date(`${dayKey}T00:00:00`);
|
|
111
|
+
return Number.isNaN(date.getTime()) ? dayKey : `${MONTH_LABELS[date.getMonth()]} ${date.getDate()}`;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** `from`/`to` as one human range; a same-day window collapses to that day. */
|
|
115
|
+
export function dayRangeLabel(from: string, to: string, now: number = Date.now()): string {
|
|
116
|
+
if (!from || !to) return 'All time';
|
|
117
|
+
if (from === to) return `${dayLabel(from)}, ${new Date(`${from}T00:00:00`).getFullYear()}`;
|
|
118
|
+
const thisYear = new Date(now).getFullYear();
|
|
119
|
+
const fromYear = new Date(`${from}T00:00:00`).getFullYear();
|
|
120
|
+
const toYear = new Date(`${to}T00:00:00`).getFullYear();
|
|
121
|
+
const left = fromYear === thisYear ? dayLabel(from) : `${dayLabel(from)}, ${fromYear}`;
|
|
122
|
+
const right = `${dayLabel(to)}, ${toYear}`;
|
|
123
|
+
return `${left} – ${right}`;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* The bucket a day folds into: the day itself, its Monday, or `YYYY-MM`.
|
|
128
|
+
* Monday alignment is ISO-8601's week, which is also what a "week" row means to
|
|
129
|
+
* the reader.
|
|
130
|
+
*/
|
|
131
|
+
export function bucketKey(dayKey: string, granularity: BucketGranularity): string {
|
|
132
|
+
if (granularity === 'month') return dayKey.slice(0, 7);
|
|
133
|
+
if (granularity === 'week') {
|
|
134
|
+
const date = new Date(`${dayKey}T00:00:00`);
|
|
135
|
+
if (Number.isNaN(date.getTime())) return dayKey;
|
|
136
|
+
const monday = new Date(date);
|
|
137
|
+
monday.setDate(date.getDate() - ((date.getDay() + 6) % 7));
|
|
138
|
+
return localDayKey(monday.getTime());
|
|
139
|
+
}
|
|
140
|
+
return dayKey;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** Label for a bucket key, matching the granularity that produced it. */
|
|
144
|
+
export function bucketLabel(key: string, granularity: BucketGranularity): string {
|
|
145
|
+
if (granularity === 'month') {
|
|
146
|
+
const [year, month] = key.split('-');
|
|
147
|
+
const label = MONTH_LABELS[Number(month) - 1] ?? key;
|
|
148
|
+
const fullYear = Number(year);
|
|
149
|
+
return Number.isFinite(fullYear) && fullYear !== new Date().getFullYear() ? `${label} ${year}` : label;
|
|
150
|
+
}
|
|
151
|
+
return dayLabel(key);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* The period picker's entries, each with the dates it covers.
|
|
156
|
+
*
|
|
157
|
+
* Day / Week / Month name the SPAN (today, the last 7 days, the last 30), which
|
|
158
|
+
* is why there is no separate daily/weekly/monthly control: choosing Month and
|
|
159
|
+
* choosing "Last 30 days" are the same act.
|
|
160
|
+
*/
|
|
161
|
+
export function timeRangeOptions(now: number = Date.now()): TimeRangeOption[] {
|
|
162
|
+
const option = (id: TimeRangeType, label: string): TimeRangeOption => {
|
|
163
|
+
const window = dayWindow(id, now);
|
|
164
|
+
return { id, label, dateRange: window ? dayRangeLabel(window.from, window.to, now) : 'All time' };
|
|
165
|
+
};
|
|
166
|
+
return [
|
|
167
|
+
option('today', 'Day'),
|
|
168
|
+
option('7d', 'Week'),
|
|
169
|
+
option('30d', 'Month'),
|
|
170
|
+
option('90d', '90 days'),
|
|
171
|
+
option('all', 'All time'),
|
|
172
|
+
{ id: 'custom', label: 'Custom…', dateRange: 'Custom period' },
|
|
173
|
+
];
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* How the period's rows are bucketed for the chart and the time tab.
|
|
178
|
+
*
|
|
179
|
+
* Follows the period's own length, so the picture stays readable without
|
|
180
|
+
* asking the user a second question: a day or a month draws days, a quarter
|
|
181
|
+
* draws weeks, a long custom span or all time draws months.
|
|
182
|
+
*/
|
|
183
|
+
export function granularityFor(range: TimeRangeType, custom?: { from?: string; to?: string }): BucketGranularity {
|
|
184
|
+
if (range === 'today' || range === '7d' || range === '30d') return 'day';
|
|
185
|
+
if (range === '90d') return 'week';
|
|
186
|
+
if (range === 'all') return 'month';
|
|
187
|
+
const from = custom?.from ? parseIsoDay(custom.from) : null;
|
|
188
|
+
const to = custom?.to ? parseIsoDay(custom.to) : null;
|
|
189
|
+
if (!from || !to) return 'day';
|
|
190
|
+
const days = Math.round((Date.parse(`${to}T00:00:00`) - Date.parse(`${from}T00:00:00`)) / DAY_MS) + 1;
|
|
191
|
+
if (days <= 31) return 'day';
|
|
192
|
+
if (days <= 120) return 'week';
|
|
193
|
+
return 'month';
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* Every day in a window, oldest first.
|
|
198
|
+
*
|
|
199
|
+
* The rollup only stores days that HAVE usage, so a day with no work is absent
|
|
200
|
+
* from the payload — and a time table built from those rows silently omits it.
|
|
201
|
+
* The panel promises the PERIOD, so the range's own days are what it lists.
|
|
202
|
+
* Capped so an all-time range cannot build a decade of rows.
|
|
203
|
+
*/
|
|
204
|
+
export function daysInWindow(window: DayWindow, cap = 400): string[] {
|
|
205
|
+
const start = Date.parse(`${window.from}T00:00:00`);
|
|
206
|
+
const end = Date.parse(`${window.to}T00:00:00`);
|
|
207
|
+
if (Number.isNaN(start) || Number.isNaN(end) || end < start) return [];
|
|
208
|
+
const days: string[] = [];
|
|
209
|
+
for (let at = start; at <= end && days.length < cap; at += DAY_MS) {
|
|
210
|
+
// DST-safe: the key is recomputed from the local calendar, never by adding
|
|
211
|
+
// 86 400 000 ms to a formatted string.
|
|
212
|
+
const day = localDayKey(at);
|
|
213
|
+
if (days[days.length - 1] !== day) days.push(day);
|
|
214
|
+
}
|
|
215
|
+
return days;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* The span a set of day keys covers, or `null` when there are none.
|
|
220
|
+
*
|
|
221
|
+
* All time has no bounded window, but its table still has to list every bucket
|
|
222
|
+
* between the first and last recorded day — otherwise a quiet month in the
|
|
223
|
+
* middle of the history disappears and the rows stop adding up to the totals
|
|
224
|
+
* shown beside them.
|
|
225
|
+
*/
|
|
226
|
+
export function spanOfDays(dayKeys: Iterable<string>): DayWindow | null {
|
|
227
|
+
let from = '';
|
|
228
|
+
let to = '';
|
|
229
|
+
for (const day of dayKeys) {
|
|
230
|
+
if (!day) continue;
|
|
231
|
+
if (!from || day < from) from = day;
|
|
232
|
+
if (!to || day > to) to = day;
|
|
233
|
+
}
|
|
234
|
+
return from && to ? { from, to } : null;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/** Sort helper for day keys (`YYYY-MM-DD` sorts lexicographically). */
|
|
238
|
+
export function compareDayKeys(a: string, b: string): number {
|
|
239
|
+
return a < b ? -1 : a > b ? 1 : 0;
|
|
240
|
+
}
|