shadok-ai 0.19.63 → 0.19.64

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
@@ -1263,6 +1263,23 @@ Dock or taskbar signals it, and a notification appears. It wraps the web page
1263
1263
  as it is, so the server needs no change. `cd desktop && npm install && npm start`;
1264
1264
  packaging and shortcuts are in [`desktop/README.md`](desktop/README.md).
1265
1265
 
1266
+ ### On a phone: Home Screen app and notifications
1267
+
1268
+ The cockpit installs like an app: on iPhone, **Share → Add to Home Screen**;
1269
+ on Android or desktop Chrome/Edge, **Install**. The icon carries the cockpit's
1270
+ title, so several instances stay apart.
1271
+
1272
+ From that installed app (on iOS, only from there), tick **Notify this device**
1273
+ in the version menu (click the version number). The server then sends a push
1274
+ notification when an agent asks a question or finishes a turn that produced
1275
+ something. Muted agents and muted instances stay quiet. Tapping the notification
1276
+ opens that agent, and **Send a test notification** checks the device right away.
1277
+
1278
+ This needs HTTPS (see "Behind TLS"). Each person gets notifications only for
1279
+ the agents they can see. The push service relays an encrypted payload it cannot
1280
+ read. `SHADOK_PUSH_SUBJECT` sets the contact sent to push services (default:
1281
+ the project's URL). Design: `docs/superpowers/specs/2026-11-16-web-push-design.md`.
1282
+
1266
1283
  ### Signing in to Claude
1267
1284
 
1268
1285
  A fresh machine — most often a fresh container — has two things in its way, and
@@ -0,0 +1,35 @@
1
+ import { type PushSubscriptionData, type VapidKeys } from "./webpush.js";
2
+ export interface StoredSubscription extends PushSubscriptionData {
3
+ /** The account that subscribed this device. */
4
+ user: string;
5
+ createdAt: number;
6
+ /** A human label for the device list ("iPhone · Safari"), from the UA. */
7
+ device?: string;
8
+ }
9
+ export interface PushState {
10
+ vapid: VapidKeys;
11
+ subs: StoredSubscription[];
12
+ }
13
+ /** A person rarely has more than a few devices; the cap stops a loop in a
14
+ * client from growing the file without bound. Oldest go first. */
15
+ export declare const MAX_SUBS_PER_USER = 10;
16
+ export declare function pushFileFor(cwd?: string): string;
17
+ /**
18
+ * Add or refresh a device. Keyed by endpoint: the same device subscribing again
19
+ * (new keys after a browser reset, or another account signing in on it) REPLACES
20
+ * its row — one device never notifies twice, and never for two accounts.
21
+ */
22
+ export declare function upsertSubscription(list: readonly StoredSubscription[], sub: PushSubscriptionData, user: string, now: number, device?: string): StoredSubscription[];
23
+ /** Remove a device. Only its own account may: an endpoint is not a secret to
24
+ * whoever can read the page, so it must not be enough to unsubscribe someone. */
25
+ export declare function removeSubscription(list: readonly StoredSubscription[], endpoint: string, user: string): StoredSubscription[];
26
+ /** Drop subscriptions the push service declared dead (404/410). */
27
+ export declare function dropEndpoints(list: readonly StoredSubscription[], gone: ReadonlySet<string>): StoredSubscription[];
28
+ /** A short device label from a User-Agent — for the person's own list, never
29
+ * sent anywhere. */
30
+ export declare function deviceLabel(ua: string | undefined): string | undefined;
31
+ /** Read the state, creating the key pair on first use. Never throws: a broken
32
+ * file is replaced by a fresh key pair and an empty list — the devices on it
33
+ * were bound to keys we can no longer prove, so they would fail anyway. */
34
+ export declare function loadPushState(file?: string): PushState;
35
+ export declare function savePushState(state: PushState, file?: string): void;
@@ -0,0 +1,84 @@
1
+ /**
2
+ * Where an instance keeps its Web Push state: its VAPID key pair and the
3
+ * devices subscribed to it, in `~/.shadok-ai/push/<instanceKey>.json` (600).
4
+ *
5
+ * Per instance, because a subscription is bound to the VAPID public key it was
6
+ * created with, and each instance is its own origin to a browser — sharing one
7
+ * file between two launch directories would hand one cockpit's devices to the
8
+ * other. Each subscription names the ACCOUNT that made it, so a member is only
9
+ * ever told about agents they may see (`server.ts` filters with
10
+ * `canSeeSession` at send time, not at subscribe time: group membership
11
+ * changes, and the check must follow it).
12
+ *
13
+ * The list logic is pure (tested); `loadPushState` / `savePushState` are the
14
+ * thin fs half.
15
+ */
16
+ import fs from "node:fs";
17
+ import path from "node:path";
18
+ import { SHADOK_DIR } from "./config.js";
19
+ import { instanceKey } from "./paths.js";
20
+ import { generateVapidKeys, vapidKeysValid } from "./webpush.js";
21
+ /** A person rarely has more than a few devices; the cap stops a loop in a
22
+ * client from growing the file without bound. Oldest go first. */
23
+ export const MAX_SUBS_PER_USER = 10;
24
+ export function pushFileFor(cwd = process.cwd()) {
25
+ return path.join(SHADOK_DIR, "push", `${instanceKey(cwd)}.json`);
26
+ }
27
+ /**
28
+ * Add or refresh a device. Keyed by endpoint: the same device subscribing again
29
+ * (new keys after a browser reset, or another account signing in on it) REPLACES
30
+ * its row — one device never notifies twice, and never for two accounts.
31
+ */
32
+ export function upsertSubscription(list, sub, user, now, device) {
33
+ const rest = list.filter((s) => s.endpoint !== sub.endpoint);
34
+ const row = { ...sub, user, createdAt: now, ...(device ? { device } : {}) };
35
+ const mine = rest.filter((s) => s.user === user).sort((a, b) => a.createdAt - b.createdAt);
36
+ const drop = new Set(mine.slice(0, Math.max(0, mine.length - (MAX_SUBS_PER_USER - 1))).map((s) => s.endpoint));
37
+ return [...rest.filter((s) => !drop.has(s.endpoint)), row];
38
+ }
39
+ /** Remove a device. Only its own account may: an endpoint is not a secret to
40
+ * whoever can read the page, so it must not be enough to unsubscribe someone. */
41
+ export function removeSubscription(list, endpoint, user) {
42
+ return list.filter((s) => !(s.endpoint === endpoint && s.user === user));
43
+ }
44
+ /** Drop subscriptions the push service declared dead (404/410). */
45
+ export function dropEndpoints(list, gone) {
46
+ return list.filter((s) => !gone.has(s.endpoint));
47
+ }
48
+ /** A short device label from a User-Agent — for the person's own list, never
49
+ * sent anywhere. */
50
+ export function deviceLabel(ua) {
51
+ const s = String(ua ?? "");
52
+ if (!s)
53
+ return undefined;
54
+ const os = /iPhone/.test(s) ? "iPhone" : /iPad/.test(s) ? "iPad" : /Android/.test(s) ? "Android"
55
+ : /Mac OS X/.test(s) ? "Mac" : /Windows/.test(s) ? "Windows" : /Linux/.test(s) ? "Linux" : "";
56
+ const br = /Edg\//.test(s) ? "Edge" : /Firefox\//.test(s) ? "Firefox" : /Chrome\//.test(s) ? "Chrome"
57
+ : /Safari\//.test(s) ? "Safari" : "";
58
+ return [os, br].filter(Boolean).join(" · ") || undefined;
59
+ }
60
+ /** Read the state, creating the key pair on first use. Never throws: a broken
61
+ * file is replaced by a fresh key pair and an empty list — the devices on it
62
+ * were bound to keys we can no longer prove, so they would fail anyway. */
63
+ export function loadPushState(file = pushFileFor()) {
64
+ try {
65
+ const raw = JSON.parse(fs.readFileSync(file, "utf8"));
66
+ if (vapidKeysValid(raw?.vapid)) {
67
+ const subs = Array.isArray(raw.subs) ? raw.subs.filter((s) => s && typeof s.endpoint === "string" && typeof s.user === "string" && s.keys) : [];
68
+ return { vapid: raw.vapid, subs };
69
+ }
70
+ }
71
+ catch {
72
+ /* missing or unreadable → fresh state below */
73
+ }
74
+ const fresh = { vapid: generateVapidKeys(), subs: [] };
75
+ savePushState(fresh, file);
76
+ return fresh;
77
+ }
78
+ export function savePushState(state, file = pushFileFor()) {
79
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
80
+ const tmp = `${file}.${process.pid}.tmp`;
81
+ fs.writeFileSync(tmp, JSON.stringify(state, null, 2), { mode: 0o600 });
82
+ fs.renameSync(tmp, file);
83
+ }
84
+ //# sourceMappingURL=push-store.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"push-store.js","sourceRoot":"","sources":["../src/push-store.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AACH,OAAO,EAAE,MAAM,SAAS,CAAC;AACzB,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AACzC,OAAO,EAAE,iBAAiB,EAAE,cAAc,EAA6C,MAAM,cAAc,CAAC;AAe5G;mEACmE;AACnE,MAAM,CAAC,MAAM,iBAAiB,GAAG,EAAE,CAAC;AAEpC,MAAM,UAAU,WAAW,CAAC,GAAG,GAAW,OAAO,CAAC,GAAG,EAAE;IACrD,OAAO,IAAI,CAA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CAAC;AAED,MAAM,UAAU,aAAa,CAAC,KAAgB,EAAE,IAAI,GAAW,WAAW,EAAE;IAC1E,EAAE,CAAC,SAAS,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC,CAAC;IACnE,MAAM,GAAG,GAAG,GAAG,IAAI,IAAI,OAAO,CAAC,GAAG,MAAM,CAAC;IACzC,EAAE,CAAC,aAAa,CAAC,GAAG,EAAE,IAAI,CAAC,SAAS,CAAC,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC,EAAE,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC,CAAC;IACvE,EAAE,CAAC,UAAU,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;AAC3B,CAAC"}
package/dist/server.js CHANGED
@@ -91,6 +91,8 @@ import { secretsFor, secretsForProfile, secretNamesForProfile, secretNames, setS
91
91
  import { recordSecretAudit, readSecretAudit, filterAudit, spawnActor, httpActor, profileSecretDiff, } from "./secret-audit.js";
92
92
  import { getProfile, profileArgs, resolveSpawnModel, permissionModeArgs, isPermissionMode, isEffortLevel, mcpServersVerdict, envVarsNote, seedDefaultProfiles, migrateToTracking, seedTweakProfile, seedSkillsmithProfile, MANAGED_PROFILE_NAMES, loadProfiles, upsertProfile, removeProfile, promptEditVerdict, secretAttachVerdict, READONLY_DENY, promptOrigin, effectiveProfile, shippedProfile, profileNames, } from "./profiles.js";
93
93
  import { BOOTSTRAP_ADMIN, loadAccounts, verifyPasswordAsync, burnPasswordCheck, sessionSecret, signSession, readSessionFull, sessionAlive, bootstrapSessionsAfter, saveAccounts, userWriteVerdict, newInvite, inviteVerdict, hashPasswordAsync, promptAuthor, signSessionKey, readSessionKey, signTalkHandle, readTalkHandle, } from "./accounts.js";
94
+ import { parseSubscription, preview, sendPush } from "./webpush.js";
95
+ import { loadPushState, savePushState, upsertSubscription, removeSubscription, dropEndpoints, deviceLabel, } from "./push-store.js";
94
96
  import { AGENT_CREDENTIAL_VARS, agentAccount, headerPresent, isBrowserPerson, resolveAgentPrincipal, } from "./agent-principal.js";
95
97
  import { admins2fa, authenticationOptions, enrollCodeVerdict, isInternalClient, keepsTwoAdminsVerdict, loginNext, newEnrollCode, publicPasskey, putChallenge, readPending, registrationOptions, resetVerdict, signPending, takeChallenge, twoFactorEnableVerdict, verifyAuthentication, verifyRegistration, PENDING_TTL_MS, } from "./twofactor.js";
96
98
  import { ensureSelfRepo } from "./selfrepo.js";
@@ -1746,7 +1748,9 @@ app.get("/me", (req, res) => {
1746
1748
  // Gate everything else behind the cookie when a password is set. /me answers
1747
1749
  // for itself: it must return 401, not the login page.
1748
1750
  app.use((req, res, next) => {
1749
- if (req.path === "/me" || req.path === "/logout" || req.path.startsWith("/invite/") || requestAuthed(req))
1751
+ // `/icons/`: the Home Screen icon is fetched by the OS, which may not carry
1752
+ // the session cookie, and it is the same static Shadok for every instance.
1753
+ if (req.path === "/me" || req.path === "/logout" || req.path.startsWith("/invite/") || req.path.startsWith("/icons/") || requestAuthed(req))
1750
1754
  return next();
1751
1755
  // A peer is a NARROW principal, not a member: over HTTP it may reach ONLY
1752
1756
  // `GET /diff` (of its own agents — the handler ownership-checks). Everything
@@ -1766,6 +1770,27 @@ app.use((req, res, next) => {
1766
1770
  // page as soon as index.html was edited: you reload, nothing moves, you go hunt
1767
1771
  // the bug elsewhere. A 170 KB file read once per tab opening does not register;
1768
1772
  // the trap does.
1773
+ // The Web App Manifest: what "Add to Home Screen" installs. Generated rather than
1774
+ // static so the installed app carries THIS cockpit's name — someone with three
1775
+ // instances gets three icons they can tell apart. Behind the gate (the page links
1776
+ // it with crossorigin="use-credentials"): the title is the operator's, not public.
1777
+ app.get("/manifest.webmanifest", (_req, res) => {
1778
+ const title = titleForCwd(loadConfig(), process.cwd()) || "shadok-ai";
1779
+ res.type("application/manifest+json").json({
1780
+ name: title,
1781
+ short_name: title.length > 12 ? "shadok" : title,
1782
+ start_url: "/",
1783
+ scope: "/",
1784
+ display: "standalone",
1785
+ background_color: "#14161d",
1786
+ theme_color: "#14161d",
1787
+ icons: [
1788
+ { src: "/icons/icon-192.png", sizes: "192x192", type: "image/png", purpose: "any" },
1789
+ { src: "/icons/icon-512.png", sizes: "512x512", type: "image/png", purpose: "any" },
1790
+ { src: "/icons/maskable-512.png", sizes: "512x512", type: "image/png", purpose: "maskable" },
1791
+ ],
1792
+ });
1793
+ });
1769
1794
  const INDEX_PATH = path.join(__dirname, "..", "public", "index.html");
1770
1795
  app.get(["/", "/index.html"], (_req, res) => {
1771
1796
  let html;
@@ -2158,6 +2183,72 @@ app.put("/mute", (req, res) => {
2158
2183
  setMutedForCwd(loadConfig(), process.cwd(), req.body?.muted === true);
2159
2184
  res.json({ muted: mutedForCwd(loadConfig(), process.cwd()) });
2160
2185
  });
2186
+ // ── Web Push: wake a phone (or any browser) when an agent needs its person ──
2187
+ // The page's own attention signal (title badge, chime) dies with the page, and a
2188
+ // phone suspends a backgrounded page within seconds. A push is the only signal
2189
+ // that reaches a pocket; on iOS it works for a cockpit added to the Home Screen.
2190
+ // Design: docs/superpowers/specs/2026-11-16-web-push-design.md.
2191
+ //
2192
+ // Subscribing is a PERSON's act from a real page: an agent has nothing to be
2193
+ // woken on, and letting one register an endpoint would let it make the server
2194
+ // POST wherever it likes (parseSubscription also allowlists the push services).
2195
+ app.get("/push", (req, res) => {
2196
+ const me = currentAccount(req);
2197
+ if (!me)
2198
+ return res.status(401).json({ error: "unauthorized" });
2199
+ const st = loadPushState();
2200
+ res.json({
2201
+ publicKey: st.vapid.publicKey,
2202
+ devices: st.subs.filter((x) => x.user === me.name).map((x) => ({ endpoint: x.endpoint, device: x.device ?? null, createdAt: x.createdAt })),
2203
+ });
2204
+ });
2205
+ app.post("/push/subscribe", (req, res) => {
2206
+ if (!requestFromBrowser(req))
2207
+ return res.status(403).json({ error: "same-origin browser only" });
2208
+ const me = currentAccount(req);
2209
+ if (!me || me.agent)
2210
+ return res.status(401).json({ error: "unauthorized" });
2211
+ const parsed = parseSubscription(req.body?.subscription);
2212
+ if (!parsed.ok)
2213
+ return res.status(400).json({ error: parsed.reason });
2214
+ const st = loadPushState();
2215
+ st.subs = upsertSubscription(st.subs, parsed.sub, me.name, Date.now(), deviceLabel(req.headers["user-agent"]));
2216
+ savePushState(st);
2217
+ res.json({ ok: true });
2218
+ });
2219
+ app.post("/push/unsubscribe", (req, res) => {
2220
+ if (!requestFromBrowser(req))
2221
+ return res.status(403).json({ error: "same-origin browser only" });
2222
+ const me = currentAccount(req);
2223
+ if (!me || me.agent)
2224
+ return res.status(401).json({ error: "unauthorized" });
2225
+ const st = loadPushState();
2226
+ st.subs = removeSubscription(st.subs, String(req.body?.endpoint ?? ""), me.name);
2227
+ savePushState(st);
2228
+ res.json({ ok: true });
2229
+ });
2230
+ // "Did it work?" has to be answerable from the phone itself, without waiting for
2231
+ // an agent to ask something: send one notification to the caller's devices and
2232
+ // report what each push service answered.
2233
+ app.post("/push/test", async (req, res) => {
2234
+ if (!requestFromBrowser(req))
2235
+ return res.status(403).json({ error: "same-origin browser only" });
2236
+ const me = currentAccount(req);
2237
+ if (!me || me.agent)
2238
+ return res.status(401).json({ error: "unauthorized" });
2239
+ const st = loadPushState();
2240
+ const mine = st.subs.filter((x) => x.user === me.name);
2241
+ if (!mine.length)
2242
+ return res.status(404).json({ error: "no device subscribed for this account" });
2243
+ const msg = {
2244
+ title: titleForCwd(loadConfig(), process.cwd()) || "shadok-ai",
2245
+ body: "Notifications work on this device.",
2246
+ tag: "shadok-test",
2247
+ url: "/",
2248
+ };
2249
+ const results = await deliverPush(mine, msg);
2250
+ res.json({ results: results.map((r) => ({ device: r.sub.device ?? null, ok: r.ok, status: r.status, error: r.error })) });
2251
+ });
2161
2252
  // The caller's OWN display preferences (light/dark, chime, rail, tour seen),
2162
2253
  // stored per account so they follow the person across browsers and devices
2163
2254
  // (src/user-prefs.ts). A PERSON's: an agent or a peer is refused — it has no
@@ -10080,6 +10171,9 @@ async function finishTurn(s) {
10080
10171
  s.lastDialogKey = null;
10081
10172
  broadcast(s, { type: "turn-done", sessionId: s.id });
10082
10173
  maybeScheduleRetry(s);
10174
+ // A turn that said nothing (a quiet cron: NOTHING TO SHOW) wakes nobody.
10175
+ if (!s.lastTurnSilent)
10176
+ pushAttention(s, "done", s.recentTexts[s.recentTexts.length - 1] ?? "");
10083
10177
  // As a CHILD: tell whoever launched this agent that it is done, with its
10084
10178
  // own last block as the summary — what it wrote to be read.
10085
10179
  notifyParent(s, { kind: "done", summary: s.recentTexts[s.recentTexts.length - 1], silent: s.lastTurnSilent });
@@ -10178,6 +10272,76 @@ function sendPendingDialog(s, send) {
10178
10272
  * else that ever bypasses `finishTurn` — the dedup key is what makes that
10179
10273
  * affordable three times a second.
10180
10274
  */
10275
+ /**
10276
+ * Push the attention signal to the subscribed devices: an agent asked a
10277
+ * question, or finished a turn that produced something.
10278
+ *
10279
+ * Fire-and-forget: a push service that is slow or down must never delay the
10280
+ * turn. Skipped for a muted agent or a muted instance — the same switches that
10281
+ * silence the page's badge and chime, so "mute" means one thing everywhere.
10282
+ * Each device's ACCOUNT must still be able to see the agent at send time
10283
+ * (group membership changes after subscribing), and a dead endpoint (404/410)
10284
+ * is dropped so it does not cost a request per event forever.
10285
+ */
10286
+ function pushAttention(s, kind, text) {
10287
+ try {
10288
+ const st = loadPushState();
10289
+ if (!st.subs.length)
10290
+ return;
10291
+ const cfg = loadConfig();
10292
+ if (mutedForCwd(cfg, process.cwd()))
10293
+ return;
10294
+ const chans = loadChannels();
10295
+ const chan = chans.find((c) => c.sessionId === s.id);
10296
+ if (chan?.muted)
10297
+ return;
10298
+ const groups = loadGroups();
10299
+ const accounts = loadAccounts();
10300
+ const targets = st.subs.filter((sub) => {
10301
+ if (DEPLOYMENT_MODE !== "multi-tenant")
10302
+ return true;
10303
+ const role = sub.user === BOOTSTRAP_ADMIN ? "admin" : accounts.find((a) => a.name === sub.user)?.role;
10304
+ if (!role)
10305
+ return false; // the account was deleted
10306
+ return canSeeSession(s.id, chans, groups, viewerFor({ name: sub.user, role }));
10307
+ });
10308
+ if (!targets.length)
10309
+ return;
10310
+ const who = chan?.name || s.id.slice(0, 8);
10311
+ const cockpit = titleForCwd(cfg, process.cwd());
10312
+ const msg = {
10313
+ title: cockpit ? `${who} · ${cockpit}` : who,
10314
+ body: preview(text) || (kind === "question" ? "Waiting for your answer." : "Finished."),
10315
+ // One live notification per agent: the next one replaces it.
10316
+ tag: `agent-${s.id}`,
10317
+ url: `/#agent=${s.id}`,
10318
+ };
10319
+ if (kind === "question")
10320
+ msg.body = `❓ ${msg.body}`;
10321
+ void deliverPush(targets, msg).catch(() => { });
10322
+ }
10323
+ catch (e) {
10324
+ console.warn(`push: ${e.message}`);
10325
+ }
10326
+ }
10327
+ /** Send to each device, drop the dead ones, log the failures once each. */
10328
+ async function deliverPush(targets, msg) {
10329
+ const st = loadPushState();
10330
+ const subject = process.env.SHADOK_PUSH_SUBJECT || "https://github.com/shadok-ai/shadok-ai";
10331
+ const out = await Promise.all(targets.map(async (sub) => {
10332
+ const r = await sendPush(sub, msg, st.vapid, subject);
10333
+ if (!r.ok)
10334
+ console.warn(`push: ${sub.device ?? "device"} → ${r.status || "network"} ${r.error}`);
10335
+ return { sub, ok: r.ok, status: r.status, error: r.ok ? undefined : r.error, gone: !r.ok && r.gone };
10336
+ }));
10337
+ const gone = new Set(out.filter((r) => r.gone).map((r) => r.sub.endpoint));
10338
+ if (gone.size) {
10339
+ const fresh = loadPushState();
10340
+ fresh.subs = dropEndpoints(fresh.subs, gone);
10341
+ savePushState(fresh);
10342
+ }
10343
+ return out;
10344
+ }
10181
10345
  function publishDialog(s, d) {
10182
10346
  if (isResumeSummaryDialog(d))
10183
10347
  return;
@@ -10193,6 +10357,8 @@ function publishDialog(s, d) {
10193
10357
  return;
10194
10358
  s.lastDialogKey = key;
10195
10359
  broadcast(s, dialogMessage(s, d));
10360
+ // Same funnel, same dedup: one push per NEW question, whichever path raised it.
10361
+ pushAttention(s, "question", d.question);
10196
10362
  // A child blocked on a question is the deadlock this whole thing exists to
10197
10363
  // break: its turn is suspended, and its parent believes it is still working.
10198
10364
  // Hooking HERE covers every path — including raw `key` input — because this