@linxiraos/pi-stats 1.4.7 → 1.4.10

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.
@@ -10,6 +10,10 @@ export declare function getCostDashboardStats(range?: TimeRange, signal?: AbortS
10
10
  export declare function getRecentRequests(limit?: number, signal?: AbortSignal): Promise<MessageStats[]>;
11
11
  export declare function getRecentErrors(range?: TimeRange, limit?: number, signal?: AbortSignal): Promise<MessageStats[]>;
12
12
  export declare function getRequestDetails(id: number, signal?: AbortSignal): Promise<RequestDetails>;
13
+ /** Whether the page may close the dashboard (`zetacode stats` shown in place of a Tern block). */
14
+ export declare function getClosable(signal?: AbortSignal): Promise<boolean>;
15
+ /** Close the dashboard: its host takes the page away and stops serving it. */
16
+ export declare function closeDashboard(): Promise<void>;
13
17
  /** Ask the server to start a background sync; progress arrives on the `/api/events` stream. */
14
18
  export declare function requestSync(): Promise<LiveStatus>;
15
19
  export declare function getFrustrationDashboardStats(range?: TimeRange, signal?: AbortSignal): Promise<FrustrationDashboardStats>;
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Close, while the host shows the dashboard in place of its terminal
3
+ * (`zetacode stats` in Tern), where the page is the only way out: the button, Esc,
4
+ * or Ctrl+C with nothing selected, as in the terminal it covers. Renders
5
+ * nothing anywhere else.
6
+ */
7
+ export declare function CloseButton(): import("react").JSX.Element | null;
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Guards for the dashboard's page-wide keys (`Shell`'s shortcuts,
3
+ * `CloseButton`'s Esc and Ctrl+C): they stay out of fields being typed
4
+ * in and out of open dialogs, which own their keys.
5
+ */
6
+ /** Whether `target` takes typing (a field, a select, editable content). */
7
+ export declare function isTypingTarget(target: EventTarget | null): boolean;
8
+ /** Whether a modal dialog or drawer is open. */
9
+ export declare function isDialogOpen(): boolean;
@@ -4,7 +4,7 @@ export { closeDb } from "./db.js";
4
4
  export { refreshRollups } from "./rollup.js";
5
5
  export type { StatsJudge, StatsJudgeProvider } from "./frustration.js";
6
6
  export { getGainDashboardStats } from "./gain-aggregator.js";
7
- export { formatStatsDashboardUrl, type StartServerOptions, startServer } from "./server.js";
7
+ export { formatStatsDashboardUrl, type StartServerOptions, setStatsCloseHandler, startServer } from "./server.js";
8
8
  export type { GainDashboardStats, GainSource, GainSourceTotals, GainTimeSeriesPoint } from "./shared-types.js";
9
9
  export type { AggregatedStats, DashboardStats, FolderStats, MessageStats, ModelPerformancePoint, ModelStats, ModelTimeSeriesPoint, TimeSeriesPoint, ToolDashboardStats, ToolModelStats, ToolTimeSeriesPoint, ToolUsageStats, } from "./types.js";
10
10
  /**
@@ -1,4 +1,11 @@
1
1
  import { type StatsJudgeProvider } from "./frustration.js";
2
+ /**
3
+ * Let the page close the dashboard: while `close` is set, it shows a Close
4
+ * button (and takes Esc and Ctrl+C) that calls it. `zetacode stats` sets it while
5
+ * Tern shows the page in place of the block it runs in, where the page has no
6
+ * way out of its own; `undefined` takes Close away again.
7
+ */
8
+ export declare function setStatsCloseHandler(close: (() => void) | undefined): void;
2
9
  /**
3
10
  * Handle API requests.
4
11
  */
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "type": "module",
3
3
  "name": "@linxiraos/pi-stats",
4
- "version": "1.4.7",
4
+ "version": "1.4.10",
5
5
  "description": "Local observability dashboard for omp AI usage statistics",
6
6
  "homepage": "https://linxira-os.github.io/zeta/",
7
7
  "author": "Linxira-OS",
@@ -39,9 +39,9 @@
39
39
  "fmt": "oxfmt --no-error-on-unmatched-pattern 'src/**/*.{ts,tsx}' '{test,bench,examples,scripts}/**/*.ts' '*.ts'"
40
40
  },
41
41
  "dependencies": {
42
- "@linxiraos/pi-ai": "1.4.7",
43
- "@linxiraos/pi-catalog": "1.4.7",
44
- "@linxiraos/pi-utils": "1.4.7",
42
+ "@linxiraos/pi-ai": "1.4.10",
43
+ "@linxiraos/pi-catalog": "1.4.10",
44
+ "@linxiraos/pi-utils": "1.4.10",
45
45
  "lucide-react": "^1.24.0",
46
46
  "react": "19.2.7",
47
47
  "react-dom": "19.2.7"
@@ -81,10 +81,6 @@
81
81
  "types": "./dist/types/client/*.d.ts",
82
82
  "import": "./src/client/*.ts"
83
83
  },
84
- "./client/components/*": {
85
- "types": "./dist/types/client/components/*.d.ts",
86
- "import": "./src/client/components/*.ts"
87
- },
88
84
  "./*.js": "./src/*.ts",
89
85
  "./client/traces": {
90
86
  "types": "./dist/types/client/traces/index.d.ts",
package/src/client/api.ts CHANGED
@@ -121,6 +121,19 @@ export async function getRequestDetails(id: number, signal?: AbortSignal): Promi
121
121
  return fetchJson<RequestDetails>(`${API_BASE}/request/${id}`, { signal });
122
122
  }
123
123
 
124
+ /** Whether the page may close the dashboard (`zetacode stats` shown in place of a Tern block). */
125
+ export async function getClosable(signal?: AbortSignal): Promise<boolean> {
126
+ const { closable } = await fetchJson<{ closable: boolean }>(`${API_BASE}/close`, { signal });
127
+ return closable;
128
+ }
129
+
130
+ /** Close the dashboard: its host takes the page away and stops serving it. */
131
+ export async function closeDashboard(): Promise<void> {
132
+ const endpoint = `${API_BASE}/close`;
133
+ const res = await fetch(endpoint, { method: "POST", headers: ACTION_HEADERS });
134
+ if (!res.ok) throw new ApiError(res.status, endpoint, await readErrorMessage(res, endpoint));
135
+ }
136
+
124
137
  /** Ask the server to start a background sync; progress arrives on the `/api/events` stream. */
125
138
  export async function requestSync(): Promise<LiveStatus> {
126
139
  return fetchJson<LiveStatus>(`${API_BASE}/sync`, { method: "POST" });
@@ -0,0 +1,56 @@
1
+ import { X } from "lucide-react";
2
+ import { useEffect, useState } from "react";
3
+ import { closeDashboard, getClosable } from "../api";
4
+ import { isDialogOpen, isTypingTarget } from "./keys";
5
+
6
+ /**
7
+ * Close, while the host shows the dashboard in place of its terminal
8
+ * (`zetacode stats` in Tern), where the page is the only way out: the button, Esc,
9
+ * or Ctrl+C with nothing selected, as in the terminal it covers. Renders
10
+ * nothing anywhere else.
11
+ */
12
+ export function CloseButton() {
13
+ const closable = useClosable();
14
+
15
+ useEffect(() => {
16
+ if (!closable) return;
17
+ const onKey = (e: KeyboardEvent) => {
18
+ if (!isCloseKey(e)) return;
19
+ e.preventDefault();
20
+ close();
21
+ };
22
+ window.addEventListener("keydown", onKey);
23
+ return () => window.removeEventListener("keydown", onKey);
24
+ }, [closable]);
25
+
26
+ if (!closable) return null;
27
+ return (
28
+ <button type="button" className="btn" data-variant="ghost" onClick={close} title="Close the dashboard (Esc)">
29
+ <X size={15} />
30
+ Close
31
+ <span className="kbd">Esc</span>
32
+ </button>
33
+ );
34
+ }
35
+
36
+ function close(): void {
37
+ closeDashboard().catch(error => console.error("Closing the dashboard failed", error));
38
+ }
39
+
40
+ function useClosable(): boolean {
41
+ const [closable, setClosable] = useState(false);
42
+ useEffect(() => {
43
+ const abort = new AbortController();
44
+ getClosable(abort.signal).then(setClosable, () => {});
45
+ return () => abort.abort();
46
+ }, []);
47
+ return closable;
48
+ }
49
+
50
+ /** Esc, or Ctrl+C with no text selected (with a selection it copies), outside fields and dialogs. */
51
+ function isCloseKey(e: KeyboardEvent): boolean {
52
+ if (e.defaultPrevented || e.altKey || e.metaKey || e.shiftKey) return false;
53
+ if (isTypingTarget(e.target) || isDialogOpen()) return false;
54
+ if (e.key === "Escape") return !e.ctrlKey;
55
+ return e.ctrlKey && e.key.toLowerCase() === "c" && !window.getSelection()?.toString();
56
+ }
@@ -6,6 +6,8 @@ import { useLocale } from "../i18n/useLocale";
6
6
  import { useLiveStatus } from "../data/live";
7
7
  import type { TimeRange } from "../types";
8
8
  import { Segmented } from "../ui";
9
+ import { CloseButton } from "./CloseButton";
10
+ import { isDialogOpen, isTypingTarget } from "./keys";
9
11
  import { LanguageToggle } from "./LanguageToggle";
10
12
  import { LiveChip } from "./LiveChip";
11
13
  import { type DashboardSection, NAV } from "./nav";
@@ -98,6 +100,7 @@ export function Shell({ section, onSectionChange, range, onRangeChange, children
98
100
  />
99
101
  <LanguageToggle />
100
102
  <ThemeToggle />
103
+ <CloseButton />
101
104
  </div>
102
105
  {progress !== undefined && (
103
106
  <div className="topbar-progress">
@@ -164,17 +167,7 @@ function useShortcuts(onSection: (section: DashboardSection) => void, onRange: (
164
167
  let pendingG = 0;
165
168
  const onKey = (e: KeyboardEvent) => {
166
169
  if (e.metaKey || e.ctrlKey || e.altKey || e.defaultPrevented) return;
167
- const target = e.target;
168
- if (
169
- target instanceof HTMLElement &&
170
- (target.isContentEditable ||
171
- target.tagName === "INPUT" ||
172
- target.tagName === "TEXTAREA" ||
173
- target.tagName === "SELECT")
174
- ) {
175
- return;
176
- }
177
- if (document.querySelector('[aria-modal="true"]')) return;
170
+ if (isTypingTarget(e.target) || isDialogOpen()) return;
178
171
  const key = e.key.toLowerCase();
179
172
  if (pendingG && Date.now() - pendingG < 1200) {
180
173
  pendingG = 0;
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Guards for the dashboard's page-wide keys (`Shell`'s shortcuts,
3
+ * `CloseButton`'s Esc and Ctrl+C): they stay out of fields being typed
4
+ * in and out of open dialogs, which own their keys.
5
+ */
6
+
7
+ /** Whether `target` takes typing (a field, a select, editable content). */
8
+ export function isTypingTarget(target: EventTarget | null): boolean {
9
+ return (
10
+ target instanceof HTMLElement &&
11
+ (target.isContentEditable ||
12
+ target.tagName === "INPUT" ||
13
+ target.tagName === "TEXTAREA" ||
14
+ target.tagName === "SELECT")
15
+ );
16
+ }
17
+
18
+ /** Whether a modal dialog or drawer is open. */
19
+ export function isDialogOpen(): boolean {
20
+ return document.querySelector('[aria-modal="true"]') !== null;
21
+ }
@@ -15,6 +15,7 @@
15
15
  * can resolve to that same object; an unchanged reference does not re-render.
16
16
  */
17
17
 
18
+ import { toError } from "@linxiraos/pi-utils/type-guards";
18
19
  import { startTransition, useCallback, useEffect, useReducer, useRef, useState } from "react";
19
20
  import { currentLiveVersion, useLiveVersion } from "./live";
20
21
  import { cachedEntry, type Inflight, inflightRequest, loadQuery, type QueryFetcher, releaseQuery } from "./query-store";
@@ -60,6 +61,7 @@ export function useQuery<T>(key: readonly unknown[], fetcher: QueryFetcher<T>, o
60
61
  const version = useLiveVersion(enabled);
61
62
 
62
63
  const [, rerender] = useReducer((n: number) => n + 1, 0);
64
+ const [settled, recheck] = useReducer((n: number) => n + 1, 0);
63
65
  const [error, setError] = useState<{ key: string; error: Error } | null>(null);
64
66
  const [refreshing, setRefreshing] = useState(false);
65
67
 
@@ -82,8 +84,10 @@ export function useQuery<T>(key: readonly unknown[], fetcher: QueryFetcher<T>, o
82
84
  waiting.current = { key: targetKey, request };
83
85
  // Join the new request before leaving the old one, so a shared request isn't aborted in between.
84
86
  if (current) releaseQuery(current.key, current.request);
87
+ let succeeded = false;
85
88
  request.promise
86
89
  .then(data => {
90
+ succeeded = true;
87
91
  if (keyRef.current !== targetKey) return;
88
92
  // Revalidated to the very same object: nothing on screen changes.
89
93
  if (data === shownBefore) {
@@ -97,11 +101,15 @@ export function useQuery<T>(key: readonly unknown[], fetcher: QueryFetcher<T>, o
97
101
  })
98
102
  .catch((err: unknown) => {
99
103
  if (keyRef.current !== targetKey || request.controller.signal.aborted) return;
100
- setError({ key: targetKey, error: err instanceof Error ? err : new Error(String(err)) });
104
+ setError({ key: targetKey, error: toError(err) });
101
105
  })
102
106
  .finally(() => {
103
- if (waiting.current?.request === request) waiting.current = null;
104
- if (keyRef.current === targetKey) setRefreshing(false);
107
+ if (waiting.current?.request !== request) return;
108
+ waiting.current = null;
109
+ if (keyRef.current !== targetKey) return;
110
+ setRefreshing(false);
111
+ // A newer live version may have arrived while this older request was in flight.
112
+ if (succeeded && (cachedEntry(targetKey)?.version ?? -1) < currentLiveVersion()) recheck();
105
113
  });
106
114
  }, []);
107
115
 
@@ -128,7 +136,7 @@ export function useQuery<T>(key: readonly unknown[], fetcher: QueryFetcher<T>, o
128
136
  }
129
137
  const timer = setTimeout(() => run(keyString), wait);
130
138
  return () => clearTimeout(timer);
131
- }, [keyString, enabled, version, run, leave]);
139
+ }, [keyString, enabled, version, settled, run, leave]);
132
140
 
133
141
  useEffect(() => {
134
142
  if (!enabled || !pollMs) return;
@@ -0,0 +1,8 @@
1
+ import "react";
2
+
3
+ declare module "react" {
4
+ /** Custom properties (`--arm`, `--i` …) in `style` objects, which React passes through to the element. */
5
+ interface CSSProperties {
6
+ [property: `--${string}`]: string | number | undefined;
7
+ }
8
+ }
@@ -4,6 +4,7 @@
4
4
  * + text blocks, tool args/result, user text, subagent task text.
5
5
  */
6
6
 
7
+ import { toError } from "@linxiraos/pi-utils/type-guards";
7
8
  import { Check, Copy, X } from "lucide-react";
8
9
  import { type ReactNode, useEffect, useRef, useState } from "react";
9
10
  import { getSessionEntryDetail } from "../api";
@@ -113,7 +114,7 @@ export function SpanDrawer({
113
114
  })
114
115
  .catch(err => {
115
116
  if (controller.signal.aborted) return;
116
- setError(err instanceof Error ? err : new Error(String(err)));
117
+ setError(toError(err));
117
118
  })
118
119
  .finally(() => {
119
120
  if (!controller.signal.aborted) setLoading(false);
@@ -104,7 +104,7 @@ export const TranscriptList = memo(function TranscriptList({
104
104
  const chipText = row.span?.kind ?? row.marker?.kind ?? "";
105
105
  const rowContent = (
106
106
  <>
107
- <span className="traces-kind" style={{ "--traces-kind-color": color } as React.CSSProperties}>
107
+ <span className="traces-kind" style={{ "--traces-kind-color": color }}>
108
108
  {chipText}
109
109
  </span>
110
110
  {row.depth > 0 && (
@@ -1,4 +1,4 @@
1
- import type { CSSProperties, ReactNode } from "react";
1
+ import type { ReactNode } from "react";
2
2
 
3
3
  export interface CardProps {
4
4
  title?: ReactNode;
@@ -22,7 +22,7 @@ export function Card({ title, description, actions, flush, footer, className, in
22
22
  return (
23
23
  <section
24
24
  className={className ? `card rise ${className}` : "card rise"}
25
- style={index !== undefined ? ({ "--i": index } as CSSProperties) : undefined}
25
+ style={index !== undefined ? { "--i": index } : undefined}
26
26
  >
27
27
  {hasHeader && (
28
28
  <header className="card-header">
@@ -1,5 +1,5 @@
1
1
  import { X } from "lucide-react";
2
- import { type CSSProperties, type ReactNode, useEffect, useRef } from "react";
2
+ import { type ReactNode, useEffect, useRef } from "react";
3
3
  import { createPortal } from "react-dom";
4
4
 
5
5
  export interface DrawerProps {
@@ -50,7 +50,7 @@ export function Drawer({ open, onClose, title, subtitle, actions, width, childre
50
50
  role="dialog"
51
51
  aria-modal="true"
52
52
  tabIndex={-1}
53
- style={width !== undefined ? ({ "--drawer-w": `${width}px` } as CSSProperties) : undefined}
53
+ style={width !== undefined ? { "--drawer-w": `${width}px` } : undefined}
54
54
  >
55
55
  <header className="drawer-header">
56
56
  <div className="drawer-titles">
@@ -1,4 +1,4 @@
1
- import { type CSSProperties, type ReactNode, useEffect, useRef, useState } from "react";
1
+ import { type ReactNode, useEffect, useRef, useState } from "react";
2
2
  import { Sparkline } from "../charts/Sparkline";
3
3
 
4
4
  export interface StatDelta {
@@ -58,10 +58,7 @@ export interface StatGridProps {
58
58
  /** Tiles sharing one card, separated by hairlines. */
59
59
  export function StatGrid({ min, children }: StatGridProps) {
60
60
  return (
61
- <div
62
- className="stat-grid rise"
63
- style={min !== undefined ? ({ "--stat-min": `${min}px` } as CSSProperties) : undefined}
64
- >
61
+ <div className="stat-grid rise" style={min !== undefined ? { "--stat-min": `${min}px` } : undefined}>
65
62
  {children}
66
63
  </div>
67
64
  );
package/src/db.ts CHANGED
@@ -108,7 +108,8 @@ const FORK_DEDUPE_KEY = "fork_dedupe_v1";
108
108
  // v2: tool-name sanitization at ingest (see `sanitizeToolName` in parser.ts)
109
109
  // collapses provider-side garbage names; a full re-parse replaces the polluted
110
110
  // rows already stored in existing databases.
111
- const TOOL_CALLS_BACKFILL_KEY = "tool_calls_v2";
111
+ // v3: reclassify synthetic non-executions so historical tool error rates are corrected.
112
+ const TOOL_CALLS_BACKFILL_KEY = "tool_calls_v3";
112
113
  // Older ingests dropped `Usage.orchestration` (never a stored column) when
113
114
  // pricing, so subscription models billed on orchestration tokens — multi-agent
114
115
  // Grok most notably — were priced from conversation buckets alone and could not
package/src/index.ts CHANGED
@@ -28,7 +28,7 @@ export { closeDb } from "./db";
28
28
  export { refreshRollups } from "./rollup";
29
29
  export type { StatsJudge, StatsJudgeProvider } from "./frustration";
30
30
  export { getGainDashboardStats } from "./gain-aggregator";
31
- export { formatStatsDashboardUrl, type StartServerOptions, startServer } from "./server";
31
+ export { formatStatsDashboardUrl, type StartServerOptions, setStatsCloseHandler, startServer } from "./server";
32
32
  export type { GainDashboardStats, GainSource, GainSourceTotals, GainTimeSeriesPoint } from "./shared-types";
33
33
  export type {
34
34
  AggregatedStats,
package/src/parser.ts CHANGED
@@ -481,6 +481,13 @@ function sanitizeToolName(name: string): string | null {
481
481
  return candidate.length > 0 ? candidate : null;
482
482
  }
483
483
 
484
+ /** A call the agent loop skipped carries a synthetic `executed: false` result: it never ran, so it is no tool error. */
485
+ function isToolExecutionError(message: { isError?: unknown; details?: unknown }): boolean {
486
+ if (message.isError !== true) return false;
487
+ const details = message.details as { __synthetic?: unknown; executed?: unknown } | null | undefined;
488
+ return !(details?.__synthetic === true && details.executed === false);
489
+ }
490
+
484
491
  /**
485
492
  * Build the result linkage for a `toolResult` entry: text characters fed back
486
493
  * into context plus the error flag, keyed to the originating call.
@@ -500,7 +507,7 @@ function extractToolResultLink(sessionFile: string, entry: SessionMessageEntry):
500
507
  sessionFile,
501
508
  toolCallId: msg.toolCallId,
502
509
  resultChars,
503
- isError: msg.isError === true,
510
+ isError: isToolExecutionError(msg),
504
511
  };
505
512
  }
506
513
 
package/src/server.ts CHANGED
@@ -167,6 +167,19 @@ const ensureClientBuild = async () => {
167
167
  */
168
168
  const STATS_ACTION_HEADER = "X-Zeta-Stats-Action";
169
169
 
170
+ /** What the page's Close calls; unset, the page offers none. */
171
+ let closeHandler: (() => void) | undefined;
172
+
173
+ /**
174
+ * Let the page close the dashboard: while `close` is set, it shows a Close
175
+ * button (and takes Esc and Ctrl+C) that calls it. `zetacode stats` sets it while
176
+ * Tern shows the page in place of the block it runs in, where the page has no
177
+ * way out of its own; `undefined` takes Close away again.
178
+ */
179
+ export function setStatsCloseHandler(close: (() => void) | undefined): void {
180
+ closeHandler = close;
181
+ }
182
+
170
183
  /**
171
184
  * Handle API requests.
172
185
  */
@@ -272,6 +285,17 @@ export async function handleApi(req: Request): Promise<Response> {
272
285
  return Response.json(details);
273
286
  }
274
287
 
288
+ if (path === "/api/close") {
289
+ if (req.method === "GET") return Response.json({ closable: closeHandler !== undefined });
290
+ if (req.method !== "POST") return Response.json({ error: "GET or POST required" }, { status: 405 });
291
+ if (req.headers.get(STATS_ACTION_HEADER) !== "1") {
292
+ return Response.json({ error: `${STATS_ACTION_HEADER}: 1 header required` }, { status: 403 });
293
+ }
294
+ if (!closeHandler) return Response.json({ error: "this dashboard is not closed from its page" }, { status: 404 });
295
+ closeHandler();
296
+ return new Response(null, { status: 202 });
297
+ }
298
+
275
299
  if (path === "/api/sync") {
276
300
  if (req.method !== "POST") return Response.json({ error: "POST required" }, { status: 405 });
277
301
  statsLive().requestSync();