@join-pantheon/cli 0.35.0 → 0.35.1-rc.2

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 (52) hide show
  1. package/dist/agent-outage.js +165 -35
  2. package/dist/agent-token.js +5 -3
  3. package/dist/agents.js +6 -4
  4. package/dist/approvals-list.js +87 -0
  5. package/dist/board.js +491 -88
  6. package/dist/brief.js +17 -0
  7. package/dist/cli.js +687 -95
  8. package/dist/client.js +159 -19
  9. package/dist/config.js +3 -2
  10. package/dist/continued.js +56 -1
  11. package/dist/decision-ui.js +5 -3
  12. package/dist/doctor.js +84 -16
  13. package/dist/file-lock.js +40 -5
  14. package/dist/flow-stats.js +18 -1
  15. package/dist/home-guard.js +336 -54
  16. package/dist/home-safety.js +2 -0
  17. package/dist/hud-queue.js +91 -0
  18. package/dist/install.js +15 -1
  19. package/dist/mcp-instructions.js +67 -28
  20. package/dist/mcp.js +129 -24
  21. package/dist/notice-linux.js +15 -4
  22. package/dist/notice-windows.js +2 -2
  23. package/dist/notifier.js +2 -1
  24. package/dist/notify.js +28 -9
  25. package/dist/open-in.js +4 -3
  26. package/dist/pickup.js +17 -0
  27. package/dist/plain.js +139 -3
  28. package/dist/profile.js +12 -8
  29. package/dist/protocol.js +1 -1
  30. package/dist/question-goal.js +74 -0
  31. package/dist/readiness-alert.js +24 -3
  32. package/dist/refusal.js +2 -2
  33. package/dist/relay.js +143 -28
  34. package/dist/removed.js +4 -4
  35. package/dist/run-control.js +4 -3
  36. package/dist/run-failure.js +67 -10
  37. package/dist/setup-changes.js +7 -6
  38. package/dist/signed-out.js +144 -21
  39. package/dist/spend.js +5 -4
  40. package/dist/tray.js +24 -6
  41. package/dist/update-check.js +2 -1
  42. package/dist/uri-handler.js +10 -2
  43. package/dist/which.js +2 -0
  44. package/dist/worker-policy.js +212 -10
  45. package/dist/worker.js +942 -133
  46. package/dist/worklist.js +31 -1
  47. package/helper/macos/main.swift +42 -3
  48. package/helper/macos/menubar.swift +482 -87
  49. package/helper/macos/prebuilt/manifest.json +5 -5
  50. package/helper/macos/prebuilt/pantheon-hud +0 -0
  51. package/helper/macos/prebuilt/pantheon-tray +0 -0
  52. package/package.json +1 -1
package/dist/board.js CHANGED
@@ -16,6 +16,7 @@ import { withoutAgentMarkers } from "./setup-changes.js";
16
16
  import { shellArg } from "./team-name.js";
17
17
  import { POLL_MS, powerNow } from "./power.js";
18
18
  import { runsTodayLine } from "./spend.js";
19
+ import { QUEUED_SURFACE_WAIT_MS } from "./hud-queue.js";
19
20
  const HERE = dirname(fileURLToPath(import.meta.url));
20
21
  export const CLI_ENTRY = resolve(HERE, "cli.js");
21
22
  export const BOARD_IDLE_MS = 30 * 60_000;
@@ -63,15 +64,17 @@ export function clearBoardState(pid, home = CONFIG_DIR) {
63
64
  export const LINK_TTL_MS = 30_000;
64
65
  export const boardLink = (port, nonce) => `http://127.0.0.1:${port}/#open=${nonce}`;
65
66
  export const FOCUS_RE = /^[ao]_[A-Za-z0-9]{6,48}$/;
66
- export function focusLink(link, focus) {
67
+ export const FOCUS_TEAM_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
68
+ export function focusLink(link, focus, team) {
67
69
  if (!FOCUS_RE.test(focus))
68
70
  throw new Error("not an act or decision id");
69
- return `${link}~focus=${focus}`;
71
+ return `${link}~focus=${focus}${team && FOCUS_TEAM_RE.test(team) ? `~team=${team}` : ""}`;
70
72
  }
71
73
  const TOKEN_RE = /^[0-9a-f]{64}$/;
72
74
  const ID_RE = /^[A-Za-z0-9_-]{1,80}$/;
73
75
  const MAX_BODY_BYTES = 64 * 1024;
74
76
  const SENT_KEEP_MS = 10 * 60_000;
77
+ const CLIENT_RE = /^[0-9a-f]{32}$/;
75
78
  async function openInNow(home) {
76
79
  try {
77
80
  const oi = await import("./open-in.js");
@@ -209,6 +212,9 @@ export function explainOutcome(r, nonce) {
209
212
  const notSent = /^not sent: (.*)$/m.exec(out);
210
213
  if (notSent)
211
214
  return { ok: false, message: notSent[1].trim() };
215
+ const unsure = /^unconfirmed: (.*)$/m.exec(out);
216
+ if (unsure)
217
+ return { ok: false, message: unsure[1].trim(), unsure: true };
212
218
  if (nonce !== undefined && !new RegExp(`^action ${nonce}$`, "m").test(out)) {
213
219
  return { ok: false, message: "another window took that action before it ran — nothing was sent from here; try again" };
214
220
  }
@@ -225,6 +231,9 @@ export function explainOutcome(r, nonce) {
225
231
  return { ok: true, message: stopped[1].replace(/^./, (c) => c.toUpperCase()) };
226
232
  if (r.code === 0)
227
233
  return { ok: true, message: "Done." };
234
+ const took = nonce !== undefined ? new RegExp(`^action ${nonce}$`, "m").test(out) : /^action [0-9a-f]+$/m.test(out);
235
+ if (took)
236
+ return { ok: false, unsure: true, message: "Pantheon stopped before it said whether this went through — check the thread before trying again." };
228
237
  const last = err.split("\n").map((l) => l.trim()).filter((l) => l && !/^pantheon \d|update available|upgrade/i.test(l)).at(-1);
229
238
  return { ok: false, message: last ? last.slice(0, 300) : "the relay could not be reached" };
230
239
  }
@@ -246,7 +255,7 @@ export function hudActionFor(op, item) {
246
255
  case "reply":
247
256
  if (op.kind === "ANSWER" && item.kind !== "decision")
248
257
  return { error: "only the person it waits on can answer it — add a note or ask back" };
249
- return { action: "reply", kind: op.kind, body: op.body, ...goal, ...space, ...(item.kind === "decision" ? { decision: item.id } : {}), ...ref };
258
+ return { action: "reply", kind: op.kind, body: op.body, ...goal, ...space, decision: item.id, ...ref };
250
259
  case "wake-allow":
251
260
  case "wake-deny":
252
261
  if (item.kind !== "decision" || !item.wake || !item.ref)
@@ -267,7 +276,7 @@ export function hudActionFor(op, item) {
267
276
  }
268
277
  }
269
278
  export function parseBoardAction(raw) {
270
- const v = strictObject(raw, ["op", "id", "space", "index", "kind", "body", "act"]);
279
+ const v = strictObject(raw, ["op", "id", "space", "index", "kind", "body", "act", "client"]);
271
280
  if (!v)
272
281
  return null;
273
282
  const space = v.space === undefined ? undefined : str(v.space, SPACE_RE);
@@ -297,7 +306,7 @@ export function parseBoardAction(raw) {
297
306
  return only(["index"]) && Number.isInteger(v.index) && v.index >= 0 && v.index < 10
298
307
  ? { op: "choose", id, ...sp, index: v.index } : null;
299
308
  case "reply": {
300
- if (!only(["kind", "body"]))
309
+ if (!only(["kind", "body", "client"]))
301
310
  return null;
302
311
  if (v.kind !== "ANSWER" && v.kind !== "NOTE" && v.kind !== "ASK")
303
312
  return null;
@@ -306,7 +315,10 @@ export function parseBoardAction(raw) {
306
315
  const body = v.body.trim();
307
316
  if (!body || body.length > LIMITS.bodyChars)
308
317
  return null;
309
- return { op: "reply", id, ...sp, kind: v.kind, body };
318
+ const client = v.client === undefined ? undefined : str(v.client, CLIENT_RE);
319
+ if (client === null)
320
+ return null;
321
+ return { op: "reply", id, ...sp, kind: v.kind, body, ...(client ? { client } : {}) };
310
322
  }
311
323
  default: return null;
312
324
  }
@@ -323,6 +335,7 @@ export async function startBoardServer(o = {}) {
323
335
  let port = 0;
324
336
  let lastStatus = null;
325
337
  const sent = new Map();
338
+ const outcomes = new Map();
326
339
  let chain = Promise.resolve();
327
340
  const serial = (fn) => { const p = chain.then(fn, fn); chain = p.catch(() => { }); return p; };
328
341
  const origins = () => [`http://127.0.0.1:${port}`, `http://localhost:${port}`];
@@ -382,6 +395,8 @@ export async function startBoardServer(o = {}) {
382
395
  }
383
396
  return match(await status());
384
397
  };
398
+ const settledHere = new Map();
399
+ const settledKey = (id, space) => `${space ?? ""}|${id}`;
385
400
  const knownSpace = async (space) => {
386
401
  const s = lastStatus?.status ?? await status();
387
402
  return (s.spaces ?? (s.space ? [s.space] : [])).includes(space);
@@ -410,7 +425,7 @@ export async function startBoardServer(o = {}) {
410
425
  const runQueued = (a, extra = []) => serial(async () => {
411
426
  const { text, nonce } = writeAction(a);
412
427
  try {
413
- return { r: await deps.cli(["explain", "--queued", "--only-action", "--action-id", nonce, ...extra], 30_000), nonce };
428
+ return { r: await deps.cli(["explain", "--queued", "--only-action", "--action-id", nonce, ...extra], QUEUED_SURFACE_WAIT_MS), nonce };
414
429
  }
415
430
  finally {
416
431
  dropOurs(text);
@@ -606,17 +621,37 @@ export async function startBoardServer(o = {}) {
606
621
  const r = explainOutcome(q.r, q.nonce);
607
622
  if (r.ok)
608
623
  sent.delete(op.act);
609
- sendJson(res, 200, { ok: r.ok, message: r.ok ? "Retracted." : r.message });
624
+ sendJson(res, 200, { ok: r.ok, message: r.ok ? "Retracted." : r.message, ...(r.unsure ? { unsure: true } : {}) });
610
625
  return;
611
626
  }
612
- const item = await findItem(op.id, op.space);
627
+ const client = op.op === "reply" ? op.client : undefined;
628
+ if (client) {
629
+ for (const [k, v] of outcomes)
630
+ if (deps.now() - v.at > SENT_KEEP_MS)
631
+ outcomes.delete(k);
632
+ if (outcomes.has(client)) {
633
+ sendJson(res, 200, { ok: false, message: "that reply was already sent from this page — it is not sent twice" });
634
+ return;
635
+ }
636
+ outcomes.set(client, { at: deps.now(), state: "pending" });
637
+ }
638
+ const answer = (code, body) => {
639
+ if (client)
640
+ outcomes.set(client, { at: deps.now(), state: "done", result: { ok: body.ok && code === 200, ...(body.message ?? body.error ? { message: body.message ?? body.error } : {}), ...(body.sent ? { sent: body.sent } : {}), ...(body.unsure ? { unsure: true } : {}) } });
641
+ sendJson(res, code, body);
642
+ };
643
+ for (const [k, v] of settledHere)
644
+ if (deps.now() - v.at > SENT_KEEP_MS)
645
+ settledHere.delete(k);
646
+ const item = await findItem(op.id, op.space)
647
+ ?? (op.op === "reply" && op.kind !== "ANSWER" ? settledHere.get(settledKey(op.id, op.space))?.item ?? null : null);
613
648
  if (!item) {
614
- sendJson(res, 200, { ok: false, message: "that is no longer on your board" });
649
+ answer(200, { ok: false, message: "that is no longer on your board" });
615
650
  return;
616
651
  }
617
652
  const hud = hudActionFor(op, item);
618
653
  if ("error" in hud) {
619
- sendJson(res, 400, { ok: false, error: hud.error });
654
+ answer(400, { ok: false, error: hud.error });
620
655
  return;
621
656
  }
622
657
  if (op.op === "open" && await openInNow(home) === "app") {
@@ -636,13 +671,25 @@ export async function startBoardServer(o = {}) {
636
671
  sendJson(res, 200, { ok: true, message: hud.allow ? `${hud.member} may start work on this machine — their waiting request runs now` : `Declined — ${hud.member}'s requests wait for you (pantheon wake allow ${hud.member} changes it)` });
637
672
  return;
638
673
  }
674
+ if (r.ok && (op.op === "choose" || op.op === "done" || (op.op === "reply" && op.kind === "ANSWER")))
675
+ settledHere.set(settledKey(item.id, op.space), { item, at: deps.now() });
639
676
  if (r.sent) {
640
677
  sent.set(r.sent.id, { ...(item.space ? { space: item.space } : {}), at: deps.now() });
641
678
  for (const [k, v] of sent)
642
679
  if (deps.now() - v.at > SENT_KEEP_MS)
643
680
  sent.delete(k);
644
681
  }
645
- sendJson(res, 200, { ok: r.ok, message: r.message, ...(r.sent ? { sent: r.sent.id } : {}) });
682
+ answer(200, { ok: r.ok, message: r.message, ...(r.sent ? { sent: r.sent.id } : {}), ...(r.unsure ? { unsure: true } : {}) });
683
+ return;
684
+ }
685
+ if (method === "GET" && url.pathname === "/api/outcome") {
686
+ const client = str(url.searchParams.get("client"), CLIENT_RE);
687
+ if (!client) {
688
+ sendJson(res, 400, { ok: false, error: "bad request" });
689
+ return;
690
+ }
691
+ const o2 = outcomes.get(client);
692
+ sendJson(res, 200, { ok: true, state: o2 ? o2.state : "unknown", ...(o2?.result ? { result: o2.result } : {}) });
646
693
  return;
647
694
  }
648
695
  sendJson(res, 404, { ok: false, error: "not found" });
@@ -676,7 +723,7 @@ export async function startBoardServer(o = {}) {
676
723
  }
677
724
  return { port, token, get url() { return mintLink(); }, link: mintLink, server, get keep() { return keep; }, close, lastSeen: () => lastSeen };
678
725
  }
679
- const LINK_RE = /^http:\/\/127\.0\.0\.1:\d{1,5}\/#open=[0-9a-f]{64}(?:~focus=[ao]_[A-Za-z0-9]{6,48})?$/;
726
+ const LINK_RE = /^http:\/\/127\.0\.0\.1:\d{1,5}\/#open=[0-9a-f]{64}(?:~focus=[ao]_[A-Za-z0-9]{6,48}(?:~team=[A-Za-z0-9][A-Za-z0-9._-]{0,63})?)?$/;
680
727
  export function inServiceCgroup(read = (p) => readFileSync(p, "utf8"), os = platform()) {
681
728
  if (os !== "linux")
682
729
  return false;
@@ -1079,6 +1126,11 @@ export function boardHtml(nonce) {
1079
1126
  <div id="problem" class="banner problem" role="status" hidden><strong id="problem-lead"></strong> <span id="problem-text"></span></div>
1080
1127
  <div id="stuck" class="banner problem" role="status" hidden></div>
1081
1128
  <ul id="gone" class="gone" hidden></ul>
1129
+ <section id="unsent" class="unsent" aria-labelledby="h-unsent" hidden>
1130
+ <h2 id="h-unsent">Not sent</h2>
1131
+ <p class="muted">Words you typed on something that is no longer on your board. Copy what you still need.</p>
1132
+ <ul id="l-unsent" class="gone"></ul>
1133
+ </section>
1082
1134
  <div id="banner" class="banner" role="alert" hidden></div>
1083
1135
  <main id="board" tabindex="-1" aria-busy="true">
1084
1136
  <p id="loading" class="muted">Loading your board…</p>
@@ -1155,6 +1207,10 @@ button[disabled]{opacity:.55;cursor:default}
1155
1207
  .gone{max-width:980px;margin:12px auto 0;padding:0;list-style:none}
1156
1208
  .gone>li{display:flex;flex-wrap:wrap;align-items:center;gap:8px 12px;padding:10px 14px;border:1px solid var(--line);border-radius:8px;background:var(--card);margin:0 0 8px;overflow-wrap:anywhere}
1157
1209
  .empty{margin:4px 0}
1210
+ .unsent{max-width:980px;margin:12px auto 0}
1211
+ .unsent>h2{font-size:1rem;margin:0 0 4px}
1212
+ .unsent .words{flex:1 1 100%;margin:0;white-space:pre-wrap;overflow-wrap:anywhere}
1213
+ @media (max-width:1012px){.unsent{margin-left:16px;margin-right:16px}}
1158
1214
  dialog{border:1px solid var(--line);border-radius:12px;padding:0;background:var(--card);color:var(--text);width:min(760px,96vw);max-height:92vh}
1159
1215
  dialog::backdrop{background:rgba(0,0,0,.45)}
1160
1216
  .dlg{padding:18px 20px}
@@ -1194,9 +1250,10 @@ let link = null;
1194
1250
  let session = null;
1195
1251
  // The item an alert opened the board on ("Approve or decline"): shown first, once.
1196
1252
  let focus = null;
1253
+ let focusTeam = null; // its team, when the link names one: the same id in two teams opens the right one (#110)
1197
1254
  {
1198
- const m = /^#open=([0-9a-f]{64})(?:~focus=([ao]_[A-Za-z0-9]{6,48}))?$/.exec(location.hash);
1199
- if (m) { link = m[1]; focus = m[2] || null; }
1255
+ const m = /^#open=([0-9a-f]{64})(?:~focus=([ao]_[A-Za-z0-9]{6,48})(?:~team=([A-Za-z0-9][A-Za-z0-9._-]{0,63}))?)?$/.exec(location.hash);
1256
+ if (m) { link = m[1]; focus = m[2] || null; focusTeam = m[3] || null; }
1200
1257
  // The nonce leaves the address bar and this history entry before anything else runs.
1201
1258
  history.replaceState(null, "", "/");
1202
1259
  }
@@ -1212,7 +1269,116 @@ const drafts = new Map(); // keyOf(item) -> { text, kind }: the words and the
1212
1269
  // A click's dialog closes only if it is still the dialog of what was clicked (#79): never the one opened since.
1213
1270
  const closeIf = (item, r) => { if (r && r.ok && keyOf(current) === keyOf(item)) $("detail").close(); };
1214
1271
  const sentFor = new Map(); // keyOf(item) -> { sent, until }
1215
- let retractTimer = null;
1272
+ // A send in flight belongs to its decision (#105, #110): Send is off for that decision only, also
1273
+ // after it is closed and opened again, and every other decision can still be answered meanwhile.
1274
+ const inFlight = new Map(); // keyOf(item) -> { text, kind, at, client, name }: the words being sent
1275
+ const retracting = new Set(); // keyOf(item) of a retract in flight
1276
+ // Any other action in flight on a decision — a choice, an option, Mark done, Approve (0.35.1 review,
1277
+ // item 5): one action per decision at a time, so two clicks never put two answers on the record.
1278
+ const acting = new Set(); // keyOf(item)
1279
+ const busyOn = (k) => inFlight.has(k) || acting.has(k);
1280
+ // Words just sent, still at the front of the box (round two): a Send of them again asks once first.
1281
+ const resendGuard = new Map(); // keyOf(item) -> the words sent
1282
+ // A decision answered from here: a second Send as an ANSWER would be refused (ALREADY_ANSWERED);
1283
+ // the rest of the words go as a Note (round three, F10).
1284
+ const answeredHere = new Set();
1285
+ // Each draft's decision name, so words typed on one that has left the board can still be shown — and
1286
+ // copied — under "Not sent" (round three, F9).
1287
+ const names = new Map(); // keyOf(item) -> its headline
1288
+ // Decisions this page retracted an answer on (keyOf -> the item as it was): the relay puts each back as
1289
+ // a new row, which followMoved follows — that row only (round four, narrowed in the final round).
1290
+ const retracted = new Map();
1291
+ const resendAsked = new Set();
1292
+ // How something went, for a decision that was not open then (0.35.1 review, item 15): a toast is
1293
+ // gone in seconds; this is shown when the decision is opened next.
1294
+ const notes = new Map(); // keyOf(item) -> the words
1295
+ let retractView = null; // hides the open decision's Retract when its minute is up
1296
+ let openSeq = 0; // which opening of the dialog a late detail belongs to
1297
+ const nameOf = (item) => (item && (item.headline || item.title)) || "that decision";
1298
+ // Drafts and the minute to Retract survive a reload of this tab (#110): sessionStorage, this tab
1299
+ // and this board only, gone when the tab closes — never kept past the tab, never sent as a cookie.
1300
+ const LOCAL_KEY = "pantheon-board-drafts";
1301
+ const ACT_ID = /^a_[A-Za-z0-9]{6,48}$/;
1302
+ function saveLocal() {
1303
+ try {
1304
+ const now = Date.now();
1305
+ sessionStorage.setItem(LOCAL_KEY, JSON.stringify({ drafts: [...drafts], names: [...names].filter(([k]) => drafts.has(k)), sent: [...sentFor].filter(([, v]) => v.until > now),
1306
+ inflight: [...inFlight].map(([k, f]) => [k, { text: f.text, kind: f.kind, at: f.at, client: f.client, name: f.name }]) }));
1307
+ } catch { /* storage off: this page only */ }
1308
+ }
1309
+ try {
1310
+ const j = JSON.parse(sessionStorage.getItem(LOCAL_KEY) || "null");
1311
+ const now = Date.now();
1312
+ if (j && Array.isArray(j.drafts)) for (const e of j.drafts) {
1313
+ if (Array.isArray(e) && typeof e[0] === "string" && e[1] && typeof e[1].text === "string" && e[1].text.length <= 20000 && ["ANSWER", "NOTE", "ASK"].includes(e[1].kind)) drafts.set(e[0], { text: e[1].text, kind: e[1].kind });
1314
+ }
1315
+ if (j && Array.isArray(j.names)) for (const e of j.names) {
1316
+ if (Array.isArray(e) && typeof e[0] === "string" && typeof e[1] === "string" && drafts.has(e[0])) names.set(e[0], e[1].slice(0, 300));
1317
+ }
1318
+ if (j && Array.isArray(j.sent)) for (const e of j.sent) {
1319
+ if (Array.isArray(e) && typeof e[0] === "string" && e[1] && typeof e[1].sent === "string" && ACT_ID.test(e[1].sent) && typeof e[1].until === "number" && e[1].until > now && e[1].until <= now + 60000) sentFor.set(e[0], { sent: e[1].sent, until: e[1].until });
1320
+ }
1321
+ // A reply still on its way when this tab was reloaded: Send stays off until the board says how it went.
1322
+ if (j && Array.isArray(j.inflight)) for (const e of j.inflight) {
1323
+ const f = Array.isArray(e) && e[1];
1324
+ if (typeof e[0] === "string" && f && typeof f.text === "string" && f.text.length <= 20000 && ["ANSWER", "NOTE", "ASK"].includes(f.kind)
1325
+ && typeof f.client === "string" && /^[0-9a-f]{32}$/.test(f.client) && typeof f.at === "number" && f.at <= now + 1000) {
1326
+ const name = typeof f.name === "string" ? f.name.slice(0, 300) : "that decision";
1327
+ if (now - f.at < 10 * 60_000) inFlight.set(e[0], { text: f.text, kind: f.kind, at: f.at, client: f.client, name, restored: true });
1328
+ else {
1329
+ // Too old to ask the board about: never dropped silently (0.35.1 review, item 16) — the words
1330
+ // are kept on the decision, and it says why.
1331
+ const dr = drafts.get(e[0]);
1332
+ if (!dr || !dr.text.trim()) drafts.set(e[0], { text: f.text, kind: f.kind });
1333
+ else if (!dr.text.trimStart().startsWith(f.text)) drafts.set(e[0], { text: f.text + "\\n\\n" + dr.text, kind: dr.kind });
1334
+ notes.set(e[0], "Your reply may have been sent — check the thread before sending it again. Your words are kept on it.");
1335
+ }
1336
+ }
1337
+ }
1338
+ saveLocal();
1339
+ } catch { /* nothing kept, or storage off */ }
1340
+ /** The open decision's Send and Retract, from its own state: never another decision's. */
1341
+ function syncControls() {
1342
+ const k = keyOf(current);
1343
+ $("d-send").disabled = busyOn(k);
1344
+ const s = sentFor.get(k);
1345
+ const live = !!(s && s.until > Date.now());
1346
+ $("d-retract").hidden = !live;
1347
+ $("d-retract").disabled = retracting.has(k);
1348
+ if (retractView) { clearTimeout(retractView); retractView = null; }
1349
+ if (live) retractView = setTimeout(() => { if (keyOf(current) === k) $("d-retract").hidden = true; }, s.until - Date.now() + 50);
1350
+ }
1351
+ /**
1352
+ * A decision settled by a button (a choice, an option, Mark done, Approve): what was typed
1353
+ * on it was not sent, and goes with the decision — said, never dropped silently (#110).
1354
+ */
1355
+ function settled(item, r) {
1356
+ if (!(r && r.ok)) return false;
1357
+ const k = keyOf(item);
1358
+ // What was typed on it — in the box (also words typed after the click, while it went) or kept as
1359
+ // its draft — is never dropped (round two of the 0.35.1 review). Its own outcome is said with it —
1360
+ // r.said, never the shared toast, which another decision's result may have replaced by now (round
1361
+ // three, F4). Returns true when its dialog stays open for it.
1362
+ const dr = drafts.get(k);
1363
+ const box = keyOf(current) === k ? $("d-text").value : "";
1364
+ const words = box.trim() ? box : dr && dr.text.trim() ? dr.text : "";
1365
+ if (!words) return false;
1366
+ const said = r.said || "";
1367
+ if (current && keyOf(current) !== k) {
1368
+ // Another decision is open, and the person may be typing on it (round three, F8): never switched
1369
+ // away from. The words are kept on this one — listed under "Not sent" once it leaves the board.
1370
+ drafts.set(k, { text: words, kind: (dr && dr.kind) || "NOTE" }); names.set(k, nameOf(item)); saveLocal();
1371
+ const msg = (said ? said + " " : "") + "What you typed on it was not sent — it is kept under Not sent, to copy if you still need it.";
1372
+ notes.set(k, msg);
1373
+ toast("“" + nameOf(item) + "”: " + msg);
1374
+ renderUnsent();
1375
+ return false;
1376
+ }
1377
+ if (keyOf(current) !== k) openDetail(item);
1378
+ $("d-text").value = words;
1379
+ setStatus((said ? said + " " : "") + "What you typed on it was not sent — copy it if you still need it.");
1380
+ return true;
1381
+ }
1216
1382
  let timer = null;
1217
1383
  let refreshMs = ${BOARD_REFRESH_MS};
1218
1384
 
@@ -1252,6 +1418,18 @@ function banner(msg, isError) {
1252
1418
  b.hidden = false;
1253
1419
  }
1254
1420
 
1421
+ // This page is being unloaded (a reload, closing the tab, a navigation): a send cut off by it is not
1422
+ // known to have failed, and its in-flight record is left exactly as it is, for the page that loads next
1423
+ // to ask the board about (/api/outcome) — never put back as unsent, never released (0.35.1-rc.1 re-check:
1424
+ // the old page's error handler turned Send back on, and the same words went out twice).
1425
+ let leaving = false;
1426
+ if (typeof addEventListener === "function") {
1427
+ addEventListener("pagehide", () => { leaving = true; });
1428
+ addEventListener("beforeunload", () => { leaving = true; });
1429
+ // Back from the browser's page cache after all: here again, and a send cut off meanwhile is asked
1430
+ // about like one found after a reload.
1431
+ addEventListener("pageshow", () => { leaving = false; for (const f of inFlight.values()) if (f.unknown) f.restored = true; });
1432
+ }
1255
1433
  async function api(path, body, bearer) {
1256
1434
  const headers = { "Accept": "application/json" };
1257
1435
  const cred = bearer || session;
@@ -1260,7 +1438,11 @@ async function api(path, body, bearer) {
1260
1438
  if (body !== undefined) { headers["Content-Type"] = "application/json"; init.body = JSON.stringify(body); }
1261
1439
  let res;
1262
1440
  try { res = await fetch(path, init); }
1263
- catch { const e = new Error("gone"); e.gone = true; throw e; }
1441
+ catch (err) {
1442
+ // Cut off because this page is going away (a reload, a navigation): not "the board has stopped" —
1443
+ // nothing is known about what was sent (0.35.1-rc.1 re-check).
1444
+ const e = new Error("gone"); e.gone = true; e.aborted = leaving || !!(err && err.name === "AbortError"); throw e;
1445
+ }
1264
1446
  let j = null;
1265
1447
  try { j = await res.json(); } catch { j = null; }
1266
1448
  if (res.status === 401) { const e = new Error("auth"); e.auth = true; throw e; }
@@ -1333,6 +1515,29 @@ function render() {
1333
1515
  if (keep && keep.k) {
1334
1516
  for (const b of document.querySelectorAll("[data-k]")) if (b.dataset.k === keep.k && b.dataset.a === keep.a) { b.focus(); break; }
1335
1517
  }
1518
+ renderUnsent();
1519
+ }
1520
+
1521
+ /**
1522
+ * Words typed on decisions no longer on the board (settled elsewhere, or by a button here): listed to
1523
+ * copy, until discarded (round three, F9). Only when every team could be read — a team out of reach
1524
+ * is not news that its decisions are gone — and never one being sent or open now.
1525
+ */
1526
+ function renderUnsent() {
1527
+ const s = state;
1528
+ const host = $("l-unsent");
1529
+ const readable = s && s.configured && s.relay_ok !== false && s.decisions_ok !== false && !(s.unavailable_spaces || []).length;
1530
+ const onBoard = new Set((s && s.items || []).map((i) => keyOf(i)));
1531
+ const left = readable ? [...drafts].filter(([k, d]) => d && d.text.trim() && !onBoard.has(k) && !inFlight.has(k) && keyOf(current) !== k) : [];
1532
+ $("unsent").hidden = !left.length;
1533
+ host.replaceChildren(...left.map(([k, d]) => {
1534
+ const li = el("li");
1535
+ li.append(el("strong", "", names.get(k) || "Something no longer on your board"));
1536
+ li.append(el("p", "words", d.text));
1537
+ li.append(button("Copy", () => copy(d.text)));
1538
+ li.append(button("Discard", () => { drafts.delete(k); names.delete(k); notes.delete(k); saveLocal(); renderUnsent(); }));
1539
+ return li;
1540
+ }));
1336
1541
  }
1337
1542
 
1338
1543
  function tag(b, item, a) { b.dataset.k = key(item); b.dataset.a = a; return b; }
@@ -1367,15 +1572,15 @@ function row(item, card) {
1367
1572
  wakeButtons(item).forEach((b) => acts.append(b));
1368
1573
  acts.append(tag(button("Reply…", () => openDetail(item, true)), item, "reply"));
1369
1574
  } else if (card) {
1370
- (item.choices || []).forEach((c, idx) => acts.append(tag(button(c.label, (ev) => act({ op: "choose", id: item.id, space: item.space, index: idx }, ev.currentTarget, c.label + " — sent."), idx === 0 ? "primary" : ""), item, "c" + idx)));
1371
- if (item.kind === "decision") acts.append(tag(button("Mark done", (ev) => act({ op: "done", id: item.id, space: item.space }, ev.currentTarget), ""), item, "done"));
1575
+ (item.choices || []).forEach((c, idx) => acts.append(tag(button(c.label, (ev) => act({ op: "choose", id: item.id, space: item.space, index: idx }, ev.currentTarget, c.label + " — sent.", item).then((r) => settled(item, r)), idx === 0 ? "primary" : ""), item, "c" + idx)));
1576
+ if (item.kind === "decision") acts.append(tag(button("Mark done", (ev) => act({ op: "done", id: item.id, space: item.space }, ev.currentTarget, undefined, item).then((r) => settled(item, r)), ""), item, "done"));
1372
1577
  acts.append(tag(button("Reply…", () => openDetail(item, true)), item, "reply"));
1373
- acts.append(tag(button("Explain in " + surface(), (ev) => act({ op: "open", id: item.id, space: item.space }, ev.currentTarget)), item, "explain"));
1578
+ acts.append(tag(button("Explain in " + surface(), (ev) => act({ op: "open", id: item.id, space: item.space }, ev.currentTarget, undefined, item)), item, "explain"));
1374
1579
  } else {
1375
1580
  // Under "Your agents are handling": the person can take the request back, or stop the work.
1376
1581
  if (item.run) {
1377
- acts.append(tag(button("Take over", (ev) => act({ op: "takeover", id: item.id, space: item.space }, ev.currentTarget)), item, "takeover"));
1378
- acts.append(tag(button("Stop", (ev) => act({ op: "stop", id: item.id, space: item.space }, ev.currentTarget)), item, "stop"));
1582
+ acts.append(tag(button("Take over", (ev) => act({ op: "takeover", id: item.id, space: item.space }, ev.currentTarget, undefined, item)), item, "takeover"));
1583
+ acts.append(tag(button("Stop", (ev) => act({ op: "stop", id: item.id, space: item.space }, ev.currentTarget, undefined, item)), item, "stop"));
1379
1584
  }
1380
1585
  acts.append(tag(button("Details", () => openDetail(item)), item, "details"));
1381
1586
  }
@@ -1387,11 +1592,12 @@ function row(item, card) {
1387
1592
  // Approve and Decline are pantheon wake allow|deny for the teammate the
1388
1593
  // question is about; "Just this once" is the question's own one-run answer.
1389
1594
  function wakeButtons(item, after) {
1390
- const done = (r) => { if (after && r && r.ok) after(); };
1391
- const out = [tag(button("Approve " + item.wake, (ev) => act({ op: "wake-allow", id: item.id, space: item.space }, ev.currentTarget).then(done), "primary"), item, "wake-allow")];
1595
+ // Settled from the card or the dialog alike: what was typed on it goes, and that is said (item 17).
1596
+ const done = (r) => { if (r && r.ok) { if (after) after(r); else settled(item, r); } };
1597
+ const out = [tag(button("Approve " + item.wake, (ev) => act({ op: "wake-allow", id: item.id, space: item.space }, ev.currentTarget, undefined, item).then(done), "primary"), item, "wake-allow")];
1392
1598
  const once = (item.choices || []).findIndex((c) => c.answer === "allow once");
1393
- if (once >= 0) out.push(tag(button("Just this once", (ev) => act({ op: "choose", id: item.id, space: item.space, index: once }, ev.currentTarget, "Just this once — their request runs now.").then(done)), item, "wake-once"));
1394
- out.push(tag(button("Decline", (ev) => act({ op: "wake-deny", id: item.id, space: item.space }, ev.currentTarget).then(done)), item, "wake-deny"));
1599
+ if (once >= 0) out.push(tag(button("Just this once", (ev) => act({ op: "choose", id: item.id, space: item.space, index: once }, ev.currentTarget, "Just this once — their request runs now.", item).then(done)), item, "wake-once"));
1600
+ out.push(tag(button("Decline", (ev) => act({ op: "wake-deny", id: item.id, space: item.space }, ev.currentTarget, undefined, item).then(done)), item, "wake-deny"));
1395
1601
  return out;
1396
1602
  }
1397
1603
 
@@ -1409,18 +1615,37 @@ async function copy(text) {
1409
1615
  toast("Press Ctrl+C (or Cmd+C) to copy.");
1410
1616
  }
1411
1617
 
1412
- async function act(body, btn, okText) {
1618
+ async function act(body, btn, okText, item) {
1619
+ // A result names the decision it is about whenever that decision is not the one open (#110):
1620
+ // a toast never reads as news about whatever the person is looking at by then.
1621
+ const k = item ? keyOf(item) : null;
1622
+ const named = (msg) => (item && keyOf(current) !== k ? "“" + nameOf(item) + "”: " + msg : msg);
1623
+ // One action per decision at a time (0.35.1 review, item 5) — said, never a second answer.
1624
+ if (k && busyOn(k)) { toast(named("Still sending your last answer to this — wait for it to land.")); return null; }
1625
+ if (k) acting.add(k);
1413
1626
  if (btn) btn.disabled = true;
1414
- toast("Working…");
1627
+ if (k && keyOf(current) === k) syncControls();
1628
+ toast(named("Working…"));
1629
+ // A refusal or an unconfirmed result is the decision's news: kept for it if it is not open (item 15).
1630
+ const keep = (msg) => { if (k && keyOf(current) !== k) notes.set(k, msg); };
1415
1631
  try {
1416
1632
  const r = await api("/api/action", body);
1417
- toast(r.ok ? (okText || r.message) : "Not sent — " + r.message);
1633
+ const msg = r.ok ? (okText || r.message) : (r.unsure ? "Not confirmed — " : "Not sent — ") + r.message;
1634
+ if (r && typeof r === "object") r.said = msg; // this action's own outcome, for settled() (round three, F4)
1635
+ toast(named(msg));
1636
+ if (!r.ok) keep(msg);
1418
1637
  if (r.ok) await refresh();
1419
1638
  return r;
1420
1639
  } catch (e) {
1421
- toast(e.auth ? "This board link has expired. Run pantheon board to open a fresh one." : e.gone ? "The board has stopped. Run pantheon board to start it again." : "Not sent — " + e.message);
1640
+ const msg = e.auth ? "This board link has expired. Run pantheon board to open a fresh one." : e.gone ? "The board has stopped. Run pantheon board to start it again." : "Not sent — " + e.message;
1641
+ toast(named(msg));
1642
+ keep(msg);
1422
1643
  return null;
1423
- } finally { if (btn) btn.disabled = false; }
1644
+ } finally {
1645
+ if (k) acting.delete(k);
1646
+ if (btn) btn.disabled = false;
1647
+ if (k && keyOf(current) === k) syncControls();
1648
+ }
1424
1649
  }
1425
1650
 
1426
1651
  function ownerLine(item) {
@@ -1428,7 +1653,10 @@ function ownerLine(item) {
1428
1653
  if (item.kind === "decision") return "Yours to decide.";
1429
1654
  if (item.decider) return item.decider + "'s to decide. You can add a note or ask back.";
1430
1655
  if (item.kind === "owed") return "Your agent owes this. You can add a note or ask back.";
1431
- return "Waiting on " + item.who + ". You can add a note or ask back.";
1656
+ // An Ask back reaches the one teammate this row waits on; a row for "your agent" or for several
1657
+ // people names nobody it cannot reach (round four).
1658
+ const one = typeof item.who === "string" && /^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(item.who);
1659
+ return one ? "Waiting on " + item.who + ". You can add a note, or ask " + item.who + " again with Ask back." : "Waiting on " + item.who + ". You can add a note.";
1432
1660
  }
1433
1661
 
1434
1662
  function blocks(host, list) {
@@ -1444,6 +1672,7 @@ function setStatus(msg) { $("d-status").replaceChildren(); $("d-status").textCon
1444
1672
 
1445
1673
  async function openDetail(item, focusReply) {
1446
1674
  current = item;
1675
+ const seq = ++openSeq;
1447
1676
  const d = $("detail");
1448
1677
  $("d-title").textContent = item.headline || item.title;
1449
1678
  $("d-meta").textContent = [item.who, ago(item.when), item.space ? "team " + item.space : ""].filter(Boolean).join(" · ");
@@ -1453,29 +1682,34 @@ async function openDetail(item, focusReply) {
1453
1682
  blocks($("d-body"), [{ kind: "para", text: item.detail || "" }]);
1454
1683
  $("d-options").hidden = true; $("d-options").replaceChildren();
1455
1684
  const ch = $("d-choices"); ch.replaceChildren();
1456
- if (item.wake) wakeButtons(item, () => closeIf(item, { ok: true })).forEach((b) => ch.append(b));
1457
- else (item.choices || []).forEach((c, idx) => ch.append(button(c.label, (ev) => act({ op: "choose", id: item.id, space: item.space, index: idx }, ev.currentTarget, c.label + " — sent.").then((r) => closeIf(item, r)), idx === 0 ? "primary" : "")));
1685
+ if (item.wake) wakeButtons(item, (r) => { if (!settled(item, r)) closeIf(item, r); }).forEach((b) => ch.append(b));
1686
+ else (item.choices || []).forEach((c, idx) => ch.append(button(c.label, (ev) => act({ op: "choose", id: item.id, space: item.space, index: idx }, ev.currentTarget, c.label + " — sent.", item).then((r) => { if (!settled(item, r)) closeIf(item, r); }), idx === 0 ? "primary" : "")));
1458
1687
  ch.hidden = !(item.wake || (item.choices && item.choices.length));
1459
1688
  const kind = $("d-kind"); kind.replaceChildren();
1460
1689
  for (const [v, label] of (item.kind === "decision" ? [["ANSWER", "Answer"], ["NOTE", "Note"], ["ASK", "Ask back"]] : [["NOTE", "Note"], ["ASK", "Ask back"]])) { const o = el("option", "", label); o.value = v; kind.append(o); }
1461
1690
  { const dr = drafts.get(keyOf(item)); $("d-text").value = dr ? dr.text : ""; if (dr && dr.kind && [...$("d-kind").options].some((o) => o.value === dr.kind)) $("d-kind").value = dr.kind; }
1462
- setStatus("");
1463
- { const s = sentFor.get(keyOf(item)); $("d-retract").hidden = !(s && s.until > Date.now()); }
1691
+ {
1692
+ const k = keyOf(item), note = notes.get(k);
1693
+ if (busyOn(k)) setStatus("Still sending your last answer to this — Send works again once it lands.");
1694
+ else if (note) { notes.delete(k); setStatus(note); }
1695
+ else setStatus("");
1696
+ }
1697
+ syncControls();
1464
1698
  const actions = $("d-actions"); actions.replaceChildren();
1465
1699
  // A change to this person's setup: everything it would do is shown above, then Approve or Keep as is.
1466
1700
  $("d-reply").hidden = item.kind === "change";
1467
1701
  if (item.kind === "change") {
1468
1702
  blocks($("d-body"), (item.detail || "").split("\\n\\n").map((t) => ({ kind: "para", text: t })));
1469
- ch.append(button("Approve", (ev) => act({ op: "change-approve", id: item.id }, ev.currentTarget).then((r) => closeIf(item, r))));
1470
- ch.append(button("Keep as is", (ev) => act({ op: "change-keep", id: item.id }, ev.currentTarget).then((r) => closeIf(item, r))));
1703
+ ch.append(button("Approve", (ev) => act({ op: "change-approve", id: item.id }, ev.currentTarget, undefined, item).then((r) => { if (!settled(item, r)) closeIf(item, r); })));
1704
+ ch.append(button("Keep as is", (ev) => act({ op: "change-keep", id: item.id }, ev.currentTarget, undefined, item).then((r) => { if (!settled(item, r)) closeIf(item, r); })));
1471
1705
  ch.hidden = false;
1472
1706
  $("d-thread").hidden = true; $("d-thread").replaceChildren();
1473
1707
  if (!d.open) d.showModal();
1474
1708
  $("d-close").focus();
1475
1709
  return;
1476
1710
  }
1477
- if (item.kind === "decision" && !item.wake) actions.append(button("Mark done", (ev) => act({ op: "done", id: item.id, space: item.space }, ev.currentTarget).then((r) => closeIf(item, r))));
1478
- actions.append(button("Explain in " + surface(), (ev) => act({ op: "open", id: item.id, space: item.space }, ev.currentTarget)));
1711
+ if (item.kind === "decision" && !item.wake) actions.append(button("Mark done", (ev) => act({ op: "done", id: item.id, space: item.space }, ev.currentTarget, undefined, item).then((r) => { if (!settled(item, r)) closeIf(item, r); })));
1712
+ actions.append(button("Explain in " + surface(), (ev) => act({ op: "open", id: item.id, space: item.space }, ev.currentTarget, undefined, item)));
1479
1713
  if (item.goal && item.space) actions.append(button("Show the thread", () => thread(item)));
1480
1714
  actions.append(button("Copy the question", () => copy(item.prompt)));
1481
1715
  $("d-thread").hidden = true; $("d-thread").replaceChildren();
@@ -1485,11 +1719,14 @@ async function openDetail(item, focusReply) {
1485
1719
  try {
1486
1720
  const q = "/api/detail?id=" + encodeURIComponent(item.ref) + (item.space ? "&space=" + encodeURIComponent(item.space) : "");
1487
1721
  const j = await api(q);
1488
- if (current !== item || !j || !j.ok) return;
1722
+ // Only the opening that asked: a decision closed and opened again before its detail arrived
1723
+ // gets one set of options, not one per opening (#110).
1724
+ if (seq !== openSeq || current !== item || !j || !j.ok) return;
1489
1725
  if (Array.isArray(j.blocks) && j.blocks.length) blocks($("d-body"), j.blocks);
1490
1726
  if (item.kind === "decision" && Array.isArray(j.options) && j.options.length) {
1491
1727
  const host = $("d-options");
1492
- for (const o of j.options) host.append(button("(" + o.key + ") " + o.text, (ev) => act({ op: "reply", id: item.id, space: item.space, kind: "ANSWER", body: "(" + o.key + ") " + o.text }, ev.currentTarget, "Answered (" + o.key + ") — it is no longer waiting on you.").then((r) => closeIf(item, r))));
1728
+ host.replaceChildren();
1729
+ for (const o of j.options) host.append(button("(" + o.key + ") " + o.text, (ev) => act({ op: "reply", id: item.id, space: item.space, kind: "ANSWER", body: "(" + o.key + ") " + o.text }, ev.currentTarget, "Answered (" + o.key + ") — it is no longer waiting on you.", item).then((r) => { if (!settled(item, r)) closeIf(item, r); })));
1493
1730
  host.hidden = false;
1494
1731
  }
1495
1732
  } catch { /* the short text stays */ }
@@ -1512,65 +1749,213 @@ async function thread(item) {
1512
1749
  } catch (e) { host.replaceChildren(el("p", "muted", "The thread could not be read: " + e.message)); }
1513
1750
  }
1514
1751
 
1752
+ // Not sent: the words come back to their decision. Anything typed there since stays, after them —
1753
+ // unless it already starts with them (a follow-up typed onto the same words): then nothing is added,
1754
+ // so the words are never in the box twice (0.35.1 review, item 7).
1755
+ const startsWithSent = (v, text) => v.trimStart().startsWith(text);
1756
+ function putBack(k, text, kind) {
1757
+ const dr = drafts.get(k);
1758
+ if (!dr || !dr.text.trim()) drafts.set(k, { text, kind });
1759
+ else if (!startsWithSent(dr.text, text)) drafts.set(k, { text: text + "\\n\\n" + dr.text, kind: dr.kind || kind });
1760
+ saveLocal();
1761
+ if (keyOf(current) === k) {
1762
+ const box = $("d-text"), v = box.value.trim();
1763
+ if (!v) box.value = text; else if (!startsWithSent(v, text)) box.value = text + "\\n\\n" + box.value;
1764
+ }
1765
+ }
1766
+ /** What is left of v once the words that were sent are taken off its front (item 7): a follow-up typed onto them. */
1767
+ function afterSent(v, text) {
1768
+ const t = v.trimStart();
1769
+ return t.startsWith(text) ? t.slice(text.length).replace(/^\\s+/, "") : v;
1770
+ }
1771
+ /**
1772
+ * Told on the decision it is about: its own status line when open, else a toast naming it —
1773
+ * and kept as that decision's note, shown when it opens next (0.35.1 review, item 15).
1774
+ */
1775
+ function sayOn(k, name, msg) {
1776
+ if (keyOf(current) === k) { setStatus(msg); return; }
1777
+ toast("“" + name + "”: " + msg);
1778
+ notes.set(k, msg);
1779
+ }
1780
+ /** How a reply that left this page ended (r: { ok, message, sent }), told on its own decision. */
1781
+ function landed(k, f, r) {
1782
+ // Not confirmed: the relay's answer was lost and the reply is not found yet — it may have landed (#107).
1783
+ if (!r.ok) { putBack(k, f.text, f.kind); sayOn(k, f.name, (r.unsure ? "Not confirmed — " : "Not sent — ") + sentence(r.message) + (keyOf(current) === k ? " Your words are still in the box." : " Your words are kept on it.")); return; }
1784
+ // Only the words that were sent are cleared (#105). A follow-up typed onto them loses them from its
1785
+ // front (0.35.1 review, item 7) — but only when every edit since the send was typing at the end
1786
+ // (round two: "OK" sent, then "OK, but move the demo…" retyped or pasted, kept "…, but move" and
1787
+ // lost the person's words). Anything else is kept whole, and a Send of it that still starts with
1788
+ // what was sent asks once first.
1789
+ const said = f.kind === "ANSWER" ? "Answered — it is no longer waiting on you." : f.kind === "ASK" ? "Asked — the agent that raised this owes you a reply." : "Noted — it stays waiting.";
1790
+ const cut = (v) => (f.appendOnly === true ? afterSent(v, f.text) : v.trim() === f.text ? "" : v);
1791
+ const dr = drafts.get(k);
1792
+ if (dr) { const rest = cut(dr.text); if (rest.trim()) drafts.set(k, { text: rest, kind: dr.kind }); else drafts.delete(k); }
1793
+ if (r.sent) sentFor.set(k, { sent: r.sent, until: Date.now() + 60000 });
1794
+ saveLocal();
1795
+ let left = dr ? (drafts.get(k) || { text: "" }).text : "";
1796
+ if (keyOf(current) === k) { $("d-text").value = cut($("d-text").value); left = $("d-text").value; }
1797
+ // An answer settles the decision: a second one is refused (ALREADY_ANSWERED). What is left goes as a
1798
+ // Note, and the page says so instead of offering a Send that cannot work (round three, F10).
1799
+ if (f.kind === "ANSWER") answeredHere.add(k);
1800
+ if (left.trim() && left.trimStart().startsWith(f.text)) {
1801
+ resendGuard.set(k, f.text);
1802
+ sayOn(k, f.name, said + (f.kind === "ANSWER"
1803
+ ? " The box still starts with what you just sent — take that out, then switch to Note to send the rest."
1804
+ : " The box still starts with what you just sent — take that out, or press Send again to send it all as it is."));
1805
+ return;
1806
+ }
1807
+ if (left.trim() && f.kind === "ANSWER") { sayOn(k, f.name, said + " The rest is still in the box — switch to Note to send it."); return; }
1808
+ sayOn(k, f.name, said);
1809
+ }
1810
+ /** A reason that ends as a sentence, so what follows it reads as the next one. */
1811
+ const sentence = (m) => { const t = String(m || "").trim(); return !t || /[.!?…)]$/.test(t) ? t : t + "."; };
1812
+ function newClientId() { const a = new Uint8Array(16); crypto.getRandomValues(a); return Array.from(a, (b) => b.toString(16).padStart(2, "0")).join(""); }
1813
+
1515
1814
  async function send() {
1516
1815
  const item = current;
1517
1816
  if (!item) return;
1817
+ const k = keyOf(item);
1818
+ // One send per decision at a time: a second press, the same decision opened again, or the tab
1819
+ // reloaded while its reply is on the way — never sends the words twice (#105), and says why.
1820
+ if (busyOn(k)) { setStatus("Still sending your last answer to this — Send works again once it lands."); return; }
1518
1821
  const text = $("d-text").value.trim();
1519
1822
  if (!text) { setStatus("Type your reply first."); return; }
1823
+ if ($("d-kind").value === "ANSWER" && answeredHere.has(k)) {
1824
+ setStatus("This is already answered — switch to Note to send the rest.");
1825
+ return;
1826
+ }
1827
+ const again = resendGuard.get(k);
1828
+ if (again && text.startsWith(again) && !resendAsked.has(k)) {
1829
+ resendAsked.add(k);
1830
+ setStatus("This starts with words you already sent. Press Send again to send it all as it is, or take them out first.");
1831
+ return;
1832
+ }
1833
+ resendGuard.delete(k); resendAsked.delete(k);
1520
1834
  const kind = $("d-kind").value;
1521
- const btn = $("d-send");
1522
- if (btn.disabled) return;
1523
- btn.disabled = true;
1524
- setStatus("Sending…");
1525
- const k = keyOf(item);
1526
- const here = () => keyOf(current) === k; // still the decision this was sent from?
1835
+ // The page's own id for this send: after a reload, the board says how it went (/api/outcome).
1836
+ // appendOnly: every edit to the box since this send was typing at its end (round two, item 2a).
1837
+ const f = { text, kind, at: Date.now(), client: newClientId(), name: nameOf(item), appendOnly: true };
1838
+ inFlight.set(k, f);
1527
1839
  // In flight, the words are not a draft: reopening this decision meanwhile does not show them as unsent.
1528
1840
  drafts.delete(k);
1529
- const putBack = () => { if (!drafts.has(k)) drafts.set(k, { text, kind }); if (here() && !$("d-text").value) $("d-text").value = text; };
1530
- const name = item.headline || item.title || "that decision";
1841
+ saveLocal();
1842
+ syncControls();
1843
+ setStatus("Sending…");
1531
1844
  try {
1532
- const r = await api("/api/action", { op: "reply", id: item.id, space: item.space, kind, body: text });
1533
- if (!r.ok) {
1534
- putBack();
1535
- if (here()) setStatus("Not sent — " + r.message + " Your words are still in the box.");
1536
- else toast("Not sent to “" + name + "” — " + r.message + " Your words are kept on it.");
1537
- return;
1538
- }
1539
- drafts.delete(k);
1540
- const said = kind === "ANSWER" ? "Answered — it is no longer waiting on you." : kind === "ASK" ? "Asked — the agent that raised this owes you a reply." : "Noted — it stays waiting.";
1541
- if (r.sent) sentFor.set(k, { sent: r.sent, until: Date.now() + 60000 });
1542
- if (here()) {
1543
- $("d-text").value = "";
1544
- setStatus(said);
1545
- if (r.sent) {
1546
- $("d-retract").hidden = false;
1547
- if (retractTimer) clearTimeout(retractTimer);
1548
- retractTimer = setTimeout(() => { if (keyOf(current) === k) $("d-retract").hidden = true; sentFor.delete(k); }, 60000);
1549
- }
1550
- } else toast("“" + name + "”: " + said);
1551
- refresh();
1845
+ const r = await api("/api/action", { op: "reply", id: item.id, space: item.space, kind, body: text, client: f.client });
1846
+ if (inFlight.get(k) === f) landed(k, f, r);
1847
+ if (r.ok) refresh();
1552
1848
  } catch (e) {
1553
- putBack();
1554
- const why = e.auth ? "This board link has expired. Run pantheon board to open a fresh one." : "Not sent — " + (e.gone ? "the board has stopped." : e.message);
1555
- if (here()) setStatus(why + (e.auth ? "" : " Your words are still in the box."));
1556
- else toast("“" + name + "”: " + why + (e.auth ? "" : " Your words are kept on it."));
1557
- } finally { btn.disabled = false; }
1849
+ // Cut off by this page going away: unknown, not failed — the record stays for the next page.
1850
+ if (leaving || e.aborted) { f.unknown = true; return; }
1851
+ if (inFlight.get(k) === f) {
1852
+ putBack(k, text, kind);
1853
+ const why = e.auth ? "This board link has expired. Run pantheon board to open a fresh one." : "Not sent — " + (e.gone ? "the board has stopped." : e.message);
1854
+ sayOn(k, f.name, why + (e.auth ? "" : keyOf(current) === k ? " Your words are still in the box." : " Your words are kept on it."));
1855
+ }
1856
+ } finally {
1857
+ if (!f.unknown && !leaving && inFlight.get(k) === f) { inFlight.delete(k); saveLocal(); }
1858
+ if (keyOf(current) === k) syncControls();
1859
+ }
1860
+ }
1861
+
1862
+ /**
1863
+ * Sends this tab had on their way when it was reloaded (#105): asked of the board, which knows
1864
+ * how each went. Landed: told, as if the page had never gone. Still going: Send stays off. Not
1865
+ * known (an older board, or one started since): Send stays off for a bounded while, then the
1866
+ * person is told it may have been sent — never a silent second send.
1867
+ */
1868
+ const UNKNOWN_MAX_MS = 2 * 60_000, PENDING_MAX_MS = 5 * 60_000;
1869
+ async function resolveRestored() {
1870
+ for (const [k, f] of [...inFlight]) {
1871
+ if (!f.restored || f.checking) continue;
1872
+ f.checking = true;
1873
+ let j = null;
1874
+ try { j = await api("/api/outcome?client=" + f.client); } catch { j = null; }
1875
+ f.checking = false;
1876
+ if (inFlight.get(k) !== f) continue;
1877
+ const release = () => { inFlight.delete(k); saveLocal(); if (keyOf(current) === k) syncControls(); };
1878
+ if (j && j.ok && j.state === "done" && j.result) { release(); landed(k, f, j.result); if (keyOf(current) === k) syncControls(); continue; }
1879
+ const age = Date.now() - f.at;
1880
+ if (j && j.ok && j.state === "pending" && age < PENDING_MAX_MS) continue;
1881
+ // A team this board cannot read right now is not news about the decision: not known yet (item 16).
1882
+ const team = k.slice(0, k.lastIndexOf("|"));
1883
+ const unreadable = !state || state.relay_ok === false || state.decisions_ok === false || (state.unavailable_spaces || []).includes(team);
1884
+ const there = unreadable || (state.items || []).some((i) => keyOf(i) === k);
1885
+ if (!there) {
1886
+ // Gone from the board: settled, by this reply or otherwise. The words are kept on it all the same.
1887
+ release(); putBack(k, f.text, f.kind);
1888
+ sayOn(k, f.name, "It is no longer waiting on you — your reply may have been what settled it. Your words are kept on it.");
1889
+ continue;
1890
+ }
1891
+ if (age < UNKNOWN_MAX_MS) continue;
1892
+ release();
1893
+ putBack(k, f.text, f.kind);
1894
+ sayOn(k, f.name, "Your reply may have been sent — check the thread before sending it again. Your words are kept on it.");
1895
+ }
1558
1896
  }
1559
1897
 
1560
1898
  async function retract() {
1561
- const k = keyOf(current);
1899
+ const item = current;
1900
+ if (!item) return;
1901
+ const k = keyOf(item);
1562
1902
  const s = sentFor.get(k);
1563
- const lastSent = s && s.until > Date.now() ? s.sent : null;
1564
- if (!lastSent) return;
1565
- const btn = $("d-retract");
1566
- btn.disabled = true;
1903
+ // Past its minute: said, and the button goes — never a click that does nothing (#110).
1904
+ if (!s || s.until <= Date.now()) {
1905
+ sentFor.delete(k); saveLocal(); syncControls();
1906
+ setStatus("Too late to retract — a reply can be withdrawn only in its first minute.");
1907
+ return;
1908
+ }
1909
+ if (retracting.has(k)) return;
1910
+ retracting.add(k);
1911
+ syncControls();
1567
1912
  setStatus("Retracting…");
1913
+ const name = nameOf(item);
1914
+ // How it went is told on the decision it was about: its own status line, or a toast naming it (#110).
1915
+ const say = (msg) => { if (keyOf(current) === k) setStatus(msg); else toast("“" + name + "”: " + msg); };
1568
1916
  try {
1569
- const r = await api("/api/action", { op: "retract", act: lastSent });
1570
- if (r.ok) { sentFor.delete(k); if (keyOf(current) === k) { btn.hidden = true; setStatus("Retracted."); } else toast("Retracted."); refresh(); }
1571
- else setStatus("Could not retract — " + (r.message || r.error));
1572
- } catch (e) { setStatus("Could not retract — " + e.message); }
1573
- finally { btn.disabled = false; }
1917
+ const r = await api("/api/action", { op: "retract", act: s.sent });
1918
+ // Retracted: the answer is taken back and the decision waits again (under a new id, which the next
1919
+ // refresh follows) — so a corrected Answer is allowed again (round four).
1920
+ if (r.ok) { if (sentFor.get(k) === s) sentFor.delete(k); answeredHere.delete(k); resendGuard.delete(k); resendAsked.delete(k); retracted.set(k, item); saveLocal(); say("Retracted — you can answer it again."); refresh(); }
1921
+ else say((r.unsure ? "Not confirmed — " : "Could not retract — ") + (r.message || r.error));
1922
+ } catch (e) { say("Could not retract — " + e.message); }
1923
+ finally {
1924
+ retracting.delete(k);
1925
+ if (keyOf(current) === k) syncControls();
1926
+ }
1927
+ }
1928
+
1929
+ /**
1930
+ * A decision put back under a new id (a Retract settles the old obligation and the relay opens a new
1931
+ * one for the same request): what was kept on the old key moves to the new one, and an open dialog
1932
+ * follows it, so its Send goes to the decision as it is now (round four).
1933
+ */
1934
+ function followMoved() {
1935
+ const items = (state && state.items) || [];
1936
+ const onBoard = new Set(items.map((i) => keyOf(i)));
1937
+ // Only a decision this page retracted an answer on, and only onto the row the relay puts back for it:
1938
+ // the same request, team, kind and person (final round — following any row with the same request moved
1939
+ // words and Send onto another person's row). Anything else is not followed: its words stay under Not sent.
1940
+ const same = (was, i) => i.ref === was.ref && (i.space || "") === (was.space || "") && i.kind === was.kind
1941
+ && (i.who || "") === (was.who || "") && (i.decider || "") === (was.decider || "");
1942
+ for (const [k, was] of [...retracted]) {
1943
+ if (onBoard.has(k)) continue;
1944
+ const next = items.find((i) => keyOf(i) !== k && same(was, i));
1945
+ if (!next) continue;
1946
+ const k2 = keyOf(next);
1947
+ retracted.delete(k);
1948
+ for (const m of [drafts, names, notes, resendGuard, sentFor]) if (m.has(k) && !m.has(k2)) { m.set(k2, m.get(k)); m.delete(k); }
1949
+ answeredHere.delete(k); answeredHere.delete(k2);
1950
+ if (current && keyOf(current) === k) {
1951
+ // Its buttons are the old id's: the dialog is drawn again for the new one, keeping what is in
1952
+ // the box and on the status line.
1953
+ const text = $("d-text").value, said = $("d-status").textContent, open = $("detail").open;
1954
+ if (open) { openDetail(next); $("d-text").value = text; setStatus(said); } else current = next;
1955
+ syncControls();
1956
+ }
1957
+ }
1958
+ saveLocal();
1574
1959
  }
1575
1960
 
1576
1961
  async function refresh() {
@@ -1579,8 +1964,10 @@ async function refresh() {
1579
1964
  if (!j.ok) { banner(j.error || "The board could not be read.", true); return; }
1580
1965
  if (j.refresh_ms) refreshMs = j.refresh_ms;
1581
1966
  state = j.status;
1967
+ followMoved();
1582
1968
  render();
1583
1969
  $("refresh").title = "Updated " + new Date(j.at).toLocaleTimeString();
1970
+ resolveRestored();
1584
1971
  } catch (e) {
1585
1972
  $("loading").hidden = true;
1586
1973
  if (e.auth) { keepSession(null); banner("This board link has expired. Run pantheon board to open a fresh one.", true); stop(); }
@@ -1597,8 +1984,22 @@ $("detail").addEventListener("close", () => { current = null; });
1597
1984
  $("d-send").addEventListener("click", () => send());
1598
1985
  $("d-retract").addEventListener("click", () => retract());
1599
1986
  // The words typed are kept per decision until sent (#79): closing or switching never throws them away.
1600
- const keepDraft = () => { if (current) { const v = $("d-text").value; if (v) drafts.set(keyOf(current), { text: v, kind: $("d-kind").value }); else drafts.delete(keyOf(current)); } };
1601
- $("d-text").addEventListener("input", keepDraft);
1987
+ const keepDraft = () => { if (current) { const v = $("d-text").value; if (v) { drafts.set(keyOf(current), { text: v, kind: $("d-kind").value }); names.set(keyOf(current), nameOf(current)); } else drafts.delete(keyOf(current)); saveLocal(); } };
1988
+ // Was each edit while a reply is on its way just typing at the end? Told by beforeinput, before the
1989
+ // change, from the caret: a paste over the words, a retype or a deletion is not (round two, item 2a).
1990
+ $("d-text").addEventListener("beforeinput", (ev) => {
1991
+ const f = inFlight.get(keyOf(current));
1992
+ if (!f) return;
1993
+ const t = $("d-text");
1994
+ const atEnd = t.selectionStart === t.selectionEnd && t.selectionEnd === t.value.length;
1995
+ if (!atEnd || /^delete/.test(ev.inputType || "")) f.appendOnly = false;
1996
+ f.sawBefore = true;
1997
+ });
1998
+ $("d-text").addEventListener("input", () => {
1999
+ const f = inFlight.get(keyOf(current));
2000
+ if (f) { if (!f.sawBefore) f.appendOnly = false; f.sawBefore = false; }
2001
+ keepDraft();
2002
+ });
1602
2003
  $("d-kind").addEventListener("change", keepDraft);
1603
2004
  $("d-text").addEventListener("keydown", (ev) => { if (ev.key === "Enter" && (ev.ctrlKey || ev.metaKey)) { ev.preventDefault(); send(); } });
1604
2005
  // A hidden tab stops asking: the relay is not polled for nobody, and the board
@@ -1623,7 +2024,9 @@ document.addEventListener("visibilitychange", () => { if (!document.hidden) refr
1623
2024
  if (focus && state) {
1624
2025
  const want = focus;
1625
2026
  focus = null;
1626
- const hit = (state.items || []).find((i) => i.id === want || i.ref === want);
2027
+ const hits = (state.items || []).filter((i) => i.id === want || i.ref === want);
2028
+ const teamOf = (i) => i.space || state.space;
2029
+ const hit = focusTeam ? hits.find((i) => teamOf(i) === focusTeam) : (hits.find((i) => teamOf(i) === state.space) || hits[0]);
1627
2030
  if (hit) openDetail(hit); else toast("That is no longer waiting on you.");
1628
2031
  }
1629
2032
  schedule();