llmtop 0.1.4 → 0.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (145) hide show
  1. package/README.md +70 -67
  2. package/dashboard/dist/assets/be-vietnam-pro-latin-400-normal-PpnXBOrz.woff2 +0 -0
  3. package/dashboard/dist/assets/be-vietnam-pro-latin-500-normal-B6LVzGNe.woff2 +0 -0
  4. package/dashboard/dist/assets/be-vietnam-pro-latin-600-normal-BZDkUTrt.woff2 +0 -0
  5. package/dashboard/dist/assets/be-vietnam-pro-latin-700-normal-DlW1Zbsh.woff2 +0 -0
  6. package/dashboard/dist/assets/be-vietnam-pro-latin-800-normal-BpHZASpI.woff2 +0 -0
  7. package/dashboard/dist/assets/be-vietnam-pro-latin-ext-400-normal-CiZNW1ec.woff2 +0 -0
  8. package/dashboard/dist/assets/be-vietnam-pro-latin-ext-500-normal-h0Fp6aX0.woff2 +0 -0
  9. package/dashboard/dist/assets/be-vietnam-pro-latin-ext-600-normal-BNd8euf0.woff2 +0 -0
  10. package/dashboard/dist/assets/be-vietnam-pro-latin-ext-700-normal-C8_gqRu2.woff2 +0 -0
  11. package/dashboard/dist/assets/be-vietnam-pro-latin-ext-800-normal-GEpNgheG.woff2 +0 -0
  12. package/dashboard/dist/assets/be-vietnam-pro-vietnamese-400-normal-CRcqvyg1.woff2 +0 -0
  13. package/dashboard/dist/assets/be-vietnam-pro-vietnamese-500-normal-DREgrEoJ.woff2 +0 -0
  14. package/dashboard/dist/assets/be-vietnam-pro-vietnamese-600-normal-nyU-ZL2p.woff2 +0 -0
  15. package/dashboard/dist/assets/be-vietnam-pro-vietnamese-700-normal-Csr0PCuG.woff2 +0 -0
  16. package/dashboard/dist/assets/be-vietnam-pro-vietnamese-800-normal-D4LFh2W4.woff2 +0 -0
  17. package/dashboard/dist/assets/index-C6JlgSDz.js +9 -0
  18. package/dashboard/dist/assets/index-CeDllzpB.css +1 -0
  19. package/dashboard/dist/assets/jetbrains-mono-latin-ext-wght-normal-DBQx-q_a.woff2 +0 -0
  20. package/dashboard/dist/assets/jetbrains-mono-latin-wght-normal-B9CIFXIH.woff2 +0 -0
  21. package/dashboard/dist/assets/jetbrains-mono-vietnamese-wght-normal-Bt-aOZkq.woff2 +0 -0
  22. package/dashboard/dist/index.html +2 -2
  23. package/dashboard/src/App.tsx +224 -88
  24. package/dashboard/src/controls/DateRange.tsx +3 -3
  25. package/dashboard/src/controls/Search.tsx +2 -2
  26. package/dashboard/src/controls/popover.tsx +24 -4
  27. package/dashboard/src/format.ts +1 -1
  28. package/dashboard/src/i18n.tsx +32 -4
  29. package/dashboard/src/main.tsx +11 -2
  30. package/dashboard/src/model.ts +1 -1
  31. package/dashboard/src/overview-flow.css +24 -0
  32. package/dashboard/src/overviewFlow.tsx +76 -0
  33. package/dashboard/src/sessionDetail.test.ts +19 -0
  34. package/dashboard/src/sessionScope.tsx +28 -0
  35. package/dashboard/src/shell/ConsoleFilters.tsx +203 -0
  36. package/dashboard/src/shell/Header.tsx +29 -0
  37. package/dashboard/src/shell/MobileSheet.tsx +29 -0
  38. package/dashboard/src/shell/Palette.tsx +114 -0
  39. package/dashboard/src/shell/Settings.tsx +37 -0
  40. package/dashboard/src/shell/SpecialStates.tsx +145 -0
  41. package/dashboard/src/shell/preferences.ts +71 -0
  42. package/dashboard/src/shell/styleColors.ts +5 -0
  43. package/dashboard/src/shell/useShortcuts.ts +67 -0
  44. package/dashboard/src/state.test.ts +9 -0
  45. package/dashboard/src/state.ts +13 -2
  46. package/dashboard/src/styles/commands.css +61 -0
  47. package/dashboard/src/styles/console.css +149 -0
  48. package/dashboard/src/styles/donut.css +83 -0
  49. package/dashboard/src/styles/fonts/be-vietnam-pro-LICENSE +93 -0
  50. package/dashboard/src/styles/fonts/be-vietnam-pro-latin-400-normal.woff2 +0 -0
  51. package/dashboard/src/styles/fonts/be-vietnam-pro-latin-500-normal.woff2 +0 -0
  52. package/dashboard/src/styles/fonts/be-vietnam-pro-latin-600-normal.woff2 +0 -0
  53. package/dashboard/src/styles/fonts/be-vietnam-pro-latin-700-normal.woff2 +0 -0
  54. package/dashboard/src/styles/fonts/be-vietnam-pro-latin-800-normal.woff2 +0 -0
  55. package/dashboard/src/styles/fonts/be-vietnam-pro-latin-ext-400-normal.woff2 +0 -0
  56. package/dashboard/src/styles/fonts/be-vietnam-pro-latin-ext-500-normal.woff2 +0 -0
  57. package/dashboard/src/styles/fonts/be-vietnam-pro-latin-ext-600-normal.woff2 +0 -0
  58. package/dashboard/src/styles/fonts/be-vietnam-pro-latin-ext-700-normal.woff2 +0 -0
  59. package/dashboard/src/styles/fonts/be-vietnam-pro-latin-ext-800-normal.woff2 +0 -0
  60. package/dashboard/src/styles/fonts/be-vietnam-pro-vietnamese-400-normal.woff2 +0 -0
  61. package/dashboard/src/styles/fonts/be-vietnam-pro-vietnamese-500-normal.woff2 +0 -0
  62. package/dashboard/src/styles/fonts/be-vietnam-pro-vietnamese-600-normal.woff2 +0 -0
  63. package/dashboard/src/styles/fonts/be-vietnam-pro-vietnamese-700-normal.woff2 +0 -0
  64. package/dashboard/src/styles/fonts/be-vietnam-pro-vietnamese-800-normal.woff2 +0 -0
  65. package/dashboard/src/styles/fonts/jetbrains-mono-LICENSE +93 -0
  66. package/dashboard/src/styles/fonts/jetbrains-mono-latin-ext-wght-normal.woff2 +0 -0
  67. package/dashboard/src/styles/fonts/jetbrains-mono-latin-wght-normal.woff2 +0 -0
  68. package/dashboard/src/styles/fonts/jetbrains-mono-vietnamese-wght-normal.woff2 +0 -0
  69. package/dashboard/src/styles/fonts.css +240 -0
  70. package/dashboard/src/styles/shell.css +151 -0
  71. package/dashboard/src/styles/states.css +32 -0
  72. package/dashboard/src/styles/tokens.css +159 -0
  73. package/dashboard/src/styles.css +13 -44
  74. package/dashboard/src/tip.ts +3 -1
  75. package/dashboard/src/treemap.ts +3 -0
  76. package/dashboard/src/ui.tsx +21 -32
  77. package/dashboard/src/views/Breakdown.tsx +46 -0
  78. package/dashboard/src/views/SessionDetail.tsx +67 -0
  79. package/dashboard/src/views/breakdown.css +33 -0
  80. package/dashboard/src/views/{Activity.tsx → classic/Activity.tsx} +31 -50
  81. package/dashboard/src/views/classic/Context.tsx +140 -0
  82. package/dashboard/src/views/{Models.tsx → classic/Models.tsx} +18 -35
  83. package/dashboard/src/views/classic/Overview.tsx +80 -0
  84. package/dashboard/src/views/classic/Projects.tsx +98 -0
  85. package/dashboard/src/views/{Sessions.tsx → classic/Sessions.tsx} +14 -17
  86. package/dashboard/src/views/{Subagents.tsx → classic/Subagents.tsx} +10 -34
  87. package/dashboard/src/views/console/Activity.tsx +241 -0
  88. package/dashboard/src/views/console/ConsoleBoot.tsx +73 -0
  89. package/dashboard/src/views/console/Context.tsx +162 -0
  90. package/dashboard/src/views/console/Models.tsx +187 -0
  91. package/dashboard/src/views/console/Overview.tsx +91 -0
  92. package/dashboard/src/views/console/Projects.tsx +6 -0
  93. package/dashboard/src/views/console/ProviderMeters.tsx +35 -0
  94. package/dashboard/src/views/console/Sessions.tsx +6 -0
  95. package/dashboard/src/views/console/Subagents.tsx +137 -0
  96. package/dashboard/src/views/console/activity-context.css +92 -0
  97. package/dashboard/src/views/console/console-boot.css +137 -0
  98. package/dashboard/src/views/console/modelVisuals.tsx +29 -0
  99. package/dashboard/src/views/console/models-subagents.css +203 -0
  100. package/dashboard/src/views/donut/Activity.tsx +247 -0
  101. package/dashboard/src/views/donut/Context.tsx +169 -0
  102. package/dashboard/src/views/donut/DonutBoot.tsx +68 -0
  103. package/dashboard/src/views/donut/Models.tsx +58 -0
  104. package/dashboard/src/views/donut/Overview.tsx +49 -0
  105. package/dashboard/src/views/donut/Projects.tsx +6 -0
  106. package/dashboard/src/views/donut/Ring.tsx +30 -0
  107. package/dashboard/src/views/donut/Sessions.tsx +6 -0
  108. package/dashboard/src/views/donut/Subagents.tsx +131 -0
  109. package/dashboard/src/views/donut/activity-context.css +154 -0
  110. package/dashboard/src/views/donut/donut-boot.css +165 -0
  111. package/dashboard/src/views/donut/models-subagents.css +157 -0
  112. package/dashboard/src/views/records/Projects.tsx +140 -0
  113. package/dashboard/src/views/records/Sessions.tsx +125 -0
  114. package/dashboard/src/views/records/records.css +119 -0
  115. package/dashboard/src/views/session-detail.css +44 -0
  116. package/dashboard/src/vm/activity.ts +72 -0
  117. package/dashboard/src/vm/colors.ts +57 -0
  118. package/dashboard/src/vm/context.ts +81 -0
  119. package/dashboard/src/vm/filterChoices.ts +27 -0
  120. package/dashboard/src/vm/models.ts +50 -0
  121. package/dashboard/src/vm/overview.ts +46 -0
  122. package/dashboard/src/vm/palette.ts +63 -0
  123. package/dashboard/src/vm/projects.ts +63 -0
  124. package/dashboard/src/vm/providerBreakdown.ts +19 -0
  125. package/dashboard/src/vm/sessionDetail.ts +16 -0
  126. package/dashboard/src/vm/sessions.ts +36 -0
  127. package/dashboard/src/vm/specialStates.ts +64 -0
  128. package/dashboard/src/vm/subagents.ts +36 -0
  129. package/dashboard/src/vm.test.ts +183 -0
  130. package/package.json +1 -1
  131. package/src/api.mjs +6 -1
  132. package/src/dashboard.mjs +4 -1
  133. package/src/db.mjs +5 -2
  134. package/src/providers/codex.mjs +121 -19
  135. package/src/serve.mjs +20 -10
  136. package/dashboard/dist/assets/index-Ba0kF2tG.js +0 -9
  137. package/dashboard/dist/assets/index-NQzaBVIY.css +0 -1
  138. package/dashboard/dist/assets/montserrat-cyrillic-ext-wght-normal-CO5hGrJv.woff2 +0 -0
  139. package/dashboard/dist/assets/montserrat-cyrillic-wght-normal-EAA9jha_.woff2 +0 -0
  140. package/dashboard/dist/assets/roboto-mono-cyrillic-ext-wght-normal-BUDPrIko.woff2 +0 -0
  141. package/dashboard/dist/assets/roboto-mono-cyrillic-wght-normal-HUlVHixE.woff2 +0 -0
  142. package/dashboard/dist/assets/roboto-mono-greek-wght-normal-BJJTbwTT.woff2 +0 -0
  143. package/dashboard/src/views/Context.tsx +0 -183
  144. package/dashboard/src/views/Overview.tsx +0 -83
  145. package/dashboard/src/views/Projects.tsx +0 -116
@@ -7,21 +7,45 @@ import { DashContext, type Dash } from "./dash.ts";
7
7
  import { labelOf, type Extra } from "./extra.ts";
8
8
  import { makeFmt } from "./format.ts";
9
9
  import { T, type Key, type Lang } from "./i18n.tsx";
10
- import { buildModel, dayAdd, days, providerOptions, slice, type Filter, type Payload } from "./model.ts";
10
+ import { buildModel, dayAdd, days, slice, type Filter, type Payload } from "./model.ts";
11
11
  import { parseUrl, toUrl, VIEWS, type UrlState, type View } from "./state.ts";
12
- import { Activity } from "./views/Activity.tsx";
13
- import { Context } from "./views/Context.tsx";
14
- import { Models } from "./views/Models.tsx";
15
- import { Overview } from "./views/Overview.tsx";
16
- import { Projects } from "./views/Projects.tsx";
17
- import { Sessions } from "./views/Sessions.tsx";
18
- import { Subagents } from "./views/Subagents.tsx";
19
-
20
- // Language and theme belong to this browser, not to a link; storage may be refused, and the page works without it.
21
- const store = {
22
- get: (k: string) => { try { return localStorage.getItem(k); } catch { return null; } },
23
- set: (k: string, v: string) => { try { localStorage.setItem(k, v); } catch { /* not remembered */ } },
24
- };
12
+ import { ConsoleFilters } from "./shell/ConsoleFilters.tsx";
13
+ import { StyleColorsContext } from "./shell/styleColors.ts";
14
+ import { Palette, ShortcutHelp, ShortcutHint } from "./shell/Palette.tsx";
15
+ import { useShortcuts } from "./shell/useShortcuts.ts";
16
+ import { Boot, EmptyRange, NoProviders, ScanError } from "./shell/SpecialStates.tsx";
17
+ import { FILTER_KEYS, type FilterKey } from "./vm/filterChoices.ts";
18
+ import { Header } from "./shell/Header.tsx";
19
+ import { Settings } from "./shell/Settings.tsx";
20
+ import { SessionDetail } from "./views/SessionDetail.tsx";
21
+ import { readHiddenProviders, readLanguage, readStyle, readTheme, store, visibleModel, visibleOptions, type Style } from "./shell/preferences.ts";
22
+ import { buildColorVM } from "./vm/colors.ts";
23
+ import { Activity as ClassicActivity } from "./views/classic/Activity.tsx";
24
+ import { Activity as ConsoleActivity } from "./views/console/Activity.tsx";
25
+ import { Activity as DonutActivity } from "./views/donut/Activity.tsx";
26
+ import { Context as ClassicContext } from "./views/classic/Context.tsx";
27
+ import { Context as ConsoleContext } from "./views/console/Context.tsx";
28
+ import { Context as DonutContext } from "./views/donut/Context.tsx";
29
+ import { Models as ClassicModels } from "./views/classic/Models.tsx";
30
+ import { Models as ConsoleModels } from "./views/console/Models.tsx";
31
+ import { Models as DonutModels } from "./views/donut/Models.tsx";
32
+ import { Overview as ClassicOverview } from "./views/classic/Overview.tsx";
33
+ import { Overview as ConsoleOverview } from "./views/console/Overview.tsx";
34
+ import { Overview as DonutOverview } from "./views/donut/Overview.tsx";
35
+ import { Projects as ClassicProjects } from "./views/classic/Projects.tsx";
36
+ import { Projects as ConsoleProjects } from "./views/console/Projects.tsx";
37
+ import { Projects as DonutProjects } from "./views/donut/Projects.tsx";
38
+ import { Sessions as ClassicSessions } from "./views/classic/Sessions.tsx";
39
+ import { Sessions as ConsoleSessions } from "./views/console/Sessions.tsx";
40
+ import { Sessions as DonutSessions } from "./views/donut/Sessions.tsx";
41
+ import { Subagents as ClassicSubagents } from "./views/classic/Subagents.tsx";
42
+ import { Subagents as ConsoleSubagents } from "./views/console/Subagents.tsx";
43
+ import { Subagents as DonutSubagents } from "./views/donut/Subagents.tsx";
44
+
45
+ const classicViews = { Activity: ClassicActivity, Context: ClassicContext, Models: ClassicModels, Overview: ClassicOverview, Projects: ClassicProjects, Sessions: ClassicSessions, Subagents: ClassicSubagents };
46
+ const consoleViews = { Activity: ConsoleActivity, Context: ConsoleContext, Models: ConsoleModels, Overview: ConsoleOverview, Projects: ConsoleProjects, Sessions: ConsoleSessions, Subagents: ConsoleSubagents };
47
+
48
+ const donutViews = { Activity: DonutActivity, Context: DonutContext, Models: DonutModels, Overview: DonutOverview, Projects: DonutProjects, Sessions: DonutSessions, Subagents: DonutSubagents };
25
49
 
26
50
  const ICON: Record<string, string> = {
27
51
  overview: '<rect x="3" y="3" width="7" height="9" rx="1.5"/><rect x="14" y="3" width="7" height="5" rx="1.5"/><rect x="14" y="12" width="7" height="9" rx="1.5"/><rect x="3" y="16" width="7" height="5" rx="1.5"/>',
@@ -31,32 +55,34 @@ const ICON: Record<string, string> = {
31
55
  subagents: '<circle cx="6" cy="6" r="2.5"/><circle cx="18" cy="12" r="2.5"/><circle cx="6" cy="18" r="2.5"/><path d="M8.5 6H12v12H8.5M12 12h3.5"/>',
32
56
  activity: '<path d="M3 12h4l3-8 4 16 3-8h4"/>',
33
57
  context: '<path d="M4 17a8 8 0 1 1 16 0"/><path d="M12 17l4-6"/>',
34
- sun: '<circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M2 12h2M20 12h2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M4.9 19.1l1.4-1.4M17.7 6.3l1.4-1.4"/>',
35
- moon: '<path d="M20 14.5A8 8 0 0 1 9.5 4a8 8 0 1 0 10.5 10.5z"/>',
36
58
  refresh: '<path d="M20 12a8 8 0 1 1-2.34-5.66"/><path d="M20 4v5h-5"/>',
37
59
  };
38
60
  const Icon = ({ name, markup }: { name?: string; markup?: string }) => <svg viewBox="0 0 24 24" aria-hidden="true" dangerouslySetInnerHTML={{ __html: markup ?? ICON[name!] }} />;
39
61
 
40
62
  async function getJson<R>(url: string, init?: RequestInit): Promise<R> {
41
63
  const r = await fetch(url, init);
42
- const body = await r.json();
43
- if (!r.ok) throw new Error(body.error ?? `${r.status}`);
44
- return body;
64
+ if (!r.ok) {
65
+ const body = await r.json().catch(() => null);
66
+ throw new Error(`${r.status}${typeof body?.error === "string" ? " " + body.error : ""}`);
67
+ }
68
+ return r.json();
45
69
  }
46
70
 
47
71
  type ScanState = { busy: boolean; added?: { sessions: number; records: number }; error?: string };
48
72
  type Progress = { reason: "first" | "rebuild" | "update"; step: "find" | "read" | "finish"; done: number; total: number; bytes: number; totalBytes: number };
49
- const REASON = { first: "bootFirst", rebuild: "bootRebuild", update: "bootUpdate" } as const;
50
73
 
51
74
  // `extra` adds a second navigation section whose views get the same context as the built-in ones.
52
75
  export function App({ extra }: { extra?: Extra }) {
53
76
  const extraIds = useMemo(() => extra?.views.map((v) => v.id) ?? [], [extra]);
54
77
  const [url, setUrl] = useState(() => parseUrl(location.pathname, location.search, extraIds));
55
- const [lang, setLang] = useState<Lang>(() => {
56
- const saved = store.get("llmtop.lang");
57
- return saved === "en" || saved === "vi" ? saved : navigator.language.toLowerCase().startsWith("vi") ? "vi" : "en";
58
- });
59
- const [theme, setTheme] = useState(() => store.get("llmtop.theme") || (matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light"));
78
+ const currentUrl = useRef(url);
79
+ const [lang, setLang] = useState(readLanguage);
80
+ const [theme, setTheme] = useState(readTheme);
81
+ const [style, setStyle] = useState(() => readStyle(store.get("llmtop.style")));
82
+ const [hidden, setHidden] = useState(() => readHiddenProviders(store.get("llmtop.hiddenProviders")));
83
+ const [settingsOpen, setSettingsOpen] = useState(false);
84
+ const [paletteOpen, setPaletteOpen] = useState(false);
85
+ const [helpOpen, setHelpOpen] = useState(false);
60
86
  const [payload, setPayload] = useState<Payload | null>(null);
61
87
  const [loadError, setLoadError] = useState("");
62
88
  const [scan, setScan] = useState<ScanState>({ busy: false });
@@ -64,9 +90,20 @@ export function App({ extra }: { extra?: Extra }) {
64
90
  const L = T[lang];
65
91
  const t = useCallback((k: Key) => L[k] as string, [L]);
66
92
 
67
- useEffect(() => { document.documentElement.lang = lang; document.documentElement.dataset.theme = theme; }, [lang, theme]);
68
93
  useEffect(() => {
69
- const back = () => { setUrl(parseUrl(location.pathname, location.search, extraIds)); setLimit(25); };
94
+ const { documentElement } = document;
95
+ documentElement.lang = lang;
96
+ documentElement.dataset.theme = theme;
97
+ documentElement.dataset.style = style;
98
+ }, [lang, theme, style]);
99
+ useEffect(() => {
100
+ const back = () => {
101
+ const next = parseUrl(location.pathname, location.search, extraIds);
102
+ const previous = currentUrl.current;
103
+ if (next.view !== previous.view || next.q !== previous.q || (next.sessionsBy || "") !== (previous.sessionsBy || "")) setLimit(25);
104
+ currentUrl.current = next;
105
+ setUrl(next);
106
+ };
70
107
  addEventListener("popstate", back);
71
108
  return () => removeEventListener("popstate", back);
72
109
  }, [extraIds]);
@@ -91,28 +128,131 @@ export function App({ extra }: { extra?: Extra }) {
91
128
  getJson<Payload>("/api/data").then(setPayload, (err: Error) => setLoadError(err.message)).finally(refresh);
92
129
  }, [refresh]);
93
130
 
94
- const M = useMemo(() => (payload ? buildModel(payload) : null), [payload]);
131
+ const full = useMemo(() => payload ? buildModel(payload) : null, [payload]);
132
+ const M = useMemo(() => full && visibleModel(full, hidden), [full, hidden]);
133
+ const colors = useMemo(() => full && { ...buildColorVM(full), providerNames: full.providers }, [full]);
134
+ const providers = useMemo(() => {
135
+ if (!full || !colors) return [];
136
+ const counts = full.providers.map(() => 0);
137
+ for (const session of full.sessions) {
138
+ if (session.pr !== undefined && session.pr >= 0 && session.pr < counts.length) counts[session.pr]++;
139
+ }
140
+ return full.providers.map((name, index) => ({ name, sessions: counts[index], color: colors.providers[index] }))
141
+ .filter(({ sessions }) => sessions > 0);
142
+ }, [full, colors]);
95
143
  const f = useMemo(() => makeFmt(lang), [lang]);
96
144
 
97
145
  // While a scan runs with nothing to show yet, follow its progress over the transcripts.
98
146
  const [progress, setProgress] = useState<Progress | null>(null);
99
- const waiting = !M && scan.busy;
147
+ const waiting = scan.busy && (!M || payload?.transcripts === 0);
100
148
  useEffect(() => {
101
149
  if (!waiting) return setProgress(null);
102
150
  const id = setInterval(() => getJson<Progress | null>("/api/scan/progress").then(setProgress, () => {}), 300);
103
151
  return () => clearInterval(id);
104
152
  }, [waiting]);
105
153
 
154
+ useEffect(() => {
155
+ if (!scan.added) return;
156
+ const timer = setTimeout(() => setScan((state) => ({ ...state, added: undefined })), 4000);
157
+ return () => clearTimeout(timer);
158
+ }, [scan.added]);
159
+
106
160
  const set = useCallback((patch: Partial<UrlState>, opts: { replace?: boolean } = {}) => {
107
- setUrl((cur) => {
108
- const next = { ...cur, ...patch };
109
- if (patch.view && patch.view !== cur.view) { setLimit(25); scrollTo(0, 0); }
110
- if ("q" in patch) setLimit(25);
111
- history[opts.replace ? "replaceState" : "pushState"](null, "", toUrl(next));
112
- return next;
113
- });
161
+ const current = currentUrl.current;
162
+ const next = { ...current, ...patch };
163
+ const changedView = next.view !== current.view;
164
+ if (changedView && !("session" in patch)) delete next.session;
165
+ if (changedView || ("q" in patch) || (next.sessionsBy || "") !== (current.sessionsBy || "")) setLimit(25);
166
+ if (changedView) scrollTo(0, 0);
167
+ // A detail opened here has an entry underneath to return to. Shared links can close in place.
168
+ const state = opts.replace ? history.state : next.session && !current.session ? { llmtopOpenedSession: true } : null;
169
+ history[opts.replace ? "replaceState" : "pushState"](state, "", toUrl(next));
170
+ currentUrl.current = next;
171
+ setUrl(next);
114
172
  }, []);
115
173
 
174
+ const closeSession = () => {
175
+ if (history.state?.llmtopOpenedSession) history.back();
176
+ else set({ session: "" }, { replace: true });
177
+ };
178
+
179
+ useEffect(() => {
180
+ if (url.provider && hidden.includes(url.provider)) set({ provider: "" }, { replace: true });
181
+ }, [hidden, url.provider, set]);
182
+
183
+ const chooseLanguage = (value: Lang) => { setLang(value); store.set("llmtop.lang", value); };
184
+ const chooseStyle = (value: Style) => { setStyle(value); store.set("llmtop.style", value); };
185
+ const toggleTheme = () => {
186
+ const value = theme === "dark" ? "light" : "dark";
187
+ setTheme(value);
188
+ store.set("llmtop.theme", value);
189
+ };
190
+ const filterOrder = useRef<FilterKey[]>([]);
191
+ const previousUrl = useRef<UrlState | undefined>(undefined);
192
+ const changed = FILTER_KEYS.filter((key) => url[key] !== previousUrl.current?.[key]);
193
+ const order = [...filterOrder.current.filter((key) => !changed.includes(key)), ...changed.filter((key) => url[key])];
194
+ useEffect(() => {
195
+ filterOrder.current = order;
196
+ previousUrl.current = url;
197
+ }, [url]);
198
+ const dropKey = order.at(-1);
199
+ const removeFilter = () => { if (dropKey) set({ [dropKey]: "" }); };
200
+ const showSettings = () => setSettingsOpen(true);
201
+ const showHelp = () => setHelpOpen(true);
202
+ const showPalette = () => setPaletteOpen(true);
203
+ const toggleLanguage = () => chooseLanguage(lang === "vi" ? "en" : "vi");
204
+ const rescan = () => { if (!scan.busy) void refresh(); };
205
+ useShortcuts({
206
+ enabled: Boolean(M) && !waiting,
207
+ modalOpen: settingsOpen || helpOpen || paletteOpen || Boolean(url.session),
208
+ palette: showPalette, help: showHelp, refresh: rescan, settings: showSettings,
209
+ theme: toggleTheme, language: toggleLanguage, view: (view) => set({ view }), removeFilter,
210
+ });
211
+
212
+ useEffect(() => {
213
+ if (style === "classic" || !M || scan.busy) return;
214
+ let start: Touch | undefined;
215
+ const touchStart = (event: TouchEvent) => {
216
+ const el = event.target;
217
+ start = matchMedia("(max-width: 639px)").matches && scrollY <= 0 &&
218
+ el instanceof Element && !el.closest("dialog, input, select, button") && event.touches.length === 1 ? event.touches[0] : undefined;
219
+ };
220
+ const touchEnd = (event: TouchEvent) => {
221
+ const end = event.changedTouches[0];
222
+ if (start && end && end.clientY - start.clientY > Math.max(72, Math.abs(end.clientX - start.clientX) * 1.5) && scrollY <= 0) void refresh();
223
+ start = undefined;
224
+ };
225
+ const cancel = () => { start = undefined; };
226
+ addEventListener("touchstart", touchStart, { passive: true });
227
+ addEventListener("touchend", touchEnd, { passive: true });
228
+ addEventListener("touchcancel", cancel, { passive: true });
229
+ return () => {
230
+ removeEventListener("touchstart", touchStart);
231
+ removeEventListener("touchend", touchEnd);
232
+ removeEventListener("touchcancel", cancel);
233
+ };
234
+ }, [M, refresh, scan.busy, style]);
235
+
236
+ const toggleProvider = (name: string) => {
237
+ const next = hidden.includes(name) ? hidden.filter((provider) => provider !== name) : [...hidden, name];
238
+ setHidden(next);
239
+ store.set("llmtop.hiddenProviders", JSON.stringify(next));
240
+ };
241
+
242
+ const navRef = useRef<HTMLElement>(null);
243
+ useEffect(() => {
244
+ if (!matchMedia("(max-width: 1100px)").matches) return;
245
+ const nav = navRef.current;
246
+ const active = nav?.querySelector('[aria-current="page"]');
247
+ if (!nav || !active) return;
248
+ const scroller = style === "classic" ? nav.closest<HTMLElement>(".side") : nav;
249
+ if (!scroller || scroller.scrollWidth <= scroller.clientWidth) return;
250
+ const { left, right } = active.getBoundingClientRect();
251
+ const bounds = scroller.getBoundingClientRect();
252
+ if (left < bounds.left) scroller.scrollLeft += left - bounds.left;
253
+ else if (right > bounds.right - 16) scroller.scrollLeft += right - bounds.right + 16;
254
+ }, [style, url.view, M, lang]);
255
+
116
256
  const refreshButton = (
117
257
  <button className={`icon refresh${scan.busy ? " busy" : ""}`} onClick={refresh} disabled={scan.busy} aria-label={scan.busy ? t("scanning") : t("refresh")}>
118
258
  <Icon name="refresh" />
@@ -120,31 +260,12 @@ export function App({ extra }: { extra?: Extra }) {
120
260
  );
121
261
 
122
262
  const brand = <div className="brand"><img className="brand-lockup" src={theme === "dark" ? lockupDark : lockupLight} alt="llmtop" /></div>;
123
- if (!M) {
124
- const failed = loadError && !scan.busy;
125
- // The bar follows the bytes read, so a large transcript moves it too; finding and finishing have no measure of their own.
126
- const share = progress?.step === "read" ? (progress.totalBytes ? progress.bytes / progress.totalBytes : progress.total ? progress.done / progress.total : null) : null;
127
- return (
128
- <div className="boot" role="status">
129
- <div className="boot-in">
130
- {brand}
131
- {failed ? <>
132
- <p className="boot-msg">{t("loadFail")}</p>
133
- <p className="boot-err">{scan.error ?? loadError}</p>
134
- <button type="button" className="field clearall" onClick={refresh}>{t("retry")}</button>
135
- </> : <>
136
- <p className="boot-msg">{!scan.busy ? t("loading") : !progress || progress.step === "find" ? t("bootFind") : progress.step === "finish" ? t("bootFinish") : t(REASON[progress.reason])}</p>
137
- <div className={`boot-bar${share === null ? " wait" : ""}`}><span style={share === null ? undefined : { width: `${share * 100}%` }} /></div>
138
- <p className="boot-count">{progress?.total && progress.step !== "finish" ? `${f.int(progress.done)} / ${f.int(progress.total)} ${t("transcripts")}` : "\u00a0"}</p>
139
- </>}
140
- </div>
141
- </div>
142
- );
143
- }
263
+ if (!M || waiting) return <Boot brand={brand} progress={progress} busy={scan.busy}
264
+ error={!scan.busy ? scan.error ?? loadError : ""} retry={refresh} t={t} f={f} />;
144
265
 
145
266
  const view: View = url.view;
146
267
  const provider = url.provider ? M.providers.indexOf(url.provider) : -1;
147
- const opts = providerOptions(M, provider);
268
+ const opts = visibleOptions(M, provider, M !== full);
148
269
  const projectIdx = url.project ? M.projects.indexOf(url.project) : -1;
149
270
  const modelIdx = url.model ? M.models.indexOf(url.model) : -1;
150
271
  const effortIdx = url.effort ? M.efforts.indexOf(url.effort) : -1;
@@ -158,7 +279,7 @@ export function App({ extra }: { extra?: Extra }) {
158
279
  };
159
280
  const onProviderChange = (v: string) => {
160
281
  const nextPr = v ? M.providers.indexOf(v) : -1;
161
- const nextOpts = providerOptions(M, nextPr);
282
+ const nextOpts = visibleOptions(M, nextPr, M !== full);
162
283
  const patch: Partial<UrlState> = { provider: v };
163
284
  if (url.model && !nextOpts.models.includes(M.models.indexOf(url.model))) patch.model = "";
164
285
  if (url.project && !nextOpts.projects.includes(M.projects.indexOf(url.project))) patch.project = "";
@@ -167,34 +288,15 @@ export function App({ extra }: { extra?: Extra }) {
167
288
  };
168
289
  const dash: Dash = { M, S: url, filter, lang, L, t, f, limit, more: () => setLimit((n) => n + 25), set };
169
290
  const list = days(filter.from, filter.to), F = slice(M, filter);
291
+ const projectFacts = view === "projects" ? slice(M, { ...filter, project: -1 }) : F;
170
292
  const ev = extra?.views.find((v) => v.id === view);
171
293
  const nav = (k: View) => <button key={k} onClick={() => set({ view: k })} aria-current={view === k ? "page" : undefined}><Icon name={k} />{t(k as Key)}</button>;
172
- const body = ({ overview: () => <Overview F={F} list={list} />, projects: () => <Projects F={slice(M, { ...filter, project: -1 })} />, sessions: () => <Sessions F={F} />, models: () => <Models F={F} />, subagents: () => <Subagents F={F} />, activity: () => <Activity F={F} list={list} />, context: () => <Context F={F} list={list} /> } as Record<string, () => ReactNode>)[view]?.();
294
+ const renderer = style;
295
+ const { Activity, Context, Models, Overview, Projects, Sessions, Subagents } = renderer === "console" ? consoleViews : renderer === "donut" ? donutViews : classicViews;
296
+ const body = ({ overview: () => <Overview F={F} list={list} />, projects: () => <Projects F={projectFacts} />, sessions: () => <Sessions F={F} />, models: () => <Models F={F} />, subagents: () => <Subagents F={F} />, activity: () => <Activity F={F} list={list} />, context: () => <Context F={F} list={list} /> } as Record<string, () => ReactNode>)[view]?.();
173
297
 
174
- return (
175
- <DashContext.Provider value={dash}>
176
- <div className="app">
177
- <aside className="side">
178
- {brand}
179
- <div className="navlabel">{t("usage")}</div>
180
- <nav className="nav">{VIEWS.map(nav)}</nav>
181
- {extra ? <><div className="navlabel">{labelOf(extra.label, lang)}</div><nav className="nav quiet">{extra.views.map((v) => <button key={v.id} onClick={() => set({ view: v.id })} aria-current={view === v.id ? "page" : undefined}><Icon markup={v.icon} />{labelOf(v.label, lang)}</button>)}</nav></> : null}
182
- {/* The scan and the app's settings: below the nav on wide screens, at the end of the nav bar on narrow ones. */}
183
- <div className="foot">
184
- <div className="scan">
185
- <div className="si">{scan.busy ? t("scanning") : <>{t("scanned")} {f.scanTime(M.scanned)}{scan.added?.sessions ? <span>{L.scanNew(scan.added.sessions)}</span> : null}</>}</div>
186
- {refreshButton}
187
- </div>
188
- <div className="prefs">
189
- <div className="seg" role="group">{(["vi", "en"] as const).map((k) => <button key={k} aria-pressed={lang === k} onClick={() => { setLang(k); store.set("llmtop.lang", k); }}>{k.toUpperCase()}</button>)}</div>
190
- <button className="icon" aria-label={t("theme")} onClick={() => { const v = theme === "dark" ? "light" : "dark"; setTheme(v); store.set("llmtop.theme", v); }}><Icon name={theme === "dark" ? "sun" : "moon"} /></button>
191
- </div>
192
- </div>
193
- </aside>
194
- <main><div className="wrap">
195
- <h1 className="sr">{ev ? labelOf(ev.label, lang) : t(view as Key)}</h1>
196
- {ev?.filters === false ? null : (
197
- <div className="filters">
298
+ const classicFilters = renderer === "classic" && ev?.filters !== false ? (
299
+ <div className="filters">
198
300
  <div className="seg" role="group">{([["1", "today"], ["7", "d7"], ["14", "d14"], ["30", "d30"], ["all", "all"]] as const).map(([k, l]) => <button key={k} aria-pressed={url.range === k} onClick={() => set({ range: k, from: "", to: "" })}>{t(l)}</button>)}</div>
199
301
  <DateRange from={filter.from} to={filter.to} min={M.first} max={M.today} onChange={(from, to) => set({ range: "", from, to })}
200
302
  locale={f.locale} weekdays={L.wdShort} label={t("dates")} prevLabel={t("prevMonth")} nextLabel={t("nextMonth")} />
@@ -203,11 +305,45 @@ export function App({ extra }: { extra?: Extra }) {
203
305
  <Select label={t("model")} value={filter.model < 0 ? "" : url.model} onChange={(v) => set({ model: v })} options={[{ value: "", label: t("allModels") }, ...opts.models.map((m) => ({ value: M.models[m], label: M.models[m] }))]} />
204
306
  <Select label={t("effort")} value={filter.effort < 0 ? "" : url.effort} onChange={(v) => set({ effort: v })} options={[{ value: "", label: t("allEfforts") }, ...opts.levels.map((e) => ({ value: M.efforts[e], label: M.efforts[e] }))]} />
205
307
  {filter.provider >= 0 || filter.project >= 0 || filter.model >= 0 || filter.effort >= 0 ? <button className="field clearall" onClick={() => set({ provider: "", project: "", model: "", effort: "" })}><svg viewBox="0 0 16 16" aria-hidden="true"><path d="M4.5 4.5l7 7M11.5 4.5l-7 7" /></svg>{t("reset")}</button> : null}
206
- </div>)}
207
- {scan.error ? <p className="alert" style={{ margin: "-8px 0 14px" }}>{t("scanFail")}: {scan.error}</p> : null}
208
- {ev ? ev.render() : body}
209
- </div></main>
308
+ </div>
309
+ ) : null;
310
+
311
+ const navigation = <>
312
+ <div className="navlabel">{t("usage")}</div>
313
+ <nav className="nav swipe" ref={navRef}>{VIEWS.map(nav)}</nav>
314
+ {extra ? <><div className="navlabel">{labelOf(extra.label, lang)}</div><nav className="nav quiet">{extra.views.map((v) => <button key={v.id} onClick={() => set({ view: v.id })} aria-current={view === v.id ? "page" : undefined}><Icon markup={v.icon} />{labelOf(v.label, lang)}</button>)}</nav></> : null}
315
+ </>;
316
+
317
+ return (
318
+ <DashContext.Provider value={dash}>
319
+ <StyleColorsContext.Provider value={colors}>
320
+ <div className="app" data-renderer={renderer}>
321
+ <Header brand={brand} navigation={renderer === "classic" ? classicFilters : <div className="shell-nav swipe">{navigation}</div>} status={scan.busy ? t("scanning") : <>{t("scanned")} {f.scanTime(M.scanned)}{scan.added?.sessions ? <span>{L.scanNew(scan.added.sessions)}</span> : null}</>}
322
+ refresh={refreshButton} lang={lang} theme={theme} themeLabel={t("theme")} settingsLabel={t("settings")}
323
+ onLanguage={toggleLanguage} onTheme={toggleTheme} onSettings={showSettings} help={renderer === "donut" ? showHelp : undefined} helpLabel={t("shortcuts")} />
324
+ {renderer === "classic" ? <aside className="side">
325
+ {brand}
326
+ {navigation}
327
+ </aside> : null}
328
+ <main>
329
+ <div className="wrap">
330
+ <h1 className="view-heading">{ev ? labelOf(ev.label, lang) : t(view as Key)}</h1>
331
+ {ev?.filters === false ? null : renderer === "classic"
332
+ ? <div className="classic-mobile-filters"><ConsoleFilters onPalette={showPalette} /></div>
333
+ : <ConsoleFilters variant={renderer} onPalette={showPalette} />}
334
+ {scan.error ? <ScanError error={scan.error} retry={refresh} busy={scan.busy} /> : null}
335
+ {ev ? ev.render() : !payload?.transcripts ? <NoProviders refresh={refresh} busy={scan.busy} /> :
336
+ renderer !== "classic" && !(view === "sessions" && url.q.trim()) && !(view === "projects" ? projectFacts : F).length ? <EmptyRange dropKey={dropKey} /> : body}
337
+ {renderer === "console" ? <ShortcutHint openHelp={showHelp} /> : null}
338
+ </div>
339
+ {url.session ? <SessionDetail sessionKey={url.session} onClose={closeSession} /> : null}
340
+ {paletteOpen ? <Palette onClose={() => setPaletteOpen(false)} refresh={rescan} settings={showSettings} theme={toggleTheme} language={toggleLanguage} /> : null}
341
+ {helpOpen ? <ShortcutHelp onClose={() => setHelpOpen(false)} /> : null}
342
+ {settingsOpen ? <Settings style={style} providers={providers} hidden={hidden} onStyle={chooseStyle}
343
+ onToggle={toggleProvider} onClose={() => setSettingsOpen(false)} /> : null}
344
+ </main>
210
345
  </div>
346
+ </StyleColorsContext.Provider>
211
347
  </DashContext.Provider>
212
348
  );
213
349
  }
@@ -20,11 +20,11 @@ function weeks(m: string) {
20
20
 
21
21
  type Props = {
22
22
  from: string; to: string; min: string; max: string; onChange: (from: string, to: string) => void;
23
- locale: string; weekdays: readonly string[]; label: string; prevLabel: string; nextLabel: string;
23
+ locale: string; weekdays: readonly string[]; label: string; prevLabel: string; nextLabel: string; containFocus?: boolean;
24
24
  };
25
25
 
26
- export function DateRange({ from, to, min, max, onChange, locale, weekdays, label, prevLabel, nextLabel }: Props) {
27
- const p = usePopover();
26
+ export function DateRange({ from, to, min, max, onChange, locale, weekdays, label, prevLabel, nextLabel, containFocus }: Props) {
27
+ const p = usePopover(containFocus);
28
28
  const [count, setCount] = useState(2);
29
29
  const [start, setStart] = useState(monthOf(to)); // the first month shown
30
30
  const [anchor, setAnchor] = useState<string | null>(null);
@@ -1,12 +1,12 @@
1
1
  // A text field for searching: a magnifier, the text, and a clear button once there is text; Escape clears too.
2
2
  import { useRef } from "react";
3
3
 
4
- export function Search({ value, onChange, placeholder, clearLabel }: { value: string; onChange: (v: string) => void; placeholder: string; clearLabel: string }) {
4
+ export function Search({ value, onChange, placeholder, clearLabel, shortcutTarget }: { value: string; onChange: (v: string) => void; placeholder: string; clearLabel: string; shortcutTarget?: boolean }) {
5
5
  const input = useRef<HTMLInputElement>(null);
6
6
  return (
7
7
  <label className="field search">
8
8
  <svg className="mag" viewBox="0 0 16 16" aria-hidden="true"><circle cx="7" cy="7" r="4.5" /><path d="M10.5 10.5L14 14" /></svg>
9
- <input ref={input} type="text" role="searchbox" spellCheck={false} autoComplete="off" placeholder={placeholder} value={value}
9
+ <input ref={input} data-dashboard-search={shortcutTarget || undefined} type="text" role="searchbox" spellCheck={false} autoComplete="off" placeholder={placeholder} value={value}
10
10
  onChange={(e) => onChange(e.target.value)} onKeyDown={(e) => { if (e.key === "Escape" && value) { e.preventDefault(); onChange(""); } }} />
11
11
  {value ? (
12
12
  <button type="button" className="clear" aria-label={clearLabel} onClick={() => { onChange(""); input.current?.focus(); }}>
@@ -1,7 +1,7 @@
1
1
  // Open state for a control with a popover: closes on a click outside it or on Escape, which returns focus to the trigger.
2
2
  import { useEffect, useLayoutEffect, useRef, useState } from "react";
3
3
 
4
- export function usePopover<T extends HTMLElement = HTMLButtonElement>() {
4
+ export function usePopover<T extends HTMLElement = HTMLButtonElement>(containFocus = false) {
5
5
  const [open, setOpen] = useState(false);
6
6
  const [shift, setShift] = useState(0);
7
7
  const root = useRef<HTMLDivElement>(null);
@@ -11,18 +11,38 @@ export function usePopover<T extends HTMLElement = HTMLButtonElement>() {
11
11
  useEffect(() => {
12
12
  if (!open) return;
13
13
  const outside = (e: PointerEvent) => { if (!root.current?.contains(e.target as Node)) setOpen(false); };
14
- const key = (e: KeyboardEvent) => { if (e.key === "Escape") { setOpen(false); trigger.current?.focus(); } };
14
+ const key = (e: KeyboardEvent) => {
15
+ const dialog = pop.current;
16
+ const nested = e.target instanceof Element && e.target.closest('[role="dialog"]');
17
+ if (nested && nested !== dialog && dialog?.contains(nested)) return;
18
+ if (e.key === "Escape") {
19
+ e.preventDefault();
20
+ setOpen(false);
21
+ trigger.current?.focus();
22
+ return;
23
+ }
24
+ if (!containFocus || e.key !== "Tab" || !dialog) return;
25
+ const stops = [...dialog.querySelectorAll<HTMLElement>('button:not(:disabled), input:not(:disabled), select:not(:disabled), [tabindex]')]
26
+ .filter((element) => element.tabIndex >= 0 && element.getClientRects().length > 0);
27
+ const first = stops[0], last = stops.at(-1);
28
+ const active = document.activeElement;
29
+ if (e.shiftKey ? active === first || !dialog.contains(active) : active === last || !dialog.contains(active)) {
30
+ e.preventDefault();
31
+ (e.shiftKey ? last : first)?.focus();
32
+ }
33
+ };
15
34
  document.addEventListener("pointerdown", outside);
16
35
  document.addEventListener("keydown", key);
17
36
  return () => { document.removeEventListener("pointerdown", outside); document.removeEventListener("keydown", key); };
18
- }, [open]);
37
+ }, [containFocus, open]);
19
38
 
20
39
  // The popover opens under the trigger's left edge, moved left as far as it takes to stay 8 px inside the window.
21
40
  useLayoutEffect(() => {
22
41
  if (!open || !pop.current || !root.current) { setShift(0); return; }
42
+ if (containFocus) pop.current.querySelector<HTMLElement>("input, button:not(:disabled)")?.focus();
23
43
  const left = root.current.getBoundingClientRect().left, room = document.documentElement.clientWidth - 8;
24
44
  setShift(Math.max(8 - left, Math.min(0, room - (left + pop.current.offsetWidth))));
25
- }, [open]);
45
+ }, [containFocus, open]);
26
46
 
27
47
  const close = (refocus = true) => { setOpen(false); if (refocus) trigger.current?.focus(); };
28
48
  return { open, setOpen, close, root, trigger, pop, place: { left: shift } };
@@ -10,7 +10,7 @@ export function makeFmt(lang: "vi" | "en") {
10
10
  return new Intl.NumberFormat(loc, { maximumFractionDigits: !u || v >= 100 ? 0 : v >= 10 ? 1 : 2 }).format(v) + u;
11
11
  };
12
12
  const int = (n: number) => new Intl.NumberFormat(loc).format(Math.round(n));
13
- const usd = (n: number) => { const d = n >= 100 || Number.isInteger(n) ? 0 : 2; return "$" + new Intl.NumberFormat(loc, { maximumFractionDigits: d, minimumFractionDigits: d }).format(n); };
13
+ const usd = (n: number) => { const d = Math.abs(n) >= 10000 ? 0 : 2; return "$" + new Intl.NumberFormat(loc, { maximumFractionDigits: d, minimumFractionDigits: d }).format(n); };
14
14
  const pct = (n: number) => new Intl.NumberFormat(loc, { style: "percent", maximumFractionDigits: n > 0 && n < 0.1 ? 1 : 0 }).format(n);
15
15
  const dshort = (d: string) => new Intl.DateTimeFormat(loc, { day: "numeric", month: "short", timeZone: "UTC" }).format(new Date(d + "T00:00:00Z"));
16
16
  return {
@@ -1,6 +1,16 @@
1
1
  // Every string the page shows, in Vietnamese and English.
2
2
  export const T = {
3
- vi: { usage: "Sử dụng", overview: "Tổng quan", projects: "Dự án", sessions: "Phiên làm việc", models: "Model & effort", subagents: "Subagent", activity: "Hoạt động",
3
+ vi: {
4
+ sessionsByCost: "Xem phiên theo chi phí", sessionsByOutput: "Xem phiên theo token đầu ra",
5
+ activeDay: "Ngày có hoạt động", viewDaySessions: "Xem phiên ngày này",
6
+ usageCost: "Chi phí sử dụng", costExplanation: "Dựa trên chi phí được ghi nhận hoặc ước tính theo bảng giá model. Khoản thực trả có thể khác.",
7
+ sessionsWithRebuild: "Phiên có dựng lại cache", sessionsWithCompaction: "Phiên có nén context", sessionsWithSubagent: "Phiên có hoạt động subagent", clearSessionScope: "Bỏ lọc theo hoạt động phiên",
8
+ sessionDetails: "Chi tiết phiên", sessionUnavailable: "Không tìm thấy phiên trong dữ liệu đang hiển thị.", wholeSession: "Số liệu của toàn bộ phiên.", providerOutputShare: "Tỷ trọng tổng token đầu ra", modelBreakdown: "Phân bổ theo model", viewSessions: "Xem phiên", projectComparison: "Đang so sánh mọi dự án trong kỳ", selectedProject: "Dự án đã chọn", shareTotalCost: "Tỷ trọng trên tổng chi phí", estimatedCost: "Chi phí ước tính",
9
+ palette: "Bảng lệnh", palettePlaceholder: "Gõ để lọc, tìm phiên hoặc chạy lệnh…", palFilters: "Bộ lọc gợi ý", palSessions: "Phiên", palCommands: "Lệnh", shortcuts: "Phím tắt", kHelp: "Trợ giúp", kSearch: "Tìm", kCommands: "Lệnh", kViews: "Màn hình", kRescan: "Quét lại", toggleLanguage: "Đổi ngôn ngữ",
10
+ noProviders: "Chưa tìm thấy dữ liệu của provider nào", noProvidersHelp: "llmtop đọc transcript trên máy. Hãy chạy một phiên rồi quét lại.", configHelp: "Hướng dẫn cấu hình", configHelpBody: "Cấu hình provider trong llmtop.config.json hoặc qua LLMTOP_CONFIG, rồi mở lại dashboard.", loadFailHelp: "Kiểm tra llmtop serve đang chạy rồi thử lại.", scanDetails: "Chi tiết", widenTo: (n: string) => `Mở rộng ra ${n} ngày`, lastSeen: (d: string) => `Lần gần nhất: ${d}`, dropFilter: (x: string) => `Bỏ lọc ${x}`, noMatch: (q: string) => `Không phiên nào khớp “${q}”`, searchAll: "Tìm trong tất cả thời gian", scopeAllMatches: (n: string) => `${n} phiên khớp trong tất cả thời gian`,
11
+ filters: "Bộ lọc", filterModels: "Lọc model…", apply: "Áp dụng", back: "Quay lại", showSessions: (n: string) => `Xem ${n} phiên`, comparedWith: (r: string) => `So với: ${r}`, avgPerDay: "TB/ngày", onlyProvider: (p: string) => `Chỉ tìm thấy ${p} trên máy này — các thanh chia theo model`, reqPerHour: "Request mỗi giờ", succeeded: "thành công", source: "Nguồn", subRequests: "Request của subagent", sameMain: "Ngang mức phiên", addFilter: "+ Thêm bộ lọc", newest: "Mới nhất",
12
+ settings: "Cài đặt", style: "Kiểu giao diện", styleClassic: "Cổ điển", styleConsole: "Console", styleDonut: "Donut", styleClassicDesc: "Sidebar, thẻ KPI — bố cục cũ", styleConsoleDesc: "Kiểu htop, đơn sắc, phím tắt", styleDonutDesc: "Hình và số lớn, ít chữ", providersShown: "Provider hiển thị · tự phát hiện trên máy này", rescanProviders: "Quét lại để tìm provider mới", close: "Đóng",
13
+ usage: "Sử dụng", overview: "Tổng quan", projects: "Dự án", sessions: "Phiên làm việc", models: "Model & effort", subagents: "Subagent", activity: "Hoạt động",
4
14
  scanned: "Quét lúc", untitled: "(chưa có tiêu đề)", costUnknown: "Không có bản ghi chi phí của host", costEstimated: "Không có bản ghi chi phí của host; ước tính theo bảng giá", costPartial: "Host đánh dấu chi phí chưa đủ", today: "Hôm nay", perHour: "Theo giờ", hour: "Giờ", d7: "7 ngày", d14: "14 ngày", d30: "30 ngày", all: "Tất cả", dates: "Khoảng ngày", prevMonth: "Tháng trước", nextMonth: "Tháng sau", clear: "Xoá", allProviders: "Tất cả provider", allProjects: "Tất cả dự án", allModels: "Tất cả model", provider: "Provider", project: "Dự án", model: "Model", reset: "Bỏ lọc",
5
15
  out: "Output token", cost: "Chi phí", costList: "Chi phí niêm yết", sess: "Phiên", cache: "Đọc từ cache", saved: "Cache tiết kiệm", bars: "Dạng cột", areas: "Dạng vùng", shares: "Mỗi cột 100%", savedTip: "So với gửi lại cả context làm input ở mỗi request, đã trừ phần ghi cache trả thêm", reread: (p: string) => `Đọc context: ${p} chi phí`, perM: "$ / 1M token", behave: "Mỗi model làm việc thế nào", bOut: "Output mỗi request", bThink: "Thinking trong output", bSteps: "Request mỗi lượt owner", bTools: "Tool call mỗi request", bFail: "Tool call lỗi", bSpeed: "Tốc độ output", oneModel: "Phiên chỉ dùng model này", speed: "Tốc độ", tps: "token/giây", vsPrev: "so với kỳ trước", noPrev: "chưa có kỳ trước",
6
16
  perDay: "Theo ngày", topProjects: "Dự án dùng nhiều nhất", seeAll: "Xem tất cả", hours: "Khung giờ làm việc", peak: "Cao điểm", perBreak: "Tốn thêm mỗi lần", onAverage: "trung bình", overHour: "Sau hơn 1 giờ", ofRebuilds: "số lần dựng lại", failed: "Lượt lỗi", ofCalls: (p: string) => `${p} số lượt gọi`, fromTool: (n: string) => `Từ ${n}`, ofFailures: "số lượt lỗi", otherModel: "Khác model đã gọi", ofSubagents: "số subagent", subCost: "Chi phí subagent", ofAllCost: (usd: string) => `${usd} trong tổng chi phí`, belowMain: "Thấp hơn mức phiên", aboveMain: "Cao hơn mức phiên", ofSubReq: "request của subagent", toolCount: "công cụ", weekend: "Cuối tuần", sameHour: "Phiên cùng giờ", atMost: (n: string) => `thường vậy, nhiều nhất ${n}`, perTurn: "Agent làm mỗi lượt owner", topSessions: "Phiên lớn nhất", dailyTable: "Bảng số liệu theo ngày", hourlyTable: "Bảng số liệu theo giờ",
@@ -20,9 +30,23 @@ export const T = {
20
30
  perReqAt: (b: string) => `Mỗi request ở ${b}`, whatAt: (b: string) => `so với ở ${b}`, noRequest: "Không có request trong transcript", under: (v: string) => `Dưới ${v}`, andOver: (v: string) => `Từ ${v}`,
21
31
  otherPoints: "Nén ở mốc khác", estimate: "Ước tính", estNotes: ["Mỗi phiên được chạy lại với mốc nén đó", "Chưa tính phần đọc lại file sau mỗi lần nén, nên mốc thấp hơn hiện tại thực tế tốn hơn số hiện", "Giá niêm yết"],
22
32
  allSessions: "Mọi phiên", long4: "Nén từ 4 lần", rebuildIdle: "Dựng lại sau khi nghỉ", compactsAtCol: "Nén ở", sessCompacted: "Phiên có nén", againstNow: "So với hiện tại", now: "hiện tại", byDefault: "mặc định", recorded: "Thực tế",
23
- recordedVal: (n: string, usd: string) => `${n} lần nén, ${usd} tiền nén`,
33
+ recordedVal: (n: string, usd: string) => `${n} lần nén · chi phí nén ước tính ${usd}`,
34
+ bootHint: "Lần đầu mất khoảng một phút. Những lần sau chỉ đọc phần mới.",
35
+ bootStepFind: "tìm transcript", bootStepRead: "đọc transcript", bootStepTotal: "tổng hợp số liệu",
36
+ bootChipFind: "Tìm", bootChipRead: "Đọc", bootChipTotal: "Tổng hợp",
37
+ bootFiles: "file", bootLoadData: "tải dữ liệu", bootFinding: "đang tìm", bootTotalling: "tổng hợp",
24
38
  refresh: "Làm mới", scanning: "Đang quét…", bootFind: "Đang tìm transcript…", bootFirst: "Đang đọc transcript lần đầu", bootRebuild: "Đang dựng lại dữ liệu sau khi cập nhật", bootUpdate: "Đang quét transcript mới", bootFinish: "Đang tổng hợp số liệu…", transcripts: "transcript", retry: "Thử lại", scanNew: (n: number) => `${n} phiên mới`, scanFail: "Quét lỗi", loadFail: "Không đọc được dữ liệu", loading: "Đang tải…" },
25
- en: { usage: "Usage", overview: "Overview", projects: "Projects", sessions: "Sessions", models: "Models & effort", subagents: "Subagents", activity: "Activity",
39
+ en: {
40
+ sessionsByCost: "View sessions by cost", sessionsByOutput: "View sessions by output tokens",
41
+ activeDay: "Day with activity", viewDaySessions: "View sessions from this day",
42
+ usageCost: "Usage cost", costExplanation: "Uses recorded cost when available, or an estimate from model list prices. Your actual bill may differ.",
43
+ sessionsWithRebuild: "Sessions with cache rebuilds", sessionsWithCompaction: "Sessions with compaction", sessionsWithSubagent: "Sessions with subagent activity", clearSessionScope: "Clear session scope",
44
+ sessionDetails: "Session details", sessionUnavailable: "This session could not be found in the displayed data.", wholeSession: "Figures for the whole session.", providerOutputShare: "Share of total output tokens", modelBreakdown: "Breakdown by model", viewSessions: "View sessions", projectComparison: "Comparing all projects in this period", selectedProject: "Selected project", shareTotalCost: "Share of total cost", estimatedCost: "Estimated cost",
45
+ palette: "Command palette", palettePlaceholder: "Filter, find a session or run a command…", palFilters: "Suggested filters", palSessions: "Sessions", palCommands: "Commands", shortcuts: "Keyboard shortcuts", kHelp: "Help", kSearch: "Search", kCommands: "Commands", kViews: "Views", kRescan: "Rescan", toggleLanguage: "Switch language",
46
+ noProviders: "No provider data found yet", noProvidersHelp: "llmtop reads local transcripts. Run a session, then rescan.", configHelp: "Configuration guide", configHelpBody: "Configure providers in llmtop.config.json or via LLMTOP_CONFIG, then reopen the dashboard.", loadFailHelp: "Check that llmtop serve is running, then retry.", scanDetails: "Details", widenTo: (n: string) => `Widen to ${n} days`, lastSeen: (d: string) => `Last seen: ${d}`, dropFilter: (x: string) => `Drop ${x}`, noMatch: (q: string) => `No session matches “${q}”`, searchAll: "Search all time", scopeAllMatches: (n: string) => `${n} matching sessions across all time`,
47
+ filters: "Filters", filterModels: "Filter models…", apply: "Apply", back: "Back", showSessions: (n: string) => `Show ${n} sessions`, comparedWith: (r: string) => `Compared with: ${r}`, avgPerDay: "avg/day", onlyProvider: (p: string) => `Only ${p} found on this machine — bars split by model`, reqPerHour: "Requests per hour", succeeded: "succeeded", source: "Source", subRequests: "Subagent requests", sameMain: "Same as session level", addFilter: "+ Add filter", newest: "Newest",
48
+ settings: "Settings", style: "Style", styleClassic: "Classic", styleConsole: "Console", styleDonut: "Donut", styleClassicDesc: "Sidebar and KPI cards", styleConsoleDesc: "htop-like, mono, keyboard", styleDonutDesc: "Big shapes and numbers", providersShown: "Providers shown · detected on this machine", rescanProviders: "Rescan for new providers", close: "Close",
49
+ usage: "Usage", overview: "Overview", projects: "Projects", sessions: "Sessions", models: "Models & effort", subagents: "Subagents", activity: "Activity",
26
50
  scanned: "Scanned", untitled: "(untitled)", costUnknown: "No cost record from the host", costEstimated: "No cost record from the host; estimated from the price table", costPartial: "The host marked this cost incomplete", today: "Today", perHour: "Per hour", hour: "Hour", d7: "7 days", d14: "14 days", d30: "30 days", all: "All", dates: "Date range", prevMonth: "Previous month", nextMonth: "Next month", clear: "Clear", allProviders: "All providers", allProjects: "All projects", allModels: "All models", provider: "Provider", project: "Project", model: "Model", reset: "Clear filters",
27
51
  out: "Output tokens", cost: "Cost", costList: "List-price cost", sess: "Sessions", cache: "Read from cache", saved: "Saved by cache", bars: "Columns", areas: "Areas", shares: "Each column as 100%", savedTip: "Against sending the whole context as input on every request, less what cache writes cost extra", reread: (p: string) => `Reading context: ${p} of cost`, perM: "$ / 1M tokens", behave: "How each model works", bOut: "Output per request", bThink: "Thinking share of output", bSteps: "Requests per owner turn", bTools: "Tool calls per request", bFail: "Failed tool calls", bSpeed: "Output speed", oneModel: "Sessions on this model only", speed: "Speed", tps: "tokens/s", vsPrev: "vs prev. period", noPrev: "no previous period",
28
52
  perDay: "Per day", topProjects: "Top projects", seeAll: "See all", hours: "Working hours", peak: "Peak", perBreak: "Extra per rebuild", onAverage: "on average", overHour: "After over an hour", ofRebuilds: "of rebuilds", failed: "Failed calls", ofCalls: (p: string) => `${p} of calls`, fromTool: (n: string) => `From ${n}`, ofFailures: "of failures", otherModel: "On another model", ofSubagents: "of subagents", subCost: "Subagent cost", ofAllCost: (usd: string) => `${usd} of all cost`, belowMain: "Below session level", aboveMain: "Above session level", ofSubReq: "of subagent requests", toolCount: "tools", weekend: "Weekends", sameHour: "Same-hour sessions", atMost: (n: string) => `typical, at most ${n}`, perTurn: "Agent work per owner turn", topSessions: "Largest sessions", dailyTable: "Daily figures", hourlyTable: "Hourly figures",
@@ -42,7 +66,11 @@ export const T = {
42
66
  perReqAt: (b: string) => `Per request at ${b}`, whatAt: (b: string) => `what it is at ${b}`, noRequest: "No request in the transcript", under: (v: string) => `Under ${v}`, andOver: (v: string) => `${v} and over`,
43
67
  otherPoints: "Compacting at other points", estimate: "Estimate", estNotes: ["Each session replayed with compaction at that point", "Files read again after a compaction are not counted, so points below now cost more than shown", "List prices"],
44
68
  allSessions: "All sessions", long4: "Compacted 4+ times", rebuildIdle: "Rebuild after idle", compactsAtCol: "Compacts at", sessCompacted: "Sessions compacted", againstNow: "Against now", now: "now", byDefault: "default", recorded: "Recorded",
45
- recordedVal: (n: string, usd: string) => `${n} compactions, ${usd} compacting`,
69
+ recordedVal: (n: string, usd: string) => `${n} compactions · estimated compaction cost ${usd}`,
70
+ bootHint: "The first scan takes about a minute. Later scans only read what is new.",
71
+ bootStepFind: "find transcripts", bootStepRead: "read transcripts", bootStepTotal: "put the figures together",
72
+ bootChipFind: "Find", bootChipRead: "Read", bootChipTotal: "Total",
73
+ bootFiles: "files", bootLoadData: "load data", bootFinding: "finding", bootTotalling: "totalling",
46
74
  refresh: "Refresh", scanning: "Scanning…", bootFind: "Finding transcripts…", bootFirst: "Reading your transcripts for the first time", bootRebuild: "Rebuilding the data after an update", bootUpdate: "Scanning new transcripts", bootFinish: "Putting the figures together…", transcripts: "transcripts", retry: "Try again", scanNew: (n: number) => `${n} new sessions`, scanFail: "Scan failed", loadFail: "Cannot read the data", loading: "Loading…" },
47
75
  };
48
76
 
@@ -1,9 +1,18 @@
1
1
  import { createRoot } from "react-dom/client";
2
2
  import { App } from "./App.tsx";
3
- import "@fontsource-variable/montserrat";
4
- import "@fontsource-variable/roboto-mono";
3
+ import { readLanguage, readStyle, readTheme, store } from "./shell/preferences.ts";
5
4
  import "./styles.css";
5
+ import "./styles/tokens.css";
6
+ import "./styles/fonts.css";
7
+ import "./styles/shell.css";
8
+ import "./styles/console.css";
9
+ import "./styles/donut.css";
6
10
  import { installTip } from "./tip.ts";
7
11
 
12
+ const { documentElement } = document;
13
+ documentElement.lang = readLanguage();
14
+ documentElement.dataset.style = readStyle(store.get("llmtop.style"));
15
+ documentElement.dataset.theme = readTheme();
16
+
8
17
  installTip(document.getElementById("tip")!);
9
18
  createRoot(document.getElementById("root")!).render(<App />);
@@ -11,7 +11,7 @@
11
11
 
12
12
  export type Run = [effort: number, requests: number];
13
13
  export type Session = {
14
- id: string; pr?: number; p: number; title: string; day: string; hour: number; min: number; dur: number; api: number; tool: number;
14
+ id: string; key?: string; pr?: number; p: number; title: string; day: string; hour: number; min: number; dur: number; api: number; tool: number;
15
15
  owner: number; compact: number; la: number; lr: number; parent: number; subs: unknown[]; cost: number;
16
16
  costState: "ok" | "unknown" | "incomplete" | "estimated"; out: number; runs: Run[];
17
17
  // Models without a price row, and models whose host cost misses the price table, in this session.