shadok-ai 0.19.42 → 0.19.44

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/README.md CHANGED
@@ -1074,7 +1074,8 @@ travels over `/ws`, and the page itself is static HTML, so a proxy that drops
1074
1074
  connects. In nginx:
1075
1075
 
1076
1076
  ```nginx
1077
- location / {
1077
+ # The WebSocket — the ONLY path that upgrades, and the only one that may wait.
1078
+ location = /ws {
1078
1079
  proxy_pass http://127.0.0.1:3789;
1079
1080
  proxy_http_version 1.1;
1080
1081
  proxy_set_header Upgrade $http_upgrade;
@@ -1082,10 +1083,29 @@ location / {
1082
1083
  proxy_set_header Host $host;
1083
1084
  proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; # see below
1084
1085
  proxy_set_header X-Forwarded-Proto $scheme; # Secure cookies
1086
+ # proxy_read_timeout 3600s; # optional, and ONLY here — see "Idle timeout"
1087
+ }
1088
+
1089
+ # Everything else: ordinary requests, ordinary (default, 60s) read timeout.
1090
+ location / {
1091
+ proxy_pass http://127.0.0.1:3789;
1092
+ proxy_http_version 1.1;
1093
+ proxy_set_header Host $host;
1094
+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; # see below
1095
+ proxy_set_header X-Forwarded-Proto $scheme; # Secure cookies
1085
1096
  client_max_body_size 50m; # match the server's paste limit
1086
1097
  }
1087
1098
  ```
1088
1099
 
1100
+ Two locations, because the two kinds of traffic want opposite things from the
1101
+ proxy: `/ws` is one long-lived socket that may legitimately stay quiet, and
1102
+ everything under `/` is a short request that should fail fast when the server
1103
+ does not answer. `/ws` is the only WebSocket path the server has, so the
1104
+ `Upgrade`/`Connection` headers — and any long timeout — belong there and nowhere
1105
+ else. Both locations carry the `Host` / `X-Forwarded-*` lines on purpose: each
1106
+ `location` is configured on its own, and the server needs the client address
1107
+ and scheme on the socket as much as on a plain request.
1108
+
1089
1109
  **Forward the client address.** An agent authenticates to its own server with a
1090
1110
  session key that never expires, so the server accepts that key **only from this
1091
1111
  machine, directly** — never from the network, where a key leaked by a
@@ -1119,8 +1139,19 @@ idle-close a quiet socket (nginx `proxy_read_timeout`, 60s by default;
1119
1139
  Cloudflare ~100s) — the symptom is a cockpit that keeps flashing
1120
1140
  "reconnecting…" even though nothing is wrong. The server sends a WebSocket ping
1121
1141
  every 25s (tunable with `SHADOK_WS_PING_MS`) to keep the connection warm, so no
1122
- proxy change is normally needed; if your proxy still cuts it, raise
1123
- `proxy_read_timeout` above the ping interval.
1142
+ proxy change is normally needed — nginx's default 60s is already more than
1143
+ twice the ping interval. If your proxy still cuts it, raise `proxy_read_timeout`
1144
+ above the ping interval **in `location = /ws` only, never in `location /`**.
1145
+
1146
+ A long read timeout is right for a resting agent's silent socket and wrong for
1147
+ everything else. On a plain `GET`, it is how long the proxy keeps holding a
1148
+ request the server never answers — and the browser holds its end for just as
1149
+ long. A browser opens only about six HTTP/1.1 connections to one host, so a
1150
+ handful of unanswered requests is enough to occupy them all and freeze that
1151
+ cockpit's own updates for the whole timeout, while the proxy and the server
1152
+ keep those connections open too. With the default, the same failure clears in a
1153
+ minute. If your `location /` carries a raised `proxy_read_timeout` today, move
1154
+ it to `location = /ws`.
1124
1155
 
1125
1156
  **Sleep / wake / network blips.** When the machine comes back (an `online`
1126
1157
  event, the tab becoming visible, a back/forward-cache restore), the cockpit
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "shadok-ai",
3
- "version": "0.19.42",
3
+ "version": "0.19.44",
4
4
  "main": "dist/session.js",
5
5
  "scripts": {
6
6
  "test": "node --import tsx --test --test-timeout=120000 test/*.ts context/*/test/*.test.mjs",
package/public/index.html CHANGED
@@ -4760,6 +4760,89 @@
4760
4760
  }
4761
4761
  });
4762
4762
  }
4763
+ // ── Poll guard (invariant 69) ─────────────────────────────────
4764
+ // A periodic poll must be UNABLE to accumulate. A bare `fetch` in a timer has
4765
+ // no deadline, so when a server stops answering one endpoint every tick adds a
4766
+ // request that never settles. Nothing bounds that pile, and it does not stay
4767
+ // this page's problem: the browser's socket pool is shared, so once it is full
4768
+ // any NEW connection queues — and a WebSocket needs a new one. Another, healthy
4769
+ // cockpit open in a different tab then shows every agent on "connecting…" for
4770
+ // ever while its page keeps working (it reuses sockets it already holds).
4771
+ //
4772
+ // Two halves, and each is needed. The deadline frees the socket; without the
4773
+ // in-flight guard there is still one stuck request per tick until it fires.
4774
+ // The guard alone would hold one socket for ever and freeze that poll.
4775
+ //
4776
+ // A tick that finds its endpoint in flight sends NOTHING and joins the pending
4777
+ // answer, which is why the result is a snapshot ({ok, status, json()}) and not
4778
+ // the Response: a body can be read once, a snapshot by every caller. The body
4779
+ // is read INSIDE the deadline — headers that arrive and a body that stalls is
4780
+ // the same hang one step later.
4781
+ //
4782
+ // GET only, by signature: there is no `init`. Coalescing a write would drop
4783
+ // one, and a deliberate, legitimately long request (an upload, a paste, a
4784
+ // transcription, a sign-in step) must never inherit a polling deadline — those
4785
+ // keep calling `fetch` directly.
4786
+ //
4787
+ // Kept inline rather than in an ESM module: a module reaches this script
4788
+ // through the deferred bridge (invariant 10), and the stub covering the gap
4789
+ // would have to be either a bare fetch — the bug, back exactly when the page
4790
+ // is already degraded — or a copy of this logic. The factory takes its
4791
+ // environment as an argument so test/poll-guard.test.ts can lift the text
4792
+ // between the two markers out of this file and run THIS code on fake timers.
4793
+ // poll-guard:start
4794
+ const POLL_TIMEOUT_MS = 15000;
4795
+ function makePollFetch(env) {
4796
+ const inFlight = new Map();
4797
+ return function pollFetch(url, opts) {
4798
+ const key = (opts && opts.key) || url;
4799
+ const pending = inFlight.get(key);
4800
+ if (pending) return pending;
4801
+ const timeoutMs = (opts && opts.timeoutMs) || env.timeoutMs;
4802
+ const ctl = new env.AbortController();
4803
+ let timer;
4804
+ // Raced as well as aborted: the slot must come back at the deadline even
4805
+ // if something underneath ignores the signal.
4806
+ const deadline = new Promise((_, reject) => {
4807
+ timer = env.setTimeout(() => {
4808
+ const err = new Error("poll timed out after " + timeoutMs + "ms: " + url);
4809
+ err.name = "TimeoutError";
4810
+ reject(err);
4811
+ ctl.abort();
4812
+ }, timeoutMs);
4813
+ });
4814
+ // Started one microtask late so the slot is registered BEFORE anything can
4815
+ // settle: a fetch that throws synchronously would otherwise run `finally`
4816
+ // first and leave a dead promise in the map — that endpoint silenced for
4817
+ // the life of the page.
4818
+ const run = Promise.resolve()
4819
+ .then(() => Promise.race([
4820
+ (async () => {
4821
+ const res = await env.fetch(url, { signal: ctl.signal });
4822
+ const text = await res.text();
4823
+ return { ok: res.ok, status: res.status, json: async () => JSON.parse(text) };
4824
+ })(),
4825
+ deadline,
4826
+ ]))
4827
+ .finally(() => {
4828
+ env.clearTimeout(timer);
4829
+ if (inFlight.get(key) === run) inFlight.delete(key);
4830
+ });
4831
+ inFlight.set(key, run);
4832
+ return run;
4833
+ };
4834
+ }
4835
+ // poll-guard:end
4836
+ // `fetch` is looked up at call time, so the 401 → login wrapper installed in
4837
+ // the first inline script stays on the path.
4838
+ const pollFetch = makePollFetch({
4839
+ fetch: (url, init) => fetch(url, init),
4840
+ AbortController,
4841
+ setTimeout: (fn, ms) => setTimeout(fn, ms),
4842
+ clearTimeout: (id) => clearTimeout(id),
4843
+ timeoutMs: POLL_TIMEOUT_MS,
4844
+ });
4845
+
4763
4846
  // ── Bouchons du pont ESM (invariant 10) ─────────────────────────────────
4764
4847
  // Le bloc module ci-dessus est DIFFÉRÉ : il s'exécute après le parsing,
4765
4848
  // alors que ce script-ci tourne PENDANT et câble déjà les boutons.
@@ -7490,9 +7573,9 @@
7490
7573
  let chans, srvGroups, srvFolders;
7491
7574
  try {
7492
7575
  [chans, srvGroups, srvFolders] = await Promise.all([
7493
- fetch("/channels").then((r) => r.json()),
7494
- fetch("/groups").then((r) => r.json()).catch(() => null),
7495
- fetch("/agent-folders").then((r) => r.json()).catch(() => null),
7576
+ pollFetch("/channels").then((r) => r.json()),
7577
+ pollFetch("/groups").then((r) => r.json()).catch(() => null),
7578
+ pollFetch("/agent-folders").then((r) => r.json()).catch(() => null),
7496
7579
  ]);
7497
7580
  } catch { return; }
7498
7581
  adoptFolders(srvFolders);
@@ -7645,7 +7728,7 @@
7645
7728
  let firstAgentStep = null;
7646
7729
  async function syncFirstAgent() {
7647
7730
  let st;
7648
- try { st = await (await fetch("/first-agent")).json(); } catch { return; }
7731
+ try { st = await (await pollFetch("/first-agent")).json(); } catch { return; }
7649
7732
  const now = !!(st && st.pending);
7650
7733
  // The lead's spawn reports the same real steps as a tab (src/first-agent.ts),
7651
7734
  // plus "Saying hello" while its greeting is under way.
@@ -9880,7 +9963,7 @@
9880
9963
  const listEl = $("liveList");
9881
9964
  let live = [];
9882
9965
  try {
9883
- live = await (await fetch("/live")).json();
9966
+ live = await (await pollFetch("/live")).json();
9884
9967
  } catch { live = []; }
9885
9968
  if (!Array.isArray(live) || live.length === 0) { field.hidden = true; return; }
9886
9969
  field.hidden = false;
@@ -10379,7 +10462,7 @@
10379
10462
  }
10380
10463
  }
10381
10464
  async function refreshAuthRows() {
10382
- try { lastAuth = await (await fetch("/auth")).json(); }
10465
+ try { lastAuth = await (await pollFetch("/auth")).json(); }
10383
10466
  catch { lastAuth = null; }
10384
10467
  if (!verMenu.hidden) renderAuthRows();
10385
10468
  updateExpiryBanner(); // the banner must track the clock even menu-closed
@@ -11542,7 +11625,7 @@
11542
11625
  if (restoring || swapped) return;
11543
11626
  let list;
11544
11627
  try {
11545
- const r = await fetch("/rooms");
11628
+ const r = await pollFetch("/rooms");
11546
11629
  if (!r.ok) return;
11547
11630
  list = await r.json();
11548
11631
  } catch { return; }
@@ -13281,7 +13364,7 @@
13281
13364
  }
13282
13365
  }
13283
13366
  async function refreshAccountBanner() {
13284
- const r = await fetch("/connected-accounts").catch(() => null);
13367
+ const r = await pollFetch("/connected-accounts").catch(() => null);
13285
13368
  const j = r && r.ok ? await r.json().catch(() => null) : null;
13286
13369
  // A failed fetch keeps what is shown: an unreachable server is not a reconnect.
13287
13370
  if (j && Array.isArray(j.accounts)) caBannerAccounts = j.accounts;
@@ -16015,7 +16098,7 @@
16015
16098
 
16016
16099
  // ── Security panel ──────────────────────────────────────
16017
16100
  async function securityInbox() {
16018
- try { const r = await fetch("/2fa/inbox"); return r.ok ? await r.json() : null; } catch { return null; }
16101
+ try { const r = await pollFetch("/2fa/inbox"); return r.ok ? await r.json() : null; } catch { return null; }
16019
16102
  }
16020
16103
  async function refreshSecurityBadge() {
16021
16104
  if ($("securityBtn").hidden) return;
@@ -16125,7 +16208,7 @@
16125
16208
 
16126
16209
  // ── Agent reports panel ─────────────────────────────────
16127
16210
  async function reportsInbox() {
16128
- try { const r = await fetch("/reports"); return r.ok ? await r.json() : null; } catch { return null; }
16211
+ try { const r = await pollFetch("/reports"); return r.ok ? await r.json() : null; } catch { return null; }
16129
16212
  }
16130
16213
  async function refreshReportsBadge() {
16131
16214
  if ($("reportsBtn").hidden) return;
@@ -17488,12 +17571,14 @@
17488
17571
 
17489
17572
  async function refreshUsage() {
17490
17573
  try {
17491
- const u = await (await fetch("/usage")).json();
17574
+ const u = await (await pollFetch("/usage")).json();
17492
17575
  paintGauge($("quota5h"), u.fiveHour);
17493
17576
  paintGauge($("quota7d"), u.sevenDay);
17494
17577
  paceBlocked = !!u.blocked;
17495
17578
  paceReason = u.reason || null;
17496
17579
  } catch {
17580
+ // A poll that timed out lands here too (pollFetch rejects on abort) — the
17581
+ // same branch on purpose, never a path around it.
17497
17582
  // Leave the gauges on their last values, but not the verdict: a stuck
17498
17583
  // `true` would make the client demand confirmation forever where the
17499
17584
  // server would let the send through. The server re-checks and is the