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

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 (51) hide show
  1. package/dist/agent-outage.js +156 -36
  2. package/dist/agent-token.js +5 -3
  3. package/dist/approvals-list.js +87 -0
  4. package/dist/board.js +472 -87
  5. package/dist/brief.js +17 -0
  6. package/dist/cli.js +687 -95
  7. package/dist/client.js +159 -19
  8. package/dist/config.js +3 -2
  9. package/dist/continued.js +56 -1
  10. package/dist/decision-ui.js +5 -3
  11. package/dist/doctor.js +81 -15
  12. package/dist/file-lock.js +39 -4
  13. package/dist/flow-stats.js +18 -1
  14. package/dist/home-guard.js +317 -54
  15. package/dist/home-safety.js +2 -0
  16. package/dist/hud-queue.js +91 -0
  17. package/dist/install.js +15 -1
  18. package/dist/mcp-instructions.js +55 -20
  19. package/dist/mcp.js +114 -24
  20. package/dist/notice-linux.js +15 -4
  21. package/dist/notice-windows.js +2 -2
  22. package/dist/notifier.js +2 -1
  23. package/dist/notify.js +8 -4
  24. package/dist/open-in.js +4 -3
  25. package/dist/pickup.js +17 -0
  26. package/dist/plain.js +139 -3
  27. package/dist/profile.js +12 -8
  28. package/dist/protocol.js +1 -1
  29. package/dist/question-goal.js +74 -0
  30. package/dist/readiness-alert.js +24 -3
  31. package/dist/refusal.js +2 -2
  32. package/dist/relay.js +142 -28
  33. package/dist/removed.js +4 -4
  34. package/dist/run-control.js +4 -3
  35. package/dist/run-failure.js +67 -10
  36. package/dist/setup-changes.js +7 -6
  37. package/dist/signed-out.js +144 -21
  38. package/dist/spend.js +2 -2
  39. package/dist/tray.js +24 -6
  40. package/dist/update-check.js +2 -1
  41. package/dist/uri-handler.js +10 -2
  42. package/dist/which.js +2 -0
  43. package/dist/worker-policy.js +212 -10
  44. package/dist/worker.js +847 -114
  45. package/dist/worklist.js +31 -1
  46. package/helper/macos/main.swift +42 -3
  47. package/helper/macos/menubar.swift +482 -87
  48. package/helper/macos/prebuilt/manifest.json +5 -5
  49. package/helper/macos/prebuilt/pantheon-hud +0 -0
  50. package/helper/macos/prebuilt/pantheon-tray +0 -0
  51. 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
 
@@ -1333,6 +1499,29 @@ function render() {
1333
1499
  if (keep && keep.k) {
1334
1500
  for (const b of document.querySelectorAll("[data-k]")) if (b.dataset.k === keep.k && b.dataset.a === keep.a) { b.focus(); break; }
1335
1501
  }
1502
+ renderUnsent();
1503
+ }
1504
+
1505
+ /**
1506
+ * Words typed on decisions no longer on the board (settled elsewhere, or by a button here): listed to
1507
+ * copy, until discarded (round three, F9). Only when every team could be read — a team out of reach
1508
+ * is not news that its decisions are gone — and never one being sent or open now.
1509
+ */
1510
+ function renderUnsent() {
1511
+ const s = state;
1512
+ const host = $("l-unsent");
1513
+ const readable = s && s.configured && s.relay_ok !== false && s.decisions_ok !== false && !(s.unavailable_spaces || []).length;
1514
+ const onBoard = new Set((s && s.items || []).map((i) => keyOf(i)));
1515
+ const left = readable ? [...drafts].filter(([k, d]) => d && d.text.trim() && !onBoard.has(k) && !inFlight.has(k) && keyOf(current) !== k) : [];
1516
+ $("unsent").hidden = !left.length;
1517
+ host.replaceChildren(...left.map(([k, d]) => {
1518
+ const li = el("li");
1519
+ li.append(el("strong", "", names.get(k) || "Something no longer on your board"));
1520
+ li.append(el("p", "words", d.text));
1521
+ li.append(button("Copy", () => copy(d.text)));
1522
+ li.append(button("Discard", () => { drafts.delete(k); names.delete(k); notes.delete(k); saveLocal(); renderUnsent(); }));
1523
+ return li;
1524
+ }));
1336
1525
  }
1337
1526
 
1338
1527
  function tag(b, item, a) { b.dataset.k = key(item); b.dataset.a = a; return b; }
@@ -1367,15 +1556,15 @@ function row(item, card) {
1367
1556
  wakeButtons(item).forEach((b) => acts.append(b));
1368
1557
  acts.append(tag(button("Reply…", () => openDetail(item, true)), item, "reply"));
1369
1558
  } 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"));
1559
+ (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)));
1560
+ 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
1561
  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"));
1562
+ acts.append(tag(button("Explain in " + surface(), (ev) => act({ op: "open", id: item.id, space: item.space }, ev.currentTarget, undefined, item)), item, "explain"));
1374
1563
  } else {
1375
1564
  // Under "Your agents are handling": the person can take the request back, or stop the work.
1376
1565
  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"));
1566
+ acts.append(tag(button("Take over", (ev) => act({ op: "takeover", id: item.id, space: item.space }, ev.currentTarget, undefined, item)), item, "takeover"));
1567
+ acts.append(tag(button("Stop", (ev) => act({ op: "stop", id: item.id, space: item.space }, ev.currentTarget, undefined, item)), item, "stop"));
1379
1568
  }
1380
1569
  acts.append(tag(button("Details", () => openDetail(item)), item, "details"));
1381
1570
  }
@@ -1387,11 +1576,12 @@ function row(item, card) {
1387
1576
  // Approve and Decline are pantheon wake allow|deny for the teammate the
1388
1577
  // question is about; "Just this once" is the question's own one-run answer.
1389
1578
  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")];
1579
+ // Settled from the card or the dialog alike: what was typed on it goes, and that is said (item 17).
1580
+ const done = (r) => { if (r && r.ok) { if (after) after(r); else settled(item, r); } };
1581
+ 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
1582
  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"));
1583
+ 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"));
1584
+ 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
1585
  return out;
1396
1586
  }
1397
1587
 
@@ -1409,18 +1599,37 @@ async function copy(text) {
1409
1599
  toast("Press Ctrl+C (or Cmd+C) to copy.");
1410
1600
  }
1411
1601
 
1412
- async function act(body, btn, okText) {
1602
+ async function act(body, btn, okText, item) {
1603
+ // A result names the decision it is about whenever that decision is not the one open (#110):
1604
+ // a toast never reads as news about whatever the person is looking at by then.
1605
+ const k = item ? keyOf(item) : null;
1606
+ const named = (msg) => (item && keyOf(current) !== k ? "“" + nameOf(item) + "”: " + msg : msg);
1607
+ // One action per decision at a time (0.35.1 review, item 5) — said, never a second answer.
1608
+ if (k && busyOn(k)) { toast(named("Still sending your last answer to this — wait for it to land.")); return null; }
1609
+ if (k) acting.add(k);
1413
1610
  if (btn) btn.disabled = true;
1414
- toast("Working…");
1611
+ if (k && keyOf(current) === k) syncControls();
1612
+ toast(named("Working…"));
1613
+ // A refusal or an unconfirmed result is the decision's news: kept for it if it is not open (item 15).
1614
+ const keep = (msg) => { if (k && keyOf(current) !== k) notes.set(k, msg); };
1415
1615
  try {
1416
1616
  const r = await api("/api/action", body);
1417
- toast(r.ok ? (okText || r.message) : "Not sent — " + r.message);
1617
+ const msg = r.ok ? (okText || r.message) : (r.unsure ? "Not confirmed — " : "Not sent — ") + r.message;
1618
+ if (r && typeof r === "object") r.said = msg; // this action's own outcome, for settled() (round three, F4)
1619
+ toast(named(msg));
1620
+ if (!r.ok) keep(msg);
1418
1621
  if (r.ok) await refresh();
1419
1622
  return r;
1420
1623
  } 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);
1624
+ 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;
1625
+ toast(named(msg));
1626
+ keep(msg);
1422
1627
  return null;
1423
- } finally { if (btn) btn.disabled = false; }
1628
+ } finally {
1629
+ if (k) acting.delete(k);
1630
+ if (btn) btn.disabled = false;
1631
+ if (k && keyOf(current) === k) syncControls();
1632
+ }
1424
1633
  }
1425
1634
 
1426
1635
  function ownerLine(item) {
@@ -1428,7 +1637,10 @@ function ownerLine(item) {
1428
1637
  if (item.kind === "decision") return "Yours to decide.";
1429
1638
  if (item.decider) return item.decider + "'s to decide. You can add a note or ask back.";
1430
1639
  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.";
1640
+ // An Ask back reaches the one teammate this row waits on; a row for "your agent" or for several
1641
+ // people names nobody it cannot reach (round four).
1642
+ const one = typeof item.who === "string" && /^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(item.who);
1643
+ 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
1644
  }
1433
1645
 
1434
1646
  function blocks(host, list) {
@@ -1444,6 +1656,7 @@ function setStatus(msg) { $("d-status").replaceChildren(); $("d-status").textCon
1444
1656
 
1445
1657
  async function openDetail(item, focusReply) {
1446
1658
  current = item;
1659
+ const seq = ++openSeq;
1447
1660
  const d = $("detail");
1448
1661
  $("d-title").textContent = item.headline || item.title;
1449
1662
  $("d-meta").textContent = [item.who, ago(item.when), item.space ? "team " + item.space : ""].filter(Boolean).join(" · ");
@@ -1453,29 +1666,34 @@ async function openDetail(item, focusReply) {
1453
1666
  blocks($("d-body"), [{ kind: "para", text: item.detail || "" }]);
1454
1667
  $("d-options").hidden = true; $("d-options").replaceChildren();
1455
1668
  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" : "")));
1669
+ if (item.wake) wakeButtons(item, (r) => { if (!settled(item, r)) closeIf(item, r); }).forEach((b) => ch.append(b));
1670
+ 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
1671
  ch.hidden = !(item.wake || (item.choices && item.choices.length));
1459
1672
  const kind = $("d-kind"); kind.replaceChildren();
1460
1673
  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
1674
  { 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()); }
1675
+ {
1676
+ const k = keyOf(item), note = notes.get(k);
1677
+ if (busyOn(k)) setStatus("Still sending your last answer to this — Send works again once it lands.");
1678
+ else if (note) { notes.delete(k); setStatus(note); }
1679
+ else setStatus("");
1680
+ }
1681
+ syncControls();
1464
1682
  const actions = $("d-actions"); actions.replaceChildren();
1465
1683
  // A change to this person's setup: everything it would do is shown above, then Approve or Keep as is.
1466
1684
  $("d-reply").hidden = item.kind === "change";
1467
1685
  if (item.kind === "change") {
1468
1686
  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))));
1687
+ 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); })));
1688
+ 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
1689
  ch.hidden = false;
1472
1690
  $("d-thread").hidden = true; $("d-thread").replaceChildren();
1473
1691
  if (!d.open) d.showModal();
1474
1692
  $("d-close").focus();
1475
1693
  return;
1476
1694
  }
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)));
1695
+ 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); })));
1696
+ actions.append(button("Explain in " + surface(), (ev) => act({ op: "open", id: item.id, space: item.space }, ev.currentTarget, undefined, item)));
1479
1697
  if (item.goal && item.space) actions.append(button("Show the thread", () => thread(item)));
1480
1698
  actions.append(button("Copy the question", () => copy(item.prompt)));
1481
1699
  $("d-thread").hidden = true; $("d-thread").replaceChildren();
@@ -1485,11 +1703,14 @@ async function openDetail(item, focusReply) {
1485
1703
  try {
1486
1704
  const q = "/api/detail?id=" + encodeURIComponent(item.ref) + (item.space ? "&space=" + encodeURIComponent(item.space) : "");
1487
1705
  const j = await api(q);
1488
- if (current !== item || !j || !j.ok) return;
1706
+ // Only the opening that asked: a decision closed and opened again before its detail arrived
1707
+ // gets one set of options, not one per opening (#110).
1708
+ if (seq !== openSeq || current !== item || !j || !j.ok) return;
1489
1709
  if (Array.isArray(j.blocks) && j.blocks.length) blocks($("d-body"), j.blocks);
1490
1710
  if (item.kind === "decision" && Array.isArray(j.options) && j.options.length) {
1491
1711
  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))));
1712
+ host.replaceChildren();
1713
+ 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
1714
  host.hidden = false;
1494
1715
  }
1495
1716
  } catch { /* the short text stays */ }
@@ -1512,65 +1733,211 @@ async function thread(item) {
1512
1733
  } catch (e) { host.replaceChildren(el("p", "muted", "The thread could not be read: " + e.message)); }
1513
1734
  }
1514
1735
 
1736
+ // Not sent: the words come back to their decision. Anything typed there since stays, after them —
1737
+ // unless it already starts with them (a follow-up typed onto the same words): then nothing is added,
1738
+ // so the words are never in the box twice (0.35.1 review, item 7).
1739
+ const startsWithSent = (v, text) => v.trimStart().startsWith(text);
1740
+ function putBack(k, text, kind) {
1741
+ const dr = drafts.get(k);
1742
+ if (!dr || !dr.text.trim()) drafts.set(k, { text, kind });
1743
+ else if (!startsWithSent(dr.text, text)) drafts.set(k, { text: text + "\\n\\n" + dr.text, kind: dr.kind || kind });
1744
+ saveLocal();
1745
+ if (keyOf(current) === k) {
1746
+ const box = $("d-text"), v = box.value.trim();
1747
+ if (!v) box.value = text; else if (!startsWithSent(v, text)) box.value = text + "\\n\\n" + box.value;
1748
+ }
1749
+ }
1750
+ /** What is left of v once the words that were sent are taken off its front (item 7): a follow-up typed onto them. */
1751
+ function afterSent(v, text) {
1752
+ const t = v.trimStart();
1753
+ return t.startsWith(text) ? t.slice(text.length).replace(/^\\s+/, "") : v;
1754
+ }
1755
+ /**
1756
+ * Told on the decision it is about: its own status line when open, else a toast naming it —
1757
+ * and kept as that decision's note, shown when it opens next (0.35.1 review, item 15).
1758
+ */
1759
+ function sayOn(k, name, msg) {
1760
+ if (keyOf(current) === k) { setStatus(msg); return; }
1761
+ toast("“" + name + "”: " + msg);
1762
+ notes.set(k, msg);
1763
+ }
1764
+ /** How a reply that left this page ended (r: { ok, message, sent }), told on its own decision. */
1765
+ function landed(k, f, r) {
1766
+ // Not confirmed: the relay's answer was lost and the reply is not found yet — it may have landed (#107).
1767
+ 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; }
1768
+ // Only the words that were sent are cleared (#105). A follow-up typed onto them loses them from its
1769
+ // front (0.35.1 review, item 7) — but only when every edit since the send was typing at the end
1770
+ // (round two: "OK" sent, then "OK, but move the demo…" retyped or pasted, kept "…, but move" and
1771
+ // lost the person's words). Anything else is kept whole, and a Send of it that still starts with
1772
+ // what was sent asks once first.
1773
+ 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.";
1774
+ const cut = (v) => (f.appendOnly === true ? afterSent(v, f.text) : v.trim() === f.text ? "" : v);
1775
+ const dr = drafts.get(k);
1776
+ if (dr) { const rest = cut(dr.text); if (rest.trim()) drafts.set(k, { text: rest, kind: dr.kind }); else drafts.delete(k); }
1777
+ if (r.sent) sentFor.set(k, { sent: r.sent, until: Date.now() + 60000 });
1778
+ saveLocal();
1779
+ let left = dr ? (drafts.get(k) || { text: "" }).text : "";
1780
+ if (keyOf(current) === k) { $("d-text").value = cut($("d-text").value); left = $("d-text").value; }
1781
+ // An answer settles the decision: a second one is refused (ALREADY_ANSWERED). What is left goes as a
1782
+ // Note, and the page says so instead of offering a Send that cannot work (round three, F10).
1783
+ if (f.kind === "ANSWER") answeredHere.add(k);
1784
+ if (left.trim() && left.trimStart().startsWith(f.text)) {
1785
+ resendGuard.set(k, f.text);
1786
+ sayOn(k, f.name, said + (f.kind === "ANSWER"
1787
+ ? " The box still starts with what you just sent — take that out, then switch to Note to send the rest."
1788
+ : " The box still starts with what you just sent — take that out, or press Send again to send it all as it is."));
1789
+ return;
1790
+ }
1791
+ 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; }
1792
+ sayOn(k, f.name, said);
1793
+ }
1794
+ /** A reason that ends as a sentence, so what follows it reads as the next one. */
1795
+ const sentence = (m) => { const t = String(m || "").trim(); return !t || /[.!?…)]$/.test(t) ? t : t + "."; };
1796
+ function newClientId() { const a = new Uint8Array(16); crypto.getRandomValues(a); return Array.from(a, (b) => b.toString(16).padStart(2, "0")).join(""); }
1797
+
1515
1798
  async function send() {
1516
1799
  const item = current;
1517
1800
  if (!item) return;
1801
+ const k = keyOf(item);
1802
+ // One send per decision at a time: a second press, the same decision opened again, or the tab
1803
+ // reloaded while its reply is on the way — never sends the words twice (#105), and says why.
1804
+ if (busyOn(k)) { setStatus("Still sending your last answer to this — Send works again once it lands."); return; }
1518
1805
  const text = $("d-text").value.trim();
1519
1806
  if (!text) { setStatus("Type your reply first."); return; }
1807
+ if ($("d-kind").value === "ANSWER" && answeredHere.has(k)) {
1808
+ setStatus("This is already answered — switch to Note to send the rest.");
1809
+ return;
1810
+ }
1811
+ const again = resendGuard.get(k);
1812
+ if (again && text.startsWith(again) && !resendAsked.has(k)) {
1813
+ resendAsked.add(k);
1814
+ setStatus("This starts with words you already sent. Press Send again to send it all as it is, or take them out first.");
1815
+ return;
1816
+ }
1817
+ resendGuard.delete(k); resendAsked.delete(k);
1520
1818
  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?
1819
+ // The page's own id for this send: after a reload, the board says how it went (/api/outcome).
1820
+ // appendOnly: every edit to the box since this send was typing at its end (round two, item 2a).
1821
+ const f = { text, kind, at: Date.now(), client: newClientId(), name: nameOf(item), appendOnly: true };
1822
+ inFlight.set(k, f);
1527
1823
  // In flight, the words are not a draft: reopening this decision meanwhile does not show them as unsent.
1528
1824
  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";
1825
+ saveLocal();
1826
+ syncControls();
1827
+ setStatus("Sending…");
1531
1828
  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();
1829
+ const r = await api("/api/action", { op: "reply", id: item.id, space: item.space, kind, body: text, client: f.client });
1830
+ if (inFlight.get(k) === f) landed(k, f, r);
1831
+ if (r.ok) refresh();
1552
1832
  } 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; }
1833
+ if (inFlight.get(k) === f) {
1834
+ putBack(k, text, kind);
1835
+ 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);
1836
+ sayOn(k, f.name, why + (e.auth ? "" : keyOf(current) === k ? " Your words are still in the box." : " Your words are kept on it."));
1837
+ }
1838
+ } finally {
1839
+ if (inFlight.get(k) === f) { inFlight.delete(k); saveLocal(); }
1840
+ if (keyOf(current) === k) syncControls();
1841
+ }
1842
+ }
1843
+
1844
+ /**
1845
+ * Sends this tab had on their way when it was reloaded (#105): asked of the board, which knows
1846
+ * how each went. Landed: told, as if the page had never gone. Still going: Send stays off. Not
1847
+ * known (an older board, or one started since): Send stays off for a bounded while, then the
1848
+ * person is told it may have been sent — never a silent second send.
1849
+ */
1850
+ const UNKNOWN_MAX_MS = 2 * 60_000, PENDING_MAX_MS = 5 * 60_000;
1851
+ async function resolveRestored() {
1852
+ for (const [k, f] of [...inFlight]) {
1853
+ if (!f.restored || f.checking) continue;
1854
+ f.checking = true;
1855
+ let j = null;
1856
+ try { j = await api("/api/outcome?client=" + f.client); } catch { j = null; }
1857
+ f.checking = false;
1858
+ if (inFlight.get(k) !== f) continue;
1859
+ const release = () => { inFlight.delete(k); saveLocal(); if (keyOf(current) === k) syncControls(); };
1860
+ if (j && j.ok && j.state === "done" && j.result) { release(); landed(k, f, j.result); if (keyOf(current) === k) syncControls(); continue; }
1861
+ const age = Date.now() - f.at;
1862
+ if (j && j.ok && j.state === "pending" && age < PENDING_MAX_MS) continue;
1863
+ // A team this board cannot read right now is not news about the decision: not known yet (item 16).
1864
+ const team = k.slice(0, k.lastIndexOf("|"));
1865
+ const unreadable = !state || state.relay_ok === false || state.decisions_ok === false || (state.unavailable_spaces || []).includes(team);
1866
+ const there = unreadable || (state.items || []).some((i) => keyOf(i) === k);
1867
+ if (!there) {
1868
+ // Gone from the board: settled, by this reply or otherwise. The words are kept on it all the same.
1869
+ release(); putBack(k, f.text, f.kind);
1870
+ 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.");
1871
+ continue;
1872
+ }
1873
+ if (age < UNKNOWN_MAX_MS) continue;
1874
+ release();
1875
+ putBack(k, f.text, f.kind);
1876
+ sayOn(k, f.name, "Your reply may have been sent — check the thread before sending it again. Your words are kept on it.");
1877
+ }
1558
1878
  }
1559
1879
 
1560
1880
  async function retract() {
1561
- const k = keyOf(current);
1881
+ const item = current;
1882
+ if (!item) return;
1883
+ const k = keyOf(item);
1562
1884
  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;
1885
+ // Past its minute: said, and the button goes — never a click that does nothing (#110).
1886
+ if (!s || s.until <= Date.now()) {
1887
+ sentFor.delete(k); saveLocal(); syncControls();
1888
+ setStatus("Too late to retract — a reply can be withdrawn only in its first minute.");
1889
+ return;
1890
+ }
1891
+ if (retracting.has(k)) return;
1892
+ retracting.add(k);
1893
+ syncControls();
1567
1894
  setStatus("Retracting…");
1895
+ const name = nameOf(item);
1896
+ // How it went is told on the decision it was about: its own status line, or a toast naming it (#110).
1897
+ const say = (msg) => { if (keyOf(current) === k) setStatus(msg); else toast("“" + name + "”: " + msg); };
1568
1898
  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; }
1899
+ const r = await api("/api/action", { op: "retract", act: s.sent });
1900
+ // Retracted: the answer is taken back and the decision waits again (under a new id, which the next
1901
+ // refresh follows) — so a corrected Answer is allowed again (round four).
1902
+ 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(); }
1903
+ else say((r.unsure ? "Not confirmed — " : "Could not retract — ") + (r.message || r.error));
1904
+ } catch (e) { say("Could not retract — " + e.message); }
1905
+ finally {
1906
+ retracting.delete(k);
1907
+ if (keyOf(current) === k) syncControls();
1908
+ }
1909
+ }
1910
+
1911
+ /**
1912
+ * A decision put back under a new id (a Retract settles the old obligation and the relay opens a new
1913
+ * one for the same request): what was kept on the old key moves to the new one, and an open dialog
1914
+ * follows it, so its Send goes to the decision as it is now (round four).
1915
+ */
1916
+ function followMoved() {
1917
+ const items = (state && state.items) || [];
1918
+ const onBoard = new Set(items.map((i) => keyOf(i)));
1919
+ // Only a decision this page retracted an answer on, and only onto the row the relay puts back for it:
1920
+ // the same request, team, kind and person (final round — following any row with the same request moved
1921
+ // words and Send onto another person's row). Anything else is not followed: its words stay under Not sent.
1922
+ const same = (was, i) => i.ref === was.ref && (i.space || "") === (was.space || "") && i.kind === was.kind
1923
+ && (i.who || "") === (was.who || "") && (i.decider || "") === (was.decider || "");
1924
+ for (const [k, was] of [...retracted]) {
1925
+ if (onBoard.has(k)) continue;
1926
+ const next = items.find((i) => keyOf(i) !== k && same(was, i));
1927
+ if (!next) continue;
1928
+ const k2 = keyOf(next);
1929
+ retracted.delete(k);
1930
+ 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); }
1931
+ answeredHere.delete(k); answeredHere.delete(k2);
1932
+ if (current && keyOf(current) === k) {
1933
+ // Its buttons are the old id's: the dialog is drawn again for the new one, keeping what is in
1934
+ // the box and on the status line.
1935
+ const text = $("d-text").value, said = $("d-status").textContent, open = $("detail").open;
1936
+ if (open) { openDetail(next); $("d-text").value = text; setStatus(said); } else current = next;
1937
+ syncControls();
1938
+ }
1939
+ }
1940
+ saveLocal();
1574
1941
  }
1575
1942
 
1576
1943
  async function refresh() {
@@ -1579,8 +1946,10 @@ async function refresh() {
1579
1946
  if (!j.ok) { banner(j.error || "The board could not be read.", true); return; }
1580
1947
  if (j.refresh_ms) refreshMs = j.refresh_ms;
1581
1948
  state = j.status;
1949
+ followMoved();
1582
1950
  render();
1583
1951
  $("refresh").title = "Updated " + new Date(j.at).toLocaleTimeString();
1952
+ resolveRestored();
1584
1953
  } catch (e) {
1585
1954
  $("loading").hidden = true;
1586
1955
  if (e.auth) { keepSession(null); banner("This board link has expired. Run pantheon board to open a fresh one.", true); stop(); }
@@ -1597,8 +1966,22 @@ $("detail").addEventListener("close", () => { current = null; });
1597
1966
  $("d-send").addEventListener("click", () => send());
1598
1967
  $("d-retract").addEventListener("click", () => retract());
1599
1968
  // 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);
1969
+ 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(); } };
1970
+ // Was each edit while a reply is on its way just typing at the end? Told by beforeinput, before the
1971
+ // change, from the caret: a paste over the words, a retype or a deletion is not (round two, item 2a).
1972
+ $("d-text").addEventListener("beforeinput", (ev) => {
1973
+ const f = inFlight.get(keyOf(current));
1974
+ if (!f) return;
1975
+ const t = $("d-text");
1976
+ const atEnd = t.selectionStart === t.selectionEnd && t.selectionEnd === t.value.length;
1977
+ if (!atEnd || /^delete/.test(ev.inputType || "")) f.appendOnly = false;
1978
+ f.sawBefore = true;
1979
+ });
1980
+ $("d-text").addEventListener("input", () => {
1981
+ const f = inFlight.get(keyOf(current));
1982
+ if (f) { if (!f.sawBefore) f.appendOnly = false; f.sawBefore = false; }
1983
+ keepDraft();
1984
+ });
1602
1985
  $("d-kind").addEventListener("change", keepDraft);
1603
1986
  $("d-text").addEventListener("keydown", (ev) => { if (ev.key === "Enter" && (ev.ctrlKey || ev.metaKey)) { ev.preventDefault(); send(); } });
1604
1987
  // A hidden tab stops asking: the relay is not polled for nobody, and the board
@@ -1623,7 +2006,9 @@ document.addEventListener("visibilitychange", () => { if (!document.hidden) refr
1623
2006
  if (focus && state) {
1624
2007
  const want = focus;
1625
2008
  focus = null;
1626
- const hit = (state.items || []).find((i) => i.id === want || i.ref === want);
2009
+ const hits = (state.items || []).filter((i) => i.id === want || i.ref === want);
2010
+ const teamOf = (i) => i.space || state.space;
2011
+ const hit = focusTeam ? hits.find((i) => teamOf(i) === focusTeam) : (hits.find((i) => teamOf(i) === state.space) || hits[0]);
1627
2012
  if (hit) openDetail(hit); else toast("That is no longer waiting on you.");
1628
2013
  }
1629
2014
  schedule();