@gjsify/responsiveness 0.0.0-stage → 0.64.56

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 gjsify contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,69 @@
1
- # Temporary Holding Version
1
+ # @gjsify/responsiveness
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Measure main-loop stalls in a GJS app and turn "it freezes when I open a folder" into a number, a
4
+ span name and a test. Design: [ADR 0149](../../../docs/adr/0149-a-main-loop-stall-is-measured-where-it-happens.md).
5
+
6
+ GJS runs JavaScript on the GTK main thread. A synchronous slice over ~16 ms drops a frame; over
7
+ 50 ms a person feels it.
8
+
9
+ ```ts
10
+ import { span } from '@gjsify/responsiveness';
11
+
12
+ await span('open folder', () => openFolder());
13
+ ```
14
+
15
+ ## Arming
16
+
17
+ Off by default and free when off: no timer, and `mark()`/`span()` return a shared inert handle.
18
+
19
+ ```bash
20
+ GJSIFY_STALL_MS=50 gjs … # 50 documented default, 16 for frame work
21
+ GJSIFY_STALL_STACKS=1 … # also capture a stack when a span opens
22
+ ```
23
+
24
+ Armed, a `GLib.PRIORITY_HIGH` timer wakes the process 100 times a second. That is a debugging and
25
+ test mode, not a production default; install it as a `devDependency` unless you ship a bug-report
26
+ mode. Or arm in code: `armStallWatchdog({ thresholdMs, stacks, onStall })`.
27
+
28
+ ## What you get
29
+
30
+ - **One structured record per stall** — `GLib.log_structured` in the `gjsify-responsiveness`
31
+ domain at warning level with `GJSIFY_STALL_MS`, `GJSIFY_STALL_SPAN`, `GJSIFY_STALL_DEPTH` and
32
+ the optional `GJSIFY_STALL_STACK`: `journalctl GJSIFY_STALL_SPAN='open folder'`. `console.warn`
33
+ where GLib is absent (Node).
34
+ - **Counters** — `getStallCounters()` → `{ stalls, worstMs, totalMs, bySpan }`,
35
+ `resetStallCounters()`.
36
+ - **Spans** — `mark(label).end()` and `span(label, fn)`; a stall names the innermost open span and
37
+ the depth. No open span is a finding too: it points at the profiler.
38
+
39
+ ### The limit
40
+
41
+ A JS watchdog runs again only after the blocking code has returned, so it can say *that* the loop
42
+ stopped, *for how long* and *which span was open* — never *which function*. For that use the
43
+ sampling profiler: `gjs --profile=out.syscap …`, or `GJS_ENABLE_PROFILER=1` for an installed app,
44
+ then open the capture in Sysprof.
45
+
46
+ ## Scenario tests
47
+
48
+ ```ts
49
+ import { scenario } from '@gjsify/responsiveness/scenario';
50
+
51
+ await scenario('open folder', { budgetMs: 300, runs: 5, warmup: 1 }, () => openFolder());
52
+ ```
53
+
54
+ A scenario is an `@gjsify/unit` test: it calibrates the stall threshold on 200 ms of idle noise
55
+ (`max(50, 3 × p99)`), discards the warmup, takes the **median** of `runs`, and asserts
56
+ `median <= budgetMs` and `stalls === 0`. `GJSIFY_PERF_SOFT=1` softens only the duration, for known
57
+ slow runners; the stall assertion stays hard. Use `measureScenario()` (root entry, headless) for the numbers without the
58
+ assertions. GTK scenarios gate on `on('Display', …)` and run under `xvfb-run`.
59
+
60
+ ## Rules this measures against
61
+
62
+ No synchronous I/O on the UI thread (no `DatabaseSync` query, `readFileSync`, sync `Gio` call in a
63
+ handler); lists as a lazy `GListModel` behind `Gtk.ListView`; images decoded asynchronously at
64
+ display size; input-driven work debounced; unavoidable synchronous work chunked at
65
+ `GLib.PRIORITY_DEFAULT_IDLE`; crypto and parsing over a few hundred KB in a worker or forked child.
66
+
67
+ ## License
68
+
69
+ MIT
@@ -0,0 +1 @@
1
+ var e=Object.defineProperty,__name=(t,n)=>e(t,`name`,{value:n,configurable:!0});export{__name};
@@ -0,0 +1 @@
1
+ import{DEFAULT_STALL_MS as e,LOG_DOMAIN as t,armStallWatchdog as n,disarmStallWatchdog as r,getStallCounters as i,isStallWatchdogArmed as a,mark as o,resetStallCounters as s,span as c}from"./watchdog.js";import{measureScenario as l,median as u,percentile as d,thresholdFromNoise as f}from"./scenario.js";export{e as DEFAULT_STALL_MS,t as LOG_DOMAIN,n as armStallWatchdog,r as disarmStallWatchdog,i as getStallCounters,a as isStallWatchdogArmed,o as mark,l as measureScenario,u as median,d as percentile,s as resetStallCounters,c as span,f as thresholdFromNoise};
@@ -0,0 +1 @@
1
+ import"./_virtual/_rolldown/runtime.js";import{measureScenario as e}from"./scenario.js";import{expect as t,it as n}from"@gjsify/unit";function perfSoft(){return globalThis.process?.env?.GJSIFY_PERF_SOFT===`1`}async function scenario(r,i,a){let o=i.runs??5,s=i.warmup??1;await n(r,async()=>{let n=await e(r,i,a);if(n.medianMs>i.budgetMs){let e=`${r}: median ${n.medianMs.toFixed(1)} ms over budget ${i.budgetMs} ms`;perfSoft()?console.warn(`[gjsify-responsiveness] ${e} (GJSIFY_PERF_SOFT)`):t(n.medianMs<=i.budgetMs).toBe(!0)}if(n.stalls>0){let e=Object.entries(n.bySpan).map(([e,t])=>`${e}×${t}`).join(`, `);console.warn(`[gjsify-responsiveness] ${r}: ${n.stalls} stall(s), worst ${n.worstStallMs.toFixed(1)} ms over ${n.thresholdMs.toFixed(0)} ms in ${e}`)}t(n.stalls).toBe(0)},{timeout:i.budgetMs*(o+s)+5e3})}export{scenario};
@@ -0,0 +1 @@
1
+ import"./_virtual/_rolldown/runtime.js";import{armStallWatchdog as e,disarmStallWatchdog as t,getStallCounters as n,isStallWatchdogArmed as r,resetStallCounters as i}from"./watchdog.js";import{monotonicMs as a,startLagMonitor as o}from"@gjsify/utils/main-loop";const sleep=e=>new Promise(t=>setTimeout(t,e));function median(e){if(e.length===0)return 0;let t=e.slice().sort((e,t)=>e-t),n=t.length>>1;return t.length%2?t[n]:(t[n-1]+t[n])/2}function percentile(e,t){if(e.length===0)return 0;let n=e.slice().sort((e,t)=>e-t);return n[Math.min(n.length-1,Math.max(0,Math.ceil(t/100*n.length)-1))]}function thresholdFromNoise(e){return Math.max(50,3*percentile(e,99))}async function calibrate(){let e=[],t=o({intervalMs:10,thresholdMs:1/0,onSample:t=>e.push(t)});return await sleep(200),t.stop(),thresholdFromNoise(e)}async function measureScenario(o,s,c){let l=s.runs??5,u=s.warmup??1,d=r(),f=await calibrate();e({thresholdMs:f});try{for(let e=0;e<u;e++)await c(),await sleep(20);i();let e=[];for(let t=0;t<l;t++){let t=a();await c(),e.push(a()-t),await sleep(20)}let t=n();return{name:o,medianMs:median(e),runsMs:e,stalls:t.stalls,worstStallMs:t.worstMs,thresholdMs:f,bySpan:t.bySpan}}finally{t(),d&&e()}}export{measureScenario,median,percentile,thresholdFromNoise};
@@ -0,0 +1 @@
1
+ import"./_virtual/_rolldown/runtime.js";import{monotonicMs as e,startLagMonitor as t}from"@gjsify/utils/main-loop";const n=`gjsify-responsiveness`,r=50,i=Object.freeze({end:()=>0});let a,o=!1,s,c=[],l=[],u=!1,d=emptyCounters();function emptyCounters(){return{stalls:0,worstMs:0,totalMs:0,bySpan:{}}}function env(e){return globalThis.process?.env?.[e]}function glibLog(){return globalThis.imports?.gi?.GLib}function emit(e){let t=`main loop stalled ${e.ms.toFixed(1)} ms in ${e.span??`(no open span)`}`,r=glibLog();if(r?.log_structured){let i={MESSAGE:t,GJSIFY_STALL_MS:e.ms.toFixed(1),GJSIFY_STALL_SPAN:e.span??``,GJSIFY_STALL_DEPTH:String(e.depth)};e.stack&&(i.GJSIFY_STALL_STACK=e.stack),r.log_structured(n,r.LogLevelFlags.LEVEL_WARNING,i)}else console.warn(`[${n}] ${t}`)}function onStall(t){let n=e(),r=n-t,i=[...l,...c].filter(e=>Math.min(e.end??n,n)-Math.max(e.start,r)>=t*.5),a;for(let e of i)(!a||e.start>=a.start)&&(a=e);let o={ms:t,span:a?.label??null,depth:i.length};a?.stack&&(o.stack=a.stack),d.stalls+=1,d.totalMs+=t,t>d.worstMs&&(d.worstMs=t);let u=o.span??`(none)`;d.bySpan[u]=(d.bySpan[u]??0)+1,emit(o),s?.(o)}function armFromEnv(){if(u)return;u=!0;let e=env(`GJSIFY_STALL_MS`);if(e===void 0||e===``)return;let t=Number(e);Number.isFinite(t)&&t>0&&!a&&armStallWatchdog({thresholdMs:t})}function armStallWatchdog(e={}){return u=!0,disarmStallWatchdog(),o=e.stacks??env(`GJSIFY_STALL_STACKS`)===`1`,s=e.onStall,a=t({intervalMs:10,thresholdMs:e.thresholdMs??(Number(env(`GJSIFY_STALL_MS`))||50),onStall}),disarmStallWatchdog}function disarmStallWatchdog(){a?.stop(),a=void 0,s=void 0,c=[],l=[]}function isStallWatchdogArmed(){return armFromEnv(),a!==void 0}function mark(t){if(armFromEnv(),!a)return i;let n={label:t,start:e()};o&&(n.stack=Error().stack),c.push(n);let r=!1;return{end(){if(r)return 0;r=!0;let t=c.lastIndexOf(n);return t!==-1&&c.splice(t,1),n.end=e(),l.push(n),l.length>64&&l.shift(),n.end-n.start}}}function span(e,t){let n=mark(e),r;try{r=t()}catch(e){throw n.end(),e}return r instanceof Promise?r.finally(()=>n.end()):(n.end(),r)}function getStallCounters(){return{...d,bySpan:{...d.bySpan}}}function resetStallCounters(){d=emptyCounters()}export{r as DEFAULT_STALL_MS,n as LOG_DOMAIN,armStallWatchdog,disarmStallWatchdog,getStallCounters,isStallWatchdogArmed,mark,resetStallCounters,span};
@@ -0,0 +1,4 @@
1
+ export { armStallWatchdog, DEFAULT_STALL_MS, disarmStallWatchdog, getStallCounters, isStallWatchdogArmed, LOG_DOMAIN, mark, resetStallCounters, span, } from './watchdog.js';
2
+ export type { SpanHandle, StallCounters, StallRecord, WatchdogOptions } from './watchdog.js';
3
+ export { measureScenario, median, percentile, thresholdFromNoise } from './scenario.js';
4
+ export type { ScenarioOptions, ScenarioResult } from './scenario.js';
@@ -0,0 +1,6 @@
1
+ import { type ScenarioOptions } from './scenario.js';
2
+ /**
3
+ * `it(name)` that asserts `median <= budgetMs` and `stalls === 0`.
4
+ * `GJSIFY_PERF_SOFT=1` softens only the duration; a stall stays a failure.
5
+ */
6
+ export declare function scenario(name: string, options: ScenarioOptions, fn: () => void | Promise<void>): Promise<void>;
@@ -0,0 +1,24 @@
1
+ export interface ScenarioOptions {
2
+ /** The median of `runs` must stay within this, ms. */
3
+ budgetMs: number;
4
+ /** Measured runs. Default 5. */
5
+ runs?: number;
6
+ /** Runs discarded before measuring. Default 1. */
7
+ warmup?: number;
8
+ }
9
+ export interface ScenarioResult {
10
+ name: string;
11
+ medianMs: number;
12
+ runsMs: number[];
13
+ stalls: number;
14
+ worstStallMs: number;
15
+ /** The calibrated stall threshold the runs were armed at, ms. */
16
+ thresholdMs: number;
17
+ bySpan: Record<string, number>;
18
+ }
19
+ export declare function median(values: readonly number[]): number;
20
+ export declare function percentile(values: readonly number[], p: number): number;
21
+ /** The threshold an idle host earns: `max(50, 3 × p99 noise)`, so a loaded runner raises its own bar. */
22
+ export declare function thresholdFromNoise(noiseMs: readonly number[]): number;
23
+ /** Drive `fn` and measure it without asserting. {@link scenario} is this plus the budget. */
24
+ export declare function measureScenario(name: string, options: ScenarioOptions, fn: () => void | Promise<void>): Promise<ScenarioResult>;
@@ -0,0 +1,2 @@
1
+ declare const _default: () => Promise<void>;
2
+ export default _default;
@@ -0,0 +1,47 @@
1
+ export declare const LOG_DOMAIN = "gjsify-responsiveness";
2
+ export declare const DEFAULT_STALL_MS = 50;
3
+ export interface StallRecord {
4
+ /** How late the loop ran its timer, ms. */
5
+ ms: number;
6
+ /** Innermost open span at detection, or `null`: nothing was marked, ask the profiler. */
7
+ span: string | null;
8
+ /** Open spans at detection. */
9
+ depth: number;
10
+ /** Stack captured when that span OPENED (`GJSIFY_STALL_STACKS=1`); detection time has the wrong one. */
11
+ stack?: string;
12
+ }
13
+ export interface StallCounters {
14
+ stalls: number;
15
+ worstMs: number;
16
+ totalMs: number;
17
+ /** Stall count per innermost span label; `(none)` when no span was open. */
18
+ bySpan: Record<string, number>;
19
+ }
20
+ export interface WatchdogOptions {
21
+ /** Stall threshold in ms. Default `GJSIFY_STALL_MS`, else 50 (16 for frame work). */
22
+ thresholdMs?: number;
23
+ /** Capture a stack at span open. Default `GJSIFY_STALL_STACKS=1`. */
24
+ stacks?: boolean;
25
+ /** Called per stall, after the counters and the log record. */
26
+ onStall?: (record: StallRecord) => void;
27
+ }
28
+ export interface SpanHandle {
29
+ /** Close the span; returns its duration in ms (0 for the inert handle). */
30
+ end(): number;
31
+ }
32
+ /**
33
+ * Arm the watchdog. Armed it wakes the process 100 times a second: a debugging
34
+ * and test mode, not a production default. Returns the disarm function.
35
+ */
36
+ export declare function armStallWatchdog(options?: WatchdogOptions): () => void;
37
+ export declare function disarmStallWatchdog(): void;
38
+ export declare function isStallWatchdogArmed(): boolean;
39
+ /**
40
+ * Open a span. Unarmed this returns a shared inert handle: no allocation, no clock read.
41
+ * A stall names the innermost span that covered it, open or just closed.
42
+ */
43
+ export declare function mark(label: string): SpanHandle;
44
+ /** Run `fn` inside a span; a returned promise keeps it open until it settles. */
45
+ export declare function span<T>(label: string, fn: () => T): T;
46
+ export declare function getStallCounters(): StallCounters;
47
+ export declare function resetStallCounters(): void;
@@ -0,0 +1,2 @@
1
+ declare const _default: () => Promise<void>;
2
+ export default _default;
package/package.json CHANGED
@@ -1,6 +1,80 @@
1
1
  {
2
- "name": "@gjsify/responsiveness",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "@gjsify/responsiveness",
3
+ "version": "0.64.56",
4
+ "description": "Main-loop responsiveness for GJS apps: spans, a stall watchdog (GJSIFY_STALL_MS), structured stall records, counters and a scenario() test harness with a median budget. Opt-in, zero cost unarmed (ADR 0149).",
5
+ "module": "lib/esm/index.js",
6
+ "types": "lib/types/index.d.ts",
7
+ "type": "module",
8
+ "sideEffects": false,
9
+ "exports": {
10
+ ".": {
11
+ "types": "./lib/types/index.d.ts",
12
+ "default": "./lib/esm/index.js"
13
+ },
14
+ "./scenario": {
15
+ "types": "./lib/types/scenario-test.d.ts",
16
+ "default": "./lib/esm/scenario-test.js"
17
+ }
18
+ },
19
+ "files": [
20
+ "lib",
21
+ "!lib/types/**/*.spec.d.ts"
22
+ ],
23
+ "scripts": {
24
+ "clear": "gjsify clear lib tmp tsconfig.tsbuildinfo test.gjs.mjs test.node.mjs",
25
+ "check": "gjsify tsc --noEmit",
26
+ "build": "gjsify run build:gjsify && gjsify run build:types",
27
+ "build:gjsify": "gjsify build --library 'src/**/*.{ts,js}' --exclude 'src/**/*.spec.{mts,ts}' 'src/test.{mts,ts}'",
28
+ "build:types": "gjsify tsc",
29
+ "build:test": "gjsify run build:test:gjs && gjsify run build:test:node",
30
+ "build:test:gjs": "gjsify build src/test.mts --app gjs --outfile test.gjs.mjs",
31
+ "build:test:node": "gjsify build src/test.mts --app node --outfile test.node.mjs",
32
+ "test": "gjsify run build:gjsify && gjsify run build:test && gjsify run test:node && gjsify run test:gjs",
33
+ "test:gjs": "gjsify run test.gjs.mjs",
34
+ "test:node": "node test.node.mjs"
35
+ },
36
+ "keywords": [
37
+ "gjs",
38
+ "responsiveness",
39
+ "stall",
40
+ "watchdog",
41
+ "performance"
42
+ ],
43
+ "dependencies": {
44
+ "@gjsify/utils": "^0.64.56"
45
+ },
46
+ "peerDependencies": {
47
+ "@gjsify/unit": "^0.64.56"
48
+ },
49
+ "peerDependenciesMeta": {
50
+ "@gjsify/unit": {
51
+ "optional": true
52
+ }
53
+ },
54
+ "devDependencies": {
55
+ "@gjsify/unit": "^0.64.56",
56
+ "@gjsify/cli": "^0.64.56",
57
+ "@types/node": "^25.9.2",
58
+ "typescript": "^6.0.3"
59
+ },
60
+ "license": "MIT",
61
+ "repository": {
62
+ "type": "git",
63
+ "url": "git+https://github.com/gjsify/gjsify.git",
64
+ "directory": "packages/gjs/responsiveness"
65
+ },
66
+ "bugs": {
67
+ "url": "https://github.com/gjsify/gjsify/issues"
68
+ },
69
+ "homepage": "https://github.com/gjsify/gjsify/tree/main/packages/gjs/responsiveness#readme",
70
+ "gjsify": {
71
+ "tier": 3,
72
+ "runtimes": {
73
+ "gjs": "polyfill",
74
+ "node": "polyfill",
75
+ "browser": "none",
76
+ "nativescript": "none"
77
+ },
78
+ "headless": true
79
+ }
80
+ }