@linxiraos/pi-stats 1.4.6 → 1.4.9

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 (47) hide show
  1. package/CHANGELOG.md +15 -1
  2. package/README.md +18 -18
  3. package/dist/client/index.js +86 -86
  4. package/dist/types/chunked-insert.d.ts +32 -0
  5. package/dist/types/client/api.d.ts +4 -0
  6. package/dist/types/client/app/CloseButton.d.ts +7 -0
  7. package/dist/types/client/app/keys.d.ts +9 -0
  8. package/dist/types/client/traces/SpanDrawer.d.ts +9 -3
  9. package/dist/types/client/traces/TimelineCanvas.d.ts +3 -1
  10. package/dist/types/client/traces/TraceView.d.ts +13 -0
  11. package/dist/types/client/traces/index.d.ts +5 -0
  12. package/dist/types/client/traces/trace-colors.d.ts +3 -1
  13. package/dist/types/client/ui/SearchInput.d.ts +2 -1
  14. package/dist/types/db.d.ts +5 -5
  15. package/dist/types/index.d.ts +1 -1
  16. package/dist/types/parser.d.ts +1 -1
  17. package/dist/types/port-conflict.d.ts +9 -3
  18. package/dist/types/server.d.ts +14 -3
  19. package/dist/types/shared-types.d.ts +3 -2
  20. package/dist/types/trace.d.ts +27 -1
  21. package/dist/types/types.d.ts +6 -1
  22. package/package.json +12 -10
  23. package/src/chunked-insert.ts +89 -0
  24. package/src/client/api.ts +13 -0
  25. package/src/client/app/CloseButton.tsx +56 -0
  26. package/src/client/app/Shell.tsx +4 -11
  27. package/src/client/app/keys.ts +21 -0
  28. package/src/client/data/query.ts +12 -4
  29. package/src/client/react-css.d.ts +8 -0
  30. package/src/client/traces/SpanDrawer.tsx +58 -10
  31. package/src/client/traces/TimelineCanvas.tsx +13 -4
  32. package/src/client/traces/TraceView.tsx +171 -153
  33. package/src/client/traces/TranscriptList.tsx +1 -1
  34. package/src/client/traces/index.ts +5 -0
  35. package/src/client/traces/trace-colors.ts +14 -10
  36. package/src/client/ui/Card.tsx +2 -2
  37. package/src/client/ui/Drawer.tsx +2 -2
  38. package/src/client/ui/SearchInput.tsx +9 -1
  39. package/src/client/ui/Stat.tsx +2 -5
  40. package/src/db.ts +203 -151
  41. package/src/index.ts +1 -1
  42. package/src/parser.ts +22 -6
  43. package/src/port-conflict.ts +67 -30
  44. package/src/server.ts +63 -31
  45. package/src/shared-types.ts +3 -2
  46. package/src/trace.ts +119 -35
  47. package/src/types.ts +6 -1
@@ -0,0 +1,32 @@
1
+ import type { Database, SQLQueryBindings } from "bun:sqlite";
2
+ /** Shape of one ingest table write; see {@link ChunkedInsert}. */
3
+ export interface ChunkedInsertSpec {
4
+ /** `INSERT` or `INSERT OR IGNORE`. */
5
+ verb: "INSERT" | "INSERT OR IGNORE";
6
+ table: string;
7
+ columns: readonly string[];
8
+ /** Columns naming one transcript entry; fork copies repeat them under another `session_file`. */
9
+ identity: readonly string[];
10
+ /** Trailing `ON CONFLICT … DO UPDATE` clause, if any. */
11
+ upsert?: string;
12
+ }
13
+ /**
14
+ * Multi-row writer for one ingest table: buffers rows and writes them as
15
+ * `INSERT … VALUES (…), (…)` chunks, so the per-statement costs (trigger
16
+ * program setup, statement journal, the temp b-tree SQLite stages trigger
17
+ * inserts through) are paid per chunk instead of per row.
18
+ *
19
+ * Every row passes a first-writer-wins fork guard: forked transcripts copy
20
+ * their parent's entries verbatim, so a row whose identity another
21
+ * `session_file` already stored is skipped. Buffered rows are invisible to
22
+ * that lookup, so a row colliding with a buffered row of another transcript
23
+ * flushes the buffer first; the stored outcome equals writing row by row.
24
+ */
25
+ export declare class ChunkedInsert {
26
+ #private;
27
+ constructor(database: Database, spec: ChunkedInsertSpec);
28
+ /** Buffer one row unless another transcript already owns `identity`. */
29
+ add(sessionFile: string, identity: readonly SQLQueryBindings[], values: readonly SQLQueryBindings[]): void;
30
+ /** Write the remaining rows; returns how many stored rows the writer inserted or updated. */
31
+ finish(): number;
32
+ }
@@ -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;
@@ -1,14 +1,20 @@
1
1
  /**
2
- * Detail drawer for a selected trace span. Fetches the full journal entry on
3
- * demand (`/api/session/entry`) and renders per-kind detail: model usage grid
2
+ * Detail drawer for a selected trace span. Loads the full journal entry on
3
+ * demand (live API or embedded snapshot) and renders per-kind detail: model usage grid
4
4
  * + text blocks, tool args/result, user text, subagent task text.
5
5
  */
6
6
  import type { TraceSpan, TraceTrack } from "../types.js";
7
+ export type TraceEntryLoader = (file: string, entryId: string, signal: AbortSignal) => Promise<{
8
+ entry: unknown;
9
+ }>;
7
10
  export interface SpanDrawerProps {
8
11
  span: TraceSpan | null;
9
12
  track: TraceTrack | null;
10
13
  onClose: () => void;
11
14
  /** Selects the first span of the given child track ("open child track"). */
12
15
  onOpenChildTrack?: (childTrackId: string) => void;
16
+ loadEntry?: TraceEntryLoader;
17
+ inline?: boolean;
18
+ onNavigate?: (trackId: string, entryId: string) => void;
13
19
  }
14
- export declare function SpanDrawer({ span, track, onClose, onOpenChildTrack }: SpanDrawerProps): import("react").JSX.Element | null;
20
+ export declare function SpanDrawer({ span, track, onClose, onOpenChildTrack, loadEntry, inline, onNavigate, }: SpanDrawerProps): import("react").JSX.Element | null;
@@ -27,6 +27,8 @@ export interface TimelineCanvasProps {
27
27
  collapsed: ReadonlySet<string>;
28
28
  onToggleCollapse: (trackId: string) => void;
29
29
  traceStart: number;
30
+ /** Live route focuses immediately; embedded viewers wait for user interaction. */
31
+ autoFocus?: boolean;
30
32
  }
31
33
  /** Per-lane span positions on the virtual axis, parallel to `LaneRow.spans`. */
32
34
  interface LaneAxis {
@@ -42,5 +44,5 @@ export declare function buildLaneAxes(layout: {
42
44
  }, scale: Pick<TraceScale, "toU">): LaneAxis[];
43
45
  /** First index whose running-max end reaches `u0`: every earlier span ends before the viewport. */
44
46
  export declare function firstVisible(maxEndU: Float64Array, u0: number): number;
45
- export declare function TimelineCanvas({ tracks, scale, viewport, onViewportChange, selected, onSelect, matchIds, collapsed, onToggleCollapse, traceStart, }: TimelineCanvasProps): import("react").JSX.Element;
47
+ export declare function TimelineCanvas({ tracks, scale, viewport, onViewportChange, selected, onSelect, matchIds, collapsed, onToggleCollapse, traceStart, autoFocus, }: TimelineCanvasProps): import("react").JSX.Element;
46
48
  export {};
@@ -3,9 +3,22 @@
3
3
  * flamegraph canvas, transcript list, tool aggregates, and the span drawer.
4
4
  * Owns the shared viewport/selection state so all pieces stay in sync.
5
5
  */
6
+ import type { SessionTrace } from "../types.js";
7
+ import { type TraceEntryLoader } from "./SpanDrawer.js";
6
8
  export interface TraceViewProps {
7
9
  file: string;
8
10
  active: boolean;
9
11
  onBack: () => void;
10
12
  }
11
13
  export declare function TraceView({ file, active, onBack }: TraceViewProps): import("react").JSX.Element;
14
+ /** Data and host integration supplied to the shared live/offline trace viewer. */
15
+ export interface SessionTraceViewProps {
16
+ trace: SessionTrace;
17
+ view?: "timeline" | "full";
18
+ loadEntry?: TraceEntryLoader;
19
+ /** Embedded viewers keep details inside their own layout, without a modal. */
20
+ embedded?: boolean;
21
+ onNavigate?: (trackId: string, entryId: string) => void;
22
+ }
23
+ /** Data-driven viewer shared by the live route and self-contained HTML exports. */
24
+ export declare function SessionTraceView({ trace, view, loadEntry, embedded, onNavigate, }: SessionTraceViewProps): import("react").JSX.Element;
@@ -0,0 +1,5 @@
1
+ /** Shared trace UI for live dashboards and embedded offline viewers. */
2
+ export type { SessionTrace } from "../types.js";
3
+ export type { TraceEntryLoader } from "./SpanDrawer.js";
4
+ export { SessionTraceView, type SessionTraceViewProps } from "./TraceView.js";
5
+ export { TraceThemeRoot } from "./trace-colors.js";
@@ -3,6 +3,8 @@
3
3
  * design tokens so canvas drawing follows the active theme.
4
4
  */
5
5
  import type { TraceSpanKind } from "../types.js";
6
+ /** Embedded viewers resolve canvas colors from their scoped style root. */
7
+ export declare const TraceThemeRoot: import("react").Context<HTMLElement | null>;
6
8
  export interface TraceTheme {
7
9
  /** Span fill per category. */
8
10
  category: Record<TraceSpanKind, string>;
@@ -32,6 +34,6 @@ export interface TraceTheme {
32
34
  export declare const CATEGORY_VARS: Record<TraceSpanKind, string>;
33
35
  /**
34
36
  * Current trace palette. Re-reads the tokens whenever the resolved theme
35
- * changes (store or a direct `data-theme` attribute write).
37
+ * changes, without loading the live dashboard's theme preference store.
36
38
  */
37
39
  export declare function useTraceTheme(): TraceTheme;
@@ -2,7 +2,8 @@ export interface SearchInputProps {
2
2
  value: string;
3
3
  onChange: (value: string) => void;
4
4
  placeholder?: string;
5
+ label?: string;
5
6
  width?: number;
6
7
  }
7
8
  /** Text filter with a leading search glyph. */
8
- export declare function SearchInput({ value, onChange, placeholder, width }: SearchInputProps): import("react").JSX.Element;
9
+ export declare function SearchInput({ value, onChange, placeholder, label, width, }: SearchInputProps): import("react").JSX.Element;
@@ -77,7 +77,7 @@ export declare function completeSessionSync(reconcile: boolean): void;
77
77
  * `provider`, token counts, and `responseId`. The `UNIQUE(session_file,
78
78
  * entry_id)` constraint alone keys each row by file, so without the guard
79
79
  * below the same provider request would land twice and inflate every
80
- * aggregate. The `WHERE NOT EXISTS` clause skips inserts whose
80
+ * aggregate. The {@link ChunkedInsert} fork guard skips inserts whose
81
81
  * `(entry_id, timestamp)` already exists under a different `session_file` —
82
82
  * first-write-wins across the lineage. Same-file re-syncs still hit the
83
83
  * `ON CONFLICT(session_file, entry_id)` upsert below, which re-derives the
@@ -111,9 +111,9 @@ export declare function getDailyActivity(days?: number): Promise<DailyActivityPo
111
111
  export declare function markSessionBackfillsComplete(): void;
112
112
  /**
113
113
  * Insert user-message stats. Idempotent via UNIQUE(session_file, entry_id).
114
- * The `WHERE NOT EXISTS` clause matches {@link insertMessageStats}: forks
115
- * copy user entries verbatim into the child JSONL, so the same
116
- * `(entry_id, timestamp)` must not land twice across different session files.
114
+ * The fork guard matches {@link insertMessageStats}: forks copy user entries
115
+ * verbatim into the child JSONL, so the same `(entry_id, timestamp)` must not
116
+ * land twice across different session files.
117
117
  */
118
118
  export declare function insertUserMessageStats(stats: Iterable<UserMessageStats>): number;
119
119
  /**
@@ -205,7 +205,7 @@ export declare function getPendingFrustrationTotals(cutoff?: number | null): {
205
205
  export declare function upsertFrustrationVerdicts(verdicts: readonly FrustrationVerdict[]): void;
206
206
  /**
207
207
  * Insert tool-call rows. Idempotent via UNIQUE(session_file, tool_call_id);
208
- * the `WHERE NOT EXISTS` guard mirrors {@link insertMessageStats}: forked
208
+ * the fork guard mirrors {@link insertMessageStats}: forked
209
209
  * sessions deep-copy assistant entries (same `entry_id`, `timestamp`, and
210
210
  * tool-call ids under a new file), so first-write-wins across the lineage
211
211
  * keeps aggregates from double counting. Keyed on the assistant entry
@@ -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
  /**
@@ -81,7 +81,7 @@ export declare function listSessionFolders(): Promise<string[]>;
81
81
  * transcripts, never transcripts of their own; a killed run can leave one
82
82
  * behind until the next `zetacode gc --compress --apply` removes it.
83
83
  */
84
- export declare const COMPRESS_SCRATCH_PREFIX = ".omp-gc-compress-";
84
+ export declare const COMPRESS_SCRATCH_PREFIX = ".zeta-gc-compress-";
85
85
  /** Whether `relativePath` (from any ancestor directory) lies inside a compress scratch directory. */
86
86
  export declare function isCompressScratchPath(relativePath: string): boolean;
87
87
  /**
@@ -7,10 +7,16 @@ export declare const STATS_DASHBOARD_SECURITY_VERSION = "3";
7
7
  /** IPv4 loopback address shared by the dashboard server and reuse probe. */
8
8
  export declare const STATS_DASHBOARD_HOSTNAME = "127.0.0.1";
9
9
  /**
10
- * Reuse a secure dashboard or reclaim an insecure HTTP dashboard before binding.
10
+ * How {@link startServer} proceeds with the requested port: bind it, reuse the
11
+ * dashboard already serving it, or fall back to an ephemeral port because the
12
+ * holder is neither reusable nor safe to stop.
13
+ */
14
+ export type StatsPortClaim = "bind" | "reuse" | "fallback";
15
+ /**
16
+ * Reuse a current dashboard, or upgrade an older one, before binding.
11
17
  * The preflight is needed on platforms that permit wildcard and loopback-specific
12
18
  * listeners to coexist on one port.
13
19
  */
14
- export declare function prepareStatsPort(port: number, hostname?: string): Promise<"retry" | "reuse">;
20
+ export declare function prepareStatsPort(port: number, hostname?: string): Promise<StatsPortClaim>;
15
21
  /** Reuse or reclaim a listener found after the server bind reports EADDRINUSE. */
16
- export declare function recoverStatsPort(port: number, hostname?: string): Promise<"retry" | "reuse">;
22
+ export declare function recoverStatsPort(port: number, hostname?: string): Promise<StatsPortClaim>;
@@ -1,13 +1,18 @@
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
  */
5
12
  export declare function handleApi(req: Request): Promise<Response>;
6
13
  /** Format a dashboard origin, including brackets required by IPv6 literals. */
7
14
  export declare function formatStatsDashboardUrl(hostname: string, port: number): string;
8
- /**
9
- * Start the HTTP server, reusing a live dashboard or reclaiming a stale omp listener.
10
- */
15
+ /** A dashboard this process started or found; `port` is where it listens, which may differ from the one requested. */
11
16
  export interface StatsServerHandle {
12
17
  hostname: string;
13
18
  port: number;
@@ -23,4 +28,10 @@ export interface StartServerOptions {
23
28
  */
24
29
  language?: string;
25
30
  }
31
+ /**
32
+ * Start the dashboard on `port`, or reuse the current dashboard already serving it.
33
+ * An older dashboard there is stopped and replaced; any other holder (a foreign
34
+ * program, or a dashboard too busy to answer the identity probe) is left running
35
+ * and the dashboard binds an ephemeral port instead.
36
+ */
26
37
  export declare function startServer(port?: number, hostname?: string, options?: StartServerOptions): Promise<StatsServerHandle>;
@@ -661,7 +661,7 @@ export interface TraceTrack {
661
661
  agent: string | null;
662
662
  /** session_init.resolvedModel ?? first assistant model. */
663
663
  model: string | null;
664
- /** Absolute transcript path (for entry fetch). */
664
+ /** Absolute transcript path for live entry fetch, or the embedded snapshot key. */
665
665
  file: string;
666
666
  /** Sorted by start. */
667
667
  spans: TraceSpan[];
@@ -702,12 +702,13 @@ export interface SessionTrace {
702
702
  cwd: string | null;
703
703
  startedAt: number;
704
704
  endedAt: number;
705
- /** Root transcript mtime; doubles as the ETag. */
705
+ /** Root transcript mtime, or recorded root activity/header time for offline snapshots. */
706
706
  mtimeMs: number;
707
707
  /**
708
708
  * Conditional-request fingerprint `"<rootMs>:<childHighMs>"` (see
709
709
  * traceFingerprintForEtag): the server ETag is built from this, so a
710
710
  * subagent-only append changes the ETag even when the root is untouched.
711
+ * Offline snapshots use "snapshot" and do not support HTTP revalidation.
711
712
  */
712
713
  etag: string;
713
714
  /** DFS order, main first. */
@@ -17,7 +17,7 @@ export declare class TracePathError extends Error {
17
17
  * span assembly changes so browsers don't revalidate stale cached bodies
18
18
  * against an unchanged transcript mtime.
19
19
  */
20
- export declare const TRACE_ETAG_VERSION = 3;
20
+ export declare const TRACE_ETAG_VERSION = 4;
21
21
  /** Freshness of a root trace: root mtime plus the child-transcript set fingerprint. */
22
22
  export interface TraceFingerprint {
23
23
  rootMtimeMs: number;
@@ -42,6 +42,32 @@ export declare function traceMemoForTests(): {
42
42
  * file (its ETag pre-check), sparing a second walk.
43
43
  */
44
44
  export declare function buildSessionTrace(fileParam: string, fingerprint?: TraceFingerprint): Promise<SessionTrace>;
45
+ /** Header metadata used by snapshot traces, including journals without a schema version. */
46
+ export interface TraceSnapshotHeader {
47
+ timestamp?: string;
48
+ cwd?: string;
49
+ title?: string;
50
+ }
51
+ /** The journal data for one embedded transcript; its header may be stored separately. */
52
+ export interface SessionTraceSnapshot {
53
+ header?: TraceSnapshotHeader | null;
54
+ entries: readonly SessionEntry[];
55
+ }
56
+ /** A collected child transcript, keyed by its slash-joined path from the root. */
57
+ export interface SubSessionTraceSnapshot extends SessionTraceSnapshot {
58
+ parent: string | null;
59
+ }
60
+ /**
61
+ * Assemble an offline trace using the same timing joins and rollups as the live
62
+ * filesystem builder. Only supplied snapshots participate: no filesystem, DB,
63
+ * network, or wall-clock reads. Track files are snapshot keys, never disk paths.
64
+ *
65
+ * Missing parent transcripts attach their readable descendants to main. Unlike
66
+ * filesystem discovery, already-collected snapshots need no depth limit.
67
+ * `mtimeMs` is the root's last activity (or header time, then 0); the constant
68
+ * `etag` identifies a snapshot, not a conditional HTTP response.
69
+ */
70
+ export declare function buildSessionTraceFromSnapshots(root: SessionTraceSnapshot, subSessions?: Readonly<Record<string, SubSessionTraceSnapshot>>): SessionTrace;
45
71
  /** Fetch one full journal entry by id from a transcript, for the span drawer. */
46
72
  export declare function getTraceEntry(fileParam: string, entryId: string): Promise<SessionEntry | null>;
47
73
  /**
@@ -266,11 +266,16 @@ export interface ToolCallStats {
266
266
  callsInTurn: number;
267
267
  /** Serialized argument characters */
268
268
  argsChars: number;
269
+ /** Result text characters, when the same parse also read the call's `toolResult` */
270
+ resultChars?: number;
271
+ /** Result error flag, set together with `resultChars` */
272
+ isError?: boolean;
269
273
  }
270
274
  /**
271
275
  * Result linkage emitted when the parser sees a `toolResult` message entry.
272
276
  * Applied as an UPDATE on the persisted tool-call row — results can land in a
273
- * later incremental sync pass than the call that produced them.
277
+ * later incremental sync pass than the call that produced them (calls parsed
278
+ * in the same pass already carry the result, so their UPDATE is a no-op).
274
279
  */
275
280
  export interface ToolResultLink {
276
281
  sessionFile: string;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "type": "module",
3
3
  "name": "@linxiraos/pi-stats",
4
- "version": "1.4.6",
4
+ "version": "1.4.9",
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,20 +39,20 @@
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.6",
43
- "@linxiraos/pi-catalog": "1.4.6",
44
- "@linxiraos/pi-utils": "1.4.6",
42
+ "@linxiraos/pi-ai": "1.4.9",
43
+ "@linxiraos/pi-catalog": "1.4.9",
44
+ "@linxiraos/pi-utils": "1.4.9",
45
45
  "lucide-react": "^1.24.0",
46
46
  "react": "19.2.7",
47
47
  "react-dom": "19.2.7"
48
48
  },
49
49
  "devDependencies": {
50
- "@types/bun": "1.4.3",
50
+ "@types/bun": "1.4.4",
51
51
  "@types/react": "19.3.0",
52
52
  "@types/react-dom": "19.3.0"
53
53
  },
54
54
  "engines": {
55
- "bun": ">=1.3.14"
55
+ "bun": ">=1.4.4"
56
56
  },
57
57
  "files": [
58
58
  "src",
@@ -81,10 +81,12 @@
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"
84
+ "./*.js": "./src/*.ts",
85
+ "./client/traces": {
86
+ "types": "./dist/types/client/traces/index.d.ts",
87
+ "import": "./src/client/traces/index.ts"
87
88
  },
88
- "./*.js": "./src/*.ts"
89
+ "./client/styles.css": "./src/client/styles.css",
90
+ "./client/traces/traces.css": "./src/client/traces/traces.css"
89
91
  }
90
92
  }
@@ -0,0 +1,89 @@
1
+ import type { Database, SQLQueryBindings } from "bun:sqlite";
2
+
3
+ /** Bind parameters per statement; SQLite builds older than 3.32 cap a statement at 999. */
4
+ const MAX_BINDS = 999;
5
+
6
+ /** Shape of one ingest table write; see {@link ChunkedInsert}. */
7
+ export interface ChunkedInsertSpec {
8
+ /** `INSERT` or `INSERT OR IGNORE`. */
9
+ verb: "INSERT" | "INSERT OR IGNORE";
10
+ table: string;
11
+ columns: readonly string[];
12
+ /** Columns naming one transcript entry; fork copies repeat them under another `session_file`. */
13
+ identity: readonly string[];
14
+ /** Trailing `ON CONFLICT … DO UPDATE` clause, if any. */
15
+ upsert?: string;
16
+ }
17
+
18
+ /**
19
+ * Multi-row writer for one ingest table: buffers rows and writes them as
20
+ * `INSERT … VALUES (…), (…)` chunks, so the per-statement costs (trigger
21
+ * program setup, statement journal, the temp b-tree SQLite stages trigger
22
+ * inserts through) are paid per chunk instead of per row.
23
+ *
24
+ * Every row passes a first-writer-wins fork guard: forked transcripts copy
25
+ * their parent's entries verbatim, so a row whose identity another
26
+ * `session_file` already stored is skipped. Buffered rows are invisible to
27
+ * that lookup, so a row colliding with a buffered row of another transcript
28
+ * flushes the buffer first; the stored outcome equals writing row by row.
29
+ */
30
+ export class ChunkedInsert {
31
+ readonly #database: Database;
32
+ readonly #spec: ChunkedInsertSpec;
33
+ readonly #chunkRows: number;
34
+ readonly #chunkSql: string;
35
+ readonly #claimed: string;
36
+ #params: SQLQueryBindings[] = [];
37
+ #rows = 0;
38
+ /** Identity → `session_file` of each buffered row. */
39
+ #buffered = new Map<string, string>();
40
+ #changes = 0;
41
+
42
+ constructor(database: Database, spec: ChunkedInsertSpec) {
43
+ this.#database = database;
44
+ this.#spec = spec;
45
+ this.#chunkRows = Math.floor(MAX_BINDS / spec.columns.length);
46
+ this.#chunkSql = this.#sql(this.#chunkRows);
47
+ this.#claimed = `SELECT 1 FROM ${spec.table} WHERE ${spec.identity.map(column => `${column} = ?`).join(" AND ")} AND session_file <> ? LIMIT 1`;
48
+ }
49
+
50
+ /** Buffer one row unless another transcript already owns `identity`. */
51
+ add(sessionFile: string, identity: readonly SQLQueryBindings[], values: readonly SQLQueryBindings[]): void {
52
+ const key = identity.join("\0");
53
+ const owner = this.#buffered.get(key);
54
+ if (owner !== sessionFile) {
55
+ if (owner !== undefined) this.#flush();
56
+ if (this.#database.query(this.#claimed).get(...identity, sessionFile)) return;
57
+ this.#buffered.set(key, sessionFile);
58
+ }
59
+ for (const value of values) this.#params.push(value);
60
+ if (++this.#rows === this.#chunkRows) this.#flush();
61
+ }
62
+
63
+ /** Write the remaining rows; returns how many stored rows the writer inserted or updated. */
64
+ finish(): number {
65
+ this.#flush();
66
+ return this.#changes;
67
+ }
68
+
69
+ #flush(): void {
70
+ if (this.#rows === 0) return;
71
+ if (this.#rows === this.#chunkRows) {
72
+ this.#changes += this.#database.query(this.#chunkSql).run(...this.#params).changes;
73
+ } else {
74
+ // Partial chunks vary in size; keep them out of the statement cache.
75
+ using statement = this.#database.prepare(this.#sql(this.#rows));
76
+ this.#changes += statement.run(...this.#params).changes;
77
+ }
78
+ this.#params = [];
79
+ this.#rows = 0;
80
+ this.#buffered.clear();
81
+ }
82
+
83
+ #sql(rows: number): string {
84
+ const { verb, table, columns, upsert } = this.#spec;
85
+ const row = `(${columns.map(() => "?").join(", ")})`;
86
+ const values = Array.from({ length: rows }, () => row).join(", ");
87
+ return `${verb} INTO ${table} (${columns.join(", ")}) VALUES ${values}${upsert ? ` ${upsert}` : ""}`;
88
+ }
89
+ }
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
+ }